The goal of this article is to demonstrate how to create an erc20 token in the shortest possible time.
let’s start with the basics: what is an erc20 token?
Reading: How to create a token on ethereum
In recent years, the erc20 token specification has become the de facto standard for ethereum tokens. In other words, most Ethereum contracts in existence 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.
what makes erc20 tokens so attractive and successful? there are several factors at play:
- erc20 tokens are simple and easy to implement, as you will see in this tutorial.
- the erc20 standard solves a major problem, as blockchain-based markets and crypto wallets they 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.
- was the first popular specification that offered standardization of ethereum tokens. it was by no means the first, but thanks to its popularity, it quickly became the industry standard.
Like other ethereum tokens, erc20 tokens are implemented as smart contracts and run on the ethereum virtual machine (evm) in a decentralized manner.
solidity: the smart contract programming language
This is where the fun begins, as you should be able to start creating a simple erc20 contract in no time. this is a simple task, simple enough that this article demonstrates how you can write and implement an erc20 token in less than an hour.
The token we will create in this demo will be a basic implementation of erc20, without too many bells and whistles. however, I’ve seen many similar simple tokens in the real world, and they tend to work quite well.
erc20 token standard overview
what is erc20?
In a nutshell, the erc20 standard defines a set of functions that all erc20 tokens will implement to enable integration with other contracts, wallets or marketplaces. this set of functions is quite short and basic.
erc20 features allow an external user, for example a crypto wallet application, to find out a user’s balance and transfer funds from one user to another with proper authorization.
the smart contract defines two specifically defined events:
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 the standard erc20 features, many erc20 tokens also have additional fields and some have become a de facto part of the erc20 standard, if not in writing, in practice. here are some examples of such fields.
here are some points regarding erc20 and robustness nomenclature:
- A public function can be accessed outside of the contract itself
- view basically means constant, i.e. the internal state of the contract will not be changed by the function
- an event is solidity’s way of allowing clients to e.g. your application’s interface to receive notifications about specific events within the contract
write an erc20 token to solidity
Now that we’ve outlined the basics and explained what it takes to create an erc20 token, it’s time to start writing some logic.
First, we need to define two mapping objects. this is the notion of robustness for an associative array or key/value:
the expression mapping(address => uint256) defines an associative array whose keys are of type address, a number used to indicate the account addresses, and whose values are of type uint256 — a 256-bit integer that typically used to store balance tokens.
The first mapping object, balances, will contain the token balance of each owner account.
The second allocation object, Allowed, will include all accounts approved for withdrawals from a given account along with the allowable withdrawal amount for each.
As you can see, the allowed mapping value field is itself a mapping that maps the address of the account to its approved withdrawal amount.
These mappings along with all other fields in the contract will be stored on the blockchain and mined, resulting in the changes being propagated to all user nodes on the network.
Blockchain storage is expensive and users on your contract will have to pay for it, one way or another. therefore, you should always try to minimize storage size and writes to the blockchain.
Now that we have the required data structures in place, we can start writing the erc20 logic in the appropriate functions.
set the number of ico tokens
how do we set the amount of ico tokens? well, there are several ways to set the maximum number of ico tokens and this topic might be worth discussing on its own.
For the needs of our ecr20 tutorial, we will use the simplest approach: set the total number of tokens at the time of contract creation, and initially allocate them all to the “contract owner”, i.e. the account that implemented the contract. smart contract:
A constructor is a special function automatically called by ethereum right after the contract is implemented. typically used to initialize the state of the token using parameters passed by the contract implementation account.
msg is a global variable declared and populated by ethereum itself. contains important data for the execution of the contract. the field we are using here: msg.sender contains the ethereum account that is running the current contract function.
Only the implementation account can enter the constructor of a contract. when the contract is started, this function allocates the available tokens to the “contract owner” account.
get total token supply
this function will return the number of all tokens allocated by this contract regardless of owner.
get token balance from owner
balanceof will return the current balance of an account’s token, identified by its owner’s address.
transfer tokens to another account
As its name suggests, the transfer function is used to move a number of numtokens from the owner’s balance to that of another user or recipient. the owner of the transfer is msg.sender, that is, the one that executes the function, which implies that only the owner of the tokens can transfer them to others.
the way solidity asserts a predicate is require. in this case that the transferring account has sufficient balance to execute the transfer. if a required statement fails, the transaction is immediately rolled back with no changes written to the blockchain.
Just before exiting, the function triggers the erc20 event passthrough, allowing registered listeners to react to its completion.
approve delegate to withdraw tokens
This function is most often used in a token market scenario.
what approval does is allow an owner, i.e. msg.sender, to approve a delegate account — possibly the marketplace itself — withdraw tokens from their account and transfer them to other accounts.
As you can see, this function is used for scenarios where owners offer tokens on a market. allows the market to finalize the transaction without waiting for prior approval.
at the end of its execution, this function fires an approval event.
get the amount of tokens approved for withdrawal
This function returns the current number of tokens approved by an owner to a specific delegate, as set in the approval function.
transfer tokens by delegate
The transferfrom function is the peer of the approval function, which we discussed earlier. allows a delegate approved for withdrawal to transfer owner funds to a third party account.
The two require statements at the start of the function 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 passing the number of numtokens from the owner to the buyer, this function also subtracts numtokens from the delegate’s allocation. this essentially allows a delegate with a given allocation to split it into several separate withdrawals, which is typical market behavior.
we could stop here and have a valid erc20 implementation. however, we want to go one step further as we want an industrial strength token. this requires us to make our code a bit more secure, though we’ll still be able to keep the token relatively simple, if not basic.
safemath robustness library
safemath is a robustness library intended to deal with one of the ways hackers break contracts: the integer overflow attack. In such an attack, the hacker forces the contract to use incorrect numerical values by passing parameters that will push the relevant integers beyond their maximum values.
safemath protects against this by testing for overflow before doing the arithmetic, thus removing the danger of an overflow attack. the library is so small that the impact on contract size is minimal, incurs no performance, and reduces storage cost penalties.
let’s add safemath to our code:
safemath uses assertions to check the correctness of passed parameters. if the assertion fails, the function execution will stop immediately and all changes to the blockchain will be reverted.
Next, let’s add the following statement that presents the library to the solidity compiler:
using safemath for uint256;
then we replace the naive arithmetic we used at the beginning with safe functions:
pack it all together
In solidity, the functions and events of a smart contract are wrapped in an entity called a contract that can silently translate to a “blockchain class”. Below is the erc20 compliant contract we created, including an essential part of our code. the name and symbol fields can be changed at will. most tokens keep the decimal value at 18, so we’ll do the same.
implementation of the ethereum contract
The time has come to implement our contract on the blockchain. after implementation, 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 often use implementation tools like truffle. even the 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 in your browser and a Rinkeby (Ethereum testnet) account with at least some Rinkeby ether. These are relatively simple steps, so we won’t go into the details.
In case you don’t have either, head over to metamask and rinkeby for download links and clear installation and usage instructions.
Now that we have all the building blocks in place, we’ll head over to remixing and pasting the above code, including the pragma line and the safemath library, into the inline editor.
Next, we’ll go to the second tab on the right called “run” and click “deploy“. a metamask popup will appear asking us to confirm the transaction. of course, we will approve it.
- green box: make sure you are in rinkeby
- blue box: set your total supply of tokens
- red box: roll it out!
Congratulations! You just implemented your first erc20 token, like a true ethereum pro. As promised, the token is simple and lightweight, yet fully functional, erc20 compliant, and mathsafe protected. it is ready to be bought, paid and transferred through the blockchain.
is that all there is to smart contracts?
no, not even close, as our brief demo barely scratches the surface and deals only with one aspect of smart contract development.
Smart contracts can be much more complex depending on their business logic, their modeling of user interaction, whether or not they allow minting and recording of tokens, the lifecycle changes you introduce to the contract, the need admin-level capabilities that usually comes with a set of admin-authorized features, etc. you get the idea.
Still, if you can replicate what we did here, it will be a strong foundation for expanding your knowledge and moving on to more complex contracts when needed.
See also: How to mine Ethereum Classic | f2pool