Gateway interface for oracle communication

The Gateway class provides the connection between your application and Switchboard oracle operators. It handles:

  • Fetching signed price data from oracles
  • Managing oracle selection and consensus
  • Batch operations for multiple feeds
  • Network latency optimization
  • Variable overrides for dynamic task customization

Gateways are geo-distributed endpoints that route requests to available oracle operators for optimal performance.

Variable overrides allow you to dynamically customize oracle task execution by providing key-value pairs that replace variables within oracle jobs. This is particularly useful for:

  • API Key Management: Override API keys for different environments
  • Dynamic Parameters: Change URLs, endpoints, or query parameters
  • A/B Testing: Switch between different data sources
  • Environment Configuration: Use different settings for dev/staging/prod
// Create gateway
const gateway = new Gateway(program, 'https://gateway.switchboard.xyz');

// Basic feed fetch with API key override
const response = await gateway.fetchSignatures({
jobs: [buildApiJob('${API_KEY}')], // Job uses ${API_KEY} variable
numSignatures: 3,
variableOverrides: {
'API_KEY': 'prod-api-key-123',
'BASE_URL': 'https://api.prod.example.com'
}
});

// Batch processing with environment-specific overrides
const batchResponse = await gateway.fetchSignaturesBatch({
feedConfigs: [{
jobs: [buildJob('${ENDPOINT}/price/${SYMBOL}')],
maxVariance: 0.5,
minResponses: 2
}],
numSignatures: 5,
variableOverrides: {
'ENDPOINT': 'https://api.staging.example.com',
'SYMBOL': 'BTCUSD',
'TIMEOUT': '30000'
}
});

// Multi-feed with shared overrides
const multiResponse = await gateway.fetchSignaturesMulti({
feedConfigs: [
{ jobs: [priceJob1], maxVariance: 1.0, minResponses: 1 },
{ jobs: [priceJob2], maxVariance: 1.5, minResponses: 2 }
],
numSignatures: 4,
variableOverrides: {
'API_VERSION': 'v2',
'RATE_LIMIT': '100'
}
});

// Consensus with authentication override
const consensusResponse = await gateway.fetchSignaturesConsensus({
feedConfigs: [{ feed: myFeedConfig }],
numSignatures: 7,
variableOverrides: {
'AUTH_TOKEN': await getAuthToken(),
'REGION': 'us-east-1'
}
});

Variables in oracle jobs use the ${VARIABLE_NAME} syntax:

const httpJob = {
tasks: [{
httpTask: {
url: '${BASE_URL}/api/${VERSION}/price?symbol=${SYMBOL}&key=${API_KEY}',
method: 'GET',
headers: {
'Authorization': 'Bearer ${AUTH_TOKEN}',
'User-Agent': '${USER_AGENT}'
}
}
}]
};
  1. Security: Never hardcode sensitive API keys in jobs - use overrides
  2. Environment Management: Use overrides to switch between dev/staging/prod
  3. Flexibility: Design jobs with variables for maximum reusability
  4. Validation: Ensure all required variables are provided in overrides
  5. Documentation: Document expected variables in your job definitions

Gateway

Constructors

  • Constructs a Gateway instance

    Parameters

    • program: Program

      The Anchor program instance

    • gatewayUrl: string

      The URL of the switchboard gateway

    • OptionaloracleKey: PublicKey

      Optional specific oracle key

    Returns Gateway

Methods

  • Initializes a Surge instance

    Parameters

    • params: { apiKey: string; verbose?: boolean }

      The parameters for the surge instance

      • apiKey: string

        The API key for authentication

      • Optionalverbose?: boolean

        Whether to enable verbose logging

    Returns Surge

    A new instance of dSurge

  • Fetches signatures from the gateway.

    REST API endpoint: /api/v1/fetch_signatures

    Parameters

    • params: {
          recentHash?: string;
          encodedJobs: string[];
          numSignatures: number;
          maxVariance: number;
          minResponses: number;
          useTimestamp?: boolean;
          variableOverrides?: Record<string, string>;
      }

    Returns Promise<{ responses: FeedEvalResponse[]; failures: string[] }>

    A promise that resolves to the feed evaluation responses.

    if the request fails.

  • Fetches signatures from the gateway. REST API endpoint: /api/v1/gateway_attest_enclave

    Parameters

    • params: {
          timestamp: number;
          quote: string;
          oracle_pubkey: string;
          oracle_reward_wallet: string;
          oracle_ed25519_enclave_signer: string;
          oracle_secp256k1_enclave_signer: string;
          recentHash: string;
      }

    Returns Promise<AttestEnclaveResponse>

    A promise that resolves to the attestation response.

    if the request fails.

  • Fetches an attestation quote from the gateway.

    REST API endpoint: /api/v1/gateway_fetch_quote

    Parameters

    • params: { blockhash: string; get_for_oracle: boolean; get_for_guardian: boolean }

    Returns Promise<FetchQuoteResponse[]>

    A promise that resolves to the quote response.

    if the request fails.

  • Fetches signatures from the gateway.

    REST API endpoint: /api/v1/fetch_signatures

    Parameters

    • params: {
          recentHash?: string;
          jobs: IOracleJob[];
          numSignatures?: number;
          maxVariance?: number;
          minResponses?: number;
          useTimestamp?: boolean;
          variableOverrides?: Record<string, string>;
      }

    Returns Promise<{ responses: FeedEvalResponse[]; failures: string[] }>

    A promise that resolves to the feed evaluation responses.

    if the request fails.

  • Fetches signatures from multiple feeds

    Parameters

    • params: {
          recentHash?: string;
          feedConfigs: FeedRequestV1[];
          numSignatures?: number;
          useTimestamp?: boolean;
          variableOverrides?: Record<string, string>;
      }

    Returns Promise<FetchSignaturesMultiResponse>

    A promise that resolves to the feed evaluation responses.

    if the request fails.

  • Parameters

    • params: {
          recentHash?: string;
          encodedConfigs: {
              encodedJobs: string[];
              maxVariance: number;
              minResponses: number;
          }[];
          numSignatures: number;
          useTimestamp?: boolean;
          variableOverrides?: Record<string, string>;
      }

    Returns Promise<FetchSignaturesMultiResponse>

  • Fetches signatures from the gateway without pre-encoded jobs REST API endpoint: /api/v1/fetch_signatures_batch

    Parameters

    • params: {
          recentHash?: string;
          feedConfigs: FeedRequestV1[];
          numSignatures?: number;
          useTimestamp?: boolean;
          useEd25519?: boolean;
          variableOverrides?: Record<string, string>;
      }

    Returns Promise<FetchSignaturesBatchResponse>

    A promise that resolves to the feed evaluation responses.

    if the request fails.

  • Fetches signatures from the gateway. REST API endpoint: /api/v1/fetch_signatures_batch

    Parameters

    • params: {
          recentHash?: string;
          encodedConfigs: {
              encodedJobs: string[];
              maxVariance: number;
              minResponses: number;
          }[];
          numSignatures: number;
          useTimestamp?: boolean;
          variableOverrides?: Record<string, string>;
      }

    Returns Promise<FetchSignaturesBatchResponse>

    A promise that resolves to the feed evaluation responses.

    if the request fails.

  • Fetches signatures using consensus mechanism REST API endpoint: /api/v1/fetch_signatures_consensus

    Parameters

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

    Returns Promise<FetchSignaturesConsensusResponse>

    A promise that resolves to the consensus response.

    if the request fails.

  • Fetches oracle quote data from the gateway

    This method retrieves signed price quotes from oracle operators through the gateway interface. It's the primary method for fetching oracle data using the modern quote terminology.

    • Uses Ed25519 signature scheme for efficient verification
    • Supports both protobuf and legacy job specifications
    • Implements consensus mechanism across multiple oracles
    • Returns structured response with oracle metadata

    The returned response contains:

    • oracle_responses: Array of signed oracle data
    • recent_hash: Recent Solana block hash for replay protection
    • slot: Recent slot number for temporal validation

    Parameters

    • crossbar: CrossbarClient

      Crossbar client for data routing and feed resolution

    • feedHashes: string[]

      Array of feed hashes to fetch (hex strings, max 16)

    • numSignatures: number = 1

      Number of oracle signatures required (default: 1, max based on queue config)

    • OptionalvariableOverrides: Record<string, string>

    Returns Promise<FetchSignaturesConsensusResponse>

    Oracle quote response with signatures

    When gateway is unreachable or returns error

    When crossbar cannot resolve feed hashes

    When insufficient oracles are available

    2.14.0

    import { CrossbarClient } from '@switchboard-xyz/common';

    // Initialize crossbar client
    const crossbar = CrossbarClient.default();

    // Single feed quote
    const btcQuote = await gateway.fetchQuote(
    crossbar,
    ['0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f'], // BTC/USD
    1 // Single signature for fast updates
    );

    // Multi-feed quote for DeFi protocol
    const defiAssets = [
    '0xef0d8b6fcd0104e3e75096912fc8e1e432893da4f18faedaacca7e5875da620f', // BTC/USD
    '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', // ETH/USD
    '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', // SOL/USD
    '0x9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba' // USDC/USD
    ];

    const portfolioQuote = await gateway.fetchQuote(
    crossbar,
    defiAssets,
    5 // Higher consensus for financial operations
    );

    // Access oracle responses
    console.log('Oracle responses:', portfolioQuote.oracle_responses.length);
    console.log('Recent slot:', portfolioQuote.slot);

    // Process individual feed responses
    portfolioQuote.oracle_responses.forEach((oracle, index) => {
    oracle.feed_responses.forEach((feed, feedIndex) => {
    console.log(`Oracle ${index}, Feed ${feedIndex}:`, {
    feedHash: feed.feed_hash,
    value: feed.success_value,
    confidence: feed.min_oracle_samples
    });
    });
    });
  • Fetches the randomness reveal from the gateway.

    Parameters

    • params:
          | {
              randomnessAccount: PublicKey;
              slothash: string;
              slot: number;
              rpc?: string;
          }
          | { randomnessId: string; timestamp: number; minStalenessSeconds: number }

      The parameters for the randomness reveal.

    Returns Promise<RandomnessRevealResponse>

    The randomness reveal response.

Properties

program: Program

The Anchor program instance

gatewayUrl: string

The URL of the switchboard gateway

oracleKey?: PublicKey

Optional specific oracle key