0
0
BlockchainHow-ToBeginner ยท 3 min read

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, and allowance.
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 decimals properly, 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 transfer or approve functions, 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

ConceptDescription
contract MyToken is ERC20Defines 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.