presign-guard-wallet 0.10.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/algorand.js +85 -0
- package/index.d.ts +17 -1
- package/index.js +116 -2
- package/limits.js +16 -0
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -233,6 +233,38 @@ client.register("xrpl:*", new ExactXrplScheme(xrpl)); // x402 payments in RLUSD,
|
|
|
233
233
|
|
|
234
234
|
`network` is `"xrpl:0"` (mainnet) or `"xrpl:1"` (testnet). The check itself is still paid on Base (or with credits).
|
|
235
235
|
|
|
236
|
+
## Algorand (USDC)
|
|
237
|
+
|
|
238
|
+
`algorandSigner` guards an Algorand signer for x402's AVM client (`@x402/avm`). In an x402 payment group the agent signs one transaction: its USDC transfer to the seller (the seller's facilitator signs and pays the fee transaction). The guarded signer signs only that: an asset transfer of USDC (ASA 31566704 on mainnet, 10458941 on testnet) from the agent's own address, with no close-out, rekey or clawback. It counts toward your `USDC` limit, and pause stops it. Anything else is refused with `unsupported_chain`.
|
|
239
|
+
|
|
240
|
+
```js
|
|
241
|
+
import { toClientAvmSigner } from "@x402/avm";
|
|
242
|
+
import { ExactAvmScheme } from "@x402/avm/exact/client";
|
|
243
|
+
|
|
244
|
+
const guarded = guardWallet(walletClient, { pay, limits: { tokens: { USDC: { perDay: "5" } } } });
|
|
245
|
+
const algo = guarded.algorandSigner(toClientAvmSigner(process.env.AVM_PRIVATE_KEY), { network: "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" });
|
|
246
|
+
client.register("algorand:*", new ExactAvmScheme(algo)); // x402 payments in USDC on Algorand, within limits
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
`network` is the mainnet id above (default) or `"algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="` (testnet). The account must be opted in to USDC. Algorand transfers aren't sent to presign-guard (it checks EVM and XRPL); the local rules above are the check.
|
|
250
|
+
|
|
251
|
+
## MPP sessions on Tempo
|
|
252
|
+
|
|
253
|
+
`tempoSessionAccount(account)` gives a guarded viem account to pay MPP **sessions** (TIP-1034) with mppx's session client: the agent opens a payment channel once and pays each call with a signed voucher, no transaction per call.
|
|
254
|
+
|
|
255
|
+
```js
|
|
256
|
+
import { sessionManager } from "mppx/client";
|
|
257
|
+
const session = sessionManager({
|
|
258
|
+
account: guarded.tempoSessionAccount(privateKeyToAccount(process.env.AGENT_KEY)), // { chainId: 42431 } for the testnet
|
|
259
|
+
credentialContext: { depositRaw: "1000000" }, // each deposit: 1 USDC.e
|
|
260
|
+
topUpAmount: "1",
|
|
261
|
+
});
|
|
262
|
+
const res = await session.fetch("https://presign-guard.fizzl.eu/v1/check", { method: "POST", body });
|
|
263
|
+
await session.close(); // the service settles what was used, the rest comes back
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
The account signs only a transaction with one call to Tempo's channel escrow that opens or tops up a channel in USDC.e for this account (nothing attached, the fee in USDC.e); that deposit counts toward your `USDC` limit, booked to the payee, when it is signed. Besides that it signs the channel's vouchers and close authorizations (EIP-712, the escrow's domain), which can only move money already deposited. Raw hashes, messages and anything else are refused, and `pause()` covers it. Unspent deposit comes back when the channel closes, but stays counted as spent in the current window.
|
|
267
|
+
|
|
236
268
|
## Signed verdicts
|
|
237
269
|
|
|
238
270
|
presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash of your request inside the signed body; see [Signed verdicts](https://github.com/Fizzl13/presign-guard#signed-verdicts)). The wallet checks that signature before it acts:
|
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
|
@@ -1,10 +1,16 @@
|
|
|
1
|
-
import type { WalletClient } from "viem";
|
|
1
|
+
import type { LocalAccount, WalletClient } from "viem";
|
|
2
2
|
|
|
3
3
|
export declare const PRESIGN_URL: string;
|
|
4
4
|
export declare const PRESIGN_SIGNERS: string[];
|
|
5
5
|
export declare const SUPPORTED_CHAINS: number[];
|
|
6
6
|
/** Tempo chain id -> the stablecoins (lowercase) the wallet may transfer there, checked locally instead of by presign-guard. */
|
|
7
7
|
export declare const TEMPO_TOKENS: Record<number, string[]>;
|
|
8
|
+
/** Tempo's TIP-1034 channel escrow (MPP sessions). */
|
|
9
|
+
export declare const TEMPO_ESCROW: string;
|
|
10
|
+
/** What an MPP session transaction deposits ({ token, payee, deposit }), or throws PresignBlockedError when the wallet would not sign it. */
|
|
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>;
|
|
8
14
|
export declare const VERSION: string;
|
|
9
15
|
export declare const CREDIT_HEADER: string;
|
|
10
16
|
|
|
@@ -137,6 +143,16 @@ export interface GuardControls {
|
|
|
137
143
|
* wallet server's receipts, approval messages). Call report() with what happened afterwards.
|
|
138
144
|
*/
|
|
139
145
|
withPurchase<T>(info: Purchase, fn: (report: (outcome: PurchaseOutcome) => void) => Promise<T> | T, opts?: { onChecked?: (check: AnswerCheck, out: T) => Promise<T> | T }): Promise<T>;
|
|
146
|
+
/**
|
|
147
|
+
* A guarded viem account for MPP sessions on Tempo (mppx's session client): signs only a channel open/top-up in
|
|
148
|
+
* Tempo's escrow, in USDC.e, for this account (the deposit counts toward the USDC limits), plus its vouchers.
|
|
149
|
+
*/
|
|
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;
|
|
140
156
|
/** The same guard (checks, limits, pause, purchases) on another WalletClient, e.g. one for Tempo: both spend from one budget. */
|
|
141
157
|
wrap<W extends object>(wallet: W): W & GuardControls;
|
|
142
158
|
}
|
package/index.js
CHANGED
|
@@ -32,6 +32,15 @@
|
|
|
32
32
|
// which counts toward the USDC limits like any other USDC transfer. Anything
|
|
33
33
|
// else on Tempo is refused (code "unsupported_chain").
|
|
34
34
|
//
|
|
35
|
+
// MPP sessions on Tempo: tempoSessionAccount(account) gives a guarded viem account for mppx's
|
|
36
|
+
// session client. It signs one thing on chain, opening or topping up a payment channel in
|
|
37
|
+
// Tempo's escrow in USDC.e (the deposit counts toward the USDC limits), plus that channel's
|
|
38
|
+
// vouchers and close authorizations; raw hashes, messages and anything else are refused.
|
|
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
|
+
//
|
|
35
44
|
// XRP Ledger: xrplSigner(signer) wraps an XRPL signer ({ classicAddress, sign(tx) },
|
|
36
45
|
// e.g. createXrplWalletSigner from @x402/xrpl) the same way. It signs only
|
|
37
46
|
// Payment transactions, each checked by presign-guard first (type "xrpl": fake
|
|
@@ -39,13 +48,15 @@
|
|
|
39
48
|
// toward the limits (XRP toward an XRP limit, RLUSD toward USDC). Use it with
|
|
40
49
|
// @x402/xrpl's ExactXrplScheme to pay x402 services in RLUSD.
|
|
41
50
|
|
|
42
|
-
import { encodeFunctionData } from "viem";
|
|
51
|
+
import { decodeFunctionData, encodeFunctionData, parseAbi } from "viem";
|
|
43
52
|
import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
|
|
44
53
|
import { createLimiter, memoryStore } from "./limits.js";
|
|
45
54
|
import { createRemoteLimiter } from "./remote.js";
|
|
46
55
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
47
56
|
|
|
48
57
|
import { mandateFor } from "./mandate.js";
|
|
58
|
+
import { ALGORAND_USDC, readAlgorandTxn } from "./algorand.js";
|
|
59
|
+
export { ALGORAND_USDC } from "./algorand.js";
|
|
49
60
|
export { mandatePayer, mandateDigest, mandateBinding } from "./mandate.js";
|
|
50
61
|
export { memoryStore };
|
|
51
62
|
|
|
@@ -58,8 +69,16 @@ export const TEMPO_TOKENS = {
|
|
|
58
69
|
42431: ["0x20c0000000000000000000000000000000000000"],
|
|
59
70
|
};
|
|
60
71
|
const TEMPO_TRANSFERS = new Set(["transfer", "transferWithMemo"]);
|
|
72
|
+
// MPP sessions (TIP-1034): deposits into Tempo's channel escrow, and the vouchers that spend them.
|
|
73
|
+
export const TEMPO_ESCROW = "0x4d50500000000000000000000000000000000000";
|
|
74
|
+
const ESCROW_ABI = parseAbi([
|
|
75
|
+
"function open(address payee, address operator, address token, uint96 deposit, bytes32 salt, address authorizedSigner)",
|
|
76
|
+
"function topUp((address payer, address payee, address operator, address token, bytes32 salt, address authorizedSigner, bytes32 expiringNonceHash) descriptor, uint96 additionalDeposit)",
|
|
77
|
+
]);
|
|
78
|
+
const TRANSFER_ABI = parseAbi(["function transfer(address to, uint256 amount)"]);
|
|
79
|
+
const VOUCHER_DOMAIN = "TIP20 Channel Reserve";
|
|
61
80
|
export const XRPL_NETWORKS = ["xrpl:0", "xrpl:1"];
|
|
62
|
-
export const VERSION = "0.
|
|
81
|
+
export const VERSION = "0.12.0";
|
|
63
82
|
export const CREDIT_HEADER = "x-credit-key";
|
|
64
83
|
const ROUTE = "POST /v1/check";
|
|
65
84
|
|
|
@@ -97,6 +116,33 @@ export function checkRequestFor(method, args, { chainId, origin } = {}) {
|
|
|
97
116
|
return null;
|
|
98
117
|
}
|
|
99
118
|
|
|
119
|
+
// The one transaction an MPP session account signs: a single call to Tempo's escrow, open or topUp, in the
|
|
120
|
+
// chain's stablecoin, for this account, nothing attached. Returns what it deposits, or throws.
|
|
121
|
+
export function sessionDeposit(tx, chainId, address) {
|
|
122
|
+
const no = (why) => { throw new PresignBlockedError(`MPP session account: ${why}; nothing was signed`, { code: "unsupported_chain" }); };
|
|
123
|
+
const tokens = TEMPO_TOKENS[chainId];
|
|
124
|
+
if (Number(tx?.chainId ?? chainId) !== chainId) no(`the transaction is for chain ${tx?.chainId}, not ${chainId}`);
|
|
125
|
+
if (tx?.feeToken !== undefined && !tokens.includes(String(tx.feeToken).toLowerCase())) no("the fee is not paid in the session stablecoin");
|
|
126
|
+
const calls = Array.isArray(tx?.calls) ? tx.calls : tx?.to ? [{ to: tx.to, data: tx.data, value: tx.value }] : [];
|
|
127
|
+
if (calls.length !== 1) no(`only one escrow call is signed (got ${calls.length})`);
|
|
128
|
+
const [call] = calls;
|
|
129
|
+
if (String(call.to ?? "").toLowerCase() !== TEMPO_ESCROW) no("the call is not to Tempo's channel escrow");
|
|
130
|
+
if (BigInt(call.value ?? 0n) > 0n) no("value is attached");
|
|
131
|
+
let decoded;
|
|
132
|
+
try { decoded = decodeFunctionData({ abi: ESCROW_ABI, data: call.data }); } catch { no("only opening or topping up a channel is signed"); }
|
|
133
|
+
const me = String(address).toLowerCase();
|
|
134
|
+
if (decoded.functionName === "open") {
|
|
135
|
+
const [payee, , token, deposit, , signer] = decoded.args;
|
|
136
|
+
if (!tokens.includes(token.toLowerCase())) no("the channel is not in the session stablecoin");
|
|
137
|
+
if (signer.toLowerCase() !== me) no("the channel's voucher signer is not this account");
|
|
138
|
+
return { token: token.toLowerCase(), payee, deposit };
|
|
139
|
+
}
|
|
140
|
+
const [descriptor, deposit] = decoded.args;
|
|
141
|
+
if (!tokens.includes(descriptor.token.toLowerCase())) no("the channel is not in the session stablecoin");
|
|
142
|
+
if (descriptor.payer.toLowerCase() !== me) no("the channel is not this account's");
|
|
143
|
+
return { token: descriptor.token.toLowerCase(), payee: descriptor.payee, deposit };
|
|
144
|
+
}
|
|
145
|
+
|
|
100
146
|
const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
|
|
101
147
|
|
|
102
148
|
// What the agent says it is buying, for the signatures made inside withPurchase().
|
|
@@ -298,6 +344,28 @@ export function guardWallet(wallet, {
|
|
|
298
344
|
return limiter ? withinLimits("signXrplPayment", request, verdict, run) : run();
|
|
299
345
|
}
|
|
300
346
|
|
|
347
|
+
// Algorand: sign only a USDC transfer from this address, within the limits (Algorand is not covered by presign-guard).
|
|
348
|
+
async function algorandSign(signer, network, txns, indexesToSign) {
|
|
349
|
+
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
350
|
+
const mine = (indexesToSign ?? txns.map((_, i) => i)).filter((i) => Number.isInteger(i) && i >= 0 && i < txns.length);
|
|
351
|
+
if (mine.length !== 1) throw new PresignBlockedError(`on Algorand this wallet signs one USDC transfer per payment (asked for ${mine.length}); nothing was signed`, { code: "unsupported_chain" });
|
|
352
|
+
let t;
|
|
353
|
+
try { t = readAlgorandTxn(txns[mine[0]]); } catch (err) { throw new PresignBlockedError(`could not read the Algorand transaction (${err.message}); nothing was signed`, { code: "unsupported_chain" }); }
|
|
354
|
+
const usdc = ALGORAND_USDC[network];
|
|
355
|
+
const why = t.type !== "axfer" ? `it is a "${t.type}" transaction, not an asset transfer`
|
|
356
|
+
: t.sender !== signer.address ? "it is not sent from this account"
|
|
357
|
+
: t.assetId !== usdc ? `asset ${t.assetId} is not USDC (${usdc})`
|
|
358
|
+
: t.closeTo ? "it closes the account's USDC out"
|
|
359
|
+
: t.rekeyTo ? "it rekeys the account"
|
|
360
|
+
: t.clawbackFrom ? "it is a clawback"
|
|
361
|
+
: !t.receiver ? "it has no receiver"
|
|
362
|
+
: null;
|
|
363
|
+
if (why) throw new PresignBlockedError(`on Algorand this wallet only sends USDC: ${why}; nothing was signed`, { code: "unsupported_chain" });
|
|
364
|
+
const request = { type: "algorand", network, txn: { type: t.type, sender: t.sender, receiver: t.receiver, amount: String(t.amount), assetId: String(t.assetId) }, ...(origin ? { origin } : {}) };
|
|
365
|
+
const run = () => signer.signTransactions(txns, mine);
|
|
366
|
+
return limiter ? withinLimits("signAlgorandTransfer", request, null, run) : run();
|
|
367
|
+
}
|
|
368
|
+
|
|
301
369
|
const extras = {
|
|
302
370
|
/**
|
|
303
371
|
* The same guard on an XRP Ledger signer ({ classicAddress, sign(tx) }, e.g. createXrplWalletSigner
|
|
@@ -309,6 +377,52 @@ export function guardWallet(wallet, {
|
|
|
309
377
|
if (!XRPL_NETWORKS.includes(network)) throw new TypeError(`xrplSigner: network must be one of ${XRPL_NETWORKS.join(", ")}`);
|
|
310
378
|
return { classicAddress: signer.classicAddress, sign: (tx) => xrplSign(signer, network, tx) };
|
|
311
379
|
},
|
|
380
|
+
/**
|
|
381
|
+
* A guarded viem account for MPP sessions on Tempo (e.g. mppx's sessionManager): it signs only
|
|
382
|
+
* a transaction that opens or tops up a payment channel in Tempo's escrow, in USDC.e, for this
|
|
383
|
+
* account (the deposit counts toward the USDC limits, booked to the payee, when it is signed),
|
|
384
|
+
* and the channel's vouchers and close authorizations (EIP-712, escrow domain; they only move
|
|
385
|
+
* money already deposited). Raw hashes, messages and anything else are refused.
|
|
386
|
+
*/
|
|
387
|
+
tempoSessionAccount: (account, { chainId = 4217 } = {}) => {
|
|
388
|
+
if (!TEMPO_TOKENS[chainId]) throw new TypeError(`tempoSessionAccount: chainId must be ${Object.keys(TEMPO_TOKENS).join(" or ")}`);
|
|
389
|
+
if (!account || typeof account.signTransaction !== "function" || typeof account.signTypedData !== "function") throw new TypeError("tempoSessionAccount(account): account must be a local viem account (privateKeyToAccount)");
|
|
390
|
+
const refuse = (what) => async () => { throw new PresignBlockedError(`MPP session account: ${what} is not signed; nothing was signed`, { code: "unsupported_chain" }); };
|
|
391
|
+
return {
|
|
392
|
+
...account,
|
|
393
|
+
sign: refuse("a raw hash"),
|
|
394
|
+
signMessage: refuse("a message"),
|
|
395
|
+
signAuthorization: refuse("an EIP-7702 authorization"),
|
|
396
|
+
signTypedData: async (typedData) => {
|
|
397
|
+
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
398
|
+
const d = typedData?.domain ?? {};
|
|
399
|
+
const ok = ["Voucher", "CloseAuthorization"].includes(typedData?.primaryType) && d.name === VOUCHER_DOMAIN
|
|
400
|
+
&& String(d.verifyingContract ?? "").toLowerCase() === TEMPO_ESCROW && Number(d.chainId) === chainId;
|
|
401
|
+
if (!ok) throw new PresignBlockedError(`MPP session account: only channel vouchers on Tempo's escrow are signed (got ${typedData?.primaryType ?? "nothing"}); nothing was signed`, { code: "unsupported_chain" });
|
|
402
|
+
return account.signTypedData(typedData);
|
|
403
|
+
},
|
|
404
|
+
signTransaction: async (tx, opts) => {
|
|
405
|
+
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
406
|
+
const { token, payee, deposit } = sessionDeposit(tx, chainId, account.address);
|
|
407
|
+
const run = () => account.signTransaction(tx, opts);
|
|
408
|
+
if (!limiter) return run();
|
|
409
|
+
const request = checkRequestFor("writeContract", { address: token, abi: TRANSFER_ABI, functionName: "transfer", args: [payee, deposit] }, { chainId, origin });
|
|
410
|
+
return withinLimits("writeContract", request, null, run);
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
},
|
|
414
|
+
/**
|
|
415
|
+
* The same guard on an x402 AVM client signer ({ address, signTransactions(txns, indexesToSign) }, e.g.
|
|
416
|
+
* toClientAvmSigner from @x402/avm): of the transactions it is asked to sign it signs only an asset transfer
|
|
417
|
+
* of USDC on that network from this address (no close-out, rekey or clawback), counted toward the USDC limit.
|
|
418
|
+
* The facilitator's fee-payer transaction in the same group is not this signer's and is left unsigned.
|
|
419
|
+
* network: the x402 id of Algorand mainnet (default) or testnet.
|
|
420
|
+
*/
|
|
421
|
+
algorandSigner: (signer, { network = "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=" } = {}) => {
|
|
422
|
+
if (!signer || typeof signer.signTransactions !== "function" || typeof signer.address !== "string") throw new TypeError("algorandSigner(signer): signer needs address and signTransactions(txns, indexesToSign) (e.g. toClientAvmSigner from @x402/avm)");
|
|
423
|
+
if (!ALGORAND_USDC[network]) throw new TypeError(`algorandSigner: network must be one of ${Object.keys(ALGORAND_USDC).join(", ")}`);
|
|
424
|
+
return { address: signer.address, signTransactions: (txns, indexesToSign) => algorandSign(signer, network, txns, indexesToSign) };
|
|
425
|
+
},
|
|
312
426
|
/** Stop every checked method until resume(). */
|
|
313
427
|
pause: () => { paused = true; },
|
|
314
428
|
resume: () => { paused = false; },
|
package/limits.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// it can spend that amount, so it counts when it is given; an unlimited
|
|
11
11
|
// one or setApprovalForAll is over any limit;
|
|
12
12
|
// - an EIP-3009 payment or Permit2 transfer signature;
|
|
13
|
+
// - an Algorand asset transfer: USDC (ASA 31566704) counts toward the USDC limit;
|
|
13
14
|
// - an XRP Ledger Payment: XRP (drops) counts toward an XRP limit, RLUSD from
|
|
14
15
|
// Ripple's issuer toward the USDC limit (a dollar is a dollar), any other
|
|
15
16
|
// issued currency as an unknown token. SendMax, when set, is what can leave.
|
|
@@ -20,6 +21,7 @@
|
|
|
20
21
|
// Amounts are kept at 18 decimals so one budget can cover the same token with
|
|
21
22
|
// different decimals on different chains (USDC is 18 on BNB Chain, 6 elsewhere).
|
|
22
23
|
import { decodeFunctionData, formatUnits, parseAbi, parseUnits } from "viem";
|
|
24
|
+
import { ALGORAND_USDC } from "./algorand.js";
|
|
23
25
|
|
|
24
26
|
const SCALE = 18;
|
|
25
27
|
const NATIVE = "native";
|
|
@@ -89,6 +91,7 @@ export function normalizeLimits(limits) {
|
|
|
89
91
|
if (symbol === "USDC") {
|
|
90
92
|
for (const [chain, list] of Object.entries(USDC)) for (const [addr, decimals] of list) put(`${chain}:${addr}`, { budget: name, decimals });
|
|
91
93
|
for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:rlusd`, { budget: name, decimals: SCALE });
|
|
94
|
+
for (const [net, asa] of Object.entries(ALGORAND_USDC)) put(`${net}:${asa}`, { budget: name, decimals: 6 });
|
|
92
95
|
} else if (symbol === "XRP") {
|
|
93
96
|
for (const net of Object.keys(XRPL_RLUSD_ISSUERS)) put(`${net}:${NATIVE}`, { budget: name, decimals: 6 });
|
|
94
97
|
} else if (["ETH", "BNB", "POL"].includes(symbol)) {
|
|
@@ -114,6 +117,7 @@ const scaled = (raw, decimals) => (decimals <= SCALE ? raw * 10n ** BigInt(SCALE
|
|
|
114
117
|
export function spendFor(request, verdict) {
|
|
115
118
|
const out = { items: [], counterparties: [], unknown: false };
|
|
116
119
|
if (request.type === "xrpl") return xrplSpend(request, out);
|
|
120
|
+
if (request.type === "algorand") return algorandSpend(request, out);
|
|
117
121
|
const chainId = request.chainId;
|
|
118
122
|
if (request.type === "transaction") {
|
|
119
123
|
const to = lower(request.to ?? null);
|
|
@@ -175,6 +179,18 @@ function xrplSpend(request, out) {
|
|
|
175
179
|
return out;
|
|
176
180
|
}
|
|
177
181
|
|
|
182
|
+
// An Algorand asset transfer (read from the unsigned transaction by algorandSigner): the asset, amount and receiver.
|
|
183
|
+
// Anything else (a payment in ALGO, a close-out, a rekey, a clawback) can't be counted and is unknown.
|
|
184
|
+
function algorandSpend(request, out) {
|
|
185
|
+
const net = request.network;
|
|
186
|
+
const t = request.txn ?? {};
|
|
187
|
+
const to = typeof t.receiver === "string" ? lower(t.receiver) : null;
|
|
188
|
+
out.counterparties.push(to);
|
|
189
|
+
if (t.type !== "axfer" || t.closeTo || t.rekeyTo || t.clawbackFrom || !/^\d+$/.test(String(t.assetId ?? "")) || !/^\d+$/.test(String(t.amount ?? ""))) { out.unknown = true; return out; }
|
|
190
|
+
out.items.push({ chainId: net, token: String(t.assetId), amount: BigInt(t.amount), to });
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
|
|
178
194
|
const fmt = (x) => (x === null ? "unlimited" : formatUnits(x, SCALE));
|
|
179
195
|
const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "a new contract");
|
|
180
196
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "presign-guard-wallet",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"telegram.js",
|
|
32
32
|
"remote.js",
|
|
33
33
|
"mandate.js",
|
|
34
|
+
"algorand.js",
|
|
34
35
|
"telegram.d.ts",
|
|
35
36
|
"README.md",
|
|
36
37
|
"LICENSE"
|
|
@@ -49,6 +50,7 @@
|
|
|
49
50
|
"viem": "^2.30.0"
|
|
50
51
|
},
|
|
51
52
|
"devDependencies": {
|
|
53
|
+
"@x402/avm": "^2.28.0",
|
|
52
54
|
"@x402/fetch": "^2.27.0",
|
|
53
55
|
"viem": "^2.56.9"
|
|
54
56
|
},
|