chain-insights 0.85.2 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -0
  2. package/bin/install.cjs +2 -1
  3. package/dist/{active-q3yViZhc.cjs → active-COPA14FA.cjs} +2 -16
  4. package/dist/{active-D2aabYRF.mjs → active-CyC4jFka.mjs} +2 -7
  5. package/dist/{active-D2aabYRF.mjs.map → active-CyC4jFka.mjs.map} +1 -1
  6. package/dist/address-card-C-NB03XP.cjs +218 -0
  7. package/dist/address-card-LYaT5yz0.mjs +190 -0
  8. package/dist/address-card-LYaT5yz0.mjs.map +1 -0
  9. package/dist/address-risk-DPuXBsvH.cjs +806 -0
  10. package/dist/address-risk-Da6FsfGx.mjs +653 -0
  11. package/dist/address-risk-Da6FsfGx.mjs.map +1 -0
  12. package/dist/{capabilities-Mxa4oQdd.cjs → capabilities-DkNreyv7.cjs} +1 -1
  13. package/dist/{capabilities-bZOr5Ads.mjs → capabilities-w5bNR7F9.mjs} +2 -2
  14. package/dist/{capabilities-bZOr5Ads.mjs.map → capabilities-w5bNR7F9.mjs.map} +1 -1
  15. package/dist/cli.cjs +138 -46
  16. package/dist/cli.mjs +138 -46
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/{deployer-screen-B5yrXZGo.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-B5yrXZGo.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-0SOQ_HFf.cjs → deployer-screen-CFLi7OeH.cjs} +2 -2
  21. package/dist/{dex-registry-BY67f4Ul.mjs → dex-registry-Bkri0--q.mjs} +10 -2
  22. package/dist/{dex-registry-BY67f4Ul.mjs.map → dex-registry-Bkri0--q.mjs.map} +1 -1
  23. package/dist/{dex-registry-BhGJUG9_.cjs → dex-registry-CyR3GyRr.cjs} +20 -0
  24. package/dist/{dex-tool-7BK_gD6H.mjs → dex-tool-D0K_Qx4N.mjs} +4 -4
  25. package/dist/dex-tool-D0K_Qx4N.mjs.map +1 -0
  26. package/dist/{dex-tool-Be9NAuD8.cjs → dex-tool-DQ5Eg0LO.cjs} +3 -3
  27. package/dist/{exchange-deposit-check-C5MseGlZ.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CXHZCHWW.mjs → exchange-deposit-check-DIALj2sm.mjs} +19 -19
  29. package/dist/exchange-deposit-check-DIALj2sm.mjs.map +1 -0
  30. package/dist/{exchange-registry-CT0rRW__.cjs → exchange-registry-CEgkeQV1.cjs} +16 -93
  31. package/dist/{exchange-registry-CoLgHw6d.mjs → exchange-registry-Dr5UtcT5.mjs} +17 -94
  32. package/dist/exchange-registry-Dr5UtcT5.mjs.map +1 -0
  33. package/dist/{exchange-tool-Dc46SJ49.mjs → exchange-tool-B7E29YoQ.mjs} +4 -4
  34. package/dist/exchange-tool-B7E29YoQ.mjs.map +1 -0
  35. package/dist/{exchange-tool-B2SMeC5f.cjs → exchange-tool-CXaUBAd2.cjs} +3 -3
  36. package/dist/{graph-schema-CcrYPpSv.cjs → graph-schema-Bn3txQCj.cjs} +115 -12
  37. package/dist/{graph-schema-CRQuKya1.mjs → graph-schema-DvABR1yl.mjs} +97 -12
  38. package/dist/graph-schema-DvABR1yl.mjs.map +1 -0
  39. package/dist/{layer-routing-YDj-ynG9.cjs → layer-routing-j48SQ8Wk.cjs} +2 -2
  40. package/dist/{layer-routing-DCJVNN6O.mjs → layer-routing-r4IbIQSr.mjs} +3 -3
  41. package/dist/layer-routing-r4IbIQSr.mjs.map +1 -0
  42. package/dist/mcp-proxy.cjs +62 -15
  43. package/dist/mcp-proxy.d.cts.map +1 -1
  44. package/dist/mcp-proxy.d.mts.map +1 -1
  45. package/dist/mcp-proxy.mjs +62 -15
  46. package/dist/mcp-proxy.mjs.map +1 -1
  47. package/dist/public-file-BISyAesm.mjs +133 -0
  48. package/dist/public-file-BISyAesm.mjs.map +1 -0
  49. package/dist/public-file-DDp2CrUl.cjs +138 -0
  50. package/dist/{request-timeout-DxwNijQD.cjs → request-timeout-BXiIt9Jy.cjs} +0 -1
  51. package/dist/{request-timeout-K3ljP0pa.mjs → request-timeout-DetG2xO4.mjs} +2 -2
  52. package/dist/{request-timeout-K3ljP0pa.mjs.map → request-timeout-DetG2xO4.mjs.map} +1 -1
  53. package/dist/{token-lookup-Cf59VdGe.mjs → token-lookup-Ck0q7crJ.mjs} +2 -2
  54. package/dist/{token-lookup-Cf59VdGe.mjs.map → token-lookup-Ck0q7crJ.mjs.map} +1 -1
  55. package/dist/{token-lookup-DqjSRIxd.cjs → token-lookup-DLe4erP9.cjs} +1 -1
  56. package/dist/token-risk-CpMfFRoY.cjs +1004 -0
  57. package/dist/token-risk-DhnJc2kJ.mjs +971 -0
  58. package/dist/token-risk-DhnJc2kJ.mjs.map +1 -0
  59. package/dist/{tool-visibility-D8Up081E.cjs → tool-visibility-BCa-tmyZ.cjs} +11 -2
  60. package/dist/{tool-visibility-DuTds7V4.mjs → tool-visibility-BstrSl4s.mjs} +12 -3
  61. package/dist/tool-visibility-BstrSl4s.mjs.map +1 -0
  62. package/docs/contributing.md +10 -8
  63. package/docs/development.md +5 -5
  64. package/docs/evals.md +16 -1
  65. package/docs/graph-query-compatibility.md +15 -2
  66. package/docs/graph-tools.md +44 -6
  67. package/docs/mcp-proxy.md +189 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +76 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +680 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +61 -0
  74. package/skills/chain-insights-address-risk/agents/openai.yaml +4 -0
  75. package/skills/chain-insights-aml-exchange/SKILL.md +9 -7
  76. package/skills/chain-insights-cypher/SKILL.md +79 -3
  77. package/skills/chain-insights-token-risk/SKILL.md +81 -0
  78. package/skills/chain-insights-token-risk/agents/openai.yaml +4 -0
  79. package/skills/chain-insights-virtuals/reference.md +1 -1
  80. package/dist/dex-tool-7BK_gD6H.mjs.map +0 -1
  81. package/dist/exchange-deposit-check-CXHZCHWW.mjs.map +0 -1
  82. package/dist/exchange-registry-CoLgHw6d.mjs.map +0 -1
  83. package/dist/exchange-tool-Dc46SJ49.mjs.map +0 -1
  84. package/dist/graph-schema-CRQuKya1.mjs.map +0 -1
  85. package/dist/layer-routing-DCJVNN6O.mjs.map +0 -1
  86. package/dist/public-tools-CBszU2oX.cjs +0 -1334
  87. package/dist/public-tools-DVhUjSDV.mjs +0 -1333
  88. package/dist/public-tools-DVhUjSDV.mjs.map +0 -1
  89. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"exchange-registry-CoLgHw6d.mjs","names":[],"sources":["../src/mcp/exchange-registry.ts"],"sourcesContent":["/**\n * The centralized exchange lookup, as meta_exchange_lookup and\n * aml_exchange_deposit_check read it.\n *\n * registry/exchanges/<network>.json lists every centralized exchange the\n * indexer-evm-cex registry of the network names, with its id, its display name\n * and its aliases, and under each only the wallets proven on that network's\n * own data: hot wallets that receive the sweeps of its deposits, gas wallets\n * that top deposits up, and spenders that pull approved deposits. Each wallet\n * carries the payer proof and the block it was proven at, always above 0. An\n * exchange tag, or a wallet of another network at the same address, never\n * enters the file: it stays in the indexer's registry and reaches the graph.\n * So an exchange may list no wallet; its deposits, its SWEPT links and its\n * hot wallets are read from the graph (aml_exchange_deposit_check). It is\n * written by scripts/pin-exchange-registry.mjs and held to the rules below by\n * tests/exchange-registry.test.ts.\n *\n * The proxy reads the file as it reads the DEX registry (src/mcp/dex-registry.ts):\n *\n * cached ~/.chain-insights/cache/exchange-registry-<network>.json, younger than one hour\n * fetched the copy on main, https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/exchanges/<network>.json,\n * within 3 s, at most once an hour per network\n * packaged registry/exchanges/<network>.json of the installed package\n *\n * A fetched file is used only when it passes the rules. A row merged on main\n * reaches every running proxy within the hour, with no release. A lookup is a\n * proxy tool and never a table or a graph property.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { chainInsightsHome } from './cache-location.js'\nimport {\n DEX_REGISTRY_FETCH_BUDGET_MS,\n DEX_REGISTRY_TTL_MS,\n NEAR_DISTANCE,\n NEAR_MIN_ALIAS_LENGTH,\n damerauLevenshtein,\n normalizeDexNetwork,\n normaliseName,\n} from './dex-registry.js'\n\nexport const EXCHANGE_REGISTRY_SCHEMA = 'chain-insights.exchange-registry.v1' as const\nexport const EXCHANGE_REGISTRY_URL_ENV = 'CHAIN_INSIGHTS_EXCHANGE_REGISTRY_URL'\nexport const EXCHANGE_REGISTRY_PUBLIC_URL =\n 'https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/exchanges/{network}.json'\n\nexport const WALLET_ROLES = ['hot_wallet', 'gas_wallet', 'spender'] as const\nexport type WalletRole = (typeof WALLET_ROLES)[number]\nexport type ExchangeRegistrySource = 'fetched' | 'cached' | 'packaged' | 'none'\n\n/** One wallet of an exchange, with its evidence. */\nexport interface ExchangeWallet {\n address: string\n role: WalletRole\n /** What the chain showed: payers, the sample that pays only this exchange, the window. */\n evidence: string\n /** The block the payer proof is pinned at, always above 0. */\n proven_at_block: number\n}\n\n/** One exchange of the lookup file. */\nexport interface ExchangeEntry {\n /** The stable lower-case id, the word the graph's labels carry. */\n exchange: string\n display: string\n aliases: string[]\n wallets: ExchangeWallet[]\n}\n\nexport interface ExchangeRegistryDocument {\n schema: typeof EXCHANGE_REGISTRY_SCHEMA\n network: string\n registry_version: number\n recorded_on: string\n rows: ExchangeEntry[]\n}\n\nexport interface LoadedExchangeRegistry {\n document: ExchangeRegistryDocument\n source: ExchangeRegistrySource\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/\nconst EXCHANGE_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst isStringList = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((entry) => typeof entry === 'string')\n\n/** The fault of a lookup file, or null when it is valid for the network. */\nexport function exchangeRegistryFault(value: unknown, network: string): string | null {\n if (!isRecord(value)) return 'the file is not a JSON object'\n if (value.schema !== EXCHANGE_REGISTRY_SCHEMA) {\n return `schema is ${JSON.stringify(value.schema)}, not ${EXCHANGE_REGISTRY_SCHEMA}`\n }\n if (value.network !== network)\n return `network is ${JSON.stringify(value.network)}, not ${network}`\n if (!Number.isInteger(value.registry_version) || (value.registry_version as number) < 0) {\n return 'registry_version is not a whole number'\n }\n if (typeof value.recorded_on !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}$/.test(value.recorded_on)) {\n return 'recorded_on is not a YYYY-MM-DD day'\n }\n if (!Array.isArray(value.rows) || value.rows.length === 0) return 'rows is empty'\n const ids = new Set<string>()\n const owners = new Map<string, string>()\n for (const [index, row] of value.rows.entries()) {\n const at = `rows[${index}]`\n if (!isRecord(row)) return `${at} is not an object`\n if (typeof row.exchange !== 'string' || !EXCHANGE_RE.test(row.exchange))\n return `${at}.exchange is not an id: ${String(row.exchange)}`\n if (ids.has(row.exchange)) return `${at}.exchange ${row.exchange} is listed twice`\n ids.add(row.exchange)\n if (typeof row.display !== 'string' || row.display.trim() === '')\n return `${at} (${row.exchange}) has no display`\n if (!isStringList(row.aliases)) return `${at} (${row.exchange}) aliases is not a list of names`\n if (!Array.isArray(row.wallets)) return `${at} (${row.exchange}) wallets is not a list`\n for (const wallet of row.wallets) {\n if (!isRecord(wallet)) return `${at} (${row.exchange}) has a wallet that is not an object`\n const address = wallet.address\n if (typeof address !== 'string' || !ADDRESS_RE.test(address))\n return `${at} (${row.exchange}) address ${String(address)} is not lowercase 0x plus 40 hex characters`\n if (!WALLET_ROLES.includes(wallet.role as WalletRole))\n return `${at} (${row.exchange}) role ${String(wallet.role)} is not hot_wallet, gas_wallet or spender`\n if (typeof wallet.evidence !== 'string' || wallet.evidence.trim() === '')\n return `${at} (${row.exchange}) ${address} has no evidence`\n if (!Number.isInteger(wallet.proven_at_block) || (wallet.proven_at_block as number) <= 0)\n return `${at} (${row.exchange}) ${address} proven_at_block is not a block above 0: only a wallet proven on this chain is listed`\n const owner = owners.get(address)\n if (owner !== undefined)\n return `${at} (${row.exchange}) ${address} is also a wallet of ${owner}`\n owners.set(address, row.exchange)\n }\n }\n return null\n}\n\n/** The URL of the served copy: the public file on main, or the override with {network} filled in. */\nexport function exchangeRegistryUrl(network: string, env: NodeJS.ProcessEnv = process.env): string {\n const override = env[EXCHANGE_REGISTRY_URL_ENV]?.trim()\n const template = override || EXCHANGE_REGISTRY_PUBLIC_URL\n if (template.includes('{network}')) return template.replaceAll('{network}', network)\n return template.endsWith('/') ? `${template}${network}.json` : template\n}\n\nexport function exchangeRegistryCachePath(network: string): string {\n return path.join(chainInsightsHome(), 'cache', `exchange-registry-${network}.json`)\n}\n\n/** registry/exchanges of the installed package: next to dist/, or the repository root when run from source. */\nexport function packagedExchangeRegistryDir(): string {\n const candidates = [\n fileURLToPath(new URL('../registry/exchanges', import.meta.url)),\n fileURLToPath(new URL('../../registry/exchanges', import.meta.url)),\n ]\n return (\n candidates.find((candidate) => existsSync(path.join(candidate, 'robinhood.json'))) ??\n candidates[0]!\n )\n}\n\n/** The packaged copy of a network, or null when the package carries none. A packaged copy that fails the rules throws. */\nexport function readPackagedExchangeRegistry(\n network: string,\n dir: string = packagedExchangeRegistryDir()\n): ExchangeRegistryDocument | null {\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(path.join(dir, `${network}.json`), 'utf8'))\n } catch {\n return null\n }\n const fault = exchangeRegistryFault(parsed, network)\n if (fault)\n throw new Error(\n `the packaged exchange lookup registry/exchanges/${network}.json is malformed: ${fault}`\n )\n return parsed as ExchangeRegistryDocument\n}\n\ninterface CacheFile {\n document: ExchangeRegistryDocument\n checked_at_ms: number\n source: 'fetched' | 'packaged'\n}\n\nasync function readCache(network: string): Promise<CacheFile | null> {\n try {\n const parsed = JSON.parse(await readFile(exchangeRegistryCachePath(network), 'utf8')) as unknown\n if (!isRecord(parsed) || typeof parsed.checked_at_ms !== 'number') return null\n if (parsed.source !== 'fetched' && parsed.source !== 'packaged') return null\n if (exchangeRegistryFault(parsed.document, network) !== null) return null\n return parsed as unknown as CacheFile\n } catch {\n return null\n }\n}\n\nasync function writeCache(network: string, file: CacheFile): Promise<void> {\n const target = exchangeRegistryCachePath(network)\n await mkdir(path.dirname(target), { recursive: true })\n const scratch = `${target}.${process.pid}.tmp`\n await writeFile(scratch, JSON.stringify(file, null, 2) + '\\n', { mode: 0o600 })\n await rename(scratch, target)\n}\n\nexport interface LoadExchangeRegistryOptions {\n fetch?: typeof fetch\n now?: () => number\n env?: NodeJS.ProcessEnv\n log?: (line: string) => void\n packagedDir?: string\n budgetMs?: number\n}\n\nasync function fetchDocument(\n network: string,\n options: LoadExchangeRegistryOptions\n): Promise<{ document: ExchangeRegistryDocument } | { fault: string }> {\n const url = exchangeRegistryUrl(network, options.env)\n let response: Response\n try {\n response = await (options.fetch ?? fetch)(url, {\n signal: AbortSignal.timeout(options.budgetMs ?? DEX_REGISTRY_FETCH_BUDGET_MS),\n })\n } catch (err) {\n return { fault: `${url} unreachable: ${err instanceof Error ? err.message : String(err)}` }\n }\n if (response.status !== 200) return { fault: `${url} answered HTTP ${response.status}` }\n let parsed: unknown\n try {\n parsed = JSON.parse(await response.text())\n } catch {\n return { fault: `${url} is not JSON` }\n }\n const fault = exchangeRegistryFault(parsed, network)\n return fault\n ? { fault: `${url} is malformed: ${fault}` }\n : { document: parsed as ExchangeRegistryDocument }\n}\n\n/** A network with no file: no rows, so every lookup on it answers with an empty list. */\nfunction emptyDocument(network: string): ExchangeRegistryDocument {\n return {\n schema: EXCHANGE_REGISTRY_SCHEMA,\n network,\n registry_version: 0,\n recorded_on: '1970-01-01',\n rows: [],\n }\n}\n\nconst defaultLog = (line: string): void => {\n process.stderr.write(`[chain-insights] exchange-registry: ${line}\\n`)\n}\n\n/**\n * The lookup file of one network: the fresh cache, else the public file, else\n * the stale cache, else the packaged copy. A packaged copy with a higher\n * version than the cache or the public file wins. A network with no file\n * anywhere answers with no rows; it never throws for a well-formed network.\n */\nexport async function loadExchangeRegistry(\n rawNetwork: unknown,\n options: LoadExchangeRegistryOptions = {}\n): Promise<LoadedExchangeRegistry> {\n const network = normalizeDexNetwork(rawNetwork)\n const now = options.now ?? Date.now\n const log = options.log ?? defaultLog\n const packaged = readPackagedExchangeRegistry(network, options.packagedDir)\n const pick = (\n document: ExchangeRegistryDocument,\n source: ExchangeRegistrySource\n ): LoadedExchangeRegistry =>\n packaged !== null && packaged.registry_version > document.registry_version\n ? { document: packaged, source: 'packaged' }\n : { document, source }\n\n const cache = await readCache(network)\n const age = cache ? now() - cache.checked_at_ms : Infinity\n if (cache && age >= 0 && age < DEX_REGISTRY_TTL_MS) {\n return pick(cache.document, cache.source === 'fetched' ? 'cached' : 'packaged')\n }\n const save = async (file: CacheFile): Promise<void> => {\n try {\n await writeCache(network, file)\n } catch (err) {\n log(\n `the cache ${exchangeRegistryCachePath(network)} could not be written: ${err instanceof Error ? err.message : String(err)}`\n )\n }\n }\n const outcome = await fetchDocument(network, options)\n const checked = now()\n if ('document' in outcome) {\n await save({ document: outcome.document, checked_at_ms: checked, source: 'fetched' })\n return pick(outcome.document, 'fetched')\n }\n if (cache) {\n log(outcome.fault)\n await save({ ...cache, checked_at_ms: checked })\n return pick(cache.document, cache.source === 'fetched' ? 'cached' : 'packaged')\n }\n if (packaged) {\n log(outcome.fault)\n await save({ document: packaged, checked_at_ms: checked, source: 'packaged' })\n return { document: packaged, source: 'packaged' }\n }\n return { document: emptyDocument(network), source: 'none' }\n}\n\n// ─── The name and the address match ───────────────────────────────────────────\n\nexport interface ExchangeCandidate {\n exchange: string\n display: string\n distance: number\n}\n\nexport interface ExchangeMatchResult {\n matched: ExchangeEntry | null\n /** The name as typed, when the match is a near hit. */\n took_for?: string\n candidates: ExchangeCandidate[]\n /** Every exchange the file lists for the network, by display name. */\n listed: string[]\n}\n\n/**\n * One name against the rows, as matchDex does for a DEX: exact on the id, the\n * display and the aliases; then within two letters of an alias of four or more\n * characters. A tie is listed, never guessed.\n */\nexport function matchExchange(name: string, rows: ExchangeEntry[]): ExchangeMatchResult {\n const listed = rows.map((row) => row.display)\n const wanted = normaliseName(name)\n if (!wanted) return { matched: null, candidates: [], listed }\n const exact = rows.filter((row) =>\n [row.exchange, row.display, ...row.aliases].some((written) => normaliseName(written) === wanted)\n )\n if (exact.length === 1) return { matched: exact[0]!, candidates: [], listed }\n if (exact.length > 1) {\n return {\n matched: null,\n candidates: exact.map((row) => ({\n exchange: row.exchange,\n display: row.display,\n distance: 0,\n })),\n listed,\n }\n }\n const near: Array<{ row: ExchangeEntry; distance: number }> = []\n for (const row of rows) {\n const distances = [row.exchange, row.display, ...row.aliases]\n .map(normaliseName)\n .filter((alias) => alias.length >= NEAR_MIN_ALIAS_LENGTH)\n .map((alias) => damerauLevenshtein(wanted, alias))\n if (distances.length === 0) continue\n const distance = Math.min(...distances)\n if (distance <= NEAR_DISTANCE) near.push({ row, distance })\n }\n if (near.length === 0) return { matched: null, candidates: [], listed }\n const least = Math.min(...near.map((hit) => hit.distance))\n const nearest = near.filter((hit) => hit.distance === least)\n if (nearest.length === 1)\n return { matched: nearest[0]!.row, took_for: name.trim(), candidates: [], listed }\n return {\n matched: null,\n candidates: nearest.map(({ row, distance }) => ({\n exchange: row.exchange,\n display: row.display,\n distance,\n })),\n listed,\n }\n}\n\n/** The exchange and the wallet a lowercase address is, or null when no row lists it. */\nexport function exchangeOfWallet(\n address: string,\n rows: ExchangeEntry[]\n): { entry: ExchangeEntry; wallet: ExchangeWallet } | null {\n for (const entry of rows) {\n const wallet = entry.wallets.find((candidate) => candidate.address === address)\n if (wallet) return { entry, wallet }\n }\n return null\n}\n\n/** The exchange a list of graph label words names, or null: the first word that is an id, a display name or an alias. */\nexport function exchangeOfLabels(\n labels: readonly string[],\n rows: ExchangeEntry[]\n): ExchangeEntry | null {\n for (const word of labels) {\n const wanted = normaliseName(word)\n if (!wanted) continue\n const row = rows.find((entry) =>\n [entry.exchange, entry.display, ...entry.aliases].some(\n (name) => normaliseName(name) === wanted\n )\n )\n if (row) return row\n }\n return null\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,2BAA2B;AACxC,MAAa,4BAA4B;AACzC,MAAa,+BACX;AAEF,MAAa,eAAe;CAAC;CAAc;CAAc;AAAS;AAoClE,MAAM,aAAa;AACnB,MAAM,cAAc;AAEpB,SAAS,SAAS,OAAkD;CAClE,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE;AAEA,MAAM,gBAAgB,UACpB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ;;AAG1E,SAAgB,sBAAsB,OAAgB,SAAgC;CACpF,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,IAAI,MAAM,WAAW,0BACnB,OAAO,aAAa,KAAK,UAAU,MAAM,MAAM,EAAE,QAAQ;CAE3D,IAAI,MAAM,YAAY,SACpB,OAAO,cAAc,KAAK,UAAU,MAAM,OAAO,EAAE,QAAQ;CAC7D,IAAI,CAAC,OAAO,UAAU,MAAM,gBAAgB,KAAM,MAAM,mBAA8B,GACpF,OAAO;CAET,IAAI,OAAO,MAAM,gBAAgB,YAAY,CAAC,sBAAsB,KAAK,MAAM,WAAW,GACxF,OAAO;CAET,IAAI,CAAC,MAAM,QAAQ,MAAM,IAAI,KAAK,MAAM,KAAK,WAAW,GAAG,OAAO;CAClE,MAAM,sBAAM,IAAI,IAAY;CAC5B,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,CAAC,OAAO,QAAQ,MAAM,KAAK,QAAQ,GAAG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MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,aAAa,KAAK;CAC3D,IAAI,QAAQ,WAAW,GACrB,OAAO;EAAE,SAAS,QAAQ,EAAE,CAAE;EAAK,UAAU,KAAK,KAAK;EAAG,YAAY,CAAC;EAAG;CAAO;CACnF,OAAO;EACL,SAAS;EACT,YAAY,QAAQ,KAAK,EAAE,KAAK,gBAAgB;GAC9C,UAAU,IAAI;GACd,SAAS,IAAI;GACb;EACF,EAAE;EACF;CACF;AACF;;AAGA,SAAgB,iBACd,SACA,MACyD;CACzD,KAAK,MAAM,SAAS,MAAM;EACxB,MAAM,SAAS,MAAM,QAAQ,MAAM,cAAc,UAAU,YAAY,OAAO;EAC9E,IAAI,QAAQ,OAAO;GAAE;GAAO;EAAO;CACrC;CACA,OAAO;AACT;;AAGA,SAAgB,iBACd,QACA,MACsB;CACtB,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,SAAS,cAAc,IAAI;EACjC,IAAI,CAAC,QAAQ;EACb,MAAM,MAAM,KAAK,MAAM,UACrB;GAAC,MAAM;GAAU,MAAM;GAAS,GAAG,MAAM;EAAO,CAAC,CAAC,MAC/C,SAAS,cAAc,IAAI,MAAM,MACpC,CACF;EACA,IAAI,KAAK,OAAO;CAClB;CACA,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"exchange-tool-Dc46SJ49.mjs","names":[],"sources":["../src/mcp/exchange-tool.ts"],"sourcesContent":["/**\n * meta_exchange_lookup: a centralized exchange's name becomes its wallets.\n *\n * A local tool of the proxy. It matches the name against the exchange lookup\n * file (src/mcp/exchange-registry.ts) and answers from it alone: no graph read,\n * no cost. The file lists every exchange, and only the wallets proven on that\n * network's own data, each with its payer proof and the block it was proven\n * at. An address instead of a name says whose wallet the address is. Whether\n * an address is a deposit, and which hot wallet it swept into, is read from\n * the graph by aml_exchange_deposit_check.\n *\n * The description below is the contract with every host, Claude Desktop chat\n * included, which reads no skill: it carries the rule the skill\n * chain-insights-aml-exchange opens with. tests/host-parity.test.ts holds it to\n * the skill's trigger words.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport {\n exchangeOfWallet,\n matchExchange,\n type ExchangeCandidate,\n type ExchangeEntry,\n type ExchangeRegistrySource,\n type ExchangeWallet,\n type LoadedExchangeRegistry,\n} from './exchange-registry.js'\n\n/**\n * The rule the exchange skill opens with, carried by both of its doors: where a\n * trail ends, and where an exchange's wallets come from.\n */\nexport const EXCHANGE_OPENING_RULE =\n 'Money that reaches an exchange deposit with a SWEPT link entered that exchange there: the trail ends at the deposit, and never walks on past a hot wallet. ' +\n \"Take an exchange's wallets from meta_exchange_lookup, never from a guess or a graph search by name.\"\n\nexport const META_EXCHANGE_LOOKUP_TOOL = 'meta_exchange_lookup' as const\nexport const META_EXCHANGE_LOOKUP_SCHEMA = 'chain-insights.meta-exchange-lookup.v1' as const\nexport const META_EXCHANGE_LOOKUP_TITLE = 'Centralized exchange by name or address'\nexport const META_EXCHANGE_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...) ' +\n 'and gives no address, or asks which exchange a wallet belongs to. It turns the name into the hot wallets of that exchange on the network, ' +\n \"The file lists only wallets proven on that chain's own data, each with its payer proof and the block it was proven at, and its gas wallets; \" +\n 'an exchange may list none, and its deposits and hot wallets are still marked in the graph. ' +\n 'A misspelling within two letters is taken and named in took_for. Send address instead (0x plus 40 hex, any case) to learn whose hot wallet ' +\n 'or gas wallet it is. It reads no graph and costs nothing. ' +\n `${EXCHANGE_OPENING_RULE} Give a name or an address, not both.`\nexport const META_EXCHANGE_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_EXCHANGE_LOOKUP_ARGS = ['network', 'name', 'address'] as const\n\nexport type WalletRow = Omit<ExchangeWallet, 'role'>\n\nexport interface ExchangeMatch {\n exchange: string\n display: string\n hot_wallets: WalletRow[]\n gas_wallets: WalletRow[]\n spenders: WalletRow[]\n}\n\nexport interface ListedExchange {\n exchange: string\n display: string\n hot_wallets: number\n}\n\nexport interface MetaExchangeLookupResult {\n schema: typeof META_EXCHANGE_LOOKUP_SCHEMA\n network: string\n registry_version: number\n registry_source: ExchangeRegistrySource\n recorded_on: string\n matched: ExchangeMatch | null\n /** A near name hit: the name as typed. An address hit: the role the address holds. */\n took_for?: string\n candidates: ExchangeCandidate[]\n /** Every exchange the lookup lists for the network, by display name. */\n listed: string[]\n /** With no name and no address: every listed exchange, with its id and its hot wallet count. */\n exchanges?: ListedExchange[]\n hint: string\n}\n\nexport interface ExchangeToolDependencies {\n loadExchangeRegistry: (network: string) => Promise<LoadedExchangeRegistry>\n}\n\nexport type MetaExchangeLookupToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorResult(text: string): MetaExchangeLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: MetaExchangeLookupResult): MetaExchangeLookupToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],\n structuredContent: structured as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\n\nfunction walletsOf(entry: ExchangeEntry, role: ExchangeWallet['role']): WalletRow[] {\n return entry.wallets\n .filter((wallet) => wallet.role === role)\n .map(({ address, evidence, proven_at_block }) => ({ address, evidence, proven_at_block }))\n}\n\n/** One row of the lookup as the tool returns it. */\nexport function exchangeMatchOf(entry: ExchangeEntry): ExchangeMatch {\n return {\n exchange: entry.exchange,\n display: entry.display,\n hot_wallets: walletsOf(entry, 'hot_wallet'),\n gas_wallets: walletsOf(entry, 'gas_wallet'),\n spenders: walletsOf(entry, 'spender'),\n }\n}\n\nconst ROLE_WORDS: Record<ExchangeWallet['role'], string> = {\n hot_wallet: 'a hot wallet',\n gas_wallet: 'a gas wallet',\n spender: 'a spender',\n}\n\nconst NO_SEARCH_BY_NAME = 'Send no graph search by name.'\n\nfunction hintFor(\n result: Omit<MetaExchangeLookupResult, 'hint'>,\n name: string | null,\n address: string | null\n): string {\n const { network } = result\n if (address !== null && !result.matched) {\n return (\n `${ANSWER_HINT} ${address} is no wallet the exchange lookup lists for ${network}: the file lists only wallets proven on this chain. ` +\n `The graph marks deposits and hot wallets of every exchange: call aml_exchange_deposit_check {network: \"${network}\", address: \"${address}\"} ` +\n 'to read its cex_role, its exchange and its SWEPT links.'\n )\n }\n if (address !== null && result.matched) {\n return (\n `${ANSWER_HINT} Say in one line: \"${address} is ${result.took_for} of ${result.matched.display} on ${network}.\" ` +\n 'A trail that reaches it has entered the exchange: end the trail there. Never walk on past a hot wallet.'\n )\n }\n if (name === null) {\n return `${ANSWER_HINT} These are the exchanges the lookup lists for ${network}. Call meta_exchange_lookup with a name for its wallets.`\n }\n if (result.matched) {\n const { matched } = result\n const took = result.took_for\n ? `Say in one line: \"I took ${matched.display} for ${result.took_for}.\" Ask nothing. `\n : ''\n const count = matched.hot_wallets.length\n const wallets =\n count === 0\n ? `${matched.display} on ${network}: the lookup lists no wallet of it proven on this chain yet; the graph marks its deposits and hot wallets. `\n : `${matched.display} on ${network}: ${count} hot wallet${count === 1 ? '' : 's'} proven on this chain. `\n return (\n `${ANSWER_HINT} ${took}${wallets}` +\n 'A deposit of this exchange has a SWEPT link into its hot wallet. Read SWEPT anchored on the address the trail reached, never on a hot wallet: ' +\n 'a hot wallet links to many thousands of deposits. To check one address, call aml_exchange_deposit_check. ' +\n `${EXCHANGE_OPENING_RULE}`\n )\n }\n if (result.candidates.length > 0) {\n const names = result.candidates\n .map((candidate) => `${candidate.display} (${candidate.exchange})`)\n .join(', ')\n return `${ANSWER_HINT} ${result.candidates.length} exchanges fit \"${name}\": ${names}. Name both or pick one: call meta_exchange_lookup with each id. Never guess one.`\n }\n return (\n `${ANSWER_HINT} The exchange lookup holds no wallet of \"${name}\" for ${network}` +\n (result.listed.length > 0 ? `; it lists ${result.listed.join(', ')}. ` : '. ') +\n 'If the user knows one address of that exchange (a deposit address, or a wallet it paid them from), call aml_exchange_deposit_check with it. ' +\n NO_SEARCH_BY_NAME\n )\n}\n\n/** meta_exchange_lookup, {network, name?, address?}. Every argument is checked before the lookup is read. */\nexport async function handleMetaExchangeLookup(\n args: unknown,\n deps: ExchangeToolDependencies\n): Promise<MetaExchangeLookupToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult((err as Error).message)\n }\n const rawName = record.name\n if (rawName !== undefined && rawName !== null && typeof rawName !== 'string') {\n return errorResult('invalid_name: name must be the exchange name as text')\n }\n const name = typeof rawName === 'string' && rawName.trim() !== '' ? rawName.trim() : null\n const rawAddress = record.address\n if (rawAddress !== undefined && rawAddress !== null && typeof rawAddress !== 'string') {\n return errorResult('invalid_address: address must be 0x plus 40 hex characters')\n }\n const addressText =\n typeof rawAddress === 'string' && rawAddress.trim() !== '' ? rawAddress.trim() : null\n if (name !== null && addressText !== null)\n return errorResult('Give a name or an address, not both.')\n if (addressText !== null && !ADDRESS_FORM.test(addressText)) {\n return errorResult('invalid_address: address must be 0x plus 40 hex characters')\n }\n const address = addressText === null ? null : addressText.toLowerCase()\n\n let loaded: LoadedExchangeRegistry\n try {\n loaded = await deps.loadExchangeRegistry(network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError\n ? err.message\n : `exchange lookup unavailable: ${(err as Error).message}`\n )\n }\n const { document } = loaded\n const listed = document.rows.map((row) => row.display)\n const base = {\n schema: META_EXCHANGE_LOOKUP_SCHEMA,\n network,\n registry_version: document.registry_version,\n registry_source: loaded.source,\n recorded_on: document.recorded_on,\n }\n\n if (name === null && address === null) {\n const result = {\n ...base,\n matched: null,\n candidates: [],\n listed,\n exchanges: document.rows.map((row) => ({\n exchange: row.exchange,\n display: row.display,\n hot_wallets: row.wallets.filter((wallet) => wallet.role === 'hot_wallet').length,\n })),\n }\n return textResult({ ...result, hint: hintFor(result, null, null) })\n }\n\n if (address !== null) {\n const owner = exchangeOfWallet(address, document.rows)\n const result = {\n ...base,\n matched: owner ? exchangeMatchOf(owner.entry) : null,\n ...(owner ? { took_for: ROLE_WORDS[owner.wallet.role] } : {}),\n candidates: [],\n listed,\n }\n return textResult({ ...result, hint: hintFor(result, null, address) })\n }\n\n const match = matchExchange(name as string, document.rows)\n const result = {\n ...base,\n matched: match.matched ? exchangeMatchOf(match.matched) : null,\n ...(match.took_for ? { took_for: match.took_for } : {}),\n candidates: match.candidates,\n listed,\n }\n return textResult({ ...result, hint: hintFor(result, name, null) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,wBACX;AAGF,MAAa,4BAA4B;AACzC,MAAa,8BAA8B;AAC3C,MAAa,6BAA6B;AAC1C,MAAa,mCACX,urBAMG,sBAAsB;AAC3B,MAAa,mCAAmC;CAC9C,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;AA8CA,SAAS,SAAS,OAAkD;CAClE,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE;AAEA,SAAS,YAAY,MAA4C;CAC/D,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ;EAAK,CAAC;EAAG,SAAS;CAAK;AAC5D;AAEA,SAAS,WAAW,YAAoE;CACtF,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM,KAAK,UAAU,YAAY,MAAM,CAAC;EAAE,CAAC;EACrE,mBAAmB;EACnB,SAAS;CACX;AACF;AAEA,MAAM,eAAe;AAErB,SAAS,UAAU,OAAsB,MAA2C;CAClF,OAAO,MAAM,QACV,QAAQ,WAAW,OAAO,SAAS,IAAI,CAAC,C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SAAS;CACxB;CAEA,IAAI,SAAS,QAAQ,YAAY,MAAM;EACrC,MAAM,SAAS;GACb,GAAG;GACH,SAAS;GACT,YAAY,CAAC;GACb;GACA,WAAW,SAAS,KAAK,KAAK,SAAS;IACrC,UAAU,IAAI;IACd,SAAS,IAAI;IACb,aAAa,IAAI,QAAQ,QAAQ,WAAW,OAAO,SAAS,YAAY,CAAC,CAAC;GAC5E,EAAE;EACJ;EACA,OAAO,WAAW;GAAE,GAAG;GAAQ,MAAM,QAAQ,QAAQ,MAAM,IAAI;EAAE,CAAC;CACpE;CAEA,IAAI,YAAY,MAAM;EACpB,MAAM,QAAQ,iBAAiB,SAAS,SAAS,IAAI;EACrD,MAAM,SAAS;GACb,GAAG;GACH,SAAS,QAAQ,gBAAgB,MAAM,KAAK,IAAI;GAChD,GAAI,QAAQ,EAAE,UAAU,WAAW,MAAM,OAAO,MAAM,IAAI,CAAC;GAC3D,YAAY,CAAC;GACb;EACF;EACA,OAAO,WAAW;GAAE,GAAG;GAAQ,MAAM,QAAQ,QAAQ,MAAM,OAAO;EAAE,CAAC;CACvE;CAEA,MAAM,QAAQ,cAAc,MAAgB,SAAS,IAAI;CACzD,MAAM,SAAS;EACb,GAAG;EACH,SAAS,MAAM,UAAU,gBAAgB,MAAM,OAAO,IAAI;EAC1D,GAAI,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;EACrD,YAAY,MAAM;EAClB;CACF;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,MAAM,IAAI;CAAE,CAAC;AACpE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph-schema-CRQuKya1.mjs","names":["errorResult","isRecord"],"sources":["../src/mcp/contract-read.ts","../src/mcp/flows.ts","../src/mcp/graph-schema-cache.ts","../src/mcp/graph-schema.ts"],"sourcesContent":["/**\n * The Contract read of the facts layer: what one contract is, and what its\n * code lets its owner do, by its address.\n *\n * USE facts MATCH (c:Contract {address: \"0x…\"}) RETURN c.capabilities, …\n *\n * No tool of its own: `graph_query` and `graph_query_batch` carry it. This file\n * is the one source of what the package says about the read. Three places\n * teach it: the `graph_query` and `graph_query_batch` descriptions and the\n * graph hints of the MCP proxy (src/mcp/proxy.ts), the `chain-insights-cypher`\n * skill and docs/graph-tools.md. A host that loads no skill (Claude Desktop\n * chat) reads only the tool description, so the rule of the read rides on it.\n * tests/contract-read.test.ts holds the three to this file, and the read\n * itself to the words of the graph server.\n */\n\n/** The address of the examples: USDG on robinhood, a proxy. */\nexport const CONTRACT_READ_ADDRESS = '0x5fc5360d0400a0fd4f2af552add042d716f1d168'\n\n/** The nine properties the read serves, in the server's order. The first five lists arrive as JSON lists of strings. */\nexport const CONTRACT_READ_PROPERTIES = [\n 'contract_address',\n 'capabilities',\n 'observed',\n 'standards',\n 'roles',\n 'listings',\n 'implementation_address',\n 'beacon_address',\n 'created_block',\n] as const\n\n/** The properties that arrive as lists of words. An empty list is `[]`. */\nexport const CONTRACT_READ_LISTS = [\n 'capabilities',\n 'observed',\n 'standards',\n 'roles',\n 'listings',\n] as const\n\n/** What the code lets its owner do. */\nexport const CONTRACT_CAPABILITY_WORDS = [\n 'owner_mint',\n 'blacklist',\n 'pause',\n 'fee_set',\n 'max_tx_set',\n 'upgradeable',\n 'self_destruct',\n 'owner_withdraw',\n 'trading_switch',\n 'self_destruct_unproven',\n] as const\n\n/** What the chain shows the contract did. */\nexport const CONTRACT_OBSERVED_WORDS = [\n 'owner_minted',\n 'issuer_froze',\n 'taxed_transfer',\n 'traded_as_pool',\n] as const\n\n/** The words of `listings`. */\nexport const CONTRACT_LISTING_WORDS = [\n 'dex_venue',\n 'bridge',\n 'bridge_token',\n 'mixer',\n 'smart_account',\n] as const\n\n/** The read in full, with every property it serves. The server gives the same text as the example of a refusal. */\nexport const CONTRACT_READ_EXAMPLE =\n `USE facts MATCH (c:Contract {address: \"${CONTRACT_READ_ADDRESS}\"}) RETURN c.contract_address AS contract, c.capabilities AS capabilities, ` +\n 'c.observed AS observed, c.standards AS standards, c.roles AS roles, c.listings AS listings, ' +\n 'c.implementation_address AS implementation, c.beacon_address AS beacon, c.created_block AS created_block'\n\n/** The short read of the tool text. The server's own description shows the same one. */\nexport const CONTRACT_READ_SHORT = `USE facts MATCH (c:Contract {address: \"${CONTRACT_READ_ADDRESS}\"}) RETURN c.capabilities AS capabilities, c.observed AS observed, c.implementation_address AS implementation`\n\n/** What the read answers, in the server's words. */\nexport const CONTRACT_READ_MEANING =\n 'capabilities is what the code lets its owner do, observed is what was seen on the chain, and zero rows means the contract is not classified yet, never that it is safe; it states what the bytecode allows and is never a verdict'\n\n/** The plain words of the three capabilities an answer names first. A column name or a capability word is never printed. */\nexport const CONTRACT_PLAIN_WORDS =\n 'owner_mint: the owner can create new tokens. blacklist: the owner can block an address from moving the token. upgradeable: the code behind the address can be replaced.'\n\n/**\n * The one sentence of the `graph_query` and `graph_query_batch` descriptions.\n * It carries the routing rule, the read, the meaning of can against did, zero\n * rows and the answer rule, so a host that loads no skill follows them too.\n */\nexport const GRAPH_QUERY_CONTRACT_READ_SENTENCE =\n `\"What is this contract\" and \"what can its owner do\", for one contract address, is a USE facts Contract read: ${CONTRACT_READ_SHORT}. ` +\n `It ${CONTRACT_READ_MEANING.replace(/^capabilities is/, 'answers one row: capabilities is')}. ` +\n 'The address is the only key: no WHERE, no search by capability, role or implementation. ' +\n `Say it in plain words, never the word itself and never \"scam\", \"rug pull\", \"safe\" or a score: ${CONTRACT_PLAIN_WORDS}`\n\n/** The graph hint of the read: its key, its properties, its words and how to answer from them. */\nexport const CONTRACT_READ_HINT =\n `- One contract by its address on USE facts, with a RETURN of c.<property> items: ${CONTRACT_READ_EXAMPLE}. ` +\n 'One node, no relationship, no day, no WHERE and no $parameter; the address is a 42-character literal in either case, and LIMIT is optional and only 1. One row or none. ' +\n `Properties: ${CONTRACT_READ_PROPERTIES.join(', ')}. ${CONTRACT_READ_LISTS.join(', ')} are lists of words, [] when empty. ` +\n `capabilities is what the code lets its owner do: ${CONTRACT_CAPABILITY_WORDS.join(', ')}. For a proxy it already holds what the implementation allows. ` +\n \"observed is what the chain shows happened: owner_minted (the contract's creator minted new supply after its creation day), issuer_froze (the issuer froze or wiped a holder), taxed_transfer (the token is proven as taxed from its transfers), traded_as_pool (the contract is the pool of a trade). \" +\n `standards holds words such as erc20, erc4626 and eip1967_proxy, roles words such as pair_pool, vault and router, listings ${CONTRACT_LISTING_WORDS.join(', ')}. ` +\n 'Can is not did: a capability says the code allows it, an observed word says it happened. Zero rows means the contract is not classified yet, never that it has no capability and never that it is safe. ' +\n 'Any other form is refused with facts_no_anchor, and its example is the read above: the address is the only key. Each word of a list is one billed element. ' +\n `Answer with what the bytecode allows, in plain words, never a verdict: no \"scam\", \"rug pull\", \"safe\" or score from these words, and upgradeable is a capability like every other. ${CONTRACT_PLAIN_WORDS}`\n","/**\n * graph_expand, the one dedicated tool of the local proxy, called by the Chain\n * Insights view (ui://chain-insights/view) when the investigator clicks. Its\n * _meta says visibility [\"app\"], so a host keeps it away from the model: the\n * model writes its own graph_query, and the view draws the rows by their column\n * names.\n *\n * Two forms, told apart by the arguments:\n *\n * - node, {network, address, in_offset?, out_offset?}: one address with up to\n * 250 newest senders and 250 newest receivers, a text summary and\n * chain-insights.flows.v1 in structuredContent. Composed from at most five\n * anchored graph_query reads on the topology graph: the node, then its\n * outgoing and its incoming FLOWED_TO, newest first, two reads a side because\n * a reply holds at most 200 rows. On a lane whose money family lists\n * ROUTED_TO (the three link levels) each side reads FLOWED_TO and ROUTED_TO\n * together, newest first, so the 250 a side count both: a route is one step\n * that changes the asset, from a payer to the final receiver of a swap, and\n * its edge carries link_kind ROUTED_TO. A router or a pool is never an end of\n * a route. Any other lane gets the reads of 0.82.0, byte for byte.\n * - link, {network, from, to, day}: the transfers between two known addresses\n * on one UTC day, newest first, at most 50, a short text summary and\n * chain-insights.transfers.v1 in structuredContent. One anchored USE facts\n * graph_query read.\n * - link page, {network, from, to, day, limit, skip?, first_day?}: a page of\n * `limit` transfers (1 to 50) newest first, read from `day` back one UTC day\n * at a time, at most TRANSFERS_MAX_DAYS (a week of) reads a call, never before\n * first_day. The answer carries `next` ({day, skip}, or null when every\n * transfer back to first_day is listed) which the next call sends back as\n * day and skip. The view's \"More transfers\".\n * - details, {network, address, details: true}: the lifetime totals, counts,\n * role and labels of one address, chain-insights.address.v1, one anchored\n * topology read. The view fills its panel with it when the rows of a query\n * carried no totals.\n *\n * Every read goes through the proxy's remote client, the same path and payment\n * wrapping a graph_query call takes, and is billed as a graph_query. Every\n * argument is checked before the first read, so a refused call reaches no graph\n * endpoint and costs nothing.\n */\n\nimport type { SwapLinkShape } from './layer-routing.js'\n\nexport const FLOWS_SCHEMA = 'chain-insights.flows.v1'\nexport const GRAPH_EXPAND_TOOL = 'graph_expand'\nexport const FLOWS_NETWORK = 'robinhood'\n\n/** How many senders and how many receivers one page shows, at most. */\nexport const FLOWS_PER_SIDE = 250\n/** The view data of one answer: at most this many addresses, the centre included... */\nexport const FLOWS_MAX_NODES = 500\n/**\n * ...and under this many characters of JSON. Hosts drop an app tool result\n * over about 150,000 characters.\n */\nexport const FLOWS_MAX_CHARS = 140_000\n/**\n * The graph endpoint cuts a reply at 200 rows, whatever the LIMIT, so one side\n * of a page is read in reads of at most this many rows.\n */\nexport const FLOWS_READ_ROWS = 200\n/** The text of a node answer holds at most this many lines. */\nexport const FLOWS_SUMMARY_MAX_LINES = 20\n/** Where a graph_expand page may start on each side, at most. */\nexport const FLOWS_MAX_OFFSET = 10_000\n\nexport const TRANSFERS_SCHEMA = 'chain-insights.transfers.v1'\n/** A link answer lists at most this many transfers... */\nexport const TRANSFERS_MAX = 50\n/**\n * ...from the rows one read brings back. A facts read takes no ORDER BY and\n * the server cuts a reply at 200 rows, so the read asks for the whole cap and\n * the newest rows are picked here.\n */\nexport const TRANSFERS_READ_ROWS = 200\n/** The text of a link answer names at most this many transfers. */\nexport const TRANSFERS_SUMMARY_ROWS = 5\n/** A paged link answer reads at most this many days (a week) in one call: a sparse link costs at most this many reads a page, and a week of it comes back at once. */\nexport const TRANSFERS_MAX_DAYS = 7\n/** Where a paged link answer stops reading back when the caller names no first_day. */\nexport const TRANSFERS_FLOOR_DAY = '2015-01-01'\n\nexport const ADDRESS_SCHEMA = 'chain-insights.address.v1'\n\nexport type FlowNode = {\n address: string\n role: string\n labels: string[]\n total_in_usd: number\n total_out_usd: number\n degree_in: number\n degree_out: number\n}\n\n/** The two level 2 links an edge of a lane with the levels can be. */\nexport type FlowLinkKind = 'FLOWED_TO' | 'ROUTED_TO'\n\nexport type FlowEdge = {\n from: string\n to: string\n /** What was sent: on a route, what the payer gave. */\n usd: number\n tx_count: number\n first_seen_ms: number\n last_seen_ms: number\n /**\n * Set on a lane with the levels only: FLOWED_TO (funds between addresses),\n * ROUTED_TO (a swap route, one step that changes the asset), or both joined\n * with \", \" when the pair holds both, as the view joins the link kinds of\n * graph_query rows. The view shows it as the link kind.\n */\n link_kind?: string\n /** A route only: what the receiver got, in USD (bought_usd_sum). */\n bought_usd?: number\n /** A route only: how many swaps the route holds. */\n swap_count?: number\n}\n\nexport type FlowCursor = { in_offset: number; out_offset: number }\n\n/** The links of the centre not loaded yet, past the cursor, on each side. */\nexport type FlowRemaining = { senders: number; receivers: number }\n\nexport type FlowView = {\n schema: typeof FLOWS_SCHEMA\n network: string\n center: string\n nodes: FlowNode[]\n edges: FlowEdge[]\n cursor: FlowCursor\n truncated: boolean\n /** Set on every node page. A view that does not know it ignores it. */\n remaining?: FlowRemaining\n /** Set on a lane with the levels only: the links the page read, both level 2 links. */\n link_kinds?: FlowLinkKind[]\n}\n\ntype Row = Record<string, unknown>\n\nexport type FlowsPage = {\n center: Row\n senders: Row[]\n receivers: Row[]\n inOffset: number\n outOffset: number\n /** `levels` on a lane whose money family lists ROUTED_TO; absent or `route` on the graph of before. */\n shape?: SwapLinkShape\n}\n\n/** One graph_query answer as the remote client returns it. */\nexport type GraphQueryAnswer = {\n content?: Array<{ type: string; text?: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n}\n\nexport type FlowsToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nexport type FlowsDependencies = {\n /** One graph_query call through the proxy's remote client. */\n graphQuery: (args: { network: string; query: string }) => Promise<GraphQueryAnswer>\n /**\n * The whole refusal of a failed read, text and structured facts\n * (chain-insights.refusal.v1: the free tier spent, a wallet that cannot\n * pay). When given it replaces describeFailure, so the view can say why in\n * the viewer's own words and time.\n */\n refusal?: (err: unknown) => Promise<FlowsToolResult>\n /** The text of a call that threw (payment required, transport failure). */\n describeFailure: (err: unknown) => string\n /** Why no read can run (the graph endpoint is not connected), checked after the arguments. */\n unavailable?: () => string | undefined\n /**\n * The lane's graph shape (`meta_network_capabilities`, kept by the proxy). A\n * node page reads ROUTED_TO beside FLOWED_TO only when it answers `levels`;\n * absent, `route` or a read that throws keeps the reads of 0.82.0.\n */\n linkShape?: (network: string) => Promise<SwapLinkShape> | SwapLinkShape\n now?: () => Date\n}\n\nexport const INVALID_ADDRESS_TEXT =\n 'invalid_address: a full 0x address of 40 hexadecimal characters is needed, for example 0x04911a118f11c75667e4d0dfb8e640af5a353550'\nexport const OFFSET_TOO_LARGE_TEXT = `invalid_offset: in_offset and out_offset must each be at most ${FLOWS_MAX_OFFSET}`\nexport const OFFSET_NEGATIVE_TEXT =\n 'invalid_offset: in_offset and out_offset must each be a whole number, 0 or more'\n\nexport const INVALID_DAY_TEXT =\n 'invalid_day: day must be a calendar date written YYYY-MM-DD (UTC), for example 2026-07-10'\nexport const BOTH_FORMS_TEXT =\n 'invalid_arguments: pass address (with in_offset and out_offset) to expand a node, or from, to and day to list the transfers of a link, not both'\nexport const INVALID_LIMIT_TEXT = 'invalid_limit: limit must be a whole number from 1 to 50'\nexport const INVALID_SKIP_TEXT = 'invalid_skip: skip must be a whole number of 0 or more'\nexport const INVALID_FIRST_DAY_TEXT =\n 'invalid_first_day: first_day must be a calendar date written YYYY-MM-DD (UTC), not after day'\nexport const DETAILS_FORM_TEXT =\n 'invalid_arguments: details takes address alone; pass no from, to, day or offsets with it'\n\nconst ADDRESS_PATTERN = /^0x[0-9a-f]{40}$/\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\nconst CODE_PREFIX = /^([a-z][a-z0-9_]*):\\s*/\n\n/**\n * The address lower-cased, or null when it is not 0x and 40 hexadecimal\n * characters. Only an address that passes is ever written into a read, so the\n * reads can carry it as a literal.\n */\nexport function normalizeFlowsAddress(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const address = raw.trim().toLowerCase()\n return ADDRESS_PATTERN.test(address) ? address : null\n}\n\n/**\n * The day as YYYY-MM-DD when it is a real calendar date, or null. Only a day\n * that passes is ever written into a read.\n */\nexport function normalizeFlowsDay(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const day = raw.trim()\n if (!DAY_PATTERN.test(day)) return null\n const time = Date.parse(`${day}T00:00:00Z`)\n if (Number.isNaN(time) || new Date(time).toISOString().slice(0, 10) !== day) return null\n return day\n}\n\n/**\n * The one facts read of a link: the transfers from one address to another on\n * one day. A facts read names the pair with one day, takes no ORDER BY and\n * holds at most 200 rows, so the read asks for the whole cap and the order is\n * made in buildTransfersView. Both addresses and the day have passed their\n * checks, so they are written into the read as literals.\n */\nexport function transfersReadFor(from: string, to: string, day: string): string {\n return (\n `USE facts MATCH (a:Address {address: \"${from}\"})-[t:TRANSFER]->(b:Address {address: \"${to}\"}) ` +\n `WHERE t.block_date = \"${day}\" ` +\n 'RETURN t.tx_id AS tx_id, t.block_timestamp AS block_timestamp, t.amount AS amount, ' +\n `t.asset_symbol AS asset_symbol, t.amount_usd AS amount_usd LIMIT ${TRANSFERS_READ_ROWS}`\n )\n}\n\n/** The UTC day before a YYYY-MM-DD day. */\nexport function dayBefore(day: string): string {\n return new Date(Date.parse(`${day}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10)\n}\n\n/**\n * The one topology read of a details call: the address alone, with its\n * lifetime rollups and activity span. The address has passed its check, so it\n * is written into the read as a literal.\n */\nexport function detailsReadFor(address: string): string {\n return (\n `USE topology MATCH (b:Address {address: \"${address}\"}) RETURN ${NODE_FIELDS}, ` +\n 'b.first_activity_timestamp AS first_activity_timestamp, b.last_activity_timestamp AS last_activity_timestamp LIMIT 1'\n )\n}\n\nexport type AddressView = FlowNode & {\n schema: typeof ADDRESS_SCHEMA\n network: string\n is_exchange: boolean\n is_sanctioned: boolean\n is_scam: boolean\n is_victim: boolean\n pool: boolean\n first_activity_timestamp: number | null\n last_activity_timestamp: number | null\n}\n\n/** chain-insights.address.v1 from the one row of a details read. */\nexport function buildAddressView(network: string, address: string, row: Row): AddressView {\n const node = flowsNodeOf({ ...row, address })\n return {\n schema: ADDRESS_SCHEMA,\n network,\n ...node,\n is_exchange: row.is_exchange === true,\n is_sanctioned: row.is_sanctioned === true,\n is_scam: row.is_scam === true,\n is_victim: row.is_victim === true,\n pool: row.pool === true,\n first_activity_timestamp: flowsNumberOrNull(row.first_activity_timestamp),\n last_activity_timestamp: flowsNumberOrNull(row.last_activity_timestamp),\n }\n}\n\n/** The one line of a details answer. */\nexport function addressSummary(view: AddressView): string {\n return (\n `${view.address} on ${view.network}: ${roleWord(view.role)}; lifetime ${formatFlowsUsd(view.total_in_usd)} in, ` +\n `${formatFlowsUsd(view.total_out_usd)} out; ${view.degree_in} senders and ${view.degree_out} receivers in the topology graph` +\n (view.labels.length ? `; labels ${view.labels.join(', ')}` : '') +\n '.'\n )\n}\n\nconst NODE_FIELDS =\n 'b.address AS address, b.labels AS labels, b.is_exchange AS is_exchange, ' +\n 'b.is_sanctioned AS is_sanctioned, b.is_scam AS is_scam, b.is_victim AS is_victim, b:Pool AS pool, ' +\n 'b.total_in_usd AS total_in_usd, b.total_out_usd AS total_out_usd, b.degree_in AS degree_in, b.degree_out AS degree_out'\nconst PARTY_FIELDS =\n NODE_FIELDS +\n ', f.amount_usd_sum AS usd, f.tx_count AS tx_count, ' +\n 'f.first_seen_timestamp AS first_seen, f.last_seen_timestamp AS last_seen'\n// Newest link first, the address breaking a tie, so a page and the next one\n// never share or skip a link.\nconst PAGE_ORDER = ' ORDER BY f.last_seen_timestamp DESC, b.address'\n// On a lane with the levels a side reads both level 2 links: the link type\n// comes back as link_kind and breaks the last tie (a pair can hold both), and\n// a route carries what the receiver got and its swap count.\nconst LEVELS_PARTY_FIELDS =\n PARTY_FIELDS +\n ', type(f) AS link_kind, f.bought_usd_sum AS bought_usd, f.swap_count AS swap_count'\nconst LEVELS_PAGE_ORDER = PAGE_ORDER + ', link_kind'\n\n/** One anchored read of a page, with the SKIP and LIMIT it carries. */\nexport type FlowsRead = { id: 'node' | 'out' | 'in'; query: string; skip: number; limit: number }\n\n/**\n * The anchored reads of one page: the node, then the receivers, then the\n * senders. Each side asks for one row more than it shows: the extra row says\n * another page exists. A reply holds at most FLOWS_READ_ROWS rows, so a side\n * is read in chunks on the same order, each starting where the last one ends.\n */\nexport function flowsReadsFor(\n address: string,\n inOffset: number,\n outOffset: number,\n shape: SwapLinkShape = 'route'\n): FlowsRead[] {\n const levels = shape === 'levels'\n const fields = levels ? LEVELS_PARTY_FIELDS : PARTY_FIELDS\n const order = levels ? LEVELS_PAGE_ORDER : PAGE_ORDER\n const side = (id: 'out' | 'in', offset: number, match: string): FlowsRead[] => {\n const reads: FlowsRead[] = []\n for (let done = 0; done < FLOWS_PER_SIDE + 1; done += FLOWS_READ_ROWS) {\n const skip = offset + done\n const limit = Math.min(FLOWS_READ_ROWS, FLOWS_PER_SIDE + 1 - done)\n reads.push({\n id,\n query: `USE topology MATCH ${match} RETURN ${fields}${order}${skip > 0 ? ` SKIP ${skip}` : ''} LIMIT ${limit}`,\n skip,\n limit,\n })\n }\n return reads\n }\n return [\n {\n id: 'node',\n query: `USE topology MATCH (b:Address {address: '${address}'}) RETURN ${NODE_FIELDS} LIMIT 1`,\n skip: 0,\n limit: 1,\n },\n ...(levels\n ? [\n // The self link (a route of the address to itself, a swap for\n // itself) is read once, on the receivers' side.\n ...side('out', outOffset, `(a:Address {address: '${address}'})-[f:FLOWED_TO|ROUTED_TO]->(b:Address)`),\n ...side(\n 'in',\n inOffset,\n `(b:Address)-[f:FLOWED_TO|ROUTED_TO]->(a:Address {address: '${address}'}) WHERE b.address <> '${address}'`\n ),\n ]\n : [\n ...side('out', outOffset, `(a:Address {address: '${address}'})-[f:FLOWED_TO]->(b:Address)`),\n ...side('in', inOffset, `(b:Address)-[f:FLOWED_TO]->(a:Address {address: '${address}'})`),\n ]),\n ]\n}\n\n/** The role word of an address, first match wins. */\nexport function flowsRole(row: Row): string {\n if (row.is_exchange === true) return 'exchange'\n if (row.is_sanctioned === true) return 'sanctioned'\n if (row.is_scam === true) return 'scam'\n if (row.is_victim === true) return 'victim'\n if (row.pool === true) return 'pool'\n if (Array.isArray(row.labels) && row.labels.includes('SelfTrader')) return 'self_trader'\n return 'other'\n}\n\n/** The role as the text answers write it: a role code becomes words. */\nfunction roleWord(role: string): string {\n return role === 'self_trader' ? 'self-trading contract' : role\n}\n\nfunction flowsFloat(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction flowsInt(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : 0\n}\n\nfunction flowsNodeOf(row: Row): FlowNode {\n const labels = Array.isArray(row.labels)\n ? row.labels.filter((label): label is string => typeof label === 'string')\n : []\n return {\n address: typeof row.address === 'string' ? row.address : '',\n role: flowsRole(row),\n labels,\n total_in_usd: flowsFloat(row.total_in_usd),\n total_out_usd: flowsFloat(row.total_out_usd),\n degree_in: flowsInt(row.degree_in),\n degree_out: flowsInt(row.degree_out),\n }\n}\n\nfunction assembleFlowView(\n network: string,\n page: FlowsPage,\n senders: Row[],\n receivers: Row[],\n truncated: boolean\n): FlowView {\n const center = flowsNodeOf(page.center)\n const levels = page.shape === 'levels'\n const cursor = {\n in_offset: page.inOffset + senders.length,\n out_offset: page.outOffset + receivers.length,\n }\n // The degrees count FLOWED_TO counterparties only. On a lane with the levels\n // a page also holds routes, so what remains is known only as \"more\" (the\n // extra row of the read): at least one, never a count the degrees cannot give.\n const remainingOf = (degree: number, next: number, more: boolean) =>\n levels ? (more ? Math.max(1, degree - next) : 0) : Math.max(0, degree - next)\n const view: FlowView = {\n schema: FLOWS_SCHEMA,\n network,\n center: center.address,\n nodes: [center],\n edges: [],\n cursor,\n truncated,\n ...(levels ? { link_kinds: ['FLOWED_TO', 'ROUTED_TO'] as FlowLinkKind[] } : {}),\n remaining: {\n senders: remainingOf(center.degree_in, cursor.in_offset, page.senders.length > senders.length),\n receivers: remainingOf(\n center.degree_out,\n cursor.out_offset,\n page.receivers.length > receivers.length\n ),\n },\n }\n const seen = new Set([center.address])\n const edgeAt = new Map<string, FlowEdge>()\n const add = (row: Row, incoming: boolean) => {\n const node = flowsNodeOf(row)\n if (!seen.has(node.address)) {\n seen.add(node.address)\n view.nodes.push(node)\n }\n const edge: FlowEdge = {\n from: incoming ? node.address : center.address,\n to: incoming ? center.address : node.address,\n usd: flowsFloat(row.usd),\n tx_count: flowsInt(row.tx_count),\n first_seen_ms: flowsInt(row.first_seen),\n last_seen_ms: flowsInt(row.last_seen),\n }\n if (!levels) {\n view.edges.push(edge)\n return\n }\n const kind: FlowLinkKind = row.link_kind === 'ROUTED_TO' ? 'ROUTED_TO' : 'FLOWED_TO'\n edge.link_kind = kind\n if (kind === 'ROUTED_TO') {\n edge.bought_usd = flowsFloat(row.bought_usd)\n edge.swap_count = flowsInt(row.swap_count)\n }\n // A pair that holds both links is one edge, as the view draws one link a\n // direction: the sums added, the kinds joined.\n const key = `${edge.from}->${edge.to}`\n const kept = edgeAt.get(key)\n if (!kept) {\n edgeAt.set(key, edge)\n view.edges.push(edge)\n return\n }\n kept.usd += edge.usd\n kept.tx_count += edge.tx_count\n kept.first_seen_ms = Math.min(kept.first_seen_ms, edge.first_seen_ms)\n kept.last_seen_ms = Math.max(kept.last_seen_ms, edge.last_seen_ms)\n kept.link_kind = [kept.link_kind, kind].filter(Boolean).sort().join(', ')\n if (edge.bought_usd !== undefined) kept.bought_usd = edge.bought_usd\n if (edge.swap_count !== undefined) kept.swap_count = edge.swap_count\n }\n for (const row of senders) add(row, true)\n for (const row of receivers) add(row, false)\n return view\n}\n\nfunction fitsFlowBudget(view: FlowView): boolean {\n return view.nodes.length <= FLOWS_MAX_NODES && JSON.stringify(view).length < FLOWS_MAX_CHARS\n}\n\n/**\n * How many senders and receivers stay after `drops` of the oldest links go,\n * one at a time from the longer side, the senders first on a tie.\n */\nfunction keptAfterDrops(senders: number, receivers: number, drops: number): [number, number] {\n let s = senders\n let r = receivers\n for (let left = Math.min(drops, s + r); left > 0; left -= 1) {\n if (s >= r) s -= 1\n else r -= 1\n }\n return [s, r]\n}\n\n/**\n * flows.v1 from one page: the centre first, then the senders and the\n * receivers, each newest first, at most FLOWS_PER_SIDE a side. When the view\n * data would hold more than FLOWS_MAX_NODES addresses or reach FLOWS_MAX_CHARS\n * characters, the oldest links go first, the view is marked truncated, and the\n * cursor still says where the next page starts.\n *\n * Each dropped link only makes the view smaller, so the fewest drops that fit\n * are found by halving: about ten views are measured for a full page, not one\n * per dropped link.\n */\nexport function buildFlowView(network: string, page: FlowsPage): FlowView {\n const overflow = page.senders.length > FLOWS_PER_SIDE || page.receivers.length > FLOWS_PER_SIDE\n const senders = page.senders.slice(0, FLOWS_PER_SIDE)\n const receivers = page.receivers.slice(0, FLOWS_PER_SIDE)\n const viewAfter = (drops: number) => {\n const [s, r] = keptAfterDrops(senders.length, receivers.length, drops)\n return assembleFlowView(\n network,\n page,\n senders.slice(0, s),\n receivers.slice(0, r),\n overflow || drops > 0\n )\n }\n // Dropping every link is the floor: that view is answered even when it does\n // not fit.\n let low = 0\n let high = senders.length + receivers.length\n while (low < high) {\n const mid = (low + high) >> 1\n if (fitsFlowBudget(viewAfter(mid))) high = mid\n else low = mid + 1\n }\n return viewAfter(low)\n}\n\nexport function formatFlowsUsd(value: number): string {\n if (!(value > 0)) return '$0'\n if (value < 0.01) return 'under $0.01'\n const whole = Math.floor(value)\n const cents = Math.round((value - whole) * 100)\n if (cents === 100) return formatFlowsUsd(whole + 1)\n const grouped = whole.toFixed(0).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return `$${grouped}.${String(cents).padStart(2, '0')}`\n}\n\nfunction formatFlowsAge(lastSeenMs: number, now: Date): string {\n if (lastSeenMs <= 0) return 'at an unknown time'\n const date = new Date(lastSeenMs).toISOString().slice(0, 10)\n const days = Math.trunc((now.getTime() - lastSeenMs) / 86_400_000)\n if (days < 1) return `${date} (less than a day ago)`\n if (days === 1) return `${date} (1 day ago)`\n return `${date} (${days} days ago)`\n}\n\n/** The role word, with up to three address labels beside it. */\nfunction roleText(node: FlowNode | undefined): string {\n if (!node) return 'other'\n const word = roleWord(node.role)\n if (node.labels.length === 0) return word\n return `${word} (${node.labels.slice(0, 3).join(', ')})`\n}\n\nfunction sideLines(title: string, parties: string[]): string[] {\n if (parties.length === 0) return [`${title}, newest first: none.`]\n const lines = [`${title}, newest first (${parties.length}):`]\n // A side with more than six counterparties lists two on a line, so a full\n // page stays within the line budget.\n const perLine = parties.length > 6 ? 2 : 1\n for (let start = 0; start < parties.length; start += perLine) {\n lines.push(`- ${parties.slice(start, start + perLine).join('; ')}`)\n }\n return lines\n}\n\n/**\n * The text of a node answer: the centre, its role and lifetime totals, then\n * every counterparty of the view with its USD, transaction count and last-seen\n * date and age. At most FLOWS_SUMMARY_MAX_LINES lines.\n */\nexport function flowsSummary(view: FlowView, now: Date): string {\n if (view.link_kinds) return levelsSummary(view, now)\n const nodes = new Map(view.nodes.map((node) => [node.address, node]))\n const center = nodes.get(view.center)\n const party = (address: string, edge: FlowEdge) =>\n `${address} ${roleText(nodes.get(address))}, ${formatFlowsUsd(edge.usd)} in ${edge.tx_count} tx, last seen ${formatFlowsAge(edge.last_seen_ms, now)}`\n const senders: string[] = []\n const receivers: string[] = []\n for (const edge of view.edges) {\n if (edge.to === view.center) senders.push(party(edge.from, edge))\n else receivers.push(party(edge.to, edge))\n }\n const lines = [\n `Money flows of ${view.center} on ${view.network}: ${roleText(center)}; lifetime ${formatFlowsUsd(center?.total_in_usd ?? 0)} in, ${formatFlowsUsd(center?.total_out_usd ?? 0)} out; ${center?.degree_in ?? 0} senders and ${center?.degree_out ?? 0} receivers in the topology graph.`,\n ...sideLines('Recent senders', senders),\n ...sideLines('Recent receivers', receivers),\n ]\n const body = lines.slice(0, FLOWS_SUMMARY_MAX_LINES - 2)\n const footer = pagingLines(view, senders.length, receivers.length, center)\n return [...body, ...footer].join('\\n')\n}\n\n/** What one edge of a lane with the levels moved: funds, a swap route, or both. */\nfunction levelsAmount(edge: FlowEdge): string {\n if (edge.link_kind === 'ROUTED_TO') {\n return `swap route, ${formatFlowsUsd(edge.usd)} paid and ${formatFlowsUsd(edge.bought_usd ?? 0)} got in ${edge.swap_count ?? 0} swaps`\n }\n if (edge.link_kind === 'FLOWED_TO') return `${formatFlowsUsd(edge.usd)} in ${edge.tx_count} tx`\n return `funds and a swap route, ${formatFlowsUsd(edge.usd)} in ${edge.tx_count} tx`\n}\n\n/**\n * The text of a node answer on a lane with the levels: the same lines, each\n * counterparty saying whether it is funds or a swap route, and the address's\n * swap for itself (its self link) on a line of its own.\n */\nfunction levelsSummary(view: FlowView, now: Date): string {\n const nodes = new Map(view.nodes.map((node) => [node.address, node]))\n const center = nodes.get(view.center)\n const party = (address: string, edge: FlowEdge) =>\n `${address} ${roleText(nodes.get(address))}, ${levelsAmount(edge)}, last seen ${formatFlowsAge(edge.last_seen_ms, now)}`\n const senders: string[] = []\n const receivers: string[] = []\n const self: string[] = []\n for (const edge of view.edges) {\n if (edge.from === view.center && edge.to === view.center) {\n self.push(\n `Swapped for itself: ${levelsAmount(edge)}, last seen ${formatFlowsAge(edge.last_seen_ms, now)}.`\n )\n } else if (edge.to === view.center) senders.push(party(edge.from, edge))\n else receivers.push(party(edge.to, edge))\n }\n const lines = [\n `Money flows of ${view.center} on ${view.network}: ${roleText(center)}; lifetime ${formatFlowsUsd(center?.total_in_usd ?? 0)} in, ${formatFlowsUsd(center?.total_out_usd ?? 0)} out in funds between addresses; ${center?.degree_in ?? 0} senders and ${center?.degree_out ?? 0} receivers of funds, swap routes not counted.`,\n ...self,\n ...sideLines('Recent senders and payers through a swap', senders),\n ...sideLines('Recent receivers and receivers through a swap', receivers),\n ]\n const body = lines.slice(0, FLOWS_SUMMARY_MAX_LINES - 2)\n // A pair that holds both links is one line, so the page names its counts,\n // not a range of links.\n const where = `Showing ${senders.length} senders and ${receivers.length} receivers on this page, funds and swap routes together, newest first.`\n const more = view.truncated || (view.remaining?.senders ?? 0) + (view.remaining?.receivers ?? 0) > 0\n const footer = more\n ? [where, 'More senders and receivers load when an address in the picture is double-clicked.']\n : [where]\n return [...body, ...footer].join('\\n')\n}\n\n/** Where this page sits, and that the picture loads the rest when an address is clicked. */\nfunction pagingLines(\n view: FlowView,\n shownSenders: number,\n shownReceivers: number,\n center: FlowNode | undefined\n): string[] {\n const totalIn = center?.degree_in ?? 0\n const totalOut = center?.degree_out ?? 0\n const { in_offset: nextIn, out_offset: nextOut } = view.cursor\n const range = (shown: number, next: number, total: number) =>\n shown === 0 ? `none of ${total}` : `${next - shown + 1} to ${next} of ${total}`\n const where = `Showing senders ${range(shownSenders, nextIn, totalIn)} and receivers ${range(shownReceivers, nextOut, totalOut)}, newest first.`\n if (!view.truncated && nextIn >= totalIn && nextOut >= totalOut) return [where]\n return [\n where,\n 'More senders and receivers load when an address in the picture is double-clicked.',\n ]\n}\n\nexport type TransferRow = {\n tx_id: string\n block_timestamp: number | null\n amount: number | string | null\n asset_symbol: string | null\n amount_usd: number | null\n}\n\nexport type TransfersCursor = { day: string; skip: number }\n\nexport type TransfersView = {\n schema: typeof TRANSFERS_SCHEMA\n network: string\n from: string\n to: string\n day: string\n transfers: TransferRow[]\n truncated: boolean\n /** Paged answers only: the earliest day read, how many days the call read, and where the next page starts (null: every transfer back to first_day is listed). */\n through_day?: string\n days_read?: number\n next?: TransfersCursor | null\n}\n\nexport type TransfersPageRequest = { skip: number; firstDay: string | null; limit: number }\n\n/** A finite number, or a decimal string read as one, or null. */\nfunction flowsNumberOrNull(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\nfunction transferOf(row: Row): TransferRow {\n const amount =\n typeof row.amount === 'number' && Number.isFinite(row.amount)\n ? row.amount\n : typeof row.amount === 'string' && row.amount.trim() !== ''\n ? row.amount\n : null\n return {\n tx_id: typeof row.tx_id === 'string' ? row.tx_id : '',\n block_timestamp: flowsNumberOrNull(row.block_timestamp),\n amount,\n asset_symbol:\n typeof row.asset_symbol === 'string' && row.asset_symbol !== '' ? row.asset_symbol : null,\n amount_usd: flowsNumberOrNull(row.amount_usd),\n }\n}\n\n/**\n * chain-insights.transfers.v1 from the rows of one facts read: newest first,\n * at most TRANSFERS_MAX, truncated when more rows than that came back. The\n * facts layer takes no ORDER BY, so the order is made here.\n */\nexport function buildTransfersView(\n network: string,\n from: string,\n to: string,\n day: string,\n rows: Row[]\n): TransfersView {\n const newestFirst = rows\n .map(transferOf)\n .sort((a, b) => (b.block_timestamp ?? -Infinity) - (a.block_timestamp ?? -Infinity))\n return {\n schema: TRANSFERS_SCHEMA,\n network,\n from,\n to,\n day,\n transfers: newestFirst.slice(0, TRANSFERS_MAX),\n truncated: newestFirst.length > TRANSFERS_MAX,\n }\n}\n\nfunction transferLine(transfer: TransferRow): string {\n const time =\n transfer.block_timestamp === null\n ? 'at an unknown time'\n : `${new Date(transfer.block_timestamp).toISOString().slice(0, 19).replace('T', ' ')} UTC`\n const amount = transfer.amount === null ? 'an unknown amount' : String(transfer.amount)\n const asset = transfer.asset_symbol ? ` ${transfer.asset_symbol}` : ''\n const usd = transfer.amount_usd === null ? 'no USD price' : formatFlowsUsd(transfer.amount_usd)\n return `- ${time}, ${amount}${asset}, ${usd}, tx ${transfer.tx_id}`\n}\n\n/** The short text of a link answer: the pair, the day, the count and the newest few transfers. */\nexport function transfersSummary(view: TransfersView): string {\n const paged = view.through_day !== undefined\n const span = paged && view.through_day !== view.day ? `${view.through_day} to ${view.day}` : view.day\n const head = `Transfers from ${view.from} to ${view.to} on ${span} (UTC) on ${view.network}`\n if (view.transfers.length === 0) {\n return paged && view.next ? `${head}: none; earlier days remain before ${view.next.day}.` : `${head}: none.`\n }\n const count = view.truncated\n ? paged\n ? `${view.transfers.length}, and a day holds more than one read lists`\n : `the newest ${view.transfers.length}, and the day holds more`\n : `${view.transfers.length}`\n const lines = [\n `${head}: ${count}, newest first.`,\n ...view.transfers.slice(0, TRANSFERS_SUMMARY_ROWS).map(transferLine),\n ]\n const rest = view.transfers.length - TRANSFERS_SUMMARY_ROWS\n if (rest > 0) lines.push(`- and ${rest} more in the picture.`)\n if (paged && view.next) lines.push(`- earlier transfers remain, from ${view.next.day} back.`)\n return lines.join('\\n')\n}\n\nfunction errorResult(text: string): FlowsToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\n/** The result of a failed read: the structured refusal when the proxy builds one, else the text. */\nasync function failedRead(deps: FlowsDependencies, err: unknown): Promise<FlowsToolResult> {\n if (deps.refusal) {\n try {\n return await deps.refusal(err)\n } catch {\n // The refusal builder itself failed: the plain text still names the cause.\n }\n }\n return errorResult(deps.describeFailure(err))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction answerText(answer: GraphQueryAnswer): string {\n return (answer.content ?? [])\n .map((block) => (block.type === 'text' && typeof block.text === 'string' ? block.text : ''))\n .filter(Boolean)\n .join('\\n')\n .trim()\n}\n\n/**\n * The refusal of a read that did not answer, naming its code first:\n * error_detail.code when the graph endpoint sent its typed refusal, the code\n * its text starts with otherwise, and graph_query_failed when it names none.\n * The view marks the address it was expanding.\n */\nexport function refusalText(answer: GraphQueryAnswer): string {\n const text = answerText(answer)\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n const detailCode = isRecord(detail) && typeof detail.code === 'string' ? detail.code : ''\n const textCode = CODE_PREFIX.exec(text)?.[1] ?? ''\n const code = detailCode || textCode || 'graph_query_failed'\n const rest = textCode === code ? text.replace(CODE_PREFIX, '') : text\n return rest ? `${code}: ${rest}` : `${code}: the graph endpoint refused the read`\n}\n\n/** The endpoint says it cut the reply short (facts.query.truncated). */\nfunction cutByEndpoint(answer: GraphQueryAnswer): boolean {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n return isRecord(query) && query.truncated === true\n}\n\nfunction rowsOf(answer: GraphQueryAnswer): Row[] | null {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n const results = isRecord(query) ? query.results : undefined\n return Array.isArray(results) ? results.filter(isRecord) : null\n}\n\ntype Checked<T> = T | { error: string }\n\nfunction checkNetwork(args: Record<string, unknown>): Checked<string> {\n const rawNetwork = typeof args.network === 'string' ? args.network.trim().toLowerCase() : ''\n if (!rawNetwork) return { error: 'invalid_network: network is required; pass robinhood' }\n if (rawNetwork !== FLOWS_NETWORK) {\n return {\n error: `invalid_network: graph_expand reads the robinhood graph only; got \"${String(args.network).trim()}\"`,\n }\n }\n return FLOWS_NETWORK\n}\n\n/** The address of a node or of one end of a link; `name` says which end in a link refusal. */\nfunction checkAddress(raw: unknown, name?: string): Checked<string> {\n const address = normalizeFlowsAddress(raw)\n if (address) return address\n return {\n error: name\n ? INVALID_ADDRESS_TEXT.replace('invalid_address:', `invalid_address (${name}):`)\n : INVALID_ADDRESS_TEXT,\n }\n}\n\nfunction checkDay(raw: unknown): Checked<string> {\n const day = normalizeFlowsDay(raw)\n return day ?? { error: INVALID_DAY_TEXT }\n}\n\nfunction checkLimit(value: unknown): Checked<number> {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > TRANSFERS_MAX) {\n return { error: INVALID_LIMIT_TEXT }\n }\n return value\n}\n\nfunction checkSkip(value: unknown): Checked<number> {\n if (value === undefined || value === null) return 0\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) return { error: INVALID_SKIP_TEXT }\n return value\n}\n\nfunction checkFirstDay(value: unknown, day: string): Checked<string | null> {\n if (value === undefined || value === null) return null\n const first = normalizeFlowsDay(value)\n if (!first || first > day) return { error: INVALID_FIRST_DAY_TEXT }\n return first\n}\n\nfunction checkOffset(value: unknown): Checked<number> {\n if (value === undefined || value === null) return 0\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n return { error: OFFSET_NEGATIVE_TEXT }\n }\n if (value > FLOWS_MAX_OFFSET) return { error: OFFSET_TOO_LARGE_TEXT }\n return value\n}\n\n/**\n * Read and answer one node page. The reads run one after another: the node\n * first, so an address the graph does not hold costs one read; then the\n * receivers and the senders, the chunks of a side joined in order. A chunk that\n * comes back short, and not cut by the endpoint, ends its side, so the next\n * chunk of that side is not read or billed. The first read that does not\n * answer ends the call.\n */\nasync function runNode(\n deps: FlowsDependencies,\n network: string,\n address: string,\n inOffset: number,\n outOffset: number\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n // The lane's shape first: a read that fails keeps the reads of 0.82.0.\n let shape: SwapLinkShape = 'route'\n if (deps.linkShape) {\n try {\n shape = await deps.linkShape(network)\n } catch {\n shape = 'route'\n }\n }\n const rows: Record<FlowsRead['id'], Row[]> = { node: [], out: [], in: [] }\n const ended = new Set<FlowsRead['id']>()\n for (const read of flowsReadsFor(address, inOffset, outOffset, shape)) {\n if (ended.has(read.id)) continue\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: read.query })\n } catch (err) {\n return failedRead(deps, err)\n }\n if (answer.isError === true) return errorResult(refusalText(answer))\n const found = rowsOf(answer)\n if (!found) {\n return errorResult(\n 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows'\n )\n }\n rows[read.id].push(...found)\n if (read.id === 'node' && found.length === 0) {\n return errorResult(`${address} is not in the ${network} topology graph`)\n }\n if (found.length < read.limit && !cutByEndpoint(answer)) ended.add(read.id)\n }\n const view = buildFlowView(network, {\n center: rows.node[0] ?? {},\n senders: rows.in,\n receivers: rows.out,\n inOffset,\n outOffset,\n ...(shape === 'levels' ? { shape } : {}),\n })\n const now = deps.now ? deps.now() : new Date()\n return {\n content: [{ type: 'text', text: flowsSummary(view, now) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** Read and answer the transfers of one link on one day: a single facts read. */\nasync function runLink(\n deps: FlowsDependencies,\n network: string,\n from: string,\n to: string,\n day: string\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: transfersReadFor(from, to, day) })\n } catch (err) {\n return failedRead(deps, err)\n }\n if (answer.isError === true) return errorResult(refusalText(answer))\n const rows = rowsOf(answer)\n if (!rows) {\n return errorResult(\n 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows'\n )\n }\n const view = buildTransfersView(network, from, to, day, rows)\n return {\n content: [{ type: 'text', text: transfersSummary(view) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** One facts read of a day, as the paged walk needs it: the rows newest first, or the error that ends the call. */\nasync function readDay(\n deps: FlowsDependencies,\n network: string,\n from: string,\n to: string,\n day: string\n): Promise<{ rows: TransferRow[]; cut: boolean } | { error: string }> {\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: transfersReadFor(from, to, day) })\n } catch (err) {\n return { error: deps.describeFailure(err) }\n }\n if (answer.isError === true) return { error: refusalText(answer) }\n const rows = rowsOf(answer)\n if (!rows) {\n return { error: 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows' }\n }\n const newestFirst = rows\n .map(transferOf)\n .sort((a, b) => (b.block_timestamp ?? -Infinity) - (a.block_timestamp ?? -Infinity))\n return { rows: newestFirst, cut: rows.length >= TRANSFERS_READ_ROWS }\n}\n\n/**\n * Read and answer one page of a link's transfers: from `day` back, one day a\n * read, until the page holds `limit` transfers, TRANSFERS_MAX_DAYS days were\n * read, or the day before first_day is reached. `skip` passes over the\n * transfers of `day` an earlier page listed. The first read that does not\n * answer ends the call.\n */\nasync function runLinkPage(\n deps: FlowsDependencies,\n network: string,\n from: string,\n to: string,\n day: string,\n page: TransfersPageRequest\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n const floor = page.firstDay ?? TRANSFERS_FLOOR_DAY\n const transfers: TransferRow[] = []\n let current = day\n let skip = page.skip\n let daysRead = 0\n let through = day\n let truncated = false\n let next: TransfersCursor | null = null\n for (;;) {\n if (current < floor) break\n if (daysRead >= TRANSFERS_MAX_DAYS) {\n next = { day: current, skip }\n break\n }\n const read = await readDay(deps, network, from, to, current)\n if ('error' in read) return errorResult(read.error)\n daysRead += 1\n through = current\n if (read.cut) truncated = true\n const rest = read.rows.slice(skip)\n const room = page.limit - transfers.length\n if (rest.length > room) {\n transfers.push(...rest.slice(0, room))\n next = { day: current, skip: skip + room }\n break\n }\n transfers.push(...rest)\n const earlier = dayBefore(current)\n if (transfers.length >= page.limit) {\n next = earlier < floor ? null : { day: earlier, skip: 0 }\n break\n }\n current = earlier\n skip = 0\n }\n const view: TransfersView = {\n schema: TRANSFERS_SCHEMA,\n network,\n from,\n to,\n day,\n transfers,\n truncated,\n through_day: through,\n days_read: daysRead,\n next,\n }\n return {\n content: [{ type: 'text', text: transfersSummary(view) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** Read and answer the details of one address: a single anchored topology read. */\nasync function runDetails(\n deps: FlowsDependencies,\n network: string,\n address: string\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: detailsReadFor(address) })\n } catch (err) {\n return failedRead(deps, err)\n }\n if (answer.isError === true) return errorResult(refusalText(answer))\n const rows = rowsOf(answer)\n if (!rows) {\n return errorResult(\n 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows'\n )\n }\n if (rows.length === 0) return errorResult(`${address} is not in the ${network} topology graph`)\n const view = buildAddressView(network, address, rows[0]!)\n return {\n content: [{ type: 'text', text: addressSummary(view) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\nfunction given(record: Record<string, unknown>, keys: string[]): boolean {\n return keys.some((key) => record[key] !== undefined && record[key] !== null)\n}\n\n/**\n * graph_expand, the node form {network, address, in_offset?, out_offset?} or the\n * link form {network, from, to, day}. Every argument is checked before the\n * first read.\n */\nexport async function handleGraphExpand(\n args: unknown,\n deps: FlowsDependencies\n): Promise<FlowsToolResult> {\n const record = isRecord(args) ? args : {}\n const network = checkNetwork(record)\n if (typeof network !== 'string') return errorResult(network.error)\n\n const isLink = given(record, ['from', 'to', 'day'])\n if (isLink && given(record, ['address', 'in_offset', 'out_offset', 'details']))\n return errorResult(BOTH_FORMS_TEXT)\n\n if (isLink) {\n const from = checkAddress(record.from, 'from')\n if (typeof from !== 'string') return errorResult(from.error)\n const to = checkAddress(record.to, 'to')\n if (typeof to !== 'string') return errorResult(to.error)\n const day = checkDay(record.day)\n if (typeof day !== 'string') return errorResult(day.error)\n // A limit, a skip or a first_day asks for a page across days; without them the call is the one-day read.\n if (given(record, ['limit', 'skip', 'first_day'])) {\n const limit = checkLimit(record.limit)\n if (typeof limit !== 'number') return errorResult(limit.error)\n const skip = checkSkip(record.skip)\n if (typeof skip !== 'number') return errorResult(skip.error)\n const firstDay = checkFirstDay(record.first_day, day)\n if (firstDay !== null && typeof firstDay !== 'string') return errorResult(firstDay.error)\n return runLinkPage(deps, network, from, to, day, { skip, firstDay, limit })\n }\n return runLink(deps, network, from, to, day)\n }\n\n if (record.details !== undefined && record.details !== null) {\n if (record.details !== true) return errorResult(DETAILS_FORM_TEXT)\n if (given(record, ['in_offset', 'out_offset'])) return errorResult(DETAILS_FORM_TEXT)\n const address = checkAddress(record.address)\n if (typeof address !== 'string') return errorResult(address.error)\n return runDetails(deps, network, address)\n }\n\n const address = checkAddress(record.address)\n if (typeof address !== 'string') return errorResult(address.error)\n const inOffset = checkOffset(record.in_offset)\n if (typeof inOffset !== 'number') return errorResult(inOffset.error)\n const outOffset = checkOffset(record.out_offset)\n if (typeof outOffset !== 'number') return errorResult(outOffset.error)\n return runNode(deps, network, address, inOffset, outOffset)\n}\n\nexport const GRAPH_EXPAND_TITLE = 'Expand a node or a link in the picture'\n\nexport const GRAPH_EXPAND_DESCRIPTION =\n 'Expand an open Chain Insights picture. Called by the view when the investigator clicks, never by the model. ' +\n 'A node, {network, address, in_offset?, out_offset?}, loads the newest senders and receivers of one address ' +\n '(up to 250 a side, from the offsets); on a lane whose money family lists ROUTED_TO a side holds its swap routes too, ' +\n 'each one step that changes the asset with link_kind ROUTED_TO, never a router or a pool as a holder; ' +\n 'billed as at most five graph_query topology reads. A link, {network, from, to, day}, ' +\n 'lists the transfers between two addresses on one UTC day (YYYY-MM-DD), newest first, at most 50; billed as ' +\n 'one graph_query facts read. A link page, {network, from, to, day, limit, skip?, first_day?}, lists `limit` (1-50) ' +\n 'transfers from `day` back across days, newest first, and answers a `next` cursor ({day, skip}) while older ones ' +\n 'remain; billed as at most seven facts reads (a week). Details, {network, address, details: true}, answer the lifetime totals, ' +\n 'counts, role and labels of one address; billed as one topology read. Read-only; an argument refused before a read costs nothing.'\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { CACHE_TTL_MS, chainInsightsHome } from './cache-location.js'\nimport type { GraphSchemaDocument } from './graph-schema.js'\n\n// The graph schema of one network on one endpoint, kept on disk beside the tool\n// list cache (src/mcp/schema-cache.ts) with the same home and the same 24 hour\n// lifetime: ~/.chain-insights/cache/schema-<network>-<endpoint hash>.json.\n//\n// A schema built while a read failed is kept for a short time only. Kept for\n// 24 hours, one refused or rate-limited read would hide a section of the schema\n// for a whole day.\n\n/** How long a schema with a failed read stays fresh. */\nexport const PARTIAL_SCHEMA_TTL_MS = 10 * 60 * 1000\n\ninterface GraphSchemaCacheFile {\n cached_at: number\n complete: boolean\n endpoint: string\n document: GraphSchemaDocument\n}\n\nfunction endpointHash(endpoint: string): string {\n return createHash('sha256').update(endpoint).digest('hex').slice(0, 12)\n}\n\n/** The cache file of a network on an endpoint. The network is an identifier already checked by the caller. */\nexport function graphSchemaCachePath(network: string, endpoint: string): string {\n return path.join(chainInsightsHome(), 'cache', `schema-${network}-${endpointHash(endpoint)}.json`)\n}\n\n/**\n * The cached schema, marked cached, or null when there is none, it is stale, or\n * the file cannot be read. A cache is derived data: a damaged file is a miss and\n * the next build replaces it.\n */\nexport async function loadGraphSchemaCache(\n network: string,\n endpoint: string,\n now: Date\n): Promise<GraphSchemaDocument | null> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(graphSchemaCachePath(network, endpoint), 'utf8'))\n } catch {\n return null\n }\n const file = parsed as Partial<GraphSchemaCacheFile> | null\n if (\n !file ||\n typeof file.cached_at !== 'number' ||\n file.endpoint !== endpoint ||\n file.document?.schema !== 'chain-insights.graph-schema.v1'\n ) {\n return null\n }\n const lifetime = file.complete === true ? CACHE_TTL_MS : PARTIAL_SCHEMA_TTL_MS\n const age = now.getTime() - file.cached_at\n if (age < 0 || age > lifetime) return null\n return { ...file.document, cached: true }\n}\n\n/** `network` is the name the caller asked for, the same one a later load asks with. */\nexport async function saveGraphSchemaCache(\n network: string,\n document: GraphSchemaDocument,\n endpoint: string,\n complete: boolean,\n now: Date\n): Promise<void> {\n const target = graphSchemaCachePath(network, endpoint)\n const file: GraphSchemaCacheFile = {\n cached_at: now.getTime(),\n complete,\n endpoint,\n document: { ...document, cached: false },\n }\n await mkdir(path.dirname(target), { recursive: true })\n // Written beside the target and renamed, so a second proxy reading the file\n // never sees half of it.\n const scratch = `${target}.${process.pid}.tmp`\n await writeFile(scratch, JSON.stringify(file, null, 2) + '\\n', { mode: 0o600 })\n await rename(scratch, target)\n}\n","/**\n * meta_schema: the live graph schema of one network, read from the graph\n * endpoint and kept on disk for 24 hours.\n *\n * The graph serves four read-only catalog statements on `USE topology` through\n * the ordinary graph_query tool: `CALL db.labels()`, `CALL db.relationshipTypes()`,\n * `CALL db.propertyKeys()` and `SHOW INDEXES`. They name the labels, the link\n * types, every property key and the indexes. They do not say which keys belong to\n * which kind, so the main kinds are sampled with the two probe forms the server\n * admits (`keys(a)` on addresses, `keys(r)` on a link). The facts relationships\n * and the chain lookups come from the network's published capabilities.\n *\n * One build is one MCP session and runs its reads one after another: the public\n * endpoint allows about 30 requests a minute for each IP address, and opening a\n * session costs three of them. A read that fails leaves its section empty and\n * adds a note. It never fails the tool.\n */\n\nimport { findNetworkCapability, mirrorGraphNetworkCapabilities } from './capabilities.js'\nimport type { NetworkCapability } from './capabilities.js'\nimport { PaymentRequiredError } from './client.js'\nimport { CONTRACT_READ_PROPERTIES } from './contract-read.js'\nimport { refusalText, type GraphQueryAnswer } from './flows.js'\nimport { loadGraphSchemaCache, saveGraphSchemaCache } from './graph-schema-cache.js'\nimport { levelLines, swapLinkShape } from './layer-routing.js'\n\nexport const GRAPH_SCHEMA_ID = 'chain-insights.graph-schema.v1' as const\nexport const GRAPH_SCHEMA_SOURCE = 'live catalog' as const\nexport const META_SCHEMA_TITLE = 'Graph schema'\nexport const META_SCHEMA_DESCRIPTION =\n 'Return the live graph schema of one network: the labels, the link types, the field names of an address and of each main link, the indexes, the USE facts relationships with the TRANSFER columns and the properties of the Contract read, and the USE chain lookups. ' +\n 'Call it first when you need field names. It is cached for 24 hours; pass refresh=true to rebuild it.'\n\n/** Fields of an address come from this many sampled nodes, and of a link from this many sampled links. */\nexport const ADDRESS_SAMPLE_LIMIT = 20\nexport const LINK_SAMPLE_LIMIT = 5\n\n/** The link types an agent queries. Each is sampled only when the graph lists it. */\nexport const SAMPLED_LINK_TYPES = [\n 'FLOWED_TO',\n 'ROUTED_TO',\n 'OPERATED_BY',\n 'LINKED',\n 'SWAPPED',\n 'BRIDGED',\n 'ADDED_LIQUIDITY',\n 'REMOVED_LIQUIDITY',\n 'SWEPT',\n] as const\n\n/**\n * The values of `cex_role` on an `:Exchange` address: which wallet of its\n * exchange the address is. The labels layer sets it from the exchange label's\n * subtype; `SWEPT` (layer `cex_sweeps`) runs from a `deposit` to the\n * `hot_wallet` it swept into.\n */\nexport const CEX_ROLES = ['deposit', 'hot_wallet', 'cold_wallet', 'withdrawal'] as const\n\n/** The note a schema carries when the graph serves `SWEPT` or `cex_role`. */\nexport const EXCHANGE_SCHEMA_NOTE =\n `cex_role on an :Exchange address says which wallet of its exchange it is: ${CEX_ROLES.join(', ')}. ` +\n 'SWEPT runs from an exchange deposit to the hot wallet it swept into; a trail that reaches it ends there. ' +\n 'inferred_exchange_role (deposit or hot_wallet) is the exchange model\\'s guess, with its ml:exchange-roles:<model>:<basis> entry in inferred_sources: never a label, never a SWEPT link, and always said as inferred by that model.'\n\n// The TRANSFER columns the cypher skill lists, in its order. tests/graph-schema.test.ts\n// holds this list to the skill and to the columns the graph server maps on TRANSFER\n// (tests/fixtures/facts-columns.json).\nexport const FACTS_TRANSFER_COLUMNS = [\n 'tx_id',\n 'block_date',\n 'block_height',\n 'block_timestamp',\n 'event_index',\n 'edge_index',\n 'kind',\n 'asset_contract',\n 'asset_symbol',\n 'amount',\n 'amount_usd',\n 'price_usd',\n 'price_missing',\n 'token_id',\n 'token_standard',\n 'operator_address',\n 'raw_amount',\n 'decimals',\n] as const\n\n// `CALL db.schema.visualization()` is not read. It bills about 427 units where\n// the four statements below bill 13 to 133 each, and it adds only which labels a\n// link type joins, which the cypher skill and the served hints already say.\nconst CATALOG_READS = {\n labels: { label: 'labels', query: 'USE topology CALL db.labels()' },\n linkTypes: { label: 'link types', query: 'USE topology CALL db.relationshipTypes()' },\n propertyKeys: { label: 'property keys', query: 'USE topology CALL db.propertyKeys()' },\n indexes: { label: 'indexes', query: 'USE topology SHOW INDEXES' },\n} as const\n\nexport function addressSampleQuery(): string {\n return `USE topology MATCH (a:Address) RETURN keys(a) AS keys LIMIT ${ADDRESS_SAMPLE_LIMIT}`\n}\n\nexport function linkSampleQuery(linkType: string): string {\n return `USE topology MATCH ()-[r:${linkType}]->() RETURN keys(r) AS keys LIMIT ${LINK_SAMPLE_LIMIT}`\n}\n\nexport interface GraphSchemaIndex {\n name: string\n entity: 'node' | 'link'\n /** The labels of a node index, the link types of a link index. */\n types: string[]\n properties: string[]\n state: string\n}\n\nexport interface GraphSchemaDocument {\n schema: typeof GRAPH_SCHEMA_ID\n network: string\n built_at: string\n source: typeof GRAPH_SCHEMA_SOURCE\n cached: boolean\n /** Units the reads of the build billed, summed from the replies. A cached document keeps the units of its build. */\n billed_units: number\n layers: {\n topology: {\n labels: string[]\n link_types: string[]\n property_keys: string[]\n indexes: GraphSchemaIndex[]\n samples: Record<string, string[]>\n }\n /** `contract_properties` is what `MATCH (c:Contract {address})` returns; a schema cached before it has none. */\n facts: { relationships: string[]; transfer_columns: string[]; contract_properties?: string[] }\n chain: { lookups: string[] }\n }\n /** `levels` when the lane serves ROUTED_TO; absent on the graph of before. */\n swap_links?: 'levels'\n notes: string[]\n}\n\n/** A refusal with its own words for the caller: a bad argument, an unserved network, an endpoint that is down. */\nexport class GraphSchemaError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'GraphSchemaError'\n }\n}\n\nexport interface GraphSchemaClient {\n callTool(request: { name: string; arguments: Record<string, unknown> }): Promise<unknown>\n}\n\ntype Row = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction sortedUnique(values: Iterable<string>): string[] {\n return [...new Set(values)].sort()\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string' && entry !== '')\n : []\n}\n\nconst NETWORK_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/\n\n/**\n * The network as a lower-case identifier. It becomes part of a file name and of\n * every query, so only an identifier passes.\n */\nexport function normalizeSchemaNetwork(raw: unknown): string {\n const network = typeof raw === 'string' ? raw.trim().toLowerCase() : ''\n if (!network) {\n throw new GraphSchemaError(\n 'invalid_network: network is required. Pass the identifier of a served network, for example robinhood.'\n )\n }\n if (!NETWORK_PATTERN.test(network)) {\n throw new GraphSchemaError(\n `invalid_network: \"${String(raw).trim()}\" is not a network identifier. Pass the identifier of a served network, for example robinhood.`\n )\n }\n return network\n}\n\n// ─── Reading ──────────────────────────────────────────────────────────────────\n\nfunction queryBlock(structured: unknown): Row | null {\n const facts = isRecord(structured) ? structured.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n return isRecord(query) ? query : null\n}\n\n/** The `facts.query` block of one graph_query reply, from structuredContent or from the JSON text. */\nfunction answerQuery(answer: GraphQueryAnswer): Row | null {\n const fromStructured = queryBlock(answer.structuredContent)\n if (fromStructured) return fromStructured\n for (const block of answer.content ?? []) {\n if (block.type !== 'text' || typeof block.text !== 'string') continue\n try {\n const parsed = queryBlock(JSON.parse(block.text))\n if (parsed) return parsed\n } catch {\n /* not JSON: try the next block */\n }\n }\n return null\n}\n\n// A failure after which every later read would fail the same way: the endpoint\n// limits requests, or it asks for payment. The build stops sending reads.\ntype Halt = 'rate_limit' | 'payment'\n\nfunction haltOfError(err: unknown): Halt | undefined {\n if (err instanceof PaymentRequiredError) return 'payment'\n const code = isRecord(err) ? err.code : undefined\n const message = err instanceof Error ? err.message : String(err)\n if (code === 429 || /\\b429\\b|too many requests|rate.?limit/i.test(message)) return 'rate_limit'\n if (/\\b402\\b|payment required/i.test(message)) return 'payment'\n return undefined\n}\n\nfunction haltOfAnswer(answer: GraphQueryAnswer): Halt | undefined {\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n return isRecord(detail) && detail.class === 'capacity' ? 'rate_limit' : undefined\n}\n\nexport interface BuildOptions {\n client: GraphSchemaClient\n /** A normalized network identifier. */\n network: string\n now?: () => Date\n /** A wait between two reads, in milliseconds. One build needs none: it stays under the rate limit. */\n pauseMs?: number\n sleep?: (ms: number) => Promise<void>\n}\n\nexport interface BuildResult {\n document: GraphSchemaDocument\n /** False when a read failed: the document has a section missing. */\n complete: boolean\n}\n\nfunction describeIndex(row: Row): GraphSchemaIndex | null {\n const name = typeof row.name === 'string' ? row.name : ''\n const entity =\n row.entityType === 'NODE' ? 'node' : row.entityType === 'RELATIONSHIP' ? 'link' : null\n const properties = stringList(row.properties)\n // A lookup index names no label and no property: it tells an agent nothing.\n if (!name || !entity || properties.length === 0) return null\n return {\n name,\n entity,\n types: stringList(row.labelsOrTypes),\n properties,\n state: typeof row.state === 'string' && row.state ? row.state : 'unknown',\n }\n}\n\nexport async function buildGraphSchema(options: BuildOptions): Promise<BuildResult> {\n const { client } = options\n const now = options.now ?? (() => new Date())\n const pauseMs = options.pauseMs ?? 0\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms)))\n\n const problems: string[] = []\n const remarks: string[] = []\n let billed = 0\n let calls = 0\n let halted = false\n\n async function pace(): Promise<void> {\n if (calls > 0 && pauseMs > 0) await sleep(pauseMs)\n calls += 1\n }\n\n function fail(label: string, reason: string, halt?: Halt): null {\n problems.push(`${label} could not be read: ${reason}`)\n if (halt && !halted) {\n halted = true\n if (halt === 'payment') {\n problems.push(\n 'The endpoint asks for payment, so the reads after it were not sent. Fix the payment setup, then call again with refresh=true.'\n )\n } else {\n // The endpoint says how long to wait: \"retry after 23 seconds\".\n const wait = /retry after (\\d+) seconds?/i.exec(reason)?.[1]\n problems.push(\n `The endpoint is limiting requests, so the reads after it were not sent. Call again after ${wait ? `${wait} seconds` : 'a minute'} with refresh=true.`\n )\n }\n }\n return null\n }\n\n async function graphRead(network: string, label: string, query: string): Promise<Row[] | null> {\n if (halted) return null\n await pace()\n let answer: GraphQueryAnswer\n try {\n answer = (await client.callTool({\n name: 'graph_query',\n arguments: { network, query },\n })) as GraphQueryAnswer\n } catch (err) {\n return fail(label, err instanceof Error ? err.message : String(err), haltOfError(err))\n }\n const block = answerQuery(answer ?? {})\n if (block && typeof block.billable_units === 'number') billed += block.billable_units\n if (answer?.isError === true) {\n return fail(label, refusalText(answer), haltOfAnswer(answer))\n }\n if (!block || !Array.isArray(block.results)) {\n return fail(label, 'the reply holds no rows')\n }\n return block.results.filter(isRecord)\n }\n\n // ── The network: capabilities first, so an unserved name costs no graph read.\n let network = options.network\n let capability: NetworkCapability | undefined\n await pace()\n try {\n const answer = (await client.callTool({\n name: 'network_capabilities',\n arguments: {},\n })) as GraphQueryAnswer\n if (answer?.isError === true) {\n fail('network capabilities', refusalText(answer), haltOfAnswer(answer))\n } else {\n const facts = isRecord(answer?.structuredContent) ? answer.structuredContent.facts : undefined\n const capabilities = isRecord(facts) ? facts.capabilities : undefined\n const networks =\n isRecord(capabilities) && Array.isArray(capabilities.networks)\n ? capabilities.networks\n : null\n if (!networks) {\n fail('network capabilities', 'the reply lists no networks')\n } else {\n const document = mirrorGraphNetworkCapabilities({ networks })\n capability = findNetworkCapability(document, options.network)\n if (!capability) {\n const served = document.networks.map((entry) => entry.network).join(', ')\n throw new GraphSchemaError(\n `network_not_served: \"${options.network}\" is not a network this endpoint serves. Served networks: ${served || 'none'}.`\n )\n }\n network = capability.network\n }\n }\n } catch (err) {\n if (err instanceof GraphSchemaError) throw err\n fail('network capabilities', err instanceof Error ? err.message : String(err), haltOfError(err))\n }\n\n // ── Topology: the catalog, then a sample of the main kinds.\n const topology: GraphSchemaDocument['layers']['topology'] = {\n labels: [],\n link_types: [],\n property_keys: [],\n indexes: [],\n samples: {},\n }\n const topologyOff = capability?.layers?.topology?.enabled === false\n if (topologyOff) {\n remarks.push('The topology layer is off on this network.')\n } else {\n const labels = await graphRead(network, CATALOG_READS.labels.label, CATALOG_READS.labels.query)\n if (labels) topology.labels = sortedUnique(labels.flatMap((row) => stringList([row.label])))\n\n const linkTypes = await graphRead(\n network,\n CATALOG_READS.linkTypes.label,\n CATALOG_READS.linkTypes.query\n )\n if (linkTypes) {\n topology.link_types = sortedUnique(\n linkTypes.flatMap((row) => stringList([row.relationshipType]))\n )\n }\n\n const keys = await graphRead(\n network,\n CATALOG_READS.propertyKeys.label,\n CATALOG_READS.propertyKeys.query\n )\n if (keys) {\n topology.property_keys = sortedUnique(keys.flatMap((row) => stringList([row.propertyKey])))\n }\n\n const indexes = await graphRead(\n network,\n CATALOG_READS.indexes.label,\n CATALOG_READS.indexes.query\n )\n if (indexes) {\n topology.indexes = indexes\n .map(describeIndex)\n .filter((index): index is GraphSchemaIndex => index !== null)\n .sort((a, b) => a.name.localeCompare(b.name))\n }\n\n // An address is sampled unless the label list was read and has no Address.\n const labelsRead = labels !== null\n if (!labelsRead || topology.labels.includes('Address')) {\n const rows = await graphRead(network, 'the Address sample', addressSampleQuery())\n if (rows) topology.samples['Address'] = unionOfKeys(rows)\n }\n\n const sampled = SAMPLED_LINK_TYPES.filter((type) => topology.link_types.includes(type))\n if (linkTypes === null && !halted) {\n problems.push('The link samples were skipped: the link types are unknown.')\n }\n for (const type of sampled) {\n const rows = await graphRead(network, `the ${type} sample`, linkSampleQuery(type))\n if (rows) topology.samples[type] = unionOfKeys(rows)\n }\n\n const unsampled = topology.link_types.filter(\n (type) => !(SAMPLED_LINK_TYPES as readonly string[]).includes(type)\n )\n if (unsampled.length > 0) {\n remarks.push(\n `Link types with no sample: ${unsampled.join(', ')}. Read the keys of one with USE topology MATCH ()-[r:<TYPE>]->() RETURN keys(r) AS keys LIMIT ${LINK_SAMPLE_LIMIT}.`\n )\n }\n }\n\n // ── Facts and chain: what the network publishes.\n const facts: GraphSchemaDocument['layers']['facts'] = { relationships: [], transfer_columns: [] }\n const chain: GraphSchemaDocument['layers']['chain'] = { lookups: [] }\n if (capability) {\n if (capability.layers?.facts?.enabled === false) {\n remarks.push('The facts layer is off on this network.')\n } else {\n facts.relationships = stringList(capability.layers?.facts?.relationships)\n if (facts.relationships.includes('TRANSFER')) {\n facts.transfer_columns = [...FACTS_TRANSFER_COLUMNS]\n }\n facts.contract_properties = [...CONTRACT_READ_PROPERTIES]\n }\n const admission = capability.chain_admission\n if (admission?.enabled === false) {\n remarks.push(`The chain layer is off (status ${admission.status ?? 'unknown'}).`)\n } else {\n chain.lookups = stringList(admission?.lookups)\n }\n }\n\n const words = [...topology.property_keys, ...Object.values(topology.samples).flat()]\n if (words.includes('synced_through_height') || words.includes('pair_key')) {\n remarks.push(\n 'synced_through_height and pair_key are sync bookkeeping: never filter or sort on them.'\n )\n }\n if (topology.link_types.includes('SWEPT') || topology.property_keys.includes('cex_role')) {\n remarks.push(EXCHANGE_SCHEMA_NOTE)\n }\n // The lane's graph shape: its money family lists ROUTED_TO, or the catalog\n // does. The graph of before gets no remark, so its schema reads as in 0.81.0.\n const levels =\n swapLinkShape(capability?.graph_progress?.families) === 'levels' ||\n topology.link_types.includes('ROUTED_TO')\n if (levels) remarks.push(levelLines().join(' '))\n remarks.push('Fields come from a sample of the live graph. A rare field may be missing.')\n\n return {\n complete: problems.length === 0,\n document: {\n schema: GRAPH_SCHEMA_ID,\n network,\n built_at: now().toISOString(),\n source: GRAPH_SCHEMA_SOURCE,\n cached: false,\n billed_units: billed,\n layers: { topology, facts, chain },\n ...(levels ? { swap_links: 'levels' as const } : {}),\n notes: [...problems, ...remarks],\n },\n }\n}\n\nfunction unionOfKeys(rows: Row[]): string[] {\n return sortedUnique(rows.flatMap((row) => stringList(row.keys)))\n}\n\n// ─── Reading from the cache, or building ──────────────────────────────────────\n\nexport interface GetGraphSchemaOptions {\n /** As the caller wrote it: normalized here. */\n network: unknown\n refresh?: boolean\n endpoint: string\n /**\n * Runs `fn` with one connected client. It is called once for a build and not at\n * all when the cache answers, so a cache hit opens no session.\n */\n withClient: <T>(fn: (client: GraphSchemaClient) => Promise<T>) => Promise<T>\n now?: () => Date\n pauseMs?: number\n sleep?: (ms: number) => Promise<void>\n}\n\n// Builds in flight, by endpoint and network: two callers that ask for one\n// schema at once share one build and pay for it once.\nconst building = new Map<string, Promise<GraphSchemaDocument>>()\n\nexport async function getGraphSchema(options: GetGraphSchemaOptions): Promise<GraphSchemaDocument> {\n const network = normalizeSchemaNetwork(options.network)\n const now = options.now ?? (() => new Date())\n if (options.refresh !== true) {\n const cached = await loadGraphSchemaCache(network, options.endpoint, now())\n if (cached) return cached\n }\n const key = `${options.endpoint}\\n${network}`\n const running = building.get(key)\n if (running) return running\n const build = (async () => {\n const { document, complete } = await options.withClient((client) =>\n buildGraphSchema({\n client,\n network,\n now,\n ...(options.pauseMs === undefined ? {} : { pauseMs: options.pauseMs }),\n ...(options.sleep ? { sleep: options.sleep } : {}),\n })\n )\n try {\n await saveGraphSchemaCache(network, document, options.endpoint, complete, now())\n } catch (err) {\n document.notes.push(\n `The schema could not be saved to the cache: ${err instanceof Error ? err.message : String(err)}`\n )\n }\n return document\n })()\n building.set(key, build)\n try {\n return await build\n } finally {\n building.delete(key)\n }\n}\n\n// ─── Text ─────────────────────────────────────────────────────────────────────\n\nfunction listLine(title: string, values: string[], empty = 'none read'): string {\n return `${title}: ${values.length > 0 ? values.join(', ') : empty}`\n}\n\n/** The schema as the model and the terminal read it. */\nexport function formatGraphSchemaText(document: GraphSchemaDocument): string {\n const { topology, facts, chain } = document.layers\n const origin = document.cached\n ? 'from the cache, kept 24 hours; refresh=true rebuilds it'\n : `read now for ${document.billed_units} billed units and cached for 24 hours`\n const lines = [\n `Graph schema, network ${document.network}`,\n `Source: ${document.source}, built ${document.built_at} (${origin})`,\n '',\n 'USE topology',\n listLine('Labels', topology.labels),\n listLine('Link types', topology.link_types),\n listLine(`Property keys (${topology.property_keys.length})`, topology.property_keys),\n ]\n lines.push(topology.indexes.length > 0 ? 'Indexes:' : 'Indexes: none read')\n for (const index of topology.indexes) {\n lines.push(\n `- ${index.entity} ${index.types.join('|')}(${index.properties.join(', ')}) ${index.state}`\n )\n }\n const sampled = Object.entries(topology.samples)\n lines.push(sampled.length > 0 ? 'Fields, from a sample:' : 'Fields, from a sample: none read')\n for (const [kind, fields] of sampled) lines.push(`- ${kind}: ${fields.join(', ')}`)\n lines.push(\n '',\n 'USE facts',\n listLine('Relationships', facts.relationships),\n listLine('TRANSFER columns', facts.transfer_columns),\n ...(facts.contract_properties?.length\n ? [listLine('Contract properties, one contract by its address', facts.contract_properties)]\n : []),\n '',\n 'USE chain',\n listLine('Lookups', chain.lookups)\n )\n if (document.notes.length > 0) {\n lines.push('', 'Notes:', ...document.notes.map((note) => `- ${note}`))\n }\n return lines.join('\\n')\n}\n\n// ─── The MCP tool ─────────────────────────────────────────────────────────────\n\nexport interface GraphSchemaDependencies {\n endpoint: string\n withClient: GetGraphSchemaOptions['withClient']\n /** The text of a failure that is not a GraphSchemaError: payment required, transport. */\n describeFailure: (err: unknown) => string\n now?: () => Date\n pauseMs?: number\n sleep?: (ms: number) => Promise<void>\n}\n\nexport type MetaSchemaResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nfunction errorResult(text: string): MetaSchemaResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\n/** meta_schema, {network, refresh?}. Every argument is checked before the first read. */\nexport async function handleMetaSchema(\n args: unknown,\n deps: GraphSchemaDependencies\n): Promise<MetaSchemaResult> {\n const record = isRecord(args) ? args : {}\n const refresh = record.refresh\n if (refresh !== undefined && refresh !== null && typeof refresh !== 'boolean') {\n return errorResult('invalid_refresh: refresh must be true or false')\n }\n try {\n const document = await getGraphSchema({\n network: record.network,\n refresh: refresh === true,\n endpoint: deps.endpoint,\n withClient: deps.withClient,\n ...(deps.now ? { now: deps.now } : {}),\n ...(deps.pauseMs === undefined ? {} : { pauseMs: deps.pauseMs }),\n ...(deps.sleep ? { sleep: deps.sleep } : {}),\n })\n return {\n content: [{ type: 'text', text: formatGraphSchemaText(document) }],\n structuredContent: document as unknown as Record<string, unknown>,\n isError: false,\n }\n } catch (err) {\n return errorResult(err instanceof GraphSchemaError ? err.message : deps.describeFailure(err))\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,wBAAwB;;AAGrC,MAAa,2BAA2B;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,4BAA4B;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAWA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,wBACX,0CAA0C,sBAAsB;;AAKlE,MAAa,sBAAsB,0CAA0C,sBAAsB;;AAGnG,MAAa,wBACX;;AAGF,MAAa,uBACX;;;;;;AAOF,MAAa,qCACX,gHAAgH,oBAAoB,OAC9H,sBAAsB,QAAQ,oBAAoB,kCAAkC,EAAE,0LAEK;;AAGnG,MAAa,qBACX,oFAAoF,sBAAsB,yLAE3F,yBAAyB,KAAK,IAAI,EAAE,IAAI,oBAAoB,KAAK,IAAI,EAAE,uFAClC,0BAA0B,KAAK,IAAI,EAAE,ieAEoC,uBAAuB,KAAK,IAAI,EAAE,yhBAGsB;;ACnEvL,MAAa,eAAe;AAC5B,MAAa,oBAAoB;AACjC,MAAa,gBAAgB;;AAG7B,MAAa,iBAAiB;;AAE9B,MAAa,kBAAkB;;;;;AAK/B,MAAa,kBAAkB;;;;;AAK/B,MAAa,kBAAkB;;AAI/B,MAAa,mBAAmB;AAEhC,MAAa,mBAAmB;;AAEhC,MAAa,gBAAgB;;;;;;AAM7B,MAAa,sBAAsB;;AAEnC,MAAa,yBAAyB;;AAEtC,MAAa,qBAAqB;;AAElC,MAAa,sBAAsB;AAEnC,MAAa,iBAAiB;AAuG9B,MAAa,uBACX;AACF,MAAa,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D,GAAI,MAAM,qBAAqB,SAC3B,CAAC,SAAS,oDAAoD,MAAM,mBAAmB,CAAC,IACxF,CAAC,GACL,IACA,aACA,SAAS,WAAW,MAAM,OAAO,CACnC;CACA,IAAI,SAAS,MAAM,SAAS,GAC1B,MAAM,KAAK,IAAI,UAAU,GAAG,SAAS,MAAM,KAAK,SAAS,KAAK,MAAM,CAAC;CAEvE,OAAO,MAAM,KAAK,IAAI;AACxB;AAoBA,SAAS,YAAY,MAAgC;CACnD,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ;EAAK,CAAC;EAAG,SAAS;CAAK;AAC5D;;AAGA,eAAsB,iBACpB,MACA,MAC2B;CAC3B,MAAM,SAAS,SAAS,IAAI,IAAI,OAAO,CAAC;CACxC,MAAM,UAAU,OAAO;CACvB,IAAI,YAAY,KAAA,KAAa,YAAY,QAAQ,OAAO,YAAY,WAClE,OAAO,YAAY,gDAAgD;CAErE,IAAI;EACF,MAAM,WAAW,MAAM,eAAe;GACpC,SAAS,OAAO;GAChB,SAAS,YAAY;GACrB,UAAU,KAAK;GACf,YAAY,KAAK;GACjB,GAAI,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;GACpC,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,KAAK,QAAQ;GAC9D,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;EAC5C,CAAC;EACD,OAAO;GACL,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM,sBAAsB,QAAQ;GAAE,CAAC;GACjE,mBAAmB;GACnB,SAAS;EACX;CACF,SAAS,KAAK;EACZ,OAAO,YAAY,eAAe,mBAAmB,IAAI,UAAU,KAAK,gBAAgB,GAAG,CAAC;CAC9F;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"layer-routing-DCJVNN6O.mjs","names":[],"sources":["../src/mcp/layer-routing.ts"],"sourcesContent":["// The one source of the routing rule of the three read layers, and of the move\n// that each class of refusal asks of an agent.\n//\n// Three places teach them: the graph hints that the MCP proxy serves\n// (GRAPH_SCHEMA_HINTS in proxy.ts builds its two routing hints from this file),\n// the `chain-insights-cypher` skill and docs/graph-tools.md. The skill and the\n// guide are Markdown and hold the lines word for word. tests/layer-routing.test.ts\n// fails when one of the three differs from this file by one word.\n//\n// The rule follows the graph server's own: topology searches outward from one\n// known address, while facts and chain look up one known thing. The wording asks\n// the agent to say first what the question names (an address, a pair with a day,\n// a transaction, a block), because a question that names none of them is served\n// on no layer today. Nothing here is a limit. A limit that the server publishes\n// is read from `meta_network_capabilities`, and the text names the field, never\n// the number.\n//\n// `USE chain` serves the four labels of the server's chain catalogue and no\n// other: a transaction by its `tx_id`, a block by its `block_height` or its\n// `block_hash`, an address at one block (`Address`, with an optional `at_block`),\n// and the head, which takes no key. A kind (`:Account`, `:Contract`) is never a\n// lookup label: the `Address` lookup reads it as `is_contract` and `nonce`.\n// tests/fixtures/chain-catalogue.json pins the labels, and\n// tests/chain-catalogue-pin.test.ts holds every chain recipe and the chain\n// routing line to them. The depth below which a past block is served is a limit\n// that the server publishes, so the text names its field and never its number.\n\n/** The routing rule, in one sentence. The server states it in the same words. */\nexport const ROUTING_RULE =\n 'Route by what the question names: an address, a pair with a day, a transaction or a block. Topology searches outward from an address, while facts and chain look up one known thing.'\n\n/** The rule in three lines, one for each layer. */\nexport const ROUTING_LINES = [\n 'I know an address and want its links, senders, receivers, hops or a route: `USE topology`, anchored on that address.',\n 'I know both addresses of a pair and one day, and want the rows of that day: `USE facts`.',\n \"I want the chain's own record of a transaction by its `tx_id`, a block by its `block_height` or `block_hash`, an address at one block (`Address`), or the head: `USE chain`.\",\n] as const\n\n/**\n * One contract by its address is a facts lookup too, with one node and no day\n * (src/mcp/contract-read.ts holds the read and what its answer means).\n */\nexport const ROUTING_CONTRACT =\n '\"What is this contract\" and \"what can its owner do\", for one contract address, is a `USE facts` `Contract` read by that address, with no pair and no day.'\n\n/** The chain layer reads one address at one block. A search for counterparties stays on topology. */\nexport const ROUTING_ADDRESS_ON_CHAIN =\n '`USE chain` with `Address` reads the balance, the nonce or the kind of one address, now or at a past block with `at_block`. A past block must be at least `chain_admission.at_block_min_depth` blocks below the tip. To find the counterparties of an address, search `USE topology`, then read the pair and one day on `USE facts`.'\n\n/** What to do when two layers fit. */\nexport const ROUTING_TWO_FIT =\n 'A transaction is a chain question: read it on `USE chain` by its `tx_id`. Chain gives its `block_date`; the transfers between a pair on that day are a `USE facts` read.'\n\n/** The key that each layer hands to the next. Each key keeps its name. */\nexport const ROUTING_HANDOFF =\n 'The layers hand each other keys, and each key keeps its name. Topology gives the pair and the first and last seen time. Facts gives the `tx_id` and the `block_height`. Chain takes an `address`, a `tx_id`, a `block_height` or a `block_hash`, and gives the `block_date` of a transaction or a block.'\n\n/**\n * Where money entered an exchange: the link `SWEPT` (layer `cex_sweeps`, family\n * annotations) and the node property `cex_role`. A trail ends at it.\n */\nexport const ROUTING_SWEPT =\n \"`SWEPT` runs from an exchange deposit to the hot wallet it swept into (layer `cex_sweeps`, family annotations), and `cex_role` on an `:Exchange` address says which wallet of its exchange it is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. A trail that reaches a `SWEPT` link ends there: say the money entered the exchange at that deposit, swept n times into that hot wallet, name the exchange from `labels`, and never walk on past a hot wallet. Read `SWEPT` anchored on an address; call `aml_exchange_deposit_check` for one address and `meta_exchange_lookup` for an exchange by name. With no `cex_role`, `inferred_exchange_role` (`deposit` or `hot_wallet`, with its `ml:exchange-roles:` entry in `inferred_sources`) is the exchange model's guess, never a label: say it is inferred by that model, never a confirmed exchange address.\"\n\n/**\n * A whole-chain question is a time-bounded topology search, sent only when the\n * family of its link type is close to the head; a refusal names the family.\n */\nexport const ROUTING_NOT_SERVED =\n \"A question about the whole chain (recent activity, the biggest senders, a top list) is a `USE topology` search: bound it by time with `f.last_seen_timestamp >= <epoch ms>` on the `FLOWED_TO` link, then sort and `LIMIT`. A search has 10 s. Read `Head` first (`USE chain MATCH (h:Head) RETURN h.behind_money, h.behind_dex, h.behind_transfers`, under a second): a `FLOWED_TO` or `ROUTED_TO` search is sent when `behind_money` is at most 100000; a `SWAPPED`, `ADDED_LIQUIDITY` or `REMOVED_LIQUIDITY` search when `behind_dex` is at most 100000; a `TRANSFERRED` search when `behind_transfers` is at most 100000 (100000 blocks is a few hours: a robinhood block is about a tenth of a second apart from the next). When the family is further behind, the search cannot finish, so do not send it: say which family, how many blocks, and ask for an address. On a server whose Head has no `behind_money`, read `h.graph_blocks_behind` and hold it to the same limit. On a server whose Head has no `behind_transfers`, it serves no `TRANSFERRED` link: send no `TRANSFERRED` search. Never turn the block count into days or hours by head. To say how fresh the data is, give the newest `_utc` time you read on the layer you used: a family's lag counts its slowest layer, and the links of an address and the facts rows are often newer than it. If the server refuses the search with `anchor_missing` or `family_behind`, or stops it with `query_timeout`, it cannot search the whole chain now: say so in one line, name the family the refusal names, and ask for an address or drop the link type that is behind. A narrower window times out the same way, so do not send it again.\"\n\n/**\n * The level rule, in one sentence. The descriptions of graph_query and\n * meta_dex_lookup carry it word for word, so a host that loads no skill reads\n * it, and every skill that teaches the levels repeats it\n * (tests/host-parity.test.ts).\n */\nexport const LEVEL_RULE =\n 'Money is read on three levels: level 2 (`FLOWED_TO`, `ROUTED_TO`) traces money, one link per pair of addresses in USD, level 1 (`TRANSFERRED`, `SWAPPED`, `ADDED_LIQUIDITY`, `REMOVED_LIQUIDITY`) holds the assets and the pools, and a single transaction is a `USE facts` row.'\n\n/** Which links a trace walks, and which links answer a pool question. */\nexport const LEVEL_TRACE =\n \"Where money went or came from is a walk on `FLOWED_TO` and `ROUTED_TO`: a `ROUTED_TO` step is a swap that changes the asset, a self link when the payer got the bought asset itself, and the payer's `SWAPPED` links name what it sold, what it got and at which pool. A router or a pool never holds the money. Who traded at a pool is its `SWAPPED` links, each from a trader to the pool, and who provides its liquidity is `ADDED_LIQUIDITY` and `REMOVED_LIQUIDITY`.\"\n\n/** How a reader tells the two graph shapes apart, lane by lane. */\nexport const LEVEL_LANE =\n 'A lane whose `money` family in `meta_network_capabilities` lists no `ROUTED_TO` has the graph of before: there `SWAPPED` runs from a payer to a recipient and holds the whole route, with its `pools`.'\n\n/** What a pool is on the levels: no trace, its level 1 links. */\nexport const LEVEL_POOL =\n 'A pool has no level 2 link. Asked about a pool, say it is a pool and offer its traders and its liquidity providers from level 1, never an empty trace.'\n\n/** The actor exposure read (AC11 hint) on a lane with the levels. */\nexport const LEVEL_EXPOSURE =\n 'On a lane whose `money` family lists `ROUTED_TO`, the actor exposure read over one `LINKED` hop walks `FLOWED_TO|ROUTED_TO` and returns `r.amount_usd_sum` and `r.tx_count`, which both links carry, in place of `FLOWED_TO|SWAPPED` and `coalesce(r.amount_usd_sum, r.bought_usd)`.'\n\n/** Which link list a guarded walk or route sends, lane by lane. */\nexport const LEVEL_WALK =\n 'A guarded walk or route writes `FLOWED_TO|ROUTED_TO` on a lane whose `money` family lists `ROUTED_TO`, and `FLOWED_TO|SWAPPED` on the graph of before; nothing else in it changes.'\n\n/** The level sentences, in the order a reader meets them. */\nexport function levelLines(): string[] {\n return [LEVEL_RULE, LEVEL_TRACE, LEVEL_POOL, LEVEL_LANE, LEVEL_WALK, LEVEL_EXPOSURE]\n}\n\n/**\n * The shape of the swap links a lane serves. `levels`: `ROUTED_TO` is the whole\n * route of a payer and a receiver (level 2) and `SWAPPED` runs from a trader to\n * one pool (level 1). `route`: the graph of before, where `SWAPPED` runs from a\n * payer to a recipient and holds the route.\n */\nexport type SwapLinkShape = 'levels' | 'route'\n\n/** One family as `meta_network_capabilities` reports it in `graph_progress.families`. */\nexport interface ServedFamily {\n name: string\n layers: string[]\n link_types?: string[]\n link_levels?: Record<string, number>\n}\n\n/**\n * The shape of a lane, from its `money` family: `levels` when the family lists\n * `ROUTED_TO` (in `link_types` or `link_levels`) or its layer `routed`, else\n * `route`. A lane that reports no families has the graph of before.\n */\nexport function swapLinkShape(families: readonly ServedFamily[] | undefined): SwapLinkShape {\n const money = families?.find((family) => family.name === 'money')\n if (!money) return 'route'\n const lists =\n money.link_types?.includes('ROUTED_TO') === true ||\n (money.link_levels !== undefined && 'ROUTED_TO' in money.link_levels) ||\n money.layers.includes('routed')\n return lists ? 'levels' : 'route'\n}\n\n/** What a refusal carries, and which part of it decides the move. */\nexport const MOVE_INTRO =\n 'A refused, killed, busy or failed query comes back with `error_detail`: `code`, `rule`, `class`, `fix` and `example`. The `class` decides your next move.'\n\n/** The move for each class of the refusal envelope. */\nexport const MOVE_BY_CLASS = {\n refused: 'Class `refused`: read `fix`, rewrite the query from `example`, and send it once.',\n killed: 'Class `killed`: narrow the query (fewer properties, rows or hops) and send it once.',\n capacity: 'Class `capacity`: wait at least 5 seconds, then send the same query once.',\n failed: 'Class `failed`: tell the user what is down. Do not retry.',\n} as const\n\n/** A `fix` that names another layer. */\nexport const MOVE_OTHER_LAYER = 'A `fix` that names another layer means move to that layer.'\n\n/** One try, then the user. Never a loop. */\nexport const MOVE_ONCE =\n 'One rewrite or one retry for each query. When it is refused or busy again, stop and tell the user. Quote the `fix` text and send nothing more for that question.'\n\n/** After a refusal or a kill the server has already said no. */\nexport const MOVE_NEVER_SAME = 'Never send the same text again after `refused` or `killed`.'\n\n/** A batch has good members that already ran. */\nexport const MOVE_BATCH = 'In a batch, send again only the members that came back `capacity`.'\n\n/** The routing sentences, in the order a reader meets them. */\nexport function routingLines(): string[] {\n return [\n ROUTING_RULE,\n ...ROUTING_LINES,\n ROUTING_CONTRACT,\n ROUTING_ADDRESS_ON_CHAIN,\n ROUTING_TWO_FIT,\n ROUTING_HANDOFF,\n ROUTING_SWEPT,\n ROUTING_NOT_SERVED,\n ]\n}\n\n/** The move-by-class sentences, in the order a reader meets them. */\nexport function moveLines(): string[] {\n return [\n MOVE_INTRO,\n MOVE_BY_CLASS.refused,\n MOVE_BY_CLASS.killed,\n MOVE_BY_CLASS.capacity,\n MOVE_BY_CLASS.failed,\n MOVE_OTHER_LAYER,\n MOVE_ONCE,\n MOVE_NEVER_SAME,\n MOVE_BATCH,\n ]\n}\n\n/**\n * The routing rule and its three lines, with the question that no layer serves,\n * as one paragraph. The proxy serves it first among its instructions: a host\n * that keeps only the start of the instructions (Claude Code keeps 2 KB) still\n * shows the agent where each kind of question goes, and which kind goes nowhere.\n */\nexport function routingHead(): string {\n return `Pick the layer first. ${ROUTING_RULE} 1. ${ROUTING_LINES[0]} 2. ${ROUTING_LINES[1]} 3. ${ROUTING_LINES[2]} ${ROUTING_CONTRACT} ${ROUTING_NOT_SERVED}`\n}\n\n/**\n * The three hints that the MCP proxy serves for routing, for refusals and for\n * the levels of money. Each is one line of the served instructions.\n */\nexport function routingHintLines(): string[] {\n return [\n `- Pick the layer first. ${ROUTING_RULE} 1. ${ROUTING_LINES[0]} 2. ${ROUTING_LINES[1]} 3. ${ROUTING_LINES[2]} ${ROUTING_CONTRACT} ${ROUTING_NOT_SERVED} ${ROUTING_ADDRESS_ON_CHAIN} ${ROUTING_TWO_FIT} ${ROUTING_HANDOFF} ${ROUTING_SWEPT} The lookups that USE chain serves are listed in chain_admission.lookups of meta_network_capabilities. Read every limit that the server publishes from meta_network_capabilities (chain_admission and, when the server sends them, topology_admission and facts_admission). Never write a limit down.`,\n `- Act on a refusal by its class. ${moveLines().join(' ')}`,\n `- ${levelLines().join(' ')}`,\n ]\n}\n"],"mappings":";;AA4BA,MAAa,eACX;;AAGF,MAAa,gBAAgB;CAC3B;CACA;CACA;AACF;;;;;AAMA,MAAa,mBACX;;AAGF,MAAa,2BACX;;AAGF,MAAa,kBACX;;AAGF,MAAa,kBACX;;;;;AAMF,MAAa,gBACX;;;;;AAMF,MAAa,qBACX;;;;;;;AAQF,MAAa,aACX;;AAGF,MAAa,cACX;;AAGF,MAAa,aACX;;AAGF,MAAa,aACX;;AAGF,MAAa,iBACX;;AAGF,MAAa,aACX;;AAGF,SAAgB,aAAuB;CACrC,OAAO;EAAC;EAAY;EAAa;EAAY;EAAY;EAAY;CAAc;AACrF;;;;;;AAuBA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