presign-guard-wallet 0.20.1 → 0.22.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 +39 -5
- package/index.d.ts +9 -4
- package/index.js +147 -9
- package/package.json +2 -1
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 `
|
|
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
|
|---|---|
|
|
@@ -52,7 +52,18 @@ try {
|
|
|
52
52
|
}
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
`wallet` is the same client. `signMessage` is checked too, as a plain message: a sign-in message (Sign-In with Ethereum) for another site than `origin` is red, unreadable bytes are orange; it counts toward no limit (`checkMessages: false` turns this off).
|
|
55
|
+
`wallet` is the same client. `signMessage` is checked too, as a plain message: a sign-in message (Sign-In with Ethereum) for another site than `origin` is red, unreadable bytes are orange; it counts toward no limit (`checkMessages: false` turns this off).
|
|
56
|
+
|
|
57
|
+
viem's other ways to sign or send are checked the same way, so a library that uses them can't go around the wallet:
|
|
58
|
+
|
|
59
|
+
| Method | Checked as |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `sendTransactionSync`, `signTransaction` | `sendTransaction` (a signed transaction is as good as sent: anyone can broadcast it) |
|
|
62
|
+
| `writeContractSync` | `writeContract` |
|
|
63
|
+
| `sendCalls`, `sendCallsSync` (EIP-5792 batches) | every call, as a transaction from the wallet; one red or stopped call stops the whole batch. Each call counts toward `perTx` on its own and all of them toward the day's limit, booked before anything is signed |
|
|
64
|
+
| `deployContract` | a deployment: not checked by presign-guard, but the value it sends counts toward the limits |
|
|
65
|
+
|
|
66
|
+
Every other method (`getAddresses`, `extend`, `sendRawTransaction` for a transaction that is already signed, …) works as before, unchecked.
|
|
56
67
|
|
|
57
68
|
## Options
|
|
58
69
|
|
|
@@ -61,8 +72,8 @@ try {
|
|
|
61
72
|
| `pay` | required (optional with `creditKey`) | A fetch that pays x402 (`wrapFetchWithPayment`); cap it with spend controls |
|
|
62
73
|
| `creditKey` | | A presign-guard credit key (`pgc_…`): checks are paid from prepaid credits first, then with `pay`. See [Prepaid credits](#prepaid-credits) |
|
|
63
74
|
| `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"
|
|
75
|
+
| `onOrange` | `"stop"` | `"stop"`, `"allow"` or `async (verdict, { method, request }) => boolean`. `"allow"` does not cover [EIP-7702 authorizations](#eip-7702-authorizations) |
|
|
76
|
+
| `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
77
|
| `origin` | | The site asking for the signature: its domain age and phishing lists are checked too |
|
|
67
78
|
| `onVerdict` | | `(verdict, { method, request, paidWith, creditsLeft }) => void`, e.g. for logging; `paidWith` is `"credits"` or `"x402"` |
|
|
68
79
|
| `verifyReceipts` | `"require"` | Check presign-guard's signed receipt on every verdict; `"off"` skips it |
|
|
@@ -232,6 +243,29 @@ const wallet = guardWallet(walletClient, {
|
|
|
232
243
|
|
|
233
244
|
If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
|
|
234
245
|
|
|
246
|
+
## EIP-7702 authorizations
|
|
247
|
+
|
|
248
|
+
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:
|
|
249
|
+
|
|
250
|
+
| Verdict | What the wallet does |
|
|
251
|
+
|---|---|
|
|
252
|
+
| 🟢 green | Signs: revoking a delegation (`0x000…000`), or a contract on GoPlus's trust list |
|
|
253
|
+
| 🟠 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 |
|
|
254
|
+
| 🔴 red | Never signs: no contract at the address, a contract that is itself a delegated wallet, an unverified, flagged or sanctioned contract |
|
|
255
|
+
|
|
256
|
+
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).
|
|
257
|
+
|
|
258
|
+
```js
|
|
259
|
+
const wallet = guardWallet(walletClient, {
|
|
260
|
+
pay,
|
|
261
|
+
onOrange: async (verdict, { method, request }) => method === "signAuthorization" ? askUser(request.address, verdict.reasons) : false,
|
|
262
|
+
});
|
|
263
|
+
const authorization = await wallet.signAuthorization({ contractAddress: smartAccount }); // the contract you chose to delegate to
|
|
264
|
+
await wallet.sendTransaction({ to: account.address, data, authorizationList: [authorization] });
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
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.
|
|
268
|
+
|
|
235
269
|
## Checking x402 payments against what the seller asked
|
|
236
270
|
|
|
237
271
|
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 +384,7 @@ presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash
|
|
|
350
384
|
|
|
351
385
|
## Costs and coverage
|
|
352
386
|
|
|
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`.
|
|
387
|
+
- $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
388
|
- 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
389
|
- The requests carry `user-agent: presign-guard-wallet/<version>` so the service can count how often the package is used.
|
|
356
390
|
|
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
|
|
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,11 @@ export interface GuardOptions {
|
|
|
202
203
|
server?: { url: string; key: string; fetch?: typeof globalThis.fetch; requestTimeoutMs?: number };
|
|
203
204
|
}
|
|
204
205
|
|
|
205
|
-
/**
|
|
206
|
+
/**
|
|
207
|
+
* The same wallet client. Checked first: sendTransaction, writeContract, signTypedData, signAuthorization (EIP-7702),
|
|
208
|
+
* signMessage, and viem's other ways to sign or send: signTransaction, sendTransactionSync, writeContractSync,
|
|
209
|
+
* sendCalls and sendCallsSync (every call), deployContract (its value counts toward the limits).
|
|
210
|
+
*/
|
|
206
211
|
export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W & GuardControls;
|
|
207
212
|
export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string; x402?: Record<string, unknown>; from?: string }): CheckRequest | null;
|
|
208
213
|
/**
|
package/index.js
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
// presign-guard-wallet: a viem wallet for AI agents that asks presign-guard
|
|
2
2
|
// before it signs.
|
|
3
3
|
//
|
|
4
|
-
// Before every sendTransaction, writeContract and signTypedData
|
|
4
|
+
// Before every sendTransaction, writeContract and signTypedData (and viem's
|
|
5
|
+
// other ways to sign or send: signTransaction, sendTransactionSync,
|
|
6
|
+
// writeContractSync, sendCalls, sendCallsSync, deployContract), the wallet
|
|
5
7
|
// pays $0.01 (x402, USDC) for a presign-guard verdict on exactly what is about
|
|
6
8
|
// to be signed, and acts on it:
|
|
7
9
|
// green → signs
|
|
8
10
|
// orange → onOrange: "stop" (default, throws), "allow", or your own async
|
|
9
11
|
// function that decides (e.g. ask the user)
|
|
10
12
|
// red → throws PresignBlockedError; nothing is signed
|
|
13
|
+
// EIP-7702 authorizations (signAuthorization, and the authorizationList of a
|
|
14
|
+
// transaction) are checked too, and stricter: a delegation hands the contract
|
|
15
|
+
// the whole wallet, so an orange one is signed only when your onOrange function
|
|
16
|
+
// says yes ("allow" does not cover it), and a failed check always stops.
|
|
11
17
|
// Every verdict must carry presign-guard's signed receipt for exactly this
|
|
12
18
|
// request, checked against its pinned signer (or a key certified by the Fizzl
|
|
13
19
|
// payout wallet): a missing, changed or forged verdict is never a signature.
|
|
@@ -51,6 +57,7 @@
|
|
|
51
57
|
// @x402/xrpl's ExactXrplScheme to pay x402 services in RLUSD.
|
|
52
58
|
|
|
53
59
|
import { bytesToHex, decodeFunctionData, encodeFunctionData, parseAbi } from "viem";
|
|
60
|
+
import { recoverAuthorizationAddress } from "viem/utils";
|
|
54
61
|
import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
|
|
55
62
|
import { createLimiter, memoryStore } from "./limits.js";
|
|
56
63
|
import { createRemoteLimiter } from "./remote.js";
|
|
@@ -81,7 +88,7 @@ const ESCROW_ABI = parseAbi([
|
|
|
81
88
|
const TRANSFER_ABI = parseAbi(["function transfer(address to, uint256 amount)"]);
|
|
82
89
|
const VOUCHER_DOMAIN = "TIP20 Channel Reserve";
|
|
83
90
|
export const XRPL_NETWORKS = ["xrpl:0", "xrpl:1"];
|
|
84
|
-
export const VERSION = "0.
|
|
91
|
+
export const VERSION = "0.22.0";
|
|
85
92
|
export const CREDIT_HEADER = "x-credit-key";
|
|
86
93
|
const ROUTE = "POST /v1/check";
|
|
87
94
|
|
|
@@ -134,6 +141,7 @@ function senderOf(args, client) {
|
|
|
134
141
|
// What presign-guard should check for a wallet call, or null for calls it does not cover. With `from` (the
|
|
135
142
|
// sending wallet) presign-guard simulates a transaction and reports what really leaves the wallet.
|
|
136
143
|
export function checkRequestFor(method, args, { chainId, origin, x402, from } = {}) {
|
|
144
|
+
method = SAME_AS[method] ?? method;
|
|
137
145
|
const base = { chainId, ...(origin ? { origin } : {}) };
|
|
138
146
|
const sender = from ? { from } : {};
|
|
139
147
|
if (method === "sendTransaction") {
|
|
@@ -151,6 +159,20 @@ export function checkRequestFor(method, args, { chainId, origin, x402, from } =
|
|
|
151
159
|
if (message === null) return null;
|
|
152
160
|
return { type: "message", method: "personal_sign", message, ...(chainId ? { chainId } : {}), ...(origin ? { origin } : {}), ...sender };
|
|
153
161
|
}
|
|
162
|
+
if (method === "signAuthorization") {
|
|
163
|
+
// EIP-7702: viem takes the contract as contractAddress (before address) and fills in the client's chain id
|
|
164
|
+
// when none is given. The chain id inside the authorization may be 0: valid on every chain.
|
|
165
|
+
const address = args?.contractAddress ?? args?.address;
|
|
166
|
+
if (typeof address !== "string") return null;
|
|
167
|
+
const signedChain = args?.chainId ?? chainId;
|
|
168
|
+
const nonce = args?.nonce;
|
|
169
|
+
return {
|
|
170
|
+
type: "authorization", chainId: Number(signedChain) || chainId, address,
|
|
171
|
+
...(signedChain !== undefined && { authorizationChainId: Number(signedChain) }),
|
|
172
|
+
...(nonce !== undefined && nonce !== null && { nonce: String(nonce) }),
|
|
173
|
+
...(origin ? { origin } : {}), ...sender,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
154
176
|
if (method === "signTypedData") {
|
|
155
177
|
const { domain, types, primaryType, message } = args;
|
|
156
178
|
// A payment made by mandatePayer() (mandate.js) is checked against its mandate too.
|
|
@@ -188,7 +210,16 @@ export function sessionDeposit(tx, chainId, address) {
|
|
|
188
210
|
return { token: descriptor.token.toLowerCase(), payee: descriptor.payee, deposit };
|
|
189
211
|
}
|
|
190
212
|
|
|
191
|
-
|
|
213
|
+
// viem's other ways to sign or send, each checked like the call it stands for. A signed transaction is as good as
|
|
214
|
+
// sent (anyone can broadcast it), and a deployment is checked like a transaction without a recipient: not by
|
|
215
|
+
// presign-guard, but the value it sends counts.
|
|
216
|
+
const SAME_AS = { sendTransactionSync: "sendTransaction", signTransaction: "sendTransaction", deployContract: "sendTransaction", writeContractSync: "writeContract" };
|
|
217
|
+
// EIP-5792 batches: every call in them is checked.
|
|
218
|
+
const BATCHES = new Set(["sendCalls", "sendCallsSync"]);
|
|
219
|
+
const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData", "signAuthorization", ...Object.keys(SAME_AS), ...BATCHES]);
|
|
220
|
+
|
|
221
|
+
// A signed EIP-7702 authorization, by its signature.
|
|
222
|
+
const authorizationKey = (a) => (typeof a?.r === "string" && typeof a?.s === "string" ? `${a.r}:${a.s}`.toLowerCase() : null);
|
|
192
223
|
|
|
193
224
|
// What the agent says it is buying, for the signatures made inside withPurchase().
|
|
194
225
|
const purchases = new AsyncLocalStorage();
|
|
@@ -294,8 +325,10 @@ export function guardWallet(wallet, {
|
|
|
294
325
|
|
|
295
326
|
// The verdict for a request, or null when the check could not be done and onError is "allow".
|
|
296
327
|
async function verdictFor(method, request, chainId) {
|
|
328
|
+
// An EIP-7702 authorization is never signed unchecked: onError "allow" does not cover it.
|
|
329
|
+
const mayAllow = onError === "allow" && request.type !== "authorization";
|
|
297
330
|
if (request.type !== "message" && request.type !== "solana" && request.type !== "algorand" && !SUPPORTED_CHAINS.includes(chainId) && !XRPL_NETWORKS.includes(chainId)) {
|
|
298
|
-
if (
|
|
331
|
+
if (mayAllow) return null;
|
|
299
332
|
throw new PresignBlockedError(`chain ${chainId} is not covered by presign-guard; nothing was signed`, { code: "unsupported_chain", request });
|
|
300
333
|
}
|
|
301
334
|
let verdict;
|
|
@@ -303,7 +336,7 @@ export function guardWallet(wallet, {
|
|
|
303
336
|
verdict = await check(request);
|
|
304
337
|
} catch (err) {
|
|
305
338
|
if (err instanceof PresignBlockedError && err.code === "bad_receipt") throw err;
|
|
306
|
-
if (
|
|
339
|
+
if (mayAllow) return null;
|
|
307
340
|
if (err instanceof PresignBlockedError) throw err;
|
|
308
341
|
throw new PresignBlockedError(`presign check failed (${err.message}); nothing was signed`, { code: "check_failed", request });
|
|
309
342
|
}
|
|
@@ -311,8 +344,11 @@ export function guardWallet(wallet, {
|
|
|
311
344
|
const why = (verdict.reasons || []).filter((r) => r.severity !== "info").map((r) => r.code).join(", ") || verdict.verdict;
|
|
312
345
|
if (verdict.verdict === "red") throw new PresignBlockedError(`not signed: red (${why})`, { code: "red", verdict, request });
|
|
313
346
|
if (verdict.verdict === "orange") {
|
|
314
|
-
|
|
315
|
-
|
|
347
|
+
// onOrange "allow" does not cover an EIP-7702 authorization: only your function's yes does.
|
|
348
|
+
const authorization = request.type === "authorization";
|
|
349
|
+
const ok = (onOrange === "allow" && !authorization) || (typeof onOrange === "function" && (await onOrange(verdict, { method, request })) === true);
|
|
350
|
+
const hint = authorization && onOrange === "allow" ? '; an EIP-7702 authorization is signed on orange only when your onOrange function says yes' : "";
|
|
351
|
+
if (!ok) throw new PresignBlockedError(`not signed: orange (${why})${hint}`, { code: "orange", verdict, request });
|
|
316
352
|
} else if (verdict.verdict !== "green") {
|
|
317
353
|
throw new PresignBlockedError(`not signed: unknown verdict ${verdict.verdict}`, { code: "check_failed", verdict, request });
|
|
318
354
|
}
|
|
@@ -346,10 +382,45 @@ export function guardWallet(wallet, {
|
|
|
346
382
|
return result;
|
|
347
383
|
}
|
|
348
384
|
|
|
385
|
+
// Several spends signed at once (a batch): every one booked before anything is signed, so each counts toward the
|
|
386
|
+
// window (perTx applies to each call on its own); all given back when one doesn't fit or signing fails.
|
|
387
|
+
async function withinLimitsAll(method, items, run) {
|
|
388
|
+
const ctx = purchases.getStore();
|
|
389
|
+
const purchase = ctx?.info ?? null;
|
|
390
|
+
const booked = [];
|
|
391
|
+
const giveBack = (error) => Promise.all(booked.map((b) => limiter.release(b.entries, { purchaseId: b.purchaseId, error }).catch((e) => console.warn(`[presign-guard-wallet] could not give back spending: ${e.message}`))));
|
|
392
|
+
for (const { request, verdict } of items) {
|
|
393
|
+
let b;
|
|
394
|
+
try {
|
|
395
|
+
b = await limiter.reserve({ method, request, verdict, purchase });
|
|
396
|
+
} catch (err) {
|
|
397
|
+
await giveBack(err.message);
|
|
398
|
+
throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
|
|
399
|
+
}
|
|
400
|
+
if (!b.ok) {
|
|
401
|
+
await giveBack(b.summary);
|
|
402
|
+
const err = new PresignBlockedError(`not signed: ${b.summary}`, { code: b.paused ? "paused" : "over_limit", verdict, request });
|
|
403
|
+
err.reasons = b.reasons;
|
|
404
|
+
throw err;
|
|
405
|
+
}
|
|
406
|
+
booked.push({ ...b, verdict });
|
|
407
|
+
if (b.purchaseId) ctx?.purchaseIds.push(b.purchaseId);
|
|
408
|
+
}
|
|
409
|
+
let result;
|
|
410
|
+
try {
|
|
411
|
+
result = await run();
|
|
412
|
+
} catch (err) {
|
|
413
|
+
await giveBack(err.message);
|
|
414
|
+
throw err;
|
|
415
|
+
}
|
|
416
|
+
for (const b of booked) limiter.spent(b.entries, result, { verdict: b.verdict, purchase, purchaseId: b.purchaseId, approval: b.approval ?? null });
|
|
417
|
+
return result;
|
|
418
|
+
}
|
|
419
|
+
|
|
349
420
|
// Tempo: only a plain stablecoin transfer, checked here instead of by presign-guard.
|
|
350
421
|
function tempoRequest(method, args, chainId) {
|
|
351
422
|
const tokens = TEMPO_TOKENS[chainId];
|
|
352
|
-
const ok = method === "writeContract" && tokens.includes(String(args?.address ?? "").toLowerCase())
|
|
423
|
+
const ok = (SAME_AS[method] ?? method) === "writeContract" && tokens.includes(String(args?.address ?? "").toLowerCase())
|
|
353
424
|
&& TEMPO_TRANSFERS.has(args?.functionName) && !(BigInt(args?.value ?? 0n) > 0n);
|
|
354
425
|
let request = null;
|
|
355
426
|
try { request = ok ? checkRequestFor(method, args, { chainId, origin }) : null; } catch { request = null; }
|
|
@@ -357,10 +428,76 @@ export function guardWallet(wallet, {
|
|
|
357
428
|
return request;
|
|
358
429
|
}
|
|
359
430
|
|
|
431
|
+
// EIP-7702 authorizations this wallet signed after a check, so the transaction that carries them is not
|
|
432
|
+
// charged for a second check.
|
|
433
|
+
const checkedAuthorizations = new Set();
|
|
434
|
+
|
|
435
|
+
// An EIP-7702 authorization moves nothing by itself but hands the contract the whole wallet: checked (stricter
|
|
436
|
+
// on orange and on errors, see verdictFor), counted toward no limit, signed for exactly the chain id checked.
|
|
437
|
+
async function signAuthorizationGuarded(target, original, args, rest, chainId) {
|
|
438
|
+
const request = checkRequestFor("signAuthorization", args, { chainId, origin, from: senderOf(args, target) });
|
|
439
|
+
if (!request) throw new PresignBlockedError("an EIP-7702 authorization needs the contract's address; nothing was signed", { code: "check_failed" });
|
|
440
|
+
await verdictFor("signAuthorization", request, request.chainId);
|
|
441
|
+
// Signed exactly as checked: this contract, this chain id.
|
|
442
|
+
const { contractAddress: _ignored, ...fields } = args;
|
|
443
|
+
const signed = await original({ ...fields, address: request.address, chainId: request.authorizationChainId }, ...rest);
|
|
444
|
+
const key = authorizationKey(signed);
|
|
445
|
+
if (key) checkedAuthorizations.add(key);
|
|
446
|
+
return signed;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// The signed EIP-7702 authorizations a transaction carries (authorizationList). Those this wallet signed with
|
|
450
|
+
// signAuthorization were checked then; any other one signed by the sending account is checked now, the same way.
|
|
451
|
+
// Authorizations signed by other accounts put nothing of this wallet at risk, and those for another chain do
|
|
452
|
+
// nothing on this one.
|
|
453
|
+
async function checkAuthorizationList(list, chainId, from) {
|
|
454
|
+
for (const a of list) {
|
|
455
|
+
const key = authorizationKey(a);
|
|
456
|
+
if (key && checkedAuthorizations.has(key)) continue;
|
|
457
|
+
const on = Number(a?.chainId);
|
|
458
|
+
if (on !== 0 && on !== chainId) continue;
|
|
459
|
+
let signer = null;
|
|
460
|
+
try { signer = await recoverAuthorizationAddress({ authorization: a }); } catch { signer = null; }
|
|
461
|
+
if (signer && from && signer.toLowerCase() !== from.toLowerCase()) continue;
|
|
462
|
+
// viem sends a signed authorization's `address` as the contract.
|
|
463
|
+
const request = checkRequestFor("signAuthorization", { address: a?.address, chainId: a?.chainId, nonce: a?.nonce }, { chainId, origin, from });
|
|
464
|
+
if (!request) throw new PresignBlockedError("an EIP-7702 authorization in authorizationList has no contract address; nothing was signed", { code: "check_failed" });
|
|
465
|
+
await verdictFor("signAuthorization", request, request.chainId);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// EIP-5792 batches (sendCalls, sendCallsSync): every call is checked like a transaction from the same wallet and
|
|
470
|
+
// counts toward the limits; one red or stopped call stops the whole batch, before anything is signed.
|
|
471
|
+
async function sendCallsGuarded(target, method, original, args, rest, chainId) {
|
|
472
|
+
if (TEMPO_TOKENS[chainId]) throw new PresignBlockedError(`on Tempo (chain ${chainId}) this wallet sends no batches; nothing was signed`, { code: "unsupported_chain" });
|
|
473
|
+
const calls = Array.isArray(args?.calls) ? args.calls : [];
|
|
474
|
+
if (!calls.length) throw new PresignBlockedError("a batch without calls; nothing was signed", { code: "check_failed" });
|
|
475
|
+
const from = senderOf(args, target);
|
|
476
|
+
const checked = [];
|
|
477
|
+
for (const call of calls) {
|
|
478
|
+
// A call is { to, data, value } or { to, abi, functionName, args, value }, as viem takes them.
|
|
479
|
+
const request = call?.abi
|
|
480
|
+
? checkRequestFor("writeContract", { address: call.to, abi: call.abi, functionName: call.functionName, args: call.args, value: call.value }, { chainId, origin, from })
|
|
481
|
+
: checkRequestFor("sendTransaction", call, { chainId, origin, from });
|
|
482
|
+
// A deployment in the batch: not checked, but the value it sends counts.
|
|
483
|
+
if (!request) checked.push({ request: { type: "transaction", chainId, to: null, data: call?.data ?? "0x", value: String(call?.value ?? 0n) }, verdict: null });
|
|
484
|
+
else checked.push({ request, verdict: await verdictFor(method, request, chainId) });
|
|
485
|
+
}
|
|
486
|
+
const run = () => original(args, ...rest);
|
|
487
|
+
return limiter ? withinLimitsAll(method, checked, run) : run();
|
|
488
|
+
}
|
|
489
|
+
|
|
360
490
|
async function guarded(target, method, original, args, rest) {
|
|
361
491
|
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
362
492
|
const chainId = args?.chain?.id ?? target.chain?.id;
|
|
363
493
|
const run = () => original(args, ...rest);
|
|
494
|
+
if (BATCHES.has(method)) return sendCallsGuarded(target, method, original, args, rest, chainId);
|
|
495
|
+
if (method === "signAuthorization") {
|
|
496
|
+
if (TEMPO_TOKENS[chainId]) throw new PresignBlockedError(`on Tempo (chain ${chainId}) this wallet signs no EIP-7702 authorization; nothing was signed`, { code: "unsupported_chain" });
|
|
497
|
+
return signAuthorizationGuarded(target, original, args, rest, chainId);
|
|
498
|
+
}
|
|
499
|
+
const authorizations = Array.isArray(args?.authorizationList) ? args.authorizationList : [];
|
|
500
|
+
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
501
|
// A plain message moves nothing by itself, so it is checked but not counted toward the limits.
|
|
365
502
|
if (method === "signMessage") {
|
|
366
503
|
const request = checkRequestFor(method, args, { chainId, origin, from: senderOf(args, target) });
|
|
@@ -371,10 +508,11 @@ export function guardWallet(wallet, {
|
|
|
371
508
|
const request = tempoRequest(method, args, chainId);
|
|
372
509
|
return limiter ? withinLimits(method, request, null, run) : run();
|
|
373
510
|
}
|
|
511
|
+
if (authorizations.length) await checkAuthorizationList(authorizations, chainId, senderOf(args, target));
|
|
374
512
|
const request = checkRequestFor(method, args, { chainId, origin, x402: x402Paying.getStore(), from: senderOf(args, target) });
|
|
375
513
|
if (!request) {
|
|
376
514
|
// A contract deployment is not checked, but the value it sends still counts.
|
|
377
|
-
if (limiter && method === "sendTransaction") {
|
|
515
|
+
if (limiter && (SAME_AS[method] ?? method) === "sendTransaction") {
|
|
378
516
|
return withinLimits(method, { type: "transaction", chainId, to: null, data: args?.data ?? "0x", value: String(args?.value ?? 0n) }, null, run);
|
|
379
517
|
}
|
|
380
518
|
return run();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "presign-guard-wallet",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.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",
|