@moneytools-dev/openclaw-plugin 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MoneyTools
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # MoneyTools Guard for OpenClaw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@moneytools-dev/openclaw-plugin` adds two automatic checks to an OpenClaw agent:
4
+
5
+ | When | Check | Cost |
6
+ |---|---|---|
7
+ | Before any x402 payment | [Pay precheck](https://api.moneytools.dev/v1/precheck): validates the seller's 402 terms (network, amount, asset, payTo) and screens payTo against the OFAC SDN list | free daily tier, then 0.005 USDC |
8
+ | Before any token approval (ERC-20 `approve` / `increaseAllowance`, `setApprovalForAll`, Permit2 `approve`, Permit/Permit2 signatures) | [Wallet Risk Card](https://tools.moneytools.dev/v1/wallet-risk) on the spender: 0-100 risk score, grade A-F, OFAC SDN match, address checks, open approvals | 0.02 USDC |
9
+
10
+ Paid checks are **opt-in** (`autoPay: true`); by default the plugin uses only the free tier and asks you when a check would need payment. When enabled, checks are paid in USDC on Base from the agent's own wallet. There is no MoneyTools account or API key. MoneyTools does not settle a payment when a check fails, so failed checks are not charged.
11
+
12
+ ## Install (one line)
13
+
14
+ ```bash
15
+ openclaw plugins install @moneytools-dev/openclaw-plugin && openclaw plugins enable moneytools-guard
16
+ ```
17
+
18
+ To let it pay for checks automatically (opt-in, capped at 0.25 USDC/day by default):
19
+
20
+ ```bash
21
+ openclaw config set plugins.entries.moneytools-guard.config.autoPay true
22
+ ```
23
+
24
+ From npm instead of ClawHub: `openclaw plugins install npm:@moneytools-dev/openclaw-plugin`.
25
+
26
+ The plugin is off until you enable it, and it spends nothing until you set `autoPay: true`.
27
+
28
+ ## What it spends, and from which wallet
29
+
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
+ - **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).
33
+ - **Cache**: the same URL or spender is not checked again for `cacheMinutes` (default 10).
34
+ - `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
+
36
+ ## What it decides
37
+
38
+ | Result | Default action | Config |
39
+ |---|---|---|
40
+ | Precheck `ok` | continue | |
41
+ | Precheck `warn` | ask you (OpenClaw approval) | `onPrecheckWarn`: approve / allow / block |
42
+ | Precheck `block` | block the payment | |
43
+ | Spender on OFAC SDN | block (always) | |
44
+ | Spender risk `high` | block | `onHighRisk`: block / approve |
45
+ | Spender risk `medium` | ask you | `onMediumRisk`: approve / allow / block |
46
+ | Check could not run (no wallet, cap reached, network) | ask you; nothing is charged | `onCheckError`: approve / allow / block |
47
+
48
+ ## How payments and approvals are detected
49
+
50
+ The plugin uses OpenClaw's `before_tool_call` hook.
51
+
52
+ - **x402 payment**:
53
+ - a tool whose name matches x402 / agentcash / pay / paid_fetch (`paymentToolPattern` to change) and has a URL;
54
+ - any tool call that carries a `PAYMENT-SIGNATURE` or `X-PAYMENT` header;
55
+ - an `exec` command running `agentcash fetch <url>` or sending a payment header.
56
+ - **Approval**:
57
+ - calldata with the `approve`, `increaseAllowance`, `setApprovalForAll(true)` or Permit2 `approve` selector;
58
+ - structured `{ functionName: "approve", args: [spender, ...] }` calls;
59
+ - EIP-712 `Permit` / `PermitSingle` / `PermitBatch` signatures;
60
+ - `cast send ... "approve(address,uint256)" <spender>`.
61
+ - `approve(spender, 0)` is a revoke and is not checked. MoneyTools' own check URLs are never checked, so the plugin cannot loop.
62
+
63
+ ## Tools for the agent
64
+
65
+ - `moneytools_pay_precheck { url, method? }`
66
+ - `moneytools_wallet_risk { address, chain? }`, where chain is one of base, ethereum, arbitrum, optimism, polygon, bsc or avalanche.
67
+
68
+ ## Config example (`openclaw.json`)
69
+
70
+ ```json
71
+ { "plugins": { "entries": { "moneytools-guard": { "enabled": true, "config": { "autoPay": true, "dailyBudgetUsd": 0.1, "onMediumRisk": "allow" } } } } }
72
+ ```
73
+
74
+ ## No OpenClaw? One line with AgentCash
75
+
76
+ ```bash
77
+ npx agentcash fetch "https://tools.moneytools.dev/v1/wallet-risk?address=vitalik.eth&chain=base"
78
+ npx agentcash fetch "https://api.moneytools.dev/v1/precheck?url=https://example.com/paid&method=GET"
79
+ ```
80
+
81
+ ## Tests
82
+
83
+ 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
+
85
+ ## Support
86
+
87
+ MoneyTools Team, support@moneytools.dev, https://moneytools.dev/products/payment-safety/. MIT license.
Binary file
package/index.js ADDED
@@ -0,0 +1,11 @@
1
+ // MoneyTools Guard for OpenClaw: pay precheck before every x402 payment, Wallet Risk Card before every token approval.
2
+ import { Type } from "typebox";
3
+ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
4
+ import { registerGuard, PLUGIN_ID } from "./src/guard.js";
5
+
6
+ export default definePluginEntry({
7
+ id: PLUGIN_ID,
8
+ name: "MoneyTools Guard",
9
+ description: "Before an agent pays an x402 seller, runs the MoneyTools pay precheck (0.005 USDC); before it approves a token spender, runs the Wallet Risk Card (0.02 USDC) and blocks high-risk or sanctioned spenders. Paid from the agent's own wallet; failed checks are not charged.",
10
+ register(api) { registerGuard(api, Type); },
11
+ });
@@ -0,0 +1,29 @@
1
+ {
2
+ "id": "moneytools-guard",
3
+ "name": "MoneyTools Guard",
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",
6
+ "categories": ["security"],
7
+ "enabledByDefault": false,
8
+ "activation": { "onStartup": true },
9
+ "contracts": { "tools": ["moneytools_pay_precheck", "moneytools_wallet_risk"] },
10
+ "configSchema": {
11
+ "type": "object",
12
+ "additionalProperties": false,
13
+ "properties": {
14
+ "autoPay": { "type": "boolean", "default": false, "description": "Opt-in. true = pay for checks automatically from the agent's wallet after the free tier (capped by dailyBudgetUsd). Default false = free tier only; checks that need payment ask you instead." },
15
+ "payer": { "type": "string", "enum": ["auto", "key", "agentcash", "none"], "default": "auto", "description": "auto: X402_PRIVATE_KEY if set, else an existing AgentCash wallet (~/.agentcash/wallet.json), else free tier only." },
16
+ "privateKeyEnv": { "type": "string", "default": "X402_PRIVATE_KEY", "description": "Name of the env var holding the agent's EVM private key (USDC on Base). The key never leaves the Gateway process." },
17
+ "dailyBudgetUsd": { "type": "number", "minimum": 0, "maximum": 5, "default": 0.25, "description": "Max USDC per UTC day this plugin may spend on its own checks." },
18
+ "precheckPayments": { "type": "boolean", "default": true },
19
+ "checkApprovals": { "type": "boolean", "default": true },
20
+ "onPrecheckWarn": { "type": "string", "enum": ["approve", "allow", "block"], "default": "approve" },
21
+ "onHighRisk": { "type": "string", "enum": ["block", "approve"], "default": "block" },
22
+ "onMediumRisk": { "type": "string", "enum": ["approve", "allow", "block"], "default": "approve" },
23
+ "onCheckError": { "type": "string", "enum": ["approve", "allow", "block"], "default": "approve", "description": "What to do when a check cannot run (no wallet, budget reached, network error)." },
24
+ "defaultChain": { "type": "string", "enum": ["base", "ethereum", "arbitrum", "optimism", "polygon", "bsc", "avalanche"], "default": "base" },
25
+ "paymentToolPattern": { "type": "string", "description": "Regex (case-insensitive) of tool names that make x402 payments. Default matches x402 / agentcash / pay / paid_fetch tools." },
26
+ "cacheMinutes": { "type": "number", "minimum": 0, "maximum": 1440, "default": 10 }
27
+ }
28
+ }
29
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@moneytools-dev/openclaw-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
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
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": { ".": "./index.js", "./guard": "./src/guard.js", "./detect": "./src/detect.js" },
8
+ "files": ["index.js", "src/", "openclaw.plugin.json", "assets/", "README.md", "LICENSE"],
9
+ "scripts": { "test": "node --test test/*.test.mjs" },
10
+ "dependencies": {
11
+ "typebox": "1.4.2",
12
+ "@x402/fetch": "^2.31.0",
13
+ "@x402/evm": "^2.31.0",
14
+ "viem": "^2.40.0"
15
+ },
16
+ "peerDependencies": { "openclaw": ">=2026.11.5" },
17
+ "peerDependenciesMeta": { "openclaw": { "optional": true } },
18
+ "openclaw": {
19
+ "extensions": ["./index.js"],
20
+ "compat": { "pluginApi": ">=2026.11.5", "minGatewayVersion": "2026.11.5" },
21
+ "build": { "openclawVersion": "2026.11.5", "pluginSdkVersion": "2026.11.5" }
22
+ },
23
+ "engines": { "node": ">=24.22.1" },
24
+ "keywords": ["openclaw", "openclaw-plugin", "x402", "usdc", "base", "payment-safety", "wallet-risk", "approvals", "agent"],
25
+ "license": "MIT",
26
+ "author": "MoneyTools Team <support@moneytools.dev>",
27
+ "homepage": "https://moneytools.dev/products/payment-safety/",
28
+ "bugs": { "email": "support@moneytools.dev" },
29
+ "publishConfig": { "access": "public" }
30
+ }
package/src/checks.js ADDED
@@ -0,0 +1,92 @@
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.
3
+ // MoneyTools does not settle a payment when the check itself fails, so failed checks are not charged.
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ export const PRECHECK_URL = "https://api.moneytools.dev/v1/precheck";
10
+ export const WALLET_RISK_URL = "https://tools.moneytools.dev/v1/wallet-risk";
11
+ export const MONEYTOOLS_PAY_TO = "0x64eB63904Cf9688AC5B3087A72AcF9C31a273169";
12
+ export const USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
13
+ export const BASE = "eip155:8453";
14
+ export const PRICES = { precheck: 0.005, walletRisk: 0.02 };
15
+ export const AGENTCASH_VERSION = "0.17.1"; // pinned; never @latest
16
+ const UA = "moneytools-openclaw-plugin/0.1.1";
17
+
18
+ export class CheckError extends Error { constructor(code, message) { super(message); this.code = code; } }
19
+
20
+ function decodeHeader(v) { try { return JSON.parse(Buffer.from(v, "base64").toString("utf8")); } catch { return null; } }
21
+ /** Read and verify the MoneyTools 402 quote. Throws CheckError when it is not exactly what we publish. */
22
+ export function verifyQuote(res, body, maxUsd) {
23
+ 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;
25
+ if (!a) throw new CheckError("bad_quote", "could not read the MoneyTools 402 quote");
26
+ 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 };
32
+ }
33
+
34
+ /** 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. */
35
+ export function resolvePayer(cfg = {}, env = process.env, fileExists = existsSync) {
36
+ const want = cfg.payer || "auto"; const keyEnv = cfg.privateKeyEnv || "X402_PRIVATE_KEY";
37
+ const hasKey = typeof env[keyEnv] === "string" && /^0x[0-9a-fA-F]{64}$/.test(env[keyEnv].trim());
38
+ const acWallet = join(cfg.agentcashHome || homedir(), ".agentcash", "wallet.json");
39
+ if (want === "none") return { kind: "none" };
40
+ if (want === "key") return hasKey ? { kind: "key", keyEnv } : { kind: "none", reason: `${keyEnv} is not set` };
41
+ if (want === "agentcash") return fileExists(acWallet) ? { kind: "agentcash" } : { kind: "none", reason: "no AgentCash wallet (~/.agentcash/wallet.json); run `npx agentcash onboard` first" };
42
+ if (hasKey) return { kind: "key", keyEnv };
43
+ if (fileExists(acWallet)) return { kind: "agentcash" };
44
+ return { kind: "none", reason: `no payer: set ${keyEnv} or create an AgentCash wallet` };
45
+ }
46
+
47
+ async function payWithKey(url, payer, env, deps) {
48
+ let mods;
49
+ try { mods = deps.x402 || { fetch: await import("@x402/fetch"), evm: await import("@x402/evm/exact/client"), accounts: await import("viem/accounts") }; }
50
+ catch { throw new CheckError("payer_unavailable", "@x402/fetch, @x402/evm and viem are needed for key payments"); }
51
+ const account = mods.accounts.privateKeyToAccount(env[payer.keyEnv].trim());
52
+ 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 } });
55
+ }
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 } = {}) {
58
+ 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 });
60
+ let out = ""; const t = setTimeout(() => { try { p.kill("SIGTERM"); } catch {} reject(new CheckError("timeout", "AgentCash timed out")); }, timeoutMs);
61
+ p.stdout.on("data", (d) => { out += d; if (out.length > 2e6) p.kill("SIGTERM"); });
62
+ p.on("error", (e) => { clearTimeout(t); reject(new CheckError("payer_unavailable", `could not start AgentCash: ${e.message}`)); });
63
+ p.on("close", () => { clearTimeout(t); let j; try { j = JSON.parse(out); } catch { return reject(new CheckError("payer_failed", "AgentCash returned no JSON")); }
64
+ if (j?.success === true && j.data && typeof j.data === "object") return resolve(j.data);
65
+ reject(new CheckError("payer_failed", String(j?.error?.message || j?.error || "AgentCash payment failed").slice(0, 200))); });
66
+ });
67
+ }
68
+
69
+ /** 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 } = {}) {
71
+ const first = await f(url, { headers: { accept: "application/json", "user-agent": UA } });
72
+ if (first.status === 200) return { data: await first.json(), paidUsd: 0 };
73
+ 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
+ const quote = verifyQuote(first, await first.json().catch(() => null), maxUsd);
75
+ 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 };
83
+ }
84
+
85
+ export const precheckUrl = (target, method = "GET") => `${PRECHECK_URL}?url=${encodeURIComponent(target)}&method=${encodeURIComponent(method)}`;
86
+ export const walletRiskUrl = (address, chain = "base") => `${WALLET_RISK_URL}?address=${encodeURIComponent(address)}&chain=${encodeURIComponent(chain)}`;
87
+
88
+ /** Per-process UTC-day spend cap for the plugin's own checks. */
89
+ 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; } };
92
+ }
package/src/detect.js ADDED
@@ -0,0 +1,104 @@
1
+ // Detect, from a tool call's name and params, (a) an x402 payment about to be made and (b) an ERC-20 / NFT / Permit2 approval about to be sent or signed.
2
+ // Pure functions, no I/O. Detection is heuristic and conservative: it only fires on clear signals.
3
+
4
+ const URL_KEYS = ["url", "endpoint", "resource", "resourceUrl", "resource_url", "uri", "target", "href"];
5
+ const PAY_HEADER = /^(payment-signature|x-payment)$/i;
6
+ const EXEC_TOOLS = /^(exec|bash|shell|sh|run|run_command|run_shell_command|terminal|command|code_mode_exec)$/i;
7
+ export const DEFAULT_PAYMENT_TOOL_PATTERN = /x402|agentcash|(^|[_.:\-])pay(ment)?s?([_.:\-]|$)|paid[_-]?fetch|fetch[_-]with[_-](auth|payment)|clawrouter|blockrun/i;
8
+
9
+ // approve(address,uint256) / increaseAllowance(address,uint256) / setApprovalForAll(address,bool) / Permit2 approve(address,address,uint160,uint48)
10
+ const SELECTORS = {
11
+ "0x095ea7b3": { fn: "approve", spenderArg: 0, amountArg: 1 },
12
+ "0x39509351": { fn: "increaseAllowance", spenderArg: 0, amountArg: 1 },
13
+ "0xa22cb465": { fn: "setApprovalForAll", spenderArg: 0, boolArg: 1 },
14
+ "0x87517c45": { fn: "permit2.approve", spenderArg: 1, amountArg: 2 },
15
+ };
16
+ const APPROVE_FN = /^(approve|increaseallowance|setapprovalforall|permit|permit2[._]?approve)$/i;
17
+ const PERMIT_TYPES = /^(permit|permitsingle|permitbatch|permittransferfrom|permitbatchtransferfrom)$/i;
18
+ const MAX_UINT256 = (1n << 256n) - 1n;
19
+ const ADDR = /^0x[0-9a-fA-F]{40}$/;
20
+
21
+ export const CHAINS = { base: "base", "8453": "base", "eip155:8453": "base", ethereum: "ethereum", mainnet: "ethereum", eth: "ethereum", "1": "ethereum", "eip155:1": "ethereum",
22
+ arbitrum: "arbitrum", "arbitrum-one": "arbitrum", "42161": "arbitrum", "eip155:42161": "arbitrum", optimism: "optimism", op: "optimism", "10": "optimism", "eip155:10": "optimism",
23
+ polygon: "polygon", matic: "polygon", "137": "polygon", "eip155:137": "polygon", bsc: "bsc", bnb: "bsc", "56": "bsc", "eip155:56": "bsc", avalanche: "avalanche", avax: "avalanche", "43114": "avalanche", "eip155:43114": "avalanche" };
24
+
25
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
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; } };
28
+
29
+ export function isOwnCheckUrl(url) { try { return /(^|\.)moneytools\.dev$/i.test(new URL(url).hostname); } catch { return false; } }
30
+
31
+ function findUrl(params) {
32
+ for (const k of URL_KEYS) { const u = httpUrl(params?.[k]); if (u) return u; }
33
+ for (const k of ["request", "input", "args", "arguments"]) if (isObj(params?.[k])) { const u = findUrl(params[k]); if (u) return u; }
34
+ return null;
35
+ }
36
+ function hasPaymentHeader(params) {
37
+ for (const [, v] of walk(params)) {
38
+ if (isObj(v)) { for (const k of Object.keys(v)) if (PAY_HEADER.test(k)) return true; }
39
+ if (typeof v === "string" && /^\s*(payment-signature|x-payment)\s*:/i.test(v)) return true;
40
+ }
41
+ return false;
42
+ }
43
+ function commandOf(params) { for (const k of ["command", "cmd", "script", "code", "input"]) if (typeof params?.[k] === "string") return params[k]; if (Array.isArray(params?.command)) return params.command.join(" "); return ""; }
44
+
45
+ /** Is this tool call about to pay an x402 endpoint? -> { url, method, via } | null */
46
+ export function detectX402Payment(toolName, params, opts = {}) {
47
+ const name = String(toolName || ""); const pattern = opts.paymentToolPattern || DEFAULT_PAYMENT_TOOL_PATTERN;
48
+ if (/^moneytools_/i.test(name)) return null;
49
+ const method = String(params?.method || params?.httpMethod || "GET").toUpperCase();
50
+ if (EXEC_TOOLS.test(name) || opts.toolKind === "code_mode_exec") {
51
+ const cmd = commandOf(params);
52
+ 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
+ return null;
56
+ }
57
+ const url = findUrl(params); if (!url || isOwnCheckUrl(url)) return null;
58
+ if (hasPaymentHeader(params)) return { url, method, via: "payment-header" };
59
+ if (pattern.test(name)) return { url, method, via: "tool-name" };
60
+ return null;
61
+ }
62
+
63
+ function word(hex, i) { const w = hex.slice(10 + 64 * i, 10 + 64 * (i + 1)); return w.length === 64 ? w : null; }
64
+ function decodeCalldata(data) {
65
+ if (typeof data !== "string" || !/^0x[0-9a-fA-F]{8}/.test(data)) return null;
66
+ const sel = SELECTORS[data.slice(0, 10).toLowerCase()]; if (!sel) return null;
67
+ const sw = word(data, sel.spenderArg); if (!sw) return null;
68
+ const spender = "0x" + sw.slice(24);
69
+ if (sel.boolArg !== undefined) { const b = word(data, sel.boolArg); if (!b || BigInt("0x" + b) === 0n) return null; return { fn: sel.fn, spender, unlimited: true }; }
70
+ const aw = word(data, sel.amountArg); const amount = aw ? BigInt("0x" + aw) : null;
71
+ if (sel.fn === "approve" && amount === 0n) return null; // approve(spender, 0) is a revoke
72
+ const unlimited = amount !== null && (sel.fn === "permit2.approve" ? amount >= (1n << 160n) - 1n : amount >= MAX_UINT256 / 2n);
73
+ return { fn: sel.fn, spender, amount: amount === null ? null : amount.toString(), unlimited };
74
+ }
75
+ function chainOf(params, fallback) {
76
+ for (const [k, v] of walk(params)) if (/^(chain|chainid|chain_id|network|chainname)$/i.test(k) && (typeof v === "string" || typeof v === "number")) { const c = CHAINS[String(v).toLowerCase()]; if (c) return c; }
77
+ return fallback;
78
+ }
79
+
80
+ /** Is this tool call about to grant a token approval (tx or Permit signature)? -> { spender, chain, fn, unlimited, via } | null */
81
+ export function detectApproval(toolName, params, opts = {}) {
82
+ const name = String(toolName || ""); if (/^moneytools_/i.test(name)) return null;
83
+ const chain = chainOf(params, opts.defaultChain || "base");
84
+ for (const [, v] of walk(params)) { const d = decodeCalldata(v); if (d && ADDR.test(d.spender)) return { ...d, chain, via: "calldata" }; }
85
+ for (const [, v] of walk(params)) {
86
+ if (!isObj(v)) continue;
87
+ const fn = v.functionName ?? v.function ?? v.method ?? v.action;
88
+ if (typeof fn === "string" && APPROVE_FN.test(fn.replace(/\(.*$/, ""))) {
89
+ const args = Array.isArray(v.args) ? v.args : Array.isArray(v.arguments) ? v.arguments : [];
90
+ const spender = [v.spender, v.operator, args[0]].find((x) => typeof x === "string" && ADDR.test(x));
91
+ if (spender) { const amt = v.amount ?? v.value ?? args[1]; return { fn: fn.replace(/\(.*$/, ""), spender, chain, unlimited: amt === true || /^(max|unlimited|infinite)$/i.test(String(amt)) || (/^\d+$/.test(String(amt)) && BigInt(String(amt)) >= MAX_UINT256 / 2n), via: "structured" }; }
92
+ }
93
+ if (typeof v.primaryType === "string" && PERMIT_TYPES.test(v.primaryType) && isObj(v.message)) {
94
+ const spender = [v.message.spender, v.message?.details?.spender].find((x) => typeof x === "string" && ADDR.test(x));
95
+ if (spender) return { fn: `sign:${v.primaryType}`, spender, chain: CHAINS[String(v.domain?.chainId ?? "").toLowerCase()] || chain, unlimited: false, via: "typed-data" };
96
+ }
97
+ }
98
+ if (EXEC_TOOLS.test(name) || opts.toolKind === "code_mode_exec") {
99
+ const cmd = commandOf(params);
100
+ const m = /\bcast\s+send\b[^\n]*?["']?(approve|increaseAllowance|setApprovalForAll)\s*\([^)]*\)["']?\s+(0x[0-9a-fA-F]{40})/i.exec(cmd);
101
+ if (m) { const ch = /--chain(?:-id)?\s+(\S+)/.exec(cmd)?.[1]; return { fn: m[1], spender: m[2], chain: (ch && CHAINS[ch.toLowerCase()]) || chain, unlimited: /max|uint256\.max|115792089237316195423570985008687907853269984665640564039457584007913129639935/i.test(cmd), via: "exec:cast" }; }
102
+ }
103
+ return null;
104
+ }
package/src/guard.js ADDED
@@ -0,0 +1,85 @@
1
+ // Host-free plugin logic: config, decisions, the before_tool_call handler and the two explicit tools.
2
+ import { detectX402Payment, detectApproval, DEFAULT_PAYMENT_TOOL_PATTERN, CHAINS } from "./detect.js";
3
+ import { callCheck, resolvePayer, makeBudget, precheckUrl, walletRiskUrl, PRICES, CheckError } from "./checks.js";
4
+
5
+ export const PLUGIN_ID = "moneytools-guard";
6
+ export const DEFAULTS = { autoPay: false, payer: "auto", privateKeyEnv: "X402_PRIVATE_KEY", dailyBudgetUsd: 0.25, precheckPayments: true, checkApprovals: true,
7
+ onPrecheckWarn: "approve", onHighRisk: "block", onMediumRisk: "approve", onCheckError: "approve", defaultChain: "base", paymentToolPattern: "", cacheMinutes: 10 };
8
+
9
+ export function readConfig(raw = {}) {
10
+ const c = { ...DEFAULTS, ...(raw && typeof raw === "object" ? raw : {}) };
11
+ c.dailyBudgetUsd = Math.max(0, Math.min(Number(c.dailyBudgetUsd) || 0, 5));
12
+ let pattern = DEFAULT_PAYMENT_TOOL_PATTERN; if (c.paymentToolPattern) { try { pattern = new RegExp(c.paymentToolPattern, "i"); } catch {} }
13
+ c.pattern = pattern; return c;
14
+ }
15
+
16
+ const fmtUsd = (x) => `${Number(x).toFixed(3).replace(/0+$/, "").replace(/\.$/, "")} USDC`;
17
+ function approval(title, description, severity = "warning") { return { requireApproval: { title, description: description.slice(0, 900), severity, timeoutMs: 120000, allowedDecisions: ["allow-once", "deny"] } }; }
18
+ function onError(cfg, what, e) {
19
+ const msg = `MoneyTools ${what} did not run: ${e.message}`;
20
+ if (cfg.onCheckError === "allow") return undefined;
21
+ if (cfg.onCheckError === "block") return { block: true, blockReason: msg };
22
+ return approval(`Unchecked: ${what}`, `${msg}. Nothing was charged for the check. Continue without it?`, "warning");
23
+ }
24
+
25
+ /** Decision for a precheck result (https://api.moneytools.dev/v1/precheck). */
26
+ export function decidePrecheck(cfg, url, r) {
27
+ const v = String(r?.verdict || "").toLowerCase(); const why = [r?.summary, ...(r?.reasons || []), ...(r?.warnings || [])].filter(Boolean).join("; ").slice(0, 600);
28
+ if (v === "ok") return undefined;
29
+ if (v === "block") return { block: true, blockReason: `MoneyTools pay precheck blocked this payment to ${url}: ${why || "seller terms failed the check"}` };
30
+ if (v === "warn") return cfg.onPrecheckWarn === "allow" ? undefined : cfg.onPrecheckWarn === "block" ? { block: true, blockReason: `MoneyTools pay precheck warned: ${why}` } : approval("Pay precheck warning", `MoneyTools pay precheck flagged ${url}: ${why || "see warnings"}. Pay anyway?`);
31
+ if (v === "not_402") return approval("Not an x402 seller", `MoneyTools pay precheck: ${url} did not answer with a valid x402 402. Continue?`, "info");
32
+ return undefined;
33
+ }
34
+ /** Decision for a Wallet Risk Card (https://tools.moneytools.dev/v1/wallet-risk) on the approval spender. */
35
+ export function decideRisk(cfg, a, card) {
36
+ const level = String(card?.level || "").toLowerCase(); const head = `${card?.headline || `risk ${card?.riskScore ?? "?"}/100`} (grade ${card?.grade ?? "?"})`;
37
+ const what = `${a.unlimited ? "an UNLIMITED " : "a "}${a.fn} to spender ${a.spender} on ${a.chain}`;
38
+ if (card?.sanctioned === true) return { block: true, blockReason: `MoneyTools Wallet Risk Card: spender ${a.spender} is on the OFAC SDN list. Blocked ${what}.` };
39
+ if (level === "high" || level === "critical") return cfg.onHighRisk === "approve" ? approval("High-risk spender", `Wallet Risk Card for ${what}: ${head}. Approve anyway?`, "critical") : { block: true, blockReason: `MoneyTools Wallet Risk Card: high risk for ${what}: ${head}.` };
40
+ if (level === "medium") return cfg.onMediumRisk === "allow" ? undefined : cfg.onMediumRisk === "block" ? { block: true, blockReason: `MoneyTools Wallet Risk Card: medium risk for ${what}: ${head}.` } : approval("Check this spender", `Wallet Risk Card for ${what}: ${head}. Approve?`, "warning");
41
+ return undefined;
42
+ }
43
+
44
+ export function createGuard(rawCfg, deps = {}) {
45
+ const cfg = readConfig(rawCfg); const env = deps.env || process.env; const log = deps.logger || { info() {}, warn() {} };
46
+ const budget = makeBudget(cfg.dailyBudgetUsd, deps.now); const cache = new Map(); const ttl = cfg.cacheMinutes * 60000; const now = deps.now || (() => Date.now());
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));
51
+ const walletRisk = (address, chain) => cached(`w:${chain}:${address.toLowerCase()}`, () => run(walletRiskUrl(address, chain), PRICES.walletRisk));
52
+
53
+ async function beforeToolCall(event, ctx = {}) {
54
+ const name = event?.toolName || ctx.toolName; const params = event?.params || {}; const opts = { paymentToolPattern: cfg.pattern, defaultChain: cfg.defaultChain, toolKind: event?.toolKind || ctx.toolKind };
55
+ if (cfg.checkApprovals) { const a = detectApproval(name, params, opts);
56
+ 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
+ catch (e) { return onError(cfg, "Wallet Risk Card", e); } } }
58
+ 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); }
60
+ catch (e) { return onError(cfg, "pay precheck", e); } } }
61
+ return undefined;
62
+ }
63
+ return { cfg, budget, beforeToolCall, precheck, walletRisk, payer };
64
+ }
65
+
66
+ const text = (o) => ({ content: [{ type: "text", text: JSON.stringify(o, null, 2) }], details: o });
67
+ export function toolDefs(guard, Type) {
68
+ return [
69
+ { name: "moneytools_pay_precheck", description: `Check an x402 seller URL before paying: validates its 402 terms (network, amount, asset, payTo) and screens payTo against the OFAC SDN list. Free daily tier, then ${PRICES.precheck} USDC on Base, paid from your own wallet. Failed checks are not charged.`,
70
+ parameters: Type.Object({ url: Type.String({ description: "x402 endpoint you plan to pay" }), method: Type.Optional(Type.String({ description: "HTTP method of the paid call (default GET)" })) }),
71
+ async execute(_id, p) { try { const r = await guard.precheck(p.url, (p.method || "GET").toUpperCase()); return text({ ...r.data, paidUsd: r.paidUsd }); } catch (e) { return text({ error: e.code || "error", message: e.message, charged: false }); } } },
72
+ { name: "moneytools_wallet_risk", description: `Wallet Risk Card for an EVM address or ENS name before you pay, trust or approve it: 0-100 risk score, grade A-F, OFAC SDN match, address checks, open approvals. ${PRICES.walletRisk} USDC on Base, paid from your own wallet. Failed checks are not charged.`,
73
+ parameters: Type.Object({ address: Type.String({ description: "0x address or ENS name" }), chain: Type.Optional(Type.String({ description: `one of ${[...new Set(Object.values(CHAINS))].join(", ")} (default base)` })) }),
74
+ async execute(_id, p) { try { const r = await guard.walletRisk(p.address, CHAINS[String(p.chain || "base").toLowerCase()] || "base"); return text({ ...r.data, paidUsd: r.paidUsd }); } catch (e) { return text({ error: e.code || "error", message: e.message, charged: false }); } } },
75
+ ];
76
+ }
77
+
78
+ /** register(api) body shared by the entry point and tests. */
79
+ export function registerGuard(api, Type, deps = {}) {
80
+ const guard = createGuard(api.pluginConfig || {}, { logger: api.logger, ...deps });
81
+ api.on("before_tool_call", (event, ctx) => guard.beforeToolCall(event, ctx), { priority: 60, timeoutMs: 90000 });
82
+ for (const t of toolDefs(guard, Type)) api.registerTool(t);
83
+ return guard;
84
+ }
85
+ export { CheckError };