01
text
transferFrom() is the partner to approve(). After you approve a spender, they call transferFrom() to actually move your tokens.
02
code
solidity
1function transferFrom(address from, address to, uint256 amount) public returns (bool) {2address spender = msg.sender;34// Check and update allowance5uint256 currentAllowance = _allowances[from][spender];6require(currentAllowance >= amount, "Insufficient allowance");7_allowances[from][spender] = currentAllowance - amount;89// Perform the transfer10_transfer(from, to, amount);11return true;12}
03
text
The key difference from transfer(): the tokens come from 'from' (not msg.sender), and the caller must have been approved by 'from' to spend at least 'amount' tokens.
04
note
Key Insight
This is the foundation of DeFi! DEXs, lending protocols, and yield farms all use this pattern: you approve them, then they call transferFrom() to move your tokens into their contracts.
05
text
The two-step flow (approve then transferFrom) might seem cumbersome, but it's crucial for security. You maintain control - the contract can only spend what you explicitly approved.
06
code
javascript
1// User approves DEX2await token.approve(dexAddress, parseEther("50"));34// DEX contract calls transferFrom during a swap5// Inside the DEX contract:6token.transferFrom(userAddress, dexAddress, swapAmount);
Complete
Connect your wallet to mark this lesson as complete
Earn 5 EFFORT tokens