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.

What you will learn

  • Where how to decode event logs in javascript using abi-decoder fits into an Ethereum application.
  • Which assumptions should be tested before a mainnet deployment.
  • What to read next when this concept is working.

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:

screenshot from 2020 06 18 18 53 22

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).

Turn the example into production evidence

A working demo is the beginning of verification, not the end. Add tests for failure paths, inspect every permission, and record the chain, contract address, compiler, and dependency versions used for the deployment.

Check behavior

Test expected inputs, boundary values, reverts, events, and calls made to other contracts.

Check operations

Plan key storage, monitoring, pause or upgrade authority, and a response if an assumption stops being true.

Continue from How to Decode Event Logs in JavaScript Using ABI-decoder