chain-insights 0.78.0 → 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 (65) hide show
  1. package/README.md +3 -0
  2. package/dist/cli.cjs +72 -18
  3. package/dist/cli.mjs +72 -18
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/deployer-screen-BomgSBcq.cjs +446 -0
  6. package/dist/deployer-screen-ByQBZEsg.mjs +413 -0
  7. package/dist/deployer-screen-ByQBZEsg.mjs.map +1 -0
  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 +78 -12
  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 +78 -13
  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-DvgEyqcC.cjs → token-lookup-D-5GBEwF.cjs} +15 -2
  37. package/dist/{token-lookup-sH2DesLS.mjs → token-lookup-QpIv77P2.mjs} +5 -4
  38. package/dist/token-lookup-QpIv77P2.mjs.map +1 -0
  39. package/dist/{tool-visibility-DIpgPULN.cjs → tool-visibility-D8Up081E.cjs} +8 -1
  40. package/dist/{tool-visibility-Dy3psowS.mjs → tool-visibility-DuTds7V4.mjs} +9 -2
  41. package/dist/tool-visibility-DuTds7V4.mjs.map +1 -0
  42. package/docs/contributing.md +5 -2
  43. package/docs/development.md +5 -2
  44. package/docs/graph-query-compatibility.md +20 -4
  45. package/docs/graph-tools.md +22 -8
  46. package/docs/mcp-proxy.md +111 -5
  47. package/docs/stability.md +5 -2
  48. package/package.json +2 -2
  49. package/registry/README.md +42 -5
  50. package/registry/exchanges/ethereum.json +920 -0
  51. package/registry/exchanges/robinhood.json +87 -0
  52. package/registry/robinhood.json +7 -4
  53. package/registry/robinhood.md +9 -5
  54. package/skills/chain-insights-aml-exchange/SKILL.md +134 -0
  55. package/skills/chain-insights-aml-exchange/agents/openai.yaml +4 -0
  56. package/skills/chain-insights-cypher/SKILL.md +41 -11
  57. package/skills/chain-insights-dex/SKILL.md +3 -3
  58. package/skills/chain-insights-dex-gauge/SKILL.md +2 -0
  59. package/skills/chain-insights-dex-launchpad/SKILL.md +9 -10
  60. package/skills/chain-insights-dex-vault/SKILL.md +2 -0
  61. package/skills/chain-insights-virtuals/SKILL.md +1 -1
  62. package/dist/dex-tool-D61sIjpq.mjs.map +0 -1
  63. package/dist/public-tools-DXlZcanX.mjs.map +0 -1
  64. package/dist/token-lookup-sH2DesLS.mjs.map +0 -1
  65. package/dist/tool-visibility-Dy3psowS.mjs.map +0 -1
@@ -460,7 +460,7 @@ function exchangeOutflowQueryAtDepth(address, depth) {
460
460
  query: [
461
461
  `MATCH (a:Address {address: "${escapeCypherString(address)}"})${relationshipChain}`,
462
462
  `WHERE a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(" AND ")}` : ""} AND ${poolGuards}`,
463
- `RETURN "outflow" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, ${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`,
463
+ `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`,
464
464
  "ORDER BY hops ASC",
465
465
  "LIMIT 200"
466
466
  ].join(" ")
@@ -489,12 +489,105 @@ function exchangeInflowQueryAtDepth(address, depth) {
489
489
  query: [
490
490
  `MATCH (exchange:Address)${relationshipChain}`,
491
491
  `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}`,
492
- `RETURN "inflow" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, ${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`,
492
+ `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`,
493
493
  "ORDER BY hops ASC",
494
494
  "LIMIT 200"
495
495
  ].join(" ")
496
496
  };
497
497
  }
498
+ /** How many deposits one screen reads SWEPT for, at most. */
499
+ const EXCHANGE_DEPOSIT_SWEPT_LOOKUPS = 10;
500
+ /** How many SWEPT links of one deposit the screen keeps, largest first. */
501
+ const EXCHANGE_DEPOSIT_SWEPT_LIMIT = 20;
502
+ /** The exchange id an :Exchange address's labels name (`gate`, `bitget`). */
503
+ function exchangeIdFromLabels(labels) {
504
+ return stringArrayValue(labels)?.map((label) => label.trim()).find((label) => label !== "" && label.toLowerCase() !== "exchange");
505
+ }
506
+ /**
507
+ * One exchange walk row with its end resolved: `exchange_role` is the end's
508
+ * cex_role (`exchange` when the graph carries none), `exchange` its id. An
509
+ * outflow that ends at a deposit reports the deposit as `deposit_address`
510
+ * and the node the money came from as `payer_address`.
511
+ */
512
+ function resolveExchangeEnd(row) {
513
+ const role = firstString(row["exchange_cex_role"])?.toLowerCase();
514
+ const exchangeId = exchangeIdFromLabels(row["exchange_system_labels"] ?? row["exchange_display_labels"] ?? row["exchange_labels"]);
515
+ const resolved = {
516
+ ...row,
517
+ exchange_role: role ?? "exchange",
518
+ ...exchangeId ? { exchange: exchangeId } : {}
519
+ };
520
+ if (row["direction"] === "outflow" && role === "deposit") {
521
+ resolved["payer_address"] = row["deposit_address"];
522
+ resolved["deposit_address"] = row["exchange_address"];
523
+ }
524
+ return resolved;
525
+ }
526
+ /** The deposits among resolved outflow rows, nearest first, no repeats. */
527
+ function exchangeDepositEnds(rows) {
528
+ const deposits = [];
529
+ const ordered = [...rows].sort((left, right) => (numberValue(left["hops"]) ?? 0) - (numberValue(right["hops"]) ?? 0));
530
+ for (const row of ordered) {
531
+ if (row["direction"] !== "outflow" || row["exchange_role"] !== "deposit") continue;
532
+ const deposit = firstString(row["exchange_address"]);
533
+ if (deposit && !deposits.includes(deposit)) deposits.push(deposit);
534
+ if (deposits.length >= EXCHANGE_DEPOSIT_SWEPT_LOOKUPS) break;
535
+ }
536
+ return deposits;
537
+ }
538
+ /** The SWEPT read of one deposit: each hot wallet it was swept into. */
539
+ function exchangeDepositSweptQuery(deposit, index) {
540
+ return {
541
+ id: `exchange_deposit_swept_${index + 1}`,
542
+ query: [
543
+ `MATCH (d:Address {address: "${escapeCypherString(deposit)}"})-[s:SWEPT]->(h:Address)`,
544
+ "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",
545
+ `LIMIT ${EXCHANGE_DEPOSIT_SWEPT_LIMIT}`
546
+ ].join(" ")
547
+ };
548
+ }
549
+ /**
550
+ * Attach each deposit's SWEPT links to the rows that end at it, largest sum
551
+ * first. `swept_status` says whether the read ran: `read` (with or without
552
+ * links), or `not_read` when the read failed or the deposit was past the
553
+ * lookup cap, so an empty list never reads as "never swept".
554
+ */
555
+ function attachSweptHotWallets(rows, sweptRows, readDeposits) {
556
+ const byDeposit = /* @__PURE__ */ new Map();
557
+ for (const swept of sweptRows) {
558
+ const deposit = firstString(swept["deposit_address"]);
559
+ const hotWallet = firstString(swept["hot_wallet"]);
560
+ if (!deposit || !hotWallet) continue;
561
+ const exchange = exchangeIdFromLabels(swept["hot_wallet_labels"]);
562
+ const role = firstString(swept["hot_wallet_role"]);
563
+ const sweepCount = numberValue(swept["sweep_count"]);
564
+ const amount = numberValue(swept["amount_usd_sum"]);
565
+ const paths = stringArrayValue(swept["paths"]);
566
+ const firstSeen = numberValue(swept["first_seen_timestamp"]);
567
+ const lastSeen = numberValue(swept["last_seen_timestamp"]);
568
+ const entry = {
569
+ hot_wallet: hotWallet,
570
+ ...exchange ? { hot_wallet_exchange: exchange } : {},
571
+ ...role ? { hot_wallet_role: role } : {},
572
+ ...sweepCount !== void 0 ? { sweep_count: sweepCount } : {},
573
+ ...amount !== void 0 ? { amount_usd_sum: amount } : {},
574
+ ...paths ? { paths } : {},
575
+ ...firstSeen !== void 0 ? { first_seen_timestamp: firstSeen } : {},
576
+ ...lastSeen !== void 0 ? { last_seen_timestamp: lastSeen } : {}
577
+ };
578
+ byDeposit.set(deposit, [...byDeposit.get(deposit) ?? [], entry]);
579
+ }
580
+ for (const list of byDeposit.values()) list.sort((left, right) => (right.amount_usd_sum ?? 0) - (left.amount_usd_sum ?? 0));
581
+ return rows.map((row) => {
582
+ if (row["direction"] !== "outflow" || row["exchange_role"] !== "deposit") return row;
583
+ const deposit = String(row["exchange_address"] ?? "");
584
+ return {
585
+ ...row,
586
+ swept_into: byDeposit.get(deposit) ?? [],
587
+ swept_status: readDeposits.includes(deposit) ? "read" : "not_read"
588
+ };
589
+ });
590
+ }
498
591
  function connectionProbeQuery(address, compareAddress) {
499
592
  return {
500
593
  id: "connection_probe",
@@ -570,6 +663,7 @@ function routeFromPathValue(value) {
570
663
  hops: nodes.length - 1,
571
664
  identities,
572
665
  exchange_intermediates: exchangeIntermediates,
666
+ links_addresses: exchangeIntermediates.length === 0,
573
667
  amount_usd_sum_total: edges.reduce((total, edge) => total + Number(edge["amount_usd_sum"]), 0)
574
668
  };
575
669
  }
@@ -586,6 +680,7 @@ function buildRouteEvidence(outboundRows, inboundRows) {
586
680
  route_rank_basis: "hop_count",
587
681
  depth_bound: CONNECTION_ROUTE_MAX_HOPS,
588
682
  route_found: outbound !== null || inbound !== null,
683
+ linked_outside_exchanges: [outbound, inbound].some((side) => side !== null && side.links_addresses),
589
684
  outbound,
590
685
  inbound
591
686
  };
@@ -593,9 +688,20 @@ function buildRouteEvidence(outboundRows, inboundRows) {
593
688
  function formatExchangeRows(rows) {
594
689
  return rows.map((row) => {
595
690
  const direction = String(row["direction"] ?? "flow");
596
- const exchange = String(row["exchange_address"] ?? "");
691
+ const exchangeAddress = String(row["exchange_address"] ?? "");
597
692
  const amount = row["amount_usd_sum"] ?? "";
598
- return `- ${direction}: ${exchange} (${row["hops"] ?? ""} hop(s), amount_usd_sum ${amount})`;
693
+ const hops = row["hops"] ?? "";
694
+ const exchangeId = typeof row["exchange"] === "string" ? row["exchange"] : void 0;
695
+ const role = typeof row["exchange_role"] === "string" ? row["exchange_role"] : "exchange";
696
+ const named = exchangeId ? `${exchangeId} ${role.replace(/_/g, " ")}` : void 0;
697
+ const base = `- ${direction}: ${exchangeAddress}${named ? ` (${named})` : ""} (${hops} hop(s), amount_usd_sum ${amount})`;
698
+ if (direction !== "outflow" || role !== "deposit") return base;
699
+ const swept = Array.isArray(row["swept_into"]) ? row["swept_into"] : [];
700
+ if (swept.length > 0) {
701
+ const into = swept.map((link) => `hot wallet ${link.hot_wallet}${link.hot_wallet_exchange ? ` (${link.hot_wallet_exchange})` : ""}, ${link.sweep_count ?? "?"} sweep(s)`).join("; ");
702
+ return `${base}: the money entered ${exchangeId ?? "the exchange"} at this deposit, swept into ${into}. The trail ends here.`;
703
+ }
704
+ 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.`;
599
705
  });
600
706
  }
601
707
  function numberValue(value) {
@@ -819,8 +925,27 @@ function buildRiskGraph(address, profile, rows, network) {
819
925
  node_type: "address",
820
926
  labels: displayLabels,
821
927
  ...systemLabels.length > 0 ? { system_labels: systemLabels } : {},
822
- roles: ["exchange"]
928
+ 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"]
823
929
  });
930
+ const swept = Array.isArray(row["swept_into"]) ? row["swept_into"] : [];
931
+ for (const link of swept) {
932
+ if (!nodes.has(link.hot_wallet)) nodes.set(link.hot_wallet, {
933
+ id: link.hot_wallet,
934
+ address: link.hot_wallet,
935
+ node_type: "address",
936
+ labels: link.hot_wallet_exchange ? ["Exchange", link.hot_wallet_exchange] : ["Exchange"],
937
+ roles: ["exchange", link.hot_wallet_role ?? "hot_wallet"]
938
+ });
939
+ edges.push({
940
+ source: exchange,
941
+ target: link.hot_wallet,
942
+ edge_type: "swept",
943
+ usd_amount: link.amount_usd_sum ?? 0,
944
+ amount_usd_sum: link.amount_usd_sum ?? 0,
945
+ tx_count: link.sweep_count ?? 0,
946
+ direction: "outflow"
947
+ });
948
+ }
824
949
  }
825
950
  for (let index = 0; index < path.length - 1; index += 1) {
826
951
  const edge = (Array.isArray(row["edge_props"]) ? row["edge_props"] : [])[index] ?? row;
@@ -910,8 +1035,22 @@ async function addressRisk(remoteClient, options) {
910
1035
  ...optionalResultsFor(batch, "address_feature", partialQueryFailures)[0] ?? {}
911
1036
  };
912
1037
  const labelRows = deriveLabelRows(profile);
913
- const outflows = enrichExchangeRows(optionalResultsWithPrefix(batch, "exchange_outflows_", partialQueryFailures));
914
- const inflows = enrichExchangeRows(optionalResultsWithPrefix(batch, "exchange_inflows_", partialQueryFailures));
1038
+ const resolvedOutflows = enrichExchangeRows(optionalResultsWithPrefix(batch, "exchange_outflows_", partialQueryFailures)).map(resolveExchangeEnd);
1039
+ const inflows = enrichExchangeRows(optionalResultsWithPrefix(batch, "exchange_inflows_", partialQueryFailures)).map(resolveExchangeEnd);
1040
+ const depositEnds = exchangeDepositEnds(resolvedOutflows);
1041
+ let sweptRows = [];
1042
+ let sweptRead = [];
1043
+ if (depositEnds.length > 0) {
1044
+ const sweptQueries = depositEnds.map(exchangeDepositSweptQuery);
1045
+ try {
1046
+ const sweptBatch = await callGraphBatch(trackedClient, network, sweptQueries);
1047
+ sweptRead = depositEnds.filter((_, index) => (sweptBatch.facts?.queries ?? []).some((entry) => entry.id === sweptQueries[index].id && entry.ok !== false));
1048
+ sweptRows = optionalResultsWithPrefix(sweptBatch, "exchange_deposit_swept_", partialQueryFailures);
1049
+ } catch (error) {
1050
+ collectQueryFailure(partialQueryFailures, "exchange_deposit_swept", error instanceof Error ? error.message : String(error));
1051
+ }
1052
+ }
1053
+ const outflows = attachSweptHotWallets(resolvedOutflows, sweptRows, sweptRead);
915
1054
  const connections = compareAddress ? optionalResultsFor(batch, "connection_probe", partialQueryFailures) : [];
916
1055
  const routeEvidence = shouldIncludeRouteQueries(compareAddress) ? buildRouteEvidence(optionalResultsFor(batch, "connection_route_outbound", partialQueryFailures), optionalResultsFor(batch, "connection_route_inbound", partialQueryFailures)) : void 0;
917
1056
  const exchangeRows = [...outflows, ...inflows];
@@ -952,7 +1091,11 @@ async function addressRisk(remoteClient, options) {
952
1091
  ];
953
1092
  if (Array.isArray(risk["drivers"]) && risk["drivers"].length > 0) lines.push("", "Risk drivers", risk["drivers"].map((driver) => `- ${driver}`).join("\n"));
954
1093
  if (moneyTrail) lines.push("", moneyTrailSummarySentence(moneyTrail));
955
- if (compareAddress) lines.push("", `Connection compare target: ${compareAddress}`, connections.length > 0 ? `Connection paths found: ${connections.length}` : "Connection paths found: 0");
1094
+ if (compareAddress) {
1095
+ lines.push("", `Connection compare target: ${compareAddress}`, connections.length > 0 ? `Connection paths found: ${connections.length}` : "Connection paths found: 0");
1096
+ const exchangeCrossings = [routeEvidence?.outbound, routeEvidence?.inbound].flatMap((side) => side?.exchange_intermediates ?? []);
1097
+ 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.`);
1098
+ }
956
1099
  if (compareUnresolved) lines.push("", `Unresolved compare_address: no Address found for "${compareInput}"; comparison skipped.`);
957
1100
  if (partialQueryFailures.length > 0) lines.push("", "Partial query failures", partialQueryFailures.map((failure) => `- ${failure.id}: ${failure.error}`).join("\n"));
958
1101
  const summaryText = lines.join("\n");
@@ -1023,12 +1166,18 @@ function toCsvValue(value) {
1023
1166
  return value === void 0 || value === null ? "" : String(value);
1024
1167
  }
1025
1168
  function subjectNodeForExchangeRow(row, fallbackAddress) {
1026
- return String(row["direction"] === "inflow" ? row["withdrawal_address"] ?? row["deposit_address"] ?? fallbackAddress : row["deposit_address"] ?? row["withdrawal_address"] ?? fallbackAddress);
1169
+ return String(row["direction"] === "inflow" ? row["withdrawal_address"] ?? row["deposit_address"] ?? fallbackAddress : row["payer_address"] ?? row["deposit_address"] ?? row["withdrawal_address"] ?? fallbackAddress);
1170
+ }
1171
+ function sweptIntoCell(row) {
1172
+ return (Array.isArray(row["swept_into"]) ? row["swept_into"] : []).map((link) => link.hot_wallet).join(";");
1027
1173
  }
1028
1174
  function buildAddressRiskTableHtml(tool, network, rows, subject) {
1029
1175
  const headers = [
1030
1176
  "direction",
1177
+ "exchange",
1178
+ "exchange_role",
1031
1179
  "exchange_address",
1180
+ "swept_into_hot_wallet",
1032
1181
  "subject_path_node",
1033
1182
  "hops",
1034
1183
  "amount_usd_sum",
@@ -1039,7 +1188,10 @@ function buildAddressRiskTableHtml(tool, network, rows, subject) {
1039
1188
  const subjectNode = subjectNodeForExchangeRow(row, subject);
1040
1189
  return `<tr>${[
1041
1190
  row["direction"] ?? "",
1191
+ row["exchange"] ?? "",
1192
+ row["exchange_role"] ?? "",
1042
1193
  exchangeAddress,
1194
+ sweptIntoCell(row),
1043
1195
  subjectNode,
1044
1196
  row["hops"] ?? "",
1045
1197
  row["amount_usd_sum"] ?? "",
@@ -1093,7 +1245,10 @@ async function writeAddressRiskArtifacts(network, address, compareAddress, graph
1093
1245
  const reportPath = node_path.default.join(paths.reportsRoot, `${slug}.aml-address-report.md`);
1094
1246
  const csv = [[
1095
1247
  "direction",
1248
+ "exchange",
1249
+ "exchange_role",
1096
1250
  "exchange_address",
1251
+ "swept_into_hot_wallet",
1097
1252
  "subject_path_node",
1098
1253
  "hops",
1099
1254
  "amount_usd_sum",
@@ -1103,7 +1258,10 @@ async function writeAddressRiskArtifacts(network, address, compareAddress, graph
1103
1258
  const subjectPathNode = subjectNodeForExchangeRow(row, address);
1104
1259
  return [
1105
1260
  row["direction"] ?? "",
1261
+ row["exchange"] ?? "",
1262
+ row["exchange_role"] ?? "",
1106
1263
  exchangeAddress,
1264
+ sweptIntoCell(row),
1107
1265
  subjectPathNode,
1108
1266
  row["hops"] ?? "",
1109
1267
  row["amount_usd_sum"] ?? "",
@@ -1121,7 +1279,10 @@ async function writeAddressRiskArtifacts(network, address, compareAddress, graph
1121
1279
  profile: {
1122
1280
  exchange_rows: exchangeRows.map((row) => ({
1123
1281
  direction: row["direction"],
1282
+ exchange: row["exchange"],
1283
+ exchange_role: row["exchange_role"],
1124
1284
  exchange_address: row["exchange_address"],
1285
+ ...Array.isArray(row["swept_into"]) ? { swept_into: row["swept_into"] } : {},
1125
1286
  subject_node: subjectNodeForExchangeRow(row, address),
1126
1287
  hops: row["hops"],
1127
1288
  amount_usd_sum: row["amount_usd_sum"],
@@ -1,6 +1,6 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  const require_answer_hint = require("./answer-hint-BlYEBq_Y.cjs");
3
- const require_dex_registry = require("./dex-registry-DdXOg5On.cjs");
3
+ const require_dex_registry = require("./dex-registry-BhGJUG9_.cjs");
4
4
  const require_print_result = require("./print-result-BYppJlUi.cjs");
5
5
  // src/mcp/token-lookup.ts
6
6
  /**
@@ -118,6 +118,7 @@ function rowsOf(answer) {
118
118
  const results = isRecord(query) ? query.results : void 0;
119
119
  return Array.isArray(results) ? results.filter(isRecord) : null;
120
120
  }
121
+ /** The members of a graph_query_batch answer by id. */
121
122
  function membersOf(answer) {
122
123
  const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : void 0;
123
124
  const queries = isRecord(facts) ? facts.queries : void 0;
@@ -281,7 +282,7 @@ async function handleMetaTokenLookup(args, deps) {
281
282
  candidates: [],
282
283
  total: 0,
283
284
  truncated: false,
284
- hint: `${require_answer_hint.ANSWER_HINT} This Chain Insights server does not serve the token lookup yet (${read.refusal.code}). That is not "no contract carries ${symbol}": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`
285
+ hint: `${require_answer_hint.ANSWER_HINT} This lookup gave no answer (${read.refusal.code}). That is not "no contract carries ${symbol}": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`
285
286
  });
286
287
  const total = read.rows.length;
287
288
  const candidates = read.rows.slice(0, CANDIDATES_MAX).map(candidateOf).filter((candidate) => candidate !== null);
@@ -334,6 +335,18 @@ Object.defineProperty(exports, "handleMetaTokenLookup", {
334
335
  return handleMetaTokenLookup;
335
336
  }
336
337
  });
338
+ Object.defineProperty(exports, "membersOf", {
339
+ enumerable: true,
340
+ get: function() {
341
+ return membersOf;
342
+ }
343
+ });
344
+ Object.defineProperty(exports, "refusalOf", {
345
+ enumerable: true,
346
+ get: function() {
347
+ return refusalOf;
348
+ }
349
+ });
337
350
  Object.defineProperty(exports, "token_lookup_exports", {
338
351
  enumerable: true,
339
352
  get: function() {
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
2
  import { t as ANSWER_HINT } from "./answer-hint-vOE1O6Lf.mjs";
3
- import { a as normalizeDexNetwork, t as DexRegistryError } from "./dex-registry-sPTFuCrP.mjs";
3
+ import { d as normalizeDexNetwork, r as DexRegistryError } from "./dex-registry-BY67f4Ul.mjs";
4
4
  import { i as isEpochMs, o as utcText } from "./print-result-IFARsMnL.mjs";
5
5
  // src/mcp/token-lookup.ts
6
6
  /**
@@ -118,6 +118,7 @@ function rowsOf(answer) {
118
118
  const results = isRecord(query) ? query.results : void 0;
119
119
  return Array.isArray(results) ? results.filter(isRecord) : null;
120
120
  }
121
+ /** The members of a graph_query_batch answer by id. */
121
122
  function membersOf(answer) {
122
123
  const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : void 0;
123
124
  const queries = isRecord(facts) ? facts.queries : void 0;
@@ -281,7 +282,7 @@ async function handleMetaTokenLookup(args, deps) {
281
282
  candidates: [],
282
283
  total: 0,
283
284
  truncated: false,
284
- hint: `${ANSWER_HINT} This Chain Insights server does not serve the token lookup yet (${read.refusal.code}). That is not "no contract carries ${symbol}": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`
285
+ hint: `${ANSWER_HINT} This lookup gave no answer (${read.refusal.code}). That is not "no contract carries ${symbol}": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`
285
286
  });
286
287
  const total = read.rows.length;
287
288
  const candidates = read.rows.slice(0, CANDIDATES_MAX).map(candidateOf).filter((candidate) => candidate !== null);
@@ -298,6 +299,6 @@ async function handleMetaTokenLookup(args, deps) {
298
299
  hint: hintFor(result, creatorsNotRead)
299
300
  });
300
301
  }
301
- export { SYMBOL_MAX as a, META_TOKEN_LOOKUP_TOOL as i, META_TOKEN_LOOKUP_DESCRIPTION as n, handleMetaTokenLookup as o, META_TOKEN_LOOKUP_TITLE as r, token_lookup_exports as s, META_TOKEN_LOOKUP_ANNOTATIONS as t };
302
+ export { SYMBOL_MAX as a, refusalOf as c, META_TOKEN_LOOKUP_TOOL as i, token_lookup_exports as l, META_TOKEN_LOOKUP_DESCRIPTION as n, handleMetaTokenLookup as o, META_TOKEN_LOOKUP_TITLE as r, membersOf as s, META_TOKEN_LOOKUP_ANNOTATIONS as t };
302
303
 
303
- //# sourceMappingURL=token-lookup-sH2DesLS.mjs.map
304
+ //# sourceMappingURL=token-lookup-QpIv77P2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-lookup-QpIv77P2.mjs","names":[],"sources":["../src/mcp/token-lookup.ts"],"sourcesContent":["/**\n * meta_token_lookup: a ticker or a token name becomes its contracts.\n *\n * A local tool of the proxy. It sends one anchored facts read of the Asset\n * lookup by symbol, the same read by name when the symbol answers nothing, and\n * then the creator and the factory of each candidate from topology, one batch\n * member per candidate. Nothing is matched here: the graph server matches the\n * symbol or the name, case-insensitively and exactly, and orders the rows\n * verified first, then oldest first. The proxy keeps that order.\n *\n * Tickers collide on purpose: clones reuse a symbol to borrow its trust. The\n * tool never picks one. The description below is the contract with every\n * host, Claude Desktop chat included, which reads no skill.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\n\nexport const META_TOKEN_LOOKUP_TOOL = 'meta_token_lookup'\nexport const META_TOKEN_LOOKUP_SCHEMA = 'chain-insights.meta-token-lookup.v1' as const\nexport const META_TOKEN_LOOKUP_TITLE = 'Token by ticker or name'\nexport const META_TOKEN_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a token by its ticker or name and gives no contract ' +\n '(TCITY, USDG, SPCX). It returns every contract on the network that carries that symbol, ' +\n 'verified first, then oldest first. Tickers collide: never treat the first row as the token. ' +\n 'When several match, name them and ask, or pick by the evidence the user gave. Zero candidates ' +\n 'means no contract carries the symbol: say so, and do not search the web.'\nexport const META_TOKEN_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_TOKEN_LOOKUP_ARGS = ['network', 'symbol'] as const\n\n/** The candidates returned. The read asks for one more, so a full page says there are more. */\nexport const CANDIDATES_MAX = 25\nexport const ROWS_READ = CANDIDATES_MAX + 1\n/** The graph server admits at most 20 members in one graph_query_batch. */\nexport const CREATOR_BATCH_MAX = 20\nexport const SYMBOL_MAX = 64\n\nexport const ADDRESS_INPUT_HINT = 'an address is already an anchor: read it on USE topology'\n\nexport interface TokenCandidate {\n contract: string\n symbol: string | null\n name: string | null\n token_standard: string | null\n decimals: number | null\n verified: boolean\n verification_source: string | null\n first_seen_timestamp: number | null\n first_seen_timestamp_utc: string | null\n creator: string | null\n factory: string | null\n}\n\nexport interface MetaTokenLookupResult {\n schema: typeof META_TOKEN_LOOKUP_SCHEMA\n network: string\n query: string\n matched_on: 'symbol' | 'name' | null\n candidates: TokenCandidate[]\n /** The rows the server sent, at most 26: 26 means there are more than the 25 returned. */\n total: number\n truncated: boolean\n hint: string\n}\n\n/** One graph_query or graph_query_batch reply as the remote client returns it. */\nexport type GraphAnswer = {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n}\n\nexport interface TokenToolDependencies {\n /** One graph_query through the proxy's remote client, billed as any read. */\n graphQuery: (args: { network: string; query: string }) => Promise<GraphAnswer>\n /** One graph_query_batch through the proxy's remote client, billed as any read. */\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<GraphAnswer>\n /** The reason no read can be sent now, or undefined when the graph is reachable. */\n unavailable?: () => Promise<string | undefined> | string | undefined\n /** The text of a call that threw: payment required, transport. */\n describeFailure: (err: unknown) => string\n}\n\nexport type MetaTokenLookupToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\nconst CONTRACT_FORM = /^0x[0-9a-f]{40}$/\n// A string literal of the read holds no double quote, no backslash and no\n// control character: the symbol is refused rather than escaped, so the read the\n// server receives is always the read written here.\nfunction unsafeLiteral(text: string): boolean {\n for (const char of text) {\n const code = char.codePointAt(0)!\n if (char === '\"' || char === '\\\\' || code < 0x20 || code === 0x7f) return true\n }\n return false\n}\nconst CODE_PREFIX = /^([a-z][a-z0-9_]*):\\s*/\n// Codes of a read that was stopped, not refused: the same read may answer later.\nconst TRANSIENT_CODE =\n /(timeout|memory_limit|cpu_limit|busy|_failed$|rate_limited|unavailable|too_large|node_error)/\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorResult(text: string): MetaTokenLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: MetaTokenLookupResult): MetaTokenLookupToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],\n structuredContent: structured as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** The facts Asset read by symbol or by name, in the one shape the graph server admits. */\nexport function assetQuery(key: 'symbol' | 'name', value: string): string {\n return (\n `USE facts MATCH (t:Asset {${key}: \"${value}\"}) ` +\n 'RETURN t.asset_contract AS contract, t.asset_symbol AS symbol, t.name AS name, ' +\n 't.token_standard AS token_standard, t.decimals AS decimals, t.verified AS verified, ' +\n 't.verification_source AS verification_source, t.first_seen_timestamp AS first_seen_timestamp ' +\n `LIMIT ${ROWS_READ}`\n )\n}\n\n/** The topology read of who deployed one contract: the deploying address and the transaction's sender. */\nexport function creatorQuery(contract: string): string {\n return (\n `USE topology MATCH (f:Address)-[d:DEPLOYED_CONTRACT]->(t:Address {address: \"${contract}\"}) ` +\n 'RETURN f.address AS factory, d.tx_origin AS creator LIMIT 1'\n )\n}\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null\n\nconst numberOrNull = (value: unknown): number | null => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)))\n return Number(value)\n return null\n}\n\nconst addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_FORM.test(value.trim()) ? value.trim().toLowerCase() : null\n\nfunction verifiedOf(value: unknown): boolean {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return value === 1\n if (typeof value === 'string') return ['true', '1'].includes(value.trim().toLowerCase())\n return false\n}\n\nfunction answerText(answer: GraphAnswer): string {\n return (Array.isArray(answer.content) ? answer.content : [])\n .map((block) => (isRecord(block) && typeof block.text === 'string' ? block.text : ''))\n .filter(Boolean)\n .join('\\n')\n .trim()\n}\n\nexport type Refusal = { code: string; text: string; transient: boolean }\n\n/** A graph_query answer that did not answer: its code, its text, and whether the same read may answer later. */\nexport function refusalOf(answer: GraphAnswer): Refusal {\n const text = answerText(answer)\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n const detailCode = isRecord(detail) && typeof detail.code === 'string' ? detail.code : ''\n const detailClass = isRecord(detail) && typeof detail.class === 'string' ? detail.class : ''\n const named = detailCode || CODE_PREFIX.exec(text)?.[1] || ''\n // A refusal that names no class is a stop only when its code says so; a\n // refusal in plain words (\"unknown label Asset\") is a server that lacks the read.\n const transient = detailClass ? detailClass !== 'refused' : TRANSIENT_CODE.test(named)\n const code = named || 'not_served'\n return { code, text: text || `${code}: the graph endpoint refused the read`, transient }\n}\n\n/** The result rows of a graph_query answer, or null when it holds none. */\nfunction rowsOf(answer: GraphAnswer): Array<Record<string, unknown>> | null {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n const results = isRecord(query) ? query.results : undefined\n return Array.isArray(results) ? results.filter(isRecord) : null\n}\n\nexport type Member = { id?: unknown; ok?: unknown; results?: unknown; error?: unknown }\n\n/** The members of a graph_query_batch answer by id. */\nexport function membersOf(answer: GraphAnswer): Map<string, Member> {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const queries = isRecord(facts) ? facts.queries : undefined\n const members = new Map<string, Member>()\n if (Array.isArray(queries)) {\n for (const member of queries)\n if (isRecord(member) && typeof member.id === 'string') members.set(member.id, member)\n }\n return members\n}\n\nfunction candidateOf(row: Record<string, unknown>): TokenCandidate | null {\n const contract = textOrNull(row.contract)?.trim().toLowerCase()\n if (!contract) return null\n const firstSeen = numberOrNull(row.first_seen_timestamp)\n return {\n contract,\n symbol: textOrNull(row.symbol),\n name: textOrNull(row.name),\n token_standard: textOrNull(row.token_standard),\n decimals: numberOrNull(row.decimals),\n verified: verifiedOf(row.verified),\n verification_source: textOrNull(row.verification_source),\n first_seen_timestamp: firstSeen,\n first_seen_timestamp_utc: isEpochMs(firstSeen) ? utcText(firstSeen) : null,\n creator: null,\n factory: null,\n }\n}\n\ntype Read =\n | { kind: 'rows'; rows: Array<Record<string, unknown>> }\n | { kind: 'not_served'; refusal: Refusal }\n | { kind: 'failed'; text: string }\n\nasync function readAssets(\n deps: TokenToolDependencies,\n network: string,\n key: 'symbol' | 'name',\n value: string\n): Promise<Read> {\n let answer: GraphAnswer\n try {\n answer = await deps.graphQuery({ network, query: assetQuery(key, value) })\n } catch (err) {\n return { kind: 'failed', text: deps.describeFailure(err) }\n }\n const rows = rowsOf(answer)\n if (answer.isError !== true && rows !== null) return { kind: 'rows', rows }\n const refusal = refusalOf(answer)\n if (answer.isError === true && refusal.transient) return { kind: 'failed', text: refusal.text }\n return { kind: 'not_served', refusal }\n}\n\n/**\n * The creator and the factory of each candidate, written in place. Returns why\n * some creators were not read, or null when every read answered. A read that\n * answered with no row leaves the candidate's creator empty with no note: the\n * graph holds no deployment for it.\n */\nasync function readCreators(\n deps: TokenToolDependencies,\n network: string,\n candidates: TokenCandidate[]\n): Promise<string | null> {\n const contracts = [\n ...new Set(candidates.map((c) => c.contract).filter((c) => CONTRACT_FORM.test(c))),\n ]\n const found = new Map<string, { creator: string | null; factory: string | null }>()\n const reasons: string[] = []\n let unread = candidates.length - candidates.filter((c) => CONTRACT_FORM.test(c.contract)).length\n for (let at = 0; at < contracts.length; at += CREATOR_BATCH_MAX) {\n const chunk = contracts.slice(at, at + CREATOR_BATCH_MAX)\n const queries = chunk.map((contract) => ({\n id: `creator:${contract}`,\n query: creatorQuery(contract),\n }))\n let members = new Map<string, Member>()\n try {\n const answer = await deps.graphQueryBatch({ network, queries })\n members = membersOf(answer)\n if (members.size === 0) {\n reasons.push(\n answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n )\n }\n } catch (err) {\n reasons.push(deps.describeFailure(err))\n }\n for (const contract of chunk) {\n const member = members.get(`creator:${contract}`)\n if (member?.ok === true && Array.isArray(member.results)) {\n const row = member.results.find(isRecord)\n found.set(contract, {\n creator: row ? addressOrNull(row.creator) : null,\n factory: row ? addressOrNull(row.factory) : null,\n })\n continue\n }\n unread += 1\n if (member && typeof member.error === 'string' && !reasons.includes(member.error))\n reasons.push(member.error)\n }\n }\n for (const candidate of candidates) {\n const read = found.get(candidate.contract)\n if (read) Object.assign(candidate, read)\n }\n if (unread === 0) return null\n return `${unread} of ${candidates.length}${reasons.length > 0 ? `: ${reasons.join('; ')}` : ''}`\n}\n\nconst NO_WEB =\n 'Do not search the web and do not guess a contract: a web page is not a contract on this network.'\n\nfunction hintFor(\n result: Omit<MetaTokenLookupResult, 'hint'>,\n creatorsNotRead: string | null\n): string {\n const { network, query, candidates, matched_on, truncated } = result\n const parts: string[] = [ANSWER_HINT]\n if (candidates.length === 0) {\n parts.push(\n `No contract on ${network} carries the symbol or the name \"${query}\". Say so in one line. ${NO_WEB} ` +\n 'Ask the user for the contract if they have one.'\n )\n return parts.join(' ')\n }\n if (matched_on === 'name') {\n parts.push(`No contract carries \"${query}\" as its symbol; these carry it as their name.`)\n }\n if (candidates.length === 1) {\n parts.push(\n `One contract on ${network} carries \"${query}\": ${candidates[0]!.contract}. ` +\n 'Say it is the only one on this network, then read it by this full contract on USE topology.'\n )\n } else {\n parts.push(\n `${candidates.length} contracts on ${network} carry \"${query}\"` +\n `${truncated ? `, and more exist than the ${CANDIDATES_MAX} listed` : ''}. ` +\n 'Tickers collide: never treat the first row as the token. Name them, each contract in full, ' +\n 'with its creator and first seen time, and ask which one the user means, or pick one by the evidence the user gave ' +\n '(a creator, a launch date, a price move) and say why.'\n )\n }\n if (creatorsNotRead) {\n parts.push(\n `The creators were not read for ${creatorsNotRead}. creator and factory are empty there because the read failed, ` +\n 'not because the chain holds none.'\n )\n }\n parts.push('Write every contract and creator in full, 0x plus 40 hex characters.')\n return parts.join(' ')\n}\n\n/** meta_token_lookup, {network, symbol}. Every argument is checked before a read is sent. */\nexport async function handleMetaTokenLookup(\n args: unknown,\n deps: TokenToolDependencies\n): Promise<MetaTokenLookupToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n if (typeof record.symbol !== 'string' || record.symbol.trim() === '') {\n return errorResult(\n 'invalid_symbol: symbol is required: the ticker or the name as the user wrote it, for example TCITY'\n )\n }\n const symbol = record.symbol.trim()\n if (symbol.length > SYMBOL_MAX) {\n return errorResult(`invalid_symbol: symbol holds at most ${SYMBOL_MAX} characters`)\n }\n const base = {\n schema: META_TOKEN_LOOKUP_SCHEMA,\n network,\n query: symbol,\n }\n\n if (ADDRESS_FORM.test(symbol)) {\n const address = symbol.toLowerCase()\n return textResult({\n ...base,\n matched_on: null,\n candidates: [],\n total: 0,\n truncated: false,\n hint: `${ANSWER_HINT} ${address} is a contract address, not a ticker: ${ADDRESS_INPUT_HINT}. Send no token lookup for it.`,\n })\n }\n if (unsafeLiteral(symbol)) {\n return errorResult(\n 'invalid_symbol: a symbol holds no double quote, backslash or control character. Send the ticker or the name as plain text.'\n )\n }\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No token read was sent: ${unavailable} The lookup has no answer yet, which is not \"no contract\": try again later, or ask the user for the contract. ${NO_WEB}`\n )\n }\n\n let matchedOn: 'symbol' | 'name' = 'symbol'\n let read = await readAssets(deps, network, 'symbol', symbol)\n if (read.kind === 'rows' && read.rows.length === 0) {\n matchedOn = 'name'\n read = await readAssets(deps, network, 'name', symbol)\n }\n if (read.kind === 'failed') {\n return errorResult(\n `The token read failed: ${read.text} This is not \"no contract\": send the same lookup again once, or ask the user for the contract. ${NO_WEB}`\n )\n }\n if (read.kind === 'not_served') {\n return textResult({\n ...base,\n matched_on: null,\n candidates: [],\n total: 0,\n truncated: false,\n hint:\n `${ANSWER_HINT} This lookup gave no answer (${read.refusal.code}). ` +\n `That is not \"no contract carries ${symbol}\": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`,\n })\n }\n\n const total = read.rows.length\n const candidates = read.rows\n .slice(0, CANDIDATES_MAX)\n .map(candidateOf)\n .filter((candidate): candidate is TokenCandidate => candidate !== null)\n const creatorsNotRead =\n candidates.length > 0 ? await readCreators(deps, network, candidates) : null\n const result = {\n ...base,\n matched_on: candidates.length > 0 ? matchedOn : null,\n candidates,\n total,\n truncated: total > CANDIDATES_MAX,\n }\n return textResult({ ...result, hint: hintFor(result, creatorsNotRead) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAa,yBAAyB;AACtC,MAAa,2BAA2B;AACxC,MAAa,0BAA0B;AACvC,MAAa,gCACX;AAKF,MAAa,gCAAgC;CAC3C,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;;AAIA,MAAa,iBAAiB;AAC9B,MAAa,YAAY;;AAEzB,MAAa,oBAAoB;AACjC,MAAa,aAAa;AAE1B,MAAa,qBAAqB;AAuDlC,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAItB,SAAS,cAAc,MAAuB;CAC5C,KAAK,MAAM,QAAQ,MAAM;EACvB,MAAM,OAAO,KAAK,YAAY,CAAC;EAC/B,IAAI,SAAS,QAAO,SAAS,QAAQ,OAAO,MAAQ,SAAS,KAAM,OAAO;CAC5E;CACA,OAAO;AACT;AACA,MAAM,cAAc;AAEpB,MAAM,iBACJ;AAEF,SAAS,SAAS,OAAkD;CAClE,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE;AAEA,SAAS,YAAY,MAAyC;CAC5D,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ;EAAK,CAAC;EAAG,SAAS;CAAK;AAC5D;AAEA,SAAS,WAAW,YAA8D;CAChF,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM,KAAK,UAAU,YAAY,MAAM,CAAC;EAAE,CAAC;EACrE,mBAAmB;EACnB,SAAS;CACX;AACF;;AAGA,SAAgB,WAAW,KAAwB,OAAuB;CACxE,OACE,6BAA6B,IAAI,KAAK,MAAM,4QAInC;AAEb;;AAGA,SAAgB,aAAa,U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OAAO,MAAM,WAAW,MAAM,SAAS,QAAQ,MAAM;CACvD;CACA,IAAI,KAAK,SAAS,UAChB,OAAO,YACL,0BAA0B,KAAK,KAAK,iGAAiG,QACvI;CAEF,IAAI,KAAK,SAAS,cAChB,OAAO,WAAW;EAChB,GAAG;EACH,YAAY;EACZ,YAAY,CAAC;EACb,OAAO;EACP,WAAW;EACX,MACE,GAAG,YAAY,+BAA+B,KAAK,QAAQ,KAAK,sCAC5B,OAAO,uEAAuE;CACtH,CAAC;CAGH,MAAM,QAAQ,KAAK,KAAK;CACxB,MAAM,aAAa,KAAK,KACrB,MAAM,GAAG,cAAc,CAAC,CACxB,IAAI,WAAW,CAAC,CAChB,QAAQ,cAA2C,cAAc,IAAI;CACxE,MAAM,kBACJ,WAAW,SAAS,IAAI,MAAM,aAAa,MAAM,SAAS,UAAU,IAAI;CAC1E,MAAM,SAAS;EACb,GAAG;EACH,YAAY,WAAW,SAAS,IAAI,YAAY;EAChD;EACA;EACA,WAAW,QAAQ;CACrB;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,eAAe;CAAE,CAAC;AACzE"}
@@ -49,7 +49,14 @@ const PUBLIC_MCP_TOOL_ALLOWED_ARGS = {
49
49
  "address",
50
50
  "pools"
51
51
  ],
52
- meta_token_lookup: ["network", "symbol"]
52
+ meta_token_lookup: ["network", "symbol"],
53
+ aml_deployer_screen: ["network", "address"],
54
+ meta_exchange_lookup: [
55
+ "network",
56
+ "name",
57
+ "address"
58
+ ],
59
+ aml_exchange_deposit_check: ["network", "address"]
53
60
  };
54
61
  function isHiddenRemoteToolName(name) {
55
62
  return HIDDEN_REMOTE_TOOL_NAMES.has(name);
@@ -49,7 +49,14 @@ const PUBLIC_MCP_TOOL_ALLOWED_ARGS = {
49
49
  "address",
50
50
  "pools"
51
51
  ],
52
- meta_token_lookup: ["network", "symbol"]
52
+ meta_token_lookup: ["network", "symbol"],
53
+ aml_deployer_screen: ["network", "address"],
54
+ meta_exchange_lookup: [
55
+ "network",
56
+ "name",
57
+ "address"
58
+ ],
59
+ aml_exchange_deposit_check: ["network", "address"]
53
60
  };
54
61
  function isHiddenRemoteToolName(name) {
55
62
  return HIDDEN_REMOTE_TOOL_NAMES.has(name);
@@ -87,4 +94,4 @@ function validatePublicMcpToolArguments(name, args) {
87
94
  }
88
95
  export { tool_visibility_exports as a, isAppOnlyTool as i, PUBLIC_MCP_TOOL_ALLOWED_ARGS as n, PUBLIC_MCP_TOOL_REQUIRED_ARGS as r, HIDDEN_REMOTE_TOOL_NAMES as t };
89
96
 
90
- //# sourceMappingURL=tool-visibility-Dy3psowS.mjs.map
97
+ //# sourceMappingURL=tool-visibility-DuTds7V4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-visibility-DuTds7V4.mjs","names":[],"sources":["../src/mcp/tool-visibility.ts"],"sourcesContent":["import { McpToolError, formatMcpToolError } from './print-result.js'\n\nexport const HIDDEN_REMOTE_TOOL_NAMES = new Set([\n 'topup',\n 'address_risk',\n // Hidden until its verdict is fixed: never listed, never registered, never\n // called through the proxy. The remote graph endpoint does not serve it.\n 'aml_address_risk',\n 'trace_victim_funds',\n 'trace_suspect_funds',\n 'trace_deposit_sources',\n 'trace_funds',\n 'track_funds',\n // Retired tools: never exposed publicly. Built by concatenation so the\n // retired names do not appear as literals in this file.\n ['aml_trace_victim', '_funds'].join(''),\n ['aml_trace_suspect', '_funds'].join(''),\n ['aml_trace_deposit', '_sources'].join(''),\n 'network_capabilities',\n 'usage_status',\n 'subscription_status',\n 'balance',\n 'help',\n ['money', '_flows_between_exchanges'].join(''),\n 'address_connection_risk',\n])\n\nexport const PUBLIC_MCP_TOOL_REQUIRED_ARGS: Record<string, string[]> = {\n graph_query: ['query', 'network'],\n graph_query_batch: ['network', 'queries'],\n}\n\n// normalizeRemoteToolArguments FILTERS pass-through arguments to this list, so\n// an argument that is missing here is silently STRIPPED and the caller gets a\n// default-bounded result with no error and no warning. `time_scope` shipped\n// broken for exactly this reason. Every tunable search bound below\n// (per_address_limit, row_limit) must therefore be listed the moment it\n// appears on a tool schema, and is covered end-to-end through the proxy in\n// tests/mcp-proxy.test.ts.\nexport const PUBLIC_MCP_TOOL_ALLOWED_ARGS: Record<string, string[]> = {\n // `time_scope` narrows a `USE topology` query to a temporal-shard subset\n graph_query: ['query', 'network', 'time_scope'],\n graph_query_batch: ['network', 'queries', 'per_query_timeout_seconds', 'time_scope'],\n // A local tool of the proxy (src/mcp/dex-tool.ts): the exchange by name.\n meta_dex_lookup: ['network', 'name', 'address', 'pools'],\n // A local tool of the proxy (src/mcp/token-lookup.ts): the contracts of a ticker.\n meta_token_lookup: ['network', 'symbol'],\n // A local tool of the proxy (src/mcp/deployer-screen.ts): who is behind a token or a wallet.\n aml_deployer_screen: ['network', 'address'],\n // A local tool of the proxy (src/mcp/exchange-tool.ts): a centralized exchange by name.\n meta_exchange_lookup: ['network', 'name', 'address'],\n // A local tool of the proxy (src/mcp/exchange-deposit-check.ts): is this address an exchange deposit.\n aml_exchange_deposit_check: ['network', 'address'],\n}\n\nexport function isHiddenRemoteToolName(name: string): boolean {\n return HIDDEN_REMOTE_TOOL_NAMES.has(name)\n}\n\n/**\n * True for an MCP Apps tool only a view may call: `_meta.ui.visibility` is set\n * and does not include \"model\" (for example graph_expand, visibility [\"app\"]).\n * Such a tool never appears in a tool list built for the model or the CLI.\n */\nexport function isAppOnlyTool(tool: { _meta?: Record<string, unknown> }): boolean {\n const ui = tool._meta?.ui\n if (!ui || typeof ui !== 'object' || Array.isArray(ui)) return false\n const visibility = (ui as Record<string, unknown>).visibility\n return Array.isArray(visibility) && !visibility.includes('model')\n}\n\nexport function visibleRemoteTools<T extends { name: string; _meta?: Record<string, unknown> }>(\n tools: T[]\n): T[] {\n return tools.filter((tool) => !isHiddenRemoteToolName(tool.name) && !isAppOnlyTool(tool))\n}\n\nexport function assertPublicMcpToolName(name: string): void {\n if (!isHiddenRemoteToolName(name)) return\n const replacement =\n name === 'network_capabilities'\n ? ' Use meta_network_capabilities instead.'\n : name === 'usage_status'\n ? ' Use meta_usage_status instead.'\n : name === 'subscription_status'\n ? ' Use meta_subscription_status instead.'\n : name === 'balance'\n ? ' Use wallet_balance instead.'\n : name === 'help'\n ? ' Use meta_help instead.'\n : ''\n throw new Error(`MCP tool '${name}' is not exposed by Chain Insights.${replacement}`)\n}\n\nexport function formatMcpCallError(tool: string, err: unknown): string {\n // A tool error with an envelope is the server's own answer: its text, then the\n // line of its error_detail. It is never matched against the unknown-tool\n // pattern below. A tool error with no envelope keeps the old reading, because\n // a server can answer an unknown tool as an error reply.\n if (err instanceof McpToolError && err.errorDetail) return formatMcpToolError(err)\n const message = err instanceof Error ? err.message : String(err)\n if (/\\bunknown tool\\b|\\btool\\b.*\\bnot found\\b/i.test(message)) {\n return `Unknown MCP tool \"${tool}\". Run \\`cia mcp tools --refresh\\` to list available tools.`\n }\n return message\n}\n\nexport function validatePublicMcpToolArguments(name: string, args: Record<string, unknown>): void {\n const allowedArgs = PUBLIC_MCP_TOOL_ALLOWED_ARGS[name]\n if (!allowedArgs) return\n\n const unsupportedArgs = Object.keys(args).filter((argName) => !allowedArgs.includes(argName))\n if (unsupportedArgs.length === 0) return\n\n throw new Error(\n [\n `Unsupported argument${unsupportedArgs.length === 1 ? '' : 's'} for ${name}: ${unsupportedArgs.join(', ')}.`,\n `Allowed arguments: ${allowedArgs.join(', ')}.`,\n ].join(' ')\n )\n}\n"],"mappings":";;;;;;;;;AAEA,MAAa,2CAA2B,IAAI,IAAI;CAC9C;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CAGA,CAAC,oBAAoB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACtC,CAAC,qBAAqB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACvC,CAAC,qBAAqB,UAAU,CAAC,CAAC,KAAK,EAAE;CACzC;CACA;CACA;CACA;CACA;CACA,CAAC,SAAS,0BAA0B,CAAC,CAAC,KAAK,EAAE;CAC7C;AACF,CAAC;A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EnC,OAAO;AACT;AAEA,SAAgB,+BAA+B,MAAc,MAAqC;CAChG,MAAM,cAAc,6BAA6B;CACjD,IAAI,CAAC,aAAa;CAElB,MAAM,kBAAkB,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,YAAY,CAAC,YAAY,SAAS,OAAO,CAAC;CAC5F,IAAI,gBAAgB,WAAW,GAAG;CAElC,MAAM,IAAI,MACR,CACE,uBAAuB,gBAAgB,WAAW,IAAI,KAAK,IAAI,OAAO,KAAK,IAAI,gBAAgB,KAAK,IAAI,EAAE,IAC1G,sBAAsB,YAAY,KAAK,IAAI,EAAE,EAC/C,CAAC,CAAC,KAAK,GAAG,CACZ;AACF"}
@@ -14,8 +14,11 @@ node bin/cli.js --help
14
14
 
15
15
  ## Adding AML Tools
16
16
 
17
- No AML tool lives in the Chain Insights layer today. `aml_address_risk` is
18
- hidden until its verdict is fixed.
17
+ Two AML tools live in the Chain Insights layer today, both local tools of the
18
+ MCP proxy: `aml_deployer_screen` returns facts about who is behind a token or
19
+ a wallet, never a score, and `aml_exchange_deposit_check` says whether an
20
+ address is an exchange deposit and into which hot wallet it was swept. `aml_address_risk` is hidden until its verdict is
21
+ fixed.
19
22
 
20
23
  When adding a tool, document:
21
24
 
@@ -80,7 +80,8 @@ names the source file it was verified against.
80
80
  ### Public MCP Tool Surface
81
81
 
82
82
  - The canonical public tool surface is the prefixed set `graph_*` /
83
- `meta_*` / `wallet_*`.
83
+ `meta_*` / `wallet_*`, plus the local AML tools `aml_deployer_screen` and
84
+ `aml_exchange_deposit_check`.
84
85
  - `visibleRemoteTools()` in `src/mcp/tool-visibility.ts` hides unprefixed
85
86
  backend names (`address_risk`, `trace_victim_funds`, `trace_suspect_funds`,
86
87
  `trace_deposit_sources`, `trace_funds`, `track_funds`,
@@ -89,7 +90,9 @@ names the source file it was verified against.
89
90
  `HIDDEN_REMOTE_TOOL_NAMES`. They never surface publicly. So does
90
91
  `aml_address_risk`, hidden until its verdict is fixed.
91
92
  - Local tools live in `src/mcp/proxy.ts` (`LOCAL_TOOL_NAMES`):
92
- `meta_network_capabilities`, `meta_schema`, `meta_rules`, `meta_help`,
93
+ `meta_network_capabilities`, `meta_schema`, `meta_dex_lookup`,
94
+ `meta_token_lookup`, `aml_deployer_screen`, `meta_exchange_lookup`,
95
+ `aml_exchange_deposit_check`, `meta_rules`, `meta_help`,
93
96
  `meta_usage_status`, `meta_subscription_status`, `wallet_balance`,
94
97
  `wallet_topup`, `subscription_topup`, and `graph_expand`, which only the view calls
95
98
  (`APP_ONLY_LOCAL_TOOL_NAMES`).
@@ -250,6 +250,18 @@ pattern joins: `CYCLE_PARTICIPANT`, `LAYERING_HOP`, `SMURFING_CLUSTER`,
250
250
  one carries `kind`, `source_event` `ml_pattern` and the run id in `run_id`. A
251
251
  newer run replaces them. None is money flow.
252
252
 
253
+ ### `SWEPT` — exchange deposit sweeps (topology only)
254
+
255
+ `(:Address)-[:SWEPT]->(:Address)` runs from an exchange deposit to the hot
256
+ wallet it swept into, in the layer `cex_sweeps` of the family annotations. It
257
+ is drawn only from an address the deposit rule judged a deposit; a payment
258
+ straight into a hot wallet stays `FLOWED_TO`. It carries `sweep_count`,
259
+ `amount_raw_sum`, `amount_usd_sum`, `paths` (the sweep paths seen: `plain`,
260
+ `gas_topped`, `approval_pull`, `forwarder_flush`, `forwarder_batch`) and the
261
+ first and last sweep. A withdrawn deposit loses its links. No brand sits on the
262
+ link: the exchange is named by the `labels` of its two ends. Read it anchored
263
+ on the deposit, never on a hot wallet. A trail that reaches it ends there.
264
+
253
265
  ### Swap attribution
254
266
 
255
267
  Swap attribution is read from `SWAPPED`, the aggregate (`strength`, pools,
@@ -271,10 +283,10 @@ asset, with `asset` and `amount_raw_sum` (and `fees_raw_sum` on a removal).
271
283
 
272
284
  | Form | Syntax | Supported |
273
285
  | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
274
- | Quantified path | `MATCH p = (a:Address WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address)` | ✅ upper bound ≤ 5 |
275
- | One shortest path | `MATCH p = SHORTEST 1 (a:Address {address: $from} WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address {address: $to})` | ✅ upper bound ≤ 5 |
276
- | Any shortest path | `MATCH p = ANY SHORTEST (a:Address {address: $from} WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address {address: $to})` | ✅ upper bound ≤ 5 |
277
- | Open target | `MATCH SHORTEST 1 (a:Address {address: $addr} WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address)` | ✅ upper bound ≤ 5 |
286
+ | Quantified path | `MATCH p = (a:Address WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"] AND NOT via:Exchange){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address)` | ✅ upper bound ≤ 5 |
287
+ | One shortest path | `MATCH p = SHORTEST 1 (a:Address {address: $from} WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"] AND NOT via:Exchange){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address {address: $to})` | ✅ upper bound ≤ 5 |
288
+ | Any shortest path | `MATCH p = ANY SHORTEST (a:Address {address: $from} WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"] AND NOT via:Exchange){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address {address: $to})` | ✅ upper bound ≤ 5 |
289
+ | Open target | `MATCH SHORTEST 1 (a:Address {address: $addr} WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"]) (()-[:FLOWED_TO\|SWAPPED]-(via:Address) WHERE NOT via:Pool AND NOT via:Protocol AND NOT via:System AND NOT via.address IN ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"] AND NOT via:Exchange){0,4} ()-[:FLOWED_TO\|SWAPPED]-(b:Address)` | ✅ upper bound ≤ 5 |
278
290
 
279
291
  Every form above carries the pool guard and walks `SWAPPED` beside
280
292
  `FLOWED_TO`. `WHERE NOT a:Pool` keeps the walk from starting at a `:Pool`, the
@@ -406,6 +418,10 @@ while it has a live label of that role. A flag is never `false`, so test it
406
418
  with `IS NOT NULL` or `IS NULL`, not `= false`. A withdrawn label removes its
407
419
  node label and its flag. Only `is_exchange` ends a walk.
408
420
 
421
+ An `:Exchange` address also carries `cex_role`, which wallet of its exchange it
422
+ is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. It is absent when
423
+ no live exchange label names a role.
424
+
409
425
  The labels layer adds three judgement marks with no flag: `:Poisoned` (a
410
426
  look-alike address that sent worthless dust), `:Targeted` (a poisoning target
411
427
  not yet proven to have lost money) and `:OnMoneyTrail` (on the trail the