How to Decode Event Logs in JavaScript Using ABI-decoder

In this tutorial we’ll see how to decode and make sense of event logs generated by Ethereum transactions. This tutorial will guide you on getting a transaction receipt and getting the data related to one event in their original types using the ABI-decoder library. For this tutorial you’ll need :

  • the ABI of the smart contract you try to decode events from (we’ll use the ERC20 transfer event)
  • a transaction containing one or more events of this type

Install the library

Using npm in your javascript project:

npm install abi-decoder --save

or using bower for your frontend:

bower install abi-decoder

This tutorial will be based on backend script but you can easily transcript it as you’d use in a frontend code.

Initializing

First you’ll need to include the ABI-decoder library in your project and add the ABI of the smart contracts you want to decode:

const abiDecoder = require('abi-decoder');

const erc20TransferEvent = [
      {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "name": "from",
                "type": "address"
            },
            {
                "indexed": true,
                "name": "to",
                "type": "address"
            },
            {
                "indexed": false,
                "name": "value",
                "type": "uint256"
            }
        ],
        "name": "Transfer",
        "type": "event"
    }
]

abiDecoder.addABI(erc20TransferEvent)

A great point about this library is that you can add as many ABIs you’d like and decode all events hapening in a transaction.

Fetching a transaction and decoding events

Once you have your ABI decoder instance set up with the events you want to decode, you just need to fetch the transaction receipt and feed it to the instance using the decodeLogs function:

   let receipt = await web3.eth.getTransactionReceipt("0x103577d20b4ae152ebd33d20fd32cf63aad5c5192d33efac8c9a6f071caff6ac")
   const decodedLogs = abiDecoder.decodeLogs(receipt.logs);
   console.log(decodedLogs)

which should give a result similar to this:

Every event that matched the provided ABI is decoded with the correct parameters under the events property. Non recognised events are set as undefined (null).

Leave a Reply

Your email address will not be published. Required fields are marked *