chain-insights 0.85.2 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -0
  2. package/bin/install.cjs +2 -1
  3. package/dist/{active-q3yViZhc.cjs → active-COPA14FA.cjs} +2 -16
  4. package/dist/{active-D2aabYRF.mjs → active-CyC4jFka.mjs} +2 -7
  5. package/dist/{active-D2aabYRF.mjs.map → active-CyC4jFka.mjs.map} +1 -1
  6. package/dist/address-card-C-NB03XP.cjs +218 -0
  7. package/dist/address-card-LYaT5yz0.mjs +190 -0
  8. package/dist/address-card-LYaT5yz0.mjs.map +1 -0
  9. package/dist/address-risk-B8xTh1iM.mjs +760 -0
  10. package/dist/address-risk-B8xTh1iM.mjs.map +1 -0
  11. package/dist/address-risk-WIKbjqy2.cjs +913 -0
  12. package/dist/{capabilities-Mxa4oQdd.cjs → capabilities-DkNreyv7.cjs} +1 -1
  13. package/dist/{capabilities-bZOr5Ads.mjs → capabilities-w5bNR7F9.mjs} +2 -2
  14. package/dist/{capabilities-bZOr5Ads.mjs.map → capabilities-w5bNR7F9.mjs.map} +1 -1
  15. package/dist/cli.cjs +138 -46
  16. package/dist/cli.mjs +138 -46
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/{deployer-screen-B5yrXZGo.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-B5yrXZGo.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-0SOQ_HFf.cjs → deployer-screen-CFLi7OeH.cjs} +2 -2
  21. package/dist/{dex-registry-BY67f4Ul.mjs → dex-registry-Bkri0--q.mjs} +10 -2
  22. package/dist/{dex-registry-BY67f4Ul.mjs.map → dex-registry-Bkri0--q.mjs.map} +1 -1
  23. package/dist/{dex-registry-BhGJUG9_.cjs → dex-registry-CyR3GyRr.cjs} +20 -0
  24. package/dist/{dex-tool-7BK_gD6H.mjs → dex-tool-D0K_Qx4N.mjs} +4 -4
  25. package/dist/dex-tool-D0K_Qx4N.mjs.map +1 -0
  26. package/dist/{dex-tool-Be9NAuD8.cjs → dex-tool-DQ5Eg0LO.cjs} +3 -3
  27. package/dist/{exchange-deposit-check-C5MseGlZ.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CXHZCHWW.mjs → exchange-deposit-check-DIALj2sm.mjs} +19 -19
  29. package/dist/exchange-deposit-check-DIALj2sm.mjs.map +1 -0
  30. package/dist/{exchange-registry-CT0rRW__.cjs → exchange-registry-CEgkeQV1.cjs} +16 -93
  31. package/dist/{exchange-registry-CoLgHw6d.mjs → exchange-registry-Dr5UtcT5.mjs} +17 -94
  32. package/dist/exchange-registry-Dr5UtcT5.mjs.map +1 -0
  33. package/dist/{exchange-tool-Dc46SJ49.mjs → exchange-tool-B7E29YoQ.mjs} +4 -4
  34. package/dist/exchange-tool-B7E29YoQ.mjs.map +1 -0
  35. package/dist/{exchange-tool-B2SMeC5f.cjs → exchange-tool-CXaUBAd2.cjs} +3 -3
  36. package/dist/{graph-schema-CcrYPpSv.cjs → graph-schema-Bn3txQCj.cjs} +115 -12
  37. package/dist/{graph-schema-CRQuKya1.mjs → graph-schema-DvABR1yl.mjs} +97 -12
  38. package/dist/graph-schema-DvABR1yl.mjs.map +1 -0
  39. package/dist/{layer-routing-YDj-ynG9.cjs → layer-routing-j48SQ8Wk.cjs} +2 -2
  40. package/dist/{layer-routing-DCJVNN6O.mjs → layer-routing-r4IbIQSr.mjs} +3 -3
  41. package/dist/layer-routing-r4IbIQSr.mjs.map +1 -0
  42. package/dist/mcp-proxy.cjs +62 -15
  43. package/dist/mcp-proxy.d.cts.map +1 -1
  44. package/dist/mcp-proxy.d.mts.map +1 -1
  45. package/dist/mcp-proxy.mjs +62 -15
  46. package/dist/mcp-proxy.mjs.map +1 -1
  47. package/dist/public-file-BISyAesm.mjs +133 -0
  48. package/dist/public-file-BISyAesm.mjs.map +1 -0
  49. package/dist/public-file-DDp2CrUl.cjs +138 -0
  50. package/dist/{request-timeout-DxwNijQD.cjs → request-timeout-BXiIt9Jy.cjs} +0 -1
  51. package/dist/{request-timeout-K3ljP0pa.mjs → request-timeout-DetG2xO4.mjs} +2 -2
  52. package/dist/{request-timeout-K3ljP0pa.mjs.map → request-timeout-DetG2xO4.mjs.map} +1 -1
  53. package/dist/{token-lookup-Cf59VdGe.mjs → token-lookup-Ck0q7crJ.mjs} +2 -2
  54. package/dist/{token-lookup-Cf59VdGe.mjs.map → token-lookup-Ck0q7crJ.mjs.map} +1 -1
  55. package/dist/{token-lookup-DqjSRIxd.cjs → token-lookup-DLe4erP9.cjs} +1 -1
  56. package/dist/token-risk-BkwTaKxS.cjs +1004 -0
  57. package/dist/token-risk-XVaN_Yp3.mjs +971 -0
  58. package/dist/token-risk-XVaN_Yp3.mjs.map +1 -0
  59. package/dist/{tool-visibility-D8Up081E.cjs → tool-visibility-BCa-tmyZ.cjs} +11 -2
  60. package/dist/{tool-visibility-DuTds7V4.mjs → tool-visibility-BstrSl4s.mjs} +12 -3
  61. package/dist/tool-visibility-BstrSl4s.mjs.map +1 -0
  62. package/docs/contributing.md +10 -8
  63. package/docs/development.md +5 -5
  64. package/docs/evals.md +16 -1
  65. package/docs/graph-query-compatibility.md +15 -2
  66. package/docs/graph-tools.md +44 -6
  67. package/docs/mcp-proxy.md +206 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +77 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +772 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +77 -0
  74. package/skills/chain-insights-address-risk/agents/openai.yaml +4 -0
  75. package/skills/chain-insights-aml-exchange/SKILL.md +9 -7
  76. package/skills/chain-insights-cypher/SKILL.md +80 -3
  77. package/skills/chain-insights-token-risk/SKILL.md +81 -0
  78. package/skills/chain-insights-token-risk/agents/openai.yaml +4 -0
  79. package/skills/chain-insights-virtuals/reference.md +1 -1
  80. package/dist/dex-tool-7BK_gD6H.mjs.map +0 -1
  81. package/dist/exchange-deposit-check-CXHZCHWW.mjs.map +0 -1
  82. package/dist/exchange-registry-CoLgHw6d.mjs.map +0 -1
  83. package/dist/exchange-tool-Dc46SJ49.mjs.map +0 -1
  84. package/dist/graph-schema-CRQuKya1.mjs.map +0 -1
  85. package/dist/layer-routing-DCJVNN6O.mjs.map +0 -1
  86. package/dist/public-tools-CBszU2oX.cjs +0 -1334
  87. package/dist/public-tools-DVhUjSDV.mjs +0 -1333
  88. package/dist/public-tools-DVhUjSDV.mjs.map +0 -1
  89. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"address-risk-B8xTh1iM.mjs","names":["isRecord","ADDRESS_INPUT"],"sources":["../src/mcp/exposed.ts","../src/mcp/risk-word.ts","../src/mcp/row-values.ts","../src/mcp/address-risk.ts"],"sourcesContent":["/**\n * The exposed blocks of an address: how close it sits to a scam kind.\n *\n * An :Address node may carry `exposed`, JSON text: an array with one block per\n * scam kind, sorted by scam_kind. A block says the address is in the blast\n * radius of a scam kind, a few payments from an address that is. That is a\n * grade below proof: it is never evidence against the address, it sets no\n * risk word, and it carries no number. A node with no `exposed` says nothing\n * here: no row, no \"not available\". `exposed_pass` is the writer's own\n * bookkeeping and is never read.\n *\n * The words come from the card dictionary (registry/address-card.json, list\n * `words`, question `exposure`): the grade word `exposed`, the bands\n * `exposed_band:top|high|raised`, the scam kind names `scam_kind:<kind>` and\n * the `paid_once` sentence. A kind the dictionary does not name is shown by\n * its own kind text. Pure: no read, no clock. A malformed value shows nothing\n * and is logged once, never thrown.\n */\n\nimport type { AddressCardWord } from './address-card.js'\n\nexport const EXPOSED_GRADE = 'exposed' as const\nexport const EXPOSED_BANDS = ['top', 'high', 'raised'] as const\nexport type ExposedBand = (typeof EXPOSED_BANDS)[number]\n\n/** One block of the answer, the writer's facts and the words of the dictionary. */\nexport interface ExposedBlock {\n /** Always `exposed`: a grade below proof, never evidence against the address. */\n grade: typeof EXPOSED_GRADE\n band: ExposedBand\n band_plain: string | null\n scam_kind: string\n scam_kind_name: string\n steps: number\n /** The trail id. */\n path: string | null\n path_address: string | null\n /** The addresses of the way, nearest the address first. */\n way: string[]\n link_payments: number | null\n link_two_way: boolean | null\n day: string | null\n profile: string | null\n paid_once: boolean\n /** The one sentence a reader sees. */\n text: string\n}\n\nconst defaultLog = (line: string): void => {\n process.stderr.write(`[chain-insights] exposed: ${line}\\n`)\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst textOf = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\n\nfunction wordOf(\n dictionary: readonly AddressCardWord[],\n word: string,\n value?: string\n): AddressCardWord | null {\n const items = dictionary.filter((item) => item.question === 'exposure' && item.word === word)\n if (value !== undefined) {\n const wanted = value.toLowerCase()\n const exact = items.find((item) => item.value?.toLowerCase() === wanted)\n if (exact) return exact\n }\n return items.find((item) => item.value === undefined) ?? null\n}\n\n/** The dictionary's name of a scam kind, else the kind text as the writer gave it. */\nfunction kindNameOf(kind: string, dictionary: readonly AddressCardWord[]): string {\n const item = wordOf(dictionary, 'scam_kind', kind)\n return item?.value !== undefined ? item.plain : kind\n}\n\n/** The sentence of one block, from the dictionary's words. */\nexport function exposedText(\n block: Pick<ExposedBlock, 'band' | 'scam_kind_name' | 'steps' | 'way' | 'path_address' | 'paid_once'>,\n dictionary: readonly AddressCardWord[]\n): string {\n // The direction is fixed: the address paid way[0], way[0] paid way[1], ..., the last paid the path\n // address. The sentence never says money came to the address.\n const chain = [...block.way, ...(block.path_address ? [block.path_address] : [])]\n const payments = `${block.steps} payment${block.steps === 1 ? '' : 's'} away`\n let trail = ''\n if (chain.length === 1) trail = `paid ${chain[0]}`\n else if (chain.length > 1) trail = `pays ${chain[0]}` + chain.slice(1).map((a) => `, which paid ${a}`).join('')\n if (trail && block.path_address) trail += ' on the path'\n const parts = [\n `Exposed (${block.band} band): in the blast radius of ${block.scam_kind_name}, ${payments}` +\n (trail ? `: ${trail}` : ''),\n ]\n if (block.paid_once) {\n const paid = wordOf(dictionary, 'paid_once')?.plain ?? 'Paid once, may be a victim'\n parts.push(paid.charAt(0).toLowerCase() + paid.slice(1))\n }\n return parts.join('; ')\n}\n\nfunction blockOf(\n raw: unknown,\n index: number,\n dictionary: readonly AddressCardWord[],\n fault: (line: string) => void\n): ExposedBlock | null {\n if (!isRecord(raw)) {\n fault(`block ${index} is not an object`)\n return null\n }\n const band = (EXPOSED_BANDS as readonly unknown[]).includes(raw.band) ? (raw.band as ExposedBand) : null\n const kind = textOf(raw.scam_kind)\n const steps = typeof raw.steps === 'number' && Number.isInteger(raw.steps) && raw.steps >= 0 ? raw.steps : null\n if (band === null || kind === null || steps === null) {\n fault(`block ${index} has no usable band, scam_kind or steps`)\n return null\n }\n const way = Array.isArray(raw.way) ? raw.way.filter((a): a is string => typeof a === 'string' && a !== '') : []\n const part = {\n band,\n scam_kind_name: kindNameOf(kind, dictionary),\n steps,\n way,\n path_address: textOf(raw.path_address),\n paid_once: raw.paid_once === true,\n }\n return {\n grade: EXPOSED_GRADE,\n band,\n band_plain: wordOf(dictionary, 'exposed_band', band)?.plain ?? null,\n scam_kind: kind,\n scam_kind_name: part.scam_kind_name,\n steps,\n path: textOf(raw.path),\n path_address: part.path_address,\n way,\n link_payments: typeof raw.link_payments === 'number' ? raw.link_payments : null,\n link_two_way: typeof raw.link_two_way === 'boolean' ? raw.link_two_way : null,\n day: textOf(raw.day),\n profile: textOf(raw.profile),\n paid_once: part.paid_once,\n text: exposedText(part, dictionary),\n }\n}\n\n/**\n * The blocks of a node's `exposed` property. Empty when the property is absent,\n * empty or malformed; a malformed value is logged, a block that cannot be read\n * is dropped and logged, and nothing throws.\n */\nexport function exposedOf(\n value: unknown,\n dictionary: readonly AddressCardWord[],\n log: (line: string) => void = defaultLog\n): ExposedBlock[] {\n if (value === undefined || value === null || value === '') return []\n let parsed: unknown = value\n if (typeof value === 'string') {\n try {\n parsed = JSON.parse(value)\n } catch {\n log('the exposed property is not JSON: nothing shown')\n return []\n }\n }\n if (!Array.isArray(parsed)) {\n log('the exposed property is not an array: nothing shown')\n return []\n }\n const blocks: ExposedBlock[] = []\n for (const [index, raw] of parsed.entries()) {\n const block = blockOf(raw, index, dictionary, (line) => log(line))\n if (block) blocks.push(block)\n }\n return blocks\n}\n","/**\n * The risk word of an address: the one fixed rule every risk answer applies.\n *\n * Two signals sit on an :Address node of the graph:\n *\n * rules the card's entries (identity, evidence, judgements), each a word the\n * card dictionary (registry/address-card.json, list `words`) gives a\n * level, a standing and a plain sentence;\n * model the risk model's `risk_level` (HIGH, MEDIUM, LOW, or unscored) and\n * its `risk_score`, a number from 0 to 1.\n *\n * The word of the answer is the higher of the two. A label word is never\n * lowered by the model, and only a label gives `critical`. An address no label\n * and no model speaks about is `unscored`, which is neither `low` nor safe.\n *\n * The word is computed here from the entries, never taken from the node's own\n * `risk` property: a card resolved with an older dictionary may still hold the\n * level a word had then. Pure: no read, no clock.\n */\n\nimport type { AddressCardLevel, AddressCardWord } from './address-card.js'\n\n/** The levels, lowest first: critical > high > medium > low > none. */\nexport const RISK_LEVELS = ['none', 'low', 'medium', 'high', 'critical'] as const satisfies readonly AddressCardLevel[]\nexport type RiskLevel = (typeof RISK_LEVELS)[number]\n\n/** The words an answer's risk may carry. */\nexport const RISK_WORDS = ['critical', 'high', 'medium', 'low', 'unscored'] as const\nexport type RiskWord = (typeof RISK_WORDS)[number]\n\n/** The model's word: it never gives critical. */\nexport const MODEL_WORDS = ['high', 'medium', 'low', 'not_scored'] as const\nexport type ModelWord = (typeof MODEL_WORDS)[number]\n\n/** Who set the word: the labels, the model, both at the same level, or nobody (unscored). */\nexport type SetBy = 'rules' | 'model' | 'both' | 'none'\n\n/** The questions whose words give the rules word. A judgement's level is always none today. */\nexport const RULES_QUESTIONS = ['evidence', 'identity', 'judgement'] as const\n\n/**\n * A word whose dictionary item answers the question `judgement` reaches a\n * reader as `pattern`, with its value: a judgement shows a pattern and accuses\n * nobody. That holds for `suspect:FAKE_TOKEN` and for `scam:FAKE_TOKEN` alike.\n */\nexport const JUDGEMENT_WORD_SHOWN = 'pattern'\n\n/** Why the word is what it is: one card entry, or the model. */\nexport interface Reason {\n word: string\n value?: string\n question: string\n standing?: string\n level: RiskLevel\n plain: string\n}\n\nexport interface Risk {\n word: RiskWord\n score: number | null\n rules_word: RiskLevel\n model_word: ModelWord\n set_by: SetBy\n}\n\nexport function levelRank(level: RiskLevel): number {\n return RISK_LEVELS.indexOf(level)\n}\n\n/** The rank of an answer's word: unscored below low, so any spoken word outranks it. */\nexport function riskWordRank(word: RiskWord): number {\n return word === 'unscored' ? -1 : levelRank(word)\n}\n\nconst isLevel = (value: unknown): value is RiskLevel =>\n (RISK_LEVELS as readonly unknown[]).includes(value)\n\n/** One card entry split at its first colon: `word` or `word:VALUE`. A value may hold colons. */\nexport function splitCardEntry(entry: string): { word: string; value: string | null } {\n const text = entry.trim()\n const cut = text.indexOf(':')\n if (cut < 0) return { word: text, value: null }\n const value = text.slice(cut + 1).trim()\n return { word: text.slice(0, cut).trim(), value: value === '' ? null : value }\n}\n\n/**\n * The dictionary item of one card entry, by word and value only, whatever\n * card list the entry came from: the item of the same word and the same value\n * (compared without case), else the item of that word with no value. Null for\n * a word the dictionary does not hold. The item's question is the entry's:\n * the graph writes `scam:FAKE_TOKEN_LP` in `evidence`, and the dictionary\n * says it is a judgement of level none.\n */\nexport function cardWordOf(\n entry: string,\n dictionaryWords: readonly AddressCardWord[]\n): AddressCardWord | null {\n const { word, value } = splitCardEntry(entry)\n if (word === '') return null\n const wanted = word.toLowerCase()\n const items = dictionaryWords.filter((item) => item.word.toLowerCase() === wanted)\n if (value !== null) {\n const exact = items.find((item) => item.value?.toLowerCase() === value.toLowerCase())\n if (exact) return exact\n }\n return items.find((item) => item.value === undefined) ?? null\n}\n\n/**\n * The reason of one card entry, or null for a word the dictionary does not\n * hold. Its question, level, standing and plain sentence are the dictionary\n * item's; the value is the entry's own, as the card wrote it.\n */\nexport function reasonOf(\n entry: string,\n dictionaryWords: readonly AddressCardWord[]\n): Reason | null {\n const item = cardWordOf(entry, dictionaryWords)\n if (!item || !isLevel(item.level)) return null\n const { word, value } = splitCardEntry(entry)\n const shown = item.question === 'judgement' ? JUDGEMENT_WORD_SHOWN : word.toLowerCase()\n return {\n word: shown,\n ...(value !== null ? { value } : {}),\n question: item.question,\n ...(item.standing ? { standing: item.standing } : {}),\n level: item.level,\n plain: item.plain,\n }\n}\n\n/** The highest level among the reasons of the rules questions; none when no reason carries one. */\nexport function rulesWordOf(reasons: readonly Reason[]): RiskLevel {\n let best: RiskLevel = 'none'\n for (const reason of reasons) {\n if (!(RULES_QUESTIONS as readonly string[]).includes(reason.question)) continue\n if (levelRank(reason.level) > levelRank(best)) best = reason.level\n }\n return best\n}\n\n/** The model's word from the node's risk_level: HIGH, MEDIUM, LOW in any case; anything else is not_scored. */\nexport function modelWordOf(riskLevel: unknown): ModelWord {\n const level = typeof riskLevel === 'string' ? riskLevel.trim().toLowerCase() : ''\n return level === 'high' || level === 'medium' || level === 'low' ? level : 'not_scored'\n}\n\n/** The model's number, unchanged: a finite number from 0 to 1, else null. */\nexport function modelScoreOf(riskScore: unknown): number | null {\n const score =\n typeof riskScore === 'number'\n ? riskScore\n : typeof riskScore === 'string' && riskScore.trim() !== ''\n ? Number(riskScore)\n : Number.NaN\n return Number.isFinite(score) && score >= 0 && score <= 1 ? score : null\n}\n\n/** The one sentence of the model's reason per level: the same for every address. */\nexport const MODEL_REASON_PLAIN: Record<Exclude<ModelWord, 'not_scored'>, string> = {\n high: 'The risk model scores this address high.',\n medium: 'The risk model scores this address medium.',\n low: 'The risk model scores this address low.',\n}\n\n/** The reason a model-set word carries: a prediction, and said as one. */\nexport function modelReasonOf(modelWord: Exclude<ModelWord, 'not_scored'>): Reason {\n return {\n word: 'model',\n question: 'model',\n standing: 'predicted',\n level: modelWord,\n plain: MODEL_REASON_PLAIN[modelWord],\n }\n}\n\n/**\n * The word: the higher of the rules word and the model word. `unscored` when\n * neither speaks. The score is the model's, never one made for a label.\n */\nexport function riskOf(input: {\n rulesWord: RiskLevel\n modelWord: ModelWord\n score: number | null\n}): Risk {\n const { rulesWord, modelWord } = input\n const score = modelScoreOf(input.score)\n if (rulesWord === 'none' && modelWord === 'not_scored') {\n return { word: 'unscored', score, rules_word: rulesWord, model_word: modelWord, set_by: 'none' }\n }\n const rules = levelRank(rulesWord)\n const model = modelWord === 'not_scored' ? levelRank('none') : levelRank(modelWord)\n // Either side speaks here, so the top level is above none.\n const setBy: SetBy =\n modelWord === 'not_scored' || rules > model ? 'rules' : model > rules ? 'model' : 'both'\n const top = RISK_LEVELS[Math.max(rules, model)] as Exclude<RiskLevel, 'none'>\n return {\n word: top,\n score,\n rules_word: rulesWord,\n model_word: modelWord,\n set_by: setBy,\n }\n}\n","/**\n * The values of one graph answer row, read the same way by every risk tool:\n * a list of words, a number, a text, a full address, an epoch time as UTC\n * text, and the rows and refusal of one batch member. Pure: no read.\n */\n\nimport { isEpochMs, utcText } from './timestamp-text.js'\nimport { refusalOf, type Member } from './token-lookup.js'\n\nconst ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\n\n/** The refusal codes a member's text may name anywhere in it. */\nconst NAMED_CODE = /\\b(query_timeout|family_behind|anchor_missing)\\b/\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** The non-empty strings of a list, trimmed; [] for anything else. */\nexport const strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === 'string' && v.trim() !== '').map((v) => v.trim())\n : []\n\n/** A finite number, or a text that holds one; null for anything else. */\nexport const 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\nexport const textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\n\n/** A full 0x address in lowercase, or null. */\nexport const addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null\n\n/** The UTC text of an epoch-millisecond time, or null. */\nexport const utcOrNull = (value: unknown): string | null => {\n const ms = numberOrNull(value)\n return isEpochMs(ms) ? utcText(ms) : null\n}\n\nexport const memberAnswered = (member: Member | undefined): boolean =>\n member?.ok === true && Array.isArray(member.results)\n\nexport const memberRows = (member: Member | undefined): Array<Record<string, unknown>> =>\n memberAnswered(member) ? (member!.results as unknown[]).filter(isRecord) : []\n\n/** Why a member did not answer: its code, as a refusal names it, and its text. */\nexport function memberRefusal(id: string, member: Member | undefined): { code: string; reason: string } {\n if (!member) return { code: 'not_answered', reason: `the ${id} read is missing from the batch answer` }\n const text = typeof member.error === 'string' ? member.error.trim() : ''\n if (text === '') return { code: 'not_answered', reason: `the ${id} read did not answer` }\n const refusal = refusalOf({ content: [{ type: 'text', text }] })\n // A member's text may name its code after a prefix (\"read failed: query_timeout ...\"):\n // the code it names wins over not_served.\n const named = refusal.code === 'not_served' ? NAMED_CODE.exec(text)?.[1] : undefined\n return { code: named ?? refusal.code, reason: refusal.text }\n}\n","/**\n * aml_address_risk: who is this address, and how risky is it?\n *\n * A local tool of the proxy. It sends one graph_query_batch with three reads\n * on USE topology, all anchored on the address:\n *\n * node the address: its node labels and its card (identity, roles,\n * behaviour, evidence, judgements, sources, card_version), the risk\n * model's `risk_level` and `risk_score`, and its exchange role;\n * in its senders: the newest FLOWED_TO links into it worth 1 USD or more,\n * with each sender's own card words (identities included) and model\n * level;\n * out its receivers: the same, out of it.\n *\n * The risk word is the higher of what the labels prove (rules) and what the\n * risk model predicts (model), computed by src/mcp/risk-word.ts from the card\n * entries and the card dictionary. The partners' words are computed by the\n * same rule from their own rows, and never change the address's word.\n *\n * The tool states, the host judges: the answer holds facts and measures, no\n * summary, no advice and no verdict. The only prose is each reason's fixed\n * plain sentence from the card dictionary.\n *\n * `addressRiskQueries` and `addressRiskFromMembers` are the address answer of\n * every risk tool: a tool that names many addresses batches their reads under\n * a prefix each, and builds each answer with the same code.\n */\n\nimport type { AddressCardWord, LoadedAddressCard } from './address-card.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport {\n exchangeOfLabels,\n exchangeOfWallet,\n type ExchangeEntry,\n type LoadedExchangeRegistry,\n} from './exchange-registry.js'\nimport { exposedOf, type ExposedBlock } from './exposed.js'\nimport { exchangeRoleRead } from './graph-schema.js'\nimport {\n levelRank,\n modelReasonOf,\n modelScoreOf,\n modelWordOf,\n reasonOf,\n riskOf,\n riskWordRank,\n rulesWordOf,\n splitCardEntry,\n type ModelWord,\n type Reason,\n type RiskWord,\n type SetBy,\n} from './risk-word.js'\nimport {\n addressOrNull,\n isRecord,\n memberAnswered,\n memberRefusal,\n memberRows,\n numberOrNull,\n strings,\n textOrNull,\n utcOrNull,\n} from './row-values.js'\nimport { membersOf, refusalOf, type GraphAnswer, type Member } from './token-lookup.js'\n\nexport const AML_ADDRESS_RISK_TOOL = 'aml_address_risk' as const\nexport const AML_ADDRESS_RISK_SCHEMA = 'chain-insights.aml-address-risk.v2' as const\nexport const AML_ADDRESS_RISK_TITLE = 'Address risk'\n\n/** How a host reads the answer: the one text every host reads, in the tool description. */\nexport const ADDRESS_RISK_READING_RULE =\n 'The tool states facts and measures; you write the judgement: say which reasons you rely on, ' +\n 'say when the word comes from the model alone (set_by model) that it is a prediction, never call an address safe, ' +\n 'and name a part listed in not_read as not read.'\n\nexport const AML_ADDRESS_RISK_DESCRIPTION =\n 'Answers who one address is and how risky it is: its identity, wallet roles and behaviour, its risk word with every reason, ' +\n '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, ' +\n '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. ' +\n '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. ' +\n 'risk.score is the model number from 0 to 1, or null: a label never makes a number. ' +\n 'unscored means neither labels nor the model speak about the address: it is not low and not safe. ' +\n 'A risky partner is listed beside the word and never changes it. ' +\n 'exposed, when present, is a grade below proof: one block per scam kind the address sits near (band, steps, the way of addresses), never evidence against the address, and it never changes the word. ' +\n '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. ' +\n `${ADDRESS_RISK_READING_RULE} ` +\n 'Write every address in full, all 42 characters. Pass surroundings: true for the nodes and money links behind the answer, to draw.'\n\nexport const AML_ADDRESS_RISK_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_ADDRESS_RISK_ARGS = ['network', 'address', 'surroundings'] as const\n\n/** The partners kept per direction, the newest first. One more is read to know whether more exist. */\nexport const PARTNER_LIMIT = 25\n/** The money floor of a partner link, in USD: a link under it is dust, filtered by the read. */\nexport const EXPOSURE_FLOOR_USD = 1\n/** The most nodes the surroundings carry. */\nexport const SURROUNDINGS_NODE_LIMIT = 60\n/** The addresses that are never a partner: tokens minted from and burned to them. */\nexport const ZERO_ADDRESSES = [\n '0x0000000000000000000000000000000000000000',\n '0x000000000000000000000000000000000000dead',\n] as const\n\nexport type AddressKind = 'account' | 'contract' | 'token' | 'pool' | 'unknown'\nexport type PartnerDirection = 'sent_to_subject' | 'received_from_subject'\nexport type NotReadPart = 'senders' | 'receivers' | 'counterparties'\n\nexport interface AddressRisk {\n word: RiskWord\n score: number | null\n rules_word: string\n model_word: ModelWord\n set_by: SetBy\n reasons: Reason[]\n /** Card words the dictionary does not hold: listed, they set nothing. */\n unknown_words: string[]\n /** The dictionary version that resolved the card on the graph, or null. */\n card_version: string | null\n}\n\nexport interface ModelScore {\n level: ModelWord\n score: number | null\n scored: boolean\n}\n\nexport interface RiskyPartner {\n address: string\n direction: PartnerDirection\n risk_word: RiskWord\n set_by: SetBy\n reasons: Reason[]\n tokens_worth_usd: number | null\n tx_count: number | null\n first_seen_utc: string | null\n last_seen_utc: string | null\n}\n\nexport interface ExchangeEnd {\n address: string\n direction: PartnerDirection\n /** The exchange id, from the lookup file, else the name on the card. */\n exchange: string | null\n exchange_role: string | null\n tokens_worth_usd: number | null\n first_seen_utc: string | null\n last_seen_utc: string | null\n}\n\nexport interface Exposure {\n floor_usd: typeof EXPOSURE_FLOOR_USD\n /** True for a hub (more than HUB_DEGREE links): its counterparties are not ranked, and none is read. */\n hub: boolean\n /** The address's link count on its node, when the node carries it. */\n degree_total: number | null\n /** Partner links kept: worth 1 USD or more, not a token contract, not a zero address. */\n counterparties_read: number\n /** Partner links read and dropped: a token contract or a zero address. */\n left_out: number\n /** True when a direction had more partners than PARTNER_LIMIT. */\n truncated: boolean\n with_risk: RiskyPartner[]\n /** Kept partners with at least one pattern fact and no word of medium or above. */\n pattern_partners: number\n}\n\nexport interface NotRead {\n part: NotReadPart\n code: string\n reason: string\n}\n\nexport interface SurroundingsNode {\n address: string\n role: 'subject' | 'partner' | 'exchange_end'\n kind: AddressKind\n name: string | null\n risk_word: RiskWord\n model_level: ModelWord\n}\n\nexport interface SurroundingsLink {\n from_address: string\n to_address: string\n link: 'FLOWED_TO'\n tokens_worth_usd: number | null\n first_seen_utc: string | null\n last_seen_utc: string | null\n}\n\nexport interface Surroundings {\n nodes: SurroundingsNode[]\n links: SurroundingsLink[]\n truncated: boolean\n}\n\nexport interface AmlAddressRiskResult {\n schema: typeof AML_ADDRESS_RISK_SCHEMA\n tool: typeof AML_ADDRESS_RISK_TOOL\n network: string\n address: string\n /** false when the graph holds no node for the address. */\n found: boolean\n kind: AddressKind\n identity: { word: string; name: string | null } | null\n roles: string[]\n behaviour: string | null\n risk: AddressRisk\n model: ModelScore\n /** Null when the address is not found. */\n exposure: Exposure | null\n exchange_ends: ExchangeEnd[]\n not_read: NotRead[]\n /**\n * Exposed, a grade below proof: one block per scam kind the address sits near.\n * It sets no risk word. Absent when the node has nothing to show.\n */\n exposed?: ExposedBlock[]\n surroundings?: Surroundings\n}\n\nexport interface AddressRiskDependencies {\n /** The card dictionary: the fresh cache, the public file, or the packaged copy. */\n loadAddressCard: () => Promise<LoadedAddressCard | null>\n loadExchangeRegistry: (network: string) => Promise<LoadedExchangeRegistry>\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<GraphAnswer>\n unavailable?: () => Promise<string | undefined> | string | undefined\n describeFailure: (err: unknown) => string\n}\n\nexport type AmlAddressRiskToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\n/** A full address as a caller may type it: 0x plus 40 hex characters, any case. */\nexport const ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\nconst ADDRESS_READ = /^0x[0-9a-f]{40}$/\n\nexport function assertReadAddress(address: string): void {\n if (!ADDRESS_READ.test(address)) {\n throw new Error(`address risk: ${JSON.stringify(address)} is not a lowercase 0x address`)\n }\n}\n\n/**\n * The node read: the card, the model's level and score, and the exchange role.\n * `extra` adds columns of the node `a` (a token's standard, a pool's sums).\n */\nexport function addressNodeQuery(address: string, extra: readonly string[] = []): string {\n assertReadAddress(address)\n const more = extra.length > 0 ? `, ${extra.join(', ')}` : ''\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"}) ` +\n 'RETURN labels(a) AS node_labels, a.card_version AS card_version, a.identity AS identity, a.identity_name AS identity_name, ' +\n 'a.identities AS identities, a.address_roles AS address_roles, a.behaviour AS behaviour, a.evidence AS evidence, ' +\n 'a.judgements AS judgements, a.exposed AS exposed, a.sources AS sources, a.risk_level AS risk_level, a.risk_score AS risk_score, ' +\n `${exchangeRoleRead('a')} AS exchange_role, a.degree_total AS degree_total, a.degree_out AS degree_out${more} LIMIT 1`\n )\n}\n\n/**\n * A hub has more links than this. Ranking a hub's money links by amount is\n * what costs (9 s for the zero address, 17.6 s for a pool manager, against\n * under 3.5 s for every other case measured): a hub's partner reads are not\n * sent, and its counterparties are not ranked.\n */\nexport const HUB_DEGREE = 50_000\n\n/** The link count of a hub node, or null: a node whose degree is missing is not a hub. */\nexport function hubDegreeOf(row: Record<string, unknown> | undefined): number | null {\n const degree = numberOrNull(row?.degree_total)\n return degree !== null && degree > HUB_DEGREE ? degree : null\n}\n\n/** The not-read entry of a hub's counterparties: what to ask instead. */\nexport function hubNotRead(degree: number): NotRead {\n return {\n part: 'counterparties',\n code: 'hub',\n reason: `This address has ${degree} links. Its counterparties are not ranked: ask about one counterparty, or one token.`,\n }\n}\n\n/** A partner read: the newest money links of one direction, one more than kept. */\nexport function addressPartnerQuery(address: string, direction: 'in' | 'out'): string {\n assertReadAddress(address)\n const anchor = `(a:Address {address: \"${address}\"})`\n const match =\n direction === 'in'\n ? `(b:Address)-[f:FLOWED_TO]->${anchor}`\n : `${anchor}-[f:FLOWED_TO]->(b:Address)`\n return (\n `USE topology MATCH ${match} WHERE f.amount_usd_sum >= ${EXPOSURE_FLOOR_USD} ` +\n 'RETURN b.address AS address, labels(b) AS node_labels, b.identity AS identity, b.identity_name AS identity_name, ' +\n 'b.identities AS identities, ' +\n 'b.evidence AS evidence, b.judgements AS judgements, b.risk_level AS risk_level, ' +\n `${exchangeRoleRead('b')} AS exchange_role, ` +\n 'f.amount_usd_sum AS tokens_worth_usd, f.tx_count AS tx_count, ' +\n 'f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp ' +\n `ORDER BY f.last_seen_timestamp DESC LIMIT ${PARTNER_LIMIT + 1}`\n )\n}\n\n/** The three batch members of one address, their ids under `prefix`: `${prefix}node`, `${prefix}in`, `${prefix}out`. */\nexport function addressRiskQueries(\n address: string,\n prefix = ''\n): Array<{ id: string; query: string }> {\n return [\n { id: `${prefix}node`, query: addressNodeQuery(address) },\n { id: `${prefix}in`, query: addressPartnerQuery(address, 'in') },\n { id: `${prefix}out`, query: addressPartnerQuery(address, 'out') },\n ]\n}\n\nconst answered = memberAnswered\nconst rowsOf = memberRows\n\nfunction notReadOf(part: NotReadPart, id: string, member: Member | undefined): NotRead {\n return { part, ...memberRefusal(id, member) }\n}\n\n/** The kind of an address from its node labels: Pool wins over Token over Contract over Account. */\nexport function kindOf(nodeLabels: readonly string[]): AddressKind {\n if (nodeLabels.includes('Pool')) return 'pool'\n if (nodeLabels.includes('Token')) return 'token'\n if (nodeLabels.includes('Contract')) return 'contract'\n if (nodeLabels.includes('Account')) return 'account'\n return 'unknown'\n}\n\n/**\n * The reasons and the word of one row: the top identity, every other identity\n * word that carries a level, the entries of evidence and judgements, and the\n * model level. Each entry is read by the dictionary, whatever list it came from.\n */\nexport function rowRisk(\n row: Record<string, unknown> | undefined,\n dictionary: readonly AddressCardWord[]\n): Omit<AddressRisk, 'card_version'> {\n const reasons: Reason[] = []\n const unknown: string[] = []\n const take = (entry: string, keep: (reason: Reason) => boolean = () => true) => {\n const reason = reasonOf(entry, dictionary)\n if (reason) {\n if (keep(reason)) reasons.push(reason)\n } else {\n const { word } = splitCardEntry(entry)\n if (word !== '' && !unknown.includes(word)) unknown.push(word)\n }\n }\n const identity = textOrNull(row?.identity)\n if (identity) take(identity)\n // A mixer that is not the top identity still raises the word.\n for (const word of strings(row?.identities)) {\n if (word.toLowerCase() === identity?.toLowerCase()) continue\n take(word, (reason) => reason.level !== 'none')\n }\n for (const entry of strings(row?.evidence)) take(entry)\n for (const entry of strings(row?.judgements)) take(entry)\n const modelWord = modelWordOf(row?.risk_level)\n const risk = riskOf({\n rulesWord: rulesWordOf(reasons),\n modelWord,\n score: modelScoreOf(row?.risk_score),\n })\n if (modelWord !== 'not_scored' && (risk.set_by === 'model' || risk.set_by === 'both')) {\n reasons.push(modelReasonOf(modelWord))\n }\n return { ...risk, reasons, unknown_words: unknown }\n}\n\n/** A partner row, as the answer reads it. */\ninterface Partner {\n address: string\n direction: PartnerDirection\n row: Record<string, unknown>\n kind: AddressKind\n risk: Omit<AddressRisk, 'card_version'>\n exchange: { exchange: string | null; exchange_role: string | null } | null\n}\n\nfunction isTokenContract(nodeLabels: readonly string[]): boolean {\n return nodeLabels.includes('Token') && !nodeLabels.includes('Pool')\n}\n\n/** The exchange of a partner that is an exchange wallet, or null when it is none. */\nfunction exchangeOfPartner(\n address: string,\n row: Record<string, unknown>,\n nodeLabels: readonly string[],\n exchangeRows: ExchangeEntry[]\n): Partner['exchange'] {\n const identity = textOrNull(row.identity)?.toLowerCase()\n const role = textOrNull(row.exchange_role)?.toLowerCase() ?? null\n if (identity !== 'exchange' && role === null && !nodeLabels.includes('Exchange')) return null\n const name = textOrNull(row.identity_name)\n const listed =\n exchangeOfWallet(address, exchangeRows)?.entry ??\n (name ? exchangeOfLabels([name], exchangeRows) : null)\n return { exchange: listed?.exchange ?? name, exchange_role: role }\n}\n\n/** The partners of one direction, the token contracts and zero addresses dropped and counted. */\nfunction partnersOf(\n member: Member | undefined,\n direction: PartnerDirection,\n dictionary: readonly AddressCardWord[],\n exchangeRows: ExchangeEntry[]\n): { partners: Partner[]; leftOut: number; truncated: boolean } {\n const rows = rowsOf(member)\n const partners: Partner[] = []\n let leftOut = 0\n for (const row of rows.slice(0, PARTNER_LIMIT)) {\n const address = addressOrNull(row.address)\n if (!address) continue\n const nodeLabels = strings(row.node_labels)\n if (isTokenContract(nodeLabels) || (ZERO_ADDRESSES as readonly string[]).includes(address)) {\n leftOut += 1\n continue\n }\n partners.push({\n address,\n direction,\n row,\n kind: kindOf(nodeLabels),\n risk: rowRisk(row, dictionary),\n exchange: exchangeOfPartner(address, row, nodeLabels, exchangeRows),\n })\n }\n return { partners, leftOut, truncated: rows.length > PARTNER_LIMIT }\n}\n\nfunction riskyPartnerOf(partner: Partner): RiskyPartner {\n return {\n address: partner.address,\n direction: partner.direction,\n risk_word: partner.risk.word,\n set_by: partner.risk.set_by,\n reasons: partner.risk.reasons,\n tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),\n tx_count: numberOrNull(partner.row.tx_count),\n first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),\n last_seen_utc: utcOrNull(partner.row.last_seen_timestamp),\n }\n}\n\nconst MEDIUM_RANK = levelRank('medium')\nconst wordRank = riskWordRank\n\n/** The nodes and money links behind the answer, from the rows already read. */\nfunction surroundingsOf(subject: SurroundingsNode, partners: Partner[], truncated: boolean): Surroundings {\n const nodes: SurroundingsNode[] = [subject]\n const listed = new Set([subject.address])\n let capped = false\n for (const partner of partners) {\n if (listed.has(partner.address)) continue\n if (nodes.length >= SURROUNDINGS_NODE_LIMIT) {\n capped = true\n continue\n }\n listed.add(partner.address)\n nodes.push({\n address: partner.address,\n role: partner.exchange ? 'exchange_end' : 'partner',\n kind: partner.kind,\n name: partner.exchange?.exchange ?? textOrNull(partner.row.identity_name),\n risk_word: partner.risk.word,\n model_level: partner.risk.model_word,\n })\n }\n const links: SurroundingsLink[] = []\n for (const partner of partners) {\n if (!listed.has(partner.address)) continue\n const sent = partner.direction === 'sent_to_subject'\n links.push({\n from_address: sent ? partner.address : subject.address,\n to_address: sent ? subject.address : partner.address,\n link: 'FLOWED_TO',\n tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),\n first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),\n last_seen_utc: utcOrNull(partner.row.last_seen_timestamp),\n })\n }\n return { nodes, links, truncated: truncated || capped }\n}\n\n/**\n * The address answer built from its batch members, or why it cannot be. Only\n * a node read that did not answer is a failure; a partner read that did not\n * answer is named in not_read and the answer still stands.\n */\nexport function addressRiskFromMembers(\n network: string,\n address: string,\n members: Map<string, Member>,\n dictionary: readonly AddressCardWord[],\n exchangeRows: ExchangeEntry[],\n prefix = '',\n options: {\n surroundings?: boolean\n /** The partner reads were not sent for a hub: build the hub answer when the node is one. */\n hubGuard?: boolean\n } = {}\n): { result: AmlAddressRiskResult } | { failure: string } {\n const nodeId = `${prefix}node`\n const node = members.get(nodeId)\n if (!answered(node)) {\n if (!node) return { failure: `the ${nodeId} read is missing from the batch answer` }\n return {\n failure:\n typeof node.error === 'string' && node.error.trim() !== ''\n ? node.error\n : `the ${nodeId} read did not answer`,\n }\n }\n const nodeRow = rowsOf(node)[0]\n const base = {\n schema: AML_ADDRESS_RISK_SCHEMA,\n tool: AML_ADDRESS_RISK_TOOL,\n network,\n address,\n }\n if (!nodeRow) {\n const result: AmlAddressRiskResult = {\n ...base,\n found: false,\n kind: 'unknown',\n identity: null,\n roles: [],\n behaviour: null,\n risk: {\n word: 'unscored',\n score: null,\n rules_word: 'none',\n model_word: 'not_scored',\n set_by: 'none',\n reasons: [],\n unknown_words: [],\n card_version: null,\n },\n model: { level: 'not_scored', score: null, scored: false },\n exposure: null,\n exchange_ends: [],\n not_read: [],\n ...(options.surroundings === true\n ? {\n surroundings: {\n nodes: [\n {\n address,\n role: 'subject' as const,\n kind: 'unknown' as const,\n name: null,\n risk_word: 'unscored' as const,\n model_level: 'not_scored' as const,\n },\n ],\n links: [],\n truncated: false,\n },\n }\n : {}),\n }\n return { result }\n }\n\n const risk = rowRisk(nodeRow, dictionary)\n const kind = kindOf(strings(nodeRow.node_labels))\n const identityWord = textOrNull(nodeRow.identity)\n const identityName = textOrNull(nodeRow.identity_name)\n\n const notRead: NotRead[] = []\n const degree = numberOrNull(nodeRow.degree_total)\n const hub = options.hubGuard === true ? hubDegreeOf(nodeRow) : null\n if (hub !== null) notRead.push(hubNotRead(hub))\n const directions: Array<{ id: string; part: NotReadPart; direction: PartnerDirection }> =\n hub !== null\n ? []\n : [\n { id: `${prefix}in`, part: 'senders', direction: 'sent_to_subject' },\n { id: `${prefix}out`, part: 'receivers', direction: 'received_from_subject' },\n ]\n const partners: Partner[] = []\n let leftOut = 0\n let truncated = false\n for (const { id, part, direction } of directions) {\n const member = members.get(id)\n if (!answered(member)) {\n notRead.push(notReadOf(part, id, member))\n continue\n }\n const read = partnersOf(member, direction, dictionary, exchangeRows)\n partners.push(...read.partners)\n leftOut += read.leftOut\n truncated ||= read.truncated\n }\n\n const exchangeEnds: ExchangeEnd[] = partners\n .filter((partner) => partner.exchange !== null)\n .map((partner) => ({\n address: partner.address,\n direction: partner.direction,\n exchange: partner.exchange!.exchange,\n exchange_role: partner.exchange!.exchange_role,\n tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),\n first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),\n last_seen_utc: utcOrNull(partner.row.last_seen_timestamp),\n }))\n\n const result: AmlAddressRiskResult = {\n ...base,\n found: true,\n kind,\n identity: identityWord ? { word: identityWord, name: identityName } : null,\n roles: strings(nodeRow.address_roles),\n behaviour: textOrNull(nodeRow.behaviour),\n risk: { ...risk, card_version: textOrNull(nodeRow.card_version) },\n model: { level: risk.model_word, score: risk.score, scored: risk.model_word !== 'not_scored' },\n exposure: {\n floor_usd: EXPOSURE_FLOOR_USD,\n hub: hub !== null,\n degree_total: degree,\n counterparties_read: partners.length,\n left_out: leftOut,\n truncated,\n with_risk: partners\n .filter((partner) => wordRank(partner.risk.word) >= MEDIUM_RANK)\n .map(riskyPartnerOf),\n pattern_partners: partners.filter(\n (partner) =>\n wordRank(partner.risk.word) < MEDIUM_RANK &&\n partner.risk.reasons.some((reason) => reason.question === 'judgement')\n ).length,\n },\n exchange_ends: exchangeEnds,\n not_read: notRead,\n }\n const exposed = exposedOf(nodeRow.exposed, dictionary)\n if (exposed.length > 0) result.exposed = exposed\n if (options.surroundings === true) {\n result.surroundings = surroundingsOf(\n {\n address,\n role: 'subject',\n kind,\n name: identityName,\n risk_word: risk.word,\n model_level: risk.model_word,\n },\n partners,\n truncated\n )\n }\n return { result }\n}\n\nfunction errorResult(text: string): AmlAddressRiskToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlAddressRiskResult): AmlAddressRiskToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],\n structuredContent: structured as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** aml_address_risk, {network, address, surroundings?}. Every argument is checked before a read is sent. */\nexport async function handleAmlAddressRisk(\n args: unknown,\n deps: AddressRiskDependencies\n): Promise<AmlAddressRiskToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n const raw = typeof record.address === 'string' ? record.address.trim() : ''\n if (!ADDRESS_INPUT.test(raw)) {\n return errorResult(\n 'invalid_address: address is required: 0x plus 40 hex characters. ' +\n 'A name or a ticker is not an address: call meta_token_lookup or meta_exchange_lookup first.'\n )\n }\n if (record.surroundings !== undefined && typeof record.surroundings !== 'boolean') {\n return errorResult('invalid_surroundings: surroundings is true or false.')\n }\n const address = raw.toLowerCase()\n const surroundings = record.surroundings === true\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No address risk read was sent: ${unavailable} There is no answer yet, which is not \"no risk\": try again later.`\n )\n }\n\n let dictionary: readonly AddressCardWord[]\n try {\n const card = await deps.loadAddressCard()\n if (!card) throw new Error('no copy of the address card dictionary is available')\n dictionary = card.document.words\n } catch (err) {\n return errorResult(\n `No address risk read was sent: the address card dictionary did not load (${(err as Error).message}). ` +\n 'There is no answer yet, which is not \"no risk\".'\n )\n }\n\n let exchangeRows: ExchangeEntry[] = []\n try {\n exchangeRows = (await deps.loadExchangeRegistry(network)).document.rows\n } catch {\n // The lookup only names an exchange; the graph read still answers.\n }\n\n // Call 1: the node alone (about 50 ms). It says whether the address exists and whether it is a hub.\n const read = async (queries: Array<{ id: string; query: string }>) => {\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries })\n } catch (err) {\n return { failure: `${deps.describeFailure(err)} This is not \"no risk\": send the same call again once.` }\n }\n const members = membersOf(answer)\n if (members.size === 0) {\n const text = answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n return { failure: `${text} This is not \"no risk\".` }\n }\n return { members }\n }\n const [nodeQuery, ...partnerQueries] = addressRiskQueries(address)\n const first = await read([nodeQuery!])\n if ('failure' in first) return errorResult(`The address risk read failed: ${first.failure}`)\n const members = first.members\n const nodeRow = memberRows(members.get('node'))[0]\n // Call 2: the partner reads, unless the address is not found or is a hub.\n if (nodeRow && hubDegreeOf(nodeRow) === null) {\n const second = await read(partnerQueries)\n if ('failure' in second) {\n for (const { id } of partnerQueries) members.set(id, { id, ok: false, error: second.failure })\n } else {\n for (const [id, member] of second.members) members.set(id, member)\n }\n }\n const built = addressRiskFromMembers(network, address, members, dictionary, exchangeRows, '', {\n surroundings,\n hubGuard: true,\n })\n if ('failure' in built) {\n return errorResult(\n `The address risk read failed: ${built.failure} This is not \"no risk\": send the same call again once.`\n )\n }\n return textResult(built.result)\n}\n"],"mappings":";;;;;;;AAqBA,MAAa,gBAAgB;AAC7B,MAAa,gBAAgB;CAAC;CAAO;CAAQ;AAAQ;AA0BrD,MAAM,cAAc,SAAuB;CACzC,QAAQ,OAAO,MAAM,6BAA6B,KAAK,GAAG;AAC5D;AAEA,MAAMA,cAAY,UAChB,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAE9D,MAAM,UAAU,UACd,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,IAAI;AAEpE,SAAS,OACP,YACA,MACA,OACwB;CACxB,MAAM,QAAQ,WAAW,QAAQ,SAAS,KAAK,aAAa,cAAc,KAAK,SAAS,IAAI;CAC5F,IAAI,UAAU,KAAA,GAAW;EACvB,MAAM,SAAS,MAAM,YAAY;EACjC,MAAM,QAAQ,MAAM,MAAM,SAAS,KAAK,OAAO,YAAY,MAAM,MAAM;EACvE,IAAI,OAAO,OAAO;CACpB;CACA,OAAO,MAAM,MAAM,SAAS,KAAK,UAAU,KAAA,CAAS,KAAK;AAC3D;;AAGA,SAAS,WAAW,MAAc,YAAgD;CAChF,MAAM,OAAO,OAAO,YAAY,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