6 Sep 2023 · Software Engineering

    Mastering ERC20 Token in Solidity

    17 min read

    The article focuses on the ERC20 standard (Request for Comment), which is widely used to create digital tokens on the Ethereum network. It outlines the deployment procedure using Remix EVM (Ethereum Virtual Machine) and the integration of ERC20 tokens with the Solidity programming language.

    Developers can apply the knowledge in this article to create their own digital tokens for various purposes, including fundraising, incentive programs, and in-app payments. They can also create decentralized applications (dApps) that utilize these tokens for value and payment exchanges.

    While other programming languages are available, Solidity is the popular choice among developers in the decentralized finance (DeFi) space due to its simplicity and ease of use. Understanding the ERC20 standard in Solidity offers several advantages, such as streamlined development processes, a robust community for support and collaboration, and the ability to create innovative solutions for decentralized applications (dApps) and digital token use cases.

    A Brief History of the ERC20 Token

    One of the most widely used token specifications on the Ethereum network is ERC20. Due to its simplicity and adaptability, it was quickly adopted after being introduced by Fabian Vogelsteller in November 2015. ERC20 tokens are fungible (mutually interchangeable) and easy to maintain, thanks to smart contracts that establish a set of rules for the tokens to follow.

    The standardization of ERC20 tokens has completely transformed the creation and management of tokens by businesses and individuals. Before ERC20, developers found it challenging to ensure compatibility with other tokens and wallets because each token had to be designed from scratch. Now, developers can use ERC20 to create tokens that are compatible with any wallet or exchange that accepts the standard.

    Since its inception, thousands of tokens on the Ethereum network—including some of the largest and most valuable, such as Chainlink, Binance Coin, and Tether—have been built on the ERC20 standard. The standard has also influenced several other token standards, including ERC721 (for non-fungible tokens) and ERC1155 (a single smart contract containing multiple tokens). ERC20 has been instrumental in the growth and improvement of the Ethereum ecosystem.

    What Is an ERC20 Token?

    An ERC20 token is a digital asset built on the Ethereum blockchain under the ERC20 standard. These standardized tokens are fungible, meaning that each token can be exchanged for another of equal value. Introduced in 2015 to address issues with smart contract tokens, the ERC20 standard has gained popularity within the Ethereum ecosystem.

    On the Ethereum network, ERC20 tokens offer compatibility with a variety of wallets, exchanges, and decentralized applications. They also provide enhanced security and reliability, as well as the ability to be programmed to perform specific tasks. These tokens can represent a range of assets, including digital currencies, company stock, tangible goods, and reputation points, among others.

    At the time of writing this article, Ethplorer has documented the total value of all tokens in its database—known as the “Tokens Cap”—at $286.50 billion.

    Ethplorer provides information about tokens that operate on the Ethereum blockchain. The tool offers details on various aspects of these tokens, such as market value, pricing, and transaction history.

    Benefits of Utilizing ERC20 Tokens

    In the Ethereum blockchain, token creation is governed by the ERC20 technical standard. Below are some advantages of using ERC20 tokens:

    • Reduced Costs: Because ERC20 tokens eliminate the need for middlemen and enable quicker settlement times compared to traditional financial systems, they have lower transaction fees and costs.
    • Decentralization: ERC20 tokens are decentralized since they are created on the Ethereum blockchain, meaning they are not owned or controlled by a single entity. Because all transactions are recorded and published, the movement and ownership of these tokens are more transparent than with traditional, paper contracts.
    • Programmability: ERC20 tokens are programmable, allowing for the customization of actions to carry out specific tasks, such as enabling automatic payments, voting processes, or access control.
    • Security: Transactions for ERC20 tokens are stored on the immutable Ethereum blockchain, making them highly secure and resistant to hacking, fraud, and other nefarious activities.

    How Does an ERC20 Token Work?

    Tokens must adhere to guidelines outlined by ERC20 to be considered ERC20-compliant. These guidelines require the support of specific computer language features to facilitate easy interoperability across various wallets, exchanges, and decentralized apps. As a result, the Ethereum ecosystem simplifies the trading and use of tokens that comply with the ERC20 standard.

    Details of the agreement between the buyer and seller are immediately coded and executed as smart contracts, which are self-executing contracts.

    These smart contracts hold the token’s supply and enforce the restrictions specified by the ERC20 standard.

    The diagram below illustrates how an ERC20 token functions. Initially, the token owner approves 50 tokens for a spender. The spender can then withdraw up to 50 tokens at any time, representing their allowance. Once the tokens are withdrawn, the spender decides how to utilize them. To spend the tokens, the spender can use the transferFrom function, specifying the parameters of the sender, recipient, and token amount.

    An ERC20 token transaction is recorded on the Ethereum blockchain, and the token balance is updated when a user sends an ERC20 token to another user.

    Defining the ERC20 Token Standard and Its Guidelines

    The Ethereum blockchain employs a set of rules and specifications known as the ERC20 token standard to produce tokens. ERC stands for “Ethereum Request for Comment,” and the proposal identification assigned to this standard is 20. To create an ERC20 token, you must adhere to the following rules:

    • Token Name: The official name of the token.
    • Symbol: The token’s identifying abbreviation.
    • Decimal Points: The number of decimal places used to represent the token. For example, if the token has 18 decimal places, one token is equal to 1000000000000000000 (10^18) units.
    • Total Supply: The overall quantity of tokens that will be issued.
    • BalanceOf: This function returns the balance of the token.
    • Transfer: This function allows the movement of tokens from one address to another.
    • TransferFrom: This function enables authorized addresses to send tokens from other addresses (as seen in the example above).
    • Approval: This function allows one address to authorize another address to spend tokens on its behalf.
    • Allowance: This function indicates the number of tokens that have been authorized for one address to use on behalf of another (as illustrated above).

    The following diagram presents a visual representation of the functioning of the ERC20 token standard.

    Following these guidelines ensures that the token will integrate easily with other systems and wallets that accept ERC20 tokens. It also guarantees that the token can be traded on cryptocurrency exchanges that support ERC20 tokens.

    Examples of ERC20 Tokens in Action

    Below are just a few examples of ERC20 tokens in action. ERC20 tokens are widely used in the blockchain ecosystem and provide a standard way for creating and managing tokens on the Ethereum blockchain. There are numerous instances of ERC20 tokens being used in the blockchain ecosystem. Here are a few examples:

    • USDT (Tether): Tether is a stable coin that is tied to the US dollar, with each USDT token standing in for one dollar. Tether is an ERC20 token that is frequently used as a stablecoin for trading and money transfers on different cryptocurrency exchanges.
    • LINK (Chainlink): Chainlink is a decentralized oracle network that links smart contracts to outside data sources. The LINK currency is used to reward node operators for providing correct data to the network.
    • BAT (Basic Attention Token): The Brave browser ecosystem uses Basic Attention Token to compensate users for viewing adverts. On the platform, the token can be used to pay for premium products or services.
    • OMG (OmiseGO): OmiseGO is a blockchain-based payment system that enables quick, safe, and inexpensive payments. On the platform, OMG tokens are utilized as a medium of trade.
    • REP (Augur): Augur is a decentralized platform for prediction markets that enables users to build and trade their own. The REP token is used on the platform to report the results of events and to reward truthful reporting.

    While there are numerous other widely used tokens in circulation, it is currently unfeasible to present a complete list of them. Nonetheless, a picture displaying some of the well-known tokens can be found below:

    The images above provide evidence that many tokens are featured on the CoinCodex website, and it’s apparent that ERC20 tokens are popular. In the next section of this tutorial, we will explore the reasons behind the popularity of ERC20 tokens.

    ERC20 tokens are popular because of their portability and standardization, which make them easy to use and trade within the Ethereum ecosystem. To maintain compatibility with other tokens and wallets, the standard outlines a set of guidelines that all ERC20-compliant tokens must follow. The ease with which developers can create new tokens and users can interact with them has led to the widespread use of ERC20 tokens across various industries.

    Advantages of Using ERC20 Tokens Over Other Types of Tokens

    Anyone interested in the blockchain ecosystem should understand the benefits of using ERC20 tokens over other types of tokens. These tokens can serve multiple purposes, such as trading, user incentives, and fundraising. Compared to other token types, ERC20 tokens offer several advantages:

    • Standardization: To ensure interoperability among various ERC20 tokens, the standard provides a set of rules and guidelines. This standardization makes it easy for developers to create and integrate new ERC20 tokens into existing platforms.
    • Security: ERC20 tokens are based on the Ethereum blockchain, a decentralized and immutable ledger, enhancing their security. This makes it difficult for hackers or other malicious actors to compromise the token’s integrity.
    • Reduced Costs: ERC20 tokens have lower transaction fees and costs because they don’t rely on intermediaries and offer quicker settlement times compared to traditional financial systems.
    • Liquidity: ERC20 tokens are highly liquid, making it easy to buy or sell them on exchanges, thus offering investors greater flexibility in managing their portfolios.

    Use Cases for ERC20 Tokens

    Understanding the use cases for ERC20 tokens is vital for grasping the potential of blockchain technology and its real-world applications. Here are some common uses:

    • Fundraising: ERC20 tokens can be used for fundraising through Initial Coin Offerings (ICOs) or Security Token Offerings (STOs). Companies and startups can issue tokens based on the ERC20 standard to attract investors.
    • Payment Systems: In various ecosystems, ERC20 tokens can serve as a form of payment. Businesses can create their own ERC20 tokens and use them to pay for goods and services within their ecosystem.
    • Reward Systems: ERC20 tokens can be transformed into points for loyalty programs, offering users rewards for using specific services or platforms.
    • Decentralized Applications: ERC20 tokens can incentivize users to contribute to decentralized applications (dApps). For instance, a dApp offering file storage services can reward users with ERC20 tokens for donating idle disk space.

    Notable Examples of ERC20 Tokens and Their Success Stories

    Successful ERC20 tokens include several prominent examples:

    • USDT (Tether): A stablecoin valued in line with the U.S. dollar, Tether has a market cap of over $50 billion and serves as both a store of value and a medium for transferring wealth between exchanges.
    • UNI (Uniswap): This is an Automated Market Maker (AMM)-based Decentralized Exchange (DEX) that facilitates trading between ERC20 tokens. The UNI token rewards liquidity providers and serves as a governance token for voting on protocol improvements.
    • BNB (Binance Coin): Developed by the Binance cryptocurrency exchange, BNB is accepted as payment for transaction fees and offers users discounts on trading costs.

    How to Create an ERC20 Token

    This section will show you how to use OpenZeppelin to create an ERC20 token, as well as generate a Solidity token called “MyToken.” Note that if the name has already been used elsewhere, it won’t impact the token’s uniqueness; the contract address serves as the unique identifier. The ERC20 token symbol will be a short name, “MYT,” which stands for MyToken.

    Short names are often generated for ERC20 tokens to enhance convenience, readability, and smart contract efficiency, as well as to facilitate trading, strengthen branding, and enable effective communication across different platforms.

    To create your token, we’ll use Remix. Start by creating a folder where you’d like to store your file. Within the folder, create a file named “MyToken.sol.” The “.sol” extension indicates a Solidity file. Once the file is created, copy the code below the GIF output and paste it into the “MyToken.sol” file. The following GIF illustrates the process of creating a Solidity file within a folder and pasting the copied code into the file using Remix.

    Below is the Solidity code that will be utilized for creating the Token:

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
    import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
    contract MyToken is ERC20Capped, ERC20Burnable {
        address payable public owner;
        uint256 public blockReward;
            uint256 cap,
            uint256 reward
        ) ERC20("MyToken", "MYT") ERC20Capped(cap * (10 ** decimals())) {
            owner = payable(msg.sender);
            _mint(owner, 50000000 * (10 ** decimals()));
            blockReward = reward * (10 ** decimals()); // Setting block reward for first deploy
        // Setting miner reward
        function _mintMinerReward() internal {
            _mint(block.coinbase, blockReward);
        // block.conbase validation for rewarding the minder; prevents miner from manipulating teh token
        function _beforeTokenTransfer(
            address from,
            address to,
            uint256 value
        ) internal virtual override {
            if (
                from != block.coinbase &&
                to != block.coinbase &&
                block.coinbase != address(0)
            ) {
            super._beforeTokenTransfer(from, to, value);
        function _mint(
            address account,
            uint256 amount
        ) internal virtual override(ERC20Capped, ERC20) {
                ERC20.totalSupply() + amount <= cap(),
                "ERC20Capped: cap exceeded"
            super._mint(account, amount);
          //Destroying the contract
        function destroyContract() public onlyOwner {
        // Set block rewards
        function setBlockReward(uint256 reward) public onlyOwner {
            blockReward = reward * (10 ** decimals());
        //reusable modifier
        modifier onlyOwner() {
            require(msg.sender == owner, "Only the owner can call this function");

    The Code Structure

    The code above is a Solidity smart contract that establishes a custom ERC20 token named “MyToken.” It inherits from three OpenZeppelin ERC20-related contracts: ERC20Capped, ERC20Burnable, and ERC20. These contracts define a maximum token supply, allow tokens to be burned, and provide basic functionality for an ERC20 token.

    The contract includes two public state variables: owner and blockReward. The owner variable identifies the owner of the contract, while the blockReward variable specifies the number of tokens awarded to the miner who successfully mines the block containing a transfer. The contract’s constructor function takes two arguments: cap and reward. cap represents the maximum token supply, and reward represents the amount given to miners who successfully mine a block containing a transfer. The constructor sets the owner variable to msg.sender, mints 50,000,000 tokens for the owner, and sets the blockReward variable to reward multiplied by 10181018, the token’s decimal precision. The decimals() function, as defined in the OpenZeppelin ERC20 standard, always returns a value of 18. This means the token can be subdivided into as many as 10181018 individual units, allowing for precise fractional ownership and facilitating small transactions.

    Additionally, the contract includes two internal functions: _mintMinerReward() and _mint(). _mintMinerReward() is triggered when a transfer is executed and mints the blockReward amount of tokens to the miner who mined the block containing the transfer. _mint() overrides the _mint() function from ERC20Capped and ERC20 to ensure the total token supply doesn’t exceed the cap. The contract also features a public function, destroyContract(), that allows the owner to terminate the contract and recover any remaining funds. It includes another public function, setBlockReward(), that allows the owner to modify the blockReward value. Finally, the contract uses a modifier, onlyOwner, to restrict access to certain functions to the contract’s owner alone.

    Deploying the Contract

    To deploy the smart contract, we’ll continue to use Remix, the platform where the contract was developed. Remix offers a user-friendly deployment process that is both simple and straightforward. In this section, we’ll provide a step-by-step guide to deploying the smart contract using Remix. To deploy the contract, follow these steps:

    • Step 1: Click on the “Compile” button, located on the left-hand side of the smart contract interface. The image below highlights the “Auto-Compile” and “Compile” buttons within a red box. If the “Auto-Compile” feature is enabled, there’s no need to manually click on the “Compile” button.
    • Step 2: It is important to ensure that the contract to be deployed is the “MyToken” contract, which is the most important contract on the list, although there might be other sub-contracts listed as well. This is because “MyToken” contract is the one that inherits from another contract. Next, click on the second checkbox to reveal two fields where the cap and the miner’s reward for the tokens can be added. Step 3 shows the result when the dropdown is clicked.
    • Step 3: Once the dropdown mentioned in Step 2 is clicked, the deployment user interface becomes standardized and easy to understand. It is now possible to enter the cap and reward values for the smart contract. For our smart contract, we will set the cap at 100 million and the miner’s reward at 50. After inputting these values, click on the “transact” button to deploy.
    • Step 4: involves the creation of a new contract after deployment. The image below shows the newly created contract, which is indicated by the red box. Please click on it.
    • Step 5: Once you click on the newly created contract, you will be able to see the list of public functions and events that were previously discussed. You are able to view details such as the token name, token symbol, total supply, block reward, and cap values that were added during deployment. It’s important to note that the cap value is initially set at 100 million with 18 zeros. This is a representation of wei, which is the smallest unit.

    Potential Dangers and Difficulties with ERC20 Tokens

    Due to security vulnerabilities, ERC20 tokens pose the risk of significant monetary or data loss. Once deployed, contract code cannot be modified, making it challenging to fix security issues. The difficulty in tracing stolen assets from smart contracts further complicates the security of ERC20 tokens. To mitigate these risks, developers must implement robust access control mechanisms and secure smart contracts.

    Another potential concern with ERC20 tokens is the threat from backdoors. Attackers can exploit certain ERC20 functions to steal funds or violate users’ privacy, affecting individual accounts or the entire system without consent. Researchers have proposed detection techniques, such as Pied-Piper, which combines datalog analysis and directed fuzzing to identify backdoor risks in ERC20 contracts. Despite their advantages, such as interoperability and programmability, both developers and users must be cognizant of and guard against these potential risks and challenges.

    Common Mistakes to Avoid When Developing ERC20 Tokens

    Developers should be aware of several common pitfalls when creating an ERC20 token:

    1. Noncompliance with the ERC20 Standard: To ensure compatibility with other tokens and wallets, it’s essential to adhere to the ERC20 standard’s rules and specifications. Noncompliance may result in incompatibility with wallets and other ERC20 tokens.
    2. Insufficient Security Measures: ERC20 tokens are susceptible to various security threats, including hacking and phishing. Developers must implement effective security measures such as multi-factor authentication and encryption.
    3. Lack of Adequate Testing: Insufficient testing can lead to bugs and errors, potentially causing significant issues like financial loss or security breaches. Developers should conduct extensive testing to ensure the token functions as intended and is secure.
    4. Poor Transparency and Documentation: Failing to clearly explain the token’s functionalities can result in misunderstandings and mistakes. Proper documentation is essential for both developers and users to understand how to interact with the token.


    I hope you found this article informative. It covers all the essentials you need to know before using an ERC20 token. We highlighted the benefits and applications of the ERC20 token and discussed potential risks. While there is much more to learn about ERC20 tokens, I believe this article provides a solid foundation. Feel free to modify the ERC20 token code discussed in this article to build a more complex token or create one for your client. Continue exploring the world of ERC20 tokens and how to generate new ones!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Writen by:
    I'm a highly experienced Web developer and Blockchain Engineer. I possess a strong skill set and expertise in technical writing. My goal is to utilize my wide range of skills and knowledge to make valuable contributions to a dynamic organization's success. I have a genuine passion for crafting top-notch web applications and producing technical content that is precise, easily understandable, and filled with valuable information.
    Reviewed by:
    I picked up most of my soft/hardware troubleshooting skills in the US Army. A decade of Java development drove me to operations, scaling infrastructure to cope with the thundering herd. Engineering coach and CTO of Teleclinic.