presign-guard-wallet 0.15.0 → 0.16.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
@@ -266,6 +266,22 @@ client.register("algorand:*", new ExactAvmScheme(algo)); // x402 payments in USD
266
266
 
267
267
  `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.
268
268
 
269
+ ## Solana (USDC)
270
+
271
+ `solanaSigner` guards a Solana signer for x402's SVM client (`@x402/svm`). An x402 payment on Solana is one transaction: compute-budget settings, one USDC `TransferChecked` from the agent's account to the seller, and a memo (the seller's facilitator pays the fee). The guarded signer signs only that shape, with USDC as the token and the agent as the transfer's authority. Before it signs, presign-guard checks the transaction (`type: "solana"`): it reads every instruction and simulates it, so a hidden owner change or delegate is caught. The payment counts toward your `USDC` limit, and pause stops it. Anything else is refused with `unsupported_chain` before any check is paid.
272
+
273
+ ```js
274
+ import { createKeyPairSignerFromBytes, getBase58Encoder } from "@solana/kit";
275
+ import { ExactSvmScheme } from "@x402/svm/exact/client";
276
+
277
+ const guarded = guardWallet(walletClient, { pay, limits: { tokens: { USDC: { perDay: "5" } } } });
278
+ const keypair = await createKeyPairSignerFromBytes(getBase58Encoder().encode(process.env.SVM_PRIVATE_KEY));
279
+ const sol = guarded.solanaSigner(keypair); // mainnet; { network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1" } for devnet
280
+ client.register("solana:*", new ExactSvmScheme(sol)); // x402 payments in USDC on Solana, checked and within limits
281
+ ```
282
+
283
+ The check itself is still paid on Base (or with credits).
284
+
269
285
  ## MPP sessions on Tempo
270
286
 
271
287
  `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
@@ -154,6 +154,12 @@ export interface GuardControls {
154
154
  * payment group (no close-out, rekey or clawback), counted toward the USDC limits; anything else is refused.
155
155
  */
156
156
  algorandSigner<S extends { address: string; signTransactions(txns: Uint8Array[], indexesToSign?: number[]): Promise<(Uint8Array | null)[]> }>(signer: S, opts?: { network?: string }): S;
157
+ /**
158
+ * A guarded Solana signer for @x402/svm (ExactSvmScheme): signs only an x402 USDC payment from this account
159
+ * (compute budget, one TransferChecked, memo), checked by presign-guard and counted toward the USDC limits;
160
+ * anything else is refused.
161
+ */
162
+ solanaSigner<S extends { address: string; signTransactions(txs: readonly { messageBytes: Uint8Array }[], config?: unknown): Promise<readonly Record<string, Uint8Array>[]> }>(signer: S, opts?: { network?: string }): Pick<S, "address" | "signTransactions">;
157
163
  /** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
158
164
  wrap<W extends object>(wallet: W): W & GuardControls;
159
165
  }
package/index.js CHANGED
@@ -56,6 +56,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
56
56
 
57
57
  import { mandateFor } from "./mandate.js";
58
58
  import { ALGORAND_USDC, readAlgorandTxn } from "./algorand.js";
59
+ import { SOLANA_USDC, readSolanaPayment, wireTransaction } from "./solana.js";
59
60
  export { ALGORAND_USDC } from "./algorand.js";
60
61
  export { mandatePayer, mandateDigest, mandateBinding } from "./mandate.js";
61
62
  export { memoryStore };
@@ -78,7 +79,7 @@ const ESCROW_ABI = parseAbi([
78
79
  const TRANSFER_ABI = parseAbi(["function transfer(address to, uint256 amount)"]);
79
80
  const VOUCHER_DOMAIN = "TIP20 Channel Reserve";
80
81
  export const XRPL_NETWORKS = ["xrpl:0", "xrpl:1"];
81
- export const VERSION = "0.15.0";
82
+ export const VERSION = "0.16.0";
82
83
  export const CREDIT_HEADER = "x-credit-key";
83
84
  const ROUTE = "POST /v1/check";
84
85
 
@@ -291,7 +292,7 @@ export function guardWallet(wallet, {
291
292
 
292
293
  // The verdict for a request, or null when the check could not be done and onError is "allow".
293
294
  async function verdictFor(method, request, chainId) {
294
- if (request.type !== "message" && !SUPPORTED_CHAINS.includes(chainId) && !XRPL_NETWORKS.includes(chainId)) {
295
+ if (request.type !== "message" && request.type !== "solana" && !SUPPORTED_CHAINS.includes(chainId) && !XRPL_NETWORKS.includes(chainId)) {
295
296
  if (onError === "allow") return null;
296
297
  throw new PresignBlockedError(`chain ${chainId} is not covered by presign-guard; nothing was signed`, { code: "unsupported_chain", request });
297
298
  }
@@ -417,6 +418,25 @@ export function guardWallet(wallet, {
417
418
  return limiter ? withinLimits("signAlgorandTransfer", request, null, run) : run();
418
419
  }
419
420
 
421
+ // Solana: sign only an x402 payment (one USDC TransferChecked from this account, compute-budget settings and a
422
+ // memo), each checked by presign-guard (decoded and simulated) and counted toward the USDC limit.
423
+ async function solanaSign(signer, network, transactions, config) {
424
+ const out = [];
425
+ for (const tx of transactions) {
426
+ if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
427
+ let payment;
428
+ try { payment = readSolanaPayment(tx.messageBytes, signer.address, network); } catch (err) {
429
+ throw new PresignBlockedError(`on Solana this wallet only signs x402 USDC payments: ${err.message}; nothing was signed`, { code: "unsupported_chain" });
430
+ }
431
+ const request = { type: "solana", transaction: wireTransaction(tx.messageBytes, payment.numSigners), from: signer.address, ...(origin ? { origin } : {}) };
432
+ const verdict = await verdictFor("signSolanaTransfer", request, network);
433
+ const run = async () => (await signer.signTransactions([tx], config))[0];
434
+ const spend = { type: "solana", network, transfer: { mint: payment.mint, amount: String(payment.amount), destination: payment.destination } };
435
+ out.push(await (limiter ? withinLimits("signSolanaTransfer", spend, verdict, run) : run()));
436
+ }
437
+ return out;
438
+ }
439
+
420
440
  const extras = {
421
441
  /**
422
442
  * The same guard on an XRP Ledger signer ({ classicAddress, sign(tx) }, e.g. createXrplWalletSigner
@@ -469,6 +489,17 @@ export function guardWallet(wallet, {
469
489
  * The facilitator's fee-payer transaction in the same group is not this signer's and is left unsigned.
470
490
  * network: the x402 id of Algorand mainnet (default) or testnet.
471
491
  */
492
+ /**
493
+ * The same guard on a Solana signer for x402's SVM client (a @solana/kit TransactionPartialSigner, e.g.
494
+ * createKeyPairSignerFromBytes): it signs only an x402 payment (one USDC TransferChecked from this account),
495
+ * checked by presign-guard (decoded and simulated) and counted toward the USDC limit. network: mainnet
496
+ * (default) or devnet, as x402 CAIP-2 ids.
497
+ */
498
+ solanaSigner: (signer, { network = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" } = {}) => {
499
+ if (!signer || typeof signer.signTransactions !== "function" || typeof signer.address !== "string") throw new TypeError("solanaSigner(signer): signer needs address and signTransactions(transactions) (a @solana/kit TransactionPartialSigner, e.g. createKeyPairSignerFromBytes)");
500
+ if (!SOLANA_USDC[network]) throw new TypeError(`solanaSigner: network must be one of ${Object.keys(SOLANA_USDC).join(", ")}`);
501
+ return { address: signer.address, signTransactions: (transactions, config) => solanaSign(signer, network, transactions, config) };
502
+ },
472
503
  algorandSigner: (signer, { network = "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" } = {}) => {
473
504
  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)");
474
505
  if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
package/limits.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // one or setApprovalForAll is over any limit;
12
12
  // - an EIP-3009 payment or Permit2 transfer signature;
13
13
  // - an Algorand asset transfer: USDC (ASA 31566704) counts toward the USDC limit;
14
+ // - a Solana USDC transfer (x402 SVM payment): counts toward the USDC limit;
14
15
  // - an XRP Ledger Payment: XRP (drops) counts toward an XRP limit, RLUSD from
15
16
  // Ripple's issuer toward the USDC limit (a dollar is a dollar), any other
16
17
  // issued currency as an unknown token. SendMax, when set, is what can leave.
@@ -22,6 +23,7 @@
22
23
  // different decimals on different chains (USDC is 18 on BNB Chain, 6 elsewhere).
23
24
  import { decodeFunctionData, formatUnits, parseAbi, parseUnits } from "viem";
24
25
  import { ALGORAND_USDC } from "./algorand.js";
26
+ import { SOLANA_USDC } from "./solana.js";
25
27
 
26
28
  const SCALE = 18;
27
29
  const NATIVE = "native";
@@ -92,6 +94,7 @@ export function normalizeLimits(limits) {
92
94
  for (const [chain, list] of Object.entries(USDC)) for (const [addr, decimals] of list) put(`${chain}:${addr}`, { budget: name, decimals });
93
95
  for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:rlusd`, { budget: name, decimals: SCALE });
94
96
  for (const [net, asa] of Object.entries(ALGORAND_USDC)) put(`${net}:${asa}`, { budget: name, decimals: 6 });
97
+ for (const [net, mint] of Object.entries(SOLANA_USDC)) put(`${net}:${mint}`, { budget: name, decimals: 6 });
95
98
  } else if (symbol === "XRP") {
96
99
  for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:${NATIVE}`, { budget: name, decimals: 6 });
97
100
  } else if (["ETH", "BNB", "POL"].includes(symbol)) {
@@ -118,6 +121,7 @@ export function spendFor(request, verdict) {
118
121
  const out = { items: [], counterparties: [], unknown: false };
119
122
  if (request.type === "xrpl") return xrplSpend(request, out);
120
123
  if (request.type === "algorand") return algorandSpend(request, out);
124
+ if (request.type === "solana") return solanaSpend(request, out);
121
125
  const chainId = request.chainId;
122
126
  if (request.type === "transaction") {
123
127
  const to = lower(request.to ?? null);
@@ -191,6 +195,15 @@ function algorandSpend(request, out) {
191
195
  return out;
192
196
  }
193
197
 
198
+ // A Solana USDC transfer (read from the transaction by solanaSigner): the mint, amount and receiving token account.
199
+ function solanaSpend(request, out) {
200
+ const t = request.transfer ?? {};
201
+ out.counterparties.push(typeof t.destination === "string" ? t.destination : null);
202
+ if (typeof t.mint !== "string" || !/^\d+$/.test(String(t.amount ?? ""))) { out.unknown = true; return out; }
203
+ out.items.push({ chainId: request.network, token: t.mint, amount: BigInt(t.amount), to: t.destination });
204
+ return out;
205
+ }
206
+
194
207
  const fmt = (x) => (x === null ? "unlimited" : formatUnits(x, SCALE));
195
208
  const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "a new contract");
196
209
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.15.0",
3
+ "version": "0.16.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": {
@@ -32,6 +32,7 @@
32
32
  "remote.js",
33
33
  "mandate.js",
34
34
  "algorand.js",
35
+ "solana.js",
35
36
  "telegram.d.ts",
36
37
  "README.md",
37
38
  "LICENSE"
@@ -50,6 +51,7 @@
50
51
  "viem": "^2.30.0"
51
52
  },
52
53
  "devDependencies": {
54
+ "@solana/kit": "^5.5.1",
53
55
  "@x402/avm": "^2.28.0",
54
56
  "@x402/fetch": "^2.27.0",
55
57
  "viem": "^2.56.9"
package/solana.js ADDED
@@ -0,0 +1,76 @@
1
+ // Solana for the guarded wallet: just enough to read a transaction message (legacy or v0, as x402's SVM client
2
+ // hands it to the signer) and to write addresses, without a Solana SDK.
3
+
4
+ // x402 network ids and the USDC mint on each.
5
+ export const SOLANA_USDC = {
6
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // mainnet
7
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", // devnet
8
+ };
9
+ const COMPUTE_BUDGET = "ComputeBudget111111111111111111111111111111";
10
+ const MEMO = new Set(["MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr", "Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo"]);
11
+ const TOKEN_PROGRAMS = new Set(["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"]);
12
+ const TRANSFER_CHECKED = 12;
13
+
14
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
15
+ export function base58(bytes) {
16
+ let n = 0n;
17
+ for (const b of bytes) n = n * 256n + BigInt(b);
18
+ let s = "";
19
+ while (n > 0n) { s = ALPHABET[Number(n % 58n)] + s; n /= 58n; }
20
+ for (const b of bytes) { if (b !== 0) break; s = "1" + s; }
21
+ return s;
22
+ }
23
+
24
+ // A Solana message: its signer count, static account keys and instructions (program, accounts, data).
25
+ // Accounts that come from an address lookup table are null.
26
+ export function readSolanaMessage(messageBytes) {
27
+ const b = messageBytes instanceof Uint8Array ? messageBytes : new Uint8Array(messageBytes);
28
+ let i = 0;
29
+ const need = (n) => { if (i + n > b.length) throw new Error("message too short"); };
30
+ const shortvec = () => { let v = 0, shift = 0; for (;;) { need(1); const x = b[i++]; v |= (x & 0x7f) << shift; if (!(x & 0x80)) return v; shift += 7; if (shift > 14) throw new Error("bad length"); } };
31
+ const bytes = (n) => { need(n); const s = b.subarray(i, i + n); i += n; return s; };
32
+ need(1);
33
+ const versioned = (b[0] & 0x80) !== 0;
34
+ if (versioned) { if ((b[0] & 0x7f) !== 0) throw new Error(`message version ${b[0] & 0x7f} not supported`); i += 1; }
35
+ const [numSigners] = bytes(3);
36
+ const keys = Array.from({ length: shortvec() }, () => base58(bytes(32)));
37
+ bytes(32); // recent blockhash or durable nonce
38
+ const instructions = Array.from({ length: shortvec() }, () => {
39
+ const [programIndex] = bytes(1);
40
+ const accounts = Array.from(bytes(shortvec())).map((k) => keys[k] ?? null);
41
+ const data = bytes(shortvec());
42
+ return { program: keys[programIndex] ?? null, accounts, data };
43
+ });
44
+ let lookups = 0;
45
+ if (versioned) { lookups = shortvec(); for (let l = 0; l < lookups; l++) { bytes(32); bytes(shortvec()); bytes(shortvec()); } }
46
+ if (i !== b.length) throw new Error("trailing bytes");
47
+ return { numSigners, keys, instructions, lookups };
48
+ }
49
+
50
+ // The base64 wire transaction for a message, with empty signatures (what presign-guard's check reads).
51
+ export function wireTransaction(messageBytes, numSigners) {
52
+ const n = numSigners;
53
+ const head = n < 0x80 ? [n] : [(n & 0x7f) | 0x80, n >> 7];
54
+ return Buffer.concat([Buffer.from(head), Buffer.alloc(64 * n), Buffer.from(messageBytes)]).toString("base64");
55
+ }
56
+
57
+ // An x402 payment as the SVM client builds it: compute-budget settings, one USDC TransferChecked from `owner`, and
58
+ // a memo. Returns { mint, amount, source, destination }, or throws with why it is something else.
59
+ export function readSolanaPayment(messageBytes, owner, network) {
60
+ const usdc = SOLANA_USDC[network];
61
+ const msg = readSolanaMessage(messageBytes);
62
+ const transfers = [];
63
+ for (const ix of msg.instructions) {
64
+ if (ix.program === COMPUTE_BUDGET || MEMO.has(ix.program)) continue;
65
+ if (TOKEN_PROGRAMS.has(ix.program) && ix.data[0] === TRANSFER_CHECKED && ix.data.length >= 10) { transfers.push(ix); continue; }
66
+ throw new Error(`it calls ${ix.program ?? "a program from a lookup table"}, not only a USDC transfer`);
67
+ }
68
+ if (transfers.length !== 1) throw new Error(`it has ${transfers.length} token transfers, not one`);
69
+ const [source, mint, destination, authority] = transfers[0].accounts;
70
+ if (authority !== owner) throw new Error("the transfer is not signed by this account");
71
+ if (mint !== usdc) throw new Error(`token ${mint} is not USDC (${usdc})`);
72
+ if (!destination) throw new Error("the receiver comes from a lookup table");
73
+ const d = transfers[0].data;
74
+ const amount = new DataView(d.buffer, d.byteOffset).getBigUint64(1, true);
75
+ return { mint, amount, source, destination, numSigners: msg.numSigners };
76
+ }