Back to Lessons
Lesson 03

The Approval Pattern

+5EFFORT
6 sections
approve()
01
text

What if you want a smart contract (like a DEX) to spend tokens on your behalf? You can't give it your private key. Instead, ERC-20 has the approve() function.

02
code
solidity
1mapping(address => mapping(address => uint256)) private _allowances;
2
3function approve(address spender, uint256 amount) public returns (bool) {
4 address owner = msg.sender;
5 _allowances[owner][spender] = amount;
6 emit Approval(owner, spender, amount);
7 return true;
8}
9
10function allowance(address owner, address spender) public view returns (uint256) {
11 return _allowances[owner][spender];
12}
03
text

When you approve a spender, you're saying: 'I give address X permission to spend up to Y of my tokens.' The spender can then use transferFrom() to move your tokens.

04
note
Key Insight

Security Warning: Be careful what you approve! A malicious contract could drain all tokens you've approved. Always verify the spender address and consider approving only the exact amount needed.

05
text

To revoke an approval, simply approve the same address for 0 tokens. This is why many dApps have a 'Revoke' button.

06
code
javascript
1// Approve a DEX to spend 100 tokens
2await token.approve(dexAddress, parseEther("100"));
3
4// Check the allowance
5const allowed = await token.allowance(myAddress, dexAddress);
6
7// Revoke approval
8await token.approve(dexAddress, 0);
Complete

Connect your wallet to mark this lesson as complete

Earn 5 EFFORT tokens