# @switchboard-xyz/on-demand

> A Typescript client to interact with Switchboard On-Demand.

Latest version **3.10.6** (published 2026-07-30) · ISC license · 0 weekly downloads

## Install

```sh
npm install @switchboard-xyz/on-demand
pnpm add @switchboard-xyz/on-demand
yarn add @switchboard-xyz/on-demand
bun add @switchboard-xyz/on-demand
```

## Health

**Score 60/100 (C)** — status: active.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 3.10.6 |
| Published | 2026-07-30 |
| First published | 2024-03-12 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >= 18 |
| Dependencies | 15 |
| Unpacked size | 2.9 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | mgild, jessupjn, eldios, jackswitchboard, gesarki |

## Links

- npm: https://www.npmjs.com/package/@switchboard-xyz/on-demand
- npm.io page: https://npm.io/package/@switchboard-xyz/on-demand

## Dependencies (15)

- [ws](https://npm.io/package/ws.md) ^8.18.1
- [bs58](https://npm.io/package/bs58.md) ^6.0.0
- [axios](https://npm.io/package/axios.md) ^1.9
- [buffer](https://npm.io/package/buffer.md) ^6.0.3
- [events](https://npm.io/package/events.md) ^3.3.0
- [js-yaml](https://npm.io/package/js-yaml.md) ^4.1.0
- [tweetnacl](https://npm.io/package/tweetnacl.md) ^1.0.3
- [@noble/hashes](https://npm.io/package/@noble/hashes.md) ^1.8.0
- [isomorphic-ws](https://npm.io/package/isomorphic-ws.md) ^5.0.0
- [@solana/web3.js](https://npm.io/package/@solana/web3.js.md) ^1.98.4
- [@isaacs/ttlcache](https://npm.io/package/@isaacs/ttlcache.md) ^1.4.1
- [@solana/spl-token](https://npm.io/package/@solana/spl-token.md) ^0.4.14
- [@coral-xyz/anchor-31](https://npm.io/package/@coral-xyz/anchor-31.md) npm:@coral-xyz/anchor@0.31.1
- [@switchboard-xyz/common](https://npm.io/package/@switchboard-xyz/common.md) ^5.8.5
- [@switchboard-xyz/common-legacy](https://npm.io/package/@switchboard-xyz/common-legacy.md) ^1.1.1

## Recent versions

- 3.10.6 (latest) — 2026-07-30
- 2.13.2-alpha0.0.6 (alpha) — 2025-08-01
- 2.8.0-beta.0 (beta) — 2025-05-10
- 3.10.5 — 2026-07-28
- 3.10.4 — 2026-06-22
- 3.10.3 — 2026-06-07
- 3.10.2 — 2026-05-20
- 3.10.1 — 2026-04-21
- 3.9.0 — 2026-02-11
- 3.8.2 — 2026-01-08
- 3.8.1 — 2026-01-08
- 3.8.0 — 2026-01-07
- 3.7.3 — 2025-12-01
- 3.7.2 — 2025-12-01
- 3.7.1 — 2025-11-19
- … 342 more at https://npm.io/package/@switchboard-xyz/on-demand/versions

## README

<div align="center">

![Switchboard Logo](https://github.com/switchboard-xyz/switchboard/raw/main/website/static/img/icons/switchboard/avatar.png)

# Switchboard

</div>

# Switchboard On-Demand (typedoc: https://switchboard-docs.web.app)
See the full documentation at [Switchboard On-Demand Documentation](https://docs.switchboard.xyz)

Switchboard On-Demand is designed to support high-fidelity financial systems. It allows users to specify how data from both on-chain and off-chain sources is ingested and transformed.

Unlike many pull-based blockchain oracles that manage data consensus on their own Layer 1 (L1) and then propagate it to users—giving oracle operators an advantage—Switchboard Oracles operate inside confidential runtimes. This setup ensures that oracles cannot observe the data they are collecting or the operations they perform, giving the end user a 'first-look' advantage when data is propagated.

Switchboard On-Demand is ideal for blockchain-based financial applications and services, offering a solution that is cost-effective, trustless, and user-friendly.

## Key Features:
- **User-Created Oracles**: In Switchboard, users have the flexibility to build their own oracles according to their specific needs.
- **Confidential Runtimes**: Oracle operations are performed in a way that even the oracles themselves cannot observe, ensuring data integrity and user advantage.
- **High-Fidelity Financial Applications**: Designed with financial applications in mind, Switchboard ensures high accuracy and reliability for transactions and data handling.

## Browser Compatibility

This library is compatible with both **Node.js** and **browser** environments. However, some utility functions require Node.js file system access:

### Node.js-Only Functions
- `AnchorUtils.initKeypairFromFile()` - Use `web3.Keypair.fromSecretKey()` directly in browsers
- `AnchorUtils.initWalletFromFile()` - Use browser wallet adapters (e.g., Phantom, Solflare) instead
- `AnchorUtils.loadEnv()` - Use `loadProgramFromConnection()` with your own connection/wallet

### Browser Usage Example
```typescript
import * as sb from '@switchboard-xyz/on-demand';
import { CrossbarClient } from '@switchboard-xyz/common';
import { Connection, clusterApiUrl } from '@solana/web3.js';

// Use browser wallet adapter instead of file-based keypair
const connection = new Connection(clusterApiUrl('mainnet-beta'));
const program = await sb.AnchorUtils.loadProgramFromConnection(
  connection,
  walletAdapter // From @solana/wallet-adapter-react or similar
);

// Current Solana/SVM feed-hash updates use the quote program.
const crossbar = CrossbarClient.default();
const queue = await sb.Queue.loadDefault(program);
const feedHash = '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f';

const [quoteAccount] = sb.OracleQuote.getCanonicalPubkey(queue.pubkey, [feedHash]);
const updateIxs = await queue.fetchManagedUpdateIxs(crossbar, [feedHash], {
  numSignatures: 3,
  payer: walletAdapter.publicKey,
});
```

## Getting Started
To start building your own on-demand oracle with Switchboard, you can refer to the oracle specification in our [documentation](https://protos.docs.switchboard.xyz/protos/OracleJob).

### Feed Parameter Units

Solana helper methods such as `PullFeed.initIx` and `PullFeed.setConfigsIx` accept human-percent `maxVariance` values and scale them by `1e9` internally. Raw v2 `OracleFeed.maxJobRangePct` values are already scaled integers, so `1_000_000_000` means `1%`. `minJobResponses` and `minOracleSamples` are unscaled counts. See [Feed Parameter Units](https://docs.switchboard.xyz/custom-feeds/advanced-feed-configuration/feed-parameter-units).

### Example Code Snippet:
```typescript
import * as sb from '@switchboard-xyz/on-demand';
import { CrossbarClient } from '@switchboard-xyz/common';

const crossbar = CrossbarClient.default();
const queue = await sb.Queue.loadDefault(program);
const feedHash = '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f';

// Derive the quote-program account that stores the verified feed value.
const [quoteAccount] = sb.OracleQuote.getCanonicalPubkey(queue.pubkey, [feedHash]);

// Fetch Ed25519 verification + quote-program verified_update instructions.
const updateIxs = await queue.fetchManagedUpdateIxs(crossbar, [feedHash], {
    numSignatures: 3,
    payer: payer.publicKey,
});
const tx = await sb.asV0Tx({
    connection,
    ixs: updateIxs,
    signers: [payer],
    computeUnitPrice: 200_000,
    computeUnitLimitMultiple: 1.3,
});
await program.provider.connection.sendTransaction(tx, {
    // preflightCommitment is REQUIRED to be processed or disabled
    preflightCommitment: "processed",
});
```

For new Solana/SVM feed-hash integrations, read from the derived
`quoteAccount` after the managed update lands. The older
`PullFeed.fetchUpdateIx()` path targets classic PullFeed accounts and requires
legacy secp256k1-compatible queue and gateway support.

## SwitchboardSurge - Real-time Price Streaming

The `SwitchboardSurge` class provides real-time price streaming capabilities through WebSocket connections to Switchboard gateways.

### Quick Start

```typescript
import { SwitchboardSurge } from '@switchboard-xyz/on-demand';

// Initialize and subscribe to price feeds
const surge = new SwitchboardSurge({
  apiKey: 'your-api-key',
  gatewayUrl: 'http://localhost:8082', // Your gateway URL
});

// Listen for price updates
surge.on('data', (update) => {
  console.log('Price update:', update.processed.values);
});

// Subscribe to feeds (validation happens automatically)
await surge.subscribe([
  { symbol: 'BTCUSDT', source: 'BINANCE' },
  { symbol: 'ETHUSDT', source: 'BINANCE' },
]);
```

### Event Handling

```typescript
surge.on('connected', () => {
  console.log('Connected to Switchboard Surge');
});

surge.on('data', (response) => {
  // response.processed: Ready for Solana transactions
  console.log('Feed values:', response.processed.values);
  console.log('Feed hashes:', response.processed.feedHashes);
});

surge.on('error', (error) => {
  console.error('Streaming error:', error.message);
});

surge.on('disconnected', (code, reason) => {
  console.log('Disconnected:', code, reason);
});
```

### Configuration

```typescript
const surge = new SwitchboardSurge({
  apiKey: 'your-api-key',
  gatewayUrl: 'http://localhost:8082',  // Your gateway URL
  autoReconnect: true,                  // Auto-reconnect on disconnect
  maxReconnectAttempts: 5,              // Max reconnection attempts
  reconnectDelay: 1000,                 // Delay between reconnects (ms)
});
```

## Oracle Quote Functionality

The `OracleQuote` class provides utilities for working with oracle quote accounts and verified oracle data.

### Deriving Oracle Quote Accounts

```typescript
import { OracleQuote } from '@switchboard-xyz/on-demand';

// Derive the canonical oracle quote account address from feed hashes
const feedHashes = [
  'your-feed-hash-1',
  'your-feed-hash-2'
];

const [oracleAccount, bump] = OracleQuote.getCanonicalPubkey(
  queueKey,   // Queue public key for canonical derivation (required)
  feedHashes  // Uses default program ID
);
console.log('Oracle Quote Account:', oracleAccount.toString());

// Or with a custom program ID:
const [customOracleAccount, customBump] = OracleQuote.getCanonicalPubkey(
  queueKey,
  feedHashes,
  customProgramId
);
```

The `OracleQuote.getCanonicalPubkey()` method:
- Takes a queue public key as the first parameter (required)
- Takes an array of feed hashes as the second parameter (32-byte hex strings or Buffers)
- Optionally takes a program ID as the third parameter
- Returns the program-derived address for the oracle quote account
- Uses the default quote program ID `orac1eFjzWL5R3RbbdMV68K9H6TaCVVcL6LjvQQWAbz` if no program ID is provided
- Matches the Rust implementation for consistent address derivation (queue key + feed hashes as seeds)

### Feed Hash Format

Feed hashes must be provided as:
- **Hex strings**: 64-character hex strings (with or without '0x' prefix)
- **Buffers**: 32-byte Buffer objects

```typescript
// Valid formats
const feedHashes = [
  '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
  '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
  Buffer.from('1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', 'hex')
];
```

### Reading Stored Quote Accounts

Stored quote-program accounts are variable-length. Do not read feed values by
hard-coding byte offsets from a simulation or one account instance. In Rust,
use the authoritative `SwitchboardQuote` account type and its `feeds_slice()`
accessor; each `PackedFeedInfo` exposes `feed_id`, `feed_value`, `value()`, and
`min_oracle_samples`.

In JavaScript, `OracleQuote.decode(...)` parses the Ed25519 quote instruction
payload used by managed updates. It is not a stable raw account decoder for
stored quote-program account data. Until a JS account decoder is provided, use
the Rust/on-chain quote types for stored account parsing.

## Legacy PullFeed Accounts

`PullFeed.fetchUpdateIx()` and `PullFeed.fetchUpdateManyIx()` are compatibility
APIs for classic PullFeed accounts. They submit through the classic PullFeed
program path, including `pullFeedSubmitResponseConsensus`, and use the
backward-compatible secp256k1 signature flow by default.

Use these methods only when you are maintaining an existing classic PullFeed
integration and the target queue/gateway environment explicitly supports that
path. New Solana/SVM custom-feed and feed-hash integrations should use
`Queue.fetchManagedUpdateIxs(...)` and canonical `OracleQuote` accounts instead.

---
_Source: https://npm.io/package/@switchboard-xyz/on-demand · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
