Creating Your Own ERC20 Token

Sohan Rasul
10 min readMar 23, 2022

Ethereum network’s launch in 2015 created a lot of buzz in the developer community and sprouted a lot of tokens on the network. Initially, there weren’t any templates or guidelines for token development. This resulted in a variety of tokens quite different from each other. To bring this diversity to order the community came up with an ERC-20 standard to make all tokens more or less uniform.

What is an ERC20 Token?

ERC stands for Ethereum Request for Comment, and 20 is the proposal identifier number. ERC-20 was designed to improve the ETH network.

ERC-20 is one of the most significant ERCs. It has emerged as the technical standard for writing smart contracts on the Ethereum blockchain network, used for token implementation. ERC-20 contains a set of rules that all Ethereum based tokens must follow.

ERC-20 defines tokens as blockchain-based assets that can be sent/received and have value. ERC-20 tokens are similar to Bitcoin and Litecoin in many aspects. However, the most significant difference is that instead of running on their own blockchain network, ERC-20 coins run on Ethereum’s blockchain network and use gas as the transaction fee.

Before the emergence of ERC-20, everyone who created tokens had to reinvent the wheel, which means all tokens were different from each other. For example, if a developer wanted to work with another token, they had to understand the entire smart contract code of that token due to the lack of any specific structure or guidelines for building new tokens. This was particularly painful for wallets and exchange platforms — adding different types of tokens required developers to go through the code of each and every token and understand it in order to handle those tokens on their platforms. Needless to say, it was rather difficult to add new tokens to any app. Today wallets and exchanges use the ERC-20 standard to integrate various standardized tokens onto their platforms and also facilitate easy exchange between ERC-20 tokens and other tokens. The ERC-20 token standard has made interaction between tokens almost seamless and painless.

Token smart contracts are not only responsible for creating tokens but also for handling transactions and keeping track of the balances of each token holder. To get some tokens one has to send some ETH to the token’s contract in return for allocated tokens.

ERC-20 is a standard or guideline for creating new tokens. The standard defines six mandatory functions that a smart contract should implement and three optional ones.

To start you can give your token a name, a symbol, and mention how dividable your token is, by specifying the decimals. ERC specifies a set of mandatory functions, which are a bit more complex and listed below:

  • totalSupply: A method that defines the total supply of your tokens, When this limit is reached the smart contract will refuse to create new tokens.
  • balanceOf: A method that returns the number of tokens a wallet address has.
  • transfer: A method that takes a certain amount of tokens from the total supply and gives it to a user.
  • transferFrom: Another type of transfer method which is used to transfer tokens between users.
  • approve: This method verifies whether a smart contract is allowed to allocate a certain amount of tokens to a user, considering the total supply.
  • allowance: This method is exactly the same as the approved method except that it checks if one user has enough balance to send a certain amount of tokens to another.

If you know something about Object Oriented programming you can compare ERC-20 to an Interface. If you want your token to be an ERC-20 token, you have to implement the ERC-20 interface and that forces you to implement these 6 methods.

The goal of this article is to demonstrate how to create an ERC20 token in as little time as possible.

What You’ll Need

Metamask:

When deploying a smart contract, you will require funds to cover gas fees; and therefore you will require a crypto wallet to store these funds such as Metamask.

Remix — Ethereum IDE:

Remix is an online Ethereum IDE that can be used to write and deploy the smart contract (backend).

Writing an ERC20 Token in Solidity

Now that we’ve outlined the basics and explained what it takes to create an ERC20 token, it is time to start writing some logic.

Head over to your online Remix IDE and set up your remix workspace and create a solidity file named ERC20.sol

Step 1: Defining Mapping Objects

First, we need to define two mapping objects. This is the Solidity code for an associative or key/value array:

The expression mapping(address => uint256) defines an associative array whose keys are of type address— a number used to denote account addresses, and whose values are of type uint256 — a 256-bit integer typically used to store token balances.

The first mapping object, balances, will hold the token balance of each owner account.

The second mapping object, allowed, will include all of the accounts approved to withdraw from a given account together with the withdrawal sum allowed for each.

As you can see, the value field of the allowed mapping is by itself a mapping plotting account address to its approved withdrawal sum.

These mappings together with all other contract fields will be stored in the blockchain and will be mined resulting in changes being propagated to all network user nodes.

Blockchain storage is expensive and users of your contract will need to pay for, one way or another. Therefore you should always try to minimize storage size and writes into the blockchain.

Now that we have the required data structures in place, we can start to actually write the ERC20 logic into the appropriate functions.

Step 2: Setting the Number of ICO Tokens

How do we set the number of ICO tokens? Well, there are a number of ways of setting the maximal number of ICO tokens and this matter might be worth a lengthy discussion by itself.

For the needs of our ECR20 tutorial, we shall use the simplest approach: Set the total amount of tokens at contract creation time and initially assign all of them to the “contract owner” i.e. the account that deployed the smart contract:

A constructor is a special function automatically called by Ethereum right after the contract is deployed. It is typically used to initialize the token’s state using parameters passed by the contract’s deploying account.

msg is a global variable declared and populated by Ethereum itself. It contains important data for performing the contract. The field we are using here: msg.sender contains the Ethereum account executing the current contract function.

Only the deploying account can enter a contract’s constructor. When the contract is started up, this function allocates available tokens to the ‘contract owner’ account.

Step 3: Get Total Token Supply

This function will return the number of all tokens allocated by this contract regardless of owner.

Step 4: Get Token Balance of Owner

balanceOf will return the current token balance of an account, identified by its owner’s address.

Step 5: Transfer Tokens to Another Account

As its name suggests, the transfer function is used to move numTokens amount of tokens from the owner’s balance to that of another user, or receiver. The transferring owner is msg.sender i.e. the one executing the function, which implies that only the owner of the tokens can transfer them to others.

Solidity’s way of asserting a predicate is require. In this case that the transferring account has a sufficient balance to execute the transfer. If a require statement fails, the transaction is immediately rolled back with no changes written into the blockchain.

Right before exiting, the function fires ERC20 event Transfer allowing registered listeners to react to its completion.

Step 6: Approve Delegate to Withdraw Tokens

This function is most often used in a token marketplace scenario.

What approve does is to allow an owner i.e. msg.sender to approve a delegate account — possibly the marketplace itself — to withdraw tokens from his account and to transfer them to other accounts.

As you can see, this function is used for scenarios where owners are offering tokens on a marketplace. It allows the marketplace to finalize the transaction without waiting for prior approval.

At the end of its execution, this function fires an Approval event.

Step 7: Get Number of Tokens Approved for Withdrawal

This function returns the current approved number of tokens by an owner to a specific delegate, as set in the approve function.

Step 8: Transfer Tokens by Delegate

The transferFrom function is the peer of the approve function, which we discussed previously. It allows a delegate approved for withdrawal to transfer owner funds to a third-party account.

The two require statements at function start are to verify that the transaction is legitimate, i.e. that the owner has enough tokens to transfer and that the delegate has approval for (at least) numTokens to withdraw.

In addition to transferring the numTokens amount from owner to buyer, this function also subtracts numTokens from the delegate’s allowance. This basically allows a delegate with a given allowance to break it into several separate withdrawals, which is typical marketplace behavior.

We could stop here and have a valid ERC20 implementation. However, we want to go a step further, as we want an industrial strength token. This requires us to make our code a bit more secure, though we will still be able to keep the token relatively simple, if not basic.

Step 9: SafeMath Solidity Library

SafeMath is a Solidity library aimed at dealing with one way hackers have been known to break contracts: integer overflow attack. In such an attack, the hacker forces the contract to use incorrect numeric values by passing parameters that will take the relevant integers past their maximal values.

SafeMath protects against this by testing for overflow before performing the arithmetic action, thus removing the danger of overflow attack. The library is so small that the impact on contract size is minimal, incurring no performance and little storage cost penalties.

Let’s add SafeMath to our code:

SafeMath uses assert statements to verify the correctness of the passed parameters. Should assert fail, the function execution will be immediately stopped and all blockchain changes shall be rolled back.

Next, let us add the following statement introducing the library to the Solidity compiler:

using SafeMath for uint256;

Then, we replace the naive arithmetics we used at the beginning with SafeMath functions:

Ethereum Contract Deployment

The time has come to deploy our contract to the blockchain. Following deployment, our contract will be transferred to all nodes participating in the network. Any and all changes made to the contract will be propagated to all participating nodes.

Before deploying though, you will need to ensure that you have changed your metamask account to the rinkeby testnet and added ether to it via a faucet.

Once that is complete, in order to deploy our contract, we will hop over to the second tab to the right called “Run” and click “Deploy.” A MetaMask popup will appear asking us to confirm the transaction. Of course, we’ll approve it.

Congrats! You have just deployed your first ERC20 token, like a true Ethereum professional. As promised, the token is simple and lightweight, yet fully functional, ERC20 standard compliant, and secured with MathSafe. It is ready to be purchased, paid with, and transferred throughout the Blockchain.

If you have made it this far, thank you for following along with this tutorial and if it helped, be sure to check out the full code on my GitHub and connect with me on Linkedin if you have any questions. Check out this YouTube video to see a step-by-step visual walkthrough of this tutorial.

--

--