Autorisations
Transferts délégués
Autorisations est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 3 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.
Delegated Transfers
Allowances let a token owner authorize another account - the spender - to move tokens on their behalf. This is what enables decentralized exchanges and DeFi protocols to pull your tokens with permission.
The flow is: approve sets a limit, then transferFrom spends within it.
The Allowance Storage
Allowances live in a nested mapping: owner to spender to amount. It records how much each spender may move for each owner.
<code>mapping(address => mapping(address => uint256)) public allowance;</code>Setting an Allowance
The owner calls approve to authorize a spender. This overwrites any previous allowance for that spender.
<code>function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}</code>Reading an Allowance
Anyone can query the remaining allowance with the public mapping or the standard allowance(owner, spender) view function.
<code>// remaining = allowance[owner][spender];
function allowanceOf(address owner, address spender) public view returns (uint256) {
return allowance[owner][spender];
}</code>Implementing transferFrom
transferFrom lets an approved spender move tokens from the owner to a recipient. It must check both the owner's balance and the spender's allowance.
<code>function transferFrom(address from, address to, uint256 amount) public returns (bool) {
require(balanceOf[from] >= amount, 'insufficient balance');
require(allowance[from][msg.sender] >= amount, 'allowance exceeded');
allowance[from][msg.sender] -= amount;
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
return true;
}</code>Decrementing the Allowance
Notice that transferFrom reduces the allowance by the amount spent. This prevents a spender from reusing the same approval indefinitely.
<code>allowance[from][msg.sender] -= amount; // consumed</code>Infinite Approval
Some protocols request the maximum uint256 allowance so users only approve once. Many implementations skip decrementing when the allowance is set to this max value, saving gas.
<code>uint256 constant MAX = type(uint256).max;
// if (allowance == MAX) skip decrement</code>The Approve Race Condition
There is a known hazard: changing an allowance from one non-zero value to another can be front-run, letting a spender use both. The classic mitigation is to set the allowance to 0 first, then to the new value.
<code>// recommended pattern
token.approve(spender, 0);
token.approve(spender, newAmount);</code>increaseAllowance and decreaseAllowance
To avoid the race condition, some tokens add helper functions that adjust the allowance relative to its current value rather than overwriting it.
<code>function increaseAllowance(address spender, uint256 added) public returns (bool) {
allowance[msg.sender][spender] += added;
emit Approval(msg.sender, spender, allowance[msg.sender][spender]);
return true;
}</code>Real-World Use: DEX
When you trade on a DEX you first approve the router contract. The router then calls transferFrom to pull your tokens into the swap. Without the allowance the trade cannot happen.
Security Reminder
An allowance is a standing permission. Granting an infinite allowance to a malicious or buggy contract can drain your tokens. Review and revoke unused approvals regularly.
<code>// revoke by approving zero
token.approve(spender, 0);</code>Quick Check
Test your understanding of allowances.
Recap
You learned the allowance mechanism:
approvesets allowance[owner][spender]transferFromspends within the allowance and decrements it- The approve race condition is mitigated by setting to 0 first or using increase/decreaseAllowance
- Allowances power DEXs and DeFi - revoke unused ones for safety
Questions Fréquemment Posées
La leçon « Autorisations » est-elle gratuite ?
Oui — le texte complet de « Autorisations » 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 « Autorisations » ?
Transferts délégués 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 3 sur 4.
Combien de temps prend la leçon « Autorisations » ?
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.