Skip to content

Commit 7c37319

Browse files
committed
feat(api): CoinGecko retry-on-throttle + fail-loud + 1-year cache
Hardens historical rewards pricing so wrong numbers never land in the block-keyed cache for a year. Three changes layered together: 1. Retry on CoinGecko 429 with backoff ---------------------------------- Free tier throttles ~10-30/min. New coingeckoFetch helper wraps each CoinGecko request with: • up to 5 attempts • honors Retry-After header when present • exponential backoff (2^attempt seconds, capped at 60s) otherwise Applies to both current-price (fetchLavaUsdPrice) and historical-price (fetchTokenUsdPriceAt) paths. 2. Fail loud on rate-limit exhaustion ---------------------------------- Before: fetchTokenUsdPriceAt caught all errors and returned 0 → processRewardTokens fell back to current price cache → USD figure in response was WRONG but cached as if historical → wrong for a year. Now: fetchTokenUsdPriceAt throws on transient failures (rate limit, network error) and only returns 0 for legitimate "no data" (unknown denom, 404, empty market_data). Zeros cache indefinitely (permanent facts), throws don't cache (next caller retries). buildHistoricalPriceMap makes LAVA required (virtually all reward value is LAVA), other denoms best-effort. If LAVA throws, the route returns 503 with a clear "please retry" message. Cache plugin skips 4xx/5xx so no bad response gets written to Redis. 3. 1-year cache for immutable past-block snapshots ----------------------------------------------- New CACHE_TTL.IMMUTABLE = 31_536_000. Applied to: • /provider-estimated-rewards?block=N (response fully determined by past chain state + block-time prices, both unchangeable) • /provider-estimated-rewards/blocks (monthly 17th heights permanent) • /provider-rewards?from=&to= when `to` is older than today - 1 day Kept on HISTORICAL (1 day): • /providers/:addr/avatar (Keybase avatars can change) • /burn-rate (mixes immutable blocks with a "latest" field) Tests updated: 113/113. Added a case asserting that when buildHistoricalPriceMap throws, the route returns 503 AND does not call fetchRewardsBySpec — i.e. we refuse to ship a response rather than silently shipping one with the wrong price.
1 parent 405879c commit 7c37319

5 files changed

Lines changed: 135 additions & 32 deletions

File tree

‎apps/api/src/__tests__/routes-provider-estimated-rewards.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,23 @@ describe("GET /provider-estimated-rewards", () => {
193193
}
194194
});
195195

196+
it("returns 503 when historical LAVA price is unavailable (don't cache wrong data for a year)", async () => {
197+
(fetchBlockTime as ReturnType<typeof vi.fn>).mockResolvedValue("2026-03-17T15:00:00Z");
198+
(buildHistoricalPriceMap as ReturnType<typeof vi.fn>).mockRejectedValue(
199+
new Error("CoinGecko 429 after 5 attempts"),
200+
);
201+
const app = await buildApp();
202+
const res = await app.inject({
203+
method: "GET",
204+
url: "/provider-estimated-rewards?block=4697952",
205+
});
206+
expect(res.statusCode).toBe(503);
207+
expect(JSON.parse(res.body).message).toMatch(/historical LAVA price unavailable/);
208+
// Critical: fetchRewardsBySpec must NOT have been called — we refused to
209+
// ship a response rather than silently using the current price.
210+
expect(fetchRewardsBySpec).not.toHaveBeenCalled();
211+
});
212+
196213
it("uses block-time pricing when ?block= is set (historical LAVA price)", async () => {
197214
(fetchBlockTime as ReturnType<typeof vi.fn>).mockResolvedValue("2026-03-17T15:00:00Z");
198215
(buildHistoricalPriceMap as ReturnType<typeof vi.fn>).mockResolvedValue({ lava: 0.035 });

‎apps/api/src/config.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,14 @@ export const CACHE_TTL = {
9292
SLOW_MOVING: 7200,
9393
/** Optimizer metrics — aggregated hourly scores. */
9494
OPTIMIZER: 21_600,
95-
/** Historical/immutable data (past-block snapshots, avatars). */
95+
/** Slowly-changing data that's mostly historical but could update
96+
* (e.g. avatars, burn-rate overview that mixes historical+latest). */
9697
HISTORICAL: 86_400,
98+
/** Truly immutable past-block snapshots — response is fully determined by
99+
* historical chain state + block-time CoinGecko prices, both of which
100+
* never change. Cache for a year so repeated lookups never pay the
101+
* chain-RPC + 22-denom CoinGecko cost twice. */
102+
IMMUTABLE: 31_536_000,
97103
} as const;
98104

99105
export default config;

‎apps/api/src/routes/provider-estimated-rewards.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) {
7272
},
7373
},
7474
},
75-
config: { cacheTTL: CACHE_TTL.HISTORICAL },
75+
config: { cacheTTL: CACHE_TTL.IMMUTABLE },
7676
}, async (request) => {
7777
const q = request.query as { count?: number };
7878
const count = q.count ?? DEFAULT_MONTHLY_BLOCKS;
@@ -129,8 +129,9 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) {
129129
spec = q.spec.toUpperCase();
130130
}
131131

132-
// Historical blocks are immutable, so cache aggressively.
133-
if (block) request.cacheTTL = CACHE_TTL.HISTORICAL;
132+
// A historical block's response is fully determined by past chain state
133+
// and block-time CoinGecko prices — both immutable. Cache for a year.
134+
if (block) request.cacheTTL = CACHE_TTL.IMMUTABLE;
134135

135136
await prewarmPriceCache();
136137

@@ -147,8 +148,19 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) {
147148
if (block) {
148149
const blockTimeIso = await fetchBlockTime(block);
149150
const blockDate = new Date(blockTimeIso);
150-
priceOverrides = await buildHistoricalPriceMap(blockDate);
151-
priceLavaUsd = priceOverrides.lava ?? await fetchLavaUsdPrice();
151+
// buildHistoricalPriceMap throws if the REQUIRED LAVA price can't be
152+
// fetched after retries. Let it bubble so Fastify returns 503 and the
153+
// cache layer (which skips 4xx/5xx) doesn't poison the block-keyed
154+
// response with a wrong price for a year.
155+
try {
156+
priceOverrides = await buildHistoricalPriceMap(blockDate);
157+
} catch (err) {
158+
return sendApiError(
159+
reply, 503,
160+
`historical LAVA price unavailable for block ${block} (${blockTimeIso}); please retry: ${(err as Error).message}`,
161+
);
162+
}
163+
priceLavaUsd = priceOverrides.lava!;
152164
priceTimestamp = blockTimeIso;
153165
} else {
154166
priceTimestamp = new Date().toISOString();

‎apps/api/src/routes/provider-rewards.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ export async function providerRewardsRoutes(app: FastifyInstance) {
160160
new Date().getUTCDate(),
161161
);
162162
request.cacheTTL = dateTo.getTime() <= todayUtc - ONE_DAY_MS
163-
? CACHE_TTL.HISTORICAL
163+
? CACHE_TTL.IMMUTABLE
164164
: CACHE_TTL.LIST;
165165

166166
// ── Resolve specs ─────────────────────────────────────────────

‎apps/api/src/rpc/pricing.ts‎

Lines changed: 93 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,48 @@
1+
import pino from "pino";
12
import { ulavaToLavaNumber } from "@info/shared/utils";
23
import { config } from "../config.js";
34
import { fetchRest } from "./rest.js";
45
import { fetchStakingPool } from "./supply.js";
56

7+
const logger = pino({ name: "pricing" });
8+
9+
// ── CoinGecko rate-limit-aware fetch ────────────────────────────────────────
10+
// Free-tier limit is ~10-30 calls/min. On 429, honor the Retry-After header if
11+
// present, else exponential backoff. Throws after `maxAttempts` so the caller
12+
// can distinguish "couldn't fetch" from "data says zero" — critical for
13+
// historical pricing, where a silent fallback to current price would bake a
14+
// wrong USD number into the 1-year response cache.
15+
const COINGECKO_MAX_ATTEMPTS = 5;
16+
const COINGECKO_MAX_BACKOFF_MS = 60_000;
17+
18+
async function coingeckoFetch(url: string, signal?: AbortSignal): Promise<Response> {
19+
let lastErr: unknown;
20+
for (let attempt = 1; attempt <= COINGECKO_MAX_ATTEMPTS; attempt++) {
21+
try {
22+
const res = await fetch(url, { signal: signal ?? AbortSignal.timeout(20_000) });
23+
if (res.status !== 429) return res;
24+
25+
const retryAfter = parseInt(res.headers.get("retry-after") ?? "0", 10);
26+
const backoffMs = Math.min(
27+
COINGECKO_MAX_BACKOFF_MS,
28+
retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000,
29+
);
30+
if (attempt === COINGECKO_MAX_ATTEMPTS) {
31+
throw new Error(`CoinGecko 429 after ${COINGECKO_MAX_ATTEMPTS} attempts: ${url}`);
32+
}
33+
logger.warn({ url, attempt, backoffMs }, "CoinGecko 429, backing off");
34+
await new Promise((r) => setTimeout(r, backoffMs));
35+
} catch (e) {
36+
lastErr = e;
37+
if (attempt === COINGECKO_MAX_ATTEMPTS) throw e;
38+
const backoffMs = Math.min(COINGECKO_MAX_BACKOFF_MS, 2 ** attempt * 1000);
39+
logger.warn({ url, attempt, err: String(e) }, "CoinGecko fetch error, retrying");
40+
await new Promise((r) => setTimeout(r, backoffMs));
41+
}
42+
}
43+
throw lastErr ?? new Error("coingeckoFetch: unreachable");
44+
}
45+
646
/** In-memory price cache (5 min TTL) — shared across fetchLavaUsdPrice + fetchTokenUsdPrice + prewarmPriceCache */
747
const priceCache = new Map<string, { price: number; ts: number }>();
848
const PRICE_CACHE_MS = 300_000;
@@ -17,9 +57,8 @@ export async function fetchLavaUsdPrice(): Promise<number> {
1757
if (pendingLavaPrice) return pendingLavaPrice;
1858

1959
pendingLavaPrice = (async () => {
20-
const res = await fetch(
60+
const res = await coingeckoFetch(
2161
`${config.external.coingeckoApiUrl}/simple/price?ids=lava-network&vs_currencies=usd`,
22-
{ signal: AbortSignal.timeout(15_000) },
2362
);
2463
if (!res.ok) throw new Error(`CoinGecko ${res.status}`);
2564
const data = (await res.json()) as { "lava-network"?: { usd?: number } };
@@ -121,7 +160,20 @@ function formatDateForCoingecko(date: Date): string {
121160
}
122161

123162
/** Fetch USD price for a single base denom on a specific date.
124-
* Returns 0 on miss (unknown denom / CoinGecko error / no data for date). */
163+
*
164+
* Returns 0 ONLY for legitimate "no data" cases:
165+
* - denom isn't in our CoinGecko map
166+
* - CoinGecko returns 404 (coin ID not found)
167+
* - CoinGecko returns 200 with no market_data for that date
168+
*
169+
* THROWS on transient failures (rate limit after retries, network error).
170+
* That's critical: historical rewards responses get cached for a year, so
171+
* silently falling back to "no price" or current price would bake wrong
172+
* USD numbers into the cache. Better to 503 the request and retry later.
173+
*
174+
* Zeros are cached (negative result caching) because "coin not listed" /
175+
* "no data on that date" are permanent facts. Transient errors throw and
176+
* are not cached, so the next caller retries from scratch. */
125177
export async function fetchTokenUsdPriceAt(
126178
baseDenom: string,
127179
date: Date,
@@ -137,39 +189,55 @@ export async function fetchTokenUsdPriceAt(
137189
return 0;
138190
}
139191

140-
try {
141-
const res = await fetch(
142-
`${config.external.coingeckoApiUrl}/coins/${id}/history?date=${formatDateForCoingecko(date)}&localization=false`,
143-
{ signal: AbortSignal.timeout(15_000) },
144-
);
145-
if (!res.ok) {
146-
historicalPriceCache.set(k, 0);
147-
return 0;
148-
}
149-
const data = (await res.json()) as {
150-
market_data?: { current_price?: { usd?: number } };
151-
};
152-
const price = data.market_data?.current_price?.usd ?? 0;
153-
historicalPriceCache.set(k, price);
154-
return price;
155-
} catch {
192+
const res = await coingeckoFetch(
193+
`${config.external.coingeckoApiUrl}/coins/${id}/history?date=${formatDateForCoingecko(date)}&localization=false`,
194+
);
195+
if (res.status === 404) {
196+
// Legitimately unknown coin ID — cache the zero indefinitely.
156197
historicalPriceCache.set(k, 0);
157198
return 0;
158199
}
200+
if (!res.ok) {
201+
throw new Error(`CoinGecko ${res.status} for ${baseDenom} @ ${isoDate}`);
202+
}
203+
const data = (await res.json()) as {
204+
market_data?: { current_price?: { usd?: number } };
205+
};
206+
const price = data.market_data?.current_price?.usd ?? 0;
207+
historicalPriceCache.set(k, price);
208+
return price;
159209
}
160210

161211
/** Build a `baseDenom → price` map at a given date for the denoms we know about.
162-
* Callers pass this to reward-processing functions to override the live cache. */
212+
*
213+
* Sequential because CoinGecko's free tier throttles ~10-30/min; parallelizing
214+
* 22 denoms triggers 429s that coingeckoFetch spends minutes backing off.
215+
* Results cache indefinitely so the sequential cost is paid once per block.
216+
*
217+
* LAVA is fetched first (virtually all reward value is LAVA). If the LAVA
218+
* fetch throws, we let it propagate — the caller needs to know the historical
219+
* price is unavailable and return 503 rather than silently shipping a wrong
220+
* cached response. Other denoms are best-effort: if a minor denom fails after
221+
* retries, we log and continue, and downstream callers will fall back to the
222+
* current-price cache for that denom (negligible drift). */
163223
export async function buildHistoricalPriceMap(
164224
date: Date,
165225
denoms: string[] = Object.keys(DENOM_COINGECKO_ID),
166226
): Promise<Record<string, number>> {
167-
const entries = await Promise.all(
168-
denoms.map(async (d) => [d, await fetchTokenUsdPriceAt(d, date)] as const),
169-
);
227+
const orderedDenoms = denoms.includes("lava")
228+
? ["lava", ...denoms.filter((d) => d !== "lava")]
229+
: denoms;
230+
170231
const out: Record<string, number> = {};
171-
for (const [d, p] of entries) {
172-
if (p > 0) out[d] = p;
232+
for (const d of orderedDenoms) {
233+
try {
234+
const p = await fetchTokenUsdPriceAt(d, date);
235+
if (p > 0) out[d] = p;
236+
} catch (e) {
237+
if (d === "lava") throw e; // LAVA is required; bubble up to 503
238+
logger.warn({ denom: d, date: date.toISOString(), err: String(e) },
239+
"historical price unavailable, continuing without it");
240+
}
173241
}
174242
return out;
175243
}

0 commit comments

Comments
 (0)