0

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.

2 Answers 2

6

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.

2
  • Yes it did help a lot. For others, I used this as provider: var socketProvider = 'wss://ropsten.infura.io/ws';, http provider can still be used in parallel to do other things Commented May 3, 2018 at 8:55
  • Here the concern is events and that is not possible by http provider
    – rahul_eth
    Commented May 3, 2018 at 10:29
0

You can use this way to call the function: http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send

So, on successful confirmation of the transaction, you can get the values returned by the event by accessing events.eventName.returnValues form transaction receipt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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