presign-guard-wallet 0.4.0 → 0.5.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 CHANGED
@@ -155,6 +155,19 @@ These limits live in your agent's software: they stop a confused or manipulated
155
155
 
156
156
  Only the chat you name (or the `allowedUserIds` you list) can answer; anyone else's tap is refused. No server is needed: the wallet asks Telegram for your tap itself (long polling), so the bot must not have a webhook, and one bot serves one agent process at a time (a second process polling the same bot makes Telegram refuse both; the request then fails and nothing is signed). If Telegram cannot be reached, the wallet stops (`limit_unavailable`) rather than signing.
157
157
 
158
+ ### One budget for all your agents (wallet server)
159
+
160
+ With several agents, run the [wallet server](../wallet-server): one price rule and daily budget for all of them, approvals on its dashboard and on Telegram, and an activity log. The agent keeps its keys and still signs and pays itself; it only asks the server first.
161
+
162
+ ```js
163
+ const wallet = guardWallet(walletClient, {
164
+ pay,
165
+ server: { url: process.env.WALLET_SERVER_URL, key: process.env.WALLET_SERVER_KEY }, // instead of limits / onOverLimit / store
166
+ });
167
+ ```
168
+
169
+ If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
170
+
158
171
  ## Signed verdicts
159
172
 
160
173
  presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash of your request inside the signed body; see [Signed verdicts](https://github.com/Fizzl13/presign-guard#signed-verdicts)). The wallet checks that signature before it acts:
package/index.d.ts CHANGED
@@ -138,6 +138,8 @@ export interface GuardOptions {
138
138
  onSpend?: (entry: SpendEntry) => void;
139
139
  /** Where spending is kept. Default in memory (gone on a restart); fileStore from "presign-guard-wallet/file-store" for a file. */
140
140
  store?: SpendingStore;
141
+ /** A wallet server keeps the limits, the shared budget and the approvals for all your agents (instead of limits, onOverLimit and store). */
142
+ server?: { url: string; key: string; fetch?: typeof globalThis.fetch; requestTimeoutMs?: number };
141
143
  }
142
144
 
143
145
  /** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
package/index.js CHANGED
@@ -29,13 +29,14 @@
29
29
  import { encodeFunctionData } from "viem";
30
30
  import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
31
31
  import { createLimiter, memoryStore } from "./limits.js";
32
+ import { createRemoteLimiter } from "./remote.js";
32
33
 
33
34
  export { memoryStore };
34
35
 
35
36
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
36
37
  export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
37
38
  export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
38
- export const VERSION = "0.4.0";
39
+ export const VERSION = "0.5.0";
39
40
  export const CREDIT_HEADER = "x-credit-key";
40
41
  const ROUTE = "POST /v1/check";
41
42
 
@@ -90,6 +91,7 @@ const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
90
91
  * @param {object} [options.limits] spending limits: { tokens: { USDC: { perTx, perDay }, … }, unknownTokens, allow, window }
91
92
  * @param {(info: object) => boolean|Promise<boolean>} [options.onOverLimit] asked when a limit would be crossed; true = sign anyway
92
93
  * @param {(entry: object) => void} [options.onSpend] after each signed spend
94
+ * @param {{url: string, key: string}} [options.server] a wallet server (fizzl wallet-server) keeps the limits, budget and approvals for all your agents
93
95
  * @param {object} [options.store] where spending is kept (default in memory; fileStore from presign-guard-wallet/file-store)
94
96
  */
95
97
  export function guardWallet(wallet, {
@@ -108,6 +110,7 @@ export function guardWallet(wallet, {
108
110
  onOverLimit,
109
111
  onSpend,
110
112
  store,
113
+ server,
111
114
  } = {}) {
112
115
  if (!wallet || typeof wallet !== "object") throw new TypeError("wallet must be a viem WalletClient");
113
116
  if (creditKey !== undefined && !/^pgc_[A-Za-z0-9_-]{43}$/.test(String(creditKey))) throw new TypeError("creditKey must be a presign-guard credit key (pgc_…)");
@@ -116,8 +119,10 @@ export function guardWallet(wallet, {
116
119
  if (!["stop", "allow"].includes(onError)) throw new TypeError('onError must be "stop" or "allow"');
117
120
  if (!["require", "off"].includes(verifyReceipts)) throw new TypeError('verifyReceipts must be "require" or "off"');
118
121
 
119
- if (limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
120
- const limiter = limits === undefined ? null : createLimiter(limits, { store, onOverLimit, onSpend });
122
+ if (server !== undefined && (limits !== undefined || onOverLimit || store)) throw new TypeError("with server, the limits and approvals live on the wallet server: leave out limits, onOverLimit and store");
123
+ if (server === undefined && limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
124
+ const limiter = server !== undefined ? createRemoteLimiter({ ...server, fetch: server.fetch ?? plainFetch, onSpend })
125
+ : limits === undefined ? null : createLimiter(limits, { store, onOverLimit, onSpend });
121
126
  let paused = false;
122
127
 
123
128
  let creditsLeft = null;
@@ -190,7 +195,7 @@ export function guardWallet(wallet, {
190
195
  throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
191
196
  }
192
197
  if (!booked.ok) {
193
- const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: "over_limit", verdict, request });
198
+ const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: booked.paused ? "paused" : "over_limit", verdict, request });
194
199
  err.reasons = booked.reasons;
195
200
  throw err;
196
201
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,6 +15,9 @@
15
15
  "./telegram": {
16
16
  "types": "./telegram.d.ts",
17
17
  "default": "./telegram.js"
18
+ },
19
+ "./limits": {
20
+ "default": "./limits.js"
18
21
  }
19
22
  },
20
23
  "main": "./index.js",
@@ -26,6 +29,7 @@
26
29
  "file-store.js",
27
30
  "file-store.d.ts",
28
31
  "telegram.js",
32
+ "remote.js",
29
33
  "telegram.d.ts",
30
34
  "README.md",
31
35
  "LICENSE"
package/remote.js ADDED
@@ -0,0 +1,50 @@
1
+ // Limits kept by a wallet server instead of in this process: one budget and
2
+ // one set of rules for all of an owner's agents, approvals on the server's
3
+ // dashboard or Telegram. Same interface as createLimiter in limits.js.
4
+ //
5
+ // The server only counts, asks and records; this agent still signs and pays
6
+ // itself, and its keys never leave it. When the server can't be reached, the
7
+ // wallet stops (limit_unavailable) instead of signing.
8
+
9
+ export function createRemoteLimiter({ url, key, fetch: fetchImpl = globalThis.fetch, requestTimeoutMs = 35_000, onSpend } = {}) {
10
+ if (typeof url !== "string" || !/^https?:\/\//.test(url)) throw new TypeError("server.url must be the wallet server's URL (https://…)");
11
+ if (typeof key !== "string" || !key.startsWith("awk_")) throw new TypeError("server.key must be an agent key (awk_…) made on the server's dashboard");
12
+ const base = url.replace(/\/$/, "");
13
+
14
+ async function call(method, path, body) {
15
+ const ctl = new AbortController();
16
+ const t = setTimeout(() => ctl.abort(), requestTimeoutMs);
17
+ try {
18
+ const res = await fetchImpl(`${base}${path}`, { method, headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json" }, body: body === undefined ? undefined : JSON.stringify(body, (_k, v) => (typeof v === "bigint" ? v.toString() : v)), signal: ctl.signal });
19
+ const data = await res.json().catch(() => null);
20
+ if (!res.ok) throw new Error(`wallet server ${path}: ${data?.message ?? data?.error ?? `HTTP ${res.status}`}`);
21
+ return data;
22
+ } finally { clearTimeout(t); }
23
+ }
24
+
25
+ return {
26
+ remote: true,
27
+ async reserve({ method, request, verdict }) {
28
+ let r = await call("POST", "/v1/reserve", { method, request, verdict: verdict ?? null });
29
+ if (r.status === "ok") return { ok: true, entries: (r.entries ?? []).map((id) => ({ id })) };
30
+ if (r.status === "paused") return { ok: false, paused: true, summary: r.summary ?? "paused on the wallet server", reasons: [] };
31
+ if (r.status === "denied") return { ok: false, hardStop: true, summary: r.summary, reasons: r.reasons ?? [] };
32
+ if (r.status !== "pending") throw new Error(`wallet server: unexpected answer ${r.status}`);
33
+ // Over a limit: the owner decides on the dashboard or Telegram. Wait for it.
34
+ const id = r.approvalId, summary = r.summary, deadline = (r.expiresAt ?? Date.now() + 600_000) + 10_000;
35
+ while (Date.now() < deadline) {
36
+ const a = await call("GET", `/v1/approvals/${encodeURIComponent(id)}?wait=25`);
37
+ if (a.status === "approved") return { ok: true, entries: (a.entries ?? []).map((x) => ({ id: x })), approved: true };
38
+ if (a.status === "denied") return { ok: false, asked: true, summary: `${summary} (denied by the owner)`, reasons: [] };
39
+ if (a.status === "expired") return { ok: false, asked: true, summary: `${summary} (no answer in time)`, reasons: [] };
40
+ }
41
+ return { ok: false, asked: true, summary: `${summary} (no answer in time)`, reasons: [] };
42
+ },
43
+ async release(entries) { if (entries?.length) await call("POST", "/v1/release", { entries: entries.map((e) => e.id) }); },
44
+ spent(entries, result, info) {
45
+ for (const e of entries ?? []) { try { onSpend?.({ id: e.id, result, verdict: info?.verdict ?? null, receiptId: info?.verdict?.receipt?.request_id ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); } }
46
+ if (entries?.length) call("POST", "/v1/spent", { entries: entries.map((e) => e.id), result: typeof result === "string" ? result : null }).catch((err) => console.warn(`[presign-guard-wallet] ${err.message}`));
47
+ },
48
+ async spending() { return (await call("GET", "/v1/spending")).spending; },
49
+ };
50
+ }