Select Page

How to create ERC-20 token on Ethereum network?

erc-20-token-on-ethereum

The popularity and wide use of the ERC20 tokens have grown a lot in the Ethereum blockchain space in recent years. As most Ethereum contracts are ERC-20 compliant these days, it can be very useful for Ethereum developers and investors to have detailed knowledge about this token.

Features like simplicity, ease of use, and ease of deployment contribute to the success and popular use of ERC-20 tokens. The ERC20 standard resolve a crucial problem faced by crypto-wallets and blockchain-based marketplaces by including rules of interaction with other tokens along with purchase rules.

Implemented as smart contracts, ERC20 tokens are executed on the Ethereum Virtual Machine in a decentralized way, just like other Ethereum tokens.

Solidity

Solidity is the language used to write Ethereum smart contracts. Developers knowledgeable in JavaScript or C-like languages can easily figure out code written in Solidity.

In this article, we will show how to create an ERC20 contract with the use of Solidity and deploy an ERC20 token quickly. Before that, let’s have a quick overview of ERC20.

What is ERC20?

ERC20 standard defines the set of functions (which are short and basic) that all ERC20 tokens have to implement in order to enable integration with other contracts, marketplaces, or wallets.

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);

These functions allow external users like crypto-wallet apps to find out balance of a user’s account and transfer funds to another user with proper authorization.

Two specifically events are defined by the smart contract.

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

When a user is granted the rights to withdraw tokens from an account and the tokens are transferred, these events are invoked or emitted.
Many ERC20 tokens feature additional fields like:

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

ERC20 and Solidity nomenclature’s vital features include:

  • public function – This function can be accessed outside of the contract itself
  • view function – In simple words, it means ‘constant’. It implies that the internal state of the contract will not be changed by the function.
  • event function – This function allows clients to be notified about certain occurrences in the contract.

Writing an ERC20 Token in Solidity

1. Find mapping objects

According to the Solidity notion for a key/value or associative array, you must find two mapping objects:

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

· mapping(address => uint256) – It is defining an associative array that has keys of the type address (a number that is used to denote account addresses) and that has values of the type uint256 (a 256-bit integer that is used to store token balances).

· balances – It is the first mapping object that will hold the token balance of each owner’s account.

· allowed – It is the second mapping object that will include all of the accounts that have been approved to withdraw tokens from a given account and the withdrawal sum that has been allowed for each account.

These mappings will be stored in the blockchain along with all other contract fields. Then, they will be mined to propagate changes across all user nodes of the network. One should always try to minimize storage size because blockchain storage is expensive and users of a smart contract need to pay for it.

Now, let’s start writing ERC20 logics into the apt functions.

2. Set the Number of ICO Tokens

There are several ways through which you can set the maximal number of ICO tokens. However, in this article, we will use the simplest approach by setting the total amount of tokens at the time of contract creation and initially assigning all of them to the account owner (the accounts that has deployed the smart contract):

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

constructor – A special function called by Ethereum automatically after the contract is deployed for initializing the token’s state by using parameters passed by the contract’s deploying account.

msg – A global variable that is declared and populated by Ethereum itself, as it holds crucial data for performing the contract.

msg.sender – The field that contains the Ethereum account that is executing the current contract function.

The account responsible for deployment is the only one that can enter a contract’s constructor as this function is responsible for allocating the available tokens to the ‘contract owner’ account once the contract has started up.

3. Get the Total Token Supply

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

This function is responsible for returning the number of all tokens allocated by this contract irrespective of the owner.

1.Get Token Balance of the Owner.

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

balanceOf – The function responsible for returning the current token balance of an account, identified by its owner’s address.

1.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;
}

transfer – The function responsible for moving numTokens (amount of tokens) from the owner’s balance to receiver (another user).

msg.sender – It represents the transferring owner who is the one executing the function. Only the owner of the tokens can transfer them to other users.

require – Statement used by solidity to assert a predicate. If the account doesn’t have enough balance to execute the transfer and this statement fails, the transaction will roll back immediately without any changes being written into the blockchain.

 

Build your customized project-specific ERC tokens with

LeewayHertz Ethereum Token Development Services

4. Approve Delegates to Withdraw Tokens.

This function is mostly 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;
}

approve – The function that allows the msg.sender (the owner) to give approval to a delegate account for withdrawing tokens from their account and transferring them to other accounts.

This function is mostly used for scenarios where owners are offering tokens in a marketplace, as it enables the marketplace to finalize the transaction without waiting for prior approval.

An Approval event is fired by this function at the end of its execution.

5. Get the Number of Tokens Approved for Withdrawal

This function is mostly used in a token marketplace scenario.

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.

1.Transfer of Tokens by Approved Delegates.

transferFrom – The function that allows the delegate who approved for withdrawal to transfer the 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 the beginning of the function start are responsible for verifying that the transaction being conducted is legitimate or not, if the owner has enough balance to transfer the tokens, and that the delegate has been approved to withdraw the numTokens.

In addition, this function also subtracts the numTokens from the delegate’s allowance. As per the typical marketplace behavior, the delegate is allowed to break their given allowance into several separate withdrawals.

By the end of this step, you’ll have a valid ERC20 implementation. However, to gain a token with industrial strength, a few more steps are required.

6. Add the SafeMath Solidity Library

SafeMath is a solidity library that aims at tackling one-way hackers who are known to break contracts via integer overflow attack.

Integer Overflow Attack – By passing parameters that’ll take relevant integers past their maximal values, the contract is forced by the hacker to use incorrect numeric values.

With the help of SafeMath, you can protect your contract against this attack. It tests the contract for overflow before performing the arithmetic action. This step eliminates the risk of an overflow attack. Also, the SafeMath library is incredibly small in size. So, it incurs no penalties on performance and storage costs.

You can add SafeMath library to your contract by:

library SafeMath { // Only relevant functions
function 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;
}
}

assert – Statements used by SafeMath for verification of the correctness of the passed parameters. In case this statement fails, it will immediately stop the function execution and roll back all the blockchain changes.

Use the following statement to add the library to the Solidity compiler:

using SafeMath for uint256;

After that, replace the following in your previously written code 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);

All smart contract’s functions and events are wrapped together in Solidity into a ‘contract’, also known as a ‘blockchain class’.

Deployment of Ethereum Contract

Usually, Ethereum developers leverage deployment tools like Truffle or Remix (which is a simpler tool compared to Truffle). To use Remix, you must install the MetaMask plugin on your browser, and must have a Rinkeby account (Rinkeby is an Ethereum test network) with a minimum of one Rinkeby Ether in it.

After deployment, your contract will be transferred to all the nodes participating in the network. So, any changes that you make to the contract will be propagated to all participating nodes.

After installing everything, you should go to Remix and paste your code, including the pragma line and the SafeMath library.

After pasting the code in the online editor, move over to the second tab and click “Deploy”. Once you approve the confirmation of the transaction, you’ll successfully deploy an ERC20 token! It will be ready to be purchased, paid with, and transferred throughout the Blockchain.

Conclusion

The contract discussed in this article is a brief demonstration of how Ethereum smart contracts are developed. Smart contracts increase in complexity depending on your:
business logic

  • user interaction’s modelling
  • choice of minting or burning tokens
  • introduction of lifecycle changes
  • need of admin-level capabilities, etc.

In this article, we showed you how you can create ERC20 tokens on your own. By following the intricate steps effectively and paying close attention to all the details, you can create and deploy ERC20 tokens successfully.

While the basics of the process don’t look highly complex, it can be a really troublesome task to do the entire process effectively and without any mistakes. It is noteworthy that creating and deploying ERC20 tokens that match your requirements can be a complex task, which demands a lot of significant effort, careful work, expert guidance, and proper supervision to ensure seamless proceedings. Partnering with a highly-efficient Ethereum development team or firm can make it much easier for you to deal with all the intricate complexities of creating and deploying an ERC20 token. Leveraging the expertise and experience of Ethereum professionals can help you easily implement all your requirements, meet your expectations, and successfully create and deploy your ERC20 token.

LeewayHertz is one of the leading software development companies of the blockchain space. With highly experienced developers, our team of experts can help you with all kinds of Ethereum services that you require.

If you are looking for a blockchain development partner for creating and deploying ERC20 tokens or any other Ethereum-related services, please feel free to contact our experts.

Webinar Details

Author’s Bio

Akash Takyar
Akash Takyar
CEO LeewayHertz
Akash Takyar is the founder and CEO at LeewayHertz. The experience of building over 100+ platforms for startups and enterprises allows Akash to rapidly architect and design solutions that are scalable and beautiful.
Akash's ability to build enterprise-grade technology solutions has attracted over 30 Fortune 500 companies, including Siemens, 3M, P&G and Hershey’s. Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.

All information will be kept confidential.

 

Insights