ERC-20 tokens — How I made my own cryptocurrency using the ERC-20 standard.
The other day, my mom came into my room showing me an article about all the rage about the metaverse. She was telling me all about how it made absolutely no sense. I mean people were putting all their life savings to own property online, how would that benefit them at all...?
A concept like that didn’t make sense to her at all, and neither did it for me up until a few months ago.
One of the things you can own on the web are tokens. And that’s exactly what I’ll be telling you about in this article: ERC-20 tokens.
In this article, I’ll mainly be telling you all about the ERC-20 standard and tokens, then will jump into a video tutorial at the end.
TL;DR
- Tokens are assets that are defined by smart contracts deployed on a blockchain.
- People wanted to make exchanging tokens easier and make where did the ERC-20 standard come from
- The ERC-20 standard is made up of 8 mandatory functions and events.
- Sending tokens to smart contracts instead of ether or a blockchain’s original currency/coin can result in your tokens being burned.
- The use of the approve function
- ERC-20 tokens can be used for a wide variety of things. Including stocks, ballots, and crypto tokens/currencies.
- Tutorial
First, what the hell are tokens???
Lots of people generalize tokens as being cryptocurrencies. It’s partly true…
There are many lists of types of tokens, but here are some of the main ones:
- NFT’s (non-fungible tokens): art, songs, videos, tweets, and even memes.
- Payment tokens: simply cryptocurrency coins.
- Security tokens: tokenized physical assets that are added to the blockchain in order to add an extra layer of security.
- Utility tokens: they act like coupons or vouchers. It represents a person’s right to access a product or service when the token is redeemed.
For a cryptocurrency to be an actual coin, it has to have its own blockchain. Bitcoin and Ether have their own blockchains and are called native assets of the blockchain. They can only be used for payment, although they are technically tokens.
To put it simply: look at Bitcoin. Bitcoin tokens can only be used as coins. They are a form of monetary value. Bitcoins have no value outside of finance.
Tokens originate from smart contracts that are supported by a blockchain. They can be used as coins that have monetary value, but can also represent a whole bunch of other stuff— from ownership of a song to votes. From assets to access rights.
For example, you can make a certain token to represent stocks, loan contracts, even your own cryptocurrency 😉.
What can ERC-20 tokens be?
There are ERC-20 tokens that represent real estate, art, stocks, unused hard drive space, and more.
Many companies require you to go through a brokerage firm to buy their stocks. Smart contracts, in this case, ERC-20 tokens, are exactly the way the third-party — brokerage firms — are replaced.
Anyone can buy and sell their ERC-20 tokens whenever they’d like. You don’t need any complex process. Only a wallet with some coins in it, and in a few clicks, you can buy any amount of stocks you want.
It represents a tradable asset or utility that resides on its own blockchain and allows the holder to use it for investment or economic purposes — Investopedia.
Plenty of well-known digital currencies use the ERC-20 standard, including Chainlink (LINK), Tether (USDT), and Shiba Inu (SHIB).
Where did the ERC-20 standard come from?
The ERC-20 standard is not the only one out there, there’s a loooong list of standards for tokens and smart contracts. For example the ERC-721 standard for non-fungible tokens.
The ERC-20 abbreviation originated from one of Ethereum’s EIP’s, short for the Ethereum Improvement Proposal.
It’s how and where all the improvements to the ethereum chain originate. For example, when a proposal that people from the Ethereum community support and have implemented if considered useful.
Ethereum Improvement Proposals (EIPs) describe standards for the Ethereum platform, including core protocol specifications, client APIs, and contract standards. GitHub
The ERC part stands for Ethreum Request for Comment. 20 is just a number that stands for the order of the EIP discussion.
Of course, these changes can’t be made to the blockchain because it’s decentralized. It would mean somebody out there had the power to manipulate the entire network.
So these improvements are presented as updates to the network that users can opt-in or out of adopting. Most of the time many people decide to adopt the updates since they are only introduced if a failure in the current system, theoretically or not, occurs.
This is what happened with Ethereum and Ethereum Classic. About $50,000,000 of currencies and tokens were stolen. A new version of the Ethreum network, where all those stolen funds were put into their original accounts, was released. It’s the main Ethereum chain that most people use today. The old version of the chain is still running though. It was named Ethreum Classic.
Why are standards needed for tokens?
Let’s go back in time a little. Only by a couple of years. To the beginning of Ethreum.
In 2015, every time someone wanted to make a token, they had to start all over, using their unique blueprint of what a smart contract looked like. The code that made up the token smart contract was unregulated. That resulted in each smart contract being slightly different.
Let’s put it this way: each contract spoke a different language and there was no way for them to understand each other unless a translator got involved.
If you wanted your token to be on an exchange platform, often called digital banks where people could sell, buy, and exchange currencies and tokens, the exchange would have to write its custom code to be able to communicate with yours and allow people to trade.
The community was distributed. There was no way to implement blockchain technology (smart contracts) on a large scale, this stood in the way of large-scale adoption of the technology.
As long as each individual or group came along and used their unique standard, it would be extremely difficult to have the smart contract interact with individuals, exchanges, and even other smart contracts.
ERC standards were introduced exactly for this reason — to make smart contracts, or tokens, more scalable. Using standards, it’s much easier for people to use and exchange tokens.
Okay, so…what‘s it made of?
The ERC-20 standard only controls only certain areas of a smart contract.
There are mandatory functions that must be included in the code for a contract to adhere to the ERC-20 standard.
Some optional ones can be added but aren’t necessary. As well as additional functions that can be added by the admin like _burn and _mint, which we will see later.
Getter Functions
Getter functions have a ‘read’ property. They use relatively small amounts of gas as they don’t change anything about the blockchain. They’re simply there to let people see certain information about the smart contract or coin when called.
totalSupply
function totalSupply() public view returns (uint256)
The totalSupply function displays the number of tokens in circulation. The return of this function increases or decreases after someone either mints or burns tokens. It does nothing else other than helping us fetch that value.
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance)
The balanceOf function takes an address as a parameter and returns the number of tokens that the address has. This function doesn’t change the state of the smart contract either.
allowance
function allowance(address owner, address spender) external view returns (uint256);
The last of the getter functions: allowance. This one is a bit more complicated. This defines the number of tokens from the owner’s account the spender is allowed to spend and use.
In the ERC-20 standard, an account owner can allow other accounts to spend her tokens on her behalf. So the allowance is the number of tokens that the owner allows the spender to use.
But the thing is, allowance is often not used as an allowance from an individual to the other, but instead in Defi DApps to allow the app to spend and exchange tokens on your behalf.
Transfer Functions
These functions have a ‘write’ property. Meaning that they change the state of the blockchain; therefore, using up more gas when called. Tokens are transferred and allowances are changed.
transfer
function transfer(address _to, uint256 _value) public returns (bool success)
Transfers money from the account of the caller of the function, to the account specified as a parameter. Simple, right?
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
The transferFrom function directly relates to the allowance function we discussed before. Although this time, it’s meant to be used by the spender. The spender uses this function when they decide they want to spend their allowance by transferring tokens from the account giving them the allowance (_from), the whichever account (_to) they feel like being generous towards that day.
It takes in the _to and _from parameters but also takes in the amount of money is requested by the spender.
Finally, it returns whether the transaction was a success or not (bool), and emits the Transfer event, which we’ll talk about shortly.
approve
function approve(address _spender, uint256 _value) public returns (bool success)
The approve is how the caller of the function sets the allowance another account is allowed to spend from the caller’s account. It also triggers the Approval event which I’ll talk about in a few lines…
Although this function can be tricky. For example, if you have an allowance of 50 tokens and the owner sets a new allowance of 60, you might end up with an allowance of 110 tokens. This is just one case scenario if setting an allowance isn’t done right. So it’s safer, as an owner, to set the allowance to 0 first, then set it to whatever value you’d like.
Events
Think of events like timers, except they don’t go off once a certain amount of time passes, but instead, by changes that are made to certain areas of the blockchain (certain functions being called). Once a function that triggers an event is called, the event is emitted.
This sends a kind of notification to whoever ‘subscribed’ to the event every time it is emitted.
Approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
The Approval event is emitted by the owner setting a new allowance for the spender, or by them setting it to a new value. The value is the new allowance. This event is emitted after someone calls the approve function.
Transfer
event Transfer(address indexed from, address indexed to, uint256 value);
Transfer’s emitted when some of the allowance you have given to the spender is used by the spender. They use your allowance and transfer some of the tokens you permitted them to use from your account to the address of their choice.
Optional
function name() public view returns (string)function symbol() public view returns (string)function decimals() public view returns (uint8)
These three functions specify:
- The name of your coin.
- The symbol you want it to have. The usual is 3 to 4 letters. (i.e. LINK, USDT, SHIB, OMG...etc)
- The number of decimals you want your token to be divisible by. Most people go for 18.
Other Functions
Now, the previous functions were the ones that were defined by the ERC-20 standard. But many contracts include other useful functions like mint and burn, and some other ones I’ll talk about
mint
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
This function is pretty simple. It just mines tokens. Of course, this seems like quite a problematic function at first: anyone can just mint tokens which will cause the value of existing tokens to go down.
But let’s not forget that it requires the caller of the function (msg.sender) to be the admin. A variable that was set to the deployer of the contract in the constructor.
So the only person who can mint tokens is the owner of the contract. Not so problematic anymore right?
It can also be considered a transfer function that emits the Transfer event. As the tokens are being sent from the 0x0…000 address to the admin’s address.
burn
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount;}
_totalSupply -= amount; emit Transfer(account, address(0), amount); }
This one’s easy: it takes a number as a parameter and burns that amount from the address that called the function.
This function can be useful when the admin of the contract or just anyone wants to burn some of their tokens to make the other ones more valuable or for whatever other reason they choose to.
It also emits the Transfer event, as it transfers coins from the account that calls the function to the 0x0…000 (0)address.
Failures of the ERC-20 standard
One big problem we shouldn’t ignore is that when we want to buy an ERC-20 token, we have to send ether to the contract, not another ERC-20 token. And that is where a lot of people go wrong.
They try to send other tokens to the contract, which results in them being burned, which means they’re sent to the 0x00…000 address. An address that no one has access to.
When we go to Etherscan and try to look up the address, it tells us that the address is not owned by anyone. It’s used by the blockchain to burn or mint currencies.
When someone burns tokens or ether, they’re sent to this address. And when someone mints tokens or ether, they are being sent by this address.
An example of this is when miners generate new currency into circulation — the rewards they get are sent by this address to the miner’s account.
DeFi Apps’ Allowance
DAO’s approval of allowances can result in them being able to spend as much money as they can from your account.
When exchanges or DeFi apps want to have permission to trade your coins and tokens, they use the token allowance function. When logging onto a DeFi app or website, in the back of your mind you know that you’re there to have it do something on your behalf.
Let’s take Compound as an example. To lend your coins and tokens on Compound, you have to go through something like this:
It might say “ENABLE” or “ALLOWANCE” depending on the smart contract. This can give the app full control over your tokens. It can be harmful since a lot of smart contracts are not out there for a good reason.
DeFi gets its reputation of scams for a reason, and it’s because the percentage of scams out there is extremely high — and it’s not a risk many people are willing to take.
Exchanges VS Wallet providers
If you’re someone interested in knowing more about tokens, you’ll come across and will need to know the difference between crypto wallets and exchanges.
It’s hard to know the difference between them since many service companies provide both on a single platform, but not really… and you’ll see exactly how.
Let’s take very dear Coinbase as an example. Coinbase is certainly an exchange: people can buy and sell their tokens and coins on it. But it’s not a wallet provider. It’s a centralized cryptocurrency brokerage that manages your cryptocurrency for you. It has control over your private keys.
In contrast to Coinbase Wallet. Coinbase wallet is simply a place where you can store your cryptocurrency and have full control and responsibility for it. Now that is a wallet provider.
Of course, each one has its list of pros and cons. Exchanges make it easier for you to have cryptocurrency: they manage your account and its security — all the complicated stuff. But, it’s a big compromise on security as it’s a centralized organization and could run away with your money any time they wanted to — if they’re not trustworthy.
Wallet providers, on the other hand, provide great security that comes from you being the only person with access to your assets. You can see how that could be a pain in the… rear end if you have to deal with all the technical stuff.
But eventually, the choice is all about you, your preferences and your needs.
Kk… now what??
In terms of flexibility and fungibility, ERC-20 tokens are one of the best.
Very fungible since every time you exchange an ERC-20 token for another, it still has the same exact value. They’re not unique, they all represent the same thing.
Let’s take fiat money as an example.
Exchanging two $5 bills for one $10 bill will not change anything at all. The overall value will still be $10. Both versions of it can accomplish the same things and provide you with the same services and products.
In terms of flexibility, there are some super cool use cases for ERC-20 tokens. It’s as flexible as a fungible token can get. Anything that has the same value when exchanged for another unit can be represented using the ERC-20 standard.
Meaning that the ERC-20 standard is perfect for making things like cryptocurrencies!
How to make your own cryptocurrency!
Step-by-Step video tutorial of how I made my ERC-20 token.
Having previous experience with JavaScript of Solidity is helpful to understand the code in the video, but not necessary, so you will still be able to keep up with the steps
- The code used in this video can be found in this repository.
This tutorial was made with the help of this video and this OpenZeppelin library from GitHub.