Skip to content

WebSocket API Reference ​

The WebSocket API provides a real-time connection-based interface for subscribing to events on the IOST Layer 2 network. Through WebSocket, you can receive live updates on new blocks, transactions, and other on-chain activities as they occur.

Endpoint ​

The WebSocket API endpoint for IOST Layer 2 is: wss://l2-mainnet.iost.io/ws

Request Format ​

WebSocket requests are typically sent as JSON-RPC messages over an open connection. A typical subscription message might look like this:

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "subscribe",
  "params": ["newHeads"]
}

The above message subscribes to new block headers. Adjust the params array as needed to subscribe to different events.

Example Usage ​

Below are several examples demonstrating how to use the WebSocket API.

Using JavaScript (Native WebSocket) ​

javascript
// Create a new WebSocket connection
const ws = new WebSocket("wss://l2-mainnet.iost.io/ws");

// Connection opened
ws.onopen = function () {
  console.log("WebSocket connected.");

  // Subscribe to new block headers (example)
  const subscribeMessage = {
    jsonrpc: "2.0",
    id: 1,
    method: "subscribe",
    params: ["newHeads"]
  };
  ws.send(JSON.stringify(subscribeMessage));
};

// Listen for incoming messages
ws.onmessage = function (event) {
  console.log("Received:", event.data);
};

// Handle errors
ws.onerror = function (error) {
  console.error("WebSocket error:", error);
};

// Connection closed
ws.onclose = function (event) {
  console.log("WebSocket connection closed.", event);
};

Additional Resources ​

For more information on using WebSocket connections and the JSON-RPC protocol over WebSocket, please refer to the WebSocket API documentation and the Ethereum JSON-RPC Specification.

Released under the MIT License.