Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(wallet-linkage): ship a Solana same-controller wallet scorer, endpoint, and MCP tool
nirholas112749dfeb1d
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex fdbde9189..b087a29c9 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -127,7 +127,7 @@ packages, a generated standalone GitHub mirror). See| OKX.AI marketplace services | [api/okx/3d/[service].js](api/okx/3d/%5Bservice%5D.js) `→ /api/okx/3d/*` | Live | 3D services sold to other agents on OKX.AI (agent #2632). The **listed** line-up (rebuilt 2026-08-22) is **three.ws Forge**: four paid A2MCP rows (`forge-draft` $0.01 / `forge-standard` $0.05 / `forge-hd` $0.25 / `forge-image` $0.25) plus a free `forge-status` poll, tools in [api/_okx3d/forge.js](api/_okx3d/forge.js). Each row is a real MCP Streamable HTTP server whose paid `forge_3d` tool 402s with `eip155:196` leading; the buyer receives exactly what the ChatGPT custom GPT receives (GLB + concept image + viewer + AR link), because both fronts shape responses through [api/_mcp-studio/studio-shape.js](api/_mcp-studio/studio-shape.js). Agent Identity Studio and the single-capability REST endpoints are on the **back burner**: `listed: false` keeps them out of the listing and the submission payload while they stay deployed and payable. Catalog source of truth: [api/_lib/okx-catalog.js](api/_lib/okx-catalog.js); pipeline: [api/_okx3d/](api/_okx3d); showcase: [pages/agent-identities.html](pages/agent-identities.html) `→ /agent-identities` + [src/agent-identities.js](src/agent-identities.js), fed at runtime by [api/agent-identities.js](api/agent-identities.js) `→ /api/agent-identities` (demo runs from `data/agent-identities.json` merged with the live catalog row, so the price the page quotes is the price the paid endpoint charges); docs: [docs/okx-marketplace.md](docs/okx-marketplace.md), [docs/agent-identities.md](docs/agent-identities.md). Tests: [tests/api/okx-forge.test.js](tests/api/okx-forge.test.js) || 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`, `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) |+| 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) || 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) |@@ -469,6 +469,7 @@ packages/assistant-mcp/ → @three-ws/assistant-mcp (MCP server — gepackages/vanity-mcp/ → @three-ws/vanity-mcp (MCP server — Solana vanity bounty market + rarity gallery)packages/naming-mcp/ → @three-ws/naming-mcp (MCP server — .sol resolve + *.threews.sol identity availability)packages/intel-mcp/ → @three-ws/intel-mcp (MCP server — smart-money, signals, KOL, copy-trade intel)+packages/wallet-linkage/ → @three-ws/wallet-linkage (Solana wallet-linkage scorer: shared fee payer, first-funder, token-account control, direct transfer, funding burst; noisy-OR, 0-100 score; ported from wallet-sleuth)packages/marketplace-mcp/ → @three-ws/marketplace-mcp (MCP server — agent marketplace + skills catalog browse)packages/x402-mcp/ → @three-ws/x402-mcp (MCP server — self-custodial x402 buyer: find/inspect/pay any service in USDC)packages/metaplex-agent-mcp/ → @three-ws/metaplex-agent-mcp (MCP server: mint + register on-chain agents in the Metaplex Agent Registry, self-custody or Phantom/Solflare)diff --git a/api/_lib/crypto-catalog/index.js b/api/_lib/crypto-catalog/index.jsindex aacb2c0b7..6577af9e1 100644--- a/api/_lib/crypto-catalog/index.js+++ b/api/_lib/crypto-catalog/index.js@@ -27,6 +27,7 @@ import airdropsEntry from './airdrops.js';import bondingEntry from './bonding.js';import holdersEntry from './holders.js';import launchesEntry from './launches.js';+import linkageEntry from './linkage.js';import portfolioEntry from './portfolio.js';import securityEntry from './security.js';import symbolEntry from './symbol.js';@@ -49,6 +50,7 @@ const STATIC_ENTRIES = [{ mod: bondingEntry, source: 'bonding.js' },{ mod: holdersEntry, source: 'holders.js' },{ mod: launchesEntry, source: 'launches.js' },+ { mod: linkageEntry, source: 'linkage.js' },{ mod: portfolioEntry, source: 'portfolio.js' },{ mod: securityEntry, source: 'security.js' },{ mod: symbolEntry, source: 'symbol.js' },diff --git a/api/_lib/crypto-catalog/linkage.js b/api/_lib/crypto-catalog/linkage.jsnew file mode 100644index 000000000..0a7558a7b--- /dev/null+++ b/api/_lib/crypto-catalog/linkage.js@@ -0,0 +1,69 @@+// Catalog entry for GET /api/crypto/linkage: the free wallet-linkage endpoint.+//+// The /api/crypto index merges this descriptor into the bundle's discovery doc+// + OpenAPI (via the STATIC_ENTRIES barrel in index.js). Plain, serializable,+// no imports, no side effects.++export default {+ slug: 'linkage',+ method: 'GET',+ path: '/api/crypto/linkage',+ title: 'Wallet Linkage',+ summary:+ 'Are these Solana wallets the same person? Pairwise 0-100 same-controller scores with evidence (shared fee payer, first-funder, SPL token-account control, direct transfer, funding burst), combined by noisy-OR across 2-10 addresses. Keyless, live on-chain history.',+ inputSchema: {+ type: 'object',+ required: ['addresses'],+ properties: {+ addresses: {+ type: 'string',+ description: 'Comma-separated list of 2 to 10 Solana addresses to cross-check for shared control.',+ },+ },+ },+ outputSchema: {+ type: 'object',+ properties: {+ addresses: { type: 'array', items: { type: 'string' } },+ pairs: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ a: { type: 'string' },+ b: { type: 'string' },+ score: { type: 'integer' },+ band: { type: 'string', enum: ['none', 'weak', 'moderate', 'strong', 'confirmed'] },+ topSignal: { type: ['string', 'null'] },+ signals: { type: 'array', items: { type: 'string' } },+ evidence: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ weight: { type: 'number' },+ evidence: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ kind: { type: 'string' },+ account: { type: 'string' },+ signature: { type: 'string' },+ detail: { type: 'string' },+ },+ },+ },+ },+ },+ },+ },+ },+ },+ complete: { type: 'boolean' },+ ts: { type: 'string', format: 'date-time' },+ },+ },+ example: '/api/crypto/linkage?addresses=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump,11111111111111111111111111111111',+};diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 1a43cf3d4..d3ef97c89 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -1607,6 +1607,12 @@ export const limits = {// free nodes the whole platform shares, so it gets a tighter per-IP burst// than the family's 60/min.cryptoHoldersIp: (ip) => getLimiter('crypto-holders:ip', { limit: 20, window: '1 m' }).limit(ip),+ // /api/crypto/linkage walks each address's recent history (a signatures page+ // plus up to DEFAULT_SIGNATURE_LIMIT parsed-transaction fetches) against the+ // shared Solana RPC lanes, so it gets its own tighter-than-the-family burst+ // plus a global hourly ceiling, the same shape as the holders family above.+ cryptoLinkageIp: (ip) => getLimiter('crypto-linkage:ip', { limit: 10, window: '1 m' }).limit(ip),+ cryptoLinkageGlobal: () => getLimiter('crypto-linkage:global', { limit: 600, window: '1 h' }).limit('global'),// Free Crypto Data API family (api/crypto/*). Keyless, no-account reads an agent// makes mid-task (wallet portfolio, token snapshots). Some paths fan out to the// keyed Helius/public-RPC upstreams, so a generous-but-bounded per-IP burst keepsdiff --git a/api/crypto/linkage.js b/api/crypto/linkage.jsnew file mode 100644index 000000000..a73030318--- /dev/null+++ b/api/crypto/linkage.js@@ -0,0 +1,134 @@+// GET /api/crypto/linkage: are these Solana wallets the same person?+//+// Agent use-case: a sniper or copy-trade agent vetting early buyers of a coin+// needs to know whether they are independent actors or the creator's own+// alts. One call answers it: pairwise 0-100 same-controller scores with+// evidence, across 2-10 addresses, combined by noisy-OR over six real+// on-chain signals (shared fee payer, first-funder, SPL token-account+// control, direct transfer, funding burst). Keyless, real RPC history, never+// a mock.+//+// Part of the free Crypto Data API (/api/crypto/*). Backed by+// @three-ws/wallet-linkage (ported from the owner's proprietary+// wallet-sleuth), given this deployment's own Solana RPC failover chain as+// its injected client so it never talks to a hardcoded endpoint.+//+// Query:+// addresses = <Solana address>,<Solana address>[,...] (required, 2-10)+//+// Response: { addresses[], pairs: [{ a, b, score, band, topSignal, signals[],+// evidence[] }], complete, ts }+// `complete:false` means at least one address's history walk hit its time or+// request budget before finishing: scores are still real, just possibly+// based on partial history.++import { analyzeLinkage } from '@three-ws/wallet-linkage';++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 { solanaConnection } from '../_lib/solana/connection.js';+import { cacheGet, cacheSet } from '../_lib/cache.js';+import { staleEnvelope } from '../_lib/rpc-degrade.js';++const MIN_ADDRESSES = 2;+const MAX_ADDRESSES = 10;++// Repeat lookups of the same set absorb into this window; linkage facts move+// slowly (new transactions, not price), so a few minutes of staleness is a+// correct answer, not a stale one.+const LINKAGE_FRESH_MS = 5 * 60_000;+const LINKAGE_LKG_TTL_S = 24 * 3600;++const EXAMPLE = '/api/crypto/linkage?addresses=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump,11111111111111111111111111111111';++const linkageLkgKey = (addresses) => `crypto:linkage:lkg:${addresses.join(',')}`;++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, linkageRl, globalRl, linkageGlobalRl] = await Promise.all([+ limits.cryptoDataIp(ip),+ limits.cryptoLinkageIp(ip),+ limits.cryptoDataGlobal(),+ limits.cryptoLinkageGlobal(),+ ]);+ if (!ipRl.success) return rateLimited(res, ipRl);+ if (!linkageRl.success) return rateLimited(res, linkageRl);+ if (!globalRl.success) return rateLimited(res, globalRl);+ if (!linkageGlobalRl.success) return rateLimited(res, linkageGlobalRl);++ const url = new URL(req.url, 'http://localhost');+ const raw = (url.searchParams.get('addresses') || '').trim();+ if (!raw) {+ return error(res, 400, 'missing_addresses', 'query param `addresses` is required: 2 to 10 comma-separated Solana addresses', {+ example: EXAMPLE,+ });+ }++ const addresses = [...new Set(raw.split(',').map((a) => a.trim()).filter(Boolean))];+ if (addresses.length < MIN_ADDRESSES || addresses.length > MAX_ADDRESSES) {+ return error(res, 400, 'invalid_address_count', `pass between ${MIN_ADDRESSES} and ${MAX_ADDRESSES} distinct addresses`, {+ received: addresses.length,+ example: EXAMPLE,+ });+ }+ const evm = addresses.find(isValidEvmAddress);+ if (evm) {+ return error(res, 400, 'unsupported_chain', 'this endpoint reads Solana wallet linkage only (Solana first). Pass base58 Solana addresses', {+ address: evm,+ example: EXAMPLE,+ });+ }+ const invalid = addresses.find((a) => !isValidSolanaAddress(a));+ if (invalid) {+ return error(res, 400, 'invalid_address', '`addresses` must each be a base58 Solana address (32-44 chars)', {+ address: invalid,+ example: EXAMPLE,+ });+ }++ const lkgKey = linkageLkgKey(addresses);+ const cached = await cacheGet(lkgKey);+ if (cached && cached.body && typeof cached.at === 'number' && Date.now() - cached.at < LINKAGE_FRESH_MS) {+ return json(res, 200, cached.body, {+ 'cache-control': 'public, s-maxage=120, stale-while-revalidate=120',+ 'x-linkage-cache': 'hit',+ });+ }++ const ts = new Date().toISOString();+ let result;+ try {+ const connection = solanaConnection({ network: 'mainnet' });+ result = await analyzeLinkage(connection, addresses);+ } catch (err) {+ if (cached && cached.body && typeof cached.at === 'number') {+ return json(res, 200, staleEnvelope(cached.body, cached.at), {+ 'cache-control': 'public, s-maxage=30, stale-while-revalidate=60',+ 'x-linkage-stale': '1',+ });+ }+ return json(res, 503, {+ error: 'upstream_unavailable',+ error_description: 'Solana RPC is temporarily unreachable, retry shortly',+ message: err?.message || String(err),+ retry_after: 15,+ ts,+ }, { 'cache-control': 'no-store', 'retry-after': '15' });+ }++ const body = {+ addresses: result.addresses,+ pairs: result.pairs,+ complete: result.complete,+ ts,+ };+ cacheSet(lkgKey, { body, at: Date.now() }, LINKAGE_LKG_TTL_S).catch(() => {});++ return json(res, 200, body, {+ 'cache-control': 'public, s-maxage=120, stale-while-revalidate=120',+ });+});diff --git a/package-lock.json b/package-lock.jsonindex 0c0a38170..264cbed8e 100644--- a/package-lock.json+++ b/package-lock.json@@ -81,7 +81,8 @@"packages/home-mcp","packages/blender-mcp","packages/ai-sdk",- "packages/langchain"+ "packages/langchain",+ "packages/wallet-linkage"],"dependencies": {"@0xsplits/splits-sdk": "^6.6.0",@@ -29244,6 +29245,10 @@"resolved": "walk-sdk","link": true},+ "node_modules/@three-ws/wallet-linkage": {+ "resolved": "packages/wallet-linkage",+ "link": true+ },"node_modules/@three-ws/witness": {"resolved": "packages/witness","link": true@@ -58176,6 +58181,16 @@"node": ">=20"}},+ "packages/wallet-linkage": {+ "name": "@three-ws/wallet-linkage",+ "version": "0.1.0",+ "license": "SEE LICENSE IN LICENSE",+ "dependencies": {+ "@solana/web3.js": "^1.99.0",+ "bs58": "^6.0.0",+ "lru-cache": "^11.5.2"+ }+ },"packages/witness": {"name": "@three-ws/witness","version": "0.1.0",diff --git a/package.json b/package.jsonindex 5cce70955..b24e8f0a6 100644--- a/package.json+++ b/package.json@@ -138,7 +138,8 @@"packages/home-mcp","packages/blender-mcp","packages/ai-sdk",- "packages/langchain"+ "packages/langchain",+ "packages/wallet-linkage"],"main": "src/app.js","browserslist": [diff --git a/packages/intel-mcp/README.md b/packages/intel-mcp/README.mdindex edb56fab8..21a204879 100644--- a/packages/intel-mcp/README.md+++ b/packages/intel-mcp/README.md@@ -65,12 +65,13 @@ npx -y @modelcontextprotocol/inspector npx @three-ws/intel-mcp| -------------------- | --------- | ------------------------------------------------------------------------------------------------------------ || `smart_money_coin` | read-only | Score a coin by WHO is net-buying it — 0–100 smart-money score, reputable buyers, funder clusters, sybil flag. || `wallet_intel` | read-only | One wallet's realized reputation: score, win rate, behavioral labels, and its funder cluster. |+| `wallet_linkage` | read-only | Cross-check 2-10 Solana wallets for shared control: 0-100 same-controller score per pair, with evidence. || `signal_feed` | read-only | A signal feed's proven accuracy (hit-rate, realized/follower ROI) and recent emissions with on-chain proof. || `kol_leaderboard` | read-only | Rank tracked KOL traders by realized P&L over a 7d / 30d window. || `kol_trades` | read-only | Recent KOL trades on a specific mint, across the tracked KOL set. || `copy_smart_wallets` | read-only | Browse the ranked copy-trade Smart Money directory — filter by chain, category, and sort. |-All six tools read live data: scores, feeds, and rankings move between calls, so none are idempotent.+All seven tools read live data: scores, feeds, and rankings move between calls, so none are idempotent.### Input parameters@@ -78,6 +79,8 @@ All six tools read live data: scores, feeds, and rankings move between calls, so**`wallet_intel`** — `wallet` (required), `network` (`mainnet` | `devnet`, default `mainnet`).+**`wallet_linkage`**: `addresses` (required, array of 2-10 Solana addresses).+**`signal_feed`** — `slug` (required), `network` (`mainnet` | `devnet`, default `mainnet`).**`kol_leaderboard`** — `window` (`7d` | `30d`, default `7d`), `limit` (1–100, default 25).@@ -124,6 +127,29 @@ All six tools read live data: scores, feeds, and rankings move between calls, so`computed: false` on a coin or wallet means the smart-money graph has no on-chain history for it yet — that's an honest "not enough data", not a failure.+```jsonc+// wallet_linkage+> { "addresses": ["FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "11111111111111111111111111111111"] }+{+ "ok": true,+ "addresses": ["FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "11111111111111111111111111111111"],+ "pairs": [+ {+ "a": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "b": "11111111111111111111111111111111",+ "score": 0,+ "band": "none",+ "topSignal": null,+ "signals": [],+ "evidence": []+ }+ ],+ "complete": true+}+```++`complete: false` on the response means at least one address's history walk hit its time or request budget before finishing: scores are still real signals, just possibly based on partial history.+## Requirements- **Node.js >= 20.**diff --git a/packages/intel-mcp/src/index.js b/packages/intel-mcp/src/index.jsindex 51efea0e6..d8c3c3d22 100755--- a/packages/intel-mcp/src/index.js+++ b/packages/intel-mcp/src/index.js@@ -4,6 +4,7 @@// Gives any AI assistant the three.ws market-intelligence surface over stdio:// • smart_money_coin — judge a coin by WHO is net-buying it (0–100 score)// • wallet_intel — one wallet's realized reputation card+// • wallet_linkage : are these 2-10 wallets the same person (0-100 score)// • signal_feed — a feed's proven accuracy + recent emissions// • kol_leaderboard — ranked KOL traders by realized P&L// • kol_trades — recent KOL trades on a given mint@@ -26,6 +27,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'import { def as smartMoneyCoin } from './tools/smart-money-coin.js';import { def as walletIntel } from './tools/wallet-intel.js';+import { def as walletLinkage } from './tools/wallet-linkage.js';import { def as signalFeed } from './tools/signal-feed.js';import { def as kolLeaderboard } from './tools/kol-leaderboard.js';import { def as kolTrades } from './tools/kol-trades.js';@@ -38,6 +40,7 @@ const { version: PKG_VERSION } = require('../package.json');export const TOOLS = [smartMoneyCoin,walletIntel,+ walletLinkage,signalFeed,kolLeaderboard,kolTrades,@@ -58,7 +61,9 @@ export function buildServer() {'three.ws Intel MCP — read the market the way the smart money does. smart_money_coin ' +'scores a coin by WHO is net-buying it (a 0–100 reputation-weighted score, funder clusters, ' +'and a sybil flag). wallet_intel pulls one wallet\'s realized track record (score, win rate, ' +- 'labels, funder cluster). signal_feed reads a feed\'s proven accuracy and recent emissions ' ++ 'labels, funder cluster). wallet_linkage cross-checks 2-10 wallets for shared control (shared ' ++ 'fee payer, first funder, token-account ownership, direct transfers, funding bursts), each ' ++ 'pair scored 0-100 with evidence. signal_feed reads a feed\'s proven accuracy and recent emissions ' +'with realized ROI. kol_leaderboard ranks tracked KOL traders by P&L; kol_trades shows their ' +'recent trades on a given mint. copy_smart_wallets browses the ranked copy-trade Smart Money ' +'directory. All data comes live from the public three.ws API — no API key, signer, or payment ' +diff --git a/packages/intel-mcp/src/tools/wallet-linkage.js b/packages/intel-mcp/src/tools/wallet-linkage.jsnew file mode 100644index 000000000..e6a25031b--- /dev/null+++ b/packages/intel-mcp/src/tools/wallet-linkage.js@@ -0,0 +1,32 @@+// `wallet_linkage`: are these Solana wallets the same person? Read-only.+//+// Wraps GET /api/crypto/linkage?addresses=A,B[,...].++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'wallet_linkage',+ title: 'Wallet linkage: same-controller scoring across 2-10 addresses',+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ description:+ "Cross-check 2 to 10 Solana addresses for shared control. Each pair gets a 0-100 score (band: none/weak/moderate/strong/confirmed) combining six real on-chain signals by noisy-OR: shared fee payer, one address's first funder being the other, both sharing a first funder, SPL token-account control, direct transfers, and a shared funder sending similar amounts in a short window. Every match comes with evidence (the signature or account that triggered it). `complete:false` on a pair's bundle means its history walk hit a time/request budget before finishing. Use this to check whether a coin's early buyers are independent, or the creator's own alts, or whether a copy-trade leader secretly controls the creator wallet of a coin they are pumping.",+ inputSchema: {+ addresses: z+ .array(z.string().min(1))+ .min(2)+ .max(10)+ .describe('2 to 10 Solana addresses to cross-check for shared control.'),+ },+ async handler(args) {+ const addresses = Array.isArray(args?.addresses) ? args.addresses.map((a) => String(a).trim()).filter(Boolean) : [];+ const data = await apiRequest('/api/crypto/linkage', { query: { addresses: addresses.join(',') } });+ return {+ ok: true,+ addresses: data?.addresses ?? addresses,+ pairs: Array.isArray(data?.pairs) ? data.pairs : [],+ complete: data?.complete ?? false,+ };+ },+};diff --git a/packages/wallet-linkage/LICENSE b/packages/wallet-linkage/LICENSEnew file mode 100644index 000000000..0445314d8--- /dev/null+++ b/packages/wallet-linkage/LICENSE@@ -0,0 +1,28 @@+Wallet Linkage (ported from Wallet Sleuth)++Copyright (c) 2026 nirholas. All rights reserved.++PROPRIETARY AND CONFIDENTIAL. SOURCE AVAILABLE, NOT OPEN SOURCE.++This package ports the Solana linkage signals and noisy-OR scorer from the+owner's proprietary `wallet-sleuth` repository into three.ws, under the+permission the owner grants themselves as the author of both repositories.+The original license grants and prohibitions on `wallet-sleuth` continue to+apply to this derived code:++Permission is granted to:+ - View and read this source for evaluation purposes.+ - Reference this source, with attribution, for evaluation purposes.++Permission is NOT granted, without prior written permission from the+copyright holder, to:+ - Copy or redistribute this source outside the three.ws monorepo.+ - Modify or create derivative works beyond integrating it into three.ws.+ - Run, deploy, or host this source as a standalone product or service.+ - Use this source in another product.+ - Sell or sublicense this source.+ - Remove this notice.++This file exists to satisfy the wallet-sleuth license's requirement that its+notice travel with the ported code. It does not change three.ws's own+license for the rest of the monorepo.diff --git a/packages/wallet-linkage/README.md b/packages/wallet-linkage/README.mdnew file mode 100644index 000000000..47bdd7a86--- /dev/null+++ b/packages/wallet-linkage/README.md@@ -0,0 +1,82 @@+# @three-ws/wallet-linkage++Answers one question: are these two Solana wallets the same person? Ported+from the owner's proprietary `wallet-sleuth`, trimmed to the signals a launch+platform needs (Solana first; EVM signals are out of scope), with the+upstream license header preserved in [LICENSE](./LICENSE).++## What it does++Given 2 to 10 addresses, `analyzeLinkage` collects each one's recent Solana+activity through an **injected RPC client** (never a hardcoded endpoint, so+the caller's own failover chain is used) and scores every pair with six+signals, combined by noisy-OR into one 0-100 score:++| Signal | Weight | What it catches |+|---|---|---|+| `solana-account-control` | 1.0 | One address is an SPL token account owned by the other, or paid to create it (rent payer). |+| `solana-fee-payer` | 0.9 | Both addresses have transactions signed and fee-paid by the same key. |+| `peer-first-funding` | 0.9 | One address's very first inbound transfer came from the other. |+| `common-first-funder` | 0.8 | Both addresses' first inbound transfer came from the same third account. |+| `direct-transfer` | 0.75 | Value moved directly between the two addresses (dust filtered, recency-discounted). |+| `funding-burst` | 0.6 | The same funder sent both addresses similar amounts within a short window. |++A third-party address that funds three or more of the addresses under+analysis (or appears in the runtime exclusion list) is treated as a shared+service/exchange wallet, not evidence of a link, see "Exclusions" below.++## Usage++```js+import { analyzeLinkage } from '@three-ws/wallet-linkage';+import { solanaConnection } from '../../api/_lib/solana/connection.js';++const connection = solanaConnection({ network: 'mainnet' });+const result = await analyzeLinkage(connection, [addressA, addressB]);+// result.pairs[0] => { a, b, score, band, topSignal, signals, evidence }+```++The `connection` argument is duck-typed: anything exposing+`getSignaturesForAddress`, `getParsedTransaction`, and `getAccountInfo` with+`@solana/web3.js`-shaped return values works, so a caller can inject a mock+in tests or a different failover chain entirely.++### Score bands++| Score | Band |+|---|---|+| 85-100 | `confirmed` |+| 65-84 | `strong` |+| 40-64 | `moderate` |+| 20-39 | `weak` |+| 0-19 | `none` |++### Bounded by design++Each collector call is capped by a signature count AND a wall-clock budget+(`signatureLimit`, `budgetMs` in `opts`). A slow RPC lane or a wallet with+years of history degrades to a partial answer (`complete: false`) instead of+hanging a request.++### Exclusions++Known service/exchange accounts are never hardcoded in this package (a real+third-party address in committed code would need the CLAUDE.md+crypto-project commit gate). Supply them at runtime instead:++- `WALLET_LINKAGE_EXCLUDED_ACCOUNTS`: comma-separated address list.+- `WALLET_LINKAGE_EXCLUSIONS_PATH`: path to a JSON array of addresses.++## Used by++- `GET /api/crypto/linkage`: the public pairwise-linkage endpoint.+- `wallet_linkage` in `packages/intel-mcp`: the MCP tool.+- `api/_lib/trade-firewall.js`: flags early buyers linked to a coin's creator.+- `api/_lib/copy-eligibility.js`: refuses a copy-trade leader linked to the+ creator of the coin being copied.++## License++Proprietary, ported from `wallet-sleuth` under the owner's own permission as+author of both repositories. See [LICENSE](./LICENSE). This does not change+the license of the rest of the three.ws monorepo.diff --git a/packages/wallet-linkage/package.json b/packages/wallet-linkage/package.jsonnew file mode 100644index 000000000..2f93b3849--- /dev/null+++ b/packages/wallet-linkage/package.json@@ -0,0 +1,29 @@+{+ "name": "@three-ws/wallet-linkage",+ "version": "0.1.0",+ "description": "Solana wallet linkage signals (shared fee payer, first-funder, account control, direct transfer, funding burst) combined by noisy-OR into a 0-100 same-controller score with evidence. Ported from the owner's proprietary wallet-sleuth; chain-agnostic scorer, Solana-first signals.",+ "type": "module",+ "private": true,+ "author": "nirholas <[email protected]>",+ "license": "SEE LICENSE IN LICENSE",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/wallet-linkage"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "dependencies": {+ "@solana/web3.js": "^1.99.0",+ "bs58": "^6.0.0",+ "lru-cache": "^11.5.2"+ }+}diff --git a/packages/wallet-linkage/src/collect.js b/packages/wallet-linkage/src/collect.jsnew file mode 100644index 000000000..ecd5cb8cb--- /dev/null+++ b/packages/wallet-linkage/src/collect.js@@ -0,0 +1,175 @@+// Solana activity collector: walks one address's recent transaction history+// through an injected RPC client (the caller's own failover-chain Connection,+// never a hardcoded endpoint) and reduces it to the shapes the signals need:+// inbound/outbound transfers, the set of fee payers seen on its transactions,+// and its first inbound transfer (the funding root).+//+// Bounded by both a signature-count cap and a wall-clock budget: deep wallet+// history on a slow RPC lane must degrade to a partial, honest answer+// (`complete: false`) rather than hang a request (see the work order's+// "signals need deep history and RPC is slow" never-blocked row).++import { PublicKey } from '@solana/web3.js';++const TOKEN_PROGRAMS = new Set([+ 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',+ 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',+]);++export const DEFAULT_SIGNATURE_LIMIT = 40;+export const DEFAULT_BUDGET_MS = 8_000;++function toPubkey(address) {+ return address instanceof PublicKey ? address : new PublicKey(address);+}++function tokenOwnerAt(tx, accountAddress) {+ const keys = tx?.transaction?.message?.accountKeys ?? [];+ const idx = keys.findIndex((k) => (k?.pubkey ?? k) === accountAddress);+ if (idx < 0) return null;+ const pre = (tx?.meta?.preTokenBalances ?? []).find((b) => b.accountIndex === idx);+ const post = (tx?.meta?.postTokenBalances ?? []).find((b) => b.accountIndex === idx);+ return (post ?? pre)?.owner ?? null;+}++/**+ * Reduce one `jsonParsed` transaction to its fee payer and the wallet-level+ * transfers it carried. Native SOL instructions already name wallets; SPL+ * instructions name token accounts, so the destination is resolved to its+ * owning wallet via the transaction's pre/post token balances.+ *+ * @param {object} tx parsed transaction+ * @param {string} signature+ * @returns {{ feePayer: string|null, transfers: Array<object> }}+ */+export function extractTransfers(tx, signature) {+ const message = tx?.transaction?.message;+ const feePayerKey = message?.accountKeys?.[0]?.pubkey ?? message?.accountKeys?.[0] ?? null;+ const feePayer = feePayerKey?.toBase58?.() ?? (typeof feePayerKey === 'string' ? feePayerKey : null);+ const blockTime = tx?.blockTime ?? null;+ const instructions = message?.instructions ?? [];+ const transfers = [];++ for (const ix of instructions) {+ const parsed = ix?.parsed;+ if (!parsed || typeof parsed !== 'object') continue;+ const type = parsed.type;+ const info = parsed.info ?? {};++ if (ix.program === 'system' && type === 'transfer') {+ const amount = Number(info.lamports ?? 0) / 1e9;+ if (info.source && info.destination && amount > 0) {+ transfers.push({ from: info.source, to: info.destination, amount, asset: 'SOL', kind: 'native', signature, blockTime });+ }+ continue;+ }+ if (ix.program === 'system' && type === 'createAccount') {+ const amount = Number(info.lamports ?? 0) / 1e9;+ if (info.source && info.newAccount) {+ transfers.push({ from: info.source, to: info.newAccount, amount, asset: 'SOL', kind: 'create', signature, blockTime });+ }+ continue;+ }+ if ((type === 'transfer' || type === 'transferChecked') && TOKEN_PROGRAMS.has(ix.programId)) {+ const amount = Number(info.tokenAmount?.uiAmount ?? info.amount ?? 0);+ const from = info.authority ?? null;+ const to = info.destination ? tokenOwnerAt(tx, info.destination) : null;+ if (from && to && amount > 0) {+ transfers.push({ from, to, amount, asset: info.mint ?? 'SPL', kind: 'token', signature, blockTime });+ }+ }+ }++ return { feePayer, transfers };+}++/**+ * Collect one address's recent activity into the shape every linkage signal+ * reads: `transfers` (chronological), `payers` (fee payers across its own+ * transactions), and `firstInbound` (the earliest transfer that funded it).+ *+ * @param {object} connection injected RPC client: `getSignaturesForAddress`,+ * `getParsedTransaction`: a `@solana/web3.js` Connection, or anything+ * shaped like one.+ * @param {string} address+ * @param {{ signatureLimit?: number, budgetMs?: number, commitment?: string }} [opts]+ */+export async function collectActivity(connection, address, opts = {}) {+ const { signatureLimit = DEFAULT_SIGNATURE_LIMIT, budgetMs = DEFAULT_BUDGET_MS, commitment = 'confirmed' } = opts;+ const startedAt = Date.now();+ const deadline = startedAt + budgetMs;+ const warnings = [];++ let signatures = [];+ try {+ signatures = await connection.getSignaturesForAddress(toPubkey(address), { limit: signatureLimit });+ } catch (err) {+ return {+ address,+ transfers: [],+ payers: new Set(),+ firstInbound: null,+ complete: false,+ fetchMs: Date.now() - startedAt,+ warnings: [`signatures: ${err?.message || err}`],+ };+ }++ const transfers = [];+ const payers = new Set();+ let truncated = false;++ for (const sig of signatures) {+ if (Date.now() >= deadline) {+ truncated = true;+ break;+ }+ if (sig.err) continue;+ let tx;+ try {+ tx = await connection.getParsedTransaction(sig.signature, { maxSupportedTransactionVersion: 0, commitment });+ } catch (err) {+ warnings.push(`tx ${String(sig.signature).slice(0, 8)}: ${err?.message || err}`);+ continue;+ }+ if (!tx) continue;+ const { feePayer, transfers: txTransfers } = extractTransfers(tx, sig.signature);+ if (feePayer) payers.add(feePayer);+ for (const t of txTransfers) transfers.push({ ...t, blockTime: t.blockTime ?? sig.blockTime ?? null });+ }++ transfers.sort((a, b) => (a.blockTime ?? 0) - (b.blockTime ?? 0));+ const firstInbound = transfers.find((t) => t.to === address && t.from !== address) ?? null;++ return {+ address,+ transfers,+ payers,+ firstInbound,+ complete: !truncated,+ fetchMs: Date.now() - startedAt,+ warnings,+ };+}++/**+ * Best-effort account facts beyond transfer history: whether `address` is+ * itself an SPL token account, and who owns it. Feeds `solana-account-control`.+ * A lookup failure is never fatal: it just means this signal has nothing to+ * add for this address.+ *+ * @param {object} connection injected RPC client exposing `getAccountInfo`.+ * @param {string} address+ */+export async function fetchAccountFacts(connection, address) {+ try {+ const info = await connection.getAccountInfo(toPubkey(address), { encoding: 'jsonParsed' });+ const parsed = info?.value?.data?.parsed ?? info?.data?.parsed;+ if (parsed?.type === 'account' && parsed?.info?.owner) {+ return { tokenOwner: parsed.info.owner, isTokenAccount: true };+ }+ } catch {+ // Best-effort: see docstring above.+ }+ return { tokenOwner: null, isTokenAccount: false };+}diff --git a/packages/wallet-linkage/src/exclusions.js b/packages/wallet-linkage/src/exclusions.jsnew file mode 100644index 000000000..ebc0bd3d5--- /dev/null+++ b/packages/wallet-linkage/src/exclusions.js@@ -0,0 +1,40 @@+// Known service/exchange accounts excluded from the signals that key on a+// shared counterparty (fee payer, first funder, funding burst): a hot wallet+// that funds thousands of unrelated users is not evidence two of them share a+// controller. Loaded at runtime from WALLET_LINKAGE_EXCLUDED_ACCOUNTS (a comma+// separated address list) and/or a JSON array file at+// WALLET_LINKAGE_EXCLUSIONS_PATH. Never hardcoded here: a real third-party+// address committed to this repo would need the CLAUDE.md crypto-project+// commit gate, so the set is supplied by the deployment instead (this ports+// the upstream exclusion-list CONCEPT, not its literal list).++import { readFileSync } from 'node:fs';++let cached = null;++export function loadExclusions(env = process.env) {+ if (cached) return cached;+ const set = new Set();+ const inline = env.WALLET_LINKAGE_EXCLUDED_ACCOUNTS;+ if (inline) {+ for (const addr of inline.split(',').map((s) => s.trim()).filter(Boolean)) set.add(addr);+ }+ const path = env.WALLET_LINKAGE_EXCLUSIONS_PATH;+ if (path) {+ try {+ const data = JSON.parse(readFileSync(path, 'utf8'));+ if (Array.isArray(data)) {+ for (const addr of data) if (typeof addr === 'string') set.add(addr);+ }+ } catch {+ // A missing or invalid exclusions file degrades to the inline list+ // only: this set is a precision tweak, never core correctness.+ }+ }+ cached = set;+ return set;+}++export function resetExclusionsCache() {+ cached = null;+}diff --git a/packages/wallet-linkage/src/index.js b/packages/wallet-linkage/src/index.jsnew file mode 100644index 000000000..126ab6f24--- /dev/null+++ b/packages/wallet-linkage/src/index.js@@ -0,0 +1,70 @@+// Public entry point: score every pair among 2-10 Solana addresses for shared+// control, using an injected RPC client so callers route through their own+// failover chain instead of a hardcoded endpoint.++import { collectActivity, fetchAccountFacts } from './collect.js';+import { runSignals } from './signals.js';+import { scorePair } from './score.js';+import { loadExclusions } from './exclusions.js';++export { collectActivity, fetchAccountFacts, extractTransfers } from './collect.js';+export { runSignals, ALL_SIGNALS, solanaAccountControl, solanaFeePayer, peerFirstFunding, commonFirstFunder, directTransfer, fundingBurst } from './signals.js';+export { scorePair, bandFor } from './score.js';+export { loadExclusions, resetExclusionsCache } from './exclusions.js';++const MIN_ADDRESSES = 2;+const MAX_ADDRESSES = 10;++/**+ * @param {object} connection an injected RPC client exposing+ * `getSignaturesForAddress`, `getParsedTransaction`, `getAccountInfo`: a+ * `@solana/web3.js` Connection, or anything shaped like one. Callers wire in+ * their own failover chain here (three.ws uses `solanaConnection()`).+ * @param {string[]} addresses 2 to 10 Solana addresses.+ * @param {{ signatureLimit?: number, budgetMs?: number, exclusions?: Set<string> }} [opts]+ * @returns {Promise<{ addresses: string[], pairs: Array<object>, complete: boolean }>}+ */+export async function analyzeLinkage(connection, addresses, opts = {}) {+ const unique = [...new Set(addresses)];+ if (unique.length < MIN_ADDRESSES || unique.length > MAX_ADDRESSES) {+ throw new Error(`analyzeLinkage requires between ${MIN_ADDRESSES} and ${MAX_ADDRESSES} distinct addresses`);+ }+ const exclusions = opts.exclusions ?? loadExclusions();++ const bundles = await Promise.all(+ unique.map(async (address) => {+ const [activity, facts] = await Promise.all([+ collectActivity(connection, address, opts),+ fetchAccountFacts(connection, address),+ ]);+ const createTransfer = activity.transfers.find((t) => t.to === address && t.kind === 'create');+ return { ...activity, facts, rentPayer: createTransfer?.from ?? null };+ }),+ );++ // Hub detection across the requested set: a third-party address funding+ // three or more of the addresses under analysis reads as a shared+ // exchange/service wallet, not a controller link (see signals.js).+ const sharedBy = new Map();+ for (const bundle of bundles) {+ const funders = new Set();+ for (const t of bundle.transfers) if (t.to === bundle.address && t.from) funders.add(t.from);+ if (bundle.firstInbound?.from) funders.add(bundle.firstInbound.from);+ for (const f of funders) sharedBy.set(f, (sharedBy.get(f) ?? 0) + 1);+ }+ const ctx = { exclusions, sharedBy };++ const byAddress = new Map(bundles.map((b) => [b.address, b]));+ const pairs = [];+ for (let i = 0; i < unique.length; i++) {+ for (let j = i + 1; j < unique.length; j++) {+ const a = byAddress.get(unique[i]);+ const b = byAddress.get(unique[j]);+ const signalResults = runSignals(a, b, ctx);+ const scored = scorePair(signalResults);+ pairs.push({ a: a.address, b: b.address, ...scored, evidence: signalResults });+ }+ }++ return { addresses: unique, pairs, complete: bundles.every((b) => b.complete) };+}diff --git a/packages/wallet-linkage/src/score.js b/packages/wallet-linkage/src/score.jsnew file mode 100644index 000000000..e441dc3a9--- /dev/null+++ b/packages/wallet-linkage/src/score.js@@ -0,0 +1,42 @@+// Noisy-OR combiner: independent signals of confidence c1..cn combine into one+// probability that two addresses share a controller as 1 - product(1 - ci).+// This is how wallet-sleuth folds several weak-to-strong signals into one+// score without letting any single signal dominate by itself, and it stays+// chain-agnostic: it only ever sees `{ id, weight, evidence }`, never a chain.++const BANDS = [+ { min: 85, band: 'confirmed' },+ { min: 65, band: 'strong' },+ { min: 40, band: 'moderate' },+ { min: 20, band: 'weak' },+ { min: 0, band: 'none' },+];++export function bandFor(score) {+ for (const b of BANDS) if (score >= b.min) return b.band;+ return 'none';+}++function clamp01(n) {+ return Math.min(1, Math.max(0, n));+}++/**+ * @param {Array<{id:string, weight:number, evidence:Array}>} signalResults+ * @returns {{ score: number, band: string, topSignal: string|null, signals: string[] }}+ */+export function scorePair(signalResults) {+ if (!signalResults.length) {+ return { score: 0, band: 'none', topSignal: null, signals: [] };+ }+ let q = 1;+ for (const r of signalResults) q *= 1 - clamp01(r.weight);+ const score = Math.round(clamp01(1 - q) * 100);+ const top = signalResults.slice().sort((x, y) => y.weight - x.weight)[0];+ return {+ score,+ band: bandFor(score),+ topSignal: top?.id ?? null,+ signals: signalResults.map((r) => r.id),+ };+}diff --git a/packages/wallet-linkage/src/signals.js b/packages/wallet-linkage/src/signals.jsnew file mode 100644index 000000000..f2a286f53--- /dev/null+++ b/packages/wallet-linkage/src/signals.js@@ -0,0 +1,161 @@+// The six Solana linkage signals in scope (wallet-sleuth also has EVM signals+// such as `evm-deployer`/`gas-funding`; those are out of scope here, Solana+// first). Each signal inspects a pair of collected activity bundles (see+// collect.js) and either finds nothing (`null`) or returns+// `{ id, weight, evidence: [{ kind, signature|account, detail }] }`, the exact+// shape the /api/crypto/linkage endpoint and the noisy-OR scorer (score.js)+// both expect.++const DUST_SOL = 0.001; // below this, a "direct transfer" is noise, not a link+const BURST_WINDOW_S = 24 * 3600;+const BURST_RATIO = 2; // same funder, amounts within 2x of each other count as a burst+const RECENCY_HALF_LIFE_S = 180 * 24 * 3600; // 180 days++// A third-party address that shows up as funder/fee-payer for three or more of+// the addresses under analysis (or sits on the runtime exclusion list) reads+// as a shared exchange/service wallet, not evidence those addresses share a+// controller: the false-positive the work order calls out by name.+function isHubOrExcluded(address, ctx) {+ if (!address) return true;+ if (ctx.exclusions.has(address)) return true;+ if ((ctx.sharedBy.get(address) ?? 0) >= 3) return true;+ return false;+}++export function solanaAccountControl(a, b) {+ const evidence = [];+ if (a.facts.tokenOwner === b.address) {+ evidence.push({ kind: 'token_account_owner', account: a.address, detail: `${a.address} is a token account owned by ${b.address}` });+ }+ if (b.facts.tokenOwner === a.address) {+ evidence.push({ kind: 'token_account_owner', account: b.address, detail: `${b.address} is a token account owned by ${a.address}` });+ }+ if (a.rentPayer === b.address) {+ evidence.push({ kind: 'rent_payer', account: a.address, detail: `${b.address} paid to create ${a.address}` });+ }+ if (b.rentPayer === a.address) {+ evidence.push({ kind: 'rent_payer', account: b.address, detail: `${a.address} paid to create ${b.address}` });+ }+ if (!evidence.length) return null;+ return { id: 'solana-account-control', weight: 1, evidence };+}++export function solanaFeePayer(a, b, ctx) {+ const shared = [...a.payers].filter((p) => b.payers.has(p) && !isHubOrExcluded(p, ctx));+ if (!shared.length) return null;+ return {+ id: 'solana-fee-payer',+ weight: 0.9,+ evidence: shared.map((payer) => ({+ kind: 'shared_fee_payer',+ account: payer,+ detail: `${a.address} and ${b.address} both have transactions signed and paid for by ${payer}`,+ })),+ };+}++export function peerFirstFunding(a, b) {+ const evidence = [];+ if (a.firstInbound?.from === b.address) {+ evidence.push({ kind: 'first_funder', signature: a.firstInbound.signature, detail: `${a.address}'s first inbound transfer came from ${b.address}` });+ }+ if (b.firstInbound?.from === a.address) {+ evidence.push({ kind: 'first_funder', signature: b.firstInbound.signature, detail: `${b.address}'s first inbound transfer came from ${a.address}` });+ }+ if (!evidence.length) return null;+ return { id: 'peer-first-funding', weight: 0.9, evidence };+}++export function commonFirstFunder(a, b, ctx) {+ const fa = a.firstInbound?.from;+ const fb = b.firstInbound?.from;+ if (!fa || !fb || fa !== fb) return null;+ if (fa === a.address || fa === b.address) return null;+ if (isHubOrExcluded(fa, ctx)) return null;+ return {+ id: 'common-first-funder',+ weight: 0.8,+ evidence: [+ {+ kind: 'common_first_funder',+ account: fa,+ signature: a.firstInbound.signature,+ detail: `${a.address} and ${b.address} were both first funded by ${fa}`,+ },+ ],+ };+}++export function directTransfer(a, b) {+ const now = Date.now() / 1000;+ const direct = a.transfers.filter(+ (t) => t.amount >= DUST_SOL && ((t.from === a.address && t.to === b.address) || (t.from === b.address && t.to === a.address)),+ );+ if (!direct.length) return null;+ const evidence = direct+ .slice()+ .sort((x, y) => (y.blockTime ?? 0) - (x.blockTime ?? 0))+ .slice(0, 5)+ .map((t) => ({+ kind: 'direct_transfer',+ signature: t.signature,+ detail: `${t.amount} ${t.asset} moved directly from ${t.from} to ${t.to}`,+ }));+ // Recency discount: a transfer from long ago is weaker evidence of a+ // CURRENT shared controller than one from last week.+ const mostRecent = Math.max(...direct.map((t) => t.blockTime ?? 0));+ const ageS = Math.max(0, now - mostRecent);+ const recencyFactor = Math.pow(0.5, ageS / RECENCY_HALF_LIFE_S);+ return { id: 'direct-transfer', weight: 0.75 * Math.max(0.3, recencyFactor), evidence };+}++export function fundingBurst(a, b, ctx) {+ const bFunders = new Map();+ for (const t of b.transfers) {+ if (t.to === b.address && t.from && t.from !== a.address) bFunders.set(t.from, t);+ }+ for (const t of a.transfers) {+ if (t.to !== a.address || !t.from || t.from === b.address) continue;+ const match = bFunders.get(t.from);+ if (!match) continue;+ if (isHubOrExcluded(t.from, ctx)) continue;+ const dt = Math.abs((t.blockTime ?? 0) - (match.blockTime ?? 0));+ if (dt > BURST_WINDOW_S) continue;+ const ratio = t.amount > match.amount ? t.amount / match.amount : match.amount / t.amount;+ if (ratio > BURST_RATIO) continue;+ return {+ id: 'funding-burst',+ weight: 0.6,+ evidence: [+ {+ kind: 'funding_burst',+ account: t.from,+ signature: t.signature,+ detail: `${t.from} funded both ${a.address} (${t.amount} ${t.asset}) and ${b.address} (${match.amount} ${match.asset}) within ${Math.round(dt / 3600)}h`,+ },+ ],+ };+ }+ return null;+}++export const ALL_SIGNALS = [solanaAccountControl, solanaFeePayer, peerFirstFunding, commonFirstFunder, directTransfer, fundingBurst];++/**+ * Run every in-scope signal over one address pair. A single signal throwing+ * (a malformed bundle, an unexpected shape) never blocks the others: the+ * noisy-OR scorer degrades gracefully with fewer inputs instead of failing+ * the whole pair.+ */+export function runSignals(a, b, ctx) {+ const results = [];+ for (const signal of ALL_SIGNALS) {+ try {+ const r = signal(a, b, ctx);+ if (r) results.push(r);+ } catch {+ // See docstring above.+ }+ }+ return results;+}diff --git a/tests/wallet-linkage.test.js b/tests/wallet-linkage.test.jsnew file mode 100644index 000000000..dd9759d67--- /dev/null+++ b/tests/wallet-linkage.test.js@@ -0,0 +1,273 @@+// Unit tests for @three-ws/wallet-linkage: every fixture address below is a+// freshly generated Keypair with no real on-chain history (clearly synthetic,+// per CLAUDE.md), and the RPC client is an in-memory mock, never a live call.+import { describe, it, expect } from 'vitest';++import { analyzeLinkage, scorePair, bandFor, runSignals } from '../packages/wallet-linkage/src/index.js';++// Synthetic addresses (see header comment). Grouped by which scenario they feed.+const A = '4R2oiBtedGSybD1ydHJUuhR3f3xGhMDG1koKLvSoLkFE';+const B = 'AJWHsJ2Jf1uPCyRUWmLtMwKWPThTh6HqTtmhQSCbqHxz';+const C = 'E8wnGkdJ6Zhk685bsBszgBukDshyusgcfFnzWvfg6gLY';+const PAYER = '5Wi3E9FWx9xLFaBuyreTNo88KE3a9GLVTmVeQMFiA7uM';+const TOKENACC = 'Eikdxk12cSv37z8DNcmkVRNsW2s2guYcdZMT7eJZiyz8';+const XD = '39uzFU7hFMo4k5r18AsrGJYq69C7Ak8BRcj32QVCgjHf';+const XE = 'BrHXRgGn12G5kr2yUQy31BBVa6j473dfyU2xn1AkxKf6';+const FUNDER = '5xgS6r8RoHAVq7VdjdsPy2ewKHWhhweP8AiyiuJyy4Fy';+const XD_FIRST = 'G1VPwNMBYv7jGx78FuNsq9SiKYWiV7diPSfZKYGLkVca';+const XE_FIRST = '3wrkk9aQTVoW88pFVeKuRMbEMpzZzAnuhgttpBy6bAgm';+const P = '5m6YZJ1GnNQG9EYTQTZaLjQY5Bu4CHqvhLtjXjZQR8iH';+const Q = '8Un7Wo3GHpFBm5TbRx2T68PX3uqjNrrNF6jpLKZSrVYS';+const R = '2NjV3yypiWSxkLMmgTah9ffSw81atuxpXjY8FxeaYKW2';+const HUBX = 'BTkMFgjwubXkhq9RNtqAGbkho7bsyBnonqB2JKbHNw5W';+const S = 'CZz77skYYDfBL78CwKPZtsYuTBnQ4dXpYjFRceBDJGyd';+const T = 'F7TshAiAZfHBDTpDkVEPfRum1bybAY8yYSWzrZC6rjqG';+const U = '7K9CPT2uDrPkrR2CkETkdXz9L2MPwmEpbbBetNAjZd2s';+const V = 'E8wnGkdJ6Zhk685bsBszgBukDshyusgcfFnzWvfg6gLY'; // reuse C's key, unrelated to V's history in this file+const W = '3zxXkjgT9b57ZuZC1mE56xuoGAGk3vqnyqhEiywGyrB7';++function nativeIx(source, destination, sol) {+ return { program: 'system', programId: '11111111111111111111111111111111', parsed: { type: 'transfer', info: { source, destination, lamports: Math.round(sol * 1e9) } } };+}++function tx({ feePayer, otherKeys = [], blockTime, instructions }) {+ return {+ blockTime,+ transaction: { message: { accountKeys: [feePayer, ...otherKeys].map((k) => ({ pubkey: k })), instructions } },+ meta: { preTokenBalances: [], postTokenBalances: [] },+ };+}++/**+ * @param {Record<string,string[]>} signaturesByAddress+ * @param {Record<string, object>} txBySignature+ * @param {Record<string, object>} [accountInfoByAddress]+ */+function makeConnection(signaturesByAddress, txBySignature, accountInfoByAddress = {}) {+ return {+ async getSignaturesForAddress(pubkey) {+ const addr = pubkey.toBase58();+ return (signaturesByAddress[addr] || []).map((signature) => ({+ signature,+ blockTime: txBySignature[signature]?.blockTime ?? null,+ err: null,+ }));+ },+ async getParsedTransaction(signature) {+ return txBySignature[signature] ?? null;+ },+ async getAccountInfo(pubkey) {+ const addr = pubkey.toBase58();+ return accountInfoByAddress[addr] ?? null;+ },+ };+}++describe('score.js: noisy-OR combiner', () => {+ it('returns none/0 for no signals', () => {+ expect(scorePair([])).toEqual({ score: 0, band: 'none', topSignal: null, signals: [] });+ });++ it('combines two signals higher than either alone', () => {+ const solo = scorePair([{ id: 'x', weight: 0.6, evidence: [] }]);+ const combined = scorePair([+ { id: 'x', weight: 0.6, evidence: [] },+ { id: 'y', weight: 0.6, evidence: [] },+ ]);+ expect(combined.score).toBeGreaterThan(solo.score);+ // 1 - (1-0.6)(1-0.6) = 0.84+ expect(combined.score).toBe(84);+ });++ it('bands the score at the documented thresholds', () => {+ expect(bandFor(90)).toBe('confirmed');+ expect(bandFor(70)).toBe('strong');+ expect(bandFor(50)).toBe('moderate');+ expect(bandFor(25)).toBe('weak');+ expect(bandFor(5)).toBe('none');+ });+});++describe('analyzeLinkage: peer-first-funding + shared fee payer', () => {+ const sigFundAFromB = tx({ feePayer: B, otherKeys: [A], blockTime: 1000, instructions: [nativeIx(B, A, 1)] });+ const sigPayerToA = tx({ feePayer: PAYER, otherKeys: [A], blockTime: 2000, instructions: [nativeIx(PAYER, A, 0.0001)] });+ const sigPayerToB = tx({ feePayer: PAYER, otherKeys: [B], blockTime: 2000, instructions: [nativeIx(PAYER, B, 0.0001)] });++ const connection = makeConnection(+ {+ [A]: ['sig_fund_A_from_B', 'sig_payer_to_A'],+ [B]: ['sig_fund_A_from_B', 'sig_payer_to_B'],+ },+ {+ sig_fund_A_from_B: sigFundAFromB,+ sig_payer_to_A: sigPayerToA,+ sig_payer_to_B: sigPayerToB,+ },+ );++ it('scores the pair strong/confirmed with both signals as evidence', async () => {+ const result = await analyzeLinkage(connection, [A, B]);+ expect(result.complete).toBe(true);+ expect(result.pairs).toHaveLength(1);+ const pair = result.pairs[0];+ expect(pair.signals).toContain('peer-first-funding');+ expect(pair.signals).toContain('solana-fee-payer');+ expect(pair.score).toBeGreaterThanOrEqual(65);+ expect(['strong', 'confirmed']).toContain(pair.band);+ const feePayerEvidence = pair.evidence.find((s) => s.id === 'solana-fee-payer');+ expect(feePayerEvidence.evidence.some((e) => e.account === PAYER)).toBe(true);+ });+});++describe('analyzeLinkage: shared fee payer survives the REAL @solana/web3.js shape', () => {+ // Real `getParsedTransaction` wraps every `accountKeys[].pubkey` in a+ // PublicKey instance, not a plain string (the `tx()` helper above uses+ // plain strings, which is why the other fee-payer test cannot catch a+ // collector that forgets to call `.toBase58()`). This fixture mimics the+ // real shape with a minimal `{ toBase58() }` stand-in.+ const asPubkey = (addr) => ({ toBase58: () => addr });+ function realShapeTx({ feePayer, otherKeys = [], blockTime, instructions }) {+ return {+ blockTime,+ transaction: { message: { accountKeys: [feePayer, ...otherKeys].map((k) => ({ pubkey: asPubkey(k) })), instructions } },+ meta: { preTokenBalances: [], postTokenBalances: [] },+ };+ }++ const sigPayerToP = realShapeTx({ feePayer: PAYER, otherKeys: [P], blockTime: 3000, instructions: [nativeIx(PAYER, P, 0.01)] });+ const sigPayerToQ = realShapeTx({ feePayer: PAYER, otherKeys: [Q], blockTime: 3000, instructions: [nativeIx(PAYER, Q, 0.01)] });++ const connection = makeConnection(+ { [P]: ['sig_payer_to_p'], [Q]: ['sig_payer_to_q'] },+ { sig_payer_to_p: sigPayerToP, sig_payer_to_q: sigPayerToQ },+ );++ it('still finds the shared fee payer when accountKeys[].pubkey is a PublicKey-shaped object', async () => {+ const result = await analyzeLinkage(connection, [P, Q]);+ const pair = result.pairs[0];+ expect(pair.signals).toContain('solana-fee-payer');+ const evidence = pair.evidence.find((s) => s.id === 'solana-fee-payer');+ expect(evidence.evidence.some((e) => e.account === PAYER)).toBe(true);+ });+});++describe('analyzeLinkage: unrelated addresses score none', () => {+ const sigFundCFromFunder = tx({ feePayer: FUNDER, otherKeys: [C], blockTime: 500, instructions: [nativeIx(FUNDER, C, 2)] });+ const connection = makeConnection(+ { [A]: [], [C]: ['sig_fund_C'] },+ { sig_fund_C: sigFundCFromFunder },+ );++ it('finds no evidence and scores 0 / none', async () => {+ const result = await analyzeLinkage(connection, [A, C]);+ expect(result.pairs[0]).toMatchObject({ score: 0, band: 'none', signals: [] });+ });+});++describe('analyzeLinkage: solana-account-control via SPL token-account ownership', () => {+ const connection = makeConnection(+ { [TOKENACC]: [], [A]: [] },+ {},+ { [TOKENACC]: { value: { data: { parsed: { type: 'account', info: { owner: A } } } } } },+ );++ it('flags the token account as controlled by its owner', async () => {+ const result = await analyzeLinkage(connection, [TOKENACC, A]);+ const pair = result.pairs[0];+ expect(pair.signals).toEqual(['solana-account-control']);+ expect(pair.score).toBe(100);+ expect(pair.band).toBe('confirmed');+ });+});++describe('analyzeLinkage: funding-burst', () => {+ const sigXdFirst = tx({ feePayer: XD_FIRST, otherKeys: [XD], blockTime: 100, instructions: [nativeIx(XD_FIRST, XD, 5)] });+ const sigFunderToXd = tx({ feePayer: FUNDER, otherKeys: [XD], blockTime: 5000, instructions: [nativeIx(FUNDER, XD, 1.0)] });+ const sigXeFirst = tx({ feePayer: XE_FIRST, otherKeys: [XE], blockTime: 200, instructions: [nativeIx(XE_FIRST, XE, 3)] });+ const sigFunderToXe = tx({ feePayer: FUNDER, otherKeys: [XE], blockTime: 5200, instructions: [nativeIx(FUNDER, XE, 1.05)] });++ const connection = makeConnection(+ {+ [XD]: ['sig_xd_first', 'sig_funder_xd'],+ [XE]: ['sig_xe_first', 'sig_funder_xe'],+ },+ {+ sig_xd_first: sigXdFirst,+ sig_funder_xd: sigFunderToXd,+ sig_xe_first: sigXeFirst,+ sig_funder_xe: sigFunderToXe,+ },+ );++ it('flags a shared funder sending similar amounts within a short window, without tripping common-first-funder', async () => {+ const result = await analyzeLinkage(connection, [XD, XE]);+ const pair = result.pairs[0];+ expect(pair.signals).toContain('funding-burst');+ expect(pair.signals).not.toContain('common-first-funder');+ });+});++describe('analyzeLinkage: hub exclusion suppresses common-first-funder', () => {+ const mk = (addr, blockTime) => tx({ feePayer: HUBX, otherKeys: [addr], blockTime, instructions: [nativeIx(HUBX, addr, 0.5)] });++ const connection = makeConnection(+ { [P]: ['sig_p'], [Q]: ['sig_q'], [R]: ['sig_r'] },+ { sig_p: mk(P, 10), sig_q: mk(Q, 20), sig_r: mk(R, 30) },+ );++ it('does not treat a funder of 3+ requested addresses as a controller link', async () => {+ const result = await analyzeLinkage(connection, [P, Q, R]);+ for (const pair of result.pairs) {+ expect(pair.signals).not.toContain('common-first-funder');+ expect(pair.score).toBe(0);+ }+ });+});++describe('analyzeLinkage: common-first-funder fires for a non-hub shared funder', () => {+ const mk = (addr, blockTime) => tx({ feePayer: U, otherKeys: [addr], blockTime, instructions: [nativeIx(U, addr, 0.5)] });++ const connection = makeConnection(+ { [S]: ['sig_s'], [T]: ['sig_t'] },+ { sig_s: mk(S, 10), sig_t: mk(T, 20) },+ );++ it('flags two addresses first funded by the same non-hub third party', async () => {+ const result = await analyzeLinkage(connection, [S, T]);+ const pair = result.pairs[0];+ expect(pair.signals).toContain('common-first-funder');+ const ev = pair.evidence.find((s) => s.id === 'common-first-funder');+ expect(ev.evidence[0].account).toBe(U);+ });+});++describe('analyzeLinkage: direct transfer between the pair', () => {+ const sigVFirst = tx({ feePayer: W, otherKeys: [V], blockTime: 50, instructions: [nativeIx(W, V, 4)] });+ const sigDirect = tx({ feePayer: V, otherKeys: [W], blockTime: 90, instructions: [nativeIx(V, W, 2)] });++ const connection = makeConnection(+ { [V]: ['sig_v_first', 'sig_direct'], [W]: ['sig_direct'] },+ { sig_v_first: sigVFirst, sig_direct: sigDirect },+ );++ it('flags value moved directly between the two addresses', async () => {+ const result = await analyzeLinkage(connection, [V, W]);+ const pair = result.pairs[0];+ expect(pair.signals).toContain('direct-transfer');+ const ev = pair.evidence.find((s) => s.id === 'direct-transfer');+ expect(ev.evidence[0].detail).toContain('2 SOL');+ });+});++describe('analyzeLinkage: input validation', () => {+ it('rejects fewer than 2 addresses', async () => {+ await expect(analyzeLinkage(makeConnection({}, {}), [A])).rejects.toThrow();+ });+});++describe('runSignals', () => {+ it('never throws even when a bundle is missing expected shape', () => {+ const broken = { address: A, transfers: [], payers: new Set(), firstInbound: null, facts: {}, rentPayer: null };+ expect(() => runSignals(broken, broken, { exclusions: new Set(), sharedBy: new Map() })).not.toThrow();+ });+});