presign-guard-wallet 0.11.0 → 0.13.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 +30 -0
- package/algorand.js +85 -0
- package/index.d.ts +13 -1
- package/index.js +70 -4
- package/limits.js +16 -0
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -202,6 +202,21 @@ const wallet = guardWallet(walletClient, {
|
|
|
202
202
|
|
|
203
203
|
If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
|
|
204
204
|
|
|
205
|
+
## Checking x402 payments against what the seller asked
|
|
206
|
+
|
|
207
|
+
Wrap the x402 payment scheme with `x402Checked` and the payment requirements it pays (the `accepts` entry it chose) go along with the presign-guard check of its EIP-3009 signature. presign-guard then makes a signature that pays more than asked, someone else, another token or another chain red (`X402_AMOUNT_ABOVE_REQUIRED`, `X402_RECIPIENT_MISMATCH`, `X402_ASSET_MISMATCH`, `X402_NETWORK_MISMATCH`), and one that stays valid far longer than the seller's timeout orange (`X402_VALIDITY_TOO_LONG`), before anything is signed. It catches a hostile server or a broken client library.
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
import { guardWallet, x402Checked } from "presign-guard-wallet";
|
|
211
|
+
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
212
|
+
|
|
213
|
+
const wallet = guardWallet(walletClient, { pay });
|
|
214
|
+
const signer = { address: account.address, signTypedData: (t) => wallet.signTypedData({ account, ...t }) };
|
|
215
|
+
client.register("eip155:8453", x402Checked(new ExactEvmScheme(signer)));
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
It combines with a mandate: `x402Checked(mandatePayer(scheme, mandate))`.
|
|
219
|
+
|
|
205
220
|
## Paying under a mandate
|
|
206
221
|
|
|
207
222
|
A principal can give an agent a signed spending mandate ([x402 `authority` extension draft](https://github.com/x402-foundation/x402/pull/3220), `x402-mandate/1`): "spend up to CAP, to recipients in R, until T". Wrap the payment scheme with `mandatePayer` and each x402 payment is made under it: the EIP-3009 nonce becomes the binding of (mandate, paymentId), so the settled payment proves which grant it used, and the guarded wallet sends the mandate along with the check. presign-guard then makes a payment outside the mandate red (over `perPayment` or `cap`, another recipient, payer or token, expired, bad signature), before anything is signed.
|
|
@@ -233,6 +248,21 @@ client.register("xrpl:*", new ExactXrplScheme(xrpl)); // x402 payments in RLUSD,
|
|
|
233
248
|
|
|
234
249
|
`network` is `"xrpl:0"` (mainnet) or `"xrpl:1"` (testnet). The check itself is still paid on Base (or with credits).
|
|
235
250
|
|
|
251
|
+
## Algorand (USDC)
|
|
252
|
+
|
|
253
|
+
`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`.
|
|
254
|
+
|
|
255
|
+
```js
|
|
256
|
+
import { toClientAvmSigner } from "@x402/avm";
|
|
257
|
+
import { ExactAvmScheme } from "@x402/avm/exact/client";
|
|
258
|
+
|
|
259
|
+
const guarded = guardWallet(walletClient, { pay, limits: { tokens: { USDC: { perDay: "5" } } } });
|
|
260
|
+
const algo = guarded.algorandSigner(toClientAvmSigner(process.env.AVM_PRIVATE_KEY), { network: "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" });
|
|
261
|
+
client.register("algorand:*", new ExactAvmScheme(algo)); // x402 payments in USDC on Algorand, within limits
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
`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.
|
|
265
|
+
|
|
236
266
|
## MPP sessions on Tempo
|
|
237
267
|
|
|
238
268
|
`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
|
}
|
|
@@ -185,7 +192,12 @@ export interface GuardOptions {
|
|
|
185
192
|
|
|
186
193
|
/** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
|
|
187
194
|
export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W & GuardControls;
|
|
188
|
-
export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string }): CheckRequest | null;
|
|
195
|
+
export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string; x402?: Record<string, unknown> }): CheckRequest | null;
|
|
196
|
+
/**
|
|
197
|
+
* Wrap an x402 client scheme so the payment requirements it pays go along with the presign-guard check of its
|
|
198
|
+
* EIP-3009 signature (red when the signature pays more, someone else, another token or chain than asked).
|
|
199
|
+
*/
|
|
200
|
+
export function x402Checked<S extends { scheme?: string; createPaymentPayload: (...args: any[]) => Promise<unknown> }>(scheme: S): S;
|
|
189
201
|
|
|
190
202
|
/** A principal's signed spending mandate (x402 `authority` extension draft, x402-mandate/1). */
|
|
191
203
|
export interface MandateEnvelope {
|
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.
|
|
81
|
+
export const VERSION = "0.13.0";
|
|
76
82
|
export const CREDIT_HEADER = "x-credit-key";
|
|
77
83
|
const ROUTE = "POST /v1/check";
|
|
78
84
|
|
|
@@ -90,8 +96,33 @@ export class PresignBlockedError extends Error {
|
|
|
90
96
|
// JSON with bigints as decimal strings (viem uses bigint for values and amounts).
|
|
91
97
|
const toJson = (value) => JSON.stringify(value, (_k, v) => (typeof v === "bigint" ? v.toString() : v));
|
|
92
98
|
|
|
99
|
+
// The x402 payment requirements being paid right now (x402Checked), so presign-guard can check that the
|
|
100
|
+
// EIP-3009 signature pays exactly what the seller asked: amount, payTo, asset, network, validity.
|
|
101
|
+
const x402Paying = new AsyncLocalStorage();
|
|
102
|
+
function cleanRequirements(r) {
|
|
103
|
+
if (!r || typeof r !== "object") return null;
|
|
104
|
+
const out = {};
|
|
105
|
+
for (const k of ["scheme", "network", "amount", "maxAmountRequired", "asset", "payTo", "maxTimeoutSeconds"]) if (r[k] !== undefined && r[k] !== null) out[k] = typeof r[k] === "bigint" ? r[k].toString() : r[k];
|
|
106
|
+
if (r.extra && typeof r.extra === "object") out.extra = { ...(r.extra.name !== undefined && { name: r.extra.name }), ...(r.extra.version !== undefined && { version: r.extra.version }) };
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Wrap an x402 client scheme (e.g. new ExactEvmScheme(guardedSigner)) so the payment requirements it pays go
|
|
112
|
+
* along with the presign-guard check of the EIP-3009 signature: a signature that pays more, someone else, another
|
|
113
|
+
* token or chain than the seller asked is red (X402_AMOUNT_ABOVE_REQUIRED, X402_RECIPIENT_MISMATCH, …).
|
|
114
|
+
*/
|
|
115
|
+
export function x402Checked(scheme) {
|
|
116
|
+
return Object.assign(Object.create(scheme), {
|
|
117
|
+
scheme: scheme.scheme ?? "exact",
|
|
118
|
+
createPaymentPayload(x402Version, requirements, ...rest) {
|
|
119
|
+
return x402Paying.run(cleanRequirements(requirements), () => scheme.createPaymentPayload(x402Version, requirements, ...rest));
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
93
124
|
// What presign-guard should check for a wallet call, or null for calls it does not cover.
|
|
94
|
-
export function checkRequestFor(method, args, { chainId, origin } = {}) {
|
|
125
|
+
export function checkRequestFor(method, args, { chainId, origin, x402 } = {}) {
|
|
95
126
|
const base = { chainId, ...(origin ? { origin } : {}) };
|
|
96
127
|
if (method === "sendTransaction") {
|
|
97
128
|
if (!args?.to) return null; // contract deployment: nothing to screen
|
|
@@ -105,7 +136,8 @@ export function checkRequestFor(method, args, { chainId, origin } = {}) {
|
|
|
105
136
|
const { domain, types, primaryType, message } = args;
|
|
106
137
|
// A payment made by mandatePayer() (mandate.js) is checked against its mandate too.
|
|
107
138
|
const under = primaryType === "TransferWithAuthorization" ? mandateFor(message?.nonce) : null;
|
|
108
|
-
|
|
139
|
+
const paying = primaryType === "TransferWithAuthorization" && x402 ? { x402: { accepted: x402 } } : {};
|
|
140
|
+
return { type: "signature", ...base, typedData: { domain, types, primaryType, message }, ...(under && { mandate: { ...under.envelope, paymentId: under.paymentId } }), ...paying };
|
|
109
141
|
}
|
|
110
142
|
return null;
|
|
111
143
|
}
|
|
@@ -311,7 +343,7 @@ export function guardWallet(wallet, {
|
|
|
311
343
|
const request = tempoRequest(method, args, chainId);
|
|
312
344
|
return limiter ? withinLimits(method, request, null, run) : run();
|
|
313
345
|
}
|
|
314
|
-
const request = checkRequestFor(method, args, { chainId, origin });
|
|
346
|
+
const request = checkRequestFor(method, args, { chainId, origin, x402: x402Paying.getStore() });
|
|
315
347
|
if (!request) {
|
|
316
348
|
// A contract deployment is not checked, but the value it sends still counts.
|
|
317
349
|
if (limiter && method === "sendTransaction") {
|
|
@@ -338,6 +370,28 @@ export function guardWallet(wallet, {
|
|
|
338
370
|
return limiter ? withinLimits("signXrplPayment", request, verdict, run) : run();
|
|
339
371
|
}
|
|
340
372
|
|
|
373
|
+
// Algorand: sign only a USDC transfer from this address, within the limits (Algorand is not covered by presign-guard).
|
|
374
|
+
async function algorandSign(signer, network, txns, indexesToSign) {
|
|
375
|
+
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
376
|
+
const mine = (indexesToSign ?? txns.map((_, i) => i)).filter((i) => Number.isInteger(i) && i >= 0 && i < txns.length);
|
|
377
|
+
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" });
|
|
378
|
+
let t;
|
|
379
|
+
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" }); }
|
|
380
|
+
const usdc = ALGORAND_USDC[network];
|
|
381
|
+
const why = t.type !== "axfer" ? `it is a "${t.type}" transaction, not an asset transfer`
|
|
382
|
+
: t.sender !== signer.address ? "it is not sent from this account"
|
|
383
|
+
: t.assetId !== usdc ? `asset ${t.assetId} is not USDC (${usdc})`
|
|
384
|
+
: t.closeTo ? "it closes the account's USDC out"
|
|
385
|
+
: t.rekeyTo ? "it rekeys the account"
|
|
386
|
+
: t.clawbackFrom ? "it is a clawback"
|
|
387
|
+
: !t.receiver ? "it has no receiver"
|
|
388
|
+
: null;
|
|
389
|
+
if (why) throw new PresignBlockedError(`on Algorand this wallet only sends USDC: ${why}; nothing was signed`, { code: "unsupported_chain" });
|
|
390
|
+
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 } : {}) };
|
|
391
|
+
const run = () => signer.signTransactions(txns, mine);
|
|
392
|
+
return limiter ? withinLimits("signAlgorandTransfer", request, null, run) : run();
|
|
393
|
+
}
|
|
394
|
+
|
|
341
395
|
const extras = {
|
|
342
396
|
/**
|
|
343
397
|
* The same guard on an XRP Ledger signer ({ classicAddress, sign(tx) }, e.g. createXrplWalletSigner
|
|
@@ -383,6 +437,18 @@ export function guardWallet(wallet, {
|
|
|
383
437
|
},
|
|
384
438
|
};
|
|
385
439
|
},
|
|
440
|
+
/**
|
|
441
|
+
* The same guard on an x402 AVM client signer ({ address, signTransactions(txns, indexesToSign) }, e.g.
|
|
442
|
+
* toClientAvmSigner from @x402/avm): of the transactions it is asked to sign it signs only an asset transfer
|
|
443
|
+
* of USDC on that network from this address (no close-out, rekey or clawback), counted toward the USDC limit.
|
|
444
|
+
* The facilitator's fee-payer transaction in the same group is not this signer's and is left unsigned.
|
|
445
|
+
* network: the x402 id of Algorand mainnet (default) or testnet.
|
|
446
|
+
*/
|
|
447
|
+
algorandSigner: (signer, { network = "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" } = {}) => {
|
|
448
|
+
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)");
|
|
449
|
+
if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
|
|
450
|
+
return { address: signer.address, signTransactions: (txns, indexesToSign) => algorandSign(signer, network, txns, indexesToSign) };
|
|
451
|
+
},
|
|
386
452
|
/** Stop every checked method until resume(). */
|
|
387
453
|
pause: () => { paused = true; },
|
|
388
454
|
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.
|
|
3
|
+
"version": "0.13.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
|
},
|