Chapter 5 of 9
The token with OpenZeppelin
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.
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract FuelToken is ERC20 {
constructor() ERC20("FuelToken", "FUEL") {}
}
importbrings OpenZeppelin'sERC20contract into your file.contract FuelToken is ERC20means your contract inherits everything an ERC-20 can do.ERC20("FuelToken", "FUEL")gives the coin its name and symbol.- The body
{}is empty: nothing else is needed to have balances and transfers.
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
- ERC-20 is the common token standard; OpenZeppelin offers a safe version of it.
- By inheriting from
ERC20, three lines are enough to have a token. - With 18 decimals the balance is tokens times 1018; for us 1 token is 1 litre.