presign-guard-wallet 0.26.1 → 0.28.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 +37 -2
- package/index.d.ts +30 -2
- package/index.js +117 -3
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
# presign-guard-wallet
|
|
2
2
|
|
|
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).
|
|
3
|
+
A [viem](https://viem.sh) wallet for AI agents that asks [presign-guard](https://presign-guard.fizzl.eu) before it signs. [Tether WDK](#tether-wdk-accounts) accounts and Solana signers too: see [Solana](#solana-usdc).
|
|
4
4
|
|
|
5
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
|
|---|---|
|
|
9
|
-
| 🟢 green | Signs |
|
|
9
|
+
| 🟢 green | Signs; with `onIncomplete: "stop"`, not when presign-guard says a check couldn't run (`checks_complete: false`) |
|
|
10
10
|
| 🟠 orange | `onOrange`: `"stop"` (default, throws), `"allow"`, or your own function (e.g. ask the user) |
|
|
11
11
|
| 🔴 red | Throws `PresignBlockedError` with the reasons; **nothing is signed** |
|
|
12
12
|
|
|
13
|
+
On red and orange the error message ends with presign-guard's fix for the first reason that has one ("to fix: approve exactly the amount needed…", "don't retry: …"), so an agent that reads only the error knows whether to rebuild the request or stop.
|
|
14
|
+
|
|
13
15
|
On top of that it can keep to **spending limits** you set per token (per transaction and per day), and ask a human for anything over them. See [Spending limits](#spending-limits).
|
|
14
16
|
|
|
15
17
|
presign-guard decodes approvals, `increaseAllowance`, `setApprovalForAll`, EIP-2612 and Permit2 permits, EIP-3009 transfer authorizations (what an x402 payment signs) and Seaport orders, and screens every spender, recipient and token: known drainers and phishing addresses, sanctions, unlimited approvals to a plain wallet, honeypot tokens, unverified or brand-new contracts, and, with `origin`, new or lookalike domains and phishing sites. See the [reason codes](https://github.com/Fizzl13/presign-guard#reason-codes).
|
|
@@ -73,6 +75,7 @@ Every other method (`getAddresses`, `extend`, `sendRawTransaction` for a transac
|
|
|
73
75
|
| `creditKey` | | A presign-guard credit key (`pgc_…`): checks are paid from prepaid credits first, then with `pay`. See [Prepaid credits](#prepaid-credits) |
|
|
74
76
|
| `fetch` | `globalThis.fetch` | Plain fetch used for credit-paid checks |
|
|
75
77
|
| `onOrange` | `"stop"` | `"stop"`, `"allow"` or `async (verdict, { method, request }) => boolean`. `"allow"` does not cover [EIP-7702 authorizations](#eip-7702-authorizations) |
|
|
78
|
+
| `onIncomplete` | `"allow"` | A green whose `checks_complete` is `false` (a check that applies couldn't run this time, named in `not_checked`): `"allow"` signs, `"stop"` throws code `incomplete`, or `async (verdict, { method, request }) => boolean` decides (e.g. stop above an amount) |
|
|
76
79
|
| `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 |
|
|
77
80
|
| `origin` | | The site asking for the signature: its domain age and phishing lists are checked too |
|
|
78
81
|
| `onVerdict` | | `(verdict, { method, request, paidWith, creditsLeft }) => void`, e.g. for logging; `paidWith` is `"credits"` or `"x402"` |
|
|
@@ -359,6 +362,38 @@ const sol = guarded.solanaSigner(keypair, { any: true });
|
|
|
359
362
|
// limits: { tokens: { USDC: { perDay: "5" }, SOL: { perTx: "0.1", perDay: "0.5" } } }
|
|
360
363
|
```
|
|
361
364
|
|
|
365
|
+
## Tether WDK accounts
|
|
366
|
+
|
|
367
|
+
`guardWdkAccount` puts the same guard in front of a [Tether WDK](https://docs.wdk.tether.io) EVM account (`@tetherto/wdk-wallet-evm`). Your agent keeps calling the WDK methods it knows; each one that signs is checked by presign-guard first, counts toward your limits, and stops on red:
|
|
368
|
+
|
|
369
|
+
| WDK method | Checked as |
|
|
370
|
+
|---|---|
|
|
371
|
+
| `transfer({ token, recipient, amount })` | the ERC-20 `transfer` it sends |
|
|
372
|
+
| `approve({ token, spender, amount })` | the ERC-20 `approve` it sends (an unlimited approve to a plain wallet is red) |
|
|
373
|
+
| `sendTransaction(tx)`, `signTransaction(tx)` | the transaction, simulated from the account; EIP-7702 authorizations in `authorizationList` too |
|
|
374
|
+
| `signTypedData({ domain, types, message })` | the signature, with the one top-level type WDK will sign (two top-level types: refused) |
|
|
375
|
+
| `sign(message)` | the message (unless `checkMessages: false`) |
|
|
376
|
+
| `signAuthorization(auth)`, `delegate(address)` | an EIP-7702 authorization, signed for exactly the contract and chain checked |
|
|
377
|
+
|
|
378
|
+
Balances, quotes and every other read go straight to the account. A transaction that is already signed (a raw hex string for `sendTransaction`) is refused, because it can't be checked before it was signed.
|
|
379
|
+
|
|
380
|
+
```js
|
|
381
|
+
import WalletManagerEvm from "@tetherto/wdk-wallet-evm";
|
|
382
|
+
import { guardWdkAccount } from "presign-guard-wallet";
|
|
383
|
+
|
|
384
|
+
const wallet = new WalletManagerEvm(process.env.SEED_PHRASE, { provider: "https://rpc.xlayer.tech" });
|
|
385
|
+
const account = guardWdkAccount(await wallet.getAccount(0), {
|
|
386
|
+
chainId: 196, // X Layer; 8453 for Base, 1 for Ethereum, …
|
|
387
|
+
pay, // or creditKey
|
|
388
|
+
limits: { tokens: { "196:0x779Ded0c9e1022225f8E0630b35a9b54bE713736": { perTx: "5", perDay: "20", decimals: 6 } } }, // USD₮0
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
await account.transfer({ token: "0x779Ded0c9e1022225f8E0630b35a9b54bE713736", recipient: shop, amount: 2_000_000n });
|
|
392
|
+
// red → PresignBlockedError, nothing signed; over 5 USD₮0 → over_limit
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
Already guarding a viem wallet? `guarded.wdkAccount(account, { chainId })` gives the WDK account the same checks, pause and budget. To pay x402 APIs with the guarded account, hand it to `wdkEvmSigner` from `x402-safe-fetch/wdk`: the payment's EIP-3009 signature is checked like any other `signTypedData`.
|
|
396
|
+
|
|
362
397
|
## MPP sessions on Tempo
|
|
363
398
|
|
|
364
399
|
`tempoSessionAccount(account)` gives a guarded viem account to pay MPP **sessions** (TIP-1034) with mppx's session client: the agent opens a payment channel once and pays each call with a signed voucher, no transaction per call.
|
package/index.d.ts
CHANGED
|
@@ -17,7 +17,13 @@ export declare const CREDIT_HEADER: string;
|
|
|
17
17
|
/** A presign-guard verdict: see https://presign-guard.fizzl.eu/openapi.json */
|
|
18
18
|
export interface PresignVerdict {
|
|
19
19
|
verdict: "green" | "orange" | "red";
|
|
20
|
-
reasons?: Array<{ code: string; severity: "red" | "orange" | "info"; subject?: string; details?: Record<string, unknown> }>;
|
|
20
|
+
reasons?: Array<{ code: string; severity: "red" | "orange" | "info"; subject?: string; details?: Record<string, unknown>; fix?: { expected: string; saw: string; change: string; retry: "change" | "elsewhere" | "ask" | "never"; set?: Record<string, unknown> } }>;
|
|
21
|
+
/** true when every orange and red reason can be changed into green */
|
|
22
|
+
fixable?: boolean;
|
|
23
|
+
checked?: Array<{ check: string; what: string }>;
|
|
24
|
+
not_checked?: Array<{ check: string; because: "unavailable" | "not_sent" | "out_of_scope"; why: string; send?: string; subject?: string }>;
|
|
25
|
+
/** false when a check that applies couldn't run this time */
|
|
26
|
+
checks_complete?: boolean;
|
|
21
27
|
subject?: Record<string, unknown>;
|
|
22
28
|
receipt?: Record<string, unknown>;
|
|
23
29
|
[key: string]: unknown;
|
|
@@ -31,7 +37,7 @@ export type CheckRequest =
|
|
|
31
37
|
| { type: "authorization"; chainId: number; address: string; authorizationChainId?: number; nonce?: string; origin?: string; from?: string };
|
|
32
38
|
|
|
33
39
|
export declare class PresignBlockedError extends Error {
|
|
34
|
-
code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain" | "over_limit" | "paused" | "limit_unavailable";
|
|
40
|
+
code: "red" | "orange" | "incomplete" | "check_failed" | "bad_receipt" | "unsupported_chain" | "over_limit" | "paused" | "limit_unavailable";
|
|
35
41
|
verdict: PresignVerdict | null;
|
|
36
42
|
request: CheckRequest | null;
|
|
37
43
|
/** With code "over_limit": which limits would be crossed. */
|
|
@@ -173,7 +179,22 @@ export interface GuardControls {
|
|
|
173
179
|
solanaSigner<S extends { address: string; signTransactions(txs: readonly { messageBytes: Uint8Array }[], config?: unknown): Promise<readonly Record<string, Uint8Array>[]> }>(signer: S, opts?: { network?: string; any?: boolean }): Pick<S, "address" | "signTransactions">;
|
|
174
180
|
/** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
|
|
175
181
|
wrap<W extends object>(wallet: W): W & GuardControls;
|
|
182
|
+
/**
|
|
183
|
+
* The same guard on a Tether WDK EVM account (@tetherto/wdk-wallet-evm) on chain chainId: transfer, approve,
|
|
184
|
+
* sendTransaction, signTransaction, signTypedData, sign, signAuthorization and delegate are checked by presign-guard
|
|
185
|
+
* first and count toward the limits; red is never signed. A signed raw transaction is refused.
|
|
186
|
+
*/
|
|
187
|
+
wdkAccount<A extends WdkEvmAccount>(account: A, opts: { chainId: number }): A & WdkGuardControls;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** What the guard needs from a Tether WDK EVM account (WalletAccountEvm). Methods it doesn't have are not added. */
|
|
191
|
+
export interface WdkEvmAccount {
|
|
192
|
+
getAddress(): Promise<string>;
|
|
193
|
+
signTypedData(typedData: { domain: Record<string, unknown>; types: Record<string, unknown>; message: Record<string, unknown> }): Promise<string>;
|
|
194
|
+
[method: string]: unknown;
|
|
176
195
|
}
|
|
196
|
+
/** pause, resume, paused, spending and withPurchase, as on the guarded viem wallet. */
|
|
197
|
+
export type WdkGuardControls = Pick<GuardControls, "pause" | "resume" | "paused" | "spending" | "withPurchase">;
|
|
177
198
|
|
|
178
199
|
export interface GuardOptions {
|
|
179
200
|
/** A fetch that pays x402, e.g. wrapFetchWithPayment(fetch, client) with spend controls. Each check costs $0.01. Optional when creditKey is set. */
|
|
@@ -184,6 +205,8 @@ export interface GuardOptions {
|
|
|
184
205
|
fetch?: typeof globalThis.fetch;
|
|
185
206
|
/** 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. */
|
|
186
207
|
onOrange?: "stop" | "allow" | ((verdict: PresignVerdict, info: { method: string; request: CheckRequest }) => boolean | Promise<boolean>);
|
|
208
|
+
/** A green whose checks_complete is false (a check that applies couldn't run): "allow" (default) signs, "stop" throws code "incomplete", a function decides. */
|
|
209
|
+
onIncomplete?: "allow" | "stop" | ((verdict: PresignVerdict, info: { method: string; request: CheckRequest }) => boolean | Promise<boolean>);
|
|
187
210
|
/** When the check cannot be done (outage, unsupported chain). Default "stop". A forged or changed verdict, and an EIP-7702 authorization, always stop. */
|
|
188
211
|
onError?: "stop" | "allow";
|
|
189
212
|
/** The site asking for the signature, if any: domain age and phishing lists are checked. */
|
|
@@ -216,6 +239,11 @@ export interface GuardOptions {
|
|
|
216
239
|
* sendCalls and sendCallsSync (every call), deployContract (its value counts toward the limits).
|
|
217
240
|
*/
|
|
218
241
|
export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W & GuardControls;
|
|
242
|
+
/**
|
|
243
|
+
* A Tether WDK EVM account (@tetherto/wdk-wallet-evm) that asks presign-guard before it signs: guardWallet's options
|
|
244
|
+
* plus chainId, the chain the account is on (8453 Base, 196 X Layer, 1 Ethereum, …).
|
|
245
|
+
*/
|
|
246
|
+
export declare function guardWdkAccount<A extends WdkEvmAccount>(account: A, options: GuardOptions & { chainId: number }): A & WdkGuardControls;
|
|
219
247
|
export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string; x402?: Record<string, unknown>; from?: string }): CheckRequest | null;
|
|
220
248
|
/**
|
|
221
249
|
* Wrap an x402 client scheme so the payment requirements it pays go along with the presign-guard check of its
|
package/index.js
CHANGED
|
@@ -75,7 +75,7 @@ export { memoryStore };
|
|
|
75
75
|
|
|
76
76
|
export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
|
|
77
77
|
export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
|
|
78
|
-
export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161, 4663, 43114];
|
|
78
|
+
export const SUPPORTED_CHAINS = [1, 10, 56, 137, 143, 196, 8453, 42161, 4663, 43114];
|
|
79
79
|
// Tempo: the stablecoins the wallet may send there (the ones the USDC limit covers).
|
|
80
80
|
export const TEMPO_TOKENS = {
|
|
81
81
|
4217: ["0x20c000000000000000000000b9537d11c60e8b50"],
|
|
@@ -89,6 +89,35 @@ const ESCROW_ABI = parseAbi([
|
|
|
89
89
|
"function topUp((address payer, address payee, address operator, address token, bytes32 salt, address authorizedSigner, bytes32 expiringNonceHash) descriptor, uint96 additionalDeposit)",
|
|
90
90
|
]);
|
|
91
91
|
const TRANSFER_ABI = parseAbi(["function transfer(address to, uint256 amount)"]);
|
|
92
|
+
const APPROVE_ABI = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]);
|
|
93
|
+
|
|
94
|
+
// Tether WDK (@tetherto/wdk-wallet-evm). Its EVM account signs EIP-712 with ethers, which works out the primary type
|
|
95
|
+
// itself: the one struct type no other type refers to.
|
|
96
|
+
function wdkRootTypes(types) {
|
|
97
|
+
const used = new Set();
|
|
98
|
+
for (const fields of Object.values(types)) for (const f of fields ?? []) used.add(String(f?.type ?? "").replace(/\[\d*\]/g, ""));
|
|
99
|
+
return Object.keys(types).filter((n) => !used.has(n));
|
|
100
|
+
}
|
|
101
|
+
// A signed authorization as ethers gives it ({ address, chainId, nonce, signature: { r, s, yParity } }), as viem has it.
|
|
102
|
+
function viemAuthorization(a) {
|
|
103
|
+
const sig = a?.signature ?? a;
|
|
104
|
+
return {
|
|
105
|
+
address: a?.address,
|
|
106
|
+
...(a?.chainId !== undefined && a?.chainId !== null && { chainId: Number(a.chainId) }),
|
|
107
|
+
...(a?.nonce !== undefined && a?.nonce !== null && { nonce: Number(a.nonce) }),
|
|
108
|
+
r: sig?.r, s: sig?.s, yParity: sig?.yParity,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
// A WDK transaction ({ to, value, data, chainId?, authorizationList?, gas fields }) as viem's sendTransaction takes it.
|
|
112
|
+
function wdkTransaction(tx) {
|
|
113
|
+
if (typeof tx === "string") throw new PresignBlockedError("a transaction that is already signed can't be checked before signing: pass the transaction itself; nothing was sent", { code: "check_failed" });
|
|
114
|
+
if (!tx || typeof tx !== "object") throw new TypeError("a WDK transaction is an object { to, value, data }");
|
|
115
|
+
return {
|
|
116
|
+
to: tx.to ?? undefined, data: tx.data ?? "0x", value: BigInt(tx.value ?? 0),
|
|
117
|
+
...(tx.chainId !== undefined && tx.chainId !== null && { chain: { id: Number(tx.chainId) } }),
|
|
118
|
+
...(Array.isArray(tx.authorizationList) && tx.authorizationList.length && { authorizationList: tx.authorizationList.map(viemAuthorization) }),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
92
121
|
const VOUCHER_DOMAIN = "TIP20 Channel Reserve";
|
|
93
122
|
export const XRPL_NETWORKS = ["xrpl:0", "xrpl:1"];
|
|
94
123
|
export const VERSION = "0.23.0";
|
|
@@ -238,6 +267,15 @@ function cleanPurchase(info) {
|
|
|
238
267
|
return out;
|
|
239
268
|
}
|
|
240
269
|
|
|
270
|
+
// presign-guard's fix for the first orange or red reason that has one (what to change to get green), for the error
|
|
271
|
+
// message: an agent that reads only the error still learns whether to rebuild the request or not sign at all.
|
|
272
|
+
function fixHint(verdict) {
|
|
273
|
+
const fix = (verdict?.reasons || []).find((r) => r?.severity !== "info" && r?.fix?.change)?.fix;
|
|
274
|
+
if (!fix) return "";
|
|
275
|
+
const what = fix.retry === "change" ? "to fix" : fix.retry === "never" ? "don't retry" : fix.retry === "elsewhere" ? "use another contract, pool or site" : "ask the user";
|
|
276
|
+
return `; ${what}: ${String(fix.change).slice(0, 240)}`;
|
|
277
|
+
}
|
|
278
|
+
|
|
241
279
|
/**
|
|
242
280
|
* @param {object} wallet a viem WalletClient
|
|
243
281
|
* @param {object} options
|
|
@@ -246,6 +284,8 @@ function cleanPurchase(info) {
|
|
|
246
284
|
* @param {typeof fetch} [options.fetch] plain fetch for credit-paid checks (default globalThis.fetch)
|
|
247
285
|
* @param {"stop"|"allow"|((verdict: object, info: object) => boolean|Promise<boolean>)} [options.onOrange]
|
|
248
286
|
* @param {"stop"|"allow"} [options.onError] when the check cannot be done (default "stop")
|
|
287
|
+
* @param {"allow"|"stop"|((verdict: object, info: object) => boolean|Promise<boolean>)} [options.onIncomplete] a green whose
|
|
288
|
+
* checks_complete is false (a check that applies couldn't run): "allow" (default) signs, "stop" throws, a function decides
|
|
249
289
|
* @param {string} [options.origin] the site asking for the signature, if any (domain age, phishing lists)
|
|
250
290
|
* @param {(verdict: object, info: {method: string, request: object}) => void} [options.onVerdict]
|
|
251
291
|
* @param {string} [options.presignUrl]
|
|
@@ -263,6 +303,7 @@ export function guardWallet(wallet, {
|
|
|
263
303
|
pay,
|
|
264
304
|
onOrange = "stop",
|
|
265
305
|
onError = "stop",
|
|
306
|
+
onIncomplete = "allow",
|
|
266
307
|
origin,
|
|
267
308
|
onVerdict,
|
|
268
309
|
presignUrl = PRESIGN_URL,
|
|
@@ -283,6 +324,7 @@ export function guardWallet(wallet, {
|
|
|
283
324
|
if (typeof pay !== "function" && !creditKey) throw new TypeError("pay is required: a fetch that pays x402, e.g. wrapFetchWithPayment(fetch, client), or a creditKey");
|
|
284
325
|
if (!["stop", "allow"].includes(onOrange) && typeof onOrange !== "function") throw new TypeError('onOrange must be "stop", "allow" or a function');
|
|
285
326
|
if (!["stop", "allow"].includes(onError)) throw new TypeError('onError must be "stop" or "allow"');
|
|
327
|
+
if (!["stop", "allow"].includes(onIncomplete) && typeof onIncomplete !== "function") throw new TypeError('onIncomplete must be "allow", "stop" or a function');
|
|
286
328
|
if (!["require", "off"].includes(verifyReceipts)) throw new TypeError('verifyReceipts must be "require" or "off"');
|
|
287
329
|
if (typeof checkMessages !== "boolean") throw new TypeError("checkMessages must be true or false");
|
|
288
330
|
|
|
@@ -345,15 +387,20 @@ export function guardWallet(wallet, {
|
|
|
345
387
|
}
|
|
346
388
|
onVerdict?.(verdict, { method, request, paidWith: verdict.paidWith, creditsLeft });
|
|
347
389
|
const why = (verdict.reasons || []).filter((r) => r.severity !== "info").map((r) => r.code).join(", ") || verdict.verdict;
|
|
348
|
-
if (verdict.verdict === "red") throw new PresignBlockedError(`not signed: red (${why})`, { code: "red", verdict, request });
|
|
390
|
+
if (verdict.verdict === "red") throw new PresignBlockedError(`not signed: red (${why})${fixHint(verdict)}`, { code: "red", verdict, request });
|
|
349
391
|
if (verdict.verdict === "orange") {
|
|
350
392
|
// onOrange "allow" does not cover an EIP-7702 authorization: only your function's yes does.
|
|
351
393
|
const authorization = request.type === "authorization";
|
|
352
394
|
const ok = (onOrange === "allow" && !authorization) || (typeof onOrange === "function" && (await onOrange(verdict, { method, request })) === true);
|
|
353
395
|
const hint = authorization && onOrange === "allow" ? '; an EIP-7702 authorization is signed on orange only when your onOrange function says yes' : "";
|
|
354
|
-
if (!ok) throw new PresignBlockedError(`not signed: orange (${why})${hint}`, { code: "orange", verdict, request });
|
|
396
|
+
if (!ok) throw new PresignBlockedError(`not signed: orange (${why})${hint}${fixHint(verdict)}`, { code: "orange", verdict, request });
|
|
355
397
|
} else if (verdict.verdict !== "green") {
|
|
356
398
|
throw new PresignBlockedError(`not signed: unknown verdict ${verdict.verdict}`, { code: "check_failed", verdict, request });
|
|
399
|
+
} else if (verdict.checks_complete === false && onIncomplete !== "allow") {
|
|
400
|
+
// Green on less than usual: a check that applies couldn't run this time (presign-guard's not_checked says which).
|
|
401
|
+
const ok = typeof onIncomplete === "function" && (await onIncomplete(verdict, { method, request })) === true;
|
|
402
|
+
const missing = (verdict.not_checked || []).filter((n) => n?.because === "unavailable").map((n) => n.check).join(", ") || "unknown";
|
|
403
|
+
if (!ok) throw new PresignBlockedError(`not signed: green, but not every check ran (${missing}); check again in a moment`, { code: "incomplete", verdict, request });
|
|
357
404
|
}
|
|
358
405
|
return verdict;
|
|
359
406
|
}
|
|
@@ -697,6 +744,18 @@ export function guardWallet(wallet, {
|
|
|
697
744
|
if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
|
|
698
745
|
return { address: signer.address, signTransactions: (txns, indexesToSign) => algorandSign(signer, network, txns, indexesToSign, any === true) };
|
|
699
746
|
},
|
|
747
|
+
/**
|
|
748
|
+
* The same guard on a Tether WDK EVM account (@tetherto/wdk-wallet-evm WalletAccountEvm) on chain chainId:
|
|
749
|
+
* transfer, approve, sendTransaction, signTransaction, signTypedData, sign, signAuthorization and delegate are
|
|
750
|
+
* each checked by presign-guard first and count toward the limits like the viem calls they match; red is never
|
|
751
|
+
* signed. Every other method (balances, quotes, getAddress) is the account's own. The returned account also has
|
|
752
|
+
* pause, resume, paused, spending and withPurchase.
|
|
753
|
+
*/
|
|
754
|
+
wdkAccount: (account, { chainId } = {}) => {
|
|
755
|
+
if (!account || typeof account.getAddress !== "function" || typeof account.signTypedData !== "function") throw new TypeError("wdkAccount(account): needs a Tether WDK EVM account (WalletAccountEvm from @tetherto/wdk-wallet-evm)");
|
|
756
|
+
if (!Number.isInteger(chainId) || chainId <= 0) throw new TypeError("wdkAccount(account, { chainId }): chainId is the chain the account is on, e.g. 8453 for Base");
|
|
757
|
+
return wdkProxy(account, chainId);
|
|
758
|
+
},
|
|
700
759
|
/** Stop every checked method until resume(). */
|
|
701
760
|
pause: () => { paused = true; },
|
|
702
761
|
resume: () => { paused = false; },
|
|
@@ -741,6 +800,53 @@ export function guardWallet(wallet, {
|
|
|
741
800
|
},
|
|
742
801
|
};
|
|
743
802
|
|
|
803
|
+
// A WDK account behind the guard: each signing method is checked as the viem call it matches (guarded), then the
|
|
804
|
+
// account itself signs exactly what was checked. Calls go to the account itself, so its own inner calls (approve
|
|
805
|
+
// sends through sendTransaction) are not checked twice.
|
|
806
|
+
function wdkProxy(account, chainId) {
|
|
807
|
+
let address = null;
|
|
808
|
+
const target = async () => {
|
|
809
|
+
if (address === null) {
|
|
810
|
+
const a = String(await account.getAddress());
|
|
811
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new TypeError(`the WDK account gave no EVM address (${a.slice(0, 60)})`);
|
|
812
|
+
address = a;
|
|
813
|
+
}
|
|
814
|
+
return { chain: { id: chainId }, account: { address } };
|
|
815
|
+
};
|
|
816
|
+
const call = async (method, args, run) => guarded(await target(), method, (checked) => run(checked), args, []);
|
|
817
|
+
const amount = (v) => {
|
|
818
|
+
try { return BigInt(v); } catch { throw new TypeError(`amount must be a whole number of base units (got ${String(v).slice(0, 40)})`); }
|
|
819
|
+
};
|
|
820
|
+
const withAuthorizations = (o) => (Array.isArray(o?.authorizationList) && o.authorizationList.length ? { authorizationList: o.authorizationList.map(viemAuthorization) } : {});
|
|
821
|
+
const methods = {
|
|
822
|
+
sendTransaction: (tx) => call("sendTransaction", wdkTransaction(tx), () => account.sendTransaction(tx)),
|
|
823
|
+
signTransaction: (tx) => call("signTransaction", wdkTransaction(tx), () => account.signTransaction(tx)),
|
|
824
|
+
transfer: (o) => call("writeContract", { address: o?.token, abi: TRANSFER_ABI, functionName: "transfer", args: [o?.recipient, amount(o?.amount)], ...withAuthorizations(o) }, () => account.transfer(o)),
|
|
825
|
+
approve: (o) => call("writeContract", { address: o?.token, abi: APPROVE_ABI, functionName: "approve", args: [o?.spender, amount(o?.amount)] }, () => account.approve(o)),
|
|
826
|
+
signTypedData: async (typedData) => {
|
|
827
|
+
const { EIP712Domain: _domainType, ...types } = typedData?.types ?? {};
|
|
828
|
+
const roots = wdkRootTypes(types);
|
|
829
|
+
if (roots.length !== 1) throw new PresignBlockedError(`typed data with ${roots.length ? `several top-level types (${roots.join(", ")})` : "no top-level type"}: WDK would pick one itself, so it is not checked or signed`, { code: "check_failed" });
|
|
830
|
+
return call("signTypedData", { domain: typedData.domain, types, primaryType: roots[0], message: typedData.message }, () => account.signTypedData({ ...typedData, types }));
|
|
831
|
+
},
|
|
832
|
+
sign: (message) => (checkMessages
|
|
833
|
+
? call("signMessage", { message: typeof message === "string" ? message : { raw: message } }, () => account.sign(message))
|
|
834
|
+
: account.sign(message)),
|
|
835
|
+
// Signed for exactly the contract and chain id checked (a chain id of 0 only when asked for explicitly).
|
|
836
|
+
signAuthorization: (auth) => call("signAuthorization", { contractAddress: auth?.address, ...(auth?.chainId !== undefined && auth?.chainId !== null && { chainId: Number(auth.chainId) }), ...(auth?.nonce !== undefined && auth?.nonce !== null && { nonce: auth.nonce }) },
|
|
837
|
+
(checked) => account.signAuthorization({ ...auth, address: checked.address, chainId: checked.chainId })),
|
|
838
|
+
delegate: (delegateAddress) => call("signAuthorization", { contractAddress: delegateAddress }, () => account.delegate(delegateAddress)),
|
|
839
|
+
};
|
|
840
|
+
return new Proxy(account, {
|
|
841
|
+
get(t, prop) {
|
|
842
|
+
if (Object.hasOwn(methods, prop) && typeof t[prop] === "function") return async (...args) => methods[prop](...args);
|
|
843
|
+
if (Object.hasOwn(extras, prop) && !(prop in t) && ["pause", "resume", "paused", "spending", "withPurchase"].includes(prop)) return extras[prop];
|
|
844
|
+
const value = Reflect.get(t, prop, t);
|
|
845
|
+
return typeof value === "function" ? value.bind(t) : value;
|
|
846
|
+
},
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
|
|
744
850
|
const proxyFor = (w) => new Proxy(w, {
|
|
745
851
|
get(target, prop, receiver) {
|
|
746
852
|
if (Object.hasOwn(extras, prop) && !(prop in target)) return extras[prop];
|
|
@@ -751,3 +857,11 @@ export function guardWallet(wallet, {
|
|
|
751
857
|
});
|
|
752
858
|
return proxyFor(wallet);
|
|
753
859
|
}
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* A Tether WDK EVM account (@tetherto/wdk-wallet-evm) that asks presign-guard before it signs: the same options as
|
|
863
|
+
* guardWallet, plus chainId, the chain the account is on. Same as guardWallet(..., options).wdkAccount(account, { chainId }).
|
|
864
|
+
*/
|
|
865
|
+
export function guardWdkAccount(account, { chainId, ...options } = {}) {
|
|
866
|
+
return guardWallet({ chain: { id: chainId } }, options).wdkAccount(account, { chainId });
|
|
867
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "presign-guard-wallet",
|
|
3
|
-
"version": "0.
|
|
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).",
|
|
3
|
+
"version": "0.28.0",
|
|
4
|
+
"description": "A wallet for AI agents (viem or Tether WDK 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": {
|
|
7
7
|
".": {
|
|
@@ -67,6 +67,9 @@
|
|
|
67
67
|
"agents",
|
|
68
68
|
"wallet",
|
|
69
69
|
"viem",
|
|
70
|
+
"tether",
|
|
71
|
+
"wdk",
|
|
72
|
+
"usdt0",
|
|
70
73
|
"solana",
|
|
71
74
|
"algorand",
|
|
72
75
|
"security",
|