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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(crypto-api): publish the portfolio and airdrops endpoints in the catalog and cache the pump.fun leg
nirholas3247a7566433
diff --git a/api/_lib/crypto-catalog/airdrops.js b/api/_lib/crypto-catalog/airdrops.jsnew file mode 100644index 000000000..6377759d4--- /dev/null+++ b/api/_lib/crypto-catalog/airdrops.js@@ -0,0 +1,78 @@+// Catalog entry for GET /api/crypto/airdrops: the free airdrop-eligibility+// endpoint.+//+// The /api/crypto index merges this descriptor into the bundle's discovery doc+// + OpenAPI (via the STATIC_ENTRIES barrel in index.js). Plain, serializable,+// no imports, no side effects.++export default {+ slug: 'airdrops',+ method: 'GET',+ path: '/api/crypto/airdrops',+ title: 'Airdrop Eligibility',+ summary:+ "Score a wallet's real on-chain activity against the live airdrop registry: per-airdrop met/missing/manual criteria, an eligibility verdict, and the measured activity behind it. Omit the address to get the registry alone. Solana is keyless; EVM scanning needs an explorer key.",+ inputSchema: {+ type: 'object',+ properties: {+ address: {+ type: 'string',+ description: 'Wallet to score (Solana base58 or EVM 0x). Omit to return the registry alone.',+ },+ },+ },+ outputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string' },+ family: { type: 'string', enum: ['solana', 'evm'] },+ activity: {+ type: 'object',+ description: 'Measured on-chain activity: tx_count, days_active, account_age_days, unique_tokens, and the chains behind them.',+ },+ opportunities: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ name: { type: 'string' },+ chain: { type: 'string' },+ status: { type: 'string' },+ score: { type: 'number' },+ eligibility: {+ type: 'string',+ enum: ['qualified', 'in_progress', 'not_eligible'],+ },+ met: { type: 'array', items: { type: 'object' } },+ missing: { type: 'array', items: { type: 'object' } },+ manual: { type: 'array', items: { type: 'object' } },+ estimatedValue: { type: ['string', 'null'] },+ deadline: { type: ['string', 'null'] },+ source: { type: ['string', 'null'] },+ },+ },+ },+ otherFamily: {+ type: 'array',+ description: 'Registry entries on the other chain family, returned unevaluated rather than scored as a fake zero.',+ items: { type: 'object' },+ },+ summary: { type: 'object' },+ registry: {+ type: 'array',+ description: 'Returned instead of a scored result when no address is supplied.',+ items: { type: 'object' },+ },+ thresholds: {+ type: 'object',+ properties: {+ qualified: { type: 'number' },+ inProgress: { type: 'number' },+ },+ },+ ts: { type: 'string', format: 'date-time' },+ },+ },+ example: '/api/crypto/airdrops?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+};diff --git a/api/_lib/crypto-catalog/index.js b/api/_lib/crypto-catalog/index.jsindex c0a74557c..aacb2c0b7 100644--- a/api/_lib/crypto-catalog/index.js+++ b/api/_lib/crypto-catalog/index.js@@ -23,9 +23,11 @@ import { readdirSync } from 'node:fs';import { fileURLToPath, pathToFileURL } from 'node:url';import { basename, dirname, join } from 'node:path';+import airdropsEntry from './airdrops.js';import bondingEntry from './bonding.js';import holdersEntry from './holders.js';import launchesEntry from './launches.js';+import portfolioEntry from './portfolio.js';import securityEntry from './security.js';import symbolEntry from './symbol.js';import tokenEntry from './token.js';@@ -43,9 +45,11 @@ import whalesEntry from './whales.js';// >>> Adding an endpoint: drop `api/_lib/crypto-catalog/<slug>.js` AND add its// >>> import + line here. The import is what makes it exist in production.const STATIC_ENTRIES = [+ { mod: airdropsEntry, source: 'airdrops.js' },{ mod: bondingEntry, source: 'bonding.js' },{ mod: holdersEntry, source: 'holders.js' },{ mod: launchesEntry, source: 'launches.js' },+ { mod: portfolioEntry, source: 'portfolio.js' },{ mod: securityEntry, source: 'security.js' },{ mod: symbolEntry, source: 'symbol.js' },{ mod: tokenEntry, source: 'token.js' },diff --git a/api/_lib/crypto-catalog/portfolio.js b/api/_lib/crypto-catalog/portfolio.jsnew file mode 100644index 000000000..c23de7cb3--- /dev/null+++ b/api/_lib/crypto-catalog/portfolio.js@@ -0,0 +1,95 @@+// Catalog entry for GET /api/crypto/portfolio: the free portfolio-overview+// endpoint.+//+// The /api/crypto index merges this descriptor into the bundle's discovery doc+// + OpenAPI (via the STATIC_ENTRIES barrel in index.js). Plain, serializable,+// no imports, no side effects.++export default {+ slug: 'portfolio',+ method: 'GET',+ path: '/api/crypto/portfolio',+ title: 'Portfolio Overview',+ summary:+ 'A wallet read shaped for a portfolio view rather than a raw balance dump: stable/major/other classification, top-asset allocation with palette slots, per-row portfolio share, per-token 24h change, and an aggregate 24h move that states its own coverage. Keyless on Solana; Ethereum needs a provider key.',+ inputSchema: {+ type: 'object',+ required: ['address'],+ properties: {+ address: {+ type: 'string',+ description: 'Wallet address to inspect (Solana base58 or EVM 0x).',+ },+ chain: {+ type: 'string',+ enum: ['solana', 'ethereum'],+ default: 'solana',+ description: 'Chain to read. Solana is keyless; Ethereum needs a provider key.',+ },+ },+ },+ outputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string' },+ chain: { type: 'string' },+ totalUsd: { type: 'number' },+ unpricedCount: { type: 'integer' },+ change24h: {+ type: ['object', 'null'],+ properties: {+ usd: { type: 'number' },+ pct: { type: 'number' },+ coveragePct: {+ type: 'number',+ description: 'Share of portfolio value the 24h move actually covers. Nothing is extrapolated over the gap.',+ },+ },+ },+ summary: {+ type: 'object',+ description: 'Value split across stable / major / other, each with usd, pct and count.',+ },+ topAssets: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ symbol: { type: ['string', 'null'] },+ name: { type: ['string', 'null'] },+ usd: { type: 'number' },+ pct: { type: 'number' },+ slot: { type: 'integer', description: 'Palette slot, so a chart colors consistently across reloads.' },+ logo: { type: ['string', 'null'] },+ },+ },+ },+ rows: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ symbol: { type: ['string', 'null'] },+ name: { type: ['string', 'null'] },+ kind: { type: 'string', enum: ['native', 'token'] },+ class: { type: 'string', enum: ['stable', 'major', 'other'] },+ amount: { type: 'number' },+ price: { type: ['number', 'null'] },+ usd: { type: ['number', 'null'] },+ pct: { type: ['number', 'null'] },+ change24h: { type: ['number', 'null'] },+ logo: { type: ['string', 'null'] },+ },+ },+ },+ tokenCount: { type: 'integer' },+ truncated: { type: 'boolean' },+ stale: { type: 'boolean' },+ ts: { type: 'string', format: 'date-time' },+ sources: { type: 'array', items: { type: 'string' } },+ },+ },+ example: '/api/crypto/portfolio?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana',+};diff --git a/api/_lib/crypto-trending.js b/api/_lib/crypto-trending.jsindex c6b663a3b..950c04cb5 100644--- a/api/_lib/crypto-trending.js+++ b/api/_lib/crypto-trending.js@@ -33,6 +33,7 @@import { scorePressure } from './x402/pump-trending-score.js';import { summarizeWindowUsd, median } from './x402/pump-volume-anomaly.js';import { dexScreenerTrending, gmgnSmartMoneyRank } from './gmgn-feed.js';+import { cacheWrap } from './cache.js';import { gmgnTokenUrl } from '../../src/shared/trading-terminals.js';const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';@@ -43,6 +44,9 @@ const FETCH_TIMEOUT_MS = Number(process.env.CRYPTO_TRENDING_TIMEOUT_MS || 6000);const PUMP_TRADE_COINS = Number(process.env.CRYPTO_TRENDING_TRADE_COINS || 20);const PUMP_TRADES_PER_COIN = Number(process.env.CRYPTO_TRENDING_TRADES_PER_COIN || 100);const PUMP_CONCURRENCY = Number(process.env.CRYPTO_TRENDING_CONCURRENCY || 6);+// Seconds a composed pump.fun leg is reused across callers. Matches the+// cache-control max-age /api/crypto/trending sets on its own response.+const PUMP_CACHE_TTL_S = Number(process.env.CRYPTO_TRENDING_PUMP_TTL_S || 30);// Ranking weights + saturation caps (see header). Exported so tests + docs read// from one source of truth.@@ -327,7 +331,17 @@ export async function fetchGmgnTrending({ window }) {export async function composeTrending({ window, limit, source, nowMs = Date.now(), deps = {} }) {const windowSec = windowToSec(window);const cappedLimit = Math.min(50, Math.max(1, limit));- const pumpfun = deps.pumpfun || (() => fetchPumpfunTrending({ windowSec, limit: cappedLimit, nowMs }));+ // One trending call costs pump.fun ~21 requests (the board plus per-coin trade+ // feeds), and pump.fun throttles a caller that repeats that too quickly. Without+ // a shared cache, back-to-back requests starve their own pump leg and the fused+ // ranking silently degrades to dexscreener-only. The TTL matches the endpoint's+ // own edge cache, so a cached leg is never staler than the response around it.+ const pumpfun =+ deps.pumpfun ||+ (() =>+ cacheWrap(`crypto:trending:pumpfun:${windowSec}:${cappedLimit}`, PUMP_CACHE_TTL_S, () =>+ fetchPumpfunTrending({ windowSec, limit: cappedLimit, nowMs }),+ ));const dexscreener = deps.dexscreener || (() => fetchDexTrending({ window }));const gmgn = deps.gmgn || (() => fetchGmgnTrending({ window }));@@ -362,7 +376,7 @@ export async function composeTrending({ window, limit, source, nowMs = Date.now(sources,};if (!sources.length) {- out.note = 'All upstream market sources were unavailable — returning an empty ranking. Retry shortly.';+ out.note = 'All upstream market sources were unavailable. Returning an empty ranking; retry shortly.';} else if (source === 'all' && sources.length < jobs.length) {const down = settled.filter((s) => s.rows.length === 0).map((s) => s.name);out.note = `Partial data: ${down.join(', ')} unavailable; ranked from ${sources.join(', ')}.`;diff --git a/api/crypto/bonding.js b/api/crypto/bonding.jsindex 244e03baa..0e5f2e39b 100644--- a/api/crypto/bonding.js+++ b/api/crypto/bonding.js@@ -19,7 +19,9 @@ import { getBondingStatus } from '../_lib/pump-bonding.js';const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;export default wrap(async (req, res) => {- if (cors(req, res, { origins: '*' })) return;+ // Pin the advertised verbs to what this handler answers: the shared default+ // also names POST, which preflight-approves a request that then 405s.+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.marketDataIp(clientIp(req));diff --git a/api/crypto/launches.js b/api/crypto/launches.jsindex 959131052..6c64a90cb 100644--- a/api/crypto/launches.js+++ b/api/crypto/launches.js@@ -52,7 +52,9 @@ export function toLaunch(coin, nowMs) {}export default wrap(async (req, res) => {- if (cors(req, res, { origins: '*' })) return;+ // Pin the advertised verbs to what this handler answers: the shared default+ // also names POST, which preflight-approves a request that then 405s.+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.marketDataIp(clientIp(req));@@ -63,7 +65,7 @@ export default wrap(async (req, res) => {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})`);+ return error(res, 400, 'invalid_limit', `\`limit\` must be a positive integer (default ${DEFAULT_LIMIT}); values above ${MAX_LIMIT} are capped at ${MAX_LIMIT}, not rejected`);}const limit = Math.min(MAX_LIMIT, limitRaw ?? DEFAULT_LIMIT);diff --git a/api/crypto/trending.js b/api/crypto/trending.jsindex c6aa313df..b83cfa715 100644--- a/api/crypto/trending.js+++ b/api/crypto/trending.js@@ -1,8 +1,8 @@// GET /api/crypto/trending// -------------------------// Free, keyless "what's hot right now" feed for AI agents. Returns Solana tokens-// ranked by MOMENTUM — a blend of windowed trade volume, buy pressure, a volume-// spike (anomaly) signal, and short-window price change — fused across pump.fun,+// ranked by MOMENTUM: a blend of windowed trade volume, buy pressure, a volume+// spike (anomaly) signal, and short-window price change, fused across pump.fun,// DexScreener's boosted board, and (best-effort) GMGN smart money.//// A discovery agent asks one URL instead of scraping five sites: it gets a@@ -11,13 +11,13 @@// docs/crypto-api.md.//// Query:-// window = 5m | 1h | 24h (default 1h) — trade window the score measures+// window = 5m | 1h | 24h (default 1h) trade window the score measures// limit = 1..50 (default 20)-// source = pumpfun | all (default all) — 'pumpfun' restricts to the+// source = pumpfun | all (default all) where 'pumpfun' restricts to the// pump.fun board; 'all' fuses every source//// Response: { window, tokens: [{ mint, symbol, name, marketCapUsd, volumeUsd,-// change, score, url }], count, ts, sources[] } — tokens ranked by score desc.+// change, score, url }], count, ts, sources[] }. Tokens are ranked by score desc.//// Never 500s on a well-formed request: every source failing yields 200 with an// empty ranking + a note. Bad window/source/limit are coerced to sane defaults.diff --git a/api/crypto/wallet.js b/api/crypto/wallet.jsindex 05af8d670..2aa443aa4 100644--- a/api/crypto/wallet.js+++ b/api/crypto/wallet.js@@ -1,7 +1,7 @@-// GET /api/crypto/wallet — free, keyless wallet portfolio for AI agents.+// GET /api/crypto/wallet: free, keyless wallet portfolio for AI agents.//-// Agent use-case: an autonomous agent needs to inspect a wallet — its own or a-// counterparty's — before it transacts. A treasury agent checks its runway, a+// Agent use-case: an autonomous agent needs to inspect a wallet (its own or a+// counterparty's) before it transacts. A treasury agent checks its runway, a// copy-trade agent mirrors a leader's holdings, a pre-trade check inspects who// it's about to deal with. One call returns native balance, every SPL token,// and a rough USD valuation, so the agent doesn't have to juggle an RPC + a@@ -10,7 +10,7 @@// Free-endpoint pattern (x402-overhaul campaign convention): plain handler,// `cors`/`wrap`/`error` from _lib/http.js, rate-limited by IP via _lib/rate-limit.js.// No key, no account. The Solana path returns REAL balances even without a Helius-// key — it falls back to the public RPC `getTokenAccountsByOwner` walk and prices+// key: it falls back to the public RPC `getTokenAccountsByOwner` walk and prices// via Jupiter Lite + the pump.fun bonding curve (all keyless). Helius DAS is used// only as a faster path when HELIUS_API_KEY is present.@@ -37,7 +37,7 @@ const CHAIN_ALIASES = {mainnet: 'evm',};-// Round a USD figure to cents-ish precision without importing a bignum lib — these+// Round a USD figure to cents-ish precision without importing a bignum lib. These// are display valuations, not settlement amounts. Keeps 6 significant sub-dollar// digits so sub-cent token values ($0.0000123) don't collapse to 0.function roundUsd(n) {@@ -46,7 +46,7 @@ function roundUsd(n) {}// Map the rich internal balance shape to the stable public contract. Unpriced-// tokens (price 0 — Jupiter/pump.fun couldn't route them) keep their amount but+// tokens (price 0, meaning Jupiter/pump.fun couldn't route them) keep their amount but// report `usd: null`, never a fake 0 valuation and never dropped from the list.function shapeToken(t) {const priced = Number(t.price) > 0;@@ -81,7 +81,7 @@ export default wrap(async function handler(req, res) {const ip = clientIp(req);const [ipRl, globalRl] = await Promise.all([limits.cryptoDataIp(ip), limits.cryptoDataGlobal()]);if (!ipRl.success || !globalRl.success) {- return error(res, 429, 'rate_limited', 'too many requests — slow down and retry shortly', {+ return error(res, 429, 'rate_limited', 'too many requests, slow down and retry shortly', {retryAfter: 60,});}@@ -118,14 +118,14 @@ export default wrap(async function handler(req, res) {} catch (err) {// EVM without an Alchemy key: honest 503 naming the gap, never a mock.if (err?.code === 'not_configured') {- return error(res, 503, 'not_configured', 'this chain requires a provider key that is not set on this deployment — Solana works keyless', {+ return error(res, 503, 'not_configured', 'this chain requires a provider key that is not set on this deployment; Solana works keyless', {chain: rawChain,});}// Every live RPC path failed and there was no cached snapshot to fall back on.- // Surface a retryable 503 with Retry-After — never a 500 on a well-formed request.+ // Surface a retryable 503 with Retry-After, never a 500 on a well-formed request.res.setHeader('retry-after', '15');- return error(res, 503, 'upstream_unavailable', 'wallet data source is temporarily unavailable — retry shortly', {+ return error(res, 503, 'upstream_unavailable', 'wallet data source is temporarily unavailable, retry shortly', {retryAfter: 15,});}@@ -151,7 +151,7 @@ export default wrap(async function handler(req, res) {sources: sourcesFor(chain),};// A stale flag from the balance layer means every live path failed and we served- // the wallet's last-known-good snapshot — pass that honesty through to the caller.+ // the wallet's last-known-good snapshot. Pass that honesty through to the caller.if (balances.stale) body.stale = true;// Public read, safe to CDN-cache briefly: balances move, but a 30s edge cachediff --git a/api/crypto/whales.js b/api/crypto/whales.jsindex 35c20ce1e..1b6d28bed 100644--- a/api/crypto/whales.js+++ b/api/crypto/whales.js@@ -1,9 +1,9 @@-// GET /api/crypto/whales — FREE whale / large-buy activity for AI agents.+// GET /api/crypto/whales: FREE whale / large-buy activity for AI agents.//// Agent use-case: a trading or sniper agent, mid-task, wants to know if big// money is moving into a token (or the pump.fun market broadly) BEFORE it// commits. A whale already in = price impact ahead; no whales = thin. This is a-// free, keyless read of large buys — high signal, no account, no payment.+// free, keyless read of large buys: high signal, no account, no payment.//// ?mint=<spl-mint> → whale BUYS of that token (per-transaction rows)// (omit mint) → top whale WALLETS active across pump.fun right now@@ -36,7 +36,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;- // Public read bucket — keyless, generous, per-IP flood guard.+ // Public read bucket: keyless, generous, per-IP flood guard.const rl = await limits.marketDataIp(clientIp(req));setRateLimitHeaders(res, rl);if (!rl.success) return rateLimited(res, rl);@@ -85,7 +85,7 @@ export default wrap(async (req, res) => {// Feed down (no trades reachable) → 200 empty + a note, per the never-500 rule.if (degraded) {body.note =- 'pump.fun feed is temporarily unavailable — returning an empty whale set; retry shortly';+ 'pump.fun feed is temporarily unavailable. Returning an empty whale set; retry shortly.';}return json(res, 200, body, {diff --git a/docs/agent-abilities/ABILITIES.md b/docs/agent-abilities/ABILITIES.mdindex 36950770b..5944e195c 100644--- a/docs/agent-abilities/ABILITIES.md+++ b/docs/agent-abilities/ABILITIES.md@@ -2016,7 +2016,7 @@ Read the crowd on any token before acting — from a free one-call API, an agentA free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.-pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (bonding, holders, launches, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.+pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.diff --git a/docs/agent-abilities/FULL-ARTICLE.md b/docs/agent-abilities/FULL-ARTICLE.mdindex f4d59ef72..04c431f25 100644--- a/docs/agent-abilities/FULL-ARTICLE.md+++ b/docs/agent-abilities/FULL-ARTICLE.md@@ -2153,7 +2153,7 @@ Token sentiment on demand: POST /api/sentiment scores any text (Positive/NegativA free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.-**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (bonding, holders, launches, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.+**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.**Why it matters:** Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.diff --git a/docs/agent-abilities/chapters/11-markets-intelligence.md b/docs/agent-abilities/chapters/11-markets-intelligence.mdindex 68b7287f9..7d9c07380 100644--- a/docs/agent-abilities/chapters/11-markets-intelligence.md+++ b/docs/agent-abilities/chapters/11-markets-intelligence.md@@ -96,7 +96,7 @@ Token sentiment on demand: POST /api/sentiment scores any text (Positive/NegativA free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.-**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (bonding, holders, launches, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.+**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.**Why it matters:** Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.diff --git a/docs/crypto-api.md b/docs/crypto-api.mdindex 99e1adb56..dedce6f74 100644--- a/docs/crypto-api.md+++ b/docs/crypto-api.md@@ -43,9 +43,11 @@ is documented in its section below and machine-readable in the OpenAPI doc.| Endpoint | Verb(s) | What it answers ||----------|---------|-----------------|+| [`/api/crypto/airdrops`](https://three.ws/api/crypto/airdrops) | `GET` | Which airdrops a wallet is on track for - its real on-chain activity scored against the live registry, with met/missing criteria per airdrop. || [`/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/holders`](https://three.ws/api/crypto/holders) | `GET` | Holder distribution for a Solana token — top wallets with % of supply, cumulative top-10 share, and a documented concentration verdict. || [`/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/portfolio`](https://three.ws/api/crypto/portfolio) | `GET` | A wallet read shaped for a portfolio view - stable/major/other split, top-asset allocation, per-token 24h change, and an aggregate 24h move that states its own coverage. || [`/api/crypto/security`](https://three.ws/api/crypto/security) | `GET` | Pre-trade rug check for a Solana token — authority, concentration, liquidity, mutability, and LP-custody facts composed into a deterministic riskLevel. || [`/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. |@@ -825,6 +827,193 @@ curl -s "https://three.ws/api/crypto/holders?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3---+## `GET /api/crypto/portfolio` - Portfolio overview++**Use-case.** A *treasury or reporting agent* already has the raw balances from+[`/api/crypto/wallet`](#get-apicryptowallet--wallet-portfolio) and needs the+next layer: how the value splits across stables, majors and everything else,+which assets dominate, and whether the book is up or down on the day. This is+that layer, computed once server-side so every client renders the same numbers.++### Request++| Param | Type | Default | Notes |+|-----------|--------|----------|-------|+| `address` | string | required | Wallet address. Solana base58 or EVM `0x`. |+| `chain` | enum | `solana` | `solana` (alias `sol`) or `ethereum` (aliases `eth`, `evm`, `mainnet`). |++### Response++```json+{+ "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "chain": "solana",+ "totalUsd": 1284.51,+ "unpricedCount": 2,+ "change24h": { "usd": -22.4, "pct": -1.71, "coveragePct": 96.2 },+ "summary": {+ "stable": { "usd": 400.0, "pct": 31.14, "count": 1 },+ "major": { "usd": 800.5, "pct": 62.32, "count": 1 },+ "other": { "usd": 84.01, "pct": 6.54, "count": 3 }+ },+ "topAssets": [+ { "id": "native", "symbol": "SOL", "name": "Solana", "usd": 800.5, "pct": 62.32, "slot": 1, "logo": null }+ ],+ "rows": [+ {+ "id": "native",+ "symbol": "SOL",+ "name": "Solana",+ "kind": "native",+ "class": "major",+ "amount": 10.58,+ "price": 75.66,+ "usd": 800.5,+ "pct": 62.32,+ "change24h": -1.78,+ "logo": null+ }+ ],+ "tokenCount": 5,+ "truncated": false,+ "ts": "2026-08-10T16:31:34.527Z",+ "sources": ["solana-rpc", "jupiter-lite", "dexscreener"]+}+```++- **`change24h.coveragePct`** - the share of portfolio value the aggregate move+ actually covers. Tokens beyond the enrichment cap keep `change24h: null` and+ are excluded from the aggregate rather than extrapolated over.+- **`class`** - `stable`, `major` or `other`, so a chart can group without+ re-deriving the taxonomy per client.+- **`slot`** - a palette slot per top asset, so the same wallet colors the same+ way across reloads and across surfaces.+- **`stale: true`** - present only when the balance source served a cached read.++### Sources++- **Solana (keyless):** Helius DAS when the deployment has a key, else a public+ RPC walk; prices from Jupiter Lite plus the pump.fun curve; 24h changes from+ DexScreener's batch endpoint (30 mints per call, top 60 holdings) and the+ multi-provider SOL price failover.+- **Ethereum:** the same `getBalances()` EVM path (needs a provider key) - its+ tokens already carry CoinGecko 24h changes.++### States++- **Wallet with holdings** -> `200` with the full overview.+- **Empty wallet** -> `200` with `totalUsd: 0`, empty `rows`/`topAssets` - a+ valid empty, not an error.+- **Missing/invalid `address`, unsupported `chain`** -> `400` with an example.+- **Chain needs a key this deployment lacks** -> `503 not_configured`, naming+ that Solana works keyless.+- **Balance source unreachable** -> `503` + `Retry-After`. Never `500`.+- **Rate-limited** -> `429`.++### Examples++```bash+# Full overview for a Solana wallet+curl -s "https://three.ws/api/crypto/portfolio?address=<wallet>"++# Just the day's move and how much of the book it covers+curl -s "https://three.ws/api/crypto/portfolio?address=<wallet>" | jq '.change24h'+```++---++## `GET /api/crypto/airdrops` - Airdrop eligibility++**Use-case.** A *wallet-strategy agent* wants to know which upcoming airdrops a+wallet is already on track for, and exactly what is missing for the rest. One+call measures the wallet's real on-chain activity and scores it against the live+registry, so the agent can act on the gap instead of guessing at farming advice.++### Request++| Param | Type | Default | Notes |+|-----------|--------|---------|-------|+| `address` | string | none | Wallet to score (Solana base58 or EVM `0x`). Omit it to get the registry alone - the directory view before any lookup. |++### Response++```json+{+ "address": "<wallet>",+ "family": "solana",+ "activity": {+ "family": "solana",+ "tx_count": 412,+ "days_active": 96,+ "account_age_days": 640,+ "unique_tokens": 23,+ "capped": false,+ "chains": ["solana"]+ },+ "opportunities": [+ {+ "id": "jupiter-jupuary",+ "name": "Jupiter",+ "chain": "solana",+ "status": "confirmed",+ "score": 82,+ "eligibility": "qualified",+ "met": [{ "description": "50+ transactions on Solana", "met": true }],+ "missing": [],+ "manual": [{ "description": "Swap through the aggregator and try limit orders" }],+ "estimatedValue": "$100 - $2,000",+ "deadline": null,+ "source": "https://jup.ag"+ }+ ],+ "otherFamily": [],+ "summary": { "qualified": 3, "inProgress": 2, "notEligible": 4 },+ "thresholds": { "qualified": 70, "inProgress": 40 },+ "registryUpdated": "2026-08-01",+ "ts": "2026-08-10T16:31:34.527Z"+}+```++- **`met` / `missing` / `manual`** - criteria that the measured activity clears,+ criteria it does not, and criteria no on-chain read can settle (governance+ votes, off-chain quests). Manual criteria never inflate the score.+- **`otherFamily`** - registry entries for the chain family this address is not+ on, returned unevaluated so a UI can say "check this with your other wallet"+ instead of rendering a fake zero.+- **`eligibility`** - `qualified`, `in_progress` or `not_eligible`, decided by+ the `thresholds` returned alongside it, so the cutoffs are never implicit.++### Sources++- **Solana (keyless):** the rotating RPC chain, for transaction count, active+ days, account age and distinct tokens touched.+- **EVM:** Etherscan V2 behind `ETHERSCAN_API_KEY`.+- **Registry:** [`data/airdrops.json`](../data/airdrops.json), with its+ `updated` date echoed as `registryUpdated`.++### States++- **No `address`** -> `200` with `registry` + `thresholds`: the directory view.+- **Scored wallet** -> `200` with activity, opportunities and summary.+- **Invalid address (neither Solana nor EVM)** -> `400`.+- **EVM requested where no explorer key is set** -> `503 not_configured`,+ naming that Solana wallets work keyless.+- **Activity sources unreachable** -> `503` + `Retry-After`. Never `500`.+- **Rate-limited** -> `429`.++### Examples++```bash+# The registry alone, before any wallet lookup+curl -s "https://three.ws/api/crypto/airdrops" | jq '.registry[].name'++# Score a wallet and list only what it already qualifies for+curl -s "https://three.ws/api/crypto/airdrops?address=<wallet>" \+ | jq '.opportunities[] | select(.eligibility == "qualified") | .name'+```++---+## Related- [Market Data API](/docs/market-data-api) - the paid x402 twin: coin prices, DeFi TVL, yields, gas, and the per-datapoint fabricdiff --git a/tests/crypto-catalog.test.js b/tests/crypto-catalog.test.jsindex c52d32e8b..342b09fcd 100644--- a/tests/crypto-catalog.test.js+++ b/tests/crypto-catalog.test.js@@ -3,7 +3,7 @@// the GET /api/crypto index handler's HTML-vs-JSON content negotiation.import { describe, it, expect } from 'vitest';-import { mkdtempSync } from 'node:fs';+import { mkdtempSync, readdirSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';@@ -190,3 +190,38 @@ describe('GET /api/crypto content negotiation', () => {expect(res._body).toContain('three.ws Crypto Data API');});});++// The discovery contract promises the catalog lists EVERY endpoint in the+// bundle ("a new endpoint appears the moment it ships"). It only holds if each+// api/crypto/<slug>.js handler has a descriptor wired into the static barrel:+// /api/crypto/portfolio and /api/crypto/airdrops shipped live but undescribed,+// so agents reading the index or the OpenAPI doc could not see them at all.+describe('crypto-catalog covers every shipped endpoint', () => {+ const HANDLER_DIR = resolve(HERE, '../api/crypto');+ // Discovery machinery, not endpoints of their own.+ const NON_ENDPOINT = new Set(['index.js', 'openapi.js']);++ it('has a descriptor for every api/crypto handler, and no descriptor without one', async () => {+ const handlers = readdirSync(HANDLER_DIR)+ .filter((f) => f.endsWith('.js') && !NON_ENDPOINT.has(f) && !f.startsWith('_'))+ .map((f) => f.replace(/\.js$/, ''))+ .sort();++ const entries = await loadCatalog({ fresh: true });+ const slugs = entries.map((e) => e.slug).sort();++ expect(slugs).toEqual(handlers);+ for (const e of entries) {+ expect(e.path).toBe(`/api/crypto/${e.slug}`);+ }+ });++ it('surfaces every descriptor in the generated OpenAPI paths', async () => {+ const entries = await loadCatalog({ fresh: true });+ const doc = buildOpenApiDoc(entries, { origin: 'https://three.ws', version: '1.0.0' });+ for (const e of entries) {+ expect(doc.paths[e.path]).toBeTruthy();+ }+ expect(validateOpenApiDoc(doc)).toEqual([]);+ });+});