presign-guard-wallet 0.5.0 → 0.7.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
@@ -71,6 +71,8 @@ try {
71
71
 
72
72
  Chains: Ethereum (1), Optimism (10), BNB Chain (56), Polygon (137), Base (8453), Arbitrum (42161).
73
73
 
74
+ **Tempo** (4217, and the Moderato testnet 42431) is not covered by presign-guard. There the wallet signs exactly one thing, checked locally: a TIP-20 `transfer` or `transferWithMemo` of USDC.e (pathUSD on the testnet), with no value attached, counted toward your `USDC` limits. Anything else on Tempo is refused (`unsupported_chain`). Guard a Tempo wallet client next to your main one with `guarded.wrap(tempoWalletClient)`: both share the same limits, pause and purchase records.
75
+
74
76
  ## Prepaid credits
75
77
 
76
78
  Agents that sign a lot can prepay: one x402 payment of **$0.80 for 100 checks** or **$7.00 for 1000** (20% / 30% off), valid for a year.
@@ -155,6 +157,23 @@ These limits live in your agent's software: they stop a confused or manipulated
155
157
 
156
158
  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
159
 
160
+ ### Say what is being bought
161
+
162
+ Wrap a purchase in `withPurchase` to record what it is for. The URL and description then show up:
163
+ - in `onSpend`;
164
+ - in the Telegram approval message;
165
+ - on the wallet server's receipt for that payment.
166
+
167
+ `report` adds what happened afterwards.
168
+
169
+ ```js
170
+ const res = await wallet.withPurchase({ url, description: "BTC signal for the daily report" }, async (report) => {
171
+ const res = await payWithThisWallet(url); // an x402 fetch whose signer is this guarded wallet
172
+ report({ httpStatus: res.status });
173
+ return res;
174
+ });
175
+ ```
176
+
158
177
  ### One budget for all your agents (wallet server)
159
178
 
160
179
  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
@@ -3,6 +3,8 @@ import type { WalletClient } from "viem";
3
3
  export declare const PRESIGN_URL: string;
4
4
  export declare const PRESIGN_SIGNERS: string[];
5
5
  export declare const SUPPORTED_CHAINS: number[];
6
+ /** Tempo chain id -> the stablecoins (lowercase) the wallet may transfer there, checked locally instead of by presign-guard. */
7
+ export declare const TEMPO_TOKENS: Record<number, string[]>;
6
8
  export declare const VERSION: string;
7
9
  export declare const CREDIT_HEADER: string;
8
10
 
@@ -73,6 +75,22 @@ export interface OverLimitInfo {
73
75
  /** One line for a human, e.g. "8 USDC is over the limit of 20 per 24h (15 used)". */
74
76
  summary: string;
75
77
  spending: SpendingRow[];
78
+ /** What the agent said it is buying (withPurchase), or null. */
79
+ purchase: Purchase | null;
80
+ }
81
+
82
+ /** What is being bought, given to withPurchase. */
83
+ export interface Purchase {
84
+ url?: string;
85
+ description?: string;
86
+ }
87
+
88
+ /** What happened after signing, given to report() inside withPurchase. */
89
+ export interface PurchaseOutcome {
90
+ httpStatus?: number;
91
+ settlement?: { transaction?: string; network?: string; [key: string]: unknown };
92
+ error?: string;
93
+ [key: string]: unknown;
76
94
  }
77
95
 
78
96
  export interface SpendEntry {
@@ -88,6 +106,7 @@ export interface SpendEntry {
88
106
  result: unknown;
89
107
  verdict: PresignVerdict | null;
90
108
  receiptId: string | null;
109
+ purchase: Purchase | null;
91
110
  }
92
111
 
93
112
  /** Where spending is kept. amount is a decimal string at 18 decimals. */
@@ -107,6 +126,13 @@ export interface GuardControls {
107
126
  paused(): boolean;
108
127
  /** Per token: the limits, what was spent in the current window and what is left; null without limits. */
109
128
  spending(): Promise<SpendingRow[] | null>;
129
+ /**
130
+ * Record what is being bought: every signature made inside fn carries it (onSpend, the
131
+ * wallet server's receipts, approval messages). Call report() with what happened afterwards.
132
+ */
133
+ withPurchase<T>(info: Purchase, fn: (report: (outcome: PurchaseOutcome) => void) => Promise<T> | T): Promise<T>;
134
+ /** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
135
+ wrap<W extends object>(wallet: W): W & GuardControls;
110
136
  }
111
137
 
112
138
  export interface GuardOptions {
package/index.js CHANGED
@@ -25,18 +25,31 @@
25
25
  // function, e.g. ask the user on their phone); without it, it stops. These
26
26
  // limits live in the agent's software: an agent with the raw key can go around
27
27
  // them. See limits.js for what counts as spending.
28
+ //
29
+ // Tempo (chain 4217, testnet 42431) is not covered by presign-guard. There the
30
+ // wallet signs only one thing, checked here: a TIP-20 transfer or
31
+ // transferWithMemo of USDC.e (pathUSD on the testnet), with no value attached,
32
+ // which counts toward the USDC limits like any other USDC transfer. Anything
33
+ // else on Tempo is refused (code "unsupported_chain").
28
34
 
29
35
  import { encodeFunctionData } from "viem";
30
36
  import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
31
37
  import { createLimiter, memoryStore } from "./limits.js";
32
38
  import { createRemoteLimiter } from "./remote.js";
39
+ import { AsyncLocalStorage } from "node:async_hooks";
33
40
 
34
41
  export { memoryStore };
35
42
 
36
43
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
37
44
  export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
38
45
  export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
39
- export const VERSION = "0.5.0";
46
+ // Tempo: the stablecoins the wallet may send there (the ones the USDC limit covers).
47
+ export const TEMPO_TOKENS = {
48
+ 4217: ["0x20c000000000000000000000b9537d11c60e8b50"],
49
+ 42431: ["0x20c0000000000000000000000000000000000000"],
50
+ };
51
+ const TEMPO_TRANSFERS = new Set(["transfer", "transferWithMemo"]);
52
+ export const VERSION = "0.7.0";
40
53
  export const CREDIT_HEADER = "x-credit-key";
41
54
  const ROUTE = "POST /v1/check";
42
55
 
@@ -74,6 +87,20 @@ export function checkRequestFor(method, args, { chainId, origin } = {}) {
74
87
 
75
88
  const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
76
89
 
90
+ // What the agent says it is buying, for the signatures made inside withPurchase().
91
+ const purchases = new AsyncLocalStorage();
92
+ function cleanPurchase(info) {
93
+ if (!info || typeof info !== "object") throw new TypeError("withPurchase(info, fn): info must be { url?, description? }");
94
+ const out = {};
95
+ if (info.url !== undefined && info.url !== null) {
96
+ const url = String(info.url);
97
+ if (!/^https?:\/\//.test(url)) throw new TypeError("purchase url must start with https:// or http://");
98
+ out.url = url.slice(0, 500);
99
+ }
100
+ if (info.description !== undefined && info.description !== null) out.description = String(info.description).slice(0, 300);
101
+ return out;
102
+ }
103
+
77
104
  /**
78
105
  * @param {object} wallet a viem WalletClient
79
106
  * @param {object} options
@@ -188,9 +215,11 @@ export function guardWallet(wallet, {
188
215
 
189
216
  // Within the limits (or approved by onOverLimit): book, sign, and give it back if signing fails.
190
217
  async function withinLimits(method, request, verdict, run) {
218
+ const ctx = purchases.getStore();
219
+ const purchase = ctx?.info ?? null;
191
220
  let booked;
192
221
  try {
193
- booked = await limiter.reserve({ method, request, verdict });
222
+ booked = await limiter.reserve({ method, request, verdict, purchase });
194
223
  } catch (err) {
195
224
  throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
196
225
  }
@@ -199,21 +228,37 @@ export function guardWallet(wallet, {
199
228
  err.reasons = booked.reasons;
200
229
  throw err;
201
230
  }
231
+ if (booked.purchaseId) ctx?.purchaseIds.push(booked.purchaseId);
202
232
  let result;
203
233
  try {
204
234
  result = await run();
205
235
  } catch (err) {
206
- await limiter.release(booked.entries).catch((e) => console.warn(`[presign-guard-wallet] could not give back spending: ${e.message}`));
236
+ 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
237
  throw err;
208
238
  }
209
- limiter.spent(booked.entries, result, { verdict });
239
+ limiter.spent(booked.entries, result, { verdict, purchase, purchaseId: booked.purchaseId });
210
240
  return result;
211
241
  }
212
242
 
213
- async function guarded(method, original, args, rest) {
243
+ // Tempo: only a plain stablecoin transfer, checked here instead of by presign-guard.
244
+ function tempoRequest(method, args, chainId) {
245
+ const tokens = TEMPO_TOKENS[chainId];
246
+ const ok = method === "writeContract" && tokens.includes(String(args?.address ?? "").toLowerCase())
247
+ && TEMPO_TRANSFERS.has(args?.functionName) && !(BigInt(args?.value ?? 0n) > 0n);
248
+ let request = null;
249
+ try { request = ok ? checkRequestFor(method, args, { chainId, origin }) : null; } catch { request = null; }
250
+ if (!request) throw new PresignBlockedError(`on Tempo (chain ${chainId}) this wallet only sends USDC.e transfers; nothing was signed`, { code: "unsupported_chain" });
251
+ return request;
252
+ }
253
+
254
+ async function guarded(target, method, original, args, rest) {
214
255
  if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
215
- const chainId = args?.chain?.id ?? wallet.chain?.id;
256
+ const chainId = args?.chain?.id ?? target.chain?.id;
216
257
  const run = () => original(args, ...rest);
258
+ if (TEMPO_TOKENS[chainId]) {
259
+ const request = tempoRequest(method, args, chainId);
260
+ return limiter ? withinLimits(method, request, null, run) : run();
261
+ }
217
262
  const request = checkRequestFor(method, args, { chainId, origin });
218
263
  if (!request) {
219
264
  // A contract deployment is not checked, but the value it sends still counts.
@@ -231,16 +276,48 @@ export function guardWallet(wallet, {
231
276
  pause: () => { paused = true; },
232
277
  resume: () => { paused = false; },
233
278
  paused: () => paused,
279
+ /**
280
+ * The same guard (checks, limits, pause, purchases) on another viem WalletClient, e.g. one
281
+ * for Tempo next to the one for Base: both spend from one budget.
282
+ */
283
+ wrap: (other) => {
284
+ if (!other || typeof other !== "object") throw new TypeError("wrap(wallet): wallet must be a viem WalletClient");
285
+ return proxyFor(other);
286
+ },
234
287
  /** Per token: the limits, what was spent in the current window and what is left (null without limits). */
235
288
  spending: async () => (limiter ? limiter.spending() : null),
289
+ /**
290
+ * Say what is being bought: every signature fn makes is recorded with { url, description }
291
+ * (onSpend, the wallet server's receipts, its Telegram approval messages). fn gets a
292
+ * report(outcome) function for what happened afterwards, e.g. { httpStatus, settlement }.
293
+ */
294
+ withPurchase: async (info, fn) => {
295
+ if (typeof fn !== "function") throw new TypeError("withPurchase(info, fn): fn must be a function");
296
+ const ctx = { info: cleanPurchase(info), purchaseIds: [], outcome: null };
297
+ const report = (outcome) => { ctx.outcome = outcome && typeof outcome === "object" ? outcome : null; };
298
+ const annotate = async (extra) => {
299
+ if (!limiter?.annotate || !ctx.purchaseIds.length || (!ctx.outcome && !extra)) return;
300
+ await limiter.annotate(ctx.purchaseIds, { ...(ctx.outcome ?? {}), ...(extra ?? {}) }).catch((e) => console.warn(`[presign-guard-wallet] could not record the outcome: ${e.message}`));
301
+ };
302
+ let out;
303
+ try {
304
+ out = await purchases.run(ctx, () => fn(report));
305
+ } catch (err) {
306
+ await annotate({ error: String(err?.message ?? err).slice(0, 300) });
307
+ throw err;
308
+ }
309
+ await annotate();
310
+ return out;
311
+ },
236
312
  };
237
313
 
238
- return new Proxy(wallet, {
314
+ const proxyFor = (w) => new Proxy(w, {
239
315
  get(target, prop, receiver) {
240
316
  if (Object.hasOwn(extras, prop) && !(prop in target)) return extras[prop];
241
317
  const value = Reflect.get(target, prop, receiver);
242
318
  if (typeof prop !== "string" || !GUARDED.has(prop) || typeof value !== "function") return value;
243
- return (args, ...rest) => guarded(prop, value.bind(target), args, rest);
319
+ return (args, ...rest) => guarded(target, prop, value.bind(target), args, rest);
244
320
  },
245
321
  });
322
+ return proxyFor(wallet);
246
323
  }
package/limits.js CHANGED
@@ -5,7 +5,7 @@
5
5
  //
6
6
  // What counts as spending:
7
7
  // - the native value sent with a transaction (ETH, BNB, POL);
8
- // - an ERC-20 transfer or transferFrom;
8
+ // - an ERC-20 transfer or transferFrom (and a TIP-20 transferWithMemo on Tempo);
9
9
  // - an allowance (approve, increaseAllowance, Permit, Permit2): whoever gets
10
10
  // it can spend that amount, so it counts when it is given; an unlimited
11
11
  // one or setApprovalForAll is over any limit;
@@ -29,6 +29,9 @@ const USDC = {
29
29
  137: [["0x3c499c542cef5e3811e1192ce70d8cc03d5c3359", 6], ["0x2791bca1f2de4661ed88a30c99a7a9449aa84174", 6]],
30
30
  8453: [["0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", 6]],
31
31
  42161: [["0xaf88d065e77c8cc2239327c5edb3a432268e5831", 6], ["0xff970a61a04b1ca14834a43f5de4533ebddb5cc8", 6]],
32
+ // Tempo: USDC.e (bridged USDC, what MPP charges in), and pathUSD on the Moderato testnet.
33
+ 4217: [["0x20c000000000000000000000b9537d11c60e8b50", 6]],
34
+ 42431: [["0x20c0000000000000000000000000000000000000", 6]],
32
35
  };
33
36
  const NATIVE_SYMBOL = { 1: "ETH", 10: "ETH", 8453: "ETH", 42161: "ETH", 56: "BNB", 137: "POL" };
34
37
  export const KNOWN_TOKENS = ["USDC", "ETH", "BNB", "POL"];
@@ -38,6 +41,7 @@ const ERC20_ABI = parseAbi([
38
41
  "function increaseAllowance(address spender, uint256 addedValue)",
39
42
  "function transfer(address to, uint256 amount)",
40
43
  "function transferFrom(address from, address to, uint256 amount)",
44
+ "function transferWithMemo(address to, uint256 amount, bytes32 memo)",
41
45
  "function setApprovalForAll(address operator, bool approved)",
42
46
  ]);
43
47
 
@@ -110,7 +114,7 @@ export function spendFor(request, verdict) {
110
114
  if (call.functionName === "approve" || call.functionName === "increaseAllowance") {
111
115
  if (a[1] > 0n) out.items.push({ chainId, token: to, amount: capped(a[1]), to: lower(a[0]) });
112
116
  out.counterparties.push(lower(a[0]));
113
- } else if (call.functionName === "transfer") {
117
+ } else if (call.functionName === "transfer" || call.functionName === "transferWithMemo") {
114
118
  out.items.push({ chainId, token: to, amount: capped(a[1]), to: lower(a[0]) });
115
119
  out.counterparties.push(lower(a[0]));
116
120
  } else if (call.functionName === "transferFrom") {
@@ -219,7 +223,7 @@ export function createLimiter(limits, { store = memoryStore(), onOverLimit, onSp
219
223
  if (result.reasons.length) {
220
224
  const summary = result.reasons.map((r) => r.message).join("; ");
221
225
  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;
226
+ 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
227
  if (!approved) return { ok: false, ...result, summary, asked: true };
224
228
  }
225
229
  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 +234,7 @@ export function createLimiter(limits, { store = memoryStore(), onOverLimit, onSp
230
234
  spent(entries, result, info) {
231
235
  if (!onSpend) return;
232
236
  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}`); }
237
+ 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
238
  }
235
239
  },
236
240
  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.7.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;