Skip to content

Commit 405879c

Browse files
committed
feat(api): block-time pricing + historical provider coverage for rewards
/provider-estimated-rewards?block=N now produces a self-consistent snapshot that matches jsinfo's stored monthly JSON: prices are as-of the block, and the provider set is the chain's pairing list at that block (not today's). Before this change, a historical-block query: • Priced tokens at the CURRENT LAVA price (drifts from jsinfo as price moves) • Iterated the CURRENT provider set (missed providers who've since unbonded/deregistered — ~14/48 missing on March 17, worth ~$2,922 USD) After: • block-time LAVA price via CoinGecko /coins/lava-network/history, passed through as a price-override map down to processRewardTokens • provider set fetched with x-cosmos-block-height header so chain RPC returns the historical pairing list Changes: - rpc/block.ts: export fetchBlockTime(height) for block → ISO timestamp - rpc/pricing.ts: fetchTokenUsdPriceAt(denom, date) and buildHistoricalPriceMap with indefinite caching (historical prices don't change) - rpc/providers.ts: optional blockHeight on fetchProvidersForSpec + fetchProvidersWithSpecs. Default undefined → current state, unchanged for every non-rewards caller (/providers, /specs, etc.) - rpc/rewards.ts: optional priceOverrides on fetchRewardsBySpec. Threads into processRewardTokens where it takes precedence over the live price cache. - routes/provider-estimated-rewards.ts: when ?block= is set, fetches block time → builds historical price map → passes both blockHeight and overrides down. meta.priceTimestamp = block time; meta.priceLavaUsd = historical price. - tests: new assertions for block-time pricing, historical provider coverage, and that live-mode doesn't accidentally call historical helpers. 112/112.
1 parent 3397a24 commit 405879c

7 files changed

Lines changed: 203 additions & 18 deletions

File tree

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

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,19 @@ vi.mock("../rpc/lava.js", () => ({
88
fetchProvidersWithSpecs: vi.fn(),
99
fetchRewardsBySpec: vi.fn(),
1010
fetchBlockAtTimestamp: vi.fn(),
11+
fetchBlockTime: vi.fn(),
1112
fetchLavaUsdPrice: vi.fn(),
13+
buildHistoricalPriceMap: vi.fn(),
1214
}));
1315

1416
const {
1517
prewarmPriceCache,
1618
fetchProvidersWithSpecs,
1719
fetchRewardsBySpec,
1820
fetchBlockAtTimestamp,
21+
fetchBlockTime,
1922
fetchLavaUsdPrice,
23+
buildHistoricalPriceMap,
2024
} = await import("../rpc/lava.js");
2125
const { providerEstimatedRewardsRoutes } = await import("../routes/provider-estimated-rewards.js");
2226

@@ -88,6 +92,8 @@ beforeEach(() => {
8892
(fetchBlockAtTimestamp as ReturnType<typeof vi.fn>).mockImplementation(
8993
(unix: number) => Promise.resolve(1_000_000 + Math.floor(unix / 1000)),
9094
);
95+
(fetchBlockTime as ReturnType<typeof vi.fn>).mockResolvedValue("2026-03-17T15:00:00Z");
96+
(buildHistoricalPriceMap as ReturnType<typeof vi.fn>).mockResolvedValue({ lava: 0.035 });
9197
});
9298

9399
describe("GET /provider-estimated-rewards", () => {
@@ -187,6 +193,56 @@ describe("GET /provider-estimated-rewards", () => {
187193
}
188194
});
189195

196+
it("uses block-time pricing when ?block= is set (historical LAVA price)", async () => {
197+
(fetchBlockTime as ReturnType<typeof vi.fn>).mockResolvedValue("2026-03-17T15:00:00Z");
198+
(buildHistoricalPriceMap as ReturnType<typeof vi.fn>).mockResolvedValue({ lava: 0.035 });
199+
const app = await buildApp();
200+
const res = await app.inject({
201+
method: "GET",
202+
url: "/provider-estimated-rewards?block=4697952",
203+
});
204+
expect(res.statusCode).toBe(200);
205+
const body = JSON.parse(res.body);
206+
// meta.priceLavaUsd reflects historical price, meta.priceTimestamp = block time
207+
expect(body.meta.priceLavaUsd).toBe(0.035);
208+
expect(body.meta.priceTimestamp).toBe("2026-03-17T15:00:00Z");
209+
// fetchRewardsBySpec got the override map as the 4th arg
210+
const calls = (fetchRewardsBySpec as ReturnType<typeof vi.fn>).mock.calls;
211+
for (const [, , , overridesArg] of calls) {
212+
expect(overridesArg).toEqual({ lava: 0.035 });
213+
}
214+
// fetchLavaUsdPrice is NOT called when historical overrides provide a lava price
215+
expect(fetchLavaUsdPrice).not.toHaveBeenCalled();
216+
});
217+
218+
it("snapshots the provider set at the historical block (not current)", async () => {
219+
(fetchBlockTime as ReturnType<typeof vi.fn>).mockResolvedValue("2026-03-17T15:00:00Z");
220+
(buildHistoricalPriceMap as ReturnType<typeof vi.fn>).mockResolvedValue({ lava: 0.035 });
221+
const app = await buildApp();
222+
await app.inject({ method: "GET", url: "/provider-estimated-rewards?block=4697952" });
223+
// fetchProvidersWithSpecs was called with the block height so chain RPC
224+
// returns the provider set as it existed at that block (includes providers
225+
// who have since deregistered).
226+
expect(fetchProvidersWithSpecs).toHaveBeenCalledWith(4697952);
227+
});
228+
229+
it("uses live prices + current provider set when ?block= is omitted", async () => {
230+
(fetchLavaUsdPrice as ReturnType<typeof vi.fn>).mockResolvedValue(0.025);
231+
const app = await buildApp();
232+
const res = await app.inject({ method: "GET", url: "/provider-estimated-rewards" });
233+
const body = JSON.parse(res.body);
234+
expect(body.meta.priceLavaUsd).toBe(0.025);
235+
// Provider set fetched without a block arg (current state)
236+
expect(fetchProvidersWithSpecs).toHaveBeenCalledWith(undefined);
237+
// No historical price map needed
238+
expect(buildHistoricalPriceMap).not.toHaveBeenCalled();
239+
// No override passed through to fetchRewardsBySpec
240+
const calls = (fetchRewardsBySpec as ReturnType<typeof vi.fn>).mock.calls;
241+
for (const [, , , overridesArg] of calls) {
242+
expect(overridesArg).toBeUndefined();
243+
}
244+
});
245+
190246
it("filters response to a single spec when ?spec= is provided", async () => {
191247
const app = await buildApp();
192248
const res = await app.inject({

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

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import type { FastifyInstance } from "fastify";
22
import { CACHE_TTL } from "../config.js";
33
import {
44
RPC_BATCH_SIZE,
5+
buildHistoricalPriceMap,
56
fetchBlockAtTimestamp,
7+
fetchBlockTime,
68
fetchLavaUsdPrice,
79
fetchProvidersWithSpecs,
810
fetchRewardsBySpec,
@@ -131,13 +133,29 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) {
131133
if (block) request.cacheTTL = CACHE_TTL.HISTORICAL;
132134

133135
await prewarmPriceCache();
134-
// Tokens at block N are priced with the CURRENT LAVA price (matches lava-ops
135-
// Job 2). Surface the price + timestamp in meta so consumers know the USD
136-
// figure is not historical and shouldn't be interpreted as price movement.
137-
const priceTimestamp = new Date().toISOString();
138-
const priceLavaUsd = await fetchLavaUsdPrice();
139136

140-
const { providers: providerMap, specNames } = await fetchProvidersWithSpecs();
137+
// When querying a historical block:
138+
// • Build a block-time price map so USD values match the snapshot the
139+
// block would have produced (not today's LAVA price).
140+
// • Snapshot the provider set AT the block, not the current chain state,
141+
// so providers who've since deregistered still appear.
142+
// Without a block, default to live prices + current provider set.
143+
let priceTimestamp: string;
144+
let priceLavaUsd: number;
145+
let priceOverrides: Record<string, number> | undefined;
146+
147+
if (block) {
148+
const blockTimeIso = await fetchBlockTime(block);
149+
const blockDate = new Date(blockTimeIso);
150+
priceOverrides = await buildHistoricalPriceMap(blockDate);
151+
priceLavaUsd = priceOverrides.lava ?? await fetchLavaUsdPrice();
152+
priceTimestamp = blockTimeIso;
153+
} else {
154+
priceTimestamp = new Date().toISOString();
155+
priceLavaUsd = await fetchLavaUsdPrice();
156+
}
157+
158+
const { providers: providerMap, specNames } = await fetchProvidersWithSpecs(block);
141159
const addresses = Array.from(providerMap.keys());
142160

143161
const results: Array<{
@@ -150,7 +168,7 @@ export async function providerEstimatedRewardsRoutes(app: FastifyInstance) {
150168
for (let i = 0; i < addresses.length; i += RPC_BATCH_SIZE) {
151169
const batch = addresses.slice(i, i + RPC_BATCH_SIZE);
152170
const rewardResults = await Promise.all(
153-
batch.map((addr) => fetchRewardsBySpec(addr, specNames, block)),
171+
batch.map((addr) => fetchRewardsBySpec(addr, specNames, block, priceOverrides)),
154172
);
155173

156174
for (let j = 0; j < batch.length; j++) {

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,20 @@ const LAVA_GENESIS_UNIX = 1_713_350_000; // ~2024-04-17
77
const blockAtTsCache = new Map<number, number>();
88
const BLOCK_AT_TS_CACHE_MAX = 200;
99

10+
/** Fetch the timestamp of a given block height (ISO 8601 string).
11+
* Used for historical pricing — lets callers query CoinGecko for LAVA
12+
* price at the block's date instead of using the current price. */
13+
export async function fetchBlockTime(height: number): Promise<string> {
14+
const res = await fetch(`${config.lava.rpcUrl}/block?height=${height}`, {
15+
signal: AbortSignal.timeout(10_000),
16+
});
17+
if (!res.ok) throw new Error(`RPC ${res.status}`);
18+
const data = (await res.json()) as {
19+
result: { block: { header: { time: string } } };
20+
};
21+
return data.result.block.header.time;
22+
}
23+
1024
export async function fetchLatestBlockHeight(): Promise<{
1125
height: number;
1226
time: string;

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// New code should import directly from the focused modules.
55

66
export { RPC_BATCH_SIZE } from "./rest.js";
7-
export { fetchBlockAtTimestamp, fetchLatestBlockHeight } from "./block.js";
7+
export { fetchBlockAtTimestamp, fetchBlockTime, fetchLatestBlockHeight } from "./block.js";
88
export { fetchAllSpecs } from "./specs.js";
99
export { fetchTotalSupply, fetchCirculatingSupply } from "./supply.js";
1010
export {
@@ -20,6 +20,8 @@ export {
2020
} from "./providers.js";
2121
export {
2222
fetchLavaUsdPrice,
23+
fetchTokenUsdPriceAt,
24+
buildHistoricalPriceMap,
2325
prewarmPriceCache,
2426
computeTVL,
2527
} from "./pricing.js";

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,77 @@ export async function prewarmPriceCache(): Promise<void> {
103103
}
104104
}
105105

106+
// ── Historical pricing (CoinGecko /coins/{id}/history) ──────────────────────
107+
// Used for rewards snapshots at historical block heights — we want the LAVA
108+
// price as it was on that date, not the current price. Results are cached by
109+
// (denom, date) tuple indefinitely since historical prices don't change.
110+
111+
interface HistoricalPriceKey { baseDenom: string; date: string /* YYYY-MM-DD */ }
112+
const historicalPriceCache = new Map<string, number>();
113+
const keyStr = (k: HistoricalPriceKey) => `${k.baseDenom}@${k.date}`;
114+
115+
// Format a Date to CoinGecko's expected `DD-MM-YYYY` string.
116+
function formatDateForCoingecko(date: Date): string {
117+
const dd = String(date.getUTCDate()).padStart(2, "0");
118+
const mm = String(date.getUTCMonth() + 1).padStart(2, "0");
119+
const yyyy = date.getUTCFullYear();
120+
return `${dd}-${mm}-${yyyy}`;
121+
}
122+
123+
/** 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). */
125+
export async function fetchTokenUsdPriceAt(
126+
baseDenom: string,
127+
date: Date,
128+
): Promise<number> {
129+
const isoDate = date.toISOString().slice(0, 10);
130+
const k = keyStr({ baseDenom, date: isoDate });
131+
const cached = historicalPriceCache.get(k);
132+
if (cached !== undefined) return cached;
133+
134+
const id = DENOM_COINGECKO_ID[baseDenom];
135+
if (!id) {
136+
historicalPriceCache.set(k, 0);
137+
return 0;
138+
}
139+
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 {
156+
historicalPriceCache.set(k, 0);
157+
return 0;
158+
}
159+
}
160+
161+
/** 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. */
163+
export async function buildHistoricalPriceMap(
164+
date: Date,
165+
denoms: string[] = Object.keys(DENOM_COINGECKO_ID),
166+
): Promise<Record<string, number>> {
167+
const entries = await Promise.all(
168+
denoms.map(async (d) => [d, await fetchTokenUsdPriceAt(d, date)] as const),
169+
);
170+
const out: Record<string, number> = {};
171+
for (const [d, p] of entries) {
172+
if (p > 0) out[d] = p;
173+
}
174+
return out;
175+
}
176+
106177
/** Fetch USD price for a base denom — reads from cache (pre-warmed by prewarmPriceCache) */
107178
export async function fetchTokenUsdPrice(baseDenom: string): Promise<number> {
108179
const cached = priceCache.get(baseDenom);

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

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@ export interface ProviderForSpec {
2323
endpoints: ProviderEndpoint[];
2424
}
2525

26-
export async function fetchProvidersForSpec(specId: string): Promise<ProviderForSpec[]> {
26+
/** Fetch all providers staked on a given spec at `blockHeight` (or current if
27+
* omitted). Historical queries require an archive node and are only used by
28+
* the rewards endpoints — everything else should pass undefined. */
29+
export async function fetchProvidersForSpec(
30+
specId: string,
31+
blockHeight?: number,
32+
): Promise<ProviderForSpec[]> {
2733
const data = await fetchRest<{
2834
stakeEntry: Array<{
2935
address: string;
@@ -41,7 +47,7 @@ export async function fetchProvidersForSpec(specId: string): Promise<ProviderFor
4147
api_interfaces?: string[];
4248
}>;
4349
}>;
44-
}>(`/lavanet/lava/pairing/providers/${specId}`);
50+
}>(`/lavanet/lava/pairing/providers/${specId}`, blockHeight);
4551

4652
return (data.stakeEntry ?? []).map((entry) => {
4753
const allAddons = new Set<string>();
@@ -93,8 +99,14 @@ export interface ProviderSpecEntry {
9399
moniker: string;
94100
}
95101

96-
/** Build per-provider spec data + address list + spec name map from chain RPC */
97-
export async function fetchProvidersWithSpecs(): Promise<{
102+
/** Build per-provider spec data + address list + spec name map from chain RPC.
103+
* Pass `blockHeight` to snapshot the provider set at a historical block —
104+
* this is how the rewards endpoints recover providers who were active at
105+
* the block but have since deregistered. Only rewards callers pass this;
106+
* everything else uses the current (default) provider set. */
107+
export async function fetchProvidersWithSpecs(
108+
blockHeight?: number,
109+
): Promise<{
98110
providers: Map<string, { moniker: string; identity: string; commission: string; specs: ProviderSpecEntry[] }>;
99111
specNames: Map<string, string>;
100112
}> {
@@ -108,7 +120,7 @@ export async function fetchProvidersWithSpecs(): Promise<{
108120
for (let i = 0; i < allSpecs.length; i += RPC_BATCH_SIZE) {
109121
const batch = allSpecs.slice(i, i + RPC_BATCH_SIZE);
110122
const results = await Promise.all(
111-
batch.map((s) => fetchProvidersForSpec(s.index)
123+
batch.map((s) => fetchProvidersForSpec(s.index, blockHeight)
112124
.then((ps) => ps.map((p) => ({ ...p, specId: s.index, specName: s.name })))
113125
.catch(() => [] as Array<ProviderForSpec & { specId: string; specName: string }>)),
114126
);

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

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,14 @@ export interface ProcessedRewards {
3939
tokens: RewardToken[];
4040
}
4141

42-
/** Convert multi-denom reward array to USD total + per-token breakdown */
42+
/** Convert multi-denom reward array to USD total + per-token breakdown.
43+
* When `priceOverrides` is passed, its entries (keyed by base denom, e.g.
44+
* "lava") take precedence over the live price cache. Used by historical-
45+
* block rewards queries to price tokens at the block's date rather than
46+
* the current CoinGecko price. */
4347
async function processRewardTokens(
4448
rewards: Array<{ denom: string; amount: string }>,
49+
priceOverrides?: Record<string, number>,
4550
): Promise<ProcessedRewards> {
4651
const tokens: RewardToken[] = [];
4752
let totalUsd = 0;
@@ -66,7 +71,8 @@ async function processRewardTokens(
6671
const baseAmount = parseFloat(displayAmount);
6772
if (!isFinite(baseAmount) || baseAmount <= 0) continue;
6873

69-
const price = await fetchTokenUsdPrice(conversion.baseDenom);
74+
const price = priceOverrides?.[conversion.baseDenom]
75+
?? await fetchTokenUsdPrice(conversion.baseDenom);
7076
const usd = price > 0 ? baseAmount * price : 0;
7177
totalUsd += usd;
7278

@@ -148,13 +154,16 @@ export interface RewardsBySpecEntry {
148154
* then splits "Boost: ETH1", "Pools: ETH1", "Subscription: ETH1" into per-spec groups.
149155
*
150156
* Pass blockHeight to query historical chain state (archive node required).
151-
* Note: USD values still use current CoinGecko prices even for historical blocks —
152-
* matches the old Job 2 behavior where CoinGecko was called at pipeline-run time.
157+
* Pass priceOverrides (keyed by base denom, e.g. "lava") to price tokens at a
158+
* specific point in time — typically the block's date for historical queries,
159+
* so USD figures match jsinfo's block-time snapshot instead of drifting with
160+
* the current LAVA price.
153161
*/
154162
export async function fetchRewardsBySpec(
155163
address: string,
156164
specNameMap: Map<string, string>,
157165
blockHeight?: number,
166+
priceOverrides?: Record<string, number>,
158167
): Promise<RewardsBySpecEntry[]> {
159168
try {
160169
const data = await fetchRest<EstimatedRewardsResponse>(
@@ -201,7 +210,10 @@ export async function fetchRewardsBySpec(
201210
const tokens: RewardToken[] = [];
202211
let totalUsd = 0;
203212
for (const [denom, amount] of denomMap) {
204-
const processed = await processRewardTokens([{ denom, amount: amount.toString() }]);
213+
const processed = await processRewardTokens(
214+
[{ denom, amount: amount.toString() }],
215+
priceOverrides,
216+
);
205217
tokens.push(...processed.tokens);
206218
totalUsd += processed.totalUsd;
207219
}

0 commit comments

Comments
 (0)