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!
2 Answers
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;
}
-
-
2@JustinThomas
const instance = Web3.eth.contract(ABI).at(ADDRESS); instance.FooEvent().watch((err, response) => { console.log (response); })
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 at 8:32
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.