chain-insights 0.85.1 → 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 (90) 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-BCk6ldOs.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-BCk6ldOs.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-BG3Ihrd2.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-DhzNC3wD.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CJxDbgI_.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-hpmah4XX.mjs → token-lookup-Ck0q7crJ.mjs} +3 -6
  54. package/dist/token-lookup-Ck0q7crJ.mjs.map +1 -0
  55. package/dist/{token-lookup-BhoDUqiB.cjs → token-lookup-DLe4erP9.cjs} +2 -5
  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 +192 -10
  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-CJxDbgI_.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/token-lookup-hpmah4XX.mjs.map +0 -1
  90. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -0,0 +1,806 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
+ const require_dex_registry = require("./dex-registry-CyR3GyRr.cjs");
3
+ const require_exchange_registry = require("./exchange-registry-CEgkeQV1.cjs");
4
+ const require_graph_schema = require("./graph-schema-Bn3txQCj.cjs");
5
+ const require_print_result = require("./print-result-BYppJlUi.cjs");
6
+ const require_token_lookup = require("./token-lookup-DLe4erP9.cjs");
7
+ // src/mcp/risk-word.ts
8
+ /** The levels, lowest first: critical > high > medium > low > none. */
9
+ const RISK_LEVELS = [
10
+ "none",
11
+ "low",
12
+ "medium",
13
+ "high",
14
+ "critical"
15
+ ];
16
+ /** The questions whose words give the rules word. A judgement's level is always none today. */
17
+ const RULES_QUESTIONS = [
18
+ "evidence",
19
+ "identity",
20
+ "judgement"
21
+ ];
22
+ /**
23
+ * A word whose dictionary item answers the question `judgement` reaches a
24
+ * reader as `pattern`, with its value: a judgement shows a pattern and accuses
25
+ * nobody. That holds for `suspect:FAKE_TOKEN` and for `scam:FAKE_TOKEN` alike.
26
+ */
27
+ const JUDGEMENT_WORD_SHOWN = "pattern";
28
+ function levelRank(level) {
29
+ return RISK_LEVELS.indexOf(level);
30
+ }
31
+ /** The rank of an answer's word: unscored below low, so any spoken word outranks it. */
32
+ function riskWordRank(word) {
33
+ return word === "unscored" ? -1 : levelRank(word);
34
+ }
35
+ const isLevel = (value) => RISK_LEVELS.includes(value);
36
+ /** One card entry split at its first colon: `word` or `word:VALUE`. A value may hold colons. */
37
+ function splitCardEntry(entry) {
38
+ const text = entry.trim();
39
+ const cut = text.indexOf(":");
40
+ if (cut < 0) return {
41
+ word: text,
42
+ value: null
43
+ };
44
+ const value = text.slice(cut + 1).trim();
45
+ return {
46
+ word: text.slice(0, cut).trim(),
47
+ value: value === "" ? null : value
48
+ };
49
+ }
50
+ /**
51
+ * The dictionary item of one card entry, by word and value only, whatever
52
+ * card list the entry came from: the item of the same word and the same value
53
+ * (compared without case), else the item of that word with no value. Null for
54
+ * a word the dictionary does not hold. The item's question is the entry's:
55
+ * the graph writes `scam:FAKE_TOKEN_LP` in `evidence`, and the dictionary
56
+ * says it is a judgement of level none.
57
+ */
58
+ function cardWordOf(entry, dictionaryWords) {
59
+ const { word, value } = splitCardEntry(entry);
60
+ if (word === "") return null;
61
+ const wanted = word.toLowerCase();
62
+ const items = dictionaryWords.filter((item) => item.word.toLowerCase() === wanted);
63
+ if (value !== null) {
64
+ const exact = items.find((item) => item.value?.toLowerCase() === value.toLowerCase());
65
+ if (exact) return exact;
66
+ }
67
+ return items.find((item) => item.value === void 0) ?? null;
68
+ }
69
+ /**
70
+ * The reason of one card entry, or null for a word the dictionary does not
71
+ * hold. Its question, level, standing and plain sentence are the dictionary
72
+ * item's; the value is the entry's own, as the card wrote it.
73
+ */
74
+ function reasonOf(entry, dictionaryWords) {
75
+ const item = cardWordOf(entry, dictionaryWords);
76
+ if (!item || !isLevel(item.level)) return null;
77
+ const { word, value } = splitCardEntry(entry);
78
+ return {
79
+ word: item.question === "judgement" ? JUDGEMENT_WORD_SHOWN : word.toLowerCase(),
80
+ ...value !== null ? { value } : {},
81
+ question: item.question,
82
+ ...item.standing ? { standing: item.standing } : {},
83
+ level: item.level,
84
+ plain: item.plain
85
+ };
86
+ }
87
+ /** The highest level among the reasons of the rules questions; none when no reason carries one. */
88
+ function rulesWordOf(reasons) {
89
+ let best = "none";
90
+ for (const reason of reasons) {
91
+ if (!RULES_QUESTIONS.includes(reason.question)) continue;
92
+ if (levelRank(reason.level) > levelRank(best)) best = reason.level;
93
+ }
94
+ return best;
95
+ }
96
+ /** The model's word from the node's risk_level: HIGH, MEDIUM, LOW in any case; anything else is not_scored. */
97
+ function modelWordOf(riskLevel) {
98
+ const level = typeof riskLevel === "string" ? riskLevel.trim().toLowerCase() : "";
99
+ return level === "high" || level === "medium" || level === "low" ? level : "not_scored";
100
+ }
101
+ /** The model's number, unchanged: a finite number from 0 to 1, else null. */
102
+ function modelScoreOf(riskScore) {
103
+ const score = typeof riskScore === "number" ? riskScore : typeof riskScore === "string" && riskScore.trim() !== "" ? Number(riskScore) : NaN;
104
+ return Number.isFinite(score) && score >= 0 && score <= 1 ? score : null;
105
+ }
106
+ /** The one sentence of the model's reason per level: the same for every address. */
107
+ const MODEL_REASON_PLAIN = {
108
+ high: "The risk model scores this address high.",
109
+ medium: "The risk model scores this address medium.",
110
+ low: "The risk model scores this address low."
111
+ };
112
+ /** The reason a model-set word carries: a prediction, and said as one. */
113
+ function modelReasonOf(modelWord) {
114
+ return {
115
+ word: "model",
116
+ question: "model",
117
+ standing: "predicted",
118
+ level: modelWord,
119
+ plain: MODEL_REASON_PLAIN[modelWord]
120
+ };
121
+ }
122
+ /**
123
+ * The word: the higher of the rules word and the model word. `unscored` when
124
+ * neither speaks. The score is the model's, never one made for a label.
125
+ */
126
+ function riskOf(input) {
127
+ const { rulesWord, modelWord } = input;
128
+ const score = modelScoreOf(input.score);
129
+ if (rulesWord === "none" && modelWord === "not_scored") return {
130
+ word: "unscored",
131
+ score,
132
+ rules_word: rulesWord,
133
+ model_word: modelWord,
134
+ set_by: "none"
135
+ };
136
+ const rules = levelRank(rulesWord);
137
+ const model = modelWord === "not_scored" ? levelRank("none") : levelRank(modelWord);
138
+ const setBy = modelWord === "not_scored" || rules > model ? "rules" : model > rules ? "model" : "both";
139
+ return {
140
+ word: RISK_LEVELS[Math.max(rules, model)],
141
+ score,
142
+ rules_word: rulesWord,
143
+ model_word: modelWord,
144
+ set_by: setBy
145
+ };
146
+ }
147
+ // src/mcp/row-values.ts
148
+ /**
149
+ * The values of one graph answer row, read the same way by every risk tool:
150
+ * a list of words, a number, a text, a full address, an epoch time as UTC
151
+ * text, and the rows and refusal of one batch member. Pure: no read.
152
+ */
153
+ const ADDRESS_INPUT$1 = /^0x[0-9a-fA-F]{40}$/;
154
+ /** The refusal codes a member's text may name anywhere in it. */
155
+ const NAMED_CODE = /\b(query_timeout|family_behind|anchor_missing)\b/;
156
+ function isRecord(value) {
157
+ return !!value && typeof value === "object" && !Array.isArray(value);
158
+ }
159
+ /** The non-empty strings of a list, trimmed; [] for anything else. */
160
+ const strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" && v.trim() !== "").map((v) => v.trim()) : [];
161
+ /** A finite number, or a text that holds one; null for anything else. */
162
+ const numberOrNull = (value) => {
163
+ if (typeof value === "number" && Number.isFinite(value)) return value;
164
+ if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value);
165
+ return null;
166
+ };
167
+ const textOrNull = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
168
+ /** A full 0x address in lowercase, or null. */
169
+ const addressOrNull = (value) => typeof value === "string" && ADDRESS_INPUT$1.test(value.trim()) ? value.trim().toLowerCase() : null;
170
+ /** The UTC text of an epoch-millisecond time, or null. */
171
+ const utcOrNull = (value) => {
172
+ const ms = numberOrNull(value);
173
+ return require_print_result.isEpochMs(ms) ? require_print_result.utcText(ms) : null;
174
+ };
175
+ const memberAnswered = (member) => member?.ok === true && Array.isArray(member.results);
176
+ const memberRows = (member) => memberAnswered(member) ? member.results.filter(isRecord) : [];
177
+ /** Why a member did not answer: its code, as a refusal names it, and its text. */
178
+ function memberRefusal(id, member) {
179
+ if (!member) return {
180
+ code: "not_answered",
181
+ reason: `the ${id} read is missing from the batch answer`
182
+ };
183
+ const text = typeof member.error === "string" ? member.error.trim() : "";
184
+ if (text === "") return {
185
+ code: "not_answered",
186
+ reason: `the ${id} read did not answer`
187
+ };
188
+ const refusal = require_token_lookup.refusalOf({ content: [{
189
+ type: "text",
190
+ text
191
+ }] });
192
+ return {
193
+ code: (refusal.code === "not_served" ? NAMED_CODE.exec(text)?.[1] : void 0) ?? refusal.code,
194
+ reason: refusal.text
195
+ };
196
+ }
197
+ // src/mcp/address-risk.ts
198
+ var address_risk_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
199
+ AML_ADDRESS_RISK_DESCRIPTION: () => AML_ADDRESS_RISK_DESCRIPTION,
200
+ AML_ADDRESS_RISK_TITLE: () => AML_ADDRESS_RISK_TITLE,
201
+ AML_ADDRESS_RISK_TOOL: () => AML_ADDRESS_RISK_TOOL,
202
+ handleAmlAddressRisk: () => handleAmlAddressRisk
203
+ });
204
+ const AML_ADDRESS_RISK_TOOL = "aml_address_risk";
205
+ const AML_ADDRESS_RISK_SCHEMA = "chain-insights.aml-address-risk.v2";
206
+ const AML_ADDRESS_RISK_TITLE = "Address risk";
207
+ const AML_ADDRESS_RISK_DESCRIPTION = `Answers who one address is and how risky it is: its identity, wallet roles and behaviour, its risk word with every reason, the risk model level and score, the partners it exchanged money with (1 USD or more, the 25 newest each way) that carry a risk word of medium or above, and the exchange wallets its money came from or reached. Three reads anchored on the address, in two calls (the node first), billed as any read. risk.word is the higher of what labels prove (rules_word) and what the risk model predicts (model_word); critical comes only from a label. risk.score is the model number from 0 to 1, or null: a label never makes a number. unscored means neither labels nor the model speak about the address: it is not low and not safe. A risky partner is listed beside the word and never changes it. A hub (more than 50,000 links, such as the zero address or a pool manager) has its counterparties not ranked: exposure.hub is true, counterparties_read is 0, and not_read names counterparties; ask about one counterparty, or one token, instead. The tool states facts and measures; you write the judgement: say which reasons you rely on, say when the word comes from the model alone (set_by model) that it is a prediction, never call an address safe, and name a part listed in not_read as not read. Write every address in full, all 42 characters. Pass surroundings: true for the nodes and money links behind the answer, to draw.`;
208
+ const AML_ADDRESS_RISK_ANNOTATIONS = {
209
+ readOnlyHint: true,
210
+ idempotentHint: true,
211
+ openWorldHint: false
212
+ };
213
+ /** The partners kept per direction, the newest first. One more is read to know whether more exist. */
214
+ const PARTNER_LIMIT = 25;
215
+ /** The money floor of a partner link, in USD: a link under it is dust, filtered by the read. */
216
+ const EXPOSURE_FLOOR_USD = 1;
217
+ /** The most nodes the surroundings carry. */
218
+ const SURROUNDINGS_NODE_LIMIT = 60;
219
+ /** The addresses that are never a partner: tokens minted from and burned to them. */
220
+ const ZERO_ADDRESSES = ["0x0000000000000000000000000000000000000000", "0x000000000000000000000000000000000000dead"];
221
+ /** A full address as a caller may type it: 0x plus 40 hex characters, any case. */
222
+ const ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/;
223
+ const ADDRESS_READ = /^0x[0-9a-f]{40}$/;
224
+ function assertReadAddress(address) {
225
+ if (!ADDRESS_READ.test(address)) throw new Error(`address risk: ${JSON.stringify(address)} is not a lowercase 0x address`);
226
+ }
227
+ /**
228
+ * The node read: the card, the model's level and score, and the exchange role.
229
+ * `extra` adds columns of the node `a` (a token's standard, a pool's sums).
230
+ */
231
+ function addressNodeQuery(address, extra = []) {
232
+ assertReadAddress(address);
233
+ const more = extra.length > 0 ? `, ${extra.join(", ")}` : "";
234
+ return `USE topology MATCH (a:Address {address: "${address}"}) RETURN labels(a) AS node_labels, a.card_version AS card_version, a.identity AS identity, a.identity_name AS identity_name, a.identities AS identities, a.address_roles AS address_roles, a.behaviour AS behaviour, a.evidence AS evidence, a.judgements AS judgements, a.sources AS sources, a.risk_level AS risk_level, a.risk_score AS risk_score, ${require_graph_schema.exchangeRoleRead("a")} AS exchange_role, a.degree_total AS degree_total, a.degree_out AS degree_out${more} LIMIT 1`;
235
+ }
236
+ /**
237
+ * A hub has more links than this. Ranking a hub's money links by amount is
238
+ * what costs (9 s for the zero address, 17.6 s for a pool manager, against
239
+ * under 3.5 s for every other case measured): a hub's partner reads are not
240
+ * sent, and its counterparties are not ranked.
241
+ */
242
+ const HUB_DEGREE = 5e4;
243
+ /** The link count of a hub node, or null: a node whose degree is missing is not a hub. */
244
+ function hubDegreeOf(row) {
245
+ const degree = numberOrNull(row?.degree_total);
246
+ return degree !== null && degree > HUB_DEGREE ? degree : null;
247
+ }
248
+ /** The not-read entry of a hub's counterparties: what to ask instead. */
249
+ function hubNotRead(degree) {
250
+ return {
251
+ part: "counterparties",
252
+ code: "hub",
253
+ reason: `This address has ${degree} links. Its counterparties are not ranked: ask about one counterparty, or one token.`
254
+ };
255
+ }
256
+ /** A partner read: the newest money links of one direction, one more than kept. */
257
+ function addressPartnerQuery(address, direction) {
258
+ assertReadAddress(address);
259
+ const anchor = `(a:Address {address: "${address}"})`;
260
+ return `USE topology MATCH ${direction === "in" ? `(b:Address)-[f:FLOWED_TO]->${anchor}` : `${anchor}-[f:FLOWED_TO]->(b:Address)`} WHERE f.amount_usd_sum >= ${EXPOSURE_FLOOR_USD} RETURN b.address AS address, labels(b) AS node_labels, b.identity AS identity, b.identity_name AS identity_name, b.identities AS identities, b.evidence AS evidence, b.judgements AS judgements, b.risk_level AS risk_level, ${require_graph_schema.exchangeRoleRead("b")} AS exchange_role, f.amount_usd_sum AS tokens_worth_usd, f.tx_count AS tx_count, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp ORDER BY f.last_seen_timestamp DESC LIMIT 26`;
261
+ }
262
+ /** The three batch members of one address, their ids under `prefix`: `${prefix}node`, `${prefix}in`, `${prefix}out`. */
263
+ function addressRiskQueries(address, prefix = "") {
264
+ return [
265
+ {
266
+ id: `${prefix}node`,
267
+ query: addressNodeQuery(address)
268
+ },
269
+ {
270
+ id: `${prefix}in`,
271
+ query: addressPartnerQuery(address, "in")
272
+ },
273
+ {
274
+ id: `${prefix}out`,
275
+ query: addressPartnerQuery(address, "out")
276
+ }
277
+ ];
278
+ }
279
+ const answered = memberAnswered;
280
+ const rowsOf = memberRows;
281
+ function notReadOf(part, id, member) {
282
+ return {
283
+ part,
284
+ ...memberRefusal(id, member)
285
+ };
286
+ }
287
+ /** The kind of an address from its node labels: Pool wins over Token over Contract over Account. */
288
+ function kindOf(nodeLabels) {
289
+ if (nodeLabels.includes("Pool")) return "pool";
290
+ if (nodeLabels.includes("Token")) return "token";
291
+ if (nodeLabels.includes("Contract")) return "contract";
292
+ if (nodeLabels.includes("Account")) return "account";
293
+ return "unknown";
294
+ }
295
+ /**
296
+ * The reasons and the word of one row: the top identity, every other identity
297
+ * word that carries a level, the entries of evidence and judgements, and the
298
+ * model level. Each entry is read by the dictionary, whatever list it came from.
299
+ */
300
+ function rowRisk(row, dictionary) {
301
+ const reasons = [];
302
+ const unknown = [];
303
+ const take = (entry, keep = () => true) => {
304
+ const reason = reasonOf(entry, dictionary);
305
+ if (reason) {
306
+ if (keep(reason)) reasons.push(reason);
307
+ } else {
308
+ const { word } = splitCardEntry(entry);
309
+ if (word !== "" && !unknown.includes(word)) unknown.push(word);
310
+ }
311
+ };
312
+ const identity = textOrNull(row?.identity);
313
+ if (identity) take(identity);
314
+ for (const word of strings(row?.identities)) {
315
+ if (word.toLowerCase() === identity?.toLowerCase()) continue;
316
+ take(word, (reason) => reason.level !== "none");
317
+ }
318
+ for (const entry of strings(row?.evidence)) take(entry);
319
+ for (const entry of strings(row?.judgements)) take(entry);
320
+ const modelWord = modelWordOf(row?.risk_level);
321
+ const risk = riskOf({
322
+ rulesWord: rulesWordOf(reasons),
323
+ modelWord,
324
+ score: modelScoreOf(row?.risk_score)
325
+ });
326
+ if (modelWord !== "not_scored" && (risk.set_by === "model" || risk.set_by === "both")) reasons.push(modelReasonOf(modelWord));
327
+ return {
328
+ ...risk,
329
+ reasons,
330
+ unknown_words: unknown
331
+ };
332
+ }
333
+ function isTokenContract(nodeLabels) {
334
+ return nodeLabels.includes("Token") && !nodeLabels.includes("Pool");
335
+ }
336
+ /** The exchange of a partner that is an exchange wallet, or null when it is none. */
337
+ function exchangeOfPartner(address, row, nodeLabels, exchangeRows) {
338
+ const identity = textOrNull(row.identity)?.toLowerCase();
339
+ const role = textOrNull(row.exchange_role)?.toLowerCase() ?? null;
340
+ if (identity !== "exchange" && role === null && !nodeLabels.includes("Exchange")) return null;
341
+ const name = textOrNull(row.identity_name);
342
+ return {
343
+ exchange: (require_exchange_registry.exchangeOfWallet(address, exchangeRows)?.entry ?? (name ? require_exchange_registry.exchangeOfLabels([name], exchangeRows) : null))?.exchange ?? name,
344
+ exchange_role: role
345
+ };
346
+ }
347
+ /** The partners of one direction, the token contracts and zero addresses dropped and counted. */
348
+ function partnersOf(member, direction, dictionary, exchangeRows) {
349
+ const rows = rowsOf(member);
350
+ const partners = [];
351
+ let leftOut = 0;
352
+ for (const row of rows.slice(0, PARTNER_LIMIT)) {
353
+ const address = addressOrNull(row.address);
354
+ if (!address) continue;
355
+ const nodeLabels = strings(row.node_labels);
356
+ if (isTokenContract(nodeLabels) || ZERO_ADDRESSES.includes(address)) {
357
+ leftOut += 1;
358
+ continue;
359
+ }
360
+ partners.push({
361
+ address,
362
+ direction,
363
+ row,
364
+ kind: kindOf(nodeLabels),
365
+ risk: rowRisk(row, dictionary),
366
+ exchange: exchangeOfPartner(address, row, nodeLabels, exchangeRows)
367
+ });
368
+ }
369
+ return {
370
+ partners,
371
+ leftOut,
372
+ truncated: rows.length > PARTNER_LIMIT
373
+ };
374
+ }
375
+ function riskyPartnerOf(partner) {
376
+ return {
377
+ address: partner.address,
378
+ direction: partner.direction,
379
+ risk_word: partner.risk.word,
380
+ set_by: partner.risk.set_by,
381
+ reasons: partner.risk.reasons,
382
+ tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),
383
+ tx_count: numberOrNull(partner.row.tx_count),
384
+ first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),
385
+ last_seen_utc: utcOrNull(partner.row.last_seen_timestamp)
386
+ };
387
+ }
388
+ const MEDIUM_RANK = levelRank("medium");
389
+ const wordRank = riskWordRank;
390
+ /** The nodes and money links behind the answer, from the rows already read. */
391
+ function surroundingsOf(subject, partners, truncated) {
392
+ const nodes = [subject];
393
+ const listed = /* @__PURE__ */ new Set([subject.address]);
394
+ let capped = false;
395
+ for (const partner of partners) {
396
+ if (listed.has(partner.address)) continue;
397
+ if (nodes.length >= SURROUNDINGS_NODE_LIMIT) {
398
+ capped = true;
399
+ continue;
400
+ }
401
+ listed.add(partner.address);
402
+ nodes.push({
403
+ address: partner.address,
404
+ role: partner.exchange ? "exchange_end" : "partner",
405
+ kind: partner.kind,
406
+ name: partner.exchange?.exchange ?? textOrNull(partner.row.identity_name),
407
+ risk_word: partner.risk.word,
408
+ model_level: partner.risk.model_word
409
+ });
410
+ }
411
+ const links = [];
412
+ for (const partner of partners) {
413
+ if (!listed.has(partner.address)) continue;
414
+ const sent = partner.direction === "sent_to_subject";
415
+ links.push({
416
+ from_address: sent ? partner.address : subject.address,
417
+ to_address: sent ? subject.address : partner.address,
418
+ link: "FLOWED_TO",
419
+ tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),
420
+ first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),
421
+ last_seen_utc: utcOrNull(partner.row.last_seen_timestamp)
422
+ });
423
+ }
424
+ return {
425
+ nodes,
426
+ links,
427
+ truncated: truncated || capped
428
+ };
429
+ }
430
+ /**
431
+ * The address answer built from its batch members, or why it cannot be. Only
432
+ * a node read that did not answer is a failure; a partner read that did not
433
+ * answer is named in not_read and the answer still stands.
434
+ */
435
+ function addressRiskFromMembers(network, address, members, dictionary, exchangeRows, prefix = "", options = {}) {
436
+ const nodeId = `${prefix}node`;
437
+ const node = members.get(nodeId);
438
+ if (!answered(node)) {
439
+ if (!node) return { failure: `the ${nodeId} read is missing from the batch answer` };
440
+ return { failure: typeof node.error === "string" && node.error.trim() !== "" ? node.error : `the ${nodeId} read did not answer` };
441
+ }
442
+ const nodeRow = rowsOf(node)[0];
443
+ const base = {
444
+ schema: AML_ADDRESS_RISK_SCHEMA,
445
+ tool: AML_ADDRESS_RISK_TOOL,
446
+ network,
447
+ address
448
+ };
449
+ if (!nodeRow) return { result: {
450
+ ...base,
451
+ found: false,
452
+ kind: "unknown",
453
+ identity: null,
454
+ roles: [],
455
+ behaviour: null,
456
+ risk: {
457
+ word: "unscored",
458
+ score: null,
459
+ rules_word: "none",
460
+ model_word: "not_scored",
461
+ set_by: "none",
462
+ reasons: [],
463
+ unknown_words: [],
464
+ card_version: null
465
+ },
466
+ model: {
467
+ level: "not_scored",
468
+ score: null,
469
+ scored: false
470
+ },
471
+ exposure: null,
472
+ exchange_ends: [],
473
+ not_read: [],
474
+ ...options.surroundings === true ? { surroundings: {
475
+ nodes: [{
476
+ address,
477
+ role: "subject",
478
+ kind: "unknown",
479
+ name: null,
480
+ risk_word: "unscored",
481
+ model_level: "not_scored"
482
+ }],
483
+ links: [],
484
+ truncated: false
485
+ } } : {}
486
+ } };
487
+ const risk = rowRisk(nodeRow, dictionary);
488
+ const kind = kindOf(strings(nodeRow.node_labels));
489
+ const identityWord = textOrNull(nodeRow.identity);
490
+ const identityName = textOrNull(nodeRow.identity_name);
491
+ const notRead = [];
492
+ const degree = numberOrNull(nodeRow.degree_total);
493
+ const hub = options.hubGuard === true ? hubDegreeOf(nodeRow) : null;
494
+ if (hub !== null) notRead.push(hubNotRead(hub));
495
+ const directions = hub !== null ? [] : [{
496
+ id: `${prefix}in`,
497
+ part: "senders",
498
+ direction: "sent_to_subject"
499
+ }, {
500
+ id: `${prefix}out`,
501
+ part: "receivers",
502
+ direction: "received_from_subject"
503
+ }];
504
+ const partners = [];
505
+ let leftOut = 0;
506
+ let truncated = false;
507
+ for (const { id, part, direction } of directions) {
508
+ const member = members.get(id);
509
+ if (!answered(member)) {
510
+ notRead.push(notReadOf(part, id, member));
511
+ continue;
512
+ }
513
+ const read = partnersOf(member, direction, dictionary, exchangeRows);
514
+ partners.push(...read.partners);
515
+ leftOut += read.leftOut;
516
+ truncated ||= read.truncated;
517
+ }
518
+ const exchangeEnds = partners.filter((partner) => partner.exchange !== null).map((partner) => ({
519
+ address: partner.address,
520
+ direction: partner.direction,
521
+ exchange: partner.exchange.exchange,
522
+ exchange_role: partner.exchange.exchange_role,
523
+ tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),
524
+ first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),
525
+ last_seen_utc: utcOrNull(partner.row.last_seen_timestamp)
526
+ }));
527
+ const result = {
528
+ ...base,
529
+ found: true,
530
+ kind,
531
+ identity: identityWord ? {
532
+ word: identityWord,
533
+ name: identityName
534
+ } : null,
535
+ roles: strings(nodeRow.address_roles),
536
+ behaviour: textOrNull(nodeRow.behaviour),
537
+ risk: {
538
+ ...risk,
539
+ card_version: textOrNull(nodeRow.card_version)
540
+ },
541
+ model: {
542
+ level: risk.model_word,
543
+ score: risk.score,
544
+ scored: risk.model_word !== "not_scored"
545
+ },
546
+ exposure: {
547
+ floor_usd: EXPOSURE_FLOOR_USD,
548
+ hub: hub !== null,
549
+ degree_total: degree,
550
+ counterparties_read: partners.length,
551
+ left_out: leftOut,
552
+ truncated,
553
+ with_risk: partners.filter((partner) => wordRank(partner.risk.word) >= MEDIUM_RANK).map(riskyPartnerOf),
554
+ pattern_partners: partners.filter((partner) => wordRank(partner.risk.word) < MEDIUM_RANK && partner.risk.reasons.some((reason) => reason.question === "judgement")).length
555
+ },
556
+ exchange_ends: exchangeEnds,
557
+ not_read: notRead
558
+ };
559
+ if (options.surroundings === true) result.surroundings = surroundingsOf({
560
+ address,
561
+ role: "subject",
562
+ kind,
563
+ name: identityName,
564
+ risk_word: risk.word,
565
+ model_level: risk.model_word
566
+ }, partners, truncated);
567
+ return { result };
568
+ }
569
+ function errorResult(text) {
570
+ return {
571
+ content: [{
572
+ type: "text",
573
+ text
574
+ }],
575
+ isError: true
576
+ };
577
+ }
578
+ function textResult(structured) {
579
+ return {
580
+ content: [{
581
+ type: "text",
582
+ text: JSON.stringify(structured, null, 2)
583
+ }],
584
+ structuredContent: structured,
585
+ isError: false
586
+ };
587
+ }
588
+ /** aml_address_risk, {network, address, surroundings?}. Every argument is checked before a read is sent. */
589
+ async function handleAmlAddressRisk(args, deps) {
590
+ const record = isRecord(args) ? args : {};
591
+ let network;
592
+ try {
593
+ network = require_dex_registry.normalizeDexNetwork(record.network);
594
+ } catch (err) {
595
+ return errorResult(err instanceof require_dex_registry.DexRegistryError ? err.message : `invalid_network: ${err.message}`);
596
+ }
597
+ const raw = typeof record.address === "string" ? record.address.trim() : "";
598
+ if (!ADDRESS_INPUT.test(raw)) return errorResult("invalid_address: address is required: 0x plus 40 hex characters. A name or a ticker is not an address: call meta_token_lookup or meta_exchange_lookup first.");
599
+ if (record.surroundings !== void 0 && typeof record.surroundings !== "boolean") return errorResult("invalid_surroundings: surroundings is true or false.");
600
+ const address = raw.toLowerCase();
601
+ const surroundings = record.surroundings === true;
602
+ const unavailable = await deps.unavailable?.();
603
+ if (unavailable) return errorResult(`No address risk read was sent: ${unavailable} There is no answer yet, which is not "no risk": try again later.`);
604
+ let dictionary;
605
+ try {
606
+ const card = await deps.loadAddressCard();
607
+ if (!card) throw new Error("no copy of the address card dictionary is available");
608
+ dictionary = card.document.words;
609
+ } catch (err) {
610
+ return errorResult(`No address risk read was sent: the address card dictionary did not load (${err.message}). There is no answer yet, which is not "no risk".`);
611
+ }
612
+ let exchangeRows = [];
613
+ try {
614
+ exchangeRows = (await deps.loadExchangeRegistry(network)).document.rows;
615
+ } catch {}
616
+ const read = async (queries) => {
617
+ let answer;
618
+ try {
619
+ answer = await deps.graphQueryBatch({
620
+ network,
621
+ queries
622
+ });
623
+ } catch (err) {
624
+ return { failure: `${deps.describeFailure(err)} This is not "no risk": send the same call again once.` };
625
+ }
626
+ const members = require_token_lookup.membersOf(answer);
627
+ if (members.size === 0) return { failure: `${answer.isError === true ? require_token_lookup.refusalOf(answer).text : "the batch answer held no reads"} This is not "no risk".` };
628
+ return { members };
629
+ };
630
+ const [nodeQuery, ...partnerQueries] = addressRiskQueries(address);
631
+ const first = await read([nodeQuery]);
632
+ if ("failure" in first) return errorResult(`The address risk read failed: ${first.failure}`);
633
+ const members = first.members;
634
+ const nodeRow = memberRows(members.get("node"))[0];
635
+ if (nodeRow && hubDegreeOf(nodeRow) === null) {
636
+ const second = await read(partnerQueries);
637
+ if ("failure" in second) for (const { id } of partnerQueries) members.set(id, {
638
+ id,
639
+ ok: false,
640
+ error: second.failure
641
+ });
642
+ else for (const [id, member] of second.members) members.set(id, member);
643
+ }
644
+ const built = addressRiskFromMembers(network, address, members, dictionary, exchangeRows, "", {
645
+ surroundings,
646
+ hubGuard: true
647
+ });
648
+ if ("failure" in built) return errorResult(`The address risk read failed: ${built.failure} This is not "no risk": send the same call again once.`);
649
+ return textResult(built.result);
650
+ }
651
+ Object.defineProperty(exports, "ADDRESS_INPUT", {
652
+ enumerable: true,
653
+ get: function() {
654
+ return ADDRESS_INPUT;
655
+ }
656
+ });
657
+ Object.defineProperty(exports, "AML_ADDRESS_RISK_ANNOTATIONS", {
658
+ enumerable: true,
659
+ get: function() {
660
+ return AML_ADDRESS_RISK_ANNOTATIONS;
661
+ }
662
+ });
663
+ Object.defineProperty(exports, "AML_ADDRESS_RISK_DESCRIPTION", {
664
+ enumerable: true,
665
+ get: function() {
666
+ return AML_ADDRESS_RISK_DESCRIPTION;
667
+ }
668
+ });
669
+ Object.defineProperty(exports, "AML_ADDRESS_RISK_TITLE", {
670
+ enumerable: true,
671
+ get: function() {
672
+ return AML_ADDRESS_RISK_TITLE;
673
+ }
674
+ });
675
+ Object.defineProperty(exports, "AML_ADDRESS_RISK_TOOL", {
676
+ enumerable: true,
677
+ get: function() {
678
+ return AML_ADDRESS_RISK_TOOL;
679
+ }
680
+ });
681
+ Object.defineProperty(exports, "SURROUNDINGS_NODE_LIMIT", {
682
+ enumerable: true,
683
+ get: function() {
684
+ return SURROUNDINGS_NODE_LIMIT;
685
+ }
686
+ });
687
+ Object.defineProperty(exports, "addressNodeQuery", {
688
+ enumerable: true,
689
+ get: function() {
690
+ return addressNodeQuery;
691
+ }
692
+ });
693
+ Object.defineProperty(exports, "addressOrNull", {
694
+ enumerable: true,
695
+ get: function() {
696
+ return addressOrNull;
697
+ }
698
+ });
699
+ Object.defineProperty(exports, "addressPartnerQuery", {
700
+ enumerable: true,
701
+ get: function() {
702
+ return addressPartnerQuery;
703
+ }
704
+ });
705
+ Object.defineProperty(exports, "addressRiskFromMembers", {
706
+ enumerable: true,
707
+ get: function() {
708
+ return addressRiskFromMembers;
709
+ }
710
+ });
711
+ Object.defineProperty(exports, "address_risk_exports", {
712
+ enumerable: true,
713
+ get: function() {
714
+ return address_risk_exports;
715
+ }
716
+ });
717
+ Object.defineProperty(exports, "assertReadAddress", {
718
+ enumerable: true,
719
+ get: function() {
720
+ return assertReadAddress;
721
+ }
722
+ });
723
+ Object.defineProperty(exports, "handleAmlAddressRisk", {
724
+ enumerable: true,
725
+ get: function() {
726
+ return handleAmlAddressRisk;
727
+ }
728
+ });
729
+ Object.defineProperty(exports, "hubDegreeOf", {
730
+ enumerable: true,
731
+ get: function() {
732
+ return hubDegreeOf;
733
+ }
734
+ });
735
+ Object.defineProperty(exports, "isRecord", {
736
+ enumerable: true,
737
+ get: function() {
738
+ return isRecord;
739
+ }
740
+ });
741
+ Object.defineProperty(exports, "kindOf", {
742
+ enumerable: true,
743
+ get: function() {
744
+ return kindOf;
745
+ }
746
+ });
747
+ Object.defineProperty(exports, "memberAnswered", {
748
+ enumerable: true,
749
+ get: function() {
750
+ return memberAnswered;
751
+ }
752
+ });
753
+ Object.defineProperty(exports, "memberRefusal", {
754
+ enumerable: true,
755
+ get: function() {
756
+ return memberRefusal;
757
+ }
758
+ });
759
+ Object.defineProperty(exports, "memberRows", {
760
+ enumerable: true,
761
+ get: function() {
762
+ return memberRows;
763
+ }
764
+ });
765
+ Object.defineProperty(exports, "numberOrNull", {
766
+ enumerable: true,
767
+ get: function() {
768
+ return numberOrNull;
769
+ }
770
+ });
771
+ Object.defineProperty(exports, "riskWordRank", {
772
+ enumerable: true,
773
+ get: function() {
774
+ return riskWordRank;
775
+ }
776
+ });
777
+ Object.defineProperty(exports, "rowRisk", {
778
+ enumerable: true,
779
+ get: function() {
780
+ return rowRisk;
781
+ }
782
+ });
783
+ Object.defineProperty(exports, "splitCardEntry", {
784
+ enumerable: true,
785
+ get: function() {
786
+ return splitCardEntry;
787
+ }
788
+ });
789
+ Object.defineProperty(exports, "strings", {
790
+ enumerable: true,
791
+ get: function() {
792
+ return strings;
793
+ }
794
+ });
795
+ Object.defineProperty(exports, "textOrNull", {
796
+ enumerable: true,
797
+ get: function() {
798
+ return textOrNull;
799
+ }
800
+ });
801
+ Object.defineProperty(exports, "utcOrNull", {
802
+ enumerable: true,
803
+ get: function() {
804
+ return utcOrNull;
805
+ }
806
+ });