Events
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.
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.
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.
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:
You can filter what data you want to be returned. Since the Transfer event returns from, to, and value we can filter on these properties. Blockchain data return is not instantenous, and can take time to return results.
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.
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.