[Ethereum] Events not being received in nodejs, using truffle, ganache and metamask

eventsnodejsweb3js

I'm using web3 1.0, lets say this is my smartcontract:

contract Foo {
    event NewUser(
        address userAddress,
        uint amount
    );

    function addUser() public payable{
        emit NewUser(msg.sender, msg.value);
    }
}

The events get fired in Remix perfectly well.

The problem is when I run a nodejs with express back-end and I try to watch the events with the following piece of code:

contract.events.NewUser({}, 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);

The first log gets called with value null and when the event can't get triggered. Does anyone have any idea what could be the issue?

Best Answer

Former HttpProvider and ganache does not support web3 1.0's event subscription. Please check out the documentation. For testing purpose for now, you may use the beta version of ganache-cli with WebsocketProvider.

Related Topic