@moneytools-dev/openclaw-plugin 0.1.1 → 0.1.2

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 CHANGED
@@ -29,7 +29,9 @@ The plugin is off until you enable it, and it spends nothing until you set `auto
29
29
 
30
30
  - **Payer** (`payer: "auto"`): the EVM key in `X402_PRIVATE_KEY` if set (the same variable AgentCash and x402 clients use), otherwise an existing AgentCash wallet (`~/.agentcash/wallet.json`, paid through the pinned `agentcash@0.17.1` CLI). The plugin never reads the AgentCash wallet file; it only checks that it exists. If neither is present, only the free tier is used.
31
31
  - **Price guard**: before paying, the plugin reads the 402 quote and pays only if it is USDC on Base, payTo is the MoneyTools wallet `0x64eB63904Cf9688AC5B3087A72AcF9C31a273169`, and the amount is at most the published price (0.005 or 0.02 USDC).
32
- - **Daily cap**: `dailyBudgetUsd` (default 0.25 USDC per UTC day, max 5).
32
+ - **Signed-payment check**: with a key payer, the plugin signs only the single verified requirement, then checks the signed authorization (amount, USDC, Base, payTo, validity window) against the quote before sending it. One paid request, no automatic retry. With the AgentCash payer, AgentCash is limited to x402 on Base and to the quoted price (`--max-amount`).
33
+ - **Daily cap**: `dailyBudgetUsd` (default 0.25 USDC per UTC day, max 5). Spend is reserved before each payment starts, so parallel checks cannot exceed the cap; a payment that does not complete gives its reservation back. Identical checks running at the same time share one payment.
34
+ - **What is sent**: only the scheme, host, port and path of the URL being checked. User info, query strings and fragments (API keys, signed links) are dropped before the precheck request and are not logged.
33
35
  - **Cache**: the same URL or spender is not checked again for `cacheMinutes` (default 10).
34
36
  - `autoPay` (default `false`): with `false` the plugin never pays; precheck uses its free daily tier, and a check that needs payment (always the Wallet Risk Card) goes to `onCheckError`, which asks you by default.
35
37
 
@@ -82,6 +84,11 @@ npx agentcash fetch "https://api.moneytools.dev/v1/precheck?url=https://example.
82
84
 
83
85
  Run `npm test`. The tests make no network calls and spend nothing. The x402 signing test uses a random throwaway key against a local server.
84
86
 
87
+ ## Changelog
88
+
89
+ - **0.1.2**: signed payments are checked against the verified quote before sending; atomic daily-budget reservation; user info, query and fragment stripped from checked URLs.
90
+ - **0.1.1**: paid checks opt-in (`autoPay` default false), 0.25 USDC/day cap.
91
+
85
92
  ## Support
86
93
 
87
94
  MoneyTools Team, support@moneytools.dev, https://moneytools.dev/products/payment-safety/. MIT license.
@@ -2,7 +2,7 @@
2
2
  "id": "moneytools-guard",
3
3
  "name": "MoneyTools Guard",
4
4
  "description": "Pay precheck before every x402 payment (0.005 USDC) and a Wallet Risk Card before every token approval (0.02 USDC); blocks sanctioned or high-risk spenders. Paid checks are opt-in (autoPay) and paid from the agent's own wallet (X402_PRIVATE_KEY or an existing AgentCash wallet); daily cap 0.25 USDC by default; failed checks are not charged.",
5
- "version": "0.1.1",
5
+ "version": "0.1.2",
6
6
  "categories": ["security"],
7
7
  "enabledByDefault": false,
8
8
  "activation": { "onStartup": true },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moneytools-dev/openclaw-plugin",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "OpenClaw plugin: MoneyTools pay precheck before every x402 payment and a Wallet Risk Card before every token approval. Pays from the agent's own wallet; failed checks are not charged.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/checks.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // Calls the two MoneyTools checks and pays for them from the agent's own wallet.
2
- // Before paying, the 402 quote is verified: USDC on Base, payTo = MoneyTools team wallet, amount <= the published price.
2
+ // Before paying, the 402 quote is verified (exact scheme, USDC on Base, payTo = MoneyTools team wallet, amount <= the published price),
3
+ // the key payer signs only that verified requirement, and the signed authorization is checked against it again before it is sent.
4
+ // Spend is reserved against the daily cap before any payment starts, so parallel checks cannot exceed it.
3
5
  // MoneyTools does not settle a payment when the check itself fails, so failed checks are not charged.
4
6
  import { spawn } from "node:child_process";
5
7
  import { existsSync } from "node:fs";
@@ -13,22 +15,40 @@ export const USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
13
15
  export const BASE = "eip155:8453";
14
16
  export const PRICES = { precheck: 0.005, walletRisk: 0.02 };
15
17
  export const AGENTCASH_VERSION = "0.17.1"; // pinned; never @latest
16
- const UA = "moneytools-openclaw-plugin/0.1.1";
18
+ const UA = "moneytools-openclaw-plugin/0.1.2";
17
19
 
18
20
  export class CheckError extends Error { constructor(code, message) { super(message); this.code = code; } }
19
21
 
20
22
  function decodeHeader(v) { try { return JSON.parse(Buffer.from(v, "base64").toString("utf8")); } catch { return null; } }
23
+ const usdUnits = (usd) => BigInt(Math.round(Number(usd) * 1e6));
24
+ const sameAddr = (a, b) => typeof a === "string" && a.toLowerCase() === b.toLowerCase();
21
25
  /** Read and verify the MoneyTools 402 quote. Throws CheckError when it is not exactly what we publish. */
22
26
  export function verifyQuote(res, body, maxUsd) {
23
27
  const pr = (res.headers.get("payment-required") && decodeHeader(res.headers.get("payment-required"))) || body;
24
- const a = Array.isArray(pr?.accepts) ? pr.accepts.find((x) => x?.network === BASE) || pr.accepts[0] : null;
28
+ const a = Array.isArray(pr?.accepts) ? pr.accepts.find((x) => x?.network === BASE && x?.scheme === "exact") || pr.accepts[0] : null;
25
29
  if (!a) throw new CheckError("bad_quote", "could not read the MoneyTools 402 quote");
26
30
  const amount = String(a.amount ?? a.maxAmountRequired ?? "");
27
- if (a.network !== BASE || String(a.asset || "").toLowerCase() !== USDC_BASE) throw new CheckError("bad_quote", "MoneyTools quote is not USDC on Base; not paying");
28
- if (String(a.payTo || "").toLowerCase() !== MONEYTOOLS_PAY_TO.toLowerCase()) throw new CheckError("bad_quote", "MoneyTools quote payTo is not the MoneyTools wallet; not paying");
29
- const usd = Number(amount) / 1e6;
30
- if (!/^\d+$/.test(amount) || !(usd > 0) || usd > maxUsd + 1e-9) throw new CheckError("over_price", `MoneyTools quoted ${usd} USDC, above the ${maxUsd} USDC cap; not paying`);
31
- return { amountUsd: usd, accept: a };
31
+ if (a.scheme !== "exact") throw new CheckError("bad_quote", "MoneyTools quote is not an exact-scheme payment; not paying");
32
+ if (a.network !== BASE || !sameAddr(a.asset, USDC_BASE)) throw new CheckError("bad_quote", "MoneyTools quote is not USDC on Base; not paying");
33
+ if (!sameAddr(a.payTo, MONEYTOOLS_PAY_TO)) throw new CheckError("bad_quote", "MoneyTools quote payTo is not the MoneyTools wallet; not paying");
34
+ if (!/^\d+$/.test(amount) || BigInt(amount) <= 0n || BigInt(amount) > usdUnits(maxUsd)) throw new CheckError("over_price", `MoneyTools quoted ${Number(amount) / 1e6} USDC, above the ${maxUsd} USDC cap; not paying`);
35
+ return { amountUsd: Number(amount) / 1e6, amountUnits: amount, accept: a, paymentRequired: pr };
36
+ }
37
+
38
+ /** Check a signed x402 payment against the verified quote before it leaves the process. Throws CheckError on any mismatch. */
39
+ export function verifySignedPayment(payload, quote, maxUsd, now = () => Date.now()) {
40
+ const fail = (why) => { throw new CheckError("bad_payment", `signed payment does not match the verified MoneyTools quote (${why}); not sending`); };
41
+ const acc = payload?.accepted; const auth = payload?.payload?.authorization;
42
+ if (!acc || !auth) fail("no exact-scheme authorization");
43
+ if (payload.x402Version !== 2) fail("x402 version");
44
+ if (acc.scheme !== "exact" || acc.network !== BASE) fail("scheme/network");
45
+ if (!sameAddr(acc.asset, USDC_BASE)) fail("asset");
46
+ if (!sameAddr(acc.payTo, MONEYTOOLS_PAY_TO) || !sameAddr(auth.to, MONEYTOOLS_PAY_TO)) fail("payTo");
47
+ if (String(acc.amount) !== quote.amountUnits || !/^\d+$/.test(String(auth.value)) || BigInt(auth.value) !== BigInt(quote.amountUnits)) fail("amount");
48
+ if (BigInt(auth.value) > usdUnits(maxUsd)) fail("amount above cap");
49
+ const validBefore = Number(auth.validBefore); const maxWindow = Number(quote.accept.maxTimeoutSeconds || 300) + 120;
50
+ if (!Number.isFinite(validBefore) || validBefore > Math.floor(now() / 1000) + maxWindow) fail("authorization window");
51
+ return true;
32
52
  }
33
53
 
34
54
  /** Which wallet pays: "key" (env X402_PRIVATE_KEY or the configured env var), "agentcash" (existing ~/.agentcash/wallet.json), or "none". Never reads the key file itself. */
@@ -44,19 +64,26 @@ export function resolvePayer(cfg = {}, env = process.env, fileExists = existsSyn
44
64
  return { kind: "none", reason: `no payer: set ${keyEnv} or create an AgentCash wallet` };
45
65
  }
46
66
 
47
- async function payWithKey(url, payer, env, deps) {
67
+ async function payWithKey(url, quote, maxUsd, payer, env, deps) {
48
68
  let mods;
49
69
  try { mods = deps.x402 || { fetch: await import("@x402/fetch"), evm: await import("@x402/evm/exact/client"), accounts: await import("viem/accounts") }; }
50
70
  catch { throw new CheckError("payer_unavailable", "@x402/fetch, @x402/evm and viem are needed for key payments"); }
71
+ if (quote.paymentRequired?.x402Version !== 2) throw new CheckError("bad_quote", "MoneyTools quote is not x402 v2; not paying");
51
72
  const account = mods.accounts.privateKeyToAccount(env[payer.keyEnv].trim());
52
73
  const client = new mods.fetch.x402Client(); mods.evm.registerExactEvmScheme(client, { signer: account });
53
- const paid = mods.fetch.wrapFetchWithPayment(deps.fetch, client);
54
- return paid(url, { headers: { accept: "application/json", "user-agent": UA } });
74
+ const http = new mods.fetch.x402HTTPClient(client);
75
+ // Sign only the requirement we verified; never let the client pick another one.
76
+ const payload = await http.createPaymentPayload({ ...quote.paymentRequired, accepts: [quote.accept] });
77
+ verifySignedPayment(payload, quote, maxUsd, deps.now);
78
+ // One paid request, no automatic retry: a second 402 is treated as a failed (uncharged) check.
79
+ return deps.fetch(url, { headers: { accept: "application/json", "user-agent": UA, ...http.encodePaymentSignatureHeader(payload) } });
55
80
  }
56
- /** Run `npx -y agentcash@<pinned> fetch <url> --format json`; AgentCash signs with its own wallet. */
57
- export function runAgentcash(url, { timeoutMs = 60000, spawnFn = spawn } = {}) {
81
+ /** Run `npx -y agentcash@<pinned> fetch <url> --format json ...`; AgentCash signs with its own wallet. */
82
+ /** AgentCash signs inside its own process; it is limited to x402 on Base and to maxUsd per request (--max-amount). */
83
+ export function runAgentcash(url, { timeoutMs = 60000, spawnFn = spawn, maxUsd } = {}) {
58
84
  return new Promise((resolve, reject) => {
59
- const p = spawnFn("npx", ["-y", `agentcash@${AGENTCASH_VERSION}`, "fetch", url, "--format", "json"], { stdio: ["ignore", "pipe", "pipe"], env: process.env });
85
+ if (!(Number(maxUsd) > 0)) return reject(new CheckError("payer_failed", "no price cap for AgentCash; not paying"));
86
+ const p = spawnFn("npx", ["-y", `agentcash@${AGENTCASH_VERSION}`, "fetch", url, "--format", "json", "--payment-protocol", "x402", "--payment-network", "base", "--max-amount", String(maxUsd)], { stdio: ["ignore", "pipe", "pipe"], env: process.env });
60
87
  let out = ""; const t = setTimeout(() => { try { p.kill("SIGTERM"); } catch {} reject(new CheckError("timeout", "AgentCash timed out")); }, timeoutMs);
61
88
  p.stdout.on("data", (d) => { out += d; if (out.length > 2e6) p.kill("SIGTERM"); });
62
89
  p.on("error", (e) => { clearTimeout(t); reject(new CheckError("payer_unavailable", `could not start AgentCash: ${e.message}`)); });
@@ -67,26 +94,47 @@ export function runAgentcash(url, { timeoutMs = 60000, spawnFn = spawn } = {}) {
67
94
  }
68
95
 
69
96
  /** GET a MoneyTools check. Free tier first (unpaid request); on 402 verify the quote, then pay from the agent's wallet. */
70
- export async function callCheck(url, { maxUsd, payer, env = process.env, fetch: f = globalThis.fetch, x402, agentcash = runAgentcash, budget } = {}) {
97
+ export async function callCheck(url, { maxUsd, payer, env = process.env, fetch: f = globalThis.fetch, x402, agentcash = runAgentcash, budget, now } = {}) {
71
98
  const first = await f(url, { headers: { accept: "application/json", "user-agent": UA } });
72
99
  if (first.status === 200) return { data: await first.json(), paidUsd: 0 };
73
100
  if (first.status !== 402) { const j = await first.json().catch(() => ({})); throw new CheckError(j.error || `http_${first.status}`, j.message || `MoneyTools returned HTTP ${first.status}`); }
74
101
  const quote = verifyQuote(first, await first.json().catch(() => null), maxUsd);
75
102
  if (!payer || payer.kind === "none") throw new CheckError("no_payer", payer?.reason || "no wallet configured to pay for the check");
76
- if (budget && !budget.canSpend(quote.amountUsd)) throw new CheckError("budget", `daily check budget reached (${budget.limitUsd} USDC)`);
77
- let data;
78
- if (payer.kind === "key") { const r = await payWithKey(url, payer, env, { fetch: f, x402 }); data = await r.json().catch(() => ({}));
79
- if (r.status !== 200) throw new CheckError(data.error || `http_${r.status}`, data.message || `paid check failed with HTTP ${r.status} (not charged)`); }
80
- else data = await agentcash(url);
81
- budget?.spend(quote.amountUsd);
82
- return { data, paidUsd: quote.amountUsd };
103
+ // Reserve before any await so concurrent checks cannot both pass the cap; released if the payment does not complete.
104
+ const hold = budget ? budget.reserve(quote.amountUsd) : null;
105
+ if (budget && !hold) throw new CheckError("budget", `daily check budget reached (${budget.limitUsd} USDC)`);
106
+ try {
107
+ let data;
108
+ if (payer.kind === "key") { const r = await payWithKey(url, quote, maxUsd, payer, env, { fetch: f, x402, now }); data = await r.json().catch(() => ({}));
109
+ if (r.status !== 200) throw new CheckError(data.error || `http_${r.status}`, data.message || `paid check failed with HTTP ${r.status} (not charged)`); }
110
+ else data = await agentcash(url, { maxUsd: quote.amountUsd });
111
+ hold?.commit();
112
+ return { data, paidUsd: quote.amountUsd };
113
+ } catch (e) { hold?.release(); throw e; }
83
114
  }
84
115
 
85
- export const precheckUrl = (target, method = "GET") => `${PRECHECK_URL}?url=${encodeURIComponent(target)}&method=${encodeURIComponent(method)}`;
116
+ /** Only scheme, host, port and path of a target URL are sent to MoneyTools: user info, query string and fragment are dropped. */
117
+ export function sanitizeTargetUrl(target) {
118
+ let u; try { u = new URL(String(target).trim()); } catch { throw new CheckError("bad_url", "not a valid URL"); }
119
+ if (!/^https?:$/.test(u.protocol)) throw new CheckError("bad_url", "only http(s) URLs can be prechecked");
120
+ u.username = ""; u.password = ""; u.search = ""; u.hash = ""; return u.toString();
121
+ }
122
+ export const precheckUrl = (target, method = "GET") => `${PRECHECK_URL}?url=${encodeURIComponent(sanitizeTargetUrl(target))}&method=${encodeURIComponent(method)}`;
86
123
  export const walletRiskUrl = (address, chain = "base") => `${WALLET_RISK_URL}?address=${encodeURIComponent(address)}&chain=${encodeURIComponent(chain)}`;
87
124
 
88
- /** Per-process UTC-day spend cap for the plugin's own checks. */
125
+ /** Per-process UTC-day spend cap for the plugin's own checks. reserve() is synchronous (atomic in the event loop): a reservation counts toward the cap
126
+ * from the moment it is made, is kept by commit() and given back by release() when the payment does not complete. */
89
127
  export function makeBudget(limitUsd, now = () => Date.now()) {
90
- let day = "", spent = 0; const roll = () => { const d = new Date(now()).toISOString().slice(0, 10); if (d !== day) { day = d; spent = 0; } };
91
- return { limitUsd, canSpend(x) { roll(); return spent + x <= limitUsd + 1e-9; }, spend(x) { roll(); spent += x; }, get spentUsd() { roll(); return spent; } };
128
+ const cap = usdUnits(limitUsd); let day = "", units = 0n;
129
+ const roll = () => { const d = new Date(now()).toISOString().slice(0, 10); if (d !== day) { day = d; units = 0n; } return day; };
130
+ return {
131
+ limitUsd,
132
+ canSpend(x) { roll(); return units + usdUnits(x) <= cap; },
133
+ reserve(x) {
134
+ const d = roll(); const amt = usdUnits(x); if (amt <= 0n || units + amt > cap) return null;
135
+ units += amt; let done = false;
136
+ return { commit() { done = true; }, release() { if (done) return; done = true; if (roll() === d) units -= amt; } };
137
+ },
138
+ get spentUsd() { roll(); return Number(units) / 1e6; },
139
+ };
92
140
  }
package/src/detect.js CHANGED
@@ -24,7 +24,9 @@ export const CHAINS = { base: "base", "8453": "base", "eip155:8453": "base", eth
24
24
 
25
25
  const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
26
26
  function* walk(v, depth = 0, key = "") { if (depth > 6) return; yield [key, v]; if (Array.isArray(v)) { for (const x of v.slice(0, 50)) yield* walk(x, depth + 1, key); } else if (isObj(v)) { for (const [k, x] of Object.entries(v).slice(0, 100)) yield* walk(x, depth + 1, k); } }
27
- const httpUrl = (s) => { if (typeof s !== "string") return null; try { const u = new URL(s.trim()); return /^https?:$/.test(u.protocol) ? u.toString() : null; } catch { return null; } };
27
+ // Returned URLs carry only scheme, host, port and path: user info, query string and fragment are dropped so they never reach logs or the check API.
28
+ export const stripUrl = (s) => { if (typeof s !== "string") return null; try { const u = new URL(s.trim()); if (!/^https?:$/.test(u.protocol)) return null; u.username = ""; u.password = ""; u.search = ""; u.hash = ""; return u.toString(); } catch { return null; } };
29
+ const httpUrl = stripUrl;
28
30
 
29
31
  export function isOwnCheckUrl(url) { try { return /(^|\.)moneytools\.dev$/i.test(new URL(url).hostname); } catch { return false; } }
30
32
 
@@ -50,8 +52,8 @@ export function detectX402Payment(toolName, params, opts = {}) {
50
52
  if (EXEC_TOOLS.test(name) || opts.toolKind === "code_mode_exec") {
51
53
  const cmd = commandOf(params);
52
54
  const m = /\bagentcash(?:@[\w.\-]+)?\s+(?:fetch|fetch-auth)\s+["']?(https?:\/\/[^\s"']+)/i.exec(cmd);
53
- if (m && !isOwnCheckUrl(m[1])) return { url: m[1], method: /(?:-m|--method)\s+(POST|PUT|PATCH|DELETE)/i.exec(cmd)?.[1]?.toUpperCase() || "GET", via: "exec:agentcash" };
54
- if (/(payment-signature|x-payment)\s*:/i.test(cmd)) { const u = /(https?:\/\/[^\s"']+)/.exec(cmd)?.[1]; if (u && !isOwnCheckUrl(u)) return { url: u, method: /-X\s+(POST|PUT|PATCH|DELETE)/i.exec(cmd)?.[1]?.toUpperCase() || "GET", via: "exec:payment-header" }; }
55
+ if (m && !isOwnCheckUrl(m[1]) && stripUrl(m[1])) return { url: stripUrl(m[1]), method: /(?:-m|--method)\s+(POST|PUT|PATCH|DELETE)/i.exec(cmd)?.[1]?.toUpperCase() || "GET", via: "exec:agentcash" };
56
+ if (/(payment-signature|x-payment)\s*:/i.test(cmd)) { const u = /(https?:\/\/[^\s"']+)/.exec(cmd)?.[1]; if (u && !isOwnCheckUrl(u) && stripUrl(u)) return { url: stripUrl(u), method: /-X\s+(POST|PUT|PATCH|DELETE)/i.exec(cmd)?.[1]?.toUpperCase() || "GET", via: "exec:payment-header" }; }
55
57
  return null;
56
58
  }
57
59
  const url = findUrl(params); if (!url || isOwnCheckUrl(url)) return null;
package/src/guard.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Host-free plugin logic: config, decisions, the before_tool_call handler and the two explicit tools.
2
2
  import { detectX402Payment, detectApproval, DEFAULT_PAYMENT_TOOL_PATTERN, CHAINS } from "./detect.js";
3
- import { callCheck, resolvePayer, makeBudget, precheckUrl, walletRiskUrl, PRICES, CheckError } from "./checks.js";
3
+ import { callCheck, resolvePayer, makeBudget, precheckUrl, walletRiskUrl, sanitizeTargetUrl, PRICES, CheckError } from "./checks.js";
4
4
 
5
5
  export const PLUGIN_ID = "moneytools-guard";
6
6
  export const DEFAULTS = { autoPay: false, payer: "auto", privateKeyEnv: "X402_PRIVATE_KEY", dailyBudgetUsd: 0.25, precheckPayments: true, checkApprovals: true,
@@ -45,9 +45,16 @@ export function createGuard(rawCfg, deps = {}) {
45
45
  const cfg = readConfig(rawCfg); const env = deps.env || process.env; const log = deps.logger || { info() {}, warn() {} };
46
46
  const budget = makeBudget(cfg.dailyBudgetUsd, deps.now); const cache = new Map(); const ttl = cfg.cacheMinutes * 60000; const now = deps.now || (() => Date.now());
47
47
  const payer = () => (cfg.autoPay ? resolvePayer(cfg, env, deps.fileExists) : { kind: "none", reason: "autoPay is off (free tier only)" });
48
- async function cached(key, fn) { const hit = cache.get(key); if (hit && now() - hit.at < ttl) return hit.v; const v = await fn(); cache.set(key, { v, at: now() }); if (cache.size > 500) cache.delete(cache.keys().next().value); return v; }
49
- const run = (url, maxUsd) => callCheck(url, { maxUsd, payer: payer(), env, fetch: deps.fetch || globalThis.fetch, x402: deps.x402, agentcash: deps.agentcash, budget });
50
- const precheck = (target, method) => cached(`p:${method}:${target}`, () => run(precheckUrl(target, method), PRICES.precheck));
48
+ const inflight = new Map();
49
+ // Results are cached, and identical checks already running share one request (and at most one payment).
50
+ async function cached(key, fn) {
51
+ const hit = cache.get(key); if (hit && now() - hit.at < ttl) return hit.v;
52
+ if (inflight.has(key)) return inflight.get(key);
53
+ const p = (async () => { try { const v = await fn(); cache.set(key, { v, at: now() }); if (cache.size > 500) cache.delete(cache.keys().next().value); return v; } finally { inflight.delete(key); } })();
54
+ inflight.set(key, p); return p;
55
+ }
56
+ const run = (url, maxUsd) => callCheck(url, { maxUsd, payer: payer(), env, fetch: deps.fetch || globalThis.fetch, x402: deps.x402, agentcash: deps.agentcash, budget, now: deps.now });
57
+ const precheck = async (target, method) => { const t = sanitizeTargetUrl(target); return cached(`p:${method}:${t}`, () => run(precheckUrl(t, method), PRICES.precheck)); };
51
58
  const walletRisk = (address, chain) => cached(`w:${chain}:${address.toLowerCase()}`, () => run(walletRiskUrl(address, chain), PRICES.walletRisk));
52
59
 
53
60
  async function beforeToolCall(event, ctx = {}) {
@@ -56,7 +63,7 @@ export function createGuard(rawCfg, deps = {}) {
56
63
  if (a) { try { const { data, paidUsd } = await walletRisk(a.spender, a.chain); log.info?.(`[${PLUGIN_ID}] wallet-risk ${a.spender} ${a.chain}: ${data?.level} (${paidUsd ? fmtUsd(paidUsd) : "free/cached"})`); return decideRisk(cfg, a, data); }
57
64
  catch (e) { return onError(cfg, "Wallet Risk Card", e); } } }
58
65
  if (cfg.precheckPayments) { const p = detectX402Payment(name, params, opts);
59
- if (p) { try { const { data, paidUsd } = await precheck(p.url, p.method); log.info?.(`[${PLUGIN_ID}] precheck ${p.url}: ${data?.verdict} (${paidUsd ? fmtUsd(paidUsd) : "free/cached"})`); return decidePrecheck(cfg, p.url, data); }
66
+ if (p) { try { const { data, paidUsd } = await precheck(p.url, p.method); log.info?.(`[${PLUGIN_ID}] precheck ${sanitizeTargetUrl(p.url)}: ${data?.verdict} (${paidUsd ? fmtUsd(paidUsd) : "free/cached"})`); return decidePrecheck(cfg, p.url, data); }
60
67
  catch (e) { return onError(cfg, "pay precheck", e); } } }
61
68
  return undefined;
62
69
  }