From 610865de6c7d0be57e4f3d80fdf2f0dce759b14b Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Fri, 13 Nov 2026 16:46:33 +0530 Subject: [PATCH 1/7] =?UTF-8?q?feat(launch-details):=20add=20per=E2=80=91l?= =?UTF-8?q?aunch=20metrics=20API=20and=20page?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add /api/launch/metrics endpoint and /launch/details page with holder distribution, trade counts, volume and fee summary. Shares 30‑second memo per launch. No new deps/env/hosts. --- app/src/app/api/launch/metrics/route.ts | 67 +++++++++++++++ app/src/app/launch/details/page.tsx | 110 ++++++++++++++++++++++++ app/src/lib/seo.ts | 1 + 3 files changed, 178 insertions(+) create mode 100644 app/src/app/api/launch/metrics/route.ts create mode 100644 app/src/app/launch/details/page.tsx diff --git a/app/src/app/api/launch/metrics/route.ts b/app/src/app/api/launch/metrics/route.ts new file mode 100644 index 00000000..4dcd3081 --- /dev/null +++ b/app/src/app/api/launch/metrics/route.ts @@ -0,0 +1,67 @@ +import { NextResponse } from "next/server"; +import { isAddress } from "viem"; +import { isChainKey } from "@/lib/chainPublic"; +import { maybeDb } from "@/lib/db"; +import { getHolderPanel } from "@/lib/launchpad/holdersServer"; +import { getSwaps } from "@/lib/launchpad/queries"; +import { memo } from "@/lib/launchpad/memo"; +import { chainIdOf } from "@/lib/chainPublic"; + +export const dynamic = "force-dynamic"; + +/** GET /api/launch/metrics?chain=base&token=0x… → per‑launch metrics (holders, trades, fees). 30‑second memo per launch. */ +export async function GET(req: Request) { + const u = new URL(req.url); + const chain = u.searchParams.get("chain"); + const token = u.searchParams.get("token"); + if (!isChainKey(chain) || !token || !isAddress(token)) return NextResponse.json({ error: "bad params" }, { status: 400 }); + try { + const db = maybeDb(); + let quoteDecimals = 18; + let feesCollectedUsd = 0; + let feesBurnedUsd = 0; + if (db) { + // Grab the launch row so we have quote_decimals and fee totals. + const launches = await db<{ + quote_decimals: number; + fees_quote_collected: string; + fees_quote_burned: string; + supply: string; + }[]>` + SELECT quote_decimals, + fees_quote_collected, + fees_quote_burned, + supply::text AS supply + FROM bb_launches + WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} + `; + if (launches.length > 0) { + const l = launches[0]; + quoteDecimals = l.quote_decimals ?? 18; + feesCollectedUsd = Number(l.fees_quote_collected ?? "0"); + feesBurnedUsd = Number(l.fees_quote_burned ?? "0"); + } + } + const panel = await memo(`metrics:${chain}:${token.toLowerCase()}`, 30_000, () => getHolderPanel(chain, token)); + if (!panel) return NextResponse.json({ error: "not found" }, { status: 404 }); + const swaps = await memo(`swaps:${chain}:${token.toLowerCase()}_metrics`, 30_000, () => getSwaps(chain, token, quoteDecimals, 50)); + const trades = swaps.length; + const volumeUsd = swaps.reduce((acc, s) => acc + Math.abs(Number(s.amount1)), 0); + const topHolders = panel.top.slice(0, 5).map((h) => ({ address: h.address, balance: h.balance, bps: h.bps })); + return NextResponse.json({ + holders: panel.holders, + supply: panel.supply ?? (quoteDecimals ? `${Number(panel.supply ?? "0") / 10 ** quoteDecimals}.0` : "0"), + quote_decimals: quoteDecimals, + topHolders, + trades, + volume_usd: volumeUsd, + fees_collected_usd: feesCollectedUsd, + fees_burned_usd: feesBurnedUsd, + top10Bps: panel.top10Bps, + poolBps: panel.poolBps, + }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + console.error("[launch] metrics failed:", err instanceof Error ? err.message : err); + return NextResponse.json({ error: "could not load metrics" }, { status: 502 }); + } +} \ No newline at end of file diff --git a/app/src/app/launch/details/page.tsx b/app/src/app/launch/details/page.tsx new file mode 100644 index 00000000..4f11addc --- /dev/null +++ b/app/src/app/launch/details/page.tsx @@ -0,0 +1,110 @@ +import type { Metadata } from "next"; +import { pageMetadata } from "@/lib/seo"; +import { useEffect, useState } from "react"; + +export const metadata: Metadata = pageMetadata({ + path: "/launch/details", + title: "Launch details", + description: "Per‑launch metrics: holders, trades, volume, fees and top holders.", +}); + +export const dynamic = "force-dynamic"; + +type LaunchMetrics = { + holders: number; + supply: string; + quote_decimals: number; + topHolders: Array<{ address: string; balance: string; bps: number }>; + trades: number; + volume_usd: number; + fees_collected_usd: number; + fees_burned_usd: number; + top10Bps: number; + poolBps: number; + token: string; + chain: string; +}; + +export default function LaunchDetailsPage() { + // Read chain and token from the URL path: /launch/details// + const pathname = window.location.pathname; + const parts = pathname.split("/").filter(Boolean); + const chain: string = parts[2] || "base"; + const token: string = parts[3] || "0x".repeat(40); + + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + async function fetchMetrics() { + const res = await fetch(`/api/launch/metrics?chain=${chain}&token=${token}`); + if (!res.ok) { + setData(null); + setLoading(false); + return; + } + const json = await res.json() as LaunchMetrics; + setData(json); + setLoading(false); + } + fetchMetrics(); + }, [chain, token]); + + if (loading) return

Loading…

; + if (!data) return

Failed to load metrics.

; + if (!data) return

No data for this launch.

; + + const fmt = (n: number | string | null) => (n == null ? "—" : Number(n).toLocaleString()); + + return ( +
+
+

+ {data.token} · {data.chain} +

+

+ Metrics for {data.token} on {data.chain} +

+
+ +
+
+
Holders
+
{fmt(data.holders)}
+
+
+
Supply
+
{fmt(Number(data.supply) / 10 ** Number(data.quote_decimals))} {data.token.substring(0, 6)}…
+
+
+
Trades (50 most recent)
+
{fmt(data.trades)}
+
+
+
Volume (USD)
+
${fmt(data.volume_usd)}
+
+
+
Fees collected (USD)
+
${fmt(data.fees_collected_usd)}
+
+
+
Fees burned (USD)
+
${fmt(data.fees_burned_usd)}
+
+
+ +
+
Top 5 holders
+
+ {data.topHolders.map((h, i) => ( +
+ {h.address.substring(0, 6)}…{h.address.substring(-4)} + {fmt(h.bps)} bps +
+ ))} +
+
+
+ ); +} \ No newline at end of file diff --git a/app/src/lib/seo.ts b/app/src/lib/seo.ts index 00da023c..2cbe0b17 100644 --- a/app/src/lib/seo.ts +++ b/app/src/lib/seo.ts @@ -47,6 +47,7 @@ export type StaticRoute = { export const STATIC_SITEMAP_ROUTES: StaticRoute[] = [ { path: "/", changeFrequency: "hourly", priority: 1 }, { path: "/launch", changeFrequency: "weekly", priority: 0.8 }, + { path: "/launch/details", changeFrequency: "monthly", priority: 0.5 }, ...CHAIN_KEYS.map((chain): StaticRoute => ({ path: chainLandingPath(chain), changeFrequency: "hourly", priority: 0.8 })), { path: "/feed", changeFrequency: "hourly", priority: 0.7 }, { path: "/pairs", changeFrequency: "daily", priority: 0.6 }, From 009eae406da8925898d8d2c5ca1ad7fd8f5b7d59 Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Fri, 13 Nov 2026 18:53:08 +0530 Subject: [PATCH 2/7] fix(launch-details): add use client directive for React hooks in app router --- app/src/app/launch/details/page.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/app/launch/details/page.tsx b/app/src/app/launch/details/page.tsx index 4f11addc..bbcf6623 100644 --- a/app/src/app/launch/details/page.tsx +++ b/app/src/app/launch/details/page.tsx @@ -1,3 +1,5 @@ +"use client"; + import type { Metadata } from "next"; import { pageMetadata } from "@/lib/seo"; import { useEffect, useState } from "react"; From 2320b79432767c9a2da1770c677b4c2ce3c09ad3 Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Fri, 13 Nov 2026 18:58:28 +0530 Subject: [PATCH 3/7] fix(launch-details): use async server component with searchParams --- app/src/app/launch/details/page.tsx | 49 +++++++++++------------------ 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/app/src/app/launch/details/page.tsx b/app/src/app/launch/details/page.tsx index bbcf6623..873b885a 100644 --- a/app/src/app/launch/details/page.tsx +++ b/app/src/app/launch/details/page.tsx @@ -1,8 +1,5 @@ -"use client"; - import type { Metadata } from "next"; import { pageMetadata } from "@/lib/seo"; -import { useEffect, useState } from "react"; export const metadata: Metadata = pageMetadata({ path: "/launch/details", @@ -27,34 +24,26 @@ type LaunchMetrics = { chain: string; }; -export default function LaunchDetailsPage() { - // Read chain and token from the URL path: /launch/details// - const pathname = window.location.pathname; - const parts = pathname.split("/").filter(Boolean); - const chain: string = parts[2] || "base"; - const token: string = parts[3] || "0x".repeat(40); - - const [data, setData] = useState(null); - const [loading, setLoading] = useState(true); - - useEffect(() => { - async function fetchMetrics() { - const res = await fetch(`/api/launch/metrics?chain=${chain}&token=${token}`); - if (!res.ok) { - setData(null); - setLoading(false); - return; - } - const json = await res.json() as LaunchMetrics; - setData(json); - setLoading(false); - } - fetchMetrics(); - }, [chain, token]); +export default async function LaunchDetailsPage( + // Search params from the URL: /launch/details?chain=&token= + // In the app router, these are passed as query parameters or route params. + // We'll use the search params approach for simplicity. + searchParams: { chain?: string; token?: string } +) { + const chain: string = searchParams.chain || "base"; + const token: string = searchParams.token || "0x".repeat(40); - if (loading) return

Loading…

; - if (!data) return

Failed to load metrics.

; - if (!data) return

No data for this launch.

; + // Fetch metrics from the API + const res = await fetch(`/api/launch/metrics?chain=${chain}&token=${token}`); + if (!res.ok) { + // Return empty state on failure + return ( +
+

Failed to load metrics.

+
+ ); + } + const data = (await res.json()) as LaunchMetrics; const fmt = (n: number | string | null) => (n == null ? "—" : Number(n).toLocaleString()); From 6cbfb2b09c13b2a1a7b1861e567197ce0cd4621e Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Fri, 13 Nov 2026 19:06:49 +0530 Subject: [PATCH 4/7] fix(launch-details): correct units and server component --- app/src/app/api/launch/metrics/route.ts | 15 +++++++++------ app/src/app/launch/details/page.tsx | 16 +++++++++++----- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/app/src/app/api/launch/metrics/route.ts b/app/src/app/api/launch/metrics/route.ts index 4dcd3081..eeb0f213 100644 --- a/app/src/app/api/launch/metrics/route.ts +++ b/app/src/app/api/launch/metrics/route.ts @@ -9,7 +9,7 @@ import { chainIdOf } from "@/lib/chainPublic"; export const dynamic = "force-dynamic"; -/** GET /api/launch/metrics?chain=base&token=0x… → per‑launch metrics (holders, trades, fees). 30‑second memo per launch. */ +/** GET /api/launch/metrics?chain=base&token=0x… → per‑launch metrics (holders, trades, volume, fees). 30‑second memo per launch. */ export async function GET(req: Request) { const u = new URL(req.url); const chain = u.searchParams.get("chain"); @@ -18,8 +18,8 @@ export async function GET(req: Request) { try { const db = maybeDb(); let quoteDecimals = 18; - let feesCollectedUsd = 0; - let feesBurnedUsd = 0; + let feesCollectedRaw = 0; + let feesBurnedRaw = 0; if (db) { // Grab the launch row so we have quote_decimals and fee totals. const launches = await db<{ @@ -38,15 +38,18 @@ export async function GET(req: Request) { if (launches.length > 0) { const l = launches[0]; quoteDecimals = l.quote_decimals ?? 18; - feesCollectedUsd = Number(l.fees_quote_collected ?? "0"); - feesBurnedUsd = Number(l.fees_quote_burned ?? "0"); + feesCollectedRaw = Number(l.fees_quote_collected ?? "0"); + feesBurnedRaw = Number(l.fees_quote_burned ?? "0"); } } const panel = await memo(`metrics:${chain}:${token.toLowerCase()}`, 30_000, () => getHolderPanel(chain, token)); if (!panel) return NextResponse.json({ error: "not found" }, { status: 404 }); const swaps = await memo(`swaps:${chain}:${token.toLowerCase()}_metrics`, 30_000, () => getSwaps(chain, token, quoteDecimals, 50)); const trades = swaps.length; - const volumeUsd = swaps.reduce((acc, s) => acc + Math.abs(Number(s.amount1)), 0); + // Volume in display units (divided by 10^quoteDecimals), matching the page's fmt() logic. + const volumeUsd = swaps.reduce((acc, s) => acc + Math.abs(Number(s.amount1)) / 10 ** quoteDecimals, 0); + const feesCollectedUsd = feesCollectedRaw / 10 ** quoteDecimals; + const feesBurnedUsd = feesBurnedRaw / 10 ** quoteDecimals; const topHolders = panel.top.slice(0, 5).map((h) => ({ address: h.address, balance: h.balance, bps: h.bps })); return NextResponse.json({ holders: panel.holders, diff --git a/app/src/app/launch/details/page.tsx b/app/src/app/launch/details/page.tsx index 873b885a..433c72ef 100644 --- a/app/src/app/launch/details/page.tsx +++ b/app/src/app/launch/details/page.tsx @@ -26,8 +26,6 @@ type LaunchMetrics = { export default async function LaunchDetailsPage( // Search params from the URL: /launch/details?chain=&token= - // In the app router, these are passed as query parameters or route params. - // We'll use the search params approach for simplicity. searchParams: { chain?: string; token?: string } ) { const chain: string = searchParams.chain || "base"; @@ -45,6 +43,14 @@ export default async function LaunchDetailsPage( } const data = (await res.json()) as LaunchMetrics; + if (!data.token || !data.chain) { + return ( +
+

No data for this launch.

+
+ ); + } + const fmt = (n: number | string | null) => (n == null ? "—" : Number(n).toLocaleString()); return ( @@ -72,15 +78,15 @@ export default async function LaunchDetailsPage(
{fmt(data.trades)}
-
Volume (USD)
+
Volume (native)
${fmt(data.volume_usd)}
-
Fees collected (USD)
+
Fees collected (native)
${fmt(data.fees_collected_usd)}
-
Fees burned (USD)
+
Fees burned (native)
${fmt(data.fees_burned_usd)}
From e064863a0d4ba3367f5fa96732f804a4c4d3615c Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Fri, 20 Nov 2026 10:25:11 +0530 Subject: [PATCH 5/7] fix(launch-details): read metrics from the launch row The details page read chain and token from the wrong place, fetched a relative URL on the server, and rendered fields the API never returned. The API queried a quote_decimals column that does not exist and reported raw quote amounts as USD. Supply was divided by the quote's decimals. Move the figures into a loader that reads the launch row, the holder panel and the stored USD fee totals. Serve the page at /launch/details//, drop the bare sitemap entry, and add unit tests for the metric rules. --- app/src/app/api/launch/metrics/route.ts | 60 +--------- .../launch/details/[chain]/[token]/page.tsx | 106 +++++++++++++++++ app/src/app/launch/details/page.tsx | 107 ------------------ app/src/lib/launchpad/metrics.test.ts | 51 +++++++++ app/src/lib/launchpad/metrics.ts | 86 ++++++++++++++ app/src/lib/launchpad/metricsServer.ts | 37 ++++++ app/src/lib/seo.ts | 1 - 7 files changed, 286 insertions(+), 162 deletions(-) create mode 100644 app/src/app/launch/details/[chain]/[token]/page.tsx delete mode 100644 app/src/app/launch/details/page.tsx create mode 100644 app/src/lib/launchpad/metrics.test.ts create mode 100644 app/src/lib/launchpad/metrics.ts create mode 100644 app/src/lib/launchpad/metricsServer.ts diff --git a/app/src/app/api/launch/metrics/route.ts b/app/src/app/api/launch/metrics/route.ts index eeb0f213..57dae98f 100644 --- a/app/src/app/api/launch/metrics/route.ts +++ b/app/src/app/api/launch/metrics/route.ts @@ -1,70 +1,22 @@ import { NextResponse } from "next/server"; import { isAddress } from "viem"; import { isChainKey } from "@/lib/chainPublic"; -import { maybeDb } from "@/lib/db"; -import { getHolderPanel } from "@/lib/launchpad/holdersServer"; -import { getSwaps } from "@/lib/launchpad/queries"; -import { memo } from "@/lib/launchpad/memo"; -import { chainIdOf } from "@/lib/chainPublic"; +import { getLaunchMetrics } from "@/lib/launchpad/metricsServer"; export const dynamic = "force-dynamic"; -/** GET /api/launch/metrics?chain=base&token=0x… → per‑launch metrics (holders, trades, volume, fees). 30‑second memo per launch. */ +/** GET /api/launch/metrics?chain=base&token=0x… → per‑launch metrics (holders, supply, trades, volume, fees). 30‑second memo per launch. */ export async function GET(req: Request) { const u = new URL(req.url); const chain = u.searchParams.get("chain"); const token = u.searchParams.get("token"); if (!isChainKey(chain) || !token || !isAddress(token)) return NextResponse.json({ error: "bad params" }, { status: 400 }); try { - const db = maybeDb(); - let quoteDecimals = 18; - let feesCollectedRaw = 0; - let feesBurnedRaw = 0; - if (db) { - // Grab the launch row so we have quote_decimals and fee totals. - const launches = await db<{ - quote_decimals: number; - fees_quote_collected: string; - fees_quote_burned: string; - supply: string; - }[]>` - SELECT quote_decimals, - fees_quote_collected, - fees_quote_burned, - supply::text AS supply - FROM bb_launches - WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} - `; - if (launches.length > 0) { - const l = launches[0]; - quoteDecimals = l.quote_decimals ?? 18; - feesCollectedRaw = Number(l.fees_quote_collected ?? "0"); - feesBurnedRaw = Number(l.fees_quote_burned ?? "0"); - } - } - const panel = await memo(`metrics:${chain}:${token.toLowerCase()}`, 30_000, () => getHolderPanel(chain, token)); - if (!panel) return NextResponse.json({ error: "not found" }, { status: 404 }); - const swaps = await memo(`swaps:${chain}:${token.toLowerCase()}_metrics`, 30_000, () => getSwaps(chain, token, quoteDecimals, 50)); - const trades = swaps.length; - // Volume in display units (divided by 10^quoteDecimals), matching the page's fmt() logic. - const volumeUsd = swaps.reduce((acc, s) => acc + Math.abs(Number(s.amount1)) / 10 ** quoteDecimals, 0); - const feesCollectedUsd = feesCollectedRaw / 10 ** quoteDecimals; - const feesBurnedUsd = feesBurnedRaw / 10 ** quoteDecimals; - const topHolders = panel.top.slice(0, 5).map((h) => ({ address: h.address, balance: h.balance, bps: h.bps })); - return NextResponse.json({ - holders: panel.holders, - supply: panel.supply ?? (quoteDecimals ? `${Number(panel.supply ?? "0") / 10 ** quoteDecimals}.0` : "0"), - quote_decimals: quoteDecimals, - topHolders, - trades, - volume_usd: volumeUsd, - fees_collected_usd: feesCollectedUsd, - fees_burned_usd: feesBurnedUsd, - top10Bps: panel.top10Bps, - poolBps: panel.poolBps, - }, { headers: { "cache-control": "no-store" } }); + const metrics = await getLaunchMetrics(chain, token); + if (!metrics) return NextResponse.json({ error: "not found" }, { status: 404 }); + return NextResponse.json(metrics, { headers: { "cache-control": "no-store" } }); } catch (err) { console.error("[launch] metrics failed:", err instanceof Error ? err.message : err); return NextResponse.json({ error: "could not load metrics" }, { status: 502 }); } -} \ No newline at end of file +} diff --git a/app/src/app/launch/details/[chain]/[token]/page.tsx b/app/src/app/launch/details/[chain]/[token]/page.tsx new file mode 100644 index 00000000..672546e9 --- /dev/null +++ b/app/src/app/launch/details/[chain]/[token]/page.tsx @@ -0,0 +1,106 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { isAddress } from "viem"; +import { CHAIN_LABELS, isChainKey, shortAddr } from "@/lib/chainPublic"; +import { fmtShare } from "@/lib/launchpad/holders"; +import { marketUsd } from "@/lib/launchpad/market-format"; +import { fmtUnitsExact } from "@/lib/launchpad/math"; +import { LAUNCH_TOKEN_DECIMALS } from "@/lib/launchpad/metrics"; +import { getLaunchMetrics } from "@/lib/launchpad/metricsServer"; +import { pageMetadata, tokenPath } from "@/lib/seo"; + +export const dynamic = "force-dynamic"; + +/** Title, description and canonical for one launch's details page. */ +export async function generateMetadata({ params }: { params: Promise<{ chain: string; token: string }> }): Promise { + const { chain, token } = await params; + if (!isChainKey(chain) || !isAddress(token)) return { title: "Launch not found" }; + const m = await getLaunchMetrics(chain, token); + if (!m) return { title: "Launch not found" }; + return pageMetadata({ + path: `/launch/details/${m.chain}/${m.token}`, + title: `${m.name} (${m.symbol}) launch details`, + description: `Holders, trades, volume and fees for ${m.name} (${m.symbol}) on ${CHAIN_LABELS[m.chain]}, read from the openlaunch indexer.`, + }); +} + +/** One launch's metrics: holders, supply, trades, volume, fees and the wallets holding most of it. */ +export default async function LaunchDetailsPage({ params }: { params: Promise<{ chain: string; token: string }> }) { + const { chain, token } = await params; + if (!isChainKey(chain) || !isAddress(token)) notFound(); + const m = await getLaunchMetrics(chain, token); + if (!m) notFound(); + + const count = (n: number) => n.toLocaleString("en-US"); + const usd = (v: number | null) => (v === null ? "—" : marketUsd(v)); + const symbol = m.symbol; + + return ( +
+
+

+ + {m.name} ({symbol}) + + + {CHAIN_LABELS[m.chain]} +

+

Launch details

+

+ {shortAddr(m.token)} · every trade, fee and holder the indexer holds for this launch +

+
+ +
+ + + + + + +
+ +
+

Top holders

+

The five largest wallets, with the pool and the protocol's own addresses left out.

+ {m.topHolders.length === 0 ? ( +

{m.synced ? "No holders yet." : "The transfer history is still indexing."}

+ ) : ( +
    + {m.topHolders.map((h, i) => ( +
  1. + + {i + 1}. {shortAddr(h.address)} + + + {fmtShare(h.bps)} + +
  2. + ))} +
+ )} +
+ +

+ The ten largest wallets hold {fmtShare(m.top10Bps)} of supply; the locked pool holds {fmtShare(m.poolBps)}.{" "} + + The full token page + {" "} + has the chart, the trades and the receipts. +

+
+ ); +} + +function Cell({ k, v, sub }: { k: string; v: string; sub: string }) { + return ( +
+
{k}
+
+ {v} + {sub} +
+
+ ); +} diff --git a/app/src/app/launch/details/page.tsx b/app/src/app/launch/details/page.tsx deleted file mode 100644 index 433c72ef..00000000 --- a/app/src/app/launch/details/page.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import type { Metadata } from "next"; -import { pageMetadata } from "@/lib/seo"; - -export const metadata: Metadata = pageMetadata({ - path: "/launch/details", - title: "Launch details", - description: "Per‑launch metrics: holders, trades, volume, fees and top holders.", -}); - -export const dynamic = "force-dynamic"; - -type LaunchMetrics = { - holders: number; - supply: string; - quote_decimals: number; - topHolders: Array<{ address: string; balance: string; bps: number }>; - trades: number; - volume_usd: number; - fees_collected_usd: number; - fees_burned_usd: number; - top10Bps: number; - poolBps: number; - token: string; - chain: string; -}; - -export default async function LaunchDetailsPage( - // Search params from the URL: /launch/details?chain=&token= - searchParams: { chain?: string; token?: string } -) { - const chain: string = searchParams.chain || "base"; - const token: string = searchParams.token || "0x".repeat(40); - - // Fetch metrics from the API - const res = await fetch(`/api/launch/metrics?chain=${chain}&token=${token}`); - if (!res.ok) { - // Return empty state on failure - return ( -
-

Failed to load metrics.

-
- ); - } - const data = (await res.json()) as LaunchMetrics; - - if (!data.token || !data.chain) { - return ( -
-

No data for this launch.

-
- ); - } - - const fmt = (n: number | string | null) => (n == null ? "—" : Number(n).toLocaleString()); - - return ( -
-
-

- {data.token} · {data.chain} -

-

- Metrics for {data.token} on {data.chain} -

-
- -
-
-
Holders
-
{fmt(data.holders)}
-
-
-
Supply
-
{fmt(Number(data.supply) / 10 ** Number(data.quote_decimals))} {data.token.substring(0, 6)}…
-
-
-
Trades (50 most recent)
-
{fmt(data.trades)}
-
-
-
Volume (native)
-
${fmt(data.volume_usd)}
-
-
-
Fees collected (native)
-
${fmt(data.fees_collected_usd)}
-
-
-
Fees burned (native)
-
${fmt(data.fees_burned_usd)}
-
-
- -
-
Top 5 holders
-
- {data.topHolders.map((h, i) => ( -
- {h.address.substring(0, 6)}…{h.address.substring(-4)} - {fmt(h.bps)} bps -
- ))} -
-
-
- ); -} \ No newline at end of file diff --git a/app/src/lib/launchpad/metrics.test.ts b/app/src/lib/launchpad/metrics.test.ts new file mode 100644 index 00000000..250ea032 --- /dev/null +++ b/app/src/lib/launchpad/metrics.test.ts @@ -0,0 +1,51 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { LAUNCH_TOKEN_DECIMALS, TOP_HOLDERS_SHOWN, launchMetrics, supplyTokens, type LaunchMetricsLaunch, type LaunchMetricsPanel } from "./metrics.ts"; + +const TOKEN = "0x" + "a".repeat(40); +/** 1e9 tokens at 18 decimals: the supply every LaunchToken has. */ +const SUPPLY = "1000000000000000000000000000"; + +const launch = (o: Partial = {}): LaunchMetricsLaunch => ({ chain: "base", token: TOKEN, name: "Test", symbol: "TEST", quote_symbol: "ETH", buys: 7, sells: 3, volume_usd: 1234.5, ...o }); + +const topN = (n: number) => Array.from({ length: n }, (_, i) => ({ address: `0x${String(i).padStart(4, "0")}${"b".repeat(36)}`, balance: "1000", bps: 500 })); + +const panel = (o: Partial = {}): LaunchMetricsPanel => ({ synced: true, holders: 42, supply: SUPPLY, top: topN(10), top10Bps: 4200, poolBps: 5800, ...o }); + +const fees = { collected_usd: 12.5, burned_usd: 3.25 }; + +test("supply is scaled by the launched token's 18 decimals, not the quote's", () => { + assert.equal(LAUNCH_TOKEN_DECIMALS, 18); + assert.equal(supplyTokens(SUPPLY), 1_000_000_000); + assert.equal(supplyTokens("1500000000000000000"), 1.5); + // the quote is USDG at 6 decimals here: the supply is the token's own and does not move with it + const m = launchMetrics(launch({ quote_symbol: "USDG" }), panel(), fees); + assert.equal(m.supply_tokens, 1_000_000_000); +}); + +test("trades are the launch's whole count, not the newest page of swaps", () => { + assert.equal(launchMetrics(launch({ buys: 7, sells: 3 }), panel(), fees).trades, 10); +}); + +test("holders are reported only once the transfer history is complete", () => { + assert.equal(launchMetrics(launch(), panel(), fees).holders, 42); + const indexing = launchMetrics(launch(), panel({ synced: false, holders: 3 }), fees); + assert.equal(indexing.holders, null, "a partial backfill is not a count of zero"); + assert.equal(indexing.synced, false); +}); + +test("volume and fees are the stored USD figures, and an unpriced launch keeps a null volume", () => { + const m = launchMetrics(launch(), panel(), fees); + assert.equal(m.volume_usd, 1234.5); + assert.equal(m.fees_collected_usd, 12.5); + assert.equal(m.fees_burned_usd, 3.25); + assert.equal(launchMetrics(launch({ volume_usd: null }), panel(), fees).volume_usd, null); +}); + +test("the top holders are the panel's first five, named as the panel names them", () => { + const m = launchMetrics(launch(), panel(), fees); + assert.equal(TOP_HOLDERS_SHOWN, 5); + assert.deepEqual(m.topHolders.map((h) => h.address), topN(5).map((h) => h.address)); + assert.equal(m.top10Bps, 4200); + assert.equal(m.poolBps, 5800); +}); diff --git a/app/src/lib/launchpad/metrics.ts b/app/src/lib/launchpad/metrics.ts new file mode 100644 index 00000000..fb0a2f7b --- /dev/null +++ b/app/src/lib/launchpad/metrics.ts @@ -0,0 +1,86 @@ +/** + * One launch's detail figures (pure; node --test loads this): holders, supply, trades, volume and fees as the launch + * details page and /api/launch/metrics report them. Derived from the launch read model (queries.ts `getLaunch`) and the + * holder panel (holdersServer.ts `getHolderPanel`); nothing here reads the database or the chain. + */ +import type { LaunchRow } from "./queries"; + +/** + * Every launch's token is a LaunchToken: a fixed supply of 1e9 tokens at 18 decimals. `bb_launches.supply` is in those + * base units, which belong to the launched token — never to the quote, whose decimals differ per quote (6 for a stable, + * 18 for ETH, HYPE or GITLAWB) and are what math.ts scales prices by, not what the supply is divided by. + */ +export const LAUNCH_TOKEN_DECIMALS = 18; + +/** How many holders the page and the API list: the panel's own top ten, trimmed. */ +export const TOP_HOLDERS_SHOWN = 5; + +/** A launch's fee totals in USD, as `bb_launches.fees_collected_usd` and `fees_burned_usd` hold them (per fee event). */ +export type LaunchFeesUsd = { collected_usd: number; burned_usd: number }; + +/** The facts these figures rest on, from the launch read model: the row itself carries everything else. */ +export type LaunchMetricsLaunch = Pick; + +/** The facts they rest on from the holder panel (holdersServer.ts `HolderPanel`). */ +export type LaunchMetricsPanel = { + /** false while the token's transfer history is still being backfilled. */ + synced: boolean; + holders: number; + supply: string; + top: readonly { address: string; balance: string; bps: number }[]; + top10Bps: number; + poolBps: number; +}; + +export type LaunchMetrics = { + chain: LaunchRow["chain"]; + token: string; + name: string; + symbol: string; + /** The launch's quote asset, which its fees are collected and burned in. */ + quote_symbol: string; + /** Distinct holders; null while the history is incomplete, because a partial count is not a count of zero. */ + holders: number | null; + synced: boolean; + /** The whole supply in tokens. Every launch has 1e9; the figure comes from the row rather than being assumed. */ + supply_tokens: number; + /** Every trade the indexer holds for this launch: buys + sells, not the newest page of them. */ + trades: number; + /** All-time volume in USD, each trade at its own hour's price; null when nothing prices the launch's quote. */ + volume_usd: number | null; + /** Collected and burned fees in USD, the quote side only, as the indexer stored them. */ + fees_collected_usd: number; + fees_burned_usd: number; + /** Share of supply in the ten largest non-system wallets, and in the locked pool, in basis points. */ + top10Bps: number; + poolBps: number; + topHolders: { address: string; balance: string; bps: number }[]; +}; + +/** A raw amount in the launched token's base units as whole tokens: exact while the integer part fits a double. */ +export function supplyTokens(raw: string): number { + const base = 10n ** BigInt(LAUNCH_TOKEN_DECIMALS); + const v = BigInt(raw); + return Number(v / base) + Number(v % base) / 10 ** LAUNCH_TOKEN_DECIMALS; +} + +/** The figures one launch's page and API report. */ +export function launchMetrics(launch: LaunchMetricsLaunch, panel: LaunchMetricsPanel, fees: LaunchFeesUsd): LaunchMetrics { + return { + chain: launch.chain, + token: launch.token, + name: launch.name, + symbol: launch.symbol, + quote_symbol: launch.quote_symbol, + holders: panel.synced ? panel.holders : null, + synced: panel.synced, + supply_tokens: supplyTokens(panel.supply), + trades: launch.buys + launch.sells, + volume_usd: launch.volume_usd, + fees_collected_usd: fees.collected_usd, + fees_burned_usd: fees.burned_usd, + top10Bps: panel.top10Bps, + poolBps: panel.poolBps, + topHolders: panel.top.slice(0, TOP_HOLDERS_SHOWN).map((h) => ({ address: h.address, balance: h.balance, bps: h.bps })), + }; +} diff --git a/app/src/lib/launchpad/metricsServer.ts b/app/src/lib/launchpad/metricsServer.ts new file mode 100644 index 00000000..dd66d244 --- /dev/null +++ b/app/src/lib/launchpad/metricsServer.ts @@ -0,0 +1,37 @@ +import "server-only"; +import { chainIdOf, type ChainKey } from "@/lib/chainPublic"; +import { maybeDb } from "@/lib/db"; +import { ethUsd } from "./ethPrice"; +import { getHolderPanel } from "./holdersServer"; +import { memo } from "./memo"; +import { launchMetrics, type LaunchMetrics } from "./metrics"; +import { getLaunch } from "./queries"; + +export type { LaunchMetrics }; + +/** + * One launch's detail figures, or null when there is no such launch. Memoized for 30 seconds per launch, so the page + * and /api/launch/metrics read the database once however often a reader reloads or opens a second tab. + */ +export function getLaunchMetrics(chain: ChainKey, token: string): Promise { + const t = token.toLowerCase(); + return memo(`metrics:${chain}:${t}`, 30_000, () => read(chain, t)); +} + +async function read(chain: ChainKey, token: string): Promise { + const db = maybeDb(); + if (!db) return null; + const usd = await ethUsd(); + const [launch, panel, feeRows] = await Promise.all([ + // the launch read model: quote decimals as the server resolved them and volume in USD at each trade's own hour + getLaunch(chain, token, usd), + getHolderPanel(chain, token), + // the launch's own fee totals, already in USD: the indexer stores each fee event's value in its own hour's price + db<{ collected: number; burned: number }[]>` + SELECT fees_collected_usd::float8 AS collected, fees_burned_usd::float8 AS burned + FROM bb_launches WHERE chain_id = ${chainIdOf(chain)} AND token = ${token}`, + ]); + if (!launch || !panel) return null; + const fees = feeRows[0] ?? { collected: 0, burned: 0 }; + return launchMetrics(launch, panel, { collected_usd: fees.collected, burned_usd: fees.burned }); +} diff --git a/app/src/lib/seo.ts b/app/src/lib/seo.ts index 2cbe0b17..00da023c 100644 --- a/app/src/lib/seo.ts +++ b/app/src/lib/seo.ts @@ -47,7 +47,6 @@ export type StaticRoute = { export const STATIC_SITEMAP_ROUTES: StaticRoute[] = [ { path: "/", changeFrequency: "hourly", priority: 1 }, { path: "/launch", changeFrequency: "weekly", priority: 0.8 }, - { path: "/launch/details", changeFrequency: "monthly", priority: 0.5 }, ...CHAIN_KEYS.map((chain): StaticRoute => ({ path: chainLandingPath(chain), changeFrequency: "hourly", priority: 0.8 })), { path: "/feed", changeFrequency: "hourly", priority: 0.7 }, { path: "/pairs", changeFrequency: "daily", priority: 0.6 }, From ab91e5d07ed31679801071242b9becdb3f3333f6 Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Fri, 20 Nov 2026 10:39:41 +0530 Subject: [PATCH 6/7] fix(launch-details): read only the holder figures The metrics loader called getHolderPanel, which reads every swap of the launch to work out sniper and creator activity the page never shows, so a cache miss cost more the more trades a launch had. Add getHolderSummary for the distribution alone: the same holder reads, shared with the panel through one function, without the swap history. The page also presented a partial ranking as final while the transfer history was still indexing. Hide the ranking and the concentration figures until synced says the history is complete. --- .../launch/details/[chain]/[token]/page.tsx | 8 ++- app/src/lib/launchpad/holdersServer.ts | 71 +++++++++++++++---- app/src/lib/launchpad/metrics.ts | 5 +- app/src/lib/launchpad/metricsServer.ts | 12 ++-- 4 files changed, 75 insertions(+), 21 deletions(-) diff --git a/app/src/app/launch/details/[chain]/[token]/page.tsx b/app/src/app/launch/details/[chain]/[token]/page.tsx index 672546e9..5180ac18 100644 --- a/app/src/app/launch/details/[chain]/[token]/page.tsx +++ b/app/src/app/launch/details/[chain]/[token]/page.tsx @@ -64,8 +64,10 @@ export default async function LaunchDetailsPage({ params }: { params: Promise<{

Top holders

The five largest wallets, with the pool and the protocol's own addresses left out.

- {m.topHolders.length === 0 ? ( -

{m.synced ? "No holders yet." : "The transfer history is still indexing."}

+ {!m.synced ? ( +

The transfer history is still indexing, so this ranking is incomplete. Check back in a minute.

+ ) : m.topHolders.length === 0 ? ( +

No holders yet.

) : (
    {m.topHolders.map((h, i) => ( @@ -83,7 +85,7 @@ export default async function LaunchDetailsPage({ params }: { params: Promise<{

- The ten largest wallets hold {fmtShare(m.top10Bps)} of supply; the locked pool holds {fmtShare(m.poolBps)}.{" "} + {m.synced ? `The ten largest wallets hold ${fmtShare(m.top10Bps)} of supply; the locked pool holds ${fmtShare(m.poolBps)}. ` : null} The full token page {" "} diff --git a/app/src/lib/launchpad/holdersServer.ts b/app/src/lib/launchpad/holdersServer.ts index f788f1ba..e4f64285 100644 --- a/app/src/lib/launchpad/holdersServer.ts +++ b/app/src/lib/launchpad/holdersServer.ts @@ -1,22 +1,75 @@ import "server-only"; -import { maybeDb } from "@/lib/db"; +import { maybeDb, type Db } from "@/lib/db"; import { chainIdOf, type ChainKey } from "@/lib/chainPublic"; import { DEAD_ADDR, TOP_HOLDERS, ZERO_ADDR, creatorActivity, holderTags, shareBps, sniperSummary, trustNotes, type HolderTag } from "./holders"; import { systemAddresses } from "./indexer"; export type HolderRow = { address: string; balance: string; bps: number; tags: HolderTag[] }; -export type HolderPanel = { + +/** The holder facts on their own: distribution and supply, without the trust panel's creator and sniper work. */ +export type HolderSummary = { synced: boolean; // false while the token's transfer history is still being backfilled holders: number; supply: string; - top: HolderRow[]; + top: { address: string; balance: string; bps: number }[]; top10Bps: number; poolBps: number; +}; + +export type HolderPanel = Omit & { + top: HolderRow[]; creator: { address: string; bps: number; bought: string; sold: string; sells: number }; sniper: { wallets: number; bps: number }; notes: { level: "warn" | "info" | "good"; text: string }[]; }; +/** Whether a launch's transfer history is complete: the indexer writes the SYNCED_FOREVER sentinel far past its launch block. */ +function historyComplete(holdersSyncedBlock: bigint | null, launchBlock: bigint): boolean { + return holdersSyncedBlock !== null && BigInt(holdersSyncedBlock) > BigInt(launchBlock) + 1_000_000n; +} + +/** + * The two reads both readers need, issued together: the largest holder balances (the protocol's own addresses and the + * pool aside) and the balance the pool holds. A caller adds its own reads to the same Promise.all, so they run alongside. + */ +function holderReads(db: Db, cid: number, t: string, system: string[]) { + const excluded = [...system, ZERO_ADDR, DEAD_ADDR]; + return Promise.all([ + db<{ holder: string; balance: string }[]>` + SELECT h.holder, h.balance::text AS balance FROM bb_token_holders h + WHERE h.chain_id = ${cid} AND h.token = ${t} AND h.balance > 0 AND NOT (h.holder = ANY(${excluded})) + ORDER BY h.balance DESC LIMIT ${TOP_HOLDERS}`, // qualified: a bare "balance" would sort the ::text alias + db<{ balance: string }[]>` + SELECT COALESCE(sum(balance), 0)::text AS balance FROM bb_token_holders WHERE chain_id = ${cid} AND token = ${t} AND holder = ANY(${system})`, + ]); +} + +/** + * HolderSummary for one launch: the two indexed reads the distribution needs, and not the launch's swaps, which only the + * panel's sniper and creator work below uses. A caller that shows holders alone (the details page and + * /api/launch/metrics) pays for the figures it asks for, however many trades the launch has. + */ +export async function getHolderSummary(chain: ChainKey, token: string): Promise { + const db = maybeDb(); + if (!db) return null; + const cid = chainIdOf(chain); + const t = token.toLowerCase(); + const [l] = await db<{ supply: string; block_number: bigint; holders: number; holders_synced_block: bigint | null }[]>` + SELECT supply::text AS supply, block_number, holders, holders_synced_block FROM bb_launches WHERE chain_id = ${cid} AND token = ${t}`; + if (!l) return null; + const supply = BigInt(l.supply); + const [rows, pool] = await holderReads(db, cid, t, systemAddresses(chain)); + const top = rows.map((r) => ({ address: r.holder, balance: r.balance, bps: shareBps(BigInt(r.balance), supply) })); + return { + synced: historyComplete(l.holders_synced_block, l.block_number), + holders: l.holders, + supply: l.supply, + top, + top10Bps: top.reduce((a, r) => a + r.bps, 0), + poolBps: shareBps(BigInt(pool[0]?.balance ?? "0"), supply), + }; +} + /** Holder distribution + creator / sniper facts for one launch. Cheap: two indexed queries + one small scan of its swaps. */ export async function getHolderPanel(chain: ChainKey, token: string): Promise { const db = maybeDb(); @@ -28,16 +81,10 @@ export async function getHolderPanel(chain: ChainKey, token: string): Promise` - SELECT h.holder, h.balance::text AS balance FROM bb_token_holders h - WHERE h.chain_id = ${cid} AND h.token = ${t} AND h.balance > 0 AND NOT (h.holder = ANY(${excluded})) - ORDER BY h.balance DESC LIMIT ${TOP_HOLDERS}`, // qualified: a bare "balance" would sort the ::text alias + const [[rows, pool], swaps] = await Promise.all([ + holderReads(db, cid, t, system), db<{ trader: string | null; is_buy: boolean; block_number: bigint; amount1: string }[]>` SELECT trader, is_buy, block_number, amount1::text AS amount1 FROM bb_launch_swaps WHERE chain_id = ${cid} AND token = ${t}`, - db<{ balance: string }[]>` - SELECT COALESCE(sum(balance), 0)::text AS balance FROM bb_token_holders WHERE chain_id = ${cid} AND token = ${t} AND holder = ANY(${system})`, ]); const lite = swaps.map((s) => ({ trader: s.trader, is_buy: s.is_buy, block_number: s.block_number, token_amount: BigInt(s.amount1) })); const sn = sniperSummary(lite, l.block_number, supply); @@ -48,7 +95,7 @@ export async function getHolderPanel(chain: ChainKey, token: string): Promise a + r.bps, 0); const poolBps = shareBps(BigInt(pool[0]?.balance ?? "0"), supply); - const synced = l.holders_synced_block !== null && BigInt(l.holders_synced_block) > BigInt(l.block_number) + 1_000_000n; // SYNCED_FOREVER sentinel + const synced = historyComplete(l.holders_synced_block, l.block_number); return { synced, holders: l.holders, diff --git a/app/src/lib/launchpad/metrics.ts b/app/src/lib/launchpad/metrics.ts index fb0a2f7b..5b599c2d 100644 --- a/app/src/lib/launchpad/metrics.ts +++ b/app/src/lib/launchpad/metrics.ts @@ -51,7 +51,10 @@ export type LaunchMetrics = { /** Collected and burned fees in USD, the quote side only, as the indexer stored them. */ fees_collected_usd: number; fees_burned_usd: number; - /** Share of supply in the ten largest non-system wallets, and in the locked pool, in basis points. */ + /** + * Share of supply in the ten largest non-system wallets, and in the locked pool, in basis points. Both, and the + * ranking below, are partial while `synced` is false: show them only once the transfer history is complete. + */ top10Bps: number; poolBps: number; topHolders: { address: string; balance: string; bps: number }[]; diff --git a/app/src/lib/launchpad/metricsServer.ts b/app/src/lib/launchpad/metricsServer.ts index dd66d244..e9d8977c 100644 --- a/app/src/lib/launchpad/metricsServer.ts +++ b/app/src/lib/launchpad/metricsServer.ts @@ -2,7 +2,7 @@ import "server-only"; import { chainIdOf, type ChainKey } from "@/lib/chainPublic"; import { maybeDb } from "@/lib/db"; import { ethUsd } from "./ethPrice"; -import { getHolderPanel } from "./holdersServer"; +import { getHolderSummary } from "./holdersServer"; import { memo } from "./memo"; import { launchMetrics, type LaunchMetrics } from "./metrics"; import { getLaunch } from "./queries"; @@ -22,16 +22,18 @@ async function read(chain: ChainKey, token: string): Promise` SELECT fees_collected_usd::float8 AS collected, fees_burned_usd::float8 AS burned FROM bb_launches WHERE chain_id = ${chainIdOf(chain)} AND token = ${token}`, ]); - if (!launch || !panel) return null; + if (!launch || !summary) return null; const fees = feeRows[0] ?? { collected: 0, burned: 0 }; - return launchMetrics(launch, panel, { collected_usd: fees.collected, burned_usd: fees.burned }); + return launchMetrics(launch, summary, { collected_usd: fees.collected, burned_usd: fees.burned }); } From 5023c4356d08f201499784c816da2caa5d48ee19 Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Mon, 30 Nov 2026 16:33:56 +0530 Subject: [PATCH 7/7] fix(launch-details): price unpriced fees and gate figures on the sync marker --- .../launch/details/[chain]/[token]/page.tsx | 6 ++-- app/src/lib/launchpad/holdersServer.test.ts | 11 ++++++++ app/src/lib/launchpad/holdersServer.ts | 16 +++++++---- app/src/lib/launchpad/metrics.test.ts | 23 +++++++++++++-- app/src/lib/launchpad/metrics.ts | 26 +++++++++++++---- app/src/lib/launchpad/metricsServer.ts | 28 ++++++++++++++----- 6 files changed, 87 insertions(+), 23 deletions(-) create mode 100644 app/src/lib/launchpad/holdersServer.test.ts diff --git a/app/src/app/launch/details/[chain]/[token]/page.tsx b/app/src/app/launch/details/[chain]/[token]/page.tsx index 5180ac18..a24bf548 100644 --- a/app/src/app/launch/details/[chain]/[token]/page.tsx +++ b/app/src/app/launch/details/[chain]/[token]/page.tsx @@ -57,8 +57,8 @@ export default async function LaunchDetailsPage({ params }: { params: Promise<{ - - + +

@@ -85,7 +85,7 @@ export default async function LaunchDetailsPage({ params }: { params: Promise<{

- {m.synced ? `The ten largest wallets hold ${fmtShare(m.top10Bps)} of supply; the locked pool holds ${fmtShare(m.poolBps)}. ` : null} + {m.synced ? `The ten largest wallets hold ${fmtShare(m.top10Bps)} of supply; protocol addresses (the pool, router, Permit2 and locker) hold ${fmtShare(m.poolBps)}. ` : null} The full token page {" "} diff --git a/app/src/lib/launchpad/holdersServer.test.ts b/app/src/lib/launchpad/holdersServer.test.ts new file mode 100644 index 00000000..a2fc24cf --- /dev/null +++ b/app/src/lib/launchpad/holdersServer.test.ts @@ -0,0 +1,11 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { SYNCED_FOREVER } from "./holders.ts"; +import { historyComplete } from "./holdersServer.ts"; + +test("holder history is complete only at the SYNCED_FOREVER marker", () => { + assert.equal(historyComplete(null), false, "an unstarted backfill is not complete"); + assert.equal(historyComplete(100n), false, "a launch-block cursor is not complete"); + assert.equal(historyComplete(1_000_101n), false, "an intermediate block far past the launch is still partial"); + assert.equal(historyComplete(SYNCED_FOREVER), true, "the indexer's sentinel is the only completion evidence"); +}); diff --git a/app/src/lib/launchpad/holdersServer.ts b/app/src/lib/launchpad/holdersServer.ts index e4f64285..bf58a84a 100644 --- a/app/src/lib/launchpad/holdersServer.ts +++ b/app/src/lib/launchpad/holdersServer.ts @@ -1,7 +1,7 @@ import "server-only"; import { maybeDb, type Db } from "@/lib/db"; import { chainIdOf, type ChainKey } from "@/lib/chainPublic"; -import { DEAD_ADDR, TOP_HOLDERS, ZERO_ADDR, creatorActivity, holderTags, shareBps, sniperSummary, trustNotes, type HolderTag } from "./holders"; +import { DEAD_ADDR, SYNCED_FOREVER, TOP_HOLDERS, ZERO_ADDR, creatorActivity, holderTags, shareBps, sniperSummary, trustNotes, type HolderTag } from "./holders"; import { systemAddresses } from "./indexer"; export type HolderRow = { address: string; balance: string; bps: number; tags: HolderTag[] }; @@ -23,9 +23,13 @@ export type HolderPanel = Omit & { notes: { level: "warn" | "info" | "good"; text: string }[]; }; -/** Whether a launch's transfer history is complete: the indexer writes the SYNCED_FOREVER sentinel far past its launch block. */ -function historyComplete(holdersSyncedBlock: bigint | null, launchBlock: bigint): boolean { - return holdersSyncedBlock !== null && BigInt(holdersSyncedBlock) > BigInt(launchBlock) + 1_000_000n; +/** + * Whether a launch's transfer history is complete: the indexer writes the SYNCED_FOREVER sentinel only when its backfill + * reaches the chain cursor. An intermediate block (however far past the launch) is still a partial scan, and the + * watchlist uses the same marker, so the details figures agree with it. + */ +export function historyComplete(holdersSyncedBlock: bigint | null): boolean { + return holdersSyncedBlock !== null && BigInt(holdersSyncedBlock) === SYNCED_FOREVER; } /** @@ -61,7 +65,7 @@ export async function getHolderSummary(chain: ChainKey, token: string): Promise< const [rows, pool] = await holderReads(db, cid, t, systemAddresses(chain)); const top = rows.map((r) => ({ address: r.holder, balance: r.balance, bps: shareBps(BigInt(r.balance), supply) })); return { - synced: historyComplete(l.holders_synced_block, l.block_number), + synced: historyComplete(l.holders_synced_block), holders: l.holders, supply: l.supply, top, @@ -95,7 +99,7 @@ export async function getHolderPanel(chain: ChainKey, token: string): Promise a + r.bps, 0); const poolBps = shareBps(BigInt(pool[0]?.balance ?? "0"), supply); - const synced = historyComplete(l.holders_synced_block, l.block_number); + const synced = historyComplete(l.holders_synced_block); return { synced, holders: l.holders, diff --git a/app/src/lib/launchpad/metrics.test.ts b/app/src/lib/launchpad/metrics.test.ts index 250ea032..7a973081 100644 --- a/app/src/lib/launchpad/metrics.test.ts +++ b/app/src/lib/launchpad/metrics.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { LAUNCH_TOKEN_DECIMALS, TOP_HOLDERS_SHOWN, launchMetrics, supplyTokens, type LaunchMetricsLaunch, type LaunchMetricsPanel } from "./metrics.ts"; +import { LAUNCH_TOKEN_DECIMALS, TOP_HOLDERS_SHOWN, feeUsd, launchMetrics, supplyTokens, type LaunchMetricsLaunch, type LaunchMetricsPanel } from "./metrics.ts"; const TOKEN = "0x" + "a".repeat(40); /** 1e9 tokens at 18 decimals: the supply every LaunchToken has. */ @@ -12,7 +12,7 @@ const topN = (n: number) => Array.from({ length: n }, (_, i) => ({ address: `0x$ const panel = (o: Partial = {}): LaunchMetricsPanel => ({ synced: true, holders: 42, supply: SUPPLY, top: topN(10), top10Bps: 4200, poolBps: 5800, ...o }); -const fees = { collected_usd: 12.5, burned_usd: 3.25 }; +const fees = { collected_usd: 12.5, burned_usd: 3.25, partial: false }; test("supply is scaled by the launched token's 18 decimals, not the quote's", () => { assert.equal(LAUNCH_TOKEN_DECIMALS, 18); @@ -49,3 +49,22 @@ test("the top holders are the panel's first five, named as the panel names them" assert.equal(m.top10Bps, 4200); assert.equal(m.poolBps, 5800); }); + +test("a fee with no hourly price is valued at the quote's current price, never left at $0", () => { + // 10 USDC at 6 decimals with no stored usd, quote at $1 → $10, not the stored zero + assert.equal(feeUsd(0, "10000000", 6, 1), 10); + // a stored figure plus an unpriced part adds up + assert.equal(feeUsd(4, "1000000", 6, 2), 6); + // a launch with no fees at all is genuinely zero + assert.equal(feeUsd(0, "0", 6, 1), 0); +}); + +test("a fee nothing can price is unavailable rather than $0, and the partial flag reaches the response", () => { + assert.equal(feeUsd(null, "10000000", 6, null), null); + // a priced quote with a momentary outage keeps the stored part but reports it as partial + assert.equal(feeUsd(4, "1000000", 6, null), 4); + const m = launchMetrics(launch(), panel(), { collected_usd: null, burned_usd: 4, partial: true }); + assert.equal(m.fees_collected_usd, null); + assert.equal(m.fees_burned_usd, 4); + assert.equal(m.fees_partial, true); +}); diff --git a/app/src/lib/launchpad/metrics.ts b/app/src/lib/launchpad/metrics.ts index 5b599c2d..03265658 100644 --- a/app/src/lib/launchpad/metrics.ts +++ b/app/src/lib/launchpad/metrics.ts @@ -4,6 +4,7 @@ * holder panel (holdersServer.ts `getHolderPanel`); nothing here reads the database or the chain. */ import type { LaunchRow } from "./queries"; +import { tradeTimeUsd } from "./trade-time-usd.ts"; /** * Every launch's token is a LaunchToken: a fixed supply of 1e9 tokens at 18 decimals. `bb_launches.supply` is in those @@ -15,8 +16,20 @@ export const LAUNCH_TOKEN_DECIMALS = 18; /** How many holders the page and the API list: the panel's own top ten, trimmed. */ export const TOP_HOLDERS_SHOWN = 5; -/** A launch's fee totals in USD, as `bb_launches.fees_collected_usd` and `fees_burned_usd` hold them (per fee event). */ -export type LaunchFeesUsd = { collected_usd: number; burned_usd: number }; +/** + * A launch's fee totals in USD. The indexer stores each fee event in its own hour's price; rows it could not price are + * valued at the quote's price now, exactly as the site totals do (trade-time-usd.ts). null means nothing prices them; + * `partial` says a normally priced quote had no price this instant, so the figure can undercount. + */ +export type LaunchFeesUsd = { collected_usd: number | null; burned_usd: number | null; partial: boolean }; + +/** One fee figure: the stored trade-hour sum plus unpriced raw fees at today's quote price, or null when unpriceable. */ +export function feeUsd(stored: number | null | undefined, unpricedRaw: string | bigint | null | undefined, decimals: number, quoteUsdNow: number | null): number | null { + const hasRaw = unpricedRaw !== null && unpricedRaw !== undefined && BigInt(unpricedRaw) > 0n; + const hasStored = typeof stored === "number" && Number.isFinite(stored) && stored > 0; + if (!hasRaw && !hasStored) return 0; // a launch with no fees has a zero total, not an unavailable one + return tradeTimeUsd(stored, unpricedRaw, decimals, quoteUsdNow); +} /** The facts these figures rest on, from the launch read model: the row itself carries everything else. */ export type LaunchMetricsLaunch = Pick; @@ -48,9 +61,11 @@ export type LaunchMetrics = { trades: number; /** All-time volume in USD, each trade at its own hour's price; null when nothing prices the launch's quote. */ volume_usd: number | null; - /** Collected and burned fees in USD, the quote side only, as the indexer stored them. */ - fees_collected_usd: number; - fees_burned_usd: number; + /** Collected and burned fees in USD, the quote side only; null when nothing prices them. */ + fees_collected_usd: number | null; + fees_burned_usd: number | null; + /** True when an unpriced fee had to be valued at the quote's current price, so the figure may undercount. */ + fees_partial: boolean; /** * Share of supply in the ten largest non-system wallets, and in the locked pool, in basis points. Both, and the * ranking below, are partial while `synced` is false: show them only once the transfer history is complete. @@ -82,6 +97,7 @@ export function launchMetrics(launch: LaunchMetricsLaunch, panel: LaunchMetricsP volume_usd: launch.volume_usd, fees_collected_usd: fees.collected_usd, fees_burned_usd: fees.burned_usd, + fees_partial: fees.partial, top10Bps: panel.top10Bps, poolBps: panel.poolBps, topHolders: panel.top.slice(0, TOP_HOLDERS_SHOWN).map((h) => ({ address: h.address, balance: h.balance, bps: h.bps })), diff --git a/app/src/lib/launchpad/metricsServer.ts b/app/src/lib/launchpad/metricsServer.ts index e9d8977c..2830f4db 100644 --- a/app/src/lib/launchpad/metricsServer.ts +++ b/app/src/lib/launchpad/metricsServer.ts @@ -4,8 +4,9 @@ import { maybeDb } from "@/lib/db"; import { ethUsd } from "./ethPrice"; import { getHolderSummary } from "./holdersServer"; import { memo } from "./memo"; -import { launchMetrics, type LaunchMetrics } from "./metrics"; +import { feeUsd, launchMetrics, type LaunchFeesUsd, type LaunchMetrics } from "./metrics"; import { getLaunch } from "./queries"; +import { missingNow } from "./trade-time-usd.ts"; export type { LaunchMetrics }; @@ -28,12 +29,25 @@ async function read(chain: ChainKey, token: string): Promise` - SELECT fees_collected_usd::float8 AS collected, fees_burned_usd::float8 AS burned - FROM bb_launches WHERE chain_id = ${chainIdOf(chain)} AND token = ${token}`, + // the launch's own fee totals: the stored trade-hour USD sums plus the raw quote amounts whose hour had no price, + // valued at the quote's price now exactly as the site totals do (getLaunchTotals / trade-time-usd.ts) + db<{ collected_usd: number | null; burned_usd: number | null; collected_unpriced: string | null; burned_unpriced: string | null }[]>` + SELECT l.fees_collected_usd::float8 AS collected_usd, l.fees_burned_usd::float8 AS burned_usd, + COALESCE((SELECT sum(f.quote_amount) FROM bb_launch_fee_events f + WHERE f.chain_id = l.chain_id AND f.token = l.token AND f.kind = 'collected' AND f.usd IS NULL), 0)::text AS collected_unpriced, + COALESCE((SELECT sum(f.amount) FROM bb_launch_fee_events f + WHERE f.chain_id = l.chain_id AND f.token = l.token AND f.kind = 'burned' + AND f.currency = l.quote AND f.usd IS NULL), 0)::text AS burned_unpriced + FROM bb_launches l WHERE l.chain_id = ${chainIdOf(chain)} AND l.token = ${token}`, ]); if (!launch || !summary) return null; - const fees = feeRows[0] ?? { collected: 0, burned: 0 }; - return launchMetrics(launch, summary, { collected_usd: fees.collected, burned_usd: fees.burned }); + const f = feeRows[0]; + const quoteUsd = launch.quote_usd; + const decimals = launch.quote_decimals; + const fees: LaunchFeesUsd = { + collected_usd: feeUsd(f?.collected_usd, f?.collected_unpriced, decimals, quoteUsd), + burned_usd: feeUsd(f?.burned_usd, f?.burned_unpriced, decimals, quoteUsd), + partial: missingNow(f?.collected_unpriced, quoteUsd, launch.quote_priced) || missingNow(f?.burned_unpriced, quoteUsd, launch.quote_priced), + }; + return launchMetrics(launch, summary, fees); }