Surge Tutorial
Example Code: The complete working example for this tutorial is available at sb-on-demand-examples/solana/surge
This tutorial walks you through implementing Switchboard Surge for real-time price streaming on Solana.
Prerequisites
Node.js 18+
Solana keypair with an active Surge subscription (subscribe here)
Basic TypeScript knowledge
Installation
npm install @switchboard-xyz/on-demand
# or
yarn add @switchboard-xyz/on-demandBasic 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
Explore code examples
Learn about Crossbar gateway
Join our Discord for support
Last updated