presign-guard-wallet 0.20.0 → 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 |
@@ -185,7 +185,7 @@ Only the chat you name (or the `allowedUserIds` you list) can answer; anyone els
185
185
  });
186
186
  ```
187
187
 
188
- What you sign is a text that starts with `fizzl-approval-v1` and names the agent, the amount, the network, the recipient, the URL, presign-guard's verdict, an id and an expiry time. It is never a transaction (Algorand signs transactions over `TX` + the transaction), so a signed approval can't be used as a payment. A decline, no answer in time, or a signature from another key counts as Deny. Without `owner`, the account the AC2 service is paired with is used, fixed at the first request. If the AC2 service isn't running or no wallet is paired, the wallet stops (`limit_unavailable`) rather than signing. The agent still signs and pays with its own key, on any network; only the approval comes from your wallet. This module talks to the AC2 service over its local socket (`~/.ac2/ac2d.sock`, or `AC2_DAEMON_SOCKET`) and adds no packages.
188
+ What you sign is a text that starts with `fizzl-approval-v1` and names the agent, the amount, the network, the recipient, the URL, presign-guard's verdict, an id and an expiry time. It is never a transaction (Algorand signs transactions over `TX` + the transaction), so a signed approval can't be used as a payment. A decline, no answer in time, or a signature from another key counts as Deny. Without `owner`, the account the AC2 service is paired with is used, fixed at the first request. Each request first registers with the AC2 service as an agent: after a restart or a dropped link the service only waits for your wallet again once an agent is there, and the request then waits up to a minute (`connectTimeoutMs`) for your wallet to come back, so keep AC2 Wallet open. If the AC2 service isn't running or your wallet doesn't come back, the wallet stops (`limit_unavailable`) rather than signing. The agent still signs and pays with its own key, on any network; only the approval comes from your wallet. This module talks to the AC2 service over its local socket (`~/.ac2/ac2d.sock`, or `AC2_DAEMON_SOCKET`) and adds no packages.
189
189
 
190
190
  `verifyApproval(owner, payload, signature)` checks a stored approval again later.
191
191
 
@@ -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/ac2.d.ts CHANGED
@@ -7,6 +7,8 @@ export interface Ac2ApproverOptions {
7
7
  socket?: string;
8
8
  /** How long the agent waits for your approval. Default 10 minutes; no answer counts as Deny. */
9
9
  timeoutMs?: number;
10
+ /** How long to wait for your wallet to (re)connect to the AC2 service before asking. Default 1 minute. */
11
+ connectTimeoutMs?: number;
10
12
  /** Name of the agent in the request. Default "Your agent". */
11
13
  label?: string;
12
14
  }
package/ac2.js CHANGED
@@ -14,12 +14,15 @@
14
14
  // transactions over "TX" + the transaction, so a signed approval can't be used as a payment.
15
15
  //
16
16
  // Needs the AC2 service (ac2-cli) running on this machine and paired with your wallet (`ac2 pair`). This module
17
- // talks to it over its local socket (~/.ac2/ac2d.sock, or AC2_DAEMON_SOCKET) and needs no extra packages. If the
18
- // service isn't running or no wallet is paired, the wallet stops (limit_unavailable) rather than signing.
17
+ // talks to it over its local socket (~/.ac2/ac2d.sock, or AC2_DAEMON_SOCKET) and needs no extra packages. Each
18
+ // request registers as an agent first (agent.hello): after a restart or a dropped link the service only waits
19
+ // for the wallet again once an agent is there, and then this module waits (default 1 minute) for the wallet to
20
+ // come back, so keep AC2 Wallet open. If the service isn't running or the wallet doesn't come back, the wallet
21
+ // stops (limit_unavailable) rather than signing.
19
22
 
20
23
  import { connect as netConnect } from "node:net";
21
24
  import { createHash, createPublicKey, randomBytes, verify } from "node:crypto";
22
- import { homedir } from "node:os";
25
+ import { homedir, hostname } from "node:os";
23
26
  import { join } from "node:path";
24
27
 
25
28
  const PREFIX = "fizzl-approval-v1";
@@ -66,16 +69,20 @@ export function verifyApproval(owner, payload, signature) {
66
69
  }
67
70
  }
68
71
 
69
- // One request to the AC2 service: newline-delimited JSON, answered on the same connection.
70
- function controlRequest(path, method, params, { timeoutMs, connect }) {
71
- return new Promise((resolve, reject) => {
72
+ // A connection to the AC2 service: newline-delimited JSON requests, answered by id on the same connection.
73
+ // Kept open for one approval, so the agent stays registered while it waits for the wallet.
74
+ function openSession(path, connect) {
75
+ return new Promise((resolveOpen, rejectOpen) => {
72
76
  const sock = connect(path);
73
- let buf = "";
74
- const done = (fn, arg) => { clearTimeout(timer); sock.destroy(); fn(arg); };
75
- const timer = setTimeout(() => done(reject, Object.assign(new Error(`the AC2 service did not answer ${method} in time`), { code: "timeout" })), timeoutMs);
77
+ const pending = new Map();
78
+ let buf = "", seq = 0, open = false;
79
+ const failAll = (err) => { for (const p of pending.values()) { clearTimeout(p.timer); p.reject(err); } pending.clear(); };
76
80
  sock.setEncoding("utf8");
77
- sock.on("error", (err) => done(reject, Object.assign(new Error(`can't reach the AC2 service at ${path} (${err.code ?? err.message}): start it and pair your wallet with \`ac2 pair\``), { code: "unreachable" })));
78
- sock.on("connect", () => sock.write(`${JSON.stringify({ id: 1, method, params })}\n`));
81
+ sock.on("error", (err) => {
82
+ const e = Object.assign(new Error(`can't reach the AC2 service at ${path} (${err.code ?? err.message}): start it (\`ac2 service start\`) and pair your wallet with \`ac2 pair\``), { code: "unreachable" });
83
+ if (!open) rejectOpen(e); else failAll(e);
84
+ });
85
+ sock.on("close", () => failAll(Object.assign(new Error("the AC2 service closed the connection"), { code: "unreachable" })));
79
86
  sock.on("data", (chunk) => {
80
87
  buf += chunk;
81
88
  for (let nl = buf.indexOf("\n"); nl >= 0; nl = buf.indexOf("\n")) {
@@ -83,11 +90,26 @@ function controlRequest(path, method, params, { timeoutMs, connect }) {
83
90
  buf = buf.slice(nl + 1);
84
91
  let frame;
85
92
  try { frame = JSON.parse(line); } catch { continue; }
86
- if (frame.id !== 1) continue; // events and other replies
87
- if (frame.error) return done(reject, Object.assign(new Error(`AC2 service: ${frame.error.message ?? frame.error.code}`), { code: frame.error.code }));
88
- return done(resolve, frame.result);
93
+ const p = frame.id !== undefined && pending.get(frame.id);
94
+ if (!p) continue; // events
95
+ pending.delete(frame.id);
96
+ clearTimeout(p.timer);
97
+ if (frame.error) p.reject(Object.assign(new Error(`AC2 service: ${frame.error.message ?? frame.error.code}`), { code: frame.error.code }));
98
+ else p.resolve(frame.result);
89
99
  }
90
100
  });
101
+ sock.on("connect", () => {
102
+ open = true;
103
+ resolveOpen({
104
+ request: (method, params, timeoutMs = 10_000) => new Promise((resolve, reject) => {
105
+ const id = ++seq;
106
+ const timer = setTimeout(() => { pending.delete(id); reject(Object.assign(new Error(`the AC2 service did not answer ${method} in time`), { code: "timeout" })); }, timeoutMs);
107
+ pending.set(id, { resolve, reject, timer });
108
+ sock.write(`${JSON.stringify({ id, method, params })}\n`);
109
+ }),
110
+ close: () => sock.destroy(),
111
+ });
112
+ });
91
113
  });
92
114
  }
93
115
 
@@ -113,54 +135,75 @@ export function approvalText(info, { label, id, expiresAt }) {
113
135
  * @param {string} [o.owner] your Algorand address; only its signature approves. Default: the wallet the AC2 service is paired with, fixed at the first request.
114
136
  * @param {string} [o.socket] the AC2 service's socket (default ~/.ac2/ac2d.sock or AC2_DAEMON_SOCKET)
115
137
  * @param {number} [o.timeoutMs] how long the agent waits for you (default 10 minutes); no answer = deny
138
+ * @param {number} [o.connectTimeoutMs] how long to wait for the wallet to (re)connect to the service (default 1 minute)
116
139
  * @param {string} [o.label] name of the agent in the request (default "Your agent")
117
140
  */
118
- export function ac2Approver({ owner, socket = defaultSocketPath(), timeoutMs = 600_000, label = "Your agent", connect = netConnect, now = () => Date.now() } = {}) {
141
+ export function ac2Approver({ owner, socket = defaultSocketPath(), timeoutMs = 600_000, connectTimeoutMs = 60_000, label = "Your agent", connect = netConnect, now = () => Date.now(), pollMs = 1000 } = {}) {
119
142
  if (owner !== undefined && !algorandPublicKey(owner)) throw new TypeError("owner must be an Algorand address (58 characters, with a valid checksum)");
120
143
  if (!(timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number of milliseconds");
121
144
  let pinned = owner ?? null;
122
- const ask = (method, params, ms = 10_000) => controlRequest(socket, method, params, { timeoutMs: ms, connect });
123
145
 
124
- return async function onOverLimit(info) {
125
- if (!pinned) {
126
- const status = await ask("daemon.status", {});
127
- const address = status?.connection?.walletAddress;
128
- if (status?.connection?.state !== "connected" || !algorandPublicKey(address)) throw Object.assign(new Error("no wallet is paired with the AC2 service: run `ac2 pair` and scan the code with your wallet"), { code: "not_connected" });
129
- pinned = address;
130
- }
131
- const id = randomBytes(8).toString("hex");
132
- const expiresAt = now() + timeoutMs;
133
- const text = approvalText(info, { label, id, expiresAt });
134
- const where = info.purchase?.url ? (() => { try { return ` for ${new URL(info.purchase.url).host}`; } catch { return ""; } })() : "";
135
- let result;
146
+ // Register as an agent (the service then waits for the wallet if it wasn't), and wait until the wallet is there.
147
+ async function walletReady(session) {
136
148
  try {
137
- result = await ask("agent.request", {
138
- type: "ac2/SigningRequest",
139
- body: {
140
- description: `${label}: over your limit${where}. ${info.summary ?? ""}`.slice(0, 300),
141
- encoding: "base64",
142
- payload: Buffer.from(text).toString("base64"),
143
- schema: SCHEMA,
144
- display_hint: "text",
145
- sig_hint: "raw-ed25519",
146
- key_type: "account",
147
- },
148
- responseTypes: ["ac2/SigningResponse", "ac2/SigningRejected"],
149
- expires_in_seconds: Math.ceil(timeoutMs / 1000),
150
- timeoutMs,
151
- }, timeoutMs + 15_000);
149
+ await session.request("agent.hello", { agent: `presign-guard-wallet-${process.pid}`, host: hostname() });
152
150
  } catch (err) {
153
- if (err.code === "timeout" || /timed? ?out/i.test(err.message)) return false; // no answer in time
154
- throw err;
151
+ if (err.code !== "agent_taken") throw err; // another request of this process holds the name: it is registered
152
+ }
153
+ const until = now() + connectTimeoutMs;
154
+ for (;;) {
155
+ const status = await session.request("daemon.status", {});
156
+ const c = status?.connection ?? {};
157
+ if (c.state === "connected" && !c.locked) return c;
158
+ if (now() >= until) throw Object.assign(new Error(`your wallet is not connected to the AC2 service (${c.state ?? "no connection"}${c.locked ? ", locked" : ""}): open AC2 Wallet on your phone, or pair it with \`ac2 pair\``), { code: "not_connected" });
159
+ await new Promise((ok) => setTimeout(ok, pollMs));
155
160
  }
156
- if (result?.status === "unavailable") throw Object.assign(new Error(`the AC2 service can't ask your wallet (${result.reason})`), { code: result.reason });
157
- const msg = result?.message;
158
- if (result?.status !== "response" || msg?.type !== "ac2/SigningResponse") return false; // declined
159
- if (now() > expiresAt) return false;
160
- if (!verifyApproval(pinned, text, msg.body?.signature)) {
161
- console.warn("[presign-guard-wallet] AC2 approval refused: the signature is not from the owner's account");
162
- return false;
161
+ }
162
+
163
+ return async function onOverLimit(info) {
164
+ const session = await openSession(socket, connect);
165
+ try {
166
+ const connection = await walletReady(session);
167
+ if (!pinned) {
168
+ if (!algorandPublicKey(connection.walletAddress)) throw Object.assign(new Error("the AC2 service doesn't report your wallet's Algorand address: set owner to your address"), { code: "not_connected" });
169
+ pinned = connection.walletAddress;
170
+ }
171
+ const id = randomBytes(8).toString("hex");
172
+ const expiresAt = now() + timeoutMs;
173
+ const text = approvalText(info, { label, id, expiresAt });
174
+ const where = info.purchase?.url ? (() => { try { return ` for ${new URL(info.purchase.url).host}`; } catch { return ""; } })() : "";
175
+ let result;
176
+ try {
177
+ result = await session.request("agent.request", {
178
+ type: "ac2/SigningRequest",
179
+ body: {
180
+ description: `${label}: over your limit${where}. ${info.summary ?? ""}`.slice(0, 300),
181
+ encoding: "base64",
182
+ payload: Buffer.from(text).toString("base64"),
183
+ schema: SCHEMA,
184
+ display_hint: "text",
185
+ sig_hint: "raw-ed25519",
186
+ key_type: "account",
187
+ },
188
+ responseTypes: ["ac2/SigningResponse", "ac2/SigningRejected"],
189
+ expires_in_seconds: Math.ceil(timeoutMs / 1000),
190
+ timeoutMs,
191
+ }, timeoutMs + Math.min(15_000, timeoutMs)); // a little longer than the service waits, so it answers first
192
+ } catch (err) {
193
+ if (err.code === "timeout" || /timed? ?out/i.test(err.message)) return false; // no answer in time
194
+ throw err;
195
+ }
196
+ if (result?.status === "unavailable") throw Object.assign(new Error(`the AC2 service can't ask your wallet (${result.reason})`), { code: result.reason });
197
+ const msg = result?.message;
198
+ if (result?.status !== "response" || msg?.type !== "ac2/SigningResponse") return false; // declined
199
+ if (now() > expiresAt) return false;
200
+ if (!verifyApproval(pinned, text, msg.body?.signature)) {
201
+ console.warn("[presign-guard-wallet] AC2 approval refused: the signature is not from the owner's account");
202
+ return false;
203
+ }
204
+ return { approved: true, proof: { via: "ac2", owner: pinned, id, payload: text, signature: msg.body.signature, signedAt: new Date(now()).toISOString() } };
205
+ } finally {
206
+ session.close();
163
207
  }
164
- return { approved: true, proof: { via: "ac2", owner: pinned, id, payload: text, signature: msg.body.signature, signedAt: new Date(now()).toISOString() } };
165
208
  };
166
209
  }
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.0",
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",