chain-insights 0.85.2 → 0.93.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-B8xTh1iM.mjs +760 -0
  10. package/dist/address-risk-B8xTh1iM.mjs.map +1 -0
  11. package/dist/address-risk-WIKbjqy2.cjs +913 -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-BkwTaKxS.cjs +1004 -0
  57. package/dist/token-risk-XVaN_Yp3.mjs +971 -0
  58. package/dist/token-risk-XVaN_Yp3.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 +206 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +77 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +772 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +77 -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 +80 -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 +1 @@
1
- {"version":3,"file":"deployer-screen-B5yrXZGo.mjs","names":[],"sources":["../src/mcp/deployer-screen.ts"],"sourcesContent":["/**\n * aml_deployer_screen: who is behind a token or a wallet, as facts.\n *\n * A local tool of the proxy. It sends one graph_query_batch with two reads on\n * USE topology, both anchored on the address:\n *\n * token the address as a contract: its first creation (DEPLOYED_CONTRACT),\n * the launcher (the transaction's sender), the launcher's first funder\n * of all time and its first inbound bridge deposit;\n * wallet the address as the launcher itself: the same funder and bridge reads.\n *\n * The funder is the launcher's earliest inbound FLOWED_TO. On a lane whose\n * money family lists ROUTED_TO (the three link levels) it is the earliest of\n * its inbound FLOWED_TO and ROUTED_TO from another address: a launcher funded\n * by the proceeds of a swap names the payer of that swap. A self route (the\n * launcher swapped for itself) is never the funder: it spent money the\n * launcher already held, so the search goes on to what paid it in. Any other\n * lane gets the reads of 0.82.0, byte for byte.\n *\n * The token read answers first when it holds a row; the wallet read answers\n * otherwise. The tool returns facts and never a score, a level or a verdict:\n * the description below is the contract with every host, Claude Desktop chat\n * included, which reads no skill.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport type { SwapLinkShape } from './layer-routing.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\nimport {\n membersOf,\n refusalOf,\n type GraphAnswer,\n type Member,\n type TokenToolDependencies,\n} from './token-lookup.js'\n\nexport const AML_DEPLOYER_SCREEN_TOOL = 'aml_deployer_screen' as const\nexport const AML_DEPLOYER_SCREEN_SCHEMA = 'chain-insights.aml-deployer-screen.v1' as const\nexport const AML_DEPLOYER_SCREEN_TITLE = 'Deployer screen'\nexport const AML_DEPLOYER_SCREEN_DESCRIPTION =\n 'Facts only, no score and no verdict: screens who is behind a token or a wallet. ' +\n 'For a token contract it returns the creation transaction and the launcher (the wallet that sent it); ' +\n 'for a wallet, that wallet as the launcher. Then the launcher\\'s first funder of all time and what kind of ' +\n 'wallet that funder is (wallet, contract, bridge, bundler, launchpad, exchange, mixer, scam), how many addresses the ' +\n 'funder ever paid, the sanctions, scam, victim and risk labels on each, and the first inbound bridge deposit. ' +\n 'The caller decides. A fresh launcher funded by a wallet that paid few addresses is the pattern to look at; ' +\n 'a funder that paid thousands is shared infrastructure. A launcher that is a bundler hides the real sender: ' +\n 'launcher_resolved is then false. On a lane whose money family lists ROUTED_TO the first funder may have paid ' +\n 'through a swap (funded_via swap): it paid, a router and a pool swapped, the launcher got another asset; a swap ' +\n 'the launcher made for itself is never its funder. not_covered lists what the graph cannot see yet.'\nexport const AML_DEPLOYER_SCREEN_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_DEPLOYER_SCREEN_ARGS = ['network', 'address'] as const\n\n/** What the two reads cannot see yet, named in every answer. */\nexport const NOT_COVERED = ['exploit_labels', 'ml_labels', 'bridge_sender', 'ethereum_history'] as const\n\nexport type CrimeKind = 'sanctioned' | 'scam' | 'victim' | 'issuer_frozen' | 'risk'\nexport interface Crime {\n kind: CrimeKind\n value: string\n level: string | null\n}\n\nexport interface Party {\n address: string\n roles: string[]\n crime: Crime[]\n first_activity: number | null\n first_activity_utc: string | null\n degree_in: number | null\n degree_out: number | null\n}\n\nexport type FunderKind = 'scam' | 'mixer' | 'exchange' | 'bridge' | 'bundler' | 'launchpad' | 'contract' | 'wallet'\n\nexport interface Funder {\n address: string\n kind: FunderKind\n roles: string[]\n crime: Crime[]\n degree_out: number | null\n first_activity: number | null\n first_activity_utc: string | null\n funded_at: number | null\n funded_at_utc: string | null\n funding_tx_count: number | null\n funding_usd: number | null\n /**\n * On a lane with the levels only: `transfer` when the first money came on\n * FLOWED_TO, `swap` when on ROUTED_TO (the funder paid, the launcher got the\n * bought asset; funding_usd is then what the launcher got).\n */\n funded_via?: 'transfer' | 'swap'\n}\n\nexport interface Creation {\n tx: string | null\n block: number | null\n time: number | null\n time_utc: string | null\n deployer: string | null\n factory: string | null\n mode: 'direct' | 'factory'\n}\n\nexport interface BridgedIn {\n chain: string | null\n bridge: string | null\n kind: string | null\n asset: string | null\n first_block: number | null\n}\n\nexport interface AmlDeployerScreenResult {\n schema: typeof AML_DEPLOYER_SCREEN_SCHEMA\n tool: typeof AML_DEPLOYER_SCREEN_TOOL\n network: string\n input: string\n /** false when the graph holds no node for the address: every fact below is then null. */\n found: boolean\n input_kind: 'token' | 'wallet' | null\n token: { address: string; roles: string[] } | null\n creation: Creation | null\n launcher: Party | null\n launcher_resolved: boolean | null\n first_funder: Funder | null\n bridged_in: BridgedIn | null\n not_covered: string[]\n hint: string\n}\n\nexport type DeployerScreenDependencies = Pick<\n TokenToolDependencies,\n 'graphQueryBatch' | 'unavailable' | 'describeFailure'\n> & {\n /**\n * The lane's graph shape (`meta_network_capabilities`, kept by the proxy).\n * The funder read walks ROUTED_TO only when it answers `levels`; absent,\n * `route` or a read that throws keeps the reads of 0.82.0.\n */\n linkShape?: (network: string) => Promise<SwapLinkShape> | SwapLinkShape\n}\n\nexport type AmlDeployerScreenToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\n// The only address form ever written into a read: 0x and 40 lowercase hex.\nconst ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\nconst ADDRESS_READ = /^0x[0-9a-f]{40}$/\n\n// The funder's first inbound flow and the first inbound bridge deposit of the\n// launcher `l`, and the columns both reads return about them.\nconst FUNDER_READ = 'OPTIONAL MATCH (f:Address)-[e:FLOWED_TO]->(l)'\n// On a lane with the levels: the first money from another address, funds or a\n// swap route; the self route is left out (it spent what the launcher held).\nconst LEVELS_FUNDER_READ =\n 'OPTIONAL MATCH (f:Address)-[e:FLOWED_TO|ROUTED_TO]->(l) WHERE f.address <> l.address'\n// What the launcher got: a route carries it in bought_usd_sum, a FLOWED_TO in\n// amount_usd_sum; and which link it came on.\nconst LEVELS_FUNDING_COLUMNS =\n 'coalesce(e.bought_usd_sum, e.amount_usd_sum) AS funding_usd, type(e) AS funding_link'\nconst BRIDGE_READ =\n \"OPTIONAL MATCH (ch:Chain)-[b:BRIDGED]->(l) WHERE b.kind IN ['TOKEN_DEPOSIT','NATIVE_DEPOSIT']\"\nconst PARTY_COLUMNS = [\n 'labels(l) AS launcher_roles',\n 'l.first_activity_timestamp AS launcher_first_activity',\n 'l.degree_in AS launcher_degree_in',\n 'l.degree_out AS launcher_degree_out',\n 'l.is_sanctioned AS launcher_is_sanctioned',\n 'l.is_scam AS launcher_is_scam',\n 'l.is_victim AS launcher_is_victim',\n 'l.is_issuer_frozen AS launcher_is_issuer_frozen',\n 'l.label_risk_labels AS launcher_risk_labels',\n 'l.label_risk_levels AS launcher_risk_levels',\n 'f.address AS funder',\n 'labels(f) AS funder_roles',\n 'f.degree_out AS funder_degree_out',\n 'f.first_activity_timestamp AS funder_first_activity',\n 'f.is_sanctioned AS funder_is_sanctioned',\n 'f.is_scam AS funder_is_scam',\n 'f.is_victim AS funder_is_victim',\n 'f.is_issuer_frozen AS funder_is_issuer_frozen',\n 'f.label_risk_labels AS funder_risk_labels',\n 'f.label_risk_levels AS funder_risk_levels',\n 'e.first_seen_timestamp AS funded_at',\n 'e.tx_count AS funding_tx_count',\n 'e.amount_usd_sum AS funding_usd',\n 'ch.network AS bridged_chain',\n 'ch.address AS bridged_bridge',\n 'b.kind AS bridged_kind',\n 'b.asset AS bridged_asset',\n 'b.first_height AS bridged_first_block',\n].join(', ')\nconst TOKEN_COLUMNS = [\n 't.address AS token',\n 'labels(t) AS token_roles',\n 'c.tx_origin AS launcher',\n 'c.deployer_address AS deployer',\n 'c.factory_address AS factory',\n 'c.kind AS creation_kind',\n 'c.tx_id AS creation_tx',\n 'c.block_height AS creation_block',\n 'c.block_timestamp AS creation_time',\n].join(', ')\n\nfunction assertReadAddress(address: string): void {\n if (!ADDRESS_READ.test(address)) {\n throw new Error(`deployer screen: ${JSON.stringify(address)} is not a lowercase 0x address`)\n }\n}\n\n/** The token read: the address as a contract, its first creation and who sent it. */\nexport function tokenScreenQuery(address: string, shape: SwapLinkShape = 'route'): string {\n assertReadAddress(address)\n return [\n `USE topology MATCH (t:Address {address:'${address}'})<-[c:DEPLOYED_CONTRACT]-(:Address)`,\n 'WITH t, c ORDER BY c.block_height LIMIT 1',\n 'MATCH (l:Address {address: c.tx_origin})',\n funderRead(shape),\n 'WITH t, c, l, f, e ORDER BY e.first_seen_timestamp LIMIT 1',\n BRIDGE_READ,\n 'WITH t, c, l, f, e, ch, b ORDER BY b.first_height LIMIT 1',\n `RETURN ${TOKEN_COLUMNS}, ${partyColumns(shape)} LIMIT 1`,\n ].join(' ')\n}\n\nfunction funderRead(shape: SwapLinkShape): string {\n return shape === 'levels' ? LEVELS_FUNDER_READ : FUNDER_READ\n}\n\nfunction partyColumns(shape: SwapLinkShape): string {\n return shape === 'levels'\n ? PARTY_COLUMNS.replace('e.amount_usd_sum AS funding_usd', LEVELS_FUNDING_COLUMNS)\n : PARTY_COLUMNS\n}\n\n/** The wallet read: the address as the launcher itself. */\nexport function walletScreenQuery(address: string, shape: SwapLinkShape = 'route'): string {\n assertReadAddress(address)\n return [\n `USE topology MATCH (l:Address {address:'${address}'})`,\n funderRead(shape),\n 'WITH l, f, e ORDER BY e.first_seen_timestamp LIMIT 1',\n BRIDGE_READ,\n 'WITH l, f, e, ch, b ORDER BY b.first_height LIMIT 1',\n `RETURN l.address AS launcher, ${partyColumns(shape)} LIMIT 1`,\n ].join(' ')\n}\n\n/** The one batch the tool sends: members `token` and `wallet`. */\nexport function deployerScreenQueries(\n address: string,\n shape: SwapLinkShape = 'route'\n): Array<{ id: 'token' | 'wallet'; query: string }> {\n return [\n { id: 'token', query: tokenScreenQuery(address, shape) },\n { id: 'wallet', query: walletScreenQuery(address, shape) },\n ]\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\n\nconst numberOrNull = (value: unknown): number | null => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)))\n return Number(value)\n return null\n}\n\nconst addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null\n\nconst utcOrNull = (ms: number | null): string | null => (isEpochMs(ms) ? utcText(ms) : null)\n\n/**\n * A label from a third-party explorer tag source is training data, never served.\n * The graph is not meant to carry one; this drops it if it ever does.\n */\nexport function isServedLabel(value: string): boolean {\n const lower = value.trim().toLowerCase()\n return !(lower.startsWith('etherscan') || lower.startsWith('data:etherscan'))\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\n\n/** labels(n) minus Address, with an unserved label dropped. */\nfunction rolesOf(value: unknown): string[] {\n return strings(value).filter((role) => role !== 'Address' && isServedLabel(role))\n}\n\n// The flag of each judgement mark, and the mark's label word served as its value.\nconst FLAG_CRIMES: Array<[CrimeKind, string, string]> = [\n ['sanctioned', 'is_sanctioned', 'Sanctioned'],\n ['scam', 'is_scam', 'Scam'],\n ['victim', 'is_victim', 'Victim'],\n ['issuer_frozen', 'is_issuer_frozen', 'IssuerFrozen'],\n]\n\n/** The flags that are true, then one risk entry per served risk label with its level. */\nfunction crimeOf(row: Record<string, unknown>, prefix: 'launcher' | 'funder'): Crime[] {\n const crime: Crime[] = []\n for (const [kind, flag, value] of FLAG_CRIMES) {\n if (row[`${prefix}_${flag}`] === true) crime.push({ kind, value, level: null })\n }\n const labels = Array.isArray(row[`${prefix}_risk_labels`]) ? (row[`${prefix}_risk_labels`] as unknown[]) : []\n const levels = Array.isArray(row[`${prefix}_risk_levels`]) ? (row[`${prefix}_risk_levels`] as unknown[]) : []\n labels.forEach((label, at) => {\n if (typeof label !== 'string' || label.trim() === '' || !isServedLabel(label)) return\n crime.push({ kind: 'risk', value: label, level: textOrNull(levels[at]) })\n })\n return crime\n}\n\n/** The funder kinds, first match wins; a contract with no role is 'contract', no match is a plain wallet. */\nexport const FUNDER_KIND_RULES: ReadonlyArray<\n readonly [FunderKind, (roles: readonly string[], isScam: boolean) => boolean]\n> = [\n ['scam', (roles, isScam) => isScam || roles.includes('Scam')],\n ['mixer', (roles) => roles.includes('Mixer')],\n ['exchange', (roles) => roles.includes('Exchange')],\n ['bridge', (roles) => roles.includes('Bridge')],\n ['bundler', (roles) => roles.includes('Bundler')],\n ['launchpad', (roles) => roles.includes('Pool') || roles.includes('Protocol')],\n ['contract', (roles) => roles.includes('Contract')],\n]\n\nexport function funderKind(roles: readonly string[], isScam = false): FunderKind {\n return FUNDER_KIND_RULES.find(([, rule]) => rule(roles, isScam))?.[0] ?? 'wallet'\n}\n\nfunction partyOf(row: Record<string, unknown>): Party | null {\n const address = addressOrNull(row.launcher)\n if (!address) return null\n const firstActivity = numberOrNull(row.launcher_first_activity)\n return {\n address,\n roles: rolesOf(row.launcher_roles),\n crime: crimeOf(row, 'launcher'),\n first_activity: firstActivity,\n first_activity_utc: utcOrNull(firstActivity),\n degree_in: numberOrNull(row.launcher_degree_in),\n degree_out: numberOrNull(row.launcher_degree_out),\n }\n}\n\nfunction funderOf(row: Record<string, unknown>): Funder | null {\n const address = addressOrNull(row.funder)\n if (!address) return null\n const roles = rolesOf(row.funder_roles)\n const firstActivity = numberOrNull(row.funder_first_activity)\n const fundedAt = numberOrNull(row.funded_at)\n return {\n address,\n kind: funderKind(roles, row.funder_is_scam === true),\n roles,\n crime: crimeOf(row, 'funder'),\n degree_out: numberOrNull(row.funder_degree_out),\n first_activity: firstActivity,\n first_activity_utc: utcOrNull(firstActivity),\n funded_at: fundedAt,\n funded_at_utc: utcOrNull(fundedAt),\n funding_tx_count: numberOrNull(row.funding_tx_count),\n funding_usd: numberOrNull(row.funding_usd),\n // Only a levels read returns funding_link; a read of before adds no key.\n ...(row.funding_link === 'ROUTED_TO'\n ? { funded_via: 'swap' as const }\n : row.funding_link === 'FLOWED_TO'\n ? { funded_via: 'transfer' as const }\n : {}),\n }\n}\n\nfunction bridgedInOf(row: Record<string, unknown>): BridgedIn | null {\n const chain = textOrNull(row.bridged_chain)\n const kind = textOrNull(row.bridged_kind)\n if (!chain && !kind) return null\n const asset = textOrNull(row.bridged_asset)\n return {\n chain,\n bridge: addressOrNull(row.bridged_bridge) ?? textOrNull(row.bridged_bridge),\n kind,\n asset: addressOrNull(asset) ?? asset,\n first_block: numberOrNull(row.bridged_first_block),\n }\n}\n\nfunction creationOf(row: Record<string, unknown>): Creation {\n const factory = addressOrNull(row.factory)\n const kind = textOrNull(row.creation_kind)\n const time = numberOrNull(row.creation_time)\n return {\n tx: textOrNull(row.creation_tx)?.toLowerCase() ?? null,\n block: numberOrNull(row.creation_block),\n time,\n time_utc: utcOrNull(time),\n deployer: addressOrNull(row.deployer),\n factory,\n mode: kind === 'factory' || (kind !== 'direct' && factory !== null) ? 'factory' : 'direct',\n }\n}\n\n/** The first row of a member that names a launcher, or null when it has none. */\nfunction launcherRow(member: Member | undefined): Record<string, unknown> | null {\n if (!member || !Array.isArray(member.results)) return null\n return member.results.find((row) => isRecord(row) && addressOrNull(row.launcher) !== null) ?? null\n}\n\nconst answered = (member: Member | undefined): boolean =>\n member?.ok === true && Array.isArray(member.results)\n\nfunction memberFailure(id: string, member: Member | undefined): string {\n if (!member) return `the ${id} read is missing from the batch answer`\n return typeof member.error === 'string' && member.error.trim() !== ''\n ? member.error\n : `the ${id} read did not answer`\n}\n\n/** The screen built from the two batch members, or why it cannot be. */\nexport function screenFromMembers(\n network: string,\n input: string,\n members: Map<string, Member>\n): { result: AmlDeployerScreenResult } | { failure: string } {\n const token = members.get('token')\n const wallet = members.get('wallet')\n const base = {\n schema: AML_DEPLOYER_SCREEN_SCHEMA,\n tool: AML_DEPLOYER_SCREEN_TOOL,\n network,\n input,\n not_covered: [...NOT_COVERED] as string[],\n }\n\n // A token read that failed cannot be told from \"not a token\": no fallback.\n if (!answered(token)) return { failure: memberFailure('token', token) }\n const tokenRow = launcherRow(token)\n if (tokenRow) {\n const launcher = partyOf(tokenRow)!\n const result = {\n ...base,\n found: true,\n input_kind: 'token' as const,\n token: {\n address: addressOrNull(tokenRow.token) ?? input,\n roles: rolesOf(tokenRow.token_roles),\n },\n creation: creationOf(tokenRow),\n launcher,\n launcher_resolved: !launcher.roles.includes('Bundler'),\n first_funder: funderOf(tokenRow),\n bridged_in: bridgedInOf(tokenRow),\n }\n return { result: { ...result, hint: hintFor(result) } }\n }\n\n if (!answered(wallet)) return { failure: memberFailure('wallet', wallet) }\n const walletRow = launcherRow(wallet)\n if (walletRow) {\n const launcher = partyOf(walletRow)!\n const result = {\n ...base,\n found: true,\n input_kind: 'wallet' as const,\n token: null,\n creation: null,\n launcher,\n launcher_resolved: !launcher.roles.includes('Bundler'),\n first_funder: funderOf(walletRow),\n bridged_in: bridgedInOf(walletRow),\n }\n return { result: { ...result, hint: hintFor(result) } }\n }\n\n const result = {\n ...base,\n found: false,\n input_kind: null,\n token: null,\n creation: null,\n launcher: null,\n launcher_resolved: null,\n first_funder: null,\n bridged_in: null,\n }\n return { result: { ...result, hint: hintFor(result) } }\n}\n\nconst FACTS_ONLY =\n 'Report these as facts. Give no score, no risk level and no verdict of your own: the user decides.'\n\nfunction hintFor(result: Omit<AmlDeployerScreenResult, 'hint'>): string {\n const parts: string[] = [ANSWER_HINT]\n if (!result.found) {\n parts.push(\n `${result.input} is not in the Chain Insights Graph of ${result.network}: no flow, creation or bridge touches it. ` +\n 'Say so in one line. That is not proof the address is clean, and it is not proof it is a token. ' +\n 'Check the network and the address with the user.'\n )\n return parts.join(' ')\n }\n parts.push(FACTS_ONLY)\n if (result.input_kind === 'wallet' && result.launcher?.roles.some((r) => r === 'Contract' || r === 'Token')) {\n parts.push(\n 'The address is a contract, but the graph holds no creation record for it, so it was screened as a wallet.'\n )\n }\n if (result.launcher_resolved === false) {\n parts.push(\n 'The launcher is a bundler: it sends transactions for others, so the person behind the launch is not known from this read.'\n )\n }\n if (!result.first_funder) parts.push('The launcher has no inbound flow in the graph: no first funder.')\n if (result.first_funder?.funded_via === 'swap') {\n parts.push(\n 'The first funder paid the launcher through a swap: say it paid one asset and the launcher got another, and never name a router or a pool as the funder.'\n )\n }\n parts.push(`not_covered names what the graph cannot see yet (${NOT_COVERED.join(', ')}); say so when it matters.`)\n return parts.join(' ')\n}\n\nfunction errorResult(text: string): AmlDeployerScreenToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlDeployerScreenResult): AmlDeployerScreenToolResult {\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\n/** aml_deployer_screen, {network, address}. Every argument is checked before a read is sent. */\nexport async function handleAmlDeployerScreen(\n args: unknown,\n deps: DeployerScreenDependencies\n): Promise<AmlDeployerScreenToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n const raw = typeof record.address === 'string' ? record.address.trim() : ''\n if (!ADDRESS_INPUT.test(raw)) {\n return errorResult(\n 'invalid_address: address is required: a token contract or a wallet, 0x plus 40 hex characters. ' +\n 'A ticker or a name is not an address: call meta_token_lookup first.'\n )\n }\n const address = raw.toLowerCase()\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No deployer screen read was sent: ${unavailable} There is no answer yet, which is not \"not found\": try again later.`\n )\n }\n\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\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries: deployerScreenQueries(address, shape) })\n } catch (err) {\n return errorResult(\n `The deployer screen read failed: ${deps.describeFailure(err)} This is not \"not found\": send the same screen again once.`\n )\n }\n const members = membersOf(answer)\n if (members.size === 0) {\n const text = answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n return errorResult(`The deployer screen read failed: ${text} This is not \"not found\".`)\n }\n const screen = screenFromMembers(network, address, members)\n if ('failure' in screen) {\n return errorResult(\n `The deployer screen read failed: ${screen.failure} This is not \"not found\": send the same screen again once.`\n )\n }\n return textResult(screen.result)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,2BAA2B;AACxC,MAAa,6BAA6B;AAC1C,MAAa,4BAA4B;AACzC,MAAa,kCACX;AAUF,MAAa,kCAAkC;CAC7C,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;;AAIA,MAAa,cAAc;CAAC;CAAkB;CAAa;CAAiB;AAAkB;AAgG9F,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAIrB,MAAM,cAAc;AAGpB,MAAM,qBACJ;AAGF,MAAM,yBACJ;AACF,MAAM,cACJ;AACF,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF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"sources":["../src/mcp/deployer-screen.ts"],"sourcesContent":["/**\n * aml_deployer_screen: who is behind a token or a wallet, as facts.\n *\n * A local tool of the proxy. It sends one graph_query_batch with two reads on\n * USE topology, both anchored on the address:\n *\n * token the address as a contract: its first creation (DEPLOYED_CONTRACT),\n * the launcher (the transaction's sender), the launcher's first funder\n * of all time and its first inbound bridge deposit;\n * wallet the address as the launcher itself: the same funder and bridge reads.\n *\n * The funder is the launcher's earliest inbound FLOWED_TO. On a lane whose\n * money family lists ROUTED_TO (the three link levels) it is the earliest of\n * its inbound FLOWED_TO and ROUTED_TO from another address: a launcher funded\n * by the proceeds of a swap names the payer of that swap. A self route (the\n * launcher swapped for itself) is never the funder: it spent money the\n * launcher already held, so the search goes on to what paid it in. Any other\n * lane gets the reads of 0.82.0, byte for byte.\n *\n * The token read answers first when it holds a row; the wallet read answers\n * otherwise. The tool returns facts and never a score, a level or a verdict:\n * the description below is the contract with every host, Claude Desktop chat\n * included, which reads no skill.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport type { SwapLinkShape } from './layer-routing.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\nimport {\n membersOf,\n refusalOf,\n type GraphAnswer,\n type Member,\n type TokenToolDependencies,\n} from './token-lookup.js'\n\nexport const AML_DEPLOYER_SCREEN_TOOL = 'aml_deployer_screen' as const\nexport const AML_DEPLOYER_SCREEN_SCHEMA = 'chain-insights.aml-deployer-screen.v1' as const\nexport const AML_DEPLOYER_SCREEN_TITLE = 'Deployer screen'\nexport const AML_DEPLOYER_SCREEN_DESCRIPTION =\n 'Facts only, no score and no verdict: screens who is behind a token or a wallet. ' +\n 'For a token contract it returns the creation transaction and the launcher (the wallet that sent it); ' +\n 'for a wallet, that wallet as the launcher. Then the launcher\\'s first funder of all time and what kind of ' +\n 'wallet that funder is (wallet, contract, bridge, bundler, launchpad, exchange, mixer, scam), how many addresses the ' +\n 'funder ever paid, the sanctions, scam, victim and risk labels on each, and the first inbound bridge deposit. ' +\n 'The caller decides. A fresh launcher funded by a wallet that paid few addresses is the pattern to look at; ' +\n 'a funder that paid thousands is shared infrastructure. A launcher that is a bundler hides the real sender: ' +\n 'launcher_resolved is then false. On a lane whose money family lists ROUTED_TO the first funder may have paid ' +\n 'through a swap (funded_via swap): it paid, a router and a pool swapped, the launcher got another asset; a swap ' +\n 'the launcher made for itself is never its funder. not_covered lists what the graph cannot see yet.'\nexport const AML_DEPLOYER_SCREEN_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_DEPLOYER_SCREEN_ARGS = ['network', 'address'] as const\n\n/** What the two reads cannot see yet, named in every answer. */\nexport const NOT_COVERED = ['exploit_labels', 'ml_labels', 'bridge_sender', 'ethereum_history'] as const\n\nexport type CrimeKind = 'sanctioned' | 'scam' | 'victim' | 'issuer_frozen' | 'risk'\nexport interface Crime {\n kind: CrimeKind\n value: string\n level: string | null\n}\n\nexport interface Party {\n address: string\n roles: string[]\n crime: Crime[]\n first_activity: number | null\n first_activity_utc: string | null\n degree_in: number | null\n degree_out: number | null\n}\n\nexport type FunderKind = 'scam' | 'mixer' | 'exchange' | 'bridge' | 'bundler' | 'launchpad' | 'contract' | 'wallet'\n\nexport interface Funder {\n address: string\n kind: FunderKind\n roles: string[]\n crime: Crime[]\n degree_out: number | null\n first_activity: number | null\n first_activity_utc: string | null\n funded_at: number | null\n funded_at_utc: string | null\n funding_tx_count: number | null\n funding_usd: number | null\n /**\n * On a lane with the levels only: `transfer` when the first money came on\n * FLOWED_TO, `swap` when on ROUTED_TO (the funder paid, the launcher got the\n * bought asset; funding_usd is then what the launcher got).\n */\n funded_via?: 'transfer' | 'swap'\n}\n\nexport interface Creation {\n tx: string | null\n block: number | null\n time: number | null\n time_utc: string | null\n deployer: string | null\n factory: string | null\n mode: 'direct' | 'factory'\n}\n\nexport interface BridgedIn {\n chain: string | null\n bridge: string | null\n kind: string | null\n asset: string | null\n first_block: number | null\n}\n\nexport interface AmlDeployerScreenResult {\n schema: typeof AML_DEPLOYER_SCREEN_SCHEMA\n tool: typeof AML_DEPLOYER_SCREEN_TOOL\n network: string\n input: string\n /** false when the graph holds no node for the address: every fact below is then null. */\n found: boolean\n input_kind: 'token' | 'wallet' | null\n token: { address: string; roles: string[] } | null\n creation: Creation | null\n launcher: Party | null\n launcher_resolved: boolean | null\n first_funder: Funder | null\n bridged_in: BridgedIn | null\n not_covered: string[]\n hint: string\n}\n\nexport type DeployerScreenDependencies = Pick<\n TokenToolDependencies,\n 'graphQueryBatch' | 'unavailable' | 'describeFailure'\n> & {\n /**\n * The lane's graph shape (`meta_network_capabilities`, kept by the proxy).\n * The funder read walks ROUTED_TO only when it answers `levels`; absent,\n * `route` or a read that throws keeps the reads of 0.82.0.\n */\n linkShape?: (network: string) => Promise<SwapLinkShape> | SwapLinkShape\n}\n\nexport type AmlDeployerScreenToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\n// The only address form ever written into a read: 0x and 40 lowercase hex.\nconst ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\nconst ADDRESS_READ = /^0x[0-9a-f]{40}$/\n\n// The funder's first inbound flow and the first inbound bridge deposit of the\n// launcher `l`, and the columns both reads return about them.\nconst FUNDER_READ = 'OPTIONAL MATCH (f:Address)-[e:FLOWED_TO]->(l)'\n// On a lane with the levels: the first money from another address, funds or a\n// swap route; the self route is left out (it spent what the launcher held).\nconst LEVELS_FUNDER_READ =\n 'OPTIONAL MATCH (f:Address)-[e:FLOWED_TO|ROUTED_TO]->(l) WHERE f.address <> l.address'\n// What the launcher got: a route carries it in bought_usd_sum, a FLOWED_TO in\n// amount_usd_sum; and which link it came on.\nconst LEVELS_FUNDING_COLUMNS =\n 'coalesce(e.bought_usd_sum, e.amount_usd_sum) AS funding_usd, type(e) AS funding_link'\nconst BRIDGE_READ =\n \"OPTIONAL MATCH (ch:Chain)-[b:BRIDGED]->(l) WHERE b.kind IN ['TOKEN_DEPOSIT','NATIVE_DEPOSIT']\"\nconst PARTY_COLUMNS = [\n 'labels(l) AS launcher_roles',\n 'l.first_activity_timestamp AS launcher_first_activity',\n 'l.degree_in AS launcher_degree_in',\n 'l.degree_out AS launcher_degree_out',\n 'l.is_sanctioned AS launcher_is_sanctioned',\n 'l.is_scam AS launcher_is_scam',\n 'l.is_victim AS launcher_is_victim',\n 'l.is_issuer_frozen AS launcher_is_issuer_frozen',\n 'l.label_risk_labels AS launcher_risk_labels',\n 'l.label_risk_levels AS launcher_risk_levels',\n 'f.address AS funder',\n 'labels(f) AS funder_roles',\n 'f.degree_out AS funder_degree_out',\n 'f.first_activity_timestamp AS funder_first_activity',\n 'f.is_sanctioned AS funder_is_sanctioned',\n 'f.is_scam AS funder_is_scam',\n 'f.is_victim AS funder_is_victim',\n 'f.is_issuer_frozen AS funder_is_issuer_frozen',\n 'f.label_risk_labels AS funder_risk_labels',\n 'f.label_risk_levels AS funder_risk_levels',\n 'e.first_seen_timestamp AS funded_at',\n 'e.tx_count AS funding_tx_count',\n 'e.amount_usd_sum AS funding_usd',\n 'ch.network AS bridged_chain',\n 'ch.address AS bridged_bridge',\n 'b.kind AS bridged_kind',\n 'b.asset AS bridged_asset',\n 'b.first_height AS bridged_first_block',\n].join(', ')\nconst TOKEN_COLUMNS = [\n 't.address AS token',\n 'labels(t) AS token_roles',\n 'c.tx_origin AS launcher',\n 'c.deployer_address AS deployer',\n 'c.factory_address AS factory',\n 'c.kind AS creation_kind',\n 'c.tx_id AS creation_tx',\n 'c.block_height AS creation_block',\n 'c.block_timestamp AS creation_time',\n].join(', ')\n\nfunction assertReadAddress(address: string): void {\n if (!ADDRESS_READ.test(address)) {\n throw new Error(`deployer screen: ${JSON.stringify(address)} is not a lowercase 0x address`)\n }\n}\n\n/** The token read: the address as a contract, its first creation and who sent it. */\nexport function tokenScreenQuery(address: string, shape: SwapLinkShape = 'route'): string {\n assertReadAddress(address)\n return [\n `USE topology MATCH (t:Address {address:'${address}'})<-[c:DEPLOYED_CONTRACT]-(:Address)`,\n 'WITH t, c ORDER BY c.block_height LIMIT 1',\n 'MATCH (l:Address {address: c.tx_origin})',\n funderRead(shape),\n 'WITH t, c, l, f, e ORDER BY e.first_seen_timestamp LIMIT 1',\n BRIDGE_READ,\n 'WITH t, c, l, f, e, ch, b ORDER BY b.first_height LIMIT 1',\n `RETURN ${TOKEN_COLUMNS}, ${partyColumns(shape)} LIMIT 1`,\n ].join(' ')\n}\n\nfunction funderRead(shape: SwapLinkShape): string {\n return shape === 'levels' ? LEVELS_FUNDER_READ : FUNDER_READ\n}\n\nfunction partyColumns(shape: SwapLinkShape): string {\n return shape === 'levels'\n ? PARTY_COLUMNS.replace('e.amount_usd_sum AS funding_usd', LEVELS_FUNDING_COLUMNS)\n : PARTY_COLUMNS\n}\n\n/** The wallet read: the address as the launcher itself. */\nexport function walletScreenQuery(address: string, shape: SwapLinkShape = 'route'): string {\n assertReadAddress(address)\n return [\n `USE topology MATCH (l:Address {address:'${address}'})`,\n funderRead(shape),\n 'WITH l, f, e ORDER BY e.first_seen_timestamp LIMIT 1',\n BRIDGE_READ,\n 'WITH l, f, e, ch, b ORDER BY b.first_height LIMIT 1',\n `RETURN l.address AS launcher, ${partyColumns(shape)} LIMIT 1`,\n ].join(' ')\n}\n\n/** The one batch the tool sends: members `token` and `wallet`. */\nexport function deployerScreenQueries(\n address: string,\n shape: SwapLinkShape = 'route'\n): Array<{ id: 'token' | 'wallet'; query: string }> {\n return [\n { id: 'token', query: tokenScreenQuery(address, shape) },\n { id: 'wallet', query: walletScreenQuery(address, shape) },\n ]\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\n\nconst numberOrNull = (value: unknown): number | null => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)))\n return Number(value)\n return null\n}\n\nconst addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null\n\nconst utcOrNull = (ms: number | null): string | null => (isEpochMs(ms) ? utcText(ms) : null)\n\n/**\n * A label from a third-party explorer tag source is training data, never served.\n * The graph is not meant to carry one; this drops it if it ever does.\n */\nexport function isServedLabel(value: string): boolean {\n const lower = value.trim().toLowerCase()\n return !(lower.startsWith('etherscan') || lower.startsWith('data:etherscan'))\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\n\n/** labels(n) minus Address, with an unserved label dropped. */\nfunction rolesOf(value: unknown): string[] {\n return strings(value).filter((role) => role !== 'Address' && isServedLabel(role))\n}\n\n// The flag of each judgement mark, and the mark's label word served as its value.\nconst FLAG_CRIMES: Array<[CrimeKind, string, string]> = [\n ['sanctioned', 'is_sanctioned', 'Sanctioned'],\n ['scam', 'is_scam', 'Scam'],\n ['victim', 'is_victim', 'Victim'],\n ['issuer_frozen', 'is_issuer_frozen', 'IssuerFrozen'],\n]\n\n/** The flags that are true, then one risk entry per served risk label with its level. */\nfunction crimeOf(row: Record<string, unknown>, prefix: 'launcher' | 'funder'): Crime[] {\n const crime: Crime[] = []\n for (const [kind, flag, value] of FLAG_CRIMES) {\n if (row[`${prefix}_${flag}`] === true) crime.push({ kind, value, level: null })\n }\n const labels = Array.isArray(row[`${prefix}_risk_labels`]) ? (row[`${prefix}_risk_labels`] as unknown[]) : []\n const levels = Array.isArray(row[`${prefix}_risk_levels`]) ? (row[`${prefix}_risk_levels`] as unknown[]) : []\n labels.forEach((label, at) => {\n if (typeof label !== 'string' || label.trim() === '' || !isServedLabel(label)) return\n crime.push({ kind: 'risk', value: label, level: textOrNull(levels[at]) })\n })\n return crime\n}\n\n/** The funder kinds, first match wins; a contract with no role is 'contract', no match is a plain wallet. */\nexport const FUNDER_KIND_RULES: ReadonlyArray<\n readonly [FunderKind, (roles: readonly string[], isScam: boolean) => boolean]\n> = [\n ['scam', (roles, isScam) => isScam || roles.includes('Scam')],\n ['mixer', (roles) => roles.includes('Mixer')],\n ['exchange', (roles) => roles.includes('Exchange')],\n ['bridge', (roles) => roles.includes('Bridge')],\n ['bundler', (roles) => roles.includes('Bundler')],\n ['launchpad', (roles) => roles.includes('Pool') || roles.includes('Protocol')],\n ['contract', (roles) => roles.includes('Contract')],\n]\n\nexport function funderKind(roles: readonly string[], isScam = false): FunderKind {\n return FUNDER_KIND_RULES.find(([, rule]) => rule(roles, isScam))?.[0] ?? 'wallet'\n}\n\nfunction partyOf(row: Record<string, unknown>): Party | null {\n const address = addressOrNull(row.launcher)\n if (!address) return null\n const firstActivity = numberOrNull(row.launcher_first_activity)\n return {\n address,\n roles: rolesOf(row.launcher_roles),\n crime: crimeOf(row, 'launcher'),\n first_activity: firstActivity,\n first_activity_utc: utcOrNull(firstActivity),\n degree_in: numberOrNull(row.launcher_degree_in),\n degree_out: numberOrNull(row.launcher_degree_out),\n }\n}\n\nfunction funderOf(row: Record<string, unknown>): Funder | null {\n const address = addressOrNull(row.funder)\n if (!address) return null\n const roles = rolesOf(row.funder_roles)\n const firstActivity = numberOrNull(row.funder_first_activity)\n const fundedAt = numberOrNull(row.funded_at)\n return {\n address,\n kind: funderKind(roles, row.funder_is_scam === true),\n roles,\n crime: crimeOf(row, 'funder'),\n degree_out: numberOrNull(row.funder_degree_out),\n first_activity: firstActivity,\n first_activity_utc: utcOrNull(firstActivity),\n funded_at: fundedAt,\n funded_at_utc: utcOrNull(fundedAt),\n funding_tx_count: numberOrNull(row.funding_tx_count),\n funding_usd: numberOrNull(row.funding_usd),\n // Only a levels read returns funding_link; a read of before adds no key.\n ...(row.funding_link === 'ROUTED_TO'\n ? { funded_via: 'swap' as const }\n : row.funding_link === 'FLOWED_TO'\n ? { funded_via: 'transfer' as const }\n : {}),\n }\n}\n\nfunction bridgedInOf(row: Record<string, unknown>): BridgedIn | null {\n const chain = textOrNull(row.bridged_chain)\n const kind = textOrNull(row.bridged_kind)\n if (!chain && !kind) return null\n const asset = textOrNull(row.bridged_asset)\n return {\n chain,\n bridge: addressOrNull(row.bridged_bridge) ?? textOrNull(row.bridged_bridge),\n kind,\n asset: addressOrNull(asset) ?? asset,\n first_block: numberOrNull(row.bridged_first_block),\n }\n}\n\nfunction creationOf(row: Record<string, unknown>): Creation {\n const factory = addressOrNull(row.factory)\n const kind = textOrNull(row.creation_kind)\n const time = numberOrNull(row.creation_time)\n return {\n tx: textOrNull(row.creation_tx)?.toLowerCase() ?? null,\n block: numberOrNull(row.creation_block),\n time,\n time_utc: utcOrNull(time),\n deployer: addressOrNull(row.deployer),\n factory,\n mode: kind === 'factory' || (kind !== 'direct' && factory !== null) ? 'factory' : 'direct',\n }\n}\n\n/** The first row of a member that names a launcher, or null when it has none. */\nfunction launcherRow(member: Member | undefined): Record<string, unknown> | null {\n if (!member || !Array.isArray(member.results)) return null\n return member.results.find((row) => isRecord(row) && addressOrNull(row.launcher) !== null) ?? null\n}\n\nconst answered = (member: Member | undefined): boolean =>\n member?.ok === true && Array.isArray(member.results)\n\nfunction memberFailure(id: string, member: Member | undefined): string {\n if (!member) return `the ${id} read is missing from the batch answer`\n return typeof member.error === 'string' && member.error.trim() !== ''\n ? member.error\n : `the ${id} read did not answer`\n}\n\n/** The screen built from the two batch members, or why it cannot be. */\nexport function screenFromMembers(\n network: string,\n input: string,\n members: Map<string, Member>\n): { result: AmlDeployerScreenResult } | { failure: string } {\n const token = members.get('token')\n const wallet = members.get('wallet')\n const base = {\n schema: AML_DEPLOYER_SCREEN_SCHEMA,\n tool: AML_DEPLOYER_SCREEN_TOOL,\n network,\n input,\n not_covered: [...NOT_COVERED] as string[],\n }\n\n // A token read that failed cannot be told from \"not a token\": no fallback.\n if (!answered(token)) return { failure: memberFailure('token', token) }\n const tokenRow = launcherRow(token)\n if (tokenRow) {\n const launcher = partyOf(tokenRow)!\n const result = {\n ...base,\n found: true,\n input_kind: 'token' as const,\n token: {\n address: addressOrNull(tokenRow.token) ?? input,\n roles: rolesOf(tokenRow.token_roles),\n },\n creation: creationOf(tokenRow),\n launcher,\n launcher_resolved: !launcher.roles.includes('Bundler'),\n first_funder: funderOf(tokenRow),\n bridged_in: bridgedInOf(tokenRow),\n }\n return { result: { ...result, hint: hintFor(result) } }\n }\n\n if (!answered(wallet)) return { failure: memberFailure('wallet', wallet) }\n const walletRow = launcherRow(wallet)\n if (walletRow) {\n const launcher = partyOf(walletRow)!\n const result = {\n ...base,\n found: true,\n input_kind: 'wallet' as const,\n token: null,\n creation: null,\n launcher,\n launcher_resolved: !launcher.roles.includes('Bundler'),\n first_funder: funderOf(walletRow),\n bridged_in: bridgedInOf(walletRow),\n }\n return { result: { ...result, hint: hintFor(result) } }\n }\n\n const result = {\n ...base,\n found: false,\n input_kind: null,\n token: null,\n creation: null,\n launcher: null,\n launcher_resolved: null,\n first_funder: null,\n bridged_in: null,\n }\n return { result: { ...result, hint: hintFor(result) } }\n}\n\nconst FACTS_ONLY =\n 'Report these as facts. Give no score, no risk level and no verdict of your own: the user decides.'\n\nfunction hintFor(result: Omit<AmlDeployerScreenResult, 'hint'>): string {\n const parts: string[] = [ANSWER_HINT]\n if (!result.found) {\n parts.push(\n `${result.input} is not in the Chain Insights Graph of ${result.network}: no flow, creation or bridge touches it. ` +\n 'Say so in one line. That is not proof the address is clean, and it is not proof it is a token. ' +\n 'Check the network and the address with the user.'\n )\n return parts.join(' ')\n }\n parts.push(FACTS_ONLY)\n if (result.input_kind === 'wallet' && result.launcher?.roles.some((r) => r === 'Contract' || r === 'Token')) {\n parts.push(\n 'The address is a contract, but the graph holds no creation record for it, so it was screened as a wallet.'\n )\n }\n if (result.launcher_resolved === false) {\n parts.push(\n 'The launcher is a bundler: it sends transactions for others, so the person behind the launch is not known from this read.'\n )\n }\n if (!result.first_funder) parts.push('The launcher has no inbound flow in the graph: no first funder.')\n if (result.first_funder?.funded_via === 'swap') {\n parts.push(\n 'The first funder paid the launcher through a swap: say it paid one asset and the launcher got another, and never name a router or a pool as the funder.'\n )\n }\n parts.push(`not_covered names what the graph cannot see yet (${NOT_COVERED.join(', ')}); say so when it matters.`)\n return parts.join(' ')\n}\n\nfunction errorResult(text: string): AmlDeployerScreenToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlDeployerScreenResult): AmlDeployerScreenToolResult {\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\n/** aml_deployer_screen, {network, address}. Every argument is checked before a read is sent. */\nexport async function handleAmlDeployerScreen(\n args: unknown,\n deps: DeployerScreenDependencies\n): Promise<AmlDeployerScreenToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n const raw = typeof record.address === 'string' ? record.address.trim() : ''\n if (!ADDRESS_INPUT.test(raw)) {\n return errorResult(\n 'invalid_address: address is required: a token contract or a wallet, 0x plus 40 hex characters. ' +\n 'A ticker or a name is not an address: call meta_token_lookup first.'\n )\n }\n const address = raw.toLowerCase()\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No deployer screen read was sent: ${unavailable} There is no answer yet, which is not \"not found\": try again later.`\n )\n }\n\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\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries: deployerScreenQueries(address, shape) })\n } catch (err) {\n return errorResult(\n `The deployer screen read failed: ${deps.describeFailure(err)} This is not \"not found\": send the same screen again once.`\n )\n }\n const members = membersOf(answer)\n if (members.size === 0) {\n const text = answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n return errorResult(`The deployer screen read failed: ${text} This is not \"not found\".`)\n }\n const screen = screenFromMembers(network, address, members)\n if ('failure' in screen) {\n return errorResult(\n `The deployer screen read failed: ${screen.failure} This is not \"not found\": send the same screen again once.`\n )\n }\n return textResult(screen.result)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,2BAA2B;AACxC,MAAa,6BAA6B;AAC1C,MAAa,4BAA4B;AACzC,MAAa,kCACX;AAUF,MAAa,kCAAkC;CAC7C,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;;AAIA,MAAa,cAAc;CAAC;CAAkB;CAAa;CAAiB;AAAkB;AAgG9F,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAIrB,MAAM,cAAc;AAGpB,MAAM,qBACJ;AAGF,MAAM,yBACJ;AACF,MAAM,cACJ;AACF,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AACX,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,kBAAkB,SAAuB;CAChD,IAAI,CAAC,aAAa,KAAK,OAAO,GAC5B,MAAM,IAAI,MAAM,oBAAoB,KAAK,UAAU,OAAO,EAAE,+BAA+B;AAE/F;;AAGA,SAAgB,iBAAiB,SAAiB,QAAuB,SAAiB;CACxF,kBAAkB,OAAO;CACzB,OAAO;EACL,2CAA2C,QAAQ;EACnD;EACA;EACA,WAAW,KAAK;EAChB;EACA;EACA;EACA,UAAU,cAAc,IAAI,aAAa,KAAK,EAAE;CAClD,CAAC,CAAC,KAAK,GAAG;AACZ;AAEA,SAAS,W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,UAAU,IAAI,YAAY;CAEhC,MAAM,cAAc,MAAM,KAAK,cAAc;CAC7C,IAAI,aACF,OAAO,YACL,qCAAqC,YAAY,oEACnD;CAIF,IAAI,QAAuB;CAC3B,IAAI,KAAK,WACP,IAAI;EACF,QAAQ,MAAM,KAAK,UAAU,OAAO;CACtC,QAAQ;EACN,QAAQ;CACV;CAGF,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,KAAK,gBAAgB;GAAE;GAAS,SAAS,sBAAsB,SAAS,KAAK;EAAE,CAAC;CACjG,SAAS,KAAK;EACZ,OAAO,YACL,oCAAoC,KAAK,gBAAgB,GAAG,EAAE,2DAChE;CACF;CACA,MAAM,UAAU,UAAU,MAAM;CAChC,IAAI,QAAQ,SAAS,GAEnB,OAAO,YAAY,oCADN,OAAO,YAAY,OAAO,UAAU,MAAM,CAAC,CAAC,OAAO,iCACJ,0BAA0B;CAExF,MAAM,SAAS,kBAAkB,SAAS,SAAS,OAAO;CAC1D,IAAI,aAAa,QACf,OAAO,YACL,oCAAoC,OAAO,QAAQ,2DACrD;CAEF,OAAO,WAAW,OAAO,MAAM;AACjC"}
@@ -1,8 +1,8 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  const require_answer_hint = require("./answer-hint-BlYEBq_Y.cjs");
3
- const require_dex_registry = require("./dex-registry-BhGJUG9_.cjs");
3
+ const require_dex_registry = require("./dex-registry-CyR3GyRr.cjs");
4
4
  const require_print_result = require("./print-result-BYppJlUi.cjs");
5
- const require_token_lookup = require("./token-lookup-DqjSRIxd.cjs");
5
+ const require_token_lookup = require("./token-lookup-DLe4erP9.cjs");
6
6
  // src/mcp/deployer-screen.ts
7
7
  /**
8
8
  * aml_deployer_screen: who is behind a token or a wallet, as facts.
@@ -277,6 +277,14 @@ async function loadRegistry(rawNetwork, options = {}) {
277
277
  }
278
278
  }
279
279
  /** Lower case, with every space, ".", "-" and "_" removed: "Uni v4" and "uni-v4" are "univ4". */
280
+ /** The exchange that lists a contract, by any role or as a helper, or null. */
281
+ /** The exchange whose pool manager this address is: a vault exchange that holds its pools in one contract. */
282
+ function dexManagerOf(address, rows) {
283
+ return rows.find((row) => row.trail_type === "vault" && row.roles[address] === "manager") ?? null;
284
+ }
285
+ function dexOfAddress(address, rows) {
286
+ return rows.find((row) => address in row.roles || row.helpers?.includes(address)) ?? null;
287
+ }
280
288
  function normaliseName(name) {
281
289
  return name.toLowerCase().replace(/[\s.\-_]+/g, "");
282
290
  }
@@ -363,6 +371,6 @@ function matchDex(name, rows) {
363
371
  covered
364
372
  };
365
373
  }
366
- export { NEAR_MIN_ALIAS_LENGTH as a, loadRegistry as c, normalizeDexNetwork as d, NEAR_DISTANCE as i, matchDex as l, DEX_REGISTRY_TTL_MS as n, damerauLevenshtein as o, DexRegistryError as r, dex_registry_exports as s, DEX_REGISTRY_FETCH_BUDGET_MS as t, normaliseName as u };
374
+ export { NEAR_MIN_ALIAS_LENGTH as a, dexOfAddress as c, matchDex as d, normaliseName as f, NEAR_DISTANCE as i, dex_registry_exports as l, DEX_REGISTRY_TTL_MS as n, damerauLevenshtein as o, normalizeDexNetwork as p, DexRegistryError as r, dexManagerOf as s, DEX_REGISTRY_FETCH_BUDGET_MS as t, loadRegistry as u };
367
375
 
368
- //# sourceMappingURL=dex-registry-BY67f4Ul.mjs.map
376
+ //# sourceMappingURL=dex-registry-Bkri0--q.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dex-registry-BY67f4Ul.mjs","names":[],"sources":["../src/mcp/dex-registry.ts"],"sourcesContent":["/**\n * The exchange registry, as the proxy tool meta_dex_lookup reads it.\n *\n * The reviewed table lives in this repository, registry/<network>.md, and its\n * served copy registry/<network>.json is checked in CI\n * (scripts/pin-dex-registry.mjs). The proxy reads the copy three ways, in this\n * order:\n *\n * cached ~/.chain-insights/cache/dex-registry-<network>.json, younger than one hour\n * fetched the copy on main, https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/<network>.json,\n * within 3 s, at most once an hour per network and never two in flight\n * packaged registry/<network>.json of the installed package, when the fetch fails and no cache exists\n *\n * A fetched file is used only when it passes the same rules the pin script\n * applies. A malformed file never replaces a good cache: the stale cache keeps\n * answering and one line names the fault. So a proxy that never reaches GitHub\n * behaves like the skill memo of its own version, and a row merged on main\n * reaches every running proxy within the hour, with no release.\n *\n * matchDex turns a name into one exchange: normalise, exact on key, display and\n * aliases, then within two letters of an alias of four or more characters. One\n * winner is matched, a tie is listed, never guessed, and no hit names every\n * covered exchange.\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'\n\nexport const DEX_REGISTRY_SCHEMA = 'chain-insights.dex-registry.v1' as const\n/** How long a cached registry stays fresh. CACHE_TTL_MS (24 h) stays the lifetime of the schema caches. */\nexport const DEX_REGISTRY_TTL_MS = 60 * 60 * 1000\n/** The most a fetch of the public file may take on the call path. */\nexport const DEX_REGISTRY_FETCH_BUDGET_MS = 3_000\nexport const DEX_REGISTRY_URL_ENV = 'CHAIN_INSIGHTS_DEX_REGISTRY_URL'\nexport const DEX_REGISTRY_PUBLIC_URL =\n 'https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/{network}.json'\n\nexport const TRAIL_TYPES = ['plain', 'vault', 'gauge', 'launchpad'] as const\nexport type TrailType = (typeof TRAIL_TYPES)[number]\nexport const ROLES = ['factory', 'manager', 'router'] as const\nexport type Role = (typeof ROLES)[number]\nexport type RegistrySource = 'fetched' | 'cached' | 'packaged'\n\n/** One exchange of the served copy. */\nexport interface DexEntry {\n dex: string\n display: string\n aliases: string[]\n trail_type: TrailType\n adapters: string[]\n roles: Record<string, Role>\n /**\n * Contracts of the exchange the trail does not read: a position NFT, a staking gauge, a parts\n * deployer, a vault's swap router. A lookup by address finds them; no read is sent for them.\n */\n helpers?: string[]\n /** Its factory addresses, or the one manager of a vault. */\n factories: string[]\n /** Its routers, or the manager of a vault: a vault forwards its own swaps. */\n routers: string[]\n example_pool: string | null\n pool_floor: number | null\n since_block: number\n source: string\n}\n\nexport interface DexRegistryDocument {\n schema: typeof DEX_REGISTRY_SCHEMA\n network: string\n registry_version: number\n recorded_on: string\n rows: DexEntry[]\n}\n\nexport interface LoadedRegistry {\n document: DexRegistryDocument\n source: RegistrySource\n loaded_at_ms: number\n}\n\n/** A refusal with its own words for the caller: a network the registry does not cover. */\nexport class DexRegistryError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DexRegistryError'\n }\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/\n// An example pool is a pool address, or the pool id of a manager that keeps its pools by id.\nconst POOL_RE = /^0x(?:[0-9a-f]{40}|[0-9a-f]{64})$/\nconst DEX_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/\nconst NETWORK_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/\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 network as a lower-case identifier; it becomes part of a file name and a URL. */\nexport function normalizeDexNetwork(raw: unknown): string {\n const network = typeof raw === 'string' ? raw.trim().toLowerCase() : ''\n if (!network) {\n throw new DexRegistryError(\n 'invalid_network: network is required. Pass the identifier of a served network, for example robinhood.'\n )\n }\n if (!NETWORK_RE.test(network)) {\n throw new DexRegistryError(`invalid_network: \"${String(raw)}\" is not a network identifier`)\n }\n return network\n}\n\n/**\n * The fault of a registry document, or null when it is valid for the network:\n * the rules of registry/README.md, the same ones the pin script applies.\n */\nexport function registryFault(value: unknown, network: string): string | null {\n if (!isRecord(value)) return 'the file is not a JSON object'\n if (value.schema !== DEX_REGISTRY_SCHEMA) {\n return `schema is ${JSON.stringify(value.schema)}, not ${DEX_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 keys = new Set<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.dex !== 'string' || !DEX_RE.test(row.dex))\n return `${at}.dex is not a key: ${String(row.dex)}`\n if (keys.has(row.dex)) return `${at}.dex ${row.dex} is listed twice`\n keys.add(row.dex)\n if (typeof row.display !== 'string' || row.display.trim() === '')\n return `${at} (${row.dex}) has no display`\n if (!isStringList(row.aliases)) return `${at} (${row.dex}) aliases is not a list of names`\n if (!TRAIL_TYPES.includes(row.trail_type as TrailType)) {\n return `${at} (${row.dex}) trail_type ${String(row.trail_type)} is not plain, vault, gauge or launchpad`\n }\n if (!isStringList(row.adapters)) return `${at} (${row.dex}) adapters is not a list`\n if (!isRecord(row.roles)) return `${at} (${row.dex}) roles is not a map`\n for (const [address, role] of Object.entries(row.roles)) {\n if (!ADDRESS_RE.test(address))\n return `${at} (${row.dex}) address ${address} is not lowercase 0x plus 40 hex characters`\n if (!ROLES.includes(role as Role))\n return `${at} (${row.dex}) role ${String(role)} is not factory, manager or router`\n }\n if (row.helpers !== undefined) {\n if (!isStringList(row.helpers)) return `${at} (${row.dex}) helpers is not a list`\n for (const address of row.helpers) {\n if (!ADDRESS_RE.test(address))\n return `${at} (${row.dex}) address ${address} is not lowercase 0x plus 40 hex characters`\n }\n }\n for (const field of ['factories', 'routers'] as const) {\n const list = row[field]\n if (!isStringList(list)) return `${at} (${row.dex}) ${field} is not a list`\n for (const address of list) {\n if (!ADDRESS_RE.test(address))\n return `${at} (${row.dex}) address ${address} is not lowercase 0x plus 40 hex characters`\n if (!(address in row.roles))\n return `${at} (${row.dex}) ${field} names ${address}, which roles lacks`\n }\n }\n if ((row.factories as string[]).length === 0)\n return `${at} (${row.dex}) has no factory or manager`\n if (\n row.example_pool !== null &&\n (typeof row.example_pool !== 'string' || !POOL_RE.test(row.example_pool))\n ) {\n return `${at} (${row.dex}) example_pool ${String(row.example_pool)} is not a pool`\n }\n if (\n row.pool_floor !== null &&\n (!Number.isInteger(row.pool_floor) || (row.pool_floor as number) < 0)\n ) {\n return `${at} (${row.dex}) pool_floor is not a whole number`\n }\n if (!Number.isInteger(row.since_block) || (row.since_block as number) < 0) {\n return `${at} (${row.dex}) since_block is not a block`\n }\n if (typeof row.source !== 'string' || !row.source.startsWith('https://')) {\n return `${at} (${row.dex}) source is not an https link`\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 dexRegistryUrl(network: string, env: NodeJS.ProcessEnv = process.env): string {\n const override = env[DEX_REGISTRY_URL_ENV]?.trim()\n const template = override || DEX_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 dexRegistryCachePath(network: string): string {\n return path.join(chainInsightsHome(), 'cache', `dex-registry-${network}.json`)\n}\n\n/** The registry/ folder of the installed package: next to dist/, or the repository root when run from source. */\nexport function packagedRegistryDir(): string {\n const candidates = [\n fileURLToPath(new URL('../registry', import.meta.url)),\n fileURLToPath(new URL('../../registry', 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 is a defect: it throws. */\nexport function readPackagedRegistry(\n network: string,\n dir: string = packagedRegistryDir()\n): DexRegistryDocument | 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 = registryFault(parsed, network)\n if (fault)\n throw new Error(\n `the packaged exchange registry registry/${network}.json is malformed: ${fault}`\n )\n return parsed as DexRegistryDocument\n}\n\ninterface CacheFile {\n schema: typeof DEX_REGISTRY_SCHEMA\n network: string\n registry_version: number\n recorded_on: string\n rows: DexEntry[]\n /** When the copy was read: the fetch, or the first start with no fetch. */\n cached_at_ms: number\n /** When a fetch was last tried. The cache is fresh for an hour after it. */\n checked_at_ms: number\n source: 'fetched' | 'packaged'\n}\n\nconst documentOf = (file: CacheFile): DexRegistryDocument => ({\n schema: file.schema,\n network: file.network,\n registry_version: file.registry_version,\n recorded_on: file.recorded_on,\n rows: file.rows,\n})\n\nasync function readCache(network: string): Promise<CacheFile | null> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(dexRegistryCachePath(network), 'utf8'))\n } catch {\n return null\n }\n if (!isRecord(parsed) || registryFault(parsed, network) !== null) return null\n if (typeof parsed.checked_at_ms !== 'number' || typeof parsed.cached_at_ms !== 'number')\n return null\n if (parsed.source !== 'fetched' && parsed.source !== 'packaged') return null\n return parsed as unknown as CacheFile\n}\n\nasync function writeCache(file: CacheFile): Promise<void> {\n const target = dexRegistryCachePath(file.network)\n await mkdir(path.dirname(target), { recursive: true })\n // Written beside the target and renamed, so a second proxy never reads 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\nexport interface LoadRegistryOptions {\n fetch?: typeof fetch\n now?: () => number\n env?: NodeJS.ProcessEnv\n /** One line per fault: a failed fetch, a malformed file, a cache that cannot be written. */\n log?: (line: string) => void\n packagedDir?: string\n budgetMs?: number\n}\n\ntype FetchOutcome = { document: DexRegistryDocument } | { fault: string }\n\nasync function fetchRegistry(network: string, options: LoadRegistryOptions): Promise<FetchOutcome> {\n const url = dexRegistryUrl(network, options.env)\n const fetchImpl = options.fetch ?? fetch\n let response: Response\n try {\n response = await fetchImpl(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 = registryFault(parsed, network)\n if (fault) return { fault: `${url} is malformed: ${fault}` }\n return { document: parsed as DexRegistryDocument }\n}\n\n// Fetches in flight, by network: two calls at once share one fetch.\nconst inFlight = new Map<string, Promise<LoadedRegistry>>()\n\nconst defaultLog = (line: string): void => {\n process.stderr.write(`[chain-insights] dex-registry: ${line}\\n`)\n}\n\n/**\n * The registry of one network: the fresh cache, else the public file, else the\n * stale cache, else the packaged copy. A packaged copy with a higher registry\n * version than the cache or the public file wins, so an upgrade is never\n * answered from an older file. Never throws for a network the package covers.\n */\nexport async function loadRegistry(\n rawNetwork: unknown,\n options: LoadRegistryOptions = {}\n): Promise<LoadedRegistry> {\n const network = normalizeDexNetwork(rawNetwork)\n const now = options.now ?? Date.now\n const log = options.log ?? defaultLog\n const packaged = readPackagedRegistry(network, options.packagedDir)\n const newer = (document: DexRegistryDocument): boolean =>\n packaged !== null && packaged.registry_version > document.registry_version\n const fromPackaged = (): LoadedRegistry => ({\n document: packaged!,\n source: 'packaged',\n loaded_at_ms: now(),\n })\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 if (newer(cache)) return fromPackaged()\n return {\n document: documentOf(cache),\n source: cache.source === 'fetched' ? 'cached' : 'packaged',\n loaded_at_ms: now(),\n }\n }\n\n const running = inFlight.get(network)\n if (running) return running\n const load = (async (): Promise<LoadedRegistry> => {\n const outcome = await fetchRegistry(network, options)\n const checked = now()\n const save = async (file: CacheFile): Promise<void> => {\n try {\n await writeCache(file)\n } catch (err) {\n log(\n `the cache ${dexRegistryCachePath(network)} could not be written: ${err instanceof Error ? err.message : String(err)}`\n )\n }\n }\n if ('document' in outcome) {\n const { document } = outcome\n await save({ ...document, cached_at_ms: checked, checked_at_ms: checked, source: 'fetched' })\n if (newer(document)) return fromPackaged()\n return { document, source: 'fetched', loaded_at_ms: checked }\n }\n log(outcome.fault)\n if (cache) {\n // The stale cache keeps answering, and the next fetch waits an hour.\n await save({ ...cache, checked_at_ms: checked })\n if (newer(cache)) return fromPackaged()\n return {\n document: documentOf(cache),\n source: cache.source === 'fetched' ? 'cached' : 'packaged',\n loaded_at_ms: checked,\n }\n }\n if (!packaged) {\n throw new DexRegistryError(\n `network_not_covered: the exchange registry covers no network \"${network}\", and ${outcome.fault}`\n )\n }\n await save({ ...packaged, cached_at_ms: checked, checked_at_ms: checked, source: 'packaged' })\n return fromPackaged()\n })()\n inFlight.set(network, load)\n try {\n return await load\n } finally {\n inFlight.delete(network)\n }\n}\n\n// ─── The name match ───────────────────────────────────────────────────────────\n\n/** Lower case, with every space, \".\", \"-\" and \"_\" removed: \"Uni v4\" and \"uni-v4\" are \"univ4\". */\nexport function normaliseName(name: string): string {\n return name.toLowerCase().replace(/[\\s.\\-_]+/g, '')\n}\n\n/** The optimal string alignment distance: insertions, deletions, substitutions and swaps of two neighbours. */\nexport function damerauLevenshtein(a: string, b: string): number {\n const rows = a.length + 1\n const cols = b.length + 1\n const d: number[][] = Array.from({ length: rows }, (_, i) =>\n Array.from({ length: cols }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))\n )\n for (let i = 1; i < rows; i += 1) {\n for (let j = 1; j < cols; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n let best = Math.min(d[i - 1]![j]! + 1, d[i]![j - 1]! + 1, d[i - 1]![j - 1]! + cost)\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, d[i - 2]![j - 2]! + 1)\n }\n d[i]![j] = best\n }\n }\n return d[a.length]![b.length]!\n}\n\n/** The most letters a near hit may differ by, and the shortest alias a near hit is taken from. */\nexport const NEAR_DISTANCE = 2\nexport const NEAR_MIN_ALIAS_LENGTH = 4\n\nexport interface DexCandidate {\n dex: string\n display: string\n distance: number\n}\n\nexport interface DexMatchResult {\n matched: DexEntry | null\n /** The name as typed, when the match is a near hit. */\n took_for?: string\n candidates: DexCandidate[]\n /** Every covered exchange, by display name. */\n covered: string[]\n}\n\n/**\n * One name against the registry rows:\n * one exact hit matched\n * several exact hits candidates at distance 0, matched null\n * no exact hit, one nearest exchange matched, took_for the name\n * no exact hit, a tie at the nearest candidates, matched null\n * nothing within two letters matched null, no candidates\n */\nexport function matchDex(name: string, rows: DexEntry[]): DexMatchResult {\n const covered = rows.map((row) => row.display)\n const wanted = normaliseName(name)\n if (!wanted) return { matched: null, candidates: [], covered }\n const exact = rows.filter((row) =>\n [row.dex, row.display, ...row.aliases].some((written) => normaliseName(written) === wanted)\n )\n if (exact.length === 1) return { matched: exact[0]!, candidates: [], covered }\n if (exact.length > 1) {\n return {\n matched: null,\n candidates: exact.map((row) => ({ dex: row.dex, display: row.display, distance: 0 })),\n covered,\n }\n }\n const near: Array<{ row: DexEntry; distance: number }> = []\n for (const row of rows) {\n const distances = row.aliases\n .map(normaliseName)\n .filter((alias) => alias.length >= NEAR_MIN_ALIAS_LENGTH)\n .map((alias) => damerauLevenshtein(wanted, alias))\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: [], covered }\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: [], covered }\n return {\n matched: null,\n candidates: nearest.map(({ row, distance }) => ({\n dex: row.dex,\n display: row.display,\n distance,\n })),\n covered,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,sBAAsB;;AAEnC,MAAa,sBA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I,aAAa,KAAK;CAC3D,IAAI,QAAQ,WAAW,GACrB,OAAO;EAAE,SAAS,QAAQ,EAAE,CAAE;EAAK,UAAU,KAAK,KAAK;EAAG,YAAY,CAAC;EAAG;CAAQ;CACpF,OAAO;EACL,SAAS;EACT,YAAY,QAAQ,KAAK,EAAE,KAAK,gBAAgB;GAC9C,KAAK,IAAI;GACT,SAAS,IAAI;GACb;EACF,EAAE;EACF;CACF;AACF"}
1
+ {"version":3,"file":"dex-registry-Bkri0--q.mjs","names":[],"sources":["../src/mcp/dex-registry.ts"],"sourcesContent":["/**\n * The exchange registry, as the proxy tool meta_dex_lookup reads it.\n *\n * The reviewed table lives in this repository, registry/<network>.md, and its\n * served copy registry/<network>.json is checked in CI\n * (scripts/pin-dex-registry.mjs). The proxy reads the copy three ways, in this\n * order:\n *\n * cached ~/.chain-insights/cache/dex-registry-<network>.json, younger than one hour\n * fetched the copy on main, https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/<network>.json,\n * within 3 s, at most once an hour per network and never two in flight\n * packaged registry/<network>.json of the installed package, when the fetch fails and no cache exists\n *\n * A fetched file is used only when it passes the same rules the pin script\n * applies. A malformed file never replaces a good cache: the stale cache keeps\n * answering and one line names the fault. So a proxy that never reaches GitHub\n * behaves like the skill memo of its own version, and a row merged on main\n * reaches every running proxy within the hour, with no release.\n *\n * matchDex turns a name into one exchange: normalise, exact on key, display and\n * aliases, then within two letters of an alias of four or more characters. One\n * winner is matched, a tie is listed, never guessed, and no hit names every\n * covered exchange.\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'\n\nexport const DEX_REGISTRY_SCHEMA = 'chain-insights.dex-registry.v1' as const\n/** How long a cached registry stays fresh. CACHE_TTL_MS (24 h) stays the lifetime of the schema caches. */\nexport const DEX_REGISTRY_TTL_MS = 60 * 60 * 1000\n/** The most a fetch of the public file may take on the call path. */\nexport const DEX_REGISTRY_FETCH_BUDGET_MS = 3_000\nexport const DEX_REGISTRY_URL_ENV = 'CHAIN_INSIGHTS_DEX_REGISTRY_URL'\nexport const DEX_REGISTRY_PUBLIC_URL =\n 'https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/{network}.json'\n\nexport const TRAIL_TYPES = ['plain', 'vault', 'gauge', 'launchpad'] as const\nexport type TrailType = (typeof TRAIL_TYPES)[number]\nexport const ROLES = ['factory', 'manager', 'router'] as const\nexport type Role = (typeof ROLES)[number]\nexport type RegistrySource = 'fetched' | 'cached' | 'packaged'\n\n/** One exchange of the served copy. */\nexport interface DexEntry {\n dex: string\n display: string\n aliases: string[]\n trail_type: TrailType\n adapters: string[]\n roles: Record<string, Role>\n /**\n * Contracts of the exchange the trail does not read: a position NFT, a staking gauge, a parts\n * deployer, a vault's swap router. A lookup by address finds them; no read is sent for them.\n */\n helpers?: string[]\n /** Its factory addresses, or the one manager of a vault. */\n factories: string[]\n /** Its routers, or the manager of a vault: a vault forwards its own swaps. */\n routers: string[]\n example_pool: string | null\n pool_floor: number | null\n since_block: number\n source: string\n}\n\nexport interface DexRegistryDocument {\n schema: typeof DEX_REGISTRY_SCHEMA\n network: string\n registry_version: number\n recorded_on: string\n rows: DexEntry[]\n}\n\nexport interface LoadedRegistry {\n document: DexRegistryDocument\n source: RegistrySource\n loaded_at_ms: number\n}\n\n/** A refusal with its own words for the caller: a network the registry does not cover. */\nexport class DexRegistryError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DexRegistryError'\n }\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/\n// An example pool is a pool address, or the pool id of a manager that keeps its pools by id.\nconst POOL_RE = /^0x(?:[0-9a-f]{40}|[0-9a-f]{64})$/\nconst DEX_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/\nconst NETWORK_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/\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 network as a lower-case identifier; it becomes part of a file name and a URL. */\nexport function normalizeDexNetwork(raw: unknown): string {\n const network = typeof raw === 'string' ? raw.trim().toLowerCase() : ''\n if (!network) {\n throw new DexRegistryError(\n 'invalid_network: network is required. Pass the identifier of a served network, for example robinhood.'\n )\n }\n if (!NETWORK_RE.test(network)) {\n throw new DexRegistryError(`invalid_network: \"${String(raw)}\" is not a network identifier`)\n }\n return network\n}\n\n/**\n * The fault of a registry document, or null when it is valid for the network:\n * the rules of registry/README.md, the same ones the pin script applies.\n */\nexport function registryFault(value: unknown, network: string): string | null {\n if (!isRecord(value)) return 'the file is not a JSON object'\n if (value.schema !== DEX_REGISTRY_SCHEMA) {\n return `schema is ${JSON.stringify(value.schema)}, not ${DEX_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 keys = new Set<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.dex !== 'string' || !DEX_RE.test(row.dex))\n return `${at}.dex is not a key: ${String(row.dex)}`\n if (keys.has(row.dex)) return `${at}.dex ${row.dex} is listed twice`\n keys.add(row.dex)\n if (typeof row.display !== 'string' || row.display.trim() === '')\n return `${at} (${row.dex}) has no display`\n if (!isStringList(row.aliases)) return `${at} (${row.dex}) aliases is not a list of names`\n if (!TRAIL_TYPES.includes(row.trail_type as TrailType)) {\n return `${at} (${row.dex}) trail_type ${String(row.trail_type)} is not plain, vault, gauge or launchpad`\n }\n if (!isStringList(row.adapters)) return `${at} (${row.dex}) adapters is not a list`\n if (!isRecord(row.roles)) return `${at} (${row.dex}) roles is not a map`\n for (const [address, role] of Object.entries(row.roles)) {\n if (!ADDRESS_RE.test(address))\n return `${at} (${row.dex}) address ${address} is not lowercase 0x plus 40 hex characters`\n if (!ROLES.includes(role as Role))\n return `${at} (${row.dex}) role ${String(role)} is not factory, manager or router`\n }\n if (row.helpers !== undefined) {\n if (!isStringList(row.helpers)) return `${at} (${row.dex}) helpers is not a list`\n for (const address of row.helpers) {\n if (!ADDRESS_RE.test(address))\n return `${at} (${row.dex}) address ${address} is not lowercase 0x plus 40 hex characters`\n }\n }\n for (const field of ['factories', 'routers'] as const) {\n const list = row[field]\n if (!isStringList(list)) return `${at} (${row.dex}) ${field} is not a list`\n for (const address of list) {\n if (!ADDRESS_RE.test(address))\n return `${at} (${row.dex}) address ${address} is not lowercase 0x plus 40 hex characters`\n if (!(address in row.roles))\n return `${at} (${row.dex}) ${field} names ${address}, which roles lacks`\n }\n }\n if ((row.factories as string[]).length === 0)\n return `${at} (${row.dex}) has no factory or manager`\n if (\n row.example_pool !== null &&\n (typeof row.example_pool !== 'string' || !POOL_RE.test(row.example_pool))\n ) {\n return `${at} (${row.dex}) example_pool ${String(row.example_pool)} is not a pool`\n }\n if (\n row.pool_floor !== null &&\n (!Number.isInteger(row.pool_floor) || (row.pool_floor as number) < 0)\n ) {\n return `${at} (${row.dex}) pool_floor is not a whole number`\n }\n if (!Number.isInteger(row.since_block) || (row.since_block as number) < 0) {\n return `${at} (${row.dex}) since_block is not a block`\n }\n if (typeof row.source !== 'string' || !row.source.startsWith('https://')) {\n return `${at} (${row.dex}) source is not an https link`\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 dexRegistryUrl(network: string, env: NodeJS.ProcessEnv = process.env): string {\n const override = env[DEX_REGISTRY_URL_ENV]?.trim()\n const template = override || DEX_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 dexRegistryCachePath(network: string): string {\n return path.join(chainInsightsHome(), 'cache', `dex-registry-${network}.json`)\n}\n\n/** The registry/ folder of the installed package: next to dist/, or the repository root when run from source. */\nexport function packagedRegistryDir(): string {\n const candidates = [\n fileURLToPath(new URL('../registry', import.meta.url)),\n fileURLToPath(new URL('../../registry', 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 is a defect: it throws. */\nexport function readPackagedRegistry(\n network: string,\n dir: string = packagedRegistryDir()\n): DexRegistryDocument | 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 = registryFault(parsed, network)\n if (fault)\n throw new Error(\n `the packaged exchange registry registry/${network}.json is malformed: ${fault}`\n )\n return parsed as DexRegistryDocument\n}\n\ninterface CacheFile {\n schema: typeof DEX_REGISTRY_SCHEMA\n network: string\n registry_version: number\n recorded_on: string\n rows: DexEntry[]\n /** When the copy was read: the fetch, or the first start with no fetch. */\n cached_at_ms: number\n /** When a fetch was last tried. The cache is fresh for an hour after it. */\n checked_at_ms: number\n source: 'fetched' | 'packaged'\n}\n\nconst documentOf = (file: CacheFile): DexRegistryDocument => ({\n schema: file.schema,\n network: file.network,\n registry_version: file.registry_version,\n recorded_on: file.recorded_on,\n rows: file.rows,\n})\n\nasync function readCache(network: string): Promise<CacheFile | null> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(dexRegistryCachePath(network), 'utf8'))\n } catch {\n return null\n }\n if (!isRecord(parsed) || registryFault(parsed, network) !== null) return null\n if (typeof parsed.checked_at_ms !== 'number' || typeof parsed.cached_at_ms !== 'number')\n return null\n if (parsed.source !== 'fetched' && parsed.source !== 'packaged') return null\n return parsed as unknown as CacheFile\n}\n\nasync function writeCache(file: CacheFile): Promise<void> {\n const target = dexRegistryCachePath(file.network)\n await mkdir(path.dirname(target), { recursive: true })\n // Written beside the target and renamed, so a second proxy never reads 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\nexport interface LoadRegistryOptions {\n fetch?: typeof fetch\n now?: () => number\n env?: NodeJS.ProcessEnv\n /** One line per fault: a failed fetch, a malformed file, a cache that cannot be written. */\n log?: (line: string) => void\n packagedDir?: string\n budgetMs?: number\n}\n\ntype FetchOutcome = { document: DexRegistryDocument } | { fault: string }\n\nasync function fetchRegistry(network: string, options: LoadRegistryOptions): Promise<FetchOutcome> {\n const url = dexRegistryUrl(network, options.env)\n const fetchImpl = options.fetch ?? fetch\n let response: Response\n try {\n response = await fetchImpl(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 = registryFault(parsed, network)\n if (fault) return { fault: `${url} is malformed: ${fault}` }\n return { document: parsed as DexRegistryDocument }\n}\n\n// Fetches in flight, by network: two calls at once share one fetch.\nconst inFlight = new Map<string, Promise<LoadedRegistry>>()\n\nconst defaultLog = (line: string): void => {\n process.stderr.write(`[chain-insights] dex-registry: ${line}\\n`)\n}\n\n/**\n * The registry of one network: the fresh cache, else the public file, else the\n * stale cache, else the packaged copy. A packaged copy with a higher registry\n * version than the cache or the public file wins, so an upgrade is never\n * answered from an older file. Never throws for a network the package covers.\n */\nexport async function loadRegistry(\n rawNetwork: unknown,\n options: LoadRegistryOptions = {}\n): Promise<LoadedRegistry> {\n const network = normalizeDexNetwork(rawNetwork)\n const now = options.now ?? Date.now\n const log = options.log ?? defaultLog\n const packaged = readPackagedRegistry(network, options.packagedDir)\n const newer = (document: DexRegistryDocument): boolean =>\n packaged !== null && packaged.registry_version > document.registry_version\n const fromPackaged = (): LoadedRegistry => ({\n document: packaged!,\n source: 'packaged',\n loaded_at_ms: now(),\n })\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 if (newer(cache)) return fromPackaged()\n return {\n document: documentOf(cache),\n source: cache.source === 'fetched' ? 'cached' : 'packaged',\n loaded_at_ms: now(),\n }\n }\n\n const running = inFlight.get(network)\n if (running) return running\n const load = (async (): Promise<LoadedRegistry> => {\n const outcome = await fetchRegistry(network, options)\n const checked = now()\n const save = async (file: CacheFile): Promise<void> => {\n try {\n await writeCache(file)\n } catch (err) {\n log(\n `the cache ${dexRegistryCachePath(network)} could not be written: ${err instanceof Error ? err.message : String(err)}`\n )\n }\n }\n if ('document' in outcome) {\n const { document } = outcome\n await save({ ...document, cached_at_ms: checked, checked_at_ms: checked, source: 'fetched' })\n if (newer(document)) return fromPackaged()\n return { document, source: 'fetched', loaded_at_ms: checked }\n }\n log(outcome.fault)\n if (cache) {\n // The stale cache keeps answering, and the next fetch waits an hour.\n await save({ ...cache, checked_at_ms: checked })\n if (newer(cache)) return fromPackaged()\n return {\n document: documentOf(cache),\n source: cache.source === 'fetched' ? 'cached' : 'packaged',\n loaded_at_ms: checked,\n }\n }\n if (!packaged) {\n throw new DexRegistryError(\n `network_not_covered: the exchange registry covers no network \"${network}\", and ${outcome.fault}`\n )\n }\n await save({ ...packaged, cached_at_ms: checked, checked_at_ms: checked, source: 'packaged' })\n return fromPackaged()\n })()\n inFlight.set(network, load)\n try {\n return await load\n } finally {\n inFlight.delete(network)\n }\n}\n\n// ─── The name match ───────────────────────────────────────────────────────────\n\n/** Lower case, with every space, \".\", \"-\" and \"_\" removed: \"Uni v4\" and \"uni-v4\" are \"univ4\". */\n/** The exchange that lists a contract, by any role or as a helper, or null. */\n/** The exchange whose pool manager this address is: a vault exchange that holds its pools in one contract. */\nexport function dexManagerOf(address: string, rows: readonly DexEntry[]): DexEntry | null {\n return rows.find((row) => row.trail_type === 'vault' && row.roles[address] === 'manager') ?? null\n}\n\nexport function dexOfAddress(address: string, rows: readonly DexEntry[]): DexEntry | null {\n return rows.find((row) => address in row.roles || row.helpers?.includes(address)) ?? null\n}\n\nexport function normaliseName(name: string): string {\n return name.toLowerCase().replace(/[\\s.\\-_]+/g, '')\n}\n\n/** The optimal string alignment distance: insertions, deletions, substitutions and swaps of two neighbours. */\nexport function damerauLevenshtein(a: string, b: string): number {\n const rows = a.length + 1\n const cols = b.length + 1\n const d: number[][] = Array.from({ length: rows }, (_, i) =>\n Array.from({ length: cols }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))\n )\n for (let i = 1; i < rows; i += 1) {\n for (let j = 1; j < cols; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n let best = Math.min(d[i - 1]![j]! + 1, d[i]![j - 1]! + 1, d[i - 1]![j - 1]! + cost)\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, d[i - 2]![j - 2]! + 1)\n }\n d[i]![j] = best\n }\n }\n return d[a.length]![b.length]!\n}\n\n/** The most letters a near hit may differ by, and the shortest alias a near hit is taken from. */\nexport const NEAR_DISTANCE = 2\nexport const NEAR_MIN_ALIAS_LENGTH = 4\n\nexport interface DexCandidate {\n dex: string\n display: string\n distance: number\n}\n\nexport interface DexMatchResult {\n matched: DexEntry | null\n /** The name as typed, when the match is a near hit. */\n took_for?: string\n candidates: DexCandidate[]\n /** Every covered exchange, by display name. */\n covered: string[]\n}\n\n/**\n * One name against the registry rows:\n * one exact hit matched\n * several exact hits candidates at distance 0, matched null\n * no exact hit, one nearest exchange matched, took_for the name\n * no exact hit, a tie at the nearest candidates, matched null\n * nothing within two letters matched null, no candidates\n */\nexport function matchDex(name: string, rows: DexEntry[]): DexMatchResult {\n const covered = rows.map((row) => row.display)\n const wanted = normaliseName(name)\n if (!wanted) return { matched: null, candidates: [], covered }\n const exact = rows.filter((row) =>\n [row.dex, row.display, ...row.aliases].some((written) => normaliseName(written) === wanted)\n )\n if (exact.length === 1) return { matched: exact[0]!, candidates: [], covered }\n if (exact.length > 1) {\n return {\n matched: null,\n candidates: exact.map((row) => ({ dex: row.dex, display: row.display, distance: 0 })),\n covered,\n }\n }\n const near: Array<{ row: DexEntry; distance: number }> = []\n for (const row of rows) {\n const distances = row.aliases\n .map(normaliseName)\n .filter((alias) => alias.length >= NEAR_MIN_ALIAS_LENGTH)\n .map((alias) => damerauLevenshtein(wanted, alias))\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: [], covered }\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: [], covered }\n return {\n matched: null,\n candidates: nearest.map(({ row, distance }) => ({\n dex: row.dex,\n display: row.display,\n distance,\n })),\n covered,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,sBAAsB;;AAEnC,MAAa,sBAAsB;;AAEnC,MAAa,+BAA+B;AAC5C,MAAa,uBAAuB;AACpC,MAAa,0BACX;AAEF,MAAa,cAAc;CAAC;CAAS;CAAS;CAAS;AAAW;AAElE,MAAa,QAAQ;CAAC;CAAW;CAAW;AAAQ;;AA0CpD,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,MAAM,aAAa;AAEnB,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,aAAa;AAE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UAAU,KAAK,KAAK;EAAG,YAAY,CAAC;EAAG;CAAQ;CACpF,OAAO;EACL,SAAS;EACT,YAAY,QAAQ,KAAK,EAAE,KAAK,gBAAgB;GAC9C,KAAK,IAAI;GACT,SAAS,IAAI;GACb;EACF,EAAE;EACF;CACF;AACF"}
@@ -278,6 +278,14 @@ async function loadRegistry(rawNetwork, options = {}) {
278
278
  }
279
279
  }
280
280
  /** Lower case, with every space, ".", "-" and "_" removed: "Uni v4" and "uni-v4" are "univ4". */
281
+ /** The exchange that lists a contract, by any role or as a helper, or null. */
282
+ /** The exchange whose pool manager this address is: a vault exchange that holds its pools in one contract. */
283
+ function dexManagerOf(address, rows) {
284
+ return rows.find((row) => row.trail_type === "vault" && row.roles[address] === "manager") ?? null;
285
+ }
286
+ function dexOfAddress(address, rows) {
287
+ return rows.find((row) => address in row.roles || row.helpers?.includes(address)) ?? null;
288
+ }
281
289
  function normaliseName(name) {
282
290
  return name.toLowerCase().replace(/[\s.\-_]+/g, "");
283
291
  }
@@ -400,6 +408,18 @@ Object.defineProperty(exports, "damerauLevenshtein", {
400
408
  return damerauLevenshtein;
401
409
  }
402
410
  });
411
+ Object.defineProperty(exports, "dexManagerOf", {
412
+ enumerable: true,
413
+ get: function() {
414
+ return dexManagerOf;
415
+ }
416
+ });
417
+ Object.defineProperty(exports, "dexOfAddress", {
418
+ enumerable: true,
419
+ get: function() {
420
+ return dexOfAddress;
421
+ }
422
+ });
403
423
  Object.defineProperty(exports, "dex_registry_exports", {
404
424
  enumerable: true,
405
425
  get: function() {
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
2
  import { t as ANSWER_HINT } from "./answer-hint-vOE1O6Lf.mjs";
3
- import { t as LEVEL_RULE } from "./layer-routing-DCJVNN6O.mjs";
4
- import { d as normalizeDexNetwork, l as matchDex, r as DexRegistryError } from "./dex-registry-BY67f4Ul.mjs";
3
+ import { t as LEVEL_RULE } from "./layer-routing-r4IbIQSr.mjs";
4
+ import { c as dexOfAddress, d as matchDex, p as normalizeDexNetwork, r as DexRegistryError } from "./dex-registry-Bkri0--q.mjs";
5
5
  // src/mcp/dex-recipes.ts
6
6
  /** The trail-type skill of each trail, for hosts that load skills. */
7
7
  const TRAIL_SKILLS = {
@@ -541,7 +541,7 @@ async function handleMetaDexLookup(args, deps) {
541
541
  }
542
542
  let match;
543
543
  if (address !== null) {
544
- const holder = document.rows.find((row) => address in row.roles || row.helpers?.includes(address));
544
+ const holder = dexOfAddress(address, document.rows);
545
545
  match = {
546
546
  matched: holder ?? null,
547
547
  ...holder ? { took_for: `${holder.roles[address] ?? "helper"}, served` } : {},
@@ -619,4 +619,4 @@ async function handleMetaDexLookup(args, deps) {
619
619
  }
620
620
  export { dex_tool_exports as a, META_DEX_LOOKUP_TOOL as i, META_DEX_LOOKUP_DESCRIPTION as n, handleMetaDexLookup as o, META_DEX_LOOKUP_TITLE as r, META_DEX_LOOKUP_ANNOTATIONS as t };
621
621
 
622
- //# sourceMappingURL=dex-tool-7BK_gD6H.mjs.map
622
+ //# sourceMappingURL=dex-tool-D0K_Qx4N.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dex-tool-D0K_Qx4N.mjs","names":[],"sources":["../src/mcp/dex-recipes.ts","../src/mcp/dex-tool.ts"],"sourcesContent":["/**\n * The first reads of each trail type, filled with the addresses of one\n * exchange. meta_dex_lookup returns them, so a host that loads no skill\n * (Claude Desktop chat) still gets the tested reads of\n * skills/chain-insights-dex*. The shapes are the skills' own: R3 and R4 of\n * chain-insights-dex, G1, G4 and G5 of the gauge trail, V1, V3 and V4 of the\n * vault trail, L1 to L3 of the launchpad trail.\n *\n * A value the lookup cannot know (a seller, a day, a transaction) is written\n * as a placeholder in angle brackets, and the step's `why` says where it comes\n * from. Every address the lookup knows is written in full.\n *\n * Two graph shapes, picked per lane (src/mcp/layer-routing.ts swapLinkShape):\n * `route`, the graph of before, where SWAPPED runs from a payer to a recipient\n * and holds the whole route; and `levels`, where ROUTED_TO is the route of a\n * payer and a receiver (level 2) and SWAPPED runs from a trader to one pool\n * (level 1). Every `route` read is the one of chain-insights 0.81.0, byte for\n * byte: tests/link-levels.test.ts holds them to tests/fixtures/dex-reads-0.81.0.json.\n */\n\nimport type { DexEntry, TrailType } from './dex-registry.js'\nimport type { SwapLinkShape } from './layer-routing.js'\n\nexport interface RecipeStep {\n step: string\n why: string\n query: string\n}\n\n/** The trail-type skill of each trail, for hosts that load skills. */\nexport const TRAIL_SKILLS: Record<TrailType, string> = {\n plain: 'chain-insights-dex',\n gauge: 'chain-insights-dex-gauge',\n vault: 'chain-insights-dex-vault',\n launchpad: 'chain-insights-dex-launchpad',\n}\n\nconst SELLER = '<seller address>'\nconst DAY = '<YYYY-MM-DD>'\nconst TX = '<tx_id>'\nconst TOKEN = '<launched token address>'\n\n/**\n * The pools one factory deployed, ranked (R3). On the graph of before, by the\n * pool's lifetime volume. On a lane with the levels a pool has no address\n * totals (its transactions are not on FLOWED_TO), so the pools are ranked by\n * the USD sold into each on its SWAPPED links (R3L).\n */\nexport function poolsByFactoryQuery(\n factory: string,\n limit = 10,\n shape: SwapLinkShape = 'route'\n): string {\n if (shape === 'levels') {\n return (\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[:DEPLOYED_CONTRACT]->(p:Pool) ` +\n 'MATCH (t:Address)-[s:SWAPPED]->(p) ' +\n 'RETURN f.address AS from_address, p.address AS to_address, p.labels AS to_labels, sum(s.sold_usd) AS swapped_usd, sum(s.swap_count) AS swap_count ' +\n `ORDER BY swapped_usd DESC LIMIT ${limit}`\n )\n }\n return (\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[:DEPLOYED_CONTRACT]->(p:Pool) WHERE p.total_volume_usd IS NOT NULL ` +\n 'RETURN f.address AS from_address, p.address AS to_address, p.labels AS to_labels, p.total_volume_usd AS total_volume_usd, p.tx_total_count AS tx_total_count ' +\n `ORDER BY p.total_volume_usd DESC LIMIT ${limit}`\n )\n}\n\n/** The senders of one pool on FLOWED_TO, by lifetime volume (R4, G1). */\nfunction sellersIntoPoolQuery(pool: string): string {\n return (\n `USE topology MATCH (s:Address)-[f:FLOWED_TO]->(p:Address {address: \"${pool}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(s) AS from_node_labels, f.amount_usd_sum AS amount_usd_sum, f.tx_count AS tx_count, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp, s.labels AS from_labels, p.labels AS to_labels, s.is_exchange AS from_is_exchange, p.is_exchange AS to_is_exchange ' +\n 'ORDER BY f.amount_usd_sum DESC LIMIT 25'\n )\n}\n\n/** The payers whose swaps name one contract as the recipient, by sold volume (V4 shape). */\nfunction sellersIntoContractQuery(contract: string): string {\n return (\n `USE topology MATCH (s:Address)-[sw:SWAPPED]->(r:Address {address: \"${contract}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, r.address AS to_address, labels(s) AS from_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.pools AS pools, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.sold_usd DESC LIMIT 25'\n )\n}\n\n/** One seller's swaps (R5, G2, V1). */\nfunction sellerSwapsQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[sw:SWAPPED]->(r:Address) ` +\n 'RETURN s.address AS from_address, r.address AS to_address, labels(r) AS to_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.pools AS pools, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.swap_count DESC LIMIT 25'\n )\n}\n\n/** The facts SWAP rows of a seller and one recipient on one day (R6, G4, V3). */\nfunction swapRowsQuery(recipient: string): string {\n return (\n `USE facts MATCH (s:Address {address: \"${SELLER}\"})-[x:SWAP]->(r:Address {address: \"${recipient}\"}) WHERE x.block_date = \"${DAY}\" ` +\n 'RETURN x.tx_id AS tx_id, x.block_timestamp AS block_timestamp, x.payer AS payer, x.recipient AS recipient, x.sold_asset_symbol AS sold_asset_symbol, x.sold_usd AS sold_usd, x.bought_asset_symbol AS bought_asset_symbol, x.bought_usd AS bought_usd LIMIT 50'\n )\n}\n\n/** The transfers one router made in one transaction (G5). */\nfunction routerPayoutQuery(router: string): string {\n return (\n `USE facts MATCH (r:Address {address: \"${router}\"})-[t:TRANSFER]->(b:Address) WHERE t.block_date = \"${DAY}\" AND t.tx_id = \"${TX}\" ` +\n 'RETURN r.address AS from_address, b.address AS to_address, t.amount_usd AS amount_usd, t.asset_symbol AS asset_symbol, t.kind AS kind, t.tx_id AS tx_id LIMIT 10'\n )\n}\n\n/** The traders at one pool or pool manager on SWAPPED, by sold volume (levels). */\nfunction tradersAtPoolQuery(pool: string): string {\n return (\n `USE topology MATCH (s:Address)-[sw:SWAPPED]->(p:Address {address: \"${pool}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(s) AS from_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.first_seen_height AS first_seen_height, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.sold_usd DESC LIMIT 25'\n )\n}\n\n/** One trader's routes on ROUTED_TO: who got what it bought (levels). */\nfunction traderRoutesQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[r:ROUTED_TO]->(b:Address) ` +\n 'RETURN s.address AS from_address, b.address AS to_address, labels(b) AS to_node_labels, r.tx_count AS tx_count, r.swap_count AS swap_count, r.amount_usd_sum AS amount_usd_sum, r.bought_usd_sum AS bought_usd_sum, r.unpriced_count AS unpriced_count, r.first_seen_timestamp AS first_seen_timestamp, r.last_seen_timestamp AS last_seen_timestamp ' +\n 'ORDER BY r.amount_usd_sum DESC LIMIT 25'\n )\n}\n\n/** One trader's swaps on SWAPPED: the pools and the assets (levels). */\nfunction traderPoolSwapsQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[sw:SWAPPED]->(p:Address) ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(p) AS to_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.swap_count DESC LIMIT 25'\n )\n}\n\nconst dayStep: RecipeStep = {\n step: 'The day of a swap link',\n why: 'A SWAPPED link carries heights, not times: read the block of its last_seen_height for the day the facts reads need.',\n query:\n 'USE chain MATCH (b:Block {block_height: <last_seen_height>}) RETURN b.block_date, b.block_timestamp',\n}\n\n/**\n * The pool a trail starts from: the busiest pool read, else the registry's\n * example pool, else none.\n */\nfunction startPool(entry: DexEntry, topPool: string | null): string | null {\n return topPool ?? entry.example_pool ?? null\n}\n\nfunction poolsStep(entry: DexEntry, shape: SwapLinkShape = 'route'): RecipeStep | null {\n const factory = entry.factories.find((address) => entry.roles[address] === 'factory')\n if (!factory) return null\n const members = entry.factories.filter((a) => entry.roles[a] === 'factory').join(', ')\n if (shape === 'levels') {\n return {\n step: 'Pools of the exchange, by factory',\n why: `The pools ${entry.display} deployed, by the USD sold into each on its SWAPPED links, with its swap count. A pool has no address totals on this lane. A pool nobody swapped in is left out. One batch member per factory: ${members}.`,\n query: poolsByFactoryQuery(factory, 10, 'levels'),\n }\n }\n return {\n step: 'Pools of the exchange, by factory',\n why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${members}.`,\n query: poolsByFactoryQuery(factory),\n }\n}\n\n/** The first reads of the exchange's trail type, with its addresses filled in. */\nexport function recipeFor(\n entry: DexEntry,\n topPool: string | null,\n shape: SwapLinkShape = 'route'\n): RecipeStep[] {\n return shape === 'levels' ? levelsRecipeFor(entry, topPool) : routeRecipeFor(entry, topPool)\n}\n\nconst routesStep: RecipeStep = {\n step: \"Who got what a trader bought\",\n why: 'Fill a trader from the first step. Each ROUTED_TO link is the swaps of one payer and one receiver, in USD: a link to the trader itself means it bought for itself, any other receiver is the buyer. No router and no pool is a receiver.',\n query: traderRoutesQuery(),\n}\n\nconst poolSwapsStep: RecipeStep = {\n step: \"A trader's pools and assets\",\n why: 'Fill the trader: each SWAPPED link is one pool and one asset pair, with what the pool got (sold) and what it gave (bought).',\n query: traderPoolSwapsQuery(),\n}\n\n/** The reads of a lane with the levels: SWAPPED to a pool, ROUTED_TO for the route. */\nfunction levelsRecipeFor(entry: DexEntry, topPool: string | null): RecipeStep[] {\n const pool = startPool(entry, topPool)\n const steps: RecipeStep[] = []\n const poolTraders = (at: string): RecipeStep => ({\n step: 'Traders at the busiest pool',\n why: `The traders of ${at} on SWAPPED, by sold volume. A trader that is a contract is often an aggregator or a bot: say \"a contract\". A sender that only adds liquidity is on ADDED_LIQUIDITY, not here.`,\n query: tradersAtPoolQuery(at),\n })\n switch (entry.trail_type) {\n case 'gauge': {\n const router = entry.routers[0]\n if (pool) steps.push(poolTraders(pool))\n else {\n const pools = poolsStep(entry, 'levels')\n if (pools) steps.push(pools)\n }\n steps.push(routesStep)\n if (router) {\n steps.push(dayStep)\n steps.push({\n step: \"A trader's swaps through the router on one day\",\n why: `Fill the trader and the day: each row gives the tx_id of one swap that named the router ${router}; the router is never the buyer.`,\n query: swapRowsQuery(router),\n })\n steps.push({\n step: 'Who the router paid in that transaction',\n why: 'Fill the day and the tx_id: the receiver of the bought asset is the buyer. A pool or a pool manager there is the next leg, not the buyer.',\n query: routerPayoutQuery(router),\n })\n }\n break\n }\n case 'vault': {\n const manager = entry.factories[0]!\n steps.push({\n step: 'Traders at the pool manager',\n why: `${entry.display} keeps every pool in one manager, ${manager}. Each SWAPPED link into it is one trader and one asset pair: the pair names the pool.`,\n query: tradersAtPoolQuery(manager),\n })\n steps.push(routesStep)\n steps.push(dayStep)\n steps.push({\n step: 'The facts SWAP row past the manager',\n why: 'Fill the trader and the day: the recipient column names who the manager paid.',\n query: swapRowsQuery(manager),\n })\n break\n }\n case 'launchpad': {\n const factory = entry.factories[0]!\n steps.push({\n step: 'Launches of the launchpad, newest first',\n why: `The contracts ${factory} created, with the creator of each.`,\n query:\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[d:DEPLOYED_CONTRACT]->(t:Address) ` +\n 'RETURN f.address AS from_address, t.address AS to_address, labels(t) AS to_node_labels, t.labels AS to_labels, d.tx_origin AS creator, d.tx_id AS tx_id, d.block_height AS block_height, d.block_timestamp AS created_timestamp ORDER BY d.block_height DESC LIMIT 25',\n })\n steps.push({\n step: 'Traders on the curve of one launched token',\n why: 'Fill a launched token from the first step. A curve is a pool: its traders are its SWAPPED links. A launch whose curve is another contract has its traders on that contract.',\n query: tradersAtPoolQuery(TOKEN),\n })\n steps.push({\n step: 'The first pool of one launched token',\n why: 'The oldest ADDED_LIQUIDITY into a :Pool is the graduation. None means it has not graduated in the graph yet.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[l:ADDED_LIQUIDITY]->(p:Pool) ` +\n 'RETURN t.address AS from_address, p.address AS to_address, p.labels AS to_labels, l.asset AS asset, l.usd AS usd, l.first_seen_height AS first_seen_height ORDER BY l.first_seen_height ASC LIMIT 5',\n })\n break\n }\n case 'plain': {\n if (pool) steps.push(poolTraders(pool))\n else {\n const pools = poolsStep(entry, 'levels')\n if (pools) steps.push(pools)\n }\n steps.push(routesStep)\n steps.push(poolSwapsStep)\n steps.push(dayStep)\n steps.push({\n step: 'The swaps of a trader and a receiver on one day',\n why: 'Fill the trader, the receiver and the day.',\n query: swapRowsQuery('<recipient address>'),\n })\n break\n }\n }\n return steps\n}\n\n/** The reads of a lane with the graph of before: SWAPPED holds the route. */\nfunction routeRecipeFor(entry: DexEntry, topPool: string | null): RecipeStep[] {\n const pool = startPool(entry, topPool)\n const steps: RecipeStep[] = []\n switch (entry.trail_type) {\n case 'gauge': {\n const router = entry.routers[0]\n if (router) {\n steps.push({\n step: 'Sellers into the router',\n why: `On ${entry.display} a swap pays the router, and the router pays on. These are the payers whose swaps name the router ${router}; the router is never the buyer.`,\n query: sellersIntoContractQuery(router),\n })\n }\n if (pool) {\n steps.push({\n step: 'Sellers into the busiest pool',\n why: `The senders of ${pool} on FLOWED_TO. A sender that also adds liquidity is a liquidity provider, not a seller.`,\n query: sellersIntoPoolQuery(pool),\n })\n } else {\n const pools = poolsStep(entry)\n if (pools) steps.push(pools)\n }\n if (router) {\n steps.push(dayStep)\n steps.push({\n step: \"A seller's swaps through the router on one day\",\n why: 'Fill the seller from the first step and the day from the block read: each row gives the tx_id of one swap.',\n query: swapRowsQuery(router),\n })\n steps.push({\n step: 'Who the router paid in that transaction',\n why: 'Fill the day and the tx_id: the receiver of the bought asset is the buyer. A pool or a pool manager there is the next leg, not the buyer.',\n query: routerPayoutQuery(router),\n })\n }\n break\n }\n case 'vault': {\n const manager = entry.factories[0]!\n steps.push({\n step: 'The swaps the pool manager settles',\n why: `${entry.display} keeps every pool in one manager, ${manager}. A manager deploys nothing: its pools are the pools of the swaps it settles.`,\n query: sellersIntoContractQuery(manager),\n })\n steps.push({\n step: \"One seller's swaps\",\n why: 'Fill a seller from the first step. A recipient that is the manager is never the buyer: read the facts row past it.',\n query: sellerSwapsQuery(),\n })\n steps.push(dayStep)\n steps.push({\n step: 'The facts SWAP row past the manager',\n why: 'Fill the seller and the day: the recipient column names who the manager paid.',\n query: swapRowsQuery(manager),\n })\n break\n }\n case 'launchpad': {\n const factory = entry.factories[0]!\n steps.push({\n step: 'Launches of the launchpad, newest first',\n why: `The contracts ${factory} created, with the creator of each.`,\n query:\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[d:DEPLOYED_CONTRACT]->(t:Address) ` +\n 'RETURN f.address AS from_address, t.address AS to_address, labels(t) AS to_node_labels, t.labels AS to_labels, d.tx_origin AS creator, d.tx_id AS tx_id, d.block_height AS block_height, d.block_timestamp AS created_timestamp ORDER BY d.block_height DESC LIMIT 25',\n })\n steps.push({\n step: 'Traders on the curve of one launched token',\n why: 'Fill a launched token from the first step.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[f:FLOWED_TO]-(b:Address) WHERE NOT t:Pool ` +\n 'RETURN startNode(f).address AS from_address, endNode(f).address AS to_address, labels(b) AS node_labels, f.tx_count AS tx_count, f.amount_usd_sum AS amount_usd_sum, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp ORDER BY f.tx_count DESC LIMIT 25',\n })\n steps.push({\n step: 'The first pool of one launched token',\n why: 'The oldest ADDED_LIQUIDITY into a :Pool is the graduation. None means it has not graduated in the graph yet.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[l:ADDED_LIQUIDITY]->(p:Pool) ` +\n 'RETURN t.address AS from_address, p.address AS to_address, p.labels AS to_labels, l.asset AS asset, l.usd AS usd, l.first_seen_height AS first_seen_height ORDER BY l.first_seen_height ASC LIMIT 5',\n })\n break\n }\n case 'plain': {\n if (pool) {\n steps.push({\n step: 'Sellers into the busiest pool',\n why: `The senders of ${pool} on FLOWED_TO, by lifetime volume. A seller that is a contract is often an aggregator or a router: say \"a contract\".`,\n query: sellersIntoPoolQuery(pool),\n })\n } else {\n const pools = poolsStep(entry)\n if (pools) steps.push(pools)\n }\n steps.push({\n step: \"Who a seller's swaps paid\",\n why: 'Fill a seller from the first step. Keep the rows whose pools hold the pool: the recipient is the buyer.',\n query: sellerSwapsQuery(),\n })\n steps.push(dayStep)\n steps.push({\n step: 'The swaps of a seller and a recipient on one day',\n why: 'Fill the seller, the recipient and the day.',\n query: swapRowsQuery('<recipient address>'),\n })\n break\n }\n }\n return steps\n}\n","/**\n * meta_dex_lookup: an exchange's name becomes its addresses.\n *\n * A local tool of the proxy. It matches the name against the exchange registry\n * (src/mcp/dex-registry.ts) at no cost, then sends one graph_query_batch of\n * anchored reads: Head for the family lag, each factory, manager and router by\n * its address, and the pools each factory deployed. Nothing is read by name and\n * nothing is gated on a family lag: a factory deployed months ago is not stale\n * because the swap family is behind. A name that is not covered sends no read.\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 exchange skills open\n * with, and the level rule. tests/host-parity.test.ts holds it to the skills'\n * trigger words and to the level rule.\n *\n * The first reads follow the lane's graph shape (`linkShape`, read from\n * meta_network_capabilities): on a lane whose money family lists ROUTED_TO the\n * reads name SWAPPED from a trader to the pool and ROUTED_TO for the route; on\n * any other lane they are the reads of chain-insights 0.81.0, byte for byte.\n * The pool read follows the shape too: on a lane with the levels a pool has no\n * address totals, so its pools are ranked by the USD sold into each on SWAPPED.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { recipeFor, TRAIL_SKILLS, type RecipeStep, poolsByFactoryQuery } from './dex-recipes.js'\nimport { LEVEL_RULE, type SwapLinkShape } from './layer-routing.js'\nimport {\n DexRegistryError,\n matchDex,\n dexOfAddress,\n normalizeDexNetwork,\n type DexCandidate,\n type DexEntry,\n type DexMatchResult,\n type LoadedRegistry,\n type RegistrySource,\n type Role,\n type TrailType,\n} from './dex-registry.js'\n\nexport const META_DEX_LOOKUP_TOOL = 'meta_dex_lookup'\nexport const META_DEX_LOOKUP_SCHEMA = 'chain-insights.meta-dex-lookup.v1' as const\nexport const META_DEX_LOOKUP_TITLE = 'Exchange by name or address'\nexport const META_DEX_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a decentralized exchange, a launchpad or a vault ' +\n '(Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, ' +\n \"Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's \" +\n 'factories, routers or pool manager, its biggest pools, and the first reads to send, ' +\n 'with every address in full. A misspelling within two letters is taken and named in ' +\n 'took_for. When matched is null the name is not covered: say so, list covered, and send ' +\n 'no graph query for the name. Never ask the user for a pool, factory or router address. ' +\n 'When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, ' +\n 'any case, with no name): the answer is the exchange whose factory, router or manager it is, ' +\n 'and took_for names the role it holds. When matched is null no exchange row holds the address: ' +\n 'send no read for it. A centralized exchange (Binance, OKX, Bitget) goes to meta_exchange_lookup instead. Give a name or an address, not both. ' +\n `${LEVEL_RULE} The first reads follow the lane: where it serves ROUTED_TO, the traders of a pool are its SWAPPED links and the route of a trader is ROUTED_TO. ` +\n 'There each pool carries swapped_usd (the USD sold into it on its SWAPPED links) and swap_count, in place of total_volume_usd and tx_total_count.'\nexport const META_DEX_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_DEX_LOOKUP_ARGS = ['network', 'name', 'address', 'pools'] as const\n\n/** The pools returned per exchange, and per factory read. */\nexport const POOLS_LIMIT = 10\n/** A batch holds at most 20 members; Head and the pool reads take their share. */\nconst CONTRACT_MEMBERS_MAX = 12\n\nexport interface ContractRow {\n address: string\n role: Role\n confirmed: boolean\n confirmed_by?: string\n}\n\n/** A pool on the graph of before: its address totals, as in 0.81.0. */\nexport interface RoutePoolRow {\n address: string\n labels: string[]\n total_volume_usd: number\n tx_total_count: number\n}\n\n/**\n * A pool on a lane with the levels. A pool has no address totals there: its\n * transactions are not on FLOWED_TO. Its numbers are the sums of its SWAPPED\n * links: `swapped_usd`, the USD sold into it, and `swap_count`, its swaps.\n */\nexport interface LevelsPoolRow {\n address: string\n labels: string[]\n swapped_usd: number\n swap_count: number\n}\n\nexport type PoolRow = RoutePoolRow | LevelsPoolRow\n\nexport interface FamilyLag {\n behind_money: number | null\n behind_dex: number | null\n behind_transfers: number | null\n}\n\nexport interface DexMatch {\n dex: string\n display: string\n trail_type: TrailType\n /** The skill a host with skills loads next. */\n skill: string\n factories: ContractRow[]\n routers: ContractRow[]\n manager: ContractRow | null\n pools: PoolRow[]\n recipe: RecipeStep[]\n}\n\nexport interface CoveredExchange {\n dex: string\n display: string\n trail_type: TrailType\n factories: string[]\n routers: string[]\n}\n\nexport interface MetaDexLookupResult {\n schema: typeof META_DEX_LOOKUP_SCHEMA\n network: string\n registry_version: number\n registry_source: RegistrySource\n matched: DexMatch | null\n /** A near name hit: the name as typed. An address hit: the role it holds and the verification cell. */\n took_for?: string\n candidates: DexCandidate[]\n covered: string[]\n /** With no name: every covered exchange, with its key, trail type and contracts. */\n exchanges?: CoveredExchange[]\n families: FamilyLag | null\n /** `levels` on a lane whose money family lists ROUTED_TO; absent on the graph of before. */\n swap_links?: 'levels'\n /** What a read could not do: a lane that is not reachable, a member that was refused. */\n notes?: string[]\n hint: string\n}\n\n/** The batch reply as the remote client returns it. */\nexport type BatchAnswer = {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n}\n\nexport interface DexToolDependencies {\n loadRegistry: (network: string) => Promise<LoadedRegistry>\n /** One graph_query_batch through the proxy's remote client, billed as any read. */\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<BatchAnswer>\n /** The reason no read can be sent now, or undefined when the graph is reachable. */\n unavailable?: () => Promise<string | undefined> | string | undefined\n /** The text of a call that threw: payment required, transport. */\n describeFailure: (err: unknown) => string\n /**\n * The shape of the lane's swap links, read from meta_network_capabilities.\n * Absent, or a read that fails, means the graph of before (`route`).\n */\n linkShape?: (network: string) => Promise<SwapLinkShape> | SwapLinkShape\n}\n\nexport type MetaDexLookupToolResult = {\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): MetaDexLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\ntype Member = { id?: unknown; ok?: unknown; results?: unknown; error?: unknown }\n\nfunction membersOf(answer: BatchAnswer): Map<string, Member> {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const queries = isRecord(facts) ? facts.queries : undefined\n const members = new Map<string, Member>()\n if (Array.isArray(queries)) {\n for (const member of queries)\n if (isRecord(member) && typeof member.id === 'string') members.set(member.id, member)\n }\n return members\n}\n\nconst rowsOf = (member: Member | undefined): Array<Record<string, unknown>> =>\n member?.ok === true && Array.isArray(member.results) ? member.results.filter(isRecord) : []\n\nconst numberOrNull = (value: unknown): number | null => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)))\n return Number(value)\n return null\n}\n\nconst stringList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n\n/** A column of a row, read under its alias or as the query wrote it (h.behind_dex). */\nfunction column(row: Record<string, unknown>, name: string, variable: string): unknown {\n return name in row ? row[name] : row[`${variable}.${name}`]\n}\n\nexport const HEAD_QUERY =\n 'USE chain MATCH (h:Head) RETURN h.behind_money, h.behind_dex, h.behind_transfers'\n\nexport function contractQuery(address: string): string {\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"}) ` +\n 'RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT 1'\n )\n}\n\nexport function contractListQuery(addresses: string[]): string {\n return (\n `USE topology MATCH (a:Address) WHERE a.address IN [${addresses.map((a) => `\"${a}\"`).join(', ')}] ` +\n `RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT ${addresses.length}`\n )\n}\n\n/** The anchored reads of one exchange: Head, each contract, and the pools of each factory. */\nexport function lookupQueries(\n entry: DexEntry,\n pools: boolean,\n shape: SwapLinkShape = 'route'\n): Array<{ id: string; query: string }> {\n const contracts = Object.keys(entry.roles)\n const queries: Array<{ id: string; query: string }> = [{ id: 'head', query: HEAD_QUERY }]\n if (contracts.length <= CONTRACT_MEMBERS_MAX) {\n for (const address of contracts)\n queries.push({ id: `contract:${address}`, query: contractQuery(address) })\n } else {\n queries.push({ id: 'contracts', query: contractListQuery(contracts) })\n }\n if (pools) {\n for (const factory of entry.factories.filter((address) => entry.roles[address] === 'factory')) {\n queries.push({ id: `pools:${factory}`, query: poolsByFactoryQuery(factory, POOLS_LIMIT, shape) })\n }\n }\n return queries\n}\n\nfunction confirmation(\n row: Record<string, unknown> | undefined\n): Pick<ContractRow, 'confirmed' | 'confirmed_by'> {\n if (!row) return { confirmed: false }\n if (row.is_contract === true) return { confirmed: true, confirmed_by: 'is_contract' }\n if (stringList(row.node_labels).includes('Contract'))\n return { confirmed: true, confirmed_by: ':Contract' }\n return { confirmed: false }\n}\n\n/** The pools of the batch, merged over the factories and ranked by the shape's number. */\nfunction readPools(members: Map<string, Member>, shape: SwapLinkShape): PoolRow[] {\n const byAddress = new Map<string, { row: PoolRow; rank: number }>()\n for (const [id, member] of members) {\n if (!id.startsWith('pools:')) continue\n for (const row of rowsOf(member)) {\n const address = typeof row.to_address === 'string' ? row.to_address : null\n const rank = numberOrNull(shape === 'levels' ? row.swapped_usd : row.total_volume_usd)\n if (!address || rank === null || byAddress.has(address)) continue\n const labels = stringList(row.to_labels)\n byAddress.set(address, {\n rank,\n row:\n shape === 'levels'\n ? { address, labels, swapped_usd: rank, swap_count: numberOrNull(row.swap_count) ?? 0 }\n : {\n address,\n labels,\n total_volume_usd: rank,\n tx_total_count: numberOrNull(row.tx_total_count) ?? 0,\n },\n })\n }\n }\n return [...byAddress.values()]\n .sort((a, b) => b.rank - a.rank)\n .slice(0, POOLS_LIMIT)\n .map(({ row }) => row)\n}\n\nfunction readMatch(\n entry: DexEntry,\n members: Map<string, Member>,\n read: boolean,\n shape: SwapLinkShape\n): {\n contracts: Map<string, ContractRow>\n pools: PoolRow[]\n families: FamilyLag | null\n notes: string[]\n} {\n const notes: string[] = []\n const contracts = new Map<string, ContractRow>()\n const listed = new Map(rowsOf(members.get('contracts')).map((row) => [String(row.address), row]))\n for (const [address, role] of Object.entries(entry.roles)) {\n const row = members.has(`contract:${address}`)\n ? rowsOf(members.get(`contract:${address}`))[0]\n : listed.get(address)\n contracts.set(address, { address, role, ...confirmation(row) })\n }\n const pools = readPools(members, shape)\n const head = rowsOf(members.get('head'))[0]\n const families: FamilyLag | null = head\n ? {\n behind_money: numberOrNull(column(head, 'behind_money', 'h')),\n behind_dex: numberOrNull(column(head, 'behind_dex', 'h')),\n behind_transfers: numberOrNull(column(head, 'behind_transfers', 'h')),\n }\n : null\n if (read) {\n for (const [id, member] of members) {\n if (member.ok !== true)\n notes.push(\n `${id}: ${typeof member.error === 'string' ? member.error : 'the read was not served'}`\n )\n }\n }\n return { contracts, pools, families, notes }\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\n\n/** The hint's last rule on a lane with the levels; the graph of before keeps its 0.81.0 text. */\nconst LEVELS_HINT =\n `${LEVEL_RULE} Each pool carries swapped_usd, the USD sold into it on its SWAPPED links, and swap_count, its swaps: say \"tokens worth about N USD sold into the pool\", never its lifetime volume. ` +\n 'Read families before a whole-chain SWAPPED search: it is sent when behind_dex is at most 100000, and a ROUTED_TO search when behind_money is. Never ask the user for an address.'\nconst ROUTE_HINT =\n 'Read families before a SWAPPED search: it is sent when behind_dex is at most 100000. Never ask the user for an address.'\n\nfunction hintFor(\n result: Omit<MetaDexLookupResult, 'hint'>,\n name: string | null,\n address: string | null = null\n): string {\n const closing = result.swap_links === 'levels' ? LEVELS_HINT : ROUTE_HINT\n if (address !== null && !result.matched) {\n return `${ANSWER_HINT} No exchange row holds ${address}: it is not a registered exchange contract. Send no exchange read for it; read the graph for what the address did.`\n }\n if (address !== null && result.matched) {\n const { matched } = result\n return (\n `${ANSWER_HINT} Say in one line: \"${address} is a ${result.took_for} row of ${matched.display}.\" Ask nothing. ` +\n `Exchange ${matched.display}, trail ${matched.trail_type}: send the first reads of recipe, ` +\n `anchored on the addresses above, and load ${matched.skill} when this host has skills. ` +\n closing\n )\n }\n if (name === null) {\n return `${ANSWER_HINT} These are the exchanges the registry covers. Call meta_dex_lookup with a name for its addresses and first reads.`\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 return (\n `${ANSWER_HINT} ${took}Exchange ${matched.display}, trail ${matched.trail_type}: send the first reads of recipe, ` +\n `anchored on the addresses above, and load ${matched.skill} when this host has skills. ` +\n closing\n )\n }\n if (result.candidates.length > 0) {\n const names = result.candidates\n .map((candidate) => `${candidate.display} (${candidate.dex})`)\n .join(', ')\n return `${ANSWER_HINT} ${result.candidates.length} rows fit \"${name}\": ${names}. Name both or pick one: call meta_dex_lookup with each key. Never guess one, never ask the user for an address.`\n }\n return `${ANSWER_HINT} ${name} is not covered. Send no query for the name: say so in one line and list the covered exchanges by name.`\n}\n\nfunction textResult(structured: MetaDexLookupResult): MetaDexLookupToolResult {\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\n/** meta_dex_lookup, {network, name?, address?, pools?}. Every argument is checked before the registry is read. */\nexport async function handleMetaDexLookup(\n args: unknown,\n deps: DexToolDependencies\n): Promise<MetaDexLookupToolResult> {\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 const rawPools = record.pools\n if (rawPools !== undefined && rawPools !== null && typeof rawPools !== 'boolean') {\n return errorResult('invalid_pools: pools must be true or false')\n }\n const pools = rawPools !== false\n\n let loaded: LoadedRegistry\n try {\n loaded = await deps.loadRegistry(network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError\n ? err.message\n : `exchange registry unavailable: ${(err as Error).message}`\n )\n }\n const { document } = loaded\n const base = {\n schema: META_DEX_LOOKUP_SCHEMA,\n network,\n registry_version: document.registry_version,\n registry_source: loaded.source,\n }\n\n if (name === null && address === null) {\n const result = {\n ...base,\n matched: null,\n candidates: [],\n covered: document.rows.map((row) => row.display),\n exchanges: document.rows.map((row) => ({\n dex: row.dex,\n display: row.display,\n trail_type: row.trail_type,\n factories: row.factories,\n routers: row.routers,\n })),\n families: null,\n }\n return textResult({ ...result, hint: hintFor(result, null) })\n }\n\n let match: DexMatchResult\n if (address !== null) {\n const holder = dexOfAddress(address, document.rows)\n match = {\n matched: holder ?? null,\n ...(holder ? { took_for: `${holder.roles[address] ?? 'helper'}, served` } : {}),\n candidates: [],\n covered: document.rows.map((row) => row.display),\n }\n } else {\n match = matchDex(name as string, document.rows)\n }\n if (!match.matched) {\n const result = {\n ...base,\n matched: null,\n candidates: match.candidates,\n covered: match.covered,\n families: null,\n }\n return textResult({ ...result, hint: hintFor(result, name, address) })\n }\n\n const entry = match.matched\n const unavailable = await deps.unavailable?.()\n // The shape is read first: the pool read of the batch follows it.\n let shape: SwapLinkShape = 'route'\n if (!unavailable && deps.linkShape) {\n try {\n shape = await deps.linkShape(network)\n } catch {\n shape = 'route'\n }\n }\n const queries = lookupQueries(entry, pools, shape)\n let members = new Map<string, Member>()\n const notes: string[] = []\n if (unavailable) {\n notes.push(\n `No graph read was sent: ${unavailable} The contracts are the reviewed registry rows, not yet confirmed on the graph.`\n )\n } else {\n try {\n const answer = await deps.graphQueryBatch({ network, queries })\n members = membersOf(answer)\n if (answer.isError === true && members.size === 0) {\n const first = Array.isArray(answer.content) ? answer.content[0] : undefined\n notes.push(\n `The graph refused the reads: ${isRecord(first) && typeof first.text === 'string' ? first.text : 'no reason given'}`\n )\n }\n } catch (err) {\n notes.push(`The graph reads failed: ${deps.describeFailure(err)}`)\n }\n }\n const read = readMatch(entry, members, members.size > 0, shape)\n notes.push(...read.notes)\n const contractsOf = (role: Role): ContractRow[] =>\n [...read.contracts.values()].filter((contract) => contract.role === role)\n const topPool = read.pools[0]?.address ?? null\n const matched: DexMatch = {\n dex: entry.dex,\n display: entry.display,\n trail_type: entry.trail_type,\n skill: TRAIL_SKILLS[entry.trail_type],\n factories: contractsOf('factory'),\n routers: contractsOf('router'),\n manager: contractsOf('manager')[0] ?? null,\n pools: read.pools,\n recipe: recipeFor(entry, topPool, shape),\n }\n const result = {\n ...base,\n matched,\n ...(match.took_for ? { took_for: match.took_for } : {}),\n candidates: [],\n covered: match.covered,\n families: read.families,\n ...(shape === 'levels' ? { swap_links: 'levels' as const } : {}),\n ...(notes.length > 0 ? { notes } : {}),\n }\n return textResult({ ...result, hint: hintFor(result, name, address) })\n}\n"],"mappings":";;;;;;AA8BA,MAAa,eAA0C;CACrD,OAAO;CACP,OAAO;CACP,OAAO;CACP,WAAW;AACb;AAEA,MAAM,SAAS;AACf,MAAM,MAAM;AACZ,MAAM,KAAK;AACX,MAAM,QAAQ;;;;;;;AAQd,SAAgB,oBACd,SACA,QAAQ,IACR,QAAuB,SACf;CACR,IAAI,UAAU,UACZ,OACE,4CAA4C,QAAQ,0PAGjB;CAGvC,OACE,4CAA4C,QAAQ,8QAEV;AAE9C;;AAGA,SAAS,qBAAqB,MAAsB;CAClD,OACE,uEAAuE,KAAK;AAIhF;;AAGA,SAAS,yBAAyB,UAA0B;CAC1D,OACE,sEAAsE,SAAS;AAInF;;AAGA,SAAS,mBAA2B;CAClC,OACE,4CAA4C,OAAO;AAIvD;;AAGA,SAAS,cAAc,WAA2B;CAChD,OACE,yCAAyC,OAAO,sCAAsC,U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,MAAM,KACJ,gCAAgC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,mBACnG;EACF;CACF,SAAS,KAAK;EACZ,MAAM,KAAK,2BAA2B,KAAK,gBAAgB,GAAG,GAAG;CACnE;CAEF,MAAM,OAAO,UAAU,OAAO,SAAS,QAAQ,OAAO,GAAG,KAAK;CAC9D,MAAM,KAAK,GAAG,KAAK,KAAK;CACxB,MAAM,eAAe,SACnB,CAAC,GAAG,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC,QAAQ,aAAa,SAAS,SAAS,IAAI;CAC1E,MAAM,UAAU,KAAK,MAAM,EAAE,EAAE,WAAW;CAC1C,MAAM,UAAoB;EACxB,KAAK,MAAM;EACX,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,OAAO,aAAa,MAAM;EAC1B,WAAW,YAAY,SAAS;EAChC,SAAS,YAAY,QAAQ;EAC7B,SAAS,YAAY,SAAS,CAAC,CAAC,MAAM;EACtC,OAAO,KAAK;EACZ,QAAQ,UAAU,OAAO,SAAS,KAAK;CACzC;CACA,MAAM,SAAS;EACb,GAAG;EACH;EACA,GAAI,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;EACrD,YAAY,CAAC;EACb,SAAS,MAAM;EACf,UAAU,KAAK;EACf,GAAI,UAAU,WAAW,EAAE,YAAY,SAAkB,IAAI,CAAC;EAC9D,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;CACtC;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,MAAM,OAAO;CAAE,CAAC;AACvE"}
@@ -1,7 +1,7 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  const require_answer_hint = require("./answer-hint-BlYEBq_Y.cjs");
3
- const require_layer_routing = require("./layer-routing-YDj-ynG9.cjs");
4
- const require_dex_registry = require("./dex-registry-BhGJUG9_.cjs");
3
+ const require_layer_routing = require("./layer-routing-j48SQ8Wk.cjs");
4
+ const require_dex_registry = require("./dex-registry-CyR3GyRr.cjs");
5
5
  // src/mcp/dex-recipes.ts
6
6
  /** The trail-type skill of each trail, for hosts that load skills. */
7
7
  const TRAIL_SKILLS = {
@@ -541,7 +541,7 @@ async function handleMetaDexLookup(args, deps) {
541
541
  }
542
542
  let match;
543
543
  if (address !== null) {
544
- const holder = document.rows.find((row) => address in row.roles || row.helpers?.includes(address));
544
+ const holder = require_dex_registry.dexOfAddress(address, document.rows);
545
545
  match = {
546
546
  matched: holder ?? null,
547
547
  ...holder ? { took_for: `${holder.roles[address] ?? "helper"}, served` } : {},