Implementação de um token
transfer e approve
Implementação de um token é uma aula grátis de Web3 & DApp Development Fundamentals no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web3 & DApp Development Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Building a Token
Now you will implement the core of an ERC-20 token from scratch. Understanding the internals helps you debug and audit real tokens, even when you later use libraries.
We will focus on the state, transfer, and approve.
Core State Variables
A token needs to track balances and total supply. Balances are stored in a mapping from address to amount.
<code>contract Token {
string public name = 'MyToken';
string public symbol = 'MTK';
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
}</code>The Constructor
The constructor mints an initial supply to the deployer. We increase totalSupply and credit the creator's balance.
<code>constructor(uint256 initialSupply) {
totalSupply = initialSupply;
balanceOf[msg.sender] = initialSupply;
}</code>The Events
Declare the two required events. We will emit Transfer on every movement and Approval when an allowance is set.
<code>event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);</code>Implementing transfer
The transfer function moves tokens from the caller to a recipient. It must check the caller has enough balance and emit the Transfer event.
<code>function transfer(address to, uint256 amount) public returns (bool) {
require(balanceOf[msg.sender] >= amount, 'insufficient balance');
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}</code>Guarding Against Zero Address
Sending tokens to address(0) effectively destroys them by accident. Many implementations reject it explicitly.
<code>function transfer(address to, uint256 amount) public returns (bool) {
require(to != address(0), 'transfer to zero');
require(balanceOf[msg.sender] >= amount, 'insufficient');
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}</code>The allowance Mapping
To support delegated transfers we add a nested mapping: owner to spender to approved amount.
<code>mapping(address => mapping(address => uint256)) public allowance;</code>Implementing approve
The approve function lets the caller authorize a spender to move up to a certain amount of their tokens. It records the allowance and emits Approval.
<code>function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}</code>Overflow Safety
Since Solidity 0.8, arithmetic reverts on overflow and underflow automatically. The subtraction in transfer is safe: if the balance is too low it reverts, though the explicit require gives a clearer error.
Why Return bool
The standard specifies a bool return for compatibility. We return true on success. On failure we revert, which is the modern convention and safer than silently returning false.
Putting It Together
With state, events, transfer, and approve in place you have a functioning fungible token. The next lesson adds transferFrom to complete the allowance flow.
<code>// state + constructor + events + transfer + approve
// = a minimal working ERC-20</code>Quick Check
Test your understanding of implementing a token.
Recap
You implemented the core of an ERC-20 token:
- State: name, symbol, decimals, totalSupply, balanceOf mapping
- Constructor mints the initial supply to the deployer
transferchecks balance, updates state, emitsTransferapproverecords an allowance and emitsApproval- Guard against the zero address and rely on 0.8 overflow safety
Perguntas Frequentes
A aula “Implementação de um token” é grátis?
Sim — o texto completo de “Implementação de um token” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web3 & DApp Development Fundamentals, atualize para CoddyKit PRO. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
O que vou aprender em “Implementação de um token”?
transfer e approve Você pratica Web3 & DApp Development Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Web3 & DApp Development Fundamentals?
Nenhuma experiência prévia é necessária. Web3 & DApp Development Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Implementação de um token”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Web3 & DApp Development Fundamentals?
Sim. Cada aula de Web3 & DApp Development Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- O padrão ERC-20
- Implementação de um token
- Permissões
- Emissão e queima