presign-guard-wallet 0.27.0 → 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 CHANGED
@@ -1,6 +1,6 @@
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
 
@@ -362,6 +362,38 @@ const sol = guarded.solanaSigner(keypair, { any: true });
362
362
  // limits: { tokens: { USDC: { perDay: "5" }, SOL: { perTx: "0.1", perDay: "0.5" } } }
363
363
  ```
364
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
+
365
397
  ## MPP sessions on Tempo
366
398
 
367
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
@@ -179,7 +179,22 @@ export interface GuardControls {
179
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">;
180
180
  /** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
181
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;
182
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">;
183
198
 
184
199
  export interface GuardOptions {
185
200
  /** A fetch that pays x402, e.g. wrapFetchWithPayment(fetch, client) with spend controls. Each check costs $0.01. Optional when creditKey is set. */
@@ -224,6 +239,11 @@ export interface GuardOptions {
224
239
  * sendCalls and sendCallsSync (every call), deployContract (its value counts toward the limits).
225
240
  */
226
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;
227
247
  export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string; x402?: Record<string, unknown>; from?: string }): CheckRequest | null;
228
248
  /**
229
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";
@@ -715,6 +744,18 @@ export function guardWallet(wallet, {
715
744
  if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
716
745
  return { address: signer.address, signTransactions: (txns, indexesToSign) => algorandSign(signer, network, txns, indexesToSign, any === true) };
717
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
+ },
718
759
  /** Stop every checked method until resume(). */
719
760
  pause: () => { paused = true; },
720
761
  resume: () => { paused = false; },
@@ -759,6 +800,53 @@ export function guardWallet(wallet, {
759
800
  },
760
801
  };
761
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
+
762
850
  const proxyFor = (w) => new Proxy(w, {
763
851
  get(target, prop, receiver) {
764
852
  if (Object.hasOwn(extras, prop) && !(prop in target)) return extras[prop];
@@ -769,3 +857,11 @@ export function guardWallet(wallet, {
769
857
  });
770
858
  return proxyFor(wallet);
771
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.27.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",