chain-insights 0.79.2 → 0.80.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 (61) hide show
  1. package/README.md +2 -0
  2. package/dist/cli.cjs +43 -13
  3. package/dist/cli.mjs +43 -13
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/{deployer-screen-4AxZhsrO.cjs → deployer-screen-BomgSBcq.cjs} +2 -2
  6. package/dist/{deployer-screen-eix6pvW7.mjs → deployer-screen-ByQBZEsg.mjs} +3 -3
  7. package/dist/{deployer-screen-eix6pvW7.mjs.map → deployer-screen-ByQBZEsg.mjs.map} +1 -1
  8. package/dist/{dex-registry-sPTFuCrP.mjs → dex-registry-BY67f4Ul.mjs} +2 -2
  9. package/dist/{dex-registry-sPTFuCrP.mjs.map → dex-registry-BY67f4Ul.mjs.map} +1 -1
  10. package/dist/{dex-registry-DdXOg5On.cjs → dex-registry-BhGJUG9_.cjs} +36 -0
  11. package/dist/{dex-tool-CDmhhXfk.cjs → dex-tool-B6AymECb.cjs} +2 -2
  12. package/dist/{dex-tool-D61sIjpq.mjs → dex-tool-CjUZY19i.mjs} +3 -3
  13. package/dist/dex-tool-CjUZY19i.mjs.map +1 -0
  14. package/dist/exchange-deposit-check-CMGTPv-T.mjs +209 -0
  15. package/dist/exchange-deposit-check-CMGTPv-T.mjs.map +1 -0
  16. package/dist/exchange-deposit-check-hJGDHLz1.cjs +242 -0
  17. package/dist/exchange-registry-CT0rRW__.cjs +347 -0
  18. package/dist/exchange-registry-CoLgHw6d.mjs +319 -0
  19. package/dist/exchange-registry-CoLgHw6d.mjs.map +1 -0
  20. package/dist/exchange-tool-B2SMeC5f.cjs +218 -0
  21. package/dist/exchange-tool-Dc46SJ49.mjs +179 -0
  22. package/dist/exchange-tool-Dc46SJ49.mjs.map +1 -0
  23. package/dist/{graph-schema-D4LAefGf.mjs → graph-schema-B8KMeX75.mjs} +19 -3
  24. package/dist/{graph-schema-D4LAefGf.mjs.map → graph-schema-B8KMeX75.mjs.map} +1 -1
  25. package/dist/{graph-schema-C8Pi6r7c.cjs → graph-schema-D8rHCsBJ.cjs} +23 -1
  26. package/dist/mcp-proxy.cjs +65 -13
  27. package/dist/mcp-proxy.d.cts +1 -0
  28. package/dist/mcp-proxy.d.cts.map +1 -1
  29. package/dist/mcp-proxy.d.mts +1 -0
  30. package/dist/mcp-proxy.d.mts.map +1 -1
  31. package/dist/mcp-proxy.mjs +65 -14
  32. package/dist/mcp-proxy.mjs.map +1 -1
  33. package/dist/{public-tools-DXlZcanX.mjs → public-tools-CU1nukHW.mjs} +171 -10
  34. package/dist/public-tools-CU1nukHW.mjs.map +1 -0
  35. package/dist/{public-tools-Cfc1OPNS.cjs → public-tools-yvRiFSry.cjs} +170 -9
  36. package/dist/{token-lookup-DBN3Lxl7.cjs → token-lookup-D-5GBEwF.cjs} +1 -1
  37. package/dist/{token-lookup-Bv_Fviis.mjs → token-lookup-QpIv77P2.mjs} +2 -2
  38. package/dist/{token-lookup-Bv_Fviis.mjs.map → token-lookup-QpIv77P2.mjs.map} +1 -1
  39. package/dist/{tool-visibility-DwNr6Rp9.cjs → tool-visibility-D8Up081E.cjs} +7 -1
  40. package/dist/{tool-visibility-DlxA8R00.mjs → tool-visibility-DuTds7V4.mjs} +8 -2
  41. package/dist/tool-visibility-DuTds7V4.mjs.map +1 -0
  42. package/docs/contributing.md +4 -3
  43. package/docs/development.md +4 -2
  44. package/docs/graph-query-compatibility.md +20 -4
  45. package/docs/graph-tools.md +17 -8
  46. package/docs/mcp-proxy.md +62 -2
  47. package/docs/stability.md +4 -2
  48. package/package.json +1 -1
  49. package/registry/README.md +37 -0
  50. package/registry/exchanges/ethereum.json +920 -0
  51. package/registry/exchanges/robinhood.json +87 -0
  52. package/skills/chain-insights-aml-exchange/SKILL.md +134 -0
  53. package/skills/chain-insights-aml-exchange/agents/openai.yaml +4 -0
  54. package/skills/chain-insights-cypher/SKILL.md +41 -11
  55. package/skills/chain-insights-dex/SKILL.md +1 -1
  56. package/skills/chain-insights-dex-gauge/SKILL.md +2 -0
  57. package/skills/chain-insights-dex-launchpad/SKILL.md +2 -0
  58. package/skills/chain-insights-dex-vault/SKILL.md +2 -0
  59. package/dist/dex-tool-D61sIjpq.mjs.map +0 -1
  60. package/dist/public-tools-DXlZcanX.mjs.map +0 -1
  61. package/dist/tool-visibility-DlxA8R00.mjs.map +0 -1
@@ -0,0 +1,242 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
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-D8rHCsBJ.cjs");
7
+ const require_print_result = require("./print-result-BYppJlUi.cjs");
8
+ const require_token_lookup = require("./token-lookup-D-5GBEwF.cjs");
9
+ // src/mcp/exchange-deposit-check.ts
10
+ /**
11
+ * aml_exchange_deposit_check: is this address an exchange deposit, of which
12
+ * exchange, and into which hot wallet was it swept?
13
+ *
14
+ * A local tool of the proxy. It sends one graph_query_batch with two reads on
15
+ * USE topology, both anchored on the address:
16
+ *
17
+ * node the address: its node labels, its label words and `cex_role`;
18
+ * swept its `SWEPT` links: each hot wallet it swept into, with the sweep
19
+ * count, the USD sum, the paths and the first and last sweep.
20
+ *
21
+ * `SWEPT` (layer `cex_sweeps`) is drawn only from an address the deposit rule
22
+ * judged a deposit, and `cex_role` comes from the exchange label's subtype. The
23
+ * graph judges, this tool only reads. The exchange is named from the lookup
24
+ * file (src/mcp/exchange-registry.ts): the hot wallet it swept into, else a
25
+ * label word.
26
+ */
27
+ var exchange_deposit_check_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ handleAmlExchangeDepositCheck: () => handleAmlExchangeDepositCheck });
28
+ const AML_EXCHANGE_DEPOSIT_CHECK_TOOL = "aml_exchange_deposit_check";
29
+ const AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA = "chain-insights.aml-exchange-deposit-check.v1";
30
+ const AML_EXCHANGE_DEPOSIT_CHECK_TITLE = "Exchange deposit check";
31
+ 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, anchored on the address: two reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, or when the user asks where money entered an exchange. ${require_exchange_tool.EXCHANGE_OPENING_RULE}`;
32
+ const AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS = {
33
+ readOnlyHint: true,
34
+ idempotentHint: true,
35
+ openWorldHint: false
36
+ };
37
+ /** The most hot wallets one deposit's read returns. */
38
+ const SWEPT_LIMIT = 20;
39
+ const ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/;
40
+ const ADDRESS_READ = /^0x[0-9a-f]{40}$/;
41
+ function assertReadAddress(address) {
42
+ if (!ADDRESS_READ.test(address)) throw new Error(`exchange deposit check: ${JSON.stringify(address)} is not a lowercase 0x address`);
43
+ }
44
+ /** The node read: the address, its marks and its cex_role. */
45
+ function depositNodeQuery(address) {
46
+ assertReadAddress(address);
47
+ 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 LIMIT 1`;
48
+ }
49
+ /** The swept read: each hot wallet the address swept into. */
50
+ function depositSweptQuery(address) {
51
+ assertReadAddress(address);
52
+ 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}`;
53
+ }
54
+ /** The one batch the tool sends: members `node` and `swept`. */
55
+ function depositCheckQueries(address) {
56
+ return [{
57
+ id: "node",
58
+ query: depositNodeQuery(address)
59
+ }, {
60
+ id: "swept",
61
+ query: depositSweptQuery(address)
62
+ }];
63
+ }
64
+ function isRecord(value) {
65
+ return !!value && typeof value === "object" && !Array.isArray(value);
66
+ }
67
+ const strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
68
+ const numberOrNull = (value) => {
69
+ if (typeof value === "number" && Number.isFinite(value)) return value;
70
+ if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value);
71
+ return null;
72
+ };
73
+ const textOrNull = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
74
+ const addressOrNull = (value) => typeof value === "string" && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null;
75
+ const utcOrNull = (ms) => require_print_result.isEpochMs(ms) ? require_print_result.utcText(ms) : null;
76
+ function cexRoleOf(value) {
77
+ const role = textOrNull(value)?.toLowerCase();
78
+ return require_graph_schema.CEX_ROLES.includes(role ?? "") ? role : null;
79
+ }
80
+ const answered = (member) => member?.ok === true && Array.isArray(member.results);
81
+ const rowsOf = (member) => answered(member) ? member.results.filter(isRecord) : [];
82
+ function memberFailure(id, member) {
83
+ if (!member) return `the ${id} read is missing from the batch answer`;
84
+ return typeof member.error === "string" && member.error.trim() !== "" ? member.error : `the ${id} read did not answer`;
85
+ }
86
+ /** The check built from the two batch members and the lookup rows, or why it cannot be. */
87
+ function depositCheckFromMembers(network, address, members, rows) {
88
+ const node = members.get("node");
89
+ const swept = members.get("swept");
90
+ if (!answered(node)) return { failure: memberFailure("node", node) };
91
+ if (!answered(swept)) return { failure: memberFailure("swept", swept) };
92
+ const nodeRow = rowsOf(node)[0];
93
+ const labels = strings(nodeRow?.labels);
94
+ const sweeps = [];
95
+ let exchange = null;
96
+ for (const row of rowsOf(swept)) {
97
+ const hot = addressOrNull(row.hot_wallet);
98
+ if (!hot) continue;
99
+ const listed = require_exchange_registry.exchangeOfWallet(hot, rows)?.entry ?? require_exchange_registry.exchangeOfLabels(strings(row.hot_wallet_labels), rows);
100
+ exchange ??= listed;
101
+ const first = numberOrNull(row.first_seen_timestamp);
102
+ const last = numberOrNull(row.last_seen_timestamp);
103
+ sweeps.push({
104
+ hot_wallet: hot,
105
+ hot_wallet_exchange: listed?.exchange ?? null,
106
+ hot_wallet_role: textOrNull(row.hot_wallet_role),
107
+ sweep_count: numberOrNull(row.sweep_count),
108
+ amount_usd_sum: numberOrNull(row.amount_usd_sum),
109
+ paths: strings(row.paths),
110
+ first_seen: first,
111
+ first_seen_utc: utcOrNull(first),
112
+ last_seen: last,
113
+ last_seen_utc: utcOrNull(last)
114
+ });
115
+ }
116
+ sweeps.sort((a, b) => (b.sweep_count ?? 0) - (a.sweep_count ?? 0));
117
+ exchange ??= require_exchange_registry.exchangeOfLabels(labels, rows) ?? require_exchange_registry.exchangeOfWallet(address, rows)?.entry ?? null;
118
+ const role = cexRoleOf(nodeRow?.cex_role);
119
+ const found = nodeRow !== void 0 || sweeps.length > 0;
120
+ const result = {
121
+ schema: AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA,
122
+ tool: AML_EXCHANGE_DEPOSIT_CHECK_TOOL,
123
+ network,
124
+ address,
125
+ found,
126
+ is_deposit: role === "deposit" || sweeps.length > 0,
127
+ cex_role: role ?? (sweeps.length > 0 ? "deposit" : null),
128
+ exchange: exchange?.exchange ?? null,
129
+ exchange_display: exchange?.display ?? null,
130
+ labels,
131
+ swept: sweeps
132
+ };
133
+ return { result: {
134
+ ...result,
135
+ hint: hintFor(result)
136
+ } };
137
+ }
138
+ /** " once", " 3 times", or "" when the graph gave no count. */
139
+ function timesText(count) {
140
+ if (count === null) return "";
141
+ return count === 1 ? " once" : ` ${count} times`;
142
+ }
143
+ function hintFor(result) {
144
+ const { address, network } = result;
145
+ const name = result.exchange_display ?? "its exchange (name it from labels)";
146
+ if (!result.found) return `${require_answer_hint.ANSWER_HINT} ${address} is not in the Chain Insights Graph of ${network}: no flow touches it. Say so in one line, and check the network and the address with the user.`;
147
+ if (result.is_deposit) {
148
+ const top = result.swept[0];
149
+ const into = top ? ` It swept${timesText(top.sweep_count)} into the hot wallet ${top.hot_wallet}` + (result.swept.length > 1 ? `, and into ${result.swept.length - 1} more hot wallets (swept lists them)` : "") + "." : " The graph holds no SWEPT link of it yet: its sweeps are not drawn.";
150
+ 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. ` + require_exchange_tool.EXCHANGE_OPENING_RULE;
151
+ }
152
+ 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.`;
153
+ 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.`;
154
+ }
155
+ function errorResult(text) {
156
+ return {
157
+ content: [{
158
+ type: "text",
159
+ text
160
+ }],
161
+ isError: true
162
+ };
163
+ }
164
+ function textResult(structured) {
165
+ return {
166
+ content: [{
167
+ type: "text",
168
+ text: JSON.stringify(structured, null, 2)
169
+ }],
170
+ structuredContent: structured,
171
+ isError: false
172
+ };
173
+ }
174
+ /** aml_exchange_deposit_check, {network, address}. Every argument is checked before a read is sent. */
175
+ async function handleAmlExchangeDepositCheck(args, deps) {
176
+ const record = isRecord(args) ? args : {};
177
+ let network;
178
+ try {
179
+ network = require_dex_registry.normalizeDexNetwork(record.network);
180
+ } catch (err) {
181
+ return errorResult(err instanceof require_dex_registry.DexRegistryError ? err.message : `invalid_network: ${err.message}`);
182
+ }
183
+ const raw = typeof record.address === "string" ? record.address.trim() : "";
184
+ if (!ADDRESS_INPUT.test(raw)) return errorResult("invalid_address: address is required: 0x plus 40 hex characters. An exchange name is not an address: call meta_exchange_lookup for its wallets.");
185
+ const address = raw.toLowerCase();
186
+ const unavailable = await deps.unavailable?.();
187
+ if (unavailable) return errorResult(`No exchange deposit read was sent: ${unavailable} There is no answer yet, which is not "no deposit": try again later.`);
188
+ let rows = [];
189
+ try {
190
+ rows = (await deps.loadExchangeRegistry(network)).document.rows;
191
+ } catch {}
192
+ let answer;
193
+ try {
194
+ answer = await deps.graphQueryBatch({
195
+ network,
196
+ queries: depositCheckQueries(address)
197
+ });
198
+ } catch (err) {
199
+ return errorResult(`The exchange deposit read failed: ${deps.describeFailure(err)} This is not "no deposit": send the same check again once.`);
200
+ }
201
+ const members = require_token_lookup.membersOf(answer);
202
+ if (members.size === 0) return errorResult(`The exchange deposit read failed: ${answer.isError === true ? require_token_lookup.refusalOf(answer).text : "the batch answer held no reads"} This is not "no deposit".`);
203
+ const check = depositCheckFromMembers(network, address, members, rows);
204
+ if ("failure" in check) return errorResult(`The exchange deposit read failed: ${check.failure} This is not "no deposit": send the same check again once.`);
205
+ return textResult(check.result);
206
+ }
207
+ Object.defineProperty(exports, "AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS", {
208
+ enumerable: true,
209
+ get: function() {
210
+ return AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS;
211
+ }
212
+ });
213
+ Object.defineProperty(exports, "AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION", {
214
+ enumerable: true,
215
+ get: function() {
216
+ return AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION;
217
+ }
218
+ });
219
+ Object.defineProperty(exports, "AML_EXCHANGE_DEPOSIT_CHECK_TITLE", {
220
+ enumerable: true,
221
+ get: function() {
222
+ return AML_EXCHANGE_DEPOSIT_CHECK_TITLE;
223
+ }
224
+ });
225
+ Object.defineProperty(exports, "AML_EXCHANGE_DEPOSIT_CHECK_TOOL", {
226
+ enumerable: true,
227
+ get: function() {
228
+ return AML_EXCHANGE_DEPOSIT_CHECK_TOOL;
229
+ }
230
+ });
231
+ Object.defineProperty(exports, "exchange_deposit_check_exports", {
232
+ enumerable: true,
233
+ get: function() {
234
+ return exchange_deposit_check_exports;
235
+ }
236
+ });
237
+ Object.defineProperty(exports, "handleAmlExchangeDepositCheck", {
238
+ enumerable: true,
239
+ get: function() {
240
+ return handleAmlExchangeDepositCheck;
241
+ }
242
+ });
@@ -0,0 +1,347 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
+ const require_cache_location = require("./cache-location-C09AE55j.cjs");
3
+ const require_dex_registry = require("./dex-registry-BhGJUG9_.cjs");
4
+ let node_url = require("node:url");
5
+ let node_path = require("node:path");
6
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
7
+ let node_fs = require("node:fs");
8
+ let node_fs_promises = require("node:fs/promises");
9
+ // src/mcp/exchange-registry.ts
10
+ /**
11
+ * The centralized exchange lookup, as meta_exchange_lookup and
12
+ * aml_exchange_deposit_check read it.
13
+ *
14
+ * registry/exchanges/<network>.json lists every centralized exchange the
15
+ * indexer-evm-cex registry of the network names, with its id, its display name
16
+ * and its aliases, and under each only the wallets proven on that network's
17
+ * own data: hot wallets that receive the sweeps of its deposits, gas wallets
18
+ * that top deposits up, and spenders that pull approved deposits. Each wallet
19
+ * carries the payer proof and the block it was proven at, always above 0. An
20
+ * exchange tag, or a wallet of another network at the same address, never
21
+ * enters the file: it stays in the indexer's registry and reaches the graph.
22
+ * So an exchange may list no wallet; its deposits, its SWEPT links and its
23
+ * hot wallets are read from the graph (aml_exchange_deposit_check). It is
24
+ * written by scripts/pin-exchange-registry.mjs and held to the rules below by
25
+ * tests/exchange-registry.test.ts.
26
+ *
27
+ * The proxy reads the file as it reads the DEX registry (src/mcp/dex-registry.ts):
28
+ *
29
+ * cached ~/.chain-insights/cache/exchange-registry-<network>.json, younger than one hour
30
+ * fetched the copy on main, https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/exchanges/<network>.json,
31
+ * within 3 s, at most once an hour per network
32
+ * packaged registry/exchanges/<network>.json of the installed package
33
+ *
34
+ * A fetched file is used only when it passes the rules. A row merged on main
35
+ * reaches every running proxy within the hour, with no release. A lookup is a
36
+ * proxy tool and never a table or a graph property.
37
+ */
38
+ var exchange_registry_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ loadExchangeRegistry: () => loadExchangeRegistry });
39
+ const EXCHANGE_REGISTRY_SCHEMA = "chain-insights.exchange-registry.v1";
40
+ const EXCHANGE_REGISTRY_URL_ENV = "CHAIN_INSIGHTS_EXCHANGE_REGISTRY_URL";
41
+ const EXCHANGE_REGISTRY_PUBLIC_URL = "https://raw.githubusercontent.com/chainswarm/chain-insights/main/registry/exchanges/{network}.json";
42
+ const WALLET_ROLES = [
43
+ "hot_wallet",
44
+ "gas_wallet",
45
+ "spender"
46
+ ];
47
+ const ADDRESS_RE = /^0x[0-9a-f]{40}$/;
48
+ const EXCHANGE_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
49
+ function isRecord(value) {
50
+ return !!value && typeof value === "object" && !Array.isArray(value);
51
+ }
52
+ const isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
53
+ /** The fault of a lookup file, or null when it is valid for the network. */
54
+ function exchangeRegistryFault(value, network) {
55
+ if (!isRecord(value)) return "the file is not a JSON object";
56
+ if (value.schema !== EXCHANGE_REGISTRY_SCHEMA) return `schema is ${JSON.stringify(value.schema)}, not ${EXCHANGE_REGISTRY_SCHEMA}`;
57
+ if (value.network !== network) return `network is ${JSON.stringify(value.network)}, not ${network}`;
58
+ if (!Number.isInteger(value.registry_version) || value.registry_version < 0) return "registry_version is not a whole number";
59
+ if (typeof value.recorded_on !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value.recorded_on)) return "recorded_on is not a YYYY-MM-DD day";
60
+ if (!Array.isArray(value.rows) || value.rows.length === 0) return "rows is empty";
61
+ const ids = /* @__PURE__ */ new Set();
62
+ const owners = /* @__PURE__ */ new Map();
63
+ for (const [index, row] of value.rows.entries()) {
64
+ const at = `rows[${index}]`;
65
+ if (!isRecord(row)) return `${at} is not an object`;
66
+ if (typeof row.exchange !== "string" || !EXCHANGE_RE.test(row.exchange)) return `${at}.exchange is not an id: ${String(row.exchange)}`;
67
+ if (ids.has(row.exchange)) return `${at}.exchange ${row.exchange} is listed twice`;
68
+ ids.add(row.exchange);
69
+ if (typeof row.display !== "string" || row.display.trim() === "") return `${at} (${row.exchange}) has no display`;
70
+ if (!isStringList(row.aliases)) return `${at} (${row.exchange}) aliases is not a list of names`;
71
+ if (!Array.isArray(row.wallets)) return `${at} (${row.exchange}) wallets is not a list`;
72
+ for (const wallet of row.wallets) {
73
+ if (!isRecord(wallet)) return `${at} (${row.exchange}) has a wallet that is not an object`;
74
+ const address = wallet.address;
75
+ if (typeof address !== "string" || !ADDRESS_RE.test(address)) return `${at} (${row.exchange}) address ${String(address)} is not lowercase 0x plus 40 hex characters`;
76
+ if (!WALLET_ROLES.includes(wallet.role)) return `${at} (${row.exchange}) role ${String(wallet.role)} is not hot_wallet, gas_wallet or spender`;
77
+ if (typeof wallet.evidence !== "string" || wallet.evidence.trim() === "") return `${at} (${row.exchange}) ${address} has no evidence`;
78
+ if (!Number.isInteger(wallet.proven_at_block) || wallet.proven_at_block <= 0) return `${at} (${row.exchange}) ${address} proven_at_block is not a block above 0: only a wallet proven on this chain is listed`;
79
+ const owner = owners.get(address);
80
+ if (owner !== void 0) return `${at} (${row.exchange}) ${address} is also a wallet of ${owner}`;
81
+ owners.set(address, row.exchange);
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+ /** The URL of the served copy: the public file on main, or the override with {network} filled in. */
87
+ function exchangeRegistryUrl(network, env = process.env) {
88
+ const template = env[EXCHANGE_REGISTRY_URL_ENV]?.trim() || EXCHANGE_REGISTRY_PUBLIC_URL;
89
+ if (template.includes("{network}")) return template.replaceAll("{network}", network);
90
+ return template.endsWith("/") ? `${template}${network}.json` : template;
91
+ }
92
+ function exchangeRegistryCachePath(network) {
93
+ return node_path.default.join(require_cache_location.chainInsightsHome(), "cache", `exchange-registry-${network}.json`);
94
+ }
95
+ /** registry/exchanges of the installed package: next to dist/, or the repository root when run from source. */
96
+ function packagedExchangeRegistryDir() {
97
+ const candidates = [(0, node_url.fileURLToPath)(new URL("../registry/exchanges", require("url").pathToFileURL(__filename).href)), (0, node_url.fileURLToPath)(new URL("../../registry/exchanges", require("url").pathToFileURL(__filename).href))];
98
+ return candidates.find((candidate) => (0, node_fs.existsSync)(node_path.default.join(candidate, "robinhood.json"))) ?? candidates[0];
99
+ }
100
+ /** The packaged copy of a network, or null when the package carries none. A packaged copy that fails the rules throws. */
101
+ function readPackagedExchangeRegistry(network, dir = packagedExchangeRegistryDir()) {
102
+ let parsed;
103
+ try {
104
+ parsed = JSON.parse((0, node_fs.readFileSync)(node_path.default.join(dir, `${network}.json`), "utf8"));
105
+ } catch {
106
+ return null;
107
+ }
108
+ const fault = exchangeRegistryFault(parsed, network);
109
+ if (fault) throw new Error(`the packaged exchange lookup registry/exchanges/${network}.json is malformed: ${fault}`);
110
+ return parsed;
111
+ }
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
+ /** A network with no file: no rows, so every lookup on it answers with an empty list. */
149
+ function emptyDocument(network) {
150
+ return {
151
+ schema: EXCHANGE_REGISTRY_SCHEMA,
152
+ network,
153
+ registry_version: 0,
154
+ recorded_on: "1970-01-01",
155
+ rows: []
156
+ };
157
+ }
158
+ const defaultLog = (line) => {
159
+ process.stderr.write(`[chain-insights] exchange-registry: ${line}\n`);
160
+ };
161
+ /**
162
+ * 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.
166
+ */
167
+ async function loadExchangeRegistry(rawNetwork, options = {}) {
168
+ 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 {
220
+ document: emptyDocument(network),
221
+ source: "none"
222
+ };
223
+ }
224
+ /**
225
+ * One name against the rows, as matchDex does for a DEX: exact on the id, the
226
+ * display and the aliases; then within two letters of an alias of four or more
227
+ * characters. A tie is listed, never guessed.
228
+ */
229
+ function matchExchange(name, rows) {
230
+ const listed = rows.map((row) => row.display);
231
+ const wanted = require_dex_registry.normaliseName(name);
232
+ if (!wanted) return {
233
+ matched: null,
234
+ candidates: [],
235
+ listed
236
+ };
237
+ const exact = rows.filter((row) => [
238
+ row.exchange,
239
+ row.display,
240
+ ...row.aliases
241
+ ].some((written) => require_dex_registry.normaliseName(written) === wanted));
242
+ if (exact.length === 1) return {
243
+ matched: exact[0],
244
+ candidates: [],
245
+ listed
246
+ };
247
+ if (exact.length > 1) return {
248
+ matched: null,
249
+ candidates: exact.map((row) => ({
250
+ exchange: row.exchange,
251
+ display: row.display,
252
+ distance: 0
253
+ })),
254
+ listed
255
+ };
256
+ const near = [];
257
+ for (const row of rows) {
258
+ const distances = [
259
+ row.exchange,
260
+ row.display,
261
+ ...row.aliases
262
+ ].map(require_dex_registry.normaliseName).filter((alias) => alias.length >= require_dex_registry.NEAR_MIN_ALIAS_LENGTH).map((alias) => require_dex_registry.damerauLevenshtein(wanted, alias));
263
+ if (distances.length === 0) continue;
264
+ const distance = Math.min(...distances);
265
+ if (distance <= require_dex_registry.NEAR_DISTANCE) near.push({
266
+ row,
267
+ distance
268
+ });
269
+ }
270
+ if (near.length === 0) return {
271
+ matched: null,
272
+ candidates: [],
273
+ listed
274
+ };
275
+ const least = Math.min(...near.map((hit) => hit.distance));
276
+ const nearest = near.filter((hit) => hit.distance === least);
277
+ if (nearest.length === 1) return {
278
+ matched: nearest[0].row,
279
+ took_for: name.trim(),
280
+ candidates: [],
281
+ listed
282
+ };
283
+ return {
284
+ matched: null,
285
+ candidates: nearest.map(({ row, distance }) => ({
286
+ exchange: row.exchange,
287
+ display: row.display,
288
+ distance
289
+ })),
290
+ listed
291
+ };
292
+ }
293
+ /** The exchange and the wallet a lowercase address is, or null when no row lists it. */
294
+ function exchangeOfWallet(address, rows) {
295
+ for (const entry of rows) {
296
+ const wallet = entry.wallets.find((candidate) => candidate.address === address);
297
+ if (wallet) return {
298
+ entry,
299
+ wallet
300
+ };
301
+ }
302
+ return null;
303
+ }
304
+ /** The exchange a list of graph label words names, or null: the first word that is an id, a display name or an alias. */
305
+ function exchangeOfLabels(labels, rows) {
306
+ for (const word of labels) {
307
+ const wanted = require_dex_registry.normaliseName(word);
308
+ if (!wanted) continue;
309
+ const row = rows.find((entry) => [
310
+ entry.exchange,
311
+ entry.display,
312
+ ...entry.aliases
313
+ ].some((name) => require_dex_registry.normaliseName(name) === wanted));
314
+ if (row) return row;
315
+ }
316
+ return null;
317
+ }
318
+ Object.defineProperty(exports, "exchangeOfLabels", {
319
+ enumerable: true,
320
+ get: function() {
321
+ return exchangeOfLabels;
322
+ }
323
+ });
324
+ Object.defineProperty(exports, "exchangeOfWallet", {
325
+ enumerable: true,
326
+ get: function() {
327
+ return exchangeOfWallet;
328
+ }
329
+ });
330
+ Object.defineProperty(exports, "exchange_registry_exports", {
331
+ enumerable: true,
332
+ get: function() {
333
+ return exchange_registry_exports;
334
+ }
335
+ });
336
+ Object.defineProperty(exports, "loadExchangeRegistry", {
337
+ enumerable: true,
338
+ get: function() {
339
+ return loadExchangeRegistry;
340
+ }
341
+ });
342
+ Object.defineProperty(exports, "matchExchange", {
343
+ enumerable: true,
344
+ get: function() {
345
+ return matchExchange;
346
+ }
347
+ });