2

As per the web3 doc, I'm using following code to watch the events from a contract:

contractInstance.eNonIssueDeposits({}, {fromBlock: 0, toBlock: 'latest'}, (error, result) => {
    if (!error) {
        console.log(result);
    } else {
        console.log(error);
    }
});

The Tx is successful and also logged an event but the function callback didn't initiated. What's wrong with the code?

3

For future readers.

Instead of using websocket provider:

new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'));

I was using HTTP provider:

new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/FouhRlBDjcMlyh0gT7oL'));

For events, you need to use their websocket service and you don't need any API keys for that.

Sample code below:

var Web3 = require('web3');
var ROPSTEN_WSS = 'wss://ropsten.infura.io/ws';
var provider = new Web3.providers.WebsocketProvider(ROPSTEN_WSS);
var web3 = new Web3(provider);

provider.on('error', e => {
    console.error('WS Infura Error', e);
});

provider.on('end', e => {
    console.log('WS closed');
    console.log('Attempting to reconnect...');
    provider = new Web3.providers.WebsocketProvider(ROPSTEN_WSS);
    provider.on('connect', function () {
        console.log('WSS Reconnected');
    });
    web3.setProvider(provider);
});

var myContract = new web3.eth.Contract(ABI, '0x....');
myContract.events.EventName({
    filter: {myIndexedParam: [20,23]},
    fromBlock: 0,
    toBlock: 'latest'
}).on('data', function(event) {
    console.log(event.returnValues);
}).on('error', console.error);
  • 1
    +1 this saved me – Nyxynyx Jul 22 '18 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.