diff --git a/app/src/app/api/stats/route.test.ts b/app/src/app/api/stats/route.test.ts new file mode 100644 index 00000000..44355df5 --- /dev/null +++ b/app/src/app/api/stats/route.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { getMock, resetMock } from "@/lib/db-mock"; +import { clearMemo } from "@/lib/launchpad/memo"; +import { GET } from "./route.ts"; + +function request(query = ""): Request { + return new Request(`http://localhost/api/stats${query}`); +} + +beforeEach(() => { + clearMemo(); + resetMock(); +}); + +test("GET returns the stats shape and defaults to 30d for unknown values", async () => { + const res = await GET(request("?window=7d&chain=base")); + assert.equal(res.status, 200); + assert.equal(res.headers.get("cache-control"), "no-store"); + const body = (await res.json()) as { window: string; chain: string | null; available: boolean; by_chain: Array<{ chain: string }>; series: unknown[]; top: unknown[]; totals: { launches: number } }; + // The test database is the in-memory mock: it answers with no rows, so the window is honestly empty. + assert.equal(body.window, "7d"); + assert.equal(body.chain, "base"); + assert.equal(body.available, true); + assert.deepEqual(body.by_chain.map((c) => c.chain), ["base"]); + assert.equal(body.series.length, 7); + assert.deepEqual(body.top, []); + assert.equal(body.totals.launches, 0); + + const fallback = (await (await GET(request("?window=forever&chain=ethereum"))).json()) as { window: string; chain: string | null; by_chain: unknown[] }; + assert.equal(fallback.window, "30d"); + assert.equal(fallback.chain, null); + assert.equal(fallback.by_chain.length, 4); +}); + +test("format=csv serves one header row and a download filename", async () => { + const res = await GET(request("?window=7d&chain=base&format=csv")); + assert.equal(res.status, 200); + assert.match(res.headers.get("content-type") ?? "", /^text\/csv/); + assert.equal(res.headers.get("content-disposition"), 'attachment; filename="openlaunch-stats-7d-base.csv"'); + const lines = (await res.text()).trimEnd().split("\n"); + assert.equal(lines.length, 8); + assert.equal(lines[0], "chain,day,launches,launchers,trades,traders,volume_usd,fees_collected_usd,fees_burned_usd,unpriced_trades,unpriced_fee_events"); + for (const line of lines.slice(1)) assert.match(line, /^base,\d{4}-\d{2}-\d{2},0,0,0,0,0,0,0,0,0$/); + + const all = await GET(request("?format=csv")); + assert.equal(all.headers.get("content-disposition"), 'attachment; filename="openlaunch-stats-30d.csv"'); +}); + +test("CSV export fails loudly when the stats read is unavailable, but a healthy empty index exports 200", async () => { + getMock().dbUnavailable = true; + const outage = await GET(request("?window=all&format=csv")); + assert.equal(outage.status, 503, "a failed read must not look like an empty export"); + assert.equal(outage.headers.get("cache-control"), "no-store"); + + getMock().dbUnavailable = false; + clearMemo(); // the failure was memoized under the same window/chain + const empty = await GET(request("?window=all&format=csv")); + assert.equal(empty.status, 200); + const lines = (await empty.text()).trimEnd().split("\n"); + assert.equal(lines.length, 1, "a genuinely empty all-time index is a header-only CSV"); + assert.match(lines[0], /^chain,day,launches/); +}); diff --git a/app/src/app/api/stats/route.ts b/app/src/app/api/stats/route.ts new file mode 100644 index 00000000..8111f69f --- /dev/null +++ b/app/src/app/api/stats/route.ts @@ -0,0 +1,42 @@ +import { NextResponse } from "next/server"; +import { getProtocolStatsCached } from "@/lib/stats/server"; +import { parseStatsChain, parseStatsFormat, parseStatsWindow, statsCsv } from "@/lib/stats/stats"; + +export const dynamic = "force-dynamic"; + +/** + * GET /api/stats?window=7d|30d|90d|all&chain=base|robinhood|arc|elysium&format=json|csv + * + * Protocol aggregates derived from the same index as the site. USD values are + * fixed at each trade's or fee's own UTC hour; events with no price for that + * hour are excluded and counted, not valued at today's price. `available:false` + * means the database is unset or the read failed — the empty shapes are not + * facts. The page and this endpoint share one 30 s memo. + */ +export async function GET(req: Request): Promise { + const url = new URL(req.url); + const window = parseStatsWindow(url.searchParams.get("window")); + const chain = parseStatsChain(url.searchParams.get("chain")); + const format = parseStatsFormat(url.searchParams.get("format")); + const stats = await getProtocolStatsCached(window, chain); + const headers = { "cache-control": "no-store" }; + + // A CSV is handed to spreadsheets and reporting jobs: a header-only file from a failed read looks like a real, + // empty export. JSON keeps its documented `available: false` shape; CSV fails loudly instead. + if (format === "csv" && !stats.available) { + return new Response("stats unavailable\n", { status: 503, headers: { ...headers, "content-type": "text/plain; charset=utf-8" } }); + } + + if (format === "csv") { + return new Response(statsCsv(stats), { + status: 200, + headers: { + ...headers, + "content-type": "text/csv; charset=utf-8", + "content-disposition": `attachment; filename="openlaunch-stats-${window}${chain ? `-${chain}` : ""}.csv"`, + }, + }); + } + + return NextResponse.json(stats, { status: 200, headers }); +} diff --git a/app/src/app/llms.txt/route.ts b/app/src/app/llms.txt/route.ts index efbc6545..daea12c6 100644 --- a/app/src/app/llms.txt/route.ts +++ b/app/src/app/llms.txt/route.ts @@ -134,7 +134,10 @@ ${pairApplySection()} - GET ${SITE_URL}/api/launch/meta/ - POST ${SITE_URL}/api/launch/sync?chain=base|robinhood|arc|elysium&tx=0x… (index a tx you just sent) - GET ${SITE_URL}/api/health -Pages: / (list, ?chain=), /launch (?chain=), /t// (trade + fees), /rules, /agents. +- GET ${SITE_URL}/api/stats?window=7d|30d|90d|all&chain=base|robinhood|arc|elysium&format=json|csv + Launches, trades, trade-time USD volume, creator fees and burns per chain and UTC day. available:false means the + database is unset or the aggregate read failed; the empty shapes are not facts. CSV is one row per UTC day. +Pages: / (list, ?chain=), /launch (?chain=), /t// (trade + fees), /stats (protocol totals + daily series), /rules, /agents. `; return new Response(body, { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "public, max-age=300" } }); } diff --git a/app/src/app/stats/page.tsx b/app/src/app/stats/page.tsx new file mode 100644 index 00000000..507ffa7d --- /dev/null +++ b/app/src/app/stats/page.tsx @@ -0,0 +1,166 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { ArrowUpRight, ChartNoAxesColumn, Download, Info } from "lucide-react"; +import SectionIntro from "@/components/sections/SectionIntro"; +import shell from "@/components/sections/SectionShell.module.css"; +import StatsChart from "@/components/stats/StatsChart"; +import styles from "@/components/stats/Stats.module.css"; +import { ChainLogo } from "@/components/launchpad/ChainLogo"; +import { CHAIN_KEYS, CHAIN_LABELS } from "@/lib/chainPublic"; +import { BRAND_GITHUB } from "@/lib/brand"; +import { fmtUsd } from "@/lib/launchpad/math"; +import { pageMetadata } from "@/lib/seo"; +import { getProtocolStatsCached } from "@/lib/stats/server"; +import { DEFAULT_STATS_WINDOW, STATS_WINDOWS, parseStatsChain, parseStatsWindow, statsHref, type StatsWindow } from "@/lib/stats/stats"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = pageMetadata({ + path: "/stats", + title: "Protocol stats", + description: "Launches, trades, trade-time USD volume, creator fees and burns across every openlaunch chain, read from the chain index. Daily series and CSV download.", +}); + +const WINDOW_LABEL: Record = { "7d": "7 days", "30d": "30 days", "90d": "90 days", all: "All time" }; + +const n = (v: number): string => Math.round(v).toLocaleString("en-US"); + +/** `/api/stats` with the current filters, preserving only what the caller chose. */ +function apiHref(window: StatsWindow, chain: string | null, format?: "csv"): string { + const params = new URLSearchParams({ window }); + if (chain) params.set("chain", chain); + if (format) params.set("format", format); + return `/api/stats?${params.toString()}`; +} + +export default async function StatsPage({ searchParams }: { searchParams: Promise<{ window?: string; chain?: string }> }) { + const sp = await searchParams; + const window = parseStatsWindow(sp.window, DEFAULT_STATS_WINDOW); + const chain = parseStatsChain(sp.chain); + const stats = await getProtocolStatsCached(window, chain); + const scope = chain ? CHAIN_LABELS[chain] : "all chains"; + + return ( +
+ } + title="Protocol stats" + description={<>Launches, trades, trade-time volume and fee flows, aggregated from the same chain index the site reads. No estimates and no scores: every figure is a sum of indexed events, and events without a price for their hour are counted rather than guessed.} + > + JSON API + + + +
+ + +
+ + {!stats.available ? ( +
+

Chain index

+

Stats are temporarily unavailable.

+

The page reads the site's Postgres index of factory, locker and PoolManager events. It is not configured or the aggregate read failed, so there are no numbers to show — an empty card would be a lie. Try again shortly, or read the same contract in the API.

+
+ ) : ( + <> +
+
+

Launches

+

{n(stats.totals.launches)}

+

{n(stats.totals.launchers)} launcher wallets

+
+
+

Trades

+

{n(stats.totals.trades)}

+

{n(stats.totals.traders)} trader wallets

+
+
+

Volume

+

{fmtUsd(stats.totals.volume_usd, { compact: true })}

+

USD at each trade's own hour

+
+
+

To creators

+

{fmtUsd(stats.totals.fees_to_creators_usd, { compact: true })}

+

{fmtUsd(stats.totals.fees_burned_usd, { compact: true })} burned

+
+
+ + {stats.totals.usd_partial ? ( +

+

+ ) : null} + +
+ + +
+ +
+
+

By chain

{WINDOW_LABEL[window]}
+
+ + + + {stats.by_chain.map((row) => ( + + + + + + + + + ))} + +
ChainLaunchesTradesVolumeTo creatorsBurned
{CHAIN_LABELS[row.chain]}{n(row.launches)}{n(row.trades)}{fmtUsd(row.volume_usd, { compact: true })}{fmtUsd(row.fees_to_creators_usd, { compact: true })}{fmtUsd(row.fees_burned_usd, { compact: true })}
+
+
+ +
+

Top launches by volume

{WINDOW_LABEL[window]}
+ {stats.top.length === 0 ? ( +

No indexed trades in this window yet.

+ ) : ( +
    + {stats.top.map((launch, i) => ( +
  1. + {i + 1} +
    + {launch.symbol || "—"} + {launch.name || launch.token} +
    +
    {fmtUsd(launch.volume_usd, { compact: true })}{n(launch.trades)} trades · {CHAIN_LABELS[launch.chain]}
    +
  2. + ))} +
+ )} +
+
+ +
+

Every figure is an aggregate of the site's Postgres index of bb_launches, bb_launch_swaps and bb_launch_fee_events, which follow the factory, locker and Uniswap v4 PoolManager events. The chain is the source of truth; the index lags by a few blocks and a very new launch may not be synced yet.

+

USD is trade-time USD: the quote's price in the event's own UTC hour, fixed when the event was indexed. An event with no price for that hour is excluded from the USD sums and counted in the warning above. The home page totals additionally fall back to the current price for those events, so the two can differ when a price feed was down.

+

Fees to creators are collected quote fees minus burned quote fees. Token-side fee burns are not valued in USD. Holders shown on a launch are the indexed transfer-history count, not this page's aggregate.

+

Download the daily series as CSV above, or read /api/stats with window=7d|30d|90d|all and chain=base|robinhood|arc|elysium. The same numbers are on this page, one memoized read per window. Method and field notes: docs/stats.md.

+
+ + )} +
+ ); +} diff --git a/app/src/components/stats/Stats.module.css b/app/src/components/stats/Stats.module.css new file mode 100644 index 00000000..ce1f8d19 --- /dev/null +++ b/app/src/components/stats/Stats.module.css @@ -0,0 +1,438 @@ +.controls { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + margin: -8px 0 20px; +} + +.tabs { + display: inline-flex; + flex-wrap: wrap; + gap: 3px; + padding: 3px; + border: 1px solid var(--color-line); + border-radius: 12px; + background: var(--color-card); +} + +.tab { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 34px; + padding: 0 11px; + border-radius: 9px; + color: var(--color-body); + font-size: 13px; + font-weight: 600; + white-space: nowrap; + transition: background-color 150ms, color 150ms; +} + +.tab:hover { + background: var(--color-paper); + color: var(--color-ink); +} + +.tabActive, +.tabActive:hover { + background: var(--color-ink); + color: var(--color-inverse); +} + +.cards { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.card { + min-width: 0; + padding: 16px; + border: 1px solid var(--color-line); + border-radius: 14px; + background: var(--color-card); +} + +.cardLabel { + color: var(--color-muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.cardValue { + margin-top: 8px; + color: var(--color-ink); + font-family: var(--font-mono); + font-size: 26px; + font-weight: 700; + line-height: 1.1; + letter-spacing: -0.03em; + overflow-wrap: anywhere; +} + +.cardNote { + margin-top: 6px; + color: var(--color-muted); + font-size: 12px; + line-height: 1.5; +} + +.warning { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 14px; + padding: 12px 14px; + border: 1px solid color-mix(in srgb, var(--color-warm) 35%, var(--color-line)); + border-radius: 12px; + background: var(--color-warm-soft); + color: var(--color-warm-ink); + font-size: 12.5px; + line-height: 1.6; +} + +.warning svg { + flex-shrink: 0; + margin-top: 2px; +} + +.charts { + display: grid; + grid-template-columns: 1fr; + gap: 12px; + margin-top: 20px; +} + +.chart { + min-width: 0; + margin: 0; + padding: 16px; + border: 1px solid var(--color-line); + border-radius: 14px; + background: var(--color-card); +} + +.chartCaption { + display: flex; + flex-direction: column; + gap: 3px; + margin-bottom: 10px; +} + +.chartTitle { + color: var(--color-ink); + font-size: 14px; + font-weight: 700; +} + +.chartNote { + color: var(--color-muted); + font-size: 12px; +} + +.plot { + display: block; + width: 100%; + height: auto; + overflow: visible; +} + +.grid { + stroke: var(--color-chart-grid); + stroke-width: 1; +} + +.axis { + fill: var(--color-muted); + font-family: var(--font-mono); + font-size: 10px; +} + +.bar { + fill: var(--color-brand); + opacity: 0.82; +} + +.bar:hover { + opacity: 1; +} + +.chartEmpty { + padding: 28px; + border: 1px dashed var(--color-line-strong); + border-radius: 14px; + color: var(--color-muted); + font-size: 13px; + text-align: center; +} + +.dataTable { + margin-top: 10px; + padding-top: 8px; + border-top: 1px solid var(--color-line); +} + +.dataTable summary { + display: flex; + align-items: center; + min-height: 32px; + color: var(--color-body); + font-size: 12px; + cursor: pointer; +} + +.tableScroll { + max-height: 260px; + overflow: auto; +} + +.tableScroll table { + width: 100%; + border-collapse: collapse; + font-size: 12px; +} + +.tableScroll th, +.tableScroll td { + padding: 5px 8px; + border-bottom: 1px solid var(--color-line); + text-align: left; + white-space: nowrap; +} + +.tableScroll thead th { + color: var(--color-muted); + font-weight: 600; +} + +.twoCol { + display: grid; + grid-template-columns: 1fr; + gap: 12px; + margin-top: 20px; +} + +.panel { + min-width: 0; + overflow: hidden; + border: 1px solid var(--color-line); + border-radius: 14px; + background: var(--color-card); +} + +.panelHeading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 48px; + padding: 0 14px; + border-bottom: 1px solid var(--color-line); + color: var(--color-ink); + font-size: 13px; + font-weight: 700; +} + +.panelHeading span { + color: var(--color-muted); + font-size: 11px; + font-weight: 500; +} + +.table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.table th, +.table td { + padding: 9px 12px; + border-bottom: 1px solid var(--color-line); + text-align: left; + white-space: nowrap; +} + +.table thead th { + color: var(--color-muted); + font-size: 10px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.table tbody tr:last-child th, +.table tbody tr:last-child td { + border-bottom: 0; +} + +.table tbody th { + color: var(--color-ink); + font-weight: 600; +} + +.chainName { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.numeric { + text-align: right !important; + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; +} + +.topList { + margin: 0; + padding: 0; + list-style: none; +} + +.topList li { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + border-bottom: 1px solid var(--color-line); +} + +.topList li:last-child { + border-bottom: 0; +} + +.topRank { + width: 18px; + flex-shrink: 0; + color: var(--color-muted); + font-family: var(--font-mono); + font-size: 12px; + text-align: right; +} + +.topName { + min-width: 0; + flex: 1; +} + +.topName a { + color: var(--color-ink); + font-size: 13px; + font-weight: 600; +} + +.topName a:hover { + text-decoration: underline; + text-underline-offset: 3px; +} + +.topName span { + display: block; + overflow: hidden; + color: var(--color-muted); + font-size: 11px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.topValue { + display: flex; + flex-direction: column; + flex-shrink: 0; + gap: 2px; + text-align: right; +} + +.topValue span:first-child { + color: var(--color-ink); + font-family: var(--font-mono); + font-size: 13px; + font-weight: 600; +} + +.topValue span:last-child { + color: var(--color-muted); + font-size: 11px; +} + +.emptyRow { + padding: 24px 14px; + color: var(--color-muted); + font-size: 13px; + text-align: center; +} + +.notes { + margin-top: 20px; + padding-top: 16px; + border-top: 1px solid var(--color-line); + color: var(--color-muted); + font-size: 12.5px; + line-height: 1.7; +} + +.notes p + p { + margin-top: 8px; +} + +.notes a { + color: var(--color-body); + text-decoration: underline; + text-underline-offset: 3px; +} + +.unavailable { + padding: 28px; + border: 1px solid var(--color-line); + border-radius: 14px; + background: var(--color-card); +} + +.unavailable h2 { + margin-top: 8px; + color: var(--color-ink); + font-size: 22px; + font-weight: 700; + letter-spacing: -0.03em; +} + +.unavailable p { + max-width: 620px; + margin-top: 8px; + color: var(--color-body); + font-size: 14px; + line-height: 1.7; +} + +@media (min-width: 900px) { + .cards { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + + .charts, + .twoCol { + grid-template-columns: 1fr 1fr; + } +} + +@media (max-width: 639px) { + .controls { + align-items: flex-start; + flex-direction: column; + } + + .cardValue { + font-size: 22px; + } +} + +@media (prefers-reduced-motion: reduce) { + .tab { + transition: none; + } +} diff --git a/app/src/components/stats/StatsChart.tsx b/app/src/components/stats/StatsChart.tsx new file mode 100644 index 00000000..0f61db0c --- /dev/null +++ b/app/src/components/stats/StatsChart.tsx @@ -0,0 +1,117 @@ +import { fmtUsd } from "@/lib/launchpad/math"; +import type { StatsDay } from "@/lib/stats/stats"; +import styles from "./Stats.module.css"; + +type Metric = "volume_usd" | "launches" | "fees_collected_usd"; + +type Props = { + points: StatsDay[]; + metric: Metric; + title: string; + caption: string; + /** `usd` adds the dollar sign and compact notation; `count` prints whole numbers. */ + kind: "usd" | "count"; +}; + +const W = 720; +const H = 238; +const LEFT = 56; +const RIGHT = 8; +const TOP = 14; +const BOTTOM = 26; +const PLOT_W = W - LEFT - RIGHT; +const PLOT_H = H - TOP - BOTTOM; + +function valueOf(point: StatsDay, metric: Metric): number { + if (metric === "volume_usd") return point.volume_usd; + if (metric === "fees_collected_usd") return point.fees_collected_usd; + return point.launches; +} + +function label(value: number, kind: Props["kind"]): string { + return kind === "usd" ? fmtUsd(value, { compact: true }) : Math.round(value).toLocaleString("en-US"); +} + +/** The disclosure promises exact figures: no compact notation and no rounding to cents. */ +function exactLabel(value: number, kind: Props["kind"]): string { + if (kind === "count") return Math.round(value).toLocaleString("en-US"); + if (!Number.isFinite(value)) return "—"; + return `$${value.toLocaleString("en-US", { maximumFractionDigits: 20 })}`; +} + +function shortDay(day: string): string { + return new Date(`${day}T00:00:00.000Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }); +} + +/** + * A server-rendered daily bar chart with the numbers in a disclosure below it. + * No client JavaScript: the SVG is the visual, the table is the exact data, and + * every bar carries its day and value in a for a pointer. Long series + * (the all-time window) share bars sub-pixel, which is honest at that scale. + */ +export default function StatsChart({ points, metric, title, caption, kind }: Props) { + if (points.length === 0) { + return <div className={styles.chartEmpty}>No indexed activity in this window yet.</div>; + } + const values = points.map((p) => Math.max(0, valueOf(p, metric))); + const max = Math.max(1, ...values); + const slot = PLOT_W / points.length; + const barWidth = Math.max(0.8, Math.min(24, slot * 0.68)); + const tickPercent = [0, 0.5, 1]; + const xLabels = [...new Set([0, Math.floor((points.length - 1) / 2), points.length - 1])]; + + return ( + <figure className={styles.chart}> + <figcaption className={styles.chartCaption}> + <span className={styles.chartTitle}>{title}</span> + <span className={styles.chartNote}>{caption}</span> + </figcaption> + <svg className={styles.plot} viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${title}. ${caption}`}> + {tickPercent.map((pct) => { + const y = TOP + PLOT_H - PLOT_H * pct; + return ( + <g key={pct}> + <line className={styles.grid} x1={LEFT} x2={W - RIGHT} y1={y} y2={y} /> + <text className={styles.axis} x={LEFT - 8} y={y + 3} textAnchor="end">{label(max * pct, kind)}</text> + </g> + ); + })} + {points.map((point, i) => { + const value = Math.max(0, valueOf(point, metric)); + const height = (value / max) * PLOT_H; + const x = LEFT + i * slot + (slot - barWidth) / 2; + return ( + <rect + key={point.day} + className={styles.bar} + x={x} + y={TOP + PLOT_H - height} + width={barWidth} + height={height} + rx={Math.min(2, barWidth / 2)} + > + <title>{`${point.day}: ${label(value, kind)}`} + + ); + })} + {xLabels.map((i) => ( + + {shortDay(points[i].day)} + + ))} + +
+ View daily figures +
+ + + + + {points.map((point) => )} + +
{title}
Day (UTC){title}
{point.day}{exactLabel(valueOf(point, metric), kind)}
+
+
+ + ); +} diff --git a/app/src/lib/db-mock.ts b/app/src/lib/db-mock.ts index f87c87c7..7ec51dc6 100644 --- a/app/src/lib/db-mock.ts +++ b/app/src/lib/db-mock.ts @@ -22,8 +22,12 @@ type MockState = { // unreachable transport, so the RPC-outage path is exercised through viem // itself rather than a hand-rolled stub. transportOutage: boolean; + // When set, maybeDb() reports an unconfigured database, so readers take their unavailable/failure path. + dbUnavailable: boolean; // What getLaunchTotals' one aggregation over bb_launches returns: a row per (chain, quote). launchTotalsRows: { chain_id: number; quote: string; launches: bigint; trades: bigint; volume: string; burned: string; creators: string; volume_usd?: number; collected_usd?: number; burned_usd?: number; volume_unpriced?: string; collected_unpriced?: string; burned_unpriced?: string }[]; + // What /api/stats' top-launches read returns (both the windowed and all-time queries). + statsTopRows: { chain_id: number; token: string; name: string; symbol: string; trades: number; volume_usd: number; holders: number; holders_synced_block: bigint | null; block_time: string }[]; // What the B20 node (chain-mock's b20Client) answers to totalSupply(), per address; "fail" = that call fails, null = the node is down. b20Supply: Record | null; b20SupplyReads: number; @@ -43,7 +47,9 @@ export function resetMock() { verifyShouldThrow: false, verifyResult: true, transportOutage: false, + dbUnavailable: false, launchTotalsRows: [], + statsTopRows: [], b20Supply: null, b20SupplyReads: 0, }; @@ -101,6 +107,11 @@ function fakeDb(strings: TemplateStringsArray, ...values: unknown[]): Promise Promise) => { +(fakeDb as any).begin = async (options: unknown, fn?: (tx: any) => Promise) => { const m = getMock(); const snap = snapshot(m); + const run = typeof options === "function" ? options : fn!; // postgres.js begin(options, fn) or begin(fn) try { - return await fn(fakeDb); + return await run(fakeDb); } catch (e) { restore(m, snap); throw e; @@ -145,7 +157,7 @@ function fakeDb(strings: TemplateStringsArray, ...values: unknown[]): Promise { test("static sitemap covers every indexable route and skips /admin and /me", () => { const paths = STATIC_SITEMAP_ROUTES.map((r) => r.path); - for (const p of ["/", "/launch", "/base", "/robinhood", "/arc", "/feed", "/rules", "/about", "/agents"]) { + for (const p of ["/", "/launch", "/base", "/robinhood", "/arc", "/feed", "/stats", "/rules", "/about", "/agents"]) { assert.ok(paths.includes(p), `missing ${p}`); } assert.ok(!paths.includes("/admin"), "/admin must stay out of the sitemap"); diff --git a/app/src/lib/seo.ts b/app/src/lib/seo.ts index 00da023c..8431d56a 100644 --- a/app/src/lib/seo.ts +++ b/app/src/lib/seo.ts @@ -49,6 +49,7 @@ export const STATIC_SITEMAP_ROUTES: StaticRoute[] = [ { path: "/launch", changeFrequency: "weekly", priority: 0.8 }, ...CHAIN_KEYS.map((chain): StaticRoute => ({ path: chainLandingPath(chain), changeFrequency: "hourly", priority: 0.8 })), { path: "/feed", changeFrequency: "hourly", priority: 0.7 }, + { path: "/stats", changeFrequency: "hourly", priority: 0.7 }, { path: "/pairs", changeFrequency: "daily", priority: 0.6 }, { path: "/rules", changeFrequency: "monthly", priority: 0.6 }, { path: "/about", changeFrequency: "monthly", priority: 0.6 }, diff --git a/app/src/lib/stats/server.test.ts b/app/src/lib/stats/server.test.ts new file mode 100644 index 00000000..dccb666e --- /dev/null +++ b/app/src/lib/stats/server.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { getMock, resetMock } from "@/lib/db-mock"; +import { SYNCED_FOREVER } from "@/lib/launchpad/holders"; +import { getProtocolStats } from "./server.ts"; + +const TOKEN = `0x${"ab".repeat(20)}`; +const row = (name: string, holders: number, holders_synced_block: bigint | null) => ({ + chain_id: 8453, + token: TOKEN, + name, + symbol: name.toUpperCase(), + trades: 3, + volume_usd: 100, + holders, + holders_synced_block, + block_time: "2026-11-01T00:00:00.000Z", +}); + +beforeEach(() => resetMock()); + +test("top launches report holders only after the transfer backfill completes, in both windows", async () => { + getMock().statsTopRows = [row("synced", 0, SYNCED_FOREVER), row("indexing", 3, 1_000_101n), row("unstarted", 9, null)]; + for (const window of ["7d", "all"] as const) { + const stats = await getProtocolStats({ window, now: Date.parse("2026-11-13T12:00:00.000Z") }); + assert.deepEqual( + stats.top.map((t) => t.holders), + [0, null, null], + `${window}: a partial backfill is not a count of zero`, + ); + } +}); diff --git a/app/src/lib/stats/server.ts b/app/src/lib/stats/server.ts new file mode 100644 index 00000000..27f3ea34 --- /dev/null +++ b/app/src/lib/stats/server.ts @@ -0,0 +1,288 @@ +import "server-only"; +import { CHAIN_KEYS, chainIdOf, chainKeyOf, type ChainKey } from "@/lib/chainPublic"; +import { maybeDb, type Db } from "@/lib/db"; +import { SYNCED_FOREVER } from "@/lib/launchpad/holders"; +import { memo } from "@/lib/launchpad/memo"; +import { + DEFAULT_STATS_WINDOW, + emptyStatsDay, + fillStatsSeries, + statsTotals, + utcDay, + windowStartDay, + type ProtocolStats, + type StatsChain, + type StatsDay, + type StatsTopLaunch, + type StatsTotals, + type StatsWindow, +} from "./stats.ts"; + +type LaunchAgg = { chain_id: number | null; launches: number; launchers: number }; +type SwapAgg = { chain_id: number | null; trades: number; traders: number; unpriced_trades: number; volume_usd: number }; +type FeeAgg = { chain_id: number | null; collected_usd: number; burned_usd: number; unpriced_fee_events: number }; + +type LaunchDay = { day: string; launches: number; launchers: number }; +type SwapDay = { day: string; trades: number; traders: number; unpriced_trades: number; volume_usd: number }; +type FeeDay = { day: string; fees_collected_usd: number; fees_burned_usd: number; unpriced_fee_events: number }; + +type TopRaw = { + chain_id: number; + token: string; + name: string; + symbol: string; + trades: number; + volume_usd: number; + holders: number; + holders_synced_block: bigint | null; + block_time: string; +}; + +function zeroTotals(): StatsTotals { + return statsTotals({ + launches: 0, + launchers: 0, + trades: 0, + traders: 0, + volume_usd: 0, + fees_collected_usd: 0, + fees_burned_usd: 0, + unpriced_trades: 0, + unpriced_fee_events: 0, + }); +} + +function emptyStats(window: StatsWindow, chain: ChainKey | null, now: number, available: boolean): ProtocolStats { + const chains = chain ? [chain] : CHAIN_KEYS; + return { + window, + chain, + available, + since: windowStartDay(window, now), + until: utcDay(now), + generated_at: new Date(now).toISOString(), + totals: zeroTotals(), + by_chain: chains.map((c): StatsChain => ({ chain: c, ...zeroTotals() })), + series: [], + top: [], + }; +} + +function findAgg(rows: readonly T[], chain: ChainKey | null): T | undefined { + const id = chain ? chainIdOf(chain) : null; + return rows.find((row) => row.chain_id === id); +} + +function chainAgg(rows: readonly T[], chain: ChainKey): T | undefined { + return rows.find((row) => row.chain_id === chainIdOf(chain)); +} + +function topLaunch(row: TopRaw): StatsTopLaunch | null { + const chain = chainKeyOf(row.chain_id); + if (!chain) return null; + return { + chain, + token: String(row.token).toLowerCase(), + name: String(row.name), + symbol: String(row.symbol), + trades: Number(row.trades), + volume_usd: Number(row.volume_usd) || 0, + // The same completion marker the watchlist uses: an unfinished backfill is not a holder count of zero. + holders: row.holders_synced_block !== null && BigInt(row.holders_synced_block) === SYNCED_FOREVER ? Number(row.holders) : null, + launched_at: row.block_time, + }; +} + +/** + * Protocol aggregates for the stats page and `/api/stats`. + * + * Three aggregate reads (launches, swaps, fees) each include the per-chain rows + * and the global row in one `GROUPING SETS` pass, plus one daily series per + * table and one top-launches read. Every USD sum is the stored trade-time value; + * rows with no price for their hour are counted, never back-filled at today's + * price. A read failure returns `available: false` with empty shapes instead of + * taking the page down. + */ +export async function getProtocolStats(opts: { window?: StatsWindow; chain?: ChainKey | null; now?: number } = {}): Promise { + const window = opts.window ?? DEFAULT_STATS_WINDOW; + const chain = opts.chain ?? null; + const now = opts.now ?? Date.now(); + const db = maybeDb(); + if (!db) return emptyStats(window, chain, now, false); + + const startDay = windowStartDay(window, now); + const since = startDay ? `${startDay}T00:00:00.000Z` : null; + const until = utcDay(now); + // The exported series ends at `until`. Bound every read at the next UTC midnight so an event committed just after + // the request started cannot land in the totals while falling outside the days the response exports. + const untilExclusive = `${new Date(Date.parse(`${until}T00:00:00.000Z`) + 86_400_000).toISOString().slice(0, 10)}T00:00:00.000Z`; + + const readRows = async (q: Db) => { + const launchWindow = since ? q`AND block_time >= ${since}::timestamptz AND block_time < ${untilExclusive}::timestamptz` : q`AND block_time < ${untilExclusive}::timestamptz`; + const swapWindow = since ? q`AND block_time >= ${since}::timestamptz AND block_time < ${untilExclusive}::timestamptz` : q`AND block_time < ${untilExclusive}::timestamptz`; + const feeWindow = since ? q`AND f.block_time >= ${since}::timestamptz AND f.block_time < ${untilExclusive}::timestamptz` : q`AND f.block_time < ${untilExclusive}::timestamptz`; + const launchChain = chain ? q`AND chain_id = ${chainIdOf(chain)}` : q``; + const swapChain = chain ? q`AND chain_id = ${chainIdOf(chain)}` : q``; + const feeChain = chain ? q`AND f.chain_id = ${chainIdOf(chain)}` : q``; + const topSince = since ? q`AND s.block_time >= ${since}::timestamptz AND s.block_time < ${untilExclusive}::timestamptz` : q``; + const topUntil = q`AND block_time < ${untilExclusive}::timestamptz`; + return Promise.all([ + q` + SELECT chain_id, count(*)::int AS launches, count(DISTINCT launcher)::int AS launchers + FROM bb_launches + WHERE true ${launchChain} ${launchWindow} + GROUP BY GROUPING SETS ((chain_id), ())`, + q` + SELECT chain_id, count(*)::int AS trades, count(DISTINCT trader)::int AS traders, + count(*) FILTER (WHERE usd IS NULL)::int AS unpriced_trades, + coalesce(sum(usd), 0)::float8 AS volume_usd + FROM bb_launch_swaps + WHERE true ${swapChain} ${swapWindow} + GROUP BY GROUPING SETS ((chain_id), ())`, + q` + SELECT f.chain_id, + coalesce(sum(f.usd) FILTER (WHERE f.kind = 'collected'), 0)::float8 AS collected_usd, + coalesce(sum(f.usd) FILTER (WHERE f.kind = 'burned'), 0)::float8 AS burned_usd, + count(*) FILTER (WHERE f.usd IS NULL AND (f.kind = 'collected' OR (f.kind = 'burned' AND f.currency = l.quote)))::int AS unpriced_fee_events + FROM bb_launch_fee_events f + LEFT JOIN bb_launches l ON l.chain_id = f.chain_id AND l.token = f.token + WHERE f.kind IN ('collected', 'burned') ${feeChain} ${feeWindow} + GROUP BY GROUPING SETS ((f.chain_id), ())`, + q` + SELECT to_char(date_trunc('day', block_time AT TIME ZONE 'UTC'), 'YYYY-MM-DD') AS day, + count(*)::int AS launches, count(DISTINCT launcher)::int AS launchers + FROM bb_launches + WHERE true ${launchChain} ${launchWindow} + GROUP BY 1 ORDER BY 1`, + q` + SELECT to_char(date_trunc('day', block_time AT TIME ZONE 'UTC'), 'YYYY-MM-DD') AS day, + count(*)::int AS trades, count(DISTINCT trader)::int AS traders, + count(*) FILTER (WHERE usd IS NULL)::int AS unpriced_trades, + coalesce(sum(usd), 0)::float8 AS volume_usd + FROM bb_launch_swaps + WHERE true ${swapChain} ${swapWindow} + GROUP BY 1 ORDER BY 1`, + q` + SELECT to_char(date_trunc('day', f.block_time AT TIME ZONE 'UTC'), 'YYYY-MM-DD') AS day, + coalesce(sum(f.usd) FILTER (WHERE f.kind = 'collected'), 0)::float8 AS fees_collected_usd, + coalesce(sum(f.usd) FILTER (WHERE f.kind = 'burned'), 0)::float8 AS fees_burned_usd, + count(*) FILTER (WHERE f.usd IS NULL AND (f.kind = 'collected' OR (f.kind = 'burned' AND f.currency = l.quote)))::int AS unpriced_fee_events + FROM bb_launch_fee_events f + LEFT JOIN bb_launches l ON l.chain_id = f.chain_id AND l.token = f.token + WHERE f.kind IN ('collected', 'burned') ${feeChain} ${feeWindow} + GROUP BY 1 ORDER BY 1`, + since + ? q` + SELECT s.chain_id, s.token, l.name, l.symbol, count(*)::int AS trades, + coalesce(sum(s.usd), 0)::float8 AS volume_usd, l.holders, l.holders_synced_block, l.block_time + FROM bb_launch_swaps s + JOIN bb_launches l ON l.chain_id = s.chain_id AND l.token = s.token + WHERE true ${topSince} ${chain ? q`AND s.chain_id = ${chainIdOf(chain)}` : q``} + GROUP BY s.chain_id, s.token, l.name, l.symbol, l.holders, l.holders_synced_block, l.block_time + ORDER BY volume_usd DESC, trades DESC + LIMIT 10` + : q` + SELECT chain_id, token, name, symbol, (buys + sells)::int AS trades, + volume_usd::float8 AS volume_usd, holders, holders_synced_block, block_time + FROM bb_launches + WHERE true ${launchChain} ${topUntil} + ORDER BY volume_usd DESC, trades DESC + LIMIT 10`, + ]); + }; + + try { + // One REPEATABLE READ snapshot for the aggregates and the daily series: a swap committing mid-read cannot show + // in one figure but not the other. Every query goes through the transaction handle, never the pool. + const [launchAgg, swapAgg, feeAgg, launchDays, swapDays, feeDays, topRaw] = await db.begin( + "isolation level repeatable read read only", + (tx) => readRows(tx as unknown as Db), + ); + + const globalLaunch = findAgg(launchAgg, null); + const globalSwap = findAgg(swapAgg, null); + const globalFee = findAgg(feeAgg, null); + const totals = statsTotals({ + launches: Number(globalLaunch?.launches ?? 0), + launchers: Number(globalLaunch?.launchers ?? 0), + trades: Number(globalSwap?.trades ?? 0), + traders: Number(globalSwap?.traders ?? 0), + volume_usd: Number(globalSwap?.volume_usd ?? 0), + fees_collected_usd: Number(globalFee?.collected_usd ?? 0), + fees_burned_usd: Number(globalFee?.burned_usd ?? 0), + unpriced_trades: Number(globalSwap?.unpriced_trades ?? 0), + unpriced_fee_events: Number(globalFee?.unpriced_fee_events ?? 0), + }); + + const chains = chain ? [chain] : CHAIN_KEYS; + const by_chain = chains.map((c): StatsChain => { + const l = chainAgg(launchAgg, c); + const s = chainAgg(swapAgg, c); + const f = chainAgg(feeAgg, c); + return { + chain: c, + ...statsTotals({ + launches: Number(l?.launches ?? 0), + launchers: Number(l?.launchers ?? 0), + trades: Number(s?.trades ?? 0), + traders: Number(s?.traders ?? 0), + volume_usd: Number(s?.volume_usd ?? 0), + fees_collected_usd: Number(f?.collected_usd ?? 0), + fees_burned_usd: Number(f?.burned_usd ?? 0), + unpriced_trades: Number(s?.unpriced_trades ?? 0), + unpriced_fee_events: Number(f?.unpriced_fee_events ?? 0), + }), + }; + }); + + const byDay = new Map(); + const dayOf = (day: string): StatsDay => { + const hit = byDay.get(day); + if (hit) return hit; + const fresh = emptyStatsDay(day); + byDay.set(day, fresh); + return fresh; + }; + for (const row of launchDays) { + const d = dayOf(row.day); + d.launches = Number(row.launches); + d.launchers = Number(row.launchers); + } + for (const row of swapDays) { + const d = dayOf(row.day); + d.trades = Number(row.trades); + d.traders = Number(row.traders); + d.volume_usd = Number(row.volume_usd); + d.unpriced_trades = Number(row.unpriced_trades); + } + for (const row of feeDays) { + const d = dayOf(row.day); + d.fees_collected_usd = Number(row.fees_collected_usd); + d.fees_burned_usd = Number(row.fees_burned_usd); + d.unpriced_fee_events = Number(row.unpriced_fee_events); + } + const series = fillStatsSeries([...byDay.values()].sort((a, b) => a.day.localeCompare(b.day)), startDay, until); + const top = topRaw.map(topLaunch).filter((row): row is StatsTopLaunch => row !== null); + + return { + window, + chain, + available: true, + since: startDay ?? series[0]?.day ?? null, + until, + generated_at: new Date(now).toISOString(), + totals, + by_chain, + series, + top, + }; + } catch (error) { + console.warn("[stats] aggregate read failed:", error instanceof Error ? error.message : error); + return emptyStats(window, chain, now, false); + } +} + +/** The page and the API share one 30 s memo per window/chain. */ +export function getProtocolStatsCached(window: StatsWindow, chain: ChainKey | null): Promise { + return memo(`stats:${window}:${chain ?? "all"}`, 30_000, () => getProtocolStats({ window, chain })); +} diff --git a/app/src/lib/stats/stats.test.ts b/app/src/lib/stats/stats.test.ts new file mode 100644 index 00000000..251aa91c --- /dev/null +++ b/app/src/lib/stats/stats.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + dayRange, + emptyStatsDay, + fillStatsSeries, + parseStatsChain, + parseStatsFormat, + parseStatsWindow, + statsCsv, + statsHref, + statsTotals, + utcDay, + windowStartDay, + type ProtocolStats, + type StatsDay, +} from "./stats.ts"; + +const NOW = Date.UTC(2026, 10, 13, 12, 0, 0); // 2026-11-13T12:00:00Z + +test("parseStatsWindow accepts only the four windows and keeps the caller's fallback", () => { + assert.equal(parseStatsWindow("7d"), "7d"); + assert.equal(parseStatsWindow("30d"), "30d"); + assert.equal(parseStatsWindow("90d"), "90d"); + assert.equal(parseStatsWindow("all"), "all"); + assert.equal(parseStatsWindow("1y"), "30d"); + assert.equal(parseStatsWindow(null), "30d"); + assert.equal(parseStatsWindow("nope", "7d"), "7d"); +}); + +test("parseStatsChain and parseStatsFormat reject everything they do not know", () => { + assert.equal(parseStatsChain("base"), "base"); + assert.equal(parseStatsChain("elysium"), "elysium"); + assert.equal(parseStatsChain("ethereum"), null); + assert.equal(parseStatsChain(null), null); + assert.equal(parseStatsFormat("csv"), "csv"); + assert.equal(parseStatsFormat("JSON"), "json"); + assert.equal(parseStatsFormat(null), "json"); +}); + +test("windowStartDay includes today and the days before it", () => { + assert.equal(windowStartDay("7d", NOW), "2026-11-07"); + assert.equal(windowStartDay("30d", NOW), "2026-10-15"); + assert.equal(windowStartDay("90d", NOW), "2026-08-16"); + assert.equal(windowStartDay("all", NOW), null); + assert.equal(utcDay(NOW), "2026-11-13"); +}); + +test("dayRange is inclusive, finite and bounded", () => { + assert.deepEqual(dayRange("2026-11-07", "2026-11-09"), ["2026-11-07", "2026-11-08", "2026-11-09"]); + assert.deepEqual(dayRange("2026-11-09", "2026-11-07"), []); + assert.deepEqual(dayRange("junk", "2026-11-09"), []); +}); + +test("fillStatsSeries leaves missing days at zero and keeps the values it has", () => { + const a: StatsDay = { ...emptyStatsDay("2026-11-07"), launches: 2, launchers: 1, trades: 5, traders: 3, volume_usd: 100, fees_collected_usd: 4, fees_burned_usd: 1, unpriced_trades: 1 }; + const b: StatsDay = { ...emptyStatsDay("2026-11-09"), launches: 1, launchers: 1 }; + const out = fillStatsSeries([a, b], "2026-11-07", "2026-11-10"); + assert.deepEqual(out.map((d) => d.day), ["2026-11-07", "2026-11-08", "2026-11-09", "2026-11-10"]); + assert.deepEqual(out[0], a); + assert.deepEqual(out[1], emptyStatsDay("2026-11-08")); + assert.deepEqual(out[2], b); + assert.deepEqual(out[3], emptyStatsDay("2026-11-10")); +}); + +test("fillStatsSeries with no start day (all) begins at the first row", () => { + const a = { ...emptyStatsDay("2026-10-01"), launches: 1 }; + const b = { ...emptyStatsDay("2026-10-03"), launches: 1 }; + assert.deepEqual(fillStatsSeries([b, a], null, "2026-10-04").map((d) => d.day), ["2026-10-01", "2026-10-02", "2026-10-03", "2026-10-04"]); + assert.deepEqual(fillStatsSeries([], null, "2026-10-04"), []); + assert.deepEqual(fillStatsSeries([a], "2026-10-02", "2026-10-04"), [emptyStatsDay("2026-10-02"), emptyStatsDay("2026-10-03"), emptyStatsDay("2026-10-04")]); +}); + +test("statsTotals derives creator fees and the partial-USD flag", () => { + const totals = statsTotals({ + launches: 3, + launchers: 2, + trades: 10, + traders: 4, + volume_usd: 1_000, + fees_collected_usd: 30, + fees_burned_usd: 12, + unpriced_trades: 0, + unpriced_fee_events: 0, + }); + assert.equal(totals.fees_to_creators_usd, 18); + assert.equal(totals.usd_partial, false); + assert.equal(statsTotals({ ...totals, unpriced_trades: 1 }).usd_partial, true); + assert.equal(statsTotals({ ...totals, unpriced_fee_events: 1 }).usd_partial, true); +}); + +test("statsCsv is one header and one machine-readable row per day", () => { + const day = { ...emptyStatsDay("2026-11-12"), launches: 2, launchers: 1, trades: 5, traders: 3, volume_usd: 1234.5, fees_collected_usd: 4, fees_burned_usd: 1.25, unpriced_trades: 1 }; + const stats: ProtocolStats = { + window: "7d", + chain: "base", + available: true, + since: "2026-11-12", + until: "2026-11-13", + generated_at: "2026-11-13T12:00:00.000Z", + totals: statsTotals(day), + by_chain: [{ chain: "base", ...statsTotals(day) }], + series: [day], + top: [], + }; + const csv = statsCsv(stats); + assert.equal(csv, "chain,day,launches,launchers,trades,traders,volume_usd,fees_collected_usd,fees_burned_usd,unpriced_trades,unpriced_fee_events\nbase,2026-11-12,2,1,5,3,1234.5,4,1.25,1,0\n"); + const allLines = statsCsv({ ...stats, chain: null }).trimEnd().split("\n"); + assert.match(allLines[1], /^all,2026-11-12,/); +}); + +test("statsHref keeps the default URL and encodes only real filters", () => { + assert.equal(statsHref("30d", null), "/stats"); + assert.equal(statsHref("7d", null), "/stats?window=7d"); + assert.equal(statsHref("30d", "base"), "/stats?chain=base"); + assert.equal(statsHref("90d", "robinhood"), "/stats?window=90d&chain=robinhood"); +}); diff --git a/app/src/lib/stats/stats.ts b/app/src/lib/stats/stats.ts new file mode 100644 index 00000000..471340db --- /dev/null +++ b/app/src/lib/stats/stats.ts @@ -0,0 +1,163 @@ +import { isChainKey, type ChainKey } from "../chainKeys.ts"; + +/** + * Pure helpers for the public protocol stats. No DB, no Next.js: `stats.test.ts` + * loads this directly, and the server module and the page share the same + * window parsing, day buckets and CSV so the API and the page cannot drift. + * + * Every USD figure here is trade-time USD: the value stored on each swap or fee + * event from the quote's price in that event's own UTC hour. An event with no + * price for its hour is excluded and counted (`unpriced_*`), never valued at + * today's price. That is the honest figure for a chart; the home page totals + * additionally fall back to the current price for those events. + */ + +export const STATS_WINDOWS = ["7d", "30d", "90d", "all"] as const; +export type StatsWindow = (typeof STATS_WINDOWS)[number]; +export const DEFAULT_STATS_WINDOW: StatsWindow = "30d"; + +export type StatsFormat = "json" | "csv"; + +export function parseStatsWindow(raw: unknown, fallback: StatsWindow = DEFAULT_STATS_WINDOW): StatsWindow { + return typeof raw === "string" && (STATS_WINDOWS as readonly string[]).includes(raw) ? (raw as StatsWindow) : fallback; +} + +export function parseStatsChain(raw: unknown): ChainKey | null { + return isChainKey(raw) ? raw : null; +} + +export function parseStatsFormat(raw: unknown): StatsFormat { + return raw === "csv" ? "csv" : "json"; +} + +const DAY_MS = 86_400_000; + +/** The UTC day of a timestamp, `YYYY-MM-DD`. */ +export function utcDay(ms: number): string { + return new Date(ms).toISOString().slice(0, 10); +} + +/** Midnight UTC of `day`, as a `YYYY-MM-DD` string that is safe to parse. */ +export function dayStart(day: string): number { + return Date.parse(`${day}T00:00:00.000Z`); +} + +/** + * First day in the window, or null for `all` (the first day with any data). + * Windows include today: `7d` is today and the six days before it. + */ +export function windowStartDay(window: StatsWindow, now = Date.now()): string | null { + if (window === "all") return null; + const days = window === "7d" ? 7 : window === "30d" ? 30 : 90; + return utcDay(dayStart(utcDay(now)) - (days - 1) * DAY_MS); +} + +/** Inclusive list of UTC days. Bounded so a corrupt timestamp cannot allocate forever. */ +export function dayRange(fromDay: string, toDay: string): string[] { + const from = dayStart(fromDay); + const to = dayStart(toDay); + if (!Number.isFinite(from) || !Number.isFinite(to) || from > to) return []; + const days: string[] = []; + for (let t = from; t <= to && days.length < 3_660; t += DAY_MS) days.push(utcDay(t)); + return days; +} + +export type StatsDay = { + day: string; + launches: number; + launchers: number; + trades: number; + traders: number; + volume_usd: number; + fees_collected_usd: number; + fees_burned_usd: number; + unpriced_trades: number; + unpriced_fee_events: number; +}; + +export type StatsTotals = Omit & { + fees_to_creators_usd: number; + /** True when at least one trade or quote-side fee has no trade-time USD and is left out of the USD sums. */ + usd_partial: boolean; +}; + +export type StatsChain = StatsTotals & { chain: ChainKey }; + +export type StatsTopLaunch = { + chain: ChainKey; + token: string; + name: string; + symbol: string; + trades: number; + volume_usd: number; + /** null while the launch's transfer history is still indexing: a partial count is not a count of zero. */ + holders: number | null; + launched_at: string; +}; + +export type ProtocolStats = { + window: StatsWindow; + chain: ChainKey | null; + /** False when DATABASE_URL is unset or the aggregate read failed; the shapes are then empty, not zero facts. */ + available: boolean; + since: string | null; + until: string; + generated_at: string; + totals: StatsTotals; + by_chain: StatsChain[]; + series: StatsDay[]; + top: StatsTopLaunch[]; +}; + +export function emptyStatsDay(day: string): StatsDay { + return { + day, + launches: 0, + launchers: 0, + trades: 0, + traders: 0, + volume_usd: 0, + fees_collected_usd: 0, + fees_burned_usd: 0, + unpriced_trades: 0, + unpriced_fee_events: 0, + }; +} + +/** + * Fill a day-by-day series from `fromDay` through `toDay`, leaving gaps at zero. + * With `fromDay=null` (the `all` window) the series starts at its first row; + * an empty series stays empty. Rows outside the range are ignored. + */ +export function fillStatsSeries(rows: readonly StatsDay[], fromDay: string | null, toDay: string): StatsDay[] { + const byDay = new Map(rows.map((row) => [row.day, row])); + const first = fromDay ?? rows.reduce((min, row) => (min === null || row.day < min ? row.day : min), null); + if (first === null || first > toDay) return []; + return dayRange(first, toDay).map((day) => byDay.get(day) ?? emptyStatsDay(day)); +} + +/** A totals row from a global aggregate; the caller supplies the distinct-wallet counts. */ +export function statsTotals(input: Omit): StatsTotals { + return { + ...input, + fees_to_creators_usd: input.fees_collected_usd - input.fees_burned_usd, + usd_partial: input.unpriced_trades > 0 || input.unpriced_fee_events > 0, + }; +} + +/** The CSV served by `/api/stats?format=csv`: one row per UTC day. */ +export function statsCsv(stats: ProtocolStats): string { + const header = "chain,day,launches,launchers,trades,traders,volume_usd,fees_collected_usd,fees_burned_usd,unpriced_trades,unpriced_fee_events"; + const chain = stats.chain ?? "all"; + const rows = stats.series.map((d) => [chain, d.day, d.launches, d.launchers, d.trades, d.traders, d.volume_usd, d.fees_collected_usd, d.fees_burned_usd, d.unpriced_trades, d.unpriced_fee_events].join(",")); + return `${[header, ...rows].join("\n")}\n`; +} + +/** `/stats` with only the parameters that differ from the default. */ +export function statsHref(window: StatsWindow, chain: ChainKey | null): string { + const params = new URLSearchParams(); + if (window !== DEFAULT_STATS_WINDOW) params.set("window", window); + if (chain) params.set("chain", chain); + const query = params.toString(); + return query ? `/stats?${query}` : "/stats"; +} diff --git a/docs/stats.md b/docs/stats.md new file mode 100644 index 00000000..bddd55a4 --- /dev/null +++ b/docs/stats.md @@ -0,0 +1,114 @@ +# Protocol stats + +`/stats` is the public protocol page; `/api/stats` is the same aggregate as JSON or CSV. Both read the site's Postgres +index of factory, locker and Uniswap v4 PoolManager events. The chain is the source of truth; the index lags by a few +blocks. + +``` +GET /api/stats?window=7d|30d|90d|all&chain=base|robinhood|arc|elysium&format=json|csv +``` + +- `window` defaults to `30d`. +- `chain` is optional; omitted means every configured chain. +- `format=csv` returns the daily series as `text/csv` with a filename. The default is JSON. +- The endpoint is `no-store`; the server memoizes one read per window/chain for 30 seconds. +- `available: false` means `DATABASE_URL` is unset or the aggregate read failed. The empty shapes are not zero facts. + +## What is counted + +| field | source | meaning | +| --- | --- | --- | +| `launches` | `bb_launches` | LaunchFactory launches whose `block_time` is in the window | +| `launchers` | `bb_launches` | Distinct launcher wallets | +| `trades` | `bb_launch_swaps` | Indexed PoolManager swaps | +| `traders` | `bb_launch_swaps` | Distinct `trader` values; unknown traders are not counted | +| `volume_usd` | `bb_launch_swaps.usd` | Sum of trade-time USD | +| `fees_collected_usd` | `bb_launch_fee_events` (`collected`) | Quote-side fees collected | +| `fees_burned_usd` | `bb_launch_fee_events` (`burned`) | Quote-side fees burned | +| `fees_to_creators_usd` | derived | `collected - burned` | +| `unpriced_trades` | `bb_launch_swaps` | Trades with no USD price for their own hour | +| `unpriced_fee_events` | `bb_launch_fee_events` | Quote-side fee events with no USD price for their own hour | +| `usd_partial` | derived | True when either unpriced count is above zero | + +`fees_burned_usd` only includes burns in the launch's quote currency. A burn of the launched token has no USD value +here; it is still in the raw on-chain events. + +## Trade-time USD + +USD is fixed at each event's own UTC hour from `bb_quote_usd_hourly`: the live price the indexer saw during that hour, +or a historical close filled in by `scripts/usd-backfill.ts`. It is not "today's price applied to old volume". Events +with no price for their hour are excluded from the USD sums and counted in `unpriced_*`; the page shows a warning when +that happens. + +The home page hero uses the same stored trade-time values, but additionally falls back to the current quote price for +events with no hourly value. That makes the hero's all-time USD figure slightly more complete than `/stats` when a +feed was down. The difference is exactly the `unpriced_*` counts. + +## Response shape + +```json +{ + "window": "30d", + "chain": null, + "available": true, + "since": "2026-10-15", + "until": "2026-11-13", + "generated_at": "2026-11-13T12:00:00.000Z", + "totals": { + "launches": 0, + "launchers": 0, + "trades": 0, + "traders": 0, + "volume_usd": 0, + "fees_collected_usd": 0, + "fees_burned_usd": 0, + "fees_to_creators_usd": 0, + "unpriced_trades": 0, + "unpriced_fee_events": 0, + "usd_partial": false + }, + "by_chain": [{ "chain": "base", "launches": 0 }], + "series": [{ "day": "2026-10-15", "launches": 0 }], + "top": [{ "chain": "base", "token": "0x…", "name": "…", "symbol": "…", "trades": 0, "volume_usd": 0, "holders": 0, "launched_at": "…" }] +} +``` + +`by_chain` contains every configured chain when no `chain` filter is set, and only the selected chain otherwise. +`series` is filled day by day from `since` through `until`; days with no activity are zeros, not gaps. Launches are +bucketed by launch time and trades by trade time, so a launch older than the window can still add trades and volume +to it. `top` is the ten launches with the most trade-time USD volume in the window (all-time stored volume when +`window=all`). A top launch's `holders` is `null` until its transfer backfill reaches the indexer's completion marker; +a synced launch with no holders returns `0`, not `null`. The CSV export returns `503` when the stats read is +unavailable, so a failed aggregation cannot be mistaken for an empty download. + +The CSV is the `series` only, one row per UTC day, with a `chain` column (`all` or the selected key). + +## Why these choices + +- **Facts, not scores.** There is no safety score, no ranking of "quality", no estimate for missing prices. +- **Trade-time USD.** Valuing old volume at today's price makes a chart move when the quote moves, not when people + trade. The index already stores each event's value; the stats read it rather than recomputing. +- **Day buckets are UTC.** `to_char(date_trunc('day', block_time AT TIME ZONE 'UTC'), 'YYYY-MM-DD')` in every series + query; the page labels the axis accordingly. +- **One read per window/chain.** `getProtocolStatsCached` memoizes for 30 seconds; the page and the API share the memo, + so a refresh does not multiply database queries. +- **Fail soft, but never fake zeros.** A read failure returns `available: false` and empty shapes, and the page says + so instead of drawing a zero chart. + +## Code + +- `app/src/lib/stats/stats.ts` — pure window parsing, UTC day buckets, series fill, totals derivation and CSV. +- `app/src/lib/stats/server.ts` — the three aggregate reads (`GROUPING SETS` per chain + global), daily series and top + launches; `available: false` on failure. +- `app/src/app/api/stats/route.ts` — JSON/CSV endpoint, query parsing and headers. +- `app/src/app/stats/page.tsx` — the page: cards, daily charts, per-chain table, top launches and method notes. +- `app/src/components/stats/StatsChart.tsx` — server-rendered SVG bars plus the exact figures in a disclosure. +- `app/src/lib/stats/stats.test.ts` — window, fill, CSV and URL tests. + +## Tests + +``` +cd app && npm test +``` + +The stats cases are `src/lib/stats/stats.test.ts` and `src/app/api/stats/route.test.ts`.