Exploring ERC20 Tokens: The Powerhouse Behind Ethereum's Tokenized World4
Tags: ethereum, security, blockchain, beginners
Published: 2023-07-12 13:20:53

Tokens used to refer to small, insignificant objects like transportation or arcade game tokens. But now, with blockchain technology, tokens have a new meaning. They represent assets, currency, or access rights and are not limited to specific places. Blockchain tokens can be used globally and have multiple functions. They can also be easily traded on global markets.

In this chapter, we will learn about how tokens are created and used. We will also discuss important characteristics of tokens like how they can be exchanged with each other and their inherent value. Lastly, we will explore the standards and technologies behind tokens and even try creating our own.

## How Token Are Used

Tokens have many different uses, not just as a digital currency. They can do multiple things at the same time. Here are some examples:

1. **Currency**: Tokens can be used like money for buying and selling things.
2. **Resource**: Tokens can represent things you earn or produce in a sharing economy. For example, tokens could show how much storage or computer power you have to share with others.
3. **Asset**: Tokens can show that you own something valuable, like gold, real estate, or even a virtual item in a video game.
4. **Access**: Tokens can give you permission to use something, like a special website, a discussion forum, a hotel room, or a rental car.
5. **Equity**: Tokens can show that you have a share of a digital organization or a regular company.
6. **Voting**: Tokens can let you take part in making decisions in a digital system or in a legal system.
7. **Collectible**: Tokens can be special digital or physical items that people like to collect, such as unique digital artwork or rare physical objects.
8. **Identity**: Tokens can show who you are in the digital world or in the real world. It could be a picture or an official ID card.
9. **Attestation**: Tokens can be proof that something is true, like a certificate or a degree from a college.
10. **Utility**: Tokens can be used to get access to a specific service or to pay for it.

Sometimes, one token can do many of these things together. It can be hard to tell them apart because in the physical world, they are usually connected. But in the digital world, we can separate them and make them work independently. For example, we can have a token that proves something without showing who you are.

## Tokens & Fungibility


Fungibility refers to the ability to interchange individual units of a token without any difference in value or function. Tokens are considered fungible when each unit can be substituted with another unit.

However, if a token's historical origin can be traced, it may not be entirely fungible. The ability to track the origin can lead to actions like blacklisting or whitelisting, which reduces or eliminates fungibility.

Non-fungible tokens (NFTs) are different because each token represents a unique item, whether tangible or intangible. For instance, a token representing ownership of a specific Van Gogh painting is not the same as a token representing a Picasso painting, even if they are part of the same "art ownership token" system. Similarly, a token representing a specific digital collectible like a [CryptoKitty](https://www.cryptokitties.co/) is not interchangeable with other CryptoKitties. Each non-fungible token has a unique identifier, such as a serial number, to differentiate it from others.

> **Fungibility refers to the property of a good or asset where its individual units are essentially interchangeable and indistinguishable from one another. In simple terms, it means that each unit of the item is the same as any other unit. For example, traditional currencies like dollars or euros are fungible. If you have a $10 bill, you can exchange it for another $10 bill, and they hold the same value and function.**

> **Non-fungibility, on the other hand, refers to the uniqueness and non-interchangeability of individual units of a particular item. Each unit is distinct and cannot be substituted for another unit without differences in value or characteristics. A common example of non-fungible items are collectibles, such as trading cards or rare coins. Each trading card or coin has unique features or attributes that make it different from others, making them non-fungible.**

## Counterparty Risk

Counterparty risk means the risk that the other party involved in a transaction won't fulfill their obligations. Sometimes, transactions involve more than two parties, which increases this risk. For instance, if you sell a certificate of deposit for a precious metal, there are three parties involved: the seller, the buyer, and the custodian who holds the metal. The custodian's involvement adds extra risk because they have control over the physical asset.

When assets are traded using ownership tokens, there's also a risk related to the custodian. It's important to know if they actually have the asset and if they'll recognize the token transfer as a valid ownership transfer. Whether in the digital or physical world, understanding who holds the underlying asset and the rules that apply to it is crucial.

## Tokens and Intrinsicality
The word "_intrinsic_" derives from the Latin "_intra_," meaning "_from within_."

Some tokens represent digital items that are inherent to the blockchain itself. These assets are governed by the consensus rules of the blockchain, meaning that there is no additional counterparty risk involved. For example, if you own the private keys to a CryptoKitty, you directly own the digital asset without relying on any other party. The ownership is determined by the blockchain's rules, and there is no intermediary involved.

> **Consensus rules are a set of agreed-upon rules in a blockchain network that determine how transactions are approved and added to the blockchain. These rules ensure that everyone in the network agrees on which transactions are valid and in what order they should be recorded.**

On the other hand, many tokens are used to represent external assets like real estate, voting shares, trademarks, or gold bars. The ownership of these assets is governed by laws, customs, and policies outside the blockchain. This means that token issuers and owners may still rely on traditional legal contracts and systems. These external assets carry additional counterparty risk because they are held by custodians, recorded in external registries, or subject to laws and policies beyond the blockchain.

One significant benefit of blockchain-based tokens is the potential to convert external assets into intrinsic assets, thereby eliminating counterparty risk. For example, transitioning from equity in a traditional corporation (external) to an equity or voting token in a decentralized autonomous organization (DAO) (intrinsic) removes the need for intermediaries and reduces counterparty risk.

## Using Tokens: Utility or Equity


Not all projects necessarily require tokens, and there are potential disadvantages to their use. While the idea of "tokenizing everything" may sound appealing, practical limitations exist when integrating blockchain platforms like Ethereum into existing societal structures.

Let's clarify the role of tokens in new projects. Most projects use tokens in two main ways: **utility tokens** and **equity tokens**, although these roles are often mixed up.

Utility tokens are used to gain access to specific services, applications, or resources. For instance, they might be required to use shared storage or access social media networks.

Equity tokens represent ownership or control in something, like a startup. They can range from shares that don't have voting rights but allow for dividends, to voting shares in a decentralized organization where token holders have a say in decision-making.

In summary, while tokens have utility and equity roles in projects, not all projects require tokens. The integration of blockchain platforms has limitations in their practical applicability within existing structures.

#### It's A Duck

Many startups face a problem: they want to use tokens to raise funds, but offering equity to the public is regulated in most places. To work around this, some startups try to call their equity tokens "utility tokens" and present them as service access vouchers. However, it's unclear if regulators will accept this strategy.

There's a saying: "If something looks and sounds like a duck, it probably is a duck." Regulators are unlikely to be fooled by these word games. They may see these attempts as trying to deceive the public by pretending the tokens are something they're not.

## Tokens on Ethereum

Tokens existed before Ethereum, including the first blockchain currency, Bitcoin. Other token platforms were also built on different cryptocurrencies. However, Ethereum introduced the first token standard, which led to a huge increase in token creation.

**Vitalik Buterin**, one of Ethereum's founders, saw tokens as a valuable use of a programmable blockchain like Ethereum. In the early days, it was common to see Vitalik and others wearing T-shirts with the Ethereum logo and an example of a smart contract on the back, often showcasing a token implementation.

On Ethereum, tokens work differently from the native cryptocurrency called ether. **The Ethereum protocol doesn't have built-in support for tokens**. While sending ether is a basic function of Ethereum, tokens require the use of smart contracts. Smart contracts handle ownership, transfers, and access rights for tokens. To create a new token on Ethereum, a new smart contract needs to be developed and deployed. The smart contract defines how the token functions. It's generally recommended to follow existing token standards for compatibility and ease of use. We will discuss these standards later in the chapter and explore their benefits and drawbacks.

### The ERC20 Token Standard

The first token standard on Ethereum was introduced in November 2015 by Fabian Vogelsteller as an Ethereum Request for Comments (ERC). It was given the number 20 and became known as the "ERC20 token." Most tokens today are based on this ERC20 standard.

ERC20 is a standard for fungible tokens, which means that each unit of the token is interchangeable with others and has no unique properties.

The ERC20 standard defines a common interface for token contracts, allowing compatible tokens to be accessed and used in the same way. It includes a set of required functions and events that every implementation of the standard must have, as well as optional functions and attributes that developers can add.

The required functions and events of an ERC20-compliant token contract include:

- **totalSupply**: Returns the total number of tokens in existence.
- **balanceOf**: Returns the token balance of a specific address.
- **transfer**: Transfers a certain amount of tokens from the sender's address to another address.
- **transferFrom**: Transfers tokens from one address to another, with approval.
- **approve**: Authorizes a specific address to withdraw tokens from the sender's account.
- **allowance**: Returns the remaining amount of tokens that a spender is allowed to withdraw from an owner's account.
- **Transfer**: Event triggered when a transfer of tokens occurs.
- **Approval**: Event logged when an approval is made.

In addition to these required functions, there are optional functions defined by the ERC20 standard:

- **name**: Returns the human-readable name of the token.
- **symbol**: Returns a symbol representing the token.
- **decimals**: Specifies the number of decimal places used for token amounts.

These functions help ensure compatibility and consistency among ERC20 tokens. Here’s what an ERC20 interface specification looks like in Solidity:

```
contract ERC20 {
   function totalSupply() constant returns (uint theTotalSupply);

   function balanceOf(address _owner) constant returns (uint balance);

   function transfer(address _to, uint _value) returns (bool success);

   function transferFrom(address _from, address _to, uint _value) returns (bool success);

   function approve(address _spender, uint _value) returns (bool success);

   function allowance(address _owner, address _spender) constant returns(uint remaining);

   event Transfer(address indexed _from, address indexed _to, uint _value);

   event Approval(address indexed _owner, address indexed _spender, uint _value);
}
```
### ERC20 Workflows: "transfer" and "approve & transferFrom"

The ERC20 token standard has two transfer functions to support different ways of using tokens.

The first way is a simple, one-step process using the transfer function. It is commonly used by wallets to send tokens from one wallet to another. This is how most token transactions happen. For example, if Alice wants to send 10 tokens to Bob, her wallet sends a transaction to the token contract, using the transfer function with Bob's address and 10 tokens as the inputs. The token contract then updates the token balances, subtracting 10 tokens from Alice's account and adding 10 tokens to Bob's account. It also records this transfer as a "Transfer" event.

The second way is a two-step process using the approve and transferFrom functions. This method allows token owners to delegate control of their tokens to another address. It is often used when a token owner wants to allow a specific contract or entity to distribute their tokens. For example, during an ICO, a company may approve a crowdsale contract to distribute tokens to buyers. The crowdsale contract can then use the transferFrom function to transfer tokens from the owner's account to each buyer's account.

These different approaches give flexibility in how tokens are used, allowing for direct transfers or delegation of control in specific scenarios like ICOs.

>**A Token Sale Event (TSE) is a way for companies and organizations to raise money by selling digital tokens. It is similar to when a company sells shares to investors in a stock exchange, which is called an Initial Public Offering (IPO). However, unlike IPOs that have strict rules and regulations, TSEs are more open, global, and not as organized.**


![approve and transferFrom](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0iafuz4v8hay58nchrjd.png)

To allow the AliceICO contract to sell AliceCoin tokens, Alice follows two steps. First, she creates the AliceCoin contract and keeps all the AliceCoin tokens for herself. Then, she creates the AliceICO contract, which can sell tokens for ether.

Now, Alice wants to enable the AliceICO contract to sell tokens. She sends a special request to the AliceCoin contract, telling it to allow the AliceICO contract to sell 50% of all the AliceCoin tokens. This request is recorded in an event.

When someone like Bob buys tokens from the AliceICO contract using ether, the contract needs to send AliceCoin tokens to Bob. The AliceICO contract has a set rate for converting ether to tokens. It uses this rate to calculate how many tokens Bob will receive based on the amount of ether he sends.

To make the transfer, the AliceICO contract uses a special function provided by the AliceCoin contract. It specifies Alice as the sender and Bob as the recipient. It also includes the calculated number of tokens to transfer. This transfer is recorded in an event.

The AliceICO contract can repeat this process multiple times as long as it doesn't sell more tokens than what Alice approved. It can keep track of the available tokens by checking the approved amount.

In simple terms, Alice allows the AliceICO contract to sell her AliceCoin tokens. When someone buys tokens, the AliceICO contract calculates how many tokens to give based on the amount of ether. The tokens are transferred from Alice to the buyer using special functions, and the contract can sell tokens as long as it doesn't go over the approved limit.

### Issues with ERC20 Tokens

ERC20 tokens have become very popular, with many tokens being created for various purposes like crowdfunding and auctions. However, there are some issues and differences compared to regular ether transactions.

When you transfer ether, you send it directly to someone's address. But with ERC20 tokens, the transfers happen within the token contract itself, not directly to the recipient's address. The token contract keeps track of balances and events. So, when you transfer tokens, no transaction is actually sent to the recipient. Instead, the recipient's address is added to a list within the token contract. This means that the token contract changes, but not the recipient's address. Some wallets may not show your token balance unless you add the specific token contract to the wallet.

There are differences between tokens and ether. Ether can be sent and received easily, but tokens need special functions like "transfer" or "approve & transferFrom" that exist only in the ERC20 contract. These token transfers don't trigger any actions in the recipient's contract. It can be confusing because tokens are meant to function like cryptocurrencies, but they have these differences.

Another issue is that even when you want to send tokens, you still need to have some ether to pay for transaction fees. Tokens cannot be used to directly pay for fees, and the token contract can't pay for fees on your behalf. This can create confusion, especially if you didn't realize you needed ether to send tokens.

These issues are specific to ERC20 tokens and can be challenging to handle. They may require changes to the token interface or even to the Ethereum network itself. Some issues may not have a perfect solution, so user interfaces may need to be designed to make things easier and provide a consistent experience for users.

### ERC223: A Proposed Token Contract Interface Standard

The ERC223 proposal addresses the issue of accidentally sending tokens to contracts that may not support them. It does this by checking whether the destination address is a contract or not. In ERC223, contracts that want to receive tokens must have a function called "tokenFallback" implemented. If the recipient of a token transfer is a contract and it doesn't have support for tokens (meaning it doesn't have the tokenFallback function), the transfer will fail. This helps prevent tokens from being lost or stuck in contracts that cannot handle them properly.

The ERC223 contract interface specification is:

```
interface ERC223Token {
  uint public totalSupply;

  function balanceOf(address who) public view returns (uint);

  function name() public view returns (string _name);

  function symbol() public view returns (string _symbol);

  function decimals() public view returns (uint8 _decimals);

  function totalSupply() public view returns (uint256 _supply);

  function transfer(address to, uint value) public returns (bool ok);

  function transfer(address to, uint value, bytes data) public returns (bool ok);

  function transfer(address to, uint value, bytes data, string custom_fallback)public returns (bool ok);

  event Transfer(address indexed from, address indexed to, uint value,bytes indexed data);
}
```
ERC223 is not widely implemented, and there is some debate [in the ERC discussion](https://github.com/ethereum/EIPs/issues/223) thread about backward compatibility and trade-offs between implementing changes at the contract interface level versus the user interface.

### ERC777: A Proposed Token Contract Interface Standard

ERC777 is a proposal to make token contracts better. It has a few goals:

1. It works with existing ERC20 tokens, so they can still be used.
2. Tokens can be sent using a "_send_" function, just like how we send ether.
3. It can be registered with ERC820, which helps keep track of token contracts.
4. Contracts and addresses can decide which tokens to send using a special function called "_tokensToSend_".
5. Contracts and addresses can know when they receive tokens by having a function called "_tokensReceived_". This prevents tokens from getting stuck in contracts.
6. Existing contracts can use proxy contracts for the special token functions.
7. It doesn't matter if tokens are sent to a contract or a regular address, it works the same way.
8. There are specific events for creating and destroying tokens, so we can keep track of what happens to them.
9. Trusted third parties called operators can move tokens for token holders.
10. Extra information can be added to token transactions using special fields called "userData" and "operatorData".

In simple terms, ERC777 aims to improve token contracts by making them work better with existing tokens, allowing easier token transfers, giving more control over tokens, and adding useful features like events and extra transaction information.

The ERC777 contract interface specification is:

```
interface ERC777Token {
    function name() public constant returns (string);

    function symbol() public constant returns (string);

    function totalSupply() public constant returns (uint256);

    function granularity() public constant returns (uint256);

    function balanceOf(address owner) public constant returns (uint256);

    function send(address to, uint256 amount, bytes userData) public;

    function authorizeOperator(address operator) public;

    function revokeOperator(address operator) public;

    function isOperatorFor(address operator, address tokenHolder) public constant returns (bool);

    function operatorSend(address from, address to, uint256 amount, bytes userData,bytes operatorData) public;

    event Sent(address indexed operator, address indexed from, address indexed to, uint256 amount, bytes userData, bytes operatorData);

    event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData);

    event Burned(address indexed operator, address indexed from, uint256 amount, bytes userData, bytes operatorData);

    event AuthorizedOperator(address indexed operator, address indexed tokenHolder);

    event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
```

## Using Token Standards

In the previous section, we discussed various proposed and widely used standards for token contracts. Now, let's explore what these standards do, whether you should use them, how to use them, and if you should add extra functionality beyond these standards. We will also consider which standards to use.

#### What Are Token Standards? What Is Their Purpose?

Token standards provide a set of rules that token contracts must follow. For example, the ERC20 standard specifies the functions and behavior a token contract should have. You can also add extra features if you want.

The main purpose of these standards is to make different contracts work together smoothly. Wallets, exchanges, and other tools can easily interact with contracts that follow the standard. If you create a token contract that follows the ERC20 standard, people can use it with existing wallets without any extra work.

These standards describe what contracts should do, but not how they should be made. You have the freedom to decide how to implement the functions inside your contract. The standards provide some requirements for how the contract should behave in certain situations, but they don't give specific instructions. For example, they might specify how the transfer function should handle a zero value.

In simple terms, token standards are like a set of rules that token contracts should follow. They help different contracts work well together. You can add more features if you want, and the standards describe what the contract should do, but not how to make it.

#### Should You Use These Standards?

Every developer faces a tough decision: should they stick to existing standards or go beyond them to create something new and innovative?

This decision is not easy to make. Standards by their nature limit your ability to innovate because they provide a specific framework that you must follow. However, these standards have been developed based on the experience of many applications and usually work well for most use cases.

There is a bigger issue to consider as well: the importance of interoperability and widespread adoption. If you choose to use an existing standard, you benefit from the existing systems and tools designed to work with that standard. If you deviate from the standard, you have to consider the cost of building your own support infrastructure or convincing others to support your new standard. Choosing to ignore existing standards and creating everything from scratch is known as "Not Invented Here" syndrome, and it goes against the principles of open source culture. However, progress and innovation sometimes require breaking away from tradition. It's a challenging choice that requires careful consideration.

#### Security by Maturity

When implementing a standard like ERC20, you have two options: use an existing implementation or create your own. This choice has important security implications.

Existing implementations have been thoroughly tested and used in real-world scenarios. They have proven to be secure and reliable, handling millions of dollars' worth of tokens. Creating your own implementation is challenging and risky, as there are many ways it can be compromised. It is safer to use a well-established implementation like OpenZeppelin's ERC20, which focuses on security.

If you choose an existing implementation, you can still add your own custom features if needed. However, be cautious, as adding complexity increases the chance of introducing vulnerabilities. Each line of code you add expands the potential risks. You might not discover problems until your contract holds significant value and someone exploits it.

### Security by Maturity

When implementing a standard like ERC20, you have two options: use an existing implementation or create your own. This choice has important security implications.

Existing implementations have been thoroughly tested and used in real-world scenarios. They have proven to be secure and reliable, handling millions of dollars' worth of tokens. Creating your own implementation is challenging and risky, as there are many ways it can be compromised. It is safer to use a well-established implementation like OpenZeppelin's ERC20, which focuses on security.

If you choose an existing implementation, you can still add your own custom features if needed. However, be cautious, as adding complexity increases the chance of introducing vulnerabilities. Each line of code you add expands the potential risks. You might not discover problems until your contract holds significant value and someone exploits it.

### Extensions to Token Interface Standards

The token standards we discussed provide a basic set of functions, but many projects have created their own versions with more features. These additional features include:

1. **Owner control**: The ability to give specific addresses special powers like blacklisting or minting tokens.
2. **Burning**: The ability to intentionally destroy tokens by sending them to an unspendable address or reducing the total supply.
3. **Minting**: The ability to create new tokens and increase the total supply.
4. **Crowdfunding**: The ability to sell tokens through auctions or other methods.
5. **Caps**: Setting limits on the maximum token supply.
6. **Recovery backdoors**: Allowing designated addresses to recover funds or reverse transactions if needed.
7. **Whitelisting**: Restricting token transfers to specific addresses, often used for vetted investors.
8. **Blacklisting**: Preventing token transfers to specific addresses.

There are example implementations available, but no widely accepted standard for these features.

When deciding whether to add extra features to a token standard, developers need to consider the trade-off between innovation and risk, as well as interoperability and security. It's important to carefully weigh the benefits and potential drawbacks before implementing additional functionality.

### Tokens and ICOs

Tokens have become an important part of Ethereum, but not all tokens are trustworthy. Many tokens being offered now are scams or schemes to make quick money.

It's important to understand that the long-term impact and potential of tokens and the technology behind them is different from the current situation. Some tokens are fraudulent or designed to trick people.

We should recognize the potential of tokens and the platform they are built on, but also be aware of the scams and fraudulent activities happening now. Token standards and the platform have the potential to bring big changes in the future, but we need to be cautious and careful in the present.

#### Conclusion

Tokens are a really useful thing in Ethereum. They can be the starting point for many important applications that work without any central control. In this chapter, we learned about different kinds of tokens and standards. You even got to make your own token and build something with it.