Subscribing to Events
Real-time updates are crucial for many blockchain applications, enabling them to react instantly to changes on the ledger. The @ocap/client
library's GraphQLClient
provides robust capabilities for subscribing to blockchain events, ensuring your application stays synchronized with the network.
This section delves into how to leverage subscriptions to monitor blockchain activities. For an overview of all client functionalities, refer to Client Capabilities.
How Subscriptions Work#
Blockchain event subscriptions are facilitated over a WebSocket connection. The GraphQLClient
manages this connection automatically, transparently handling the underlying WebSocket setup and teardown. When you subscribe to an event, the client establishes a connection to the Forge node's WebSocket endpoint and listens for relevant data.
The following diagram illustrates the typical flow of an event subscription:
subscribe
Method#
The subscribe
method allows you to listen for specific real-time events on the blockchain. When an event matching your specified topic occurs, your provided callback function is executed with the event data.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the event topic to subscribe to (e.g., |
|
| A function that will be called with the event data whenever the specified event occurs. |
Returns
The subscribe
method returns the GraphQLClient
instance itself, allowing for method chaining. The underlying WebSocket client manages the event listeners.
Example
const GraphQLClient = require('@ocap/client');
const { fromRandom, WalletType } = require('@ocap/wallet');
const Mcrypto = require('@ocap/mcrypto');
const client = new GraphQLClient('http://localhost:8210/api');
(async () => {
// Subscribe to 'tx.create' events
client.subscribe('tx.create', (tx) => {
console.log('New transaction created:', tx.hash);
// You can process the transaction data here
});
// Listen for errors on the underlying WebSocket connection
client._socketClient.on('error', (error) => {
console.error('WebSocket Error:', error.message);
});
console.log('Subscribed to tx.create events. Waiting for transactions...');
// Example: Declare a new account to trigger a 'tx.create' event
const wallet = fromRandom(
WalletType({
role: Mcrypto.types.RoleType.ROLE_ACCOUNT,
pk: Mcrypto.types.KeyType.SECP256K1,
hash: Mcrypto.types.HashType.SHA3,
})
);
const hash = await client.declare({
moniker: 'subscription-test-user',
wallet,
});
console.log('Declared new account with transaction hash:', hash);
})();
This example demonstrates how to subscribe to tx.create
events. When a new transaction is created on the blockchain (e.g., by declaring a new account), the provided callback function will log its hash. It also shows how to listen for errors on the WebSocket connection that powers the subscriptions.
unsubscribe
Method#
If you no longer need to listen for a specific event, you can use the unsubscribe
method to remove the previously registered callback. This helps manage resources and prevent unnecessary processing.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the event topic to unsubscribe from. |
|
| The exact callback function that was previously registered for the topic. |
Returns
The unsubscribe
method returns the GraphQLClient
instance itself.
Example
const GraphQLClient = require('@ocap/client');
const client = new GraphQLClient('http://localhost:8210/api');
const myTransactionCallback = (tx) => {
console.log('Received transaction:', tx.hash);
// After receiving one transaction, we might want to stop listening
client.unsubscribe('tx.create', myTransactionCallback);
console.log('Unsubscribed from tx.create events.');
};
(async () => {
client.subscribe('tx.create', myTransactionCallback);
console.log('Subscribed to tx.create events.');
// In a real application, a transaction would happen here naturally,
// or you would declare one to test.
// For demonstration, let's wait a bit and then manually trigger unsubscribe
await new Promise(resolve => setTimeout(resolve, 5000));
if (client._socketClient.hasListeners('tx.create', myTransactionCallback)) {
client.unsubscribe('tx.create', myTransactionCallback);
console.log('Manually unsubscribed from tx.create events after 5 seconds.');
} else {
console.log('Already unsubscribed or no listeners found.');
}
})();
This example shows how to subscribe to an event and then later unsubscribe from it using the same topic and callback function. This is essential for preventing memory leaks and managing event listeners effectively.
Common Subscription Topics#
The most commonly used subscription topic is tx.create
, which allows you to receive notifications for every new transaction that is created and submitted to the blockchain. Other topics may be available depending on the specific Forge node configuration and future updates.
Understanding how to subscribe to real-time events is vital for building dynamic and responsive blockchain applications. You can now react to on-chain changes as they happen. Next, explore the various Transaction Types and Usage to learn how to interact with the blockchain by sending different kinds of transactions.