29

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!

1

3 Answers 3

30

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;
}
5
  • What is the javascript web3 code for event listening? Sep 4, 2017 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, 2017 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, 2017 at 8:38
  • listening events using these lib can be risky as you may miss some events when some unexpected error occurs. best way to deal with such a flow is to make a loop and rather grab logs from the target contract Mar 26, 2022 at 8:32
  • Looks like it may become possible in new Solidity versions - soliditylang.org/blog/2023/07/19/… Jul 20, 2023 at 9:14
2

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.

1

Just to add on to ETH's answer.

Blockchains use State Tries to store state, and are as such, poor databases. Storing(and as a consequence, listening to) events is extremely expensive (ABOUT $73,000 for a Gigabyte of storage).

And if you can't store events, you can't listen to them. Most blockchains I'm aware of don't even give you access to store emitted events as a result of this

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.