Indexing events and filtering

In our auction smart contract, we used the indexed argument in BidEvent() declaration for a clever reason:

event BidEvent(address indexed highestBidder, uint256 highestBid);

When you use the indexed keyword in your event, your Ethereum node will internally index arguments to build on indexable search log, making it searchable, meaning you can easily perform a lookup by value later on. 

Suppose that the event was emitted by the MyAuction contract with the arguments BidEvent(26, “bidder's address”);. In this case, a low-level EVM log with multiple entries will be generated with two topics and a data field as shown in the following browser console screenshot:

The topics and data fields are as follows:

  •  Topics:
    • The event signature: The large hex number 0d993d4f8a84158f5329713d6d13ef54e77b325040c887c8b3e565cfd0cd3e21 is equal to the Keccak-256 hash of BidEvent (address, uint256)
    • HighestBidder: The bidder's address, ABI-encoded
  • Data:
    • Highest bid value, ABI-encoded
The indexed attribute can be granted to up to three arguments and will cause the respective arguments to be treated as log topics instead of data.

As you know, logs tend to be much larger and sometimes longer. In web3.js, you can filter data in your contract's log by simply applying a filter as follows:

var contractAddress="0x00..."
const filter = web3.eth.filter({fromBlock: 1000000,toBlock: 'latest',address: contractAddress,topics: [web3.sha3('BidEvent(address, uint256)')]})
filter.get((error, result) => {
if (!error) {
console.log(result);
}
});

The preceding filter will give you all the log entries for the BidEvent event corresponding to your filtering object, in which we define the blocks (fromBlock, toBlock) to read the log from, along with the account address and the event we are interested in. To listen for state changes that fit the previous filter and call a callback, you can use the watch method instead, as follows:

filter.watch(function(error, result) {
if (!error) {
console.log(result);
}
});

To stop and uninstall the filter, you can use the stopWatching method: filter.stopWatching();

As shown in the preceding screenshot, the log outputs are ABI-encoded, and to decode a log receipt, you can use decodeParameter available in web3Js 1.0 as follows:

web3.eth.abi.decodeParameter(‘uint256', '0000000000000000000000001829d79cce6aa43d13e67216b355e81a7fffb220')

Alternatively, you can use an external library such as https://github.com/ConsenSys/abi-decoder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset