presign-guard-wallet 0.4.0 → 0.6.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,36 @@ 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
+ ### Say what is being bought
159
+
160
+ Wrap a purchase in `withPurchase` to record what it is for. The URL and description then show up:
161
+ - in `onSpend`;
162
+ - in the Telegram approval message;
163
+ - on the wallet server's receipt for that payment.
164
+
165
+ `report` adds what happened afterwards.
166
+
167
+ ```js
168
+ const res = await wallet.withPurchase({ url, description: "BTC signal for the daily report" }, async (report) => {
169
+ const res = await payWithThisWallet(url); // an x402 fetch whose signer is this guarded wallet
170
+ report({ httpStatus: res.status });
171
+ return res;
172
+ });
173
+ ```
174
+
175
+ ### One budget for all your agents (wallet server)
176
+
177
+ 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.
178
+
179
+ ```js
180
+ const wallet = guardWallet(walletClient, {
181
+ pay,
182
+ server: { url: process.env.WALLET_SERVER_URL, key: process.env.WALLET_SERVER_KEY }, // instead of limits / onOverLimit / store
183
+ });
184
+ ```
185
+
186
+ If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
187
+
158
188
  ## Signed verdicts
159
189
 
160
190
  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
@@ -73,6 +73,22 @@ export interface OverLimitInfo {
73
73
  /** One line for a human, e.g. "8 USDC is over the limit of 20 per 24h (15 used)". */
74
74
  summary: string;
75
75
  spending: SpendingRow[];
76
+ /** What the agent said it is buying (withPurchase), or null. */
77
+ purchase: Purchase | null;
78
+ }
79
+
80
+ /** What is being bought, given to withPurchase. */
81
+ export interface Purchase {
82
+ url?: string;
83
+ description?: string;
84
+ }
85
+
86
+ /** What happened after signing, given to report() inside withPurchase. */
87
+ export interface PurchaseOutcome {
88
+ httpStatus?: number;
89
+ settlement?: { transaction?: string; network?: string; [key: string]: unknown };
90
+ error?: string;
91
+ [key: string]: unknown;
76
92
  }
77
93
 
78
94
  export interface SpendEntry {
@@ -88,6 +104,7 @@ export interface SpendEntry {
88
104
  result: unknown;
89
105
  verdict: PresignVerdict | null;
90
106
  receiptId: string | null;
107
+ purchase: Purchase | null;
91
108
  }
92
109
 
93
110
  /** Where spending is kept. amount is a decimal string at 18 decimals. */
@@ -107,6 +124,11 @@ export interface GuardControls {
107
124
  paused(): boolean;
108
125
  /** Per token: the limits, what was spent in the current window and what is left; null without limits. */
109
126
  spending(): Promise<SpendingRow[] | null>;
127
+ /**
128
+ * Record what is being bought: every signature made inside fn carries it (onSpend, the
129
+ * wallet server's receipts, approval messages). Call report() with what happened afterwards.
130
+ */
131
+ withPurchase<T>(info: Purchase, fn: (report: (outcome: PurchaseOutcome) => void) => Promise<T> | T): Promise<T>;
110
132
  }
111
133
 
112
134
  export interface GuardOptions {
@@ -138,6 +160,8 @@ export interface GuardOptions {
138
160
  onSpend?: (entry: SpendEntry) => void;
139
161
  /** Where spending is kept. Default in memory (gone on a restart); fileStore from "presign-guard-wallet/file-store" for a file. */
140
162
  store?: SpendingStore;
163
+ /** A wallet server keeps the limits, the shared budget and the approvals for all your agents (instead of limits, onOverLimit and store). */
164
+ server?: { url: string; key: string; fetch?: typeof globalThis.fetch; requestTimeoutMs?: number };
141
165
  }
142
166
 
143
167
  /** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
package/index.js CHANGED
@@ -29,13 +29,15 @@
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";
33
+ import { AsyncLocalStorage } from "node:async_hooks";
32
34
 
33
35
  export { memoryStore };
34
36
 
35
37
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
36
38
  export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
37
39
  export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
38
- export const VERSION = "0.4.0";
40
+ export const VERSION = "0.6.0";
39
41
  export const CREDIT_HEADER = "x-credit-key";
40
42
  const ROUTE = "POST /v1/check";
41
43
 
@@ -73,6 +75,20 @@ export function checkRequestFor(method, args, { chainId, origin } = {}) {
73
75
 
74
76
  const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
75
77
 
78
+ // What the agent says it is buying, for the signatures made inside withPurchase().
79
+ const purchases = new AsyncLocalStorage();
80
+ function cleanPurchase(info) {
81
+ if (!info || typeof info !== "object") throw new TypeError("withPurchase(info, fn): info must be { url?, description? }");
82
+ const out = {};
83
+ if (info.url !== undefined && info.url !== null) {
84
+ const url = String(info.url);
85
+ if (!/^https?:\/\//.test(url)) throw new TypeError("purchase url must start with https:// or http://");
86
+ out.url = url.slice(0, 500);
87
+ }
88
+ if (info.description !== undefined && info.description !== null) out.description = String(info.description).slice(0, 300);
89
+ return out;
90
+ }
91
+
76
92
  /**
77
93
  * @param {object} wallet a viem WalletClient
78
94
  * @param {object} options
@@ -90,6 +106,7 @@ const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
90
106
  * @param {object} [options.limits] spending limits: { tokens: { USDC: { perTx, perDay }, … }, unknownTokens, allow, window }
91
107
  * @param {(info: object) => boolean|Promise<boolean>} [options.onOverLimit] asked when a limit would be crossed; true = sign anyway
92
108
  * @param {(entry: object) => void} [options.onSpend] after each signed spend
109
+ * @param {{url: string, key: string}} [options.server] a wallet server (fizzl wallet-server) keeps the limits, budget and approvals for all your agents
93
110
  * @param {object} [options.store] where spending is kept (default in memory; fileStore from presign-guard-wallet/file-store)
94
111
  */
95
112
  export function guardWallet(wallet, {
@@ -108,6 +125,7 @@ export function guardWallet(wallet, {
108
125
  onOverLimit,
109
126
  onSpend,
110
127
  store,
128
+ server,
111
129
  } = {}) {
112
130
  if (!wallet || typeof wallet !== "object") throw new TypeError("wallet must be a viem WalletClient");
113
131
  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 +134,10 @@ export function guardWallet(wallet, {
116
134
  if (!["stop", "allow"].includes(onError)) throw new TypeError('onError must be "stop" or "allow"');
117
135
  if (!["require", "off"].includes(verifyReceipts)) throw new TypeError('verifyReceipts must be "require" or "off"');
118
136
 
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 });
137
+ 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");
138
+ if (server === undefined && limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
139
+ const limiter = server !== undefined ? createRemoteLimiter({ ...server, fetch: server.fetch ?? plainFetch, onSpend })
140
+ : limits === undefined ? null : createLimiter(limits, { store, onOverLimit, onSpend });
121
141
  let paused = false;
122
142
 
123
143
  let creditsLeft = null;
@@ -183,25 +203,28 @@ export function guardWallet(wallet, {
183
203
 
184
204
  // Within the limits (or approved by onOverLimit): book, sign, and give it back if signing fails.
185
205
  async function withinLimits(method, request, verdict, run) {
206
+ const ctx = purchases.getStore();
207
+ const purchase = ctx?.info ?? null;
186
208
  let booked;
187
209
  try {
188
- booked = await limiter.reserve({ method, request, verdict });
210
+ booked = await limiter.reserve({ method, request, verdict, purchase });
189
211
  } catch (err) {
190
212
  throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
191
213
  }
192
214
  if (!booked.ok) {
193
- const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: "over_limit", verdict, request });
215
+ const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: booked.paused ? "paused" : "over_limit", verdict, request });
194
216
  err.reasons = booked.reasons;
195
217
  throw err;
196
218
  }
219
+ if (booked.purchaseId) ctx?.purchaseIds.push(booked.purchaseId);
197
220
  let result;
198
221
  try {
199
222
  result = await run();
200
223
  } catch (err) {
201
- await limiter.release(booked.entries).catch((e) => console.warn(`[presign-guard-wallet] could not give back spending: ${e.message}`));
224
+ await limiter.release(booked.entries, { purchaseId: booked.purchaseId, error: err.message }).catch((e) => console.warn(`[presign-guard-wallet] could not give back spending: ${e.message}`));
202
225
  throw err;
203
226
  }
204
- limiter.spent(booked.entries, result, { verdict });
227
+ limiter.spent(booked.entries, result, { verdict, purchase, purchaseId: booked.purchaseId });
205
228
  return result;
206
229
  }
207
230
 
@@ -228,6 +251,29 @@ export function guardWallet(wallet, {
228
251
  paused: () => paused,
229
252
  /** Per token: the limits, what was spent in the current window and what is left (null without limits). */
230
253
  spending: async () => (limiter ? limiter.spending() : null),
254
+ /**
255
+ * Say what is being bought: every signature fn makes is recorded with { url, description }
256
+ * (onSpend, the wallet server's receipts, its Telegram approval messages). fn gets a
257
+ * report(outcome) function for what happened afterwards, e.g. { httpStatus, settlement }.
258
+ */
259
+ withPurchase: async (info, fn) => {
260
+ if (typeof fn !== "function") throw new TypeError("withPurchase(info, fn): fn must be a function");
261
+ const ctx = { info: cleanPurchase(info), purchaseIds: [], outcome: null };
262
+ const report = (outcome) => { ctx.outcome = outcome && typeof outcome === "object" ? outcome : null; };
263
+ const annotate = async (extra) => {
264
+ if (!limiter?.annotate || !ctx.purchaseIds.length || (!ctx.outcome && !extra)) return;
265
+ await limiter.annotate(ctx.purchaseIds, { ...(ctx.outcome ?? {}), ...(extra ?? {}) }).catch((e) => console.warn(`[presign-guard-wallet] could not record the outcome: ${e.message}`));
266
+ };
267
+ let out;
268
+ try {
269
+ out = await purchases.run(ctx, () => fn(report));
270
+ } catch (err) {
271
+ await annotate({ error: String(err?.message ?? err).slice(0, 300) });
272
+ throw err;
273
+ }
274
+ await annotate();
275
+ return out;
276
+ },
231
277
  };
232
278
 
233
279
  return new Proxy(wallet, {
package/limits.js CHANGED
@@ -219,7 +219,7 @@ export function createLimiter(limits, { store = memoryStore(), onOverLimit, onSp
219
219
  if (result.reasons.length) {
220
220
  const summary = result.reasons.map((r) => r.message).join("; ");
221
221
  if (result.hardStop || !onOverLimit) return { ok: false, ...result, summary };
222
- const approved = (await onOverLimit({ method: info.method, request: info.request, verdict: info.verdict, reasons: result.reasons, summary, spending: await summarize(used) })) === true;
222
+ const approved = (await onOverLimit({ method: info.method, request: info.request, verdict: info.verdict, reasons: result.reasons, summary, spending: await summarize(used), purchase: info.purchase ?? null })) === true;
223
223
  if (!approved) return { ok: false, ...result, summary, asked: true };
224
224
  }
225
225
  const entries = result.charges.filter((c) => c.amount > 0n).map((c) => ({ id: newId(), at: now(), budget: c.budget, amount: c.amount.toString(), method: info.method, chainId: info.request.chainId, to: spend.items[0]?.to ?? info.request.to ?? null }));
@@ -230,7 +230,7 @@ export function createLimiter(limits, { store = memoryStore(), onOverLimit, onSp
230
230
  spent(entries, result, info) {
231
231
  if (!onSpend) return;
232
232
  for (const e of entries) {
233
- try { onSpend({ ...e, amount: formatUnits(BigInt(e.amount), SCALE), result, verdict: info.verdict ?? null, receiptId: info.verdict?.receipt?.request_id ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); }
233
+ try { onSpend({ ...e, amount: formatUnits(BigInt(e.amount), SCALE), result, verdict: info.verdict ?? null, receiptId: info.verdict?.receipt?.request_id ?? null, purchase: info.purchase ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); }
234
234
  }
235
235
  },
236
236
  spending: async () => summarize(await usedNow()),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.4.0",
3
+ "version": "0.6.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,52 @@
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, purchase }) {
28
+ let r = await call("POST", "/v1/reserve", { method, request, verdict: verdict ?? null, ...(purchase ? { purchase } : {}) });
29
+ if (r.status === "ok") return { ok: true, entries: (r.entries ?? []).map((id) => ({ id })), purchaseId: r.purchaseId ?? null };
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, purchaseId: a.purchaseId ?? null };
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, info) { if (entries?.length) await call("POST", "/v1/release", { entries: entries.map((e) => e.id), ...(info?.purchaseId ? { purchaseId: info.purchaseId, error: String(info.error ?? "").slice(0, 300) || null } : {}) }); },
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, purchase: info?.purchase ?? null, purchaseId: info?.purchaseId ?? 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, ...(info?.purchaseId ? { purchaseId: info.purchaseId } : {}) }).catch((err) => console.warn(`[presign-guard-wallet] ${err.message}`));
47
+ },
48
+ // What happened after signing (e.g. the API's answer and the x402 settlement), on the server's receipt.
49
+ async annotate(purchaseIds, outcome) { await call("POST", "/v1/purchases/annotate", { ids: purchaseIds, outcome }); },
50
+ async spending() { return (await call("GET", "/v1/spending")).spending; },
51
+ };
52
+ }
package/telegram.js CHANGED
@@ -80,6 +80,11 @@ function poller(token, call) {
80
80
  function messageFor(info, label) {
81
81
  const lines = [`<b>${escape(label)} wants to sign something over your limit</b>`, ""];
82
82
  lines.push(escape(info.summary));
83
+ if (info.purchase?.description || info.purchase?.url) {
84
+ lines.push("");
85
+ if (info.purchase.description) lines.push(`for: ${escape(info.purchase.description)}`);
86
+ if (info.purchase.url) lines.push(`<code>${escape(info.purchase.url)}</code>`);
87
+ }
83
88
  const r = info.request ?? {};
84
89
  lines.push("", `<code>${escape(info.method)}</code> · chain ${escape(r.chainId)}${r.to ? ` · to <code>${escape(r.to)}</code>` : ""}`);
85
90
  const v = info.verdict?.verdict;