Developers
Tutorials

Events

5min

Events on Caduceus are a way to raise awareness of, and track all historical transactions as they are persisted in blocks.

There are three main ways to subscribe to events in Web3.js, the preferred Javascript library for interacting with blockchain Events.



The eth subscribe method

This method of subscribing to events is like a “catch-all” method. It captures all event logs and therefore is all inclusive and exhaustive. Event logs are stored in a special area on EVM.

JS


The subscribe method will return a Subscription instance. The subscription instance has these properties and methods:

  • id – This is the subscription id
  • unsubscribe(callback) – This method can be used to unsubscribe from the subscription
  • subscribe(callback) – This method can be used to re-subscribe with the same parameters as the initial subscription had
  • arguments – The subscription arguments that are used when re-subscribing.



getPastEvents

The first method is called getPastEvents and is attached to a contract’s instance. It gets full historical data based on a filter criteria. As an example, if we have an ERC20 token we want to get all past Transfer events where the value transferred was 1000 or 1337, we will do the following in our user-facing Javascript:

JS


You can filter what data you want to be returned. Since the Transfer event returns fromto, and value we can filter on these properties. Blockchain data return is not instantenous, and can take time to return results.



Contract instance event method

The second way to subscribe to events from a contract is to use the event methods that have been automatically generated by web3.js on your contract instance. This requires an ABI. This method is also temporary in nature, and will delete events when the user session ends.

JS


Each events method will return an EventEmitter. The events that you can listen to are the ones we are listening to in the example code above. Where:

  • data – Will fire each time an event of the type you are listening for has been emitted
  • changed – Will fire for each event of the type you are listening for that has been removed from the blockchain.
  • error – Will fire if an error in the event subscription occurs.
  • connected – Will fire when the subscription has successfully established a connection. It will return a subscription id. This event only fires once.