Web3.py – How to Decode Ethereum Transaction Logs

logsweb3js

I can filter my events (please see), but instead of that if I know only the transaction hash and if its already deployed, is it possible to obtain and parse the transaction's log data using Web3.py? Please see the solution for web3.js.

=> Is there any web3.eth.abi.decodeLog function under Web3.py?


For example, from receipt we can obtain the logs.data.

> tx = '0x5c7e74a21419a6ff825aca9b54df1a86599b4b1ee82e60e6410e8d54cbb58b2c'    
> web3.eth.getTransactionReceipt(tx).logs
    [{
        address: "0x611dc53934550684825f3477ecb68029b1b908f3",
        blockHash: "0x356829b068046b6d44147663f8bd6c187e9507c578d9ec9d69e65d7a248ff368",
        blockNumber: 1180103,
        data: "0x0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000002e516d52736142454763717851634a6242784369314c4e39697a3562444147445752364878375a76577167716d64520000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007536369656e636500000000000000000000000000000000000000000000000000",
        logIndex: 0,
        removed: false,
        topics: ["0x711007a4be830d68a6d2a7b6546227b676bf9e7d7a0e3c248552ed72cfec2441", "0x0000000000000000000000004e4a0750350796164d8defc442a712b7557bf282"],
        transactionHash: "0x5c7e74a21419a6ff825aca9b54df1a86599b4b1ee82e60e6410e8d54cbb58b2c",
        transactionIndex: 0
    }]

Example log I have is, where string has a dynamic size. If possible, I want to decode web3.eth.getTransactionReceipt(tx).logs[<index>]['data] and web3.eth.getTransactionReceipt(tx).logs[<index>]['topics].

event LogJob(address indexed clusterAddress,
             string indexed key,
             uint index,
             uint8 fileID,
             string desc,
             string hash
             );

Best Answer

From Web3.py documentation:

myContract = web3.eth.contract(address=contract_address, abi=contract_abi)
tx_hash = myContract.functions.myFunction().transact()
receipt = web3.eth.getTransactionReceipt(tx_hash)
logs = myContract.events.myEvent().processReceipt(receipt)

ContractEvent provides methods to interact with contract events. Positional and keyword arguments supplied to the contract event subclass will be used to find the contract event by signature.

Related Topic