7

I have a smart contract with an event.

    event NewContractCreated(address _callerAddress, address _newContractAddress);

I know how to actively listen for new events:

var newContractEvent = myContract.NewContractCreated();
newContractEvent.watch(function(error, result){
      if (!error){
        console.log("Success");
        console.log("New Contract Address: " + result.args._newContractAddress);
        console.log("Creator: " + result.args._callerAddress);
      }
  });

That works just fine for me. But my question is: how do I listen for and pull the exact same data for events that happened before I started watching?

I tried the exact same thing but using get instead of watch... it half worked. It printed the top line "Success" but did not print the rest of the log lines.

3 Answers 3

5

You should be able to specify the period (in block no) to watch. According the documentation here

fromBlock: Number|String - The number of the earliest block (latest may be given to mean the most recent and pending currently mining, block). By default latest.

toBlock: Number|String - The number of the latest block (latest may be given to mean the most recent and pending currently mining, block). By default latest.

In your case, that should work :

var newContractEvent = myContract.NewContractCreated();
newContractEvent.watch({fromBlock: 0, toBlock: 'latest'}, function(error, result){
      if (!error){
        console.log("Success");
        console.log("New Contract Address: " + result.args._newContractAddress);
        console.log("Creator: " + result.args._callerAddress);
      }
  });
1

Try

var newContractEvent = myContract.NewContractCreated({}, {fromBlock: 12345, toBlock: 'latest'});
newContractEvent.watch(function(error, result) {
    if (!error){
        console.log("Success");
        console.log("New Contract Address: " + result.args._newContractAddress);
        console.log("Creator: " + result.args._callerAddress);
        JSON.stringify(result);
    }
});

See How do I retrieve the Voted events from The DAO for further information on using your event's indexed parameters as filter elements.

0

My suggestion would be

  • Create a filter with options {fromBlock:.., toBlock:.., address:.Contract_addr.}
  • Then use filter.get() to receive events from the past
  • Consider caching of past events if you are using MetaMask or remote node

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.