Subscriptions
Solana Subscriptions

Solana WebSocket Subscriptions

WebSocket subscriptions in Solana offer a way to monitor blockchain events in real time. Using WebSockets, you can subscribe to specific updates, such as changes in account data, signature statuses, or slot notifications, without constantly polling the network. This is essential for building responsive and efficient Solana-based applications.

How dRPC charges subscriptions#

This billing will be valid from 1 February 2025

  • Subscription: Establishing WSS connection and subscribing to events.
  • Notification: Receiving notifications from the events you've subscribed to.
Action TypeCU
Subscription25
Notification100

Supported Subscription Types#

Solana WebSocket API supports multiple subscription types:

Account Changes
Subscribe to updates on a specific account's data. Useful for tracking balance changes or updates to program accounts.

Signature Status
Monitor the status of a specific transaction signature. Get notified when a transaction is confirmed or finalized.

Slot Updates
Track updates for each new slot, such as when a validator produces a new block.

Logs
Subscribe to transaction logs generated by Solana programs. Useful for debugging and monitoring program execution.

Example: Subscribe to Account Changes
Below is an example of using WebSockets to subscribe to updates on a specific account:

import WebSocket from 'ws';
 
// Connect to the Solana WebSocket endpoint
const ws = new WebSocket('wss://lb.drpc.org/ogws?network=solana&dkey=YOUR-DRPC-KEY');
 
ws.on('open', () => {
  // Subscribe to account changes
  ws.send(JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "accountSubscribe",
    params: [
      "YourAccountPublicKeyHere",
      {
        encoding: "base64",
      }
    ]
  }));
});
 
ws.on('message', (data) => {
  const response = JSON.parse(data.toString());
  console.log("Account Update:", response);
});

Why Use WebSocket Subscriptions?#

Real-Time Notifications: Get immediate updates on blockchain events without polling.
Resource Efficiency: Reduce the bandwidth and server load required for continuous data fetching.
Seamless User Experience: Provide instant feedback to users about blockchain activities.

Best Practices#

Use Filters: Subscribe only to the data you need to minimize resource use.
Reconnect Automatically: Ensure your WebSocket client can handle disconnections and re-establish connections.
Throttle Updates: If your application receives frequent updates, implement throttling to prevent data overload. \

WebSocket subscriptions on Solana enable developers to build fast, responsive, and efficient blockchain-based applications. By leveraging these tools, you can ensure your application stays up-to-date with on-chain activity.