Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions app/src/app/api/launch/metrics/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { isAddress } from "viem";
import { isChainKey } 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, 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 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 });
}
}
108 changes: 108 additions & 0 deletions app/src/app/launch/details/[chain]/[token]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
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<Metadata> {
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 (
<main className="relative mx-auto max-w-6xl px-4 pt-6 sm:pt-10 pb-16 space-y-5 sm:space-y-6">
<header className="max-w-2xl">
<p className="text-sm text-muted">
<Link href={tokenPath(m.chain, m.token)} className="hover:text-ink">
{m.name} ({symbol})
</Link>
<span aria-hidden="true"> · </span>
{CHAIN_LABELS[m.chain]}
</p>
<h1 className="mt-2 font-display font-bold tracking-[-0.02em] text-ink text-3xl sm:text-4xl">Launch details</h1>
<p className="mt-2 text-base text-body">
<span className="font-mono">{shortAddr(m.token)}</span> · every trade, fee and holder the indexer holds for this launch
</p>
</header>

<dl className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
<Cell k="Holders" v={m.holders === null ? "—" : count(m.holders)} sub={m.synced ? "wallets holding it, the pool aside" : "the transfer history is still indexing"} />
<Cell k="Supply" v={`${count(m.supply_tokens)} ${symbol}`} sub="fixed at launch, never minted again" />
<Cell k="Trades" v={count(m.trades)} sub="buys and sells, all time" />
<Cell k="Volume" v={usd(m.volume_usd)} sub={m.volume_usd === null ? `nothing prices ${m.quote_symbol} yet` : "each trade at its own hour's price"} />
<Cell k="Fees collected" v={usd(m.fees_collected_usd)} sub={m.fees_partial ? `collected in ${m.quote_symbol}; some fees have no price yet` : `collected in ${m.quote_symbol}`} />
<Cell k="Fees burned" v={usd(m.fees_burned_usd)} sub={m.fees_partial ? `burned in ${m.quote_symbol}; some fees have no price yet` : `burned in ${m.quote_symbol}`} />
</dl>

<section className="rounded-2xl border border-line bg-card p-5 shadow-card">
<h2 className="font-display text-base font-semibold text-ink">Top holders</h2>
<p className="mt-1 text-sm text-muted">The five largest wallets, with the pool and the protocol&apos;s own addresses left out.</p>
{!m.synced ? (
<p className="mt-4 text-sm text-muted">The transfer history is still indexing, so this ranking is incomplete. Check back in a minute.</p>
) : m.topHolders.length === 0 ? (
<p className="mt-4 text-sm text-muted">No holders yet.</p>
) : (
<ol className="mt-4 space-y-2">
{m.topHolders.map((h, i) => (
<li key={h.address} className="flex items-baseline justify-between gap-3 text-sm">
<span className="min-w-0 truncate">
<span className="text-muted tnum">{i + 1}.</span> <span className="font-mono text-ink">{shortAddr(h.address)}</span>
</span>
<span className="shrink-0 text-body tnum" title={`${fmtUnitsExact(h.balance, LAUNCH_TOKEN_DECIMALS)} ${symbol}`}>
{fmtShare(h.bps)}
</span>
</li>
))}
</ol>
)}
</section>

<p className="text-sm text-muted">
{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}
<Link href={tokenPath(m.chain, m.token)} className="underline decoration-line-strong underline-offset-4 hover:text-ink">
The full token page
</Link>{" "}
has the chart, the trades and the receipts.
</p>
</main>
);
}

function Cell({ k, v, sub }: { k: string; v: string; sub: string }) {
return (
<div className="rounded-2xl border border-line bg-card p-5 shadow-card">
<dt className="text-sm text-muted">{k}</dt>
<dd className="mt-1">
<span className="block font-display text-2xl font-bold text-ink tnum">{v}</span>
<span className="mt-1 block text-xs text-faint">{sub}</span>
</dd>
</div>
);
}
11 changes: 11 additions & 0 deletions app/src/lib/launchpad/holdersServer.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
77 changes: 64 additions & 13 deletions app/src/lib/launchpad/holdersServer.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,79 @@
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 { 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[] };
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<HolderSummary, "top"> & {
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 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;
}

/**
* 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<HolderSummary | null> {
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),
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<HolderPanel | null> {
const db = maybeDb();
Expand All @@ -28,16 +85,10 @@ export async function getHolderPanel(chain: ChainKey, token: string): Promise<Ho
if (!l) return null;
const supply = BigInt(l.supply);
const system = systemAddresses(chain);
const excluded = [...system, ZERO_ADDR, DEAD_ADDR];
const [rows, swaps, pool] = await 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
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);
Expand All @@ -48,7 +99,7 @@ export async function getHolderPanel(chain: ChainKey, token: string): Promise<Ho
const creatorBps = shareBps(BigInt(creatorRow?.balance ?? "0"), supply);
const top10Bps = top.reduce((a, r) => 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);
return {
synced,
holders: l.holders,
Expand Down
70 changes: 70 additions & 0 deletions app/src/lib/launchpad/metrics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { test } from "node:test";
import assert from "node:assert/strict";
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. */
const SUPPLY = "1000000000000000000000000000";

const launch = (o: Partial<LaunchMetricsLaunch> = {}): 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> = {}): 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, partial: false };

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);
});

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);
});
Loading
Loading