Listening to Events in Web3 – How to Listen to Events Generated by an Existing Contract in Web3 1.x.x?

cpp-ethereumeventslogsweb3js

Currently I'm unable to find a working solution. Let's say I have the following smartcontract:

contract Manufacturer {
    event LogNewOrder(string order);

    string[] public orders;

    function addOrder(string newOrder) public {
        orders.push(newOrder);
        emit LogNewOrder(newOrder);

        return;
    }
}

If a third party calls the method addOrder(newOrder), the manufacturer should be informed about, because he must perform things. What is the best method with web3 to listen to events? If I do something like this:

instance.events.allEvents({ fromBlock: 0 })
.on('data', function(event){
    console.log(event);
})
.on('changed', function(event){
    console.log(event);
})
.on('error', console.error);

then nothing happens.

Best Answer

In version 1.x.x using HttpProvider is deprecated you have to use webSocketProvider for listening events web3js.readthedocs.io/en/1.0/web3-eth.html?highlight=deprecated.

web3socket = new Web3(new Web3.providers.WebsocketProvider("your websocket conn"));
socketInstance =new web3socket.eth.Contract(ABI,ConAd);
socketInstance.events.LogNewOrder((err, events)=>{
console.log(err, events)})

I hope this would help you.

Related Topic