1

I am using Infura, Ropsten Test network, Web3@0.20 in the back-end of my Express website. I want to listen events in my ERC20 contract. I tried a lot of methods, but still failed. How do I revise it? Thanks a lot.

contract.Transfer({}, { fromBlock: 0, toBlock: 'latest' }).get((error, 
eventResult) => {
  if (error)
      console.log('Error in myEvent event handler: ' + error);
  else
      console.log('myEvent: ' + JSON.stringify(eventResult.args));
});
  • Infura only support events through websockets. And web3 v0.20 doesn't have support for websockets. Your options is to use web3 v1.0 or another alternative like ether.js. – Ismael Jun 11 at 18:59
  • If I use front-end with Metamask. Is it possible? – user53449 Jun 12 at 13:44
  • I didn't try Metamask with events but I think it uses Infura. – Ismael Jun 12 at 16:43
0

This is how it works on both web3 versions with infura HttpProvider.

web3 0.2:

    myContract.events.Transfer({
        filter: {_from: SOME_ADDRESS},
        fromBlock: 6000000,
        toBlock: 'latest'
    }, function(error, result){
        if(!error) {
            console.log(result);
        }else {
            console.log(error);
        }
    });

web3 1.0

    new Promise(function(resolve, reject) {
        myContract.getPastEvents('Transfer', {
            filter: {_from: SOME_ADDRESS},
            fromBlock: 6000000,
            toBlock: 'latest'
        }, function(error, event){
            if(!error) {
                resolve(event);
            } else {
                resolve(error);
            }
        });
    });

In web3 1.0 you have to do it as promise if you want to keep using the HttpProvider. Note that myContract is the instance of my contract and 'Transfer' is the name of my event, you should have different event name.

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