Web3.py – How to Get Tokens Transferred and Process Receipts

receiptsweb3.py

I'm trying to find how etherscan finds the "Tokens Transferred" using the logs of a given transaction. Using this 0x52caaf79bf913064a70a6c9d917fd4190cdb099fe79e7d3a9dfe0600e1cfbc81 arbitrary transaction as an example.

enter image description here

I used the below code (web3.py) to find the logs in the transaction receipt:

from web3 import Web3
provider = Web3.HTTPProvider('https://mainnet.infura.io/v3/XXXXXXXXXXXXX')
w3 = Web3(provider)

receipt=  w3.eth.getTransactionReceipt('0x52caaf79bf913064a70a6c9d917fd4190cdb099fe79e7d3a9dfe0600e1cfbc81')

Running receipt["logs"] generates the logs which can be found in Etherscan under "event logs". However, only 3 log indices result in the tokens transferred section (logs 156, 158 and 162).

Can someone help me understand how does etherscan knows that only these should appear in the picture seen above, from amongst all the logs?

Best Answer

It searches for all events:

  1. Which have been emitted by the designated ERC20 token contract, which in your case is:

    To: Contract 0xc73e0383f3aff3215e6f04b0331d58cecf0ab849

    This value should appear in the to field of the transaction receipt

  2. Whose first topic (topics[0]) is equal to the hash of the signature of the Transfer event:

    In Javascript, this value is Web3.utils.keccak256("Transfer(address,address,uint256)")

    You may use the equivalent code in Python if you need to...

Related Topic