Categories
ABI data analytics erc20 javascript web3js

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-deocder library in your project and add the abi of the smart contracts you want to decode:

Join the newsletter

Get a weekly summary of what is happening in the Ethereum developer space for free

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 decoer instance setted 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 recosgnised events are set as undefined (null).

Leave a Reply