How I Built My Own ERC-20 Token

Girik Narang
11 min readJul 4, 2022

--

A Step-by-step Guide to Creating and Deploying an ERC-20 Token on the Ethereum Blockchain.

“The 2008 financial crisis cost the global economy trillions of dollars and destroyed trust between large financial institutions and the public, who were left to pay the price, while the large banks were bailed out.”

The year is 2009.

Following one of the worst financial disasters in history, an individual or a group of programmers under the pseudonymous name Satoshi Nakamoto issued a white paper to address the centralized control of money and the trust placed upon financial institutions in handling public assets. In the traditional financial system, transactions can be reversed or tampered with by third parties, and fees can pile up quickly. Bitcoin was presented as a way to transact without requiring a third party, making transactions more secure and dismissing a substantial percentage of fees. Rather, the unique system utilized cryptographic proof to maintain the integrity of the network instead of relying on banks and other economic institutions.

Although Bitcoin was the first of its kind, it’s safe to say that we’ve come a long way in the realm of decentralized finance (Defi) and cryptocurrency. In previous years, one of the central concerns around the popularity of these coins was that they demanded a ton of energy to verify transactions and were consequently detrimental to the environment. Nowadays, we’re seeing numerous coins transition from PoW to PoS, which not only offers further potential for scalability but is also more suitable for the environment.

In addition to these changes, initiatives like SolarCoin (which encourages distributed renewable energy generation) and FileCoin (which introduced a cheaper and safer way to store data) have shown promise that cryptocurrency is more than just a digital asset and has so many possibilities and applications. Just think about it; thousands of unique coins, each with its own purpose and identity. At first glance, it can definitely be overwhelming, especially if you’re new to this space.

To save you time, here’s a quick list of some of the more popular cryptocurrencies that you’ll likely encounter and should be familiar with:

  • Bitcoin is the first and most valuable cryptocurrency.
  • Ethereum is commonly used to carry out financial transactions more complex than those supported by Bitcoin.
  • Cardano is a competitor to Ethereum, led by one of its co-founders.
  • Litecoin is an adaptation of Bitcoin intended to make payments more manageable.
  • Solana is another competitor to Ethereum that emphasizes speed and cost-effectiveness.
  • Stablecoins are a class of cryptocurrencies whose values are designed to stay stable relative to real-world assets such as the dollar.

However, there is a crucial difference between traditional cryptos and tokens. While cryptos are the native asset of a blockchain, tokens are created by platforms and applications built on an existing blockchain. In other words, when a cryptocurrency uses or “borrows” another blockchain network, it is considered a token.

So what exactly are ERC-20 tokens?

ERC-20 Tokens

Back in 2015, when the Ethereum network first launched, developers noticed that a considerable number of people were using the platform for experimenting with token development. In the beginning, there weren’t any templates or guidelines for developing tokens. This resulted in a variety of tokens that were totally disconnected from each other. To bring this diversity to order, the community devised the ERC-20 standard to ensure that all tokens were more or less consistent. ERC is short for Ethereum Request for Comment, and 20 is the proposal identifier number.

The Ethereum platform in itself consists of a blockchain that is capable of storing transactions and a virtual machine that is capable of running smart contracts. It’s necessary to understand that tokens live on the Ethereum blockchain. They aren’t independent coins and thus rely on Ethereum’s blockchain and platform. In case you’re confused, the native currency on the Ethereum network is Ether (ETH); however, Ethereum can still sustain tokens like ERC-20 and ERC-721.

ERC-20 Tokens Live on the Ethereum Blockchain

ERC-20 is one of the most consequential ERCs since it has become the technical standard for writing smart contracts on the Ethereum blockchain, used for token implementation. ERC-20 incorporates a set of rules that all Ethereum-based tokens must obey. This standard is similar to Bitcoin and Litecoin in many aspects, as they define tokens as blockchain-based assets that can be sent/received and retain value. However, the most notable difference is that instead of running on their own blockchain network, ERC-20 tokens operate on Ethereum’s blockchain network and use gas as the transaction fee.

Before the inception of the token standard, people who created tokens had a challenging time transacting with each other since all tokens were different from one other. For instance, if a developer wanted to work with another token, they had to understand that token's entire smart contract code, as there were no specific guidelines or structures for creating new tokens. This was particularly tough for wallets and exchange platforms since adding various types of tokens required developers to go through each and every token's code and understand it to regulate those tokens on their platforms. Needless to say, it was somewhat problematic to add new tokens to any application. Today, wallets and exchanges use the ERC-20 standard to integrate various standardized tokens onto their platforms and encourage easy exchange between ERC-20 and other tokens. It’s clear that the new ERC-20 standard has made exchange between tokens systematized and effortless.

But what actually makes the ERC-20 guideline distinct from any other token standard?

The standard stipulates six mandatory functions a smart contract should implement and three optional variables the developer controls.

To begin with, you can give your token a name, symbol and state how divisible your token is by defining the number of decimals. However, you must also obey a set of mandatory functions, which are a bit more complex and listed below:

  • TotalSupply: Provides details about the total token supply
  • BalanceOf: Provides the account balance of the owner’s account
  • Transfer: Executes transfers of a determined number of tokens to a specified address
  • TransferFrom: Executes transfers of a determined number of tokens from a specified address
  • Approve: Authorizes a spender to withdraw a set number of tokens from a designated account
  • Allowance: Returns a set number of tokens from a spender to the owner

If you’re familiar with Object-Oriented programming, you can correspond ERC-20 to an Interface. If you want your token to be an ERC-20 token, you must implement the ERC-20 interface, which compels you to enforce these functions.

Now that we know what ERC-20 tokens are and how they work let’s dive deeper into how we can create and deploy our own token.

This article aims to help you develop your own ERC-20 token and provide a solid understanding of how it operates and communicates with the blockchain. Don’t hesitate to ask questions if anything is unclear!

What You’ll Need

Photo by Dose Media on Unsplash

Metamask:

When deploying a smart contract (Ethereum Mainnet or Test Network), you will require funds to cover gas fees and therefore need a wallet to store these funds. I highly recommend Metamask as your crypto wallet, although other options exist.

Remix — Ethereum IDE:

After trying multiple IDEs, I found Remix to be the best since there is no installation or need to open the terminal. I used Remix to write and deploy the smart contract for my token.

Etherscan:

Want to see the result of your hard work? With Etherscan, you can search the entire Ethereum blockchain (including test networks) for free. It displays past transactions, wallets, smart contracts, and other information related to Ethereum-based assets.

Building the Token

Step #1: Setting up Your Workspace

Set up your remix workspace with a solidity file, and name it token.sol.

Step #2: Declaring License + Solidity Version

To start, I declared the license, which is an MIT license. When announcing the solidity version, I recommend going with the latest one (unless you are following an older tutorial or a feature you require is no longer available).

Step #3: Safe Math Library

Call the safe math interface to use math functions in the contract.

This library provides mathematical functions that protect your contract from overflows and underflows. Overflow occurs when an arithmetic operation tries to form a numeric value outside the range that can be defined with a given number of bits.

Step #4: Implementing Mandatory ERC-20 Functions

Remember the mandatory functions that every ERC-20 token must include? Well, it’s time to add them to our smart contract!

The first of the six, which is the totalSupply function essentially returns the amount of these tokens that exist. This means that the total sum of the token balances of all the token holders must correspond with the total supply. Along with that, thebalanceOf function returns the balance of the owner of the address using the contract.

Thetransfer function enables transfers of tokens from the person who called the contract to another address. The transferFrom function, on the other hand, refers to the transfer of tokens you do not own but have been approved to spend. It is used together with the approve function when an address establishes a certain allowance of tokens for another address to spend for them.

Finally, the allowance function returns the amount which the spender is still allowed to withdraw from the owner.

Allowance or access permissions allow a third party to have the right to carry out a transaction of a specific amount of our tokens, which are associated with our address. For example, this can be used to authorize a contract to transfer tokens on your behalf or to charge fees in sub-currencies.

The event functions are needed if the ERC-20 contract changes for whatever reason, effectively notifying services outside of the blockchain to let users know something went wrong.

Step #5: Contract Function

A contract function to receive approval and perform a function in one call.

Step #6: Token Contract + Mapping

In my case, I chose to call itOpioid Tracking Token (sneak peek of my next project) but you can replace this with the name of your own token. Below the name, we have four defined variables— the first will keep track of the total supply, and the other three are utilized to enhance readability throughout the contract.

The two mapping functions give users the ability to spend their tokens.

Step #7: Customizing Our Token

At this point, we are initializing the constructor and choosing our token's name, symbol, decimals, and total supply value. Then we declare the total supply to be equal to your wallet’s balance for this token.

Using this, we can customize the token. The token details can be adjusted according to the needs of your own project!

  • Opioid Tracking Tokenis the name of the token.
  • OPTis the token symbol, which is short for the token's name.
  • 18is an integer value that represents token decimals. This determines how divisible your token is. The standard is 18, so I opted to go with that.
  • 1000000000000000000000is the token supply, and an integer value. This will determine the total quantity of tokens in existence. Note that the total supply value must have additional zeros depending on your decimals. For example, if your Token Decimals value is four and you want 100 tokens in existence, then you would enter 100000.
  • 0xaD29B940d55757c4B19DF62f7D7157c16e7Fdb24 is the Wallet Address.Replace this with your Metamask Wallet Address (you can copy and paste this directly from the Metamask extension in your browser). This is also where the initial pool of tokens will go.

Step #8: Final Functions

totalSupply returns the total supply of tokens.

balanceOfwill return the balance or amount of tokens held at the wallet address.

transfer will execute the transfer of tokens from the sender’s account to a different one. The transfer function must emit the transfer event (created earlier) on a successful transfer of tokens.

transferFrom is what a spender calls to spend an allowance. It requires two operations: transfer the amount being spent and lower the allowance by that amount.

approve will check if the total supply has the amount of token which needs to be allocated to a user.

allowance will allow anybody to check if a user has enough balance to perform the transfer to another user.

approveAndCall will execute the transactions of buying and spending tokens.

public payable prevents accounts from directly sending ETH to the contract and users paying gas on transactions where they forget to mention the function name.

Step #9: Deploying Your Token

Now that the code is finalized, let’s compile and deploy our Token! First, confirm that your Metamask wallet is connected to a test network.

Start by heading over to the solidity compiler and ensure you have chosen the correct one. Once your file is compiled, you should notice a green checkmark on the Solidity Compiler icon.

Next, click “Deploy and Run Transactions” on the left and set the environment to Injected Web3. Set the contract to your token’s name, and hit deploy. If everything is running correctly, your Metamask extension will open and prompt you to pay gas fees to deploy the contract. Don’t worry; it won’t cost you anything. Instead, we’ll be using test ETH from a faucet. I recommend using the Rinkeby test network. However, feel free to use whichever one you are most familiar with.

After clicking confirm, wait a few seconds for your token to be added to the blockchain. Then extend the terminal, and click on “block” to show details about the transaction. Once you locate your contract address, copy it as you’ll require it for this last step.

Step #10: View Your Token on Etherscan

Are you ready to see your hard work in action?

Copy the transaction hash from your smart contact and search it on Etherscan. You should see your token popup, and from there, you can verify that you are the owner of it.

You can also import tokens directly into your Metamask wallet by going into the extension, clicking “Assets” thenImport Tokens.” Finally, paste your token address and click “Add Custom Token.”

So how did it go for you? Were you able to successfully follow along?

If you’re seeking more clarification behind the code or want to see the token deployed, check out this video I made where I walk you through the entire project.

This project was modified from CodeWithJoe’s How To Create Your Own Ethereum Token tutorial. See the original Github project here:

Let’s Connect!

If you enjoyed reading this article or learned something new, I’d love to connect on LinkedIn. If you’d like to stay updated on my recent articles or projects, you can subscribe to my monthly newsletter here!

--

--

Girik Narang
Girik Narang

Written by Girik Narang

just trying to solve problems.

No responses yet