Surge Tutorial

Example Code: The complete working example for this tutorial is available at sb-on-demand-examples/solana/surgearrow-up-right

This tutorial walks you through implementing Switchboard Surge for real-time price streaming on Solana.

Prerequisites

Installation

npm install @switchboard-xyz/on-demand
# or
yarn add @switchboard-xyz/on-demand

Basic Implementation

Connect to Surge and stream real-time prices:

import * as sb from "@switchboard-xyz/on-demand";

// Load environment (keypair, connection, queue, etc.)
const { keypair, connection, queue } = await sb.AnchorUtils.loadEnv();

// Initialize Surge client with keypair and connection
const surge = new sb.Surge({ connection, keypair });

// Discover available feeds
const availableFeeds = await surge.getSurgeFeeds();
console.log(`Found ${availableFeeds.length} available feeds`);

// Subscribe to price feeds
await surge.connectAndSubscribe([
  { symbol: 'BTC/USD' },
  { symbol: 'SOL/USD' },
]);

// Handle real-time updates
surge.on('signedPriceUpdate', async (response: sb.SurgeUpdate) => {
  const metrics = response.getLatencyMetrics();

  // Skip heartbeat messages
  if (metrics.isHeartbeat) return;

  const prices = response.getFormattedPrices();

  metrics.perFeedMetrics.forEach((feed) => {
    console.log(`${feed.symbol}: ${prices[feed.feed_hash]}`);
    console.log(`  Source → Oracle: ${feed.sourceToOracleMs}ms`);
    console.log(`  Emit Latency: ${feed.emitLatencyMs}ms`);
  });
});

Converting to Oracle Quotes

When you need to use Surge prices on-chain, convert them to Oracle Quotes:

Streaming to Frontend with Crossbar

Crossbar is Switchboard's local gateway service for streaming prices to frontend applications.

Setting Up Crossbar

React Integration

Use Case Examples

Perpetual Exchange

Arbitrage Bot

Error Handling

Next Steps

Last updated