chain-insights 0.85.2 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -0
  2. package/bin/install.cjs +2 -1
  3. package/dist/{active-q3yViZhc.cjs → active-COPA14FA.cjs} +2 -16
  4. package/dist/{active-D2aabYRF.mjs → active-CyC4jFka.mjs} +2 -7
  5. package/dist/{active-D2aabYRF.mjs.map → active-CyC4jFka.mjs.map} +1 -1
  6. package/dist/address-card-C-NB03XP.cjs +218 -0
  7. package/dist/address-card-LYaT5yz0.mjs +190 -0
  8. package/dist/address-card-LYaT5yz0.mjs.map +1 -0
  9. package/dist/address-risk-DPuXBsvH.cjs +806 -0
  10. package/dist/address-risk-Da6FsfGx.mjs +653 -0
  11. package/dist/address-risk-Da6FsfGx.mjs.map +1 -0
  12. package/dist/{capabilities-Mxa4oQdd.cjs → capabilities-DkNreyv7.cjs} +1 -1
  13. package/dist/{capabilities-bZOr5Ads.mjs → capabilities-w5bNR7F9.mjs} +2 -2
  14. package/dist/{capabilities-bZOr5Ads.mjs.map → capabilities-w5bNR7F9.mjs.map} +1 -1
  15. package/dist/cli.cjs +138 -46
  16. package/dist/cli.mjs +138 -46
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/{deployer-screen-B5yrXZGo.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-B5yrXZGo.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-0SOQ_HFf.cjs → deployer-screen-CFLi7OeH.cjs} +2 -2
  21. package/dist/{dex-registry-BY67f4Ul.mjs → dex-registry-Bkri0--q.mjs} +10 -2
  22. package/dist/{dex-registry-BY67f4Ul.mjs.map → dex-registry-Bkri0--q.mjs.map} +1 -1
  23. package/dist/{dex-registry-BhGJUG9_.cjs → dex-registry-CyR3GyRr.cjs} +20 -0
  24. package/dist/{dex-tool-7BK_gD6H.mjs → dex-tool-D0K_Qx4N.mjs} +4 -4
  25. package/dist/dex-tool-D0K_Qx4N.mjs.map +1 -0
  26. package/dist/{dex-tool-Be9NAuD8.cjs → dex-tool-DQ5Eg0LO.cjs} +3 -3
  27. package/dist/{exchange-deposit-check-C5MseGlZ.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CXHZCHWW.mjs → exchange-deposit-check-DIALj2sm.mjs} +19 -19
  29. package/dist/exchange-deposit-check-DIALj2sm.mjs.map +1 -0
  30. package/dist/{exchange-registry-CT0rRW__.cjs → exchange-registry-CEgkeQV1.cjs} +16 -93
  31. package/dist/{exchange-registry-CoLgHw6d.mjs → exchange-registry-Dr5UtcT5.mjs} +17 -94
  32. package/dist/exchange-registry-Dr5UtcT5.mjs.map +1 -0
  33. package/dist/{exchange-tool-Dc46SJ49.mjs → exchange-tool-B7E29YoQ.mjs} +4 -4
  34. package/dist/exchange-tool-B7E29YoQ.mjs.map +1 -0
  35. package/dist/{exchange-tool-B2SMeC5f.cjs → exchange-tool-CXaUBAd2.cjs} +3 -3
  36. package/dist/{graph-schema-CcrYPpSv.cjs → graph-schema-Bn3txQCj.cjs} +115 -12
  37. package/dist/{graph-schema-CRQuKya1.mjs → graph-schema-DvABR1yl.mjs} +97 -12
  38. package/dist/graph-schema-DvABR1yl.mjs.map +1 -0
  39. package/dist/{layer-routing-YDj-ynG9.cjs → layer-routing-j48SQ8Wk.cjs} +2 -2
  40. package/dist/{layer-routing-DCJVNN6O.mjs → layer-routing-r4IbIQSr.mjs} +3 -3
  41. package/dist/layer-routing-r4IbIQSr.mjs.map +1 -0
  42. package/dist/mcp-proxy.cjs +62 -15
  43. package/dist/mcp-proxy.d.cts.map +1 -1
  44. package/dist/mcp-proxy.d.mts.map +1 -1
  45. package/dist/mcp-proxy.mjs +62 -15
  46. package/dist/mcp-proxy.mjs.map +1 -1
  47. package/dist/public-file-BISyAesm.mjs +133 -0
  48. package/dist/public-file-BISyAesm.mjs.map +1 -0
  49. package/dist/public-file-DDp2CrUl.cjs +138 -0
  50. package/dist/{request-timeout-DxwNijQD.cjs → request-timeout-BXiIt9Jy.cjs} +0 -1
  51. package/dist/{request-timeout-K3ljP0pa.mjs → request-timeout-DetG2xO4.mjs} +2 -2
  52. package/dist/{request-timeout-K3ljP0pa.mjs.map → request-timeout-DetG2xO4.mjs.map} +1 -1
  53. package/dist/{token-lookup-Cf59VdGe.mjs → token-lookup-Ck0q7crJ.mjs} +2 -2
  54. package/dist/{token-lookup-Cf59VdGe.mjs.map → token-lookup-Ck0q7crJ.mjs.map} +1 -1
  55. package/dist/{token-lookup-DqjSRIxd.cjs → token-lookup-DLe4erP9.cjs} +1 -1
  56. package/dist/token-risk-CpMfFRoY.cjs +1004 -0
  57. package/dist/token-risk-DhnJc2kJ.mjs +971 -0
  58. package/dist/token-risk-DhnJc2kJ.mjs.map +1 -0
  59. package/dist/{tool-visibility-D8Up081E.cjs → tool-visibility-BCa-tmyZ.cjs} +11 -2
  60. package/dist/{tool-visibility-DuTds7V4.mjs → tool-visibility-BstrSl4s.mjs} +12 -3
  61. package/dist/tool-visibility-BstrSl4s.mjs.map +1 -0
  62. package/docs/contributing.md +10 -8
  63. package/docs/development.md +5 -5
  64. package/docs/evals.md +16 -1
  65. package/docs/graph-query-compatibility.md +15 -2
  66. package/docs/graph-tools.md +44 -6
  67. package/docs/mcp-proxy.md +189 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +76 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +680 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +61 -0
  74. package/skills/chain-insights-address-risk/agents/openai.yaml +4 -0
  75. package/skills/chain-insights-aml-exchange/SKILL.md +9 -7
  76. package/skills/chain-insights-cypher/SKILL.md +79 -3
  77. package/skills/chain-insights-token-risk/SKILL.md +81 -0
  78. package/skills/chain-insights-token-risk/agents/openai.yaml +4 -0
  79. package/skills/chain-insights-virtuals/reference.md +1 -1
  80. package/dist/dex-tool-7BK_gD6H.mjs.map +0 -1
  81. package/dist/exchange-deposit-check-CXHZCHWW.mjs.map +0 -1
  82. package/dist/exchange-registry-CoLgHw6d.mjs.map +0 -1
  83. package/dist/exchange-tool-Dc46SJ49.mjs.map +0 -1
  84. package/dist/graph-schema-CRQuKya1.mjs.map +0 -1
  85. package/dist/layer-routing-DCJVNN6O.mjs.map +0 -1
  86. package/dist/public-tools-CBszU2oX.cjs +0 -1334
  87. package/dist/public-tools-DVhUjSDV.mjs +0 -1333
  88. package/dist/public-tools-DVhUjSDV.mjs.map +0 -1
  89. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -1,1334 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
- const require_active = require("./active-q3yViZhc.cjs");
3
- const require_request_timeout = require("./request-timeout-DxwNijQD.cjs");
4
- const require_capabilities = require("./capabilities-Mxa4oQdd.cjs");
5
- let node_path = require("node:path");
6
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
7
- let node_fs_promises = require("node:fs/promises");
8
- // src/investigation/graph-normalizer.ts
9
- const GRAPH_TYPE_LABELS = /* @__PURE__ */ new Set([
10
- "Address",
11
- "Exchange",
12
- "Miner",
13
- "Validator",
14
- "Hotkey",
15
- "Subnet",
16
- "IPAddress"
17
- ]);
18
- const FLOW_EDGE_TYPES = /* @__PURE__ */ new Set([
19
- "flowed_to",
20
- "transfer",
21
- "transfer_to",
22
- "transfers_to"
23
- ]);
24
- function isRecord$1(value) {
25
- return typeof value === "object" && value !== null && !Array.isArray(value);
26
- }
27
- function stringArray(value) {
28
- return Array.isArray(value) ? value.map(String).filter(Boolean) : [];
29
- }
30
- function unique(values) {
31
- return [...new Set(values)];
32
- }
33
- function lowerSnake(value) {
34
- return value.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
35
- }
36
- function isGraphTypeLabel(label) {
37
- return GRAPH_TYPE_LABELS.has(label);
38
- }
39
- function displayLabels(node) {
40
- return unique(stringArray(node["labels"])).filter((label) => !isGraphTypeLabel(label));
41
- }
42
- function systemLabels(node) {
43
- return unique([
44
- ...stringArray(node["system_labels"]),
45
- ...stringArray(node["graph_labels"]),
46
- ...stringArray(node["raw_labels"]),
47
- ...stringArray(node["labels"]).filter(isGraphTypeLabel)
48
- ]);
49
- }
50
- function normalizeRoles(node) {
51
- const roles = stringArray(node["roles"]);
52
- const role = typeof node["role"] === "string" ? node["role"] : "";
53
- if (role === "source_exchange") roles.push("exchange");
54
- else if (role) roles.push(role);
55
- const display = stringArray(node["labels"]).map(lowerSnake);
56
- if (systemLabels(node).some((label) => lowerSnake(label) === "exchange") || display.includes("exchange")) roles.push("exchange");
57
- return unique(roles.map(lowerSnake).filter(Boolean));
58
- }
59
- function normalizeNodeType(node) {
60
- if (typeof node["node_type"] === "string" && node["node_type"].trim()) return lowerSnake(node["node_type"]);
61
- if (typeof node["address"] === "string" || typeof node["id"] === "string") return "address";
62
- const labels = systemLabels(node);
63
- if (labels.length > 0) return lowerSnake(labels[0]);
64
- return "unknown";
65
- }
66
- function normalizeNode(node) {
67
- if (!isRecord$1(node)) return {};
68
- const normalized = {};
69
- for (const [key, value] of Object.entries(node)) {
70
- if ([
71
- "address_subtypes",
72
- "entity_kind",
73
- "graph_labels",
74
- "labels",
75
- "node_type",
76
- "pattern_flags",
77
- "raw_labels",
78
- "role",
79
- "roles",
80
- "system_labels",
81
- "type"
82
- ].includes(key)) continue;
83
- normalized[key] = value;
84
- }
85
- const id = typeof node["id"] === "string" ? node["id"] : typeof node["address"] === "string" ? node["address"] : void 0;
86
- if (id) normalized["id"] = id;
87
- const address = typeof node["address"] === "string" ? node["address"] : id;
88
- if (address) normalized["address"] = address;
89
- normalized["node_type"] = normalizeNodeType(node);
90
- normalized["labels"] = displayLabels(node);
91
- const addressSubtypes = unique(stringArray(node["address_subtypes"]));
92
- if (addressSubtypes.length > 0) normalized["address_subtypes"] = addressSubtypes;
93
- const roles = normalizeRoles(node);
94
- if (roles.length > 0) normalized["roles"] = roles;
95
- if (!Array.isArray(node["flags"]) && Array.isArray(node["pattern_flags"]) && node["pattern_flags"].length > 0) normalized["flags"] = node["pattern_flags"].map(String);
96
- return normalized;
97
- }
98
- function normalizeEdgeType(edge) {
99
- const edgeType = lowerSnake(typeof edge["edge_type"] === "string" && edge["edge_type"].trim() ? edge["edge_type"] : typeof edge["type"] === "string" && edge["type"].trim() ? edge["type"] : typeof edge["relationship_type"] === "string" && edge["relationship_type"].trim() ? edge["relationship_type"] : "related_to");
100
- return FLOW_EDGE_TYPES.has(edgeType) ? "flowed_to" : edgeType;
101
- }
102
- function normalizeEdge(edge) {
103
- if (!isRecord$1(edge)) return {};
104
- const normalized = {};
105
- for (const [key, value] of Object.entries(edge)) {
106
- if ([
107
- "edge_type",
108
- "from_address",
109
- "relationship_type",
110
- "to_address",
111
- "type"
112
- ].includes(key)) continue;
113
- normalized[key] = value;
114
- }
115
- if (typeof normalized["source"] !== "string" && typeof edge["from_address"] === "string") normalized["source"] = edge["from_address"];
116
- if (typeof normalized["target"] !== "string" && typeof edge["to_address"] === "string") normalized["target"] = edge["to_address"];
117
- normalized["edge_type"] = normalizeEdgeType(edge);
118
- return normalized;
119
- }
120
- function normalizeGraphPayload(payload) {
121
- if (!isRecord$1(payload) || payload["schema"] !== "chain-insights.graph.v1") throw new Error("Unsupported graph payload schema");
122
- return {
123
- ...payload,
124
- schema: "chain-insights.graph.v1",
125
- nodes: Array.isArray(payload["nodes"]) ? payload["nodes"].map(normalizeNode) : [],
126
- edges: Array.isArray(payload["edges"]) ? payload["edges"].map(normalizeEdge) : [],
127
- flows: Array.isArray(payload["flows"]) ? payload["flows"] : [],
128
- edge_anchors: Array.isArray(payload["edge_anchors"]) ? payload["edge_anchors"] : []
129
- };
130
- }
131
- // src/investigation/risk-level.ts
132
- /**
133
- * Risk-level normalization shared by the AML tools and graph payload builders.
134
- *
135
- * The Chain Insights Graph serves the ML verdict verbatim, which historically
136
- * mixed cases (HIGH vs high) and — since the calibrated-scoring release —
137
- * includes an explicit abstention band: risk_level = UNSCORED means the model
138
- * had too little labeled graph context to stand behind a band. UNSCORED is a
139
- * "no stance" state and must never be rendered or reasoned about as low risk.
140
- */
141
- const RISK_SEVERITIES = [
142
- "low",
143
- "medium",
144
- "high",
145
- "critical"
146
- ];
147
- const UNSCORED_RISK_LEVEL = "unscored";
148
- /** Lowercased, trimmed risk level; undefined for empty/unrecognized values. */
149
- function normalizeRiskLevel(value) {
150
- if (typeof value !== "string") return void 0;
151
- const normalized = value.trim().toLowerCase();
152
- if (!normalized) return void 0;
153
- if (normalized === UNSCORED_RISK_LEVEL) return UNSCORED_RISK_LEVEL;
154
- if (RISK_SEVERITIES.includes(normalized)) return normalized;
155
- }
156
- /** True when the ML verdict explicitly abstained (no stance, not low). */
157
- function isUnscoredRiskLevel(value) {
158
- return normalizeRiskLevel(value) === UNSCORED_RISK_LEVEL;
159
- }
160
- /**
161
- * Severity ordering for comparisons: low(0) < medium(1) < high(2) <
162
- * critical(3). Unknown/unscored values rank -1 — they never win a
163
- * severity comparison, they abstain from it.
164
- */
165
- function riskSeverityRank(value) {
166
- const normalized = normalizeRiskLevel(value);
167
- if (!normalized || normalized === UNSCORED_RISK_LEVEL) return -1;
168
- return RISK_SEVERITIES.indexOf(normalized);
169
- }
170
- // src/workspace/output-root.ts
171
- const NO_WORKSPACE_ERROR = "No Chain Insights workspace found. Run: cia init .";
172
- function requireWorkspaceRoot(startDir = process.cwd()) {
173
- const workspace = require_active.findActiveWorkspace(startDir);
174
- if (!workspace) throw new Error(NO_WORKSPACE_ERROR);
175
- return workspace.root;
176
- }
177
- function workspaceOutputPaths(workspaceRoot = requireWorkspaceRoot()) {
178
- const root = node_path.default.resolve(workspaceRoot);
179
- return {
180
- root,
181
- metadataDir: node_path.default.join(root, ".chain-insights"),
182
- schemaDir: node_path.default.join(root, ".chain-insights", "schema"),
183
- runtimeDir: node_path.default.join(root, ".chain-insights", "runtime"),
184
- artifactsRoot: node_path.default.join(root, "artifacts"),
185
- entitiesRoot: node_path.default.join(root, "entities"),
186
- sessionsRoot: node_path.default.join(root, "sessions"),
187
- publishedRoot: node_path.default.join(root, "published"),
188
- reportsRoot: node_path.default.join(root, "reports"),
189
- reportGraphsRoot: node_path.default.join(root, "reports", "graphs"),
190
- reportTablesRoot: node_path.default.join(root, "reports", "tables"),
191
- logsRoot: node_path.default.join(root, ".chain-insights", "runtime", "logs")
192
- };
193
- }
194
- // src/lib/usage-accumulator.ts
195
- function createUsageAccumulator() {
196
- return {
197
- billable_units: 0,
198
- query_count: 0,
199
- truncated_queries: 0
200
- };
201
- }
202
- function usageBlock(totals) {
203
- return {
204
- billable_units: totals.billable_units,
205
- query_count: totals.query_count,
206
- truncated_queries: totals.truncated_queries
207
- };
208
- }
209
- function isRecord(value) {
210
- return typeof value === "object" && value !== null && !Array.isArray(value);
211
- }
212
- function numberValue$1(value) {
213
- if (typeof value === "number" && Number.isFinite(value)) return value;
214
- if (typeof value === "string" && value.trim()) {
215
- const parsed = Number(value);
216
- return Number.isFinite(parsed) ? parsed : void 0;
217
- }
218
- }
219
- function textOfToolResult(result) {
220
- if (!isRecord(result)) return "";
221
- const content = result["content"];
222
- if (!Array.isArray(content)) return "";
223
- return content.filter((item) => isRecord(item) && item["type"] === "text" && typeof item["text"] === "string").map((item) => item.text).join("\n");
224
- }
225
- function accumulateFacts(totals, facts) {
226
- if (!isRecord(facts)) return;
227
- const query = facts["query"];
228
- if (isRecord(query)) {
229
- const units = numberValue$1(query["billable_units"]);
230
- if (units !== void 0) totals.billable_units += units;
231
- if (query["truncated"] === true) totals.truncated_queries += 1;
232
- }
233
- const batch = facts["batch"];
234
- const batchUnits = isRecord(batch) ? numberValue$1(batch["billable_units"]) : void 0;
235
- const queries = Array.isArray(facts["queries"]) ? facts["queries"].filter(isRecord) : void 0;
236
- if (batchUnits !== void 0) totals.billable_units += batchUnits;
237
- else if (queries) for (const entry of queries) {
238
- const units = numberValue$1(entry["billable_units"]);
239
- if (units !== void 0) totals.billable_units += units;
240
- }
241
- if (queries) {
242
- for (const entry of queries) if (entry["truncated"] === true) totals.truncated_queries += 1;
243
- } else if (isRecord(batch) && batch["truncated"] === true) totals.truncated_queries += 1;
244
- }
245
- function recordGraphQueryBatchResult(totals, rawResult) {
246
- let facts;
247
- try {
248
- const text = textOfToolResult(rawResult).trim();
249
- if (text) facts = JSON.parse(text).facts;
250
- else if (isRecord(rawResult) && isRecord(rawResult["structuredContent"])) facts = rawResult["structuredContent"]["facts"];
251
- } catch {
252
- facts = void 0;
253
- }
254
- const queries = isRecord(facts) && Array.isArray(facts["queries"]) ? facts["queries"] : void 0;
255
- totals.query_count += queries ? queries.length : 1;
256
- accumulateFacts(totals, facts);
257
- }
258
- function recordGraphQueryResult(totals, rawResult) {
259
- totals.query_count += 1;
260
- let facts;
261
- try {
262
- if (isRecord(rawResult) && isRecord(rawResult["structuredContent"])) facts = rawResult["structuredContent"]["facts"];
263
- else {
264
- const text = textOfToolResult(rawResult).trim();
265
- if (text) facts = JSON.parse(text).facts;
266
- }
267
- } catch {
268
- facts = void 0;
269
- }
270
- accumulateFacts(totals, facts);
271
- }
272
- function wrapClientForUsageTracking(client, totals) {
273
- return new Proxy(client, { get(target, prop, receiver) {
274
- if (prop === "callTool") return async (...args) => {
275
- const result = await target.callTool(...args);
276
- const request = args[0];
277
- const toolName = isRecord(request) && typeof request["name"] === "string" ? request["name"] : void 0;
278
- if (toolName === "graph_query_batch") recordGraphQueryBatchResult(totals, result);
279
- else if (toolName === "graph_query") recordGraphQueryResult(totals, result);
280
- return result;
281
- };
282
- const value = Reflect.get(target, prop, target);
283
- return typeof value === "function" ? value.bind(target) : value;
284
- } });
285
- }
286
- // src/investigation/public-tools.ts
287
- const AML_ADDRESS_RISK_SUPPORTED_VERSIONS = ["v1"];
288
- const LATEST_AML_ADDRESS_RISK_VERSION = "v1";
289
- function resolveAmlAddressRiskVersion(requested) {
290
- const normalized = requested?.trim().toLowerCase();
291
- if (!normalized) return LATEST_AML_ADDRESS_RISK_VERSION;
292
- if (AML_ADDRESS_RISK_SUPPORTED_VERSIONS.includes(normalized)) return normalized;
293
- throw new Error(`Unsupported aml_address_risk version "${requested?.trim() ?? ""}". Supported versions: ${AML_ADDRESS_RISK_SUPPORTED_VERSIONS.join(", ")}.`);
294
- }
295
- function escapeCypherString(value) {
296
- return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
297
- }
298
- function textFromToolResult(result) {
299
- return (result.content ?? []).filter((item) => item.type === "text").map((item) => item.text).join("\n");
300
- }
301
- function parseGraphBatchResult(result) {
302
- const text = textFromToolResult(result).trim();
303
- if (!text) throw new Error("graph_query_batch returned no text content");
304
- const parsed = JSON.parse(text);
305
- if (!parsed.facts?.queries) throw new Error("graph_query_batch response did not include facts.queries");
306
- return parsed;
307
- }
308
- function topologyGraphQuery(query) {
309
- const trimmed = query.trim();
310
- if (/^USE\s+/i.test(trimmed)) return trimmed;
311
- return `USE topology ${trimmed}`;
312
- }
313
- function collectQueryFailure(failures, id, error) {
314
- failures.push({
315
- id,
316
- error: error || "unknown error"
317
- });
318
- }
319
- function optionalResultsFor(batch, id, failures) {
320
- const query = batch.facts?.queries?.find((entry) => entry.id === id);
321
- if (!query) return [];
322
- if (query.ok === false) {
323
- collectQueryFailure(failures, id, query.error);
324
- return [];
325
- }
326
- return query.results ?? [];
327
- }
328
- function optionalResultsWithPrefix(batch, prefix, failures) {
329
- return (batch.facts?.queries ?? []).filter((entry) => entry.id?.startsWith(prefix)).flatMap((entry) => {
330
- if (entry.ok === false) {
331
- collectQueryFailure(failures, entry.id ?? prefix, entry.error);
332
- return [];
333
- }
334
- return entry.results ?? [];
335
- });
336
- }
337
- async function callGraphBatch(remoteClient, network, queries) {
338
- const result = await remoteClient.callTool({
339
- name: "graph_query_batch",
340
- arguments: {
341
- network,
342
- queries: queries.map((query) => ({
343
- ...query,
344
- query: topologyGraphQuery(query.query)
345
- }))
346
- }
347
- }, void 0, {
348
- timeout: require_request_timeout.GRAPH_TOOL_REQUEST_TIMEOUT_MS,
349
- maxTotalTimeout: require_request_timeout.GRAPH_TOOL_REQUEST_TIMEOUT_MS
350
- });
351
- if (result.isError) throw new Error(textFromToolResult(result) || "graph_query_batch failed");
352
- return parseGraphBatchResult(result);
353
- }
354
- function addressProfileQuery(address) {
355
- return {
356
- id: "address_profile",
357
- query: [
358
- `MATCH (a:Address {address: "${escapeCypherString(address)}"})`,
359
- `RETURN a.address AS address, a.network AS network, a.labels AS display_labels, a.labels AS system_labels, a.is_exchange AS is_exchange, a.risk_score AS live_risk_score, a.risk_level AS live_risk_level, a.label_risk_labels AS label_risk_labels, a.label_risk_levels AS label_risk_levels, a.label_risk_updated_timestamps AS label_risk_updated_timestamps`,
360
- "LIMIT 1"
361
- ].join(" ")
362
- };
363
- }
364
- function addressFeatureQuery(address) {
365
- return {
366
- id: "address_feature",
367
- query: [
368
- "USE topology",
369
- `MATCH (a:Address {address: "${escapeCypherString(address)}"})`,
370
- "RETURN a.degree_in AS degree_in, a.degree_out AS degree_out, a.degree_total AS degree_total, a.tx_in_count AS tx_in_count, a.tx_out_count AS tx_out_count, a.tx_total_count AS tx_total_count, a.total_volume_usd AS total_volume_usd, a.total_in_usd AS total_in_usd, a.total_out_usd AS total_out_usd, a.net_flow_usd AS net_flow_usd, a.first_activity_timestamp AS first_activity_timestamp, a.last_activity_timestamp AS last_activity_timestamp, a.activity_span_days AS activity_span_days",
371
- "LIMIT 1"
372
- ].join(" ")
373
- };
374
- }
375
- function flowEdgeMap(variableName) {
376
- return `{amount_usd_sum: ${variableName}.amount_usd_sum, tx_count: ${variableName}.tx_count, first_seen_timestamp: ${variableName}.first_seen_timestamp, last_seen_timestamp: ${variableName}.last_seen_timestamp}`;
377
- }
378
- function pathNodeMap(variableName) {
379
- return `{address: ${variableName}.address, network: ${variableName}.network, labels: ${variableName}.labels, system_labels: ${variableName}.labels, is_exchange: ${variableName}.is_exchange${`, risk_score: ${variableName}.risk_score, risk_level: ${variableName}.risk_level`}}`;
380
- }
381
- function moneyTrailIncidentQuery(address) {
382
- return [
383
- "USE topology",
384
- `MATCH (a:Address {address: "${escapeCypherString(address)}"})-[r:MONEY_TRAIL]-()`,
385
- "RETURN r.edge_class AS edge_class, r.value AS value, r.min_hop AS min_hop, r.seed_count AS seed_count, r.primary_seed AS primary_seed, r.generation AS generation, r.network AS network, r.first_ts AS first_ts, r.last_ts AS last_ts",
386
- "LIMIT 200"
387
- ].join(" ");
388
- }
389
- function moneyTrailEndsQuery(seed) {
390
- return [
391
- "USE topology",
392
- `MATCH (s:Address {address: "${escapeCypherString(seed)}"})-[r:TRAIL_ENDS_AT]->(t:Address)`,
393
- "RETURN t.address AS address, r.fact_type AS fact_type, r.direction AS direction, r.terminal_role AS terminal_role, r.hop AS hop, r.value AS value, r.generation AS generation",
394
- "LIMIT 200"
395
- ].join(" ");
396
- }
397
- const MONEY_TRAIL_CLASS_RANK = {
398
- transport: 3,
399
- holding: 2,
400
- peripheral: 1
401
- };
402
- function buildMoneyTrailBlock(incidentRows, endRows) {
403
- if (incidentRows.length === 0) return void 0;
404
- const winningClassRank = Math.max(...incidentRows.map((row) => MONEY_TRAIL_CLASS_RANK[firstString(row["edge_class"]) ?? ""] ?? 0));
405
- const winningClass = Object.entries(MONEY_TRAIL_CLASS_RANK).find(([, rank]) => rank === winningClassRank)?.[0] ?? firstString(incidentRows[0]?.["edge_class"]) ?? "peripheral";
406
- const rowsOfWinningClass = incidentRows.filter((row) => firstString(row["edge_class"]) === winningClass);
407
- const bestRow = rowsOfWinningClass.reduce((best, row) => {
408
- return (numberValue(row["min_hop"]) ?? Number.POSITIVE_INFINITY) < (numberValue(best["min_hop"]) ?? Number.POSITIVE_INFINITY) ? row : best;
409
- }, rowsOfWinningClass[0]);
410
- const nearestEnd = endRows.reduce((best, row) => {
411
- const rowValue = numberValue(row["value"]) ?? Number.NEGATIVE_INFINITY;
412
- const bestValue = best ? numberValue(best["value"]) ?? Number.NEGATIVE_INFINITY : Number.NEGATIVE_INFINITY;
413
- return !best || rowValue > bestValue ? row : best;
414
- }, void 0);
415
- return {
416
- on_trail: true,
417
- class: winningClass,
418
- min_hop: numberValue(bestRow["min_hop"]) ?? 0,
419
- primary_seed: firstString(bestRow["primary_seed"]) ?? "",
420
- generation: numberValue(bestRow["generation"]) ?? 0,
421
- ...nearestEnd ? { nearest_trail_end: {
422
- address: firstString(nearestEnd["address"]) ?? "",
423
- fact_type: firstString(nearestEnd["fact_type"]) ?? "",
424
- value: String(nearestEnd["value"] ?? "")
425
- } } : {}
426
- };
427
- }
428
- function moneyTrailSummarySentence(block) {
429
- return block.class === "peripheral" ? `This address touched money-trail funds (${block.class}, min hop ${block.min_hop}).` : `This address sits on a money trail (${block.class}, min hop ${block.min_hop}).`;
430
- }
431
- function poolGuardTerms(nodeVariables) {
432
- return nodeVariables.map((nodeVariable) => `NOT ${nodeVariable}:Pool`).join(" AND ");
433
- }
434
- const SYSTEM_ADDRESS_LIST = `[${["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"].map((address) => `"${address}"`).join(", ")}]`;
435
- function systemGuardTerms(nodeVariables) {
436
- return nodeVariables.map((nodeVariable) => `NOT ${nodeVariable}:Protocol AND NOT ${nodeVariable}:System AND NOT ${nodeVariable}.address IN ${SYSTEM_ADDRESS_LIST}`).join(" AND ");
437
- }
438
- function walkGuardTerms(nodeVariables, hops) {
439
- return hops > 1 ? nodeVariables.map((nodeVariable) => `${poolGuardTerms([nodeVariable])} AND ${systemGuardTerms([nodeVariable])}`).join(" AND ") : poolGuardTerms(nodeVariables);
440
- }
441
- function exchangeOutflowQueries(address) {
442
- return Array.from({ length: 3 }, (_, index) => exchangeOutflowQueryAtDepth(address, index + 1));
443
- }
444
- function exchangeOutflowQueryAtDepth(address, depth) {
445
- const intermediateVariables = Array.from({ length: Math.max(depth - 1, 0) }, (_, index) => `n${index + 1}`);
446
- const nodeVariables = [
447
- "a",
448
- ...intermediateVariables,
449
- "exchange"
450
- ];
451
- const edgeVariables = Array.from({ length: depth }, (_, index) => `r${index + 1}`);
452
- const relationshipChain = edgeVariables.map((edgeVariable, index) => {
453
- return `-[${edgeVariable}:FLOWED_TO]->(${index === edgeVariables.length - 1 ? "exchange" : intermediateVariables[index]}:Address)`;
454
- }).join("");
455
- const intermediatePredicates = intermediateVariables.map((nodeVariable) => `${nodeVariable}.is_exchange IS NULL`);
456
- const poolGuards = walkGuardTerms(["a", ...intermediateVariables], depth);
457
- const depositVariable = nodeVariables[nodeVariables.length - 2];
458
- const terminalEdgeVariable = edgeVariables[edgeVariables.length - 1];
459
- return {
460
- id: `exchange_outflows_${depth}`,
461
- query: [
462
- `MATCH (a:Address {address: "${escapeCypherString(address)}"})${relationshipChain}`,
463
- `WHERE a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(" AND ")}` : ""} AND ${poolGuards}`,
464
- `RETURN "outflow" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, exchange.cex_role AS exchange_cex_role, ${depositVariable}.address AS deposit_address, ${depth} AS hops, ${terminalEdgeVariable}.amount_usd_sum AS amount_usd_sum, ${terminalEdgeVariable}.tx_count AS tx_count, ${terminalEdgeVariable}.first_seen_timestamp AS first_seen_timestamp, ${terminalEdgeVariable}.last_seen_timestamp AS last_seen_timestamp, [${nodeVariables.map((nodeVariable) => `${nodeVariable}.address`).join(", ")}] AS addresses, [${nodeVariables.map((nodeVariable) => pathNodeMap(nodeVariable)).join(", ")}] AS path_nodes, [${edgeVariables.map(flowEdgeMap).join(", ")}] AS edge_props`,
465
- "ORDER BY hops ASC",
466
- "LIMIT 200"
467
- ].join(" ")
468
- };
469
- }
470
- function exchangeInflowQueries(address) {
471
- return Array.from({ length: 3 }, (_, index) => exchangeInflowQueryAtDepth(address, index + 1));
472
- }
473
- function exchangeInflowQueryAtDepth(address, depth) {
474
- const intermediateVariables = Array.from({ length: Math.max(depth - 1, 0) }, (_, index) => `n${index + 1}`);
475
- const nodeVariables = [
476
- "exchange",
477
- ...intermediateVariables,
478
- "a"
479
- ];
480
- const edgeVariables = Array.from({ length: depth }, (_, index) => `r${index + 1}`);
481
- const relationshipChain = edgeVariables.map((edgeVariable, index) => {
482
- return `-[${edgeVariable}:FLOWED_TO]->(${index === edgeVariables.length - 1 ? "a" : intermediateVariables[index]}:Address)`;
483
- }).join("");
484
- const intermediatePredicates = intermediateVariables.map((nodeVariable) => `${nodeVariable}.is_exchange IS NULL`);
485
- const poolGuards = walkGuardTerms(["a", ...intermediateVariables], depth);
486
- const withdrawalVariable = nodeVariables[1];
487
- const terminalEdgeVariable = edgeVariables[edgeVariables.length - 1];
488
- return {
489
- id: `exchange_inflows_${depth}`,
490
- query: [
491
- `MATCH (exchange:Address)${relationshipChain}`,
492
- `WHERE a.address = "${escapeCypherString(address)}" AND a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(" AND ")}` : ""} AND ${poolGuards}`,
493
- `RETURN "inflow" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, exchange.cex_role AS exchange_cex_role, ${withdrawalVariable}.address AS withdrawal_address, ${depth} AS hops, ${terminalEdgeVariable}.amount_usd_sum AS amount_usd_sum, ${terminalEdgeVariable}.tx_count AS tx_count, ${terminalEdgeVariable}.first_seen_timestamp AS first_seen_timestamp, ${terminalEdgeVariable}.last_seen_timestamp AS last_seen_timestamp, [${nodeVariables.map((nodeVariable) => `${nodeVariable}.address`).join(", ")}] AS addresses, [${nodeVariables.map((nodeVariable) => pathNodeMap(nodeVariable)).join(", ")}] AS path_nodes, [${edgeVariables.map(flowEdgeMap).join(", ")}] AS edge_props`,
494
- "ORDER BY hops ASC",
495
- "LIMIT 200"
496
- ].join(" ")
497
- };
498
- }
499
- /** How many deposits one screen reads SWEPT for, at most. */
500
- const EXCHANGE_DEPOSIT_SWEPT_LOOKUPS = 10;
501
- /** How many SWEPT links of one deposit the screen keeps, largest first. */
502
- const EXCHANGE_DEPOSIT_SWEPT_LIMIT = 20;
503
- /** The exchange id an :Exchange address's labels name (`gate`, `bitget`). */
504
- function exchangeIdFromLabels(labels) {
505
- return stringArrayValue(labels)?.map((label) => label.trim()).find((label) => label !== "" && label.toLowerCase() !== "exchange");
506
- }
507
- /**
508
- * One exchange walk row with its end resolved: `exchange_role` is the end's
509
- * cex_role (`exchange` when the graph carries none), `exchange` its id. An
510
- * outflow that ends at a deposit reports the deposit as `deposit_address`
511
- * and the node the money came from as `payer_address`.
512
- */
513
- function resolveExchangeEnd(row) {
514
- const role = firstString(row["exchange_cex_role"])?.toLowerCase();
515
- const exchangeId = exchangeIdFromLabels(row["exchange_system_labels"] ?? row["exchange_display_labels"] ?? row["exchange_labels"]);
516
- const resolved = {
517
- ...row,
518
- exchange_role: role ?? "exchange",
519
- ...exchangeId ? { exchange: exchangeId } : {}
520
- };
521
- if (row["direction"] === "outflow" && role === "deposit") {
522
- resolved["payer_address"] = row["deposit_address"];
523
- resolved["deposit_address"] = row["exchange_address"];
524
- }
525
- return resolved;
526
- }
527
- /** The deposits among resolved outflow rows, nearest first, no repeats. */
528
- function exchangeDepositEnds(rows) {
529
- const deposits = [];
530
- const ordered = [...rows].sort((left, right) => (numberValue(left["hops"]) ?? 0) - (numberValue(right["hops"]) ?? 0));
531
- for (const row of ordered) {
532
- if (row["direction"] !== "outflow" || row["exchange_role"] !== "deposit") continue;
533
- const deposit = firstString(row["exchange_address"]);
534
- if (deposit && !deposits.includes(deposit)) deposits.push(deposit);
535
- if (deposits.length >= EXCHANGE_DEPOSIT_SWEPT_LOOKUPS) break;
536
- }
537
- return deposits;
538
- }
539
- /** The SWEPT read of one deposit: each hot wallet it was swept into. */
540
- function exchangeDepositSweptQuery(deposit, index) {
541
- return {
542
- id: `exchange_deposit_swept_${index + 1}`,
543
- query: [
544
- `MATCH (d:Address {address: "${escapeCypherString(deposit)}"})-[s:SWEPT]->(h:Address)`,
545
- "RETURN d.address AS deposit_address, 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",
546
- `LIMIT ${EXCHANGE_DEPOSIT_SWEPT_LIMIT}`
547
- ].join(" ")
548
- };
549
- }
550
- /**
551
- * Attach each deposit's SWEPT links to the rows that end at it, largest sum
552
- * first. `swept_status` says whether the read ran: `read` (with or without
553
- * links), or `not_read` when the read failed or the deposit was past the
554
- * lookup cap, so an empty list never reads as "never swept".
555
- */
556
- function attachSweptHotWallets(rows, sweptRows, readDeposits) {
557
- const byDeposit = /* @__PURE__ */ new Map();
558
- for (const swept of sweptRows) {
559
- const deposit = firstString(swept["deposit_address"]);
560
- const hotWallet = firstString(swept["hot_wallet"]);
561
- if (!deposit || !hotWallet) continue;
562
- const exchange = exchangeIdFromLabels(swept["hot_wallet_labels"]);
563
- const role = firstString(swept["hot_wallet_role"]);
564
- const sweepCount = numberValue(swept["sweep_count"]);
565
- const amount = numberValue(swept["amount_usd_sum"]);
566
- const paths = stringArrayValue(swept["paths"]);
567
- const firstSeen = numberValue(swept["first_seen_timestamp"]);
568
- const lastSeen = numberValue(swept["last_seen_timestamp"]);
569
- const entry = {
570
- hot_wallet: hotWallet,
571
- ...exchange ? { hot_wallet_exchange: exchange } : {},
572
- ...role ? { hot_wallet_role: role } : {},
573
- ...sweepCount !== void 0 ? { sweep_count: sweepCount } : {},
574
- ...amount !== void 0 ? { amount_usd_sum: amount } : {},
575
- ...paths ? { paths } : {},
576
- ...firstSeen !== void 0 ? { first_seen_timestamp: firstSeen } : {},
577
- ...lastSeen !== void 0 ? { last_seen_timestamp: lastSeen } : {}
578
- };
579
- byDeposit.set(deposit, [...byDeposit.get(deposit) ?? [], entry]);
580
- }
581
- for (const list of byDeposit.values()) list.sort((left, right) => (right.amount_usd_sum ?? 0) - (left.amount_usd_sum ?? 0));
582
- return rows.map((row) => {
583
- if (row["direction"] !== "outflow" || row["exchange_role"] !== "deposit") return row;
584
- const deposit = String(row["exchange_address"] ?? "");
585
- return {
586
- ...row,
587
- swept_into: byDeposit.get(deposit) ?? [],
588
- swept_status: readDeposits.includes(deposit) ? "read" : "not_read"
589
- };
590
- });
591
- }
592
- function connectionProbeQuery(address, compareAddress) {
593
- return {
594
- id: "connection_probe",
595
- query: [
596
- `MATCH (a:Address {address: "${escapeCypherString(address)}"})-[r:FLOWED_TO]-(b:Address {address: "${escapeCypherString(compareAddress)}"})`,
597
- "RETURN [a.address, b.address] AS addresses, 1 AS hops",
598
- "LIMIT 5"
599
- ].join(" ")
600
- };
601
- }
602
- function compareAddressExistsQuery(address) {
603
- return {
604
- id: "compare_address_exists",
605
- query: [
606
- `MATCH (a:Address {address: "${escapeCypherString(address)}"})`,
607
- "RETURN a.address AS address",
608
- "LIMIT 1"
609
- ].join(" ")
610
- };
611
- }
612
- const CONNECTION_ROUTE_DEPTH_BOUND = 4;
613
- const CONNECTION_ROUTE_MAX_HOPS = 5;
614
- function shouldIncludeRouteQueries(compareAddress) {
615
- return Boolean(compareAddress);
616
- }
617
- function connectionRouteQueries(address, compareAddress, shape = "route") {
618
- const links = shape === "levels" ? "FLOWED_TO|ROUTED_TO" : "FLOWED_TO|SWAPPED";
619
- const routeQuery = (fromAddress, toAddress) => [
620
- `MATCH p = SHORTEST 1 (a:Address {address: "${escapeCypherString(fromAddress)}"} WHERE ${walkGuardTerms(["a"], 2)})`,
621
- ` (()-[:${links}]-(via:Address) WHERE ${walkGuardTerms(["via"], 2)}){0,${CONNECTION_ROUTE_DEPTH_BOUND}}`,
622
- ` ()-[:${links}]-(b:Address {address: "${escapeCypherString(toAddress)}"}) RETURN p LIMIT 1`
623
- ].join("");
624
- return [{
625
- id: "connection_route_outbound",
626
- query: routeQuery(address, compareAddress)
627
- }, {
628
- id: "connection_route_inbound",
629
- query: routeQuery(compareAddress, address)
630
- }];
631
- }
632
- function collectOrdered(value, matches) {
633
- const collected = [];
634
- const walk = (node) => {
635
- if (Array.isArray(node)) {
636
- for (const entry of node) walk(entry);
637
- return;
638
- }
639
- if (node && typeof node === "object") {
640
- const candidate = node;
641
- if (matches(candidate)) collected.push(candidate);
642
- for (const nested of Object.values(candidate)) walk(nested);
643
- }
644
- };
645
- walk(value);
646
- return collected;
647
- }
648
- function isExchangeMarker(value) {
649
- if (value === null || value === void 0 || value === false) return false;
650
- if (typeof value === "number") return value !== 0;
651
- if (typeof value === "string") {
652
- const normalized = value.trim().toLowerCase();
653
- return normalized !== "" && normalized !== "false" && normalized !== "0" && normalized !== "null";
654
- }
655
- return value === true;
656
- }
657
- function routeFromPathValue(value) {
658
- if (!value || typeof value !== "object") return null;
659
- const nodes = collectOrdered(value, (candidate) => typeof candidate["address"] === "string");
660
- if (nodes.length < 2) return null;
661
- const edges = collectOrdered(value, (candidate) => typeof candidate["amount_usd_sum"] === "number" && !("address" in candidate));
662
- const identities = nodes.map((node) => String(node["address"]));
663
- const exchangeIntermediates = nodes.slice(1, -1).filter((node) => isExchangeMarker(node["is_exchange"])).map((node) => String(node["address"]));
664
- return {
665
- hops: nodes.length - 1,
666
- identities,
667
- exchange_intermediates: exchangeIntermediates,
668
- links_addresses: exchangeIntermediates.length === 0,
669
- amount_usd_sum_total: edges.reduce((total, edge) => total + Number(edge["amount_usd_sum"]), 0)
670
- };
671
- }
672
- function buildRouteEvidence(outboundRows, inboundRows) {
673
- const sideFrom = (rows) => {
674
- const first = rows[0];
675
- if (!first) return null;
676
- return routeFromPathValue("p" in first ? first["p"] : Object.values(first)[0]);
677
- };
678
- const outbound = sideFrom(outboundRows);
679
- const inbound = sideFrom(inboundRows);
680
- return {
681
- search_strategy: "any_shortest",
682
- route_rank_basis: "hop_count",
683
- depth_bound: CONNECTION_ROUTE_MAX_HOPS,
684
- route_found: outbound !== null || inbound !== null,
685
- linked_outside_exchanges: [outbound, inbound].some((side) => side !== null && side.links_addresses),
686
- outbound,
687
- inbound
688
- };
689
- }
690
- function formatExchangeRows(rows) {
691
- return rows.map((row) => {
692
- const direction = String(row["direction"] ?? "flow");
693
- const exchangeAddress = String(row["exchange_address"] ?? "");
694
- const amount = row["amount_usd_sum"] ?? "";
695
- const hops = row["hops"] ?? "";
696
- const exchangeId = typeof row["exchange"] === "string" ? row["exchange"] : void 0;
697
- const role = typeof row["exchange_role"] === "string" ? row["exchange_role"] : "exchange";
698
- const named = exchangeId ? `${exchangeId} ${role.replace(/_/g, " ")}` : void 0;
699
- const base = `- ${direction}: ${exchangeAddress}${named ? ` (${named})` : ""} (${hops} hop(s), amount_usd_sum ${amount})`;
700
- if (direction !== "outflow" || role !== "deposit") return base;
701
- const swept = Array.isArray(row["swept_into"]) ? row["swept_into"] : [];
702
- if (swept.length > 0) {
703
- const into = swept.map((link) => `hot wallet ${link.hot_wallet}${link.hot_wallet_exchange ? ` (${link.hot_wallet_exchange})` : ""}, ${link.sweep_count ?? "?"} sweep(s)`).join("; ");
704
- return `${base}: the money entered ${exchangeId ?? "the exchange"} at this deposit, swept into ${into}. The trail ends here.`;
705
- }
706
- return row["swept_status"] === "read" ? `${base}: the money entered ${exchangeId ?? "the exchange"} at this deposit; the graph holds no SWEPT link of it yet. The trail ends here.` : `${base}: the money entered ${exchangeId ?? "the exchange"} at this deposit; its SWEPT link was not read, call aml_exchange_deposit_check for the hot wallet. The trail ends here.`;
707
- });
708
- }
709
- function numberValue(value) {
710
- if (typeof value === "number" && Number.isFinite(value)) return value;
711
- if (typeof value === "string" && value.trim()) {
712
- const parsed = Number(value);
713
- return Number.isFinite(parsed) ? parsed : void 0;
714
- }
715
- }
716
- function firstNumber(...values) {
717
- for (const value of values) {
718
- const parsed = numberValue(value);
719
- if (parsed !== void 0) return parsed;
720
- }
721
- }
722
- function firstString(...values) {
723
- for (const value of values) if (typeof value === "string" && value.trim()) return value.trim();
724
- }
725
- function riskLevelFromScore(score) {
726
- if (score >= .85) return "critical";
727
- if (score >= .7) return "high";
728
- if (score >= .4) return "medium";
729
- return "low";
730
- }
731
- function riskRecommendation(level) {
732
- if (level === "critical" || level === "high") return "Escalate for manual review.";
733
- if (level === "medium") return "Review exchange exposure and counterparties before clearing.";
734
- return "No stored risk signal found; continue with normal monitoring.";
735
- }
736
- function riskDrivers(profile, labelRows, exchangeRows) {
737
- const drivers = [];
738
- const riskLabels = labelRows.map((row) => firstString(row["label"])).filter((label) => Boolean(label));
739
- if (riskLabels.length > 0) drivers.push(`Labels: ${[...new Set(riskLabels)].join("; ")}`);
740
- const outflowCount = exchangeRows.filter((row) => row["direction"] === "outflow").length;
741
- const inflowCount = exchangeRows.filter((row) => row["direction"] === "inflow").length;
742
- if (outflowCount > 0) drivers.push(`Forward bounded search reached ${outflowCount} exchange path(s).`);
743
- if (inflowCount > 0) drivers.push(`Backward bounded search found ${inflowCount} source exchange path(s).`);
744
- return [...new Set(drivers)];
745
- }
746
- function deriveLabelRows(profile) {
747
- const labels = Array.isArray(profile["label_risk_labels"]) ? profile["label_risk_labels"].map((value) => String(value)) : [];
748
- const riskLevels = Array.isArray(profile["label_risk_levels"]) ? profile["label_risk_levels"].map((value) => String(value)) : [];
749
- const timestamps = Array.isArray(profile["label_risk_updated_timestamps"]) ? profile["label_risk_updated_timestamps"].map((value) => numberValue(value)) : [];
750
- return [...labels.map((label, index) => ({
751
- label,
752
- risk_level: riskLevels[index] ?? "",
753
- updated_timestamp: timestamps[index] ?? 0
754
- }))].sort((a, b) => (numberValue(b["updated_timestamp"]) ?? 0) - (numberValue(a["updated_timestamp"]) ?? 0)).slice(0, 10);
755
- }
756
- const RISK_LEVEL_ORDER = [
757
- "critical",
758
- "high",
759
- "medium",
760
- "low"
761
- ];
762
- function strongestLabelRiskLevel(labelRows) {
763
- const levels = labelRows.map((row) => firstString(row["risk_level"])?.toLowerCase()).filter((level) => Boolean(level && RISK_LEVEL_ORDER.includes(level)));
764
- if (levels.length === 0) return void 0;
765
- return RISK_LEVEL_ORDER.find((candidate) => levels.includes(candidate));
766
- }
767
- function riskScoreSources(profile, labelRows) {
768
- const sources = [];
769
- if (numberValue(profile["live_risk_score"]) !== void 0) sources.push({
770
- family: "ml_risk_score",
771
- layer: "topology",
772
- source: "address_node",
773
- fields: ["risk_score", "risk_level"]
774
- });
775
- if (labelRows.length > 0) sources.push({
776
- family: "label_risk",
777
- layer: "topology",
778
- source: "address_node",
779
- labels: labelRows.map((row) => ({
780
- label: row["label"],
781
- risk_level: row["risk_level"]
782
- }))
783
- });
784
- return sources;
785
- }
786
- function terminalEdgeProperties(row) {
787
- const edgeProps = Array.isArray(row["edge_props"]) ? row["edge_props"] : [];
788
- return edgeProps[edgeProps.length - 1];
789
- }
790
- function enrichExchangeRows(rows) {
791
- return rows.map((row) => {
792
- const terminal = terminalEdgeProperties(row);
793
- if (!terminal) return row;
794
- return {
795
- ...row,
796
- amount_usd_sum: row["amount_usd_sum"] ?? terminal["amount_usd_sum"],
797
- tx_count: row["tx_count"] ?? terminal["tx_count"],
798
- first_seen_timestamp: row["first_seen_timestamp"] ?? terminal["first_seen_timestamp"],
799
- last_seen_timestamp: row["last_seen_timestamp"] ?? terminal["last_seen_timestamp"]
800
- };
801
- });
802
- }
803
- const FALLBACK_SHARED_TX_COUNT = 1e3;
804
- const FALLBACK_SHARED_USD_SUM = 5e6;
805
- const FALLBACK_SHARED_DAMPING = .1;
806
- const FALLBACK_VALUE_SATURATION_USD = 1e6;
807
- const FALLBACK_BASE_SCORE = .1;
808
- const FALLBACK_MAX_SCORE = .6;
809
- /**
810
- * Score exchange exposure when no ML risk score exists. Topology-grain:
811
- * log-scaled USD volume across exchange rows, with shared/omnibus edges
812
- * (high tx_count or USD throughput) dampened, bounded in (0, 0.6] so a
813
- * fallback can never impersonate a high ML score band.
814
- */
815
- function exchangeExposureFallbackScore(exchangeRows) {
816
- if (exchangeRows.length === 0) return 0;
817
- let weightedUsd = 0;
818
- for (const row of exchangeRows) {
819
- const usd = numberValue(row["amount_usd_sum"]) ?? 0;
820
- const shared = (numberValue(row["tx_count"]) ?? 0) >= FALLBACK_SHARED_TX_COUNT || usd >= FALLBACK_SHARED_USD_SUM;
821
- weightedUsd += shared ? usd * FALLBACK_SHARED_DAMPING : usd;
822
- }
823
- const factor = Math.log10(1 + Math.min(weightedUsd, FALLBACK_VALUE_SATURATION_USD)) / Math.log10(1000001);
824
- return Math.min(FALLBACK_MAX_SCORE, FALLBACK_BASE_SCORE + .5 * factor);
825
- }
826
- function riskAssessment(profile, labelRows, exchangeRows) {
827
- const mlRiskScore = firstNumber(profile["live_risk_score"]);
828
- const mlAbstained = isUnscoredRiskLevel(profile["live_risk_level"]);
829
- const labelRiskLevel = strongestLabelRiskLevel(labelRows);
830
- const usableMlScore = mlAbstained ? void 0 : mlRiskScore;
831
- const score = usableMlScore ?? exchangeExposureFallbackScore(exchangeRows);
832
- let level = labelRiskLevel ?? (mlAbstained && exchangeRows.length === 0 ? "unscored" : riskLevelFromScore(score));
833
- const drivers = riskDrivers(profile, labelRows, exchangeRows);
834
- if (mlAbstained) drivers.push("ml_abstained: ML verdict is UNSCORED (insufficient labeled graph context); level derived from labels/exchange exposure only");
835
- const usableMlBand = usableMlScore !== void 0 ? riskLevelFromScore(usableMlScore) : void 0;
836
- if (labelRiskLevel && usableMlBand && riskSeverityRank(usableMlBand) > riskSeverityRank(labelRiskLevel)) {
837
- level = usableMlBand;
838
- drivers.push(`ml_label_divergence: usable ML band ${usableMlBand} exceeds strongest label level ${labelRiskLevel}; reporting the more severe band — review the label`);
839
- }
840
- return {
841
- level,
842
- score,
843
- ...mlRiskScore !== void 0 ? { ml_risk_score: mlRiskScore } : {},
844
- ...mlAbstained ? { ml_verdict: "unscored" } : {},
845
- confidence: usableMlScore !== void 0 || labelRiskLevel ? "high" : exchangeRows.length > 0 ? "medium" : "low",
846
- recommendation: level === "unscored" ? "Model abstained and no label/exchange signal found; gather more context before clearing." : riskRecommendation(level),
847
- drivers,
848
- sources: riskScoreSources(profile, labelRows)
849
- };
850
- }
851
- function formatRiskScore(score) {
852
- const parsed = numberValue(score);
853
- if (parsed === void 0) return String(score ?? "unknown");
854
- return Number.isInteger(parsed) ? parsed.toString() : parsed.toFixed(2);
855
- }
856
- function stringArrayValue(value) {
857
- if (Array.isArray(value)) return value.map(String);
858
- if (typeof value === "string" && value.trim()) return [value];
859
- }
860
- function restoreSystemLabels(graph, rawNodes) {
861
- if (!Array.isArray(graph["nodes"])) return graph;
862
- const labelsByAddress = new Map(rawNodes.map((node) => [typeof node["address"] === "string" ? node["address"] : typeof node["id"] === "string" ? node["id"] : "", stringArrayValue(node["system_labels"])]).filter((entry) => Boolean(entry[0]) && Array.isArray(entry[1]) && entry[1].length > 0));
863
- return {
864
- ...graph,
865
- nodes: graph["nodes"].map((node) => {
866
- if (typeof node !== "object" || node === null || Array.isArray(node)) return node;
867
- const record = node;
868
- const address = typeof record["address"] === "string" ? record["address"] : typeof record["id"] === "string" ? record["id"] : "";
869
- const systemLabels = labelsByAddress.get(address);
870
- return systemLabels ? {
871
- ...record,
872
- system_labels: systemLabels
873
- } : record;
874
- })
875
- };
876
- }
877
- function buildRiskGraph(address, profile, rows, network) {
878
- const nodes = /* @__PURE__ */ new Map();
879
- nodes.set(address, {
880
- id: address,
881
- address,
882
- node_type: "address",
883
- labels: stringArrayValue(profile["display_labels"]) ?? [],
884
- ...stringArrayValue(profile["system_labels"]) ? { system_labels: stringArrayValue(profile["system_labels"]) } : {},
885
- ...stringArrayValue(profile["member_addresses"])?.length ? { member_addresses: stringArrayValue(profile["member_addresses"]) } : {},
886
- ...numberValue(profile["live_risk_score"]) !== void 0 ? { risk_score: numberValue(profile["live_risk_score"]) } : {},
887
- ...firstString(profile["live_risk_level"]) ? { risk_level: firstString(profile["live_risk_level"]) } : {},
888
- roles: ["subject"]
889
- });
890
- const edges = [];
891
- const mergeNode = (entry, metadata) => {
892
- const existing = nodes.get(entry) ?? {
893
- id: entry,
894
- address: entry,
895
- node_type: "address",
896
- labels: []
897
- };
898
- const labels = stringArrayValue(metadata?.["labels"]) ?? existing["labels"];
899
- const systemLabels = stringArrayValue(metadata?.["system_labels"]) ?? existing["system_labels"];
900
- const memberAddresses = stringArrayValue(metadata?.["member_addresses"]) ?? existing["member_addresses"];
901
- const riskScore = numberValue(metadata?.["risk_score"]) ?? existing["risk_score"];
902
- const riskLevel = normalizeRiskLevel(firstString(metadata?.["risk_level"])) ?? existing["risk_level"];
903
- nodes.set(entry, {
904
- ...existing,
905
- labels,
906
- ...systemLabels ? { system_labels: systemLabels } : {},
907
- ...Array.isArray(memberAddresses) && memberAddresses.length > 0 ? { member_addresses: memberAddresses } : {},
908
- ...riskScore !== void 0 ? { risk_score: riskScore } : {},
909
- ...riskLevel ? { risk_level: riskLevel } : {}
910
- });
911
- };
912
- for (const row of rows) {
913
- const rawPath = Array.isArray(row["path"]) ? row["path"] : row["addresses"];
914
- const path = Array.isArray(rawPath) ? rawPath.map(String) : [];
915
- const pathNodes = Array.isArray(row["path_nodes"]) ? row["path_nodes"] : [];
916
- for (let index = 0; index < path.length; index += 1) {
917
- const entry = path[index];
918
- mergeNode(entry, pathNodes[index]);
919
- }
920
- const exchange = typeof row["exchange_address"] === "string" ? row["exchange_address"] : "";
921
- if (exchange) {
922
- const displayLabels = stringArrayValue(row["exchange_display_labels"]) ?? [];
923
- const systemLabels = stringArrayValue(row["exchange_system_labels"]) ?? stringArrayValue(row["exchange_labels"]) ?? [];
924
- nodes.set(exchange, {
925
- id: exchange,
926
- address: exchange,
927
- node_type: "address",
928
- labels: displayLabels,
929
- ...systemLabels.length > 0 ? { system_labels: systemLabels } : {},
930
- roles: row["exchange_role"] === "deposit" || row["exchange_role"] === "hot_wallet" || row["exchange_role"] === "cold_wallet" || row["exchange_role"] === "withdrawal" ? ["exchange", String(row["exchange_role"])] : ["exchange"]
931
- });
932
- const swept = Array.isArray(row["swept_into"]) ? row["swept_into"] : [];
933
- for (const link of swept) {
934
- if (!nodes.has(link.hot_wallet)) nodes.set(link.hot_wallet, {
935
- id: link.hot_wallet,
936
- address: link.hot_wallet,
937
- node_type: "address",
938
- labels: link.hot_wallet_exchange ? ["Exchange", link.hot_wallet_exchange] : ["Exchange"],
939
- roles: ["exchange", link.hot_wallet_role ?? "hot_wallet"]
940
- });
941
- edges.push({
942
- source: exchange,
943
- target: link.hot_wallet,
944
- edge_type: "swept",
945
- usd_amount: link.amount_usd_sum ?? 0,
946
- amount_usd_sum: link.amount_usd_sum ?? 0,
947
- tx_count: link.sweep_count ?? 0,
948
- direction: "outflow"
949
- });
950
- }
951
- }
952
- for (let index = 0; index < path.length - 1; index += 1) {
953
- const edge = (Array.isArray(row["edge_props"]) ? row["edge_props"] : [])[index] ?? row;
954
- edges.push({
955
- source: path[index],
956
- target: path[index + 1],
957
- edge_type: "flowed_to",
958
- usd_amount: edge["amount_usd_sum"] ?? 0,
959
- amount_usd_sum: edge["amount_usd_sum"] ?? 0,
960
- tx_count: edge["tx_count"] ?? 0,
961
- direction: row["direction"]
962
- });
963
- }
964
- }
965
- const rawNodes = [...nodes.values()];
966
- return restoreSystemLabels(normalizeGraphPayload({
967
- schema: "chain-insights.graph.v1",
968
- nodes: rawNodes,
969
- edges,
970
- flows: [],
971
- edge_anchors: [],
972
- metadata: {
973
- address,
974
- network,
975
- generated_at: (/* @__PURE__ */ new Date()).toISOString()
976
- }
977
- }), rawNodes);
978
- }
979
- async function addressRisk(remoteClient, options) {
980
- const address = options.address.trim();
981
- const network = options.network.trim();
982
- const compareInput = options.compareAddress?.trim() ?? "";
983
- if (!address) throw new Error("address is required");
984
- if (!network) throw new Error("network is required");
985
- const usage = createUsageAccumulator();
986
- const trackedClient = wrapClientForUsageTracking(remoteClient, usage);
987
- let compareUnresolved = false;
988
- if (compareInput) compareUnresolved = !firstString(optionalResultsFor(await callGraphBatch(trackedClient, network, [compareAddressExistsQuery(compareInput)]), "compare_address_exists", [])[0]?.["address"]);
989
- const compareAddress = compareInput && !compareUnresolved ? compareInput : "";
990
- const batch = await callGraphBatch(trackedClient, network, [
991
- addressProfileQuery(address),
992
- addressFeatureQuery(address),
993
- {
994
- id: "money_trail_incident",
995
- query: moneyTrailIncidentQuery(address)
996
- },
997
- ...exchangeOutflowQueries(address),
998
- ...exchangeInflowQueries(address),
999
- ...compareAddress ? [connectionProbeQuery(address, compareAddress)] : [{
1000
- id: "connection_probe",
1001
- query: "MATCH (n:Address {address: \"__chain_insights_noop__\"}) RETURN n.address AS noop LIMIT 0"
1002
- }],
1003
- ...shouldIncludeRouteQueries(compareAddress) ? connectionRouteQueries(address, compareAddress, options.linkShape ?? await require_capabilities.readSwapLinkShape(remoteClient, network) ?? "route") : []
1004
- ]);
1005
- const partialQueryFailures = [];
1006
- const addressProfileRows = optionalResultsFor(batch, "address_profile", partialQueryFailures);
1007
- if (addressProfileRows.length === 0) return {
1008
- summaryText: `Address risk for ${network}:${address}\n\nUnresolved: no Address found for "${address}". The address may not have on-chain activity in this network.`,
1009
- structuredContent: {
1010
- schema: "chain-insights.result.v1",
1011
- tool: "aml_address_risk",
1012
- facts: {
1013
- subject: {
1014
- network,
1015
- addresses: [address]
1016
- },
1017
- unresolved: [address],
1018
- usage: usageBlock(usage)
1019
- }
1020
- },
1021
- graphData: {
1022
- schema: "chain-insights.graph.v1",
1023
- nodes: [],
1024
- edges: [],
1025
- flows: [],
1026
- edge_anchors: [],
1027
- metadata: {
1028
- address,
1029
- network,
1030
- generated_at: (/* @__PURE__ */ new Date()).toISOString()
1031
- }
1032
- }
1033
- };
1034
- const profile = {
1035
- address,
1036
- ...addressProfileRows[0] ?? {},
1037
- ...optionalResultsFor(batch, "address_feature", partialQueryFailures)[0] ?? {}
1038
- };
1039
- const labelRows = deriveLabelRows(profile);
1040
- const resolvedOutflows = enrichExchangeRows(optionalResultsWithPrefix(batch, "exchange_outflows_", partialQueryFailures)).map(resolveExchangeEnd);
1041
- const inflows = enrichExchangeRows(optionalResultsWithPrefix(batch, "exchange_inflows_", partialQueryFailures)).map(resolveExchangeEnd);
1042
- const depositEnds = exchangeDepositEnds(resolvedOutflows);
1043
- let sweptRows = [];
1044
- let sweptRead = [];
1045
- if (depositEnds.length > 0) {
1046
- const sweptQueries = depositEnds.map(exchangeDepositSweptQuery);
1047
- try {
1048
- const sweptBatch = await callGraphBatch(trackedClient, network, sweptQueries);
1049
- sweptRead = depositEnds.filter((_, index) => (sweptBatch.facts?.queries ?? []).some((entry) => entry.id === sweptQueries[index].id && entry.ok !== false));
1050
- sweptRows = optionalResultsWithPrefix(sweptBatch, "exchange_deposit_swept_", partialQueryFailures);
1051
- } catch (error) {
1052
- collectQueryFailure(partialQueryFailures, "exchange_deposit_swept", error instanceof Error ? error.message : String(error));
1053
- }
1054
- }
1055
- const outflows = attachSweptHotWallets(resolvedOutflows, sweptRows, sweptRead);
1056
- const connections = compareAddress ? optionalResultsFor(batch, "connection_probe", partialQueryFailures) : [];
1057
- const routeEvidence = shouldIncludeRouteQueries(compareAddress) ? buildRouteEvidence(optionalResultsFor(batch, "connection_route_outbound", partialQueryFailures), optionalResultsFor(batch, "connection_route_inbound", partialQueryFailures)) : void 0;
1058
- const exchangeRows = [...outflows, ...inflows];
1059
- const exchangeSearchFailures = partialQueryFailures.filter((failure) => failure.id.startsWith("exchange_outflows_") || failure.id.startsWith("exchange_inflows_"));
1060
- const exchangeSearchComplete = exchangeSearchFailures.length === 0;
1061
- const moneyTrailIncidentRows = optionalResultsFor(batch, "money_trail_incident", partialQueryFailures);
1062
- const preliminaryMoneyTrail = buildMoneyTrailBlock(moneyTrailIncidentRows, []);
1063
- let moneyTrailEndRows = [];
1064
- if (preliminaryMoneyTrail?.primary_seed) try {
1065
- moneyTrailEndRows = optionalResultsFor(await callGraphBatch(trackedClient, network, [{
1066
- id: "money_trail_ends",
1067
- query: moneyTrailEndsQuery(preliminaryMoneyTrail.primary_seed)
1068
- }]), "money_trail_ends", partialQueryFailures);
1069
- } catch (error) {
1070
- collectQueryFailure(partialQueryFailures, "money_trail_ends", error instanceof Error ? error.message : String(error));
1071
- }
1072
- const moneyTrail = buildMoneyTrailBlock(moneyTrailIncidentRows, moneyTrailEndRows);
1073
- const graphData = buildRiskGraph(address, profile, exchangeRows, network);
1074
- const risk = riskAssessment(profile, labelRows, exchangeRows);
1075
- const liveRiskScore = numberValue(profile["live_risk_score"]);
1076
- const liveRiskLevel = firstString(profile["live_risk_level"]);
1077
- const liveNodeVerdict = liveRiskScore !== void 0 || liveRiskLevel ? {
1078
- ...liveRiskScore !== void 0 ? { risk_score: liveRiskScore } : {},
1079
- ...liveRiskLevel ? { risk_level: liveRiskLevel } : {},
1080
- source: "topology_node"
1081
- } : void 0;
1082
- const lines = [
1083
- `Address risk for ${network}:${address}`,
1084
- "",
1085
- `Risk: ${risk["level"]} (${formatRiskScore(risk["score"])})`,
1086
- `Confidence: ${risk["confidence"]}`,
1087
- `Recommendation: ${risk["recommendation"]}`,
1088
- ...liveNodeVerdict ? [`Live node triage: ${liveRiskLevel ?? "unknown"} (${formatRiskScore(liveRiskScore)})`] : [],
1089
- `Graph degree: in ${profile["degree_in"] ?? "unknown"}, out ${profile["degree_out"] ?? "unknown"}.`,
1090
- "",
1091
- "Exchange behavior",
1092
- ...exchangeRows.length > 0 ? [formatExchangeRows(exchangeRows).join("\n"), ...exchangeSearchComplete ? [] : [`(incomplete: ${exchangeSearchFailures.length} other hop-depth quer${exchangeSearchFailures.length === 1 ? "y" : "ies"} failed -- there may be more exchange exposure than shown here)`]] : [exchangeSearchComplete ? "- No exchange inflow/outflow paths found in bounded search." : `- Exchange search incomplete: ${exchangeSearchFailures.length} hop-depth quer${exchangeSearchFailures.length === 1 ? "y" : "ies"} failed before returning a result. This is NOT a clean finding -- retry or narrow the search (see Partial query failures below).`]
1093
- ];
1094
- if (Array.isArray(risk["drivers"]) && risk["drivers"].length > 0) lines.push("", "Risk drivers", risk["drivers"].map((driver) => `- ${driver}`).join("\n"));
1095
- if (moneyTrail) lines.push("", moneyTrailSummarySentence(moneyTrail));
1096
- if (compareAddress) {
1097
- lines.push("", `Connection compare target: ${compareAddress}`, connections.length > 0 ? `Connection paths found: ${connections.length}` : "Connection paths found: 0");
1098
- const exchangeCrossings = [routeEvidence?.outbound, routeEvidence?.inbound].flatMap((side) => side?.exchange_intermediates ?? []);
1099
- if (routeEvidence?.route_found && !routeEvidence.linked_outside_exchanges) lines.push(`Shortest route passes through exchange address ${[...new Set(exchangeCrossings)].join(", ")}: past an exchange are its other customers, so this route links nothing.`);
1100
- }
1101
- if (compareUnresolved) lines.push("", `Unresolved compare_address: no Address found for "${compareInput}"; comparison skipped.`);
1102
- if (partialQueryFailures.length > 0) lines.push("", "Partial query failures", partialQueryFailures.map((failure) => `- ${failure.id}: ${failure.error}`).join("\n"));
1103
- const summaryText = lines.join("\n");
1104
- const structuredContent = {
1105
- schema: "chain-insights.result.v1",
1106
- tool: "aml_address_risk",
1107
- facts: {
1108
- subject: {
1109
- network,
1110
- addresses: compareAddress ? [address, compareAddress] : [address]
1111
- },
1112
- risk: {
1113
- ...risk,
1114
- ...liveNodeVerdict ? { live_node: liveNodeVerdict } : {}
1115
- },
1116
- exchange_behavior: {
1117
- outflows,
1118
- inflows,
1119
- search_status: exchangeSearchComplete ? "complete" : "incomplete",
1120
- ...exchangeSearchComplete ? {} : { failed_query_ids: exchangeSearchFailures.map((failure) => failure.id) }
1121
- },
1122
- connection: compareAddress ? {
1123
- compare_address: compareAddress,
1124
- paths: connections,
1125
- ...routeEvidence ? { route_evidence: routeEvidence } : {}
1126
- } : void 0,
1127
- money_trail: moneyTrail,
1128
- unresolved: compareUnresolved ? [compareInput] : void 0,
1129
- partial_query_errors: partialQueryFailures.length > 0 ? partialQueryFailures : void 0,
1130
- usage: usageBlock(usage)
1131
- }
1132
- };
1133
- const artifacts = options.writeArtifacts ? await writeAddressRiskArtifacts(network, address, compareAddress, graphData, exchangeRows, summaryText) : statelessArtifacts();
1134
- const evidence = artifactEvidence(artifacts);
1135
- return {
1136
- summaryText,
1137
- structuredContent: {
1138
- ...structuredContent,
1139
- artifacts,
1140
- evidence: [...evidence, {
1141
- evidence_type: "tool_summary",
1142
- summary: `aml_address_risk ${address} completed for ${network}`
1143
- }]
1144
- },
1145
- graphData
1146
- };
1147
- }
1148
- /**
1149
- * Routes the public AML tool contract to the requested implementation. An
1150
- * omitted version always follows the latest supported contract.
1151
- */
1152
- async function runAmlAddressRisk(remoteClient, options, requestedVersion) {
1153
- const version = resolveAmlAddressRiskVersion(requestedVersion);
1154
- switch (version) {
1155
- case "v1": {
1156
- const result = await addressRisk(remoteClient, options);
1157
- return {
1158
- ...result,
1159
- structuredContent: {
1160
- ...result.structuredContent,
1161
- tool_version: version
1162
- }
1163
- };
1164
- }
1165
- }
1166
- }
1167
- function toCsvValue(value) {
1168
- return value === void 0 || value === null ? "" : String(value);
1169
- }
1170
- function subjectNodeForExchangeRow(row, fallbackAddress) {
1171
- return String(row["direction"] === "inflow" ? row["withdrawal_address"] ?? row["deposit_address"] ?? fallbackAddress : row["payer_address"] ?? row["deposit_address"] ?? row["withdrawal_address"] ?? fallbackAddress);
1172
- }
1173
- function sweptIntoCell(row) {
1174
- return (Array.isArray(row["swept_into"]) ? row["swept_into"] : []).map((link) => link.hot_wallet).join(";");
1175
- }
1176
- function buildAddressRiskTableHtml(tool, network, rows, subject) {
1177
- const headers = [
1178
- "direction",
1179
- "exchange",
1180
- "exchange_role",
1181
- "exchange_address",
1182
- "swept_into_hot_wallet",
1183
- "subject_path_node",
1184
- "hops",
1185
- "amount_usd_sum",
1186
- "tx_count"
1187
- ];
1188
- const body = rows.map((row) => {
1189
- const exchangeAddress = String(row["exchange_address"] ?? "");
1190
- const subjectNode = subjectNodeForExchangeRow(row, subject);
1191
- return `<tr>${[
1192
- row["direction"] ?? "",
1193
- row["exchange"] ?? "",
1194
- row["exchange_role"] ?? "",
1195
- exchangeAddress,
1196
- sweptIntoCell(row),
1197
- subjectNode,
1198
- row["hops"] ?? "",
1199
- row["amount_usd_sum"] ?? "",
1200
- row["tx_count"] ?? ""
1201
- ].map((value) => `<td>${htmlEscape(toCsvValue(value))}</td>`).join("")}</tr>`;
1202
- }).join("\n");
1203
- return `<!doctype html>
1204
- <html lang="en">
1205
- <head>
1206
- <meta charset="utf-8">
1207
- <meta name="viewport" content="width=device-width, initial-scale=1">
1208
- <title>${htmlEscape(tool)} Risk Table</title>
1209
- <style>
1210
- :root { color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui; background: #0b0d12; color: #f4f2ea; }
1211
- body { margin: 0; background: #0b0d12; color: #f4f2ea; }
1212
- main { padding: 24px; }
1213
- h1 { font-size: 20px; margin: 0 0 8px; font-weight: 650; }
1214
- table { border-collapse: collapse; width: 100%; min-width: 900px; }
1215
- th, td { border-bottom: 1px solid rgba(255,255,255,.08); padding: 8px 10px; text-align: left; }
1216
- th { position: sticky; top: 0; background: #161a24; color: #f2dda6; font-weight: 600; }
1217
- </style>
1218
- </head>
1219
- <body>
1220
- <main>
1221
- <h1>${htmlEscape(tool)} Table</h1>
1222
- <div>Network: <strong>${htmlEscape(network)}</strong></div>
1223
- <div>Generated: <strong>${htmlEscape((/* @__PURE__ */ new Date()).toISOString())}</strong></div>
1224
- <table>
1225
- <thead><tr>${headers.map((header) => `<th>${htmlEscape(header)}</th>`).join("")}</tr></thead>
1226
- <tbody>${body}</tbody>
1227
- </table>
1228
- </main>
1229
- </body>
1230
- </html>
1231
- `;
1232
- }
1233
- async function writeAddressRiskArtifacts(network, address, compareAddress, graphData, exchangeRows, summaryText) {
1234
- const paths = workspaceOutputPaths();
1235
- await Promise.all([
1236
- (0, node_fs_promises.mkdir)(paths.reportsRoot, { recursive: true }),
1237
- (0, node_fs_promises.mkdir)(paths.reportGraphsRoot, { recursive: true }),
1238
- (0, node_fs_promises.mkdir)(paths.reportTablesRoot, { recursive: true })
1239
- ]);
1240
- const safeNetwork = network.replace(/[^A-Za-z0-9._-]+/g, "_");
1241
- const safeAddress = address.replace(/[^A-Za-z0-9._-]+/g, "_");
1242
- const slug = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z")}_aml_address_risk_${safeNetwork}_${safeAddress}`;
1243
- const graphPath = node_path.default.join(paths.reportGraphsRoot, `${slug}.graph.json`);
1244
- const tableJsonPath = node_path.default.join(paths.reportTablesRoot, `${slug}.compact-evidence.json`);
1245
- const csvPath = node_path.default.join(paths.reportTablesRoot, `${slug}.flows.csv`);
1246
- const tableHtmlPath = node_path.default.join(paths.reportsRoot, `${slug}.table.html`);
1247
- const reportPath = node_path.default.join(paths.reportsRoot, `${slug}.aml-address-report.md`);
1248
- const csv = [[
1249
- "direction",
1250
- "exchange",
1251
- "exchange_role",
1252
- "exchange_address",
1253
- "swept_into_hot_wallet",
1254
- "subject_path_node",
1255
- "hops",
1256
- "amount_usd_sum",
1257
- "tx_count"
1258
- ].join(","), ...exchangeRows.map((row) => {
1259
- const exchangeAddress = String(row["exchange_address"] ?? "");
1260
- const subjectPathNode = subjectNodeForExchangeRow(row, address);
1261
- return [
1262
- row["direction"] ?? "",
1263
- row["exchange"] ?? "",
1264
- row["exchange_role"] ?? "",
1265
- exchangeAddress,
1266
- sweptIntoCell(row),
1267
- subjectPathNode,
1268
- row["hops"] ?? "",
1269
- row["amount_usd_sum"] ?? "",
1270
- row["tx_count"] ?? ""
1271
- ].map((value) => JSON.stringify(String(value))).join(",");
1272
- })].join("\n") + "\n";
1273
- const evidence = {
1274
- schema: "chain-insights.trace.v1",
1275
- tool: "aml_address_risk",
1276
- network,
1277
- input: {
1278
- address,
1279
- ...compareAddress ? { compare_address: compareAddress } : {}
1280
- },
1281
- profile: {
1282
- exchange_rows: exchangeRows.map((row) => ({
1283
- direction: row["direction"],
1284
- exchange: row["exchange"],
1285
- exchange_role: row["exchange_role"],
1286
- exchange_address: row["exchange_address"],
1287
- ...Array.isArray(row["swept_into"]) ? { swept_into: row["swept_into"] } : {},
1288
- subject_node: subjectNodeForExchangeRow(row, address),
1289
- hops: row["hops"],
1290
- amount_usd_sum: row["amount_usd_sum"],
1291
- tx_count: row["tx_count"]
1292
- })),
1293
- report_summary: summaryText
1294
- }
1295
- };
1296
- await (0, node_fs_promises.writeFile)(graphPath, JSON.stringify(graphData, null, 2) + "\n", { mode: 384 });
1297
- await (0, node_fs_promises.writeFile)(tableJsonPath, JSON.stringify(evidence, null, 2) + "\n", { mode: 384 });
1298
- await (0, node_fs_promises.writeFile)(csvPath, csv, { mode: 384 });
1299
- await (0, node_fs_promises.writeFile)(tableHtmlPath, buildAddressRiskTableHtml("aml_address_risk", network, exchangeRows, address), { mode: 384 });
1300
- await (0, node_fs_promises.writeFile)(reportPath, [
1301
- `# Address Risk Report (${network}:${address})`,
1302
- `- Graph JSON: ${graphPath}`,
1303
- `- Table JSON: ${tableJsonPath}`,
1304
- `- CSV: ${csvPath}`,
1305
- `- Report HTML: ${tableHtmlPath}`,
1306
- "",
1307
- summaryText
1308
- ].join("\n"), { mode: 384 });
1309
- return {
1310
- graph_json: graphPath,
1311
- table_json: tableJsonPath,
1312
- flows_csv: csvPath,
1313
- table_html: tableHtmlPath,
1314
- report_md: reportPath
1315
- };
1316
- }
1317
- function statelessArtifacts() {
1318
- return {
1319
- artifacts_written: false,
1320
- artifact_mode: "stateless"
1321
- };
1322
- }
1323
- function artifactEvidence(artifacts) {
1324
- return Object.entries(artifacts).filter((entry) => entry[0] !== "artifact_mode" && typeof entry[1] === "string" && entry[1].length > 0).map(([kind, filePath]) => ({
1325
- evidence_type: "artifact_pointer",
1326
- path: filePath,
1327
- summary: `${kind} artifact`
1328
- }));
1329
- }
1330
- function htmlEscape(value) {
1331
- return String(value ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
1332
- }
1333
- exports.resolveAmlAddressRiskVersion = resolveAmlAddressRiskVersion;
1334
- exports.runAmlAddressRisk = runAmlAddressRisk;