chain-insights 0.85.2 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -0
  2. package/bin/install.cjs +2 -1
  3. package/dist/{active-q3yViZhc.cjs → active-COPA14FA.cjs} +2 -16
  4. package/dist/{active-D2aabYRF.mjs → active-CyC4jFka.mjs} +2 -7
  5. package/dist/{active-D2aabYRF.mjs.map → active-CyC4jFka.mjs.map} +1 -1
  6. package/dist/address-card-C-NB03XP.cjs +218 -0
  7. package/dist/address-card-LYaT5yz0.mjs +190 -0
  8. package/dist/address-card-LYaT5yz0.mjs.map +1 -0
  9. package/dist/address-risk-DPuXBsvH.cjs +806 -0
  10. package/dist/address-risk-Da6FsfGx.mjs +653 -0
  11. package/dist/address-risk-Da6FsfGx.mjs.map +1 -0
  12. package/dist/{capabilities-Mxa4oQdd.cjs → capabilities-DkNreyv7.cjs} +1 -1
  13. package/dist/{capabilities-bZOr5Ads.mjs → capabilities-w5bNR7F9.mjs} +2 -2
  14. package/dist/{capabilities-bZOr5Ads.mjs.map → capabilities-w5bNR7F9.mjs.map} +1 -1
  15. package/dist/cli.cjs +138 -46
  16. package/dist/cli.mjs +138 -46
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/{deployer-screen-B5yrXZGo.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-B5yrXZGo.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-0SOQ_HFf.cjs → deployer-screen-CFLi7OeH.cjs} +2 -2
  21. package/dist/{dex-registry-BY67f4Ul.mjs → dex-registry-Bkri0--q.mjs} +10 -2
  22. package/dist/{dex-registry-BY67f4Ul.mjs.map → dex-registry-Bkri0--q.mjs.map} +1 -1
  23. package/dist/{dex-registry-BhGJUG9_.cjs → dex-registry-CyR3GyRr.cjs} +20 -0
  24. package/dist/{dex-tool-7BK_gD6H.mjs → dex-tool-D0K_Qx4N.mjs} +4 -4
  25. package/dist/dex-tool-D0K_Qx4N.mjs.map +1 -0
  26. package/dist/{dex-tool-Be9NAuD8.cjs → dex-tool-DQ5Eg0LO.cjs} +3 -3
  27. package/dist/{exchange-deposit-check-C5MseGlZ.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CXHZCHWW.mjs → exchange-deposit-check-DIALj2sm.mjs} +19 -19
  29. package/dist/exchange-deposit-check-DIALj2sm.mjs.map +1 -0
  30. package/dist/{exchange-registry-CT0rRW__.cjs → exchange-registry-CEgkeQV1.cjs} +16 -93
  31. package/dist/{exchange-registry-CoLgHw6d.mjs → exchange-registry-Dr5UtcT5.mjs} +17 -94
  32. package/dist/exchange-registry-Dr5UtcT5.mjs.map +1 -0
  33. package/dist/{exchange-tool-Dc46SJ49.mjs → exchange-tool-B7E29YoQ.mjs} +4 -4
  34. package/dist/exchange-tool-B7E29YoQ.mjs.map +1 -0
  35. package/dist/{exchange-tool-B2SMeC5f.cjs → exchange-tool-CXaUBAd2.cjs} +3 -3
  36. package/dist/{graph-schema-CcrYPpSv.cjs → graph-schema-Bn3txQCj.cjs} +115 -12
  37. package/dist/{graph-schema-CRQuKya1.mjs → graph-schema-DvABR1yl.mjs} +97 -12
  38. package/dist/graph-schema-DvABR1yl.mjs.map +1 -0
  39. package/dist/{layer-routing-YDj-ynG9.cjs → layer-routing-j48SQ8Wk.cjs} +2 -2
  40. package/dist/{layer-routing-DCJVNN6O.mjs → layer-routing-r4IbIQSr.mjs} +3 -3
  41. package/dist/layer-routing-r4IbIQSr.mjs.map +1 -0
  42. package/dist/mcp-proxy.cjs +62 -15
  43. package/dist/mcp-proxy.d.cts.map +1 -1
  44. package/dist/mcp-proxy.d.mts.map +1 -1
  45. package/dist/mcp-proxy.mjs +62 -15
  46. package/dist/mcp-proxy.mjs.map +1 -1
  47. package/dist/public-file-BISyAesm.mjs +133 -0
  48. package/dist/public-file-BISyAesm.mjs.map +1 -0
  49. package/dist/public-file-DDp2CrUl.cjs +138 -0
  50. package/dist/{request-timeout-DxwNijQD.cjs → request-timeout-BXiIt9Jy.cjs} +0 -1
  51. package/dist/{request-timeout-K3ljP0pa.mjs → request-timeout-DetG2xO4.mjs} +2 -2
  52. package/dist/{request-timeout-K3ljP0pa.mjs.map → request-timeout-DetG2xO4.mjs.map} +1 -1
  53. package/dist/{token-lookup-Cf59VdGe.mjs → token-lookup-Ck0q7crJ.mjs} +2 -2
  54. package/dist/{token-lookup-Cf59VdGe.mjs.map → token-lookup-Ck0q7crJ.mjs.map} +1 -1
  55. package/dist/{token-lookup-DqjSRIxd.cjs → token-lookup-DLe4erP9.cjs} +1 -1
  56. package/dist/token-risk-CpMfFRoY.cjs +1004 -0
  57. package/dist/token-risk-DhnJc2kJ.mjs +971 -0
  58. package/dist/token-risk-DhnJc2kJ.mjs.map +1 -0
  59. package/dist/{tool-visibility-D8Up081E.cjs → tool-visibility-BCa-tmyZ.cjs} +11 -2
  60. package/dist/{tool-visibility-DuTds7V4.mjs → tool-visibility-BstrSl4s.mjs} +12 -3
  61. package/dist/tool-visibility-BstrSl4s.mjs.map +1 -0
  62. package/docs/contributing.md +10 -8
  63. package/docs/development.md +5 -5
  64. package/docs/evals.md +16 -1
  65. package/docs/graph-query-compatibility.md +15 -2
  66. package/docs/graph-tools.md +44 -6
  67. package/docs/mcp-proxy.md +189 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +76 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +680 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +61 -0
  74. package/skills/chain-insights-address-risk/agents/openai.yaml +4 -0
  75. package/skills/chain-insights-aml-exchange/SKILL.md +9 -7
  76. package/skills/chain-insights-cypher/SKILL.md +79 -3
  77. package/skills/chain-insights-token-risk/SKILL.md +81 -0
  78. package/skills/chain-insights-token-risk/agents/openai.yaml +4 -0
  79. package/skills/chain-insights-virtuals/reference.md +1 -1
  80. package/dist/dex-tool-7BK_gD6H.mjs.map +0 -1
  81. package/dist/exchange-deposit-check-CXHZCHWW.mjs.map +0 -1
  82. package/dist/exchange-registry-CoLgHw6d.mjs.map +0 -1
  83. package/dist/exchange-tool-Dc46SJ49.mjs.map +0 -1
  84. package/dist/graph-schema-CRQuKya1.mjs.map +0 -1
  85. package/dist/layer-routing-DCJVNN6O.mjs.map +0 -1
  86. package/dist/public-tools-CBszU2oX.cjs +0 -1334
  87. package/dist/public-tools-DVhUjSDV.mjs +0 -1333
  88. package/dist/public-tools-DVhUjSDV.mjs.map +0 -1
  89. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: chain-insights-address-risk
3
+ door: aml_address_risk
4
+ description: Use for the risk of one address (address-risk) — a question that asks whether a wallet or an address is risky, who it is, what labels or risk score it carries, or whom it exchanged money with.
5
+ ---
6
+
7
+ # Chain Insights: the risk of one address
8
+
9
+ Load `chain-insights-cypher` first. Its answer rules hold here, and these
10
+ hold even when it cannot load:
11
+
12
+ - Write every address in full, 42 characters, every time. Never shorten
13
+ one with `…` or `...`.
14
+ - A transfer moves tokens: "tokens worth about N USD", never "sent N USD".
15
+
16
+ ## The one call
17
+
18
+ Call `aml_address_risk` with `network` and the full `address`. Add
19
+ `surroundings: true` only when the host draws a picture. A token contract
20
+ or a pool goes to `aml_token_risk`; a ticker or a name goes to
21
+ `meta_token_lookup` or `meta_exchange_lookup` first.
22
+
23
+ The tool's first read, shown so a host without the tool can send the same
24
+ one through `graph_query`:
25
+
26
+ ```cypher
27
+ USE topology MATCH (a:Address {address: "0x766bd6598182586beda76414dc5f8deb1530a213"}) 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, coalesce(a.exchange_role, a.cex_role) AS exchange_role, a.degree_total AS degree_total, a.degree_out AS degree_out LIMIT 1
28
+ ```
29
+
30
+ ## How to read `risk`
31
+
32
+ - `risk.word` is `critical`, `high`, `medium`, `low` or `unscored`. It is the
33
+ higher of `rules_word`, what the labels prove, and `model_word`, what the
34
+ risk model predicts. Only a label gives `critical`.
35
+ - `set_by` says who set it: `rules`, `model`, `both` or `none`. A word set by
36
+ the model alone is a prediction: say so.
37
+ - `risk.score` is the model's number from 0 to 1, or null. A label never
38
+ makes a number.
39
+ - `unscored` means neither the labels nor the model speak about the
40
+ address. It is not `low`, and it is not safe.
41
+ - Each reason carries its fixed `plain` sentence. A reason with the word
42
+ `pattern` is a pattern fact: it accuses nobody and sets no word.
43
+ - A partner in `exposure.with_risk` is listed beside the word and never
44
+ changes it. Receiving money from a risky address is a fact, not guilt.
45
+
46
+ ## A hub
47
+
48
+ An address with more than 50,000 links, such as the zero address or a pool
49
+ manager, is a hub: `exposure.hub` is `true`, its counterparties are not
50
+ ranked, and `not_read` names `counterparties` with code `hub`. Its word still
51
+ comes from its card and the model. Say that its counterparties were not
52
+ ranked, and ask about one counterparty, or one token, instead.
53
+
54
+ ## The judgement is yours
55
+
56
+ The tool states facts and measures. You write the judgement:
57
+
58
+ 1. Say which reasons you rely on, in their plain words.
59
+ 2. Say when the word comes from the model alone that it is a prediction.
60
+ 3. Never call an address safe.
61
+ 4. Name a part listed in `not_read` as not read, never as "none found".
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: 'Chain Insights Address Risk'
3
+ short_description: 'The risk of one address: its word, reasons, model score and money partners'
4
+ default_prompt: 'Load chain-insights-cypher first. For the risk of one address, call aml_address_risk with the network and the full address. Read risk.word as the higher of what labels prove and what the risk model predicts; say when the model alone set it, never call an address safe, and name a part in not_read as not read.'
@@ -26,9 +26,11 @@ from `meta_exchange_lookup`, never from a guess or a graph search by name.
26
26
  A customer of a centralized exchange gets a deposit address of their own.
27
27
  The exchange later moves what arrives there into one of its hot wallets: a
28
28
  sweep. The graph draws that move as `SWEPT`, from the deposit to the hot
29
- wallet, and marks each exchange wallet with `cex_role`.
29
+ wallet, and marks each exchange wallet with `exchange_role`. A lane not yet
30
+ re-indexed still carries it as `cex_role`; read
31
+ `coalesce(a.exchange_role, a.cex_role)`.
30
32
 
31
- | `cex_role` | The wallet |
33
+ | `exchange_role` | The wallet |
32
34
  |---|---|
33
35
  | `deposit` | one customer's deposit address; the exchange knows who owns it |
34
36
  | `hot_wallet` | receives the sweeps of many deposits, and pays withdrawals |
@@ -46,7 +48,7 @@ is set on both.
46
48
  ## What a deposit address looks like
47
49
 
48
50
  The graph's deposit rule judges an address. You read its verdict
49
- (`is_deposit`, `cex_role`, `swept`) and never judge again. The rule holds a
51
+ (`is_deposit`, `exchange_role`, `swept`) and never judge again. The rule holds a
50
52
  deposit to this:
51
53
 
52
54
  | A deposit address | Never a deposit |
@@ -85,7 +87,7 @@ deposit to this:
85
87
  hot wallet), `predicted_hot_wallet` (behind a hot wallet the model itself
86
88
  inferred) or `predicted` (a hot wallet the model inferred), and
87
89
  `inferred_at` when the graph wrote it. `is_deposit` stays false and
88
- `cex_role` null: they are the sourced verdict. A sourced mark always wins,
90
+ `exchange_role` null: they are the sourced verdict. A sourced mark always wins,
89
91
  and then the answer carries no `inferred` field.
90
92
 
91
93
  ## Step 1: the doors
@@ -106,7 +108,7 @@ deposit to this:
106
108
  2. **One address: `aml_exchange_deposit_check`.** Call it with the network
107
109
  and the address in full:
108
110
  `{"network": "robinhood", "address": "0x31a817802ee183eb8b13167ffe24bd28dcc6f30c"}`.
109
- It reads the address's `cex_role` and its `SWEPT` links
111
+ It reads the address's `exchange_role` and its `SWEPT` links
110
112
  and answers `is_deposit`, the exchange, and each hot wallet it swept
111
113
  into with the sweep count, the USD sum, the paths and the first and
112
114
  last sweep. With no sourced mark, it reads the exchange model's guess
@@ -125,7 +127,7 @@ deposit to this:
125
127
  `meta_exchange_lookup` with the `address`. It answers "a hot wallet of
126
128
  Bitget on robinhood": say yes, a hot wallet of Bitget, with the address in
127
129
  full. When the file lists no wallet of that address, call
128
- `aml_exchange_deposit_check`: its `cex_role` and the exchange it names
130
+ `aml_exchange_deposit_check`: its `exchange_role` and the exchange it names
129
131
  answer the question from the graph.
130
132
  - **"Where did the money from 0x64ba5fafa7a6e1991f7f60c9b594a7131a784540
131
133
  go?"** Call `aml_exchange_deposit_check` first. When the address is a
@@ -156,7 +158,7 @@ The sweeps of one deposit, the read `aml_exchange_deposit_check` sends:
156
158
 
157
159
  ```cypher
158
160
  USE topology
159
- MATCH (a:Address {address: "0x31a817802ee183eb8b13167ffe24bd28dcc6f30c"})-[s:SWEPT]->(h:Address) RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, h.cex_role AS hot_wallet_role, s.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths LIMIT 20
161
+ MATCH (a:Address {address: "0x31a817802ee183eb8b13167ffe24bd28dcc6f30c"})-[s:SWEPT]->(h:Address) RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, coalesce(h.exchange_role, 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 LIMIT 20
160
162
  ```
161
163
 
162
164
  - **Never anchor on a hot wallet** to list its deposits: one hot wallet
@@ -126,7 +126,7 @@ Route by what the question names: an address, a pair with a day, a transaction o
126
126
  `USE chain` with `Address` reads the balance, the nonce or the kind of one address, now or at a past block with `at_block`. A past block must be at least `chain_admission.at_block_min_depth` blocks below the tip. To find the counterparties of an address, search `USE topology`, then read the pair and one day on `USE facts`.
127
127
  A transaction is a chain question: read it on `USE chain` by its `tx_id`. Chain gives its `block_date`; the transfers between a pair on that day are a `USE facts` read. "Every token that moved inside this transaction": read the chain record for `from_address`, `to_address` and `block_date`, then the facts `TRANSFER` rows of that pair on that day and keep the rows whose `tx_id` matches; a `kind` of `internal` is ETH a contract moved while it ran. Tokens the transaction moved between other pairs are not reachable from the hash alone: say so, and name the pairs you did read.
128
128
  The layers hand each other keys, and each key keeps its name. Topology gives the pair and the first and last seen time. Facts gives the `tx_id` and the `block_height`. Chain takes an `address`, a `tx_id`, a `block_height` or a `block_hash`, and gives the `block_date` of a transaction or a block.
129
- `SWEPT` runs from an exchange deposit to the hot wallet it swept into (layer `cex_sweeps`, family annotations), and `cex_role` on an `:Exchange` address says which wallet of its exchange it is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. A trail that reaches a `SWEPT` link ends there: say the money entered the exchange at that deposit, swept n times into that hot wallet, name the exchange from `labels`, and never walk on past a hot wallet. Read `SWEPT` anchored on an address; call `aml_exchange_deposit_check` for one address and `meta_exchange_lookup` for an exchange by name. With no `cex_role`, `inferred_exchange_role` (`deposit` or `hot_wallet`, with its `ml:exchange-roles:` entry in `inferred_sources`) is the exchange model's guess, never a label: say it is inferred by that model, never a confirmed exchange address.
129
+ `SWEPT` runs from an exchange deposit to the hot wallet it swept into (layer `cex_sweeps`, family annotations), and `exchange_role` on an `:Exchange` address says which wallet of its exchange it is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. A trail that reaches a `SWEPT` link ends there: say the money entered the exchange at that deposit, swept n times into that hot wallet, name the exchange from `labels`, and never walk on past a hot wallet. Read `SWEPT` anchored on an address; call `aml_exchange_deposit_check` for one address and `meta_exchange_lookup` for an exchange by name. With no `exchange_role`, `inferred_exchange_role` (`deposit` or `hot_wallet`, with its `ml:exchange-roles:` entry in `inferred_sources`) is the exchange model's guess, never a label: say it is inferred by that model, never a confirmed exchange address.
130
130
  A question about the whole chain (recent activity, the biggest senders, a top list) is a `USE topology` search: bound it by time with `f.last_seen_timestamp >= <epoch ms>` on the `FLOWED_TO` link, then sort and `LIMIT`. A search has 10 s. Read `Head` first (`USE chain MATCH (h:Head) RETURN h.behind_money, h.behind_dex, h.behind_transfers`, under a second): a `FLOWED_TO` or `ROUTED_TO` search is sent when `behind_money` is at most 100000; a `SWAPPED`, `ADDED_LIQUIDITY` or `REMOVED_LIQUIDITY` search when `behind_dex` is at most 100000; a `TRANSFERRED` search when `behind_transfers` is at most 100000 (100000 blocks is a few hours: a robinhood block is about a tenth of a second apart from the next). When the family is further behind, the search cannot finish, so do not send it: say which family, how many blocks, and ask for an address. On a server whose Head has no `behind_money`, read `h.graph_blocks_behind` and hold it to the same limit. On a server whose Head has no `behind_transfers`, it serves no `TRANSFERRED` link: send no `TRANSFERRED` search. Never turn the block count into days or hours by head. To say how fresh the data is, give the newest `_utc` time you read on the layer you used: a family's lag counts its slowest layer, and the links of an address and the facts rows are often newer than it. If the server refuses the search with `anchor_missing` or `family_behind`, or stops it with `query_timeout`, it cannot search the whole chain now: say so in one line, name the family the refusal names, and ask for an address or drop the link type that is behind. A narrower window times out the same way, so do not send it again.
131
131
 
132
132
  The graph's layers are grouped into six families, and a family is as fresh as its slowest layer. The family of a link type decides which `Head` lag a whole-chain search on it waits for.
@@ -235,6 +235,7 @@ Marks say what an address is. They sit beside the kind and are never an anchor:
235
235
  RETURN w.swap_count AS swap_count, w.sold_usd AS sold_usd, w.bought_usd AS bought_usd, w.pools AS pools LIMIT 1
236
236
  ```
237
237
  - `:Scam` (`is_scam`), `:Poisoned`, `:Victim` (`is_victim`), `:Targeted` and `:OnMoneyTrail` are judgement marks from the labels layer. Why the mark is there sits in a sorted list on the node: `risk_claims` beside `:Scam`, `:Poisoned` and `:Sanctioned`, `protection_claims` beside `:Victim` and `:Targeted`, `traced_claims` beside `:OnMoneyTrail`. `suspect_labels` holds a warning or a record that accuses nobody: the address used a mixer pool, or it is a token that copies a listed token's name. It has no mark of its own. See [Judgement marks](#judgement-marks-scams-victims-and-trails).
238
+ - `behaviour_kind` and `behaviour_group` are no marks: two properties on a busy account, how it behaves and its operator group. See [Behaviour kinds](#behaviour-kinds-busy-accounts-and-their-operator-groups).
238
239
  - A basket is a Robinhood stock-basket token: one token that holds several stock tokens in near-equal USD weights. One factory, `0xe78b036bd6da158cd61a3dac3f67e18f62ecddfd`, creates every basket, and one router, `0xb672a5d825f82dea8574711d1da696fcc48d2ae0`, mints and redeems them. A basket is `:Protocol` and `:Token`, and its `labels` carry the word `Basket`. The factory is `:Protocol` and its `labels` carry `BasketFactory`. The router has no mark of its own beyond `:Contract`. See [Baskets](#baskets-is-this-a-basket-and-what-does-it-trade).
239
240
 
240
241
  **Ask by mark.** A question that names a kind of thing (mixers, launchpad pools, NFT collections, tokens of one standard, arbitrage bots) is a label match on the mark, a probe the server answers from the label index: nine `:Mixer` rows come back in 13 ms, a count of 2.4 million `:Token` in 4 s.
@@ -351,6 +352,59 @@ WHERE "VICTIM" IN v.protection_claims
351
352
  RETURN v.address AS victim_address, p.granted_tokens AS granted_tokens, p.last_height AS last_height LIMIT 25
352
353
  ```
353
354
 
355
+ ### Behaviour kinds: busy accounts and their operator groups
356
+
357
+ A busy account can carry `behaviour_kind`: how it behaves, from a rule over one week of its own on-chain counts. The rule reads accounts with 200 or more payers plus receivers in the week that no other label names. Every other address has none. The kind goes when the account goes quiet. It is a counted fact about the account, not a model's guess: never call it inferred.
358
+
359
+ A behaviour kind describes automation or volume, it is not a risk signal by itself; say so, and never present it as an accusation.
360
+
361
+ Say the kind in its plain words, never the constant alone:
362
+
363
+ | Kind | Say |
364
+ | --- | --- |
365
+ | `SWAP_BOT_FARM_WALLET` | one wallet of a swap-bot farm: takes funds from hundreds of brand-new wallets, swaps through a router, pays hundreds of other brand-new wallets |
366
+ | `DEX_TRADER_BOT` | an automated trader: most of its transfers touch pools or routers and it swaps hundreds of times a week |
367
+ | `VOLUME_RING_HUB` | the hub of a volume ring: pays a standing set of its own wallets, which pay it back |
368
+ | `WALLET_FARM_CONTROLLER` | funds hundreds of brand-new wallets in a burst and sweeps them back |
369
+ | `FIXED_AMOUNT_DISTRIBUTOR` | pays one fixed amount to hundreds of wallets that never pay back |
370
+ | `MIXER_LOOP_HUB` | collects from wallets that withdrew from a mixer and pays wallets that deposit into one |
371
+ | `PAYOUT_DESK` | payers and receivers are different people, active almost every hour of the week: the shape of a payment desk |
372
+
373
+ `behaviour_group` is `<behaviour_kind>:<first payer address>`: 3 or more accounts of one kind whose first ever payer is that address, one operator's wallets. It is absent when the account is in no group, and never there without the kind.
374
+
375
+ How to answer:
376
+
377
+ - A trader bot is no scammer. A user who asks "is this bot a scam" gets the kind in plain words, the sentence above, and the judgement marks of the address: a scam is a `:Scam` mark with its `risk_claims`, never a behaviour kind.
378
+ - `MIXER_LOOP_HUB` is a pattern of payments around a mixer, not proof of laundering. Say what the account does, and name a laundering trail only when `:OnMoneyTrail` says so.
379
+ - A kind is no mark and no word in `labels`. A judgement mark on the same address is read and said on its own.
380
+ - When the first payer of a group is an exchange wallet (`is_exchange`), a `:Pool` or a `:Protocol` contract, the group is the accounts it funded first, not one operator: say that, and send no members read.
381
+
382
+ What kind is this address, and in which group? One read, anchored on the address:
383
+
384
+ ```cypher
385
+ USE topology
386
+ MATCH (a:Address {address: "0x1111111111111111111111111111111111111111"})
387
+ RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.behaviour_kind AS behaviour_kind, a.behaviour_group AS behaviour_group, a.risk_claims AS risk_claims LIMIT 1
388
+ ```
389
+
390
+ Its group mates, or the members of a group someone names: the first payer is the address after the colon in `behaviour_group`. Read the payer first, anchored on it:
391
+
392
+ ```cypher
393
+ USE topology
394
+ MATCH (p:Address {address: "0x2222222222222222222222222222222222222222"})
395
+ RETURN p.address AS address, labels(p) AS node_labels, p.labels AS labels, p.is_exchange AS is_exchange, p.degree_out AS receivers LIMIT 1
396
+ ```
397
+
398
+ Then its receivers that carry the group, anchored on the payer. Every member's first payment came from it, so each member is one of its receivers. Write the group in full, the kind and the 42-character address:
399
+
400
+ ```cypher
401
+ USE topology
402
+ MATCH (p:Address {address: "0x2222222222222222222222222222222222222222"})-[f:FLOWED_TO]->(b:Address) WHERE NOT p:Pool AND b.behaviour_group = "DEX_TRADER_BOT:0x2222222222222222222222222222222222222222"
403
+ RETURN p.address AS from_address, b.address AS to_address, f.amount_usd_sum AS amount_usd_sum, f.tx_count AS tx_count, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp, p.labels AS from_labels, b.labels AS to_labels, p.is_exchange AS from_is_exchange, b.is_exchange AS to_is_exchange ORDER BY f.first_seen_timestamp LIMIT 25
404
+ ```
405
+
406
+ When 25 rows come back, say there may be more members. Never write `MATCH (a:Address) WHERE a.behaviour_kind = ...` or a `WHERE` on `behaviour_group` with no address: neither is a mark, the read has no anchor and the server refuses it. A question for every account of one kind gets the same answer as a whole-chain search: ask for an address, a group or its first payer.
407
+
354
408
  ## Topology
355
409
 
356
410
  `USE topology` is the address graph: `FLOWED_TO` money flow, swaps, liquidity,
@@ -409,7 +463,7 @@ RETURN a.degree_in AS senders, a.degree_out AS receivers, a.tx_total_count AS tx
409
463
 
410
464
  Where the lane's `money` family lists `ROUTED_TO`, a pool, a pool manager or a bonding curve has none of these totals: its transactions are not on `FLOWED_TO`. Its trade is the sum of its `SWAPPED` links, `sum(s.sold_usd)` and `sum(s.swap_count)`, as in reference R3L of `chain-insights-dex`.
411
465
 
412
- Which exchange an address cashed out to: its receivers that carry the exchange flag, one hop. Ask this first; it answers in under a second. A receiver whose `cex_role` is `deposit` is a deposit address of the exchange its `labels` name: check it with `aml_exchange_deposit_check` for the hot wallet it was swept into.
466
+ Which exchange an address cashed out to: its receivers that carry the exchange flag, one hop. Ask this first; it answers in under a second. A receiver whose `exchange_role` is `deposit` is a deposit address of the exchange its `labels` name: check it with `aml_exchange_deposit_check` for the hot wallet it was swept into.
413
467
 
414
468
  ```cypher
415
469
  USE topology
@@ -605,10 +659,14 @@ wallet's do. "Where did the money from <a deposit> go" is answered by its
605
659
  "the money entered <exchange> at deposit D and was swept n times into hot
606
660
  wallet H". Use the word swept: it is the move the exchange made.
607
661
 
662
+ `exchange_role` says which wallet of its exchange an `:Exchange` address is.
663
+ A lane not yet re-indexed still carries it as `cex_role`; read
664
+ `coalesce(a.exchange_role, a.cex_role)`.
665
+
608
666
  When a walk ends at an `:Exchange` address, name the exchange from its
609
667
  `labels`, then:
610
668
 
611
- - a deposit (`cex_role` `deposit`): read its `SWEPT` link, with
669
+ - a deposit (`exchange_role` `deposit`): read its `SWEPT` link, with
612
670
  `aml_exchange_deposit_check`, and say "the money entered <exchange> at
613
671
  deposit D, swept n times into hot wallet H". The exchange can name the
614
672
  customer behind D.
@@ -669,6 +727,24 @@ Name another link type to read its keys: `SWAPPED`, `LINKED`, `OPERATED_BY`, `BR
669
727
 
670
728
  The server serves five read-only catalog calls: `CALL db.labels()`, `CALL db.relationshipTypes()`, `CALL db.propertyKeys()`, `CALL db.schema.visualization()` and `SHOW INDEXES`. `meta_schema` sends four of them for you through one session and keeps the answer, so do not send them yourself.
671
729
 
730
+ ## The address card
731
+
732
+ Read the address card (identity, address_roles, behaviour, evidence, judgements, risk), not the labels list.
733
+
734
+ Every `:Address` node carries one card. `meta_schema` lists each card property with its question, its meaning and its closed values, and each mark and flag with the words that give it.
735
+
736
+ | Question | Card properties |
737
+ |---|---|
738
+ | What is the address, and its name (an exchange id)? | `identity`, `identity_name`, `identities` |
739
+ | Which wallet is it (`exchange_deposit`, `exchange_hot_wallet` and the other roles)? | `address_roles` |
740
+ | What does one week of counts show, and does it fit the role? | `behaviour`, `behaviour_week`, `role_fit` |
741
+ | What did it do, or what was done to it? Each entry is `word:VALUE`. | `evidence` |
742
+ | Which risky patterns, that accuse nobody? Each entry is `word:VALUE`. | `judgements` |
743
+ | How high is its risk: the highest level of any live word? | `risk` |
744
+ | Who gave the answers, from which vocabulary version, and when? | `sources`, `card_version`, `card_updated_ms` |
745
+
746
+ The card sits beside the `labels` list. The recipes of this skill keep reading the marks they name.
747
+
672
748
  ## Facts: an address pair with one day
673
749
 
674
750
  `USE facts` looks up rows you already know. A facts read names an address pair with one day. A transaction is read on `USE chain`, not here. A pair is both addresses, from then to, each as `{address: "<address>"}`, and the day is `t.block_date = "YYYY-MM-DD"`. One address, a day alone, a window of days, a block range and a bare `LIMIT` are not enough. It serves `TRANSFER`, `SWAP`, `LIQUIDITY_ADD`, `LIQUIDITY_REMOVE` and `BRIDGE_CROSSING` rows. The one facts read with no pair and no day is one contract by its address, in the next section.
@@ -0,0 +1,81 @@
1
+ ---
2
+ name: chain-insights-token-risk
3
+ door: aml_token_risk
4
+ description: Use for the risk of one token or one pool (token-risk) — a question that asks whether a token, a pool or a coin launched on Virtuals is risky, who founded or deployed it, who funded the founder, or who adds and removes its liquidity.
5
+ ---
6
+
7
+ # Chain Insights: the risk of one token or pool
8
+
9
+ Load `chain-insights-cypher` first. Its answer rules hold here, and these
10
+ hold even when it cannot load:
11
+
12
+ - Write every address in full, 42 characters, every time. Never shorten
13
+ one with `…` or `...`.
14
+ - USD figures are tokens worth at day prices: "tokens worth about N USD".
15
+ A null figure is unpriced, never 0.
16
+
17
+ ## The one call
18
+
19
+ Call `aml_token_risk` with `network` and the full address of the token
20
+ contract or the pool. A ticker is no address: call `meta_token_lookup`
21
+ first, because tickers collide. A wallet goes to `aml_address_risk`. Add
22
+ `surroundings: true` only when the host draws a picture.
23
+
24
+ Two of the tool's reads, shown so a host without the tool can send the same
25
+ ones through `graph_query`. The deployment, whose `tx_origin` is the
26
+ founder:
27
+
28
+ ```cypher
29
+ USE topology MATCH (d:Address)-[r:DEPLOYED_CONTRACT]->(t:Address {address: "0x766bd6598182586beda76414dc5f8deb1530a213"}) RETURN d.address AS deployer, r.tx_origin AS tx_origin, r.factory_address AS factory_address, r.kind AS kind, r.tx_id AS tx_id, r.block_timestamp AS block_timestamp LIMIT 1
30
+ ```
31
+
32
+ The providers of the token, one row per pool address and provider: one read
33
+ gives the pools, their providers and their biggest adders at once:
34
+
35
+ ```cypher
36
+ USE topology MATCH (a:Address)-[r:ADDED_LIQUIDITY {asset: "0x766bd6598182586beda76414dc5f8deb1530a213"}]->(p:Address) RETURN p.address AS pool, a.address AS address, sum(r.usd) AS tokens_worth_usd, count(r.usd) AS priced, sum(r.event_count) AS events, min(r.first_seen_height) AS first_seen_height, max(r.last_seen_height) AS last_seen_height, labels(a) AS node_labels, a.identity AS identity, a.identity_name AS identity_name, a.identities AS identities, a.evidence AS evidence, a.judgements AS judgements, a.risk_level AS risk_level, a.risk_score AS risk_score ORDER BY tokens_worth_usd DESC LIMIT 200
37
+ ```
38
+
39
+ ## How to read `risk`
40
+
41
+ - `risk.word` is the highest of the token's own word, its founder's word
42
+ and each detailed pool's own word. `raised_by` says whose (`token`,
43
+ `founder` or `pool`) and `raised_by_address` names it. `risk.own` is the
44
+ token's own block.
45
+ - The founder is the wallet that sent the deployment. `factory.name` comes
46
+ from the exchange registry, or from the token's launchpad identity;
47
+ `named_by` says which. A factory or
48
+ launchpad (such as Virtuals), a first funder in `gas_wallets` and a
49
+ liquidity provider never raise the word: each carries its own beside it.
50
+ - Every word is the higher of what labels prove (`rules_word`) and what the
51
+ risk model predicts (`model_word`); `set_by` says which. A word set by the
52
+ model alone is a prediction: say so.
53
+ - `unscored` means neither the labels nor the model speak. It is not `low`,
54
+ and it is not safe.
55
+ - A pool row is one address. The pools inside one pool manager (such as
56
+ Uniswap v4) are answered as one row for the manager (`is_manager: true`),
57
+ with its providers and this token's side (`token_side`), not pool by pool.
58
+ A manager row has no word and never raises the token's. A manager asked
59
+ about itself lists no adders, removers or tokens (`pool_tokens: []`): its
60
+ parties and its tokens are answered per token, so ask the token.
61
+ - `pools_found` counts every pool address of the token, exact up to 500,
62
+ and each pool's `providers` counts every provider. Only the 10 biggest
63
+ are detailed (`detail: true`); `pools_truncated` says when more exist,
64
+ and `parties_truncated` when a pool's 5 biggest adders or removers may
65
+ miss a party.
66
+
67
+ ## A hub
68
+
69
+ A token or a pool with more than 50,000 links is a hub: `exposure.hub` is
70
+ `true` and its own counterparties are not ranked (`not_read` names
71
+ `counterparties`). Its founder, factory and pools are still answered. To see
72
+ who traded with it, ask about one counterparty.
73
+
74
+ ## The judgement is yours
75
+
76
+ The tool states facts and measures. You write the judgement:
77
+
78
+ 1. Say which reasons and whose word you rely on.
79
+ 2. Say when a word comes from the model alone that it is a prediction.
80
+ 3. Never call a token or a pool safe.
81
+ 4. Name a part listed in `not_read` as not read, never as "none found".
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: 'Chain Insights Token Risk'
3
+ short_description: 'The risk of one token or pool: its founder, factory, gas wallets and pools'
4
+ default_prompt: 'Load chain-insights-cypher first. For the risk of one token or pool, call aml_token_risk with the network and the full contract address; for a ticker call meta_token_lookup first. The token word is the highest of the token, its founder and its pools; a factory, a first funder and a liquidity provider never raise it. Never call a token safe, and name a part in not_read as not read.'
@@ -280,4 +280,4 @@ Ask for every launchpad pool by the two marks, never by a text match over `label
280
280
  USE topology MATCH (p:Pool:Launchpad) RETURN p.address AS address, labels(p) AS node_labels, p.labels AS labels LIMIT 25
281
281
  ```
282
282
 
283
- The core skill's golden set (`tests/fixtures/graph-marks-golden.json`) pins these rows and the live test reads them on every release.
283
+ The core skill's golden set (`tests/fixtures/graph-marks-golden.json`) pins these rows, and chain-insights-validator reads them on the staging lane.
@@ -1 +0,0 @@
1
- {"version":3,"file":"dex-tool-7BK_gD6H.mjs","names":[],"sources":["../src/mcp/dex-recipes.ts","../src/mcp/dex-tool.ts"],"sourcesContent":["/**\n * The first reads of each trail type, filled with the addresses of one\n * exchange. meta_dex_lookup returns them, so a host that loads no skill\n * (Claude Desktop chat) still gets the tested reads of\n * skills/chain-insights-dex*. The shapes are the skills' own: R3 and R4 of\n * chain-insights-dex, G1, G4 and G5 of the gauge trail, V1, V3 and V4 of the\n * vault trail, L1 to L3 of the launchpad trail.\n *\n * A value the lookup cannot know (a seller, a day, a transaction) is written\n * as a placeholder in angle brackets, and the step's `why` says where it comes\n * from. Every address the lookup knows is written in full.\n *\n * Two graph shapes, picked per lane (src/mcp/layer-routing.ts swapLinkShape):\n * `route`, the graph of before, where SWAPPED runs from a payer to a recipient\n * and holds the whole route; and `levels`, where ROUTED_TO is the route of a\n * payer and a receiver (level 2) and SWAPPED runs from a trader to one pool\n * (level 1). Every `route` read is the one of chain-insights 0.81.0, byte for\n * byte: tests/link-levels.test.ts holds them to tests/fixtures/dex-reads-0.81.0.json.\n */\n\nimport type { DexEntry, TrailType } from './dex-registry.js'\nimport type { SwapLinkShape } from './layer-routing.js'\n\nexport interface RecipeStep {\n step: string\n why: string\n query: string\n}\n\n/** The trail-type skill of each trail, for hosts that load skills. */\nexport const TRAIL_SKILLS: Record<TrailType, string> = {\n plain: 'chain-insights-dex',\n gauge: 'chain-insights-dex-gauge',\n vault: 'chain-insights-dex-vault',\n launchpad: 'chain-insights-dex-launchpad',\n}\n\nconst SELLER = '<seller address>'\nconst DAY = '<YYYY-MM-DD>'\nconst TX = '<tx_id>'\nconst TOKEN = '<launched token address>'\n\n/**\n * The pools one factory deployed, ranked (R3). On the graph of before, by the\n * pool's lifetime volume. On a lane with the levels a pool has no address\n * totals (its transactions are not on FLOWED_TO), so the pools are ranked by\n * the USD sold into each on its SWAPPED links (R3L).\n */\nexport function poolsByFactoryQuery(\n factory: string,\n limit = 10,\n shape: SwapLinkShape = 'route'\n): string {\n if (shape === 'levels') {\n return (\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[:DEPLOYED_CONTRACT]->(p:Pool) ` +\n 'MATCH (t:Address)-[s:SWAPPED]->(p) ' +\n 'RETURN f.address AS from_address, p.address AS to_address, p.labels AS to_labels, sum(s.sold_usd) AS swapped_usd, sum(s.swap_count) AS swap_count ' +\n `ORDER BY swapped_usd DESC LIMIT ${limit}`\n )\n }\n return (\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[:DEPLOYED_CONTRACT]->(p:Pool) WHERE p.total_volume_usd IS NOT NULL ` +\n 'RETURN f.address AS from_address, p.address AS to_address, p.labels AS to_labels, p.total_volume_usd AS total_volume_usd, p.tx_total_count AS tx_total_count ' +\n `ORDER BY p.total_volume_usd DESC LIMIT ${limit}`\n )\n}\n\n/** The senders of one pool on FLOWED_TO, by lifetime volume (R4, G1). */\nfunction sellersIntoPoolQuery(pool: string): string {\n return (\n `USE topology MATCH (s:Address)-[f:FLOWED_TO]->(p:Address {address: \"${pool}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(s) AS from_node_labels, f.amount_usd_sum AS amount_usd_sum, f.tx_count AS tx_count, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp, s.labels AS from_labels, p.labels AS to_labels, s.is_exchange AS from_is_exchange, p.is_exchange AS to_is_exchange ' +\n 'ORDER BY f.amount_usd_sum DESC LIMIT 25'\n )\n}\n\n/** The payers whose swaps name one contract as the recipient, by sold volume (V4 shape). */\nfunction sellersIntoContractQuery(contract: string): string {\n return (\n `USE topology MATCH (s:Address)-[sw:SWAPPED]->(r:Address {address: \"${contract}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, r.address AS to_address, labels(s) AS from_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.pools AS pools, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.sold_usd DESC LIMIT 25'\n )\n}\n\n/** One seller's swaps (R5, G2, V1). */\nfunction sellerSwapsQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[sw:SWAPPED]->(r:Address) ` +\n 'RETURN s.address AS from_address, r.address AS to_address, labels(r) AS to_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.pools AS pools, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.swap_count DESC LIMIT 25'\n )\n}\n\n/** The facts SWAP rows of a seller and one recipient on one day (R6, G4, V3). */\nfunction swapRowsQuery(recipient: string): string {\n return (\n `USE facts MATCH (s:Address {address: \"${SELLER}\"})-[x:SWAP]->(r:Address {address: \"${recipient}\"}) WHERE x.block_date = \"${DAY}\" ` +\n 'RETURN x.tx_id AS tx_id, x.block_timestamp AS block_timestamp, x.payer AS payer, x.recipient AS recipient, x.sold_asset_symbol AS sold_asset_symbol, x.sold_usd AS sold_usd, x.bought_asset_symbol AS bought_asset_symbol, x.bought_usd AS bought_usd LIMIT 50'\n )\n}\n\n/** The transfers one router made in one transaction (G5). */\nfunction routerPayoutQuery(router: string): string {\n return (\n `USE facts MATCH (r:Address {address: \"${router}\"})-[t:TRANSFER]->(b:Address) WHERE t.block_date = \"${DAY}\" AND t.tx_id = \"${TX}\" ` +\n 'RETURN r.address AS from_address, b.address AS to_address, t.amount_usd AS amount_usd, t.asset_symbol AS asset_symbol, t.kind AS kind, t.tx_id AS tx_id LIMIT 10'\n )\n}\n\n/** The traders at one pool or pool manager on SWAPPED, by sold volume (levels). */\nfunction tradersAtPoolQuery(pool: string): string {\n return (\n `USE topology MATCH (s:Address)-[sw:SWAPPED]->(p:Address {address: \"${pool}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(s) AS from_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.first_seen_height AS first_seen_height, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.sold_usd DESC LIMIT 25'\n )\n}\n\n/** One trader's routes on ROUTED_TO: who got what it bought (levels). */\nfunction traderRoutesQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[r:ROUTED_TO]->(b:Address) ` +\n 'RETURN s.address AS from_address, b.address AS to_address, labels(b) AS to_node_labels, r.tx_count AS tx_count, r.swap_count AS swap_count, r.amount_usd_sum AS amount_usd_sum, r.bought_usd_sum AS bought_usd_sum, r.unpriced_count AS unpriced_count, r.first_seen_timestamp AS first_seen_timestamp, r.last_seen_timestamp AS last_seen_timestamp ' +\n 'ORDER BY r.amount_usd_sum DESC LIMIT 25'\n )\n}\n\n/** One trader's swaps on SWAPPED: the pools and the assets (levels). */\nfunction traderPoolSwapsQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[sw:SWAPPED]->(p:Address) ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(p) AS to_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.swap_count DESC LIMIT 25'\n )\n}\n\nconst dayStep: RecipeStep = {\n step: 'The day of a swap link',\n why: 'A SWAPPED link carries heights, not times: read the block of its last_seen_height for the day the facts reads need.',\n query:\n 'USE chain MATCH (b:Block {block_height: <last_seen_height>}) RETURN b.block_date, b.block_timestamp',\n}\n\n/**\n * The pool a trail starts from: the busiest pool read, else the registry's\n * example pool, else none.\n */\nfunction startPool(entry: DexEntry, topPool: string | null): string | null {\n return topPool ?? entry.example_pool ?? null\n}\n\nfunction poolsStep(entry: DexEntry, shape: SwapLinkShape = 'route'): RecipeStep | null {\n const factory = entry.factories.find((address) => entry.roles[address] === 'factory')\n if (!factory) return null\n const members = entry.factories.filter((a) => entry.roles[a] === 'factory').join(', ')\n if (shape === 'levels') {\n return {\n step: 'Pools of the exchange, by factory',\n why: `The pools ${entry.display} deployed, by the USD sold into each on its SWAPPED links, with its swap count. A pool has no address totals on this lane. A pool nobody swapped in is left out. One batch member per factory: ${members}.`,\n query: poolsByFactoryQuery(factory, 10, 'levels'),\n }\n }\n return {\n step: 'Pools of the exchange, by factory',\n why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${members}.`,\n query: poolsByFactoryQuery(factory),\n }\n}\n\n/** The first reads of the exchange's trail type, with its addresses filled in. */\nexport function recipeFor(\n entry: DexEntry,\n topPool: string | null,\n shape: SwapLinkShape = 'route'\n): RecipeStep[] {\n return shape === 'levels' ? levelsRecipeFor(entry, topPool) : routeRecipeFor(entry, topPool)\n}\n\nconst routesStep: RecipeStep = {\n step: \"Who got what a trader bought\",\n why: 'Fill a trader from the first step. Each ROUTED_TO link is the swaps of one payer and one receiver, in USD: a link to the trader itself means it bought for itself, any other receiver is the buyer. No router and no pool is a receiver.',\n query: traderRoutesQuery(),\n}\n\nconst poolSwapsStep: RecipeStep = {\n step: \"A trader's pools and assets\",\n why: 'Fill the trader: each SWAPPED link is one pool and one asset pair, with what the pool got (sold) and what it gave (bought).',\n query: traderPoolSwapsQuery(),\n}\n\n/** The reads of a lane with the levels: SWAPPED to a pool, ROUTED_TO for the route. */\nfunction levelsRecipeFor(entry: DexEntry, topPool: string | null): RecipeStep[] {\n const pool = startPool(entry, topPool)\n const steps: RecipeStep[] = []\n const poolTraders = (at: string): RecipeStep => ({\n step: 'Traders at the busiest pool',\n why: `The traders of ${at} on SWAPPED, by sold volume. A trader that is a contract is often an aggregator or a bot: say \"a contract\". A sender that only adds liquidity is on ADDED_LIQUIDITY, not here.`,\n query: tradersAtPoolQuery(at),\n })\n switch (entry.trail_type) {\n case 'gauge': {\n const router = entry.routers[0]\n if (pool) steps.push(poolTraders(pool))\n else {\n const pools = poolsStep(entry, 'levels')\n if (pools) steps.push(pools)\n }\n steps.push(routesStep)\n if (router) {\n steps.push(dayStep)\n steps.push({\n step: \"A trader's swaps through the router on one day\",\n why: `Fill the trader and the day: each row gives the tx_id of one swap that named the router ${router}; the router is never the buyer.`,\n query: swapRowsQuery(router),\n })\n steps.push({\n step: 'Who the router paid in that transaction',\n why: 'Fill the day and the tx_id: the receiver of the bought asset is the buyer. A pool or a pool manager there is the next leg, not the buyer.',\n query: routerPayoutQuery(router),\n })\n }\n break\n }\n case 'vault': {\n const manager = entry.factories[0]!\n steps.push({\n step: 'Traders at the pool manager',\n why: `${entry.display} keeps every pool in one manager, ${manager}. Each SWAPPED link into it is one trader and one asset pair: the pair names the pool.`,\n query: tradersAtPoolQuery(manager),\n })\n steps.push(routesStep)\n steps.push(dayStep)\n steps.push({\n step: 'The facts SWAP row past the manager',\n why: 'Fill the trader and the day: the recipient column names who the manager paid.',\n query: swapRowsQuery(manager),\n })\n break\n }\n case 'launchpad': {\n const factory = entry.factories[0]!\n steps.push({\n step: 'Launches of the launchpad, newest first',\n why: `The contracts ${factory} created, with the creator of each.`,\n query:\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[d:DEPLOYED_CONTRACT]->(t:Address) ` +\n 'RETURN f.address AS from_address, t.address AS to_address, labels(t) AS to_node_labels, t.labels AS to_labels, d.tx_origin AS creator, d.tx_id AS tx_id, d.block_height AS block_height, d.block_timestamp AS created_timestamp ORDER BY d.block_height DESC LIMIT 25',\n })\n steps.push({\n step: 'Traders on the curve of one launched token',\n why: 'Fill a launched token from the first step. A curve is a pool: its traders are its SWAPPED links. A launch whose curve is another contract has its traders on that contract.',\n query: tradersAtPoolQuery(TOKEN),\n })\n steps.push({\n step: 'The first pool of one launched token',\n why: 'The oldest ADDED_LIQUIDITY into a :Pool is the graduation. None means it has not graduated in the graph yet.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[l:ADDED_LIQUIDITY]->(p:Pool) ` +\n 'RETURN t.address AS from_address, p.address AS to_address, p.labels AS to_labels, l.asset AS asset, l.usd AS usd, l.first_seen_height AS first_seen_height ORDER BY l.first_seen_height ASC LIMIT 5',\n })\n break\n }\n case 'plain': {\n if (pool) steps.push(poolTraders(pool))\n else {\n const pools = poolsStep(entry, 'levels')\n if (pools) steps.push(pools)\n }\n steps.push(routesStep)\n steps.push(poolSwapsStep)\n steps.push(dayStep)\n steps.push({\n step: 'The swaps of a trader and a receiver on one day',\n why: 'Fill the trader, the receiver and the day.',\n query: swapRowsQuery('<recipient address>'),\n })\n break\n }\n }\n return steps\n}\n\n/** The reads of a lane with the graph of before: SWAPPED holds the route. */\nfunction routeRecipeFor(entry: DexEntry, topPool: string | null): RecipeStep[] {\n const pool = startPool(entry, topPool)\n const steps: RecipeStep[] = []\n switch (entry.trail_type) {\n case 'gauge': {\n const router = entry.routers[0]\n if (router) {\n steps.push({\n step: 'Sellers into the router',\n why: `On ${entry.display} a swap pays the router, and the router pays on. These are the payers whose swaps name the router ${router}; the router is never the buyer.`,\n query: sellersIntoContractQuery(router),\n })\n }\n if (pool) {\n steps.push({\n step: 'Sellers into the busiest pool',\n why: `The senders of ${pool} on FLOWED_TO. A sender that also adds liquidity is a liquidity provider, not a seller.`,\n query: sellersIntoPoolQuery(pool),\n })\n } else {\n const pools = poolsStep(entry)\n if (pools) steps.push(pools)\n }\n if (router) {\n steps.push(dayStep)\n steps.push({\n step: \"A seller's swaps through the router on one day\",\n why: 'Fill the seller from the first step and the day from the block read: each row gives the tx_id of one swap.',\n query: swapRowsQuery(router),\n })\n steps.push({\n step: 'Who the router paid in that transaction',\n why: 'Fill the day and the tx_id: the receiver of the bought asset is the buyer. A pool or a pool manager there is the next leg, not the buyer.',\n query: routerPayoutQuery(router),\n })\n }\n break\n }\n case 'vault': {\n const manager = entry.factories[0]!\n steps.push({\n step: 'The swaps the pool manager settles',\n why: `${entry.display} keeps every pool in one manager, ${manager}. A manager deploys nothing: its pools are the pools of the swaps it settles.`,\n query: sellersIntoContractQuery(manager),\n })\n steps.push({\n step: \"One seller's swaps\",\n why: 'Fill a seller from the first step. A recipient that is the manager is never the buyer: read the facts row past it.',\n query: sellerSwapsQuery(),\n })\n steps.push(dayStep)\n steps.push({\n step: 'The facts SWAP row past the manager',\n why: 'Fill the seller and the day: the recipient column names who the manager paid.',\n query: swapRowsQuery(manager),\n })\n break\n }\n case 'launchpad': {\n const factory = entry.factories[0]!\n steps.push({\n step: 'Launches of the launchpad, newest first',\n why: `The contracts ${factory} created, with the creator of each.`,\n query:\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[d:DEPLOYED_CONTRACT]->(t:Address) ` +\n 'RETURN f.address AS from_address, t.address AS to_address, labels(t) AS to_node_labels, t.labels AS to_labels, d.tx_origin AS creator, d.tx_id AS tx_id, d.block_height AS block_height, d.block_timestamp AS created_timestamp ORDER BY d.block_height DESC LIMIT 25',\n })\n steps.push({\n step: 'Traders on the curve of one launched token',\n why: 'Fill a launched token from the first step.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[f:FLOWED_TO]-(b:Address) WHERE NOT t:Pool ` +\n 'RETURN startNode(f).address AS from_address, endNode(f).address AS to_address, labels(b) AS node_labels, f.tx_count AS tx_count, f.amount_usd_sum AS amount_usd_sum, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp ORDER BY f.tx_count DESC LIMIT 25',\n })\n steps.push({\n step: 'The first pool of one launched token',\n why: 'The oldest ADDED_LIQUIDITY into a :Pool is the graduation. None means it has not graduated in the graph yet.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[l:ADDED_LIQUIDITY]->(p:Pool) ` +\n 'RETURN t.address AS from_address, p.address AS to_address, p.labels AS to_labels, l.asset AS asset, l.usd AS usd, l.first_seen_height AS first_seen_height ORDER BY l.first_seen_height ASC LIMIT 5',\n })\n break\n }\n case 'plain': {\n if (pool) {\n steps.push({\n step: 'Sellers into the busiest pool',\n why: `The senders of ${pool} on FLOWED_TO, by lifetime volume. A seller that is a contract is often an aggregator or a router: say \"a contract\".`,\n query: sellersIntoPoolQuery(pool),\n })\n } else {\n const pools = poolsStep(entry)\n if (pools) steps.push(pools)\n }\n steps.push({\n step: \"Who a seller's swaps paid\",\n why: 'Fill a seller from the first step. Keep the rows whose pools hold the pool: the recipient is the buyer.',\n query: sellerSwapsQuery(),\n })\n steps.push(dayStep)\n steps.push({\n step: 'The swaps of a seller and a recipient on one day',\n why: 'Fill the seller, the recipient and the day.',\n query: swapRowsQuery('<recipient address>'),\n })\n break\n }\n }\n return steps\n}\n","/**\n * meta_dex_lookup: an exchange's name becomes its addresses.\n *\n * A local tool of the proxy. It matches the name against the exchange registry\n * (src/mcp/dex-registry.ts) at no cost, then sends one graph_query_batch of\n * anchored reads: Head for the family lag, each factory, manager and router by\n * its address, and the pools each factory deployed. Nothing is read by name and\n * nothing is gated on a family lag: a factory deployed months ago is not stale\n * because the swap family is behind. A name that is not covered sends no read.\n *\n * The description below is the contract with every host, Claude Desktop chat\n * included, which reads no skill: it carries the rule the exchange skills open\n * with, and the level rule. tests/host-parity.test.ts holds it to the skills'\n * trigger words and to the level rule.\n *\n * The first reads follow the lane's graph shape (`linkShape`, read from\n * meta_network_capabilities): on a lane whose money family lists ROUTED_TO the\n * reads name SWAPPED from a trader to the pool and ROUTED_TO for the route; on\n * any other lane they are the reads of chain-insights 0.81.0, byte for byte.\n * The pool read follows the shape too: on a lane with the levels a pool has no\n * address totals, so its pools are ranked by the USD sold into each on SWAPPED.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { recipeFor, TRAIL_SKILLS, type RecipeStep, poolsByFactoryQuery } from './dex-recipes.js'\nimport { LEVEL_RULE, type SwapLinkShape } from './layer-routing.js'\nimport {\n DexRegistryError,\n matchDex,\n normalizeDexNetwork,\n type DexCandidate,\n type DexEntry,\n type DexMatchResult,\n type LoadedRegistry,\n type RegistrySource,\n type Role,\n type TrailType,\n} from './dex-registry.js'\n\nexport const META_DEX_LOOKUP_TOOL = 'meta_dex_lookup'\nexport const META_DEX_LOOKUP_SCHEMA = 'chain-insights.meta-dex-lookup.v1' as const\nexport const META_DEX_LOOKUP_TITLE = 'Exchange by name or address'\nexport const META_DEX_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a decentralized exchange, a launchpad or a vault ' +\n '(Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, ' +\n \"Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's \" +\n 'factories, routers or pool manager, its biggest pools, and the first reads to send, ' +\n 'with every address in full. A misspelling within two letters is taken and named in ' +\n 'took_for. When matched is null the name is not covered: say so, list covered, and send ' +\n 'no graph query for the name. Never ask the user for a pool, factory or router address. ' +\n 'When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, ' +\n 'any case, with no name): the answer is the exchange whose factory, router or manager it is, ' +\n 'and took_for names the role it holds. When matched is null no exchange row holds the address: ' +\n 'send no read for it. A centralized exchange (Binance, OKX, Bitget) goes to meta_exchange_lookup instead. Give a name or an address, not both. ' +\n `${LEVEL_RULE} The first reads follow the lane: where it serves ROUTED_TO, the traders of a pool are its SWAPPED links and the route of a trader is ROUTED_TO. ` +\n 'There each pool carries swapped_usd (the USD sold into it on its SWAPPED links) and swap_count, in place of total_volume_usd and tx_total_count.'\nexport const META_DEX_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_DEX_LOOKUP_ARGS = ['network', 'name', 'address', 'pools'] as const\n\n/** The pools returned per exchange, and per factory read. */\nexport const POOLS_LIMIT = 10\n/** A batch holds at most 20 members; Head and the pool reads take their share. */\nconst CONTRACT_MEMBERS_MAX = 12\n\nexport interface ContractRow {\n address: string\n role: Role\n confirmed: boolean\n confirmed_by?: string\n}\n\n/** A pool on the graph of before: its address totals, as in 0.81.0. */\nexport interface RoutePoolRow {\n address: string\n labels: string[]\n total_volume_usd: number\n tx_total_count: number\n}\n\n/**\n * A pool on a lane with the levels. A pool has no address totals there: its\n * transactions are not on FLOWED_TO. Its numbers are the sums of its SWAPPED\n * links: `swapped_usd`, the USD sold into it, and `swap_count`, its swaps.\n */\nexport interface LevelsPoolRow {\n address: string\n labels: string[]\n swapped_usd: number\n swap_count: number\n}\n\nexport type PoolRow = RoutePoolRow | LevelsPoolRow\n\nexport interface FamilyLag {\n behind_money: number | null\n behind_dex: number | null\n behind_transfers: number | null\n}\n\nexport interface DexMatch {\n dex: string\n display: string\n trail_type: TrailType\n /** The skill a host with skills loads next. */\n skill: string\n factories: ContractRow[]\n routers: ContractRow[]\n manager: ContractRow | null\n pools: PoolRow[]\n recipe: RecipeStep[]\n}\n\nexport interface CoveredExchange {\n dex: string\n display: string\n trail_type: TrailType\n factories: string[]\n routers: string[]\n}\n\nexport interface MetaDexLookupResult {\n schema: typeof META_DEX_LOOKUP_SCHEMA\n network: string\n registry_version: number\n registry_source: RegistrySource\n matched: DexMatch | null\n /** A near name hit: the name as typed. An address hit: the role it holds and the verification cell. */\n took_for?: string\n candidates: DexCandidate[]\n covered: string[]\n /** With no name: every covered exchange, with its key, trail type and contracts. */\n exchanges?: CoveredExchange[]\n families: FamilyLag | null\n /** `levels` on a lane whose money family lists ROUTED_TO; absent on the graph of before. */\n swap_links?: 'levels'\n /** What a read could not do: a lane that is not reachable, a member that was refused. */\n notes?: string[]\n hint: string\n}\n\n/** The batch reply as the remote client returns it. */\nexport type BatchAnswer = {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n}\n\nexport interface DexToolDependencies {\n loadRegistry: (network: string) => Promise<LoadedRegistry>\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<BatchAnswer>\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 * The shape of the lane's swap links, read from meta_network_capabilities.\n * Absent, or a read that fails, means the graph of before (`route`).\n */\n linkShape?: (network: string) => Promise<SwapLinkShape> | SwapLinkShape\n}\n\nexport type MetaDexLookupToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\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): MetaDexLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\ntype Member = { id?: unknown; ok?: unknown; results?: unknown; error?: unknown }\n\nfunction membersOf(answer: BatchAnswer): 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\nconst rowsOf = (member: Member | undefined): Array<Record<string, unknown>> =>\n member?.ok === true && Array.isArray(member.results) ? member.results.filter(isRecord) : []\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 stringList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n\n/** A column of a row, read under its alias or as the query wrote it (h.behind_dex). */\nfunction column(row: Record<string, unknown>, name: string, variable: string): unknown {\n return name in row ? row[name] : row[`${variable}.${name}`]\n}\n\nexport const HEAD_QUERY =\n 'USE chain MATCH (h:Head) RETURN h.behind_money, h.behind_dex, h.behind_transfers'\n\nexport function contractQuery(address: string): string {\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"}) ` +\n 'RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT 1'\n )\n}\n\nexport function contractListQuery(addresses: string[]): string {\n return (\n `USE topology MATCH (a:Address) WHERE a.address IN [${addresses.map((a) => `\"${a}\"`).join(', ')}] ` +\n `RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT ${addresses.length}`\n )\n}\n\n/** The anchored reads of one exchange: Head, each contract, and the pools of each factory. */\nexport function lookupQueries(\n entry: DexEntry,\n pools: boolean,\n shape: SwapLinkShape = 'route'\n): Array<{ id: string; query: string }> {\n const contracts = Object.keys(entry.roles)\n const queries: Array<{ id: string; query: string }> = [{ id: 'head', query: HEAD_QUERY }]\n if (contracts.length <= CONTRACT_MEMBERS_MAX) {\n for (const address of contracts)\n queries.push({ id: `contract:${address}`, query: contractQuery(address) })\n } else {\n queries.push({ id: 'contracts', query: contractListQuery(contracts) })\n }\n if (pools) {\n for (const factory of entry.factories.filter((address) => entry.roles[address] === 'factory')) {\n queries.push({ id: `pools:${factory}`, query: poolsByFactoryQuery(factory, POOLS_LIMIT, shape) })\n }\n }\n return queries\n}\n\nfunction confirmation(\n row: Record<string, unknown> | undefined\n): Pick<ContractRow, 'confirmed' | 'confirmed_by'> {\n if (!row) return { confirmed: false }\n if (row.is_contract === true) return { confirmed: true, confirmed_by: 'is_contract' }\n if (stringList(row.node_labels).includes('Contract'))\n return { confirmed: true, confirmed_by: ':Contract' }\n return { confirmed: false }\n}\n\n/** The pools of the batch, merged over the factories and ranked by the shape's number. */\nfunction readPools(members: Map<string, Member>, shape: SwapLinkShape): PoolRow[] {\n const byAddress = new Map<string, { row: PoolRow; rank: number }>()\n for (const [id, member] of members) {\n if (!id.startsWith('pools:')) continue\n for (const row of rowsOf(member)) {\n const address = typeof row.to_address === 'string' ? row.to_address : null\n const rank = numberOrNull(shape === 'levels' ? row.swapped_usd : row.total_volume_usd)\n if (!address || rank === null || byAddress.has(address)) continue\n const labels = stringList(row.to_labels)\n byAddress.set(address, {\n rank,\n row:\n shape === 'levels'\n ? { address, labels, swapped_usd: rank, swap_count: numberOrNull(row.swap_count) ?? 0 }\n : {\n address,\n labels,\n total_volume_usd: rank,\n tx_total_count: numberOrNull(row.tx_total_count) ?? 0,\n },\n })\n }\n }\n return [...byAddress.values()]\n .sort((a, b) => b.rank - a.rank)\n .slice(0, POOLS_LIMIT)\n .map(({ row }) => row)\n}\n\nfunction readMatch(\n entry: DexEntry,\n members: Map<string, Member>,\n read: boolean,\n shape: SwapLinkShape\n): {\n contracts: Map<string, ContractRow>\n pools: PoolRow[]\n families: FamilyLag | null\n notes: string[]\n} {\n const notes: string[] = []\n const contracts = new Map<string, ContractRow>()\n const listed = new Map(rowsOf(members.get('contracts')).map((row) => [String(row.address), row]))\n for (const [address, role] of Object.entries(entry.roles)) {\n const row = members.has(`contract:${address}`)\n ? rowsOf(members.get(`contract:${address}`))[0]\n : listed.get(address)\n contracts.set(address, { address, role, ...confirmation(row) })\n }\n const pools = readPools(members, shape)\n const head = rowsOf(members.get('head'))[0]\n const families: FamilyLag | null = head\n ? {\n behind_money: numberOrNull(column(head, 'behind_money', 'h')),\n behind_dex: numberOrNull(column(head, 'behind_dex', 'h')),\n behind_transfers: numberOrNull(column(head, 'behind_transfers', 'h')),\n }\n : null\n if (read) {\n for (const [id, member] of members) {\n if (member.ok !== true)\n notes.push(\n `${id}: ${typeof member.error === 'string' ? member.error : 'the read was not served'}`\n )\n }\n }\n return { contracts, pools, families, notes }\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\n\n/** The hint's last rule on a lane with the levels; the graph of before keeps its 0.81.0 text. */\nconst LEVELS_HINT =\n `${LEVEL_RULE} Each pool carries swapped_usd, the USD sold into it on its SWAPPED links, and swap_count, its swaps: say \"tokens worth about N USD sold into the pool\", never its lifetime volume. ` +\n 'Read families before a whole-chain SWAPPED search: it is sent when behind_dex is at most 100000, and a ROUTED_TO search when behind_money is. Never ask the user for an address.'\nconst ROUTE_HINT =\n 'Read families before a SWAPPED search: it is sent when behind_dex is at most 100000. Never ask the user for an address.'\n\nfunction hintFor(\n result: Omit<MetaDexLookupResult, 'hint'>,\n name: string | null,\n address: string | null = null\n): string {\n const closing = result.swap_links === 'levels' ? LEVELS_HINT : ROUTE_HINT\n if (address !== null && !result.matched) {\n return `${ANSWER_HINT} No exchange row holds ${address}: it is not a registered exchange contract. Send no exchange read for it; read the graph for what the address did.`\n }\n if (address !== null && result.matched) {\n const { matched } = result\n return (\n `${ANSWER_HINT} Say in one line: \"${address} is a ${result.took_for} row of ${matched.display}.\" Ask nothing. ` +\n `Exchange ${matched.display}, trail ${matched.trail_type}: send the first reads of recipe, ` +\n `anchored on the addresses above, and load ${matched.skill} when this host has skills. ` +\n closing\n )\n }\n if (name === null) {\n return `${ANSWER_HINT} These are the exchanges the registry covers. Call meta_dex_lookup with a name for its addresses and first reads.`\n }\n if (result.matched) {\n const { matched } = result\n const took = result.took_for\n ? `Say in one line: \"I took ${matched.display} for ${result.took_for}.\" Ask nothing. `\n : ''\n return (\n `${ANSWER_HINT} ${took}Exchange ${matched.display}, trail ${matched.trail_type}: send the first reads of recipe, ` +\n `anchored on the addresses above, and load ${matched.skill} when this host has skills. ` +\n closing\n )\n }\n if (result.candidates.length > 0) {\n const names = result.candidates\n .map((candidate) => `${candidate.display} (${candidate.dex})`)\n .join(', ')\n return `${ANSWER_HINT} ${result.candidates.length} rows fit \"${name}\": ${names}. Name both or pick one: call meta_dex_lookup with each key. Never guess one, never ask the user for an address.`\n }\n return `${ANSWER_HINT} ${name} is not covered. Send no query for the name: say so in one line and list the covered exchanges by name.`\n}\n\nfunction textResult(structured: MetaDexLookupResult): MetaDexLookupToolResult {\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/** meta_dex_lookup, {network, name?, address?, pools?}. Every argument is checked before the registry is read. */\nexport async function handleMetaDexLookup(\n args: unknown,\n deps: DexToolDependencies\n): Promise<MetaDexLookupToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult((err as Error).message)\n }\n const rawName = record.name\n if (rawName !== undefined && rawName !== null && typeof rawName !== 'string') {\n return errorResult('invalid_name: name must be the exchange name as text')\n }\n const name = typeof rawName === 'string' && rawName.trim() !== '' ? rawName.trim() : null\n const rawAddress = record.address\n if (rawAddress !== undefined && rawAddress !== null && typeof rawAddress !== 'string') {\n return errorResult('invalid_address: address must be 0x plus 40 hex characters')\n }\n const addressText =\n typeof rawAddress === 'string' && rawAddress.trim() !== '' ? rawAddress.trim() : null\n if (name !== null && addressText !== null)\n return errorResult('Give a name or an address, not both.')\n if (addressText !== null && !ADDRESS_FORM.test(addressText)) {\n return errorResult('invalid_address: address must be 0x plus 40 hex characters')\n }\n const address = addressText === null ? null : addressText.toLowerCase()\n const rawPools = record.pools\n if (rawPools !== undefined && rawPools !== null && typeof rawPools !== 'boolean') {\n return errorResult('invalid_pools: pools must be true or false')\n }\n const pools = rawPools !== false\n\n let loaded: LoadedRegistry\n try {\n loaded = await deps.loadRegistry(network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError\n ? err.message\n : `exchange registry unavailable: ${(err as Error).message}`\n )\n }\n const { document } = loaded\n const base = {\n schema: META_DEX_LOOKUP_SCHEMA,\n network,\n registry_version: document.registry_version,\n registry_source: loaded.source,\n }\n\n if (name === null && address === null) {\n const result = {\n ...base,\n matched: null,\n candidates: [],\n covered: document.rows.map((row) => row.display),\n exchanges: document.rows.map((row) => ({\n dex: row.dex,\n display: row.display,\n trail_type: row.trail_type,\n factories: row.factories,\n routers: row.routers,\n })),\n families: null,\n }\n return textResult({ ...result, hint: hintFor(result, null) })\n }\n\n let match: DexMatchResult\n if (address !== null) {\n const holder = document.rows.find(\n (row) => address in row.roles || row.helpers?.includes(address)\n )\n match = {\n matched: holder ?? null,\n ...(holder ? { took_for: `${holder.roles[address] ?? 'helper'}, served` } : {}),\n candidates: [],\n covered: document.rows.map((row) => row.display),\n }\n } else {\n match = matchDex(name as string, document.rows)\n }\n if (!match.matched) {\n const result = {\n ...base,\n matched: null,\n candidates: match.candidates,\n covered: match.covered,\n families: null,\n }\n return textResult({ ...result, hint: hintFor(result, name, address) })\n }\n\n const entry = match.matched\n const unavailable = await deps.unavailable?.()\n // The shape is read first: the pool read of the batch follows it.\n let shape: SwapLinkShape = 'route'\n if (!unavailable && deps.linkShape) {\n try {\n shape = await deps.linkShape(network)\n } catch {\n shape = 'route'\n }\n }\n const queries = lookupQueries(entry, pools, shape)\n let members = new Map<string, Member>()\n const notes: string[] = []\n if (unavailable) {\n notes.push(\n `No graph read was sent: ${unavailable} The contracts are the reviewed registry rows, not yet confirmed on the graph.`\n )\n } else {\n try {\n const answer = await deps.graphQueryBatch({ network, queries })\n members = membersOf(answer)\n if (answer.isError === true && members.size === 0) {\n const first = Array.isArray(answer.content) ? answer.content[0] : undefined\n notes.push(\n `The graph refused the reads: ${isRecord(first) && typeof first.text === 'string' ? first.text : 'no reason given'}`\n )\n }\n } catch (err) {\n notes.push(`The graph reads failed: ${deps.describeFailure(err)}`)\n }\n }\n const read = readMatch(entry, members, members.size > 0, shape)\n notes.push(...read.notes)\n const contractsOf = (role: Role): ContractRow[] =>\n [...read.contracts.values()].filter((contract) => contract.role === role)\n const topPool = read.pools[0]?.address ?? null\n const matched: DexMatch = {\n dex: entry.dex,\n display: entry.display,\n trail_type: entry.trail_type,\n skill: TRAIL_SKILLS[entry.trail_type],\n factories: contractsOf('factory'),\n routers: contractsOf('router'),\n manager: contractsOf('manager')[0] ?? null,\n pools: read.pools,\n recipe: recipeFor(entry, topPool, shape),\n }\n const result = {\n ...base,\n matched,\n ...(match.took_for ? { took_for: match.took_for } : {}),\n candidates: [],\n covered: match.covered,\n families: read.families,\n ...(shape === 'levels' ? { swap_links: 'levels' as const } : {}),\n ...(notes.length > 0 ? { notes } : {}),\n }\n return textResult({ ...result, hint: hintFor(result, name, address) })\n}\n"],"mappings":";;;;;;AA8BA,MAAa,eAA0C;CACrD,OAAO;CACP,OAAO;CACP,OAAO;CACP,WAAW;AACb;AAEA,MAAM,SAAS;AACf,MAAM,MAAM;AACZ,MAAM,KAAK;AACX,MAAM,QAAQ;;;;;;;AAQd,SAAgB,oBACd,SACA,QAAQ,IACR,QAAuB,SACf;CACR,IAAI,UAAU,UACZ,OACE,4CAA4C,QAAQ,0PAGjB;CAGvC,OACE,4CAA4C,QAAQ,8QAEV;AAE9C;;AAGA,SAAS,qBAAqB,MAAsB;CAClD,OACE,uEAAuE,KAAK;AAIhF;;AAGA,SAAS,yBAAyB,UAA0B;CAC1D,OACE,sEAAsE,SAAS;AAInF;;AAGA,SAAS,mBAA2B;CAClC,OACE,4CAA4C,OAAO;AAIvD;;AAGA,SAAS,cAAc,WAA2B;CAChD,OACE,yCAAyC,OAAO,sCAAsC,UAAU,4BAA4B,IAAI;AAGpI;;AAGA,SAAS,kBAAkB,QAAwB;CACjD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J,gCAAgC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,mBACnG;EACF;CACF,SAAS,KAAK;EACZ,MAAM,KAAK,2BAA2B,KAAK,gBAAgB,GAAG,GAAG;CACnE;CAEF,MAAM,OAAO,UAAU,OAAO,SAAS,QAAQ,OAAO,GAAG,KAAK;CAC9D,MAAM,KAAK,GAAG,KAAK,KAAK;CACxB,MAAM,eAAe,SACnB,CAAC,GAAG,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC,QAAQ,aAAa,SAAS,SAAS,IAAI;CAC1E,MAAM,UAAU,KAAK,MAAM,EAAE,EAAE,WAAW;CAC1C,MAAM,UAAoB;EACxB,KAAK,MAAM;EACX,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,OAAO,aAAa,MAAM;EAC1B,WAAW,YAAY,SAAS;EAChC,SAAS,YAAY,QAAQ;EAC7B,SAAS,YAAY,SAAS,CAAC,CAAC,MAAM;EACtC,OAAO,KAAK;EACZ,QAAQ,UAAU,OAAO,SAAS,KAAK;CACzC;CACA,MAAM,SAAS;EACb,GAAG;EACH;EACA,GAAI,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;EACrD,YAAY,CAAC;EACb,SAAS,MAAM;EACf,UAAU,KAAK;EACf,GAAI,UAAU,WAAW,EAAE,YAAY,SAAkB,IAAI,CAAC;EAC9D,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;CACtC;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,MAAM,OAAO;CAAE,CAAC;AACvE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"exchange-deposit-check-CXHZCHWW.mjs","names":[],"sources":["../src/mcp/exchange-deposit-check.ts"],"sourcesContent":["/**\n * aml_exchange_deposit_check: is this address an exchange deposit, of which\n * exchange, and into which hot wallet was it swept?\n *\n * A local tool of the proxy. It sends one graph_query_batch with six reads on\n * USE topology, all anchored on the address:\n *\n * node the address: its node labels, its label words and `cex_role`;\n * swept its `SWEPT` links: each hot wallet it swept into, with the sweep\n * count, the USD sum, the paths and the first and last sweep;\n * paid_by how many addresses paid it, and how many of them are exchange\n * wallets;\n * paid how many addresses it paid, and how many of them are exchange\n * wallets;\n * swapped on how many DEX pools it swapped;\n * approved how many spenders it approved.\n *\n * The last four are the behaviour of the address, as counts: what a host needs\n * to say why an address does or does not look like a deposit, without a guess.\n * A behaviour read that fails leaves its counts null; the check still answers.\n *\n * `SWEPT` (layer `cex_sweeps`) is drawn only from an address the deposit rule\n * judged a deposit, and `cex_role` comes from the exchange label's subtype. The\n * graph judges, this tool only reads.\n *\n * The exchange model's own guess rides beside them on the node (graph sync\n * layer `inferred`): `inferred_exchange_role`, an `ml:exchange-roles:<model>:\n * <basis>` entry in `inferred_sources`, and the time it was written. It is\n * never a label and never a SWEPT link. A sourced mark always wins; an\n * address with only the guess is answered as inferred, with the model, and\n * `is_deposit` stays false. The exchange is named from the lookup\n * file (src/mcp/exchange-registry.ts): the hot wallet it swept into, else a\n * label word.\n */\n\nimport { ANSWER_HINT } from './answer-hint.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 { EXCHANGE_OPENING_RULE } from './exchange-tool.js'\nimport { CEX_ROLES } from './graph-schema.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\nimport { membersOf, refusalOf, type GraphAnswer, type Member } from './token-lookup.js'\n\nexport const AML_EXCHANGE_DEPOSIT_CHECK_TOOL = 'aml_exchange_deposit_check' as const\nexport const AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA =\n 'chain-insights.aml-exchange-deposit-check.v1' as const\nexport const AML_EXCHANGE_DEPOSIT_CHECK_TITLE = 'Exchange deposit check'\n/**\n * What the graph's deposit rule holds an address to, in the words every host\n * reads. The rule judges; a host that re-judges from payer counts or volume\n * invents a rule (\"a real deposit has many payers\") and gets the reason wrong.\n */\n/** How a deposit address behaves: the answer to \"what makes an address a deposit address\". Every result carries it as deposit_profile. */\nexport const EXCHANGE_DEPOSIT_BEHAVIOUR =\n \"A deposit address is one customer's: everything it sends goes to the wallets of one exchange (a sweep into a hot wallet), few outside addresses ever pay it, it never swaps on a DEX, and it is no token, pool, router or smart account.\"\n\nexport const EXCHANGE_DEPOSIT_PROFILE =\n `${EXCHANGE_DEPOSIT_BEHAVIOUR} ` +\n 'The graph judges that, never you: the verdict is is_deposit, cex_role and swept. Give behaviour and does_not_fit_deposit as the facts behind it, and never set a threshold of your own for payers, volume or sweeps. ' +\n 'With no deposit mark an address is not shown to be a deposit, whoever says it is one; with found false it has no activity on the network, and the claim is unproven there.'\n\n/** The one rule for an inferred answer, in the description every host reads and in the skill. */\nexport const EXCHANGE_INFERRED_RULE =\n \"An answer with inferred: true is the exchange model's prediction, not a listed source: report the address as inferred by the model, with its version (inferred_model), never as a confirmed exchange address.\"\n\nexport const AML_EXCHANGE_DEPOSIT_CHECK_DESCRIPTION =\n 'Checks one address: is it a deposit address of a centralized exchange (Binance, Bitget, Bybit, Coinbase, Gate, KuCoin, MEXC, OKX, ...), ' +\n 'of which exchange, and into which hot wallet was it swept, how many times, by which path and when. ' +\n 'It reads the SWEPT links of the address and its cex_role (deposit, hot_wallet, cold_wallet or withdrawal) on the graph, and its behaviour as counts ' +\n '(how many addresses paid it, how many it paid, how many of each are exchange wallets, the DEX pools it swapped on, the spenders it approved), anchored on the address: ' +\n 'six reads in one batch, billed as any read. Use it when a trail reaches an address that may be an exchange wallet, when the user asks where money entered an exchange, ' +\n 'or when someone says an address is an exchange deposit: a claim is never proof, the answer of this tool is. ' +\n `${EXCHANGE_DEPOSIT_PROFILE} ${EXCHANGE_INFERRED_RULE} ${EXCHANGE_OPENING_RULE}`\nexport const AML_EXCHANGE_DEPOSIT_CHECK_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_EXCHANGE_DEPOSIT_CHECK_ARGS = ['network', 'address'] as const\n\n/** The most hot wallets one deposit's read returns. */\nexport const SWEPT_LIMIT = 20\n\nexport type CexRole = (typeof CEX_ROLES)[number]\n\n/** The roles the exchange model infers. */\nexport const INFERRED_EXCHANGE_ROLES = ['deposit', 'hot_wallet'] as const\nexport type InferredExchangeRole = (typeof INFERRED_EXCHANGE_ROLES)[number]\n\n/**\n * Why the model inferred the role, from the suffix of its source entry:\n * `rule` a deposit behind a listed hot wallet, `rule-p` a deposit behind a hot\n * wallet the model inferred, `p-hub` a hot wallet the model inferred.\n */\nexport const INFERRED_BASIS = {\n rule: 'listed_hot_wallet',\n 'rule-p': 'predicted_hot_wallet',\n 'p-hub': 'predicted',\n} as const\nexport type InferredBasis = (typeof INFERRED_BASIS)[keyof typeof INFERRED_BASIS]\n\n/** The prefix of the exchange model's entries in `inferred_sources`. */\nexport const EXCHANGE_MODEL_SOURCE_PREFIX = 'ml:exchange-roles:'\n\nexport interface InferredExchangeMark {\n role: InferredExchangeRole\n model: string\n basis: InferredBasis\n /** ISO time the graph wrote the guess, or null when it carries none. */\n at: string | null\n}\n\nexport interface Sweep {\n hot_wallet: string\n /** The exchange the hot wallet is listed for, or null when the lookup lists it for none. */\n hot_wallet_exchange: string | null\n hot_wallet_role: string | null\n sweep_count: number | null\n amount_usd_sum: number | null\n paths: string[]\n first_seen: number | null\n first_seen_utc: string | null\n last_seen: number | null\n last_seen_utc: string | null\n}\n\n/** The most links one behaviour read counts: a count equal to it means \"this many or more\". */\nexport const BEHAVIOUR_COUNT_CAP = 5000\n\n/**\n * How the address behaves, as counts of its links. A null count is a read that\n * did not answer. The counts take every link, also a dust one: the graph's\n * deposit rule, which ignores dust, is the judge, and these are its evidence.\n */\nexport interface DepositBehaviour {\n /** Addresses that ever paid it. */\n payers: number | null\n /** Of those, exchange wallets (a hot wallet, or another deposit). */\n payers_exchange: number | null\n /** Addresses it ever paid. */\n receivers: number | null\n /** Of those, exchange wallets. */\n receivers_exchange: number | null\n /** DEX pools it swapped on. */\n dex_pools: number | null\n /** Spenders it approved. */\n approvals: number | null\n /** A count equal to this means \"this many or more\". */\n count_cap: typeof BEHAVIOUR_COUNT_CAP\n}\n\nexport interface AmlExchangeDepositCheckResult {\n schema: typeof AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA\n tool: typeof AML_EXCHANGE_DEPOSIT_CHECK_TOOL\n network: string\n address: string\n /** false when the graph holds no node for the address. */\n found: boolean\n /** true when the address carries cex_role deposit or has a SWEPT link. */\n is_deposit: boolean\n cex_role: CexRole | null\n /** The exchange id, from the hot wallet it swept into, else from its label words. */\n exchange: string | null\n exchange_display: string | null\n labels: string[]\n swept: Sweep[]\n /** The behaviour counts; null when the graph holds no node for the address. */\n behaviour: DepositBehaviour | null\n /** What the counts show that a deposit address does not do. Empty for a deposit, and when nothing shows. */\n does_not_fit_deposit: string[]\n /** How any deposit address behaves: the same text in every answer, for a host asked what makes one. */\n deposit_profile: string\n /** Set only when no sourced mark exists and the exchange model inferred a role. */\n inferred?: true\n inferred_role?: InferredExchangeRole\n /** The model version, from its `ml:exchange-roles:` source entry. */\n inferred_model?: string\n inferred_basis?: InferredBasis\n inferred_at?: string | null\n hint: string\n}\n\nexport interface ExchangeDepositCheckDependencies {\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 AmlExchangeDepositCheckToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nconst ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\nconst ADDRESS_READ = /^0x[0-9a-f]{40}$/\n\nfunction assertReadAddress(address: string): void {\n if (!ADDRESS_READ.test(address)) {\n throw new Error(\n `exchange deposit check: ${JSON.stringify(address)} is not a lowercase 0x address`\n )\n }\n}\n\n/** The node read: the address, its marks, its cex_role and the exchange model's inferred role. */\nexport function depositNodeQuery(address: string): string {\n assertReadAddress(address)\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"}) ` +\n 'RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.cex_role AS cex_role, ' +\n 'a.inferred_exchange_role AS inferred_exchange_role, a.inferred_sources AS inferred_sources, ' +\n 'a.inferred_exchange_role_updated_timestamp AS inferred_exchange_role_updated_timestamp LIMIT 1'\n )\n}\n\n/** The swept read: each hot wallet the address swept into. */\nexport function depositSweptQuery(address: string): string {\n assertReadAddress(address)\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"})-[s:SWEPT]->(h:Address) ` +\n 'RETURN h.address AS hot_wallet, h.labels AS hot_wallet_labels, h.cex_role AS hot_wallet_role, ' +\n 's.sweep_count AS sweep_count, s.amount_usd_sum AS amount_usd_sum, s.paths AS paths, ' +\n `s.first_seen_timestamp AS first_seen_timestamp, s.last_seen_timestamp AS last_seen_timestamp LIMIT ${SWEPT_LIMIT}`\n )\n}\n\n/** The behaviour reads: one count row each, over at most BEHAVIOUR_COUNT_CAP links. */\nexport function depositBehaviourQueries(\n address: string\n): Array<{ id: 'paid_by' | 'paid' | 'swapped' | 'approved'; query: string }> {\n assertReadAddress(address)\n const anchor = `(a:Address {address: \"${address}\"})`\n const exchange = 'sum(CASE WHEN b.is_exchange THEN 1 ELSE 0 END)'\n return [\n {\n id: 'paid_by',\n query:\n `USE topology MATCH ${anchor}<-[:FLOWED_TO]-(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n `RETURN count(b) AS payers, ${exchange} AS payers_exchange LIMIT 1`,\n },\n {\n id: 'paid',\n query:\n `USE topology MATCH ${anchor}-[:FLOWED_TO]->(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n `RETURN count(b) AS receivers, ${exchange} AS receivers_exchange LIMIT 1`,\n },\n {\n id: 'swapped',\n query:\n `USE topology MATCH ${anchor}-[:SWAPPED]->(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n 'RETURN count(b) AS dex_pools LIMIT 1',\n },\n {\n id: 'approved',\n query:\n `USE topology MATCH ${anchor}-[:APPROVED]->(b:Address) WITH b LIMIT ${BEHAVIOUR_COUNT_CAP} ` +\n 'RETURN count(b) AS approvals LIMIT 1',\n },\n ]\n}\n\n/** The one batch the tool sends: members `node`, `swept` and the four behaviour reads. */\nexport function depositCheckQueries(address: string): Array<{ id: string; query: string }> {\n return [\n { id: 'node', query: depositNodeQuery(address) },\n { id: 'swept', query: depositSweptQuery(address) },\n ...depositBehaviourQueries(address),\n ]\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\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 textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\n\nconst addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null\n\nconst utcOrNull = (ms: number | null): string | null => (isEpochMs(ms) ? utcText(ms) : null)\n\nfunction cexRoleOf(value: unknown): CexRole | null {\n const role = textOrNull(value)?.toLowerCase()\n return (CEX_ROLES as readonly string[]).includes(role ?? '') ? (role as CexRole) : null\n}\n\n/**\n * The exchange model's mark of a node row, or null. It needs both the role and\n * an `ml:exchange-roles:<model>:<basis>` source entry: a role with no entry of\n * the exchange model is no inferred mark. The model version may hold hyphens,\n * underscores and colons; the basis is the last part.\n */\nexport function inferredExchangeOf(\n row: Record<string, unknown> | undefined\n): InferredExchangeMark | null {\n const role = textOrNull(row?.inferred_exchange_role)?.toLowerCase()\n if (!(INFERRED_EXCHANGE_ROLES as readonly string[]).includes(role ?? '')) return null\n const marks: Array<{ model: string; basis: InferredBasis; suffix: string }> = []\n for (const source of strings(row?.inferred_sources)) {\n const entry = source.trim()\n if (!entry.startsWith(EXCHANGE_MODEL_SOURCE_PREFIX)) continue\n const rest = entry.slice(EXCHANGE_MODEL_SOURCE_PREFIX.length)\n const cut = rest.lastIndexOf(':')\n if (cut <= 0) continue\n const model = rest.slice(0, cut)\n const suffix = rest.slice(cut + 1)\n if (!Object.prototype.hasOwnProperty.call(INFERRED_BASIS, suffix)) continue\n marks.push({ model, basis: INFERRED_BASIS[suffix as keyof typeof INFERRED_BASIS], suffix })\n }\n // The entry that fits the role first: p-hub names a hot wallet, rule and rule-p a deposit.\n const fits = (suffix: string) => (role === 'hot_wallet') === (suffix === 'p-hub')\n const mark = marks.find((m) => fits(m.suffix)) ?? marks[0]\n if (!mark) return null\n const ms = numberOrNull(row?.inferred_exchange_role_updated_timestamp)\n return {\n role: role as InferredExchangeRole,\n model: mark.model,\n basis: mark.basis,\n at: isEpochMs(ms) ? new Date(ms).toISOString() : null,\n }\n}\n\nconst answered = (member: Member | undefined): boolean =>\n member?.ok === true && Array.isArray(member.results)\n\nconst rowsOf = (member: Member | undefined): Array<Record<string, unknown>> =>\n answered(member) ? (member!.results as unknown[]).filter(isRecord) : []\n\nfunction memberFailure(id: string, member: Member | undefined): string {\n if (!member) return `the ${id} read is missing from the batch answer`\n return typeof member.error === 'string' && member.error.trim() !== ''\n ? member.error\n : `the ${id} read did not answer`\n}\n\n/** The behaviour counts of the batch members; a member that did not answer leaves its counts null. */\nexport function behaviourFromMembers(members: Map<string, Member>): DepositBehaviour {\n const count = (id: string, column: string): number | null =>\n numberOrNull(rowsOf(members.get(id))[0]?.[column])\n return {\n payers: count('paid_by', 'payers'),\n payers_exchange: count('paid_by', 'payers_exchange'),\n receivers: count('paid', 'receivers'),\n receivers_exchange: count('paid', 'receivers_exchange'),\n dex_pools: count('swapped', 'dex_pools'),\n approvals: count('approved', 'approvals'),\n count_cap: BEHAVIOUR_COUNT_CAP,\n }\n}\n\n/** \"5000 or more\" at the cap, else the number. */\nfunction countText(count: number): string {\n return count >= BEHAVIOUR_COUNT_CAP ? `${BEHAVIOUR_COUNT_CAP} or more` : String(count)\n}\n\nconst plural = (count: number, one: string, many: string): string => (count === 1 ? one : many)\n\n/**\n * What the counts show that a deposit address does not do. Only what needs no\n * threshold: a swap, and a payment to an address that is no exchange wallet.\n * How many payers are \"few\" is the graph rule's to say, never this tool's.\n */\nexport function doesNotFitDeposit(behaviour: DepositBehaviour): string[] {\n const facts: string[] = []\n if (behaviour.dex_pools !== null && behaviour.dex_pools > 0) {\n facts.push(\n `it swapped on ${countText(behaviour.dex_pools)} DEX ${plural(behaviour.dex_pools, 'pool', 'pools')}`\n )\n }\n if (behaviour.receivers !== null && behaviour.receivers_exchange !== null) {\n const outside = behaviour.receivers - behaviour.receivers_exchange\n if (outside > 0) {\n // A capped receiver count makes the difference a floor too.\n const atCap = behaviour.receivers >= BEHAVIOUR_COUNT_CAP ? ' or more' : ''\n facts.push(\n `it paid ${outside}${atCap} ${plural(outside, 'address that is', 'addresses that are')} no exchange wallet`\n )\n }\n }\n return facts\n}\n\n/** The counts as one sentence, the read counts only. */\nexport function behaviourText(behaviour: DepositBehaviour): string {\n const parts: string[] = []\n if (behaviour.payers !== null) {\n parts.push(\n `${countText(behaviour.payers)} ${plural(behaviour.payers, 'address', 'addresses')} paid it` +\n (behaviour.payers_exchange !== null\n ? ` (${countText(behaviour.payers_exchange)} of them exchange wallets)`\n : '')\n )\n }\n if (behaviour.receivers !== null) {\n parts.push(\n `it paid ${countText(behaviour.receivers)} ${plural(behaviour.receivers, 'address', 'addresses')}` +\n (behaviour.receivers_exchange !== null\n ? ` (${countText(behaviour.receivers_exchange)} of them exchange wallets)`\n : '')\n )\n }\n if (behaviour.dex_pools !== null) {\n parts.push(\n `it swapped on ${countText(behaviour.dex_pools)} DEX ${plural(behaviour.dex_pools, 'pool', 'pools')}`\n )\n }\n if (behaviour.approvals !== null) {\n parts.push(\n `it approved ${countText(behaviour.approvals)} ${plural(behaviour.approvals, 'spender', 'spenders')}`\n )\n }\n return parts.join(', ')\n}\n\n/** The check built from the batch members and the lookup rows, or why it cannot be. */\nexport function depositCheckFromMembers(\n network: string,\n address: string,\n members: Map<string, Member>,\n rows: ExchangeEntry[]\n): { result: AmlExchangeDepositCheckResult } | { failure: string } {\n const node = members.get('node')\n const swept = members.get('swept')\n if (!answered(node)) return { failure: memberFailure('node', node) }\n if (!answered(swept)) return { failure: memberFailure('swept', swept) }\n\n const nodeRow = rowsOf(node)[0]\n const labels = strings(nodeRow?.labels)\n const sweeps: Sweep[] = []\n let exchange: ExchangeEntry | null = null\n for (const row of rowsOf(swept)) {\n const hot = addressOrNull(row.hot_wallet)\n if (!hot) continue\n const listed =\n exchangeOfWallet(hot, rows)?.entry ?? exchangeOfLabels(strings(row.hot_wallet_labels), rows)\n exchange ??= listed\n const first = numberOrNull(row.first_seen_timestamp)\n const last = numberOrNull(row.last_seen_timestamp)\n sweeps.push({\n hot_wallet: hot,\n hot_wallet_exchange: listed?.exchange ?? null,\n hot_wallet_role: textOrNull(row.hot_wallet_role),\n sweep_count: numberOrNull(row.sweep_count),\n amount_usd_sum: numberOrNull(row.amount_usd_sum),\n paths: strings(row.paths),\n first_seen: first,\n first_seen_utc: utcOrNull(first),\n last_seen: last,\n last_seen_utc: utcOrNull(last),\n })\n }\n sweeps.sort((a, b) => (b.sweep_count ?? 0) - (a.sweep_count ?? 0))\n exchange ??= exchangeOfLabels(labels, rows) ?? exchangeOfWallet(address, rows)?.entry ?? null\n const role = cexRoleOf(nodeRow?.cex_role)\n const found = nodeRow !== undefined || sweeps.length > 0\n const isDeposit = role === 'deposit' || sweeps.length > 0\n const behaviour = behaviourFromMembers(members)\n // A sourced mark always wins: the guess is read only for an address with none.\n const guess = role === null && sweeps.length === 0 ? inferredExchangeOf(nodeRow) : null\n const result: Omit<AmlExchangeDepositCheckResult, 'hint'> = {\n schema: AML_EXCHANGE_DEPOSIT_CHECK_SCHEMA,\n tool: AML_EXCHANGE_DEPOSIT_CHECK_TOOL,\n network,\n address,\n found,\n is_deposit: isDeposit,\n cex_role: role ?? (sweeps.length > 0 ? ('deposit' as const) : null),\n exchange: exchange?.exchange ?? null,\n exchange_display: exchange?.display ?? null,\n labels,\n swept: sweeps,\n behaviour: found ? behaviour : null,\n does_not_fit_deposit: found && !isDeposit && !role ? doesNotFitDeposit(behaviour) : [],\n deposit_profile: EXCHANGE_DEPOSIT_BEHAVIOUR,\n ...(guess\n ? {\n inferred: true as const,\n inferred_role: guess.role,\n inferred_model: guess.model,\n inferred_basis: guess.basis,\n inferred_at: guess.at,\n }\n : {}),\n }\n return { result: { ...result, hint: `${hintFor(result)} ${PROFILE_HINT}` } }\n}\n\n/** Closes every hint: a host asked how a deposit address behaves answers from deposit_profile, not from its own idea of one. */\nconst PROFILE_HINT =\n 'Asked how a deposit address behaves, what makes an address one or what rules one out, answer with deposit_profile.'\n\n/** \" once\", \" 3 times\", or \"\" when the graph gave no count. */\nfunction timesText(count: number | null): string {\n if (count === null) return ''\n return count === 1 ? ' once' : ` ${count} times`\n}\n\nfunction hintFor(result: Omit<AmlExchangeDepositCheckResult, 'hint'>): string {\n const { address, network } = result\n const name = result.exchange_display ?? 'its exchange (name it from labels)'\n if (!result.found) {\n return (\n `${ANSWER_HINT} ${address} is not in the Chain Insights Graph of ${network}: no flow touches it. ` +\n 'Say so in one line, and check the network and the address with the user: name no other network yourself, and say nothing about what the check covers. ' +\n 'A claim that it is an exchange deposit address is unproven on this network: never repeat it as a fact.'\n )\n }\n if (result.is_deposit) {\n const top = result.swept[0]\n const into = top\n ? ` It swept${timesText(top.sweep_count)} into the hot wallet ${top.hot_wallet}` +\n (result.swept.length > 1\n ? `, and into ${result.swept.length - 1} more hot wallets (swept lists them)`\n : '') +\n '.'\n : ' The graph holds no SWEPT link of it yet: its sweeps are not drawn.'\n return (\n `${ANSWER_HINT} Say: \"${address} is a deposit address of ${name} on ${network}.\"${into} ` +\n 'This is where the money entered the exchange: the exchange can name the customer behind the deposit. ' +\n `${behaviourHint(result)}${EXCHANGE_OPENING_RULE}`\n )\n }\n if (result.inferred && result.inferred_role && result.inferred_model) {\n return inferredHint(result, result.inferred_role, result.inferred_model)\n }\n if (result.cex_role) {\n return (\n `${ANSWER_HINT} Say: \"${address} is a ${result.cex_role.replace('_', ' ')} of ${name} on ${network}, not a deposit address.\" ` +\n 'A trail that reaches it has entered the exchange: end the trail there.'\n )\n }\n const misfit =\n result.does_not_fit_deposit.length > 0\n ? `What a deposit address does not do, and this one did: ${result.does_not_fit_deposit.join('; ')}. `\n : 'Its counts alone rule nothing out; the missing mark does: the rule of the graph did not judge it a deposit. '\n return (\n `${ANSWER_HINT} ${address} carries no deposit mark: no SWEPT link and no cex_role. ` +\n 'Say that the graph shows no sweep of it into a listed exchange hot wallet. That is not proof the address belongs to no exchange; ' +\n `its labels and its links say what else it is. ${behaviourHint(result)}${misfit}` +\n 'Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.'\n )\n}\n\n/** Why the model holds its guess, in reader words. */\nconst INFERRED_BASIS_TEXT: Record<InferredBasis, string> = {\n listed_hot_wallet: 'The model placed it behind a listed exchange hot wallet.',\n predicted_hot_wallet: 'The model placed it behind a hot wallet the model itself inferred, which no listed source names either.',\n predicted: 'The model inferred it from how the address moves money.',\n}\n\n/** The hint of an address with no sourced mark and the exchange model's guess. */\nfunction inferredHint(\n result: Omit<AmlExchangeDepositCheckResult, 'hint'>,\n role: InferredExchangeRole,\n model: string\n): string {\n const { address, network } = result\n const what = role === 'deposit' ? 'an exchange deposit' : 'an exchange hot wallet'\n const basis = result.inferred_basis ? `${INFERRED_BASIS_TEXT[result.inferred_basis]} ` : ''\n const trail =\n role === 'deposit'\n ? 'The graph draws no SWEPT link for it, so no hot wallet is named: name none yourself. '\n : 'A trail that reaches it may have entered an exchange there: say so as inferred, and name no exchange the answer does not name. '\n return (\n `${ANSWER_HINT} Say: \"${address} is ${what}, inferred by model ${model}, on ${network}. ` +\n 'No listed source names it as an exchange address.\" ' +\n `${basis}${trail}` +\n 'Report it as inferred, never as a confirmed exchange address: is_deposit (false) and cex_role (null) are the sourced verdict, and the guess does not change them. ' +\n `${behaviourHint(result)}` +\n 'Give these facts as the reason and no other: set no threshold of your own for payers, volume or sweeps.'\n )\n}\n\n/** \"Its behaviour: ... . \" for a hint, or \"\" when no count was read. */\nfunction behaviourHint(result: Omit<AmlExchangeDepositCheckResult, 'hint'>): string {\n const text = result.behaviour ? behaviourText(result.behaviour) : ''\n return text === '' ? '' : `Its behaviour, as the graph counts it: ${text}. `\n}\n\nfunction errorResult(text: string): AmlExchangeDepositCheckToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlExchangeDepositCheckResult): AmlExchangeDepositCheckToolResult {\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_exchange_deposit_check, {network, address}. Every argument is checked before a read is sent. */\nexport async function handleAmlExchangeDepositCheck(\n args: unknown,\n deps: ExchangeDepositCheckDependencies\n): Promise<AmlExchangeDepositCheckToolResult> {\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 'An exchange name is not an address: call meta_exchange_lookup for its wallets.'\n )\n }\n const address = raw.toLowerCase()\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No exchange deposit read was sent: ${unavailable} There is no answer yet, which is not \"no deposit\": try again later.`\n )\n }\n\n let rows: ExchangeEntry[] = []\n try {\n rows = (await deps.loadExchangeRegistry(network)).document.rows\n } catch {\n // The lookup only names the exchange; the graph read still answers.\n }\n\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries: depositCheckQueries(address) })\n } catch (err) {\n return errorResult(\n `The exchange deposit read failed: ${deps.describeFailure(err)} This is not \"no deposit\": send the same check again once.`\n )\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 errorResult(`The exchange deposit read failed: ${text} This is not \"no deposit\".`)\n }\n const check = depositCheckFromMembers(network, address, members, rows)\n if ('failure' in check) {\n return errorResult(\n `The exchange deposit read failed: ${check.failure} This is not \"no deposit\": send the same check again once.`\n )\n }\n return textResult(check.result)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAa,kCAAkC;AAC/C,MAAa,oCACX;AACF,MAAa,mCAAmC;;;;;;;AAOhD,MAAa,6BACX;AAWF,MAAa,yCACX,4zBAMG,GAfA,2BAA2B,kYAeF,iNAA6B;AAC3D,MAAa,yCAAyC;CACpD,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;;AAIA,MAAa,cAAc;;AAK3B,MAAa,0BAA0B,CAAC,WAAW,YAAY;;;;;;AAQ/D,MAAa,iBAAiB;CAC5B,MAAM;CACN,UAAU;CACV,SAAS;AACX;;AAIA,MAAa,+BAA+B;;AAyB5C,MAAa,sBAAsB;AAuEnC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,SAAS,kBAAkB,SAAuB;CAChD,IAAI,CAAC,aAAa,KAAK,OAAO,GAC5B,MAAM,IAAI,MACR,2BAA2B,KAAK,UAAU,OAAO,EAAE,+BACrD;AAEJ;;AAGA,SAAgB,iBAAiB,SAAyB;CACxD,kBAAkB,OAAO;CACzB,OACE,4CAA4C,QAAQ;AAKxD;;AAGA,SAAg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