I'm confused about the difference between myContract.events.MyEvent() and web3.eth.subscribe('logs', ...); Both are subscriptions to events, correct?
1 Answers
They are both subscriptions to events, but filtered a little differently.
myContract.events.MyEvent() will only return MyEvent events from the specific contract address that you used to create the web3 contract myContract
web3.eth.subscribe('logs', ...) will subscribe to all blockchain events by default.
Per the web3 documentation you can use: web3.eth.subscribe('logs', options [, callback]). Within options, you can use the address and topics to filter this broad subscription to listen to the specific events you want to listen to. In this case, if you wanted to use web3.eth.subscribe listen to the same thing as myContract.events.MyEvent() you would use the options variable and set options.address to the contract address you used to create myContract options.topics to an array where the first topic in the array is MyEvent signature. This would look something like:
web3.eth.subscribe(
'logs',
{
address: myContractAddress,
topics: [Keccak-256 hash(MyEvent(~~parameters here~~))]
},
() => console.log(Saw MyEvent);
);
References
Subscribe to Logs & Options Reference:
https://web3js.readthedocs.io/en/v1.2.7/web3-eth-subscribe.html#subscribe-logs
Event Topics:
- 1,461
- 10
- 15
smart contract-> emit myevent(string)
– Mario Roma Dec 29 '20 at 10:44node-> ??