presign-guard-wallet 0.11.0 → 0.12.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
@@ -233,6 +233,21 @@ client.register("xrpl:*", new ExactXrplScheme(xrpl)); // x402 payments in RLUSD,
233
233
 
234
234
  `network` is `"xrpl:0"` (mainnet) or `"xrpl:1"` (testnet). The check itself is still paid on Base (or with credits).
235
235
 
236
+ ## Algorand (USDC)
237
+
238
+ `algorandSigner` guards an Algorand signer for x402's AVM client (`@x402/avm`). In an x402 payment group the agent signs one transaction: its USDC transfer to the seller (the seller's facilitator signs and pays the fee transaction). The guarded signer signs only that: an asset transfer of USDC (ASA 31566704 on mainnet, 10458941 on testnet) from the agent's own address, with no close-out, rekey or clawback. It counts toward your `USDC` limit, and pause stops it. Anything else is refused with `unsupported_chain`.
239
+
240
+ ```js
241
+ import { toClientAvmSigner } from "@x402/avm";
242
+ import { ExactAvmScheme } from "@x402/avm/exact/client";
243
+
244
+ const guarded = guardWallet(walletClient, { pay, limits: { tokens: { USDC: { perDay: "5" } } } });
245
+ const algo = guarded.algorandSigner(toClientAvmSigner(process.env.AVM_PRIVATE_KEY), { network: "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" });
246
+ client.register("algorand:*", new ExactAvmScheme(algo)); // x402 payments in USDC on Algorand, within limits
247
+ ```
248
+
249
+ `network` is the mainnet id above (default) or `"algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="` (testnet). The account must be opted in to USDC. Algorand transfers aren't sent to presign-guard (it checks EVM and XRPL); the local rules above are the check.
250
+
236
251
  ## MPP sessions on Tempo
237
252
 
238
253
  `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/algorand.js ADDED
@@ -0,0 +1,85 @@
1
+ // Algorand for the guarded wallet: just enough to read an unsigned transaction (msgpack, as x402's AVM
2
+ // client hands them to the signer) and to write addresses, without an Algorand SDK.
3
+ import { createHash } from "node:crypto";
4
+
5
+ // x402 network ids and the USDC asset (ASA) on each.
6
+ export const ALGORAND_USDC = {
7
+ "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=": 31566704n, // mainnet
8
+ "algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=": 10458941n, // testnet
9
+ };
10
+
11
+ // A small msgpack decoder: maps, strings, binary, integers (as BigInt above 2^53), booleans, nil, arrays.
12
+ export function msgpackDecode(bytes) {
13
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
14
+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
15
+ let i = 0;
16
+ const str = (n) => { const s = new TextDecoder().decode(b.subarray(i, i + n)); i += n; return s; };
17
+ const bin = (n) => { const s = b.slice(i, i + n); i += n; return s; };
18
+ const map = (n) => { const o = {}; for (let k = 0; k < n; k++) { const key = read(); o[String(key)] = read(); } return o; };
19
+ const arr = (n) => { const a = []; for (let k = 0; k < n; k++) a.push(read()); return a; };
20
+ const u64 = (v) => (v <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : v);
21
+ function read() {
22
+ if (i >= b.length) throw new Error("msgpack: unexpected end");
23
+ const t = b[i++];
24
+ if (t <= 0x7f) return t;
25
+ if (t >= 0x80 && t <= 0x8f) return map(t & 0x0f);
26
+ if (t >= 0x90 && t <= 0x9f) return arr(t & 0x0f);
27
+ if (t >= 0xa0 && t <= 0xbf) return str(t & 0x1f);
28
+ if (t >= 0xe0) return t - 0x100;
29
+ switch (t) {
30
+ case 0xc0: return null;
31
+ case 0xc2: return false;
32
+ case 0xc3: return true;
33
+ case 0xc4: { const n = b[i]; i += 1; return bin(n); }
34
+ case 0xc5: { const n = dv.getUint16(i); i += 2; return bin(n); }
35
+ case 0xc6: { const n = dv.getUint32(i); i += 4; return bin(n); }
36
+ case 0xcc: return b[i++];
37
+ case 0xcd: { const v = dv.getUint16(i); i += 2; return v; }
38
+ case 0xce: { const v = dv.getUint32(i); i += 4; return v; }
39
+ case 0xcf: { const v = dv.getBigUint64(i); i += 8; return u64(v); }
40
+ case 0xd0: { const v = dv.getInt8(i); i += 1; return v; }
41
+ case 0xd1: { const v = dv.getInt16(i); i += 2; return v; }
42
+ case 0xd2: { const v = dv.getInt32(i); i += 4; return v; }
43
+ case 0xd3: { const v = dv.getBigInt64(i); i += 8; return u64(v); }
44
+ case 0xd9: { const n = b[i]; i += 1; return str(n); }
45
+ case 0xda: { const n = dv.getUint16(i); i += 2; return str(n); }
46
+ case 0xdb: { const n = dv.getUint32(i); i += 4; return str(n); }
47
+ case 0xdc: { const n = dv.getUint16(i); i += 2; return arr(n); }
48
+ case 0xdd: { const n = dv.getUint32(i); i += 4; return arr(n); }
49
+ case 0xde: { const n = dv.getUint16(i); i += 2; return map(n); }
50
+ case 0xdf: { const n = dv.getUint32(i); i += 4; return map(n); }
51
+ default: throw new Error(`msgpack: type 0x${t.toString(16)} not supported`);
52
+ }
53
+ }
54
+ const out = read();
55
+ if (i !== b.length) throw new Error("msgpack: trailing bytes");
56
+ return out;
57
+ }
58
+
59
+ const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
60
+ // An Algorand address from a 32-byte public key: base32 of the key and a 4-byte checksum.
61
+ export function algorandAddress(pub) {
62
+ const raw = Buffer.concat([Buffer.from(pub), createHash("sha512-256").update(pub).digest().subarray(28)]);
63
+ let bits = 0, v = 0, out = "";
64
+ for (const byte of raw) { v = (v << 8) | byte; bits += 8; while (bits >= 5) { out += B32[(v >>> (bits - 5)) & 31]; bits -= 5; } }
65
+ if (bits) out += B32[(v << (5 - bits)) & 31];
66
+ return out;
67
+ }
68
+
69
+ // An unsigned transaction's fields that matter for spending, as plain values (addresses as strings).
70
+ export function readAlgorandTxn(bytes) {
71
+ const t = msgpackDecode(bytes);
72
+ if (!t || typeof t !== "object" || Array.isArray(t)) throw new Error("not an Algorand transaction");
73
+ const addr = (v) => (v instanceof Uint8Array && v.length === 32 ? algorandAddress(v) : null);
74
+ return {
75
+ type: t.type ?? null,
76
+ sender: addr(t.snd),
77
+ receiver: addr(t.arcv) ?? addr(t.rcv),
78
+ amount: BigInt(t.aamt ?? t.amt ?? 0),
79
+ assetId: t.xaid === undefined ? null : BigInt(t.xaid),
80
+ closeTo: addr(t.aclose) ?? addr(t.close),
81
+ rekeyTo: addr(t.rekey),
82
+ clawbackFrom: addr(t.asnd),
83
+ fee: BigInt(t.fee ?? 0),
84
+ };
85
+ }
package/index.d.ts CHANGED
@@ -9,6 +9,8 @@ export declare const TEMPO_TOKENS: Record<number, string[]>;
9
9
  export declare const TEMPO_ESCROW: string;
10
10
  /** What an MPP session transaction deposits ({ token, payee, deposit }), or throws PresignBlockedError when the wallet would not sign it. */
11
11
  export declare function sessionDeposit(tx: any, chainId: number, address: string): { token: string; payee: string; deposit: bigint };
12
+ /** x402 network id -> the USDC asset (ASA) id on Algorand (mainnet and testnet). */
13
+ export declare const ALGORAND_USDC: Record<string, bigint>;
12
14
  export declare const VERSION: string;
13
15
  export declare const CREDIT_HEADER: string;
14
16
 
@@ -146,6 +148,11 @@ export interface GuardControls {
146
148
  * Tempo's escrow, in USDC.e, for this account (the deposit counts toward the USDC limits), plus its vouchers.
147
149
  */
148
150
  tempoSessionAccount<A extends LocalAccount>(account: A, opts?: { chainId?: 4217 | 42431 }): A;
151
+ /**
152
+ * A guarded Algorand signer for @x402/avm (ExactAvmScheme): signs only the agent's own USDC transfer in a
153
+ * payment group (no close-out, rekey or clawback), counted toward the USDC limits; anything else is refused.
154
+ */
155
+ algorandSigner<S extends { address: string; signTransactions(txns: Uint8Array[], indexesToSign?: number[]): Promise<(Uint8Array | null)[]> }>(signer: S, opts?: { network?: string }): S;
149
156
  /** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
150
157
  wrap<W extends object>(wallet: W): W & GuardControls;
151
158
  }
package/index.js CHANGED
@@ -37,6 +37,10 @@
37
37
  // Tempo's escrow in USDC.e (the deposit counts toward the USDC limits), plus that channel's
38
38
  // vouchers and close authorizations; raw hashes, messages and anything else are refused.
39
39
  //
40
+ // Algorand: algorandSigner(signer) wraps an x402 AVM client signer (toClientAvmSigner from @x402/avm). It
41
+ // signs only an asset transfer of USDC from that account (no close-out, rekey or clawback), checked here
42
+ // (presign-guard doesn't cover Algorand) and counted toward the USDC limits.
43
+ //
40
44
  // XRP Ledger: xrplSigner(signer) wraps an XRPL signer ({ classicAddress, sign(tx) },
41
45
  // e.g. createXrplWalletSigner from @x402/xrpl) the same way. It signs only
42
46
  // Payment transactions, each checked by presign-guard first (type "xrpl": fake
@@ -51,6 +55,8 @@ import { createRemoteLimiter } from "./remote.js";
51
55
  import { AsyncLocalStorage } from "node:async_hooks";
52
56
 
53
57
  import { mandateFor } from "./mandate.js";
58
+ import { ALGORAND_USDC, readAlgorandTxn } from "./algorand.js";
59
+ export { ALGORAND_USDC } from "./algorand.js";
54
60
  export { mandatePayer, mandateDigest, mandateBinding } from "./mandate.js";
55
61
  export { memoryStore };
56
62
 
@@ -72,7 +78,7 @@ const ESCROW_ABI = parseAbi([
72
78
  const TRANSFER_ABI = parseAbi(["function transfer(address to, uint256 amount)"]);
73
79
  const VOUCHER_DOMAIN = "TIP20 Channel Reserve";
74
80
  export const XRPL_NETWORKS = ["xrpl:0", "xrpl:1"];
75
- export const VERSION = "0.11.0";
81
+ export const VERSION = "0.12.0";
76
82
  export const CREDIT_HEADER = "x-credit-key";
77
83
  const ROUTE = "POST /v1/check";
78
84
 
@@ -338,6 +344,28 @@ export function guardWallet(wallet, {
338
344
  return limiter ? withinLimits("signXrplPayment", request, verdict, run) : run();
339
345
  }
340
346
 
347
+ // Algorand: sign only a USDC transfer from this address, within the limits (Algorand is not covered by presign-guard).
348
+ async function algorandSign(signer, network, txns, indexesToSign) {
349
+ if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
350
+ const mine = (indexesToSign ?? txns.map((_, i) => i)).filter((i) => Number.isInteger(i) && i >= 0 && i < txns.length);
351
+ if (mine.length !== 1) throw new PresignBlockedError(`on Algorand this wallet signs one USDC transfer per payment (asked for ${mine.length}); nothing was signed`, { code: "unsupported_chain" });
352
+ let t;
353
+ try { t = readAlgorandTxn(txns[mine[0]]); } catch (err) { throw new PresignBlockedError(`could not read the Algorand transaction (${err.message}); nothing was signed`, { code: "unsupported_chain" }); }
354
+ const usdc = ALGORAND_USDC[network];
355
+ const why = t.type !== "axfer" ? `it is a "${t.type}" transaction, not an asset transfer`
356
+ : t.sender !== signer.address ? "it is not sent from this account"
357
+ : t.assetId !== usdc ? `asset ${t.assetId} is not USDC (${usdc})`
358
+ : t.closeTo ? "it closes the account's USDC out"
359
+ : t.rekeyTo ? "it rekeys the account"
360
+ : t.clawbackFrom ? "it is a clawback"
361
+ : !t.receiver ? "it has no receiver"
362
+ : null;
363
+ if (why) throw new PresignBlockedError(`on Algorand this wallet only sends USDC: ${why}; nothing was signed`, { code: "unsupported_chain" });
364
+ const request = { type: "algorand", network, txn: { type: t.type, sender: t.sender, receiver: t.receiver, amount: String(t.amount), assetId: String(t.assetId) }, ...(origin ? { origin } : {}) };
365
+ const run = () => signer.signTransactions(txns, mine);
366
+ return limiter ? withinLimits("signAlgorandTransfer", request, null, run) : run();
367
+ }
368
+
341
369
  const extras = {
342
370
  /**
343
371
  * The same guard on an XRP Ledger signer ({ classicAddress, sign(tx) }, e.g. createXrplWalletSigner
@@ -383,6 +411,18 @@ export function guardWallet(wallet, {
383
411
  },
384
412
  };
385
413
  },
414
+ /**
415
+ * The same guard on an x402 AVM client signer ({ address, signTransactions(txns, indexesToSign) }, e.g.
416
+ * toClientAvmSigner from @x402/avm): of the transactions it is asked to sign it signs only an asset transfer
417
+ * of USDC on that network from this address (no close-out, rekey or clawback), counted toward the USDC limit.
418
+ * The facilitator's fee-payer transaction in the same group is not this signer's and is left unsigned.
419
+ * network: the x402 id of Algorand mainnet (default) or testnet.
420
+ */
421
+ algorandSigner: (signer, { network = "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" } = {}) => {
422
+ if (!signer || typeof signer.signTransactions !== "function" || typeof signer.address !== "string") throw new TypeError("algorandSigner(signer): signer needs address and signTransactions(txns, indexesToSign) (e.g. toClientAvmSigner from @x402/avm)");
423
+ if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
424
+ return { address: signer.address, signTransactions: (txns, indexesToSign) => algorandSign(signer, network, txns, indexesToSign) };
425
+ },
386
426
  /** Stop every checked method until resume(). */
387
427
  pause: () => { paused = true; },
388
428
  resume: () => { paused = false; },
package/limits.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // it can spend that amount, so it counts when it is given; an unlimited
11
11
  // one or setApprovalForAll is over any limit;
12
12
  // - an EIP-3009 payment or Permit2 transfer signature;
13
+ // - an Algorand asset transfer: USDC (ASA 31566704) counts toward the USDC limit;
13
14
  // - an XRP Ledger Payment: XRP (drops) counts toward an XRP limit, RLUSD from
14
15
  // Ripple's issuer toward the USDC limit (a dollar is a dollar), any other
15
16
  // issued currency as an unknown token. SendMax, when set, is what can leave.
@@ -20,6 +21,7 @@
20
21
  // Amounts are kept at 18 decimals so one budget can cover the same token with
21
22
  // different decimals on different chains (USDC is 18 on BNB Chain, 6 elsewhere).
22
23
  import { decodeFunctionData, formatUnits, parseAbi, parseUnits } from "viem";
24
+ import { ALGORAND_USDC } from "./algorand.js";
23
25
 
24
26
  const SCALE = 18;
25
27
  const NATIVE = "native";
@@ -89,6 +91,7 @@ export function normalizeLimits(limits) {
89
91
  if (symbol === "USDC") {
90
92
  for (const [chain, list] of Object.entries(USDC)) for (const [addr, decimals] of list) put(`${chain}:${addr}`, { budget: name, decimals });
91
93
  for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:rlusd`, { budget: name, decimals: SCALE });
94
+ for (const [net, asa] of Object.entries(ALGORAND_USDC)) put(`${net}:${asa}`, { budget: name, decimals: 6 });
92
95
  } else if (symbol === "XRP") {
93
96
  for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:${NATIVE}`, { budget: name, decimals: 6 });
94
97
  } else if (["ETH", "BNB", "POL"].includes(symbol)) {
@@ -114,6 +117,7 @@ const scaled = (raw, decimals) => (decimals <= SCALE ? raw * 10n ** BigInt(SCALE
114
117
  export function spendFor(request, verdict) {
115
118
  const out = { items: [], counterparties: [], unknown: false };
116
119
  if (request.type === "xrpl") return xrplSpend(request, out);
120
+ if (request.type === "algorand") return algorandSpend(request, out);
117
121
  const chainId = request.chainId;
118
122
  if (request.type === "transaction") {
119
123
  const to = lower(request.to ?? null);
@@ -175,6 +179,18 @@ function xrplSpend(request, out) {
175
179
  return out;
176
180
  }
177
181
 
182
+ // An Algorand asset transfer (read from the unsigned transaction by algorandSigner): the asset, amount and receiver.
183
+ // Anything else (a payment in ALGO, a close-out, a rekey, a clawback) can't be counted and is unknown.
184
+ function algorandSpend(request, out) {
185
+ const net = request.network;
186
+ const t = request.txn ?? {};
187
+ const to = typeof t.receiver === "string" ? lower(t.receiver) : null;
188
+ out.counterparties.push(to);
189
+ if (t.type !== "axfer" || t.closeTo || t.rekeyTo || t.clawbackFrom || !/^\d+$/.test(String(t.assetId ?? "")) || !/^\d+$/.test(String(t.amount ?? ""))) { out.unknown = true; return out; }
190
+ out.items.push({ chainId: net, token: String(t.assetId), amount: BigInt(t.amount), to });
191
+ return out;
192
+ }
193
+
178
194
  const fmt = (x) => (x === null ? "unlimited" : formatUnits(x, SCALE));
179
195
  const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "a new contract");
180
196
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -31,6 +31,7 @@
31
31
  "telegram.js",
32
32
  "remote.js",
33
33
  "mandate.js",
34
+ "algorand.js",
34
35
  "telegram.d.ts",
35
36
  "README.md",
36
37
  "LICENSE"
@@ -49,6 +50,7 @@
49
50
  "viem": "^2.30.0"
50
51
  },
51
52
  "devDependencies": {
53
+ "@x402/avm": "^2.28.0",
52
54
  "@x402/fetch": "^2.27.0",
53
55
  "viem": "^2.56.9"
54
56
  },