Aniruddha Deshmukh
Aniruddha Deshmukh's Blog

Follow

Aniruddha Deshmukh's Blog

Follow
Event Listeners in web3.js

Photo by Shubham Dhage on Unsplash

Event Listeners in web3.js

Aniruddha Deshmukh's photo
Aniruddha Deshmukh
·Feb 5, 2022·

2 min read

Events in Solidity

In a Solidity Smart Contract, you can emit events that can be listened to outside the contract. In the example given below, currentCount(unit count) event is created with the event keyword. This event is emitted with the help of emit keyword.

contract myContract {
    uint public count = 0;

    event currentCount(unit count);

    function increaseCount() public {
        count = count + 1;
        emit currentCount(count);
    }
}

Subscribe to an event.

these events can be Subscribed to by using web3.js.

There are different subscribe to events using web3.js:

  1. events Subscribe to an event.
myContract.events.MyEvent([options][, callback])
  1. once Subscribes to an event and unsubscribes immediately after the first event or error. Will only fire for a single event.
myContract.once(event[, options], callback)
  1. allEvents Same as events but receives all events from this smart contract. Optionally the filter property can filter those events.
myContract.events.allEvents([options][, callback])
  1. getPastEvents Gets past events for this contract.
myContract.getPastEvents(event[, options][, callback])

In this article, we are going to focus more on the events method.

events

Parameters

The ContractInstance.events.eventName() takes an options object and a callback function as parameters.

You can have a look at the code snippet from the web3 documentation given below.

myContract.events.currentCount([options][, callback])

Returns

The ContractInstance.events.eventName() returns an EventEmitter. The event emitter has the following events:

  • "data" returns Object: Fires on each incoming event with the event object as an argument.
  • "changed" returns Object: Fires on each event that was removed from the blockchain. The event will have the additional property "removed: true".
  • "error" returns Object: Fires when an error in the subscription occours.
  • "connected" returns String: Fires once after the subscription successfully connected. Returns the subscription id.
myContract.events.currentCount({
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
    fromBlock: 0
}, function(error, event){ console.log(event); })
.on('data', function(event){
    console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
    // remove event from local database
})
.on('error', console.error);

[Note]: you will require a WebSocket-based RPC URL in order to listen to events.

 
Share this