Skip to content

Commit f837f71

Browse files
committed
fix(provider-rewards): address review follow-ups
- Strict calendar-date validation: reject 2025-02-30 / 2025-04-31 etc. via Date.UTC round-trip instead of naive `new Date()` parsing. - Conditional cacheTTL: 86400s for immutable past windows (to < today), 300s for live windows. Cache plugin now honors request.cacheTTL as a per-request override of route config. - Clarify BigInt rule in CLAUDE.md and api-conventions.md — the weighted-QoS rule has an explicit exception for /provider-rewards (unweighted row-level averaging for delta parity), and an inline comment at the aggregation loop explains the choice plus why CU stays as Number (CU is not ulava; totals stay within safe-int). - Add tests for the two new calendar-invalid cases.
1 parent d29faf8 commit f837f71

5 files changed

Lines changed: 74 additions & 17 deletions

File tree

‎.claude/rules/api-conventions.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ paths:
2727
## GraphQL queries
2828
- Use materialized views (`mvRelayDailies`, `mvConsumerRelayDailies`) for aggregate queries — never query raw `relayPayments` (18.8M rows)
2929
- Date filters use `Date` type (`YYYY-MM-DD`), not `Datetime`
30-
- QoS is computed from weighted sums: `qosSyncW / qosWeight`
30+
- QoS is computed from relay-weighted sums by default: `qosSyncW / qosWeight`
31+
- Exception: `/provider-rewards` uses unweighted row-level averaging (`qosSyncSum / qosCount`) for parity with the delta reference implementation
3132

3233
## Swagger / OpenAPI
3334
- Every route must include `schema.tags` and `schema.summary` so it appears in Swagger UI (`/docs`)

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ The provider detail page (`/providers/:addr`) is expensive — it queries **ever
271271
| Token amounts | In ulava (1 LAVA = 1,000,000 ulava). Use `BigInt` — `Number` overflows |
272272
| Materialized views | Must use `mvRelayDailies` / `mvConsumerRelayDailies` for aggregates. Raw `relayPayments` (18.8M rows) will timeout |
273273
| MV date filters | Use `Date` type with `YYYY-MM-DD` format, NOT `Datetime` / ISO |
274-
| QoS computation | Weighted: `qosSyncW / qosWeight`, not simple average |
274+
| QoS computation | Default is relay-weighted: `qosSyncW / qosWeight`. Exception: `/provider-rewards` uses unweighted row-level averaging (`qosSyncSum / qosCount`) for delta parity |
275275
| Geolocation | Bitmask, not enum. A provider can be in multiple regions |
276276
| Base specs | COSMOSSDK, COSMOSSDK50, COSMOSWASM, ETHERMINT, TENDERMINT, IBC, SUIGRPC, SUIJSONRPC — exclude from chain lists |
277277
| React hooks | All `useMemo`/`useState`/`useApi` calls MUST come before conditional early returns |

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,26 @@ describe("GET /provider-rewards", () => {
169169
expect(res.statusCode).toBe(400);
170170
});
171171

172+
it("rejects calendar-invalid dates (Feb 30)", async () => {
173+
const app = await buildApp();
174+
const res = await app.inject({
175+
method: "GET",
176+
url: "/provider-rewards?from=2025-02-30&to=2025-04-01",
177+
});
178+
expect(res.statusCode).toBe(400);
179+
expect(JSON.parse(res.body).error).toMatch(/bad from date/);
180+
});
181+
182+
it("rejects calendar-invalid dates (Apr 31)", async () => {
183+
const app = await buildApp();
184+
const res = await app.inject({
185+
method: "GET",
186+
url: "/provider-rewards?from=2025-01-01&to=2025-04-31",
187+
});
188+
expect(res.statusCode).toBe(400);
189+
expect(JSON.parse(res.body).error).toMatch(/bad to date/);
190+
});
191+
172192
it("rejects date range exceeding 6 months", async () => {
173193
const app = await buildApp();
174194
const res = await app.inject({

‎apps/api/src/plugins/cache.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ declare module "fastify" {
55
interface FastifyContextConfig {
66
cacheTTL?: number;
77
}
8+
interface FastifyRequest {
9+
cacheTTL?: number;
10+
}
11+
}
12+
13+
function resolveTtl(request: FastifyRequest): number | undefined {
14+
return request.cacheTTL ?? request.routeOptions.config?.cacheTTL;
815
}
916

1017
function buildCacheKey(request: FastifyRequest): string {
@@ -27,7 +34,7 @@ function buildCacheKey(request: FastifyRequest): string {
2734
*/
2835
export const cachePlugin = fp(async (app: FastifyInstance) => {
2936
app.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
30-
const ttl = request.routeOptions.config?.cacheTTL;
37+
const ttl = resolveTtl(request);
3138
if (!ttl) return;
3239

3340
const client = app.redis;
@@ -47,7 +54,7 @@ export const cachePlugin = fp(async (app: FastifyInstance) => {
4754
});
4855

4956
app.addHook("onSend", async (request: FastifyRequest, reply: FastifyReply, payload: string) => {
50-
const ttl = request.routeOptions.config?.cacheTTL;
57+
const ttl = resolveTtl(request);
5158
if (!ttl) return payload;
5259
if (reply.getHeader("X-Cache") === "HIT") return payload;
5360
if (reply.statusCode >= 400) return payload;

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

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,33 @@ import { fetchProvidersForSpec, fetchAllProviders } from "../rpc/lava.js";
55
// ── Helpers ──────────────────────────────────────────────────────────────────
66

77
const SPEC_ID_RE = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
8+
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
89
const MAX_RANGE_MS = 6 * 30 * 24 * 60 * 60 * 1000; // ~6 months
10+
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
11+
const PAST_WINDOW_TTL = 86_400; // 1 day — immutable historical window
12+
const LIVE_WINDOW_TTL = 300; // 5 min — aligned with MV refresh cadence
913

1014
function validateSpecId(s: string): boolean {
1115
return s.length > 2 && s.length <= 50 && SPEC_ID_RE.test(s);
1216
}
1317

18+
// Parses YYYY-MM-DD strictly. Rejects calendar-invalid dates like 2025-02-30
19+
// (which `new Date()` would silently roll over to 2025-03-02).
20+
function parseStrictDate(s: string): Date | null {
21+
const m = DATE_RE.exec(s);
22+
if (!m) return null;
23+
const y = Number(m[1]);
24+
const mo = Number(m[2]);
25+
const d = Number(m[3]);
26+
if (mo < 1 || mo > 12 || d < 1 || d > 31) return null;
27+
const ts = Date.UTC(y, mo - 1, d);
28+
const rt = new Date(ts);
29+
if (rt.getUTCFullYear() !== y || rt.getUTCMonth() !== mo - 1 || rt.getUTCDate() !== d) {
30+
return null;
31+
}
32+
return rt;
33+
}
34+
1435
function computeAdjustedRewards(
1536
avgLat: number, avgAvail: number, avgSync: number, qosCus: number,
1637
): number {
@@ -82,19 +103,10 @@ export async function providerRewardsRoutes(app: FastifyInstance) {
82103
}
83104

84105
// ── Validate & normalize dates ─────────────────────────────────
85-
if (q.from.length !== 10 || q.to.length !== 10) {
86-
return reply.status(400).send({ error: "Error - bad date format" });
87-
}
88-
89-
let dateFrom = new Date(q.from + "T00:00:00Z");
90-
let dateTo = new Date(q.to + "T00:00:00Z");
91-
92-
if (isNaN(dateFrom.getTime())) {
93-
return reply.status(400).send({ error: "Error - bad from date format" });
94-
}
95-
if (isNaN(dateTo.getTime())) {
96-
return reply.status(400).send({ error: "Error - bad to date format" });
97-
}
106+
let dateFrom = parseStrictDate(q.from);
107+
if (!dateFrom) return reply.status(400).send({ error: "Error - bad from date format" });
108+
let dateTo = parseStrictDate(q.to);
109+
if (!dateTo) return reply.status(400).send({ error: "Error - bad to date format" });
98110

99111
if (dateTo < dateFrom) {
100112
[dateFrom, dateTo] = [dateTo, dateFrom];
@@ -109,6 +121,17 @@ export async function providerRewardsRoutes(app: FastifyInstance) {
109121
});
110122
}
111123

124+
// Past windows are immutable (MV refreshes catch up to yesterday within a
125+
// day), so cache them long; current windows follow MV refresh cadence.
126+
const todayUtc = Date.UTC(
127+
new Date().getUTCFullYear(),
128+
new Date().getUTCMonth(),
129+
new Date().getUTCDate(),
130+
);
131+
request.cacheTTL = dateTo.getTime() <= todayUtc - ONE_DAY_MS
132+
? PAST_WINDOW_TTL
133+
: LIVE_WINDOW_TTL;
134+
112135
// ── Resolve specs ─────────────────────────────────────────────
113136
const specs = q.specs && q.specs.length > 0 ? [...new Set(q.specs)] : null;
114137

@@ -161,6 +184,12 @@ export async function providerRewardsRoutes(app: FastifyInstance) {
161184
]);
162185

163186
// ── Compute adjusted rewards per provider ─────────────────────
187+
// NOTE: Unlike other routes, this endpoint uses unweighted row-level QoS
188+
// averaging (qos{Sync,Avail,Latency}Sum / qosCount) for parity with the
189+
// delta reference implementation, not the project-default weighted form
190+
// (qosSyncW / qosWeight). CU sums stay as Number because CU is not ulava
191+
// — totals are well within Number.MAX_SAFE_INTEGER and the response must
192+
// be JSON-serializable floats.
164193
interface ProviderTotal {
165194
moniker: string; adjustedRewards: number; relays: number; cus: number;
166195
qosCus: number; qosCount: number;

0 commit comments

Comments
 (0)