import "server-only"; import { cache } from "react"; import { maybeDb } from "@/lib/db"; import { CHAIN_KEYS, DEFAULT_CHAIN, chainIdOf, chainKeyOf, type ChainKey } from "@/lib/chainPublic"; import { quoteInfo as staticQuoteInfo, quoteUsdOf, hasPriceSource, type Quote, fixedUsdQuotes, quotesWithKey } from "./config"; import { ensureRegistry, stockList, stockUsdInUse, type Stock } from "./stocksServer"; import { unlistedQuote, type QuoteTokenMeta } from "./unlisted-quote"; import { memo } from "./memo"; import { gitlawbUsd } from "./gitlawbServer"; import { hypeUsd } from "./hypePrice"; import { loadPairs } from "./pairsServer"; import type { PairPublic } from "./pairs"; import { gitlawbLinkedUsd } from "./twig"; import { BOOST_CHAIN_ID } from "./boost"; import { boostEnabled } from "./boostSwitch"; import { canonicalImageUrl, pictureKey, reusedPictures, type PictureUse } from "./images"; import { GRACE_HOURS, LIVE_WINDOW_HOURS, STRIP_SIZE, rankTrending, type LiveTier } from "./ranking"; import { SNIPER_BLOCKS, SYNCED_FOREVER } from "./holders"; import { imagePublicBase } from "./imageStore"; import { collectNonDust } from "./feed-dust"; import { PIPS_LEADER, PIPS_RUNNER, pipFromSwapRow, tapeOrNone, type Pip } from "./trending-live"; import { launchKey } from "./list-state"; import { classifyMcap, parseMcapMode, type McapFacts, type McapClassification, type McapMode } from "./mcap-policy"; import { mcapPageQuery, type McapColumns } from "./mcap-query"; import { fdvQuote, quotePerToken, tickToTokensPerQuote, units } from "./math"; import { UNPRICED_LATERAL_SQL, launchVolumeUsd, missingNow, tradeTimeUsd } from "./trade-time-usd"; import type { RawCandle } from "./candles"; import { normalizeQuery, isAddressQuery, escapeLike, compareSearchHit, compareSearchHitByHolders, type LaunchFilter } from "./search"; /** * Read model for the UI. Every money field comes in two flavours: raw quote * units (wei / micro-USDG, as strings) and a USD float derived with the ETH * price passed in (`ethUsd`) or the stable's fixed price. Chains are mixed in * one list; each row carries its chain. */ export type LaunchRow = { chain: ChainKey; chain_id: number; token: string; token_id: number; launcher: string; quote: string; quote_key: Quote["key"]; // eth | usdg | usdc | gitlawb | twig | pair (a listed community pair, pairs.ts) | stock (a registry stock) | other (an unlisted ERC-20, unlisted-quote.ts) quote_logo: string | null; // a community pair's logo (its badge); null for every other quote quote_symbol: string; quote_decimals: number; quote_decimals_known: boolean; // false only for an unlisted quote not read yet: quote_decimals is a placeholder, do not trade quote_priced: boolean; // false when nothing prices the quote (an unlisted ERC-20, a stock without a feed): its null quote_usd is the normal state, not an outage pool_id: string; start_tick: number; lp_fee: number; supply: string; metadata_uri: string; name: string; symbol: string; block_number: number; block_time: string; tx_hash: string; tick: number; sqrt_price_x96: string | null; volume_quote: string; buys: number; sells: number; last_trade_at: string | null; fees_quote_collected: string; fees_token_collected: string; fees_quote_burned: string; fees_token_burned: string; recipients: { payout: string; bps: number }[]; trades_1h: number; traders_1h: number; traders_1h_ex: number; // distinct outside wallets in the hour (not the launcher, not sniper-window swaps) volume_1h: string; trades_24h: number; traders_24h_ex: number; // same over the day: the "live" gate (lib/launchpad/ranking.ts) volume_24h: string; last_outside_trade_at: string | null; // last swap by an outside wallet in the day window (last_trade_at counts everyone) live_tier: LiveTier | null; // sort "live" only: the tier the database ranked this row in launcher_collapsed: number; // sort "live" only: further rows of this launcher folded into this one description: string | null; image_url: string | null; /** A creator-uploaded banner (null when none; the cards then draw one from the logo). */ banner_url: string | null; holders: number; website: string | null; x_handle: string | null; // derived price_quote: number; // whole quote units per token fdv_quote: number; // whole quote units change_from_launch: number; quote_usd: number | null; // USD per 1 quote unit (null = unknown) price_usd: number | null; fdv_usd: number | null; volume_usd: number | null; volume_1h_usd: number | null; volume_24h_usd: number | null; /** Present on the market-cap list; the facts behind the optional browsing filter. */ mcap?: McapFacts & { classification: McapClassification }; }; type Raw = Omit & { token_id: bigint; block_number: bigint; tick: number | null; trades_1h: bigint | number; traders_1h?: bigint | number | null; traders_1h_ex?: bigint | number | null; trades_24h: bigint | number; traders_24h_ex?: bigint | number | null; last_outside_trade_at?: string | Date | null; live_tier?: number | null; launcher_collapsed?: bigint | number | null; }; const TIERS: LiveTier[] = ["live", "new", "quiet"]; // index = the live_tier CASE in the live sort /** Stock USD prices for this request (filled by `withStocks`). */ let stockUsdNow = new Map(); /** Unlisted quotes' on-chain symbol / decimals (bb_quote_tokens, keyed `${chain_id}:${address}`), and each chain's stock tickers they may not borrow. */ let quoteTokensNow = new Map(); let stockSymbolsNow = new Map(); let stockQuotesNow = new Map(); /** The community pairs for this request (filled by `withStocks`; every status, each listed one with its USD price or null), keyed `${chain_id}:${address}`. */ let pairsNow = new Map(); /** GITLAWB USD for this request (filled by `withStocks`; null = unknown → no USD, 0 weight in USD sorts). */ let gitlawbUsdNow: number | null = null; /** HYPE USD for this request (filled by `withStocks`; null = unknown → no USD, 0 weight in USD sorts). Elysium's native asset and WHYPE. */ let hypeUsdNow: number | null = null; /** The quote prices in use, as one value: what `withStocks` last loaded (each piece is replaced, never edited). */ type PriceState = { gitlawb: number | null; hype: number | null; pairs: Map; stocks: Map; quoteTokens: Map; stockSymbols: Map; stockQuotes: Map }; /** Capture the last published quote snapshot for readers that do not supply their own request-local snapshot. */ const priceState = (): PriceState => ({ gitlawb: gitlawbUsdNow, hype: hypeUsdNow, pairs: pairsNow, stocks: stockUsdNow, quoteTokens: quoteTokensNow, stockSymbols: stockSymbolsNow, stockQuotes: stockQuotesNow }); /** * Server-side quote resolution: static ETH/HYPE/USDG/GITLAWB/TWIG (GITLAWB gets the live price, TWIG the same one, HYPE and * WHYPE HYPE's live price), else a * listed community pair, else a registry stock, else an unlisted quote. Priced from `st` (the prices loaded now unless a * snapshot is passed). A suspended or delisted pair resolves as unlisted: no badge, no USD, out of Trending. */ function quoteInfo(chain: ChainKey, address: string, st: PriceState = priceState()): Quote { const q = staticQuoteInfo(chain, address); const linked = gitlawbLinkedUsd(q.key, st.gitlawb); // GITLAWB, and TWIG at the same price if (linked !== undefined) return { ...q, usd: linked }; if (q.key === "hype") return { ...q, usd: st.hype }; if (q.key !== "other") return q; const pair = st.pairs.get(`${chainIdOf(chain)}:${address.toLowerCase()}`); if (pair?.status === "listed") return { key: "pair", address: pair.address as Quote["address"], symbol: pair.symbol, decimals: pair.decimals, usd: pair.usd, name: pair.name, logo: pair.logo, pairKind: pair.price_kind }; const stock = st.stockQuotes.get(`${chain}:${address.toLowerCase()}`); // a stock nothing prices says so: its missing USD is not an outage (hasPriceSource) if (stock) return { key: "stock", address: stock.address as Quote["address"], symbol: stock.symbol, decimals: stock.decimals, usd: st.stocks.get(stock.address) ?? null, name: stock.name, logo: stock.logo, ...(stock.priced ? {} : { unpriced: true }) }; // an unlisted token may not borrow a stock ticker or a listed pair's symbol: it then shows by its address return unlistedQuote(address, st.quoteTokens.get(`${chainIdOf(chain)}:${address.toLowerCase()}`) ?? null, [...(st.stockSymbols.get(chain) ?? []), ...listedPairSymbols(st, chain)]); } function listedPairSymbols(st: PriceState, chain: ChainKey): string[] { return [...st.pairs.values()].filter((p) => p.chain === chain && p.status === "listed").map((p) => p.symbol); } /** bb_quote_tokens is tiny (one row per unlisted quote) and changes only when the indexer reads a new one. */ async function loadQuoteTokens(): Promise> { const db = maybeDb(); if (!db) return new Map(); const rows = await db<{ chain_id: number; address: string; symbol: string | null; name: string | null; decimals: number | null }[]>`SELECT chain_id, address, symbol, name, decimals FROM bb_quote_tokens`; return new Map(rows.map((r) => [`${r.chain_id}:${r.address}`, { symbol: r.symbol, name: r.name, decimals: r.decimals }])); } /** Load quote prices and metadata into a request-local snapshot; unavailable feeds retain null USD prices. */ async function withStocks(): Promise { // both never throw; GITLAWB is served from cache once warm (stale-while-revalidate), HYPE from a 60s memo const [gitlawb, hype] = await Promise.all([gitlawbUsd(), hypeUsd()]); let stocks = new Map(); let pairs = new Map(); let quoteTokens = new Map(); try { await ensureRegistry(); // robinhood registry (fail-soft); also starts a background refresh of the Base list stocks = new Map(await stockUsdInUse()); } catch { /* fail soft: stocks show without USD */ } try { // never throws; the last good list (prices included) is served while a refresh runs in the background pairs = new Map((await loadPairs()).map((p) => [`${chainIdOf(p.chain)}:${p.address}`, p])); } catch { /* fail soft: community pairs show as unlisted until the list reads */ } const stockSymbols = new Map(CHAIN_KEYS.map((k) => [k, stockList(k).map((s) => s.symbol)])); const stockQuotes = new Map(CHAIN_KEYS.flatMap((k) => stockList(k).map((s) => [`${k}:${s.address.toLowerCase()}`, s] as const))); try { quoteTokens = new Map(await memo("quote-tokens", 30_000, loadQuoteTokens)); } catch { /* fail soft (table not migrated yet, db blip): unlisted quotes show by address and do not trade */ } // Publish atomically for older readers; list requests retain their own snapshot across awaits. gitlawbUsdNow = gitlawb; hypeUsdNow = hype; pairsNow = pairs; stockUsdNow = stocks; quoteTokensNow = quoteTokens; stockSymbolsNow = stockSymbols; stockQuotesNow = stockQuotes; return { gitlawb, hype, pairs, stocks, quoteTokens, stockSymbols, stockQuotes }; } /** A community pair's logo for its badge; null for every other quote (a stock's logo can be a data URI, too heavy for every row). */ function pairLogo(q: Quote): string | null { return q.key === "pair" ? (q.logo ?? null) : null; } /** What a row needs to draw its quote's badge. */ function quoteBadgeFields(q: Quote): { quote_key: Quote["key"]; quote_symbol: string; quote_logo: string | null } { return { quote_key: q.key, quote_symbol: q.symbol, quote_logo: pairLogo(q) }; } /** A quote's USD price (ETH-quoted through the ETH price; null when unknown). */ function quoteUsd(q: Quote, ethUsd: number | null): number | null { return quoteUsdOf(q, ethUsd); } /** A launch row as the app uses it: indexer-only bigint columns dropped (JSON-safe), price, FDV and USD figures worked out. */ /** Columns a row carries for the trade-time USD figures (trade-time-usd.ts); read here, never passed on as they are. */ type TradeTimeCols = { volume_usd?: number | null; fees_collected_usd?: number | null; fees_burned_usd?: number | null; volume_quote_unpriced?: string | null }; function shape(raw: Raw & TradeTimeCols & Partial & { last_swap_block?: bigint; last_swap_log?: number; log_index?: number; holders_synced_block?: bigint | null }, ethUsd: number | null, prices: PriceState = priceState()): LaunchRow { // drop indexer-only bigint columns so the row is JSON-safe, the stored trade-time sums (volume_usd below is computed from // them) and the market-cap columns (read into `mcap` below) // eslint-disable-next-line @typescript-eslint/no-unused-vars const { last_swap_block, last_swap_log, log_index, holders_synced_block, volume_usd: storedVolumeUsd, fees_collected_usd, fees_burned_usd, volume_quote_unpriced, _mcap_fdv_quote, _mcap_start_quote, _mcap_outside_quote, _mcap_traders, ...r } = raw; const chain = chainKeyOf(r.chain_id) ?? DEFAULT_CHAIN; const q = quoteInfo(chain, r.quote, prices); const supply = BigInt(r.supply); const tick = r.tick ?? r.start_tick; const calculatedPrice = r.sqrt_price_x96 ? quotePerToken(BigInt(r.sqrt_price_x96), q.decimals) : 1 / tickToTokensPerQuote(tick, q.decimals); const fdv = _mcap_fdv_quote !== undefined ? (_mcap_fdv_quote ?? Number.NaN) : r.sqrt_price_x96 ? fdvQuote(BigInt(r.sqrt_price_x96), supply, q.decimals) : calculatedPrice * (Number(supply) / 1e18); const price = _mcap_fdv_quote !== undefined ? fdv / (Number(supply) / 1e18) : calculatedPrice; const launchFdv = _mcap_start_quote !== undefined ? (_mcap_start_quote ?? Number.NaN) : (1 / tickToTokensPerQuote(r.start_tick, q.decimals)) * (Number(supply) / 1e18); const quRaw = quoteUsd(q, ethUsd); const qu = quRaw !== null && Number.isFinite(quRaw) && quRaw > 0 ? quRaw : null; const mcapFacts: McapFacts = { startFdvQuote: launchFdv, fdvQuote: fdv, quoteUsd: qu, outsideVolumeQuote: _mcap_outside_quote ?? null, outsideTraders: _mcap_traders ?? null }; const usd = (raw: string) => (qu === null ? null : units(raw, q.decimals) * qu); return { ...r, chain, quote_key: q.key, quote_logo: pairLogo(q), quote_symbol: q.symbol, quote_decimals: q.decimals, quote_decimals_known: q.decimalsKnown !== false, quote_priced: hasPriceSource(q), token_id: Number(r.token_id), block_number: Number(r.block_number), tick, recipients: Array.isArray(r.recipients) ? r.recipients : [], trades_1h: Number(r.trades_1h ?? 0), traders_1h: Number(r.traders_1h ?? 0), traders_1h_ex: Number(r.traders_1h_ex ?? 0), volume_1h: String(r.volume_1h ?? "0"), trades_24h: Number(r.trades_24h ?? 0), traders_24h_ex: Number(r.traders_24h_ex ?? 0), volume_24h: String(r.volume_24h ?? "0"), last_outside_trade_at: r.last_outside_trade_at ? new Date(r.last_outside_trade_at).toISOString() : null, live_tier: r.live_tier === undefined || r.live_tier === null ? null : (TIERS[Number(r.live_tier)] ?? null), launcher_collapsed: Number(r.launcher_collapsed ?? 0), price_quote: price, fdv_quote: fdv, change_from_launch: launchFdv > 0 ? fdv / launchFdv - 1 : 0, image_url: canonicalImageUrl(r.image_url, imagePublicBase()), banner_url: canonicalImageUrl(r.banner_url, imagePublicBase()), quote_usd: qu, price_usd: qu === null || !Number.isFinite(price * qu) ? null : price * qu, fdv_usd: qu === null || !Number.isFinite(fdv * qu) ? null : fdv * qu, // all-time volume at each trade's own hour; trades with no stored value (no price history) at today's price volume_usd: launchVolumeUsd(storedVolumeUsd, volume_quote_unpriced, q.decimals, qu), volume_1h_usd: usd(String(r.volume_1h ?? "0")), volume_24h_usd: usd(String(r.volume_24h ?? "0")), ...(_mcap_fdv_quote !== undefined ? { mcap: { ...mcapFacts, classification: classifyMcap(mcapFacts) } } : {}), }; } // Rolling stats per row, one probe of the swaps index per launch: the day window (LIVE_WINDOW_HOURS, the live gate) with // the hour's figures as FILTERs. An "outside" swap is by a wallet that is not the launcher, not NULL (fails the FILTER) // and not inside the sniper window (launch block + SNIPER_BLOCKS, the holders panel's definition: one bot buying every // launch in its first seconds would otherwise make every token "live"). Sells in that window are excluded on purpose: // all supply starts in the pool, so a sell there can only be a sniper flipping what it just bought. Outside counts are the live gate and the trending // weight (lib/launchpad/ranking.ts); last_outside_at is what the live sort and its chip mean by "last trade", because // bb_launches.last_trade_at also moves on the launcher's own swaps. const OUTSIDE = `s.trader <> l.launcher AND s.block_number > l.block_number + ${SNIPER_BLOCKS}`; const HOUR = `s.block_time > now() - interval '1 hour'`; export const SELECT = `SELECT l.*, m.description, m.image_url, m.banner_url, m.website, m.x_handle, w.n1 AS trades_1h, w.t1 AS traders_1h, w.t1_ex AS traders_1h_ex, w.v1 AS volume_1h, w.n24 AS trades_24h, w.t24_ex AS traders_24h_ex, w.v24 AS volume_24h, w.last_outside_at AS last_outside_trade_at, COALESCE(u.uq, 0)::text AS volume_quote_unpriced FROM bb_launches l LEFT JOIN bb_launch_meta m ON m.chain_id = l.chain_id AND m.token = l.token LEFT JOIN LATERAL ( SELECT count(*) FILTER (WHERE ${HOUR})::int AS n1, count(DISTINCT s.trader) FILTER (WHERE ${HOUR})::int AS t1, count(DISTINCT s.trader) FILTER (WHERE ${HOUR} AND ${OUTSIDE})::int AS t1_ex, COALESCE(sum(abs(amount0)) FILTER (WHERE ${HOUR}), 0)::text AS v1, count(*)::int AS n24, count(DISTINCT s.trader) FILTER (WHERE ${OUTSIDE})::int AS t24_ex, COALESCE(sum(abs(amount0)), 0)::text AS v24, max(s.block_time) FILTER (WHERE ${OUTSIDE}) AS last_outside_at FROM bb_launch_swaps s WHERE s.chain_id = l.chain_id AND s.token = l.token AND s.block_time > now() - interval '${LIVE_WINDOW_HOURS} hours' ) w ON true LEFT JOIN LATERAL (${UNPRICED_LATERAL_SQL}) u ON true`; export type LaunchSort = "live" | "new" | "mcap" | "volume" | "gainers" | "holders"; export type VolumeWindow = "1h" | "24h" | "all"; export const LAUNCH_SORTS: LaunchSort[] = ["live", "new", "mcap", "volume", "gainers", "holders"]; /** The one place a sort name is parsed: allow-listed, with "trending" (the pre-Live name) kept as an alias of "live". */ export function parseSort(raw: string | null | undefined, fallback: F): LaunchSort | F { if (raw === "trending") return "live"; return LAUNCH_SORTS.includes(raw as LaunchSort) ? (raw as LaunchSort) : fallback; } export const VOLUME_WINDOWS: VolumeWindow[] = ["1h", "24h", "all"]; /** The raw-quote volume a Volume sort ranks by, per window: the lateral `w` in SELECT carries v1 and v24; "all" is the launch's own total. */ export const VOLUME_COLUMN_SQL: Record = { "1h": "w.v1::numeric", "24h": "w.v24::numeric", all: "l.volume_quote" }; export type ListOpts = { sort?: LaunchSort; window?: VolumeWindow; chain?: ChainKey | null; filter?: LaunchFilter | null; mcap?: McapMode; limit?: number; offset?: number; launcher?: string; quote?: string; ethUsd?: number | null }; const DEAD_ADDR = "0x000000000000000000000000000000000000dead"; export type ListPage = { items: LaunchRow[]; hasMore: boolean }; /** * Sorting + paging happen in SQL. Cross-chain money is normalized to USD inside * the query (USDG = 1, ETH = the price passed in) so "market cap" and "volume" * rank correctly across pools with different quotes. "New" orders by block * TIME, never by block number (chains have different heights). * * "Live" (the home default) applies the ranking rule from lib/launchpad/ranking.ts in SQL so paging stays * correct: tier 0 = an outside wallet traded it in the last day, ranked by outside wallets this hour, then today, * then the last outside trade; tier 1 = younger than the grace window; tier 2 = quiet; tiers 1 and 2 by age. * Outside tier 0 a launcher keeps only its newest row, and that row carries how many of its siblings were folded * (`launcher_collapsed`). The tier travels with the row (`live_tier`) so the client never recomputes it. */ export async function listLaunchesPage(opts: ListOpts = {}): Promise { const db = maybeDb(); if (!db) return { items: [], hasMore: false }; const prices = await withStocks(); const limit = Math.min(200, Math.max(1, opts.limit ?? 40)); const offset = Math.max(0, opts.offset ?? 0); const sort = opts.sort ?? "new"; const win = opts.window ?? "all"; const ethUsd = opts.ethUsd ?? null; const ethUsdKnown = ethUsd !== null && Number.isFinite(ethUsd) && ethUsd > 0 ? ethUsd : null; // no ETH price → the volume sorts rank ETH pools in ETH units (still monotonic within the chain), as before, so an ETH price // outage does not drop every ETH launch, most of Base, to the bottom. The market-cap query takes the price as unknown instead // (mcapUsdPerUnit below): ETH counted as dollars must never decide its filter, and an unpriced row sorts last there. const ethFactor = ethUsdKnown ?? 1; // stock quotes: per-address USD factors known this request (empty → treated like unknown = 0 weight in USD sorts) const stockEntries = [...prices.stocks.entries()].filter(([, v]) => v !== null && Number.isFinite(v) && v > 0) as [string, number][]; const conds = [] as ReturnType[]; if (opts.chain) conds.push(db`l.chain_id = ${chainIdOf(opts.chain)}`); if (opts.launcher) conds.push(db`l.launcher = ${opts.launcher.toLowerCase()}`); if (opts.quote) conds.push(db`l.quote = ${opts.quote.toLowerCase()}`); // a community pair's launches (with `chain`) if (opts.filter === "fee0") conds.push(db`l.lp_fee = 0`); if (opts.filter === "burn") conds.push(db`l.lp_fee > 0 AND jsonb_array_length(l.recipients) = 1 AND lower(l.recipients->0->>'payout') = ${DEAD_ADDR}`); // a fixed quote (USDG, USDC) is matched per chain: the same address elsewhere is some other token const quoteArms = (key: Quote["key"]) => { const arms = quotesWithKey(key).map(({ chain, address }) => db`(l.chain_id = ${chainIdOf(chain)} AND l.quote = ${address})`); return arms.length ? db`(${arms.reduce((a, c) => db`${a} OR ${c}`)})` : db`false`; }; if (opts.filter === "usdg" || opts.filter === "usdc") conds.push(db`${quoteArms(opts.filter)}`); // GITLAWB has a different address per chain (and none on Arc): the same chain-scoped match const isGitlawb = () => quoteArms("gitlawb"); // the quotes that take GITLAWB's USD price in the sorts: GITLAWB, and TWIG (one TWIG unwraps to one GITLAWB; gitlawbLinkedUsd) const isGitlawbPriced = () => db`(${isGitlawb()} OR ${quoteArms("twig")})`; if (opts.filter === "gitlawb") conds.push(db`${isGitlawb()}`); if (opts.filter === "twig") conds.push(db`${quoteArms("twig")}`); if (opts.filter === "today") conds.push(db`l.block_time > now() - interval '24 hours'`); const where = conds.length ? db`WHERE ${conds.reduce((a, c) => db`${a} AND ${c}`)}` : db``; // per-row USD factor and quote decimals (the stables, USDG and USDC, are the only fixed-price and non-18-dec quotes we list) // a registry stock is matched per (chain, address) like every other arm: the address is only a stock on the chain whose registry lists it /** Find the chains that list this stock address in this request's registry snapshot. */ const stockChains = (a: string) => CHAIN_KEYS.filter((k) => prices.stockQuotes.has(`${k}:${a.toLowerCase()}`)); const stockArms = stockEntries.flatMap(([a, v]) => stockChains(a).map((k) => db`WHEN (l.chain_id = ${chainIdOf(k)} AND l.quote = ${a}) THEN ${v}::double precision`)); const stockCase = stockArms.length ? stockArms.reduce((acc, c) => db`${acc} ${c}`) : db``; const gitlawbFactor = prices.gitlawb !== null && Number.isFinite(prices.gitlawb) && prices.gitlawb > 0 ? prices.gitlawb : null; // community pairs use the same request-local USD price for ordering and display; unknown prices sort last const pairs = [...prices.pairs.values()].filter((p) => p.status === "listed"); const pairArms = pairs.map((p) => db`WHEN (l.chain_id = ${chainIdOf(p.chain)} AND l.quote = ${p.address}) THEN ${p.usd !== null && Number.isFinite(p.usd) && p.usd > 0 ? p.usd : null}::double precision`); const pairCase = pairArms.length ? pairArms.reduce((acc, c) => db`${acc} ${c}`) : db``; const stables = fixedUsdQuotes(); const stableCase = stables.length ? stables.map((s) => db`WHEN (l.chain_id = ${chainIdOf(s.chain)} AND l.quote = ${s.address}) THEN ${s.usd}::double precision`).reduce((acc, c) => db`${acc} ${c}`) : db``; // ETH's price for every quote keyed "eth": address(0) where the chain's native asset is ETH (a native stable, Arc's USDC, is // keyed "usdc" and already in stableCase above) and WETH on Base const ethCaseFor = (factor: number | null) => { const ethArms = quotesWithKey("eth").map(({ chain, address }) => db`WHEN (l.chain_id = ${chainIdOf(chain)} AND l.quote = ${address}) THEN ${factor}::double precision`); return ethArms.length ? ethArms.reduce((acc, c) => db`${acc} ${c}`) : db``; }; // HYPE's price for every quote keyed "hype" (Elysium's native HYPE and WHYPE), chain-scoped like ETH; unknown has no USD const hypeFactor = prices.hype !== null && Number.isFinite(prices.hype) && prices.hype > 0 ? prices.hype : null; const hypeArms = quotesWithKey("hype").map(({ chain, address }) => db`WHEN (l.chain_id = ${chainIdOf(chain)} AND l.quote = ${address}) THEN ${hypeFactor}::double precision`); const hypeCase = hypeArms.length ? hypeArms.reduce((acc, c) => db`${acc} ${c}`) : db``; // unknown prices are NULL: 0 weight in the volume sorts (COALESCE below), last in the market-cap sort const usdPerUnitFor = (eth: number | null) => db`(CASE ${stableCase} ${pairCase} ${stockCase} WHEN ${isGitlawbPriced()} THEN ${gitlawbFactor}::double precision ${ethCaseFor(eth)} ${hypeCase} ELSE NULL::double precision END)`; const usdPerUnit = usdPerUnitFor(ethFactor); const mcapUsdPerUnit = usdPerUnitFor(ethUsdKnown); // quote decimals for the SQL valuations (the market-cap list shows the FDV computed here): one arm per registry stock that a // launch uses, so the statement grows with the stocks in use, never with a whole registry; an unlisted quote's decimals are // looked up below rather than bound one arm per bb_quote_tokens row, which has no size limit (any ERC-20 can be a quote) const stockDecArms = [...prices.stocks.keys()].flatMap((a) => stockChains(a).flatMap((k) => { const s = prices.stockQuotes.get(`${k}:${a.toLowerCase()}`); return s && s.decimals !== 18 ? [db`WHEN (l.chain_id = ${chainIdOf(k)} AND l.quote = ${a}) THEN ${s.decimals}`] : []; })); const decCase = stockDecArms.length ? stockDecArms.reduce((acc, c) => db`${acc} ${c}`) : db``; const stableDec = stables.filter((s) => s.decimals !== 18); const stableDecCase = stableDec.length ? stableDec.map((s) => db`WHEN (l.chain_id = ${chainIdOf(s.chain)} AND l.quote = ${s.address}) THEN ${s.decimals}`).reduce((acc, c) => db`${acc} ${c}`) : db``; const pairDec = pairs.filter((p) => p.decimals !== 18); const pairDecCase = pairDec.length ? pairDec.map((p) => db`WHEN (l.chain_id = ${chainIdOf(p.chain)} AND l.quote = ${p.address}) THEN ${p.decimals}`).reduce((acc, c) => db`${acc} ${c}`) : db``; // an unlisted quote: its decimals as the indexer read them (primary-key probe), 18 when unknown or out of range const unlistedDec = db`COALESCE((SELECT qt.decimals FROM bb_quote_tokens qt WHERE qt.chain_id = l.chain_id AND qt.address = l.quote AND qt.decimals BETWEEN 0 AND 36), 18)`; const qd = db`(CASE ${stableDecCase} ${pairDecCase} ${decCase} ELSE ${unlistedDec} END)`; const volCol = db.unsafe(VOLUME_COLUMN_SQL[win]); // the all-time window ranks by trade-time USD (each trade at its own hour, trades with no stored value at today's price, as // shape() shows it); 1h and 24h stay quote volume at today's price, where every trade is priced live anyway. An unknown // price weighs 0, as it always has. const volUsd = win === "all" ? db`(l.volume_usd + COALESCE(u.uq, 0) / power(10, ${qd}) * COALESCE(${usdPerUnit}, 0))` : db`(${volCol} / power(10, ${qd}) * COALESCE(${usdPerUnit}, 0))`; if (sort === "mcap") { const rows = await mcapPageQuery(db, { where, quoteDecimals: qd, quoteUsd: mcapUsdPerUnit, mode: parseMcapMode(opts.mcap), limit, offset, select: SELECT }) as unknown as (Raw & McapColumns)[]; const shaped = rows.map((r) => shape(r, ethUsd, prices)); return { items: shaped.slice(0, limit), hasMore: shaped.length > limit }; } const newest = db`l.block_time DESC, l.chain_id DESC, l.block_number DESC`; if (sort === "live") { const rows = await db` WITH base AS ( SELECT x.*, CASE WHEN x.traders_24h_ex >= 1 THEN 0 WHEN x.block_time > now() - make_interval(hours => ${GRACE_HOURS}) THEN 1 ELSE 2 END AS live_tier FROM (${db.unsafe(SELECT)} ${where}) x ), rest AS ( -- tiers 1 and 2 on purpose: the grace hour goes to a wallet's newest launch, not to every launch in a loop SELECT chain_id, token, row_number() OVER (PARTITION BY launcher ORDER BY block_time DESC, chain_id DESC, block_number DESC) AS rn, (count(*) OVER (PARTITION BY launcher) - 1)::int AS launcher_collapsed FROM base WHERE live_tier > 0 ) SELECT base.*, COALESCE(rest.launcher_collapsed, 0) AS launcher_collapsed FROM base LEFT JOIN rest ON rest.chain_id = base.chain_id AND rest.token = base.token WHERE base.live_tier = 0 OR rest.rn = 1 ORDER BY base.live_tier, base.traders_1h_ex DESC, base.traders_24h_ex DESC, base.last_outside_trade_at DESC NULLS LAST, base.block_time DESC, base.chain_id DESC, base.block_number DESC LIMIT ${limit + 1} OFFSET ${offset}`; const shaped = rows.map((r) => shape(r, ethUsd, prices)); return { items: shaped.slice(0, limit), hasMore: shaped.length > limit }; } const order = sort === "volume" ? db`ORDER BY ${volUsd} DESC, ${newest}` : sort === "gainers" ? db`ORDER BY (l.start_tick - COALESCE(l.tick, l.start_tick)) DESC, ${newest}` : sort === "holders" ? db`ORDER BY l.holders DESC, ${newest}` : db`ORDER BY ${newest}`; const rows = await db`${db.unsafe(SELECT)} ${where} ${order} LIMIT ${limit + 1} OFFSET ${offset}`; const shaped = rows.map((r) => shape(r, ethUsd, prices)); return { items: shaped.slice(0, limit), hasMore: shaped.length > limit }; } /** Back-compat: first page only. */ export async function listLaunches(opts: ListOpts = {}): Promise { return (await listLaunchesPage(opts)).items; } /** One launch by chain and token, or null. */ export async function getLaunch(chain: ChainKey, token: string, ethUsd: number | null = null): Promise { const db = maybeDb(); if (!db) return null; await withStocks(); const rows = await db`${db.unsafe(SELECT)} WHERE l.chain_id = ${chainIdOf(chain)} AND l.token = ${token.toLowerCase()}`; return rows[0] ? shape(rows[0], ethUsd) : null; } /** A bounded watchlist lookup shares the market read model without one query per token. */ export async function getLaunchesByRefs(refs: readonly { chain: ChainKey; token: string }[], ethUsd: number | null = null): Promise<{ launch: LaunchRow; holders: number | null }[]> { if (refs.length > 50) throw new Error("too many launch references"); const db = maybeDb(); if (!db || refs.length === 0) return []; await withStocks(); const matches = refs.map((ref) => db`(l.chain_id = ${chainIdOf(ref.chain)} AND l.token = ${ref.token.toLowerCase()})`); const rows = await db<(Raw & { holders_synced_block: bigint | null })[]>` ${db.unsafe(SELECT)} WHERE ${matches.reduce((a, b) => db`${a} OR ${b}`)}`; return rows.map((r) => ({ launch: shape(r, ethUsd), // Same completed-backfill sentinel as getHolderPanel. An unfinished index is not zero holders. holders: r.holders_synced_block !== null && BigInt(r.holders_synced_block) === SYNCED_FOREVER ? Number(r.holders) : null, })); } /** Find which chain a token lives on (for the legacy /t/ redirect). */ export async function findLaunchChain(token: string): Promise { const db = maybeDb(); if (!db) return null; const rows = await db<{ chain_id: number }[]>`SELECT chain_id FROM bb_launches WHERE token = ${token.toLowerCase()} ORDER BY block_time DESC, chain_id DESC, block_number DESC LIMIT 1`; return rows[0] ? chainKeyOf(rows[0].chain_id) : null; } export type SwapRow = { tx_hash: string; log_index: number; token: string; trader: string | null; amount0: string; amount1: string; is_buy: boolean; block_time: string; price_quote: number }; /** A token's newest swaps, newest first, with amounts in display units. */ export async function getSwaps(chain: ChainKey, token: string, quoteDecimals: number, limit = 50): Promise { const db = maybeDb(); if (!db) return []; const rows = await db<{ tx_hash: string; log_index: number; token: string; trader: string | null; amount0: string; amount1: string; is_buy: boolean; block_time: string; sqrt_price_x96: string }[]>` SELECT tx_hash, log_index, token, trader, amount0, amount1, is_buy, block_time, sqrt_price_x96 FROM bb_launch_swaps WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} ORDER BY block_number DESC, log_index DESC LIMIT ${Math.min(200, limit)}`; return rows.map((r) => ({ ...r, price_quote: quotePerToken(BigInt(r.sqrt_price_x96), quoteDecimals) })); } /** Home tape: launches + trades across chains, newest first. */ export type FeedItem = | { kind: "launch"; chain: ChainKey; at: string; tx_hash: string; token: string; name: string; symbol: string; launcher: string; lp_fee: number; quote_key: Quote["key"]; quote_symbol: string; quote_logo: string | null; image_url: string | null; image_reused?: true } | { kind: "swap"; chain: ChainKey; at: string; tx_hash: string; log_index: number; token: string; name: string; symbol: string; trader: string | null; is_buy: boolean; is_dev: boolean; quote_wei: string; quote_key: Quote["key"]; quote_symbol: string; quote_logo: string | null; quote_decimals: number; usd: number | null; image_url: string | null }; export type FeedSwap = Extract; /** * Which of these launches wear a picture another token registered first (images.ts: reusedPictures). The hero's coin only * shows a picture that is its token's own. When ownership cannot be checked (the read failed) every launch with a stored * picture counts as a copy: the coin then shows no picture and its caption still reacts, until the next read answers. */ async function pictureCopies(db: NonNullable>, launches: readonly { chain_id: number; token: string; image_url: string | null }[]): Promise> { const keys = [...new Set(launches.map((r) => pictureKey(r.image_url)).filter((k): k is string => k !== null))]; if (keys.length === 0) return new Set(); try { // a scan of bb_launch_meta (about 30 ms at 5,000 rows), and the home page asks on every render: read it once per half minute for a // given set of pictures. Stale is safe: a copy is judged against the earliest registration, which is older than any copy and // already in the answer, and a launch with a new picture changes the set, so it is read fresh. const sorted = [...keys].sort(); const all = await memo(`picture-owners:${sorted.join(",")}`, 30_000, () => db`SELECT chain_id, token, created_at, image_url FROM bb_launch_meta WHERE image_url ILIKE ANY(${sorted.map((k) => `%/${k}%`)}::text[])`); return reusedPictures(launches, all); } catch (error) { console.warn("[feed] picture ownership read failed:", error instanceof Error ? error.message : error); return new Set(launches.filter((r) => pictureKey(r.image_url) !== null).map((r) => `${r.chain_id}:${r.token.toLowerCase()}`)); } } /** The newest launches and trades across every chain, merged newest first, for the home feed. */ export async function getLaunchFeed(limit = 24, ethUsd: number | null = null): Promise { const db = maybeDb(); if (!db) return []; await withStocks(); const n = Math.min(100, limit); const image = (url: string | null) => canonicalImageUrl(url, imagePublicBase()); const shapeSwap = (r: { chain_id: number; at: string; tx_hash: string; log_index: number; token: string; name: string; symbol: string; quote: string; trader: string | null; is_buy: boolean; quote_wei: string; image_url: string | null; is_dev: boolean | null }): FeedSwap => { const chain = chainKeyOf(r.chain_id) ?? DEFAULT_CHAIN; const q = quoteInfo(chain, r.quote); const qu = quoteUsd(q, ethUsd); return { kind: "swap", chain, at: r.at, tx_hash: r.tx_hash, log_index: r.log_index, token: r.token, name: r.name, symbol: r.symbol, trader: r.trader, is_buy: r.is_buy, is_dev: Boolean(r.is_dev), quote_wei: r.quote_wei, quote_key: q.key, quote_symbol: q.symbol, quote_logo: pairLogo(q), quote_decimals: q.decimals, usd: qu === null ? null : units(r.quote_wei, q.decimals) * qu, image_url: image(r.image_url) }; }; const [launches, swaps] = await Promise.all([ db<{ chain_id: number; at: string; tx_hash: string; token: string; name: string; symbol: string; quote: string; launcher: string | null; lp_fee: number | null; image_url: string | null }[]>` SELECT l.chain_id, l.block_time AS at, l.tx_hash, l.token, l.name, l.symbol, l.quote, l.launcher, l.lp_fee, m.image_url FROM bb_launches l LEFT JOIN bb_launch_meta m ON m.chain_id = l.chain_id AND m.token = l.token ORDER BY l.block_time DESC LIMIT ${n}`, // Dust (feed-dust.ts) is priced and dropped after the read, so swaps come in pages: the newest 2n first, older pages // only while dust keeps the count short. Each page is a keyset read on the complete unique ordering // (block_time, log_index, chain_id, tx_hash) — a bounded scan of the block_time index, never OFFSET over a live table. collectNonDust( async (after, size) => ( await db<{ chain_id: number; at: string; tx_hash: string; log_index: number; token: string; name: string; symbol: string; quote: string; trader: string | null; is_buy: boolean; quote_wei: string; image_url: string | null; is_dev: boolean | null }[]>` SELECT s.chain_id, s.block_time AS at, s.tx_hash, s.log_index, s.token, l.name, l.symbol, l.quote, s.trader, s.is_buy, abs(s.amount0) AS quote_wei, m.image_url, (s.trader = l.launcher) AS is_dev FROM (SELECT * FROM bb_launch_swaps ${after ? db`WHERE block_time <= ${after.at} AND (block_time, log_index, chain_id, tx_hash) < (${after.at}, ${after.log_index}, ${chainIdOf(after.chain)}, ${after.tx_hash})` : db``} ORDER BY block_time DESC, log_index DESC, chain_id DESC, tx_hash DESC LIMIT ${size}) s JOIN bb_launches l ON l.chain_id = s.chain_id AND l.token = s.token LEFT JOIN bb_launch_meta m ON m.chain_id = l.chain_id AND m.token = l.token ORDER BY s.block_time DESC, s.log_index DESC, s.chain_id DESC, s.tx_hash DESC` ).map(shapeSwap), n, (i) => `${i.chain}:${i.tx_hash}:${i.log_index}`, ), ]); const reused = await pictureCopies(db, launches); const items: FeedItem[] = launches.map((r) => { const chain = chainKeyOf(r.chain_id) ?? DEFAULT_CHAIN; return { kind: "launch", chain, at: r.at, tx_hash: r.tx_hash, token: r.token, name: r.name, symbol: r.symbol, launcher: r.launcher ?? "", lp_fee: r.lp_fee ?? 0, ...quoteBadgeFields(quoteInfo(chain, r.quote)), image_url: image(r.image_url), ...(reused.has(`${r.chain_id}:${r.token.toLowerCase()}`) ? { image_reused: true as const } : {}) }; }); return [...items, ...swaps].sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime()).slice(0, n); } export type LaunchTotals = { launches: number; trades: number; /** USD sums across chains. A quote with no price right now contributes nothing; `usd_partial` says when that happened. */ volume_usd: number; fees_burned_usd: number; fees_to_creators_usd: number; /** True when a quote that normally prices had none for a launch with volume or fees (cold start, a price feed down >15 min), so the USD sums undercount right now. */ usd_partial: boolean; /** * GITLAWB sent to 0x…dEaD by launches quoted in it, raw 18-dec, Base + Robinhood combined: one token, one supply * bridged across two chains, so one figure and no per-chain split. Shown as an amount, never in USD. */ gitlawb_burned: string; /** * TWIG sent to 0x…dEaD, raw 18-dec (Base only): the trading fees of launches quoted in it, plus boosts (boost.ts). * Kept apart from gitlawb_burned: the GITLAWB behind burned TWIG stays in the TWIG contract, so it is TWIG that was * burned, and it is shown as such. */ twig_burned: string; /** The boosts' part of twig_burned, raw 18-dec (the hero's tooltip splits the two). */ twig_boost_burned: string; by_chain: Record; }; /** Platform totals (launches, trades, USD volume, fees burned and paid to creators, GITLAWB burned); zeros without a database. */ export async function getLaunchTotals(ethUsd: number | null = null): Promise { const empty = (): LaunchTotals => ({ launches: 0, trades: 0, volume_usd: 0, fees_burned_usd: 0, fees_to_creators_usd: 0, usd_partial: false, gitlawb_burned: "0", twig_burned: "0", twig_boost_burned: "0", by_chain: Object.fromEntries(CHAIN_KEYS.map((k) => [k, { launches: 0, trades: 0, volume_quote_eth: "0", volume_quote_hype: "0", volume_quote_usdg: "0", volume_quote_usdc: "0", volume_quote_gitlawb: "0", volume_quote_twig: "0" }])) as LaunchTotals["by_chain"], }); const db = maybeDb(); if (!db) return empty(); await withStocks(); const [rows, [boosted]] = await Promise.all([ db<{ 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 }[]>` SELECT l.chain_id, l.quote, count(*)::bigint AS launches, COALESCE(sum(l.buys + l.sells), 0)::bigint AS trades, COALESCE(sum(l.volume_quote), 0)::text AS volume, COALESCE(sum(l.fees_quote_burned), 0)::text AS burned, COALESCE(sum(l.fees_quote_collected - l.fees_quote_burned), 0)::text AS creators, -- trade-time USD (trade-time-usd.ts): the stored sums, and the raw amounts with no stored value COALESCE(sum(l.volume_usd), 0)::float8 AS volume_usd, COALESCE(sum(l.fees_collected_usd), 0)::float8 AS collected_usd, COALESCE(sum(l.fees_burned_usd), 0)::float8 AS burned_usd, COALESCE(sum(u.uq), 0)::text AS volume_unpriced, COALESCE(sum(uf.collected), 0)::text AS collected_unpriced, COALESCE(sum(uf.burned), 0)::text AS burned_unpriced FROM bb_launches l LEFT JOIN (SELECT chain_id, token, sum(abs(amount0)) AS uq FROM bb_launch_swaps WHERE usd IS NULL GROUP BY chain_id, token) u ON u.chain_id = l.chain_id AND u.token = l.token LEFT JOIN (SELECT f.chain_id, f.token, sum(f.quote_amount) FILTER (WHERE f.kind = 'collected') AS collected, sum(f.amount) FILTER (WHERE f.kind = 'burned') AS burned FROM bb_launch_fee_events f JOIN bb_launches fl ON fl.chain_id = f.chain_id AND fl.token = f.token WHERE f.usd IS NULL AND (f.kind = 'collected' OR (f.kind = 'burned' AND f.currency = fl.quote)) GROUP BY f.chain_id, f.token) uf ON uf.chain_id = l.chain_id AND uf.token = l.token GROUP BY l.chain_id, l.quote`, // boosts are TWIG sent to 0x…dEaD too (boost.ts): they join the TWIG burned figure while the switch is on, and // nothing else reads them here. Only boosts that name a launch count (the lane's own join), so a stray burn whose // last digits name nothing is never called a boost. Display only: a failed read counts none rather than taking // every page's totals down with it. boostEnabled() ? db<{ burned: string }[]>` SELECT COALESCE(sum(b.amount), 0)::text AS burned FROM bb_boosts b JOIN bb_launches l ON l.chain_id = b.chain_id AND l.token_id = b.tag WHERE b.chain_id = ${BOOST_CHAIN_ID}`.catch((err) => { console.warn("[totals] boost burns unread:", err instanceof Error ? err.message : err); return [{ burned: "0" }]; }) : Promise.resolve([{ burned: "0" }]), ]); const t = empty(); const add = (a: string, b: string) => (BigInt(a) + BigInt(b)).toString(); for (const r of rows) { const chain = chainKeyOf(r.chain_id); if (!chain) continue; const q = quoteInfo(chain, r.quote); const usd = quoteUsd(q, ethUsd); // trade-time USD: every trade and fee at its own hour (stored), the ones with no stored value (no price history) at // today's price. Only that last part can be missing: a quote that normally prices but has no price this instant → the // USD sums undercount; an unlisted ERC-20 (key "other") and a stock without a feed are unpriced by design and are left // out of the USD figures silently, as always const priced = hasPriceSource(q); if (missingNow(r.volume_unpriced, usd, priced) || missingNow(r.collected_unpriced, usd, priced) || missingNow(r.burned_unpriced, usd, priced)) t.usd_partial = true; const collectedUsd = tradeTimeUsd(r.collected_usd, r.collected_unpriced, q.decimals, usd) ?? 0; const burnedUsd = tradeTimeUsd(r.burned_usd, r.burned_unpriced, q.decimals, usd) ?? 0; t.launches += Number(r.launches); t.trades += Number(r.trades); t.volume_usd += tradeTimeUsd(r.volume_usd, r.volume_unpriced, q.decimals, usd) ?? 0; t.fees_burned_usd += burnedUsd; t.fees_to_creators_usd += collectedUsd - burnedUsd; const bc = t.by_chain[chain]; bc.launches += Number(r.launches); bc.trades += Number(r.trades); if (q.key === "eth") bc.volume_quote_eth = add(bc.volume_quote_eth, r.volume); else if (q.key === "hype") bc.volume_quote_hype = add(bc.volume_quote_hype, r.volume); else if (q.key === "usdg") bc.volume_quote_usdg = add(bc.volume_quote_usdg, r.volume); // USDC volume is reported at 6 decimals; Arc's native USDC is the same asset at 18, so it is scaled down to join the bucket else if (q.key === "usdc") bc.volume_quote_usdc = add(bc.volume_quote_usdc, q.decimals === 18 ? (BigInt(r.volume) / 10n ** 12n).toString() : r.volume); else if (q.key === "gitlawb") { bc.volume_quote_gitlawb = add(bc.volume_quote_gitlawb, r.volume); // GITLAWB is only ever the quote side (never a launched token), so the quote-fee burn is the whole GITLAWB burn t.gitlawb_burned = add(t.gitlawb_burned, r.burned); } else if (q.key === "twig") { bc.volume_quote_twig = add(bc.volume_quote_twig, r.volume); t.twig_burned = add(t.twig_burned, r.burned); // TWIG is only ever the quote side here too } } t.twig_boost_burned = boosted?.burned ?? "0"; t.twig_burned = add(t.twig_burned, t.twig_boost_burned); return t; } /** * getLaunchTotals, shared per request: the root layout and a chain landing page both need the site totals, * and this is one unfiltered aggregation over bb_launches. React's cache hands the second caller the first * caller's result within a server render (same ethUsd argument; ethUsd() is memoized so both read the same * price). Outside a render (route handlers) it simply calls through. */ export const getLaunchTotalsForRequest = cache(getLaunchTotals); export type FeeEventRow = { tx_hash: string; kind: string; currency: string | null; account: string | null; amount: string | null; quote_amount: string | null; token_amount: string | null; block_time: string }; /** A token's newest fee collections and burns. */ export async function getFeeEvents(chain: ChainKey, token: string, limit = 30): Promise { const db = maybeDb(); if (!db) return []; return db` SELECT tx_hash, kind, currency, account, amount, quote_amount, token_amount, block_time FROM bb_launch_fee_events WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} ORDER BY block_number DESC, log_index DESC LIMIT ${Math.min(200, limit)}`; } export type SyncCursor = { chain: ChainKey; cursor_block: number; head_block: number | null; last_run_at: string | null; last_error: string | null }; /** How far the indexer has read on each chain. */ export async function launchSyncCursors(): Promise { const db = maybeDb(); if (!db) return []; const rows = await db<{ chain_id: number; cursor_block: bigint; head_block: bigint | null; last_run_at: string | null; last_error: string | null }[]>`SELECT * FROM bb_launch_sync_cursor`; return rows .map((r) => ({ chain: chainKeyOf(r.chain_id), cursor_block: Number(r.cursor_block), head_block: r.head_block === null ? null : Number(r.head_block), last_run_at: r.last_run_at, last_error: r.last_error })) .filter((r): r is SyncCursor => r.chain !== null && CHAIN_KEYS.includes(r.chain)); } /** Search by name / symbol (substring) or exact address, across chains. Ranked: symbol exact, symbol prefix, name prefix, substring. */ export async function searchLaunches(q: string, opts: { chain?: ChainKey | null; limit?: number; ethUsd?: number | null; order?: "newest" | "holders" } = {}): Promise { const db = maybeDb(); const n = normalizeQuery(q); if (!db || !n) return []; await withStocks(); const limit = Math.min(50, Math.max(1, opts.limit ?? 20)); const chainCond = opts.chain ? db`AND l.chain_id = ${chainIdOf(opts.chain)}` : db``; const rows = isAddressQuery(n) ? await db`${db.unsafe(SELECT)} WHERE l.token = ${n} ${chainCond}` // LIKE metacharacters in n are escaped (ESCAPE '\'): a search for "%" or // "_" matches those literal characters, not every row. Pre-limit orders by // block time — never raw block numbers across chains (Base heights dwarf // Robinhood's, so the old ORDER BY hid exact matches on the low chain). : await db`${db.unsafe(SELECT)} WHERE (l.name ILIKE ${"%" + escapeLike(n) + "%"} ESCAPE '\\' OR l.symbol ILIKE ${"%" + escapeLike(n) + "%"} ESCAPE '\\') ${chainCond} ORDER BY l.block_time DESC, l.chain_id DESC, l.block_number DESC LIMIT 200`; const shaped = rows.map((r) => shape(r, opts.ethUsd ?? null)); shaped.sort((a, b) => (opts.order === "holders" ? compareSearchHitByHolders(a, b, n) : compareSearchHit(a, b, n))); return shaped.slice(0, limit); } /** * OHLCV buckets from the swap log (sparse; the client fills gaps). Prices are * whole quote units per token, derived from each swap's post-trade sqrtPrice. * `from` = earliest bucket start (unix seconds). */ export async function getCandles(chain: ChainKey, token: string, intervalS: number, from: number, quoteDecimals: number, asOf = Math.floor(Date.now() / 1000)): Promise { const db = maybeDb(); if (!db) return []; // quote-per-token = 1 / ((sqrt/2^96)^2 · 10^(qd-18)) const scale = Math.pow(10, quoteDecimals - 18); const rows = await db<{ t: number; open: number; high: number; low: number; close: number; volume: string; trades: number }[]>` WITH s AS ( SELECT floor(extract(epoch FROM block_time) / ${intervalS})::bigint * ${intervalS} AS t, 1.0 / (power(sqrt_price_x96::double precision / 79228162514264337593543950336.0, 2) * ${scale}) AS p, abs(amount0) AS v, block_number, log_index FROM bb_launch_swaps WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} AND block_time >= to_timestamp(${from}) AND block_time <= to_timestamp(${asOf}) ) SELECT t::int AS t, (array_agg(p ORDER BY block_number, log_index))[1] AS open, max(p) AS high, min(p) AS low, (array_agg(p ORDER BY block_number DESC, log_index DESC))[1] AS close, sum(v)::text AS volume, count(*)::int AS trades FROM s GROUP BY t ORDER BY t`; return rows.map((r) => ({ t: Number(r.t), open: Number(r.open), high: Number(r.high), low: Number(r.low), close: Number(r.close), volume: units(r.volume, quoteDecimals), trades: Number(r.trades) })); } /** * Seed an empty leading chart bucket from actual earlier history, not launch. * The chain/token index supplies chain order including multiple swaps per block; * the strict time boundary keeps the first requested bucket in the OHLCV query. */ export async function getCandleBaseline(chain: ChainKey, token: string, from: number, quoteDecimals: number): Promise { const db = maybeDb(); if (!db) return null; const rows = await db<{ sqrt_price_x96: string }[]>` SELECT sqrt_price_x96 FROM bb_launch_swaps WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} AND block_time < to_timestamp(${from}) ORDER BY block_number DESC, log_index DESC LIMIT 1`; return rows[0] ? quotePerToken(BigInt(rows[0].sqrt_price_x96), quoteDecimals) : null; } /** Trades by one wallet on one token, bounded to the chart snapshot's time. */ export async function getWalletSwaps(chain: ChainKey, token: string, wallet: string, asOf: number, limit = 200): Promise<{ t: number; is_buy: boolean; quote: string }[]> { if (!Number.isFinite(asOf)) return []; const db = maybeDb(); if (!db) return []; const rows = await db<{ t: number; is_buy: boolean; quote: string }[]>` SELECT extract(epoch FROM block_time)::int AS t, is_buy, abs(amount0)::text AS quote FROM bb_launch_swaps WHERE chain_id = ${chainIdOf(chain)} AND token = ${token.toLowerCase()} AND trader = ${wallet.toLowerCase()} AND block_time <= to_timestamp(${asOf}) ORDER BY block_number DESC, log_index DESC LIMIT ${Math.min(500, limit)}`; return rows.map((r) => ({ t: Number(r.t), is_buy: r.is_buy, quote: r.quote })); } /** Tokens (launched here) that a wallet has traded, with its trade counts. Balances are read on-chain by the client. */ export async function getWalletTokens(wallet: string, ethUsd: number | null = null, limit = 100): Promise<(LaunchRow & { my_buys: number; my_sells: number; my_last_trade: string })[]> { const db = maybeDb(); if (!db) return []; await withStocks(); const w = wallet.toLowerCase(); const rows = await db<(Raw & { my_buys: bigint; my_sells: bigint; my_last_trade: string })[]>` ${db.unsafe(SELECT)} JOIN LATERAL ( SELECT count(*) FILTER (WHERE is_buy)::bigint AS my_buys, count(*) FILTER (WHERE NOT is_buy)::bigint AS my_sells, max(block_time) AS my_last_trade FROM bb_launch_swaps s WHERE s.chain_id = l.chain_id AND s.token = l.token AND s.trader = ${w} ) mine ON mine.my_buys + mine.my_sells > 0 ORDER BY mine.my_last_trade DESC LIMIT ${Math.min(200, limit)}`; return rows.map((r) => ({ ...shape(r, ethUsd), my_buys: Number(r.my_buys), my_sells: Number(r.my_sells), my_last_trade: r.my_last_trade })); } export type WalletTrade = { chain: ChainKey; token: string; symbol: string; name: string; tx_hash: string; log_index: number; is_buy: boolean; quote_raw: string; quote_symbol: string; quote_decimals: number; usd: number | null; tokens: string; block_time: string }; /** One wallet's newest trades across every chain, keyed by chain, transaction and log index. */ export async function getWalletTrades(wallet: string, ethUsd: number | null = null, limit = 50): Promise { const db = maybeDb(); if (!db) return []; await withStocks(); const rows = await db<{ chain_id: number; token: string; symbol: string; name: string; quote: string; tx_hash: string; log_index: number; is_buy: boolean; amount0: string; amount1: string; block_time: string }[]>` SELECT s.chain_id, s.token, l.symbol, l.name, l.quote, s.tx_hash, s.log_index, s.is_buy, s.amount0, s.amount1, s.block_time FROM bb_launch_swaps s JOIN bb_launches l ON l.chain_id = s.chain_id AND l.token = s.token WHERE s.trader = ${wallet.toLowerCase()} ORDER BY s.block_number DESC, s.log_index DESC LIMIT ${Math.min(200, limit)}`; return rows.map((r) => { const chain = chainKeyOf(r.chain_id) ?? DEFAULT_CHAIN; const q = quoteInfo(chain, r.quote); const qu = quoteUsd(q, ethUsd); const raw = BigInt(r.amount0) < 0n ? (-BigInt(r.amount0)).toString() : r.amount0; const tok = BigInt(r.amount1) < 0n ? (-BigInt(r.amount1)).toString() : r.amount1; return { chain, token: r.token, symbol: r.symbol, name: r.name, tx_hash: r.tx_hash, log_index: r.log_index, is_buy: r.is_buy, quote_raw: raw, quote_symbol: q.symbol, quote_decimals: q.decimals, usd: qu === null ? null : units(raw, q.decimals) * qu, tokens: tok, block_time: r.block_time }; }); } /** `tape`: each board token's recent trades (oldest first), keyed by launchKey. Only the page's seed carries it: the live poll adds trades itself. */ export type TrendingSnap = { window: "1h" | "24h"; items: LaunchRow[]; tape?: Record }; export const TRENDING_CANDIDATES = 40; /** * "Hot right now" from rows already fetched: the first page of the live sort (all chains, no filter) is the candidate set. * Unlisted pairs stay in the lists (with their badge) but are never promoted here. */ export function trendingFrom(rows: LaunchRow[]): TrendingSnap { return rankTrending(rows.filter((r) => r.quote_key !== "other"), Date.now()); } /** True when a list request's first page doubles as the trending candidate set, so callers can skip `getTrending`. */ export function isTrendingSource(opts: ListOpts): boolean { return opts.sort === "live" && !opts.chain && !opts.filter && (opts.window ?? "all") === "all" && !opts.offset && (opts.limit ?? 0) >= TRENDING_CANDIDATES; } /** * Each board token's recent trades, oldest first, for the Trending cards' tapes: as many as its card has room for (the * first row is the leader, the rest are runners). One read for the whole board: * the newest swaps of each token off its (token, block_time) index, in the feed's own order. Dust is dropped after the read, as the feed does * it, so twice the rows are read; dollars use the price the board row already carries. */ export async function getBoardTapes(rows: readonly LaunchRow[]): Promise> { const db = maybeDb(); if (!db || rows.length === 0) return {}; const byId = new Map(rows.map((r) => [`${r.chain_id}:${r.token.toLowerCase()}`, r])); const found = await db<{ chain_id: number; token: string; tx_hash: string; log_index: number; is_buy: boolean; quote_wei: string; at: Date; trader: string | null }[]>` SELECT t.chain_id, t.token, s.tx_hash, s.log_index, s.is_buy, abs(s.amount0)::text AS quote_wei, s.block_time AS at, s.trader FROM unnest(${rows.map((r) => r.chain_id)}::int[], ${rows.map((r) => r.token.toLowerCase())}::text[]) AS t(chain_id, token) CROSS JOIN LATERAL ( SELECT tx_hash, log_index, is_buy, amount0, block_time, trader FROM bb_launch_swaps WHERE chain_id = t.chain_id AND token = t.token ORDER BY block_time DESC, log_index DESC LIMIT ${PIPS_LEADER * 2} ) s`; const tape: Record = {}; for (const r of found) { const row = byId.get(`${r.chain_id}:${r.token}`); if (!row) continue; const pip = pipFromSwapRow({ chain: row.chain, token: row.token, tx_hash: r.tx_hash, log_index: r.log_index, is_buy: r.is_buy, quote_wei: r.quote_wei, at: r.at, trader: r.trader }, row); if (pip) (tape[launchKey(row)] ??= []).push(pip); } rows.forEach((row, i) => { const key = launchKey(row); if (tape[key]) tape[key] = tape[key].sort((a, b) => a.at - b.at).slice(-(i === 0 ? PIPS_LEADER : PIPS_RUNNER)); }); return tape; } /** A snapshot with its tapes: the page seeds the board with it; a quiet burst of page loads shares one read. */ export async function withBoardTape(snap: TrendingSnap): Promise { if (snap.items.length === 0) return snap; // the board shows STRIP_SIZE cards (the ranking returns no more); the cap keeps a larger snapshot from fetching history nobody draws const shown = snap.items.slice(0, STRIP_SIZE + 1); const key = `board-tape:${shown.map((r) => `${r.chain_id}:${r.token}`).join(",")}`; const tape = await tapeOrNone(() => memo(key, 3_000, () => getBoardTapes(shown)), (error) => console.warn("[trending] tape read failed:", error instanceof Error ? error.message : error)); return tape ? { ...snap, tape } : snap; } /** "Hot right now": the top of the live sort, ranked for the strip by lib/launchpad/ranking.ts. */ export async function getTrending(ethUsd: number | null = null): Promise { const page = await listLaunchesPage({ sort: "live", limit: TRENDING_CANDIDATES, ethUsd }); return trendingFrom(page.items); } /** * The lists' own live quote pricing as a function, with no points rules (quotePricer below drops community pairs priced from * an outside pool; the lists show them): decimals and USD per whole quote unit, null = unpriced. For the indexer's hourly * live capture (usdLedger.ts), which is what prices each trade at its own hour. */ export async function quoteUsdNow(ethUsd: number | null): Promise<(chain: ChainKey, quote: string) => { key: Quote["key"]; decimals: number; decimalsKnown: boolean; usd: number | null }> { await withStocks(); const snap = priceState(); return (chain, quote) => { const q = quoteInfo(chain, quote, snap); return { key: q.key, decimals: q.decimals, decimalsKnown: q.decimalsKnown !== false, usd: quoteUsd(q, ethUsd) }; }; } /** * The quote pricing the lists use, as a function, for code that prices many launches at once (season points): * decimals and USD per whole quote unit (null = unpriced) for a launch's quote on its chain. `priced` is false for a * quote nothing prices (an unlisted ERC-20, a stock without a feed): its null USD will not come back, so do not wait for it. */ export async function quotePricer(ethUsd: number | null): Promise<(chain: ChainKey, quote: string) => { key: string; decimals: number; usd: number | null; priced: boolean }> { await withStocks(); // one snapshot for the caller's whole run: a page refresh loading new prices meanwhile must not change it halfway const snap = priceState(); return (chain, quote) => { const q = quoteInfo(chain, quote, snap); // a community pair counts for points only when priced from an openlaunch pool (our own index, our own average); // one priced from an outside pool is left out, like a quote nothing prices (reports/Community pairs plan.md, decision 9) if (q.key === "pair" && q.pairKind !== "launch") return { key: q.key, decimals: q.decimals, usd: null, priced: false }; return { key: q.key, decimals: q.decimals, usd: quoteUsd(q, ethUsd), priced: hasPriceSource(q) }; }; }