presign-guard-wallet 0.5.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,23 @@ 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
+
158
175
  ### One budget for all your agents (wallet server)
159
176
 
160
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.
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 {
package/index.js CHANGED
@@ -30,13 +30,14 @@ import { encodeFunctionData } from "viem";
30
30
  import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
31
31
  import { createLimiter, memoryStore } from "./limits.js";
32
32
  import { createRemoteLimiter } from "./remote.js";
33
+ import { AsyncLocalStorage } from "node:async_hooks";
33
34
 
34
35
  export { memoryStore };
35
36
 
36
37
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
37
38
  export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
38
39
  export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
39
- export const VERSION = "0.5.0";
40
+ export const VERSION = "0.6.0";
40
41
  export const CREDIT_HEADER = "x-credit-key";
41
42
  const ROUTE = "POST /v1/check";
42
43
 
@@ -74,6 +75,20 @@ export function checkRequestFor(method, args, { chainId, origin } = {}) {
74
75
 
75
76
  const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
76
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
+
77
92
  /**
78
93
  * @param {object} wallet a viem WalletClient
79
94
  * @param {object} options
@@ -188,9 +203,11 @@ export function guardWallet(wallet, {
188
203
 
189
204
  // Within the limits (or approved by onOverLimit): book, sign, and give it back if signing fails.
190
205
  async function withinLimits(method, request, verdict, run) {
206
+ const ctx = purchases.getStore();
207
+ const purchase = ctx?.info ?? null;
191
208
  let booked;
192
209
  try {
193
- booked = await limiter.reserve({ method, request, verdict });
210
+ booked = await limiter.reserve({ method, request, verdict, purchase });
194
211
  } catch (err) {
195
212
  throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
196
213
  }
@@ -199,14 +216,15 @@ export function guardWallet(wallet, {
199
216
  err.reasons = booked.reasons;
200
217
  throw err;
201
218
  }
219
+ if (booked.purchaseId) ctx?.purchaseIds.push(booked.purchaseId);
202
220
  let result;
203
221
  try {
204
222
  result = await run();
205
223
  } catch (err) {
206
- 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}`));
207
225
  throw err;
208
226
  }
209
- limiter.spent(booked.entries, result, { verdict });
227
+ limiter.spent(booked.entries, result, { verdict, purchase, purchaseId: booked.purchaseId });
210
228
  return result;
211
229
  }
212
230
 
@@ -233,6 +251,29 @@ export function guardWallet(wallet, {
233
251
  paused: () => paused,
234
252
  /** Per token: the limits, what was spent in the current window and what is left (null without limits). */
235
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
+ },
236
277
  };
237
278
 
238
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.5.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": {
package/remote.js CHANGED
@@ -24,9 +24,9 @@ export function createRemoteLimiter({ url, key, fetch: fetchImpl = globalThis.fe
24
24
 
25
25
  return {
26
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 })) };
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
30
  if (r.status === "paused") return { ok: false, paused: true, summary: r.summary ?? "paused on the wallet server", reasons: [] };
31
31
  if (r.status === "denied") return { ok: false, hardStop: true, summary: r.summary, reasons: r.reasons ?? [] };
32
32
  if (r.status !== "pending") throw new Error(`wallet server: unexpected answer ${r.status}`);
@@ -34,17 +34,19 @@ export function createRemoteLimiter({ url, key, fetch: fetchImpl = globalThis.fe
34
34
  const id = r.approvalId, summary = r.summary, deadline = (r.expiresAt ?? Date.now() + 600_000) + 10_000;
35
35
  while (Date.now() < deadline) {
36
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 };
37
+ if (a.status === "approved") return { ok: true, entries: (a.entries ?? []).map((x) => ({ id: x })), approved: true, purchaseId: a.purchaseId ?? null };
38
38
  if (a.status === "denied") return { ok: false, asked: true, summary: `${summary} (denied by the owner)`, reasons: [] };
39
39
  if (a.status === "expired") return { ok: false, asked: true, summary: `${summary} (no answer in time)`, reasons: [] };
40
40
  }
41
41
  return { ok: false, asked: true, summary: `${summary} (no answer in time)`, reasons: [] };
42
42
  },
43
- async release(entries) { if (entries?.length) await call("POST", "/v1/release", { entries: entries.map((e) => e.id) }); },
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
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}`));
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
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 }); },
48
50
  async spending() { return (await call("GET", "/v1/spending")).spending; },
49
51
  };
50
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;