Skip to main content

WebsocketAccountSubscriber

The WebsocketAccountSubscriber provides real-time account updates through WebSocket connections. It automatically handles connection management and provides event-based updates.

Constructor

pub fn new(
    pubsub: Arc<PubsubClient>,
    pubkey: Pubkey,
    commitment: CommitmentConfig
) -> Self
Parameters:
  • pubsub - Shared reference to a PubsubClient instance
  • pubkey - The account public key to subscribe to
  • commitment - Commitment level for the subscription (e.g., confirmed, finalized)
Example:
use std::sync::Arc;
use drift_pubsub_client::PubsubClient;
use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey};

let pubsub = Arc::new(PubsubClient::new("wss://api.mainnet-beta.solana.com").await?);
let account_pubkey = Pubkey::from_str("...").unwrap();
let commitment = CommitmentConfig::confirmed();

let subscriber = WebsocketAccountSubscriber::new(
    pubsub,
    account_pubkey,
    commitment
);

Methods

subscribe

pub async fn subscribe<F>(
    &self,
    subscription_name: &'static str,
    sync: bool,
    on_update: F,
) -> SdkResult<UnsubHandle>
where
    F: 'static + Send + Fn(&AccountUpdate)
Start a WebSocket account subscription task. Fetches the initial account state if sync is true, then uses event-based updates. Parameters:
  • subscription_name - User-defined identifier for the subscription
  • sync - If true, fetches account data on start to seed initial state
  • on_update - Callback function invoked on each account update
Returns:
  • UnsubHandle - Handle to unsubscribe from the stream
Example:
let unsub_handle = subscriber.subscribe(
    "my-account-sub",
    true,  // sync initial state
    |update: &AccountUpdate| {
        println!("Account updated: slot={}, lamports={}", 
            update.slot, 
            update.lamports
        );
    }
).await?;

// Later, to unsubscribe:
// unsub_handle.send(()).ok();

AccountUpdate

The account update structure passed to callbacks:
pub struct AccountUpdate {
    pub owner: Pubkey,
    pub lamports: u64,
    pub pubkey: Pubkey,
    pub data: Vec<u8>,
    pub slot: Slot,
}
Fields:
  • owner - The program that owns the account
  • lamports - Current lamport balance
  • pubkey - The account’s public key
  • data - Account data bytes
  • slot - Slot number when the update occurred

Features

  • Automatic Reconnection: Automatically reconnects on WebSocket disconnections
  • Slot Ordering: Only processes updates from later slots to prevent stale data
  • Initial Sync: Optionally fetches initial account state before streaming updates
  • Base64Zstd Encoding: Uses compressed encoding for efficient data transfer

Build docs developers (and LLMs) love