diff --git a/apps/api/src/__tests__/routes-provider-estimated-rewards.test.ts b/apps/api/src/__tests__/routes-provider-estimated-rewards.test.ts index 4ae018b..5ffb188 100644 --- a/apps/api/src/__tests__/routes-provider-estimated-rewards.test.ts +++ b/apps/api/src/__tests__/routes-provider-estimated-rewards.test.ts @@ -8,7 +8,9 @@ vi.mock("../rpc/lava.js", () => ({ fetchProvidersWithSpecs: vi.fn(), fetchRewardsBySpec: vi.fn(), fetchBlockAtTimestamp: vi.fn(), + fetchBlockTime: vi.fn(), fetchLavaUsdPrice: vi.fn(), + buildHistoricalPriceMap: vi.fn(), })); const { @@ -16,7 +18,9 @@ const { fetchProvidersWithSpecs, fetchRewardsBySpec, fetchBlockAtTimestamp, + fetchBlockTime, fetchLavaUsdPrice, + buildHistoricalPriceMap, } = await import("../rpc/lava.js"); const { providerEstimatedRewardsRoutes } = await import("../routes/provider-estimated-rewards.js"); @@ -88,6 +92,8 @@ beforeEach(() => { (fetchBlockAtTimestamp as ReturnType).mockImplementation( (unix: number) => Promise.resolve(1_000_000 + Math.floor(unix / 1000)), ); + (fetchBlockTime as ReturnType).mockResolvedValue("2026-03-17T15:00:00Z"); + (buildHistoricalPriceMap as ReturnType).mockResolvedValue({ lava: 0.035 }); }); describe("GET /provider-estimated-rewards", () => { @@ -187,6 +193,56 @@ describe("GET /provider-estimated-rewards", () => { } }); + it("uses block-time pricing when ?block= is set (historical LAVA price)", async () => { + (fetchBlockTime as ReturnType).mockResolvedValue("2026-03-17T15:00:00Z"); + (buildHistoricalPriceMap as ReturnType).mockResolvedValue({ lava: 0.035 }); + const app = await buildApp(); + const res = await app.inject({ + method: "GET", + url: "/provider-estimated-rewards?block=4697952", + }); + expect(res.statusCode).toBe(200); + const body = JSON.parse(res.body); + // meta.priceLavaUsd reflects historical price, meta.priceTimestamp = block time + expect(body.meta.priceLavaUsd).toBe(0.035); + expect(body.meta.priceTimestamp).toBe("2026-03-17T15:00:00Z"); + // fetchRewardsBySpec got the override map as the 4th arg + const calls = (fetchRewardsBySpec as ReturnType).mock.calls; + for (const [, , , overridesArg] of calls) { + expect(overridesArg).toEqual({ lava: 0.035 }); + } + // fetchLavaUsdPrice is NOT called when historical overrides provide a lava price + expect(fetchLavaUsdPrice).not.toHaveBeenCalled(); + }); + + it("snapshots the provider set at the historical block (not current)", async () => { + (fetchBlockTime as ReturnType).mockResolvedValue("2026-03-17T15:00:00Z"); + (buildHistoricalPriceMap as ReturnType).mockResolvedValue({ lava: 0.035 }); + const app = await buildApp(); + await app.inject({ method: "GET", url: "/provider-estimated-rewards?block=4697952" }); + // fetchProvidersWithSpecs was called with the block height so chain RPC + // returns the provider set as it existed at that block (includes providers + // who have since deregistered). + expect(fetchProvidersWithSpecs).toHaveBeenCalledWith(4697952); + }); + + it("uses live prices + current provider set when ?block= is omitted", async () => { + (fetchLavaUsdPrice as ReturnType).mockResolvedValue(0.025); + const app = await buildApp(); + const res = await app.inject({ method: "GET", url: "/provider-estimated-rewards" }); + const body = JSON.parse(res.body); + expect(body.meta.priceLavaUsd).toBe(0.025); + // Provider set fetched without a block arg (current state) + expect(fetchProvidersWithSpecs).toHaveBeenCalledWith(undefined); + // No historical price map needed + expect(buildHistoricalPriceMap).not.toHaveBeenCalled(); + // No override passed through to fetchRewardsBySpec + const calls = (fetchRewardsBySpec as ReturnType).mock.calls; + for (const [, , , overridesArg] of calls) { + expect(overridesArg).toBeUndefined(); + } + }); + it("filters response to a single spec when ?spec= is provided", async () => { const app = await buildApp(); const res = await app.inject({ diff --git a/apps/api/src/routes/provider-estimated-rewards.ts b/apps/api/src/routes/provider-estimated-rewards.ts index 89cb7f4..cc84ff2 100644 --- a/apps/api/src/routes/provider-estimated-rewards.ts +++ b/apps/api/src/routes/provider-estimated-rewards.ts @@ -2,7 +2,9 @@ import type { FastifyInstance } from "fastify"; import { CACHE_TTL } from "../config.js"; import { RPC_BATCH_SIZE, + buildHistoricalPriceMap, fetchBlockAtTimestamp, + fetchBlockTime, fetchLavaUsdPrice, fetchProvidersWithSpecs, fetchRewardsBySpec, @@ -131,13 +133,29 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) { if (block) request.cacheTTL = CACHE_TTL.HISTORICAL; await prewarmPriceCache(); - // Tokens at block N are priced with the CURRENT LAVA price (matches lava-ops - // Job 2). Surface the price + timestamp in meta so consumers know the USD - // figure is not historical and shouldn't be interpreted as price movement. - const priceTimestamp = new Date().toISOString(); - const priceLavaUsd = await fetchLavaUsdPrice(); - const { providers: providerMap, specNames } = await fetchProvidersWithSpecs(); + // When querying a historical block: + // • Build a block-time price map so USD values match the snapshot the + // block would have produced (not today's LAVA price). + // • Snapshot the provider set AT the block, not the current chain state, + // so providers who've since deregistered still appear. + // Without a block, default to live prices + current provider set. + let priceTimestamp: string; + let priceLavaUsd: number; + let priceOverrides: Record | undefined; + + if (block) { + const blockTimeIso = await fetchBlockTime(block); + const blockDate = new Date(blockTimeIso); + priceOverrides = await buildHistoricalPriceMap(blockDate); + priceLavaUsd = priceOverrides.lava ?? await fetchLavaUsdPrice(); + priceTimestamp = blockTimeIso; + } else { + priceTimestamp = new Date().toISOString(); + priceLavaUsd = await fetchLavaUsdPrice(); + } + + const { providers: providerMap, specNames } = await fetchProvidersWithSpecs(block); const addresses = Array.from(providerMap.keys()); const results: Array<{ @@ -150,7 +168,7 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) { for (let i = 0; i < addresses.length; i += RPC_BATCH_SIZE) { const batch = addresses.slice(i, i + RPC_BATCH_SIZE); const rewardResults = await Promise.all( - batch.map((addr) => fetchRewardsBySpec(addr, specNames, block)), + batch.map((addr) => fetchRewardsBySpec(addr, specNames, block, priceOverrides)), ); for (let j = 0; j < batch.length; j++) { diff --git a/apps/api/src/rpc/block.ts b/apps/api/src/rpc/block.ts index ea7c2d3..da49b8c 100644 --- a/apps/api/src/rpc/block.ts +++ b/apps/api/src/rpc/block.ts @@ -7,6 +7,20 @@ const LAVA_GENESIS_UNIX = 1_713_350_000; // ~2024-04-17 const blockAtTsCache = new Map(); const BLOCK_AT_TS_CACHE_MAX = 200; +/** Fetch the timestamp of a given block height (ISO 8601 string). + * Used for historical pricing — lets callers query CoinGecko for LAVA + * price at the block's date instead of using the current price. */ +export async function fetchBlockTime(height: number): Promise { + const res = await fetch(`${config.lava.rpcUrl}/block?height=${height}`, { + signal: AbortSignal.timeout(10_000), + }); + if (!res.ok) throw new Error(`RPC ${res.status}`); + const data = (await res.json()) as { + result: { block: { header: { time: string } } }; + }; + return data.result.block.header.time; +} + export async function fetchLatestBlockHeight(): Promise<{ height: number; time: string; diff --git a/apps/api/src/rpc/lava.ts b/apps/api/src/rpc/lava.ts index 3fa686a..44968de 100644 --- a/apps/api/src/rpc/lava.ts +++ b/apps/api/src/rpc/lava.ts @@ -4,7 +4,7 @@ // New code should import directly from the focused modules. export { RPC_BATCH_SIZE } from "./rest.js"; -export { fetchBlockAtTimestamp, fetchLatestBlockHeight } from "./block.js"; +export { fetchBlockAtTimestamp, fetchBlockTime, fetchLatestBlockHeight } from "./block.js"; export { fetchAllSpecs } from "./specs.js"; export { fetchTotalSupply, fetchCirculatingSupply } from "./supply.js"; export { @@ -20,6 +20,8 @@ export { } from "./providers.js"; export { fetchLavaUsdPrice, + fetchTokenUsdPriceAt, + buildHistoricalPriceMap, prewarmPriceCache, computeTVL, } from "./pricing.js"; diff --git a/apps/api/src/rpc/pricing.ts b/apps/api/src/rpc/pricing.ts index 1497316..9b80bf1 100644 --- a/apps/api/src/rpc/pricing.ts +++ b/apps/api/src/rpc/pricing.ts @@ -103,6 +103,77 @@ export async function prewarmPriceCache(): Promise { } } +// ── Historical pricing (CoinGecko /coins/{id}/history) ────────────────────── +// Used for rewards snapshots at historical block heights — we want the LAVA +// price as it was on that date, not the current price. Results are cached by +// (denom, date) tuple indefinitely since historical prices don't change. + +interface HistoricalPriceKey { baseDenom: string; date: string /* YYYY-MM-DD */ } +const historicalPriceCache = new Map(); +const keyStr = (k: HistoricalPriceKey) => `${k.baseDenom}@${k.date}`; + +// Format a Date to CoinGecko's expected `DD-MM-YYYY` string. +function formatDateForCoingecko(date: Date): string { + const dd = String(date.getUTCDate()).padStart(2, "0"); + const mm = String(date.getUTCMonth() + 1).padStart(2, "0"); + const yyyy = date.getUTCFullYear(); + return `${dd}-${mm}-${yyyy}`; +} + +/** Fetch USD price for a single base denom on a specific date. + * Returns 0 on miss (unknown denom / CoinGecko error / no data for date). */ +export async function fetchTokenUsdPriceAt( + baseDenom: string, + date: Date, +): Promise { + const isoDate = date.toISOString().slice(0, 10); + const k = keyStr({ baseDenom, date: isoDate }); + const cached = historicalPriceCache.get(k); + if (cached !== undefined) return cached; + + const id = DENOM_COINGECKO_ID[baseDenom]; + if (!id) { + historicalPriceCache.set(k, 0); + return 0; + } + + try { + const res = await fetch( + `${config.external.coingeckoApiUrl}/coins/${id}/history?date=${formatDateForCoingecko(date)}&localization=false`, + { signal: AbortSignal.timeout(15_000) }, + ); + if (!res.ok) { + historicalPriceCache.set(k, 0); + return 0; + } + const data = (await res.json()) as { + market_data?: { current_price?: { usd?: number } }; + }; + const price = data.market_data?.current_price?.usd ?? 0; + historicalPriceCache.set(k, price); + return price; + } catch { + historicalPriceCache.set(k, 0); + return 0; + } +} + +/** Build a `baseDenom → price` map at a given date for the denoms we know about. + * Callers pass this to reward-processing functions to override the live cache. */ +export async function buildHistoricalPriceMap( + date: Date, + denoms: string[] = Object.keys(DENOM_COINGECKO_ID), +): Promise> { + const entries = await Promise.all( + denoms.map(async (d) => [d, await fetchTokenUsdPriceAt(d, date)] as const), + ); + const out: Record = {}; + for (const [d, p] of entries) { + if (p > 0) out[d] = p; + } + return out; +} + /** Fetch USD price for a base denom — reads from cache (pre-warmed by prewarmPriceCache) */ export async function fetchTokenUsdPrice(baseDenom: string): Promise { const cached = priceCache.get(baseDenom); diff --git a/apps/api/src/rpc/providers.ts b/apps/api/src/rpc/providers.ts index 462ba8a..6b0bc89 100644 --- a/apps/api/src/rpc/providers.ts +++ b/apps/api/src/rpc/providers.ts @@ -23,7 +23,13 @@ export interface ProviderForSpec { endpoints: ProviderEndpoint[]; } -export async function fetchProvidersForSpec(specId: string): Promise { +/** Fetch all providers staked on a given spec at `blockHeight` (or current if + * omitted). Historical queries require an archive node and are only used by + * the rewards endpoints — everything else should pass undefined. */ +export async function fetchProvidersForSpec( + specId: string, + blockHeight?: number, +): Promise { const data = await fetchRest<{ stakeEntry: Array<{ address: string; @@ -41,7 +47,7 @@ export async function fetchProvidersForSpec(specId: string): Promise; }>; - }>(`/lavanet/lava/pairing/providers/${specId}`); + }>(`/lavanet/lava/pairing/providers/${specId}`, blockHeight); return (data.stakeEntry ?? []).map((entry) => { const allAddons = new Set(); @@ -93,8 +99,14 @@ export interface ProviderSpecEntry { moniker: string; } -/** Build per-provider spec data + address list + spec name map from chain RPC */ -export async function fetchProvidersWithSpecs(): Promise<{ +/** Build per-provider spec data + address list + spec name map from chain RPC. + * Pass `blockHeight` to snapshot the provider set at a historical block — + * this is how the rewards endpoints recover providers who were active at + * the block but have since deregistered. Only rewards callers pass this; + * everything else uses the current (default) provider set. */ +export async function fetchProvidersWithSpecs( + blockHeight?: number, +): Promise<{ providers: Map; specNames: Map; }> { @@ -108,7 +120,7 @@ export async function fetchProvidersWithSpecs(): Promise<{ for (let i = 0; i < allSpecs.length; i += RPC_BATCH_SIZE) { const batch = allSpecs.slice(i, i + RPC_BATCH_SIZE); const results = await Promise.all( - batch.map((s) => fetchProvidersForSpec(s.index) + batch.map((s) => fetchProvidersForSpec(s.index, blockHeight) .then((ps) => ps.map((p) => ({ ...p, specId: s.index, specName: s.name }))) .catch(() => [] as Array)), ); diff --git a/apps/api/src/rpc/rewards.ts b/apps/api/src/rpc/rewards.ts index 581f702..98b537f 100644 --- a/apps/api/src/rpc/rewards.ts +++ b/apps/api/src/rpc/rewards.ts @@ -39,9 +39,14 @@ export interface ProcessedRewards { tokens: RewardToken[]; } -/** Convert multi-denom reward array to USD total + per-token breakdown */ +/** Convert multi-denom reward array to USD total + per-token breakdown. + * When `priceOverrides` is passed, its entries (keyed by base denom, e.g. + * "lava") take precedence over the live price cache. Used by historical- + * block rewards queries to price tokens at the block's date rather than + * the current CoinGecko price. */ async function processRewardTokens( rewards: Array<{ denom: string; amount: string }>, + priceOverrides?: Record, ): Promise { const tokens: RewardToken[] = []; let totalUsd = 0; @@ -66,7 +71,8 @@ async function processRewardTokens( const baseAmount = parseFloat(displayAmount); if (!isFinite(baseAmount) || baseAmount <= 0) continue; - const price = await fetchTokenUsdPrice(conversion.baseDenom); + const price = priceOverrides?.[conversion.baseDenom] + ?? await fetchTokenUsdPrice(conversion.baseDenom); const usd = price > 0 ? baseAmount * price : 0; totalUsd += usd; @@ -148,13 +154,16 @@ export interface RewardsBySpecEntry { * then splits "Boost: ETH1", "Pools: ETH1", "Subscription: ETH1" into per-spec groups. * * Pass blockHeight to query historical chain state (archive node required). - * Note: USD values still use current CoinGecko prices even for historical blocks — - * matches the old Job 2 behavior where CoinGecko was called at pipeline-run time. + * Pass priceOverrides (keyed by base denom, e.g. "lava") to price tokens at a + * specific point in time — typically the block's date for historical queries, + * so USD figures match jsinfo's block-time snapshot instead of drifting with + * the current LAVA price. */ export async function fetchRewardsBySpec( address: string, specNameMap: Map, blockHeight?: number, + priceOverrides?: Record, ): Promise { try { const data = await fetchRest( @@ -201,7 +210,10 @@ export async function fetchRewardsBySpec( const tokens: RewardToken[] = []; let totalUsd = 0; for (const [denom, amount] of denomMap) { - const processed = await processRewardTokens([{ denom, amount: amount.toString() }]); + const processed = await processRewardTokens( + [{ denom, amount: amount.toString() }], + priceOverrides, + ); tokens.push(...processed.tokens); totalUsd += processed.totalUsd; }