Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(price): back SOL pricing with RedStone and Switchboard oracle rungs

nirholasf38bf3ba6365
diff --git a/api/_lib/redstone.js b/api/_lib/redstone.js
new file mode 100644
index 000000000..04f2c9bd5
--- /dev/null
+++ b/api/_lib/redstone.js
@@ -0,0 +1,67 @@
+// @ts-check
+// RedStone oracle: keyless public REST read of the redstone provider's signed
+// price stream (api.redstone.finance). One more independent methodology for
+// the price failover chains: RedStone aggregates ~20 exchange sources into a
+// signed data point, so it keeps answering through a CoinGecko rate-limit or a
+// single-exchange API outage.
+//
+// Endpoint (verified live 2026-08-05):
+// GET https://api.redstone.finance/prices?symbol=SOL&provider=redstone&limit=1
+// -> [{ symbol: "SOL", value: 73.955, timestamp: 1785974160000, source: {...}, ... }]
+// No key, no auth header, sub-second latency. The same endpoint serves any
+// listed ticker symbol, which is what makes this a general token rung and not
+// a SOL-only one.
+//
+// A stuck oracle is worse than a missing one: a `timestamp` older than
+// MAX_AGE_MS makes the row a MISS (null), so the failover chain moves on to a
+// live source instead of valuing anything with a stale print.
+
+const REDSTONE_BASE = 'https://api.redstone.finance';
+
+// RedStone publishes new data points continuously (the live feed updates on a
+// seconds cadence); ten minutes of silence means the stream is stuck, not slow.
+const MAX_AGE_MS = 10 * 60_000;
+
+/**
+ * Extract a positive, fresh USD price for `symbol` from a RedStone /prices
+ * payload. Returns null (a failover MISS, not an error) on an empty array, a
+ * row for a different symbol, a non-positive value, or a stale timestamp.
+ *
+ * @param {unknown} rows parsed JSON body of /prices?symbol=...&limit=1
+ * @param {string} symbol requested ticker, e.g. "SOL"
+ * @param {number} [now] epoch ms, injectable for tests
+ * @param {number} [maxAgeMs]
+ * @returns {number | null}
+ */
+export function parseRedstonePrice(rows, symbol, now = Date.now(), maxAgeMs = MAX_AGE_MS) {
+ if (!Array.isArray(rows)) return null;
+ const want = String(symbol || '').toUpperCase();
+ for (const row of rows) {
+ if (String(row?.symbol || '').toUpperCase() !== want) continue;
+ const value = Number(row?.value);
+ if (!Number.isFinite(value) || value <= 0) continue;
+ const ts = Number(row?.timestamp);
+ // A missing/garbled timestamp is treated as stale: freshness is the one
+ // guarantee this rung is supposed to add over a cached aggregator.
+ if (!Number.isFinite(ts) || Math.abs(now - ts) > maxAgeMs) continue;
+ return value;
+ }
+ return null;
+}
+
+/**
+ * A failover-fetch provider rung (see src/shared/failover-fetch.js) for any
+ * RedStone-listed ticker. Drop it into any `fetchFirst` chain.
+ *
+ * @param {string} symbol ticker symbol, e.g. "SOL"
+ * @param {{ name?: string }} [opts]
+ * @returns {{ name: string, url: string, parse: (r: Response) => Promise<number | null> }}
+ */
+export function redstoneProvider(symbol, { name = 'redstone' } = {}) {
+ const sym = String(symbol || '').toUpperCase();
+ return {
+ name,
+ url: `${REDSTONE_BASE}/prices?symbol=${encodeURIComponent(sym)}&provider=redstone&limit=1`,
+ parse: async (r) => parseRedstonePrice(await r.json(), sym),
+ };
+}
diff --git a/api/_lib/sol-price.js b/api/_lib/sol-price.js
index 5d0b25a80..3464fa42c 100644
--- a/api/_lib/sol-price.js
+++ b/api/_lib/sol-price.js
@@ -7,14 +7,16 @@
// one shared implementation — see api/_lib/pump-alert-runner.js / pump-launch-feed.js
// for the older inline copies this consolidates.
//
-// Seven independent free sources, tried in order (failover-fetch cools a failing
+// Nine independent free sources, tried in order (failover-fetch cools a failing
// source for 60s so a CoinGecko rate-limit doesn't tax every valuation with a
// timeout). They all quote the same asset; any disagreement is sub-1% noise.
// Exchange tickers (Kraken/Coinbase/Bitfinex), aggregators (CoinGecko/Jupiter/
-// DefiLlama) and an on-chain oracle (DIA) fail independently, so it takes a
-// near-total outage to exhaust the chain.
+// DefiLlama) and oracle networks (DIA, RedStone, Switchboard) fail
+// independently, so it takes a near-total outage to exhaust the chain.
import { fetchFirst } from '../../src/shared/failover-fetch.js';
+import { redstoneProvider } from './redstone.js';
+import { SWITCHBOARD_SOL_USD_FEED, switchboardProvider } from './switchboard.js';
const TTL_MS = 60_000;
// A 24h delta moves slowly; refreshing it every 60s alongside the spot price
@@ -44,7 +46,9 @@ const setChange = (v, now = Date.now()) => {
return n;
};
-const PROVIDERS = [
+// Exported so tests can verify the chain's ordering and each rung's parser
+// against captured payloads without any live network.
+export const PROVIDERS = [
{
name: 'coingecko',
url: 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_24hr_change=true',
@@ -89,6 +93,15 @@ const PROVIDERS = [
url: 'https://api.diadata.org/v1/assetQuotation/Solana/0x0000000000000000000000000000000000000000',
parse: async (r) => asPrice((await r.json())?.Price),
},
+ // RedStone oracle (api/_lib/redstone.js): keyless signed price stream that
+ // aggregates ~20 exchanges, with a freshness gate so a stuck print is a
+ // miss, never a valuation. Grouped with DIA in the oracle band of the
+ // chain: after the primary aggregators and tickers, before the last rung.
+ redstoneProvider('SOL'),
+ // Switchboard On-Demand via Crossbar (api/_lib/switchboard.js): the oracle
+ // network computes the feed live on request, so this survives outages of
+ // every REST price API above it.
+ switchboardProvider(SWITCHBOARD_SOL_USD_FEED),
{
// Bitfinex public ticker. Bitfinex (unlike Binance) does NOT geo-block US
// datacenter IPs, so it works from Cloud Run us-central1. Ticker array:
diff --git a/api/_lib/switchboard.js b/api/_lib/switchboard.js
new file mode 100644
index 000000000..5ee700d1f
--- /dev/null
+++ b/api/_lib/switchboard.js
@@ -0,0 +1,75 @@
+// @ts-check
+// Switchboard oracle via Crossbar: keyless REST simulation of a Switchboard
+// On-Demand feed. Crossbar asks the live oracle network to run the feed's job
+// definition right now and returns the computed value, so this is a fresh
+// multi-exchange read with a methodology fully independent of every other rung
+// in the price chains, and it needs no key, no wallet, and no on-chain
+// tooling.
+//
+// Endpoint (verified live 2026-08-05):
+// GET https://crossbar.switchboard.xyz/v2/simulate/{feedHash}
+// -> { feeds: [{ feedHash: "0x...", feedName: "Surge Stream SOL/USD, WEIGHTED",
+// results: ["74.02000000"], network: "mainnet" }], totalFeeds: 1, ... }
+// The legacy path (GET /simulate/{feedHash} -> [{ feedHash, results }]) serves
+// the same data as a bare array; the parser accepts both shapes so a Crossbar
+// rollback never blanks the rung. Feed hashes are the canonical 32-byte ids
+// from docs.switchboard.xyz (the hash of the feed's job definition), NOT
+// Solana account pubkeys.
+
+const CROSSBAR_BASE = 'https://crossbar.switchboard.xyz';
+
+// Canonical Switchboard SOL/USD feed (docs.switchboard.xyz, "Surge Stream
+// SOL/USD, WEIGHTED"). Verified live against the endpoint above.
+export const SWITCHBOARD_SOL_USD_FEED = '0x822512ee9add93518eca1c105a38422841a76c590db079eebb283deb2c14caa9';
+
+/** Lowercased hex without the 0x prefix, so both id spellings compare equal. */
+const normalizeHash = (h) => String(h || '').toLowerCase().replace(/^0x/, '');
+
+/**
+ * Extract the simulated value for `feedHash` from a Crossbar simulation
+ * payload (v2 `{ feeds: [...] }` object or legacy bare array). A feed can
+ * carry several oracle results; the median is taken so one outlier sample
+ * cannot skew the price. Returns null (a failover MISS) when the feed is
+ * absent or produced no positive finite result.
+ *
+ * @param {unknown} payload parsed JSON body of /v2/simulate/{feedHash}
+ * @param {string} feedHash the feed id that was requested
+ * @returns {number | null}
+ */
+export function parseCrossbarSimulation(payload, feedHash) {
+ const want = normalizeHash(feedHash);
+ if (!want) return null;
+ const feeds = Array.isArray(/** @type {any} */ (payload)?.feeds)
+ ? /** @type {any} */ (payload).feeds
+ : Array.isArray(payload)
+ ? payload
+ : [];
+ for (const feed of feeds) {
+ if (normalizeHash(feed?.feedHash) !== want) continue;
+ const nums = (Array.isArray(feed?.results) ? feed.results : [])
+ .map(Number)
+ .filter((n) => Number.isFinite(n) && n > 0)
+ .sort((a, b) => a - b);
+ if (!nums.length) return null;
+ const mid = Math.floor(nums.length / 2);
+ return nums.length % 2 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
+ }
+ return null;
+}
+
+/**
+ * A failover-fetch provider rung (see src/shared/failover-fetch.js) for any
+ * Switchboard feed hash. Drop it into any `fetchFirst` chain.
+ *
+ * @param {string} feedHash canonical feed id, with or without the 0x prefix
+ * @param {{ name?: string }} [opts]
+ * @returns {{ name: string, url: string, parse: (r: Response) => Promise<number | null> }}
+ */
+export function switchboardProvider(feedHash, { name = 'switchboard' } = {}) {
+ const hash = normalizeHash(feedHash);
+ return {
+ name,
+ url: `${CROSSBAR_BASE}/v2/simulate/0x${hash}`,
+ parse: async (r) => parseCrossbarSimulation(await r.json(), hash),
+ };
+}
diff --git a/tests/api/sol-price-oracle-rungs.test.js b/tests/api/sol-price-oracle-rungs.test.js
new file mode 100644
index 000000000..dd8f6d192
--- /dev/null
+++ b/tests/api/sol-price-oracle-rungs.test.js
@@ -0,0 +1,229 @@
+// Tests for the two keyless oracle rungs in the SOL price failover chain:
+// RedStone (api/_lib/redstone.js) and Switchboard-via-Crossbar
+// (api/_lib/switchboard.js), plus their wiring into api/_lib/sol-price.js.
+//
+// No live network here. The parsers are pure functions, so they are exercised
+// against fixtures captured from the REAL endpoints on 2026-08-05:
+// https://api.redstone.finance/prices?symbol=SOL&provider=redstone&limit=1
+// https://crossbar.switchboard.xyz/v2/simulate/0x8225...caa9
+// plus malformed and stale payloads, and the chain test asserts the rungs sit
+// in the oracle band of PROVIDERS (after DIA, before the final Bitfinex rung).
+
+import { describe, it, expect } from 'vitest';
+import { parseRedstonePrice, redstoneProvider } from '../../api/_lib/redstone.js';
+import {
+ parseCrossbarSimulation,
+ switchboardProvider,
+ SWITCHBOARD_SOL_USD_FEED,
+} from '../../api/_lib/switchboard.js';
+import { PROVIDERS } from '../../api/_lib/sol-price.js';
+
+// ── Fixtures: trimmed but real-shaped captures ───────────────────────────────
+
+// api.redstone.finance/prices?symbol=SOL&provider=redstone&limit=1 (2026-08-05).
+// `source` trimmed to three of the ~20 real exchange keys.
+const REDSTONE_TS = 1785974310000;
+const redstoneRow = (over = {}) => ({
+ id: '40511043-4567-47cf-b56b-dfcc6d0ebd01',
+ symbol: 'SOL',
+ provider: 'I-5rWUehEv-MjdK9gFw09RxfSLQX9DIHxG614Wf8qo0',
+ value: 73.9544894,
+ source: { 'kraken-usd': 73.98, 'coinbase-usd': 73.96, 'bitstamp-usd': 73.963 },
+ timestamp: REDSTONE_TS,
+ minutes: 58,
+ ...over,
+});
+
+// crossbar.switchboard.xyz/v2/simulate/{feedHash} (2026-08-05).
+const CROSSBAR_V2 = {
+ feeds: [
+ {
+ feedHash: SWITCHBOARD_SOL_USD_FEED,
+ feedName: 'Surge Stream SOL/USD, WEIGHTED',
+ results: ['74.02000000'],
+ receipts: null,
+ network: 'mainnet',
+ },
+ ],
+ totalFeeds: 1,
+ successfulFeeds: 1,
+ failedFeeds: 0,
+};
+
+// Legacy bare-array shape from GET /simulate/{feedHash}, same capture date.
+const CROSSBAR_LEGACY = [
+ { feedHash: SWITCHBOARD_SOL_USD_FEED, results: ['74.03000000'], receipts: null },
+];
+
+/** Minimal Response stand-in: parse() only calls r.json(). */
+const asResponse = (body) => /** @type {Response} */ ({ json: async () => body });
+
+// ── RedStone ─────────────────────────────────────────────────────────────────
+
+describe('parseRedstonePrice', () => {
+ // "now" 90 seconds after the captured data point: comfortably fresh.
+ const NOW = REDSTONE_TS + 90_000;
+
+ it('extracts the value from a real capture', () => {
+ expect(parseRedstonePrice([redstoneRow()], 'SOL', NOW)).toBe(73.9544894);
+ });
+
+ it('matches the symbol case-insensitively', () => {
+ expect(parseRedstonePrice([redstoneRow()], 'sol', NOW)).toBe(73.9544894);
+ });
+
+ it('rejects a stale data point (stuck oracle is a miss, not a price)', () => {
+ expect(parseRedstonePrice([redstoneRow()], 'SOL', REDSTONE_TS + 11 * 60_000)).toBeNull();
+ });
+
+ it('rejects a row missing its timestamp', () => {
+ expect(parseRedstonePrice([redstoneRow({ timestamp: undefined })], 'SOL', NOW)).toBeNull();
+ });
+
+ it('rejects a row for a different symbol', () => {
+ expect(parseRedstonePrice([redstoneRow({ symbol: 'BONK' })], 'SOL', NOW)).toBeNull();
+ });
+
+ it('rejects non-positive and non-numeric values', () => {
+ expect(parseRedstonePrice([redstoneRow({ value: 0 })], 'SOL', NOW)).toBeNull();
+ expect(parseRedstonePrice([redstoneRow({ value: -1 })], 'SOL', NOW)).toBeNull();
+ expect(parseRedstonePrice([redstoneRow({ value: 'oops' })], 'SOL', NOW)).toBeNull();
+ });
+
+ it('returns null on an empty array (unknown symbol upstream)', () => {
+ expect(parseRedstonePrice([], 'SOL', NOW)).toBeNull();
+ });
+
+ it('returns null on a non-array body', () => {
+ expect(parseRedstonePrice({ error: 'nope' }, 'SOL', NOW)).toBeNull();
+ expect(parseRedstonePrice(null, 'SOL', NOW)).toBeNull();
+ });
+});
+
+describe('redstoneProvider', () => {
+ it('builds the keyless single-symbol URL', () => {
+ expect(redstoneProvider('SOL').url).toBe(
+ 'https://api.redstone.finance/prices?symbol=SOL&provider=redstone&limit=1',
+ );
+ });
+
+ it('uppercases the symbol in both URL and match', async () => {
+ const p = redstoneProvider('sol');
+ expect(p.url).toContain('symbol=SOL');
+ const fresh = redstoneRow({ timestamp: Date.now() - 30_000 });
+ await expect(p.parse(asResponse([fresh]))).resolves.toBe(73.9544894);
+ });
+
+ it('parses a fresh live-shaped body and misses on a stale one', async () => {
+ const p = redstoneProvider('SOL');
+ await expect(p.parse(asResponse([redstoneRow({ timestamp: Date.now() - 5_000 })]))).resolves.toBe(
+ 73.9544894,
+ );
+ const stale = redstoneRow({ timestamp: Date.now() - 11 * 60_000 });
+ await expect(p.parse(asResponse([stale]))).resolves.toBeNull();
+ });
+});
+
+// ── Switchboard / Crossbar ───────────────────────────────────────────────────
+
+describe('parseCrossbarSimulation', () => {
+ it('extracts the value from the v2 object shape', () => {
+ expect(parseCrossbarSimulation(CROSSBAR_V2, SWITCHBOARD_SOL_USD_FEED)).toBe(74.02);
+ });
+
+ it('extracts the value from the legacy bare-array shape', () => {
+ expect(parseCrossbarSimulation(CROSSBAR_LEGACY, SWITCHBOARD_SOL_USD_FEED)).toBe(74.03);
+ });
+
+ it('treats the 0x prefix as optional on both sides', () => {
+ const bare = SWITCHBOARD_SOL_USD_FEED.slice(2);
+ expect(parseCrossbarSimulation(CROSSBAR_V2, bare)).toBe(74.02);
+ const payload = { feeds: [{ ...CROSSBAR_V2.feeds[0], feedHash: bare }] };
+ expect(parseCrossbarSimulation(payload, SWITCHBOARD_SOL_USD_FEED)).toBe(74.02);
+ });
+
+ it('takes the median when a feed carries several oracle samples', () => {
+ const feed = { feedHash: SWITCHBOARD_SOL_USD_FEED, results: ['74.05', '74.01', '74.03'] };
+ expect(parseCrossbarSimulation({ feeds: [feed] }, SWITCHBOARD_SOL_USD_FEED)).toBe(74.03);
+ const even = { feedHash: SWITCHBOARD_SOL_USD_FEED, results: ['74.00', '74.02'] };
+ expect(parseCrossbarSimulation({ feeds: [even] }, SWITCHBOARD_SOL_USD_FEED)).toBeCloseTo(74.01, 10);
+ });
+
+ it('ignores non-positive and non-numeric samples', () => {
+ const feed = { feedHash: SWITCHBOARD_SOL_USD_FEED, results: ['0', '-1', 'NaN', '74.02'] };
+ expect(parseCrossbarSimulation({ feeds: [feed] }, SWITCHBOARD_SOL_USD_FEED)).toBe(74.02);
+ });
+
+ it('misses on a dead feed (the real empty-results shape Crossbar returns)', () => {
+ const dead = [{ feedHash: '0x', results: [], result: '0', stdev: '0', variance: '0' }];
+ expect(parseCrossbarSimulation(dead, SWITCHBOARD_SOL_USD_FEED)).toBeNull();
+ });
+
+ it('misses when the requested feed is absent or results are empty', () => {
+ expect(parseCrossbarSimulation({ feeds: [] }, SWITCHBOARD_SOL_USD_FEED)).toBeNull();
+ const empty = { feeds: [{ feedHash: SWITCHBOARD_SOL_USD_FEED, results: [] }] };
+ expect(parseCrossbarSimulation(empty, SWITCHBOARD_SOL_USD_FEED)).toBeNull();
+ });
+
+ it('returns null on garbage payloads', () => {
+ expect(parseCrossbarSimulation(null, SWITCHBOARD_SOL_USD_FEED)).toBeNull();
+ expect(parseCrossbarSimulation('nope', SWITCHBOARD_SOL_USD_FEED)).toBeNull();
+ expect(parseCrossbarSimulation({}, SWITCHBOARD_SOL_USD_FEED)).toBeNull();
+ });
+});
+
+describe('switchboardProvider', () => {
+ it('builds the /v2/simulate URL with a normalized 0x hash', () => {
+ const expected = `https://crossbar.switchboard.xyz/v2/simulate/${SWITCHBOARD_SOL_USD_FEED}`;
+ expect(switchboardProvider(SWITCHBOARD_SOL_USD_FEED).url).toBe(expected);
+ expect(switchboardProvider(SWITCHBOARD_SOL_USD_FEED.slice(2)).url).toBe(expected);
+ });
+
+ it('parses a live-shaped v2 body', async () => {
+ const p = switchboardProvider(SWITCHBOARD_SOL_USD_FEED);
+ await expect(p.parse(asResponse(CROSSBAR_V2))).resolves.toBe(74.02);
+ });
+});
+
+// ── Chain wiring in sol-price.js ─────────────────────────────────────────────
+
+describe('sol-price provider chain', () => {
+ const names = PROVIDERS.map((p) => p.name);
+
+ it('includes both oracle rungs exactly once', () => {
+ expect(names.filter((n) => n === 'redstone')).toHaveLength(1);
+ expect(names.filter((n) => n === 'switchboard')).toHaveLength(1);
+ });
+
+ it('places them in the oracle band: after DIA, before the final rung', () => {
+ const dia = names.indexOf('dia');
+ const redstone = names.indexOf('redstone');
+ const switchboard = names.indexOf('switchboard');
+ expect(dia).toBeGreaterThanOrEqual(0);
+ expect(redstone).toBeGreaterThan(dia);
+ expect(switchboard).toBeGreaterThan(redstone);
+ expect(Math.max(redstone, switchboard)).toBeLessThan(names.length - 1);
+ });
+
+ it('keeps CoinGecko first (it alone carries the 24h change for free)', () => {
+ expect(names[0]).toBe('coingecko');
+ });
+
+ it('gives every rung the fields failover-fetch requires', () => {
+ for (const p of PROVIDERS) {
+ expect(typeof p.name).toBe('string');
+ expect(p.url).toMatch(/^https:\/\//);
+ expect(typeof p.parse).toBe('function');
+ }
+ });
+
+ it('points the oracle rungs at the verified keyless endpoints', () => {
+ const byName = Object.fromEntries(PROVIDERS.map((p) => [p.name, p.url]));
+ expect(byName.redstone).toBe(
+ 'https://api.redstone.finance/prices?symbol=SOL&provider=redstone&limit=1',
+ );
+ expect(byName.switchboard).toBe(
+ `https://crossbar.switchboard.xyz/v2/simulate/${SWITCHBOARD_SOL_USD_FEED}`,
+ );
+ });
+});