presign-guard-wallet 0.14.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 +19 -2
- package/index.d.ts +10 -1
- package/index.js +51 -4
- package/limits.js +13 -0
- package/package.json +3 -1
- package/solana.js +76 -0
package/README.md
CHANGED
|
@@ -52,7 +52,7 @@ try {
|
|
|
52
52
|
}
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
`wallet` is the same client:
|
|
55
|
+
`wallet` is the same client. `signMessage` is checked too, as a plain message: a sign-in message (Sign-In with Ethereum) for another site than `origin` is red, unreadable bytes are orange; it counts toward no limit (`checkMessages: false` turns this off). Every other method (`getAddresses`, `extend`, …) works as before, unchecked.
|
|
56
56
|
|
|
57
57
|
## Options
|
|
58
58
|
|
|
@@ -66,6 +66,7 @@ try {
|
|
|
66
66
|
| `origin` | | The site asking for the signature: its domain age and phishing lists are checked too |
|
|
67
67
|
| `onVerdict` | | `(verdict, { method, request, paidWith, creditsLeft }) => void`, e.g. for logging; `paidWith` is `"credits"` or `"x402"` |
|
|
68
68
|
| `verifyReceipts` | `"require"` | Check presign-guard's signed receipt on every verdict; `"off"` skips it |
|
|
69
|
+
| `checkMessages` | `true` | Check `signMessage` too ($0.01 per message, like any check); `false` signs messages unchecked |
|
|
69
70
|
| `signers` | presign-guard's published signer | Accepted signer addresses |
|
|
70
71
|
| `authority` | the Fizzl payout wallet | Wallet whose certificates also make a signer trusted (key rotation); `null` accepts only `signers` |
|
|
71
72
|
| `limits` | | Spending limits per token, see [Spending limits](#spending-limits) |
|
|
@@ -265,6 +266,22 @@ client.register("algorand:*", new ExactAvmScheme(algo)); // x402 payments in USD
|
|
|
265
266
|
|
|
266
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.
|
|
267
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
|
+
|
|
268
285
|
## MPP sessions on Tempo
|
|
269
286
|
|
|
270
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.
|
|
@@ -292,7 +309,7 @@ presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash
|
|
|
292
309
|
|
|
293
310
|
## Costs and coverage
|
|
294
311
|
|
|
295
|
-
- $0.01 per checked signature, paid with your `pay` fetch, or $0.008 / $0.007 with [prepaid credits](#prepaid-credits). Calls presign-guard does not cover (
|
|
312
|
+
- $0.01 per checked signature, paid with your `pay` fetch, or $0.008 / $0.007 with [prepaid credits](#prepaid-credits). Calls presign-guard does not cover (contract deployments) are not checked and cost nothing; `signMessage` is checked unless `checkMessages: false`.
|
|
296
313
|
- presign-guard reads public data (GoPlus, RugCheck, DexScreener, OFAC via PG1, phishing lists). A green verdict means no known problem was found, not a guarantee.
|
|
297
314
|
- The requests carry `user-agent: presign-guard-wallet/<version>` so the service can count how often the package is used.
|
|
298
315
|
|
package/index.d.ts
CHANGED
|
@@ -26,7 +26,8 @@ export interface PresignVerdict {
|
|
|
26
26
|
/** What is sent to presign-guard's POST /v1/check. */
|
|
27
27
|
export type CheckRequest =
|
|
28
28
|
| { type: "transaction"; chainId: number; to: string; data: string; value: string; origin?: string; from?: string }
|
|
29
|
-
| { type: "signature"; chainId: number; typedData: unknown; origin?: string }
|
|
29
|
+
| { type: "signature"; chainId: number; typedData: unknown; origin?: string }
|
|
30
|
+
| { type: "message"; method: "personal_sign"; message: string; chainId?: number; origin?: string; from?: string };
|
|
30
31
|
|
|
31
32
|
export declare class PresignBlockedError extends Error {
|
|
32
33
|
code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain" | "over_limit" | "paused" | "limit_unavailable";
|
|
@@ -153,6 +154,12 @@ export interface GuardControls {
|
|
|
153
154
|
* payment group (no close-out, rekey or clawback), counted toward the USDC limits; anything else is refused.
|
|
154
155
|
*/
|
|
155
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">;
|
|
156
163
|
/** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
|
|
157
164
|
wrap<W extends object>(wallet: W): W & GuardControls;
|
|
158
165
|
}
|
|
@@ -174,6 +181,8 @@ export interface GuardOptions {
|
|
|
174
181
|
presignUrl?: string;
|
|
175
182
|
/** Check presign-guard's signed receipt on every verdict. Default "require". */
|
|
176
183
|
verifyReceipts?: "require" | "off";
|
|
184
|
+
/** Check signMessage with presign-guard too (default true): eth_sign-style hashes are orange, a sign-in message for another site than origin is red. */
|
|
185
|
+
checkMessages?: boolean;
|
|
177
186
|
/** Accepted signer addresses. Default: the published signer (PRESIGN_SIGNERS). */
|
|
178
187
|
signers?: string[];
|
|
179
188
|
/** Wallet whose certificates also make a signer trusted (key rotation). Default: the Fizzl payout wallet; null accepts only `signers`. */
|
package/index.js
CHANGED
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
// toward the limits (XRP toward an XRP limit, RLUSD toward USDC). Use it with
|
|
49
49
|
// @x402/xrpl's ExactXrplScheme to pay x402 services in RLUSD.
|
|
50
50
|
|
|
51
|
-
import { decodeFunctionData, encodeFunctionData, parseAbi } from "viem";
|
|
51
|
+
import { bytesToHex, decodeFunctionData, encodeFunctionData, parseAbi } from "viem";
|
|
52
52
|
import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
|
|
53
53
|
import { createLimiter, memoryStore } from "./limits.js";
|
|
54
54
|
import { createRemoteLimiter } from "./remote.js";
|
|
@@ -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.
|
|
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
|
|
|
@@ -141,6 +142,13 @@ export function checkRequestFor(method, args, { chainId, origin, x402, from } =
|
|
|
141
142
|
const data = encodeFunctionData({ abi: args.abi, functionName: args.functionName, args: args.args });
|
|
142
143
|
return { type: "transaction", ...base, ...sender, to: args.address, data, value: String(args.value ?? 0n) };
|
|
143
144
|
}
|
|
145
|
+
if (method === "signMessage") {
|
|
146
|
+
// viem: a string is signed as text, { raw } as bytes (hex or a byte array).
|
|
147
|
+
const m = args?.message;
|
|
148
|
+
const message = typeof m === "string" ? m : typeof m?.raw === "string" ? m.raw : m?.raw instanceof Uint8Array ? bytesToHex(m.raw) : null;
|
|
149
|
+
if (message === null) return null;
|
|
150
|
+
return { type: "message", method: "personal_sign", message, ...(chainId ? { chainId } : {}), ...(origin ? { origin } : {}), ...sender };
|
|
151
|
+
}
|
|
144
152
|
if (method === "signTypedData") {
|
|
145
153
|
const { domain, types, primaryType, message } = args;
|
|
146
154
|
// A payment made by mandatePayer() (mandate.js) is checked against its mandate too.
|
|
@@ -213,6 +221,7 @@ function cleanPurchase(info) {
|
|
|
213
221
|
* @param {(entry: object) => void} [options.onSpend] after each signed spend
|
|
214
222
|
* @param {{url: string, key: string}} [options.server] a wallet server (fizzl wallet-server) keeps the limits, budget and approvals for all your agents
|
|
215
223
|
* @param {object} [options.store] where spending is kept (default in memory; fileStore from presign-guard-wallet/file-store)
|
|
224
|
+
* @param {boolean} [options.checkMessages] check signMessage too (default true): a sign-in message for another site is red
|
|
216
225
|
*/
|
|
217
226
|
export function guardWallet(wallet, {
|
|
218
227
|
pay,
|
|
@@ -225,6 +234,7 @@ export function guardWallet(wallet, {
|
|
|
225
234
|
signers = PRESIGN_SIGNERS,
|
|
226
235
|
authority = AUTHORITY,
|
|
227
236
|
creditKey,
|
|
237
|
+
checkMessages = true,
|
|
228
238
|
fetch: plainFetch = globalThis.fetch,
|
|
229
239
|
limits,
|
|
230
240
|
onOverLimit,
|
|
@@ -238,6 +248,7 @@ export function guardWallet(wallet, {
|
|
|
238
248
|
if (!["stop", "allow"].includes(onOrange) && typeof onOrange !== "function") throw new TypeError('onOrange must be "stop", "allow" or a function');
|
|
239
249
|
if (!["stop", "allow"].includes(onError)) throw new TypeError('onError must be "stop" or "allow"');
|
|
240
250
|
if (!["require", "off"].includes(verifyReceipts)) throw new TypeError('verifyReceipts must be "require" or "off"');
|
|
251
|
+
if (typeof checkMessages !== "boolean") throw new TypeError("checkMessages must be true or false");
|
|
241
252
|
|
|
242
253
|
if (server !== undefined && (limits !== undefined || onOverLimit || store)) throw new TypeError("with server, the limits and approvals live on the wallet server: leave out limits, onOverLimit and store");
|
|
243
254
|
if (server === undefined && limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
|
|
@@ -281,7 +292,7 @@ export function guardWallet(wallet, {
|
|
|
281
292
|
|
|
282
293
|
// The verdict for a request, or null when the check could not be done and onError is "allow".
|
|
283
294
|
async function verdictFor(method, request, chainId) {
|
|
284
|
-
if (!SUPPORTED_CHAINS.includes(chainId) && !XRPL_NETWORKS.includes(chainId)) {
|
|
295
|
+
if (request.type !== "message" && request.type !== "solana" && !SUPPORTED_CHAINS.includes(chainId) && !XRPL_NETWORKS.includes(chainId)) {
|
|
285
296
|
if (onError === "allow") return null;
|
|
286
297
|
throw new PresignBlockedError(`chain ${chainId} is not covered by presign-guard; nothing was signed`, { code: "unsupported_chain", request });
|
|
287
298
|
}
|
|
@@ -348,6 +359,12 @@ export function guardWallet(wallet, {
|
|
|
348
359
|
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
349
360
|
const chainId = args?.chain?.id ?? target.chain?.id;
|
|
350
361
|
const run = () => original(args, ...rest);
|
|
362
|
+
// A plain message moves nothing by itself, so it is checked but not counted toward the limits.
|
|
363
|
+
if (method === "signMessage") {
|
|
364
|
+
const request = checkRequestFor(method, args, { chainId, origin, from: senderOf(args, target) });
|
|
365
|
+
if (request) await verdictFor(method, request, chainId);
|
|
366
|
+
return run();
|
|
367
|
+
}
|
|
351
368
|
if (TEMPO_TOKENS[chainId]) {
|
|
352
369
|
const request = tempoRequest(method, args, chainId);
|
|
353
370
|
return limiter ? withinLimits(method, request, null, run) : run();
|
|
@@ -401,6 +418,25 @@ export function guardWallet(wallet, {
|
|
|
401
418
|
return limiter ? withinLimits("signAlgorandTransfer", request, null, run) : run();
|
|
402
419
|
}
|
|
403
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
|
+
|
|
404
440
|
const extras = {
|
|
405
441
|
/**
|
|
406
442
|
* The same guard on an XRP Ledger signer ({ classicAddress, sign(tx) }, e.g. createXrplWalletSigner
|
|
@@ -453,6 +489,17 @@ export function guardWallet(wallet, {
|
|
|
453
489
|
* The facilitator's fee-payer transaction in the same group is not this signer's and is left unsigned.
|
|
454
490
|
* network: the x402 id of Algorand mainnet (default) or testnet.
|
|
455
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
|
+
},
|
|
456
503
|
algorandSigner: (signer, { network = "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" } = {}) => {
|
|
457
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)");
|
|
458
505
|
if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
|
|
@@ -506,7 +553,7 @@ export function guardWallet(wallet, {
|
|
|
506
553
|
get(target, prop, receiver) {
|
|
507
554
|
if (Object.hasOwn(extras, prop) && !(prop in target)) return extras[prop];
|
|
508
555
|
const value = Reflect.get(target, prop, receiver);
|
|
509
|
-
if (typeof prop !== "string" || !GUARDED.has(prop) || typeof value !== "function") return value;
|
|
556
|
+
if (typeof prop !== "string" || !(GUARDED.has(prop) || (checkMessages && prop === "signMessage")) || typeof value !== "function") return value;
|
|
510
557
|
return (args, ...rest) => guarded(target, prop, value.bind(target), args, rest);
|
|
511
558
|
},
|
|
512
559
|
});
|
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.
|
|
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
|
+
}
|