ERC20 Token Tutorial | Toptal® (2024)

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

Let’s start with the basics: What is an ERC20 token?

In recent years, the ERC20 token specification has become the defacto standard for Ethereum tokens. In other words, most Ethereum contracts out there today are ERC20-compliant. This article will detail how you can create your own Ethereum token, but before we get started, let’s take a closer look at the ERC20 standard.

ERC20 Token Tutorial | Toptal® (1)

What makes ERC20 tokens so attractive and successful? There are several factors in play:

  1. ERC20 tokens are simple and easy to deploy, as you will see in this tutorial.
  2. The ERC20 standard solves a significant problem, as blockchain-based marketplaces and crypto-wallets need a single, standardized set of commands to communicate with the range of tokens they manage. This includes interaction rules between different tokens, as well as token purchase rules.
  3. It was the first popular specification to offer Ethereum token standardization. It was not by any means the first, but thanks to its popularity, it quickly became the industry standard.

Just like other Ethereum tokens, ERC20 token contracts are implemented as smart contracts and executed on the Ethereum Virtual Machine (EVM) in a decentralized manner.

Solidity: the Smart Contract Programming Language

Ethereum smart contracts are written in Solidity. While there are alternative languages, hardly anyone uses them for this purpose. Solidity is similar to JavaScript, so if you have some knowledge of JavaScript, or even Java and other C-like languages, you should have no trouble figuring out that a piece of code in Solidity does, even before you actually master Solidity enough to use it.

This is where the fun starts, as you should be able to start creating a simple ERC20 token contract in no time. This is a straightforward task, simple enough that this article will demonstrate how you can write and deploy an ERC20 token in under an hour.

The ERC20 token code we will be creating in this demonstration will be a bare-bones implementation, without too many bells and whistles. However, I have seen many similarly simple tokens in the real world, and they tend to do quite well.

Overview of ERC20 Token Standard

What is ERC20?

Put simply, the ERC20 standard defines a set of functions to be implemented by all ERC20 tokens so as to allow integration with other contracts, wallets, or marketplaces. This set of functions is rather short and basic.

function totalSupply() public view returns (uint256);function balanceOf(address tokenOwner) public view returns (uint);function allowance(address tokenOwner, address spender)public view returns (uint);function transfer(address to, uint tokens) public returns (bool);function approve(address spender, uint tokens) public returns (bool);function transferFrom(address from, address to, uint tokens) public returns (bool);

ERC20 functions allow an external user, say a crypto-wallet app, to find out a user’s balance and transfer funds from one user to another with proper authorization.

The ERC20 smart contract defines two specifically defined events:

event Approval(address indexed tokenOwner, address indexed spender, uint tokens);event Transfer(address indexed from, address indexed to, uint tokens);

These events will be invoked or emitted when a user is granted rights to withdraw tokens from an account, and after the tokens are actually transferred.

In addition to standard ERC20 functions, many ERC20 tokens also feature additional fields and some have become a de-facto part of the ERC20 standard, if not in writing then in practice. Here are a few examples of such fields.

string public constant name;string public constant symbol;uint8 public constant decimals;

Here are a few points regarding ERC20 and Solidity nomenclature:

  • A public function can be accessed outside of the contract itself
  • view basically means constant, i.e. the contract’s internal state will not be changed by the function
  • An event is Solidity’s way of allowing clients e.g. your application frontend to be notified on specific occurrences within the contract

Most Solidity language constructs should be clear if you already possess essential Java/JavaScript skills.

Writing an ERC20 Token in Solidity

ERC20 Token Tutorial | Toptal® (2)

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.

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

mapping(address => uint256) balances;mapping(address => mapping (address => uint256)) allowed;

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.

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:

uint256 totalSupply_;constructor(uint256 total) public { totalSupply_ = total; balances[msg.sender] = _totalSupply;}

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.

Get Total Token Supply

function totalSupply() public view returns (uint256) { return totalSupply_;}

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

Get Token Balance of Owner

function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner];}

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

Transfer Tokens to Another Account

function transfer(address receiver, uint numTokens) public returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender] — numTokens; balances[receiver] = balances[receiver] + numTokens; emit Transfer(msg.sender, receiver, numTokens); return true;}

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.

Approve Delegate to Withdraw Tokens

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

function approve(address delegate, uint numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true;}

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.

Get Number of Tokens Approved for Withdrawal

function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate];}

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

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.

function transferFrom(address owner, address buyer, uint numTokens) public returns (bool) { require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner] — numTokens; allowed[owner][msg.sender] = allowed[from][msg.sender] — numTokens; balances[buyer] = balances[buyer] + numTokens; Transfer(owner, buyer, numTokens); return true;}

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.

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.

ERC20 Token Tutorial | Toptal® (3)

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:

library SafeMath { // Only relevant functionsfunction sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a — b;}function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c;}}

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:

balances[msg.sender] = balances[msg.sender].sub(numTokens);balances[receiver] = balances[receiver].add(numTokens);balances[buyer] = balances[buyer].add(numTokens);balances[owner] = balances[owner].sub(numTokens);

Packing it all Together

In Solidity, a smart contract’s functions and events are wrapped into an entity called a contract which you can silently translate to a “blockchain class.” Below is the ERC20-compatible contract we created, including a Gist of our code. The name and symbol fields can be changed at will. Most tokens keep the decimal value at 18, so we will do the same.

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.

Ethereum developers usually employ deployment tools such as Truffle. Even Truffle is overkill for the limited needs of this article, and a simple online tool called Remix will suffice.

To use it, you will need to install the MetaMask plugin on your browser and a Rinkeby (Ethereum test network) account with at least some Rinkeby Ether in it. These are relatively simple steps, so we won’t go into detail.

In case you don’t have either, head over to MetaMask and Rinkeby for download links and to get clear installation and usage directions.

Now that we have all the building blocks in place, we will head over to Remix and paste the code above, including the pragma line and the SafeMath library, into the online editor.

Then, 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.

  • Green box: Make sure you’re on Rinkeby
  • Blue box: Set your total token supply
  • Red box: Deploy!

Gist: https://gist.github.com/giladHaimov/8e81dbde10c9aeff69a1d683ed6870be#file-basicerc20-sol

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.

Is that all there is to smart contracts?

No, not even close, as our brief demonstration barely scratches the surface and deals solely with one aspect of smart contract development.

Smart contracts can be much more complex depending on your business logic, your modeling of the user interaction, whether or not you allow token minting and burning, lifecycle changes you introduce into the contract, the need for admin-level capabilities which usually comes with an admin-authorized set of functions, and so on. You get the picture.

Still, if you can replicate what we did here, that is a solid foundation to expand your knowledge and move on to more complex contracts when necessary.

Further Reading on the Toptal Blog:

  • Time-locked Wallets: An Introduction to Ethereum Smart Contracts
  • The Ultimate ENS and ĐApp Tutorial
  • Investing in Cryptocurrencies: The Ultimate Guide
  • One-click Login With Blockchain: A MetaMask Tutorial
  • Blockchain, IoT, and the Future of Transportation: Understanding the Motoro Coin

Understanding the basics

  • What is a smart contract?

    A smart contract is a piece of code executed on the Ethereum Virtual Machine. An Ethereum smart contract is immutable and can send or receive ether and data.

  • What are ERC20 tokens?

    Put simply, ERC20 tokens are contracts that implement the ERC20 standard. Operations handled by these contracts include getting the total supply and balance of tokens, and the methods used to transfer them.

  • What programming language does Ethereum use?

    Ethereum development is currently conducted in Solidity, a contract-oriented programming language inspired by JavaScript, Python, and C++.

  • What does ERC stand for?

    ERC stands for Ethereum Request for Comment. The number 20 is assigned to this request, hence the suffix.

Tags

  • Ethereum
  • Solidity
  • ERC20
ERC20 Token Tutorial | Toptal® (2024)

FAQs

How much does it cost to create an ERC20 token? ›

On average, the cost to create ERC20 token lies between $5000 to $10,000, depending on the type of token developed and business requirements.

How do ERC20 tokens work? ›

ERC20 is a community-proposed standard for smart contracts and tokens associated with them. The standard allows users to transfer tokens and be re-used by any other Ethereum application. It also makes it easier for them to be approved because the standardized elements must all be present.

Can I create my own token? ›

You can create either a crypto coin or a token. There can be only one coin per blockchain, and you make it when building a new blockchain. Tokens are plenty, and they are easier to develop. Any crypto token is essentially a smart contract living on a blockchain.

How long does it take to create an ERC20 token? ›

If you want to learn how to create and deploy an ERC20 Token In 20 minutes, that's the right place to be. In this tutorial, you're going to understand how to create a cryptocurrency using Solidity and the ERC20 Token standard (Ethereum request of comment) maintained by OpenZeppelin.

What is ERC20 token generator? ›

Token Creation: To create an ERC-20 token, developers write a smart contract using Solidity (Ethereum's programming language) that adheres to the ERC-20 standard. The smart contract defines parameters such as the token's name, symbol, decimal places, initial supply, and functions for token transfers and management.

How do you creating your own token with no code explain? ›

Overview of No-Code Platforms

No-code platforms are tools designed to let users create tokens without needing to write any code. These platforms provide user-friendly interfaces where you can define the properties of your token and deploy it on a blockchain.

What are the disadvantages of ERC-20? ›

Despite their numerous advantages, ERC-20 tokens are not without their risks and drawbacks: Security vulnerabilities: Malicious actors can exploit vulnerabilities in ERC20 smart contracts, leading to security breaches and token theft.

Is ERC-20 a token or coin? ›

ERC-20 is the standard for tokens in the Ethereum ecosystem. Many other tokens, blockchains, and ecosystems have derived from Ethereum. One such ecosystem and blockchain belongs to Binance, the cryptocurrency exchange. The team behind Binance created its own blockchain, the Binance Chain, from an Ethereum fork.

How do I know if my token is ERC-20? ›

You can use a tool or library to call these functions on the target address. Evaluating Return Values: If the function calls succeed and return valid values (e.g., a non-zero balance or a total token supply), it's a strong indication that you're dealing with an ERC20 token contract.

How do I manually add an ERC20? ›

If you cannot find the token when you click the Assets tab, then you might need to add the token manually. Click the Add Token tab and select Custom Token to expand the search. You are required to enter the token address at the appropriate field.

Top Articles
American: Dallas – Ontario, California (and vice versa). $108. Roundtrip, including all Taxes
Android
Artem The Gambler
Www.1Tamilmv.cafe
Brady Hughes Justified
J & D E-Gitarre 905 HSS Bat Mark Goth Black bei uns günstig einkaufen
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
1970 Chevelle Ss For Sale Craigslist
Txtvrfy Sheridan Wy
Martha's Vineyard Ferry Schedules 2024
2024 Fantasy Baseball: Week 10 trade values chart and rest-of-season rankings for H2H and Rotisserie leagues
Trade Chart Dave Richard
Moviesda Dubbed Tamil Movies
Rochester Ny Missed Connections
Rainfall Map Oklahoma
Clairememory Scam
Oriellys St James Mn
Pro Groom Prices – The Pet Centre
Things To Do In Atlanta Tomorrow Night
Reddit Wisconsin Badgers Leaked
Costco Gas Foster City
Webcentral Cuny
Ally Joann
Amazing deals for DKoldies on Goodshop!
Great Clips Grandview Station Marion Reviews
Baja Boats For Sale On Craigslist
Rubber Ducks Akron Score
Wrights Camper & Auto Sales Llc
Danielle Ranslow Obituary
Abga Gestation Calculator
Lilpeachbutt69 Stephanie Chavez
Miles City Montana Craigslist
Math Minor Umn
What does wym mean?
Rund um die SIM-Karte | ALDI TALK
Σινεμά - Τι Ταινίες Παίζουν οι Κινηματογράφοι Σήμερα - Πρόγραμμα 2024 | iathens.gr
2012 Street Glide Blue Book Value
Log in or sign up to view
Zero Sievert Coop
Natashas Bedroom - Slave Commands
8 Ball Pool Unblocked Cool Math Games
This 85-year-old mom co-signed her daughter's student loan years ago. Now she fears the lender may take her house
Cnp Tx Venmo
Brandon Spikes Career Earnings
Mathews Vertix Mod Chart
Frontier Internet Outage Davenport Fl
Gelato 47 Allbud
Is TinyZone TV Safe?
Assignation en paiement ou injonction de payer ?
Unbiased Thrive Cat Food Review In 2024 - Cats.com
Turning Obsidian into My Perfect Writing App – The Sweet Setup
Noaa Duluth Mn
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 6244

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.