chain-insights 0.81.1 → 0.82.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.
- package/dist/cli.cjs +2 -2
- package/dist/cli.mjs +2 -2
- package/dist/{dex-tool-DW_hT1Z1.mjs → dex-tool-25510SNo.mjs} +64 -37
- package/dist/dex-tool-25510SNo.mjs.map +1 -0
- package/dist/{dex-tool-C6eLeZI2.cjs → dex-tool-BDERiT5t.cjs} +63 -36
- package/dist/mcp-proxy.cjs +2 -2
- package/dist/mcp-proxy.mjs +2 -2
- package/dist/mcp-proxy.mjs.map +1 -1
- package/docs/graph-tools.md +7 -0
- package/package.json +1 -1
- package/skills/chain-insights-cypher/SKILL.md +2 -0
- package/skills/chain-insights-dex/SKILL.md +8 -0
- package/skills/chain-insights-dex/reference.md +15 -2
- package/skills/chain-insights-virtuals/SKILL.md +4 -3
- package/skills/chain-insights-virtuals/reference.md +38 -0
- package/dist/dex-tool-DW_hT1Z1.mjs.map +0 -1
package/dist/cli.cjs
CHANGED
|
@@ -647,7 +647,7 @@ program.command("mcp").description("Low-level access to the Chain Insights MCP e
|
|
|
647
647
|
}
|
|
648
648
|
}
|
|
649
649
|
console.log(formatToolsTable(visibleRemoteTools(tools)));
|
|
650
|
-
const { META_DEX_LOOKUP_DESCRIPTION, META_DEX_LOOKUP_TITLE, META_DEX_LOOKUP_TOOL } = await Promise.resolve().then(() => require("./dex-tool-
|
|
650
|
+
const { META_DEX_LOOKUP_DESCRIPTION, META_DEX_LOOKUP_TITLE, META_DEX_LOOKUP_TOOL } = await Promise.resolve().then(() => require("./dex-tool-BDERiT5t.cjs")).then((n) => n.dex_tool_exports);
|
|
651
651
|
const { META_TOKEN_LOOKUP_DESCRIPTION, META_TOKEN_LOOKUP_TITLE, META_TOKEN_LOOKUP_TOOL } = await Promise.resolve().then(() => require("./token-lookup-D-5GBEwF.cjs")).then((n) => n.token_lookup_exports);
|
|
652
652
|
const { AML_DEPLOYER_SCREEN_DESCRIPTION, AML_DEPLOYER_SCREEN_TITLE, AML_DEPLOYER_SCREEN_TOOL } = await Promise.resolve().then(() => require("./deployer-screen-BomgSBcq.cjs")).then((n) => n.deployer_screen_exports);
|
|
653
653
|
console.log("");
|
|
@@ -693,7 +693,7 @@ program.command("mcp").description("Low-level access to the Chain Insights MCP e
|
|
|
693
693
|
return;
|
|
694
694
|
}
|
|
695
695
|
if (tool === "meta_dex_lookup") {
|
|
696
|
-
const { handleMetaDexLookup } = await Promise.resolve().then(() => require("./dex-tool-
|
|
696
|
+
const { handleMetaDexLookup } = await Promise.resolve().then(() => require("./dex-tool-BDERiT5t.cjs")).then((n) => n.dex_tool_exports);
|
|
697
697
|
const { loadRegistry } = await Promise.resolve().then(() => require("./dex-registry-BhGJUG9_.cjs")).then((n) => n.dex_registry_exports);
|
|
698
698
|
const { metaDexLookupArgs } = await Promise.resolve().then(() => require("./call-args-DXEmPeE-.cjs"));
|
|
699
699
|
const result = await withGraphMcpClient("chain-insights-cli-dex-lookup", (client) => handleMetaDexLookup(metaDexLookupArgs(args), {
|
package/dist/cli.mjs
CHANGED
|
@@ -645,7 +645,7 @@ program.command("mcp").description("Low-level access to the Chain Insights MCP e
|
|
|
645
645
|
}
|
|
646
646
|
}
|
|
647
647
|
console.log(formatToolsTable(visibleRemoteTools(tools)));
|
|
648
|
-
const { META_DEX_LOOKUP_DESCRIPTION, META_DEX_LOOKUP_TITLE, META_DEX_LOOKUP_TOOL } = await import("./dex-tool-
|
|
648
|
+
const { META_DEX_LOOKUP_DESCRIPTION, META_DEX_LOOKUP_TITLE, META_DEX_LOOKUP_TOOL } = await import("./dex-tool-25510SNo.mjs").then((n) => n.a);
|
|
649
649
|
const { META_TOKEN_LOOKUP_DESCRIPTION, META_TOKEN_LOOKUP_TITLE, META_TOKEN_LOOKUP_TOOL } = await import("./token-lookup-QpIv77P2.mjs").then((n) => n.l);
|
|
650
650
|
const { AML_DEPLOYER_SCREEN_DESCRIPTION, AML_DEPLOYER_SCREEN_TITLE, AML_DEPLOYER_SCREEN_TOOL } = await import("./deployer-screen-ByQBZEsg.mjs").then((n) => n.a);
|
|
651
651
|
console.log("");
|
|
@@ -691,7 +691,7 @@ program.command("mcp").description("Low-level access to the Chain Insights MCP e
|
|
|
691
691
|
return;
|
|
692
692
|
}
|
|
693
693
|
if (tool === "meta_dex_lookup") {
|
|
694
|
-
const { handleMetaDexLookup } = await import("./dex-tool-
|
|
694
|
+
const { handleMetaDexLookup } = await import("./dex-tool-25510SNo.mjs").then((n) => n.a);
|
|
695
695
|
const { loadRegistry } = await import("./dex-registry-BY67f4Ul.mjs").then((n) => n.s);
|
|
696
696
|
const { metaDexLookupArgs } = await import("./call-args-CBqbYfOE.mjs");
|
|
697
697
|
const result = await withGraphMcpClient("chain-insights-cli-dex-lookup", (client) => handleMetaDexLookup(metaDexLookupArgs(args), {
|
|
@@ -14,8 +14,14 @@ const SELLER = "<seller address>";
|
|
|
14
14
|
const DAY = "<YYYY-MM-DD>";
|
|
15
15
|
const TX = "<tx_id>";
|
|
16
16
|
const TOKEN = "<launched token address>";
|
|
17
|
-
/**
|
|
18
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The pools one factory deployed, ranked (R3). On the graph of before, by the
|
|
19
|
+
* pool's lifetime volume. On a lane with the levels a pool has no address
|
|
20
|
+
* totals (its transactions are not on FLOWED_TO), so the pools are ranked by
|
|
21
|
+
* the USD sold into each on its SWAPPED links (R3L).
|
|
22
|
+
*/
|
|
23
|
+
function poolsByFactoryQuery(factory, limit = 10, shape = "route") {
|
|
24
|
+
if (shape === "levels") return `USE topology MATCH (f:Address {address: "${factory}"})-[:DEPLOYED_CONTRACT]->(p:Pool) MATCH (t:Address)-[s:SWAPPED]->(p) 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 ORDER BY swapped_usd DESC LIMIT ${limit}`;
|
|
19
25
|
return `USE topology MATCH (f:Address {address: "${factory}"})-[:DEPLOYED_CONTRACT]->(p:Pool) WHERE p.total_volume_usd IS NOT NULL 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 ORDER BY p.total_volume_usd DESC LIMIT ${limit}`;
|
|
20
26
|
}
|
|
21
27
|
/** The senders of one pool on FLOWED_TO, by lifetime volume (R4, G1). */
|
|
@@ -62,12 +68,18 @@ const dayStep = {
|
|
|
62
68
|
function startPool(entry, topPool) {
|
|
63
69
|
return topPool ?? entry.example_pool ?? null;
|
|
64
70
|
}
|
|
65
|
-
function poolsStep(entry) {
|
|
71
|
+
function poolsStep(entry, shape = "route") {
|
|
66
72
|
const factory = entry.factories.find((address) => entry.roles[address] === "factory");
|
|
67
73
|
if (!factory) return null;
|
|
74
|
+
const members = entry.factories.filter((a) => entry.roles[a] === "factory").join(", ");
|
|
75
|
+
if (shape === "levels") return {
|
|
76
|
+
step: "Pools of the exchange, by factory",
|
|
77
|
+
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}.`,
|
|
78
|
+
query: poolsByFactoryQuery(factory, 10, "levels")
|
|
79
|
+
};
|
|
68
80
|
return {
|
|
69
81
|
step: "Pools of the exchange, by factory",
|
|
70
|
-
why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${
|
|
82
|
+
why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${members}.`,
|
|
71
83
|
query: poolsByFactoryQuery(factory)
|
|
72
84
|
};
|
|
73
85
|
}
|
|
@@ -99,7 +111,7 @@ function levelsRecipeFor(entry, topPool) {
|
|
|
99
111
|
const router = entry.routers[0];
|
|
100
112
|
if (pool) steps.push(poolTraders(pool));
|
|
101
113
|
else {
|
|
102
|
-
const pools = poolsStep(entry);
|
|
114
|
+
const pools = poolsStep(entry, "levels");
|
|
103
115
|
if (pools) steps.push(pools);
|
|
104
116
|
}
|
|
105
117
|
steps.push(routesStep);
|
|
@@ -156,7 +168,7 @@ function levelsRecipeFor(entry, topPool) {
|
|
|
156
168
|
case "plain":
|
|
157
169
|
if (pool) steps.push(poolTraders(pool));
|
|
158
170
|
else {
|
|
159
|
-
const pools = poolsStep(entry);
|
|
171
|
+
const pools = poolsStep(entry, "levels");
|
|
160
172
|
if (pools) steps.push(pools);
|
|
161
173
|
}
|
|
162
174
|
steps.push(routesStep);
|
|
@@ -289,6 +301,8 @@ function routeRecipeFor(entry, topPool) {
|
|
|
289
301
|
* meta_network_capabilities): on a lane whose money family lists ROUTED_TO the
|
|
290
302
|
* reads name SWAPPED from a trader to the pool and ROUTED_TO for the route; on
|
|
291
303
|
* any other lane they are the reads of chain-insights 0.81.0, byte for byte.
|
|
304
|
+
* The pool read follows the shape too: on a lane with the levels a pool has no
|
|
305
|
+
* address totals, so its pools are ranked by the USD sold into each on SWAPPED.
|
|
292
306
|
*/
|
|
293
307
|
var dex_tool_exports = /* @__PURE__ */ __exportAll({
|
|
294
308
|
META_DEX_LOOKUP_DESCRIPTION: () => META_DEX_LOOKUP_DESCRIPTION,
|
|
@@ -299,7 +313,7 @@ var dex_tool_exports = /* @__PURE__ */ __exportAll({
|
|
|
299
313
|
const META_DEX_LOOKUP_TOOL = "meta_dex_lookup";
|
|
300
314
|
const META_DEX_LOOKUP_SCHEMA = "chain-insights.meta-dex-lookup.v1";
|
|
301
315
|
const META_DEX_LOOKUP_TITLE = "Exchange by name or address";
|
|
302
|
-
const META_DEX_LOOKUP_DESCRIPTION = `Call this first when a question names a decentralized exchange, a launchpad or a vault (Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's factories, routers or pool manager, its biggest pools, and the first reads to send, with every address in full. A misspelling within two letters is taken and named in took_for. When matched is null the name is not covered: say so, list covered, and send no graph query for the name. Never ask the user for a pool, factory or router address. When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, any case, with no name): the answer is the exchange whose factory, router or manager it is, and took_for names the role it holds. When matched is null no exchange row holds the address: 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. ${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.`;
|
|
316
|
+
const META_DEX_LOOKUP_DESCRIPTION = `Call this first when a question names a decentralized exchange, a launchpad or a vault (Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's factories, routers or pool manager, its biggest pools, and the first reads to send, with every address in full. A misspelling within two letters is taken and named in took_for. When matched is null the name is not covered: say so, list covered, and send no graph query for the name. Never ask the user for a pool, factory or router address. When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, any case, with no name): the answer is the exchange whose factory, router or manager it is, and took_for names the role it holds. When matched is null no exchange row holds the address: 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. ${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. 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.`;
|
|
303
317
|
const META_DEX_LOOKUP_ANNOTATIONS = {
|
|
304
318
|
readOnlyHint: true,
|
|
305
319
|
idempotentHint: true,
|
|
@@ -349,7 +363,7 @@ function contractListQuery(addresses) {
|
|
|
349
363
|
return `USE topology MATCH (a:Address) WHERE a.address IN [${addresses.map((a) => `"${a}"`).join(", ")}] RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT ${addresses.length}`;
|
|
350
364
|
}
|
|
351
365
|
/** The anchored reads of one exchange: Head, each contract, and the pools of each factory. */
|
|
352
|
-
function lookupQueries(entry, pools) {
|
|
366
|
+
function lookupQueries(entry, pools, shape = "route") {
|
|
353
367
|
const contracts = Object.keys(entry.roles);
|
|
354
368
|
const queries = [{
|
|
355
369
|
id: "head",
|
|
@@ -365,7 +379,7 @@ function lookupQueries(entry, pools) {
|
|
|
365
379
|
});
|
|
366
380
|
if (pools) for (const factory of entry.factories.filter((address) => entry.roles[address] === "factory")) queries.push({
|
|
367
381
|
id: `pools:${factory}`,
|
|
368
|
-
query: poolsByFactoryQuery(factory, POOLS_LIMIT)
|
|
382
|
+
query: poolsByFactoryQuery(factory, POOLS_LIMIT, shape)
|
|
369
383
|
});
|
|
370
384
|
return queries;
|
|
371
385
|
}
|
|
@@ -381,7 +395,35 @@ function confirmation(row) {
|
|
|
381
395
|
};
|
|
382
396
|
return { confirmed: false };
|
|
383
397
|
}
|
|
384
|
-
|
|
398
|
+
/** The pools of the batch, merged over the factories and ranked by the shape's number. */
|
|
399
|
+
function readPools(members, shape) {
|
|
400
|
+
const byAddress = /* @__PURE__ */ new Map();
|
|
401
|
+
for (const [id, member] of members) {
|
|
402
|
+
if (!id.startsWith("pools:")) continue;
|
|
403
|
+
for (const row of rowsOf(member)) {
|
|
404
|
+
const address = typeof row.to_address === "string" ? row.to_address : null;
|
|
405
|
+
const rank = numberOrNull(shape === "levels" ? row.swapped_usd : row.total_volume_usd);
|
|
406
|
+
if (!address || rank === null || byAddress.has(address)) continue;
|
|
407
|
+
const labels = stringList(row.to_labels);
|
|
408
|
+
byAddress.set(address, {
|
|
409
|
+
rank,
|
|
410
|
+
row: shape === "levels" ? {
|
|
411
|
+
address,
|
|
412
|
+
labels,
|
|
413
|
+
swapped_usd: rank,
|
|
414
|
+
swap_count: numberOrNull(row.swap_count) ?? 0
|
|
415
|
+
} : {
|
|
416
|
+
address,
|
|
417
|
+
labels,
|
|
418
|
+
total_volume_usd: rank,
|
|
419
|
+
tx_total_count: numberOrNull(row.tx_total_count) ?? 0
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return [...byAddress.values()].sort((a, b) => b.rank - a.rank).slice(0, POOLS_LIMIT).map(({ row }) => row);
|
|
425
|
+
}
|
|
426
|
+
function readMatch(entry, members, read, shape) {
|
|
385
427
|
const notes = [];
|
|
386
428
|
const contracts = /* @__PURE__ */ new Map();
|
|
387
429
|
const listed = new Map(rowsOf(members.get("contracts")).map((row) => [String(row.address), row]));
|
|
@@ -393,22 +435,7 @@ function readMatch(entry, members, read) {
|
|
|
393
435
|
...confirmation(row)
|
|
394
436
|
});
|
|
395
437
|
}
|
|
396
|
-
const
|
|
397
|
-
for (const [id, member] of members) {
|
|
398
|
-
if (!id.startsWith("pools:")) continue;
|
|
399
|
-
for (const row of rowsOf(member)) {
|
|
400
|
-
const address = typeof row.to_address === "string" ? row.to_address : null;
|
|
401
|
-
const volume = numberOrNull(row.total_volume_usd);
|
|
402
|
-
if (!address || volume === null || byAddress.has(address)) continue;
|
|
403
|
-
byAddress.set(address, {
|
|
404
|
-
address,
|
|
405
|
-
labels: stringList(row.to_labels),
|
|
406
|
-
total_volume_usd: volume,
|
|
407
|
-
tx_total_count: numberOrNull(row.tx_total_count) ?? 0
|
|
408
|
-
});
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
const pools = [...byAddress.values()].sort((a, b) => b.total_volume_usd - a.total_volume_usd).slice(0, POOLS_LIMIT);
|
|
438
|
+
const pools = readPools(members, shape);
|
|
412
439
|
const head = rowsOf(members.get("head"))[0];
|
|
413
440
|
const families = head ? {
|
|
414
441
|
behind_money: numberOrNull(column(head, "behind_money", "h")),
|
|
@@ -427,7 +454,7 @@ function readMatch(entry, members, read) {
|
|
|
427
454
|
}
|
|
428
455
|
const ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/;
|
|
429
456
|
/** The hint's last rule on a lane with the levels; the graph of before keeps its 0.81.0 text. */
|
|
430
|
-
const LEVELS_HINT = `${LEVEL_RULE} 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.`;
|
|
457
|
+
const LEVELS_HINT = `${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. 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.`;
|
|
431
458
|
const ROUTE_HINT = "Read families before a SWAPPED search: it is sent when behind_dex is at most 100000. Never ask the user for an address.";
|
|
432
459
|
function hintFor(result, name, address = null) {
|
|
433
460
|
const closing = result.swap_links === "levels" ? LEVELS_HINT : ROUTE_HINT;
|
|
@@ -536,10 +563,16 @@ async function handleMetaDexLookup(args, deps) {
|
|
|
536
563
|
});
|
|
537
564
|
}
|
|
538
565
|
const entry = match.matched;
|
|
539
|
-
const
|
|
566
|
+
const unavailable = await deps.unavailable?.();
|
|
567
|
+
let shape = "route";
|
|
568
|
+
if (!unavailable && deps.linkShape) try {
|
|
569
|
+
shape = await deps.linkShape(network);
|
|
570
|
+
} catch {
|
|
571
|
+
shape = "route";
|
|
572
|
+
}
|
|
573
|
+
const queries = lookupQueries(entry, pools, shape);
|
|
540
574
|
let members = /* @__PURE__ */ new Map();
|
|
541
575
|
const notes = [];
|
|
542
|
-
const unavailable = await deps.unavailable?.();
|
|
543
576
|
if (unavailable) notes.push(`No graph read was sent: ${unavailable} The contracts are the reviewed registry rows, not yet confirmed on the graph.`);
|
|
544
577
|
else try {
|
|
545
578
|
const answer = await deps.graphQueryBatch({
|
|
@@ -554,13 +587,7 @@ async function handleMetaDexLookup(args, deps) {
|
|
|
554
587
|
} catch (err) {
|
|
555
588
|
notes.push(`The graph reads failed: ${deps.describeFailure(err)}`);
|
|
556
589
|
}
|
|
557
|
-
|
|
558
|
-
if (!unavailable && deps.linkShape) try {
|
|
559
|
-
shape = await deps.linkShape(network);
|
|
560
|
-
} catch {
|
|
561
|
-
shape = "route";
|
|
562
|
-
}
|
|
563
|
-
const read = readMatch(entry, members, members.size > 0);
|
|
590
|
+
const read = readMatch(entry, members, members.size > 0, shape);
|
|
564
591
|
notes.push(...read.notes);
|
|
565
592
|
const contractsOf = (role) => [...read.contracts.values()].filter((contract) => contract.role === role);
|
|
566
593
|
const topPool = read.pools[0]?.address ?? null;
|
|
@@ -592,4 +619,4 @@ async function handleMetaDexLookup(args, deps) {
|
|
|
592
619
|
}
|
|
593
620
|
export { dex_tool_exports as a, META_DEX_LOOKUP_TOOL as i, META_DEX_LOOKUP_DESCRIPTION as n, handleMetaDexLookup as o, META_DEX_LOOKUP_TITLE as r, META_DEX_LOOKUP_ANNOTATIONS as t };
|
|
594
621
|
|
|
595
|
-
//# sourceMappingURL=dex-tool-
|
|
622
|
+
//# sourceMappingURL=dex-tool-25510SNo.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dex-tool-25510SNo.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,OACE,yCAAyC,OAAO,sDAAsD,IAAI,mBAAmB,GAAG;AAGpI;;AAGA,SAAS,mBAAmB,MAAsB;CAChD,OACE,sEAAsE,KAAK;AAI/E;;AAGA,SAAS,oBAA4B;CACn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AAG;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"}
|
|
@@ -14,8 +14,14 @@ const SELLER = "<seller address>";
|
|
|
14
14
|
const DAY = "<YYYY-MM-DD>";
|
|
15
15
|
const TX = "<tx_id>";
|
|
16
16
|
const TOKEN = "<launched token address>";
|
|
17
|
-
/**
|
|
18
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The pools one factory deployed, ranked (R3). On the graph of before, by the
|
|
19
|
+
* pool's lifetime volume. On a lane with the levels a pool has no address
|
|
20
|
+
* totals (its transactions are not on FLOWED_TO), so the pools are ranked by
|
|
21
|
+
* the USD sold into each on its SWAPPED links (R3L).
|
|
22
|
+
*/
|
|
23
|
+
function poolsByFactoryQuery(factory, limit = 10, shape = "route") {
|
|
24
|
+
if (shape === "levels") return `USE topology MATCH (f:Address {address: "${factory}"})-[:DEPLOYED_CONTRACT]->(p:Pool) MATCH (t:Address)-[s:SWAPPED]->(p) 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 ORDER BY swapped_usd DESC LIMIT ${limit}`;
|
|
19
25
|
return `USE topology MATCH (f:Address {address: "${factory}"})-[:DEPLOYED_CONTRACT]->(p:Pool) WHERE p.total_volume_usd IS NOT NULL 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 ORDER BY p.total_volume_usd DESC LIMIT ${limit}`;
|
|
20
26
|
}
|
|
21
27
|
/** The senders of one pool on FLOWED_TO, by lifetime volume (R4, G1). */
|
|
@@ -62,12 +68,18 @@ const dayStep = {
|
|
|
62
68
|
function startPool(entry, topPool) {
|
|
63
69
|
return topPool ?? entry.example_pool ?? null;
|
|
64
70
|
}
|
|
65
|
-
function poolsStep(entry) {
|
|
71
|
+
function poolsStep(entry, shape = "route") {
|
|
66
72
|
const factory = entry.factories.find((address) => entry.roles[address] === "factory");
|
|
67
73
|
if (!factory) return null;
|
|
74
|
+
const members = entry.factories.filter((a) => entry.roles[a] === "factory").join(", ");
|
|
75
|
+
if (shape === "levels") return {
|
|
76
|
+
step: "Pools of the exchange, by factory",
|
|
77
|
+
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}.`,
|
|
78
|
+
query: poolsByFactoryQuery(factory, 10, "levels")
|
|
79
|
+
};
|
|
68
80
|
return {
|
|
69
81
|
step: "Pools of the exchange, by factory",
|
|
70
|
-
why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${
|
|
82
|
+
why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${members}.`,
|
|
71
83
|
query: poolsByFactoryQuery(factory)
|
|
72
84
|
};
|
|
73
85
|
}
|
|
@@ -99,7 +111,7 @@ function levelsRecipeFor(entry, topPool) {
|
|
|
99
111
|
const router = entry.routers[0];
|
|
100
112
|
if (pool) steps.push(poolTraders(pool));
|
|
101
113
|
else {
|
|
102
|
-
const pools = poolsStep(entry);
|
|
114
|
+
const pools = poolsStep(entry, "levels");
|
|
103
115
|
if (pools) steps.push(pools);
|
|
104
116
|
}
|
|
105
117
|
steps.push(routesStep);
|
|
@@ -156,7 +168,7 @@ function levelsRecipeFor(entry, topPool) {
|
|
|
156
168
|
case "plain":
|
|
157
169
|
if (pool) steps.push(poolTraders(pool));
|
|
158
170
|
else {
|
|
159
|
-
const pools = poolsStep(entry);
|
|
171
|
+
const pools = poolsStep(entry, "levels");
|
|
160
172
|
if (pools) steps.push(pools);
|
|
161
173
|
}
|
|
162
174
|
steps.push(routesStep);
|
|
@@ -289,6 +301,8 @@ function routeRecipeFor(entry, topPool) {
|
|
|
289
301
|
* meta_network_capabilities): on a lane whose money family lists ROUTED_TO the
|
|
290
302
|
* reads name SWAPPED from a trader to the pool and ROUTED_TO for the route; on
|
|
291
303
|
* any other lane they are the reads of chain-insights 0.81.0, byte for byte.
|
|
304
|
+
* The pool read follows the shape too: on a lane with the levels a pool has no
|
|
305
|
+
* address totals, so its pools are ranked by the USD sold into each on SWAPPED.
|
|
292
306
|
*/
|
|
293
307
|
var dex_tool_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
294
308
|
META_DEX_LOOKUP_DESCRIPTION: () => META_DEX_LOOKUP_DESCRIPTION,
|
|
@@ -299,7 +313,7 @@ var dex_tool_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
|
299
313
|
const META_DEX_LOOKUP_TOOL = "meta_dex_lookup";
|
|
300
314
|
const META_DEX_LOOKUP_SCHEMA = "chain-insights.meta-dex-lookup.v1";
|
|
301
315
|
const META_DEX_LOOKUP_TITLE = "Exchange by name or address";
|
|
302
|
-
const META_DEX_LOOKUP_DESCRIPTION = `Call this first when a question names a decentralized exchange, a launchpad or a vault (Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's factories, routers or pool manager, its biggest pools, and the first reads to send, with every address in full. A misspelling within two letters is taken and named in took_for. When matched is null the name is not covered: say so, list covered, and send no graph query for the name. Never ask the user for a pool, factory or router address. When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, any case, with no name): the answer is the exchange whose factory, router or manager it is, and took_for names the role it holds. When matched is null no exchange row holds the address: 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. ${require_layer_routing.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.`;
|
|
316
|
+
const META_DEX_LOOKUP_DESCRIPTION = `Call this first when a question names a decentralized exchange, a launchpad or a vault (Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's factories, routers or pool manager, its biggest pools, and the first reads to send, with every address in full. A misspelling within two letters is taken and named in took_for. When matched is null the name is not covered: say so, list covered, and send no graph query for the name. Never ask the user for a pool, factory or router address. When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, any case, with no name): the answer is the exchange whose factory, router or manager it is, and took_for names the role it holds. When matched is null no exchange row holds the address: 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. ${require_layer_routing.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. 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.`;
|
|
303
317
|
const META_DEX_LOOKUP_ANNOTATIONS = {
|
|
304
318
|
readOnlyHint: true,
|
|
305
319
|
idempotentHint: true,
|
|
@@ -349,7 +363,7 @@ function contractListQuery(addresses) {
|
|
|
349
363
|
return `USE topology MATCH (a:Address) WHERE a.address IN [${addresses.map((a) => `"${a}"`).join(", ")}] RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT ${addresses.length}`;
|
|
350
364
|
}
|
|
351
365
|
/** The anchored reads of one exchange: Head, each contract, and the pools of each factory. */
|
|
352
|
-
function lookupQueries(entry, pools) {
|
|
366
|
+
function lookupQueries(entry, pools, shape = "route") {
|
|
353
367
|
const contracts = Object.keys(entry.roles);
|
|
354
368
|
const queries = [{
|
|
355
369
|
id: "head",
|
|
@@ -365,7 +379,7 @@ function lookupQueries(entry, pools) {
|
|
|
365
379
|
});
|
|
366
380
|
if (pools) for (const factory of entry.factories.filter((address) => entry.roles[address] === "factory")) queries.push({
|
|
367
381
|
id: `pools:${factory}`,
|
|
368
|
-
query: poolsByFactoryQuery(factory, POOLS_LIMIT)
|
|
382
|
+
query: poolsByFactoryQuery(factory, POOLS_LIMIT, shape)
|
|
369
383
|
});
|
|
370
384
|
return queries;
|
|
371
385
|
}
|
|
@@ -381,7 +395,35 @@ function confirmation(row) {
|
|
|
381
395
|
};
|
|
382
396
|
return { confirmed: false };
|
|
383
397
|
}
|
|
384
|
-
|
|
398
|
+
/** The pools of the batch, merged over the factories and ranked by the shape's number. */
|
|
399
|
+
function readPools(members, shape) {
|
|
400
|
+
const byAddress = /* @__PURE__ */ new Map();
|
|
401
|
+
for (const [id, member] of members) {
|
|
402
|
+
if (!id.startsWith("pools:")) continue;
|
|
403
|
+
for (const row of rowsOf(member)) {
|
|
404
|
+
const address = typeof row.to_address === "string" ? row.to_address : null;
|
|
405
|
+
const rank = numberOrNull(shape === "levels" ? row.swapped_usd : row.total_volume_usd);
|
|
406
|
+
if (!address || rank === null || byAddress.has(address)) continue;
|
|
407
|
+
const labels = stringList(row.to_labels);
|
|
408
|
+
byAddress.set(address, {
|
|
409
|
+
rank,
|
|
410
|
+
row: shape === "levels" ? {
|
|
411
|
+
address,
|
|
412
|
+
labels,
|
|
413
|
+
swapped_usd: rank,
|
|
414
|
+
swap_count: numberOrNull(row.swap_count) ?? 0
|
|
415
|
+
} : {
|
|
416
|
+
address,
|
|
417
|
+
labels,
|
|
418
|
+
total_volume_usd: rank,
|
|
419
|
+
tx_total_count: numberOrNull(row.tx_total_count) ?? 0
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return [...byAddress.values()].sort((a, b) => b.rank - a.rank).slice(0, POOLS_LIMIT).map(({ row }) => row);
|
|
425
|
+
}
|
|
426
|
+
function readMatch(entry, members, read, shape) {
|
|
385
427
|
const notes = [];
|
|
386
428
|
const contracts = /* @__PURE__ */ new Map();
|
|
387
429
|
const listed = new Map(rowsOf(members.get("contracts")).map((row) => [String(row.address), row]));
|
|
@@ -393,22 +435,7 @@ function readMatch(entry, members, read) {
|
|
|
393
435
|
...confirmation(row)
|
|
394
436
|
});
|
|
395
437
|
}
|
|
396
|
-
const
|
|
397
|
-
for (const [id, member] of members) {
|
|
398
|
-
if (!id.startsWith("pools:")) continue;
|
|
399
|
-
for (const row of rowsOf(member)) {
|
|
400
|
-
const address = typeof row.to_address === "string" ? row.to_address : null;
|
|
401
|
-
const volume = numberOrNull(row.total_volume_usd);
|
|
402
|
-
if (!address || volume === null || byAddress.has(address)) continue;
|
|
403
|
-
byAddress.set(address, {
|
|
404
|
-
address,
|
|
405
|
-
labels: stringList(row.to_labels),
|
|
406
|
-
total_volume_usd: volume,
|
|
407
|
-
tx_total_count: numberOrNull(row.tx_total_count) ?? 0
|
|
408
|
-
});
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
const pools = [...byAddress.values()].sort((a, b) => b.total_volume_usd - a.total_volume_usd).slice(0, POOLS_LIMIT);
|
|
438
|
+
const pools = readPools(members, shape);
|
|
412
439
|
const head = rowsOf(members.get("head"))[0];
|
|
413
440
|
const families = head ? {
|
|
414
441
|
behind_money: numberOrNull(column(head, "behind_money", "h")),
|
|
@@ -427,7 +454,7 @@ function readMatch(entry, members, read) {
|
|
|
427
454
|
}
|
|
428
455
|
const ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/;
|
|
429
456
|
/** The hint's last rule on a lane with the levels; the graph of before keeps its 0.81.0 text. */
|
|
430
|
-
const LEVELS_HINT = `${require_layer_routing.LEVEL_RULE} 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.`;
|
|
457
|
+
const LEVELS_HINT = `${require_layer_routing.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. 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.`;
|
|
431
458
|
const ROUTE_HINT = "Read families before a SWAPPED search: it is sent when behind_dex is at most 100000. Never ask the user for an address.";
|
|
432
459
|
function hintFor(result, name, address = null) {
|
|
433
460
|
const closing = result.swap_links === "levels" ? LEVELS_HINT : ROUTE_HINT;
|
|
@@ -536,10 +563,16 @@ async function handleMetaDexLookup(args, deps) {
|
|
|
536
563
|
});
|
|
537
564
|
}
|
|
538
565
|
const entry = match.matched;
|
|
539
|
-
const
|
|
566
|
+
const unavailable = await deps.unavailable?.();
|
|
567
|
+
let shape = "route";
|
|
568
|
+
if (!unavailable && deps.linkShape) try {
|
|
569
|
+
shape = await deps.linkShape(network);
|
|
570
|
+
} catch {
|
|
571
|
+
shape = "route";
|
|
572
|
+
}
|
|
573
|
+
const queries = lookupQueries(entry, pools, shape);
|
|
540
574
|
let members = /* @__PURE__ */ new Map();
|
|
541
575
|
const notes = [];
|
|
542
|
-
const unavailable = await deps.unavailable?.();
|
|
543
576
|
if (unavailable) notes.push(`No graph read was sent: ${unavailable} The contracts are the reviewed registry rows, not yet confirmed on the graph.`);
|
|
544
577
|
else try {
|
|
545
578
|
const answer = await deps.graphQueryBatch({
|
|
@@ -554,13 +587,7 @@ async function handleMetaDexLookup(args, deps) {
|
|
|
554
587
|
} catch (err) {
|
|
555
588
|
notes.push(`The graph reads failed: ${deps.describeFailure(err)}`);
|
|
556
589
|
}
|
|
557
|
-
|
|
558
|
-
if (!unavailable && deps.linkShape) try {
|
|
559
|
-
shape = await deps.linkShape(network);
|
|
560
|
-
} catch {
|
|
561
|
-
shape = "route";
|
|
562
|
-
}
|
|
563
|
-
const read = readMatch(entry, members, members.size > 0);
|
|
590
|
+
const read = readMatch(entry, members, members.size > 0, shape);
|
|
564
591
|
notes.push(...read.notes);
|
|
565
592
|
const contractsOf = (role) => [...read.contracts.values()].filter((contract) => contract.role === role);
|
|
566
593
|
const topPool = read.pools[0]?.address ?? null;
|
package/dist/mcp-proxy.cjs
CHANGED
|
@@ -11,7 +11,7 @@ const require_layer_routing = require("./layer-routing-D9KbTKUj.cjs");
|
|
|
11
11
|
const require_graph_schema = require("./graph-schema-DNvmR6iP.cjs");
|
|
12
12
|
const require_action_log = require("./action-log-WMW6xFMx.cjs");
|
|
13
13
|
const require_answer_hint = require("./answer-hint-BlYEBq_Y.cjs");
|
|
14
|
-
const require_dex_tool = require("./dex-tool-
|
|
14
|
+
const require_dex_tool = require("./dex-tool-BDERiT5t.cjs");
|
|
15
15
|
const require_dex_registry = require("./dex-registry-BhGJUG9_.cjs");
|
|
16
16
|
const require_token_lookup = require("./token-lookup-D-5GBEwF.cjs");
|
|
17
17
|
const require_deployer_screen = require("./deployer-screen-BomgSBcq.cjs");
|
|
@@ -899,7 +899,7 @@ const GRAPH_SCHEMA_HINTS = [
|
|
|
899
899
|
"- An Address carries a kind from chain facts. topology carries :Account or :Contract as a second label on an Address (:Contract:SmartAccount for a contract wallet), with is_contract kept beside :Contract, and an address that only received has none. facts serves no kind: a facts read that names :Account, or :Contract at an end of a relationship, is refused, so ask USE topology or USE chain. One Contract node read by its address is another read, see One contract by its address below. chain Address returns is_contract, nonce and delegated_to at the newest block, or at the block named by at_block. block_timestamp is epoch milliseconds on every layer.",
|
|
900
900
|
"- Address nodes carry address, network, labels, and the role flags is_exchange, is_scam, is_victim, is_sanctioned and is_issuer_frozen. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner, owner_state) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence LIMIT 25.",
|
|
901
901
|
"- Labels hold role words, never a claim code: Exchange (plus the exchange name), Scam, Victim, Sanctioned (plus the entity name) and IssuerFrozen (plus the token symbol). Each role is also a node label and a flag on the Address: :Exchange and is_exchange follow the exchange label, :Scam and is_scam the risk label, :Victim and is_victim the protection label, :Sanctioned and is_sanctioned the sanctioned label, :IssuerFrozen and is_issuer_frozen the issuer_frozen label: an issuer froze this wallet; the token in labels says which. Each flag is present only when true and absent otherwise, never false: test IS NOT NULL or IS NULL, not = false. A withdrawn label removes its node label and its flag. Why a judgement mark is there sits in a sorted claims list on the node, written by the labels layer: risk_claims on :Scam, :Poisoned and :Sanctioned, protection_claims on :Victim and :Targeted, traced_claims on :OnMoneyTrail, and suspect_labels, with no mark, for a warning or a record that accuses nobody. risk_claims: FAKE_TOKEN (a fake-token scam: a token that copies a listed token and was sent to holders of the real token, or used as poisoning bait), FAKE_TOKEN_DEPLOYER (the sender of the transaction that created it, even through a factory), FAKE_TOKEN_LP (the wallet that seeded its pool and pulled the liquidity after the buyers paid), ADDRESS_POISONING (:Poisoned, never :Scam: a look-alike address that sent worthless dust so the target copies it), INBOUND_IMPERSONATION (a look-alike that paid the target to get into its history), PHANTOM_TRANSFER, PHANTOM_TRANSFER_EMITTER and PHANTOM_ENTRYPOINT (a contract that writes fake transfer events claiming a transfer from a look-alike that never happened), SWEEPER_DELEGATE and SWEEP_BENEFICIARY (an EIP-7702 delegate that empties accounts, and where the funds go), UNSAFE_DELEGATE (a delegate any caller can use to empty the account), APPROVAL_DRAINER and APPROVAL_DRAIN_BENEFICIARY (a spender that moved the tokens of at least three owners with their approval or Permit2 within 72 hours of the grant and paid nothing back, and the receiver), SANCTIONED. protection_claims: VICTIM (lost money to a scam the evidence walk traced: it paid the accused, was swept or was drained after the attempt; receiving a fake token or dust is never a victim) and the older ADDRESS_POISONING_TARGET (:Targeted, a target the walk has not proven lost money). traced_claims: LAUNDERED, RECEIVED, FUNDER and MIXED, the trail the evidence walk followed from an accused address. suspect_labels: FAKE_TOKEN (a copied name: a token that copies the name of a listed token, a record that accuses nobody, with no :Scam and no is_scam, never called a scam), MIXER_DEPOSITOR and MIXER_WITHDRAWER (the address itself used a mixer pool, a warning and not a theft). A risk question is answered from the marks and claims; a flow question gets no risk screen. Ask by mark, MATCH (a:Scam) WHERE \"FAKE_TOKEN\" IN a.risk_claims RETURN a.address AS address, a.risk_claims AS risk_claims LIMIT 25, or anchor on the address. A fake-token list asks both lists and keeps them apart: the scams above, then the copied names, MATCH (a:Token) WHERE \"FAKE_TOKEN\" IN a.suspect_labels RETURN a.address AS address, a.suspect_labels AS suspect_labels LIMIT 25. The mark is the anchor and a WHERE on its own properties is allowed; a WHERE with no mark and no address is refused. The graph holds no link from an accused address to its victims, so answer per address. Say what a claim means in plain words, such as \"a fake-token scam\" or \"it lost money to a scam\", never the list name or the code.",
|
|
902
|
-
"- Address nodes carry base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only; on a lane whose money family lists ROUTED_TO they count funds between addresses (FLOWED_TO) only, not swaps, so what an address got from a swap is on its ROUTED_TO links (bought_usd_sum) — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWED_TO edges carry exactly tx_count, amount_usd_sum (total money flow, token and native value merged), first_seen_timestamp, last_seen_timestamp. Lifetime aggregates are the only serving window. Averages are computed inline (amount_usd_sum / toFloat(tx_count)). tx_count counts token and native transfers plus internal native transfers (a contract sending ETH during a call), and amount_usd_sum prices them all. USE facts TRANSFER lists all three, so the rows of a pair are the transfers its link counts, up to the height the link was built to. A link covers all time and a USE facts read covers one day: read the transfers of a pair one day at a time. A transaction anchor of a pair resolves through USE facts, on the UTC day of the first_seen_timestamp or last_seen_timestamp of the link: MATCH (a:Address {address: $from})-[t:TRANSFER]->(b:Address {address: $to}) WHERE t.block_date = \"YYYY-MM-DD\" RETURN t.tx_id, t.block_timestamp LIMIT 1.",
|
|
902
|
+
"- Address nodes carry base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only; on a lane whose money family lists ROUTED_TO they count funds between addresses (FLOWED_TO) only, not swaps, so what an address got from a swap is on its ROUTED_TO links (bought_usd_sum), and a pool, a pool manager or a bonding curve has none of these totals there: its trade is the sum of its SWAPPED links (sold_usd, swap_count) — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWED_TO edges carry exactly tx_count, amount_usd_sum (total money flow, token and native value merged), first_seen_timestamp, last_seen_timestamp. Lifetime aggregates are the only serving window. Averages are computed inline (amount_usd_sum / toFloat(tx_count)). tx_count counts token and native transfers plus internal native transfers (a contract sending ETH during a call), and amount_usd_sum prices them all. USE facts TRANSFER lists all three, so the rows of a pair are the transfers its link counts, up to the height the link was built to. A link covers all time and a USE facts read covers one day: read the transfers of a pair one day at a time. A transaction anchor of a pair resolves through USE facts, on the UTC day of the first_seen_timestamp or last_seen_timestamp of the link: MATCH (a:Address {address: $from})-[t:TRANSFER]->(b:Address {address: $to}) WHERE t.block_date = \"YYYY-MM-DD\" RETURN t.tx_id, t.block_timestamp LIMIT 1.",
|
|
903
903
|
"- For actor-level exposure (AC11), UNION FLOWED_TO and SWAPPED reachability over one visible LINKED hop instead of expanding through the LINKED edge itself: MATCH (a:Address {address: $addr})-[:LINKED]-(owned:Address)-[r:FLOWED_TO|SWAPPED]-(b:Address) WHERE NOT a:Pool AND NOT a:Protocol AND NOT a:System AND NOT a.address IN [\"0x0000000000000000000000000000000000000000\", \"0x000000000000000000000000000000000000dead\"] AND NOT owned:Pool AND NOT owned:Protocol AND NOT owned:System AND NOT owned.address IN [\"0x0000000000000000000000000000000000000000\", \"0x000000000000000000000000000000000000dead\"] AND owned.address <> b.address AND a.address <> b.address RETURN owned.address, b.address, type(r), coalesce(r.amount_usd_sum, r.bought_usd) LIMIT 50.",
|
|
904
904
|
"- Labels and per-label risk live on the address node: the labels array plus three parallel lists, label_risk_labels, label_risk_levels and label_risk_updated_timestamps, where entry i of each list is one label row. No overall risk score is served. USE facts serves bounded single-event rows (TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING edges) and one Contract by its address; lifetime address metrics (degrees, totals, activity window) are node properties on USE topology.",
|
|
905
905
|
"- (from:Address)-[t:TRANSFER]->(to:Address) on USE facts returns individual transfer rows, not aggregates, with properties amount, amount_usd, asset_symbol, asset_contract, tx_id, block_height, block_timestamp, event_index, edge_index, kind, price_usd, and price_missing. Every TRANSFER row has a kind: token, native or internal. An internal row is ETH a contract sends while it runs a call, such as the ETH leg of a wrap. Add t.kind = \"internal\" to the pair and the day to read only the internal rows. A facts read names an address pair with one day, whether it is a TRANSFER row-select or a count()/sum() aggregate: both endpoint addresses as {address: \"...\"} on from and to, with WHERE t.block_date = \"YYYY-MM-DD\". A transaction is read on USE chain by its tx_id, not on facts. t.block_timestamp bounds in epoch milliseconds may narrow the day to a time window. One address, a day alone, a window of days, a block range or a bare LIMIT is not enough. A facts read holds at most 200 rows in a reply, has one relationship and no hop, and takes no ORDER BY: sort the page yourself.",
|