presign-guard-wallet 0.20.1 → 0.21.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
@@ -2,7 +2,7 @@
2
2
 
3
3
  A [viem](https://viem.sh) wallet for AI agents that asks [presign-guard](https://presign-guard.fizzl.eu) before it signs. Solana signers too: see [Solana](#solana-usdc).
4
4
 
5
- Before every `sendTransaction`, `writeContract` and `signTypedData`, the wallet pays **$0.01** (x402, USDC on Base) for a verdict on exactly what is about to be signed, and acts on it:
5
+ Before every `sendTransaction`, `writeContract`, `signTypedData` and `signAuthorization` (EIP-7702), the wallet pays **$0.01** (x402, USDC on Base) for a verdict on exactly what is about to be signed, and acts on it:
6
6
 
7
7
  | Verdict | What the wallet does |
8
8
  |---|---|
@@ -61,8 +61,8 @@ try {
61
61
  | `pay` | required (optional with `creditKey`) | A fetch that pays x402 (`wrapFetchWithPayment`); cap it with spend controls |
62
62
  | `creditKey` | | A presign-guard credit key (`pgc_…`): checks are paid from prepaid credits first, then with `pay`. See [Prepaid credits](#prepaid-credits) |
63
63
  | `fetch` | `globalThis.fetch` | Plain fetch used for credit-paid checks |
64
- | `onOrange` | `"stop"` | `"stop"`, `"allow"` or `async (verdict, { method, request }) => boolean` |
65
- | `onError` | `"stop"` | When the check cannot be done (outage, a chain presign-guard does not cover): `"stop"` or `"allow"` |
64
+ | `onOrange` | `"stop"` | `"stop"`, `"allow"` or `async (verdict, { method, request }) => boolean`. `"allow"` does not cover [EIP-7702 authorizations](#eip-7702-authorizations) |
65
+ | `onError` | `"stop"` | When the check cannot be done (outage, a chain presign-guard does not cover): `"stop"` or `"allow"`. An EIP-7702 authorization always stops |
66
66
  | `origin` | | The site asking for the signature: its domain age and phishing lists are checked too |
67
67
  | `onVerdict` | | `(verdict, { method, request, paidWith, creditsLeft }) => void`, e.g. for logging; `paidWith` is `"credits"` or `"x402"` |
68
68
  | `verifyReceipts` | `"require"` | Check presign-guard's signed receipt on every verdict; `"off"` skips it |
@@ -232,6 +232,29 @@ const wallet = guardWallet(walletClient, {
232
232
 
233
233
  If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
234
234
 
235
+ ## EIP-7702 authorizations
236
+
237
+ An EIP-7702 authorization makes the wallet run a contract's code. That contract can then move everything the wallet holds, on every later call, without asking for another signature: this is how "sweeper" drainers empty wallets. So the wallet checks every authorization before it is signed (`signAuthorization`, type `authorization` in presign-guard), and is stricter about it than about anything else:
238
+
239
+ | Verdict | What the wallet does |
240
+ |---|---|
241
+ | 🟢 green | Signs: revoking a delegation (`0x000…000`), or a contract on GoPlus's trust list |
242
+ | 🟠 orange | Signs only when your `onOrange` **function** returns `true` (`"allow"` does not cover it): any other contract (`EIP7702_AUTHORIZATION`), one valid on every chain (`chainId: 0`), one deployed recently |
243
+ | 🔴 red | Never signs: no contract at the address, a contract that is itself a delegated wallet, an unverified, flagged or sanctioned contract |
244
+
245
+ A failed check stops too, also with `onError: "allow"`. The wallet signs exactly the chain id it checked, and an authorization counts toward no spending limit (it moves nothing by itself).
246
+
247
+ ```js
248
+ const wallet = guardWallet(walletClient, {
249
+ pay,
250
+ onOrange: async (verdict, { method, request }) => method === "signAuthorization" ? askUser(request.address, verdict.reasons) : false,
251
+ });
252
+ const authorization = await wallet.signAuthorization({ contractAddress: smartAccount }); // the contract you chose to delegate to
253
+ await wallet.sendTransaction({ to: account.address, data, authorizationList: [authorization] });
254
+ ```
255
+
256
+ Authorizations in a transaction's `authorizationList` are checked as well: one signed with `signAuthorization` was checked then and is not charged again, one the sending account signed some other way is checked now, and one signed by another account (or for another chain) puts nothing of this wallet at risk and is left alone. On Tempo the wallet signs and sends no authorizations.
257
+
235
258
  ## Checking x402 payments against what the seller asked
236
259
 
237
260
  Wrap the x402 payment scheme with `x402Checked` and the payment requirements it pays (the `accepts` entry it chose) go along with the presign-guard check of its EIP-3009 signature. presign-guard then makes a signature that pays more than asked, someone else, another token or another chain red (`X402_AMOUNT_ABOVE_REQUIRED`, `X402_RECIPIENT_MISMATCH`, `X402_ASSET_MISMATCH`, `X402_NETWORK_MISMATCH`), and one that stays valid far longer than the seller's timeout orange (`X402_VALIDITY_TOO_LONG`), before anything is signed. It catches a hostile server or a broken client library.
@@ -350,7 +373,7 @@ presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash
350
373
 
351
374
  ## Costs and coverage
352
375
 
353
- - $0.01 per checked signature, paid with your `pay` fetch, or $0.008 / $0.007 with [prepaid credits](#prepaid-credits). Calls presign-guard does not cover (contract deployments) are not checked and cost nothing; `signMessage` is checked unless `checkMessages: false`.
376
+ - $0.01 per checked signature (an EIP-7702 authorization is one), paid with your `pay` fetch, or $0.008 / $0.007 with [prepaid credits](#prepaid-credits). Calls presign-guard does not cover (contract deployments) are not checked and cost nothing; `signMessage` is checked unless `checkMessages: false`.
354
377
  - presign-guard reads public data (GoPlus, RugCheck, DexScreener, OFAC via PG1, phishing lists). A green verdict means no known problem was found, not a guarantee.
355
378
  - The requests carry `user-agent: presign-guard-wallet/<version>` so the service can count how often the package is used.
356
379
 
package/index.d.ts CHANGED
@@ -27,7 +27,8 @@ export interface PresignVerdict {
27
27
  export type CheckRequest =
28
28
  | { type: "transaction"; chainId: number; to: string; data: string; value: string; origin?: string; from?: string }
29
29
  | { type: "signature"; chainId: number; typedData: unknown; origin?: string }
30
- | { type: "message"; method: "personal_sign"; message: string; chainId?: number; origin?: string; from?: string };
30
+ | { type: "message"; method: "personal_sign"; message: string; chainId?: number; origin?: string; from?: string }
31
+ | { type: "authorization"; chainId: number; address: string; authorizationChainId?: number; nonce?: string; origin?: string; from?: string };
31
32
 
32
33
  export declare class PresignBlockedError extends Error {
33
34
  code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain" | "over_limit" | "paused" | "limit_unavailable";
@@ -174,9 +175,9 @@ export interface GuardOptions {
174
175
  creditKey?: string;
175
176
  /** Plain fetch used for credit-paid checks. Default globalThis.fetch. */
176
177
  fetch?: typeof globalThis.fetch;
177
- /** What to do on an orange verdict. Default "stop". */
178
+ /** What to do on an orange verdict. Default "stop". "allow" does not cover EIP-7702 authorizations: an orange one is signed only when your function returns true. */
178
179
  onOrange?: "stop" | "allow" | ((verdict: PresignVerdict, info: { method: string; request: CheckRequest }) => boolean | Promise<boolean>);
179
- /** When the check cannot be done (outage, unsupported chain). Default "stop". A forged or changed verdict always stops. */
180
+ /** When the check cannot be done (outage, unsupported chain). Default "stop". A forged or changed verdict, and an EIP-7702 authorization, always stop. */
180
181
  onError?: "stop" | "allow";
181
182
  /** The site asking for the signature, if any: domain age and phishing lists are checked. */
182
183
  origin?: string;
@@ -202,7 +203,7 @@ export interface GuardOptions {
202
203
  server?: { url: string; key: string; fetch?: typeof globalThis.fetch; requestTimeoutMs?: number };
203
204
  }
204
205
 
205
- /** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
206
+ /** The same wallet client; sendTransaction, writeContract, signTypedData, signAuthorization (EIP-7702) and signMessage are checked first. */
206
207
  export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W & GuardControls;
207
208
  export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string; x402?: Record<string, unknown>; from?: string }): CheckRequest | null;
208
209
  /**
package/index.js CHANGED
@@ -8,6 +8,10 @@
8
8
  // orange → onOrange: "stop" (default, throws), "allow", or your own async
9
9
  // function that decides (e.g. ask the user)
10
10
  // red → throws PresignBlockedError; nothing is signed
11
+ // EIP-7702 authorizations (signAuthorization, and the authorizationList of a
12
+ // transaction) are checked too, and stricter: a delegation hands the contract
13
+ // the whole wallet, so an orange one is signed only when your onOrange function
14
+ // says yes ("allow" does not cover it), and a failed check always stops.
11
15
  // Every verdict must carry presign-guard's signed receipt for exactly this
12
16
  // request, checked against its pinned signer (or a key certified by the Fizzl
13
17
  // payout wallet): a missing, changed or forged verdict is never a signature.
@@ -51,6 +55,7 @@
51
55
  // @x402/xrpl's ExactXrplScheme to pay x402 services in RLUSD.
52
56
 
53
57
  import { bytesToHex, decodeFunctionData, encodeFunctionData, parseAbi } from "viem";
58
+ import { recoverAuthorizationAddress } from "viem/utils";
54
59
  import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
55
60
  import { createLimiter, memoryStore } from "./limits.js";
56
61
  import { createRemoteLimiter } from "./remote.js";
@@ -81,7 +86,7 @@ const ESCROW_ABI = parseAbi([
81
86
  const TRANSFER_ABI = parseAbi(["function transfer(address to, uint256 amount)"]);
82
87
  const VOUCHER_DOMAIN = "TIP20 Channel Reserve";
83
88
  export const XRPL_NETWORKS = ["xrpl:0", "xrpl:1"];
84
- export const VERSION = "0.18.0";
89
+ export const VERSION = "0.21.0";
85
90
  export const CREDIT_HEADER = "x-credit-key";
86
91
  const ROUTE = "POST /v1/check";
87
92
 
@@ -151,6 +156,20 @@ export function checkRequestFor(method, args, { chainId, origin, x402, from } =
151
156
  if (message === null) return null;
152
157
  return { type: "message", method: "personal_sign", message, ...(chainId ? { chainId } : {}), ...(origin ? { origin } : {}), ...sender };
153
158
  }
159
+ if (method === "signAuthorization") {
160
+ // EIP-7702: viem takes the contract as contractAddress (before address) and fills in the client's chain id
161
+ // when none is given. The chain id inside the authorization may be 0: valid on every chain.
162
+ const address = args?.contractAddress ?? args?.address;
163
+ if (typeof address !== "string") return null;
164
+ const signedChain = args?.chainId ?? chainId;
165
+ const nonce = args?.nonce;
166
+ return {
167
+ type: "authorization", chainId: Number(signedChain) || chainId, address,
168
+ ...(signedChain !== undefined && { authorizationChainId: Number(signedChain) }),
169
+ ...(nonce !== undefined && nonce !== null && { nonce: String(nonce) }),
170
+ ...(origin ? { origin } : {}), ...sender,
171
+ };
172
+ }
154
173
  if (method === "signTypedData") {
155
174
  const { domain, types, primaryType, message } = args;
156
175
  // A payment made by mandatePayer() (mandate.js) is checked against its mandate too.
@@ -188,7 +207,10 @@ export function sessionDeposit(tx, chainId, address) {
188
207
  return { token: descriptor.token.toLowerCase(), payee: descriptor.payee, deposit };
189
208
  }
190
209
 
191
- const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
210
+ const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData", "signAuthorization"]);
211
+
212
+ // A signed EIP-7702 authorization, by its signature.
213
+ const authorizationKey = (a) => (typeof a?.r === "string" && typeof a?.s === "string" ? `${a.r}:${a.s}`.toLowerCase() : null);
192
214
 
193
215
  // What the agent says it is buying, for the signatures made inside withPurchase().
194
216
  const purchases = new AsyncLocalStorage();
@@ -294,8 +316,10 @@ export function guardWallet(wallet, {
294
316
 
295
317
  // The verdict for a request, or null when the check could not be done and onError is "allow".
296
318
  async function verdictFor(method, request, chainId) {
319
+ // An EIP-7702 authorization is never signed unchecked: onError "allow" does not cover it.
320
+ const mayAllow = onError === "allow" && request.type !== "authorization";
297
321
  if (request.type !== "message" && request.type !== "solana" && request.type !== "algorand" && !SUPPORTED_CHAINS.includes(chainId) && !XRPL_NETWORKS.includes(chainId)) {
298
- if (onError === "allow") return null;
322
+ if (mayAllow) return null;
299
323
  throw new PresignBlockedError(`chain ${chainId} is not covered by presign-guard; nothing was signed`, { code: "unsupported_chain", request });
300
324
  }
301
325
  let verdict;
@@ -303,7 +327,7 @@ export function guardWallet(wallet, {
303
327
  verdict = await check(request);
304
328
  } catch (err) {
305
329
  if (err instanceof PresignBlockedError && err.code === "bad_receipt") throw err;
306
- if (onError === "allow") return null;
330
+ if (mayAllow) return null;
307
331
  if (err instanceof PresignBlockedError) throw err;
308
332
  throw new PresignBlockedError(`presign check failed (${err.message}); nothing was signed`, { code: "check_failed", request });
309
333
  }
@@ -311,8 +335,11 @@ export function guardWallet(wallet, {
311
335
  const why = (verdict.reasons || []).filter((r) => r.severity !== "info").map((r) => r.code).join(", ") || verdict.verdict;
312
336
  if (verdict.verdict === "red") throw new PresignBlockedError(`not signed: red (${why})`, { code: "red", verdict, request });
313
337
  if (verdict.verdict === "orange") {
314
- const ok = onOrange === "allow" || (typeof onOrange === "function" && (await onOrange(verdict, { method, request })) === true);
315
- if (!ok) throw new PresignBlockedError(`not signed: orange (${why})`, { code: "orange", verdict, request });
338
+ // onOrange "allow" does not cover an EIP-7702 authorization: only your function's yes does.
339
+ const authorization = request.type === "authorization";
340
+ const ok = (onOrange === "allow" && !authorization) || (typeof onOrange === "function" && (await onOrange(verdict, { method, request })) === true);
341
+ const hint = authorization && onOrange === "allow" ? '; an EIP-7702 authorization is signed on orange only when your onOrange function says yes' : "";
342
+ if (!ok) throw new PresignBlockedError(`not signed: orange (${why})${hint}`, { code: "orange", verdict, request });
316
343
  } else if (verdict.verdict !== "green") {
317
344
  throw new PresignBlockedError(`not signed: unknown verdict ${verdict.verdict}`, { code: "check_failed", verdict, request });
318
345
  }
@@ -357,10 +384,54 @@ export function guardWallet(wallet, {
357
384
  return request;
358
385
  }
359
386
 
387
+ // EIP-7702 authorizations this wallet signed after a check, so the transaction that carries them is not
388
+ // charged for a second check.
389
+ const checkedAuthorizations = new Set();
390
+
391
+ // An EIP-7702 authorization moves nothing by itself but hands the contract the whole wallet: checked (stricter
392
+ // on orange and on errors, see verdictFor), counted toward no limit, signed for exactly the chain id checked.
393
+ async function signAuthorizationGuarded(target, original, args, rest, chainId) {
394
+ const request = checkRequestFor("signAuthorization", args, { chainId, origin, from: senderOf(args, target) });
395
+ if (!request) throw new PresignBlockedError("an EIP-7702 authorization needs the contract's address; nothing was signed", { code: "check_failed" });
396
+ await verdictFor("signAuthorization", request, request.chainId);
397
+ // Signed exactly as checked: this contract, this chain id.
398
+ const { contractAddress: _ignored, ...fields } = args;
399
+ const signed = await original({ ...fields, address: request.address, chainId: request.authorizationChainId }, ...rest);
400
+ const key = authorizationKey(signed);
401
+ if (key) checkedAuthorizations.add(key);
402
+ return signed;
403
+ }
404
+
405
+ // The signed EIP-7702 authorizations a transaction carries (authorizationList). Those this wallet signed with
406
+ // signAuthorization were checked then; any other one signed by the sending account is checked now, the same way.
407
+ // Authorizations signed by other accounts put nothing of this wallet at risk, and those for another chain do
408
+ // nothing on this one.
409
+ async function checkAuthorizationList(list, chainId, from) {
410
+ for (const a of list) {
411
+ const key = authorizationKey(a);
412
+ if (key && checkedAuthorizations.has(key)) continue;
413
+ const on = Number(a?.chainId);
414
+ if (on !== 0 && on !== chainId) continue;
415
+ let signer = null;
416
+ try { signer = await recoverAuthorizationAddress({ authorization: a }); } catch { signer = null; }
417
+ if (signer && from && signer.toLowerCase() !== from.toLowerCase()) continue;
418
+ // viem sends a signed authorization's `address` as the contract.
419
+ const request = checkRequestFor("signAuthorization", { address: a?.address, chainId: a?.chainId, nonce: a?.nonce }, { chainId, origin, from });
420
+ if (!request) throw new PresignBlockedError("an EIP-7702 authorization in authorizationList has no contract address; nothing was signed", { code: "check_failed" });
421
+ await verdictFor("signAuthorization", request, request.chainId);
422
+ }
423
+ }
424
+
360
425
  async function guarded(target, method, original, args, rest) {
361
426
  if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
362
427
  const chainId = args?.chain?.id ?? target.chain?.id;
363
428
  const run = () => original(args, ...rest);
429
+ if (method === "signAuthorization") {
430
+ if (TEMPO_TOKENS[chainId]) throw new PresignBlockedError(`on Tempo (chain ${chainId}) this wallet signs no EIP-7702 authorization; nothing was signed`, { code: "unsupported_chain" });
431
+ return signAuthorizationGuarded(target, original, args, rest, chainId);
432
+ }
433
+ const authorizations = Array.isArray(args?.authorizationList) ? args.authorizationList : [];
434
+ if (authorizations.length && TEMPO_TOKENS[chainId]) throw new PresignBlockedError(`on Tempo (chain ${chainId}) this wallet sends no EIP-7702 authorizations; nothing was signed`, { code: "unsupported_chain" });
364
435
  // A plain message moves nothing by itself, so it is checked but not counted toward the limits.
365
436
  if (method === "signMessage") {
366
437
  const request = checkRequestFor(method, args, { chainId, origin, from: senderOf(args, target) });
@@ -371,6 +442,7 @@ export function guardWallet(wallet, {
371
442
  const request = tempoRequest(method, args, chainId);
372
443
  return limiter ? withinLimits(method, request, null, run) : run();
373
444
  }
445
+ if (authorizations.length) await checkAuthorizationList(authorizations, chainId, senderOf(args, target));
374
446
  const request = checkRequestFor(method, args, { chainId, origin, x402: x402Paying.getStore(), from: senderOf(args, target) });
375
447
  if (!request) {
376
448
  // A contract deployment is not checked, but the value it sends still counts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.20.1",
3
+ "version": "0.21.0",
4
4
  "description": "A wallet for AI agents (viem on EVM chains, Solana and Algorand) that asks presign-guard ($0.01 over x402) before every transaction, contract write and signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit (Telegram, or signed in your own wallet over AC2).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -74,6 +74,7 @@
74
74
  "approvals",
75
75
  "permit2",
76
76
  "drainer",
77
+ "eip-7702",
77
78
  "usdc",
78
79
  "spending-limits",
79
80
  "budget",