Implémenter un jeton
transfer et approve
Implémenter un jeton est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web3 & DApp Development Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
Questions Fréquemment Posées
La leçon « Implémenter un jeton » est-elle gratuite ?
Oui — le texte complet de « Implémenter un jeton » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web3 & DApp Development Fundamentals, passe à CoddyKit PRO. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Implémenter un jeton » ?
transfer et approve Tu pratiques Web3 & DApp Development Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Web3 & DApp Development Fundamentals ?
Aucune expérience préalable n'est requise. Web3 & DApp Development Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Implémenter un jeton » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Web3 & DApp Development Fundamentals ?
Oui. Chaque leçon Web3 & DApp Development Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Norme ERC-20
- Implémenter un jeton
- Autorisations
- Frappe et destruction