Back to Lessons
Lesson 04

transferFrom Explained

+5EFFORT
6 sections
transferFrom()
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) {
2 address spender = msg.sender;
3
4 // Check and update allowance
5 uint256 currentAllowance = _allowances[from][spender];
6 require(currentAllowance >= amount, "Insufficient allowance");
7 _allowances[from][spender] = currentAllowance - amount;
8
9 // Perform the transfer
10 _transfer(from, to, amount);
11 return 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 DEX
2await token.approve(dexAddress, parseEther("50"));
3
4// DEX contract calls transferFrom during a swap
5// Inside the DEX contract:
6token.transferFrom(userAddress, dexAddress, swapAmount);
Complete

Connect your wallet to mark this lesson as complete

Earn 5 EFFORT tokens