FAQ - How to listen for events

This is a basic guide that shows how to listen for an event emitted by your smart contract.

Note that we are not setting any filter here, I strongly advise to look at the documentation in order to filter the returned values.
Based on what your dapp has to do, you can subscribe to events differently.

Refer to this documentation : Web3 Events Docs

Let's consider the following smart contract:

pragma solidity ^0.5.0;

contract Events {

  event newNumber (uint _newNumber);

  function call () public {
    emit newNumber (now);
  }
}

Every time the function call() is called, it will emit the event named newNumber.

Out goal is to catch the number emitted by the function.

It is necessary to create a basic index.html file, which will import:

  • web3
  • the contract ABI
  • a logic.js file

If you need to refresh your mind on the topics above, I do suggest to watch Filip’s video here: Creating a contract instance

Based on the smart contract shown above, this is what our logic.js file will look like.

var web3 = new Web3(Web3.givenProvider);
var instance;
var user;
$(document).ready(function(){
  window.ethereum.enable().then(function(accounts){
    instance = new web3.eth.Contract(abi,'0xD78450017bAd12b6e9Ee7a1c7aCB1fBD84CFeEA9');
    user = accounts[0];
  })
  $('#trigger').click(run);
})

function run (account) {
  
  instance.methods.call().send({from:user});

}

Basically we have a button in our index.html file having id = ‘trigger’.
For each click, our logic.js file will trigger the function call() in our smart contract.

Keep in mind that our smart contract has an event called event newNumber (uint _newNumber);

This is how you listen for events.

instance.events.newNumber(function (error,result){
    console.log(result)
  })

Now let’s console.log the result:

Look at returnValues, as you can see we have a field called _newNumber
Schermata 2020-09-25 alle 10.54.31

We now just need to extrapolate it from result.

instance.events.newNumber(function (error,result){
    console.log('Here it is' + ' ' + result.returnValues._newNumber)
  })

Schermata 2020-09-25 alle 10.57.05

Happy learning,
Dani

1 Like