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): free holder distribution / concentration API (GET /api/crypto/holders)
fudjiae6088caad3f9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7690d8000..2dec3bff2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ 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 holder distribution / concentration API** — New free endpoint in the Crypto Data API: GET /api/crypto/holders shows who actually holds a Solana token before you size a position — the top wallets with their share of supply, the cumulative top-10 percentage, and a clear low/medium/high concentration verdict on documented thresholds. When the platform's indexer key is available holders are aggregated by wallet with an exact count; without it the endpoint still returns the chain's real top accounts, clearly labeled. No API key, no account, honest nulls for anything unknowable. (`/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]`diff --git a/api/_lib/crypto-catalog/holders.js b/api/_lib/crypto-catalog/holders.jsnew file mode 100644index 000000000..fc7735399--- /dev/null+++ b/api/_lib/crypto-catalog/holders.js@@ -0,0 +1,63 @@+// Catalog entry for GET /api/crypto/holders — the free holder-distribution+// 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: 'holders',+ method: 'GET',+ path: '/api/crypto/holders',+ title: 'Holders & Concentration',+ summary:+ 'Holder distribution for any Solana token: top wallets with amounts and % of supply, cumulative top-10 share, and a documented low/medium/high concentration verdict — the exit-risk read an agent needs before sizing a position. Keyless top-N via RPC; exact holder count when the deployment has an indexer key.',+ inputSchema: {+ type: 'object',+ required: ['address'],+ properties: {+ address: {+ type: 'string',+ description: 'Solana token mint to inspect (base58).',+ },+ chain: {+ type: 'string',+ enum: ['solana'],+ default: 'solana',+ description: 'Solana only — SPL token accounts have no EVM equivalent in this reader.',+ },+ limit: {+ type: 'integer',+ minimum: 1,+ maximum: 50,+ default: 10,+ description: 'How many top holders to return (capped at 50).',+ },+ },+ },+ outputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string' },+ chain: { type: 'string' },+ holderCount: { type: ['integer', 'null'] },+ top: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ owner: { type: 'string' },+ amount: { type: 'number' },+ pct: { type: ['number', 'null'] },+ },+ },+ },+ top10Pct: { type: ['number', 'null'] },+ concentration: { type: 'string', enum: ['low', 'medium', 'high', 'unknown'] },+ ts: { type: 'string', format: 'date-time' },+ sources: { type: 'array', items: { type: 'string' } },+ note: { type: 'string' },+ },+ },+ example: '/api/crypto/holders?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&limit=10',+};diff --git a/api/_lib/crypto-catalog/index.js b/api/_lib/crypto-catalog/index.jsindex 1383944a5..c0a74557c 100644--- a/api/_lib/crypto-catalog/index.js+++ b/api/_lib/crypto-catalog/index.js@@ -24,6 +24,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';import { basename, dirname, join } from 'node:path';import bondingEntry from './bonding.js';+import holdersEntry from './holders.js';import launchesEntry from './launches.js';import securityEntry from './security.js';import symbolEntry from './symbol.js';@@ -43,6 +44,7 @@ import whalesEntry from './whales.js';// >>> import + line here. The import is what makes it exist in production.const STATIC_ENTRIES = [{ mod: bondingEntry, source: 'bonding.js' },+ { mod: holdersEntry, source: 'holders.js' },{ mod: launchesEntry, source: 'launches.js' },{ mod: securityEntry, source: 'security.js' },{ mod: symbolEntry, source: 'symbol.js' },diff --git a/api/_lib/crypto-token-holders.js b/api/_lib/crypto-token-holders.jsnew file mode 100644index 000000000..ddea6ab79--- /dev/null+++ b/api/_lib/crypto-token-holders.js@@ -0,0 +1,294 @@+// Holder-distribution composition for the free Crypto Data API+// (/api/crypto/holders).+//+// An agent sizing a position needs one read: how many holders, what the top+// wallets control, and whether concentration is an exit risk. Two real paths,+// never a mock:+// - Helius DAS `getTokenAccounts` when HELIUS_API_KEY exists — enumerates the+// token's accounts page by page and aggregates by OWNER wallet, so a whale+// split across several token accounts still reads as one holder. Full+// enumeration (within the page cap) also yields the true holder count.+// - Keyless Solana RPC otherwise — `getTokenLargestAccounts` (top 20 token+// accounts) + `getMultipleAccounts` to resolve each account's owner ++// the mint's supply for percentages. A coarse-but-real top-N; the total+// holder count is unknowable keylessly and reported null, never guessed.+//+// Percentages are against on-chain supply from the same mint read the security+// endpoint uses (parseMintAccount, shared with api/v1/token/security.js).+// The `concentration` verdict is a documented threshold on top10Pct — see+// deriveConcentration; docs/crypto-api.md mirrors the exact numbers.++import { parseMintAccount } from '../v1/token/security.js';+import { solanaRpcEndpoints, makeRotatingFetch } from './solana/connection.js';++const RPC_TIMEOUT_MS = 8000;++// Helius DAS getTokenAccounts pages at up to 1000 accounts; cap the walk so a+// mega-token (millions of accounts) can't burn the invocation. Within the cap+// the holder count is exact; beyond it we report null + a note, never a guess.+const HELIUS_PAGE_LIMIT = 1000;+const HELIUS_MAX_PAGES = 5;++// Documented concentration thresholds on top10Pct (aligned with the security+// reader's top10 > 80 flag so the two surfaces can't contradict each other).+export const CONCENTRATION_HIGH_PCT = 80;+export const CONCENTRATION_MEDIUM_PCT = 50;++export const MAX_LIMIT = 50;+export const DEFAULT_LIMIT = 10;++const num = (v) => {+ const n = typeof v === 'string' ? Number(v) : v;+ return Number.isFinite(n) ? n : null;+};++/** Percentage of raw base-unit `part` against raw `total`, 2 decimals. */+export function pctOfSupply(part, total) {+ const t = num(total);+ const p = num(part);+ if (!t || t <= 0 || p == null) return null;+ return Math.round((p / t) * 10000) / 100;+}++/**+ * Aggregate token accounts by owner into a ranked holder list.+ * @param {Array<{ owner?: string|null, address?: string, amount: string|number }>} accounts+ * @param {string|number|null} supplyRaw+ * @param {number} limit+ */+export function rankHolders(accounts, supplyRaw, limit) {+ if (!Array.isArray(accounts) || !accounts.length) return [];+ const byOwner = new Map();+ for (const a of accounts) {+ const amt = num(a?.amount);+ if (amt == null || amt <= 0) continue;+ // Owner unresolved (RPC couldn't parse the account) → keep the token+ // account address as the key so the balance still counts, honestly labeled.+ const key = a.owner || a.address || 'unknown';+ byOwner.set(key, (byOwner.get(key) || 0) + amt);+ }+ return [...byOwner.entries()]+ .sort((x, y) => y[1] - x[1])+ .slice(0, limit)+ .map(([owner, amount]) => ({+ owner,+ amount,+ pct: pctOfSupply(amount, supplyRaw),+ }));+}++/** Cumulative % of supply held by the top 10 aggregated holders. */+export function top10PctOf(ranked) {+ if (!Array.isArray(ranked) || !ranked.length) return null;+ let sum = 0;+ let any = false;+ for (const h of ranked.slice(0, 10)) {+ if (h.pct == null) continue;+ sum += h.pct;+ any = true;+ }+ return any ? Math.round(sum * 100) / 100 : null;+}++/**+ * The documented threshold rule (mirror any change into docs/crypto-api.md):+ * high — top10Pct > 80+ * medium — top10Pct > 50+ * low — top10Pct ≤ 50+ * unknown — top10Pct unresolved+ */+export function deriveConcentration(top10Pct) {+ if (top10Pct == null) return 'unknown';+ if (top10Pct > CONCENTRATION_HIGH_PCT) return 'high';+ if (top10Pct > CONCENTRATION_MEDIUM_PCT) return 'medium';+ return 'low';+}++async function rpcCall(rpcFetch, method, params) {+ const resp = await rpcFetch(null, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),+ });+ return resp.json();+}++/**+ * Walk Helius DAS getTokenAccounts for a mint, aggregating by owner. Returns+ * null when no key is configured (caller falls back to keyless RPC).+ * `complete` is true iff every account was enumerated within the page cap —+ * only then is a holder count honest.+ */+export async function heliusHolderWalk(mint, { fetchImpl = fetch } = {}) {+ const key = process.env.HELIUS_API_KEY;+ if (!key) return null;+ const url = `https://mainnet.helius-rpc.com/?api-key=${key}`;+ const accounts = [];+ let complete = false;+ for (let page = 1; page <= HELIUS_MAX_PAGES; page++) {+ const r = await fetchImpl(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'holders',+ method: 'getTokenAccounts',+ params: { mint, page, limit: HELIUS_PAGE_LIMIT },+ }),+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),+ });+ if (!r.ok) throw new Error(`helius getTokenAccounts ${r.status}`);+ const json = await r.json();+ const batch = json?.result?.token_accounts;+ if (!Array.isArray(batch)) throw new Error('helius getTokenAccounts: malformed response');+ accounts.push(...batch.map((a) => ({ owner: a.owner || null, address: a.address, amount: a.amount })));+ if (batch.length < HELIUS_PAGE_LIMIT) {+ complete = true;+ break;+ }+ }+ return { accounts, complete };+}++// Default network dependency bundle — injectable for tests.+export function realHolderDeps() {+ const rpcFetch = makeRotatingFetch(solanaRpcEndpoints('mainnet'));+ return {+ fetchMintAccount: (address) =>+ rpcCall(rpcFetch, 'getAccountInfo', [address, { encoding: 'jsonParsed', commitment: 'confirmed' }]),+ fetchLargestAccounts: (address) =>+ rpcCall(rpcFetch, 'getTokenLargestAccounts', [address, { commitment: 'confirmed' }]),+ fetchAccountOwners: async (tokenAccounts) => {+ const json = await rpcCall(rpcFetch, 'getMultipleAccounts', [tokenAccounts, { encoding: 'jsonParsed', commitment: 'confirmed' }]);+ const values = json?.result?.value;+ if (!Array.isArray(values)) return new Map();+ const owners = new Map();+ values.forEach((v, i) => {+ const owner = v?.data?.parsed?.info?.owner;+ if (owner) owners.set(tokenAccounts[i], owner);+ });+ return owners;+ },+ fetchHelius: (address) => heliusHolderWalk(address),+ };+}++/**+ * Compose the holder-distribution report for one mint.+ *+ * @param {{ address: string, limit?: number }} input+ * @param {ReturnType<typeof realHolderDeps>} [deps]+ * @returns {Promise<+ * | { status: 'ok', holderCount: number|null, top: Array<{owner,amount,pct}>,+ * top10Pct: number|null, concentration: string, sources: string[], note?: string }+ * | { status: 'not_found' }+ * | { status: 'upstream_down' }+ * >}+ */+export async function composeTokenHolders({ address, limit = DEFAULT_LIMIT }, deps = realHolderDeps()) {+ const capped = Math.min(MAX_LIMIT, Math.max(1, Math.floor(limit) || DEFAULT_LIMIT));++ // The mint read anchors everything: supply for percentages, and existence —+ // a mint that isn't on chain is a not-found regardless of holder sources.+ let mint = null;+ let mintAnswered = false;+ try {+ const acct = await deps.fetchMintAccount(address);+ mintAnswered = true;+ mint = parseMintAccount(acct?.result);+ } catch { /* RPC down — holder paths below may still answer */ }++ if (mintAnswered && !mint) return { status: 'not_found' };++ const supply = mint?.supply ?? null;+ const sources = [];+ let note;++ // Preferred: Helius owner-aggregated walk (exact within the page cap).+ try {+ const helius = await deps.fetchHelius(address);+ if (helius) {+ const owners = new Map();+ for (const a of helius.accounts) {+ if (num(a.amount) > 0) owners.set(a.owner || a.address, true);+ }+ const top = rankHolders(helius.accounts, supply, capped);+ if (top.length || helius.complete) {+ sources.push('helius-das');+ if (mint) sources.push('solana-rpc');+ const top10Pct = top10PctOf(rankHolders(helius.accounts, supply, 10));+ if (!helius.complete) {+ note = `holder count omitted: more than ${HELIUS_MAX_PAGES * HELIUS_PAGE_LIMIT} token accounts — top holders are computed from the first ${HELIUS_MAX_PAGES * HELIUS_PAGE_LIMIT}.`;+ }+ return {+ status: 'ok',+ holderCount: helius.complete ? owners.size : null,+ top,+ top10Pct,+ concentration: deriveConcentration(top10Pct),+ sources,+ ...(note ? { note } : {}),+ };+ }+ }+ } catch { /* keyed path failed — fall through to the keyless truth */ }++ // Keyless: top-20 largest token accounts + owner resolution.+ // `largestAnswered` requires a REAL array answer. A JSON-RPC error envelope+ // (e.g. the public chain throttling getTokenLargestAccounts with "Too many+ // requests") is NOT an answer — counting it as one turned a throttled read+ // into a false "brand-new token, no holders" on live mints.+ let largest = null;+ let largestAnswered = false;+ try {+ const json = await deps.fetchLargestAccounts(address);+ if (Array.isArray(json?.result?.value)) {+ largestAnswered = true;+ largest = json.result.value;+ }+ } catch { /* RPC down for this call */ }++ if (largest?.length) {+ let owners = new Map();+ try {+ owners = await deps.fetchAccountOwners(largest.map((a) => a.address));+ } catch { /* owner resolution is enrichment — top-N stands on account addresses */ }+ const accounts = largest.map((a) => ({+ address: a.address,+ owner: owners.get(a.address) || null,+ amount: a.amount,+ }));+ const top = rankHolders(accounts, supply, capped);+ const top10Pct = top10PctOf(rankHolders(accounts, supply, 10));+ sources.push('solana-rpc');+ return {+ status: 'ok',+ holderCount: null,+ top,+ top10Pct,+ concentration: deriveConcentration(top10Pct),+ sources,+ note: 'keyless path: top holders from the chain\'s 20 largest token accounts; total holder count is not derivable without an indexer key.',+ };+ }++ // Nothing produced holders. Mint answered (token exists) with an empty holder+ // read → a brand-new token with no accounts yet is a valid empty, not an error.+ if (mint && largestAnswered) {+ return {+ status: 'ok',+ holderCount: null,+ top: [],+ top10Pct: null,+ concentration: 'unknown',+ sources: ['solana-rpc'],+ note: 'no token accounts found yet — brand-new or unfunded mint.',+ };+ }++ // Only reachable when the largest-accounts read failed at transport level+ // (a non-mint address already returned not_found above). The token may well+ // exist — report retryable, never a false not-found.+ return { status: 'upstream_down' };+}diff --git a/api/crypto/holders.js b/api/crypto/holders.jsnew file mode 100644index 000000000..3f4567cee--- /dev/null+++ b/api/crypto/holders.js@@ -0,0 +1,99 @@+// GET /api/crypto/holders — free holder distribution / concentration for a+// Solana token.+//+// Agent use-case: an agent sizing a position needs holder distribution before+// it commits — how many holders exist, what share the top wallets control, and+// whether the dev/insiders still dominate. High concentration = exit risk. One+// keyless call answers it with real on-chain data.+//+// Part of the free Crypto Data API (/api/crypto/*). Plain-handler pattern: no+// account, no key, generous per-IP limit. Two real paths (never a mock): a+// Helius owner-aggregated walk when the deployment has a key (exact holder+// count within its cap), else the keyless RPC truth — the chain's 20 largest+// token accounts with owners resolved, marked as such in `sources`/`note`.+//+// Query:+// address = <Solana mint> (required)+// chain = solana (optional; only 'solana'/'sol' accepted)+// limit = 1..50 (default 10) — how many top holders to return+//+// Response: { address, chain, holderCount, top: [{ owner, amount, pct }],+// top10Pct, concentration: low|medium|high|unknown, ts, sources[], note? }+// `concentration` is a documented threshold on top10Pct (>80 high, >50 medium).++import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';+import { composeTokenHolders, DEFAULT_LIMIT, MAX_LIMIT } from '../_lib/crypto-token-holders.js';++const EXAMPLE = '/api/crypto/holders?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++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 rawLimit = Number(url.searchParams.get('limit'));+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : DEFAULT_LIMIT));++ if (!address) {+ return error(res, 400, 'missing_address', 'query param `address` is required — pass a Solana token mint', {+ example: EXAMPLE,+ });+ }+ // Solana-only, honestly: SPL token accounts have no EVM equivalent here.+ if (isValidEvmAddress(address) || (rawChain && rawChain !== 'solana' && rawChain !== 'sol')) {+ return error(res, 400, 'unsupported_chain', 'this endpoint reads Solana holder distribution only — pass a base58 Solana mint address', {+ example: EXAMPLE,+ });+ }+ if (!isValidSolanaAddress(address)) {+ return error(res, 400, 'invalid_address', '`address` must be a base58 Solana mint address (32–44 chars)', {+ address,+ example: EXAMPLE,+ });+ }++ const result = await composeTokenHolders({ address, limit });+ const ts = new Date().toISOString();++ if (result.status === 'not_found') {+ return error(res, 400, 'token_not_found', `${address} is not an on-chain token mint — check the address, or discover live tokens at /api/crypto/trending`, {+ address,+ });+ }+ if (result.status === 'upstream_down') {+ return json(res, 503, {+ error: 'upstream_unavailable',+ error_description: 'holder data sources are temporarily unreachable — retry shortly',+ address,+ retry_after: 15,+ ts,+ }, { 'cache-control': 'no-store', 'retry-after': '15' });+ }++ const body = {+ address,+ chain: 'solana',+ holderCount: result.holderCount,+ top: result.top,+ top10Pct: result.top10Pct,+ concentration: result.concentration,+ ts,+ sources: result.sources,+ };+ if (result.note) body.note = result.note;++ // Distribution shifts trade by trade but a position-sizing read tolerates a+ // minute of cache; this absorbs polling bursts without hammering the RPC.+ return json(res, 200, body, {+ 'cache-control': 'public, s-maxage=60, stale-while-revalidate=60',+ });+});diff --git a/data/changelog.json b/data/changelog.jsonindex 31147f60d..7b0571f9f 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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 holder distribution / concentration API",+ "summary": "New free endpoint in the Crypto Data API: GET /api/crypto/holders shows who actually holds a Solana token before you size a position — the top wallets with their share of supply, the cumulative top-10 percentage, and a clear low/medium/high concentration verdict on documented thresholds. When the platform's indexer key is available holders are aggregated by wallet with an exact count; without it the endpoint still returns the chain's real top accounts, clearly labeled. No API key, no account, honest nulls for anything unknowable.",+ "tags": [+ "feature"+ ],+ "link": "/docs/crypto-api"+ },{"date": "2026-07-07","title": "Platformer tours — visitors jump through your store's checkpoints",diff --git a/docs/crypto-api.md b/docs/crypto-api.mdindex 2ed29e6b5..55eecca2a 100644--- a/docs/crypto-api.md+++ b/docs/crypto-api.md@@ -44,6 +44,7 @@ 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/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/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. |@@ -732,3 +733,92 @@ curl -s "https://three.ws/api/crypto/security?address=FeMbDoX7R1Psc4GEcvJdsbNbZA# Just the verdict and whycurl -s "https://three.ws/api/crypto/security?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" | jq '{riskLevel, reasons}'```++---++## `GET /api/crypto/holders` — Holders & concentration++**Use-case.** An *agent sizing a position* needs holder distribution before it+commits: how many holders exist, what share the top wallets control, whether the+dev or insiders still dominate. High concentration = exit risk — the top wallets+can drain the pool before the agent can react. One free call answers it with+real on-chain data.++### Request++| Param | Type | Default | Notes |+|-----------|---------|----------|-------|+| `address` | string | required | Solana token mint (base58). |+| `chain` | enum | `solana` | Only `solana` (alias `sol`) is accepted. |+| `limit` | integer | `10` | Top holders to return, `1`–`50` (capped, not an error). |++### Response++```json+{+ "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "chain": "solana",+ "holderCount": 3241,+ "top": [+ { "owner": "THREEsynthetic1111111111111111111111111111A", "amount": 59968211131,+ "pct": 6.0 }+ ],+ "top10Pct": 22.17,+ "concentration": "low",+ "ts": "2026-07-07T03:05:00.000Z",+ "sources": ["helius-das", "solana-rpc"]+}+```++- **`top[].owner`** — the holder's *wallet*, aggregated across all of its token+ accounts on the keyed path; on the keyless path each entry is one token+ account's resolved owner (or the account address itself if the owner read+ failed, honestly un-aggregated).+- **`top[].amount`** — raw base units. **`pct`** — % of on-chain supply, 2 decimals.+- **`holderCount`** — exact only when the keyed walk enumerated every account;+ `null` otherwise (keyless RPC cannot count holders — it is never guessed).+- LP pools and bonding-curve accounts appear among holders when they genuinely+ hold supply (e.g. an on-curve pump.fun coin's curve account) — real custody,+ reported as-is.++### The concentration rule (documented thresholds)++| Verdict | Rule |+|---------|------|+| `high` | `top10Pct` > 80 |+| `medium` | `top10Pct` > 50 |+| `low` | `top10Pct` ≤ 50 |+| `unknown` | `top10Pct` unresolved |++The 80% bar matches the security endpoint's `topHolderPctFlag`, so the two+surfaces can never contradict each other.++### Sources++- **Keyed (when the deployment has an indexer key):** Helius DAS+ `getTokenAccounts` — pages through the token's accounts and aggregates by+ owner wallet, so a whale split across accounts reads as one holder. Walk+ capped at 5,000 accounts; beyond it `holderCount` is `null` with a `note`.+- **Keyless fallback (always available):** Solana RPC `getTokenLargestAccounts`+ (the chain's top 20 token accounts) + `getMultipleAccounts` to resolve owners+ + the mint's supply for percentages. Coarse but real, and marked in `note`.++### States++- **Brand-new token, zero token accounts** → `200` with `top: []`,+ `concentration: "unknown"`, and a note — a valid empty, not an error.+- **Missing/EVM/invalid `address`** → `400` with a clear message + example.+- **Valid address that isn't an on-chain mint** → `400 token_not_found`.+- **Holder sources unreachable or throttled** → `503` + `Retry-After`. A throttled+ RPC is never reported as "no holders". Never `500`.+- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.++### Examples++```bash+# Top 10 holders of $THREE with the concentration verdict+curl -s "https://three.ws/api/crypto/holders?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"++# Just the verdict for position sizing+curl -s "https://three.ws/api/crypto/holders?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" | jq '{top10Pct, concentration}'+```diff --git a/prompts/x402-overhaul/PROGRESS.md b/prompts/x402-overhaul/PROGRESS.mdindex 80e67f3c9..ff41841ab 100644--- a/prompts/x402-overhaul/PROGRESS.md+++ b/prompts/x402-overhaul/PROGRESS.md@@ -1692,3 +1692,65 @@ both catalogs updated to say so.- The v1 reader's pure functions living inside an endpoint file(`api/v1/token/security.js`) is awkward for reuse — a future refactor couldlift them into `api/_lib/`, but NOT mid-campaign while both files are hot.++## 2026-07-07 — Prompt 03: Free Crypto Data API — Holders & Concentration++**Shipped.**++- **`GET /api/crypto/holders`** (`api/crypto/holders.js`) — free holder+ distribution for a Solana mint. Params: `address` (required), `chain`+ (solana/sol only; EVM → honest 400), `limit` 1..50 (default 10, capped not+ errored). Output: `{ address, chain, holderCount, top:[{ owner, amount,+ pct }], top10Pct, concentration: low|medium|high|unknown, ts, sources[],+ note? }`.+- **`api/_lib/crypto-token-holders.js`** — composition engine, two real paths:+ 1. **Keyed:** Helius DAS `getTokenAccounts` walk (≤5 pages × 1000), aggregated+ by OWNER wallet (a whale split across token accounts reads as one holder);+ exact `holderCount` only when the walk completed — beyond the cap it's+ null + note, never a guess.+ 2. **Keyless (always works):** RPC `getTokenLargestAccounts` (top 20) ++ `getMultipleAccounts` owner resolution + mint supply for pct; holderCount+ null (unknowable keylessly), marked in `note`.+ Supply/percentages anchor on the same `parseMintAccount` the security surfaces+ use. Concentration thresholds documented + exported: high >80 / medium >50 /+ low ≤50 / unknown — the 80 bar deliberately matches the security endpoints'+ top10 flag so surfaces can't contradict.+- **Two real bugs caught by exercising live before shipping:**+ 1. Mint readable + holder read down → was falling through to `not_found`;+ now `upstream_down` (a transport failure must never read as "token doesn't+ exist").+ 2. Public RPCs throttle `getTokenLargestAccounts` with a JSON-RPC **error+ envelope** — counting that as "answered" turned throttling into a false+ "brand-new token, no holders" for $THREE. Now only a real array counts as+ an answer; the throttled read returns a retryable 503. Both regression-tested.+- **Catalog:** `api/_lib/crypto-catalog/holders.js` + STATIC_ENTRIES barrel+ registration in `crypto-catalog/index.js` (required for production).+- **Docs:** table row + full section (concentration thresholds table, both+ source paths, LP/curve-account honesty note, states, curls) in+ `docs/crypto-api.md`. `data/changelog.json` entry (feature), validated via+ `npm run build:pages`.+- **Tests:** `tests/crypto-token-holders.test.js` — **16 tests**: pct/top10+ math, owner aggregation + limit cap + zero-balance drop + unresolved-owner+ keying, threshold boundaries (80/50 exact edges), keyless fallback shape,+ helius complete/incomplete/throwing paths, brand-new-mint valid-empty,+ not_found vs upstream_down separation incl. the error-envelope case.++**Verification (real, this session):**+- `npx vitest run tests/crypto-token-holders.test.js` → **16/16 passed**;+ `tests/crypto-catalog.test.js` green with the new barrel entry (catalog+ assembles: bonding, holders, launches, security, symbol, token, trending,+ wallet, whales).+- Live handler drive: 400 states correct. Live `$THREE` from THIS box → honest+ `503 upstream_unavailable` because the local egress is throttled for+ `getTokenLargestAccounts` on every public RPC in the chain (same limitation+ documented in prompt 02) — NOT an endpoint fault: production resolves these+ exact reads (proved live via `/api/v1/token/security` returning top1 5.99% /+ top10 22.17% for $THREE). Production 200 to be captured post-deploy alongside+ the prompt-01/02 probes.++**Adjacent gaps noticed:**+- Prompts 01–03 + 04 are now all built → the original 10-endpoint crypto bundle+ is complete. Remaining campaign work: 20 (deprecate dead endpoints),+ 21 (unified catalog), 22 (x402scan profile).+- `heliusHolderWalk` would serve prompt 22's "holder growth" momentum signal+ too if trending ever wants a holder-delta feature.diff --git a/public/changelog.json b/public/changelog.jsonindex d7eaa8ac7..395ee0652 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-07T02:58:42.682Z",+ "generated_at": "2026-07-07T03:06:11.649Z","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 holder distribution / concentration API",+ "summary": "New free endpoint in the Crypto Data API: GET /api/crypto/holders shows who actually holds a Solana token before you size a position — the top wallets with their share of supply, the cumulative top-10 percentage, and a clear low/medium/high concentration verdict on documented thresholds. When the platform's indexer key is available holders are aggregated by wallet with an exact count; without it the endpoint still returns the chain's real top accounts, clearly labeled. No API key, no account, honest nulls for anything unknowable.",+ "link": "/docs/crypto-api",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-07","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5371c3ede..844f75ba4 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=<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.</description></item>+ <item>+ <title>Free holder distribution / concentration API</title>+ <link>https://three.ws/docs/crypto-api</link>+ <guid isPermaLink="false">2026-07-07:Free holder distribution / concentration API</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/holders shows who actually holds a Solana token before you size a position — the top wallets with their share of supply, the cumulative top-10 percentage, and a clear low/medium/high concentration verdict on documented thresholds. When the platform's indexer key is available holders are aggregated by wallet with an exact count; without it the endpoint still returns the chain's real top accounts, clearly labeled. No API key, no account, honest nulls for anything unknowable.</description>+ </item><item><title>Free live pump.fun launches feed for agents</title><link>https://three.ws/docs/crypto-api</link>diff --git a/tests/crypto-token-holders.test.js b/tests/crypto-token-holders.test.jsnew file mode 100644index 000000000..0df8d6d0f--- /dev/null+++ b/tests/crypto-token-holders.test.js@@ -0,0 +1,215 @@+import { describe, it, expect } from 'vitest';++import {+ pctOfSupply,+ rankHolders,+ top10PctOf,+ deriveConcentration,+ composeTokenHolders,+ CONCENTRATION_HIGH_PCT,+ CONCENTRATION_MEDIUM_PCT,+} from '../api/_lib/crypto-token-holders.js';++// Synthetic mints/wallets only — never a real third-party address (CLAUDE.md).+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const W1 = 'THREEsynthetic1111111111111111111111111111A';+const W2 = 'THREEsynthetic2222222222222222222222222222B';+const W3 = 'THREEsynthetic3333333333333333333333333333C';++const SUPPLY = '1000000000'; // 1e9 raw units++const mintAccount = () => ({+ result: {+ value: {+ data: {+ parsed: {+ type: 'mint',+ info: { mintAuthority: null, freezeAuthority: null, supply: SUPPLY, decimals: 6 },+ },+ },+ },+ },+});++const deps = (over = {}) => ({+ fetchMintAccount: async () => mintAccount(),+ fetchLargestAccounts: async () => ({+ result: {+ value: [+ { address: 'acctA', amount: '400000000' },+ { address: 'acctB', amount: '300000000' },+ { address: 'acctC', amount: '100000000' },+ ],+ },+ }),+ fetchAccountOwners: async (addrs) =>+ new Map(addrs.map((a, i) => [a, [W1, W2, W3][i]].filter(Boolean)).filter((p) => p[1]).map((p) => p)),+ fetchHelius: async () => null, // keyless by default+ ...over,+});++describe('pctOfSupply / top10PctOf math', () => {+ it('computes 2-decimal percentages against raw supply', () => {+ expect(pctOfSupply('400000000', SUPPLY)).toBe(40);+ expect(pctOfSupply('1234567', SUPPLY)).toBe(0.12);+ expect(pctOfSupply('1', 0)).toBeNull();+ expect(pctOfSupply(null, SUPPLY)).toBeNull();+ });++ it('top10PctOf sums the top ten and ignores null pcts', () => {+ const ranked = [+ { owner: W1, amount: 400, pct: 40 },+ { owner: W2, amount: 300, pct: 30 },+ { owner: W3, amount: 100, pct: null },+ ];+ expect(top10PctOf(ranked)).toBe(70);+ expect(top10PctOf([])).toBeNull();+ expect(top10PctOf([{ owner: W1, amount: 1, pct: null }])).toBeNull();+ });+});++describe('rankHolders — owner aggregation', () => {+ it('aggregates multiple token accounts of one owner into one holder', () => {+ const ranked = rankHolders(+ [+ { owner: W1, amount: '100000000' },+ { owner: W1, amount: '150000000' },+ { owner: W2, amount: '200000000' },+ ],+ SUPPLY,+ 10,+ );+ expect(ranked).toHaveLength(2);+ expect(ranked[0]).toEqual({ owner: W1, amount: 250000000, pct: 25 });+ expect(ranked[1].owner).toBe(W2);+ });++ it('caps at limit, drops zero balances, keys unresolved owners by account address', () => {+ const ranked = rankHolders(+ [+ { owner: null, address: 'acctX', amount: '50' },+ { owner: W1, amount: '0' },+ { owner: W2, amount: '100' },+ ],+ SUPPLY,+ 1,+ );+ expect(ranked).toHaveLength(1);+ expect(ranked[0].owner).toBe(W2);+ });+});++describe('deriveConcentration — documented thresholds', () => {+ it('maps top10Pct through the documented rule', () => {+ expect(deriveConcentration(CONCENTRATION_HIGH_PCT + 0.01)).toBe('high');+ expect(deriveConcentration(CONCENTRATION_HIGH_PCT)).toBe('medium');+ expect(deriveConcentration(CONCENTRATION_MEDIUM_PCT + 0.01)).toBe('medium');+ expect(deriveConcentration(CONCENTRATION_MEDIUM_PCT)).toBe('low');+ expect(deriveConcentration(0)).toBe('low');+ expect(deriveConcentration(null)).toBe('unknown');+ });+});++describe('composeTokenHolders — keyless RPC fallback path', () => {+ it('resolves owners, ranks, and marks the keyless truth honestly', async () => {+ const r = await composeTokenHolders({ address: THREE, limit: 10 }, deps());+ expect(r.status).toBe('ok');+ expect(r.holderCount).toBeNull(); // unknowable keylessly — never guessed+ expect(r.top[0]).toEqual({ owner: W1, amount: 400000000, pct: 40 });+ expect(r.top10Pct).toBe(80);+ expect(r.concentration).toBe('medium');+ expect(r.sources).toEqual(['solana-rpc']);+ expect(r.note).toMatch(/keyless/);+ });++ it('caps limit and floors garbage to the default', async () => {+ const r = await composeTokenHolders({ address: THREE, limit: 999 }, deps());+ expect(r.top.length).toBeLessThanOrEqual(50);+ });++ it('owner resolution failing still returns top-N keyed by account address', async () => {+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchAccountOwners: async () => { throw new Error('rpc flake'); },+ }));+ expect(r.status).toBe('ok');+ expect(r.top[0].owner).toBe('acctA');+ });+});++describe('composeTokenHolders — helius path', () => {+ const heliusAccounts = [+ { owner: W1, address: 'a1', amount: '500000000' },+ { owner: W1, address: 'a2', amount: '100000000' },+ { owner: W2, address: 'a3', amount: '250000000' },+ { owner: W3, address: 'a4', amount: '50000000' },+ ];++ it('aggregates by owner and reports an exact holder count when complete', async () => {+ const r = await composeTokenHolders({ address: THREE, limit: 2 }, deps({+ fetchHelius: async () => ({ accounts: heliusAccounts, complete: true }),+ }));+ expect(r.status).toBe('ok');+ expect(r.holderCount).toBe(3);+ expect(r.top).toHaveLength(2);+ expect(r.top[0]).toEqual({ owner: W1, amount: 600000000, pct: 60 });+ expect(r.sources).toContain('helius-das');+ });++ it('incomplete walk → holderCount null with a note, top-N still real', async () => {+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchHelius: async () => ({ accounts: heliusAccounts, complete: false }),+ }));+ expect(r.holderCount).toBeNull();+ expect(r.note).toMatch(/holder count omitted/);+ expect(r.top[0].owner).toBe(W1);+ });++ it('helius throwing falls back to the keyless path', async () => {+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchHelius: async () => { throw new Error('quota'); },+ }));+ expect(r.status).toBe('ok');+ expect(r.sources).toEqual(['solana-rpc']);+ });+});++describe('composeTokenHolders — states', () => {+ it('mint answered but not a mint → not_found', async () => {+ const r = await composeTokenHolders({ address: W1 }, deps({+ fetchMintAccount: async () => ({ result: { value: null } }),+ }));+ expect(r.status).toBe('not_found');+ });++ it('brand-new mint with zero token accounts → valid empty, not an error', async () => {+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchLargestAccounts: async () => ({ result: { value: [] } }),+ }));+ expect(r.status).toBe('ok');+ expect(r.top).toEqual([]);+ expect(r.concentration).toBe('unknown');+ expect(r.note).toMatch(/brand-new/);+ });++ it('everything down → upstream_down', async () => {+ const boom = async () => { throw new Error('down'); };+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchMintAccount: boom, fetchLargestAccounts: boom, fetchHelius: async () => null,+ }));+ expect(r.status).toBe('upstream_down');+ });++ it('mint readable but holder read down → upstream_down, never a false not-found', async () => {+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchLargestAccounts: async () => { throw new Error('throttled'); },+ }));+ expect(r.status).toBe('upstream_down');+ });++ it('a JSON-RPC error envelope is NOT an answer — throttling never fakes an empty holder set', async () => {+ const r = await composeTokenHolders({ address: THREE }, deps({+ fetchLargestAccounts: async () => ({ error: { code: -32429, message: 'Too many requests' } }),+ }));+ expect(r.status).toBe('upstream_down');+ });+});