Chapter 5 of 9

The token with OpenZeppelin

Goal. Create an ERC-20 token in a few lines and understand what decimals mean.

ERC-20 is the token standard: a set of rules (balance, transfer, permission to spend) that lets wallets and sites treat any token the same way. Writing it from scratch is a needless risk, so we use OpenZeppelin's version, a widely used library reviewed by many experts.

Analogy. It is a pre-printed cash ledger: you choose the coin's name and symbol, the library already has the columns and the checks.
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract FuelToken is ERC20 {
    constructor() ERC20("FuelToken", "FUEL") {}
}

Decimals

Like prices, the blockchain works with whole numbers. To represent fractions of a token, ERC-20 uses decimals, usually 18: the balance stored in the contract is the number of tokens multiplied by 1018. So 1000000000000000000 means "1 token" and 500000000000000000 means "half a token".

In our project 1 token = 1 litre: holding 0.5 tokens means "half a litre" on paper. Just as the cent is the smallest part of the euro, here the smallest part is one billionth of a billionth of a litre.

For now this contract creates no tokens: buy() will do that in the next chapter.

Try it

Work it out by hand: how many smallest units are 2.5 tokens? (Answer: 2,500,000,000,000,000,000, that is 2.5 × 1018.) Then write how many units a decilitre is, that is 0.1 token.

What you learned

Going deeper