> ## 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.

# RPC Client

> JSON-RPC client with retry, failover, and typed helpers for common Solana methods.

## Install

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

The RPC client has no extra peer dependencies.

## Building the client

Here's a client with every option set:

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

const client = new RpcClientBuilder()
  .url('http://ny.rpc.orbitflare.com')
  .fallbackUrl('http://fra.rpc.orbitflare.com')
  .fallbackUrl('http://ams.rpc.orbitflare.com')
  .apiKey('ORBIT-XXXXXX-NNNNNN-NNNNNN')
  .commitment('confirmed')
  .retry({
    initialDelayMs: 100,
    maxDelayMs: 30_000,
    multiplier: 2.0,
    maxAttempts: 5,
  })
  .timeoutMs(30_000)
  .build();
```

Most of these have sensible defaults. A minimal setup:

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

### Builder methods

**`.url(url)`** - The primary endpoint to send requests to. If not set, the SDK checks the `ORBITFLARE_RPC_URL` environment variable.

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

**`.urls([...])`** - Set the primary and all fallbacks in one call. The first element is the primary, the rest are fallbacks.

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

**`.fallbackUrl(url)`** - Add a single fallback endpoint. Call multiple times to add several. When the primary fails, the SDK tries fallbacks in order.

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

**`.fallbackUrls([...])`** - Same as `fallbackUrl` but takes an array.

```ts theme={null}
.fallbackUrls(['http://fra.rpc.orbitflare.com', 'http://ams.rpc.orbitflare.com'])
```

**`.apiKey(key)`** - Your OrbitFlare license key. If not set, the SDK checks `ORBITFLARE_LICENSE_KEY` from the environment. The key is injected into the URL at request time, never stored in the endpoint.

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

**`.commitment(level)`** - Default commitment level used for all typed helpers. Options: `'processed'`, `'confirmed'`, `'finalized'`. Defaults to `'confirmed'`.

```ts theme={null}
.commitment('finalized')
```

**`.retry(policy)`** - Controls how the SDK retries failed requests. `initialDelayMs` is the wait before the first retry. `multiplier` scales the delay on each attempt. `maxDelayMs` caps the backoff. `maxAttempts` limits total retries per endpoint (0 means infinite). Defaults: 100ms initial, 30s max, 2x multiplier, infinite attempts.

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

**`.timeoutMs(ms)`** - HTTP timeout for each individual request. Defaults to 30 seconds.

```ts theme={null}
.timeoutMs(10_000)
```

## Available RPC methods

### `getSlot()`

Returns the current slot number.

```ts theme={null}
const slot: number = await client.getSlot();
```

### `getBalance(address)`

Returns the balance in lamports for an account.

```ts theme={null}
const lamports: number = await client.getBalance('So11111111111111111111111111111111111111112');
const sol = lamports / 1_000_000_000;
```

### `getAccountInfo(address)`

Returns the full account data or `null` if the account doesn't exist. Data is base64-encoded.

```ts theme={null}
const account = await client.getAccountInfo('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
if (account) {
  console.log('owner:', account.owner);
  console.log('lamports:', account.lamports);
  console.log('data length:', (account.data?.[0] ?? '').length);
}
```

### `getMultipleAccounts(addresses)`

Fetches multiple accounts in one call. Automatically chunks into batches of 100 (Solana's per-request limit), so you can pass any number of addresses.

```ts theme={null}
const accounts = await client.getMultipleAccounts(['addr1', 'addr2', 'addr3']);

accounts.forEach((acct, i) => {
  if (acct) console.log(`account ${i}: ${acct.lamports} lamports`);
  else console.log(`account ${i}: not found`);
});
```

### `getLatestBlockhash()`

Returns the most recent blockhash and the last block height it's valid for.

```ts theme={null}
const { blockhash, lastValidBlockHeight } = await client.getLatestBlockhash();
```

### `getTransaction(signature)`

Fetches a confirmed transaction by its signature. Returns the full transaction with metadata.

```ts theme={null}
const tx = await client.getTransaction('5K8F2j...');
console.log('slot:', tx.slot);
console.log('fee:', tx.meta?.fee);
```

### `getSignaturesForAddress(address, limit)`

Returns recent transaction signatures for an address, newest first.

```ts theme={null}
const sigs = await client.getSignaturesForAddress('So111...', 10);

for (const sig of sigs) {
  console.log(`${sig.signature} at slot ${sig.slot}`);
}
```

### `getProgramAccounts(programId)`

Returns all accounts owned by a program. Can return a lot of data.

```ts theme={null}
const accounts = await client.getProgramAccounts('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
```

### `getRecentPrioritizationFees(addresses)`

Returns recent priority fees for a set of accounts. Useful for estimating compute unit pricing.

```ts theme={null}
const fees = await client.getRecentPrioritizationFees(['6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P']);

for (const fee of fees) {
  console.log(`slot ${fee.slot}: ${fee.prioritizationFee} micro-lamports`);
}
```

### `sendTransaction(txBase64)`

Sends a signed transaction to the network. Takes a base64-encoded serialized transaction. Returns the transaction signature.

```ts theme={null}
const signature: string = await client.sendTransaction(txBase64);
console.log('sent:', signature);
```

### `simulateTransaction(txBase64)`

Simulates a transaction without submitting it. Returns logs, compute units consumed, and any errors.

```ts theme={null}
const result = await client.simulateTransaction(txBase64);
if (result.err) {
  console.log('simulation failed:', result.err);
} else {
  console.log('compute units:', result.unitsConsumed);
}
```

### `getTokenAccountsByOwner(owner, mint?, programId?)`

Returns token accounts for a wallet. Pass either a specific mint or a token program ID. If both are omitted, defaults to the SPL Token program.

```ts theme={null}
const tokens = await client.getTokenAccountsByOwner('wallet_address');

for (const token of tokens) {
  const info = token.account?.data?.parsed?.info;
  console.log(`mint: ${info?.mint} balance: ${info?.tokenAmount?.uiAmountString}`);
}
```

### `getTransactionsForAddress(address, options)`

OrbitFlare-specific method that combines `getSignaturesForAddress` and `getTransaction` into one call. Returns a `GetTransactionsResult` with the data array and an optional `paginationToken` for fetching the next page.

Supports four detail levels (`signatures`, `none`, `accounts`, `full`), bidirectional sorting, time/slot filtering, status filtering, and token account inclusion.

```ts theme={null}
const result = await client.getTransactionsForAddress('address', {
  transactionDetails: 'full',
  limit: 100,
  sortOrder: 'asc',
  filters: {
    tokenAccounts: 'all',
    status: 'succeeded',
    blockTime: { gte: 1704067200, lte: 1706745600 },
  },
});

for (const tx of result.data) {
  console.log(`slot ${tx.slot}`);
}

if (result.paginationToken) {
  // fetch next page using { paginationToken: result.paginationToken }
}
```

### `request(method, params)`

Call any RPC method by name. The SDK builds the JSON-RPC envelope, handles retry and failover, and returns the `result` field.

```ts theme={null}
const epoch = await client.request('getEpochInfo', []);
const inflation = await client.request('getInflationRate', []);
const supply = await client.request('getSupply', []);
```

### `requestRaw(body)`

Send a raw JSON-RPC body string. Same retry and failover as everything else.

```ts theme={null}
const result = await client.requestRaw(
  '{"jsonrpc":"2.0","id":1,"method":"getHealth","params":[]}',
);
```

## Full example

A script that checks the state of the network, fetches a wallet's SOL balance and token holdings, and looks up recent transactions.

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

async function main() {
  const client = new RpcClientBuilder()
    .url('http://ny.rpc.orbitflare.com')
    .fallbackUrl('http://fra.rpc.orbitflare.com')
    .commitment('confirmed')
    .build();

  const wallet = 'CKs1E69a2e9TmH4mKKLrXFF8kD3ZnwKjoEuXa6sz9WqX';

  const slot = await client.getSlot();
  const { blockhash } = await client.getLatestBlockhash();
  console.log(`network slot: ${slot}`);
  console.log(`blockhash: ${blockhash}`);

  const balance = await client.getBalance(wallet);
  console.log(`\n${wallet}`);
  console.log(`  SOL: ${(balance / 1_000_000_000).toFixed(4)}`);

  const tokens = await client.getTokenAccountsByOwner(wallet);
  for (const token of tokens) {
    const info = token?.account?.data?.parsed?.info;
    const mint = info?.mint ?? 'unknown';
    const amount = info?.tokenAmount?.uiAmountString ?? '0';
    if (amount !== '0') console.log(`  ${mint}: ${amount}`);
  }

  const sigs = await client.getSignaturesForAddress(wallet, 5);
  console.log('\nrecent transactions:');
  for (const sig of sigs) {
    const signature = sig?.signature ?? '?';
    const status = sig?.err == null ? 'ok' : 'failed';
    console.log(`  ${sig?.slot ?? 0} ${status} ${signature.slice(0, 20)}`);
  }

  const fees = await client.getRecentPrioritizationFees([wallet]);
  const total = fees.reduce(
    (acc: number, f: any) =>
      acc + (typeof f?.prioritizationFee === 'number' ? f.prioritizationFee : 0),
    0,
  );
  const avg = total / Math.max(fees.length, 1);
  console.log(`\navg priority fee: ${avg.toFixed(0)} micro-lamports`);
}

void main();
```
