13

I read that to listen to events you need to use web3.js. Are there other ways of doing it? Can a contract even somehow listen to events of another contract? Thanks!

16

A contract cannot listen to events of another contract. From Solidity docs:

Log and event data is not accessible from within contracts (not even from the contract that created a log).

web3.js is a wrapper around JSON-RPC, so another way of accessing event data is via "filters" in JSON-RPC such as eth_newFilter.

Note the dichotomy that a contract can't access events and web3.js is needed, but web3.js can't access return values from a contract invocation. So a pattern of using both an event and a return value like this may be needed:

event FooEvent(uint256 n);
function foo() returns (uint256) {
  FooEvent(1337);
  return 1337;
}
  • What is the javascript web3 code for event listening? – Justin Thomas Sep 4 '17 at 20:53
  • 2
    @JustinThomas const instance = Web3.eth.contract(ABI).at(ADDRESS); instance.FooEvent().watch((err, response) => { console.log (response); }) – Raghav Dua Sep 29 '17 at 11:42
  • @JustinThomas IMHO event listening APIs are the least clear and there are several ways of achieving the same thing. For other options to Raghav's comment, ethereum.stackexchange.com/questions/2024/… may help. – eth Oct 10 '17 at 8:38
0

I'm going to just come out and say No, a contract cannot listen for events from another contract. Solidity has emit('event') to emit events, but lacks on('event') for listening to events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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