WebSockets with Xion: Real-Time Communication
WebSockets are a powerful tool for enabling real-time, bidirectional communication between a client and a server. Within the Xion ecosystem by integrating WebSockets, you can:
Enable real-time updates for decentralized apps (dApps).
Stream blockchain events (e.g., transactions, smart contract triggers) to clients.
Build interactive and responsive user experiences.
Reduce latency compared to traditional polling methods.
Prerequisites
Before diving in, ensure you have NPM and Node.js installed on your machine.:
Create a New Project
Initialize a New Node.js Project
Make sure you have npm
and node
installed. Then, create a new Node.js project by running:
This command creates a package.json
file with default settings.
Install Required Dependencies
The most basic method for interacting with WebSockets in a Node.js environment is via the ws
package. Install ws
via the following command:
We will also use uuid
to generate a unique id for our more complex example. Install uuid
using the following command:
Setting up the Main Script
Create an index.js
File
index.js
FileWithin your project directory, create an index.js.
This file will contain all the code we'll create in the sections below.
Integrating WebSockets into your Project
Below, we’ll cover the simplest way to set up WebSockets in your JavaScript project.
Establishing a WebSocket Connection
You can find websocket endpoints for any of the available XION networks on the Public Endpoints & Resources page. Here’s how to connect to a Xion node using a WebSocket endpoint (add to your index.js file):
Subscribing to Blockchain Events
One of the most powerful features of WebSockets is the ability to subscribe to blockchain events in real time. For example, you can listen for new transactions or smart contract events.
Example: Subscribing to New Blocks
Add the following to your index.js file:
Running the Project
Execute the Script
Run the index.js
script using Node.js:
You should see output indicating that the connection to Websocket endpoint has been established, and new blocks and transactions will be logged to the console as they occur.
Example Project: Real-Time Transaction Tracker
This code creates a real-time transaction monitoring system where any time a set address receives tokens the tracker will spit out the details of the transaction. Let's break it down section by section:
Import and Setup
This section imports the necessary libraries and sets up initial variables:
The
ws
library provides WebSocket functionality for real-time communicationuuid
generates unique identifiers for each subscription requestaddress
stores the blockchain address we're monitoringwebsocket
andwsQuery
are initialized as empty variables to store the connection and query
Main Function: queryForBalanceUpdate()
This function:
Establishes a WebSocket connection to the XION testnet RPC endpoint
Creates a subscription request
Uses a unique ID (via UUID) for each request
Sets up a query filter that watches for transactions where our address appears as a recipient
Event Handlers
These event handlers manage the WebSocket lifecycle:
open
: When connection is established, it sends our subscription requestmessage
: When data is received, it parses the JSON response, logs matching transactions, and disconnectserror
: Handles and logs any errors, then disconnects
Cleanup Function: disconnectFromWebsocket()
This function ensures proper cleanup:
Checks if the connection is still open
Sends an unsubscribe request using the same ID as the subscription
Properly closes the connection
Resets the variables to null
Process Management
The final section:
Sets up an event listener to clean up the connection when the Node.js process exits
Starts the monitoring by calling the main function
Putting It All Together
Example: Real-Time Transaction Tracker
Here’s the complete example.
Execute the Script
Run the index.js
script using Node.js:
When tokens are transferred to the address set in the script the script will print out the details of the transfer.
Last updated
Was this helpful?