From d7e3bdf33762c0898f54f7ce97748dd5dbab99c2 Mon Sep 17 00:00:00 2001 From: Monkmansteve Date: Sun, 13 Oct 2024 15:50:47 +0300 Subject: [PATCH] add fallback logic --- src/api/prices/getPythPrices.ts | 21 +++++++++++++++++++-- src/constants/pyth.ts | 1 + 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/api/prices/getPythPrices.ts b/src/api/prices/getPythPrices.ts index 820ea6e5e..5fe168906 100644 --- a/src/api/prices/getPythPrices.ts +++ b/src/api/prices/getPythPrices.ts @@ -8,11 +8,28 @@ import { BN } from 'utils/helpers' export default async function fetchPythPrices(priceFeedIds: string[], assets: Asset[]) { const pricesUrl = new URL(`${pythEndpoints.api}/latest_price_feeds`) + const fallbackUrl = new URL(`${pythEndpoints.fallbackApi}/latest_price_feeds`) + try { - priceFeedIds.forEach((id) => pricesUrl.searchParams.append('ids[]', id)) + priceFeedIds.forEach((id) => { + pricesUrl.searchParams.append('ids[]', id) + fallbackUrl.searchParams.append('ids[]', id) + }) const pythResponse: PythPriceData[] = await cacheFn( - () => fetchWithTimeout(pricesUrl.toString(), FETCH_TIMEOUT).then((res) => res.json()), + async () => { + try { + return await fetchWithTimeout(pricesUrl.toString(), FETCH_TIMEOUT).then((res) => + res.json(), + ) + } catch (error) { + console.warn('Primary Pyth API failed, falling back to fallback API', error) + + return await fetchWithTimeout(fallbackUrl.toString(), FETCH_TIMEOUT).then((res) => + res.json(), + ) + } + }, pythPriceCache, `pythPrices/${priceFeedIds.flat().join('-')}`, 30, diff --git a/src/constants/pyth.ts b/src/constants/pyth.ts index 3887c8d7c..348eafaf5 100644 --- a/src/constants/pyth.ts +++ b/src/constants/pyth.ts @@ -1,4 +1,5 @@ export const pythEndpoints = { api: process.env.NEXT_PUBLIC_PYTH_API ?? 'https://hermes.pyth.network/api', + fallbackApi: 'https://hermes.pyth.network/api', candles: 'https://benchmarks.pyth.network/v1/shims/tradingview', }