Queue account management for Switchboard On-Demand

The Queue class is the primary interface for interacting with oracle operators in the Switchboard network. It manages:

  • Oracle operator authorization and verification
  • Quote fetching and signature verification
  • Address lookup table management
  • Gateway interactions for data retrieval
  • Oracle Management: Track and verify authorized oracle signers
  • Quote Operations: Fetch signed data quotes from oracle operators
  • LUT Optimization: Automatic address lookup table management
  • Network Detection: Automatic mainnet/devnet queue selection
import * as sb from '@switchboard-xyz/on-demand';

// Initialize program and connection
const program = anchor.workspace.SwitchboardOnDemand;
const connection = new Connection("https://api.devnet.solana.com");

// Load the default queue for your network
const queue = await Queue.loadDefault(program);

// Set up gateway and crossbar
const crossbar = sb.CrossbarClient.default();
const gateway = await queue.fetchGatewayFromCrossbar(crossbar);

// Fetch a quote for specific feeds (BTC/USD and ETH/USD)
const feedHashes = [
'0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f', // BTC/USD
'0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' // ETH/USD
];

const sigVerifyIx = await queue.fetchQuoteIx(
gateway,
crossbar,
feedHashes,
{
numSignatures: 3, // Require 3 oracle signatures for consensus
variableOverrides: {},
instructionIdx: 0
}
);

// Build and send transaction
const tx = await sb.asV0Tx({
connection,
ixs: [sigVerifyIx, yourBusinessLogicIx],
signers: [payer],
computeUnitPrice: 200_000,
computeUnitLimitMultiple: 1.3,
});

await connection.sendTransaction(tx, {
preflightCommitment: "processed",
});

Queue

Constructors

Methods

  • Loads the default queue for the current network

    Automatically detects whether you're on mainnet or devnet and loads the appropriate default queue. This is the recommended way to get started with Switchboard On-Demand.

    Parameters

    • program: Program

      Anchor program instance

    Returns Promise<Queue>

    The default queue for your network

    const queue = await Queue.loadDefault(program);
    console.log('Using queue:', queue.pubkey.toBase58());
  • Fetches a gateway with the latest/majority version from Crossbar

    Parameters

    • crossbar: CrossbarClient

      CrossbarClient instance

    Returns Promise<Gateway>

    Promise - Gateway instance with the latest version

  • Fetches an oracle with the latest/majority version from the queue

    This method queries all oracles on the queue, checks their health status, and selects one running the most common (majority) version. This ensures compatibility and consensus across oracle operators.

    The health checks are performed in parallel for optimal performance.

    Returns Promise<Oracle>

    Oracle instance running the majority version

    If no oracles are found on the queue

    If no oracles respond to health checks

    If no oracles are running the majority version

    const queue = new Queue(program, queuePubkey);
    const oracle = await queue.fetchOracleByLatestVersion();
    console.log('Selected oracle:', oracle.pubkey.toBase58());
  • Creates a new queue account

    Parameters

    • program: Program

      Anchor program instance

    • params: {
          allowAuthorityOverrideAfter?: number;
          requireAuthorityHeartbeatPermission?: boolean;
          requireUsagePermission?: boolean;
          maxQuoteVerificationAge?: number;
          reward?: number;
          nodeTimeout?: number;
          lutSlot?: number;
      }

      Queue configuration parameters

    Returns Promise<[Queue, Keypair, TransactionInstruction]>

    Tuple of [Queue instance, keypair, creation instruction]

  • Creates a new instance of the Queue account with a PDA for SVM (non-solana) chains.

    Parameters

    • program: Program

      The anchor program instance.

    • params: {
          sourceQueueKey: PublicKey;
          allowAuthorityOverrideAfter?: number;
          requireAuthorityHeartbeatPermission?: boolean;
          requireUsagePermission?: boolean;
          maxQuoteVerificationAge?: number;
          reward?: number;
          nodeTimeout?: number;
          lutSlot?: number;
      }

      The initialization parameters for the queue.

    Returns Promise<[Queue, TransactionInstruction]>

  • Add an Oracle to a queue and set permissions

    Parameters

    • params: {
          oracle: PublicKey;
          secp256k1Signer: Buffer;
          maxQuoteVerificationAge: number;
          mrEnclave: Buffer;
          slot: number;
      }

    Returns Promise<TransactionInstruction>

  • Static method to fetch oracle signatures using the consensus mechanism

    This convenience method creates a Queue instance and fetches signed oracle responses for multiple feed configurations. Gateway is automatically fetched from CrossbarClient.

    Parameters

    • program: Program

      Anchor program instance

    • params: {
          crossbarClient?: CrossbarClient;
          queue: PublicKey;
          feedConfigs: FeedRequest[];
          useTimestamp?: boolean;
          numSignatures?: number;
          useEd25519?: boolean;
          variableOverrides?: Record<string, string>;
      }
      • OptionalcrossbarClient?: CrossbarClient

        Optional CrossbarClient instance (defaults to CrossbarClient.default())

      • queue: PublicKey

        Public key of the queue account

      • feedConfigs: FeedRequest[]

        Array of feed configurations to fetch signatures for

      • OptionaluseTimestamp?: boolean

        Whether to use timestamp in the signature

      • OptionalnumSignatures?: number

        Number of oracle signatures to fetch

      • OptionaluseEd25519?: boolean

        Whether to use Ed25519 signatures (default: false for Secp256k1)

      • OptionalvariableOverrides?: Record<string, string>

        Optional variable overrides for job execution

    Returns Promise<FetchSignaturesConsensusResponse>

    A promise that resolves to the consensus response with oracle signatures

    If the request fails or no signatures are available

  • Manually set the network for this queue

    This method allows you to explicitly set the network type, which will be used by methods that need network-specific configuration (e.g., crossbar gateway selection).

    Parameters

    • network: CrossbarNetwork

      The network to use (SolanaMainnet or SolanaDevnet)

    Returns void

    const queue = new Queue(program, queuePubkey);
    queue.setNetwork(CrossbarNetwork.SolanaMainnet);
  • Loads the queue data from on chain and returns the listed oracle keys.

    Returns Promise<PublicKey[]>

    A promise that resolves to an array of oracle public keys.

  • Fetches oracle signatures using the consensus mechanism

    This method retrieves signed oracle responses for multiple feed configurations using the consensus endpoint. Gateway is automatically fetched from CrossbarClient.

    Parameters

    • params: {
          crossbarClient?: CrossbarClient;
          feedConfigs: FeedRequest[];
          useTimestamp?: boolean;
          numSignatures?: number;
          useEd25519?: boolean;
          variableOverrides?: Record<string, string>;
      }
      • OptionalcrossbarClient?: CrossbarClient

        Optional CrossbarClient instance (defaults to CrossbarClient.default())

      • feedConfigs: FeedRequest[]

        Array of feed configurations to fetch signatures for

      • OptionaluseTimestamp?: boolean

        Whether to use timestamp in the signature

      • OptionalnumSignatures?: number

        Number of oracle signatures to fetch

      • OptionaluseEd25519?: boolean

        Whether to use Ed25519 signatures (default: false for Secp256k1)

      • OptionalvariableOverrides?: Record<string, string>

        Optional variable overrides for job execution

    Returns Promise<FetchSignaturesConsensusResponse>

    A promise that resolves to the consensus response with oracle signatures

    If the request fails or no signatures are available

  • Adds a new MR enclave to the queue. This will allow the queue to accept signatures from the given MR enclave.

    Parameters

    • params: { mrEnclave: Uint8Array }

    Returns Promise<TransactionInstruction>

    A promise that resolves to the transaction instruction.

    if the request fails.

    if the MR enclave is already added.

    if the MR enclave is invalid.

    if the MR enclave is not a valid length.

  • Removes an MR enclave from the queue. This will prevent the queue from accepting signatures from the given MR enclave.

    Parameters

    • params: { mrEnclave: Uint8Array }

    Returns Promise<TransactionInstruction>

    A promise that resolves to the transaction instruction.

    if the request fails.

    if the MR enclave is not present.

  • Sets the queue configurations.

    Parameters

    • params: {
          authority?: PublicKey;
          reward?: number;
          nodeTimeout?: number;
          oracleFeeProportionBps?: number;
      }
      • Optionalauthority?: PublicKey

        The new authority for the queue.

      • Optionalreward?: number

        The new reward for the queue.

      • OptionalnodeTimeout?: number

        The new node timeout for the queue.

      • OptionaloracleFeeProportionBps?: number

        The oracle fee proportion in basis points (e.g., 5000 = 50%).

    Returns Promise<TransactionInstruction>

    A promise that resolves to the transaction instruction.

  • Parameters

    • params: { vault: PublicKey; enable: boolean }

    Returns Promise<TransactionInstruction>

  • Sets the oracle permission on the queue.

    Parameters

    Returns Promise<TransactionInstruction>

    A promise that resolves to the transaction instruction

  • Removes all MR enclaves from the queue.

    Returns Promise<TransactionInstruction[]>

    A promise that resolves to an array of transaction instructions.

    if the request fails.

  • Get the PDA for the queue (SVM chains that are not solana)

    Parameters

    • program: Program

      Anchor program

    • pubkey: PublicKey

      Queue pubkey

    Returns PublicKey

    Queue PDA Pubkey

  • Fetches oracle quote and creates verification instruction

    This is the primary method for fetching oracle data in the quote approach. It retrieves signed price data from oracle operators and creates the instruction to verify signatures on-chain.

    • Aggregated Data: Fetches multiple feeds in a single request
    • Consensus Verification: Requires specified number of oracle signatures
    • Ed25519 Signatures: Uses efficient signature verification on-chain
    • Cost Effective: ~90% lower costs compared to individual feed updates
    • Production Ready: Handles error cases and validation
    • Feed Format Flexibility: Accepts either feed hashes (strings) or OracleFeed objects
    • Always use multiple signatures for high-value operations
    • Validate feed hashes match your expected data sources
    • Consider oracle staking and reputation when choosing consensus levels

    Parameters

    • crossbar: CrossbarClient

      Crossbar client for data routing

    • feedHashesOrFeeds: string[] | IOracleFeed[]

      Array of feed hashes (hex strings) or array of OracleFeed objects (max 16 feeds)

    • Optionalconfigs: {
          variableOverrides?: Record<string, string>;
          numSignatures?: number;
          instructionIdx?: number;
      }

    Returns Promise<TransactionInstruction>

    Ed25519 signature verification instruction ready for transaction

    When no oracle responses are available

    When oracle index is out of bounds (>= 255)

    When too many feeds requested (> 16)

    When feed responses are missing from oracle

    2.14.0

    • fetchUpdateBundleIx - Deprecated equivalent method
    • Gateway.fetchQuote - Gateway method for raw quote data
    // Basic usage with single feed hash
    const btcFeedHash = '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f';
    const sigVerifyIx = await queue.fetchQuoteIx(
    crossbar,
    [btcFeedHash],
    {
    numSignatures: 1, // Single oracle signature
    variableOverrides: {},
    instructionIdx: 0
    }
    );

    // Using OracleFeed objects
    const btcFeed: IOracleFeed = {
    name: 'BTC/USD Price Feed',
    jobs: [btcJob1, btcJob2],
    minOracleSamples: 3,
    // ... other feed properties
    };

    const ethFeed: IOracleFeed = {
    name: 'ETH/USD Price Feed',
    jobs: [ethJob1, ethJob2],
    minOracleSamples: 3,
    };

    const feedsIx = await queue.fetchQuoteIx(
    crossbar,
    [btcFeed, ethFeed],
    {
    numSignatures: 3,
    variableOverrides: {},
    instructionIdx: 0
    }
    );

    // Multi-feed quote with higher consensus
    const feedHashes = [
    '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f', // BTC/USD
    '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', // ETH/USD
    '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890' // SOL/USD
    ];

    const multiQuoteIx = await queue.fetchQuoteIx(
    crossbar,
    feedHashes,
    {
    numSignatures: 5, // Require 5 oracle signatures for high-value operations
    variableOverrides: {},
    instructionIdx: 1 // Instruction index for multiple Ed25519 instructions
    }
    );

    // Use in your transaction with proper error handling
    try {
    const tx = await asV0Tx({
    connection,
    ixs: [sigVerifyIx, yourBusinessLogicIx],
    signers: [payer],
    computeUnitPrice: 200_000,
    computeUnitLimitMultiple: 1.3,
    });

    const txSignature = await connection.sendTransaction(tx, {
    preflightCommitment: "processed",
    });

    console.log('Transaction confirmed:', txSignature);
    } catch (error) {
    console.error('Quote fetch failed:', error);
    }
  • Creates instructions for managed oracle updates using the new quote program

    This method generates instructions to call the verified_update method in the quote program (PID: orac1eFjzWL5R3RbbdMV68K9H6TaCVVcL6LjvQQWAbz). It creates both the Ed25519 signature verification instruction and the quote program instruction that verifies and stores the oracle data.

    The oracle account is automatically derived from the feed hashes using the canonical derivation logic. Gateway is automatically fetched and cached.

    • Managed Updates: Automatically handles oracle account creation and updates
    • Verification: Uses the quote program's verified_update for secure oracle data storage
    • Ed25519 Signatures: Leverages efficient signature verification
    • Account Management: Handles oracle account initialization if needed
    • Gateway Caching: Automatically fetches and caches gateway for subsequent calls
    • Feed Format Flexibility: Accepts either feed hashes (strings) or OracleFeed objects

    Parameters

    • crossbar: CrossbarClient

      Crossbar client for data routing

    • feedHashesOrFeeds: string[] | IOracleFeed[]

      Array of feed hashes (hex strings) or array of OracleFeed objects (max 16 feeds)

    • Optionalconfigs: {
          variableOverrides?: Record<string, string>;
          numSignatures?: number;
          instructionIdx?: number;
          payer?: PublicKey;
      }

      Configuration object with optional parameters

      • OptionalvariableOverrides?: Record<string, string>

        Variable overrides for feed processing

      • OptionalnumSignatures?: number

        Number of oracle signatures required (default: 1)

      • OptionalinstructionIdx?: number

        Instruction index for Ed25519 program (default: 0)

      • Optionalpayer?: PublicKey

        Payer for oracle account creation (default: program provider payer)

    Returns Promise<TransactionInstruction[]>

    Array of instructions: [Ed25519 verification, quote program verified_update]

    When no oracle responses are available

    When oracle index is out of bounds (>= 255)

    When too many feeds requested (> 16)

    When feed responses are missing from oracle

    // Using feed hashes
    const btcFeedHash = '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f';

    // Create the instructions (oracle account is derived automatically)
    const instructions = await queue.fetchManagedUpdateIxs(
    crossbar,
    [btcFeedHash],
    {
    numSignatures: 3, // Require 3 oracle signatures for consensus
    variableOverrides: {},
    instructionIdx: 0,
    payer: myWallet.publicKey,
    programId: customQuoteProgramId // Optional: use custom program ID for oracle derivation
    }
    );

    // Using OracleFeed objects
    const btcFeed: IOracleFeed = {
    name: 'BTC/USD Price Feed',
    jobs: [btcJob1, btcJob2],
    minOracleSamples: 3,
    // ... other feed properties
    };

    const ethFeed: IOracleFeed = {
    name: 'ETH/USD Price Feed',
    jobs: [ethJob1, ethJob2],
    minOracleSamples: 3,
    };

    const instructionsFromFeeds = await queue.fetchManagedUpdateIxs(
    crossbar,
    [btcFeed, ethFeed],
    {
    numSignatures: 3,
    variableOverrides: {},
    instructionIdx: 0,
    payer: myWallet.publicKey
    }
    );

    // Build transaction with managed update instructions
    const tx = await asV0Tx({
    connection,
    ixs: [...instructions, yourBusinessLogicIx],
    signers: [payer],
    computeUnitPrice: 200_000,
    computeUnitLimitMultiple: 1.3,
    });

    await connection.sendTransaction(tx);

Properties

DEFAULT_DEVNET_KEY: PublicKey = ...
DEFAULT_MAINNET_KEY: PublicKey = ...
program: Program

The Anchor program instance.

pubkey: PublicKey

The public key of the queue account.