presign-guard-wallet 0.15.0 → 0.17.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
@@ -104,7 +104,7 @@ const wallet = guardWallet(walletClient, {
104
104
  limits: {
105
105
  tokens: {
106
106
  USDC: { perTx: "5", perDay: "20" }, // whole tokens; native and bridged USDC on every chain
107
- ETH: { perTx: "0.002", perDay: "0.01" }, // the native coin; also BNB, POL
107
+ ETH: { perTx: "0.002", perDay: "0.01" }, // the native coin; also BNB, POL, XRP, SOL
108
108
  // any other token by address (any chain) or "chainId:0x…", with its decimals:
109
109
  // "8453:0x4200…0006": { perDay: "0.01", decimals: 18 },
110
110
  },
@@ -129,7 +129,8 @@ What counts as spending:
129
129
  - the native value sent with a transaction, also with a contract deployment;
130
130
  - an ERC-20 `transfer` or `transferFrom`;
131
131
  - an **allowance** (`approve`, `increaseAllowance`, Permit, Permit2): whoever gets it can spend that amount, so it counts when it is given. An unlimited allowance or `setApprovalForAll` is over any limit, and if a human approves one anyway it uses up the rest of the window. Revoking costs nothing;
132
- - an EIP-3009 payment or Permit2 transfer signature, read from presign-guard's signed verdict. A signature it cannot decode counts as unknown spending (`unknownTokens`).
132
+ - an EIP-3009 payment or Permit2 transfer signature, read from presign-guard's signed verdict. A signature it cannot decode counts as unknown spending (`unknownTokens`);
133
+ - on Solana with `solanaSigner(…, { any: true })`: what presign-guard's signed simulation shows leaving the wallet. SOL beyond the network fee counts toward `SOL`, USDC toward `USDC`, other tokens as tokens without a limit. A token delegate is over any limit, and a transaction without a complete simulation counts as unknown spending.
133
134
 
134
135
  Other contract calls (a swap that uses an allowance you already gave) spend nothing new: the allowance was counted when it was given. Budgets are shared across chains (`USDC: { perDay: "20" }` is 20 USDC in total), checked one at a time so parallel transactions cannot both fit in the last of a budget, booked before signing and given back when signing fails. A store that cannot be read stops the wallet (`limit_unavailable`).
135
136
 
@@ -266,6 +267,29 @@ client.register("algorand:*", new ExactAvmScheme(algo)); // x402 payments in USD
266
267
 
267
268
  `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
269
 
270
+ ## Solana (USDC)
271
+
272
+ `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.
273
+
274
+ ```js
275
+ import { createKeyPairSignerFromBytes, getBase58Encoder } from "@solana/kit";
276
+ import { ExactSvmScheme } from "@x402/svm/exact/client";
277
+
278
+ const guarded = guardWallet(walletClient, { pay, limits: { tokens: { USDC: { perDay: "5" } } } });
279
+ const keypair = await createKeyPairSignerFromBytes(getBase58Encoder().encode(process.env.SVM_PRIVATE_KEY));
280
+ const sol = guarded.solanaSigner(keypair); // mainnet; { network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1" } for devnet
281
+ client.register("solana:*", new ExactSvmScheme(sol)); // x402 payments in USDC on Solana, checked and within limits
282
+ ```
283
+
284
+ The check itself is still paid on Base (or with credits).
285
+
286
+ **Other Solana transactions.** With `{ any: true }` the signer also signs transfers, swaps and other transactions, for an agent that does more than pay x402 APIs (an AgentKit Solana wallet, for example). Each one is checked by presign-guard first: every instruction is read and the transaction is simulated, so a token account handed to someone else is red, and a hidden owner or delegate change is orange. What the simulation shows leaving the wallet counts toward your limits: SOL beyond the network fee toward a `SOL` limit, USDC toward `USDC`. Without a complete simulation the spending counts as unknown, so it goes to `onOverLimit`.
287
+
288
+ ```js
289
+ const sol = guarded.solanaSigner(keypair, { any: true });
290
+ // limits: { tokens: { USDC: { perDay: "5" }, SOL: { perTx: "0.1", perDay: "0.5" } } }
291
+ ```
292
+
269
293
  ## MPP sessions on Tempo
270
294
 
271
295
  `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,13 @@ 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, unless `any`: then it is checked by presign-guard and what its simulation shows
161
+ * leaving the wallet counts toward the limits (SOL, USDC; other tokens as unknown).
162
+ */
163
+ 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">;
157
164
  /** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
158
165
  wrap<W extends object>(wallet: W): W & GuardControls;
159
166
  }
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, readSolanaMessage, 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.17.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,40 @@ 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, any) {
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
+ if (!any) throw new PresignBlockedError(`on Solana this wallet only signs x402 USDC payments: ${err.message}; nothing was signed`, { code: "unsupported_chain" });
430
+ out.push(await solanaSignAny(signer, network, tx, config));
431
+ continue;
432
+ }
433
+ const request = { type: "solana", transaction: wireTransaction(tx.messageBytes, payment.numSigners), from: signer.address, ...(origin ? { origin } : {}) };
434
+ const verdict = await verdictFor("signSolanaTransfer", request, network);
435
+ const run = async () => (await signer.signTransactions([tx], config))[0];
436
+ const spend = { type: "solana", network, transfer: { mint: payment.mint, amount: String(payment.amount), destination: payment.destination } };
437
+ out.push(await (limiter ? withinLimits("signSolanaTransfer", spend, verdict, run) : run()));
438
+ }
439
+ return out;
440
+ }
441
+
442
+ // Any other Solana transaction (solanaSigner with any): checked by presign-guard, which also simulates it;
443
+ // what the signed simulation shows leaving the wallet counts toward the limits.
444
+ async function solanaSignAny(signer, network, tx, config) {
445
+ let numSigners;
446
+ try { ({ numSigners } = readSolanaMessage(tx.messageBytes)); } catch (err) {
447
+ throw new PresignBlockedError(`not a Solana transaction this wallet can read (${err.message}); nothing was signed`, { code: "unsupported_chain" });
448
+ }
449
+ const request = { type: "solana", transaction: wireTransaction(tx.messageBytes, numSigners), from: signer.address, ...(origin ? { origin } : {}) };
450
+ const verdict = await verdictFor("signSolanaTransaction", request, network);
451
+ const run = async () => (await signer.signTransactions([tx], config))[0];
452
+ return limiter ? withinLimits("signSolanaTransaction", { type: "solana", network, simulated: true, from: signer.address }, verdict, run) : run();
453
+ }
454
+
420
455
  const extras = {
421
456
  /**
422
457
  * The same guard on an XRP Ledger signer ({ classicAddress, sign(tx) }, e.g. createXrplWalletSigner
@@ -469,6 +504,18 @@ export function guardWallet(wallet, {
469
504
  * The facilitator's fee-payer transaction in the same group is not this signer's and is left unsigned.
470
505
  * network: the x402 id of Algorand mainnet (default) or testnet.
471
506
  */
507
+ /**
508
+ * The same guard on a Solana signer for x402's SVM client (a @solana/kit TransactionPartialSigner, e.g.
509
+ * createKeyPairSignerFromBytes): it signs only an x402 payment (one USDC TransferChecked from this account),
510
+ * checked by presign-guard (decoded and simulated) and counted toward the USDC limit. network: mainnet
511
+ * (default) or devnet, as x402 CAIP-2 ids. any: also sign other transactions (transfers, swaps), each
512
+ * checked by presign-guard; what its simulation shows leaving the wallet counts toward the limits.
513
+ */
514
+ solanaSigner: (signer, { network = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", any = false } = {}) => {
515
+ 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)");
516
+ if (!SOLANA_USDC[network]) throw new TypeError(`solanaSigner: network must be one of ${Object.keys(SOLANA_USDC).join(", ")}`);
517
+ return { address: signer.address, signTransactions: (transactions, config) => solanaSign(signer, network, transactions, config, any === true) };
518
+ },
472
519
  algorandSigner: (signer, { network = "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" } = {}) => {
473
520
  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
521
  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,11 @@
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;
15
+ // - any other Solana transaction (solanaSigner with any): what presign-guard's signed simulation shows
16
+ // leaving the wallet, SOL (beyond the network fee) toward a SOL limit, USDC toward the USDC limit,
17
+ // other tokens as unknown; a token delegate is over any limit, and no or an incomplete simulation
18
+ // counts as unknown spending;
14
19
  // - an XRP Ledger Payment: XRP (drops) counts toward an XRP limit, RLUSD from
15
20
  // Ripple's issuer toward the USDC limit (a dollar is a dollar), any other
16
21
  // issued currency as an unknown token. SendMax, when set, is what can leave.
@@ -22,6 +27,7 @@
22
27
  // different decimals on different chains (USDC is 18 on BNB Chain, 6 elsewhere).
23
28
  import { decodeFunctionData, formatUnits, parseAbi, parseUnits } from "viem";
24
29
  import { ALGORAND_USDC } from "./algorand.js";
30
+ import { SOLANA_USDC } from "./solana.js";
25
31
 
26
32
  const SCALE = 18;
27
33
  const NATIVE = "native";
@@ -38,8 +44,8 @@ const USDC = {
38
44
  4217: [["0x20c000000000000000000000b9537d11c60e8b50", 6]],
39
45
  42431: [["0x20c0000000000000000000000000000000000000", 6]],
40
46
  };
41
- const NATIVE_SYMBOL = { 1: "ETH", 10: "ETH", 8453: "ETH", 42161: "ETH", 56: "BNB", 137: "POL", "xrpl:0": "XRP", "xrpl:1": "XRP" };
42
- export const KNOWN_TOKENS = ["USDC", "ETH", "BNB", "POL", "XRP"];
47
+ const NATIVE_SYMBOL = { 1: "ETH", 10: "ETH", 8453: "ETH", 42161: "ETH", 56: "BNB", 137: "POL", "xrpl:0": "XRP", "xrpl:1": "XRP", ...Object.fromEntries(Object.keys(SOLANA_USDC).map((n) => [n, "SOL"])) };
48
+ export const KNOWN_TOKENS = ["USDC", "ETH", "BNB", "POL", "XRP", "SOL"];
43
49
 
44
50
  // XRP Ledger networks and the RLUSD issuer on each (Ripple's).
45
51
  export const XRPL_RLUSD_ISSUERS = { "xrpl:0": "rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De", "xrpl:1": "rQhWct2fv4Vc4KRjRgMrxa8xPN9Zx9iLKV" };
@@ -92,8 +98,11 @@ export function normalizeLimits(limits) {
92
98
  for (const [chain, list] of Object.entries(USDC)) for (const [addr, decimals] of list) put(`${chain}:${addr}`, { budget: name, decimals });
93
99
  for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:rlusd`, { budget: name, decimals: SCALE });
94
100
  for (const [net, asa] of Object.entries(ALGORAND_USDC)) put(`${net}:${asa}`, { budget: name, decimals: 6 });
101
+ for (const [net, mint] of Object.entries(SOLANA_USDC)) put(`${net}:${mint}`, { budget: name, decimals: 6 });
95
102
  } else if (symbol === "XRP") {
96
103
  for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:${NATIVE}`, { budget: name, decimals: 6 });
104
+ } else if (symbol === "SOL") {
105
+ for (const net of Object.keys(SOLANA_USDC)) put(`${net}:${NATIVE}`, { budget: name, decimals: 9 });
97
106
  } else if (["ETH", "BNB", "POL"].includes(symbol)) {
98
107
  for (const [chain, s] of Object.entries(NATIVE_SYMBOL)) if (s === symbol) put(`${chain}:${NATIVE}`, { budget: name, decimals: 18 });
99
108
  } else {
@@ -118,6 +127,7 @@ export function spendFor(request, verdict) {
118
127
  const out = { items: [], counterparties: [], unknown: false };
119
128
  if (request.type === "xrpl") return xrplSpend(request, out);
120
129
  if (request.type === "algorand") return algorandSpend(request, out);
130
+ if (request.type === "solana") return request.simulated ? solanaSimulatedSpend(request, verdict, out) : solanaSpend(request, out);
121
131
  const chainId = request.chainId;
122
132
  if (request.type === "transaction") {
123
133
  const to = lower(request.to ?? null);
@@ -191,6 +201,39 @@ function algorandSpend(request, out) {
191
201
  return out;
192
202
  }
193
203
 
204
+ // A Solana USDC transfer (read from the transaction by solanaSigner): the mint, amount and receiving token account.
205
+ function solanaSpend(request, out) {
206
+ const t = request.transfer ?? {};
207
+ out.counterparties.push(typeof t.destination === "string" ? t.destination : null);
208
+ if (typeof t.mint !== "string" || !/^\d+$/.test(String(t.amount ?? ""))) { out.unknown = true; return out; }
209
+ out.items.push({ chainId: request.network, token: t.mint, amount: BigInt(t.amount), to: t.destination });
210
+ return out;
211
+ }
212
+
213
+ // Any Solana transaction: what leaves the wallet in presign-guard's signed simulation (base units).
214
+ function solanaSimulatedSpend(request, verdict, out) {
215
+ const sim = verdict?.simulation;
216
+ out.counterparties.push(null); // no single receiver to hold against an allow list
217
+ if (!sim || !sim.ok || sim.partial || !Array.isArray(sim.changes)) { out.unknown = true; return out; }
218
+ const chainId = request.network;
219
+ const fee = typeof sim.fee === "number" ? BigInt(Math.round(sim.fee * 1e9)) : 0n;
220
+ for (const c of sim.changes) {
221
+ if (c.type === "sol" && c.account === request.from) {
222
+ if (!/^-?\d+$/.test(String(c.lamports ?? ""))) { out.unknown = true; continue; }
223
+ const leaving = -BigInt(c.lamports) - fee;
224
+ if (leaving > 0n) out.items.push({ chainId, token: NATIVE, amount: leaving, to: null });
225
+ } else if (c.type === "token") {
226
+ if (!/^-?\d+$/.test(String(c.raw ?? ""))) { out.unknown = true; continue; }
227
+ if (BigInt(c.raw) < 0n) out.items.push({ chainId, token: c.mint, amount: -BigInt(c.raw), to: null });
228
+ } else if (c.type === "delegate") {
229
+ out.items.push({ chainId, token: c.mint, amount: null, to: c.delegate }); // someone else may spend it later
230
+ } else if (c.type === "owner") {
231
+ out.unknown = true;
232
+ }
233
+ }
234
+ return out;
235
+ }
236
+
194
237
  const fmt = (x) => (x === null ? "unlimited" : formatUnits(x, SCALE));
195
238
  const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "a new contract");
196
239
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.15.0",
3
+ "version": "0.17.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
+ }