0
 function depositToEscrow(bytes32 _id) public payable returns(uint) {
    DepositToEscrow(msg.sender,orderdata[_id].buyer,msg.value,orderdata[_id].amount);  
}

suppose this is my function in a smart contract. How to get the result of the event "DepositToEscrow" using web3

3 Answers 3

1

You have to take care of following things:

  1. Use websocket provider in order to subscribe to events in web3.js 1.0. For example, if you are using local TestRPC then instantiate the web3 as by using your websocket port (here in this case its 8545):

    const web3 = new Web3(Web3.givenProvider || "ws://127.0.0.1:8545");
    
  2. The example code for myContract having an event of MyEvent will be like:

    myContract.events.MyEvent ({
      fromBlock: 'latest',
      toBlock: 'latest'
    }, function(error, result) {
      if (!error) {
        console.log(result);
      } else {
        console.log(error);
      }
    });
    

Note: in the above block of code, I'm watching for the events in 'latest' block mined. The reason is, this block of code is the same as we have watch method in the older version. This will only watch for events that are not fired yet. If you want to get all the events, you have to use getPastEvents:

    myContract.getPastEvents('MyEvent', {
      fromBlock: 0,
      toBlock: 'latest'
    }, function(error, result) {
      if (!error) {
        console.log(result);
      } else {
        console.log(error);
      }
    });

For more details, see the Docs

1
  • I tried the above solution but it works for a specific contract. Is there a way to get all the events of a block?
    – jolly
    Jul 29, 2020 at 16:45
0

For 1.0.0, it's:

yourContract.events.YourEvent(function(error, event) {
});
1
  • I get yourContract.events as undefined. Doesn't work. Always some problems with events in web3 :(
    – Rob Magier
    Feb 4, 2019 at 22:40
-2

Something like the code below:

var depositToEscrow = [YourContractInstance].DepositToEscrow({}, 'latest');
depositToEscrow.watch(function(error, result) {
    if (result) {
        // your required code
    } else {
        // your required logic
    }
});
3
  • showing DepositToEscrow is not a function
    – sruthi23
    Jan 1, 2018 at 10:02
  • I think it's yourContract.events.DepositToEscrow in v1.0.0.
    – user19510
    Jan 1, 2018 at 11:03
  • This answer will not work in web3 1.0.0
    – Rob Magier
    Feb 4, 2019 at 22:40

Your Answer

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

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