ERC20 – Comparing Approve/TransferFrom vs Listening to Transfer Events

erc-20eventstransfer

I've been learning about the ERC20 standard and I've seen in several places statements like

If a smart contract want to detect when it receives a transfer of ERC20 tokens the standard approach is for the user to approve the transfer and for the smart contract to complete it doing a transferFrom from the user.

It is said that this pattern is particularly useful for exchanges that receive and manage multiple ERC20 tokens for their users. But can't the same thing be accomplished by listening to the contracts' Transfer events?

For example, if Uniswap wants to detect when a user sends them DAI. They can do 1 of the 2 things:

  1. The approve/transferFrom pattern where the user approves their contract address for the x DAI and then the Uniswap contract transfers the funds from the user's balance to their balance
  2. Setup an event listener on the DAI contract's Transfer event and acknowledge all the events with their address in the "to" field

Maybe there are other consideration I'm neglecting but doesn't the second approach accomplish the same effect in less transactions?

Best Answer

Think of the problem from a control an reliability perspective. Indeed you could listen to transfer events, but there are also some tradeoffs with this approach.

One of the reasons is that the receiving contract, f.e. the exchange, is able to control when the transfer happens, which allows contracts / dApps to perform additional logic before accepting the transfer - rather than relying on the sender to initiate the transaction.

Also listening to Transfer events may result in false positives or missed events, what if the receiving contract doesn't have enough gas, or multiple transfers happening at the same time, then the event listener may receive events out of order, leading to incorrect state, etc.

Conclusion

  • The receiving contract has control over when the transfer happens
  • The receiving contract can perform additional logic
  • The transfer is guaranteed as long as the user approves
  • Disadvantages may be that it requires an additional approval tx and two transactions in sum to complete the transfer, and the user needs to trust the receiving contract
Related Topic