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,11 +1,11 @@
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");
4
- const require_exchange_registry = require("./exchange-registry-CT0rRW__.cjs");
5
- const require_exchange_tool = require("./exchange-tool-B2SMeC5f.cjs");
6
- const require_graph_schema = require("./graph-schema-CcrYPpSv.cjs");
3
+ const require_dex_registry = require("./dex-registry-CyR3GyRr.cjs");
4
+ const require_exchange_registry = require("./exchange-registry-CEgkeQV1.cjs");
5
+ const require_exchange_tool = require("./exchange-tool-CXaUBAd2.cjs");
6
+ const require_graph_schema = require("./graph-schema-Bn3txQCj.cjs");
7
7
  const require_print_result = require("./print-result-BYppJlUi.cjs");
8
- const require_token_lookup = require("./token-lookup-DqjSRIxd.cjs");
8
+ const require_token_lookup = require("./token-lookup-DLe4erP9.cjs");
9
9
  // src/mcp/exchange-deposit-check.ts
10
10
  /**
11
11
  * aml_exchange_deposit_check: is this address an exchange deposit, of which
@@ -14,7 +14,7 @@ const require_token_lookup = require("./token-lookup-DqjSRIxd.cjs");
14
14
  * A local tool of the proxy. It sends one graph_query_batch with six reads on
15
15
  * USE topology, all anchored on the address:
16
16
  *
17
- * node the address: its node labels, its label words and `cex_role`;
17
+ * node the address: its node labels, its label words and `exchange_role`;
18
18
  * swept its `SWEPT` links: each hot wallet it swept into, with the sweep
19
19
  * count, the USD sum, the paths and the first and last sweep;
20
20
  * paid_by how many addresses paid it, and how many of them are exchange
@@ -29,7 +29,7 @@ const require_token_lookup = require("./token-lookup-DqjSRIxd.cjs");
29
29
  * A behaviour read that fails leaves its counts null; the check still answers.
30
30
  *
31
31
  * `SWEPT` (layer `cex_sweeps`) is drawn only from an address the deposit rule
32
- * judged a deposit, and `cex_role` comes from the exchange label's subtype. The
32
+ * judged a deposit, and `exchange_role` comes from the exchange label's subtype. The
33
33
  * graph judges, this tool only reads.
34
34
  *
35
35
  * The exchange model's own guess rides beside them on the node (graph sync
@@ -52,7 +52,7 @@ const AML_EXCHANGE_DEPOSIT_CHECK_TITLE = "Exchange deposit check";
52
52
  */
53
53
  /** How a deposit address behaves: the answer to "what makes an address a deposit address". Every result carries it as deposit_profile. */
54
54
  const EXCHANGE_DEPOSIT_BEHAVIOUR = "A deposit address is one customer's: everything it sends goes to the wallets of one exchange (a sweep into a hot wallet), few outside addresses ever pay it, it never swaps on a DEX, and it is no token, pool, router or smart account.";
55
- const AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION = `Checks one address: is it a deposit address of a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...), of which exchange, and into which hot wallet was it swept, how many times, by which path and when. It reads the SWEPT links of the address and its cex_role (deposit, hot_wallet, cold_wallet or withdrawal) on the graph, and its behaviour as counts (how many addresses paid it, how many it paid, how many of each are exchange wallets, the DEX pools it swapped on, the spenders it approved), anchored on the address: six reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, when the user asks where money entered an exchange, or when someone says an address is an exchange deposit: a claim is never proof, the answer of this tool is. ${`${EXCHANGE_DEPOSIT_BEHAVIOUR} The graph judges that, never you: the verdict is is_deposit, cex_role and swept. Give behaviour and does_not_fit_deposit as the facts behind it, and never set a threshold of your own for payers, volume or sweeps. With no deposit mark an address is not shown to be a deposit, whoever says it is one; with found false it has no activity on the network, and the claim is unproven there.`} An answer with inferred: true is the exchange model's prediction, not a listed source: report the address as inferred by the model, with its version (inferred_model), never as a confirmed exchange address. ${require_exchange_tool.EXCHANGE_OPENING_RULE}`;
55
+ const AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION = `Checks one address: is it a deposit address of a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...), of which exchange, and into which hot wallet was it swept, how many times, by which path and when. It reads the SWEPT links of the address and its exchange_role (deposit, hot_wallet, cold_wallet or withdrawal) on the graph, and its behaviour as counts (how many addresses paid it, how many it paid, how many of each are exchange wallets, the DEX pools it swapped on, the spenders it approved), anchored on the address: six reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, when the user asks where money entered an exchange, or when someone says an address is an exchange deposit: a claim is never proof, the answer of this tool is. ${`${EXCHANGE_DEPOSIT_BEHAVIOUR} The graph judges that, never you: the verdict is is_deposit, exchange_role and swept. Give behaviour and does_not_fit_deposit as the facts behind it, and never set a threshold of your own for payers, volume or sweeps. With no deposit mark an address is not shown to be a deposit, whoever says it is one; with found false it has no activity on the network, and the claim is unproven there.`} An answer with inferred: true is the exchange model's prediction, not a listed source: report the address as inferred by the model, with its version (inferred_model), never as a confirmed exchange address. ${require_exchange_tool.EXCHANGE_OPENING_RULE}`;
56
56
  const AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS = {
57
57
  readOnlyHint: true,
58
58
  idempotentHint: true,
@@ -81,15 +81,15 @@ const ADDRESS_READ = /^0x[0-9a-f]{40}$/;
81
81
  function assertReadAddress(address) {
82
82
  if (!ADDRESS_READ.test(address)) throw new Error(`exchange deposit check: ${JSON.stringify(address)} is not a lowercase 0x address`);
83
83
  }
84
- /** The node read: the address, its marks, its cex_role and the exchange model's inferred role. */
84
+ /** The node read: the address, its marks, its exchange_role and the exchange model's inferred role. */
85
85
  function depositNodeQuery(address) {
86
86
  assertReadAddress(address);
87
- return `USE topology MATCH (a:Address {address: "${address}"}) RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.cex_role AS cex_role, a.inferred_exchange_role AS inferred_exchange_role, a.inferred_sources AS inferred_sources, a.inferred_exchange_role_updated_timestamp AS inferred_exchange_role_updated_timestamp LIMIT 1`;
87
+ return `USE topology MATCH (a:Address {address: "${address}"}) RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, ${require_graph_schema.exchangeRoleRead("a")} AS exchange_role, a.inferred_exchange_role AS inferred_exchange_role, a.inferred_sources AS inferred_sources, a.inferred_exchange_role_updated_timestamp AS inferred_exchange_role_updated_timestamp LIMIT 1`;
88
88
  }
89
89
  /** The swept read: each hot wallet the address swept into. */
90
90
  function depositSweptQuery(address) {
91
91
  assertReadAddress(address);
92
- return `USE topology MATCH (a:Address {address: "${address}"})-[s:SWEPT]->(h:Address) RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, h.cex_role AS hot_wallet_role, s.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths, s.first_seen_timestamp AS first_seen_timestamp, s.last_seen_timestamp AS last_seen_timestamp LIMIT ${SWEPT_LIMIT}`;
92
+ return `USE topology MATCH (a:Address {address: "${address}"})-[s:SWEPT]->(h:Address) RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, ${require_graph_schema.exchangeRoleRead("h")} AS hot_wallet_role, s.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths, s.first_seen_timestamp AS first_seen_timestamp, s.last_seen_timestamp AS last_seen_timestamp LIMIT ${SWEPT_LIMIT}`;
93
93
  }
94
94
  /** The behaviour reads: one count row each, over at most BEHAVIOUR_COUNT_CAP links. */
95
95
  function depositBehaviourQueries(address) {
@@ -141,9 +141,9 @@ const numberOrNull = (value) => {
141
141
  const textOrNull = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
142
142
  const addressOrNull = (value) => typeof value === "string" && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null;
143
143
  const utcOrNull = (ms) => require_print_result.isEpochMs(ms) ? require_print_result.utcText(ms) : null;
144
- function cexRoleOf(value) {
144
+ function exchangeRoleOf(value) {
145
145
  const role = textOrNull(value)?.toLowerCase();
146
- return require_graph_schema.CEX_ROLES.includes(role ?? "") ? role : null;
146
+ return require_graph_schema.EXCHANGE_ROLES.includes(role ?? "") ? role : null;
147
147
  }
148
148
  /**
149
149
  * The exchange model's mark of a node row, or null. It needs both the role and
@@ -263,7 +263,7 @@ function depositCheckFromMembers(network, address, members, rows) {
263
263
  }
264
264
  sweeps.sort((a, b) => (b.sweep_count ?? 0) - (a.sweep_count ?? 0));
265
265
  exchange ??= require_exchange_registry.exchangeOfLabels(labels, rows) ?? require_exchange_registry.exchangeOfWallet(address, rows)?.entry ?? null;
266
- const role = cexRoleOf(nodeRow?.cex_role);
266
+ const role = exchangeRoleOf(nodeRow?.exchange_role);
267
267
  const found = nodeRow !== void 0 || sweeps.length > 0;
268
268
  const isDeposit = role === "deposit" || sweeps.length > 0;
269
269
  const behaviour = behaviourFromMembers(members);
@@ -275,7 +275,7 @@ function depositCheckFromMembers(network, address, members, rows) {
275
275
  address,
276
276
  found,
277
277
  is_deposit: isDeposit,
278
- cex_role: role ?? (sweeps.length > 0 ? "deposit" : null),
278
+ exchange_role: role ?? (sweeps.length > 0 ? "deposit" : null),
279
279
  exchange: exchange?.exchange ?? null,
280
280
  exchange_display: exchange?.display ?? null,
281
281
  labels,
@@ -313,9 +313,9 @@ function hintFor(result) {
313
313
  return `${require_answer_hint.ANSWER_HINT} Say: "${address} is a deposit address of ${name} on ${network}."${into} This is where the money entered the exchange: the exchange can name the customer behind the deposit. ${behaviourHint(result)}${require_exchange_tool.EXCHANGE_OPENING_RULE}`;
314
314
  }
315
315
  if (result.inferred && result.inferred_role && result.inferred_model) return inferredHint(result, result.inferred_role, result.inferred_model);
316
- if (result.cex_role) return `${require_answer_hint.ANSWER_HINT} Say: "${address} is a ${result.cex_role.replace("_", " ")} of ${name} on ${network}, not a deposit address." A trail that reaches it has entered the exchange: end the trail there.`;
316
+ if (result.exchange_role) return `${require_answer_hint.ANSWER_HINT} Say: "${address} is a ${result.exchange_role.replace("_", " ")} of ${name} on ${network}, not a deposit address." A trail that reaches it has entered the exchange: end the trail there.`;
317
317
  const misfit = result.does_not_fit_deposit.length > 0 ? `What a deposit address does not do, and this one did: ${result.does_not_fit_deposit.join("; ")}. ` : "Its counts alone rule nothing out; the missing mark does: the rule of the graph did not judge it a deposit. ";
318
- return `${require_answer_hint.ANSWER_HINT} ${address} carries no deposit mark: no SWEPT link and no cex_role. Say that the graph shows no sweep of it into a listed exchange hot wallet. That is not proof the address belongs to no exchange; its labels and its links say what else it is. ${behaviourHint(result)}${misfit}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
318
+ return `${require_answer_hint.ANSWER_HINT} ${address} carries no deposit mark: no SWEPT link and no exchange_role. Say that the graph shows no sweep of it into a listed exchange hot wallet. That is not proof the address belongs to no exchange; its labels and its links say what else it is. ${behaviourHint(result)}${misfit}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
319
319
  }
320
320
  /** Why the model holds its guess, in reader words. */
321
321
  const INFERRED_BASIS_TEXT = {
@@ -328,7 +328,7 @@ function inferredHint(result, role, model) {
328
328
  const { address, network } = result;
329
329
  const what = role === "deposit" ? "an exchange deposit" : "an exchange hot wallet";
330
330
  const basis = result.inferred_basis ? `${INFERRED_BASIS_TEXT[result.inferred_basis]} ` : "";
331
- return `${require_answer_hint.ANSWER_HINT} Say: "${address} is ${what}, inferred by model ${model}, on ${network}. No listed source names it as an exchange address." ${basis}${role === "deposit" ? "The graph draws no SWEPT link for it, so no hot wallet is named: name none yourself. " : "A trail that reaches it may have entered an exchange there: say so as inferred, and name no exchange the answer does not name. "}Report it as inferred, never as a confirmed exchange address: is_deposit (false) and cex_role (null) are the sourced verdict, and the guess does not change them. ${behaviourHint(result)}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
331
+ return `${require_answer_hint.ANSWER_HINT} Say: "${address} is ${what}, inferred by model ${model}, on ${network}. No listed source names it as an exchange address." ${basis}${role === "deposit" ? "The graph draws no SWEPT link for it, so no hot wallet is named: name none yourself. " : "A trail that reaches it may have entered an exchange there: say so as inferred, and name no exchange the answer does not name. "}Report it as inferred, never as a confirmed exchange address: is_deposit (false) and exchange_role (null) are the sourced verdict, and the guess does not change them. ${behaviourHint(result)}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
332
332
  }
333
333
  /** "Its behaviour: ... . " for a hint, or "" when no count was read. */
334
334
  function behaviourHint(result) {
@@ -1,11 +1,11 @@
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 { d as normalizeDexNetwork, r as DexRegistryError } from "./dex-registry-BY67f4Ul.mjs";
4
- import { n as exchangeOfWallet, t as exchangeOfLabels } from "./exchange-registry-CoLgHw6d.mjs";
5
- import { t as EXCHANGE_OPENING_RULE } from "./exchange-tool-Dc46SJ49.mjs";
6
- import { t as CEX_ROLES } from "./graph-schema-CRQuKya1.mjs";
3
+ import { p as normalizeDexNetwork, r as DexRegistryError } from "./dex-registry-Bkri0--q.mjs";
4
+ import { n as exchangeOfWallet, t as exchangeOfLabels } from "./exchange-registry-Dr5UtcT5.mjs";
5
+ import { t as EXCHANGE_OPENING_RULE } from "./exchange-tool-B7E29YoQ.mjs";
6
+ import { a as exchangeRoleRead, t as EXCHANGE_ROLES } from "./graph-schema-DvABR1yl.mjs";
7
7
  import { i as isEpochMs, o as utcText } from "./print-result-IFARsMnL.mjs";
8
- import { c as refusalOf, s as membersOf } from "./token-lookup-Cf59VdGe.mjs";
8
+ import { c as refusalOf, s as membersOf } from "./token-lookup-Ck0q7crJ.mjs";
9
9
  // src/mcp/exchange-deposit-check.ts
10
10
  /**
11
11
  * aml_exchange_deposit_check: is this address an exchange deposit, of which
@@ -14,7 +14,7 @@ import { c as refusalOf, s as membersOf } from "./token-lookup-Cf59VdGe.mjs";
14
14
  * A local tool of the proxy. It sends one graph_query_batch with six reads on
15
15
  * USE topology, all anchored on the address:
16
16
  *
17
- * node the address: its node labels, its label words and `cex_role`;
17
+ * node the address: its node labels, its label words and `exchange_role`;
18
18
  * swept its `SWEPT` links: each hot wallet it swept into, with the sweep
19
19
  * count, the USD sum, the paths and the first and last sweep;
20
20
  * paid_by how many addresses paid it, and how many of them are exchange
@@ -29,7 +29,7 @@ import { c as refusalOf, s as membersOf } from "./token-lookup-Cf59VdGe.mjs";
29
29
  * A behaviour read that fails leaves its counts null; the check still answers.
30
30
  *
31
31
  * `SWEPT` (layer `cex_sweeps`) is drawn only from an address the deposit rule
32
- * judged a deposit, and `cex_role` comes from the exchange label's subtype. The
32
+ * judged a deposit, and `exchange_role` comes from the exchange label's subtype. The
33
33
  * graph judges, this tool only reads.
34
34
  *
35
35
  * The exchange model's own guess rides beside them on the node (graph sync
@@ -52,7 +52,7 @@ const AML_EXCHANGE_DEPOSIT_CHECK_TITLE = "Exchange deposit check";
52
52
  */
53
53
  /** How a deposit address behaves: the answer to "what makes an address a deposit address". Every result carries it as deposit_profile. */
54
54
  const EXCHANGE_DEPOSIT_BEHAVIOUR = "A deposit address is one customer's: everything it sends goes to the wallets of one exchange (a sweep into a hot wallet), few outside addresses ever pay it, it never swaps on a DEX, and it is no token, pool, router or smart account.";
55
- const AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION = `Checks one address: is it a deposit address of a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...), of which exchange, and into which hot wallet was it swept, how many times, by which path and when. It reads the SWEPT links of the address and its cex_role (deposit, hot_wallet, cold_wallet or withdrawal) on the graph, and its behaviour as counts (how many addresses paid it, how many it paid, how many of each are exchange wallets, the DEX pools it swapped on, the spenders it approved), anchored on the address: six reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, when the user asks where money entered an exchange, or when someone says an address is an exchange deposit: a claim is never proof, the answer of this tool is. ${`${EXCHANGE_DEPOSIT_BEHAVIOUR} The graph judges that, never you: the verdict is is_deposit, cex_role and swept. Give behaviour and does_not_fit_deposit as the facts behind it, and never set a threshold of your own for payers, volume or sweeps. With no deposit mark an address is not shown to be a deposit, whoever says it is one; with found false it has no activity on the network, and the claim is unproven there.`} An answer with inferred: true is the exchange model's prediction, not a listed source: report the address as inferred by the model, with its version (inferred_model), never as a confirmed exchange address. ${EXCHANGE_OPENING_RULE}`;
55
+ const AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION = `Checks one address: is it a deposit address of a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...), of which exchange, and into which hot wallet was it swept, how many times, by which path and when. It reads the SWEPT links of the address and its exchange_role (deposit, hot_wallet, cold_wallet or withdrawal) on the graph, and its behaviour as counts (how many addresses paid it, how many it paid, how many of each are exchange wallets, the DEX pools it swapped on, the spenders it approved), anchored on the address: six reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, when the user asks where money entered an exchange, or when someone says an address is an exchange deposit: a claim is never proof, the answer of this tool is. ${`${EXCHANGE_DEPOSIT_BEHAVIOUR} The graph judges that, never you: the verdict is is_deposit, exchange_role and swept. Give behaviour and does_not_fit_deposit as the facts behind it, and never set a threshold of your own for payers, volume or sweeps. With no deposit mark an address is not shown to be a deposit, whoever says it is one; with found false it has no activity on the network, and the claim is unproven there.`} An answer with inferred: true is the exchange model's prediction, not a listed source: report the address as inferred by the model, with its version (inferred_model), never as a confirmed exchange address. ${EXCHANGE_OPENING_RULE}`;
56
56
  const AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS = {
57
57
  readOnlyHint: true,
58
58
  idempotentHint: true,
@@ -81,15 +81,15 @@ const ADDRESS_READ = /^0x[0-9a-f]{40}$/;
81
81
  function assertReadAddress(address) {
82
82
  if (!ADDRESS_READ.test(address)) throw new Error(`exchange deposit check: ${JSON.stringify(address)} is not a lowercase 0x address`);
83
83
  }
84
- /** The node read: the address, its marks, its cex_role and the exchange model's inferred role. */
84
+ /** The node read: the address, its marks, its exchange_role and the exchange model's inferred role. */
85
85
  function depositNodeQuery(address) {
86
86
  assertReadAddress(address);
87
- return `USE topology MATCH (a:Address {address: "${address}"}) RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.cex_role AS cex_role, a.inferred_exchange_role AS inferred_exchange_role, a.inferred_sources AS inferred_sources, a.inferred_exchange_role_updated_timestamp AS inferred_exchange_role_updated_timestamp LIMIT 1`;
87
+ return `USE topology MATCH (a:Address {address: "${address}"}) RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, ${exchangeRoleRead("a")} AS exchange_role, a.inferred_exchange_role AS inferred_exchange_role, a.inferred_sources AS inferred_sources, a.inferred_exchange_role_updated_timestamp AS inferred_exchange_role_updated_timestamp LIMIT 1`;
88
88
  }
89
89
  /** The swept read: each hot wallet the address swept into. */
90
90
  function depositSweptQuery(address) {
91
91
  assertReadAddress(address);
92
- return `USE topology MATCH (a:Address {address: "${address}"})-[s:SWEPT]->(h:Address) RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, h.cex_role AS hot_wallet_role, s.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths, s.first_seen_timestamp AS first_seen_timestamp, s.last_seen_timestamp AS last_seen_timestamp LIMIT ${SWEPT_LIMIT}`;
92
+ return `USE topology MATCH (a:Address {address: "${address}"})-[s:SWEPT]->(h:Address) RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, ${exchangeRoleRead("h")} AS hot_wallet_role, s.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths, s.first_seen_timestamp AS first_seen_timestamp, s.last_seen_timestamp AS last_seen_timestamp LIMIT ${SWEPT_LIMIT}`;
93
93
  }
94
94
  /** The behaviour reads: one count row each, over at most BEHAVIOUR_COUNT_CAP links. */
95
95
  function depositBehaviourQueries(address) {
@@ -141,9 +141,9 @@ const numberOrNull = (value) => {
141
141
  const textOrNull = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
142
142
  const addressOrNull = (value) => typeof value === "string" && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null;
143
143
  const utcOrNull = (ms) => isEpochMs(ms) ? utcText(ms) : null;
144
- function cexRoleOf(value) {
144
+ function exchangeRoleOf(value) {
145
145
  const role = textOrNull(value)?.toLowerCase();
146
- return CEX_ROLES.includes(role ?? "") ? role : null;
146
+ return EXCHANGE_ROLES.includes(role ?? "") ? role : null;
147
147
  }
148
148
  /**
149
149
  * The exchange model's mark of a node row, or null. It needs both the role and
@@ -263,7 +263,7 @@ function depositCheckFromMembers(network, address, members, rows) {
263
263
  }
264
264
  sweeps.sort((a, b) => (b.sweep_count ?? 0) - (a.sweep_count ?? 0));
265
265
  exchange ??= exchangeOfLabels(labels, rows) ?? exchangeOfWallet(address, rows)?.entry ?? null;
266
- const role = cexRoleOf(nodeRow?.cex_role);
266
+ const role = exchangeRoleOf(nodeRow?.exchange_role);
267
267
  const found = nodeRow !== void 0 || sweeps.length > 0;
268
268
  const isDeposit = role === "deposit" || sweeps.length > 0;
269
269
  const behaviour = behaviourFromMembers(members);
@@ -275,7 +275,7 @@ function depositCheckFromMembers(network, address, members, rows) {
275
275
  address,
276
276
  found,
277
277
  is_deposit: isDeposit,
278
- cex_role: role ?? (sweeps.length > 0 ? "deposit" : null),
278
+ exchange_role: role ?? (sweeps.length > 0 ? "deposit" : null),
279
279
  exchange: exchange?.exchange ?? null,
280
280
  exchange_display: exchange?.display ?? null,
281
281
  labels,
@@ -313,9 +313,9 @@ function hintFor(result) {
313
313
  return `${ANSWER_HINT} Say: "${address} is a deposit address of ${name} on ${network}."${into} This is where the money entered the exchange: the exchange can name the customer behind the deposit. ${behaviourHint(result)}${EXCHANGE_OPENING_RULE}`;
314
314
  }
315
315
  if (result.inferred && result.inferred_role && result.inferred_model) return inferredHint(result, result.inferred_role, result.inferred_model);
316
- if (result.cex_role) return `${ANSWER_HINT} Say: "${address} is a ${result.cex_role.replace("_", " ")} of ${name} on ${network}, not a deposit address." A trail that reaches it has entered the exchange: end the trail there.`;
316
+ if (result.exchange_role) return `${ANSWER_HINT} Say: "${address} is a ${result.exchange_role.replace("_", " ")} of ${name} on ${network}, not a deposit address." A trail that reaches it has entered the exchange: end the trail there.`;
317
317
  const misfit = result.does_not_fit_deposit.length > 0 ? `What a deposit address does not do, and this one did: ${result.does_not_fit_deposit.join("; ")}. ` : "Its counts alone rule nothing out; the missing mark does: the rule of the graph did not judge it a deposit. ";
318
- return `${ANSWER_HINT} ${address} carries no deposit mark: no SWEPT link and no cex_role. Say that the graph shows no sweep of it into a listed exchange hot wallet. That is not proof the address belongs to no exchange; its labels and its links say what else it is. ${behaviourHint(result)}${misfit}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
318
+ return `${ANSWER_HINT} ${address} carries no deposit mark: no SWEPT link and no exchange_role. Say that the graph shows no sweep of it into a listed exchange hot wallet. That is not proof the address belongs to no exchange; its labels and its links say what else it is. ${behaviourHint(result)}${misfit}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
319
319
  }
320
320
  /** Why the model holds its guess, in reader words. */
321
321
  const INFERRED_BASIS_TEXT = {
@@ -328,7 +328,7 @@ function inferredHint(result, role, model) {
328
328
  const { address, network } = result;
329
329
  const what = role === "deposit" ? "an exchange deposit" : "an exchange hot wallet";
330
330
  const basis = result.inferred_basis ? `${INFERRED_BASIS_TEXT[result.inferred_basis]} ` : "";
331
- return `${ANSWER_HINT} Say: "${address} is ${what}, inferred by model ${model}, on ${network}. No listed source names it as an exchange address." ${basis}${role === "deposit" ? "The graph draws no SWEPT link for it, so no hot wallet is named: name none yourself. " : "A trail that reaches it may have entered an exchange there: say so as inferred, and name no exchange the answer does not name. "}Report it as inferred, never as a confirmed exchange address: is_deposit (false) and cex_role (null) are the sourced verdict, and the guess does not change them. ${behaviourHint(result)}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
331
+ return `${ANSWER_HINT} Say: "${address} is ${what}, inferred by model ${model}, on ${network}. No listed source names it as an exchange address." ${basis}${role === "deposit" ? "The graph draws no SWEPT link for it, so no hot wallet is named: name none yourself. " : "A trail that reaches it may have entered an exchange there: say so as inferred, and name no exchange the answer does not name. "}Report it as inferred, never as a confirmed exchange address: is_deposit (false) and exchange_role (null) are the sourced verdict, and the guess does not change them. ${behaviourHint(result)}Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.`;
332
332
  }
333
333
  /** "Its behaviour: ... . " for a hint, or "" when no count was read. */
334
334
  function behaviourHint(result) {
@@ -389,4 +389,4 @@ async function handleAmlExchangeDepositCheck(args, deps) {
389
389
  }
390
390
  export { exchange_deposit_check_exports as a, AML_EXCHANGE_DEPOSIT_CHECK_TOOL as i, AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION as n, handleAmlExchangeDepositCheck as o, AML_EXCHANGE_DEPOSIT_CHECK_TITLE as r, AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS as t };
391
391
 
392
- //# sourceMappingURL=exchange-deposit-check-CXHZCHWW.mjs.map
392
+ //# sourceMappingURL=exchange-deposit-check-DIALj2sm.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exchange-deposit-check-DIALj2sm.mjs","names":[],"sources":["../src/mcp/exchange-deposit-check.ts"],"sourcesContent":["/**\n * aml_exchange_deposit_check: is this address an exchange deposit, of which\n * exchange, and into which hot wallet was it swept?\n *\n * A local tool of the proxy. It sends one graph_query_batch with six reads on\n * USE topology, all anchored on the address:\n *\n * node the address: its node labels, its label words and `exchange_role`;\n * swept its `SWEPT` links: each hot wallet it swept into, with the sweep\n * count, the USD sum, the paths and the first and last sweep;\n * paid_by how many addresses paid it, and how many of them are exchange\n * wallets;\n * paid how many addresses it paid, and how many of them are exchange\n * wallets;\n * swapped on how many DEX pools it swapped;\n * approved how many spenders it approved.\n *\n * The last four are the behaviour of the address, as counts: what a host needs\n * to say why an address does or does not look like a deposit, without a guess.\n * A behaviour read that fails leaves its counts null; the check still answers.\n *\n * `SWEPT` (layer `cex_sweeps`) is drawn only from an address the deposit rule\n * judged a deposit, and `exchange_role` comes from the exchange label's subtype. The\n * graph judges, this tool only reads.\n *\n * The exchange model's own guess rides beside them on the node (graph sync\n * layer `inferred`): `inferred_exchange_role`, an `ml:exchange-roles:<model>:\n * <basis>` entry in `inferred_sources`, and the time it was written. It is\n * never a label and never a SWEPT link. A sourced mark always wins; an\n * address with only the guess is answered as inferred, with the model, and\n * `is_deposit` stays false. The exchange is named from the lookup\n * file (src/mcp/exchange-registry.ts): the hot wallet it swept into, else a\n * label word.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport {\n exchangeOfLabels,\n exchangeOfWallet,\n type ExchangeEntry,\n type LoadedExchangeRegistry,\n} from './exchange-registry.js'\nimport { EXCHANGE_OPENING_RULE } from './exchange-tool.js'\nimport { EXCHANGE_ROLES, exchangeRoleRead } from './graph-schema.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\nimport { membersOf, refusalOf, type GraphAnswer, type Member } from './token-lookup.js'\n\nexport const AML_EXCHANGE_DEPOSIT_CHECK_TOOL = 'aml_exchange_deposit_check' as const\nexport const AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA =\n 'chain-insights.aml-exchange-deposit-check.v1' as const\nexport const AML_EXCHANGE_DEPOSIT_CHECK_TITLE = 'Exchange deposit check'\n/**\n * What the graph's deposit rule holds an address to, in the words every host\n * reads. The rule judges; a host that re-judges from payer counts or volume\n * invents a rule (\"a real deposit has many payers\") and gets the reason wrong.\n */\n/** How a deposit address behaves: the answer to \"what makes an address a deposit address\". Every result carries it as deposit_profile. */\nexport const EXCHANGE_DEPOSIT_BEHAVIOUR =\n \"A deposit address is one customer's: everything it sends goes to the wallets of one exchange (a sweep into a hot wallet), few outside addresses ever pay it, it never swaps on a DEX, and it is no token, pool, router or smart account.\"\n\nexport const EXCHANGE_DEPOSIT_PROFILE =\n `${EXCHANGE_DEPOSIT_BEHAVIOUR} ` +\n 'The graph judges that, never you: the verdict is is_deposit, exchange_role and swept. Give behaviour and does_not_fit_deposit as the facts behind it, and never set a threshold of your own for payers, volume or sweeps. ' +\n 'With no deposit mark an address is not shown to be a deposit, whoever says it is one; with found false it has no activity on the network, and the claim is unproven there.'\n\n/** The one rule for an inferred answer, in the description every host reads and in the skill. */\nexport const EXCHANGE_INFERRED_RULE =\n \"An answer with inferred: true is the exchange model's prediction, not a listed source: report the address as inferred by the model, with its version (inferred_model), never as a confirmed exchange address.\"\n\nexport const AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION =\n 'Checks one address: is it a deposit address of a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...), ' +\n 'of which exchange, and into which hot wallet was it swept, how many times, by which path and when. ' +\n 'It reads the SWEPT links of the address and its exchange_role (deposit, hot_wallet, cold_wallet or withdrawal) on the graph, and its behaviour as counts ' +\n '(how many addresses paid it, how many it paid, how many of each are exchange wallets, the DEX pools it swapped on, the spenders it approved), anchored on the address: ' +\n 'six reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, when the user asks where money entered an exchange, ' +\n 'or when someone says an address is an exchange deposit: a claim is never proof, the answer of this tool is. ' +\n `${EXCHANGE_DEPOSIT_PROFILE} ${EXCHANGE_INFERRED_RULE} ${EXCHANGE_OPENING_RULE}`\nexport const AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_EXCHANGE_DEPOSIT_CHECK_ARGS = ['network', 'address'] as const\n\n/** The most hot wallets one deposit's read returns. */\nexport const SWEPT_LIMIT = 20\n\nexport type ExchangeRole = (typeof EXCHANGE_ROLES)[number]\n\n/** The roles the exchange model infers. */\nexport const INFERRED_EXCHANGE_ROLES = ['deposit', 'hot_wallet'] as const\nexport type InferredExchangeRole = (typeof INFERRED_EXCHANGE_ROLES)[number]\n\n/**\n * Why the model inferred the role, from the suffix of its source entry:\n * `rule` a deposit behind a listed hot wallet, `rule-p` a deposit behind a hot\n * wallet the model inferred, `p-hub` a hot wallet the model inferred.\n */\nexport const INFERRED_BASIS = {\n rule: 'listed_hot_wallet',\n 'rule-p': 'predicted_hot_wallet',\n 'p-hub': 'predicted',\n} as const\nexport type InferredBasis = (typeof INFERRED_BASIS)[keyof typeof INFERRED_BASIS]\n\n/** The prefix of the exchange model's entries in `inferred_sources`. */\nexport const EXCHANGE_MODEL_SOURCE_PREFIX = 'ml:exchange-roles:'\n\nexport interface InferredExchangeMark {\n role: InferredExchangeRole\n model: string\n basis: InferredBasis\n /** ISO time the graph wrote the guess, or null when it carries none. */\n at: string | null\n}\n\nexport interface Sweep {\n hot_wallet: string\n /** The exchange the hot wallet is listed for, or null when the lookup lists it for none. */\n hot_wallet_exchange: string | null\n hot_wallet_role: string | null\n sweep_count: number | null\n amount_usd_sum: number | null\n paths: string[]\n first_seen: number | null\n first_seen_utc: string | null\n last_seen: number | null\n last_seen_utc: string | null\n}\n\n/** The most links one behaviour read counts: a count equal to it means \"this many or more\". */\nexport const BEHAVIOUR_COUNT_CAP = 5000\n\n/**\n * How the address behaves, as counts of its links. A null count is a read that\n * did not answer. The counts take every link, also a dust one: the graph's\n * deposit rule, which ignores dust, is the judge, and these are its evidence.\n */\nexport interface DepositBehaviour {\n /** Addresses that ever paid it. */\n payers: number | null\n /** Of those, exchange wallets (a hot wallet, or another deposit). */\n payers_exchange: number | null\n /** Addresses it ever paid. */\n receivers: number | null\n /** Of those, exchange wallets. */\n receivers_exchange: number | null\n /** DEX pools it swapped on. */\n dex_pools: number | null\n /** Spenders it approved. */\n approvals: number | null\n /** A count equal to this means \"this many or more\". */\n count_cap: typeof BEHAVIOUR_COUNT_CAP\n}\n\nexport interface AmlExchangeDepositCheckResult {\n schema: typeof AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA\n tool: typeof AML_EXCHANGE_DEPOSIT_CHECK_TOOL\n network: string\n address: string\n /** false when the graph holds no node for the address. */\n found: boolean\n /** true when the address carries exchange_role deposit or has a SWEPT link. */\n is_deposit: boolean\n exchange_role: ExchangeRole | null\n /** The exchange id, from the hot wallet it swept into, else from its label words. */\n exchange: string | null\n exchange_display: string | null\n labels: string[]\n swept: Sweep[]\n /** The behaviour counts; null when the graph holds no node for the address. */\n behaviour: DepositBehaviour | null\n /** What the counts show that a deposit address does not do. Empty for a deposit, and when nothing shows. */\n does_not_fit_deposit: string[]\n /** How any deposit address behaves: the same text in every answer, for a host asked what makes one. */\n deposit_profile: string\n /** Set only when no sourced mark exists and the exchange model inferred a role. */\n inferred?: true\n inferred_role?: InferredExchangeRole\n /** The model version, from its `ml:exchange-roles:` source entry. */\n inferred_model?: string\n inferred_basis?: InferredBasis\n inferred_at?: string | null\n hint: string\n}\n\nexport interface ExchangeDepositCheckDependencies {\n loadExchangeRegistry: (network: string) => Promise<LoadedExchangeRegistry>\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<GraphAnswer>\n unavailable?: () => Promise<string | undefined> | string | undefined\n describeFailure: (err: unknown) => string\n}\n\nexport type AmlExchangeDepositCheckToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nconst ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\nconst ADDRESS_READ = /^0x[0-9a-f]{40}$/\n\nfunction assertReadAddress(address: string): void {\n if (!ADDRESS_READ.test(address)) {\n throw new Error(\n `exchange deposit check: ${JSON.stringify(address)} is not a lowercase 0x address`\n )\n }\n}\n\n/** The node read: the address, its marks, its exchange_role and the exchange model's inferred role. */\nexport function depositNodeQuery(address: string): string {\n assertReadAddress(address)\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, ${exchangeRoleRead('a')} AS exchange_role, ` +\n 'a.inferred_exchange_role AS inferred_exchange_role, a.inferred_sources AS inferred_sources, ' +\n 'a.inferred_exchange_role_updated_timestamp AS inferred_exchange_role_updated_timestamp LIMIT 1'\n )\n}\n\n/** The swept read: each hot wallet the address swept into. */\nexport function depositSweptQuery(address: string): string {\n assertReadAddress(address)\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"})-[s:SWEPT]->(h:Address) ` +\n `RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, ${exchangeRoleRead('h')} AS hot_wallet_role, ` +\n 's.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths, ' +\n `s.first_seen_timestamp AS first_seen_timestamp, s.last_seen_timestamp AS last_seen_timestamp LIMIT ${SWEPT_LIMIT}`\n )\n}\n\n/** The behaviour reads: one count row each, over at most BEHAVIOUR_COUNT_CAP links. */\nexport function depositBehaviourQueries(\n address: string\n): Array<{ id: 'paid_by' | 'paid' | 'swapped' | 'approved'; query: string }> {\n assertReadAddress(address)\n const anchor = `(a:Address {address: \"${address}\"})`\n const exchange = 'sum(CASE WHEN b.is_exchange THEN 1 ELSE 0 END)'\n return [\n {\n id: 'paid_by',\n query:\n `USE topology MATCH ${anchor}<-[:FLOWED_TO]-(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n `RETURN count(b) AS payers, ${exchange} AS payers_exchange LIMIT 1`,\n },\n {\n id: 'paid',\n query:\n `USE topology MATCH ${anchor}-[:FLOWED_TO]->(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n `RETURN count(b) AS receivers, ${exchange} AS receivers_exchange LIMIT 1`,\n },\n {\n id: 'swapped',\n query:\n `USE topology MATCH ${anchor}-[:SWAPPED]->(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n 'RETURN count(b) AS dex_pools LIMIT 1',\n },\n {\n id: 'approved',\n query:\n `USE topology MATCH ${anchor}-[:APPROVED]->(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n 'RETURN count(b) AS approvals LIMIT 1',\n },\n ]\n}\n\n/** The one batch the tool sends: members `node`, `swept` and the four behaviour reads. */\nexport function depositCheckQueries(address: string): Array<{ id: string; query: string }> {\n return [\n { id: 'node', query: depositNodeQuery(address) },\n { id: 'swept', query: depositSweptQuery(address) },\n ...depositBehaviourQueries(address),\n ]\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\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 textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\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\nfunction exchangeRoleOf(value: unknown): ExchangeRole | null {\n const role = textOrNull(value)?.toLowerCase()\n return (EXCHANGE_ROLES as readonly string[]).includes(role ?? '') ? (role as ExchangeRole) : null\n}\n\n/**\n * The exchange model's mark of a node row, or null. It needs both the role and\n * an `ml:exchange-roles:<model>:<basis>` source entry: a role with no entry of\n * the exchange model is no inferred mark. The model version may hold hyphens,\n * underscores and colons; the basis is the last part.\n */\nexport function inferredExchangeOf(\n row: Record<string, unknown> | undefined\n): InferredExchangeMark | null {\n const role = textOrNull(row?.inferred_exchange_role)?.toLowerCase()\n if (!(INFERRED_EXCHANGE_ROLES as readonly string[]).includes(role ?? '')) return null\n const marks: Array<{ model: string; basis: InferredBasis; suffix: string }> = []\n for (const source of strings(row?.inferred_sources)) {\n const entry = source.trim()\n if (!entry.startsWith(EXCHANGE_MODEL_SOURCE_PREFIX)) continue\n const rest = entry.slice(EXCHANGE_MODEL_SOURCE_PREFIX.length)\n const cut = rest.lastIndexOf(':')\n if (cut <= 0) continue\n const model = rest.slice(0, cut)\n const suffix = rest.slice(cut + 1)\n if (!Object.prototype.hasOwnProperty.call(INFERRED_BASIS, suffix)) continue\n marks.push({ model, basis: INFERRED_BASIS[suffix as keyof typeof INFERRED_BASIS], suffix })\n }\n // The entry that fits the role first: p-hub names a hot wallet, rule and rule-p a deposit.\n const fits = (suffix: string) => (role === 'hot_wallet') === (suffix === 'p-hub')\n const mark = marks.find((m) => fits(m.suffix)) ?? marks[0]\n if (!mark) return null\n const ms = numberOrNull(row?.inferred_exchange_role_updated_timestamp)\n return {\n role: role as InferredExchangeRole,\n model: mark.model,\n basis: mark.basis,\n at: isEpochMs(ms) ? new Date(ms).toISOString() : null,\n }\n}\n\nconst answered = (member: Member | undefined): boolean =>\n member?.ok === true && Array.isArray(member.results)\n\nconst rowsOf = (member: Member | undefined): Array<Record<string, unknown>> =>\n answered(member) ? (member!.results as unknown[]).filter(isRecord) : []\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 behaviour counts of the batch members; a member that did not answer leaves its counts null. */\nexport function behaviourFromMembers(members: Map<string, Member>): DepositBehaviour {\n const count = (id: string, column: string): number | null =>\n numberOrNull(rowsOf(members.get(id))[0]?.[column])\n return {\n payers: count('paid_by', 'payers'),\n payers_exchange: count('paid_by', 'payers_exchange'),\n receivers: count('paid', 'receivers'),\n receivers_exchange: count('paid', 'receivers_exchange'),\n dex_pools: count('swapped', 'dex_pools'),\n approvals: count('approved', 'approvals'),\n count_cap: BEHAVIOUR_COUNT_CAP,\n }\n}\n\n/** \"5000 or more\" at the cap, else the number. */\nfunction countText(count: number): string {\n return count >= BEHAVIOUR_COUNT_CAP ? `${BEHAVIOUR_COUNT_CAP} or more` : String(count)\n}\n\nconst plural = (count: number, one: string, many: string): string => (count === 1 ? one : many)\n\n/**\n * What the counts show that a deposit address does not do. Only what needs no\n * threshold: a swap, and a payment to an address that is no exchange wallet.\n * How many payers are \"few\" is the graph rule's to say, never this tool's.\n */\nexport function doesNotFitDeposit(behaviour: DepositBehaviour): string[] {\n const facts: string[] = []\n if (behaviour.dex_pools !== null && behaviour.dex_pools > 0) {\n facts.push(\n `it swapped on ${countText(behaviour.dex_pools)} DEX ${plural(behaviour.dex_pools, 'pool', 'pools')}`\n )\n }\n if (behaviour.receivers !== null && behaviour.receivers_exchange !== null) {\n const outside = behaviour.receivers - behaviour.receivers_exchange\n if (outside > 0) {\n // A capped receiver count makes the difference a floor too.\n const atCap = behaviour.receivers >= BEHAVIOUR_COUNT_CAP ? ' or more' : ''\n facts.push(\n `it paid ${outside}${atCap} ${plural(outside, 'address that is', 'addresses that are')} no exchange wallet`\n )\n }\n }\n return facts\n}\n\n/** The counts as one sentence, the read counts only. */\nexport function behaviourText(behaviour: DepositBehaviour): string {\n const parts: string[] = []\n if (behaviour.payers !== null) {\n parts.push(\n `${countText(behaviour.payers)} ${plural(behaviour.payers, 'address', 'addresses')} paid it` +\n (behaviour.payers_exchange !== null\n ? ` (${countText(behaviour.payers_exchange)} of them exchange wallets)`\n : '')\n )\n }\n if (behaviour.receivers !== null) {\n parts.push(\n `it paid ${countText(behaviour.receivers)} ${plural(behaviour.receivers, 'address', 'addresses')}` +\n (behaviour.receivers_exchange !== null\n ? ` (${countText(behaviour.receivers_exchange)} of them exchange wallets)`\n : '')\n )\n }\n if (behaviour.dex_pools !== null) {\n parts.push(\n `it swapped on ${countText(behaviour.dex_pools)} DEX ${plural(behaviour.dex_pools, 'pool', 'pools')}`\n )\n }\n if (behaviour.approvals !== null) {\n parts.push(\n `it approved ${countText(behaviour.approvals)} ${plural(behaviour.approvals, 'spender', 'spenders')}`\n )\n }\n return parts.join(', ')\n}\n\n/** The check built from the batch members and the lookup rows, or why it cannot be. */\nexport function depositCheckFromMembers(\n network: string,\n address: string,\n members: Map<string, Member>,\n rows: ExchangeEntry[]\n): { result: AmlExchangeDepositCheckResult } | { failure: string } {\n const node = members.get('node')\n const swept = members.get('swept')\n if (!answered(node)) return { failure: memberFailure('node', node) }\n if (!answered(swept)) return { failure: memberFailure('swept', swept) }\n\n const nodeRow = rowsOf(node)[0]\n const labels = strings(nodeRow?.labels)\n const sweeps: Sweep[] = []\n let exchange: ExchangeEntry | null = null\n for (const row of rowsOf(swept)) {\n const hot = addressOrNull(row.hot_wallet)\n if (!hot) continue\n const listed =\n exchangeOfWallet(hot, rows)?.entry ?? exchangeOfLabels(strings(row.hot_wallet_labels), rows)\n exchange ??= listed\n const first = numberOrNull(row.first_seen_timestamp)\n const last = numberOrNull(row.last_seen_timestamp)\n sweeps.push({\n hot_wallet: hot,\n hot_wallet_exchange: listed?.exchange ?? null,\n hot_wallet_role: textOrNull(row.hot_wallet_role),\n sweep_count: numberOrNull(row.sweep_count),\n amount_usd_sum: numberOrNull(row.amount_usd_sum),\n paths: strings(row.paths),\n first_seen: first,\n first_seen_utc: utcOrNull(first),\n last_seen: last,\n last_seen_utc: utcOrNull(last),\n })\n }\n sweeps.sort((a, b) => (b.sweep_count ?? 0) - (a.sweep_count ?? 0))\n exchange ??= exchangeOfLabels(labels, rows) ?? exchangeOfWallet(address, rows)?.entry ?? null\n const role = exchangeRoleOf(nodeRow?.exchange_role)\n const found = nodeRow !== undefined || sweeps.length > 0\n const isDeposit = role === 'deposit' || sweeps.length > 0\n const behaviour = behaviourFromMembers(members)\n // A sourced mark always wins: the guess is read only for an address with none.\n const guess = role === null && sweeps.length === 0 ? inferredExchangeOf(nodeRow) : null\n const result: Omit<AmlExchangeDepositCheckResult, 'hint'> = {\n schema: AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA,\n tool: AML_EXCHANGE_DEPOSIT_CHECK_TOOL,\n network,\n address,\n found,\n is_deposit: isDeposit,\n exchange_role: role ?? (sweeps.length > 0 ? ('deposit' as const) : null),\n exchange: exchange?.exchange ?? null,\n exchange_display: exchange?.display ?? null,\n labels,\n swept: sweeps,\n behaviour: found ? behaviour : null,\n does_not_fit_deposit: found && !isDeposit && !role ? doesNotFitDeposit(behaviour) : [],\n deposit_profile: EXCHANGE_DEPOSIT_BEHAVIOUR,\n ...(guess\n ? {\n inferred: true as const,\n inferred_role: guess.role,\n inferred_model: guess.model,\n inferred_basis: guess.basis,\n inferred_at: guess.at,\n }\n : {}),\n }\n return { result: { ...result, hint: `${hintFor(result)} ${PROFILE_HINT}` } }\n}\n\n/** Closes every hint: a host asked how a deposit address behaves answers from deposit_profile, not from its own idea of one. */\nconst PROFILE_HINT =\n 'Asked how a deposit address behaves, what makes an address one or what rules one out, answer with deposit_profile.'\n\n/** \" once\", \" 3 times\", or \"\" when the graph gave no count. */\nfunction timesText(count: number | null): string {\n if (count === null) return ''\n return count === 1 ? ' once' : ` ${count} times`\n}\n\nfunction hintFor(result: Omit<AmlExchangeDepositCheckResult, 'hint'>): string {\n const { address, network } = result\n const name = result.exchange_display ?? 'its exchange (name it from labels)'\n if (!result.found) {\n return (\n `${ANSWER_HINT} ${address} is not in the Chain Insights Graph of ${network}: no flow touches it. ` +\n 'Say so in one line, and check the network and the address with the user: name no other network yourself, and say nothing about what the check covers. ' +\n 'A claim that it is an exchange deposit address is unproven on this network: never repeat it as a fact.'\n )\n }\n if (result.is_deposit) {\n const top = result.swept[0]\n const into = top\n ? ` It swept${timesText(top.sweep_count)} into the hot wallet ${top.hot_wallet}` +\n (result.swept.length > 1\n ? `, and into ${result.swept.length - 1} more hot wallets (swept lists them)`\n : '') +\n '.'\n : ' The graph holds no SWEPT link of it yet: its sweeps are not drawn.'\n return (\n `${ANSWER_HINT} Say: \"${address} is a deposit address of ${name} on ${network}.\"${into} ` +\n 'This is where the money entered the exchange: the exchange can name the customer behind the deposit. ' +\n `${behaviourHint(result)}${EXCHANGE_OPENING_RULE}`\n )\n }\n if (result.inferred && result.inferred_role && result.inferred_model) {\n return inferredHint(result, result.inferred_role, result.inferred_model)\n }\n if (result.exchange_role) {\n return (\n `${ANSWER_HINT} Say: \"${address} is a ${result.exchange_role.replace('_', ' ')} of ${name} on ${network}, not a deposit address.\" ` +\n 'A trail that reaches it has entered the exchange: end the trail there.'\n )\n }\n const misfit =\n result.does_not_fit_deposit.length > 0\n ? `What a deposit address does not do, and this one did: ${result.does_not_fit_deposit.join('; ')}. `\n : 'Its counts alone rule nothing out; the missing mark does: the rule of the graph did not judge it a deposit. '\n return (\n `${ANSWER_HINT} ${address} carries no deposit mark: no SWEPT link and no exchange_role. ` +\n 'Say that the graph shows no sweep of it into a listed exchange hot wallet. That is not proof the address belongs to no exchange; ' +\n `its labels and its links say what else it is. ${behaviourHint(result)}${misfit}` +\n 'Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.'\n )\n}\n\n/** Why the model holds its guess, in reader words. */\nconst INFERRED_BASIS_TEXT: Record<InferredBasis, string> = {\n listed_hot_wallet: 'The model placed it behind a listed exchange hot wallet.',\n predicted_hot_wallet: 'The model placed it behind a hot wallet the model itself inferred, which no listed source names either.',\n predicted: 'The model inferred it from how the address moves money.',\n}\n\n/** The hint of an address with no sourced mark and the exchange model's guess. */\nfunction inferredHint(\n result: Omit<AmlExchangeDepositCheckResult, 'hint'>,\n role: InferredExchangeRole,\n model: string\n): string {\n const { address, network } = result\n const what = role === 'deposit' ? 'an exchange deposit' : 'an exchange hot wallet'\n const basis = result.inferred_basis ? `${INFERRED_BASIS_TEXT[result.inferred_basis]} ` : ''\n const trail =\n role === 'deposit'\n ? 'The graph draws no SWEPT link for it, so no hot wallet is named: name none yourself. '\n : 'A trail that reaches it may have entered an exchange there: say so as inferred, and name no exchange the answer does not name. '\n return (\n `${ANSWER_HINT} Say: \"${address} is ${what}, inferred by model ${model}, on ${network}. ` +\n 'No listed source names it as an exchange address.\" ' +\n `${basis}${trail}` +\n 'Report it as inferred, never as a confirmed exchange address: is_deposit (false) and exchange_role (null) are the sourced verdict, and the guess does not change them. ' +\n `${behaviourHint(result)}` +\n 'Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.'\n )\n}\n\n/** \"Its behaviour: ... . \" for a hint, or \"\" when no count was read. */\nfunction behaviourHint(result: Omit<AmlExchangeDepositCheckResult, 'hint'>): string {\n const text = result.behaviour ? behaviourText(result.behaviour) : ''\n return text === '' ? '' : `Its behaviour, as the graph counts it: ${text}. `\n}\n\nfunction errorResult(text: string): AmlExchangeDepositCheckToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlExchangeDepositCheckResult): AmlExchangeDepositCheckToolResult {\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_exchange_deposit_check, {network, address}. Every argument is checked before a read is sent. */\nexport async function handleAmlExchangeDepositCheck(\n args: unknown,\n deps: ExchangeDepositCheckDependencies\n): Promise<AmlExchangeDepositCheckToolResult> {\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: 0x plus 40 hex characters. ' +\n 'An exchange name is not an address: call meta_exchange_lookup for its wallets.'\n )\n }\n const address = raw.toLowerCase()\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No exchange deposit read was sent: ${unavailable} There is no answer yet, which is not \"no deposit\": try again later.`\n )\n }\n\n let rows: ExchangeEntry[] = []\n try {\n rows = (await deps.loadExchangeRegistry(network)).document.rows\n } catch {\n // The lookup only names the exchange; the graph read still answers.\n }\n\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries: depositCheckQueries(address) })\n } catch (err) {\n return errorResult(\n `The exchange deposit read failed: ${deps.describeFailure(err)} This is not \"no deposit\": send the same check 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 exchange deposit read failed: ${text} This is not \"no deposit\".`)\n }\n const check = depositCheckFromMembers(network, address, members, rows)\n if ('failure' in check) {\n return errorResult(\n `The exchange deposit read failed: ${check.failure} This is not \"no deposit\": send the same check again once.`\n )\n }\n return textResult(check.result)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAa,kCAAkC;AAC/C,MAAa,oCACX;AACF,MAAa,mCAAmC;;;;;;;AAOhD,MAAa,6BACX;AAWF,MAAa,yCACX,i0BAMG,GAfA,2BAA2B,uYAeF,iNAA6B;AAC3D,MAAa,yCAAyC;CACpD,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;;AAIA,MAAa,cAAc;;AAK3B,MAAa,0BAA0B,CAAC,WAAW,YAAY;;;;;;AAQ/D,MAAa,iBAAiB;CAC5B,MAAM;CACN,UAAU;CACV,SAAS;AACX;;AAIA,MAAa,+BAA+B;;AAyB5C,MAAa,sBAAsB;AAuEnC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,SAAS,kBAAkB,SAAuB;CAChD,IAAI,CAAC,aAAa,KAAK,OAAO,GAC5B,MAAM,IAAI,MACR,2BAA2B,KAAK,UAAU,OAAO,EAAE,+BACrD;AAEJ;;AAGA,SAAgB,iBAAiB,SAAyB;CACxD,kBAAkB,OAAO;CACzB,OACE,4CAA4C,QAAQ,iFAC0B,iBAAiB,GAAG,EAAE;AAIxG;;AAGA,SAAgB,kBAAkB,SAAyB;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AAG,SAAS;CAC7D,QAAQ,CAER;CAEA,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,KAAK,gBAAgB;GAAE;GAAS,SAAS,oBAAoB,OAAO;EAAE,CAAC;CACxF,SAAS,KAAK;EACZ,OAAO,YACL,qCAAqC,KAAK,gBAAgB,GAAG,EAAE,2DACjE;CACF;CACA,MAAM,UAAU,UAAU,MAAM;CAChC,IAAI,QAAQ,SAAS,GAEnB,OAAO,YAAY,qCADN,OAAO,YAAY,OAAO,UAAU,MAAM,CAAC,CAAC,OAAO,iCACH,2BAA2B;CAE1F,MAAM,QAAQ,wBAAwB,SAAS,SAAS,SAAS,IAAI;CACrE,IAAI,aAAa,OACf,OAAO,YACL,qCAAqC,MAAM,QAAQ,2DACrD;CAEF,OAAO,WAAW,MAAM,MAAM;AAChC"}
@@ -1,11 +1,11 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  const require_cache_location = require("./cache-location-C09AE55j.cjs");
3
- const require_dex_registry = require("./dex-registry-BhGJUG9_.cjs");
3
+ const require_dex_registry = require("./dex-registry-CyR3GyRr.cjs");
4
+ const require_public_file = require("./public-file-DDp2CrUl.cjs");
4
5
  let node_url = require("node:url");
5
6
  let node_path = require("node:path");
6
7
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
7
8
  let node_fs = require("node:fs");
8
- let node_fs_promises = require("node:fs/promises");
9
9
  // src/mcp/exchange-registry.ts
10
10
  /**
11
11
  * The centralized exchange lookup, as meta_exchange_lookup and
@@ -24,7 +24,8 @@ let node_fs_promises = require("node:fs/promises");
24
24
  * written by scripts/pin-exchange-registry.mjs and held to the rules below by
25
25
  * tests/exchange-registry.test.ts.
26
26
  *
27
- * The proxy reads the file as it reads the DEX registry (src/mcp/dex-registry.ts):
27
+ * The proxy reads the file through the shared public file loader
28
+ * (src/mcp/public-file.ts), as it reads the address card dictionary:
28
29
  *
29
30
  * cached ~/.chain-insights/cache/exchange-registry-<network>.json, younger than one hour
30
31
  * fetched the copy on main, https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/exchanges/<network>.json,
@@ -109,42 +110,6 @@ function readPackagedExchangeRegistry(network, dir = packagedExchangeRegistryDir
109
110
  if (fault) throw new Error(`the packaged exchange lookup registry/exchanges/${network}.json is malformed: ${fault}`);
110
111
  return parsed;
111
112
  }
112
- async function readCache(network) {
113
- try {
114
- const parsed = JSON.parse(await (0, node_fs_promises.readFile)(exchangeRegistryCachePath(network), "utf8"));
115
- if (!isRecord(parsed) || typeof parsed.checked_at_ms !== "number") return null;
116
- if (parsed.source !== "fetched" && parsed.source !== "packaged") return null;
117
- if (exchangeRegistryFault(parsed.document, network) !== null) return null;
118
- return parsed;
119
- } catch {
120
- return null;
121
- }
122
- }
123
- async function writeCache(network, file) {
124
- const target = exchangeRegistryCachePath(network);
125
- await (0, node_fs_promises.mkdir)(node_path.default.dirname(target), { recursive: true });
126
- const scratch = `${target}.${process.pid}.tmp`;
127
- await (0, node_fs_promises.writeFile)(scratch, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
128
- await (0, node_fs_promises.rename)(scratch, target);
129
- }
130
- async function fetchDocument(network, options) {
131
- const url = exchangeRegistryUrl(network, options.env);
132
- let response;
133
- try {
134
- response = await (options.fetch ?? fetch)(url, { signal: AbortSignal.timeout(options.budgetMs ?? require_dex_registry.DEX_REGISTRY_FETCH_BUDGET_MS) });
135
- } catch (err) {
136
- return { fault: `${url} unreachable: ${err instanceof Error ? err.message : String(err)}` };
137
- }
138
- if (response.status !== 200) return { fault: `${url} answered HTTP ${response.status}` };
139
- let parsed;
140
- try {
141
- parsed = JSON.parse(await response.text());
142
- } catch {
143
- return { fault: `${url} is not JSON` };
144
- }
145
- const fault = exchangeRegistryFault(parsed, network);
146
- return fault ? { fault: `${url} is malformed: ${fault}` } : { document: parsed };
147
- }
148
113
  /** A network with no file: no rows, so every lookup on it answers with an empty list. */
149
114
  function emptyDocument(network) {
150
115
  return {
@@ -160,63 +125,21 @@ const defaultLog = (line) => {
160
125
  };
161
126
  /**
162
127
  * The lookup file of one network: the fresh cache, else the public file, else
163
- * the stale cache, else the packaged copy. A packaged copy with a higher
164
- * version than the cache or the public file wins. A network with no file
165
- * anywhere answers with no rows; it never throws for a well-formed network.
128
+ * the stale cache, else the packaged copy (src/mcp/public-file.ts). A packaged
129
+ * copy with a higher version than the cache or the public file wins. A network
130
+ * with no file anywhere answers with no rows; it never throws for a
131
+ * well-formed network.
166
132
  */
167
133
  async function loadExchangeRegistry(rawNetwork, options = {}) {
168
134
  const network = require_dex_registry.normalizeDexNetwork(rawNetwork);
169
- const now = options.now ?? Date.now;
170
- const log = options.log ?? defaultLog;
171
- const packaged = readPackagedExchangeRegistry(network, options.packagedDir);
172
- const pick = (document, source) => packaged !== null && packaged.registry_version > document.registry_version ? {
173
- document: packaged,
174
- source: "packaged"
175
- } : {
176
- document,
177
- source
178
- };
179
- const cache = await readCache(network);
180
- const age = cache ? now() - cache.checked_at_ms : Infinity;
181
- if (cache && age >= 0 && age < require_dex_registry.DEX_REGISTRY_TTL_MS) return pick(cache.document, cache.source === "fetched" ? "cached" : "packaged");
182
- const save = async (file) => {
183
- try {
184
- await writeCache(network, file);
185
- } catch (err) {
186
- log(`the cache ${exchangeRegistryCachePath(network)} could not be written: ${err instanceof Error ? err.message : String(err)}`);
187
- }
188
- };
189
- const outcome = await fetchDocument(network, options);
190
- const checked = now();
191
- if ("document" in outcome) {
192
- await save({
193
- document: outcome.document,
194
- checked_at_ms: checked,
195
- source: "fetched"
196
- });
197
- return pick(outcome.document, "fetched");
198
- }
199
- if (cache) {
200
- log(outcome.fault);
201
- await save({
202
- ...cache,
203
- checked_at_ms: checked
204
- });
205
- return pick(cache.document, cache.source === "fetched" ? "cached" : "packaged");
206
- }
207
- if (packaged) {
208
- log(outcome.fault);
209
- await save({
210
- document: packaged,
211
- checked_at_ms: checked,
212
- source: "packaged"
213
- });
214
- return {
215
- document: packaged,
216
- source: "packaged"
217
- };
218
- }
219
- return {
135
+ return await require_public_file.loadPublicFile({
136
+ url: exchangeRegistryUrl(network, options.env),
137
+ cachePath: exchangeRegistryCachePath(network),
138
+ fault: (value) => exchangeRegistryFault(value, network),
139
+ packaged: readPackagedExchangeRegistry(network, options.packagedDir),
140
+ version: (document) => document.registry_version,
141
+ log: options.log ?? defaultLog
142
+ }, options) ?? {
220
143
  document: emptyDocument(network),
221
144
  source: "none"
222
145
  };