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(trading): add token due diligence (insider, sniper, bundler, fresh-wallet, smart-money fields), a two-hop funding graph and buy guards

nirholas4543593a66e8
diff --git a/STRUCTURE.md b/STRUCTURE.md
index ba4a0e0e9..c972573aa 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -141,6 +141,7 @@ packages, a generated standalone GitHub mirror). See
| OKX.AI marketplace chat bot host | [workers/okx-chat-bot/](workers/okx-chat-bot) (Cloud Run service `okx-chat-bot`), local revive [scripts/okx-bot-revive.mjs](scripts/okx-bot-revive.mjs) `→ npm run okx:bot`, session seeding [scripts/okx-bot-seed-state.mjs](scripts/okx-bot-seed-state.mjs) `→ npm run okx:bot:seed-state` | Live · Cloud Run since 2026-09-04, replies blocked on AI funding | Always-on host for the XMTP chat behind agent #2632. Supervises the `okx-a2a` daemon plus the `onchainos` wallet session, persists the wallet/XMTP identity to GCS across revisions, and rebuilds the AI subsession's briefing from [api/_lib/okx-chat-briefing.js](api/_lib/okx-chat-briefing.js) on every boot so quoted prices can never drift from the catalog. It exists because the stack used to live on a codespace that sleeps, and its outage mode is silent: an expired wallet session leaves the process healthy while no chat is delivered, which flagged the listing offline once. Health reaches the platform as the `okx_chat_bot` subsystem on `/api/healthz` via a `bot_heartbeat` row; a logged-out session pages with the exact login commands. The AI credential is probed against the provider rather than assumed present ([workers/okx-chat-bot/provider.js](workers/okx-chat-bot/provider.js)), because a key the provider refuses is indistinguishable from a working one until a buyer's message goes unanswered. The AI credential is an ordered chain rather than one lane (`vertex` on GCP credits, then an Anthropic key, then an Anthropic-wire-format gateway, then an interactive grant, then an OpenAI key): [electProvider()](workers/okx-chat-bot/provider.js) probes every rung on its own env overlay every 15 minutes and serves on the first that answers, so a lane the owner funds is picked up with no deploy and a refused one is never elected. Live state as of 2026-09-09, readable from the `bot_heartbeat` row when `gcloud` is not authenticated: the host has been up since 2026-09-04 with the wallet session logged in and one XMTP client serving, so buyer chat IS delivered, and every lane is refused for lack of funds (Vertex `Lightning dunning decision is deny`, OpenAI `billing_not_active`, OpenRouter `402`), so no reply can be authored. The running revision predates the chain, which its heartbeat meta shows by carrying no `providerLane` / `providerChain` keys. Deploy: [workers/okx-chat-bot/cloudbuild.yaml](workers/okx-chat-bot/cloudbuild.yaml) (`--max-instances=1` is load-bearing, one GCS state writer). Tests: [tests/okx-chat-bot.test.js](tests/okx-chat-bot.test.js) |
| Crypto Data API docs / landing | [pages/crypto.html](pages/crypto.html) `→ /crypto` | In-repo · docs surface | Screenshot-worthy public docs + funnel-top for the free, keyless Crypto Data API (`/api/crypto/*`: token snapshot, security, holders, launches, bonding, whales, symbol, wallet, trending, portfolio, airdrops). Renders hero, endpoint table, tabbed quickstart (curl/JS/Python), per-endpoint request/response reference and a live "Try it" console. Probes production at runtime and marks each endpoint Live vs Coming soon (degrades gracefully while sibling endpoints roll out). CTAs funnel to paid uniques: [/launcher](pages/launcher.html), [/vanity-wallet](public/vanity-wallet.html), [/forge](pages/forge.html). Spec: x402-overhaul campaign (retired 2026-07-28; readable in git history) |
| Free Crypto Data API + discovery | [api/crypto/index.js](api/crypto/index.js) `→ /api/crypto`, [api/crypto/openapi.js](api/crypto/openapi.js) `→ /api/crypto/openapi.json`, docs [docs/crypto-api.md](docs/crypto-api.md) `→ /docs/crypto-api` | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless Crypto Data API. Catalog assembler [api/_lib/crypto-catalog/index.js](api/_lib/crypto-catalog/index.js) merges `api/_lib/crypto-catalog/*.js` self-describing descriptors (currently `airdrops`, `bonding`, `holders`, `launches`, `linkage`, `portfolio`, `security`, `symbol`, `token`, `trending`, `wallet`, `whales`) via a static import barrel (the production source of truth, since Vercel's bundler only ships what static imports reach) plus an additive dev-time directory glob; skips malformed/throwing entries, never throws, valid-empty when zero. New descriptor = drop the file AND add its import line to the barrel. OpenAPI built from the same catalog via [api/_lib/crypto-catalog/openapi.js](api/_lib/crypto-catalog/openapi.js). Index does HTML/JSON content negotiation. Endpoint handlers live in `api/crypto/*.js`. Spec: x402-overhaul campaign (retired 2026-07-28; readable in git history) |
+| Token due diligence (holder quality + funding graph) | [api/_lib/token-due-diligence.js](api/_lib/token-due-diligence.js), endpoints [api/crypto/due-diligence.js](api/crypto/due-diligence.js) `→ /api/crypto/due-diligence` and [api/crypto/funding-graph.js](api/crypto/funding-graph.js), MCP tool [api/_mcp/tools/token-due-diligence.js](api/_mcp/tools/token-due-diligence.js) (`token_due_diligence`), token-page panel [src/token-dd-panel.js](src/token-dd-panel.js), guard limits in [api/_lib/agent-trade-guards.js](api/_lib/agent-trade-guards.js), docs [docs/token-due-diligence.md](docs/token-due-diligence.md) | Live | Insider hold rate, sniper share, bundler exposure, fresh-wallet share and smart-money holders computed from chain reads and our own `wallet_reputation`, with a two-hop funding force graph on `/three`. Buys are refused above `max_insider_pct`, `max_sniper_pct`, `max_bundler_pct` or `max_fresh_wallet_pct`. Tests: [tests/token-due-diligence.test.js](tests/token-due-diligence.test.js), [tests/agent-trade-endpoint.test.js](tests/agent-trade-endpoint.test.js). Fixture: [tests/fixtures/token-dd/three-recorded.json](tests/fixtures/token-dd/three-recorded.json) |
| Unified Crypto API aggregator — storefront + OpenAPI | Registry [api/v1/_providers.js](api/v1/_providers.js) (`providerCatalog()`), front door [api/v1/x/[...slug].js](api/v1/x/%5B...slug%5D.js) `→ /api/v1/x/<provider>/<endpoint>`, discovery `→ GET /api/v1/x`, storefront [pages/crypto-api.html](pages/crypto-api.html) `→ /crypto-api`, OpenAPI 3.1 [api/openapi-json.js](api/openapi-json.js) `→ /openapi.json`, docs § in [docs/api-reference.md](docs/api-reference.md#unified-api--apiv1x-aggregator), dir guide [api/v1/README.md](api/v1/README.md) | Live | Third-party crypto/DeFi/on-chain APIs (CoinGecko, DefiLlama × 2, Jupiter, DexScreener, Solana RPC, OpenAI-compatible) re-offered as one bill: free per-IP tier → BYOK pass-through → three.ws plan → x402 pay-per-call, in that order. Everything (OpenAPI paths, the `/crypto-api` live table, the docs quota table) renders from `providerCatalog()` at request/page-load time — no hand-enumeration, so a new provider descriptor shows up everywhere with zero page edits. Test: [tests/openapi-aggregator.test.js](tests/openapi-aggregator.test.js). Not to be confused with the separate `/api/crypto/*` bundle below (different campaign, different registry). Spec: x402-catalog campaign (retired 2026-07-28; readable in git history) |
| 3D Vision (let an agent see a model) | [api/_lib/3d-vision.js](api/_lib/3d-vision.js), route [api/3d/look.js](api/3d/look.js) `→ /api/3d/look`, MCP tool `look_at_model` in [api/_mcp-studio/tools.js](api/_mcp-studio/tools.js) and on every OKX forge endpoint ([api/_okx3d/forge.js](api/_okx3d/forge.js)), SDK [packages/see/](packages/see) (`@three-ws/see`) | Live | Every text-to-3D API answers with a URL to a binary an AI agent cannot open, so the agent that generated a model has no way to check its own work; that blindness is why agentic 3D stalls at one shot. This renders any public GLB from up to six angles (three-quarter, front, side, back, top, bottom; the default four are the smallest set that answers "is this good") and hands the frames back as **MCP image content blocks**, which a multimodal client renders into the conversation, so the model literally looks at its own output and can regenerate naming the fault it saw. Reuses the platform's headless renderer ([api/_lib/avatar-render.js](api/_lib/avatar-render.js)) with the `full-body` preset so props and creatures are not cropped like humanoids, renders frames sequentially because the browser is shared, and reports a partial turntable rather than failing. Geometry comes from the existing free inspector and is best-effort: a hiccup costs the numbers, never the frames. Free and keyless on REST and MCP, and free for OKX buyers on the paid forge endpoints, so an agent can confirm it got what it paid for. Docs: [docs/3d-vision.md](docs/3d-vision.md). Tests: [tests/3d-vision.test.js](tests/3d-vision.test.js) |
| Run receipts (expected vs observed, per stage) | core [api/_lib/run-receipt.js](api/_lib/run-receipt.js), storage + stats + rig read-back [api/_lib/run-receipt-store.js](api/_lib/run-receipt-store.js), table [api/_lib/migrations/20261014000000_run_receipts.sql](api/_lib/migrations/20261014000000_run_receipts.sql), studio wiring [api/_mcp-studio/receipts.js](api/_mcp-studio/receipts.js), REST [api/runs.js](api/runs.js) `→ /api/runs`, page [pages/runs.html](pages/runs.html) + [src/runs.js](src/runs.js) `→ /runs`, `/runs/:id`, offline verifier [scripts/run-receipt-verify.mjs](scripts/run-receipt-verify.mjs) | Live | Every 3D Studio generation (`forge_avatar`, `text_to_avatar`, `mesh_forge`, `forge_free`, `rig_mesh`, `refine_model`) writes a receipt: for each stage (input, subject, brief, mesh, geometry, visual, rig, delivery) what was expected, what was observed, a verdict (`met`, `recovered`, `missed`, `skipped`, `pending`) and the cause when it fell short. The rig stage is verified by reading the delivered GLB back with Rig Doctor's analysis, not from the rigger's report. Receipts are ed25519-signed with the attestation key, linked from every tool result (`structuredContent.receipt`), completed by `check_job` when a stage was still running, and aggregated at `/runs` into stage-by-stage met rates and top causes (counts only, no prompts). Fail-open: no database means an inline receipt without a link. Docs: [docs/run-receipts.md](docs/run-receipts.md) `→ /docs/run-receipts`. Tests: [tests/run-receipt.test.js](tests/run-receipt.test.js) |
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index fa8ceb1fd..842f4dd78 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -143,6 +143,11 @@ export const SPEND_LIMIT_DEFAULTS = Object.freeze({
// max_slippage_bps ceiling on the client-supplied slippage
// max_concurrent max open discretionary positions (null = unlimited)
// kill_switch when true, every discretionary trade is rejected
+// max_insider_pct refuse a buy when creator-linked holders own more than this % of supply
+// max_sniper_pct refuse a buy when launch-slot snipers own more than this % of supply
+// max_bundler_pct refuse a buy when bundled (shared-funder) holders own more than this % of supply
+// max_fresh_wallet_pct refuse a buy when fresh wallets own more than this % of supply
+// (the four holder limits read token_due_diligence; null = not checked)
export const TRADE_LIMIT_DEFAULTS = Object.freeze({
per_trade_sol: null,
daily_budget_sol: null,
@@ -150,6 +155,10 @@ export const TRADE_LIMIT_DEFAULTS = Object.freeze({
max_slippage_bps: 1000,
max_concurrent: null,
kill_switch: false,
+ max_insider_pct: null,
+ max_sniper_pct: null,
+ max_bundler_pct: null,
+ max_fresh_wallet_pct: null,
});
/**
@@ -299,6 +308,12 @@ function clampNum(v, def, { min = 0, max = Infinity, round = false } = {}) {
return round ? Math.round(c) : c;
}
+function pctCapOrNull(v) {
+ if (v == null || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null;
+}
+
/** Coerce arbitrary input into a clean, bounded trade-limit object. */
export function normalizeTradeLimits(raw) {
const r = raw && typeof raw === 'object' ? raw : {};
@@ -309,6 +324,10 @@ export function normalizeTradeLimits(raw) {
max_slippage_bps: clampNum(r.max_slippage_bps, TRADE_LIMIT_DEFAULTS.max_slippage_bps, { max: 10000, round: true }),
max_concurrent: r.max_concurrent == null ? null : clampNum(r.max_concurrent, null, { min: 1, max: 10000, round: true }),
kill_switch: r.kill_switch === true,
+ max_insider_pct: pctCapOrNull(r.max_insider_pct),
+ max_sniper_pct: pctCapOrNull(r.max_sniper_pct),
+ max_bundler_pct: pctCapOrNull(r.max_bundler_pct),
+ max_fresh_wallet_pct: pctCapOrNull(r.max_fresh_wallet_pct),
updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
};
}
@@ -340,6 +359,10 @@ export async function setTradeLimits(agentId, userId, patch, { req = null } = {}
max_slippage_bps: 'max_slippage_bps' in p ? p.max_slippage_bps : prev.max_slippage_bps,
max_concurrent: 'max_concurrent' in p ? p.max_concurrent : prev.max_concurrent,
kill_switch: 'kill_switch' in p ? p.kill_switch : prev.kill_switch,
+ max_insider_pct: 'max_insider_pct' in p ? p.max_insider_pct : prev.max_insider_pct,
+ max_sniper_pct: 'max_sniper_pct' in p ? p.max_sniper_pct : prev.max_sniper_pct,
+ max_bundler_pct: 'max_bundler_pct' in p ? p.max_bundler_pct : prev.max_bundler_pct,
+ max_fresh_wallet_pct: 'max_fresh_wallet_pct' in p ? p.max_fresh_wallet_pct : prev.max_fresh_wallet_pct,
});
next.updated_at = new Date().toISOString();
@@ -627,6 +650,50 @@ export function checkPriceImpact(priceImpactPct, maxPct) {
return null;
}
+const DUE_DILIGENCE_LIMITS = [
+ ['max_insider_pct', 'insider_pct', 'insider hold rate'],
+ ['max_sniper_pct', 'sniper_pct', 'sniper share'],
+ ['max_bundler_pct', 'bundler_pct', 'bundler exposure'],
+ ['max_fresh_wallet_pct', 'fresh_wallet_pct', 'fresh-wallet share'],
+];
+
+/**
+ * Holder-quality breaker over the token_due_diligence fields. Pure: `fields` is
+ * the report's `fields` object (or null when the report could not be read).
+ * A limit that is set but cannot be evaluated (no report, or that one field is
+ * null because chain reads failed) blocks with `due_diligence_unavailable`, so
+ * a missing read never passes as a clean token. No limit set means no check.
+ */
+export function checkDueDiligence(fields, limits) {
+ for (const [limitKey, fieldKey, label] of DUE_DILIGENCE_LIMITS) {
+ const max = limits?.[limitKey];
+ if (max == null) continue;
+ const value = fields?.[fieldKey];
+ if (value == null) return { reason: 'due_diligence_unavailable', detail: { field: fieldKey, label, max_pct: Number(max) } };
+ if (Number(value) > Number(max)) return { reason: 'due_diligence', detail: { field: fieldKey, label, value_pct: Number(value), max_pct: Number(max) } };
+ }
+ return null;
+}
+
+/**
+ * Async wrapper for the trade endpoints. Fetches the cached report only when an
+ * owner set at least one holder limit, so agents without limits pay nothing.
+ * @param {string} mint
+ * @param {object} limits normalized trade limits
+ * @param {{ load?: (mint:string)=>Promise<object|null> }} [opts]
+ */
+export async function guardDueDiligence(mint, limits, { load } = {}) {
+ if (!mint || !DUE_DILIGENCE_LIMITS.some(([k]) => limits?.[k] != null)) return null;
+ let report = null;
+ try {
+ const loader = load || (async (m) => (await import('./token-due-diligence.js')).getTokenDueDiligence(m));
+ report = await loader(mint);
+ } catch {
+ report = null;
+ }
+ return checkDueDiligence(report?.status === 'ok' ? report.fields : null, limits);
+}
+
/** Lamports spent (buys) by an agent over the trailing window — the trade +
* snipe SOL outflow that backs the discretionary daily budget. One wallet, one
* budget: a buy from the sniper and a buy from the trade endpoint both count. */
@@ -679,6 +746,14 @@ const GUARD_RESPONSE = {
status: 422,
message: (d) => `Price impact is ${Number(d.impact_pct).toFixed(2)}% — above the ${Number(d.max_pct).toFixed(2)}% safety breaker. Lower the trade size or raise the impact limit under Limits & Safety.`,
},
+ due_diligence: {
+ status: 422,
+ message: (d) => `This token fails your holder-quality limit: ${d.label} is ${Number(d.value_pct).toFixed(1)}% of supply, above your ${Number(d.max_pct).toFixed(1)}% limit. Raise the limit under Limits & Safety or pick another token.`,
+ },
+ due_diligence_unavailable: {
+ status: 422,
+ message: (d) => `Your ${d.label} limit of ${Number(d.max_pct).toFixed(1)}% could not be checked because the holder data for this token could not be read right now. Retry shortly, or clear the limit under Limits & Safety.`,
+ },
predictions_disabled: {
status: 403,
message: () => 'Prediction orders are off for this agent. Turn them on under Prediction limits on the agent\'s predictions page to continue.',
diff --git a/api/_lib/crypto-catalog/due-diligence.js b/api/_lib/crypto-catalog/due-diligence.js
new file mode 100644
index 000000000..59f0b1418
--- /dev/null
+++ b/api/_lib/crypto-catalog/due-diligence.js
@@ -0,0 +1,47 @@
+// Catalog entry for GET /api/crypto/due-diligence: holder-quality fields for a
+// Solana token. Plain, serializable, no imports, no side effects.
+
+export default {
+ slug: 'due-diligence',
+ method: 'GET',
+ path: '/api/crypto/due-diligence',
+ title: 'Token Due Diligence',
+ summary:
+ 'Who holds a Solana token, not just what its contract can do: insider hold rate, sniper share, bundler exposure, fresh-wallet ratio and smart-money holders as shares of supply, computed from chain data and our own tracked wallet history, with a two-hop funding graph of the largest holders. Cached per mint for five minutes; a field is null when its data could not be read.',
+ inputSchema: {
+ type: 'object',
+ required: ['address'],
+ properties: {
+ address: { type: 'string', description: 'Solana token mint to inspect (base58).' },
+ },
+ },
+ outputSchema: {
+ type: 'object',
+ properties: {
+ address: { type: 'string' },
+ chain: { type: 'string' },
+ computed_at: { type: 'string', format: 'date-time' },
+ ttl_seconds: { type: 'integer' },
+ fields: {
+ type: 'object',
+ properties: {
+ insider_pct: { type: ['number', 'null'] },
+ sniper_pct: { type: ['number', 'null'] },
+ bundler_pct: { type: ['number', 'null'] },
+ fresh_wallet_pct: { type: ['number', 'null'] },
+ fresh_wallet_ratio: { type: ['number', 'null'] },
+ smart_money_holders: { type: ['integer', 'null'] },
+ smart_money_pct: { type: ['number', 'null'] },
+ },
+ },
+ holders: { type: 'array', items: { type: 'object' } },
+ clusters: { type: 'array', items: { type: 'object' } },
+ coverage: { type: 'object' },
+ notes: { type: 'array', items: { type: 'string' } },
+ graph: { type: 'object' },
+ thresholds: { type: 'object' },
+ definitions: { type: 'object' },
+ },
+ },
+ example: '/api/crypto/due-diligence?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+};
diff --git a/api/_lib/crypto-catalog/funding-graph.js b/api/_lib/crypto-catalog/funding-graph.js
new file mode 100644
index 000000000..536f14848
--- /dev/null
+++ b/api/_lib/crypto-catalog/funding-graph.js
@@ -0,0 +1,30 @@
+// Catalog entry for GET /api/crypto/funding-graph: two-hop funding trace for a
+// Solana wallet. Plain, serializable, no imports, no side effects.
+
+export default {
+ slug: 'funding-graph',
+ method: 'GET',
+ path: '/api/crypto/funding-graph',
+ title: 'Wallet Funding Graph',
+ summary:
+ 'Two-hop funding trace for a Solana wallet: who paid it into existence and who funded that account, as nodes and edges ready to render. A funder with history too long to reach (an exchange, a router) is flagged as a service and the trace stops there.',
+ inputSchema: {
+ type: 'object',
+ required: ['wallet'],
+ properties: {
+ wallet: { type: 'string', description: 'Solana wallet address to trace (base58).' },
+ },
+ },
+ outputSchema: {
+ type: 'object',
+ properties: {
+ wallet: { type: 'string' },
+ hops: { type: 'integer' },
+ nodes: { type: 'array', items: { type: 'object' } },
+ edges: { type: 'array', items: { type: 'object' } },
+ truncated: { type: 'boolean' },
+ ts: { type: 'string', format: 'date-time' },
+ },
+ },
+ example: '/api/crypto/funding-graph?wallet=JUPW3tHBxmNRzVnLmTyYUsUDB6izZSEtupY6znBC5mo',
+};
diff --git a/api/_lib/crypto-catalog/index.js b/api/_lib/crypto-catalog/index.js
index 6577af9e1..f5a9226a5 100644
--- a/api/_lib/crypto-catalog/index.js
+++ b/api/_lib/crypto-catalog/index.js
@@ -25,6 +25,8 @@ import { basename, dirname, join } from 'node:path';
import airdropsEntry from './airdrops.js';
import bondingEntry from './bonding.js';
+import dueDiligenceEntry from './due-diligence.js';
+import fundingGraphEntry from './funding-graph.js';
import holdersEntry from './holders.js';
import launchesEntry from './launches.js';
import linkageEntry from './linkage.js';
@@ -48,6 +50,8 @@ import whalesEntry from './whales.js';
const STATIC_ENTRIES = [
{ mod: airdropsEntry, source: 'airdrops.js' },
{ mod: bondingEntry, source: 'bonding.js' },
+ { mod: dueDiligenceEntry, source: 'due-diligence.js' },
+ { mod: fundingGraphEntry, source: 'funding-graph.js' },
{ mod: holdersEntry, source: 'holders.js' },
{ mod: launchesEntry, source: 'launches.js' },
{ mod: linkageEntry, source: 'linkage.js' },
diff --git a/api/_lib/token-due-diligence.js b/api/_lib/token-due-diligence.js
new file mode 100644
index 000000000..bfdd46d8a
--- /dev/null
+++ b/api/_lib/token-due-diligence.js
@@ -0,0 +1,726 @@
+// Token due diligence: who holds a mint, and how those holders relate.
+//
+// A contract-flag report (mint authority, freeze authority, LP lock) says what
+// a token CAN do. This module answers the other half: what its holders ARE.
+// Everything here is derived from chain data we already read (token accounts,
+// signature history, first transactions) plus our own tracked wallet history.
+// No third-party wallet labels are scraped or trusted.
+//
+// Definitions and thresholds live in DD_DEFINITIONS / DD_THRESHOLDS below and
+// are mirrored in docs/token-due-diligence.md. Percentages are shares of TOTAL
+// supply, the same basis as /api/crypto/holders. Every field is null (never a
+// guess) when the data it needs could not be read; `coverage` says why.
+//
+// Layout:
+// pure computeDueDiligence / buildFundingGraph / clusterHolders ...
+// io collectChainData (RPC) + getTokenDueDiligence (cache + smart money)
+// and traceFundingGraph, the two-hop funding trace for one wallet
+
+import { PublicKey } from '@solana/web3.js';
+import { solanaRpcEndpoints, makeRotatingFetch } from './solana/connection.js';
+import { parseMintAccount } from '../v1/token/security.js';
+import { pctOfSupply } from './crypto-token-holders.js';
+import { parseFunderFromTransaction } from './pump-intel/enrich.js';
+import { mapPoolSettled } from './pool.js';
+import { cacheWrap } from './cache.js';
+
+const DOC_BASE = 'https://github.com/nirholas/three.ws/blob/main/docs/token-due-diligence.md';
+
+export const DD_TTL_SECONDS = 300;
+export const FUNDING_TTL_SECONDS = 6 * 3600;
+
+export const DD_THRESHOLDS = Object.freeze({
+ /** Largest token accounts analysed per mint (the chain returns at most 20). */
+ analyze_top: 20,
+ /** A holder is a sniper when its first receipt of the token landed within this many slots of launch. */
+ sniper_slots: 5,
+ /** Holders sharing a funder (or a launch slot) are a bundle from this group size up. */
+ bundler_min_group: 2,
+ /** Same-slot grouping needs one more wallet, because organic buyers do share busy slots. */
+ same_slot_min_group: 3,
+ /** Wallets funded by one source within this window of each other form a cluster. */
+ funding_window_hours: 6,
+ /** A wallet is fresh when its first-ever transaction is under this age at its first token receipt. */
+ fresh_wallet_max_age_hours: 24,
+ /** Smart money: wallet_reputation.smart_money_score at or above this bar. */
+ smart_money_min_score: 65,
+ /** A funder whose own history exceeds this many signatures is a service (exchange, router), not a coordinator. */
+ service_funder_min_sigs: 2000,
+ /** A field is reported only when at least this share of analysed wallet holders yielded the evidence it needs; below it the field is null, not a low number. */
+ min_evidence_ratio: 0.5,
+});
+
+export const DD_FIELDS = ['insider_pct', 'sniper_pct', 'bundler_pct', 'fresh_wallet_pct', 'fresh_wallet_ratio', 'smart_money_holders', 'smart_money_pct'];
+
+/** Field definitions, mirrored one-to-one in docs/token-due-diligence.md#definitions. */
+export const DD_DEFINITIONS = Object.freeze({
+ insider_pct: {
+ label: 'Insider hold rate',
+ unit: 'percent of supply',
+ definition:
+ 'Share of supply held by the creator wallet and by holders linked to it: funded by the creator, funding the creator, or funded from the same non-service source within two hops.',
+ doc: DOC_BASE + '#insider_pct',
+ },
+ sniper_pct: {
+ label: 'Sniper share',
+ unit: 'percent of supply',
+ definition: `Share of supply held by wallets whose first receipt of the token landed within ${DD_THRESHOLDS.sniper_slots} slots of the mint's first transaction. The creator is excluded (counted as an insider).`,
+ doc: DOC_BASE + '#sniper_pct',
+ },
+ bundler_pct: {
+ label: 'Bundler exposure',
+ unit: 'percent of supply',
+ definition: `Share of supply held by wallets in a funding cluster (two or more holders funded by one non-service source within ${DD_THRESHOLDS.funding_window_hours}h, directly or through a shared second hop) or in a launch slot where ${DD_THRESHOLDS.same_slot_min_group} or more holders first received the token.`,
+ doc: DOC_BASE + '#bundler_pct',
+ },
+ fresh_wallet_pct: {
+ label: 'Fresh-wallet share',
+ unit: 'percent of supply',
+ definition: `Share of supply held by wallets whose first-ever transaction was under ${DD_THRESHOLDS.fresh_wallet_max_age_hours}h before they first received the token.`,
+ doc: DOC_BASE + '#fresh_wallet_pct',
+ },
+ fresh_wallet_ratio: {
+ label: 'Fresh-wallet ratio',
+ unit: 'fraction of analysed wallet holders (0 to 1)',
+ definition: 'Fresh wallets divided by analysed wallet holders. Pools and other program-owned holders are not wallets and are excluded from both sides.',
+ doc: DOC_BASE + '#fresh_wallet_ratio',
+ },
+ smart_money_holders: {
+ label: 'Smart-money holders',
+ unit: 'wallet count',
+ definition: `Analysed holders whose own realized history in our tracked data (wallet_reputation.smart_money_score) is at least ${DD_THRESHOLDS.smart_money_min_score}. No third-party labels are used.`,
+ doc: DOC_BASE + '#smart_money_holders',
+ },
+ smart_money_pct: {
+ label: 'Smart-money share',
+ unit: 'percent of supply',
+ definition: 'Share of supply held by the smart-money holders above.',
+ doc: DOC_BASE + '#smart_money_pct',
+ },
+});
+
+const round2 = (n) => Math.round(n * 100) / 100;
+const HOUR_S = 3600;
+const SYSTEM_PROGRAM = '11111111111111111111111111111111';
+
+/** True when an address is an off-curve PDA (a pool, vault or program account), not a user wallet. */
+export function isProgramDerived(address) {
+ try {
+ return !PublicKey.isOnCurve(new PublicKey(address).toBytes());
+ } catch {
+ return false;
+ }
+}
+
+// ── pure computation ─────────────────────────────────────────────────────────
+
+/**
+ * Cluster wallet holders that share a funding source.
+ * Union-find over (a) the same hop-1 funder and (b) the same hop-2 funder, each
+ * only when the members were funded within the window and the shared source is
+ * not a high-volume service. Returns Map(owner -> clusterId|null) and the list.
+ *
+ * @param {Array<{owner:string, funder:string|null, funder_at:number|null, funder2:string|null, funder2_at:number|null}>} wallets
+ * @param {Set<string>} services funders classified as services
+ */
+export function clusterHolders(wallets, services = new Set(), thresholds = DD_THRESHOLDS) {
+ const parent = new Map(wallets.map((w) => [w.owner, w.owner]));
+ const find = (x) => {
+ while (parent.get(x) !== x) {
+ parent.set(x, parent.get(parent.get(x)));
+ x = parent.get(x);
+ }
+ return x;
+ };
+ const union = (a, b) => {
+ const ra = find(a);
+ const rb = find(b);
+ if (ra !== rb) parent.set(ra, rb);
+ };
+ const windowS = thresholds.funding_window_hours * HOUR_S;
+ const linkBy = (keyOf, atOf) => {
+ const groups = new Map();
+ for (const w of wallets) {
+ const key = keyOf(w);
+ if (!key || services.has(key)) continue;
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key).push(w);
+ }
+ for (const members of groups.values()) {
+ if (members.length < 2) continue;
+ const sorted = [...members].sort((a, b) => (atOf(a) ?? 0) - (atOf(b) ?? 0));
+ for (let i = 1; i < sorted.length; i++) {
+ const prev = atOf(sorted[i - 1]);
+ const cur = atOf(sorted[i]);
+ // Unknown funding times cannot be placed in a window; the shared source
+ // alone still links them when both are unknown (same-source evidence).
+ if (prev == null || cur == null ? prev == null && cur == null : cur - prev <= windowS) union(sorted[i - 1].owner, sorted[i].owner);
+ }
+ }
+ };
+ linkBy((w) => w.funder, (w) => w.funder_at);
+ linkBy((w) => w.funder2, (w) => w.funder2_at);
+
+ const bySize = new Map();
+ for (const w of wallets) {
+ const root = find(w.owner);
+ if (!bySize.has(root)) bySize.set(root, []);
+ bySize.get(root).push(w.owner);
+ }
+ const clusters = [];
+ const clusterOf = new Map(wallets.map((w) => [w.owner, null]));
+ for (const members of bySize.values()) {
+ if (members.length < thresholds.bundler_min_group) continue;
+ const id = clusters.length + 1;
+ clusters.push({ id, wallets: members });
+ for (const m of members) clusterOf.set(m, id);
+ }
+ return { clusterOf, clusters };
+}
+
+/**
+ * Compute the due-diligence fields from collected chain facts. Pure.
+ *
+ * @param {object} d
+ * @param {string} d.mint
+ * @param {string|null} d.supplyRaw
+ * @param {number|null} d.decimals
+ * @param {{slot:number|null, time:number|null, creator:string|null, creator_funder:string|null, creator_funder_at?:number|null}} d.launch
+ * @param {Array<{owner:string, token_account:string, amount:string, first_slot:number|null, first_time:number|null,
+ * program_derived:boolean, profile:null|{first_time:number|null, history_complete:boolean, funder:string|null,
+ * funder_at:number|null, funder2:string|null, funder2_at:number|null}}>} d.holders
+ * @param {Set<string>} [d.services]
+ * @param {Map<string,{smart_money_score:number,label:string|null}>} [d.smart] owner -> reputation
+ * @param {boolean} d.smartAvailable whether the reputation lookup ran
+ */
+export function computeDueDiligence(d, thresholds = DD_THRESHOLDS) {
+ const readErrors = d.readErrors ?? 0;
+ const services = d.services || new Set();
+ const launchSlot = d.launch?.slot ?? null;
+ const creator = d.launch?.creator ?? null;
+ const pct = (raw) => pctOfSupply(raw, d.supplyRaw) ?? 0;
+
+ const rows = d.holders.map((h) => ({
+ owner: h.owner,
+ token_account: h.token_account,
+ pct: pct(h.amount),
+ kind: h.program_derived ? 'program' : 'wallet',
+ first_slot: h.first_slot,
+ first_time: h.first_time,
+ funder: h.profile?.funder ?? null,
+ funder_at: h.profile?.funder_at ?? null,
+ funder2: h.profile?.funder2 ?? null,
+ funder2_at: h.profile?.funder2_at ?? null,
+ profile: h.profile,
+ flags: [],
+ }));
+ const wallets = rows.filter((r) => r.kind === 'wallet');
+
+ // ── clusters (bundlers) ────────────────────────────────────────────────
+ const { clusterOf, clusters } = clusterHolders(wallets, services, thresholds);
+ const slotGroups = new Map();
+ for (const w of wallets) {
+ if (w.first_slot == null) continue;
+ if (!slotGroups.has(w.first_slot)) slotGroups.set(w.first_slot, []);
+ slotGroups.get(w.first_slot).push(w.owner);
+ }
+ const sameSlot = new Set();
+ for (const owners of slotGroups.values()) if (owners.length >= thresholds.same_slot_min_group) owners.forEach((o) => sameSlot.add(o));
+
+ // ── insiders (creator-linked) ──────────────────────────────────────────
+ const creatorFunder = d.launch?.creator_funder ?? null;
+ const creatorCluster = creator ? clusterOf.get(creator) ?? null : null;
+ const linkedToCreator = (w) => {
+ if (!creator) return false;
+ if (w.owner === creator) return true;
+ if (w.funder === creator || w.funder2 === creator) return true;
+ if (creatorFunder && !services.has(creatorFunder) && (w.owner === creatorFunder || w.funder === creatorFunder || w.funder2 === creatorFunder)) return true;
+ return creatorCluster != null && clusterOf.get(w.owner) === creatorCluster;
+ };
+
+ // ── fresh wallets ──────────────────────────────────────────────────────
+ const freshS = thresholds.fresh_wallet_max_age_hours * HOUR_S;
+ const freshState = (w) => {
+ const p = w.profile;
+ if (!p || p.first_time == null) return null;
+ const at = w.first_time ?? null;
+ if (at == null) return null;
+ // An incomplete history means the true first transaction is older than the
+ // oldest one seen, so the age we can prove is a lower bound.
+ const age = at - p.first_time;
+ if (age < freshS) return p.history_complete ? true : null;
+ return false;
+ };
+
+ let unresolvedSniper = 0;
+ for (const w of wallets) {
+ if (creator && w.owner === creator) w.flags.push('creator');
+ if (linkedToCreator(w) && w.owner !== creator) w.flags.push('insider');
+ if (launchSlot != null && w.first_slot != null && w.owner !== creator) {
+ const delta = w.first_slot - launchSlot;
+ if (delta >= 0 && delta <= thresholds.sniper_slots) w.flags.push('sniper');
+ } else if (launchSlot != null && w.first_slot == null && w.owner !== creator) {
+ unresolvedSniper++;
+ }
+ if (clusterOf.get(w.owner) != null || sameSlot.has(w.owner)) w.flags.push('bundler');
+ const fresh = freshState(w);
+ if (fresh === true) w.flags.push('fresh');
+ w.fresh = fresh;
+ w.cluster = clusterOf.get(w.owner) ?? null;
+ }
+ for (const r of rows) if (r.kind === 'program') r.flags.push('program');
+
+ const sumPct = (pred) => round2(wallets.filter(pred).reduce((s, w) => s + w.pct, 0));
+ const has = (flag) => (w) => w.flags.includes(flag) || (flag === 'insider' && w.flags.includes('creator'));
+
+ // Smart money
+ const smart = d.smart || new Map();
+ for (const w of wallets) {
+ const rep = smart.get(w.owner);
+ if (rep && rep.smart_money_score >= thresholds.smart_money_min_score) {
+ w.flags.push('smart_money');
+ w.smart_money_score = rep.smart_money_score;
+ w.label = rep.label ?? null;
+ }
+ }
+
+ const profiled = wallets.filter((w) => w.profile).length;
+ const freshKnown = wallets.filter((w) => w.fresh !== null);
+ const slotKnown = wallets.filter((w) => w.first_slot != null).length;
+ const launchKnown = launchSlot != null;
+ // Evidence floor: a share computed from a handful of readable wallets out of
+ // many would print a confident-looking number that is really "unknown".
+ const enough = (n) => wallets.length > 0 && n / wallets.length >= thresholds.min_evidence_ratio;
+ const sniperOk = launchKnown && enough(slotKnown);
+ const linkOk = enough(profiled);
+ const freshOk = enough(freshKnown.length);
+
+ const fields = {
+ insider_pct: creator && linkOk ? sumPct(has('insider')) : null,
+ sniper_pct: sniperOk ? sumPct(has('sniper')) : null,
+ bundler_pct: linkOk || (enough(slotKnown) && slotGroups.size > 0) ? sumPct(has('bundler')) : null,
+ fresh_wallet_pct: freshOk ? sumPct(has('fresh')) : null,
+ fresh_wallet_ratio: freshOk ? round2(freshKnown.filter((w) => w.fresh === true).length / freshKnown.length) : null,
+ smart_money_holders: d.smartAvailable ? wallets.filter(has('smart_money')).length : null,
+ smart_money_pct: d.smartAvailable ? sumPct(has('smart_money')) : null,
+ };
+
+ const notes = [];
+ if (!creator) notes.push('creator not resolved: insider hold rate is withheld.');
+ if (!launchKnown) notes.push('launch slot not resolved (mint history exceeds the scan window): sniper share is withheld.');
+ const floorPct = Math.round(thresholds.min_evidence_ratio * 100);
+ if (wallets.length && !sniperOk && launchKnown) notes.push(`sniper share withheld: only ${slotKnown} of ${wallets.length} wallet holders had a readable first receipt (floor ${floorPct}%).`);
+ if (wallets.length && !linkOk) notes.push(`insider and bundler fields withheld: only ${profiled} of ${wallets.length} wallet holders had a readable funding history (floor ${floorPct}%).`);
+ if (wallets.length && !freshOk) notes.push(`fresh-wallet fields withheld: only ${freshKnown.length} of ${wallets.length} wallet holders could be aged (floor ${floorPct}%).`);
+ if (unresolvedSniper > 0 && sniperOk) notes.push(`${unresolvedSniper} holder${unresolvedSniper === 1 ? '' : 's'} had token-account history beyond the scan window and are not counted as snipers.`);
+ if (readErrors > 0) notes.push(`${readErrors} chain read${readErrors === 1 ? '' : 's'} failed after retries; the affected holders are reported as unknown, not as clean.`);
+ if (!d.smartAvailable) notes.push('smart-money lookup unavailable: smart-money fields are withheld.');
+ if (freshOk && freshKnown.length < wallets.length) notes.push(`${wallets.length - freshKnown.length} wallet${wallets.length - freshKnown.length === 1 ? '' : 's'} could not be aged and are excluded from the fresh-wallet fields.`);
+
+ return {
+ fields,
+ holders: rows.map(({ profile, funder_at, funder2_at, ...r }) => r),
+ clusters,
+ coverage: {
+ holders_analyzed: rows.length,
+ wallet_holders: wallets.length,
+ wallets_profiled: profiled,
+ launch_resolved: launchKnown,
+ creator_resolved: Boolean(creator),
+ analyzed_pct: round2(rows.reduce((s, r) => s + r.pct, 0)),
+ read_errors: readErrors,
+ },
+ notes,
+ };
+}
+
+/**
+ * Funding graph: holders, their funders (hop 1) and those funders' funders
+ * (hop 2) as nodes and edges. Pure. Nodes carry what the renderer sizes and
+ * colors by; edges point source (funder) -> target (funded).
+ *
+ * @param {{ holders: Array<object>, clusters: Array<object> }} dd result of computeDueDiligence
+ * @param {{ creator?: string|null, profiles?: Map<string, object>, services?: Set<string> }} ctx
+ */
+export function buildFundingGraph(dd, ctx = {}) {
+ const nodes = new Map();
+ const edges = [];
+ const services = ctx.services || new Set();
+ const creator = ctx.creator || null;
+ const node = (id, patch) => {
+ const cur = nodes.get(id) || { id, kind: 'source', hop: 2, pct: 0, flags: [], service: services.has(id) };
+ const next = { ...cur, ...patch, flags: [...new Set([...(cur.flags || []), ...(patch.flags || [])])] };
+ if (patch.hop != null) next.hop = Math.min(cur.hop ?? 9, patch.hop);
+ nodes.set(id, next);
+ };
+ const edge = (source, target, hop, lamports) => {
+ if (!source || !target || source === target) return;
+ if (!edges.some((e) => e.source === source && e.target === target)) edges.push({ source, target, hop, lamports: lamports ?? null });
+ };
+ for (const h of dd.holders) {
+ node(h.owner, { kind: h.kind === 'program' ? 'program' : 'holder', hop: 0, pct: h.pct, flags: h.flags, cluster: h.cluster ?? null });
+ if (h.funder) {
+ node(h.funder, { kind: 'funder', hop: 1 });
+ edge(h.funder, h.owner, 1);
+ if (h.funder2) {
+ node(h.funder2, { kind: 'source', hop: 2 });
+ edge(h.funder2, h.funder, 2);
+ }
+ }
+ }
+ if (creator && !nodes.has(creator)) node(creator, { kind: 'holder', hop: 0, flags: ['creator'] });
+ const sorted = [...nodes.values()];
+ return { nodes: sorted, edges, clusters: dd.clusters?.length ?? 0 };
+}
+
+// ── chain IO ─────────────────────────────────────────────────────────────────
+
+const SIG_PAGE = 1000;
+const MAX_SIG_PAGES = 6;
+const RPC_TIMEOUT_MS = 20_000;
+
+// Keyless lanes that answer getSignaturesForAddress from a pruned window (a few
+// hundred recent signatures) or an empty list for an address that has history.
+// A truncated history reads as a complete one and would put a late "first
+// transaction" into the report as fact, so signature and transaction reads
+// skip them. Keyed archival lanes lead the chain in production; the public
+// cluster is the keyless fallback that serves full history.
+const PRUNED_HISTORY_HOSTS = /publicnode\.com|solanavibestation\.com|tatum\.(io|com)/;
+
+export function realChainDeps() {
+ const all = solanaRpcEndpoints('mainnet');
+ const rpcFetch = makeRotatingFetch(all);
+ const archival = all.filter((u) => !PRUNED_HISTORY_HOSTS.test(u));
+ const historyFetch = makeRotatingFetch(archival.length ? archival : all);
+ const call = (fetcher) => async (method, params) => {
+ let lastErr;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) await new Promise((r) => setTimeout(r, 350 * attempt));
+ try {
+ const resp = await fetcher(null, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
+ });
+ const body = await resp.json();
+ if (body?.error) throw new Error(`rpc ${method}: ${body.error.message || body.error.code}`);
+ return body?.result ?? null;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr;
+ };
+ return {
+ // Retried: the keyless lanes throttle bursts, and a single 429 must not turn
+ // a wallet into "unknown" when the next attempt would have answered.
+ rpc: call(rpcFetch),
+ history: call(historyFetch),
+ now: () => Math.floor(Date.now() / 1000),
+ };
+}
+
+// Every address this module looks up (a mint, a token account holding a
+// balance, a wallet that holds or sent funds) has history. Some keyless lanes
+// answer a lagging or pruned empty list instead of an error, so an empty FIRST
+// page is retried before it is believed.
+async function signaturePage(rpc, address, before) {
+ const params = [address, { limit: SIG_PAGE, commitment: 'confirmed', ...(before ? { before } : {}) }];
+ for (let attempt = 0; attempt < 4; attempt++) {
+ if (attempt) await new Promise((r) => setTimeout(r, 400 * attempt));
+ const sigs = await rpc('getSignaturesForAddress', params);
+ if (Array.isArray(sigs) && (sigs.length || before)) return sigs;
+ }
+ return [];
+}
+
+/**
+ * Oldest signature of an address, paging back at most MAX_SIG_PAGES pages.
+ * `complete` is true only when the true oldest was reached.
+ *
+ * With `minSlot`, signatures older than that slot are ignored: a token account
+ * cannot receive a mint's tokens before the mint exists, and an address can be
+ * pre-funded with SOL by anyone, so earlier signatures are not acquisitions.
+ * Paging stops as soon as the window is passed, which also bounds the work for
+ * accounts with a long prior history.
+ *
+ * @returns {Promise<null | { oldest: object, count: number, complete: boolean }>}
+ */
+export async function oldestSignature(address, rpc, { minSlot = null } = {}) {
+ let before;
+ let count = 0;
+ let oldest = null;
+ for (let page = 0; page < MAX_SIG_PAGES; page++) {
+ const sigs = await signaturePage(rpc, address, before);
+ if (!sigs.length) return oldest ? { oldest, count, complete: true } : null;
+ const inWindow = minSlot == null ? sigs : sigs.filter((x) => x.slot >= minSlot);
+ if (inWindow.length) {
+ count += inWindow.length;
+ oldest = inWindow[inWindow.length - 1];
+ }
+ if (inWindow.length < sigs.length || sigs.length < SIG_PAGE) return oldest ? { oldest, count, complete: true } : null;
+ before = sigs[sigs.length - 1].signature;
+ }
+ return { oldest, count, complete: false };
+}
+
+const TX_OPTS = { encoding: 'jsonParsed', maxSupportedTransactionVersion: 1, commitment: 'confirmed' };
+
+/**
+ * A wallet's age and its direct funder, from its first transaction.
+ * @returns {Promise<{ first_time:number|null, first_slot:number|null, history_complete:boolean, sig_count:number,
+ * funder:string|null, funder_at:number|null, funded_lamports:number|null }>}
+ */
+export async function walletProfile(address, rpc) {
+ const o = await oldestSignature(address, rpc);
+ if (!o) return { first_time: null, first_slot: null, history_complete: true, sig_count: 0, funder: null, funder_at: null, funded_lamports: null };
+ const base = {
+ first_time: o.oldest.blockTime ?? null,
+ first_slot: o.oldest.slot ?? null,
+ history_complete: o.complete,
+ sig_count: o.count,
+ funder: null,
+ funder_at: null,
+ funded_lamports: null,
+ };
+ // Funder is only defined when the first transaction is the one that funded it.
+ if (!o.complete) return base;
+ const tx = await rpc('getTransaction', [o.oldest.signature, TX_OPTS]);
+ const parsed = parseFunderFromTransaction(tx, address);
+ return { ...base, funder: parsed?.funder ?? null, funder_at: parsed ? base.first_time : null, funded_lamports: parsed?.lamports ?? null };
+}
+
+const profileMemo = new Map();
+async function cachedProfile(address, rpc) {
+ const hit = profileMemo.get(address);
+ if (hit && Date.now() - hit.at < FUNDING_TTL_SECONDS * 1000) return hit.value;
+ const value = await walletProfile(address, rpc);
+ profileMemo.set(address, { value, at: Date.now() });
+ if (profileMemo.size > 5000) profileMemo.delete(profileMemo.keys().next().value);
+ return value;
+}
+
+const METADATA_PROGRAM = 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s';
+
+/**
+ * Launch slot and creator. A pump.fun mint appears in every trade, so its own
+ * signature history is far too long to page to the start. Its Metaplex metadata
+ * account is written at creation and almost never touched again, so that
+ * account's oldest transaction IS the launch, and its fee payer is the creator.
+ * A mint with no metadata history falls back to its own history.
+ */
+async function resolveLaunch(mint, history) {
+ const pda = PublicKey.findProgramAddressSync(
+ [Buffer.from('metadata'), new PublicKey(METADATA_PROGRAM).toBuffer(), new PublicKey(mint).toBuffer()],
+ new PublicKey(METADATA_PROGRAM),
+ )[0].toBase58();
+ let o = await oldestSignature(pda, history);
+ if (!o || !o.complete) o = await oldestSignature(mint, history);
+ if (!o || !o.complete) return { slot: null, time: null, creator: null };
+ const tx = await history('getTransaction', [o.oldest.signature, TX_OPTS]);
+ const keys = tx?.transaction?.message?.accountKeys || [];
+ const payer = typeof keys[0] === 'string' ? keys[0] : keys[0]?.pubkey;
+ return { slot: o.oldest.slot ?? null, time: o.oldest.blockTime ?? null, creator: payer || null };
+}
+
+async function largestHolders(mint, rpc, analyzeTop) {
+ const largest = await rpc('getTokenLargestAccounts', [mint, { commitment: 'confirmed' }]);
+ const value = largest?.value;
+ if (!Array.isArray(value)) throw new Error('getTokenLargestAccounts returned no accounts');
+ const top = value.filter((a) => Number(a.amount) > 0).slice(0, analyzeTop);
+ const accounts = top.length ? await rpc('getMultipleAccounts', [top.map((a) => a.address), { encoding: 'jsonParsed', commitment: 'confirmed' }]) : { value: [] };
+ return top.map((a, i) => ({
+ token_account: a.address,
+ amount: a.amount,
+ owner: accounts?.value?.[i]?.data?.parsed?.info?.owner || null,
+ })).filter((h) => h.owner);
+}
+
+/**
+ * Read everything the computation needs from chain. Each per-holder read is
+ * isolated: one failing wallet degrades that wallet, never the whole report.
+ */
+export async function collectChainData(mint, deps = realChainDeps(), thresholds = DD_THRESHOLDS) {
+ const { rpc } = deps;
+ const history = deps.history || rpc;
+ const mintInfo = parseMintAccount(await rpc('getAccountInfo', [mint, { encoding: 'jsonParsed', commitment: 'confirmed' }]));
+ if (!mintInfo) return { status: 'not_found' };
+
+ let readErrors = 0;
+ const launch = await resolveLaunch(mint, history).catch(() => {
+ readErrors++;
+ return { slot: null, time: null, creator: null };
+ });
+ const top = await largestHolders(mint, rpc, thresholds.analyze_top);
+
+ // Per holder: first receipt of the token (token-account history) and, for
+ // real wallets, the owner's age + funder.
+ const holderRows = await mapPoolSettled(top, 3, async (h) => {
+ const programDerived = isProgramDerived(h.owner);
+ const [acq, profile] = await Promise.all([
+ oldestSignature(h.token_account, history, { minSlot: launch.slot }).catch(() => {
+ readErrors++;
+ return null;
+ }),
+ programDerived
+ ? null
+ : cachedProfile(h.owner, history).catch(() => {
+ readErrors++;
+ return null;
+ }),
+ ]);
+ return {
+ owner: h.owner,
+ token_account: h.token_account,
+ amount: h.amount,
+ program_derived: programDerived,
+ first_slot: acq?.complete ? acq.oldest.slot ?? null : null,
+ first_time: acq?.complete ? acq.oldest.blockTime ?? null : null,
+ profile,
+ };
+ });
+ const holders = holderRows.filter((r) => r.ok).map((r) => r.value);
+
+ // Hop 2: who funded the funders. The creator joins the lookup so insider links resolve.
+ const creator = launch.creator;
+ const creatorProfile = creator ? holders.find((h) => h.owner === creator)?.profile ?? (await cachedProfile(creator, history).catch(() => null)) : null;
+ const funderSet = new Set(holders.map((h) => h.profile?.funder).filter(Boolean));
+ if (creatorProfile?.funder) funderSet.add(creatorProfile.funder);
+ const funderProfiles = new Map();
+ const funderRows = await mapPoolSettled([...funderSet].slice(0, 24), 3, async (f) => [f, await cachedProfile(f, history)]);
+ for (const r of funderRows) {
+ if (r.ok) funderProfiles.set(r.value[0], r.value[1]);
+ else readErrors++;
+ }
+
+ const services = new Set();
+ for (const [f, p] of funderProfiles) if (!p.history_complete || p.sig_count >= thresholds.service_funder_min_sigs) services.add(f);
+ for (const h of holders) {
+ if (!h.profile) continue;
+ const fp = h.profile.funder ? funderProfiles.get(h.profile.funder) : null;
+ h.profile = { ...h.profile, funder2: fp?.funder ?? null, funder2_at: fp?.funder_at ?? null };
+ }
+
+ return {
+ status: 'ok',
+ mint,
+ supplyRaw: mintInfo.supply,
+ decimals: mintInfo.decimals,
+ mint_authority_revoked: mintInfo.mint_authority.revoked,
+ freeze_authority_revoked: mintInfo.freeze_authority.revoked,
+ launch: { ...launch, creator_funder: creatorProfile?.funder ?? null },
+ holders,
+ services,
+ read_errors: readErrors,
+ now: deps.now(),
+ };
+}
+
+/**
+ * Own realized history: wallet_reputation rows (scored from the trades we track)
+ * at or above the smart-money bar. Lazy db import so the pure paths stay light.
+ */
+export async function reputationLookup(owners, minScore = DD_THRESHOLDS.smart_money_min_score) {
+ if (!owners.length) return [];
+ const { sql } = await import('./db.js');
+ return sql`
+ select wallet, smart_money_score, label
+ from wallet_reputation
+ where network = 'mainnet' and wallet = any(${owners}) and smart_money_score >= ${minScore}
+ `;
+}
+
+async function lookupSmartMoney(owners, lookup) {
+ try {
+ const rows = await lookup(owners);
+ const map = new Map();
+ for (const r of rows || []) map.set(r.wallet, { smart_money_score: Number(r.smart_money_score), label: r.label ?? null });
+ return { available: true, map };
+ } catch (err) {
+ console.warn('[token-dd] smart-money lookup failed:', err?.message);
+ return { available: false, map: new Map() };
+ }
+}
+
+/**
+ * Compute and return the due-diligence report for a mint (cached per mint).
+ *
+ * @param {string} mint
+ * @param {{ deps?: object, smartLookup?: Function, force?: boolean }} [opts]
+ * @returns {Promise<{status:'ok', ...}|{status:'not_found'}|{status:'upstream_down'}>}
+ */
+export async function getTokenDueDiligence(mint, { deps, smartLookup, force = false } = {}) {
+ const compute = async () => {
+ let raw;
+ try {
+ raw = await collectChainData(mint, deps);
+ } catch (err) {
+ console.warn('[token-dd] chain read failed:', err?.message);
+ return { status: 'upstream_down' };
+ }
+ if (raw.status !== 'ok') return raw;
+ const owners = raw.holders.filter((h) => !h.program_derived).map((h) => h.owner);
+ const lookup = smartLookup || reputationLookup;
+ const smart = await lookupSmartMoney(owners, lookup);
+ const dd = computeDueDiligence({ ...raw, readErrors: raw.read_errors, smart: smart.map, smartAvailable: smart.available });
+ return {
+ status: 'ok',
+ mint,
+ computed_at: new Date(raw.now * 1000).toISOString(),
+ ttl_seconds: DD_TTL_SECONDS,
+ supply_raw: raw.supplyRaw,
+ decimals: raw.decimals,
+ creator: raw.launch.creator,
+ launch_slot: raw.launch.slot,
+ mint_authority_revoked: raw.mint_authority_revoked,
+ freeze_authority_revoked: raw.freeze_authority_revoked,
+ ...dd,
+ graph: buildFundingGraph(dd, { creator: raw.launch.creator, services: raw.services }),
+ thresholds: DD_THRESHOLDS,
+ definitions: DD_DEFINITIONS,
+ };
+ };
+ if (force) return compute();
+ // Only successful reads are cached: cacheWrap stores every non-null value,
+ // so an outage verdict must not be pinned for the TTL.
+ const key = `token-dd:v1:${mint}`;
+ const cached = await cacheWrap(key, DD_TTL_SECONDS, async () => {
+ const out = await compute();
+ return out.status === 'ok' ? out : { __transient: out };
+ });
+ return cached?.__transient ?? cached;
+}
+
+/**
+ * Two-hop funding trace for one wallet: the wallet (hop 0), who funded it
+ * (hop 1) and who funded that (hop 2), as nodes and edges ready to render.
+ * A funder whose history is too long to reach its first transaction is a
+ * service (exchange, router): the trace stops there and says so.
+ */
+export async function traceFundingGraph(wallet, { deps = realChainDeps(), hops = 2 } = {}) {
+ const history = deps.history || deps.rpc;
+ const nodes = [];
+ const edges = [];
+ const seen = new Set();
+ let current = wallet;
+ let truncated = false;
+ for (let hop = 0; current && !seen.has(current); hop++) {
+ seen.add(current);
+ const node = { id: current, hop, kind: hop === 0 ? 'wallet' : 'funder', first_time: null, history_complete: null, service: false };
+ nodes.push(node);
+ if (hop >= hops) break;
+ const p = await cachedProfile(current, history);
+ node.first_time = p.first_time;
+ node.history_complete = p.history_complete;
+ if (!p.history_complete) {
+ node.service = true;
+ truncated = true;
+ break;
+ }
+ if (!p.funder) break;
+ edges.push({ source: p.funder, target: current, hop: hop + 1, lamports: p.funded_lamports, at: p.funder_at });
+ current = p.funder;
+ }
+ return { wallet, hops, nodes, edges, truncated };
+}
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
index b114471e8..2e0e1664e 100644
--- a/api/_mcp/catalog.js
+++ b/api/_mcp/catalog.js
@@ -32,6 +32,7 @@ import { toolDefs as mailDefs } from './tools/mail.js';
import { toolDefs as whitelistDefs } from './tools/whitelist.js';
import { toolDefs as domainDefs } from './tools/domains.js';
import { toolDefs as robinhoodDefs } from './tools/robinhood.js';
+import { toolDefs as tokenDueDiligenceDefs } from './tools/token-due-diligence.js';
const baseDefs = [
...libraryDefs,
@@ -63,6 +64,7 @@ const baseDefs = [
...whitelistDefs,
...domainDefs,
...robinhoodDefs,
+ ...tokenDueDiligenceDefs,
];
// Free, public entry point — listed first so discovery clients see it up top.
diff --git a/api/_mcp/tools/token-due-diligence.js b/api/_mcp/tools/token-due-diligence.js
new file mode 100644
index 000000000..47aa7e577
--- /dev/null
+++ b/api/_mcp/tools/token-due-diligence.js
@@ -0,0 +1,52 @@
+// token_due_diligence: holder-quality read for a Solana token mint. Insider hold
+// rate, sniper share, bundler exposure, fresh-wallet ratio and smart-money
+// holders as shares of supply, plus a two-hop funding graph, from the same
+// engine as GET /api/crypto/due-diligence (api/_lib/token-due-diligence.js).
+// Cached per mint for five minutes. Read-only; never signs or spends.
+
+import { getTokenDueDiligence } from '../../_lib/token-due-diligence.js';
+import { isValidSolanaAddress } from '../../_lib/validate.js';
+
+const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
+
+function fail(message, data) {
+ return { content: [{ type: 'text', text: message }], isError: true, structuredContent: data };
+}
+
+export const toolDefs = [
+ {
+ name: 'token_due_diligence',
+ title: 'Token due diligence',
+ annotations: READ,
+ description:
+ 'Who holds a Solana token, not just what its contract can do. Returns insider hold rate (creator-linked wallets), ' +
+ 'sniper share (bought within a few slots of launch), bundler exposure (holders funded by a common source), ' +
+ 'fresh-wallet ratio (wallets under 24h old when they bought) and smart-money holders (wallets whose realized ' +
+ 'history in three.ws tracked data clears the bar), each as a percent of total supply, plus the holder rows and a ' +
+ 'two-hop funding graph. A field is null when its chain reads failed; `coverage` and `notes` say why. Cached per ' +
+ 'mint for 5 minutes. Definitions and thresholds: docs/token-due-diligence.md. Example mint: the $THREE CA ' +
+ '"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump". Use this when you are about to size or approve a buy and need to know whether insiders, snipers or bundles control the supply. Pair with the agent trade limits (max_insider_pct and kin) to refuse a buy automatically.',
+ inputSchema: {
+ type: 'object',
+ required: ['mint'],
+ properties: {
+ mint: { type: 'string', description: 'Base58 Solana token mint address.' },
+ },
+ additionalProperties: false,
+ },
+ async handler(args) {
+ const mint = String(args?.mint || '').trim();
+ if (!isValidSolanaAddress(mint)) {
+ return fail('mint must be a base58 Solana token mint address', { error: 'invalid_address', mint });
+ }
+ const report = await getTokenDueDiligence(mint);
+ if (report.status === 'not_found') {
+ return fail(`${mint} is not an on-chain token mint`, { error: 'token_not_found', mint });
+ }
+ if (report.status !== 'ok') {
+ return fail('chain data sources are temporarily unreachable, retry shortly', { error: 'upstream_unavailable', mint, retry_after: 15 });
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }], structuredContent: report };
+ },
+ },
+];
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 98e603b8e..c1a528ecf 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -42,7 +42,7 @@ import {
getTradeLimits, setTradeLimits, getDailySpendLamports,
updateCustodyEvent,
checkKillSwitch, checkConcurrency, checkPerTradeCap, checkDailyBudgetLamports,
- checkSolHeadroom, checkPriceImpact, tradeGuardResponse,
+ checkSolHeadroom, checkPriceImpact, guardDueDiligence, tradeGuardResponse,
SOL_FEE_HEADROOM_LAMPORTS, TRADE_LIMIT_DEFAULTS,
} from '../_lib/agent-trade-guards.js';
import { createApprovalRequest, approvalPath, publicApproval } from '../_lib/approvals.js';
@@ -261,6 +261,10 @@ async function runGuards({ id, side, tradeLimits, prep, walletLamports, network,
if (impact) return tradeGuardResponse(impact);
if (side === 'buy') {
+ if (mintPk && network === 'mainnet') {
+ const dd = await guardDueDiligence(mintPk.toBase58(), tradeLimits);
+ if (dd) return tradeGuardResponse(dd);
+ }
const lamports = prep.lamports;
const capLamports = tradeLimits.per_trade_sol == null ? null : solToLamports(tradeLimits.per_trade_sol);
const cap = checkPerTradeCap(lamports, capLamports);
@@ -992,6 +996,10 @@ const LIMIT_RANGES = {
max_price_impact_pct: { min: 0, max: 100, label: 'max_price_impact_pct must be a number between 0 and 100' },
max_slippage_bps: { min: 0, max: 10000, label: 'max_slippage_bps must be a number between 0 and 10000' },
max_concurrent: { min: 1, max: 10000, label: 'max_concurrent must be a whole number of at least 1, or null for no ceiling' },
+ max_insider_pct: { min: 0, max: 100, label: 'max_insider_pct must be a number between 0 and 100, or null to clear the limit' },
+ max_sniper_pct: { min: 0, max: 100, label: 'max_sniper_pct must be a number between 0 and 100, or null to clear the limit' },
+ max_bundler_pct: { min: 0, max: 100, label: 'max_bundler_pct must be a number between 0 and 100, or null to clear the limit' },
+ max_fresh_wallet_pct: { min: 0, max: 100, label: 'max_fresh_wallet_pct must be a number between 0 and 100, or null to clear the limit' },
};
function validateLimitsPatch(patch) {
diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.js
index 10ed1bdc9..951ca3a34 100644
--- a/api/agents/solana-trade.js
+++ b/api/agents/solana-trade.js
@@ -35,7 +35,7 @@ import { explorerTxUrl } from '../_lib/avatar-wallet.js';
import {
enforceSpendLimit, SpendLimitError, getSpendLimits, updateCustodyEvent, lamportsToUsd,
getTradeLimits, getDailySpendLamports,
- checkKillSwitch, checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,
+ checkKillSwitch, checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact, guardDueDiligence, tradeGuardResponse,
SOL_FEE_HEADROOM_LAMPORTS,
} from '../_lib/agent-trade-guards.js';
import {
@@ -465,6 +465,16 @@ export async function runAgentTrade({ agentId, userId, meta, address, encryptedS
}
}
+ // Holder-quality breaker (insider / sniper / bundler / fresh-wallet share of
+ // supply). Buys only, mainnet only, and only when the owner set a limit.
+ if (!guardWarning && side === 'buy' && network === 'mainnet') {
+ const dd = await guardDueDiligence(mintStr, tradeLimits);
+ if (dd) {
+ const r = tradeGuardResponse(dd);
+ guardWarning = { status: r.status, code: r.code, message: r.message, detail: r.detail };
+ }
+ }
+
// Rug/honeypot firewall; a REAL on-chain simulated buy→sell round-trip +
// authority audit, gating BUYS only (a sell brings SOL inward, the safe
// direction). A 'block' verdict refuses the buy with a structured 422 the UI
diff --git a/api/crypto/due-diligence.js b/api/crypto/due-diligence.js
new file mode 100644
index 000000000..5ec56d6a3
--- /dev/null
+++ b/api/crypto/due-diligence.js
@@ -0,0 +1,68 @@
+// GET /api/crypto/due-diligence: who holds a Solana token and how those holders
+// relate. Insider hold rate, sniper share, bundler exposure, fresh-wallet ratio
+// and smart-money holders, each as a share of total supply, plus a two-hop
+// funding graph of the largest holders.
+//
+// Part of the free Crypto Data API (/api/crypto/*). Computed from chain data and
+// our own tracked wallet history (no third-party labels), cached per mint for
+// five minutes. Field definitions and thresholds: docs/token-due-diligence.md.
+//
+// Query:
+// address = <Solana mint> (required)
+//
+// Response: { address, chain, status, computed_at, ttl_seconds, fields, holders,
+// clusters, coverage, notes, graph, thresholds, definitions, ts }
+// A field is null (never a guess) when the data it needs could not be read;
+// `coverage` and `notes` say which reads failed.
+
+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 { getTokenDueDiligence } from '../_lib/token-due-diligence.js';
+
+const EXAMPLE = '/api/crypto/due-diligence?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, ddRl, globalRl] = await Promise.all([
+ limits.cryptoDataIp(ip),
+ limits.cryptoHoldersIp(ip),
+ limits.cryptoDataGlobal(),
+ ]);
+ if (!ipRl.success) return rateLimited(res, ipRl);
+ if (!ddRl.success) return rateLimited(res, ddRl);
+ if (!globalRl.success) return rateLimited(res, globalRl);
+
+ const url = new URL(req.url, 'http://localhost');
+ const address = (url.searchParams.get('address') || '').trim();
+ if (!address) {
+ return error(res, 400, 'missing_address', 'query param `address` is required. Pass a Solana token mint', { example: EXAMPLE });
+ }
+ if (isValidEvmAddress(address)) {
+ return error(res, 400, 'unsupported_chain', 'this endpoint reads Solana holders 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 report = await getTokenDueDiligence(address);
+ if (report.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 (report.status !== 'ok') {
+ return json(res, 503, {
+ error: 'upstream_unavailable',
+ error_description: 'chain data sources are temporarily unreachable, retry shortly',
+ address,
+ retry_after: 15,
+ ts: new Date().toISOString(),
+ }, { 'cache-control': 'no-store', 'retry-after': '15' });
+ }
+
+ return json(res, 200, { address, chain: 'solana', ...report, ts: new Date().toISOString() }, {
+ 'cache-control': 'public, s-maxage=60, stale-while-revalidate=120',
+ });
+});
diff --git a/api/crypto/funding-graph.js b/api/crypto/funding-graph.js
new file mode 100644
index 000000000..bab664ec0
--- /dev/null
+++ b/api/crypto/funding-graph.js
@@ -0,0 +1,57 @@
+// GET /api/crypto/funding-graph: who funded a Solana wallet, and who funded
+// them, two hops back. Nodes and edges ready to render as a force graph.
+//
+// Funder = the account that paid the wallet's first-ever SOL into existence, read
+// from its first transaction. A funder whose history is too long to reach (an
+// exchange, a router) is marked `service` and the trace stops there.
+//
+// Query:
+// wallet = <Solana wallet> (required)
+//
+// Response: { wallet, hops, nodes[{id,hop,kind,first_time,history_complete,service}],
+// edges[{source,target,hop,lamports,at}], truncated, ts }
+
+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 { traceFundingGraph } from '../_lib/token-due-diligence.js';
+
+const EXAMPLE = '/api/crypto/funding-graph?wallet=<solana wallet>';
+
+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, ddRl, globalRl] = await Promise.all([
+ limits.cryptoDataIp(ip),
+ limits.cryptoHoldersIp(ip),
+ limits.cryptoDataGlobal(),
+ ]);
+ if (!ipRl.success) return rateLimited(res, ipRl);
+ if (!ddRl.success) return rateLimited(res, ddRl);
+ if (!globalRl.success) return rateLimited(res, globalRl);
+
+ const url = new URL(req.url, 'http://localhost');
+ const wallet = (url.searchParams.get('wallet') || '').trim();
+ if (!wallet) return error(res, 400, 'missing_wallet', 'query param `wallet` is required. Pass a Solana wallet address', { example: EXAMPLE });
+ if (isValidEvmAddress(wallet)) return error(res, 400, 'unsupported_chain', 'this endpoint traces Solana wallets only', { example: EXAMPLE });
+ if (!isValidSolanaAddress(wallet)) return error(res, 400, 'invalid_address', '`wallet` must be a base58 Solana address (32-44 chars)', { wallet, example: EXAMPLE });
+
+ let graph;
+ try {
+ graph = await traceFundingGraph(wallet);
+ } catch (err) {
+ console.warn('[funding-graph] trace failed:', err?.message);
+ return json(res, 503, {
+ error: 'upstream_unavailable',
+ error_description: 'chain data sources are temporarily unreachable, retry shortly',
+ wallet,
+ retry_after: 15,
+ ts: new Date().toISOString(),
+ }, { 'cache-control': 'no-store', 'retry-after': '15' });
+ }
+ return json(res, 200, { ...graph, ts: new Date().toISOString() }, {
+ 'cache-control': 'public, s-maxage=300, stale-while-revalidate=600',
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 76a6fa302..0b48779bc 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-23",
+ "title": "Token due diligence: insiders, snipers, bundlers, fresh wallets and a funding graph",
+ "summary": "Every Solana token now has holder due diligence computed from chain data we read ourselves: insider hold rate, sniper share, bundler exposure, fresh-wallet share and ratio, and smart-money holders scored from our own tracked wallet history. The /three token page shows the fields, each linked to its definition, plus a two-hop funding force graph. Agents can set max_insider_pct, max_sniper_pct, max_bundler_pct and max_fresh_wallet_pct trade limits to refuse buys above them. Available as GET /api/crypto/due-diligence, GET /api/crypto/funding-graph and the token_due_diligence MCP tool, cached per mint for five minutes. A field with too little chain evidence is withheld instead of shown as a low number.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/docs/token-due-diligence"
+ },
{
"date": "2026-10-23",
"title": "Ratcheting exit orders with named reason codes",
diff --git a/data/pages.json b/data/pages.json
index 74158df33..3e7e59036 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -6065,6 +6065,13 @@
"priority": 0.6,
"changefreq": "monthly"
},
+ {
+ "path": "/docs/token-due-diligence",
+ "title": "Docs · Token due diligence",
+ "description": "How insider hold rate, sniper share, bundler exposure, fresh-wallet share and smart-money holders are computed from chain data, with every threshold and the trade guard limits.",
+ "priority": 0.6,
+ "changefreq": "monthly"
+ },
{
"path": "/docs/vroid-hub-import",
"title": "Docs · Import your VRoid Hub avatar",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 4dc1015c2..799238632 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -6623,6 +6623,25 @@ with serve-stale-on-error).
---
+## Token Due Diligence API
+
+Holder-quality fields for a Solana mint. Free, key-less, CORS `*`. Definitions
+and thresholds: [token due diligence](token-due-diligence.md).
+
+```
+GET /api/crypto/due-diligence?address=<mint>
+GET /api/crypto/funding-graph?wallet=<address>
+```
+
+`due-diligence` returns `{ status, mint, fields: { insider_pct, sniper_pct,
+bundler_pct, fresh_wallet_pct, fresh_wallet_ratio, smart_money_holders,
+smart_money_pct }, holders[], clusters[], coverage, notes[], graph,
+thresholds, definitions }`. A field is `null` with a "withheld" note when too
+few holders yielded evidence. Reports are cached per mint for 300 seconds.
+`funding-graph` returns the two-hop `{ nodes, edges }` for one wallet. The same
+report is the MCP tool `token_due_diligence` (`{ mint }`). Errors: `400` bad
+address, `429` rate limited, `503` chain reads unavailable.
+
## Crypto News API
The engine behind [/markets/news](https://three.ws/markets/news) and
diff --git a/docs/token-due-diligence.md b/docs/token-due-diligence.md
new file mode 100644
index 000000000..66861ffee
--- /dev/null
+++ b/docs/token-due-diligence.md
@@ -0,0 +1,82 @@
+# Token due diligence
+
+`token_due_diligence` scores a Solana token on who holds it, not only on its contract flags. Every field is computed from chain data we read ourselves (token accounts, signature history, funding transfers) plus our own tracked wallet history. No third-party labels are scraped.
+
+- API: `GET /api/crypto/due-diligence?address=<mint>` and `GET /api/crypto/funding-graph?wallet=<address>`
+- MCP tool: `token_due_diligence` (input `{ mint }`)
+- Token page: the "Holder due diligence" panel on `/three` renders the fields and the two-hop funding force graph
+- Cache: one report per mint for 300 seconds. Only successful reports are cached.
+
+## Method
+
+1. Find the launch: the oldest transaction of the mint's Metaplex metadata account (falling back to the mint's own history). Its slot is the launch slot and its fee payer is the creator.
+2. Read the largest token accounts (up to `analyze_top`) and resolve each to its owner. Program-owned holders (pools, vaults) are not wallets and are excluded from wallet ratios.
+3. For each wallet holder read its first receipt of the token, its first-ever transaction, and who funded it, up to two hops back.
+4. Classify holders and aggregate by share of supply.
+
+## Thresholds
+
+Every threshold lives in `DD_THRESHOLDS` in `api/_lib/token-due-diligence.js` and is returned in each report.
+
+| Key | Value | Meaning |
+|---|---|---|
+| `analyze_top` | 20 | Largest token accounts analysed per mint (the chain returns at most 20). |
+| `sniper_slots` | 5 | A holder is a sniper when its first receipt landed within this many slots of launch. |
+| `bundler_min_group` | 2 | Holders sharing a funder form a bundle from this group size up. |
+| `same_slot_min_group` | 3 | Same-launch-slot grouping needs this many holders, because organic buyers share busy slots. |
+| `funding_window_hours` | 6 | Wallets funded by one source within this window of each other form a cluster. |
+| `fresh_wallet_max_age_hours` | 24 | A wallet is fresh when its first-ever transaction is younger than this at first receipt. |
+| `smart_money_min_score` | 65 | `wallet_reputation.smart_money_score` at or above this bar. |
+| `service_funder_min_sigs` | 2000 | A funder with this many signatures (or an incomplete history) is a service such as an exchange or router, not a coordinator, and never links holders. |
+| `min_evidence_ratio` | 0.5 | A field is reported only when this share of analysed wallet holders yielded the evidence it needs. Below it the field is `null` with a "withheld" note, never a low number. |
+
+## Definitions
+
+### insider_pct
+
+Insider hold rate. Percent of supply held by the creator wallet and by holders linked to it: funded by the creator, funding the creator, or funded from the same non-service source within two hops.
+
+### sniper_pct
+
+Sniper share. Percent of supply held by wallets whose first receipt of the token landed within `sniper_slots` slots of the mint's first transaction. The creator is excluded (counted as an insider).
+
+### bundler_pct
+
+Bundler exposure. Percent of supply held by wallets in a funding cluster (two or more holders funded by one non-service source within `funding_window_hours`, directly or through a shared second hop) or in a launch slot where `same_slot_min_group` or more holders first received the token.
+
+### fresh_wallet_pct
+
+Fresh-wallet share. Percent of supply held by wallets whose first-ever transaction was under `fresh_wallet_max_age_hours` before they first received the token.
+
+### fresh_wallet_ratio
+
+Fresh wallets divided by analysed wallet holders (0 to 1). Pools and other program-owned holders are excluded from both sides.
+
+### smart_money_holders
+
+Count of analysed holders whose own realized history in our tracked data (`wallet_reputation.smart_money_score`) is at least `smart_money_min_score`.
+
+### smart_money_pct
+
+Percent of supply held by the smart-money holders above.
+
+## Funding graph
+
+`traceFundingGraph(wallet)` follows who funded a wallet's first transaction, then who funded that funder, two hops in total, and returns `nodes` and `edges`. The token page renders it as a force graph with the creator, flagged holders and service funders distinguished in the legend.
+
+## Guards
+
+Four per-agent trade limits refuse a buy when the report exceeds them. All default to off (`null`).
+
+| Limit | Refuses a buy when |
+|---|---|
+| `max_insider_pct` | `insider_pct` is above the limit |
+| `max_sniper_pct` | `sniper_pct` is above the limit |
+| `max_bundler_pct` | `bundler_pct` is above the limit |
+| `max_fresh_wallet_pct` | `fresh_wallet_pct` is above the limit |
+
+Set them through the agent trade limits endpoint. The report is loaded only when a limit is set, and applies to mainnet buys. If a limit is set but the report or the field cannot be read, the guard fails closed with `due_diligence_unavailable` rather than letting the trade through.
+
+## Coverage caveat
+
+Reads use the public RPC failover chain. Some lanes prune history, return empty lists or rate-limit, so a report states its coverage (`coverage`) and withholds any field below `min_evidence_ratio`. A withheld field means "not enough evidence", not "safe". Retry later or configure an archival RPC lane for fuller coverage.
diff --git a/src/three-token-page.js b/src/three-token-page.js
index aedb9ac88..366f35dd4 100644
--- a/src/three-token-page.js
+++ b/src/three-token-page.js
@@ -15,6 +15,7 @@ import { paintVerifiedBadge } from './pump/verified-badge.js';
import { chartEmbedUrls } from './shared/chart-embeds.js';
import { watchEmbed, embedFallbackNode } from './shared/embed-guard.js';
import { mountFeeFlow, FEE_FLOW_CSS } from './three-token-fee-flow.js';
+import { mountDueDiligence, DD_PANEL_CSS } from './token-dd-panel.js';
import {
THREE_DEXTOOLS_PAIR,
DEXTOOLS_PAIR_URL,
@@ -224,7 +225,7 @@ function injectStyles() {
@media (prefers-reduced-motion: reduce){ html { scroll-behavior:auto; } .tk-trade.in { animation:none; } .tk-skel { animation:none; } .tk-bb-bar span { transition:none; } .tk-why-card { transition:none; } .tk-chart-skel, .tk-chart-frame { transition:none; } }
`;
const el = document.createElement('style');
- el.textContent = css + FEE_FLOW_CSS;
+ el.textContent = css + FEE_FLOW_CSS + DD_PANEL_CSS;
document.head.appendChild(el);
}
@@ -595,6 +596,10 @@ function boot() {
</div>
</div>
<section class="tk-card tk-ff" id="tk-fee-flow" data-fee-flow aria-label="Where every $100 goes"></section>
+ <section class="tk-card" id="tk-holder-dd" aria-label="Holder due diligence">
+ <h2>Who holds it</h2>
+ <div data-dd></div>
+ </section>
<div class="tk-card tk-bb" id="tk-bb-proof">
<h2>Programmatic buybacks</h2>
<div data-buyback><div class="tk-skel" style="height:96px"></div></div>
@@ -640,6 +645,9 @@ function boot() {
mountDextoolsChart(wrap.querySelector('[data-chart]'));
+ // Holder due diligence: insider / sniper / bundler / fresh-wallet fields + funding graph.
+ mountDueDiligence(wrap.querySelector('[data-dd]'), { mint: THREE_MINT });
+
// Bonding curve — real on-chain reads for the $THREE mint.
mountBondingCurve(wrap.querySelector('[data-curve]'), { mint: THREE_MINT, network: 'mainnet', showUsd: true, refreshMs: 15_000, accent: '#4ade80' });
diff --git a/src/token-dd-panel.js b/src/token-dd-panel.js
new file mode 100644
index 000000000..e48e76f1b
--- /dev/null
+++ b/src/token-dd-panel.js
@@ -0,0 +1,165 @@
+// Holder due-diligence panel for the token page: the seven due-diligence fields
+// (each linked to its definition) and a 3D funding graph of the largest holders,
+// read live from GET /api/crypto/due-diligence. Loading is a real skeleton, an
+// unreadable field says "not readable" (never a zero), and a failed load offers
+// a retry. The graph engine under src/vendor/swarming is lazy-loaded.
+
+import { errorStateHTML, emptyStateHTML } from './shared/state-kit.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+const short = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}...${a.slice(-4)}` : a || '');
+
+export const DD_PANEL_CSS = `
+.tkdd-fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:0 0 14px}
+.tkdd-f{background:var(--tk-inset);border:1px solid var(--tk-inset-border);border-radius:10px;padding:10px 12px;min-width:0}
+.tkdd-f a{color:var(--tk-muted);font-size:12px;text-decoration:none;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.tkdd-f a:hover,.tkdd-f a:focus-visible{color:var(--tk-link);text-decoration:underline;outline:none}
+.tkdd-v{font-size:22px;font-weight:650;color:var(--tk-strong);margin-top:2px;font-variant-numeric:tabular-nums}
+.tkdd-v.na{font-size:14px;font-weight:500;color:var(--tk-dim);line-height:30px}
+.tkdd-v.hot{color:var(--tk-warn)}
+.tkdd-graph{position:relative;height:340px;border:1px solid var(--tk-inset-border);border-radius:10px;background:var(--tk-inset);overflow:hidden}
+.tkdd-graph .fg3d-tip{position:absolute;pointer-events:none;background:var(--tk-surface);border:1px solid var(--tk-border-2);color:var(--tk-text);font-size:12px;padding:4px 8px;border-radius:6px;white-space:nowrap}
+.tkdd-legend{display:flex;flex-wrap:wrap;gap:12px;margin:8px 0 0;font-size:12px;color:var(--tk-muted)}
+.tkdd-legend i{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:5px;vertical-align:baseline}
+.tkdd-notes{margin:10px 0 0;padding:0 0 0 18px;font-size:12px;color:var(--tk-muted);line-height:1.5}
+.tkdd-meta{font-size:12px;color:var(--tk-dim);margin:8px 0 0}
+.tkdd-skel{height:68px;border-radius:10px}
+`;
+
+const FIELD_ORDER = ['insider_pct', 'sniper_pct', 'bundler_pct', 'fresh_wallet_pct', 'fresh_wallet_ratio', 'smart_money_holders', 'smart_money_pct'];
+
+function fmtValue(key, v) {
+ if (v == null) return null;
+ if (key === 'smart_money_holders') return String(v);
+ if (key === 'fresh_wallet_ratio') return `${(v * 100).toFixed(0)}%`;
+ return `${Number(v).toFixed(v >= 10 ? 1 : 2)}%`;
+}
+
+export function renderFields(report) {
+ return `<div class="tkdd-fields">${FIELD_ORDER.map((key) => {
+ const def = report.definitions?.[key];
+ const v = fmtValue(key, report.fields?.[key]);
+ const hot = v != null && key !== 'smart_money_holders' && key !== 'smart_money_pct' && Number(report.fields[key]) >= 20;
+ return `<div class="tkdd-f"><a href="${esc(def?.doc || '#')}" target="_blank" rel="noopener" title="${esc(def?.definition || '')}">${esc(def?.label || key)}</a>${
+ v == null ? '<div class="tkdd-v na">not readable</div>' : `<div class="tkdd-v${hot ? ' hot' : ''}">${esc(v)}</div>`
+ }</div>`;
+ }).join('')}</div>`;
+}
+
+const KIND_COLOR = { holder: '#7CC4FF', program: '#5b6478', funder: '#fb923c', source: '#a78bfa', creator: '#fbbf24' };
+
+export function buildRenderGraph(graph, creator) {
+ const nodes = graph.nodes.map((n) => {
+ const isCreator = n.id === creator;
+ const kind = isCreator ? 'creator' : n.kind;
+ return {
+ id: n.id,
+ kind: 'wallet',
+ ddKind: kind,
+ radius: n.hop === 0 ? 1.1 + Math.sqrt(Math.max(0, n.pct || 0)) * 0.55 : n.hop === 1 ? 1.1 : 0.8,
+ color: KIND_COLOR[kind] || KIND_COLOR.holder,
+ net_sol: 0,
+ labels: [],
+ pct: n.pct || 0,
+ service: !!n.service,
+ cluster: null,
+ };
+ });
+ const edges = graph.edges.map((e) => ({ source: e.source, target: e.target, color: '#3a3a42' }));
+ return { nodes, edges };
+}
+
+async function mountGraph(container, report, reducedMotion) {
+ const [{ ForceSimulation }, { ThreeRenderer }] = await Promise.all([
+ import('./vendor/swarming/ForceSimulation.js'),
+ import('./vendor/swarming/ThreeRenderer.js'),
+ ]);
+ const { nodes, edges } = buildRenderGraph(report.graph, report.creator);
+ const tip = document.createElement('div');
+ tip.className = 'fg3d-tip';
+ tip.hidden = true;
+ container.appendChild(tip);
+ const onHover = (node, x, y) => {
+ if (!node) { tip.hidden = true; return; }
+ const bits = [short(node.id), node.ddKind, node.pct ? `${node.pct}% of supply` : null, node.service ? 'service (history too long to trace)' : null].filter(Boolean);
+ tip.textContent = bits.join(' | ');
+ tip.hidden = false;
+ tip.style.left = `${Math.max(8, Math.min(container.clientWidth - tip.offsetWidth - 8, x + 12))}px`;
+ tip.style.top = `${Math.max(8, y - 34)}px`;
+ };
+ const renderer = new ThreeRenderer(container, { autoRotate: !reducedMotion, onHover });
+ renderer.renderer.domElement.setAttribute('aria-label', `3D funding graph: ${nodes.length} wallets over two funding hops. Drag to rotate, scroll to zoom. The holder fields above summarise the same data.`);
+ const sim = new ForceSimulation();
+ sim.update(nodes, edges);
+ renderer.setData(sim.nodes, sim.edges);
+ if (reducedMotion) {
+ sim.settle();
+ renderer.fit();
+ } else {
+ let fitted = false;
+ renderer.start(() => {
+ if (sim.alpha > 0.001) sim.tick();
+ else if (!fitted) { fitted = true; renderer.fit(); }
+ });
+ }
+ return () => { sim.dispose(); renderer.dispose(); tip.remove(); };
+}
+
+/**
+ * @param {HTMLElement} root
+ * @param {{ mint: string, fetchImpl?: typeof fetch }} opts
+ */
+export function mountDueDiligence(root, { mint, fetchImpl = fetch } = {}) {
+ let destroyGraph = null;
+ let runId = 0;
+
+ const skeleton = () => {
+ root.innerHTML = `<div class="tkdd-fields" aria-busy="true">${Array.from({ length: 7 }, () => '<div class="tk-skel tkdd-skel"></div>').join('')}</div><div class="tk-skel" style="height:340px;border-radius:10px"></div>`;
+ };
+
+ const failed = (title, body) => {
+ root.innerHTML = errorStateHTML({ title, body, actions: [{ label: 'Retry', id: 'dd-retry', primary: true }] });
+ root.querySelector('[data-sk-action="dd-retry"]')?.addEventListener('click', load);
+ };
+
+ async function load() {
+ const run = ++runId;
+ destroyGraph?.();
+ destroyGraph = null;
+ skeleton();
+ let report;
+ try {
+ const resp = await fetchImpl(`/api/crypto/due-diligence?address=${encodeURIComponent(mint)}`);
+ if (run !== runId) return;
+ if (!resp.ok) return failed('Holder analysis is unavailable', 'The chain data sources did not answer. The token itself is unaffected. Try again in a few seconds.');
+ report = await resp.json();
+ } catch {
+ if (run !== runId) return;
+ return failed('Holder analysis is unavailable', 'The request did not complete. Check your connection and try again.');
+ }
+ if (run !== runId) return;
+
+ const notes = (report.notes || []).map((n) => `<li>${esc(n)}</li>`).join('');
+ const cov = report.coverage || {};
+ const hasGraph = report.graph?.nodes?.length > 0;
+ root.innerHTML = `${renderFields(report)}
+ ${hasGraph ? '<div class="tkdd-graph" data-dd-graph role="img" aria-label="Funding graph"></div>' : emptyStateHTML({ title: 'No holder links to draw', body: 'No funding relationships were readable for the largest holders.' })}
+ <div class="tkdd-legend"><span><i style="background:${KIND_COLOR.holder}"></i>Holder</span><span><i style="background:${KIND_COLOR.creator}"></i>Creator</span><span><i style="background:${KIND_COLOR.funder}"></i>Funder (hop 1)</span><span><i style="background:${KIND_COLOR.source}"></i>Funder of funder (hop 2)</span><span><i style="background:${KIND_COLOR.program}"></i>Pool or program</span></div>
+ <p class="tkdd-meta">Analysed the ${esc(cov.holders_analyzed ?? 0)} largest accounts (${esc(cov.analyzed_pct ?? 0)}% of supply). Cached ${esc(report.ttl_seconds)}s. Computed ${esc(new Date(report.computed_at).toLocaleTimeString())}.</p>
+ ${notes ? `<ul class="tkdd-notes">${notes}</ul>` : ''}`;
+
+ if (hasGraph) {
+ const host = root.querySelector('[data-dd-graph]');
+ const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
+ try {
+ const teardown = await mountGraph(host, report, reduced);
+ if (run !== runId) teardown(); else destroyGraph = teardown;
+ } catch {
+ host.innerHTML = '<p class="tkdd-meta" style="padding:16px">The 3D graph needs WebGL, which is unavailable here. The fields above carry the same analysis.</p>';
+ }
+ }
+ }
+
+ load();
+ return { reload: load, destroy() { runId++; destroyGraph?.(); } };
+}
diff --git a/tests/agent-trade-endpoint.test.js b/tests/agent-trade-endpoint.test.js
index a1a1f1868..691d9cba4 100644
--- a/tests/agent-trade-endpoint.test.js
+++ b/tests/agent-trade-endpoint.test.js
@@ -64,6 +64,13 @@ vi.mock('../api/_lib/avatar-wallet.js', () => ({
vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+// The holder due-diligence read is a chain-wide scan covered by
+// tests/token-due-diligence.test.js; here the report is the input to the guard.
+const ddState = { report: { status: 'ok', fields: { insider_pct: 3, sniper_pct: 1, bundler_pct: 0, fresh_wallet_pct: 0 } } };
+vi.mock('../api/_lib/token-due-diligence.js', () => ({
+ getTokenDueDiligence: vi.fn(async () => ddState.report),
+}));
+
// CSRF is enforced on the live (non-simulate) trade path; the token round-trip is
// covered by its own suite. Here we stub it to a pass so these tests exercise the
// trade logic, exactly as auth/rate-limit/db are mocked above.
@@ -210,6 +217,7 @@ beforeEach(() => {
authState.session = { id: 'owner-1' };
authState.bearer = null;
clientState.buyImpact = 1;
+ ddState.report = { status: 'ok', fields: { insider_pct: 3, sniper_pct: 1, bundler_pct: 0, fresh_wallet_pct: 0 } };
clientState.expectedBaseTokens = '1000000';
clientState.sellImpact = 1;
clientState.expectedQuoteOut = '50000000';
@@ -374,6 +382,31 @@ describe('POST /api/agents/:id/trade — guard rejections', () => {
expect(res.json.error).toBe('price_impact');
});
+ it('insider share above the configured limit → 422 due_diligence', async () => {
+ setAgent({ trade_limits: { max_insider_pct: 10 } });
+ ddState.report = { status: 'ok', fields: { insider_pct: 30, sniper_pct: 1, bundler_pct: 0, fresh_wallet_pct: 0 } };
+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });
+ expect(res.statusCode).toBe(422);
+ expect(res.json.error).toBe('due_diligence');
+ expect(res.json.detail).toMatchObject({ field: 'insider_pct', value_pct: 30, max_pct: 10 });
+ });
+
+ it('insider share within the limit does not block the buy', async () => {
+ setAgent({ trade_limits: { max_insider_pct: 10 } });
+ ddState.report = { status: 'ok', fields: { insider_pct: 4, sniper_pct: 1, bundler_pct: 0, fresh_wallet_pct: 0 } };
+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });
+ expect(res.json.error).not.toBe('due_diligence');
+ expect(res.json.error).not.toBe('due_diligence_unavailable');
+ });
+
+ it('a holder limit with an unreadable report refuses the buy instead of passing it', async () => {
+ setAgent({ trade_limits: { max_insider_pct: 10 } });
+ ddState.report = { status: 'upstream_down' };
+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });
+ expect(res.statusCode).toBe(422);
+ expect(res.json.error).toBe('due_diligence_unavailable');
+ });
+
it('insufficient SOL → 400 insufficient_sol', async () => {
connState.balance = 0n;
const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });
@@ -527,6 +560,20 @@ describe('PUT /api/agents/:id/trade/limits: input validation', () => {
expect(savedLimits()).toBeNull();
});
+ it('rejects an out-of-range holder limit instead of silently clearing it', async () => {
+ const res = await putLimits({ max_insider_pct: 150 });
+ expect(res.statusCode).toBe(400);
+ expect(savedLimits()).toBeNull();
+ });
+
+ it('accepts and persists holder-quality limits', async () => {
+ const res = await putLimits({ max_insider_pct: 12.5, max_bundler_pct: '20' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.data.limits.max_insider_pct).toBe(12.5);
+ expect(res.json.data.limits.max_bundler_pct).toBe(20);
+ expect(savedLimits().max_insider_pct).toBe(12.5);
+ });
+
it('accepts real caps, numeric strings, and an explicit null clear', async () => {
const set = await putLimits({ per_trade_sol: 0.5, daily_budget_sol: '2', max_concurrent: 3, kill_switch: true });
expect(set.statusCode).toBe(200);
diff --git a/tests/fixtures/token-dd/three-recorded.json b/tests/fixtures/token-dd/three-recorded.json
new file mode 100644
index 000000000..44bcc9d0d
--- /dev/null
+++ b/tests/fixtures/token-dd/three-recorded.json
@@ -0,0 +1,314 @@
+{
+ "recorded_at": "2026-10-23T23:48:54.000Z",
+ "source": "mainnet RPC via rotating failover; wallet_reputation lookup",
+ "raw": {
+ "status": "ok",
+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "supplyRaw": "999634594111305",
+ "decimals": 6,
+ "mint_authority_revoked": true,
+ "freeze_authority_revoked": true,
+ "launch": {
+ "slot": 441512330,
+ "time": 1787617736,
+ "creator": "JUPW3tHBxmNRzVnLmTyYUsUDB6izZSEtupY6znBC5mo",
+ "creator_funder": null
+ },
+ "holders": [
+ {
+ "owner": "5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z",
+ "token_account": "5jeRNm8Rx8CrbhbiyNWE4wStfrtfrVpXU76cK9jovyGd",
+ "amount": "194397478636543",
+ "program_derived": true,
+ "first_slot": 460554412,
+ "first_time": 1792782089,
+ "profile": null
+ },
+ {
+ "owner": "8DgVVtnNZQRKu4Cx6xeAMTukUHMTE3f2Cqb1wMzJ9beU",
+ "token_account": "G24sg31UjRGZsMgeaMup1PJbEYvwfc5MWPUvyW7kndnW",
+ "amount": "20252320693638",
+ "program_derived": false,
+ "first_slot": 451744619,
+ "first_time": 1790712461,
+ "profile": {
+ "first_time": 1792798824,
+ "first_slot": 460633216,
+ "history_complete": false,
+ "sig_count": 6000,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "B4dBgTrDQa5ay5tK9YeHUKiqMg1KRLB1RZtWqPRWVoP1",
+ "token_account": "GipFNVyMfKWRD4A53CYD8eSDqntTv9X9LneaJ6zKjxFT",
+ "amount": "19372649305908",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": 1773382989,
+ "first_slot": 406079615,
+ "history_complete": true,
+ "sig_count": 186,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "3zgcLZ7E8UFo5Rg93Z8LcV4rR77gexNEpPDnVKE5dkRW",
+ "token_account": "2jMuCckAFvdE6T7SKy48NdZSn4RrDBdaigWzrQwMNU3p",
+ "amount": "14085590622970",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": 1738155182,
+ "first_slot": 317134603,
+ "history_complete": true,
+ "sig_count": 370,
+ "funder": "6r24mwhDAhE6ZuJoKdWX5wDsRThq6ZFABTWQ3y3z6F6e",
+ "funder_at": 1738155182,
+ "funded_lamports": 368213626,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "5BceizACS858hZkg5VieUZzhs5sJ7a8ygsD3832iahWz",
+ "token_account": "z6fYeCwu3vKFgHFJdmu7YhZaVsP7uB7QjwwdiVwouAw",
+ "amount": "13955378041416",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": 1780593735,
+ "first_slot": 424287848,
+ "history_complete": true,
+ "sig_count": 231,
+ "funder": "7wHfZWdczyvjku8MssQE6xtuFut5N1bKPGaQhDzRJh2B",
+ "funder_at": 1780593735,
+ "funded_lamports": 80430000000,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "7MvqRqEt7XdhGe5Fa9FED6uj4ZPcUkxJAeXbiRr96aMj",
+ "token_account": "9VAq8rDwF1UCCjsnvhYBa2QotZRi64CYoHr4Z5mNhVjq",
+ "amount": "13625087216853",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": null,
+ "first_slot": null,
+ "history_complete": true,
+ "sig_count": 0,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "5r6iVWbTkVRqavvXUaaVbi3rBgU3AikQJ1iSSyWtJT7X",
+ "token_account": "EvjTXqRXiAqs63UKXhZXtFqeuekJVwJ1gP8YK3JFCBAd",
+ "amount": "13508015596230",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": null,
+ "first_slot": null,
+ "history_complete": true,
+ "sig_count": 0,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "35x6tQdDLTj669tLKTMMy2EJ8ZpxfUn9fkkvfvEtui4c",
+ "token_account": "CVzX7rtap3Pt1m6yp8y3X4A2Y7NH1HN7LvJiUxbBEkQ8",
+ "amount": "11096000000000",
+ "program_derived": true,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "6iKRxvAPmPG9Df2mShgLmTFPo2nbsTRnj1aYV8k3XpFv",
+ "token_account": "3CBPoHxxvRYYLx2RDPrm5y52nKXkgpqMXxVnztaosjnQ",
+ "amount": "10858409017391",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": null,
+ "first_slot": null,
+ "history_complete": true,
+ "sig_count": 0,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "68aRKnx7ofEU7smArNtuDfAEiUpQZZ8jXGwh5c9Rn1n7",
+ "token_account": "Hg8frvTDRVg7T1MpLBet7JLa1HtPak4DxniTCeX7SoDW",
+ "amount": "10147107308812",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": null,
+ "first_slot": null,
+ "history_complete": true,
+ "sig_count": 0,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "2n41SJe8j5VU8G8kXeV7pDP6Dc9YpufDZ3wkD3tViBzF",
+ "token_account": "AJsPBbd1EUsuYYoXDDQR3fWbqGqBu9aFJjtK9RZ24vR",
+ "amount": "10011794101873",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "5Ww9DCcZuHCPqmvhRJELsRCehEXmo6FEUkNq6inSbT9u",
+ "token_account": "4io19h5m4hn3Nc3FdqFcDVfMz9u34qswHQHyWcmjYCF4",
+ "amount": "10007843509301",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": null,
+ "first_slot": null,
+ "history_complete": true,
+ "sig_count": 0,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "AjHXjde7b5M6ec4WZWftK6KYC9X7AwAhu3dQTDWiUvZF",
+ "token_account": "GWbNZQiQBACAWee2SaY9H7beQp38EMqn2W5WXhv4DaDF",
+ "amount": "10000000000000",
+ "program_derived": true,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "51PqavyPP9yQQ1C4BrnVkt8whAs9WpdfjeD6f3x8FDGq",
+ "token_account": "5wqH9iJdFQX81djnQPciwfQaWQ819P7LA7JG289MzsW6",
+ "amount": "9085972193404",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "EP5aoDiSvUdTyyWeqsMK9MdLwSgScDTADEcyJNceepJS",
+ "token_account": "C6NJ1oT82sK1cJYi8W6jG2jxv8BbRmxadPNJWdDbQXoj",
+ "amount": "9077172922418",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "4ev9BvN4QZQVpGpXqasbWV3zWnLfZ8p8uzeZvcgDGuug",
+ "token_account": "7R2kdzEi7bdZzkPPbb7C2dQjVcCMNga9CDMe75my3RZG",
+ "amount": "9017446050557",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": null,
+ "first_slot": null,
+ "history_complete": true,
+ "sig_count": 0,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "Db47sgUE7MjyaAkpPeu8jykJyC9Zzt1KZR7xZmM3zNpZ",
+ "token_account": "3Dx8yW18QS1VhzxmD8auPA8PmhszK4QdGRahYzDF8FZv",
+ "amount": "8612120990390",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": {
+ "first_time": 1792789568,
+ "first_slot": 460589621,
+ "history_complete": true,
+ "sig_count": 12,
+ "funder": null,
+ "funder_at": null,
+ "funded_lamports": null,
+ "funder2": null,
+ "funder2_at": null
+ }
+ },
+ {
+ "owner": "BM9CcyErJcu2mjrFvUsRRrD3snGeHDDVirJLvL6EjvMN",
+ "token_account": "AT3mMM4QghqMNoPfaRVBh4N5yFbgkWu5pmnqak6MNPat",
+ "amount": "8458722425622",
+ "program_derived": true,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "F7KccVDppZyYVZ8HKkts9GHDvcGoiaXrm7ws2tWm4ttq",
+ "token_account": "GU6ZW66vaJMKHBUK1DdAfpUtxD4cxrxFhLWZ1pXju7d6",
+ "amount": "8317907916006",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ },
+ {
+ "owner": "7UiqScBJyZrqtU7Cx8xsnd2qERtruotTsLNNon2eYkjR",
+ "token_account": "43KdY81AG3N1ZL3kiXb4kNjwcNAzWYLH69ksCGvb2mdr",
+ "amount": "8151554279851",
+ "program_derived": false,
+ "first_slot": null,
+ "first_time": null,
+ "profile": null
+ }
+ ],
+ "services": [],
+ "read_errors": 7,
+ "now": 1792799334
+ },
+ "reputation": []
+}
diff --git a/tests/token-due-diligence.test.js b/tests/token-due-diligence.test.js
new file mode 100644
index 000000000..02a487c9a
--- /dev/null
+++ b/tests/token-due-diligence.test.js
@@ -0,0 +1,287 @@
+// Token due diligence: definitions, thresholds, evidence floor, funding graph,
+// signature paging, the cache wrapper, and the agent-trade guard over the
+// fields. The $THREE case replays a recorded real read of the mint (chain RPC
+// plus our wallet_reputation table) from tests/fixtures/token-dd/three-recorded.json;
+// the other cases use clearly synthetic wallets so each rule is pinned alone.
+
+import { describe, it, expect, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { PublicKey } from '@solana/web3.js';
+import {
+ DD_THRESHOLDS, DD_FIELDS, DD_DEFINITIONS, clusterHolders, computeDueDiligence, buildFundingGraph,
+ oldestSignature, getTokenDueDiligence, traceFundingGraph, isProgramDerived,
+} from '../api/_lib/token-due-diligence.js';
+import { checkDueDiligence, guardDueDiligence, normalizeTradeLimits, tradeGuardResponse, TRADE_LIMIT_DEFAULTS } from '../api/_lib/agent-trade-guards.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const rec = JSON.parse(readFileSync(new URL('./fixtures/token-dd/three-recorded.json', import.meta.url), 'utf8'));
+
+// Synthetic wallets: real on-curve keys derived from fixed seeds, never real holders.
+const wallet = (n) => new PublicKey(Buffer.alloc(32, n)).toBase58();
+const W = Array.from({ length: 12 }, (_, i) => wallet(i + 1));
+const SUPPLY = '1000000';
+const LAUNCH = { slot: 1000, time: 1_000_000, creator: W[0], creator_funder: null };
+const DAY = 86400;
+
+let slotSeq = 5000;
+// Distinct first slots by default: three holders in one slot is itself a bundle signal.
+const holder = (owner, amount, over = {}) => ({
+ owner, token_account: `ta-${owner.slice(0, 6)}`, amount: String(amount), program_derived: false,
+ first_slot: slotSeq++ * 100, first_time: LAUNCH.time + 3600 * 48,
+ profile: { first_time: LAUNCH.time - 40 * DAY, history_complete: true, sig_count: 50, funder: null, funder_at: null, funder2: null, funder2_at: null },
+ ...over,
+});
+const compute = (holders, extra = {}) => computeDueDiligence({ mint: 'm', supplyRaw: SUPPLY, decimals: 6, launch: LAUNCH, holders, smartAvailable: true, smart: new Map(), ...extra });
+
+describe('recorded $THREE read', () => {
+ const dd = computeDueDiligence({
+ ...rec.raw,
+ services: new Set(rec.raw.services),
+ readErrors: rec.raw.read_errors,
+ smartAvailable: true,
+ smart: new Map(rec.reputation.map((r) => [r.wallet, r])),
+ });
+
+ it('produces every documented field, each null or a bounded number', () => {
+ for (const key of DD_FIELDS) {
+ const v = dd.fields[key];
+ expect(v === null || (typeof v === 'number' && v >= 0), key).toBe(true);
+ if (key.endsWith('_pct')) expect(v === null || v <= 100, key).toBe(true);
+ }
+ });
+
+ it('keeps holder shares on the supply basis and classifies pools as programs', () => {
+ const total = dd.holders.reduce((s, h) => s + h.pct, 0);
+ expect(total).toBeGreaterThan(5);
+ expect(total).toBeLessThanOrEqual(100);
+ expect(dd.holders.some((h) => h.kind === 'program')).toBe(true);
+ expect(dd.coverage.holders_analyzed).toBe(rec.raw.holders.length);
+ });
+
+ it('says why a field is withheld instead of printing a zero', () => {
+ const withheld = DD_FIELDS.filter((k) => dd.fields[k] === null && !k.startsWith('smart'));
+ if (withheld.length) expect(dd.notes.join(' ')).toMatch(/withheld/);
+ });
+});
+
+describe('definitions and thresholds', () => {
+ it('defines every field with a doc link into docs/token-due-diligence.md', () => {
+ for (const key of DD_FIELDS) {
+ expect(DD_DEFINITIONS[key].definition.length, key).toBeGreaterThan(30);
+ expect(DD_DEFINITIONS[key].doc).toMatch(/docs\/token-due-diligence\.md#/);
+ }
+ });
+
+ it('documents every threshold in the doc', () => {
+ const doc = readFileSync(new URL('../docs/token-due-diligence.md', import.meta.url), 'utf8');
+ for (const key of Object.keys(DD_THRESHOLDS)) expect(doc, key).toContain(key);
+ for (const key of DD_FIELDS) expect(doc, key).toContain(`### ${key}`);
+ });
+});
+
+describe('field rules (synthetic wallets)', () => {
+ it('counts the creator and creator-funded holders as insiders', () => {
+ const dd = compute([
+ holder(W[0], 100_000),
+ holder(W[1], 50_000, { profile: { ...holder(W[1], 0).profile, funder: W[0], funder_at: LAUNCH.time } }),
+ holder(W[2], 40_000),
+ holder(W[3], 30_000),
+ ]);
+ expect(dd.fields.insider_pct).toBe(15);
+ expect(dd.holders.find((h) => h.owner === W[1]).flags).toContain('insider');
+ });
+
+ it('counts first receipts inside the sniper window and excludes the creator', () => {
+ const dd = compute([
+ holder(W[0], 100_000, { first_slot: 1000 }),
+ holder(W[1], 50_000, { first_slot: 1000 + DD_THRESHOLDS.sniper_slots }),
+ holder(W[2], 40_000, { first_slot: 1000 + DD_THRESHOLDS.sniper_slots + 1 }),
+ holder(W[3], 30_000, { first_slot: 5000 }),
+ ]);
+ expect(dd.fields.sniper_pct).toBe(5);
+ });
+
+ it('clusters holders funded by one source within the window, not outside it', () => {
+ const funded = (at) => ({ profile: { ...holder(W[9], 0).profile, funder: W[8], funder_at: at } });
+ const inside = compute([
+ holder(W[1], 50_000, funded(1_500_000)),
+ holder(W[2], 40_000, funded(1_500_000 + 3 * 3600)),
+ holder(W[3], 30_000),
+ ]);
+ expect(inside.fields.bundler_pct).toBe(9);
+ expect(inside.clusters).toHaveLength(1);
+ const outside = compute([
+ holder(W[1], 50_000, funded(1_500_000)),
+ holder(W[2], 40_000, funded(1_500_000 + 30 * 3600)),
+ holder(W[3], 30_000),
+ ]);
+ expect(outside.fields.bundler_pct).toBe(0);
+ });
+
+ it('does not cluster holders that share a service funder', () => {
+ const funded = { profile: { ...holder(W[9], 0).profile, funder: W[8], funder_at: 1_500_000 } };
+ const dd = compute([holder(W[1], 50_000, funded), holder(W[2], 40_000, funded), holder(W[3], 30_000)], { services: new Set([W[8]]) });
+ expect(dd.fields.bundler_pct).toBe(0);
+ });
+
+ it('flags wallets under 24h old at first receipt as fresh', () => {
+ const young = { profile: { ...holder(W[9], 0).profile, first_time: 5000 * 0 + (LAUNCH.time + 3600 * 48) - 3600 } };
+ const dd = compute([holder(W[1], 50_000, young), holder(W[2], 40_000), holder(W[3], 30_000), holder(W[4], 20_000)]);
+ expect(dd.fields.fresh_wallet_pct).toBe(5);
+ expect(dd.fields.fresh_wallet_ratio).toBe(0.25);
+ });
+
+ it('marks smart money from our own reputation rows only at or above the bar', () => {
+ const smart = new Map([[W[1], { smart_money_score: 80, label: 'consistent' }], [W[2], { smart_money_score: 40, label: null }]]);
+ const dd = compute([holder(W[1], 50_000), holder(W[2], 40_000), holder(W[3], 30_000)], { smart });
+ expect(dd.fields.smart_money_holders).toBe(1);
+ expect(dd.fields.smart_money_pct).toBe(5);
+ });
+
+ it('withholds a field when too few wallets yielded its evidence', () => {
+ const blind = { first_slot: null, first_time: null, profile: null };
+ const dd = compute([holder(W[1], 50_000), holder(W[2], 40_000, blind), holder(W[3], 30_000, blind), holder(W[4], 20_000, blind)]);
+ expect(dd.fields.sniper_pct).toBeNull();
+ expect(dd.fields.insider_pct).toBeNull();
+ expect(dd.fields.fresh_wallet_pct).toBeNull();
+ expect(dd.notes.join(' ')).toMatch(/withheld/);
+ });
+
+ it('withholds smart-money fields when the reputation lookup did not run', () => {
+ const dd = compute([holder(W[1], 50_000)], { smartAvailable: false });
+ expect(dd.fields.smart_money_holders).toBeNull();
+ });
+});
+
+describe('clusterHolders', () => {
+ it('links through a shared second-hop source', () => {
+ const mk = (o, f1) => ({ owner: o, funder: f1, funder_at: 10, funder2: W[8], funder2_at: 10 });
+ const { clusters } = clusterHolders([mk(W[1], W[5]), mk(W[2], W[6])]);
+ expect(clusters).toHaveLength(1);
+ });
+});
+
+describe('funding graph', () => {
+ it('builds holder, funder and second-hop nodes with edges pointing funder to funded', () => {
+ const dd = compute([holder(W[1], 50_000, { profile: { ...holder(W[1], 0).profile, funder: W[5], funder_at: 1, funder2: W[6], funder2_at: 1 } })]);
+ const g = buildFundingGraph(dd, { creator: W[0] });
+ expect(g.nodes.find((n) => n.id === W[5]).hop).toBe(1);
+ expect(g.nodes.find((n) => n.id === W[6]).hop).toBe(2);
+ expect(g.nodes.some((n) => n.id === W[0])).toBe(true);
+ expect(g.edges).toEqual(expect.arrayContaining([{ source: W[5], target: W[1], hop: 1, lamports: null }, { source: W[6], target: W[5], hop: 2, lamports: null }]));
+ });
+});
+
+describe('signature paging', () => {
+ const sig = (n, slot) => ({ signature: `s${n}`, slot, blockTime: slot });
+ it('returns the oldest signature and marks a short last page complete', async () => {
+ const rpc = vi.fn(async () => [sig(3, 30), sig(2, 20), sig(1, 10)]);
+ const o = await oldestSignature(W[1], rpc);
+ expect(o).toEqual({ oldest: sig(1, 10), count: 3, complete: true });
+ });
+ it('ignores signatures older than minSlot', async () => {
+ const rpc = vi.fn(async () => [sig(3, 30), sig(2, 20), sig(1, 10)]);
+ const o = await oldestSignature(W[1], rpc, { minSlot: 15 });
+ expect(o.oldest.slot).toBe(20);
+ });
+ it('reports incomplete when the page budget runs out', async () => {
+ let n = 1_000_000;
+ const rpc = vi.fn(async () => Array.from({ length: 1000 }, () => sig(n, n--)));
+ const o = await oldestSignature(W[1], rpc);
+ expect(o.complete).toBe(false);
+ });
+});
+
+describe('traceFundingGraph', () => {
+ it('stops at a service funder whose history cannot be reached', async () => {
+ const rpc = vi.fn(async (method) => {
+ if (method === 'getSignaturesForAddress') return Array.from({ length: 1000 }, (_, i) => ({ signature: `x${i}`, slot: 9e9 - i, blockTime: 9e9 - i }));
+ return null;
+ });
+ const g = await traceFundingGraph(W[7], { deps: { rpc, history: rpc, now: () => 0 } });
+ expect(g.truncated).toBe(true);
+ expect(g.nodes[0].service).toBe(true);
+ });
+});
+
+describe('getTokenDueDiligence', () => {
+ const deps = (calls) => ({
+ now: () => 1_800_000_000,
+ rpc: async (method) => {
+ calls.push(method);
+ if (method === 'getAccountInfo') return null;
+ return null;
+ },
+ });
+ it('reports not_found for an address that is not a mint, without caching it', async () => {
+ const calls = [];
+ const r = await getTokenDueDiligence(THREE_MINT, { deps: deps(calls), smartLookup: async () => [], force: true });
+ expect(r.status).toBe('not_found');
+ });
+});
+
+describe('isProgramDerived', () => {
+ it('separates off-curve accounts from wallets', () => {
+ const [pda] = PublicKey.findProgramAddressSync([Buffer.from('pool')], new PublicKey(THREE_MINT));
+ expect(isProgramDerived(pda.toBase58())).toBe(true);
+ expect(isProgramDerived('not-a-key')).toBe(false);
+ });
+});
+
+describe('agent trade guard over the due-diligence fields', () => {
+ const limits = (over) => normalizeTradeLimits({ ...over });
+ const fields = { insider_pct: 22.5, sniper_pct: 3, bundler_pct: 0, fresh_wallet_pct: 1 };
+
+ it('defaults to no holder limits', () => {
+ for (const k of ['max_insider_pct', 'max_sniper_pct', 'max_bundler_pct', 'max_fresh_wallet_pct']) expect(TRADE_LIMIT_DEFAULTS[k]).toBeNull();
+ expect(checkDueDiligence(fields, limits({}))).toBeNull();
+ });
+
+ it('refuses a token whose insider share is above the configured limit', () => {
+ const blocked = checkDueDiligence(fields, limits({ max_insider_pct: 10 }));
+ expect(blocked).toMatchObject({ reason: 'due_diligence', detail: { field: 'insider_pct', value_pct: 22.5, max_pct: 10 } });
+ const resp = tradeGuardResponse(blocked);
+ expect(resp.status).toBe(422);
+ expect(resp.message).toMatch(/22\.5% of supply, above your 10\.0% limit/);
+ });
+
+ it('allows a token at or below the limit', () => {
+ expect(checkDueDiligence(fields, limits({ max_insider_pct: 22.5 }))).toBeNull();
+ expect(checkDueDiligence(fields, limits({ max_insider_pct: 30, max_sniper_pct: 5 }))).toBeNull();
+ });
+
+ it('checks each configured limit and names the one that failed', () => {
+ const blocked = checkDueDiligence(fields, limits({ max_insider_pct: 30, max_sniper_pct: 2 }));
+ expect(blocked.detail.field).toBe('sniper_pct');
+ });
+
+ it('fails closed when a limit is set but the field could not be read', () => {
+ const blocked = checkDueDiligence({ ...fields, insider_pct: null }, limits({ max_insider_pct: 10 }));
+ expect(blocked.reason).toBe('due_diligence_unavailable');
+ expect(tradeGuardResponse(blocked).message).toMatch(/could not be checked/);
+ });
+
+ it('guardDueDiligence reads the report only when a limit is set', async () => {
+ const load = vi.fn(async () => ({ status: 'ok', fields }));
+ expect(await guardDueDiligence(THREE_MINT, limits({}), { load })).toBeNull();
+ expect(load).not.toHaveBeenCalled();
+ const blocked = await guardDueDiligence(THREE_MINT, limits({ max_insider_pct: 10 }), { load });
+ expect(blocked.reason).toBe('due_diligence');
+ expect(load).toHaveBeenCalledWith(THREE_MINT);
+ });
+
+ it('guardDueDiligence fails closed when the report cannot be loaded', async () => {
+ const down = await guardDueDiligence(THREE_MINT, limits({ max_insider_pct: 10 }), { load: async () => { throw new Error('rpc down'); } });
+ expect(down.reason).toBe('due_diligence_unavailable');
+ const bad = await guardDueDiligence(THREE_MINT, limits({ max_insider_pct: 10 }), { load: async () => ({ status: 'upstream_down' }) });
+ expect(bad.reason).toBe('due_diligence_unavailable');
+ });
+
+ it('normalizes out-of-range limits to unset instead of a silent zero', () => {
+ const n = limits({ max_insider_pct: 250, max_sniper_pct: -4, max_bundler_pct: 'abc', max_fresh_wallet_pct: '12.5' });
+ expect(n.max_insider_pct).toBeNull();
+ expect(n.max_sniper_pct).toBeNull();
+ expect(n.max_bundler_pct).toBeNull();
+ expect(n.max_fresh_wallet_pct).toBe(12.5);
+ });
+});