> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orbitflare.com/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket Client

> Real-time subscriptions for account changes, logs, slots, and signatures with auto-reconnect.

## Install

```bash theme={null}
npm install @orbitflare/sdk ws
```

`ws` is an optional peer dependency. Install it only if you use the WebSocket client.

## Building the client

```ts theme={null}
import { WsClientBuilder } from '@orbitflare/sdk/ws';
import type { RetryPolicy } from '@orbitflare/sdk';

const client = await new WsClientBuilder()
  .url('ws://ny.rpc.orbitflare.com')
  .fallbackUrl('ws://fra.rpc.orbitflare.com')
  .apiKey('ORBIT-XXXXXX-NNNNNN-NNNNNN')
  .retry({
    initialDelayMs: 100,
    maxDelayMs: 30_000,
    multiplier: 2.0,
    maxAttempts: 0,
  })
  .pingIntervalSecs(10)
  .maxMissedPongs(3)
  .build();
```

Minimal:

```ts theme={null}
const client = await new WsClientBuilder()
  .url('ws://ny.rpc.orbitflare.com')
  .build();
```

Note that `.build()` is async - it establishes the WebSocket connection before resolving. If the connection fails, the promise rejects immediately.

### Builder methods

**`.url(url)`** - Primary WebSocket endpoint. Falls back to `ORBITFLARE_WS_URL` env var.

```ts theme={null}
.url('ws://ny.rpc.orbitflare.com')
```

**`.urls([...])`** - Primary + fallbacks in one call.

```ts theme={null}
.urls(['ws://ny.rpc.orbitflare.com', 'ws://fra.rpc.orbitflare.com'])
```

**`.fallbackUrl(url)` / `.fallbackUrls([...])`** - Add failover endpoints. On reconnect, the SDK rotates through them.

```ts theme={null}
.fallbackUrl('ws://fra.rpc.orbitflare.com')
```

**`.apiKey(key)`** - License key. Falls back to `ORBITFLARE_LICENSE_KEY` env var.

```ts theme={null}
.apiKey('ORBIT-XXXXXX-NNNNNN-NNNNNN')
```

**`.retry(policy)`** - Reconnection backoff. Default: 100ms initial, 30s max, 2x multiplier, infinite attempts.

```ts theme={null}
.retry({
  initialDelayMs: 200,
  maxDelayMs: 15_000,
  multiplier: 2.0,
  maxAttempts: 0,
})
```

**`.pingIntervalSecs(n)`** - How often the SDK sends WebSocket `Ping` frames. Default: 10.

```ts theme={null}
.pingIntervalSecs(15)
```

**`.maxMissedPongs(n)`** - Pings without a response before killing the connection. Default: 3.

```ts theme={null}
.maxMissedPongs(5)
```

## Available subscriptions

### `slotSubscribe()`

Fires every time a slot is processed, confirmed, or finalized.

```ts theme={null}
const sub = await client.slotSubscribe();
```

Each event is an object with `slot`, `parent`, and `root` fields:

```json theme={null}
{"slot": 413014740, "parent": 413014739, "root": 413014708}
```

### `accountSubscribe(address, commitment)`

Fires when the specified account's data changes.

```ts theme={null}
const sub = await client.accountSubscribe(
  'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  'confirmed',
);
```

Returns base64-encoded account data with lamports, owner, and executable flag.

### `logsSubscribe(mentions, commitment)`

Fires for transactions that mention the given addresses. Pass an empty array for all transactions.

```ts theme={null}
const sub = await client.logsSubscribe(
  ['6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P'],
  'confirmed',
);
```

All logs:

```ts theme={null}
const sub = await client.logsSubscribe([], 'confirmed');
```

### `signatureSubscribe(signature, commitment)`

Fires once when a transaction reaches the given commitment level. Useful for confirming a transaction you just sent.

```ts theme={null}
const sub = await client.signatureSubscribe('5K8F2j...', 'confirmed');
```

## Reading events

All subscriptions return a `WsSubscription`. Call `.next()` to get the next event:

```ts theme={null}
while (true) {
  const event = await sub.next();
  if (event === undefined) break;
  console.log(event);
}
```

`.next()` resolves with `undefined` when the subscription is closed.

You can also attach an event listener style callback:

```ts theme={null}
const off = sub.on((event) => {
  console.log(event);
});

// later: off();
```

## Unsubscribing

```ts theme={null}
await sub.unsubscribe();
```

This sends an unsubscribe message to the server. If you drop a subscription without calling this, the SDK detects the orphan and sends the unsubscribe automatically.

## Multiple subscriptions

All subscriptions run on a single WebSocket connection. The SDK routes notifications to the right subscription internally.

```ts theme={null}
const slots = await client.slotSubscribe();
const usdc = await client.accountSubscribe('EPjFWdd5...', 'confirmed');
const logs = await client.logsSubscribe(['6EF8r...'], 'confirmed');
```

You can add new subscriptions at any time while existing ones are running.

## Reconnection

If the connection drops, the background task reconnects with exponential backoff and re-subscribes everything automatically. Your `.next()` calls just keep working - events resume once the connection is back.

## Full example

A monitoring script that subscribes to slot updates and account changes for USDC, printing a live feed.

```ts theme={null}
import { WsClientBuilder } from '@orbitflare/sdk/ws';

async function main() {
  const client = await new WsClientBuilder()
    .url('ws://ny.rpc.orbitflare.com')
    .build();

  const slots = await client.slotSubscribe();
  const usdc = await client.accountSubscribe(
    'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    'confirmed',
  );

  console.log('watching slots and USDC mint account...');

  slots.on((slot) => {
    const s = slot?.slot ?? 0;
    const parent = slot?.parent ?? 0;
    console.log(`slot ${s} (parent ${parent})`);
  });

  usdc.on((acct) => {
    const lamports = acct?.lamports ?? 0;
    const data = acct?.data?.[0];
    const dataLen = typeof data === 'string' ? data.length : 0;
    console.log(`USDC mint updated: ${lamports} lamports, ${dataLen} bytes`);
  });

  await new Promise(() => {});
}

void main();
```
