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;23function approve(address spender, uint256 amount) public returns (bool) {4address owner = msg.sender;5_allowances[owner][spender] = amount;6emit Approval(owner, spender, amount);7return true;8}910function allowance(address owner, address spender) public view returns (uint256) {11return _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 tokens2await token.approve(dexAddress, parseEther("100"));34// Check the allowance5const allowed = await token.allowance(myAddress, dexAddress);67// Revoke approval8await token.approve(dexAddress, 0);
Complete
Connect your wallet to mark this lesson as complete
Earn 5 EFFORT tokens