Skip to main content

Handle events

In the world of programming, events play a fundamental role. They represent significant actions or changes in the state of a system, and their proper management is essential for smooth interaction and an exceptional user experience.

We will see how to handle the web3 events of the sdk so that you can create applications that react to changes in the state of the blockchain.

info

All events discussed below represent local or Alfa services changes in the state of the blockchain. They are not events of the blockchain itself.

tip

The available events are seen in the section List of available events

Eventbus

To handle the events, Alpha provides an event bus that allows you to subscribe to the events you want. The event bus is an object that can be obtained through the events property of the sdk.

tip

For more information about the event bus, see the section Event bus

Subscribe to an event

To subscribe to an event, you must call the registerHandler method of the event bus, passing as a parameter the name of the event to which you want to subscribe and a function that will be executed each time the event is emitted. Let's see how we can subscribe to the MintAssetEvent event:

const eventBus = sdk.events;

eventBus.registerHandler<MintAssetEvent>(MintAssetEvent.eventName, async (event) => {
console.log(`New asset minted: ${event.payload.asset.assetId}`);
});

It is not efficient to reload the list of assets from a wallet when sending a mining, transfer or deletion transaction because, being asynchronous, the transaction may take time to be mined and confirmed. Therefore, it is better to subscribe to asset mining, transfer and deletion events in order to update the list of assets in the wallet when these events are emitted.

info

Remember to unsubscribe from events when you no longer need them. See more information in the section Event bus