chain-insights 0.75.0 → 0.76.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/README.md +1 -0
- package/dist/{action-log-D49Par9P.mjs → action-log-Byv9Ln_6.mjs} +4 -10
- package/dist/{action-log-D49Par9P.mjs.map → action-log-Byv9Ln_6.mjs.map} +1 -1
- package/dist/{action-log-HniMMF7f.cjs → action-log-WMW6xFMx.cjs} +3 -9
- package/dist/{active-Dkf8AB1R.mjs → active-D2aabYRF.mjs} +3 -4
- package/dist/{active-Dkf8AB1R.mjs.map → active-D2aabYRF.mjs.map} +1 -1
- package/dist/{active-Bc13hJIm.cjs → active-q3yViZhc.cjs} +2 -3
- package/dist/answer-hint-BlYEBq_Y.cjs +57 -0
- package/dist/answer-hint-vOE1O6Lf.mjs +48 -0
- package/dist/answer-hint-vOE1O6Lf.mjs.map +1 -0
- package/dist/{buy-_mpdRieG.mjs → buy-B2luUbWF.mjs} +5 -6
- package/dist/{buy-_mpdRieG.mjs.map → buy-B2luUbWF.mjs.map} +1 -1
- package/dist/{buy-97M6dtEu.cjs → buy-DEoGITbT.cjs} +4 -5
- package/dist/{cache-location-CBVzUIxq.cjs → cache-location-C09AE55j.cjs} +2 -3
- package/dist/{cache-location-BO2XkfgI.mjs → cache-location-DxTTqBwk.mjs} +2 -3
- package/dist/{cache-location-BO2XkfgI.mjs.map → cache-location-DxTTqBwk.mjs.map} +1 -1
- package/dist/{call-args-B0oMK1-J.mjs → call-args-CBqbYfOE.mjs} +15 -4
- package/dist/{call-args-B0oMK1-J.mjs.map → call-args-CBqbYfOE.mjs.map} +1 -1
- package/dist/{call-args-C8Gp5gco.cjs → call-args-DXEmPeE-.cjs} +14 -2
- package/dist/{capabilities-DxojbX4D.mjs → capabilities-BRNHcabF.mjs} +5 -11
- package/dist/{capabilities-DxojbX4D.mjs.map → capabilities-BRNHcabF.mjs.map} +1 -1
- package/dist/{capabilities-Ds3320iS.cjs → capabilities-DalimVY2.cjs} +4 -10
- package/dist/{claude-desktop-Jmm4PlBZ.cjs → claude-desktop-3OksQZVE.cjs} +2 -3
- package/dist/{claude-desktop-6jwX0Lux.mjs → claude-desktop-C1SDYAP2.mjs} +2 -3
- package/dist/{claude-desktop-6jwX0Lux.mjs.map → claude-desktop-C1SDYAP2.mjs.map} +1 -1
- package/dist/cli.cjs +95 -76
- package/dist/cli.mjs +94 -75
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-7qOfAdpH.mjs → client-BaHAIidE.mjs} +10 -21
- package/dist/{client-7qOfAdpH.mjs.map → client-BaHAIidE.mjs.map} +1 -1
- package/dist/{client-C9uwHnBS.cjs → client-Ddk4X9Ko.cjs} +9 -20
- package/dist/{config-BxtMoo9c.cjs → config-BdE8LcF-.cjs} +3 -5
- package/dist/{config-9MabJh5R.mjs → config-BkLIqOYq.mjs} +4 -6
- package/dist/{config-9MabJh5R.mjs.map → config-BkLIqOYq.mjs.map} +1 -1
- package/dist/{create-CpfZq2fx.mjs → create-CluDZkuF.mjs} +3 -4
- package/dist/{create-CpfZq2fx.mjs.map → create-CluDZkuF.mjs.map} +1 -1
- package/dist/{create-DdggkF04.cjs → create-DvBumvHn.cjs} +2 -3
- package/dist/{dex-registry-Chs79Ukc.cjs → dex-registry-CZQB2YhU.cjs} +4 -26
- package/dist/{dex-registry-rziydXYq.mjs → dex-registry-D6Xxi_vr.mjs} +5 -27
- package/dist/{dex-registry-rziydXYq.mjs.map → dex-registry-D6Xxi_vr.mjs.map} +1 -1
- package/dist/{dex-tool-ib_ICiyV.mjs → dex-tool-BoAYqhZO.mjs} +8 -62
- package/dist/dex-tool-BoAYqhZO.mjs.map +1 -0
- package/dist/{dex-tool-85_76Q8i.cjs → dex-tool-DsM-pSku.cjs} +12 -72
- package/dist/{format-CSesEBvS.mjs → format-CsnW5M4D.mjs} +2 -3
- package/dist/{format-CSesEBvS.mjs.map → format-CsnW5M4D.mjs.map} +1 -1
- package/dist/{format-DfhRQq4L.cjs → format-DUzmoeaE.cjs} +1 -2
- package/dist/{graph-schema-DNJXDaTn.cjs → graph-schema-C8Pi6r7c.cjs} +8 -25
- package/dist/{graph-schema-Bxqwukqu.mjs → graph-schema-D4LAefGf.mjs} +9 -26
- package/dist/{graph-schema-Bxqwukqu.mjs.map → graph-schema-D4LAefGf.mjs.map} +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +0 -16
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +0 -16
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -7
- package/dist/{known-keys-B87ZqOgE.mjs → known-keys-BbuzCZOW.mjs} +4 -7
- package/dist/{known-keys-B87ZqOgE.mjs.map → known-keys-BbuzCZOW.mjs.map} +1 -1
- package/dist/{known-keys-PKZF5GYd.cjs → known-keys-Cy8lKDOA.cjs} +3 -6
- package/dist/mcp-proxy.cjs +65 -39
- package/dist/mcp-proxy.d.cts +2 -2
- package/dist/mcp-proxy.d.cts.map +1 -1
- package/dist/mcp-proxy.d.mts +2 -2
- package/dist/mcp-proxy.d.mts.map +1 -1
- package/dist/mcp-proxy.mjs +63 -38
- package/dist/mcp-proxy.mjs.map +1 -1
- package/dist/{print-result-if-AbNLY.cjs → print-result-BYppJlUi.cjs} +19 -19
- package/dist/{print-result-BtEAn2Wl.mjs → print-result-IFARsMnL.mjs} +9 -21
- package/dist/print-result-IFARsMnL.mjs.map +1 -0
- package/dist/{public-tools-COG3pCpD.cjs → public-tools-Cfc1OPNS.cjs} +8 -13
- package/dist/{public-tools-DIJs4SHz.mjs → public-tools-DXlZcanX.mjs} +8 -13
- package/dist/{public-tools-DIJs4SHz.mjs.map → public-tools-DXlZcanX.mjs.map} +1 -1
- package/dist/{quote-DfTut0cx.mjs → quote-41CbMc37.mjs} +2 -3
- package/dist/{quote-DfTut0cx.mjs.map → quote-41CbMc37.mjs.map} +1 -1
- package/dist/{quote-B9sYNOiv.cjs → quote-pFKcSvMv.cjs} +1 -2
- package/dist/{request-timeout-CYmQF8N7.cjs → request-timeout-DxwNijQD.cjs} +1 -2
- package/dist/{request-timeout-lBBe0mGf.mjs → request-timeout-K3ljP0pa.mjs} +2 -3
- package/dist/{request-timeout-lBBe0mGf.mjs.map → request-timeout-K3ljP0pa.mjs.map} +1 -1
- package/dist/{robinhood-CCTMagwM.mjs → robinhood-0NZsA6ZW.mjs} +2 -3
- package/dist/robinhood-0NZsA6ZW.mjs.map +1 -0
- package/dist/{robinhood-ChiT69sc.cjs → robinhood-DumTxvlA.cjs} +1 -2
- package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
- package/dist/{rolldown-runtime-C0BPl7ul.cjs → rolldown-runtime-BW-eSwOZ.cjs} +1 -2
- package/dist/{rules-BWdbOtHi.mjs → rules-B3w9pCeQ.mjs} +2 -3
- package/dist/{rules-BWdbOtHi.mjs.map → rules-B3w9pCeQ.mjs.map} +1 -1
- package/dist/{rules-BD-cNHMX.cjs → rules-BKwfmNsJ.cjs} +1 -2
- package/dist/{schema-KjZqCHbu.mjs → schema-CKnQsdw9.mjs} +6 -13
- package/dist/{schema-KjZqCHbu.mjs.map → schema-CKnQsdw9.mjs.map} +1 -1
- package/dist/{schema-tX0U0-VI.cjs → schema-CSESfCvA.cjs} +5 -12
- package/dist/{schema-cache-DRObKUvS.mjs → schema-cache-BfKHodDY.mjs} +3 -4
- package/dist/{schema-cache-DRObKUvS.mjs.map → schema-cache-BfKHodDY.mjs.map} +1 -1
- package/dist/{schema-cache-C7v9ml6S.cjs → schema-cache-NLgJmh4X.cjs} +3 -4
- package/dist/{skill-refresh-xYWZ_hua.mjs → skill-refresh-BchIsODN.mjs} +2 -3
- package/dist/{skill-refresh-xYWZ_hua.mjs.map → skill-refresh-BchIsODN.mjs.map} +1 -1
- package/dist/{skill-refresh-Be2D5FrX.cjs → skill-refresh-DaCTxhhy.cjs} +2 -3
- package/dist/{subscription-status-DIuH84fM.mjs → subscription-status-5WfPhSep.mjs} +3 -4
- package/dist/{subscription-status-DIuH84fM.mjs.map → subscription-status-5WfPhSep.mjs.map} +1 -1
- package/dist/{subscription-status-9tMfD90J.cjs → subscription-status-w4zI2KCK.cjs} +2 -3
- package/dist/token-lookup-BJ00JO9A.cjs +342 -0
- package/dist/token-lookup-XnyisLQW.mjs +303 -0
- package/dist/token-lookup-XnyisLQW.mjs.map +1 -0
- package/dist/{tool-visibility-DTAYvE9E.cjs → tool-visibility-DIpgPULN.cjs} +5 -10
- package/dist/{tool-visibility-zcmwMSbn.mjs → tool-visibility-Dy3psowS.mjs} +6 -11
- package/dist/tool-visibility-Dy3psowS.mjs.map +1 -0
- package/dist/{tools-D9ep9E7Q.mjs → tools-6pZo4h_p.mjs} +6 -21
- package/dist/{tools-D9ep9E7Q.mjs.map → tools-6pZo4h_p.mjs.map} +1 -1
- package/dist/{tools-Cmnq7yip.cjs → tools-DZLizem9.cjs} +5 -20
- package/dist/{topup-B6gZbTmv.mjs → topup--7JTo4UQ.mjs} +6 -7
- package/dist/{topup-B6gZbTmv.mjs.map → topup--7JTo4UQ.mjs.map} +1 -1
- package/dist/{topup-DVTCU2le.cjs → topup-BgI9OcUd.cjs} +5 -6
- package/dist/{topup-server-ShuYSyBY.cjs → topup-server-D9Uk1Th3.cjs} +7 -24
- package/dist/{topup-server-KQDviFXG.mjs → topup-server-DR0HaUcR.mjs} +8 -25
- package/dist/{topup-server-KQDviFXG.mjs.map → topup-server-DR0HaUcR.mjs.map} +1 -1
- package/dist/{topup-server-BcT7DIpd.mjs → topup-server-DlwzFEF1.mjs} +5 -12
- package/dist/{topup-server-BcT7DIpd.mjs.map → topup-server-DlwzFEF1.mjs.map} +1 -1
- package/dist/{topup-server-f4Gx0vji.cjs → topup-server-H1M_7PJK.cjs} +4 -11
- package/dist/{transport-error-C7OQjmC7.mjs → transport-error-68G35VPH.mjs} +3 -4
- package/dist/{transport-error-C7OQjmC7.mjs.map → transport-error-68G35VPH.mjs.map} +1 -1
- package/dist/{transport-error-qDWQn8hb.cjs → transport-error-DXy1iTpS.cjs} +2 -3
- package/dist/{update-DqBhBXFs.mjs → update-BH8F4cQ2.mjs} +3 -4
- package/dist/{update-DqBhBXFs.mjs.map → update-BH8F4cQ2.mjs.map} +1 -1
- package/dist/{update-NowrCmjR.cjs → update-DUDdQSEU.cjs} +2 -3
- package/dist/{usage-status-Frot6fPG.mjs → usage-status-BUZgRl4r.mjs} +3 -5
- package/dist/{usage-status-Frot6fPG.mjs.map → usage-status-BUZgRl4r.mjs.map} +1 -1
- package/dist/{usage-status-DonwoLR3.cjs → usage-status-DnV3I3gX.cjs} +2 -4
- package/dist/{wallet-QTo5YCFR.mjs → wallet-B1M0HdQh.mjs} +4 -8
- package/dist/{wallet-QTo5YCFR.mjs.map → wallet-B1M0HdQh.mjs.map} +1 -1
- package/dist/{wallet-CgIAfdxL.cjs → wallet-BubGd_sG.cjs} +3 -7
- package/docs/mcp-proxy.md +34 -0
- package/docs/stability.md +3 -2
- package/package.json +1 -1
- package/skills/chain-insights-cypher/SKILL.md +3 -0
- package/dist/dex-tool-ib_ICiyV.mjs.map +0 -1
- package/dist/print-result-BtEAn2Wl.mjs.map +0 -1
- package/dist/robinhood-CCTMagwM.mjs.map +0 -1
- package/dist/tool-visibility-zcmwMSbn.mjs.map +0 -1
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
+
import { t as ANSWER_HINT } from "./answer-hint-vOE1O6Lf.mjs";
|
|
3
|
+
import { a as normalizeDexNetwork, t as DexRegistryError } from "./dex-registry-D6Xxi_vr.mjs";
|
|
4
|
+
import { i as isEpochMs, o as utcText } from "./print-result-IFARsMnL.mjs";
|
|
5
|
+
// src/mcp/token-lookup.ts
|
|
6
|
+
/**
|
|
7
|
+
* meta_token_lookup: a ticker or a token name becomes its contracts.
|
|
8
|
+
*
|
|
9
|
+
* A local tool of the proxy. It sends one anchored facts read of the Asset
|
|
10
|
+
* lookup by symbol, the same read by name when the symbol answers nothing, and
|
|
11
|
+
* then the creator and the factory of each candidate from topology, one batch
|
|
12
|
+
* member per candidate. Nothing is matched here: the graph server matches the
|
|
13
|
+
* symbol or the name, case-insensitively and exactly, and orders the rows
|
|
14
|
+
* verified first, then oldest first. The proxy keeps that order.
|
|
15
|
+
*
|
|
16
|
+
* Tickers collide on purpose: clones reuse a symbol to borrow its trust. The
|
|
17
|
+
* tool never picks one. The description below is the contract with every
|
|
18
|
+
* host, Claude Desktop chat included, which reads no skill.
|
|
19
|
+
*/
|
|
20
|
+
var token_lookup_exports = /* @__PURE__ */ __exportAll({
|
|
21
|
+
META_TOKEN_LOOKUP_DESCRIPTION: () => META_TOKEN_LOOKUP_DESCRIPTION,
|
|
22
|
+
META_TOKEN_LOOKUP_TITLE: () => META_TOKEN_LOOKUP_TITLE,
|
|
23
|
+
META_TOKEN_LOOKUP_TOOL: () => META_TOKEN_LOOKUP_TOOL,
|
|
24
|
+
handleMetaTokenLookup: () => handleMetaTokenLookup
|
|
25
|
+
});
|
|
26
|
+
const META_TOKEN_LOOKUP_TOOL = "meta_token_lookup";
|
|
27
|
+
const META_TOKEN_LOOKUP_SCHEMA = "chain-insights.meta-token-lookup.v1";
|
|
28
|
+
const META_TOKEN_LOOKUP_TITLE = "Token by ticker or name";
|
|
29
|
+
const META_TOKEN_LOOKUP_DESCRIPTION = "Call this first when a question names a token by its ticker or name and gives no contract (TCITY, USDG, SPCX). It returns every contract on the network that carries that symbol, verified first, then oldest first. Tickers collide: never treat the first row as the token. When several match, name them and ask, or pick by the evidence the user gave. Zero candidates means no contract carries the symbol: say so, and do not search the web.";
|
|
30
|
+
const META_TOKEN_LOOKUP_ANNOTATIONS = {
|
|
31
|
+
readOnlyHint: true,
|
|
32
|
+
idempotentHint: true,
|
|
33
|
+
openWorldHint: false
|
|
34
|
+
};
|
|
35
|
+
/** The candidates returned. The read asks for one more, so a full page says there are more. */
|
|
36
|
+
const CANDIDATES_MAX = 25;
|
|
37
|
+
const ROWS_READ = 26;
|
|
38
|
+
/** The graph server admits at most 20 members in one graph_query_batch. */
|
|
39
|
+
const CREATOR_BATCH_MAX = 20;
|
|
40
|
+
const SYMBOL_MAX = 64;
|
|
41
|
+
const ADDRESS_INPUT_HINT = "an address is already an anchor: read it on USE topology";
|
|
42
|
+
const ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/;
|
|
43
|
+
const CONTRACT_FORM = /^0x[0-9a-f]{40}$/;
|
|
44
|
+
function unsafeLiteral(text) {
|
|
45
|
+
for (const char of text) {
|
|
46
|
+
const code = char.codePointAt(0);
|
|
47
|
+
if (char === "\"" || char === "\\" || code < 32 || code === 127) return true;
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
const CODE_PREFIX = /^([a-z][a-z0-9_]*):\s*/;
|
|
52
|
+
const TRANSIENT_CODE = /(timeout|memory_limit|cpu_limit|busy|_failed$|rate_limited|unavailable|too_large|node_error)/;
|
|
53
|
+
function isRecord(value) {
|
|
54
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
55
|
+
}
|
|
56
|
+
function errorResult(text) {
|
|
57
|
+
return {
|
|
58
|
+
content: [{
|
|
59
|
+
type: "text",
|
|
60
|
+
text
|
|
61
|
+
}],
|
|
62
|
+
isError: true
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function textResult(structured) {
|
|
66
|
+
return {
|
|
67
|
+
content: [{
|
|
68
|
+
type: "text",
|
|
69
|
+
text: JSON.stringify(structured, null, 2)
|
|
70
|
+
}],
|
|
71
|
+
structuredContent: structured,
|
|
72
|
+
isError: false
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** The facts Asset read by symbol or by name, in the one shape the graph server admits. */
|
|
76
|
+
function assetQuery(key, value) {
|
|
77
|
+
return `USE facts MATCH (t:Asset {${key}: "${value}"}) RETURN t.asset_contract AS contract, t.asset_symbol AS symbol, t.name AS name, t.token_standard AS token_standard, t.decimals AS decimals, t.verified AS verified, t.verification_source AS verification_source, t.first_seen_timestamp AS first_seen_timestamp LIMIT ${ROWS_READ}`;
|
|
78
|
+
}
|
|
79
|
+
/** The topology read of who deployed one contract: the deploying address and the transaction's sender. */
|
|
80
|
+
function creatorQuery(contract) {
|
|
81
|
+
return `USE topology MATCH (f:Address)-[d:DEPLOYED_CONTRACT]->(t:Address {address: "${contract}"}) RETURN f.address AS factory, d.tx_origin AS creator LIMIT 1`;
|
|
82
|
+
}
|
|
83
|
+
const textOrNull = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
|
|
84
|
+
const numberOrNull = (value) => {
|
|
85
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
86
|
+
if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value);
|
|
87
|
+
return null;
|
|
88
|
+
};
|
|
89
|
+
const addressOrNull = (value) => typeof value === "string" && ADDRESS_FORM.test(value.trim()) ? value.trim().toLowerCase() : null;
|
|
90
|
+
function verifiedOf(value) {
|
|
91
|
+
if (typeof value === "boolean") return value;
|
|
92
|
+
if (typeof value === "number") return value === 1;
|
|
93
|
+
if (typeof value === "string") return ["true", "1"].includes(value.trim().toLowerCase());
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
function answerText(answer) {
|
|
97
|
+
return (Array.isArray(answer.content) ? answer.content : []).map((block) => isRecord(block) && typeof block.text === "string" ? block.text : "").filter(Boolean).join("\n").trim();
|
|
98
|
+
}
|
|
99
|
+
/** A graph_query answer that did not answer: its code, its text, and whether the same read may answer later. */
|
|
100
|
+
function refusalOf(answer) {
|
|
101
|
+
const text = answerText(answer);
|
|
102
|
+
const detail = isRecord(answer.structuredContent) ? answer.structuredContent.error_detail : void 0;
|
|
103
|
+
const detailCode = isRecord(detail) && typeof detail.code === "string" ? detail.code : "";
|
|
104
|
+
const detailClass = isRecord(detail) && typeof detail.class === "string" ? detail.class : "";
|
|
105
|
+
const named = detailCode || CODE_PREFIX.exec(text)?.[1] || "";
|
|
106
|
+
const transient = detailClass ? detailClass !== "refused" : TRANSIENT_CODE.test(named);
|
|
107
|
+
const code = named || "not_served";
|
|
108
|
+
return {
|
|
109
|
+
code,
|
|
110
|
+
text: text || `${code}: the graph endpoint refused the read`,
|
|
111
|
+
transient
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** The result rows of a graph_query answer, or null when it holds none. */
|
|
115
|
+
function rowsOf(answer) {
|
|
116
|
+
const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : void 0;
|
|
117
|
+
const query = isRecord(facts) ? facts.query : void 0;
|
|
118
|
+
const results = isRecord(query) ? query.results : void 0;
|
|
119
|
+
return Array.isArray(results) ? results.filter(isRecord) : null;
|
|
120
|
+
}
|
|
121
|
+
function membersOf(answer) {
|
|
122
|
+
const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : void 0;
|
|
123
|
+
const queries = isRecord(facts) ? facts.queries : void 0;
|
|
124
|
+
const members = /* @__PURE__ */ new Map();
|
|
125
|
+
if (Array.isArray(queries)) {
|
|
126
|
+
for (const member of queries) if (isRecord(member) && typeof member.id === "string") members.set(member.id, member);
|
|
127
|
+
}
|
|
128
|
+
return members;
|
|
129
|
+
}
|
|
130
|
+
function candidateOf(row) {
|
|
131
|
+
const contract = textOrNull(row.contract)?.trim().toLowerCase();
|
|
132
|
+
if (!contract) return null;
|
|
133
|
+
const firstSeen = numberOrNull(row.first_seen_timestamp);
|
|
134
|
+
return {
|
|
135
|
+
contract,
|
|
136
|
+
symbol: textOrNull(row.symbol),
|
|
137
|
+
name: textOrNull(row.name),
|
|
138
|
+
token_standard: textOrNull(row.token_standard),
|
|
139
|
+
decimals: numberOrNull(row.decimals),
|
|
140
|
+
verified: verifiedOf(row.verified),
|
|
141
|
+
verification_source: textOrNull(row.verification_source),
|
|
142
|
+
first_seen_timestamp: firstSeen,
|
|
143
|
+
first_seen_timestamp_utc: isEpochMs(firstSeen) ? utcText(firstSeen) : null,
|
|
144
|
+
creator: null,
|
|
145
|
+
factory: null
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
async function readAssets(deps, network, key, value) {
|
|
149
|
+
let answer;
|
|
150
|
+
try {
|
|
151
|
+
answer = await deps.graphQuery({
|
|
152
|
+
network,
|
|
153
|
+
query: assetQuery(key, value)
|
|
154
|
+
});
|
|
155
|
+
} catch (err) {
|
|
156
|
+
return {
|
|
157
|
+
kind: "failed",
|
|
158
|
+
text: deps.describeFailure(err)
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const rows = rowsOf(answer);
|
|
162
|
+
if (answer.isError !== true && rows !== null) return {
|
|
163
|
+
kind: "rows",
|
|
164
|
+
rows
|
|
165
|
+
};
|
|
166
|
+
const refusal = refusalOf(answer);
|
|
167
|
+
if (answer.isError === true && refusal.transient) return {
|
|
168
|
+
kind: "failed",
|
|
169
|
+
text: refusal.text
|
|
170
|
+
};
|
|
171
|
+
return {
|
|
172
|
+
kind: "not_served",
|
|
173
|
+
refusal
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* The creator and the factory of each candidate, written in place. Returns why
|
|
178
|
+
* some creators were not read, or null when every read answered. A read that
|
|
179
|
+
* answered with no row leaves the candidate's creator empty with no note: the
|
|
180
|
+
* graph holds no deployment for it.
|
|
181
|
+
*/
|
|
182
|
+
async function readCreators(deps, network, candidates) {
|
|
183
|
+
const contracts = [...new Set(candidates.map((c) => c.contract).filter((c) => CONTRACT_FORM.test(c)))];
|
|
184
|
+
const found = /* @__PURE__ */ new Map();
|
|
185
|
+
const reasons = [];
|
|
186
|
+
let unread = candidates.length - candidates.filter((c) => CONTRACT_FORM.test(c.contract)).length;
|
|
187
|
+
for (let at = 0; at < contracts.length; at += CREATOR_BATCH_MAX) {
|
|
188
|
+
const chunk = contracts.slice(at, at + CREATOR_BATCH_MAX);
|
|
189
|
+
const queries = chunk.map((contract) => ({
|
|
190
|
+
id: `creator:${contract}`,
|
|
191
|
+
query: creatorQuery(contract)
|
|
192
|
+
}));
|
|
193
|
+
let members = /* @__PURE__ */ new Map();
|
|
194
|
+
try {
|
|
195
|
+
const answer = await deps.graphQueryBatch({
|
|
196
|
+
network,
|
|
197
|
+
queries
|
|
198
|
+
});
|
|
199
|
+
members = membersOf(answer);
|
|
200
|
+
if (members.size === 0) reasons.push(answer.isError === true ? refusalOf(answer).text : "the batch answer held no reads");
|
|
201
|
+
} catch (err) {
|
|
202
|
+
reasons.push(deps.describeFailure(err));
|
|
203
|
+
}
|
|
204
|
+
for (const contract of chunk) {
|
|
205
|
+
const member = members.get(`creator:${contract}`);
|
|
206
|
+
if (member?.ok === true && Array.isArray(member.results)) {
|
|
207
|
+
const row = member.results.find(isRecord);
|
|
208
|
+
found.set(contract, {
|
|
209
|
+
creator: row ? addressOrNull(row.creator) : null,
|
|
210
|
+
factory: row ? addressOrNull(row.factory) : null
|
|
211
|
+
});
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
unread += 1;
|
|
215
|
+
if (member && typeof member.error === "string" && !reasons.includes(member.error)) reasons.push(member.error);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
for (const candidate of candidates) {
|
|
219
|
+
const read = found.get(candidate.contract);
|
|
220
|
+
if (read) Object.assign(candidate, read);
|
|
221
|
+
}
|
|
222
|
+
if (unread === 0) return null;
|
|
223
|
+
return `${unread} of ${candidates.length}${reasons.length > 0 ? `: ${reasons.join("; ")}` : ""}`;
|
|
224
|
+
}
|
|
225
|
+
const NO_WEB = "Do not search the web and do not guess a contract: a web page is not a contract on this network.";
|
|
226
|
+
function hintFor(result, creatorsNotRead) {
|
|
227
|
+
const { network, query, candidates, matched_on, truncated } = result;
|
|
228
|
+
const parts = [ANSWER_HINT];
|
|
229
|
+
if (candidates.length === 0) {
|
|
230
|
+
parts.push(`No contract on ${network} carries the symbol or the name "${query}". Say so in one line. ${NO_WEB} Ask the user for the contract if they have one.`);
|
|
231
|
+
return parts.join(" ");
|
|
232
|
+
}
|
|
233
|
+
if (matched_on === "name") parts.push(`No contract carries "${query}" as its symbol; these carry it as their name.`);
|
|
234
|
+
if (candidates.length === 1) parts.push(`One contract on ${network} carries "${query}": ${candidates[0].contract}. Say it is the only one on this network, then read it by this full contract on USE topology.`);
|
|
235
|
+
else parts.push(`${candidates.length} contracts on ${network} carry "${query}"${truncated ? `, and more exist than the ${CANDIDATES_MAX} listed` : ""}. Tickers collide: never treat the first row as the token. Name them, each contract in full, with its creator and first seen time, and ask which one the user means, or pick one by the evidence the user gave (a creator, a launch date, a price move) and say why.`);
|
|
236
|
+
if (creatorsNotRead) parts.push(`The creators were not read for ${creatorsNotRead}. creator and factory are empty there because the read failed, not because the chain holds none.`);
|
|
237
|
+
parts.push("Write every contract and creator in full, 0x plus 40 hex characters.");
|
|
238
|
+
return parts.join(" ");
|
|
239
|
+
}
|
|
240
|
+
/** meta_token_lookup, {network, symbol}. Every argument is checked before a read is sent. */
|
|
241
|
+
async function handleMetaTokenLookup(args, deps) {
|
|
242
|
+
const record = isRecord(args) ? args : {};
|
|
243
|
+
let network;
|
|
244
|
+
try {
|
|
245
|
+
network = normalizeDexNetwork(record.network);
|
|
246
|
+
} catch (err) {
|
|
247
|
+
return errorResult(err instanceof DexRegistryError ? err.message : `invalid_network: ${err.message}`);
|
|
248
|
+
}
|
|
249
|
+
if (typeof record.symbol !== "string" || record.symbol.trim() === "") return errorResult("invalid_symbol: symbol is required: the ticker or the name as the user wrote it, for example TCITY");
|
|
250
|
+
const symbol = record.symbol.trim();
|
|
251
|
+
if (symbol.length > SYMBOL_MAX) return errorResult(`invalid_symbol: symbol holds at most ${SYMBOL_MAX} characters`);
|
|
252
|
+
const base = {
|
|
253
|
+
schema: META_TOKEN_LOOKUP_SCHEMA,
|
|
254
|
+
network,
|
|
255
|
+
query: symbol
|
|
256
|
+
};
|
|
257
|
+
if (ADDRESS_FORM.test(symbol)) {
|
|
258
|
+
const address = symbol.toLowerCase();
|
|
259
|
+
return textResult({
|
|
260
|
+
...base,
|
|
261
|
+
matched_on: null,
|
|
262
|
+
candidates: [],
|
|
263
|
+
total: 0,
|
|
264
|
+
truncated: false,
|
|
265
|
+
hint: `${ANSWER_HINT} ${address} is a contract address, not a ticker: ${ADDRESS_INPUT_HINT}. Send no token lookup for it.`
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
if (unsafeLiteral(symbol)) return errorResult("invalid_symbol: a symbol holds no double quote, backslash or control character. Send the ticker or the name as plain text.");
|
|
269
|
+
const unavailable = await deps.unavailable?.();
|
|
270
|
+
if (unavailable) return errorResult(`No token read was sent: ${unavailable} The lookup has no answer yet, which is not "no contract": try again later, or ask the user for the contract. ${NO_WEB}`);
|
|
271
|
+
let matchedOn = "symbol";
|
|
272
|
+
let read = await readAssets(deps, network, "symbol", symbol);
|
|
273
|
+
if (read.kind === "rows" && read.rows.length === 0) {
|
|
274
|
+
matchedOn = "name";
|
|
275
|
+
read = await readAssets(deps, network, "name", symbol);
|
|
276
|
+
}
|
|
277
|
+
if (read.kind === "failed") return errorResult(`The token read failed: ${read.text} This is not "no contract": send the same lookup again once, or ask the user for the contract. ${NO_WEB}`);
|
|
278
|
+
if (read.kind === "not_served") return textResult({
|
|
279
|
+
...base,
|
|
280
|
+
matched_on: null,
|
|
281
|
+
candidates: [],
|
|
282
|
+
total: 0,
|
|
283
|
+
truncated: false,
|
|
284
|
+
hint: `${ANSWER_HINT} This Chain Insights server does not serve the token lookup yet (${read.refusal.code}). That is not "no contract carries ${symbol}": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`
|
|
285
|
+
});
|
|
286
|
+
const total = read.rows.length;
|
|
287
|
+
const candidates = read.rows.slice(0, CANDIDATES_MAX).map(candidateOf).filter((candidate) => candidate !== null);
|
|
288
|
+
const creatorsNotRead = candidates.length > 0 ? await readCreators(deps, network, candidates) : null;
|
|
289
|
+
const result = {
|
|
290
|
+
...base,
|
|
291
|
+
matched_on: candidates.length > 0 ? matchedOn : null,
|
|
292
|
+
candidates,
|
|
293
|
+
total,
|
|
294
|
+
truncated: total > CANDIDATES_MAX
|
|
295
|
+
};
|
|
296
|
+
return textResult({
|
|
297
|
+
...result,
|
|
298
|
+
hint: hintFor(result, creatorsNotRead)
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
export { SYMBOL_MAX as a, META_TOKEN_LOOKUP_TOOL as i, META_TOKEN_LOOKUP_DESCRIPTION as n, handleMetaTokenLookup as o, META_TOKEN_LOOKUP_TITLE as r, token_lookup_exports as s, META_TOKEN_LOOKUP_ANNOTATIONS as t };
|
|
302
|
+
|
|
303
|
+
//# sourceMappingURL=token-lookup-XnyisLQW.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"token-lookup-XnyisLQW.mjs","names":[],"sources":["../src/mcp/token-lookup.ts"],"sourcesContent":["/**\n * meta_token_lookup: a ticker or a token name becomes its contracts.\n *\n * A local tool of the proxy. It sends one anchored facts read of the Asset\n * lookup by symbol, the same read by name when the symbol answers nothing, and\n * then the creator and the factory of each candidate from topology, one batch\n * member per candidate. Nothing is matched here: the graph server matches the\n * symbol or the name, case-insensitively and exactly, and orders the rows\n * verified first, then oldest first. The proxy keeps that order.\n *\n * Tickers collide on purpose: clones reuse a symbol to borrow its trust. The\n * tool never picks one. The description below is the contract with every\n * host, Claude Desktop chat included, which reads no skill.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\n\nexport const META_TOKEN_LOOKUP_TOOL = 'meta_token_lookup'\nexport const META_TOKEN_LOOKUP_SCHEMA = 'chain-insights.meta-token-lookup.v1' as const\nexport const META_TOKEN_LOOKUP_TITLE = 'Token by ticker or name'\nexport const META_TOKEN_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a token by its ticker or name and gives no contract ' +\n '(TCITY, USDG, SPCX). It returns every contract on the network that carries that symbol, ' +\n 'verified first, then oldest first. Tickers collide: never treat the first row as the token. ' +\n 'When several match, name them and ask, or pick by the evidence the user gave. Zero candidates ' +\n 'means no contract carries the symbol: say so, and do not search the web.'\nexport const META_TOKEN_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_TOKEN_LOOKUP_ARGS = ['network', 'symbol'] as const\n\n/** The candidates returned. The read asks for one more, so a full page says there are more. */\nexport const CANDIDATES_MAX = 25\nexport const ROWS_READ = CANDIDATES_MAX + 1\n/** The graph server admits at most 20 members in one graph_query_batch. */\nexport const CREATOR_BATCH_MAX = 20\nexport const SYMBOL_MAX = 64\n\nexport const ADDRESS_INPUT_HINT = 'an address is already an anchor: read it on USE topology'\n\nexport interface TokenCandidate {\n contract: string\n symbol: string | null\n name: string | null\n token_standard: string | null\n decimals: number | null\n verified: boolean\n verification_source: string | null\n first_seen_timestamp: number | null\n first_seen_timestamp_utc: string | null\n creator: string | null\n factory: string | null\n}\n\nexport interface MetaTokenLookupResult {\n schema: typeof META_TOKEN_LOOKUP_SCHEMA\n network: string\n query: string\n matched_on: 'symbol' | 'name' | null\n candidates: TokenCandidate[]\n /** The rows the server sent, at most 26: 26 means there are more than the 25 returned. */\n total: number\n truncated: boolean\n hint: string\n}\n\n/** One graph_query or graph_query_batch reply as the remote client returns it. */\nexport type GraphAnswer = {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n}\n\nexport interface TokenToolDependencies {\n /** One graph_query through the proxy's remote client, billed as any read. */\n graphQuery: (args: { network: string; query: string }) => Promise<GraphAnswer>\n /** One graph_query_batch through the proxy's remote client, billed as any read. */\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<GraphAnswer>\n /** The reason no read can be sent now, or undefined when the graph is reachable. */\n unavailable?: () => Promise<string | undefined> | string | undefined\n /** The text of a call that threw: payment required, transport. */\n describeFailure: (err: unknown) => string\n}\n\nexport type MetaTokenLookupToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\nconst CONTRACT_FORM = /^0x[0-9a-f]{40}$/\n// A string literal of the read holds no double quote, no backslash and no\n// control character: the symbol is refused rather than escaped, so the read the\n// server receives is always the read written here.\nfunction unsafeLiteral(text: string): boolean {\n for (const char of text) {\n const code = char.codePointAt(0)!\n if (char === '\"' || char === '\\\\' || code < 0x20 || code === 0x7f) return true\n }\n return false\n}\nconst CODE_PREFIX = /^([a-z][a-z0-9_]*):\\s*/\n// Codes of a read that was stopped, not refused: the same read may answer later.\nconst TRANSIENT_CODE =\n /(timeout|memory_limit|cpu_limit|busy|_failed$|rate_limited|unavailable|too_large|node_error)/\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorResult(text: string): MetaTokenLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: MetaTokenLookupResult): MetaTokenLookupToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],\n structuredContent: structured as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** The facts Asset read by symbol or by name, in the one shape the graph server admits. */\nexport function assetQuery(key: 'symbol' | 'name', value: string): string {\n return (\n `USE facts MATCH (t:Asset {${key}: \"${value}\"}) ` +\n 'RETURN t.asset_contract AS contract, t.asset_symbol AS symbol, t.name AS name, ' +\n 't.token_standard AS token_standard, t.decimals AS decimals, t.verified AS verified, ' +\n 't.verification_source AS verification_source, t.first_seen_timestamp AS first_seen_timestamp ' +\n `LIMIT ${ROWS_READ}`\n )\n}\n\n/** The topology read of who deployed one contract: the deploying address and the transaction's sender. */\nexport function creatorQuery(contract: string): string {\n return (\n `USE topology MATCH (f:Address)-[d:DEPLOYED_CONTRACT]->(t:Address {address: \"${contract}\"}) ` +\n 'RETURN f.address AS factory, d.tx_origin AS creator LIMIT 1'\n )\n}\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null\n\nconst numberOrNull = (value: unknown): number | null => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)))\n return Number(value)\n return null\n}\n\nconst addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_FORM.test(value.trim()) ? value.trim().toLowerCase() : null\n\nfunction verifiedOf(value: unknown): boolean {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return value === 1\n if (typeof value === 'string') return ['true', '1'].includes(value.trim().toLowerCase())\n return false\n}\n\nfunction answerText(answer: GraphAnswer): string {\n return (Array.isArray(answer.content) ? answer.content : [])\n .map((block) => (isRecord(block) && typeof block.text === 'string' ? block.text : ''))\n .filter(Boolean)\n .join('\\n')\n .trim()\n}\n\ntype Refusal = { code: string; text: string; transient: boolean }\n\n/** A graph_query answer that did not answer: its code, its text, and whether the same read may answer later. */\nfunction refusalOf(answer: GraphAnswer): Refusal {\n const text = answerText(answer)\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n const detailCode = isRecord(detail) && typeof detail.code === 'string' ? detail.code : ''\n const detailClass = isRecord(detail) && typeof detail.class === 'string' ? detail.class : ''\n const named = detailCode || CODE_PREFIX.exec(text)?.[1] || ''\n // A refusal that names no class is a stop only when its code says so; a\n // refusal in plain words (\"unknown label Asset\") is a server that lacks the read.\n const transient = detailClass ? detailClass !== 'refused' : TRANSIENT_CODE.test(named)\n const code = named || 'not_served'\n return { code, text: text || `${code}: the graph endpoint refused the read`, transient }\n}\n\n/** The result rows of a graph_query answer, or null when it holds none. */\nfunction rowsOf(answer: GraphAnswer): Array<Record<string, unknown>> | null {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n const results = isRecord(query) ? query.results : undefined\n return Array.isArray(results) ? results.filter(isRecord) : null\n}\n\ntype Member = { id?: unknown; ok?: unknown; results?: unknown; error?: unknown }\n\nfunction membersOf(answer: GraphAnswer): Map<string, Member> {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const queries = isRecord(facts) ? facts.queries : undefined\n const members = new Map<string, Member>()\n if (Array.isArray(queries)) {\n for (const member of queries)\n if (isRecord(member) && typeof member.id === 'string') members.set(member.id, member)\n }\n return members\n}\n\nfunction candidateOf(row: Record<string, unknown>): TokenCandidate | null {\n const contract = textOrNull(row.contract)?.trim().toLowerCase()\n if (!contract) return null\n const firstSeen = numberOrNull(row.first_seen_timestamp)\n return {\n contract,\n symbol: textOrNull(row.symbol),\n name: textOrNull(row.name),\n token_standard: textOrNull(row.token_standard),\n decimals: numberOrNull(row.decimals),\n verified: verifiedOf(row.verified),\n verification_source: textOrNull(row.verification_source),\n first_seen_timestamp: firstSeen,\n first_seen_timestamp_utc: isEpochMs(firstSeen) ? utcText(firstSeen) : null,\n creator: null,\n factory: null,\n }\n}\n\ntype Read =\n | { kind: 'rows'; rows: Array<Record<string, unknown>> }\n | { kind: 'not_served'; refusal: Refusal }\n | { kind: 'failed'; text: string }\n\nasync function readAssets(\n deps: TokenToolDependencies,\n network: string,\n key: 'symbol' | 'name',\n value: string\n): Promise<Read> {\n let answer: GraphAnswer\n try {\n answer = await deps.graphQuery({ network, query: assetQuery(key, value) })\n } catch (err) {\n return { kind: 'failed', text: deps.describeFailure(err) }\n }\n const rows = rowsOf(answer)\n if (answer.isError !== true && rows !== null) return { kind: 'rows', rows }\n const refusal = refusalOf(answer)\n if (answer.isError === true && refusal.transient) return { kind: 'failed', text: refusal.text }\n return { kind: 'not_served', refusal }\n}\n\n/**\n * The creator and the factory of each candidate, written in place. Returns why\n * some creators were not read, or null when every read answered. A read that\n * answered with no row leaves the candidate's creator empty with no note: the\n * graph holds no deployment for it.\n */\nasync function readCreators(\n deps: TokenToolDependencies,\n network: string,\n candidates: TokenCandidate[]\n): Promise<string | null> {\n const contracts = [\n ...new Set(candidates.map((c) => c.contract).filter((c) => CONTRACT_FORM.test(c))),\n ]\n const found = new Map<string, { creator: string | null; factory: string | null }>()\n const reasons: string[] = []\n let unread = candidates.length - candidates.filter((c) => CONTRACT_FORM.test(c.contract)).length\n for (let at = 0; at < contracts.length; at += CREATOR_BATCH_MAX) {\n const chunk = contracts.slice(at, at + CREATOR_BATCH_MAX)\n const queries = chunk.map((contract) => ({\n id: `creator:${contract}`,\n query: creatorQuery(contract),\n }))\n let members = new Map<string, Member>()\n try {\n const answer = await deps.graphQueryBatch({ network, queries })\n members = membersOf(answer)\n if (members.size === 0) {\n reasons.push(\n answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n )\n }\n } catch (err) {\n reasons.push(deps.describeFailure(err))\n }\n for (const contract of chunk) {\n const member = members.get(`creator:${contract}`)\n if (member?.ok === true && Array.isArray(member.results)) {\n const row = member.results.find(isRecord)\n found.set(contract, {\n creator: row ? addressOrNull(row.creator) : null,\n factory: row ? addressOrNull(row.factory) : null,\n })\n continue\n }\n unread += 1\n if (member && typeof member.error === 'string' && !reasons.includes(member.error))\n reasons.push(member.error)\n }\n }\n for (const candidate of candidates) {\n const read = found.get(candidate.contract)\n if (read) Object.assign(candidate, read)\n }\n if (unread === 0) return null\n return `${unread} of ${candidates.length}${reasons.length > 0 ? `: ${reasons.join('; ')}` : ''}`\n}\n\nconst NO_WEB =\n 'Do not search the web and do not guess a contract: a web page is not a contract on this network.'\n\nfunction hintFor(\n result: Omit<MetaTokenLookupResult, 'hint'>,\n creatorsNotRead: string | null\n): string {\n const { network, query, candidates, matched_on, truncated } = result\n const parts: string[] = [ANSWER_HINT]\n if (candidates.length === 0) {\n parts.push(\n `No contract on ${network} carries the symbol or the name \"${query}\". Say so in one line. ${NO_WEB} ` +\n 'Ask the user for the contract if they have one.'\n )\n return parts.join(' ')\n }\n if (matched_on === 'name') {\n parts.push(`No contract carries \"${query}\" as its symbol; these carry it as their name.`)\n }\n if (candidates.length === 1) {\n parts.push(\n `One contract on ${network} carries \"${query}\": ${candidates[0]!.contract}. ` +\n 'Say it is the only one on this network, then read it by this full contract on USE topology.'\n )\n } else {\n parts.push(\n `${candidates.length} contracts on ${network} carry \"${query}\"` +\n `${truncated ? `, and more exist than the ${CANDIDATES_MAX} listed` : ''}. ` +\n 'Tickers collide: never treat the first row as the token. Name them, each contract in full, ' +\n 'with its creator and first seen time, and ask which one the user means, or pick one by the evidence the user gave ' +\n '(a creator, a launch date, a price move) and say why.'\n )\n }\n if (creatorsNotRead) {\n parts.push(\n `The creators were not read for ${creatorsNotRead}. creator and factory are empty there because the read failed, ` +\n 'not because the chain holds none.'\n )\n }\n parts.push('Write every contract and creator in full, 0x plus 40 hex characters.')\n return parts.join(' ')\n}\n\n/** meta_token_lookup, {network, symbol}. Every argument is checked before a read is sent. */\nexport async function handleMetaTokenLookup(\n args: unknown,\n deps: TokenToolDependencies\n): Promise<MetaTokenLookupToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n if (typeof record.symbol !== 'string' || record.symbol.trim() === '') {\n return errorResult(\n 'invalid_symbol: symbol is required: the ticker or the name as the user wrote it, for example TCITY'\n )\n }\n const symbol = record.symbol.trim()\n if (symbol.length > SYMBOL_MAX) {\n return errorResult(`invalid_symbol: symbol holds at most ${SYMBOL_MAX} characters`)\n }\n const base = {\n schema: META_TOKEN_LOOKUP_SCHEMA,\n network,\n query: symbol,\n }\n\n if (ADDRESS_FORM.test(symbol)) {\n const address = symbol.toLowerCase()\n return textResult({\n ...base,\n matched_on: null,\n candidates: [],\n total: 0,\n truncated: false,\n hint: `${ANSWER_HINT} ${address} is a contract address, not a ticker: ${ADDRESS_INPUT_HINT}. Send no token lookup for it.`,\n })\n }\n if (unsafeLiteral(symbol)) {\n return errorResult(\n 'invalid_symbol: a symbol holds no double quote, backslash or control character. Send the ticker or the name as plain text.'\n )\n }\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No token read was sent: ${unavailable} The lookup has no answer yet, which is not \"no contract\": try again later, or ask the user for the contract. ${NO_WEB}`\n )\n }\n\n let matchedOn: 'symbol' | 'name' = 'symbol'\n let read = await readAssets(deps, network, 'symbol', symbol)\n if (read.kind === 'rows' && read.rows.length === 0) {\n matchedOn = 'name'\n read = await readAssets(deps, network, 'name', symbol)\n }\n if (read.kind === 'failed') {\n return errorResult(\n `The token read failed: ${read.text} This is not \"no contract\": send the same lookup again once, or ask the user for the contract. ${NO_WEB}`\n )\n }\n if (read.kind === 'not_served') {\n return textResult({\n ...base,\n matched_on: null,\n candidates: [],\n total: 0,\n truncated: false,\n hint:\n `${ANSWER_HINT} This Chain Insights server does not serve the token lookup yet (${read.refusal.code}). ` +\n `That is not \"no contract carries ${symbol}\": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`,\n })\n }\n\n const total = read.rows.length\n const candidates = read.rows\n .slice(0, CANDIDATES_MAX)\n .map(candidateOf)\n .filter((candidate): candidate is TokenCandidate => candidate !== null)\n const creatorsNotRead =\n candidates.length > 0 ? await readCreators(deps, network, candidates) : null\n const result = {\n ...base,\n matched_on: candidates.length > 0 ? matchedOn : null,\n candidates,\n total,\n truncated: total > CANDIDATES_MAX,\n }\n return textResult({ ...result, hint: hintFor(result, creatorsNotRead) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAa,yBAAyB;AACtC,MAAa,2BAA2B;AACxC,MAAa,0BAA0B;AACvC,MAAa,gCACX;AAKF,MAAa,gCAAgC;CAC3C,cAAc;CACd,gBAAgB;CAChB,eAAe;AACjB;;AAIA,MAAa,iBAAiB;AAC9B,MAAa,YAAY;;AAEzB,MAAa,oBAAoB;AACjC,MAAa,aAAa;AAE1B,MAAa,qBAAqB;AAuDlC,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAItB,SAAS,cAAc,MAA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b,GAAG;EACH,YAAY,WAAW,SAAS,IAAI,YAAY;EAChD;EACA;EACA,WAAW,QAAQ;CACrB;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,eAAe;CAAE,CAAC;AACzE"}
|
|
@@ -1,14 +1,9 @@
|
|
|
1
|
-
const require_rolldown_runtime = require("./rolldown-runtime-
|
|
2
|
-
const require_print_result = require("./print-result-
|
|
3
|
-
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
|
|
2
|
+
const require_print_result = require("./print-result-BYppJlUi.cjs");
|
|
3
|
+
// src/mcp/tool-visibility.ts
|
|
4
4
|
var tool_visibility_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
5
|
-
HIDDEN_REMOTE_TOOL_NAMES: () => HIDDEN_REMOTE_TOOL_NAMES,
|
|
6
|
-
PUBLIC_MCP_TOOL_ALLOWED_ARGS: () => PUBLIC_MCP_TOOL_ALLOWED_ARGS,
|
|
7
|
-
PUBLIC_MCP_TOOL_REQUIRED_ARGS: () => PUBLIC_MCP_TOOL_REQUIRED_ARGS,
|
|
8
5
|
assertPublicMcpToolName: () => assertPublicMcpToolName,
|
|
9
6
|
formatMcpCallError: () => formatMcpCallError,
|
|
10
|
-
isAppOnlyTool: () => isAppOnlyTool,
|
|
11
|
-
isHiddenRemoteToolName: () => isHiddenRemoteToolName,
|
|
12
7
|
validatePublicMcpToolArguments: () => validatePublicMcpToolArguments,
|
|
13
8
|
visibleRemoteTools: () => visibleRemoteTools
|
|
14
9
|
});
|
|
@@ -53,7 +48,8 @@ const PUBLIC_MCP_TOOL_ALLOWED_ARGS = {
|
|
|
53
48
|
"name",
|
|
54
49
|
"address",
|
|
55
50
|
"pools"
|
|
56
|
-
]
|
|
51
|
+
],
|
|
52
|
+
meta_token_lookup: ["network", "symbol"]
|
|
57
53
|
};
|
|
58
54
|
function isHiddenRemoteToolName(name) {
|
|
59
55
|
return HIDDEN_REMOTE_TOOL_NAMES.has(name);
|
|
@@ -89,7 +85,6 @@ function validatePublicMcpToolArguments(name, args) {
|
|
|
89
85
|
if (unsupportedArgs.length === 0) return;
|
|
90
86
|
throw new Error([`Unsupported argument${unsupportedArgs.length === 1 ? "" : "s"} for ${name}: ${unsupportedArgs.join(", ")}.`, `Allowed arguments: ${allowedArgs.join(", ")}.`].join(" "));
|
|
91
87
|
}
|
|
92
|
-
//#endregion
|
|
93
88
|
Object.defineProperty(exports, "HIDDEN_REMOTE_TOOL_NAMES", {
|
|
94
89
|
enumerable: true,
|
|
95
90
|
get: function() {
|
|
@@ -1,14 +1,9 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
import { n as formatMcpToolError, t as McpToolError } from "./print-result-
|
|
3
|
-
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
+
import { n as formatMcpToolError, t as McpToolError } from "./print-result-IFARsMnL.mjs";
|
|
3
|
+
// src/mcp/tool-visibility.ts
|
|
4
4
|
var tool_visibility_exports = /* @__PURE__ */ __exportAll({
|
|
5
|
-
HIDDEN_REMOTE_TOOL_NAMES: () => HIDDEN_REMOTE_TOOL_NAMES,
|
|
6
|
-
PUBLIC_MCP_TOOL_ALLOWED_ARGS: () => PUBLIC_MCP_TOOL_ALLOWED_ARGS,
|
|
7
|
-
PUBLIC_MCP_TOOL_REQUIRED_ARGS: () => PUBLIC_MCP_TOOL_REQUIRED_ARGS,
|
|
8
5
|
assertPublicMcpToolName: () => assertPublicMcpToolName,
|
|
9
6
|
formatMcpCallError: () => formatMcpCallError,
|
|
10
|
-
isAppOnlyTool: () => isAppOnlyTool,
|
|
11
|
-
isHiddenRemoteToolName: () => isHiddenRemoteToolName,
|
|
12
7
|
validatePublicMcpToolArguments: () => validatePublicMcpToolArguments,
|
|
13
8
|
visibleRemoteTools: () => visibleRemoteTools
|
|
14
9
|
});
|
|
@@ -53,7 +48,8 @@ const PUBLIC_MCP_TOOL_ALLOWED_ARGS = {
|
|
|
53
48
|
"name",
|
|
54
49
|
"address",
|
|
55
50
|
"pools"
|
|
56
|
-
]
|
|
51
|
+
],
|
|
52
|
+
meta_token_lookup: ["network", "symbol"]
|
|
57
53
|
};
|
|
58
54
|
function isHiddenRemoteToolName(name) {
|
|
59
55
|
return HIDDEN_REMOTE_TOOL_NAMES.has(name);
|
|
@@ -89,7 +85,6 @@ function validatePublicMcpToolArguments(name, args) {
|
|
|
89
85
|
if (unsupportedArgs.length === 0) return;
|
|
90
86
|
throw new Error([`Unsupported argument${unsupportedArgs.length === 1 ? "" : "s"} for ${name}: ${unsupportedArgs.join(", ")}.`, `Allowed arguments: ${allowedArgs.join(", ")}.`].join(" "));
|
|
91
87
|
}
|
|
92
|
-
//#endregion
|
|
93
88
|
export { tool_visibility_exports as a, isAppOnlyTool as i, PUBLIC_MCP_TOOL_ALLOWED_ARGS as n, PUBLIC_MCP_TOOL_REQUIRED_ARGS as r, HIDDEN_REMOTE_TOOL_NAMES as t };
|
|
94
89
|
|
|
95
|
-
//# sourceMappingURL=tool-visibility-
|
|
90
|
+
//# sourceMappingURL=tool-visibility-Dy3psowS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-visibility-Dy3psowS.mjs","names":[],"sources":["../src/mcp/tool-visibility.ts"],"sourcesContent":["import { McpToolError, formatMcpToolError } from './print-result.js'\n\nexport const HIDDEN_REMOTE_TOOL_NAMES = new Set([\n 'topup',\n 'address_risk',\n // Hidden until its verdict is fixed: never listed, never registered, never\n // called through the proxy. The remote graph endpoint does not serve it.\n 'aml_address_risk',\n 'trace_victim_funds',\n 'trace_suspect_funds',\n 'trace_deposit_sources',\n 'trace_funds',\n 'track_funds',\n // Retired tools: never exposed publicly. Built by concatenation so the\n // retired names do not appear as literals in this file.\n ['aml_trace_victim', '_funds'].join(''),\n ['aml_trace_suspect', '_funds'].join(''),\n ['aml_trace_deposit', '_sources'].join(''),\n 'network_capabilities',\n 'usage_status',\n 'subscription_status',\n 'balance',\n 'help',\n ['money', '_flows_between_exchanges'].join(''),\n 'address_connection_risk',\n])\n\nexport const PUBLIC_MCP_TOOL_REQUIRED_ARGS: Record<string, string[]> = {\n graph_query: ['query', 'network'],\n graph_query_batch: ['network', 'queries'],\n}\n\n// normalizeRemoteToolArguments FILTERS pass-through arguments to this list, so\n// an argument that is missing here is silently STRIPPED and the caller gets a\n// default-bounded result with no error and no warning. `time_scope` shipped\n// broken for exactly this reason. Every tunable search bound below\n// (per_address_limit, row_limit) must therefore be listed the moment it\n// appears on a tool schema, and is covered end-to-end through the proxy in\n// tests/mcp-proxy.test.ts.\nexport const PUBLIC_MCP_TOOL_ALLOWED_ARGS: Record<string, string[]> = {\n // `time_scope` narrows a `USE topology` query to a temporal-shard subset\n graph_query: ['query', 'network', 'time_scope'],\n graph_query_batch: ['network', 'queries', 'per_query_timeout_seconds', 'time_scope'],\n // A local tool of the proxy (src/mcp/dex-tool.ts): the exchange by name.\n meta_dex_lookup: ['network', 'name', 'address', 'pools'],\n // A local tool of the proxy (src/mcp/token-lookup.ts): the contracts of a ticker.\n meta_token_lookup: ['network', 'symbol'],\n}\n\nexport function isHiddenRemoteToolName(name: string): boolean {\n return HIDDEN_REMOTE_TOOL_NAMES.has(name)\n}\n\n/**\n * True for an MCP Apps tool only a view may call: `_meta.ui.visibility` is set\n * and does not include \"model\" (for example graph_expand, visibility [\"app\"]).\n * Such a tool never appears in a tool list built for the model or the CLI.\n */\nexport function isAppOnlyTool(tool: { _meta?: Record<string, unknown> }): boolean {\n const ui = tool._meta?.ui\n if (!ui || typeof ui !== 'object' || Array.isArray(ui)) return false\n const visibility = (ui as Record<string, unknown>).visibility\n return Array.isArray(visibility) && !visibility.includes('model')\n}\n\nexport function visibleRemoteTools<T extends { name: string; _meta?: Record<string, unknown> }>(\n tools: T[]\n): T[] {\n return tools.filter((tool) => !isHiddenRemoteToolName(tool.name) && !isAppOnlyTool(tool))\n}\n\nexport function assertPublicMcpToolName(name: string): void {\n if (!isHiddenRemoteToolName(name)) return\n const replacement =\n name === 'network_capabilities'\n ? ' Use meta_network_capabilities instead.'\n : name === 'usage_status'\n ? ' Use meta_usage_status instead.'\n : name === 'subscription_status'\n ? ' Use meta_subscription_status instead.'\n : name === 'balance'\n ? ' Use wallet_balance instead.'\n : name === 'help'\n ? ' Use meta_help instead.'\n : ''\n throw new Error(`MCP tool '${name}' is not exposed by Chain Insights.${replacement}`)\n}\n\nexport function formatMcpCallError(tool: string, err: unknown): string {\n // A tool error with an envelope is the server's own answer: its text, then the\n // line of its error_detail. It is never matched against the unknown-tool\n // pattern below. A tool error with no envelope keeps the old reading, because\n // a server can answer an unknown tool as an error reply.\n if (err instanceof McpToolError && err.errorDetail) return formatMcpToolError(err)\n const message = err instanceof Error ? err.message : String(err)\n if (/\\bunknown tool\\b|\\btool\\b.*\\bnot found\\b/i.test(message)) {\n return `Unknown MCP tool \"${tool}\". Run \\`cia mcp tools --refresh\\` to list available tools.`\n }\n return message\n}\n\nexport function validatePublicMcpToolArguments(name: string, args: Record<string, unknown>): void {\n const allowedArgs = PUBLIC_MCP_TOOL_ALLOWED_ARGS[name]\n if (!allowedArgs) return\n\n const unsupportedArgs = Object.keys(args).filter((argName) => !allowedArgs.includes(argName))\n if (unsupportedArgs.length === 0) return\n\n throw new Error(\n [\n `Unsupported argument${unsupportedArgs.length === 1 ? '' : 's'} for ${name}: ${unsupportedArgs.join(', ')}.`,\n `Allowed arguments: ${allowedArgs.join(', ')}.`,\n ].join(' ')\n )\n}\n"],"mappings":";;;;;;;;;AAEA,MAAa,2CAA2B,IAAI,IAAI;CAC9C;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CAGA,CAAC,oBAAoB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACtC,CAAC,qBAAqB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACvC,CAAC,qBAAqB,UAAU,CAAC,CAAC,KAAK,EAAE;CACzC;CACA;CACA;CACA;CACA;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Ac,MAAqC;CAChG,MAAM,cAAc,6BAA6B;CACjD,IAAI,CAAC,aAAa;CAElB,MAAM,kBAAkB,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,YAAY,CAAC,YAAY,SAAS,OAAO,CAAC;CAC5F,IAAI,gBAAgB,WAAW,GAAG;CAElC,MAAM,IAAI,MACR,CACE,uBAAuB,gBAAgB,WAAW,IAAI,KAAK,IAAI,OAAO,KAAK,IAAI,gBAAgB,KAAK,IAAI,EAAE,IAC1G,sBAAsB,YAAY,KAAK,IAAI,EAAE,EAC/C,CAAC,CAAC,KAAK,GAAG,CACZ;AACF"}
|
|
@@ -1,34 +1,20 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
+
import { i as normalizeWalletPrivateKey, t as decryptKey } from "./wallet-B1M0HdQh.mjs";
|
|
3
|
+
import { r as isPrivateKeyPublic, t as PUBLIC_KEY_WALLET_TEXT } from "./known-keys-BbuzCZOW.mjs";
|
|
4
4
|
import { privateKeyToAccount } from "viem/accounts";
|
|
5
5
|
import { createPublicClient, createWalletClient, formatEther, formatUnits, http, parseUnits } from "viem";
|
|
6
6
|
import { base } from "viem/chains";
|
|
7
|
-
|
|
7
|
+
// src/wallet/tools.ts
|
|
8
8
|
var tools_exports = /* @__PURE__ */ __exportAll({
|
|
9
|
-
BASE_CHAIN_ID: () => BASE_CHAIN_ID,
|
|
10
|
-
DEFAULT_BASE_RPC_URL: () => DEFAULT_BASE_RPC_URL,
|
|
11
|
-
DEFAULT_MAX_AUTO_APPROVAL_UNITS: () => DEFAULT_MAX_AUTO_APPROVAL_UNITS,
|
|
12
|
-
DEFAULT_PAYMENT_APPROVAL_UNITS: () => DEFAULT_PAYMENT_APPROVAL_UNITS,
|
|
13
|
-
PERMIT2_ADDRESS: () => PERMIT2_ADDRESS,
|
|
14
|
-
PUBLIC_BASE_RPC_URLS: () => PUBLIC_BASE_RPC_URLS,
|
|
15
|
-
USDC_ADDRESS: () => USDC_ADDRESS,
|
|
16
|
-
approvePaymentAllowance: () => approvePaymentAllowance,
|
|
17
9
|
assertWalletKeyNotPublic: () => assertWalletKeyNotPublic,
|
|
18
10
|
buildTopupInfo: () => buildTopupInfo,
|
|
19
|
-
formatWalletBalance: () => formatWalletBalance,
|
|
20
11
|
formatWalletBalanceResult: () => formatWalletBalanceResult,
|
|
21
12
|
formatWalletReadiness: () => formatWalletReadiness,
|
|
22
|
-
getBalanceEth: () => getBalanceEth,
|
|
23
|
-
getBalanceUsdc: () => getBalanceUsdc,
|
|
24
|
-
getPaymentApprovalUnits: () => getPaymentApprovalUnits,
|
|
25
13
|
getWalletAccount: () => getWalletAccount,
|
|
26
14
|
getWalletBalanceResult: () => getWalletBalanceResult,
|
|
27
15
|
getWalletBalanceText: () => getWalletBalanceText,
|
|
28
|
-
getWalletReadiness: () => getWalletReadiness,
|
|
29
16
|
parsePaymentApprovalUnits: () => parsePaymentApprovalUnits,
|
|
30
|
-
prepareWalletForPaidCalls: () => prepareWalletForPaidCalls
|
|
31
|
-
resolveMaxAutoApprovalUnits: () => resolveMaxAutoApprovalUnits
|
|
17
|
+
prepareWalletForPaidCalls: () => prepareWalletForPaidCalls
|
|
32
18
|
});
|
|
33
19
|
const BASE_CHAIN_ID = 8453;
|
|
34
20
|
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
|
|
@@ -351,7 +337,6 @@ function buildTopupInfo(address, topupUrl) {
|
|
|
351
337
|
...topupUrl ? { topup_url: topupUrl } : {}
|
|
352
338
|
};
|
|
353
339
|
}
|
|
354
|
-
//#endregion
|
|
355
340
|
export { formatWalletBalanceResult as a, getWalletAccount as c, prepareWalletForPaidCalls as d, resolveMaxAutoApprovalUnits as f, formatWalletBalance as i, getWalletBalanceResult as l, USDC_ADDRESS as n, getBalanceEth as o, tools_exports as p, buildTopupInfo as r, getBalanceUsdc as s, PERMIT2_ADDRESS as t, getWalletBalanceText as u };
|
|
356
341
|
|
|
357
|
-
//# sourceMappingURL=tools-
|
|
342
|
+
//# sourceMappingURL=tools-6pZo4h_p.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools-D9ep9E7Q.mjs","names":[],"sources":["../src/wallet/tools.ts"],"sourcesContent":["import {\n createPublicClient,\n createWalletClient,\n formatEther,\n formatUnits,\n http,\n parseUnits,\n type Address,\n type Hex,\n} from 'viem'\nimport { base } from 'viem/chains'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { decryptKey, normalizeWalletPrivateKey } from './index.js'\nimport { PUBLIC_KEY_WALLET_TEXT, isPrivateKeyPublic } from './known-keys.js'\n\nexport const BASE_CHAIN_ID = 8453\nexport const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as const\nexport const PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3' as const\nexport const DEFAULT_BASE_RPC_URL = 'https://mainnet.base.org'\nexport const DEFAULT_PAYMENT_APPROVAL_UNITS = 1_000_000n\n// Ceiling for approvals triggered automatically by a 402 `allowance_required`\n// response. The endpoint dictates the amount, so it must be bounded: a\n// malicious or compromised endpoint could otherwise demand — and have the\n// client silently sign — an allowance up to the wallet's entire balance.\n// Override with CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC; larger one-off\n// allowances go through the explicit `wallet ready --payment-usdc` path.\nexport const DEFAULT_MAX_AUTO_APPROVAL_UNITS = 10_000_000n\nexport const PUBLIC_BASE_RPC_URLS = [\n DEFAULT_BASE_RPC_URL,\n 'https://base-rpc.publicnode.com',\n 'https://base.drpc.org',\n 'https://1rpc.io/base',\n] as const\n\nconst USDC_ABI = [\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n] as const\n\nexport interface PaymentWalletAccount {\n address: Address\n privateKey: Hex\n /** True when the key is public (src/wallet/known-keys.ts): no money path may use it. */\n keyIsPublic?: boolean\n}\n\nexport interface TopupInfo {\n wallet_address: string\n network: 'Base'\n chain_id: typeof BASE_CHAIN_ID\n token: 'USDC'\n token_contract: typeof USDC_ADDRESS\n topup_url?: string\n}\n\nexport interface WalletReadiness {\n address: Address\n balanceUsdc: string\n balanceEth: string\n paymentApprovalUsdc: string\n paymentApprovalUnits: bigint\n minimumApprovalUnits: bigint\n hasUsdc: boolean | null\n hasGas: boolean | null\n hasPaymentApproval: boolean\n needsPaymentApproval: boolean\n ready: boolean\n nextSteps: string[]\n}\n\nexport interface PaymentApprovalResult {\n status: 'already_ready' | 'approved'\n txHash?: Hex\n paymentApprovalUnits: bigint\n minimumApprovalUnits: bigint\n}\n\nexport interface PrepareWalletResult {\n readiness: WalletReadiness\n approval?: PaymentApprovalResult\n}\n\nexport interface PrepareWalletOptions {\n account?: PaymentWalletAccount\n minimumApprovalUnits?: bigint\n // When set, refuse (before any on-chain action) to approve more than this\n // many USDC units. Callers that escalate to an endpoint-dictated amount must\n // pass this so an untrusted endpoint cannot drive an unbounded approval.\n maxApprovalUnits?: bigint\n approve?: boolean\n rpcUrl?: string\n}\n\n/**\n * Resolves the automatic payment-approval ceiling, honoring the\n * CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC override (validated as a positive USDC\n * amount) and otherwise returning DEFAULT_MAX_AUTO_APPROVAL_UNITS.\n */\nexport function resolveMaxAutoApprovalUnits(env: NodeJS.ProcessEnv = process.env): bigint {\n const raw = env['CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC']?.trim()\n if (!raw) return DEFAULT_MAX_AUTO_APPROVAL_UNITS\n return parsePaymentApprovalUnits(raw)\n}\n\nexport interface WalletBalanceFacts {\n address: Address\n payment_network: 'base'\n payment_network_display: 'Base'\n chain_id: typeof BASE_CHAIN_ID\n token: 'USDC'\n token_balance: string\n gas_token: 'ETH'\n gas_balance?: string\n}\n\nexport interface WalletBalanceResult {\n schema: 'chain-insights.result.v1'\n tool: 'wallet_balance'\n hint: null\n facts: {\n wallet: WalletBalanceFacts\n }\n}\n\n/**\n * The stored wallet. A stored public key still loads, so `cia wallet address`\n * and the replace path keep working, but it comes back flagged and every money\n * path refuses it (assertWalletKeyNotPublic).\n */\nexport async function getWalletAccount(): Promise<PaymentWalletAccount> {\n const privateKey = normalizeWalletPrivateKey(await decryptKey()) as Hex\n const account = privateKeyToAccount(privateKey)\n return isPrivateKeyPublic(privateKey)\n ? { address: account.address, privateKey, keyIsPublic: true }\n : { address: account.address, privateKey }\n}\n\n/** Refuses a wallet whose key is public before anything is funded or sent. */\nexport function assertWalletKeyNotPublic(account: Pick<PaymentWalletAccount, 'keyIsPublic'>): void {\n if (account.keyIsPublic === true) throw new Error(PUBLIC_KEY_WALLET_TEXT)\n}\n\nfunction baseRpcUrls(rpcUrl = process.env['BASE_RPC_URL']): string[] {\n return [\n ...(rpcUrl ? [rpcUrl] : []),\n ...PUBLIC_BASE_RPC_URLS.filter((fallbackUrl) => fallbackUrl !== rpcUrl),\n ]\n}\n\nexport async function getBalanceUsdc(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<string> {\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const client = createPublicClient({\n chain: base,\n transport: http(url),\n })\n const balance = await client.readContract({\n address: USDC_ADDRESS,\n abi: USDC_ABI,\n functionName: 'balanceOf',\n args: [address as Address],\n })\n return formatUnits(balance, 6)\n } catch {\n // Try the next public Base RPC endpoint.\n }\n }\n\n return 'unknown'\n}\n\nexport async function getBalanceEth(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<string> {\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const client = createPublicClient({\n chain: base,\n transport: http(url),\n })\n const balance = await client.getBalance({ address: address as Address })\n return formatEther(balance)\n } catch {\n // Try the next public Base RPC endpoint.\n }\n }\n\n return 'unknown'\n}\n\nexport async function getPaymentApprovalUnits(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<bigint | null> {\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const client = createPublicClient({\n chain: base,\n transport: http(url),\n })\n return await client.readContract({\n address: USDC_ADDRESS,\n abi: USDC_ABI,\n functionName: 'allowance',\n args: [address as Address, PERMIT2_ADDRESS],\n })\n } catch {\n // Try the next public Base RPC endpoint.\n }\n }\n\n return null\n}\n\nexport async function getPaymentApprovalUsdc(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<string> {\n const allowance = await getPaymentApprovalUnits(address, rpcUrl)\n return allowance === null ? 'unknown' : formatUnits(allowance, 6)\n}\n\nexport function parsePaymentApprovalUnits(amountUsdc: string): bigint {\n const trimmed = amountUsdc.trim()\n if (!/^\\d+(\\.\\d{1,6})?$/.test(trimmed) || !isPositiveDecimal(trimmed)) {\n throw new Error('Payment setup amount must be a positive USDC value with up to 6 decimals.')\n }\n return parseUnits(trimmed, 6)\n}\n\nfunction isPositiveDecimal(value: string): boolean {\n if (value === 'unknown') return false\n const parsed = Number.parseFloat(value)\n return Number.isFinite(parsed) && parsed > 0\n}\n\nfunction decimalStatus(value: string): boolean | null {\n return value === 'unknown' ? null : isPositiveDecimal(value)\n}\n\nfunction readinessNextSteps(\n readiness: Pick<WalletReadiness, 'hasUsdc' | 'hasGas' | 'needsPaymentApproval'>\n): string[] {\n const nextSteps: string[] = []\n if (readiness.hasUsdc === false) {\n nextSteps.push('Run `cia wallet topup` and send USDC on Base to this wallet.')\n }\n if (readiness.hasUsdc === null) {\n nextSteps.push(\n 'Base USDC balance could not be confirmed; retry or set BASE_RPC_URL to a working Base RPC endpoint.'\n )\n }\n if (readiness.needsPaymentApproval && readiness.hasGas === false) {\n nextSteps.push('Add a small amount of ETH on Base for the one-time payment setup gas.')\n }\n if (readiness.needsPaymentApproval && readiness.hasGas !== false) {\n nextSteps.push('Run `cia wallet ready` to finish the one-time payment setup.')\n }\n if (readiness.hasGas === null) {\n nextSteps.push(\n 'Base ETH gas balance could not be confirmed; retry or set BASE_RPC_URL to a working Base RPC endpoint.'\n )\n }\n return nextSteps\n}\n\nfunction buildWalletReadiness(params: {\n address: Address\n balanceUsdc: string\n balanceEth: string\n paymentApprovalUnits: bigint | null\n minimumApprovalUnits: bigint\n}): WalletReadiness {\n const paymentApprovalUnits = params.paymentApprovalUnits ?? 0n\n const hasUsdc = decimalStatus(params.balanceUsdc)\n const hasGas = decimalStatus(params.balanceEth)\n const hasPaymentApproval = paymentApprovalUnits >= params.minimumApprovalUnits\n const needsPaymentApproval = !hasPaymentApproval\n const ready = hasUsdc !== false && hasPaymentApproval\n const readiness = {\n address: params.address,\n balanceUsdc: params.balanceUsdc,\n balanceEth: params.balanceEth,\n paymentApprovalUsdc:\n params.paymentApprovalUnits === null ? 'unknown' : formatUnits(paymentApprovalUnits, 6),\n paymentApprovalUnits,\n minimumApprovalUnits: params.minimumApprovalUnits,\n hasUsdc,\n hasGas,\n hasPaymentApproval,\n needsPaymentApproval,\n ready,\n nextSteps: [],\n }\n return {\n ...readiness,\n nextSteps: readinessNextSteps(readiness),\n }\n}\n\nexport async function getWalletReadiness(\n account?: PaymentWalletAccount,\n minimumApprovalUnits = DEFAULT_PAYMENT_APPROVAL_UNITS\n): Promise<WalletReadiness> {\n const wallet = account ?? (await getWalletAccount())\n const [balanceUsdc, balanceEth, paymentApprovalUnits] = await Promise.all([\n getBalanceUsdc(wallet.address),\n getBalanceEth(wallet.address),\n getPaymentApprovalUnits(wallet.address),\n ])\n return buildWalletReadiness({\n address: wallet.address,\n balanceUsdc,\n balanceEth,\n paymentApprovalUnits,\n minimumApprovalUnits,\n })\n}\n\nexport function formatWalletReadiness(\n readiness: WalletReadiness,\n approval?: PaymentApprovalResult\n): string {\n const status = readiness.ready\n ? 'Ready for paid Chain Insights Graph calls'\n : 'Action needed before paid Chain Insights Graph calls'\n const setup = readiness.needsPaymentApproval\n ? `Payment setup: needs one-time setup for up to ${formatUnits(readiness.minimumApprovalUnits, 6)} USDC of paid calls`\n : 'Payment setup: ready'\n const setupCompletedLine =\n approval?.status === 'approved' ? 'Payment setup completed.' : undefined\n return [\n status,\n `Balance: ${readiness.balanceUsdc} USDC`,\n `Gas: ${readiness.balanceEth} ETH on Base`,\n setup,\n setupCompletedLine,\n 'Payment network: Base',\n `Address: ${readiness.address}`,\n ...readiness.nextSteps.map((step) => `Next: ${step}`),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nexport async function approvePaymentAllowance(\n account?: PaymentWalletAccount,\n minimumApprovalUnits = DEFAULT_PAYMENT_APPROVAL_UNITS,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<PaymentApprovalResult> {\n const wallet = account ?? (await getWalletAccount())\n assertWalletKeyNotPublic(wallet)\n const initialApprovalUnits = await getPaymentApprovalUnits(wallet.address, rpcUrl)\n if (initialApprovalUnits !== null && initialApprovalUnits >= minimumApprovalUnits) {\n return {\n status: 'already_ready',\n paymentApprovalUnits: initialApprovalUnits,\n minimumApprovalUnits,\n }\n }\n\n const clientAccount = privateKeyToAccount(wallet.privateKey)\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const publicClient = createPublicClient({ chain: base, transport: http(url) })\n const walletClient = createWalletClient({\n account: clientAccount,\n chain: base,\n transport: http(url),\n })\n const txHash = await walletClient.writeContract({\n address: USDC_ADDRESS,\n abi: USDC_ABI,\n functionName: 'approve',\n args: [PERMIT2_ADDRESS, minimumApprovalUnits],\n })\n const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash })\n if (receipt.status === 'reverted') {\n throw new Error(`Payment setup transaction reverted: ${txHash}`)\n }\n const paymentApprovalUnits = await getPaymentApprovalUnits(wallet.address, url)\n return {\n status: 'approved',\n txHash,\n paymentApprovalUnits: paymentApprovalUnits ?? minimumApprovalUnits,\n minimumApprovalUnits,\n }\n } catch (err) {\n if (url === baseRpcUrls(rpcUrl).at(-1)) throw err\n }\n }\n\n throw new Error('Unable to submit payment setup transaction on Base.')\n}\n\nexport async function prepareWalletForPaidCalls(\n options: PrepareWalletOptions = {}\n): Promise<PrepareWalletResult> {\n const minimumApprovalUnits = options.minimumApprovalUnits ?? DEFAULT_PAYMENT_APPROVAL_UNITS\n if (options.maxApprovalUnits !== undefined && minimumApprovalUnits > options.maxApprovalUnits) {\n const requested = formatUnits(minimumApprovalUnits, 6)\n throw new Error(\n `Requested payment approval of ${requested} USDC exceeds the automatic payment-approval ceiling ` +\n `of ${formatUnits(options.maxApprovalUnits, 6)} USDC. If this amount is expected, approve it deliberately with ` +\n `\\`cia wallet ready --payment-usdc ${requested}\\`, or raise the ceiling via ` +\n `CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC.`\n )\n }\n const wallet = options.account ?? (await getWalletAccount())\n const readiness = await getWalletReadiness(wallet, minimumApprovalUnits)\n\n if (!readiness.needsPaymentApproval) {\n return {\n readiness,\n approval: {\n status: 'already_ready',\n paymentApprovalUnits: readiness.paymentApprovalUnits,\n minimumApprovalUnits,\n },\n }\n }\n if (options.approve === false || readiness.hasGas === false) {\n return { readiness }\n }\n\n const approval = await approvePaymentAllowance(wallet, minimumApprovalUnits, options.rpcUrl)\n const updatedReadiness = buildWalletReadiness({\n address: wallet.address,\n balanceUsdc: readiness.balanceUsdc,\n balanceEth: readiness.balanceEth,\n paymentApprovalUnits: approval.paymentApprovalUnits,\n minimumApprovalUnits,\n })\n return { readiness: updatedReadiness, approval }\n}\n\nexport function formatWalletBalance(\n address: string,\n balanceUsdc: string,\n balanceEth?: string\n): string {\n return [\n `Payment wallet: ${address}`,\n `USDC on Base: ${balanceUsdc}`,\n balanceEth === undefined ? undefined : `Gas on Base: ${balanceEth} ETH`,\n 'Payment network: Base',\n 'Base ETH is used only for one-time payment setup gas.',\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nexport async function getWalletBalanceResult(\n account?: PaymentWalletAccount\n): Promise<WalletBalanceResult> {\n const wallet = account ?? (await getWalletAccount())\n const [balanceUsdc, balanceEth] = await Promise.all([\n getBalanceUsdc(wallet.address),\n getBalanceEth(wallet.address),\n ])\n return {\n schema: 'chain-insights.result.v1',\n tool: 'wallet_balance',\n hint: null,\n facts: {\n wallet: {\n address: wallet.address,\n payment_network: 'base',\n payment_network_display: 'Base',\n chain_id: BASE_CHAIN_ID,\n token: 'USDC',\n token_balance: balanceUsdc,\n gas_token: 'ETH',\n ...(balanceEth === undefined ? {} : { gas_balance: balanceEth }),\n },\n },\n }\n}\n\nexport function formatWalletBalanceResult(result: WalletBalanceResult): string {\n const wallet = result.facts.wallet\n return formatWalletBalance(wallet.address, wallet.token_balance, wallet.gas_balance)\n}\n\nexport async function getWalletBalanceText(account?: PaymentWalletAccount): Promise<string> {\n return formatWalletBalanceResult(await getWalletBalanceResult(account))\n}\n\nexport function buildTopupInfo(address: string, topupUrl?: string): TopupInfo {\n return {\n wallet_address: address,\n network: 'Base',\n chain_id: BASE_CHAIN_ID,\n token: 'USDC',\n token_contract: USDC_ADDRESS,\n ...(topupUrl ? { topup_url: topupUrl } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,gBAAgB;AAC7B,MAAa,eAAe;AAC5B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,iCAAiC;AAO9C,MAAa,kCAAkC;AAC/C,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;AACF;AAEA,MAAM,WAAW;CACf;EACE,MAAM;EACN,MAAM;EACN,iBAAiB;EACjB,QAAQ,CAAC;GAAE,MAAM;GA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,yBAAyB;GACzB,UAAU;GACV,OAAO;GACP,eAAe;GACf,WAAW;GACX,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,WAAW;EAChE,EACF;CACF;AACF;AAEA,SAAgB,0BAA0B,QAAqC;CAC7E,MAAM,SAAS,OAAO,MAAM;CAC5B,OAAO,oBAAoB,OAAO,SAAS,OAAO,eAAe,OAAO,WAAW;AACrF;AAEA,eAAsB,qBAAqB,SAAiD;CAC1F,OAAO,0BAA0B,MAAM,uBAAuB,OAAO,CAAC;AACxE;AAEA,SAAgB,eAAe,SAAiB,UAA8B;CAC5E,OAAO;EACL,gBAAgB;EAChB,SAAS;EACT,UAAU;EACV,OAAO;EACP,gBAAgB;EAChB,GAAI,WAAW,EAAE,WAAW,SAAS,IAAI,CAAC;CAC5C;AACF"}
|
|
1
|
+
{"version":3,"file":"tools-6pZo4h_p.mjs","names":[],"sources":["../src/wallet/tools.ts"],"sourcesContent":["import {\n createPublicClient,\n createWalletClient,\n formatEther,\n formatUnits,\n http,\n parseUnits,\n type Address,\n type Hex,\n} from 'viem'\nimport { base } from 'viem/chains'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { decryptKey, normalizeWalletPrivateKey } from './index.js'\nimport { PUBLIC_KEY_WALLET_TEXT, isPrivateKeyPublic } from './known-keys.js'\n\nexport const BASE_CHAIN_ID = 8453\nexport const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as const\nexport const PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3' as const\nexport const DEFAULT_BASE_RPC_URL = 'https://mainnet.base.org'\nexport const DEFAULT_PAYMENT_APPROVAL_UNITS = 1_000_000n\n// Ceiling for approvals triggered automatically by a 402 `allowance_required`\n// response. The endpoint dictates the amount, so it must be bounded: a\n// malicious or compromised endpoint could otherwise demand — and have the\n// client silently sign — an allowance up to the wallet's entire balance.\n// Override with CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC; larger one-off\n// allowances go through the explicit `wallet ready --payment-usdc` path.\nexport const DEFAULT_MAX_AUTO_APPROVAL_UNITS = 10_000_000n\nexport const PUBLIC_BASE_RPC_URLS = [\n DEFAULT_BASE_RPC_URL,\n 'https://base-rpc.publicnode.com',\n 'https://base.drpc.org',\n 'https://1rpc.io/base',\n] as const\n\nconst USDC_ABI = [\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n] as const\n\nexport interface PaymentWalletAccount {\n address: Address\n privateKey: Hex\n /** True when the key is public (src/wallet/known-keys.ts): no money path may use it. */\n keyIsPublic?: boolean\n}\n\nexport interface TopupInfo {\n wallet_address: string\n network: 'Base'\n chain_id: typeof BASE_CHAIN_ID\n token: 'USDC'\n token_contract: typeof USDC_ADDRESS\n topup_url?: string\n}\n\nexport interface WalletReadiness {\n address: Address\n balanceUsdc: string\n balanceEth: string\n paymentApprovalUsdc: string\n paymentApprovalUnits: bigint\n minimumApprovalUnits: bigint\n hasUsdc: boolean | null\n hasGas: boolean | null\n hasPaymentApproval: boolean\n needsPaymentApproval: boolean\n ready: boolean\n nextSteps: string[]\n}\n\nexport interface PaymentApprovalResult {\n status: 'already_ready' | 'approved'\n txHash?: Hex\n paymentApprovalUnits: bigint\n minimumApprovalUnits: bigint\n}\n\nexport interface PrepareWalletResult {\n readiness: WalletReadiness\n approval?: PaymentApprovalResult\n}\n\nexport interface PrepareWalletOptions {\n account?: PaymentWalletAccount\n minimumApprovalUnits?: bigint\n // When set, refuse (before any on-chain action) to approve more than this\n // many USDC units. Callers that escalate to an endpoint-dictated amount must\n // pass this so an untrusted endpoint cannot drive an unbounded approval.\n maxApprovalUnits?: bigint\n approve?: boolean\n rpcUrl?: string\n}\n\n/**\n * Resolves the automatic payment-approval ceiling, honoring the\n * CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC override (validated as a positive USDC\n * amount) and otherwise returning DEFAULT_MAX_AUTO_APPROVAL_UNITS.\n */\nexport function resolveMaxAutoApprovalUnits(env: NodeJS.ProcessEnv = process.env): bigint {\n const raw = env['CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC']?.trim()\n if (!raw) return DEFAULT_MAX_AUTO_APPROVAL_UNITS\n return parsePaymentApprovalUnits(raw)\n}\n\nexport interface WalletBalanceFacts {\n address: Address\n payment_network: 'base'\n payment_network_display: 'Base'\n chain_id: typeof BASE_CHAIN_ID\n token: 'USDC'\n token_balance: string\n gas_token: 'ETH'\n gas_balance?: string\n}\n\nexport interface WalletBalanceResult {\n schema: 'chain-insights.result.v1'\n tool: 'wallet_balance'\n hint: null\n facts: {\n wallet: WalletBalanceFacts\n }\n}\n\n/**\n * The stored wallet. A stored public key still loads, so `cia wallet address`\n * and the replace path keep working, but it comes back flagged and every money\n * path refuses it (assertWalletKeyNotPublic).\n */\nexport async function getWalletAccount(): Promise<PaymentWalletAccount> {\n const privateKey = normalizeWalletPrivateKey(await decryptKey()) as Hex\n const account = privateKeyToAccount(privateKey)\n return isPrivateKeyPublic(privateKey)\n ? { address: account.address, privateKey, keyIsPublic: true }\n : { address: account.address, privateKey }\n}\n\n/** Refuses a wallet whose key is public before anything is funded or sent. */\nexport function assertWalletKeyNotPublic(account: Pick<PaymentWalletAccount, 'keyIsPublic'>): void {\n if (account.keyIsPublic === true) throw new Error(PUBLIC_KEY_WALLET_TEXT)\n}\n\nfunction baseRpcUrls(rpcUrl = process.env['BASE_RPC_URL']): string[] {\n return [\n ...(rpcUrl ? [rpcUrl] : []),\n ...PUBLIC_BASE_RPC_URLS.filter((fallbackUrl) => fallbackUrl !== rpcUrl),\n ]\n}\n\nexport async function getBalanceUsdc(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<string> {\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const client = createPublicClient({\n chain: base,\n transport: http(url),\n })\n const balance = await client.readContract({\n address: USDC_ADDRESS,\n abi: USDC_ABI,\n functionName: 'balanceOf',\n args: [address as Address],\n })\n return formatUnits(balance, 6)\n } catch {\n // Try the next public Base RPC endpoint.\n }\n }\n\n return 'unknown'\n}\n\nexport async function getBalanceEth(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<string> {\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const client = createPublicClient({\n chain: base,\n transport: http(url),\n })\n const balance = await client.getBalance({ address: address as Address })\n return formatEther(balance)\n } catch {\n // Try the next public Base RPC endpoint.\n }\n }\n\n return 'unknown'\n}\n\nexport async function getPaymentApprovalUnits(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<bigint | null> {\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const client = createPublicClient({\n chain: base,\n transport: http(url),\n })\n return await client.readContract({\n address: USDC_ADDRESS,\n abi: USDC_ABI,\n functionName: 'allowance',\n args: [address as Address, PERMIT2_ADDRESS],\n })\n } catch {\n // Try the next public Base RPC endpoint.\n }\n }\n\n return null\n}\n\nexport async function getPaymentApprovalUsdc(\n address: Address | string,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<string> {\n const allowance = await getPaymentApprovalUnits(address, rpcUrl)\n return allowance === null ? 'unknown' : formatUnits(allowance, 6)\n}\n\nexport function parsePaymentApprovalUnits(amountUsdc: string): bigint {\n const trimmed = amountUsdc.trim()\n if (!/^\\d+(\\.\\d{1,6})?$/.test(trimmed) || !isPositiveDecimal(trimmed)) {\n throw new Error('Payment setup amount must be a positive USDC value with up to 6 decimals.')\n }\n return parseUnits(trimmed, 6)\n}\n\nfunction isPositiveDecimal(value: string): boolean {\n if (value === 'unknown') return false\n const parsed = Number.parseFloat(value)\n return Number.isFinite(parsed) && parsed > 0\n}\n\nfunction decimalStatus(value: string): boolean | null {\n return value === 'unknown' ? null : isPositiveDecimal(value)\n}\n\nfunction readinessNextSteps(\n readiness: Pick<WalletReadiness, 'hasUsdc' | 'hasGas' | 'needsPaymentApproval'>\n): string[] {\n const nextSteps: string[] = []\n if (readiness.hasUsdc === false) {\n nextSteps.push('Run `cia wallet topup` and send USDC on Base to this wallet.')\n }\n if (readiness.hasUsdc === null) {\n nextSteps.push(\n 'Base USDC balance could not be confirmed; retry or set BASE_RPC_URL to a working Base RPC endpoint.'\n )\n }\n if (readiness.needsPaymentApproval && readiness.hasGas === false) {\n nextSteps.push('Add a small amount of ETH on Base for the one-time payment setup gas.')\n }\n if (readiness.needsPaymentApproval && readiness.hasGas !== false) {\n nextSteps.push('Run `cia wallet ready` to finish the one-time payment setup.')\n }\n if (readiness.hasGas === null) {\n nextSteps.push(\n 'Base ETH gas balance could not be confirmed; retry or set BASE_RPC_URL to a working Base RPC endpoint.'\n )\n }\n return nextSteps\n}\n\nfunction buildWalletReadiness(params: {\n address: Address\n balanceUsdc: string\n balanceEth: string\n paymentApprovalUnits: bigint | null\n minimumApprovalUnits: bigint\n}): WalletReadiness {\n const paymentApprovalUnits = params.paymentApprovalUnits ?? 0n\n const hasUsdc = decimalStatus(params.balanceUsdc)\n const hasGas = decimalStatus(params.balanceEth)\n const hasPaymentApproval = paymentApprovalUnits >= params.minimumApprovalUnits\n const needsPaymentApproval = !hasPaymentApproval\n const ready = hasUsdc !== false && hasPaymentApproval\n const readiness = {\n address: params.address,\n balanceUsdc: params.balanceUsdc,\n balanceEth: params.balanceEth,\n paymentApprovalUsdc:\n params.paymentApprovalUnits === null ? 'unknown' : formatUnits(paymentApprovalUnits, 6),\n paymentApprovalUnits,\n minimumApprovalUnits: params.minimumApprovalUnits,\n hasUsdc,\n hasGas,\n hasPaymentApproval,\n needsPaymentApproval,\n ready,\n nextSteps: [],\n }\n return {\n ...readiness,\n nextSteps: readinessNextSteps(readiness),\n }\n}\n\nexport async function getWalletReadiness(\n account?: PaymentWalletAccount,\n minimumApprovalUnits = DEFAULT_PAYMENT_APPROVAL_UNITS\n): Promise<WalletReadiness> {\n const wallet = account ?? (await getWalletAccount())\n const [balanceUsdc, balanceEth, paymentApprovalUnits] = await Promise.all([\n getBalanceUsdc(wallet.address),\n getBalanceEth(wallet.address),\n getPaymentApprovalUnits(wallet.address),\n ])\n return buildWalletReadiness({\n address: wallet.address,\n balanceUsdc,\n balanceEth,\n paymentApprovalUnits,\n minimumApprovalUnits,\n })\n}\n\nexport function formatWalletReadiness(\n readiness: WalletReadiness,\n approval?: PaymentApprovalResult\n): string {\n const status = readiness.ready\n ? 'Ready for paid Chain Insights Graph calls'\n : 'Action needed before paid Chain Insights Graph calls'\n const setup = readiness.needsPaymentApproval\n ? `Payment setup: needs one-time setup for up to ${formatUnits(readiness.minimumApprovalUnits, 6)} USDC of paid calls`\n : 'Payment setup: ready'\n const setupCompletedLine =\n approval?.status === 'approved' ? 'Payment setup completed.' : undefined\n return [\n status,\n `Balance: ${readiness.balanceUsdc} USDC`,\n `Gas: ${readiness.balanceEth} ETH on Base`,\n setup,\n setupCompletedLine,\n 'Payment network: Base',\n `Address: ${readiness.address}`,\n ...readiness.nextSteps.map((step) => `Next: ${step}`),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nexport async function approvePaymentAllowance(\n account?: PaymentWalletAccount,\n minimumApprovalUnits = DEFAULT_PAYMENT_APPROVAL_UNITS,\n rpcUrl = process.env['BASE_RPC_URL']\n): Promise<PaymentApprovalResult> {\n const wallet = account ?? (await getWalletAccount())\n assertWalletKeyNotPublic(wallet)\n const initialApprovalUnits = await getPaymentApprovalUnits(wallet.address, rpcUrl)\n if (initialApprovalUnits !== null && initialApprovalUnits >= minimumApprovalUnits) {\n return {\n status: 'already_ready',\n paymentApprovalUnits: initialApprovalUnits,\n minimumApprovalUnits,\n }\n }\n\n const clientAccount = privateKeyToAccount(wallet.privateKey)\n for (const url of baseRpcUrls(rpcUrl)) {\n try {\n const publicClient = createPublicClient({ chain: base, transport: http(url) })\n const walletClient = createWalletClient({\n account: clientAccount,\n chain: base,\n transport: http(url),\n })\n const txHash = await walletClient.writeContract({\n address: USDC_ADDRESS,\n abi: USDC_ABI,\n functionName: 'approve',\n args: [PERMIT2_ADDRESS, minimumApprovalUnits],\n })\n const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash })\n if (receipt.status === 'reverted') {\n throw new Error(`Payment setup transaction reverted: ${txHash}`)\n }\n const paymentApprovalUnits = await getPaymentApprovalUnits(wallet.address, url)\n return {\n status: 'approved',\n txHash,\n paymentApprovalUnits: paymentApprovalUnits ?? minimumApprovalUnits,\n minimumApprovalUnits,\n }\n } catch (err) {\n if (url === baseRpcUrls(rpcUrl).at(-1)) throw err\n }\n }\n\n throw new Error('Unable to submit payment setup transaction on Base.')\n}\n\nexport async function prepareWalletForPaidCalls(\n options: PrepareWalletOptions = {}\n): Promise<PrepareWalletResult> {\n const minimumApprovalUnits = options.minimumApprovalUnits ?? DEFAULT_PAYMENT_APPROVAL_UNITS\n if (options.maxApprovalUnits !== undefined && minimumApprovalUnits > options.maxApprovalUnits) {\n const requested = formatUnits(minimumApprovalUnits, 6)\n throw new Error(\n `Requested payment approval of ${requested} USDC exceeds the automatic payment-approval ceiling ` +\n `of ${formatUnits(options.maxApprovalUnits, 6)} USDC. If this amount is expected, approve it deliberately with ` +\n `\\`cia wallet ready --payment-usdc ${requested}\\`, or raise the ceiling via ` +\n `CHAIN_INSIGHTS_MAX_AUTO_APPROVAL_USDC.`\n )\n }\n const wallet = options.account ?? (await getWalletAccount())\n const readiness = await getWalletReadiness(wallet, minimumApprovalUnits)\n\n if (!readiness.needsPaymentApproval) {\n return {\n readiness,\n approval: {\n status: 'already_ready',\n paymentApprovalUnits: readiness.paymentApprovalUnits,\n minimumApprovalUnits,\n },\n }\n }\n if (options.approve === false || readiness.hasGas === false) {\n return { readiness }\n }\n\n const approval = await approvePaymentAllowance(wallet, minimumApprovalUnits, options.rpcUrl)\n const updatedReadiness = buildWalletReadiness({\n address: wallet.address,\n balanceUsdc: readiness.balanceUsdc,\n balanceEth: readiness.balanceEth,\n paymentApprovalUnits: approval.paymentApprovalUnits,\n minimumApprovalUnits,\n })\n return { readiness: updatedReadiness, approval }\n}\n\nexport function formatWalletBalance(\n address: string,\n balanceUsdc: string,\n balanceEth?: string\n): string {\n return [\n `Payment wallet: ${address}`,\n `USDC on Base: ${balanceUsdc}`,\n balanceEth === undefined ? undefined : `Gas on Base: ${balanceEth} ETH`,\n 'Payment network: Base',\n 'Base ETH is used only for one-time payment setup gas.',\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nexport async function getWalletBalanceResult(\n account?: PaymentWalletAccount\n): Promise<WalletBalanceResult> {\n const wallet = account ?? (await getWalletAccount())\n const [balanceUsdc, balanceEth] = await Promise.all([\n getBalanceUsdc(wallet.address),\n getBalanceEth(wallet.address),\n ])\n return {\n schema: 'chain-insights.result.v1',\n tool: 'wallet_balance',\n hint: null,\n facts: {\n wallet: {\n address: wallet.address,\n payment_network: 'base',\n payment_network_display: 'Base',\n chain_id: BASE_CHAIN_ID,\n token: 'USDC',\n token_balance: balanceUsdc,\n gas_token: 'ETH',\n ...(balanceEth === undefined ? {} : { gas_balance: balanceEth }),\n },\n },\n }\n}\n\nexport function formatWalletBalanceResult(result: WalletBalanceResult): string {\n const wallet = result.facts.wallet\n return formatWalletBalance(wallet.address, wallet.token_balance, wallet.gas_balance)\n}\n\nexport async function getWalletBalanceText(account?: PaymentWalletAccount): Promise<string> {\n return formatWalletBalanceResult(await getWalletBalanceResult(account))\n}\n\nexport function buildTopupInfo(address: string, topupUrl?: string): TopupInfo {\n return {\n wallet_address: address,\n network: 'Base',\n chain_id: BASE_CHAIN_ID,\n token: 'USDC',\n token_contract: USDC_ADDRESS,\n ...(topupU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