Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(api): add token snapshot endpoint and related functionality

fudjia86616cb99b42
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 788b58bb2..4fffae8b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,9 +15,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Agent reputation now scores any wallet or agent on any chain** — The paid Agent Reputation endpoint no longer only works on three.ws agents — pass ANY counterparty and get a deterministic 0–100 trust score before you pay, trade, or delegate to it. It auto-detects the type — a Solana wallet, an EVM 0x address, a pump.fun mint, an ERC-8004 agent id, or a three.ws agent_id — and scores it from real on-chain evidence: transaction history, account age, distinct counterparties, holdings, settlement reliability, prior settled agent payments, and ERC-8004 feedback. Every score comes with the underlying evidence links and a clear list of what couldn't be read; an unknown or unscannable subject returns score:null, never a fabricated number. A new batch mode scores up to 25 counterparties in one call. It's a genuine pre-transaction trust primitive that works across chains, not just on our own platform. (`/docs/trust-primitives`) `[feature, improvement]`
- **Forge listing sharpened: clear 3D generation tiers for agents** — Forge — our text→3D and image→3D generation — now reads like the crown jewel it is on the x402 agent marketplaces. The listing leads with what agents actually build (game assets, NFT collections, 3D scenes, product viz), spells out the three quality tiers and their flat USDC prices (draft $0.05 / standard $0.15 / high $0.50), and points newcomers to the free keyless draft lane as an on-ramp. The input and output schemas are now complete enough for an agent to call it blind — the prompt, the reference-image mode, the free job-token poll, and the finished GLB — and it's tagged so it surfaces under 3D, AI, and Utility. Under the hood the discovery listing and the live payment challenge now share one source of truth, so what an agent sees can never drift from what it pays for. (`/docs/3d-api`) `[improvement]`
- **Free bonding-curve status API for pump.fun tokens** — A new free, keyless endpoint tells an agent exactly where a pump.fun token sits on its bonding curve: how far along it is toward graduation (%), how much SOL is in the curve, how many tokens are left to buy, and whether it has already graduated and migrated to Raydium or PumpSwap. Timing entries and exits around graduation is a core meme-trading move, and this is the one call that answers it — no account, no key, just GET /api/crypto/bonding?mint=<mint>. It pairs with the live launches feed to watch fresh mints climb their curve. Part of the free three.ws Crypto Data API; full reference with runnable curls at /docs/crypto-api. (`/docs/crypto-api`) `[feature]`
+- **Free live pump.fun launches feed for agents** — The Crypto Data API now has a live launch feed: GET /api/crypto/launches returns the freshest pump.fun mints, newest first, with everything a discovery or sniper agent filters on — name, symbol, age down to the tenth of a minute, current market cap, bonding-curve progress, and the dev wallet. Filter server-side with minMarketCap and maxAgeMin, then watch the interesting ones climb their curve via the bonding-status endpoint (the two share the exact same curve math, so they can never disagree). Free, no key, no account — built to be polled. Full reference with runnable curls at /docs/crypto-api. (`/docs/crypto-api`) `[feature]`
- **Free text→3D generation API for agents** — Any AI agent can now turn a text prompt into a real 3D model with one call to /api/3d/generate — free, keyless, no account, no wallet. Describe a single object and get back a textured GLB (inline when it finishes fast, otherwise a job token you poll at /api/3d/generate?job=<id>). It runs on the free draft lane (NVIDIA NIM TRELLIS): draft-fidelity geometry, GLB only, no rigging — honest about being a prototyping tier, with a generous per-IP rate limit protecting the shared GPU. Need denser meshes with PBR textures, or an animation-ready rigged character? The response and docs point straight at paid Forge Pro and Rigged Avatars. No other agent-payments platform gives away 3D generation. `[feature, sdk]`
- **Free text→3D now has a first-class API endpoint** — The free text-to-3D lane — the only text-to-mesh service in the agent-payments ecosystem — finally has a clean, versioned endpoint instead of being buried under forge job plumbing. POST a prompt to /api/v1/ai/text-to-3d and get back a textured GLB and a viewer link: no key, no wallet, nothing to sign. It runs on the free NVIDIA NIM TRELLIS lane with a per-IP quota of 10 generations a day; past that it returns a clear rate-limit notice pointing at the paid forge tiers for higher volume and quality, never a silent paywall. The GLB either comes back inline or as a job you poll to completion. (`/docs/api-reference`) `[feature]`
- **Free token security check answers "is this a rug?" in one call** — New free, keyless endpoint: GET /api/v1/token/security turns any Solana mint into an on-chain security report — the first question every trading agent asks before touching a token. It reports whether the mint and freeze authorities are still active (supply can be inflated / accounts frozen), how concentrated the top holders are, how deep the liquidity is, and how old the trading pair is, composing Solana RPC and DexScreener into one answer. There's no invented 'risk score' — just factual flags like mint_authority_active, top1_holder_over_20pct, liquidity_under_10k, and pair_younger_than_24h that agents weigh themselves. Every field is always present (null when a source can't resolve it, never faked), each section degrades independently, and an EVM address gets an honest 'Solana only' 400. Capped at 20 calls/min per IP. (`/docs/api-reference`) `[feature]`
+- **Free token-snapshot API for crypto agents** — New free endpoint in the Crypto Data API: GET /api/crypto/token returns the full current market state of any token from its contract address in one call — price, 24-hour change, market cap, FDV, liquidity, volume, and a link to its trading venue. It reads live DexScreener data on any chain it indexes, and fresh pump.fun launches that don't have a DEX pair yet still resolve through pump.fun's public record. No API key, no account — built for trading agents deciding whether to buy, alert, or ignore. (`/docs/crypto-api`) `[feature, sdk]`
- **Free trending-tokens API for crypto agents** — New free, keyless endpoint GET /api/crypto/trending gives any AI agent a ranked "what's hot right now" list in one call — no account, no key. Tokens are ranked by momentum (a 0–100 score blending windowed trade volume, buy pressure, a volume-spike signal, and short-window price change), fused live across pump.fun, DexScreener's boosted board, and GMGN smart money. Pick a window (5m, 1h, or 24h) and a source (pump.fun only or all), and get back each token's mint, symbol, market cap, volume, price change, score, and link. If an upstream is down it returns whatever ranked data it has with a note instead of failing. (`/docs/crypto-api`) `[feature]`
- **Free wallet portfolio API for agents** — New free, keyless endpoint: GET /api/crypto/wallet returns any wallet's native balance, every token it holds, and a rough USD valuation in one call — no account, no API key. It's built for agents that need to size up a wallet before they act: a treasury agent checking its own runway, a copy-trade agent reading a leader's holdings, or a pre-trade check on a counterparty. Solana works with no key at all (it falls back to the public RPC plus Jupiter and pump.fun pricing); tokens that can't be priced are still listed with their balance, never dropped or faked. `[feature]`
- **Free whale-activity API for crypto agents** — A new free, keyless endpoint tells an AI agent whether big money is moving before it trades. Call /api/crypto/whales with a token mint to see the large buys of that coin, or without one to see the top whale wallets active across pump.fun right now. Each response carries a plain bullish/bearish/neutral signal derived from net whale flow — the SOL whales bought minus the SOL they sold — with no black-box scoring. No account, no key, no payment. `[feature]`
diff --git a/api/_lib/crypto-catalog/launches.js b/api/_lib/crypto-catalog/launches.js
new file mode 100644
index 000000000..0f07087cf
--- /dev/null
+++ b/api/_lib/crypto-catalog/launches.js
@@ -0,0 +1,94 @@
+// Crypto Data API catalog entry — live pump.fun launches feed.
+// Globbed by api/_lib/crypto-catalog/index.js into the /api/crypto front-door
+// index + OpenAPI doc. Stands alone if that index doesn't exist yet.
+
+export default {
+ slug: 'launches',
+ method: 'GET',
+ path: '/api/crypto/launches',
+ title: 'Live pump.fun Launches',
+ summary:
+ 'The freshest pump.fun launches, newest first, with the fields a sniper/discovery ' +
+ 'agent filters on: name, symbol, mint, age, market cap, bonding-curve progress, and ' +
+ 'dev wallet. Poll it free, then watch the interesting mints via /api/crypto/bonding ' +
+ 'and /api/crypto/whales.',
+ free: true,
+ keyless: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ limit: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 100,
+ default: 20,
+ description: 'How many launches to return (newest first).',
+ },
+ minMarketCap: {
+ type: 'number',
+ minimum: 0,
+ description: 'Only launches at or above this USD market cap.',
+ },
+ maxAgeMin: {
+ type: 'number',
+ exclusiveMinimum: 0,
+ description: 'Only launches at most this many minutes old.',
+ },
+ },
+ },
+ outputSchema: {
+ type: 'object',
+ required: ['launches', 'count', 'ts', 'source'],
+ properties: {
+ launches: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['mint', 'url'],
+ properties: {
+ mint: { type: 'string' },
+ name: { type: ['string', 'null'] },
+ symbol: { type: ['string', 'null'] },
+ createdAt: { type: ['string', 'null'], format: 'date-time' },
+ ageMinutes: { type: ['number', 'null'] },
+ marketCapUsd: { type: ['number', 'null'] },
+ bondingProgressPct: { type: ['number', 'null'], minimum: 0, maximum: 100 },
+ graduated: { type: 'boolean' },
+ dev: { type: ['string', 'null'], description: 'creator wallet' },
+ url: { type: 'string', description: 'pump.fun coin page' },
+ imageUrl: { type: ['string', 'null'] },
+ },
+ },
+ },
+ count: { type: 'integer' },
+ ts: { type: 'string', format: 'date-time' },
+ source: {
+ type: 'string',
+ description: '"pumpfun", or "pumpfun:unavailable" when the feed is momentarily unreachable (still a 200 with an empty sweep).',
+ },
+ note: { type: 'string', description: 'present when the sweep is empty — says why' },
+ },
+ },
+ example: {
+ launches: [
+ {
+ mint: 'THREEsynthetic111111111111111111111111111111',
+ name: 'Example Launch',
+ symbol: 'EXMPL',
+ createdAt: '2026-07-07T00:00:00.000Z',
+ ageMinutes: 3.5,
+ marketCapUsd: 6543.21,
+ bondingProgressPct: 4.2,
+ graduated: false,
+ dev: 'THREEsyntheticDev11111111111111111111111111',
+ url: 'https://pump.fun/coin/THREEsynthetic111111111111111111111111111111',
+ imageUrl: null,
+ },
+ ],
+ count: 1,
+ ts: '2026-07-07T00:00:00.000Z',
+ source: 'pumpfun',
+ },
+ related: ['/api/crypto/bonding', '/api/crypto/whales', '/api/crypto/trending'],
+ tags: ['pump.fun', 'launches', 'discovery', 'sniper'],
+};
diff --git a/api/_lib/crypto-catalog/token.js b/api/_lib/crypto-catalog/token.js
new file mode 100644
index 000000000..f66c3717f
--- /dev/null
+++ b/api/_lib/crypto-catalog/token.js
@@ -0,0 +1,51 @@
+// Catalog entry for GET /api/crypto/token — the free token-snapshot endpoint.
+//
+// The /api/crypto index globs every file in this directory and merges the
+// entries into the bundle's discovery doc + OpenAPI. Each entry is a plain,
+// serializable descriptor: no imports, no side effects, safe to load anywhere.
+
+export default {
+ slug: 'token',
+ method: 'GET',
+ path: '/api/crypto/token',
+ title: 'Token Snapshot',
+ summary:
+ 'Current market state of any token by contract address in one call — price, 24 h change, market cap, FDV, liquidity, volume, venue link. DexScreener-backed with a keyless pump.fun fallback for fresh Solana launches. For buy / alert / ignore decisions.',
+ inputSchema: {
+ type: 'object',
+ required: ['address'],
+ properties: {
+ address: {
+ type: 'string',
+ description: 'Token contract address (Solana base58 mint or EVM 0x contract).',
+ },
+ chain: {
+ type: 'string',
+ description:
+ "Optional chain filter ('solana', 'ethereum', 'base', 'bsc', …). Inferred from the address shape when omitted; pins multi-chain EVM deployments to one chain.",
+ },
+ },
+ },
+ outputSchema: {
+ type: 'object',
+ properties: {
+ address: { type: 'string' },
+ chain: { type: 'string' },
+ name: { type: ['string', 'null'] },
+ symbol: { type: ['string', 'null'] },
+ priceUsd: { type: ['number', 'null'] },
+ change24h: { type: ['number', 'null'] },
+ marketCapUsd: { type: ['number', 'null'] },
+ liquidityUsd: { type: ['number', 'null'] },
+ volume24hUsd: { type: ['number', 'null'] },
+ fdvUsd: { type: ['number', 'null'] },
+ pairCreatedAt: { type: ['string', 'null'], format: 'date-time' },
+ dexId: { type: ['string', 'null'] },
+ url: { type: ['string', 'null'] },
+ ts: { type: 'string', format: 'date-time' },
+ sources: { type: 'array', items: { type: 'string' } },
+ note: { type: 'string' },
+ },
+ },
+ example: '/api/crypto/token?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+};
diff --git a/api/_lib/crypto-token-snapshot.js b/api/_lib/crypto-token-snapshot.js
new file mode 100644
index 000000000..6ac5f833b
--- /dev/null
+++ b/api/_lib/crypto-token-snapshot.js
@@ -0,0 +1,171 @@
+// Token snapshot composition for the free Crypto Data API (/api/crypto/token).
+//
+// One call answers "what is this token's current market state?" for a trading or
+// research agent that holds a contract address and must decide buy / alert /
+// ignore. It wraps the existing readers rather than reimplementing them:
+// - DexScreener via fetchTokenMarket (token-market.js) — price / liquidity /
+// mcap / volume / 24 h change, any chain DexScreener indexes, keyless.
+// - pump.fun via fetchPumpCoin (pump-bonding.js) — keyless fallback identity +
+// market cap for Solana mints with no DEX pair yet (fresh bonding-curve
+// launches are exactly the tokens an agent asks about first).
+// - Helius DAS via getMetadataForMints (token-metadata.js) — name/symbol
+// enrichment for non-pump SPL mints, only when a HELIUS_API_KEY exists;
+// degrades to null fields, never fakes.
+//
+// The composition is dependency-injectable so every path — full data, thin data,
+// each upstream down — is unit-testable with synthetic fixtures and no network.
+
+import { fetchTokenMarket, chainOf } from './token-market.js';
+import { fetchPumpCoin, mapBondingStatus } from './pump-bonding.js';
+import { getMetadataForMints } from './token-metadata.js';
+
+// The stable public contract: every response carries exactly these keys, and a
+// field that couldn't be resolved is null — never omitted, never fabricated.
+export const SNAPSHOT_FIELDS = [
+ 'address', 'chain', 'name', 'symbol', 'priceUsd', 'change24h', 'marketCapUsd',
+ 'liquidityUsd', 'volume24hUsd', 'fdvUsd', 'pairCreatedAt', 'dexId', 'url',
+];
+
+/** All-null snapshot skeleton — the shape every merge below fills into. */
+export function emptySnapshot(address, chain) {
+ const snap = {};
+ for (const k of SNAPSHOT_FIELDS) snap[k] = null;
+ snap.address = address;
+ snap.chain = chain ?? null;
+ return snap;
+}
+
+const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
+
+/** Map a fetchTokenMarket() result onto the stable snapshot shape. */
+export function snapshotFromMarket(address, m) {
+ const snap = emptySnapshot(address, m.chain);
+ snap.name = m.name ?? null;
+ snap.symbol = m.symbol ?? null;
+ snap.priceUsd = num(m.price_usd);
+ snap.change24h = num(m.change_24h);
+ snap.marketCapUsd = num(m.market_cap_usd);
+ snap.liquidityUsd = num(m.liquidity_usd);
+ snap.volume24hUsd = num(m.volume_24h_usd);
+ snap.fdvUsd = num(m.fdv_usd);
+ snap.pairCreatedAt = m.pair_created_at ? new Date(m.pair_created_at).toISOString() : null;
+ snap.dexId = m.dex ?? null;
+ snap.url = m.pair_url ?? null;
+ return snap;
+}
+
+/**
+ * Fill a snapshot's null identity/market fields from a raw pump.fun coin object.
+ * Only fills gaps — a DexScreener value already present always wins, since the
+ * DEX pair is the venue actually pricing the token.
+ */
+export function mergePumpCoin(snap, coin) {
+ if (!coin) return snap;
+ if (snap.name == null && coin.name) snap.name = coin.name;
+ if (snap.symbol == null && coin.symbol) snap.symbol = coin.symbol;
+ if (snap.marketCapUsd == null) {
+ snap.marketCapUsd = mapBondingStatus(coin).marketCapUsd;
+ }
+ if (snap.url == null) snap.url = `https://pump.fun/coin/${snap.address}`;
+ if (snap.chain == null) snap.chain = 'solana';
+ return snap;
+}
+
+/**
+ * Is this token-metadata entry the bare placeholder emitted when neither the
+ * cache nor Helius could resolve the mint? (bareEntry: symbol/name are the first
+ * six chars of the mint, decimals null.) A placeholder must never be surfaced as
+ * a real symbol.
+ */
+export function isBareMeta(meta) {
+ if (!meta) return true;
+ return meta.decimals == null && meta.symbol === meta.mint?.slice(0, 6);
+}
+
+/** Fill null name/symbol from a REAL (non-placeholder) metadata entry. */
+export function mergeMeta(snap, meta) {
+ if (isBareMeta(meta)) return snap;
+ if (snap.name == null && meta.name) snap.name = meta.name;
+ if (snap.symbol == null && meta.symbol) snap.symbol = meta.symbol;
+ return snap;
+}
+
+/**
+ * Compose the full snapshot for one address.
+ *
+ * @param {{ address: string, chain?: string|null }} input `chain` is an optional
+ * DexScreener chainId filter ('solana', 'base', 'ethereum', 'bsc', …).
+ * @param {{ fetchMarket?: Function, fetchPump?: Function, fetchMeta?: Function }} [deps]
+ * Injectable upstreams for tests; defaults are the real readers.
+ * @returns {Promise<
+ * | { status: 'ok', snapshot: object, sources: string[], note?: string }
+ * | { status: 'not_found' }
+ * | { status: 'upstream_down' }
+ * >}
+ */
+export async function composeTokenSnapshot(
+ { address, chain = null },
+ { fetchMarket = fetchTokenMarket, fetchPump = fetchPumpCoin, fetchMeta = getMetadataForMints } = {},
+) {
+ const family = chainOf(address); // 'solana' | 'evm' — validated by the caller
+ const sources = [];
+ const degraded = [];
+
+ let market = null;
+ let dexDown = false;
+ try {
+ market = await fetchMarket(address, { chain });
+ } catch {
+ dexDown = true;
+ degraded.push('dexscreener unavailable');
+ }
+ if (market) sources.push('dexscreener');
+
+ let snap = market ? snapshotFromMarket(address, market) : emptySnapshot(address, chain);
+
+ // Solana fallback/enrichment: a mint DexScreener doesn't price yet is very
+ // often a live pump.fun bonding-curve coin — the keyless coin record supplies
+ // identity + market cap. Only consulted when the DEX read left gaps.
+ let pump = null;
+ if (family === 'solana' && (!market || snap.symbol == null)) {
+ pump = await fetchPump(address);
+ if (pump.kind === 'ok') {
+ snap = mergePumpCoin(snap, pump.coin);
+ sources.push('pumpfun');
+ } else if (pump.kind === 'upstream_down') {
+ degraded.push('pump.fun unavailable');
+ }
+ }
+
+ // Helius DAS name/symbol enrichment for non-pump SPL mints — best-effort,
+ // keyed; a placeholder result is discarded, the fields stay null.
+ if (family === 'solana' && snap.symbol == null && (!pump || pump.kind !== 'ok')) {
+ try {
+ const metaMap = await fetchMeta([address]);
+ const meta = metaMap.get(address);
+ if (!isBareMeta(meta)) {
+ snap = mergeMeta(snap, meta);
+ sources.push('helius');
+ }
+ } catch { /* enrichment only — the snapshot stands without it */ }
+ }
+
+ const resolvedAnything = sources.length > 0;
+ if (!resolvedAnything) {
+ // Nothing answered. If any upstream was actually DOWN we can't distinguish
+ // "unknown token" from "source outage" — answer retryable, never a false
+ // not-found. Only when every consulted source responded and none knows the
+ // address is it genuinely not found.
+ const anyDown = dexDown || pump?.kind === 'upstream_down';
+ return { status: anyDown ? 'upstream_down' : 'not_found' };
+ }
+
+ // Family fallback for the chain field when no source named a concrete chain.
+ if (snap.chain == null) snap.chain = family === 'solana' ? 'solana' : (chain || 'evm');
+
+ const result = { status: 'ok', snapshot: snap, sources };
+ if (degraded.length) {
+ result.note = `Partial data: ${degraded.join('; ')} — null fields may be resolvable on retry.`;
+ }
+ return result;
+}
diff --git a/api/_lib/pump-launch-feed.js b/api/_lib/pump-launch-feed.js
index 5c9c3bdd9..5dccfaae3 100644
--- a/api/_lib/pump-launch-feed.js
+++ b/api/_lib/pump-launch-feed.js
@@ -81,6 +81,24 @@ async function solPriceUsd() {
return _solPrice || 0;
}
+/**
+ * Fetch the most-recent RAW pump.fun coin objects (newest-first), keeping the
+ * "feed unreachable" case distinct from "feed genuinely empty" — the free
+ * /api/crypto/launches endpoint needs that distinction for an honest `source`
+ * note, while recentPumpLaunches() below collapses both to [] on purpose.
+ *
+ * @param {{ limit?: number }} [o] how many recent coins to pull (default 50, max 100)
+ * @returns {Promise<{ kind: 'ok', coins: object[] } | { kind: 'upstream_down', coins: [] }>}
+ */
+export async function fetchRecentPumpCoins({ limit = 50 } = {}) {
+ const n = Math.min(100, Math.max(1, Number(limit) || 50));
+ const url = `${PUMP_FRONTEND_BASE}/coins?offset=0&limit=${n}&sort=created_timestamp&order=DESC&includeNsfw=false`;
+ const data = await fetchJsonWithTimeout(url);
+ if (data == null) return { kind: 'upstream_down', coins: [] };
+ const coins = Array.isArray(data) ? data : Array.isArray(data?.coins) ? data.coins : [];
+ return { kind: 'ok', coins };
+}
+
/**
* Fetch the most-recent pump.fun launches (newest-first), normalized. Returns []
* on any feed outage (the runtime treats an empty feed as "no entries this
@@ -92,10 +110,7 @@ async function solPriceUsd() {
*/
export async function recentPumpLaunches({ network = 'mainnet', limit = 50 } = {}) {
if (network !== 'mainnet') return [];
- const n = Math.min(100, Math.max(1, Number(limit) || 50));
- const url = `${PUMP_FRONTEND_BASE}/coins?offset=0&limit=${n}&sort=created_timestamp&order=DESC&includeNsfw=false`;
- const data = await fetchJsonWithTimeout(url);
- const list = Array.isArray(data) ? data : Array.isArray(data?.coins) ? data.coins : [];
+ const { coins: list } = await fetchRecentPumpCoins({ limit });
if (!list.length) return [];
const solPrice = await solPriceUsd();
const out = [];
diff --git a/api/crypto/launches.js b/api/crypto/launches.js
new file mode 100644
index 000000000..5e6a1b26a
--- /dev/null
+++ b/api/crypto/launches.js
@@ -0,0 +1,130 @@
+// GET /api/crypto/launches — free, keyless live feed of the freshest pump.fun
+// launches.
+//
+// Agent use-case: a sniper/discovery agent polls for brand-new pump.fun mints
+// with enough signal to filter — name, symbol, age, market cap, bonding-curve
+// progress, dev wallet — then hands the interesting ones to /api/crypto/bonding
+// (watch the curve) and /api/crypto/whales (watch the money). A free live feed
+// is exactly what agents poll.
+//
+// Part of the free Crypto Data API (/api/crypto/*). Plain-handler pattern: no
+// account, no key, generous per-IP limit. Real data only — the pump.fun public
+// frontend feed via api/_lib/pump-launch-feed.js; curve math shared with
+// /api/crypto/bonding via api/_lib/pump-bonding.js.
+
+import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { fetchRecentPumpCoins } from '../_lib/pump-launch-feed.js';
+import { mapBondingStatus } from '../_lib/pump-bonding.js';
+
+const DEFAULT_LIMIT = 20;
+const MAX_LIMIT = 100;
+
+// Parse an optional numeric query param. Returns null when absent, the number
+// when valid, or NaN when present-but-malformed (caller answers 400).
+function numParam(params, name) {
+ const raw = params.get(name);
+ if (raw == null || raw.trim() === '') return null;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : NaN;
+}
+
+// Raw pump.fun coin → the launch shape agents filter on. Curve math and market
+// cap come from the SAME mapBondingStatus the bonding endpoint uses, so a coin's
+// bondingProgressPct can never disagree between /launches and /bonding.
+export function toLaunch(coin, nowMs) {
+ const s = mapBondingStatus(coin);
+ const createdMs = Number(coin.created_timestamp) || null;
+ return {
+ mint: coin.mint,
+ name: coin.name || null,
+ symbol: coin.symbol || null,
+ createdAt: createdMs ? new Date(createdMs).toISOString() : null,
+ // One decimal so a 30-second-old launch reads 0.5, not a misleading 0 or 1.
+ ageMinutes: createdMs ? Math.max(0, Math.round(((nowMs - createdMs) / 60_000) * 10) / 10) : null,
+ marketCapUsd: s.marketCapUsd,
+ bondingProgressPct: s.bondingProgressPct,
+ graduated: s.graduated,
+ dev: coin.creator || null,
+ url: `https://pump.fun/coin/${coin.mint}`,
+ imageUrl: coin.image_uri || null,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://localhost');
+ const p = url.searchParams;
+
+ const limitRaw = numParam(p, 'limit');
+ if (Number.isNaN(limitRaw) || (limitRaw != null && (!Number.isInteger(limitRaw) || limitRaw < 1))) {
+ return error(res, 400, 'invalid_limit', `\`limit\` must be an integer between 1 and ${MAX_LIMIT} (default ${DEFAULT_LIMIT})`);
+ }
+ const limit = Math.min(MAX_LIMIT, limitRaw ?? DEFAULT_LIMIT);
+
+ const minMarketCap = numParam(p, 'minMarketCap');
+ if (Number.isNaN(minMarketCap) || (minMarketCap != null && minMarketCap < 0)) {
+ return error(res, 400, 'invalid_min_market_cap', '`minMarketCap` must be a non-negative number (USD)');
+ }
+
+ const maxAgeMin = numParam(p, 'maxAgeMin');
+ if (Number.isNaN(maxAgeMin) || (maxAgeMin != null && maxAgeMin <= 0)) {
+ return error(res, 400, 'invalid_max_age_min', '`maxAgeMin` must be a positive number of minutes');
+ }
+
+ // Always pull the full window upstream (one call either way) so filters can
+ // drop coins without under-filling `limit`.
+ const feed = await fetchRecentPumpCoins({ limit: MAX_LIMIT });
+ const ts = new Date().toISOString();
+
+ // Feed momentarily unreachable → an empty 200 with an honest source note,
+ // never a 500: a polling agent treats it as "nothing this sweep" and retries.
+ if (feed.kind === 'upstream_down') {
+ return json(
+ res,
+ 200,
+ {
+ launches: [],
+ count: 0,
+ ts,
+ source: 'pumpfun:unavailable',
+ note: 'pump.fun feed is temporarily unreachable — empty sweep, retry shortly',
+ },
+ { 'cache-control': 'no-store' },
+ );
+ }
+
+ const now = Date.now();
+ let launches = feed.coins
+ .filter((c) => c && c.mint)
+ .map((c) => toLaunch(c, now))
+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
+
+ // A coin whose cap/age is unknown can't prove it clears the bar — filters drop
+ // it rather than guess.
+ if (minMarketCap != null) {
+ launches = launches.filter((l) => l.marketCapUsd != null && l.marketCapUsd >= minMarketCap);
+ }
+ if (maxAgeMin != null) {
+ launches = launches.filter((l) => l.ageMinutes != null && l.ageMinutes <= maxAgeMin);
+ }
+ launches = launches.slice(0, limit);
+
+ const body = { launches, count: launches.length, ts, source: 'pumpfun' };
+ if (!launches.length) {
+ body.note = 'no launches match the current filters — relax minMarketCap / maxAgeMin or retry';
+ }
+ return json(
+ res,
+ 200,
+ body,
+ // Fresh launches appear every few seconds; a short CDN window keeps polling
+ // agents current without hammering the pump.fun feed.
+ { 'cache-control': 'public, s-maxage=10, stale-while-revalidate=20' },
+ );
+});
diff --git a/api/crypto/token.js b/api/crypto/token.js
new file mode 100644
index 000000000..b56c17592
--- /dev/null
+++ b/api/crypto/token.js
@@ -0,0 +1,106 @@
+// GET /api/crypto/token — free, keyless token market snapshot for AI agents.
+//
+// Agent use-case: a trading/research agent holds a contract address and needs the
+// token's current market state in ONE call before deciding to buy, alert, or
+// ignore. Without this it juggles DexScreener + an RPC + a price API; here one
+// free read returns identity, price, 24 h change, market cap, FDV, liquidity,
+// volume, and the venue link — with honest nulls for anything unresolvable.
+//
+// Part of the free Crypto Data API (/api/crypto/*). Plain-handler pattern: no
+// account, no key, generous per-IP limit. Real data only — DexScreener for the
+// market read (any chain it indexes), pump.fun's public coin record as the
+// keyless fallback for fresh Solana launches with no DEX pair yet, Helius DAS
+// name/symbol enrichment when a key exists (else those fields stay null).
+//
+// Query:
+// address = <Solana mint | EVM 0x contract> (required)
+// chain = solana | ethereum | base | bsc | … (optional — inferred from the
+// address shape when omitted; for multi-chain EVM deployments it
+// pins the read to one chain instead of the deepest pool overall)
+//
+// Response (stable schema — every key always present, unresolved = null):
+// { address, chain, name, symbol, priceUsd, change24h, marketCapUsd,
+// liquidityUsd, volume24hUsd, fdvUsd, pairCreatedAt, dexId, url, ts,
+// sources[], note? }
+
+import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { chainOf } from '../_lib/token-market.js';
+import { composeTokenSnapshot } from '../_lib/crypto-token-snapshot.js';
+
+const EXAMPLE = '/api/crypto/token?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Friendly aliases → the DexScreener chainId the pair filter understands.
+const CHAIN_ALIASES = { sol: 'solana', eth: 'ethereum', mainnet: 'ethereum' };
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const ip = clientIp(req);
+ const [ipRl, globalRl] = await Promise.all([limits.cryptoDataIp(ip), limits.cryptoDataGlobal()]);
+ if (!ipRl.success) return rateLimited(res, ipRl);
+ if (!globalRl.success) return rateLimited(res, globalRl);
+
+ const url = new URL(req.url, 'http://localhost');
+ const address = (url.searchParams.get('address') || '').trim();
+ const rawChain = (url.searchParams.get('chain') || '').trim().toLowerCase();
+ const chain = rawChain ? (CHAIN_ALIASES[rawChain] || rawChain) : null;
+
+ if (!address) {
+ return error(res, 400, 'missing_address', 'query param `address` is required — pass a token contract address (Solana mint or EVM 0x)', {
+ example: EXAMPLE,
+ });
+ }
+
+ // Address-family inference BEFORE any upstream call: base58 → Solana,
+ // 0x40-hex → EVM, anything else is a fast 400 instead of a wasted round-trip.
+ const family = chainOf(address);
+ if (!family) {
+ return error(res, 400, 'invalid_address', 'not a token contract address — expected a base58 Solana mint or a 0x EVM contract', {
+ address,
+ example: EXAMPLE,
+ });
+ }
+
+ // A chain that contradicts the address shape can never resolve — say so now.
+ if (chain && ((chain === 'solana') !== (family === 'solana'))) {
+ return error(res, 400, 'chain_mismatch', `address is a ${family === 'solana' ? 'Solana mint' : '0x EVM contract'} but \`chain=${rawChain}\` is ${family === 'solana' ? 'an EVM chain' : 'solana'}`, {
+ address,
+ example: EXAMPLE,
+ });
+ }
+
+ const result = await composeTokenSnapshot({ address, chain });
+ const ts = new Date().toISOString();
+
+ // Valid address shape, but no live source knows it on the requested chain —
+ // a client-input miss, not a fault (matches the bundle's /bonding convention).
+ if (result.status === 'not_found') {
+ return error(res, 400, 'token_not_found', `${address} is not a token any live source can resolve${chain ? ` on ${chain}` : ''} — check the address${chain ? ' and chain' : ''}, or discover live tokens at /api/crypto/trending`, {
+ address,
+ ...(chain ? { chain } : {}),
+ });
+ }
+
+ // Every consulted source is unreachable — never 500; 503 + Retry-After so the
+ // agent backs off and retries, per the free-API contract.
+ if (result.status === 'upstream_down') {
+ return json(res, 503, {
+ error: 'upstream_unavailable',
+ error_description: 'token data sources are temporarily unreachable — retry shortly',
+ address,
+ retry_after: 15,
+ ts,
+ }, { 'cache-control': 'no-store', 'retry-after': '15' });
+ }
+
+ const body = { ...result.snapshot, ts, sources: result.sources };
+ if (result.note) body.note = result.note;
+
+ // Market state moves fast but not sub-30s fast; a short CDN cache + SWR
+ // collapses bursts of agents polling the same token without serving stale data.
+ return json(res, 200, body, {
+ 'cache-control': 'public, s-maxage=30, stale-while-revalidate=60',
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index a70f2ee9e..0838f6fb5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-07",
+ "title": "Free live pump.fun launches feed for agents",
+ "summary": "The Crypto Data API now has a live launch feed: GET /api/crypto/launches returns the freshest pump.fun mints, newest first, with everything a discovery or sniper agent filters on — name, symbol, age down to the tenth of a minute, current market cap, bonding-curve progress, and the dev wallet. Filter server-side with minMarketCap and maxAgeMin, then watch the interesting ones climb their curve via the bonding-status endpoint (the two share the exact same curve math, so they can never disagree). Free, no key, no account — built to be polled. Full reference with runnable curls at /docs/crypto-api.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/docs/crypto-api"
+ },
+ {
+ "date": "2026-07-07",
+ "title": "Free token-snapshot API for crypto agents",
+ "summary": "New free endpoint in the Crypto Data API: GET /api/crypto/token returns the full current market state of any token from its contract address in one call — price, 24-hour change, market cap, FDV, liquidity, volume, and a link to its trading venue. It reads live DexScreener data on any chain it indexes, and fresh pump.fun launches that don't have a DEX pair yet still resolve through pump.fun's public record. No API key, no account — built for trading agents deciding whether to buy, alert, or ignore.",
+ "tags": [
+ "feature",
+ "sdk"
+ ],
+ "link": "/docs/crypto-api"
+ },
{
"date": "2026-07-07",
"title": "Free bonding-curve status API for pump.fun tokens",
diff --git a/docs/crypto-api.md b/docs/crypto-api.md
index a13884a05..50362c399 100644
--- a/docs/crypto-api.md
+++ b/docs/crypto-api.md
@@ -44,7 +44,9 @@ is documented in its section below and machine-readable in the OpenAPI doc.
| Endpoint | Verb(s) | What it answers |
|----------|---------|-----------------|
| [`/api/crypto/bonding`](https://three.ws/api/crypto/bonding) | `GET` | Where a pump.fun token sits on its bonding curve — % to graduation, SOL in the curve, and whether it has migrated to an AMM. |
+| [`/api/crypto/launches`](https://three.ws/api/crypto/launches) | `GET` | The freshest pump.fun launches, newest first — age, market cap, bonding-curve progress, dev wallet — with `minMarketCap` / `maxAgeMin` filters built for polling agents. |
| [`/api/crypto/symbol`](https://three.ws/api/crypto/symbol) | `GET` · `POST` | Whether up to 20 candidate tickers are taken — exact and fuzzy (look-alike) collisions across live registries. |
+| [`/api/crypto/token`](https://three.ws/api/crypto/token) | `GET` | The current market state of any token by contract address — price, 24 h change, market cap, FDV, liquidity, volume, and venue link in one call. |
| [`/api/crypto/trending`](https://three.ws/api/crypto/trending) | `GET` | Solana tokens ranked by momentum (volume + buy pressure + spike + short-window price change) fused across sources. |
| [`/api/crypto/wallet`](https://three.ws/api/crypto/wallet) | `GET` | A wallet's native balance, every token it holds, and a rough USD valuation — keyless on Solana. |
| [`/api/crypto/whales`](https://three.ws/api/crypto/whales) | `GET` | Large buys on pump.fun for a token or market-wide, with a deterministic bullish/bearish/neutral buy-pressure signal. |
@@ -56,6 +58,83 @@ is documented in its section below and machine-readable in the OpenAPI doc.
---
+## `GET /api/crypto/launches` — Live pump.fun launches
+
+**Use-case.** A sniper/discovery agent wants the freshest pump.fun launches with
+enough signal to filter on the spot: name, symbol, mint, **age**, current
+**market cap**, **bonding-curve progress**, and the **dev wallet**. New mints
+appear every few seconds; a free live feed is exactly what such an agent polls.
+Feed the interesting mints to [`/api/crypto/bonding`](#get-apicryptobonding--bonding-curve--graduation-status)
+to watch their curve and [`/api/crypto/whales`](#get-apicryptowhales--whale--large-buy-activity)
+to watch the money.
+
+`bondingProgressPct` here is computed by the **same shared curve math** as
+`/api/crypto/bonding` ([`api/_lib/pump-bonding.js`](../api/_lib/pump-bonding.js)),
+so the two endpoints can never disagree about a coin's progress.
+
+### Request
+
+| Param | Type | Notes |
+|-------|------|-------|
+| `limit` | integer | How many launches to return, newest first. Default `20`, values above `100` are capped (not an error). |
+| `minMarketCap` | number | Optional. Only launches at or above this USD market cap. Coins whose cap is unknown are dropped, never guessed. |
+| `maxAgeMin` | number | Optional. Only launches at most this many minutes old. |
+
+### Response
+
+```json
+{
+ "launches": [
+ {
+ "mint": "THREEsynthetic111111111111111111111111111111",
+ "name": "Example Launch",
+ "symbol": "EXMPL",
+ "createdAt": "2026-07-07T02:29:41.000Z",
+ "ageMinutes": 0.2,
+ "marketCapUsd": 1180.09,
+ "bondingProgressPct": 0.13,
+ "graduated": false,
+ "dev": "THREEsyntheticDev11111111111111111111111111",
+ "url": "https://pump.fun/coin/THREEsynthetic111111111111111111111111111111",
+ "imageUrl": "https://ipfs.io/ipfs/…"
+ }
+ ],
+ "count": 1,
+ "ts": "2026-07-07T02:29:55.000Z",
+ "source": "pumpfun"
+}
+```
+
+- **`ageMinutes`** — one decimal, so a 30-second-old launch reads `0.5`, not `0` or `1`.
+- **`bondingProgressPct`** — `0`–`100` share of the curve bought out; `100` (with
+ `graduated: true`) for a coin that already left the curve.
+- **`dev`** — the creator wallet, for dev-reputation filtering.
+- Unresolvable fields are `null`, never omitted, never faked.
+
+### States
+
+- **Launches found** → `200`, sorted newest first, filters applied.
+- **Nothing matches the filters** → `200` with `launches: [], count: 0` and a
+ `note` saying which knobs to relax — an empty sweep is a valid answer, not an error.
+- **pump.fun feed momentarily unreachable** → `200` with `launches: []` and
+ `source: "pumpfun:unavailable"` + a retry note. A polling agent treats it as
+ "nothing this sweep". Never `500`.
+- **Malformed `limit` / `minMarketCap` / `maxAgeMin`** → `400` with a clear message.
+- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.
+
+### Examples
+
+```bash
+# The 5 freshest launches
+curl "https://three.ws/api/crypto/launches?limit=5"
+
+# Snipe filter: under 30 minutes old AND already at $5k+ market cap
+curl "https://three.ws/api/crypto/launches?maxAgeMin=30&minMarketCap=5000" \
+ | jq '.launches[] | {symbol, ageMinutes, marketCapUsd, bondingProgressPct}'
+```
+
+---
+
## `GET /api/crypto/bonding` — Bonding-curve / graduation status
**Use-case.** An agent holding or watching a pump.fun token needs to know exactly
@@ -491,3 +570,75 @@ curl -s "https://three.ws/api/crypto/trending?window=1h&limit=5&source=all"
# pump.fun only, 24h window
curl -s "https://three.ws/api/crypto/trending?window=24h&source=pumpfun"
```
+
+---
+
+## `GET /api/crypto/token` — Token snapshot
+
+**Use-case.** A *trading or research agent* holds a contract address — from a
+signal, a mention, a whale buy — and must decide **buy, alert, or ignore** before
+acting. Today that means juggling DexScreener + an RPC + a price API and
+reconciling three formats. This is one free call that returns the token's whole
+current market state, with honest `null`s for anything no live source can resolve.
+
+### Request
+
+| Param | Type | Default | Notes |
+|-----------|--------|----------|-------|
+| `address` | string | required | Token contract address — Solana base58 mint or EVM `0x` contract. |
+| `chain` | string | inferred | Optional chain pin (`solana`, `ethereum`, `base`, `bsc`, …). Inferred from the address shape when omitted; for an EVM contract deployed on several chains it selects that chain instead of the deepest pool overall. Aliases `sol`/`eth` accepted. |
+
+### Response
+
+Stable schema — **every key is always present**; a field that couldn't be
+resolved is `null`, never omitted, never fabricated.
+
+```json
+{
+ "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "chain": "solana",
+ "name": "three.ws",
+ "symbol": "three",
+ "priceUsd": 0.001653,
+ "change24h": 19.41,
+ "marketCapUsd": 1652862,
+ "liquidityUsd": 206627.53,
+ "volume24hUsd": 413939.89,
+ "fdvUsd": 1652862,
+ "pairCreatedAt": "2026-04-29T07:09:01.000Z",
+ "dexId": "pumpswap",
+ "url": "https://dexscreener.com/solana/…",
+ "ts": "2026-07-07T02:30:00.000Z",
+ "sources": ["dexscreener"]
+}
+```
+
+- **`sources`** — which upstreams actually contributed (`dexscreener`,
+ `pumpfun`, `helius`), so an agent can reason about freshness and coverage.
+- **`note`** — present only when a source was down and the snapshot is partial.
+
+**Sources, in order:** DexScreener prices the deepest pool for the address (any
+chain it indexes, keyless). A Solana mint with **no DEX pair yet** — typically a
+live pump.fun bonding-curve coin — falls back to pump.fun's public coin record
+for name, symbol, market cap, and a pump.fun link. Non-pump SPL mints get
+name/symbol enrichment via Helius DAS when the deployment has a key; without one
+those fields are simply `null`.
+
+### States
+
+- **Thin data** (new launch, no pair) → `200` with the fields that exist + the rest `null`.
+- **Missing/invalid `address`, contradictory `chain`** → `400` with a message + example.
+- **Valid address no live source knows** → `400 token_not_found` with a pointer to
+ [`/api/crypto/trending`](https://three.ws/api/crypto/trending) for discovery.
+- **All upstreams unreachable** → `503` + `Retry-After` (never a false not-found, never `500`).
+- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.
+
+### Examples
+
+```bash
+# Full snapshot of $THREE by mint (chain inferred)
+curl -s "https://three.ws/api/crypto/token?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
+
+# Pin a multi-chain EVM contract to one chain
+curl -s "https://three.ws/api/crypto/token?address=0x1111111111111111111111111111111111111111&chain=base"
+```
diff --git a/docs/gcp-credits.md b/docs/gcp-credits.md
index fa66a5109..52fe14cc3 100644
--- a/docs/gcp-credits.md
+++ b/docs/gcp-credits.md
@@ -70,11 +70,11 @@ Record here once confirmed:
| Field | Value |
|---|---|
-| Billing account | _pending_ |
-| Credits applied | _pending_ |
-| Remaining balance | _pending_ |
-| Expiry date | _pending_ |
-| Covers Anthropic partner models? | _pending (see console check above)_ |
+| Billing account | `billingAccounts/01B467-A61905-9A97D2` — displayName **Sperax**, `open: true`, USD, org `530103279143` (verified 2026-07-07) |
+| Credits applied | _pending — console Credits page (CLI cannot read it)_ |
+| Remaining balance | _pending — console_ |
+| Expiry date | _pending — console_ |
+| Covers Anthropic partner models? | _pending — console check above_ |
---
@@ -101,14 +101,16 @@ gcloud services list --enabled --project aerial-vehicle-466722-p5 \
| API | Enabled? |
|---|---|
-| aiplatform.googleapis.com | _pending_ |
-| run.googleapis.com | _pending_ |
-| cloudbuild.googleapis.com | _pending_ |
-| storage.googleapis.com | _pending_ |
-| compute.googleapis.com | _pending_ |
-| bigquery.googleapis.com | _pending_ |
-| cloudbilling.googleapis.com | _pending_ |
-| monitoring.googleapis.com | _pending_ |
+| aiplatform.googleapis.com | ✅ 2026-07-07 |
+| run.googleapis.com | ✅ 2026-07-07 |
+| cloudbuild.googleapis.com | ✅ 2026-07-07 |
+| storage.googleapis.com | ✅ 2026-07-07 |
+| compute.googleapis.com | ✅ 2026-07-07 |
+| bigquery.googleapis.com | ✅ 2026-07-07 |
+| cloudbilling.googleapis.com | ✅ 2026-07-07 |
+| monitoring.googleapis.com | ✅ 2026-07-07 |
+
+Also enabled 2026-07-07: `billingbudgets.googleapis.com`, `pubsub.googleapis.com` (prompt 07 budgets/alerts).
---
@@ -118,8 +120,8 @@ gcloud services list --enabled --project aerial-vehicle-466722-p5 \
| SA | Purpose | Roles | Status |
|---|---|---|---|
-| `avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com` | Cloud Run workers (mesh/rig pipeline), used by `workers/deploy/*.sh` + cloudbuild | run/build identity | Pre-existing — confirm still valid |
-| `vercel-inference@aerial-vehicle-466722-p5.iam.gserviceaccount.com` | Vercel functions → Vertex Claude + Imagen | `roles/aiplatform.user` | **To create** (below) |
+| `avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com` | Cloud Run workers (mesh/rig pipeline), used by `workers/deploy/*.sh` + cloudbuild | run/build identity | ✅ Confirmed valid 2026-07-07 |
+| `vercel-inference@aerial-vehicle-466722-p5.iam.gserviceaccount.com` | Vercel functions → Vertex Claude + Imagen | `roles/aiplatform.user` | ✅ Created + role bound + key minted 2026-07-07 (key held locally, pending Vercel env push) |
### Create the Vercel inference SA (blocked)
@@ -394,16 +396,18 @@ any Vertex error degrading cleanly to FLUX. Which provider served each image is
logged (`[text-to-image] served by <model>`) and persisted on the forge job as
`text_to_image_model`.
-### Verification status (blocked on the same creds as the rest of this runbook)
+### Verification status
Static verification is **done**: model IDs checked against live Vertex docs; both
request/response shapes and the gate + fallback are covered by unit tests
(`tests/api/vertex-imagen.test.js`, `tests/api/text-to-image.test.js` — green).
-Live E2E ("prove the pixels") is **blocked**: no GCP creds are present (Vercel has
-no `GOOGLE_CLOUD_PROJECT`; local `gcloud` needs interactive reauth; `aiplatform`
-is not yet enabled on the project — see **Pending human actions**). Run this once
-creds land, to satisfy the quality gate before any production enablement:
+**Live E2E passed 2026-07-07**: `generateImage()` against the real project
+(`vercel-inference` SA key, `us-central1`) returned a 901 KB on-prompt PNG —
+`served by vertex-ai/gemini-2.5-flash-image`, isolated subject on a plain white
+background, visually verified. Remaining before *production* enablement: the
+3–4-prompt reconstruction-quality comparison vs the FLUX lane (below), and the
+Vercel env push. The command used:
```bash
export GOOGLE_CLOUD_PROJECT=aerial-vehicle-466722-p5
@@ -442,27 +446,32 @@ reconstruction quality holds. If it regresses, keep the image lane on FLUX
## Pending human actions (do these, in order)
-1. **Restore gcloud auth** (unblocks everything below). This environment's
- `gcloud` fails with *"Reauthentication failed. cannot prompt during
- non-interactive execution"* — the org enforces a session-control reauth
- interval. Owner runs, interactively:
- ```bash
- gcloud auth login # re-consent the project owner's Google account
- gcloud auth application-default login # for Claude Code dev sessions
- gcloud config set project aerial-vehicle-466722-p5
- ```
+1. ~~**Restore gcloud auth**~~ — ✅ done 2026-07-07 (`gcloud auth login`,
+ project `aerial-vehicle-466722-p5`). **Still pending:** `gcloud auth
+ application-default login` (ADC) — needed only for Claude Code dev sessions
+ on Vertex and any script that insists on ADC; everything below used the
+ user token / SA key instead.
2. **Confirm credits + partner-model coverage** — console Credits page; answer
the coverage question (see that section). This is the GO/NO-GO for prompt 02.
3. **Enable Claude in Model Garden** — console, accept Anthropic terms, enable
- the five model IDs listed above.
-4. **Run the live setup block** — after step 1, an agent (or the owner) runs the
- API-enable, SA-create, key-mint, Vercel-env, and quota commands above; they
- are all non-interactive once auth works.
+ the five model IDs listed above. **Confirmed still missing 2026-07-07:** the
+ smoke test returns `IAM_PERMISSION_DENIED` on
+ `publishers/anthropic/models/*` while the same SA serves Gemini images fine —
+ the terms acceptance is the only remaining gate.
+4. ~~**Run the live setup block**~~ — ✅ done 2026-07-07: APIs enabled (table
+ above), `vercel-inference` SA created + `roles/aiplatform.user` bound, key
+ minted (held locally outside the repo, pending Vercel push). Quota filing
+ still open (partner-model QPM/TPM — console).
5. **Install + auth the Vercel CLI** (`npm i -g vercel && vercel login`) so
`GCP_SERVICE_ACCOUNT_JSON` + the three location vars can be pushed and
verified with `vercel env ls`.
-6. **Run the smoke test** — `node scripts/gcp/vertex-smoke.mjs`. A green PASS
- closes out this prompt's acceptance criteria.
+6. **Run the smoke test** — `node scripts/gcp/vertex-smoke.mjs`. Attempted
+ 2026-07-07: 403 (Model Garden — step 3). The Gemini image-lane E2E **passed**
+ the same day with the same SA, proving auth, API enablement, and the client
+ code end-to-end. Re-run after step 3; a green PASS closes prompt 01.
+7. **Enable the BigQuery billing export** (prompt 07) — console-only:
+ Billing → Billing export → BigQuery. Confirmed 2026-07-07 that no dataset
+ exists yet (`bq ls` empty; `burn-report.mjs` → "export not configured").
Update the _pending_ cells in this file as each step completes.
diff --git a/public/changelog.json b/public/changelog.json
index 3ff554216..1c53568a9 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-07T01:01:47.631Z",
+ "generated_at": "2026-07-07T02:31:30.946Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -98,6 +98,16 @@
"feature"
]
},
+ {
+ "date": "2026-07-07",
+ "type": "update",
+ "title": "Free live pump.fun launches feed for agents",
+ "summary": "The Crypto Data API now has a live launch feed: GET /api/crypto/launches returns the freshest pump.fun mints, newest first, with everything a discovery or sniper agent filters on — name, symbol, age down to the tenth of a minute, current market cap, bonding-curve progress, and the dev wallet. Filter server-side with minMarketCap and maxAgeMin, then watch the interesting ones climb their curve via the bonding-status endpoint (the two share the exact same curve math, so they can never disagree). Free, no key, no account — built to be polled. Full reference with runnable curls at /docs/crypto-api.",
+ "link": "/docs/crypto-api",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-07",
"type": "update",
@@ -129,6 +139,17 @@
"feature"
]
},
+ {
+ "date": "2026-07-07",
+ "type": "update",
+ "title": "Free token-snapshot API for crypto agents",
+ "summary": "New free endpoint in the Crypto Data API: GET /api/crypto/token returns the full current market state of any token from its contract address in one call — price, 24-hour change, market cap, FDV, liquidity, volume, and a link to its trading venue. It reads live DexScreener data on any chain it indexes, and fresh pump.fun launches that don't have a DEX pair yet still resolve through pump.fun's public record. No API key, no account — built for trading agents deciding whether to buy, alert, or ignore.",
+ "link": "/docs/crypto-api",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-07-07",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 6e511335b..b3de2a813 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -78,6 +78,14 @@
<category>feature</category>
<description>A new free, keyless endpoint tells an agent exactly where a pump.fun token sits on its bonding curve: how far along it is toward graduation (%), how much SOL is in the curve, how many tokens are left to buy, and whether it has already graduated and migrated to Raydium or PumpSwap. Timing entries and exits around graduation is a core meme-trading move, and this is the one call that answers it — no account, no key, just GET /api/crypto/bonding?mint=&lt;mint&gt;. It pairs with the live launches feed to watch fresh mints climb their curve. Part of the free three.ws Crypto Data API; full reference with runnable curls at /docs/crypto-api.</description>
</item>
+ <item>
+ <title>Free live pump.fun launches feed for agents</title>
+ <link>https://three.ws/docs/crypto-api</link>
+ <guid isPermaLink="false">2026-07-07:Free live pump.fun launches feed for agents</guid>
+ <pubDate>Tue, 07 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The Crypto Data API now has a live launch feed: GET /api/crypto/launches returns the freshest pump.fun mints, newest first, with everything a discovery or sniper agent filters on — name, symbol, age down to the tenth of a minute, current market cap, bonding-curve progress, and the dev wallet. Filter server-side with minMarketCap and maxAgeMin, then watch the interesting ones climb their curve via the bonding-status endpoint (the two share the exact same curve math, so they can never disagree). Free, no key, no account — built to be polled. Full reference with runnable curls at /docs/crypto-api.</description>
+ </item>
<item>
<title>Free text→3D generation API for agents</title>
<link>https://three.ws/changelog</link>
@@ -102,6 +110,14 @@
<category>feature</category>
<description>New free, keyless endpoint: GET /api/v1/token/security turns any Solana mint into an on-chain security report — the first question every trading agent asks before touching a token. It reports whether the mint and freeze authorities are still active (supply can be inflated / accounts frozen), how concentrated the top holders are, how deep the liquidity is, and how old the trading pair is, composing Solana RPC and DexScreener into one answer. There's no invented 'risk score' — just factual flags like mint_authority_active, top1_holder_over_20pct, liquidity_under_10k, and pair_younger_than_24h that agents weigh themselves. Every field is always present (null when a source can't resolve it, never faked), each section degrades independently, and an EVM address gets an honest 'Solana only' 400. Capped at 20 calls/min per IP.</description>
</item>
+ <item>
+ <title>Free token-snapshot API for crypto agents</title>
+ <link>https://three.ws/docs/crypto-api</link>
+ <guid isPermaLink="false">2026-07-07:Free token-snapshot API for crypto agents</guid>
+ <pubDate>Tue, 07 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>New free endpoint in the Crypto Data API: GET /api/crypto/token returns the full current market state of any token from its contract address in one call — price, 24-hour change, market cap, FDV, liquidity, volume, and a link to its trading venue. It reads live DexScreener data on any chain it indexes, and fresh pump.fun launches that don't have a DEX pair yet still resolve through pump.fun's public record. No API key, no account — built for trading agents deciding whether to buy, alert, or ignore.</description>
+ </item>
<item>
<title>Free trending-tokens API for crypto agents</title>
<link>https://three.ws/docs/crypto-api</link>
diff --git a/public/features.json b/public/features.json
index bd93ee6a7..b9f8cbdd8 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-07T01:01:47.616Z",
+ "generated_at": "2026-07-07T02:31:30.927Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index b42b77a2a..81786db2d 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,25 +56,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:locale" content="en_US">
- <meta property="og:title" content="Sitemap · three.ws">
- <meta property="og:description" content="Human-readable index of every page on three.ws.">
- <meta property="og:url" content="https://three.ws/sitemap">
- <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta property="og:image:type" content="image/png">
- <meta property="og:image:alt" content="Sitemap — three.ws">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:site" content="@trythreews">
- <meta name="twitter:title" content="Sitemap · three.ws">
- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/tests/crypto-launches-endpoint.test.js b/tests/crypto-launches-endpoint.test.js
new file mode 100644
index 000000000..dc63eb7b9
--- /dev/null
+++ b/tests/crypto-launches-endpoint.test.js
@@ -0,0 +1,199 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Test the endpoint's COMPOSITION + branching (param validation, filters,
+// mapping, empty vs upstream-down), not the network beneath it. The curve math
+// (mapBondingStatus) is pure and stays REAL — the whole point is that /launches
+// and /bonding can never disagree on bondingProgressPct.
+vi.mock('../api/_lib/http.js', () => ({
+ wrap: (fn) => fn,
+ cors: () => false,
+ method: () => true,
+ rateLimited: (res) => {
+ res._json = { status: 429, body: { error: 'rate_limited' } };
+ return res;
+ },
+ error: (res, status, code, message, extra = {}) => {
+ res._json = { status, body: { error: code, error_description: message, ...extra } };
+ return res;
+ },
+ json: (res, status, body) => {
+ res._json = { status, body };
+ return res;
+ },
+}));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '1.2.3.4',
+}));
+// Keep the real module (pump-bonding.js imports isGraduated from it) and stub
+// only the network fetch.
+vi.mock('../api/_lib/pump-launch-feed.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ fetchRecentPumpCoins: vi.fn(),
+}));
+
+import handler, { toLaunch } from '../api/crypto/launches.js';
+import { fetchRecentPumpCoins } from '../api/_lib/pump-launch-feed.js';
+import { limits } from '../api/_lib/rate-limit.js';
+
+const NOW = Date.parse('2026-07-07T12:00:00.000Z');
+
+// Synthetic pump.fun coin objects only — never a real third-party mint.
+function coin(n, { ageMin = 5, mcUsd = 5000, reserves = 700_000_000 * 1e6, complete = false } = {}) {
+ return {
+ mint: `THREEsynthetic${String(n).padStart(30, '1')}`,
+ name: `Synthetic ${n}`,
+ symbol: `SYN${n}`,
+ created_timestamp: NOW - ageMin * 60_000,
+ usd_market_cap: mcUsd,
+ real_token_reserves: complete ? 0 : reserves,
+ real_sol_reserves: complete ? 0 : 12 * 1e9,
+ bonding_curve: `THREEsyntheticCurve${String(n).padStart(24, '1')}`,
+ creator: `THREEsyntheticDev${String(n).padStart(26, '1')}`,
+ image_uri: null,
+ complete,
+ };
+}
+
+function fakeRes() {
+ return { setHeader() {}, end() {}, statusCode: 200 };
+}
+function call(url) {
+ const res = fakeRes();
+ return handler({ method: 'GET', url, headers: {} }, res).then(() => res);
+}
+
+beforeEach(() => {
+ fetchRecentPumpCoins.mockReset();
+ limits.publicIp.mockResolvedValue({ success: true });
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('toLaunch mapping', () => {
+ it('maps a raw coin to the documented launch shape', () => {
+ const l = toLaunch(coin(1, { ageMin: 3.5, mcUsd: 6543.21 }), NOW);
+ expect(l).toEqual({
+ mint: expect.stringMatching(/^THREEsynthetic/),
+ name: 'Synthetic 1',
+ symbol: 'SYN1',
+ createdAt: new Date(NOW - 3.5 * 60_000).toISOString(),
+ ageMinutes: 3.5,
+ marketCapUsd: 6543.21,
+ bondingProgressPct: expect.any(Number),
+ graduated: false,
+ dev: expect.stringMatching(/^THREEsyntheticDev/),
+ url: expect.stringContaining('https://pump.fun/coin/THREEsynthetic'),
+ imageUrl: null,
+ });
+ // 700M of the 793.1M-token float still unsold → ~11.7% bought out.
+ expect(l.bondingProgressPct).toBeCloseTo((1 - 700_000_000 / 793_100_000) * 100, 1);
+ });
+
+ it('marks a completed coin graduated with progress pinned to 100', () => {
+ const l = toLaunch(coin(2, { complete: true }), NOW);
+ expect(l.graduated).toBe(true);
+ expect(l.bondingProgressPct).toBe(100);
+ });
+
+ it('degrades missing timestamps to null age, never NaN', () => {
+ const c = coin(3);
+ delete c.created_timestamp;
+ const l = toLaunch(c, NOW);
+ expect(l.createdAt).toBeNull();
+ expect(l.ageMinutes).toBeNull();
+ });
+});
+
+describe('GET /api/crypto/launches', () => {
+ it('returns launches newest-first with count/ts/source', async () => {
+ fetchRecentPumpCoins.mockResolvedValue({
+ kind: 'ok',
+ coins: [coin(1, { ageMin: 10 }), coin(2, { ageMin: 1 }), coin(3, { ageMin: 5 })],
+ });
+ const res = await call('/api/crypto/launches');
+ expect(res._json.status).toBe(200);
+ const { launches, count, source, ts } = res._json.body;
+ expect(count).toBe(3);
+ expect(source).toBe('pumpfun');
+ expect(typeof ts).toBe('string');
+ expect(launches.map((l) => l.ageMinutes)).toEqual([1, 5, 10]);
+ });
+
+ it('defaults to 20 and caps limit at 100 instead of erroring', async () => {
+ fetchRecentPumpCoins.mockResolvedValue({
+ kind: 'ok',
+ coins: Array.from({ length: 60 }, (_, i) => coin(i)),
+ });
+ const def = await call('/api/crypto/launches');
+ expect(def._json.body.count).toBe(20);
+ const capped = await call('/api/crypto/launches?limit=100');
+ expect(capped._json.body.count).toBe(60);
+ // Upstream is always asked for the full window so filters can't under-fill.
+ expect(fetchRecentPumpCoins).toHaveBeenCalledWith({ limit: 100 });
+ });
+
+ it('400s malformed limit / minMarketCap / maxAgeMin before any upstream call', async () => {
+ for (const [qs, code] of [
+ ['limit=abc', 'invalid_limit'],
+ ['limit=0', 'invalid_limit'],
+ ['limit=2.5', 'invalid_limit'],
+ ['minMarketCap=-5', 'invalid_min_market_cap'],
+ ['minMarketCap=zzz', 'invalid_min_market_cap'],
+ ['maxAgeMin=0', 'invalid_max_age_min'],
+ ['maxAgeMin=nope', 'invalid_max_age_min'],
+ ]) {
+ const res = await call(`/api/crypto/launches?${qs}`);
+ expect(res._json.status, qs).toBe(400);
+ expect(res._json.body.error, qs).toBe(code);
+ }
+ expect(fetchRecentPumpCoins).not.toHaveBeenCalled();
+ });
+
+ it('filters by minMarketCap, dropping coins whose cap is unknown', async () => {
+ const unknownCap = coin(9);
+ delete unknownCap.usd_market_cap;
+ fetchRecentPumpCoins.mockResolvedValue({
+ kind: 'ok',
+ coins: [coin(1, { mcUsd: 500 }), coin(2, { mcUsd: 9000 }), unknownCap],
+ });
+ const res = await call('/api/crypto/launches?minMarketCap=1000');
+ expect(res._json.body.count).toBe(1);
+ expect(res._json.body.launches[0].symbol).toBe('SYN2');
+ });
+
+ it('filters by maxAgeMin', async () => {
+ fetchRecentPumpCoins.mockResolvedValue({
+ kind: 'ok',
+ coins: [coin(1, { ageMin: 2 }), coin(2, { ageMin: 30 }), coin(3, { ageMin: 9 })],
+ });
+ const res = await call('/api/crypto/launches?maxAgeMin=10');
+ expect(res._json.body.launches.map((l) => l.symbol)).toEqual(['SYN1', 'SYN3']);
+ });
+
+ it('200s an empty filtered sweep with a helpful note, not an error', async () => {
+ fetchRecentPumpCoins.mockResolvedValue({ kind: 'ok', coins: [coin(1, { mcUsd: 10 })] });
+ const res = await call('/api/crypto/launches?minMarketCap=1000000');
+ expect(res._json.status).toBe(200);
+ expect(res._json.body).toMatchObject({ launches: [], count: 0, source: 'pumpfun' });
+ expect(res._json.body.note).toContain('no launches match');
+ });
+
+ it('200s (never 5xx) when the feed is unreachable, with an honest source note', async () => {
+ fetchRecentPumpCoins.mockResolvedValue({ kind: 'upstream_down', coins: [] });
+ const res = await call('/api/crypto/launches');
+ expect(res._json.status).toBe(200);
+ expect(res._json.body).toMatchObject({ launches: [], count: 0, source: 'pumpfun:unavailable' });
+ expect(res._json.body.note).toContain('retry');
+ });
+
+ it('429s when the per-IP limit is exhausted', async () => {
+ limits.publicIp.mockResolvedValue({ success: false });
+ const res = await call('/api/crypto/launches');
+ expect(res._json.status).toBe(429);
+ expect(fetchRecentPumpCoins).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/crypto-token-snapshot.test.js b/tests/crypto-token-snapshot.test.js
new file mode 100644
index 000000000..e11963d7d
--- /dev/null
+++ b/tests/crypto-token-snapshot.test.js
@@ -0,0 +1,215 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ SNAPSHOT_FIELDS,
+ emptySnapshot,
+ snapshotFromMarket,
+ mergePumpCoin,
+ mergeMeta,
+ isBareMeta,
+ composeTokenSnapshot,
+} from '../api/_lib/crypto-token-snapshot.js';
+
+// Synthetic addresses only — never a real third-party mint in fixtures (CLAUDE.md).
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const SYNTH = 'THREEsynthetic1111111111111111111111111111A';
+const EVM = '0x1111111111111111111111111111111111111111';
+
+const fullMarket = {
+ mint: THREE,
+ symbol: 'THREE',
+ name: 'three.ws',
+ chain: 'solana',
+ dex: 'pumpswap',
+ pair_url: `https://dexscreener.com/solana/${THREE}`,
+ price_usd: 0.0031,
+ change_24h: 4.2,
+ market_cap_usd: 3_100_000,
+ fdv_usd: 3_100_000,
+ liquidity_usd: 250_000,
+ volume_24h_usd: 91_000,
+ pair_created_at: 1750000000000,
+};
+
+const pumpCoin = {
+ mint: SYNTH,
+ name: 'synthetic sample',
+ symbol: 'SYNTH',
+ usd_market_cap: 42_000,
+ bonding_curve: 'curveAcct',
+ real_token_reserves: 500_000_000 * 1e6,
+ real_sol_reserves: 30 * 1e9,
+};
+
+const never = () => { throw new Error('must not be called'); };
+
+describe('snapshot shape', () => {
+ it('emptySnapshot carries every contract key, nulled', () => {
+ const snap = emptySnapshot(SYNTH, null);
+ expect(Object.keys(snap).sort()).toEqual([...SNAPSHOT_FIELDS].sort());
+ expect(snap.address).toBe(SYNTH);
+ for (const k of SNAPSHOT_FIELDS) {
+ if (k !== 'address') expect(snap[k]).toBeNull();
+ }
+ });
+
+ it('snapshotFromMarket maps every market field and keeps the full key set', () => {
+ const snap = snapshotFromMarket(THREE, fullMarket);
+ expect(Object.keys(snap).sort()).toEqual([...SNAPSHOT_FIELDS].sort());
+ expect(snap).toMatchObject({
+ address: THREE,
+ chain: 'solana',
+ symbol: 'THREE',
+ name: 'three.ws',
+ priceUsd: 0.0031,
+ change24h: 4.2,
+ marketCapUsd: 3_100_000,
+ fdvUsd: 3_100_000,
+ liquidityUsd: 250_000,
+ volume24hUsd: 91_000,
+ dexId: 'pumpswap',
+ });
+ expect(snap.pairCreatedAt).toBe(new Date(1750000000000).toISOString());
+ });
+
+ it('thin market data maps to explicit nulls, never omitted keys', () => {
+ const snap = snapshotFromMarket(SYNTH, { mint: SYNTH, chain: 'solana' });
+ expect(Object.keys(snap).sort()).toEqual([...SNAPSHOT_FIELDS].sort());
+ expect(snap.priceUsd).toBeNull();
+ expect(snap.fdvUsd).toBeNull();
+ expect(snap.pairCreatedAt).toBeNull();
+ });
+});
+
+describe('pump.fun + metadata merges', () => {
+ it('mergePumpCoin fills gaps but never overwrites DexScreener values', () => {
+ const snap = snapshotFromMarket(SYNTH, { ...fullMarket, mint: SYNTH });
+ const merged = mergePumpCoin(snap, pumpCoin);
+ expect(merged.symbol).toBe('THREE'); // market value wins
+ expect(merged.marketCapUsd).toBe(3_100_000);
+ });
+
+ it('mergePumpCoin supplies identity, mcap, and a pump.fun url on an empty snapshot', () => {
+ const merged = mergePumpCoin(emptySnapshot(SYNTH, null), pumpCoin);
+ expect(merged.symbol).toBe('SYNTH');
+ expect(merged.name).toBe('synthetic sample');
+ expect(merged.marketCapUsd).toBe(42_000);
+ expect(merged.url).toBe(`https://pump.fun/coin/${SYNTH}`);
+ expect(merged.chain).toBe('solana');
+ });
+
+ it('isBareMeta detects the unresolved placeholder and mergeMeta discards it', () => {
+ const bare = { mint: SYNTH, symbol: SYNTH.slice(0, 6), name: SYNTH.slice(0, 6), decimals: null };
+ expect(isBareMeta(bare)).toBe(true);
+ expect(isBareMeta(undefined)).toBe(true);
+ expect(isBareMeta({ mint: SYNTH, symbol: 'REAL', name: 'Real Token', decimals: 6 })).toBe(false);
+
+ const snap = mergeMeta(emptySnapshot(SYNTH, 'solana'), bare);
+ expect(snap.symbol).toBeNull();
+ const enriched = mergeMeta(emptySnapshot(SYNTH, 'solana'), { mint: SYNTH, symbol: 'REAL', name: 'Real Token', decimals: 6 });
+ expect(enriched.symbol).toBe('REAL');
+ });
+});
+
+describe('composeTokenSnapshot — chain inference + source selection', () => {
+ it('Solana address with a full DEX read → ok from dexscreener only, no pump call', async () => {
+ const r = await composeTokenSnapshot({ address: THREE }, {
+ fetchMarket: async () => fullMarket,
+ fetchPump: never,
+ fetchMeta: never,
+ });
+ expect(r.status).toBe('ok');
+ expect(r.sources).toEqual(['dexscreener']);
+ expect(r.snapshot.chain).toBe('solana');
+ expect(r.note).toBeUndefined();
+ });
+
+ it('EVM address never consults pump.fun or Solana metadata', async () => {
+ const r = await composeTokenSnapshot({ address: EVM }, {
+ fetchMarket: async () => ({ ...fullMarket, mint: EVM, chain: 'base', dex: 'uniswap' }),
+ fetchPump: never,
+ fetchMeta: never,
+ });
+ expect(r.status).toBe('ok');
+ expect(r.snapshot.chain).toBe('base');
+ });
+
+ it('passes the chain filter through to the market reader', async () => {
+ let seen = null;
+ await composeTokenSnapshot({ address: EVM, chain: 'bsc' }, {
+ fetchMarket: async (_a, opts) => { seen = opts.chain; return { ...fullMarket, mint: EVM, chain: 'bsc' }; },
+ fetchPump: never,
+ fetchMeta: never,
+ });
+ expect(seen).toBe('bsc');
+ });
+});
+
+describe('composeTokenSnapshot — degradation states', () => {
+ it('DexScreener down + pump.fun ok → 200-shaped partial with note (never blocked)', async () => {
+ const r = await composeTokenSnapshot({ address: SYNTH }, {
+ fetchMarket: async () => { throw new Error('timeout'); },
+ fetchPump: async () => ({ kind: 'ok', coin: pumpCoin }),
+ fetchMeta: never,
+ });
+ expect(r.status).toBe('ok');
+ expect(r.sources).toEqual(['pumpfun']);
+ expect(r.snapshot.symbol).toBe('SYNTH');
+ expect(r.snapshot.marketCapUsd).toBe(42_000);
+ expect(r.snapshot.priceUsd).toBeNull();
+ expect(r.note).toMatch(/dexscreener unavailable/);
+ });
+
+ it('no key, no pair: keyless pump fields still resolve while meta stays bare', async () => {
+ // Simulates a deployment without HELIUS_API_KEY — getMetadataForMints
+ // returns only the bare placeholder, which must be discarded, while the
+ // keyless pump.fun read still supplies real identity.
+ const r = await composeTokenSnapshot({ address: SYNTH }, {
+ fetchMarket: async () => null,
+ fetchPump: async () => ({ kind: 'ok', coin: pumpCoin }),
+ fetchMeta: async () => new Map([[SYNTH, { mint: SYNTH, symbol: SYNTH.slice(0, 6), name: SYNTH.slice(0, 6), decimals: null }]]),
+ });
+ expect(r.status).toBe('ok');
+ expect(r.sources).toEqual(['pumpfun']);
+ expect(r.snapshot.name).toBe('synthetic sample');
+ });
+
+ it('non-pump SPL mint resolves identity via real Helius metadata', async () => {
+ const r = await composeTokenSnapshot({ address: SYNTH }, {
+ fetchMarket: async () => null,
+ fetchPump: async () => ({ kind: 'not_found' }),
+ fetchMeta: async () => new Map([[SYNTH, { mint: SYNTH, symbol: 'REAL', name: 'Real Token', decimals: 6 }]]),
+ });
+ expect(r.status).toBe('ok');
+ expect(r.sources).toEqual(['helius']);
+ expect(r.snapshot.symbol).toBe('REAL');
+ expect(r.snapshot.priceUsd).toBeNull();
+ });
+
+ it('all sources answered, none know the address → not_found', async () => {
+ const r = await composeTokenSnapshot({ address: SYNTH }, {
+ fetchMarket: async () => null,
+ fetchPump: async () => ({ kind: 'not_found' }),
+ fetchMeta: async () => new Map(),
+ });
+ expect(r.status).toBe('not_found');
+ });
+
+ it('every source down → upstream_down, never a false not-found', async () => {
+ const r = await composeTokenSnapshot({ address: SYNTH }, {
+ fetchMarket: async () => { throw new Error('down'); },
+ fetchPump: async () => ({ kind: 'upstream_down' }),
+ fetchMeta: async () => new Map(),
+ });
+ expect(r.status).toBe('upstream_down');
+ });
+
+ it('EVM address, DexScreener down → upstream_down (no Solana fallbacks to consult)', async () => {
+ const r = await composeTokenSnapshot({ address: EVM }, {
+ fetchMarket: async () => { throw new Error('down'); },
+ fetchPump: never,
+ fetchMeta: never,
+ });
+ expect(r.status).toBe('upstream_down');
+ });
+});