presign-guard-wallet 0.2.0 → 0.4.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 +78 -1
- package/file-store.d.ts +4 -0
- package/file-store.js +29 -0
- package/index.d.ts +93 -2
- package/index.js +78 -10
- package/limits.js +245 -0
- package/package.json +20 -3
- package/telegram.d.ts +22 -0
- package/telegram.js +152 -0
package/README.md
CHANGED
|
@@ -10,6 +10,8 @@ Before every `sendTransaction`, `writeContract` and `signTypedData`, the wallet
|
|
|
10
10
|
| 🟠 orange | `onOrange`: `"stop"` (default, throws), `"allow"`, or your own function (e.g. ask the user) |
|
|
11
11
|
| 🔴 red | Throws `PresignBlockedError` with the reasons; **nothing is signed** |
|
|
12
12
|
|
|
13
|
+
On top of that it can keep to **spending limits** you set per token (per transaction and per day), and ask a human for anything over them. See [Spending limits](#spending-limits).
|
|
14
|
+
|
|
13
15
|
presign-guard decodes approvals, `increaseAllowance`, `setApprovalForAll`, EIP-2612 and Permit2 permits, EIP-3009 transfer authorizations (what an x402 payment signs) and Seaport orders, and screens every spender, recipient and token: known drainers and phishing addresses, sanctions, unlimited approvals to a plain wallet, honeypot tokens, unverified or brand-new contracts, and, with `origin`, new or lookalike domains and phishing sites. See the [reason codes](https://github.com/Fizzl13/presign-guard#reason-codes).
|
|
14
16
|
|
|
15
17
|
## Install
|
|
@@ -62,6 +64,10 @@ try {
|
|
|
62
64
|
| `verifyReceipts` | `"require"` | Check presign-guard's signed receipt on every verdict; `"off"` skips it |
|
|
63
65
|
| `signers` | presign-guard's published signer | Accepted signer addresses |
|
|
64
66
|
| `authority` | the Fizzl payout wallet | Wallet whose certificates also make a signer trusted (key rotation); `null` accepts only `signers` |
|
|
67
|
+
| `limits` | | Spending limits per token, see [Spending limits](#spending-limits) |
|
|
68
|
+
| `onOverLimit` | | `async (info) => boolean`: asked when a limit would be crossed; `true` signs anyway. Without it the wallet stops. Ready-made: [`telegramApprover`](#approve-from-your-phone-telegram) |
|
|
69
|
+
| `onSpend` | | `(entry) => void` after each signed spend, e.g. for a log |
|
|
70
|
+
| `store` | in memory | Where spending is kept; `fileStore(path)` from `presign-guard-wallet/file-store`, or your own |
|
|
65
71
|
|
|
66
72
|
Chains: Ethereum (1), Optimism (10), BNB Chain (56), Polygon (137), Base (8453), Arbitrum (42161).
|
|
67
73
|
|
|
@@ -78,6 +84,77 @@ const wallet = guardWallet(walletClient, { creditKey: credit_key, pay }); // pay
|
|
|
78
84
|
|
|
79
85
|
Each check then sends the key instead of paying. When the credits are used up (or the key is unknown or expired) the wallet pays per check with `pay`; without `pay` it stops, and nothing is signed. Verdicts are signed and checked exactly as with per-check payment. Keep the key secret: anyone who has it can spend the credits.
|
|
80
86
|
|
|
87
|
+
## Spending limits
|
|
88
|
+
|
|
89
|
+
Give the agent a budget instead of a blank cheque:
|
|
90
|
+
|
|
91
|
+
```js
|
|
92
|
+
import { guardWallet, PresignBlockedError } from "presign-guard-wallet";
|
|
93
|
+
import { fileStore } from "presign-guard-wallet/file-store";
|
|
94
|
+
|
|
95
|
+
const wallet = guardWallet(walletClient, {
|
|
96
|
+
pay,
|
|
97
|
+
limits: {
|
|
98
|
+
tokens: {
|
|
99
|
+
USDC: { perTx: "5", perDay: "20" }, // whole tokens; native and bridged USDC on every chain
|
|
100
|
+
ETH: { perTx: "0.002", perDay: "0.01" }, // the native coin; also BNB, POL
|
|
101
|
+
// any other token by address (any chain) or "chainId:0x…", with its decimals:
|
|
102
|
+
// "8453:0x4200…0006": { perDay: "0.01", decimals: 18 },
|
|
103
|
+
},
|
|
104
|
+
unknownTokens: "ask", // a token without a limit: "ask" (default), "stop" or "allow"
|
|
105
|
+
allow: ["0xShop…", "0xRouter…"], // optional: only these recipients, spenders and contracts
|
|
106
|
+
window: "24h", // the rolling window perDay applies to
|
|
107
|
+
},
|
|
108
|
+
// over a limit: a human decides (true = sign anyway); without it the wallet stops
|
|
109
|
+
onOverLimit: async ({ summary }) => askUserOnPhone(`Agent wants to sign: ${summary}. OK?`),
|
|
110
|
+
onSpend: (e) => console.log(`spent ${e.amount} ${e.budget} → ${e.to} (${e.result})`),
|
|
111
|
+
store: fileStore("./spending.json"), // survives restarts; default is in memory
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
await wallet.spending(); // [{ token: "USDC", perTx: "5", perDay: "20", used: "8.5", left: "11.5" }, …]
|
|
115
|
+
wallet.pause(); // emergency stop: nothing is signed until wallet.resume()
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The order for every signature: presign-guard's verdict first (red never reaches a human), then `onOrange`, then the limits. Over a limit, the wallet throws `PresignBlockedError` with code `over_limit` and `err.reasons` (`per_tx`, `per_day`, `unknown_token`, `unknown_spend`, `not_allowed`), unless `onOverLimit` returns `true`.
|
|
119
|
+
|
|
120
|
+
What counts as spending:
|
|
121
|
+
|
|
122
|
+
- the native value sent with a transaction, also with a contract deployment;
|
|
123
|
+
- an ERC-20 `transfer` or `transferFrom`;
|
|
124
|
+
- 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;
|
|
125
|
+
- 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`).
|
|
126
|
+
|
|
127
|
+
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`).
|
|
128
|
+
|
|
129
|
+
These limits live in your agent's software: they stop a confused or manipulated agent, not someone who has the private key. For limits the chain enforces, use a smart account with session keys; the same budget can then be set there.
|
|
130
|
+
|
|
131
|
+
### Approve from your phone (Telegram)
|
|
132
|
+
|
|
133
|
+
`onOverLimit` can be a Telegram bot: when a signature would cross a limit, you get a message with what the agent wants to sign, why it is over the limit and presign-guard's verdict, with **Approve** and **Deny** buttons. The agent waits for your tap.
|
|
134
|
+
|
|
135
|
+
1. In Telegram, talk to [@BotFather](https://t.me/BotFather), send `/newbot` and keep the token it gives you secret (an environment variable, never in code).
|
|
136
|
+
2. Send your new bot `/start`, then find your chat id:
|
|
137
|
+
```bash
|
|
138
|
+
TELEGRAM_BOT_TOKEN=... node -e 'import("presign-guard-wallet/telegram").then(async (t) => console.log(await t.findTelegramChats({ token: process.env.TELEGRAM_BOT_TOKEN })))'
|
|
139
|
+
```
|
|
140
|
+
3. Use it:
|
|
141
|
+
```js
|
|
142
|
+
import { telegramApprover } from "presign-guard-wallet/telegram";
|
|
143
|
+
|
|
144
|
+
const wallet = guardWallet(walletClient, {
|
|
145
|
+
pay,
|
|
146
|
+
limits: { tokens: { USDC: { perTx: "5", perDay: "20" } } },
|
|
147
|
+
onOverLimit: telegramApprover({
|
|
148
|
+
token: process.env.TELEGRAM_BOT_TOKEN,
|
|
149
|
+
chatId: process.env.TELEGRAM_CHAT_ID,
|
|
150
|
+
label: "research-agent",
|
|
151
|
+
timeoutMs: 10 * 60_000, // no answer in 10 minutes = Deny
|
|
152
|
+
}),
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Only the chat you name (or the `allowedUserIds` you list) can answer; anyone else's tap is refused. No server is needed: the wallet asks Telegram for your tap itself (long polling), so the bot must not have a webhook, and one bot serves one agent process at a time (a second process polling the same bot makes Telegram refuse both; the request then fails and nothing is signed). If Telegram cannot be reached, the wallet stops (`limit_unavailable`) rather than signing.
|
|
157
|
+
|
|
81
158
|
## Signed verdicts
|
|
82
159
|
|
|
83
160
|
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:
|
|
@@ -86,7 +163,7 @@ presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash
|
|
|
86
163
|
- the signature must cover exactly the request that was checked;
|
|
87
164
|
- otherwise it throws `PresignBlockedError` with code `bad_receipt`, also with `onError: "allow"`: a forged or changed "green" is never a signature.
|
|
88
165
|
|
|
89
|
-
## Costs and
|
|
166
|
+
## Costs and coverage
|
|
90
167
|
|
|
91
168
|
- $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 (`signMessage`, contract deployments) are not checked and cost nothing.
|
|
92
169
|
- 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.
|
package/file-store.d.ts
ADDED
package/file-store.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// A spending store in a JSON file, so limits survive a restart (Node only;
|
|
2
|
+
// one process per file). For several agents sharing one budget, pass your own
|
|
3
|
+
// store with the same three methods, backed by a database.
|
|
4
|
+
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
5
|
+
|
|
6
|
+
const KEEP_MS = 31 * 86_400_000;
|
|
7
|
+
|
|
8
|
+
export function fileStore(path) {
|
|
9
|
+
if (typeof path !== "string" || !path) throw new TypeError("fileStore needs a file path");
|
|
10
|
+
const read = () => {
|
|
11
|
+
try {
|
|
12
|
+
const data = JSON.parse(readFileSync(path, "utf8"));
|
|
13
|
+
return Array.isArray(data) ? data : [];
|
|
14
|
+
} catch (err) {
|
|
15
|
+
if (err.code === "ENOENT") return [];
|
|
16
|
+
throw new Error(`spending file ${path} is unreadable (${err.message}); fix or remove it`);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const write = (entries) => {
|
|
20
|
+
const tmp = `${path}.tmp`;
|
|
21
|
+
writeFileSync(tmp, JSON.stringify(entries.filter((e) => e.at >= Date.now() - KEEP_MS), null, 1));
|
|
22
|
+
renameSync(tmp, path);
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
async add(entry) { write([...read(), entry]); },
|
|
26
|
+
async remove(id) { write(read().filter((e) => e.id !== id)); },
|
|
27
|
+
async list(since) { return read().filter((e) => e.at >= since); },
|
|
28
|
+
};
|
|
29
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -21,9 +21,92 @@ export type CheckRequest =
|
|
|
21
21
|
| { type: "signature"; chainId: number; typedData: unknown; origin?: string };
|
|
22
22
|
|
|
23
23
|
export declare class PresignBlockedError extends Error {
|
|
24
|
-
code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain";
|
|
24
|
+
code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain" | "over_limit" | "paused" | "limit_unavailable";
|
|
25
25
|
verdict: PresignVerdict | null;
|
|
26
26
|
request: CheckRequest | null;
|
|
27
|
+
/** With code "over_limit": which limits would be crossed. */
|
|
28
|
+
reasons?: LimitReason[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A limit in whole tokens, e.g. "5" or "0.002". */
|
|
32
|
+
export type TokenAmount = string | number;
|
|
33
|
+
|
|
34
|
+
export interface SpendingLimits {
|
|
35
|
+
/**
|
|
36
|
+
* Per token: "USDC" (native and bridged USDC on every supported chain), "ETH", "BNB", "POL" (the native coin),
|
|
37
|
+
* a token address ("0x…", any chain) or "chainId:0x…"; tokens given by address need decimals.
|
|
38
|
+
* Budgets are shared across chains: { USDC: { perDay: "20" } } is 20 USDC in total.
|
|
39
|
+
*/
|
|
40
|
+
tokens?: Record<string, { perTx?: TokenAmount; perDay?: TokenAmount; decimals?: number }>;
|
|
41
|
+
/** Spending of a token without a limit, or a signature whose spending cannot be read. Default "ask" (onOverLimit, else stop). */
|
|
42
|
+
unknownTokens?: "stop" | "ask" | "allow";
|
|
43
|
+
/** Only these recipients, spenders and contracts; anything else goes to onOverLimit. */
|
|
44
|
+
allow?: string[];
|
|
45
|
+
/** The rolling window perDay applies to. Default "24h". */
|
|
46
|
+
window?: string | number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface LimitReason {
|
|
50
|
+
code: "per_tx" | "per_day" | "unknown_token" | "unknown_spend" | "not_allowed";
|
|
51
|
+
message: string;
|
|
52
|
+
budget?: string;
|
|
53
|
+
amount?: string;
|
|
54
|
+
limit?: string;
|
|
55
|
+
used?: string;
|
|
56
|
+
token?: string;
|
|
57
|
+
to?: string | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface SpendingRow {
|
|
61
|
+
token: string;
|
|
62
|
+
perTx: string | null;
|
|
63
|
+
perDay: string | null;
|
|
64
|
+
used: string;
|
|
65
|
+
left: string | null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface OverLimitInfo {
|
|
69
|
+
method: string;
|
|
70
|
+
request: CheckRequest;
|
|
71
|
+
verdict: PresignVerdict | null;
|
|
72
|
+
reasons: LimitReason[];
|
|
73
|
+
/** One line for a human, e.g. "8 USDC is over the limit of 20 per 24h (15 used)". */
|
|
74
|
+
summary: string;
|
|
75
|
+
spending: SpendingRow[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface SpendEntry {
|
|
79
|
+
id: string;
|
|
80
|
+
at: number;
|
|
81
|
+
budget: string;
|
|
82
|
+
/** In whole tokens. */
|
|
83
|
+
amount: string;
|
|
84
|
+
method: string;
|
|
85
|
+
chainId: number;
|
|
86
|
+
to: string | null;
|
|
87
|
+
/** What the wallet method returned (transaction hash or signature). */
|
|
88
|
+
result: unknown;
|
|
89
|
+
verdict: PresignVerdict | null;
|
|
90
|
+
receiptId: string | null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Where spending is kept. amount is a decimal string at 18 decimals. */
|
|
94
|
+
export interface SpendingStore {
|
|
95
|
+
add(entry: { id: string; at: number; budget: string; amount: string; [key: string]: unknown }): Promise<void>;
|
|
96
|
+
remove(id: string): Promise<void>;
|
|
97
|
+
list(since: number): Promise<Array<{ id: string; at: number; budget: string; amount: string }>>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export declare function memoryStore(): SpendingStore;
|
|
101
|
+
|
|
102
|
+
/** Added to the guarded wallet. */
|
|
103
|
+
export interface GuardControls {
|
|
104
|
+
/** Stop every checked method (sendTransaction, writeContract, signTypedData) until resume(). */
|
|
105
|
+
pause(): void;
|
|
106
|
+
resume(): void;
|
|
107
|
+
paused(): boolean;
|
|
108
|
+
/** Per token: the limits, what was spent in the current window and what is left; null without limits. */
|
|
109
|
+
spending(): Promise<SpendingRow[] | null>;
|
|
27
110
|
}
|
|
28
111
|
|
|
29
112
|
export interface GuardOptions {
|
|
@@ -47,8 +130,16 @@ export interface GuardOptions {
|
|
|
47
130
|
signers?: string[];
|
|
48
131
|
/** Wallet whose certificates also make a signer trusted (key rotation). Default: the Fizzl payout wallet; null accepts only `signers`. */
|
|
49
132
|
authority?: string | null;
|
|
133
|
+
/** Spending limits per token, checked after presign-guard's verdict and before signing. */
|
|
134
|
+
limits?: SpendingLimits;
|
|
135
|
+
/** Asked when a limit would be crossed (e.g. ask the user on their phone). true = sign anyway. Without it, the wallet stops. */
|
|
136
|
+
onOverLimit?: (info: OverLimitInfo) => boolean | Promise<boolean>;
|
|
137
|
+
/** Called after each signed spend, e.g. for a log. */
|
|
138
|
+
onSpend?: (entry: SpendEntry) => void;
|
|
139
|
+
/** Where spending is kept. Default in memory (gone on a restart); fileStore from "presign-guard-wallet/file-store" for a file. */
|
|
140
|
+
store?: SpendingStore;
|
|
50
141
|
}
|
|
51
142
|
|
|
52
143
|
/** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
|
|
53
|
-
export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W;
|
|
144
|
+
export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W & GuardControls;
|
|
54
145
|
export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string }): CheckRequest | null;
|
package/index.js
CHANGED
|
@@ -19,19 +19,28 @@
|
|
|
19
19
|
// from prepaid presign-guard credits (creditKey, 100 checks for $0.80 at
|
|
20
20
|
// https://presign-guard.fizzl.eu/v1/credits/100): with a key the wallet asks
|
|
21
21
|
// with the key first and only pays per check when the credits are used up.
|
|
22
|
+
//
|
|
23
|
+
// Spending limits (limits): per token, per transaction and per rolling window,
|
|
24
|
+
// plus an optional allow list. Anything over a limit goes to onOverLimit (your
|
|
25
|
+
// function, e.g. ask the user on their phone); without it, it stops. These
|
|
26
|
+
// limits live in the agent's software: an agent with the raw key can go around
|
|
27
|
+
// them. See limits.js for what counts as spending.
|
|
22
28
|
|
|
23
29
|
import { encodeFunctionData } from "viem";
|
|
24
30
|
import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
|
|
31
|
+
import { createLimiter, memoryStore } from "./limits.js";
|
|
32
|
+
|
|
33
|
+
export { memoryStore };
|
|
25
34
|
|
|
26
35
|
export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
|
|
27
36
|
export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
|
|
28
37
|
export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
|
|
29
|
-
export const VERSION = "0.
|
|
38
|
+
export const VERSION = "0.4.0";
|
|
30
39
|
export const CREDIT_HEADER = "x-credit-key";
|
|
31
40
|
const ROUTE = "POST /v1/check";
|
|
32
41
|
|
|
33
42
|
export class PresignBlockedError extends Error {
|
|
34
|
-
/** code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain" */
|
|
43
|
+
/** code: "red" | "orange" | "check_failed" | "bad_receipt" | "unsupported_chain" | "over_limit" | "paused" | "limit_unavailable" */
|
|
35
44
|
constructor(message, { code, verdict = null, request = null } = {}) {
|
|
36
45
|
super(message);
|
|
37
46
|
this.name = "PresignBlockedError";
|
|
@@ -78,6 +87,10 @@ const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
|
|
|
78
87
|
* @param {"require"|"off"} [options.verifyReceipts]
|
|
79
88
|
* @param {string[]} [options.signers]
|
|
80
89
|
* @param {string|null} [options.authority]
|
|
90
|
+
* @param {object} [options.limits] spending limits: { tokens: { USDC: { perTx, perDay }, … }, unknownTokens, allow, window }
|
|
91
|
+
* @param {(info: object) => boolean|Promise<boolean>} [options.onOverLimit] asked when a limit would be crossed; true = sign anyway
|
|
92
|
+
* @param {(entry: object) => void} [options.onSpend] after each signed spend
|
|
93
|
+
* @param {object} [options.store] where spending is kept (default in memory; fileStore from presign-guard-wallet/file-store)
|
|
81
94
|
*/
|
|
82
95
|
export function guardWallet(wallet, {
|
|
83
96
|
pay,
|
|
@@ -91,6 +104,10 @@ export function guardWallet(wallet, {
|
|
|
91
104
|
authority = AUTHORITY,
|
|
92
105
|
creditKey,
|
|
93
106
|
fetch: plainFetch = globalThis.fetch,
|
|
107
|
+
limits,
|
|
108
|
+
onOverLimit,
|
|
109
|
+
onSpend,
|
|
110
|
+
store,
|
|
94
111
|
} = {}) {
|
|
95
112
|
if (!wallet || typeof wallet !== "object") throw new TypeError("wallet must be a viem WalletClient");
|
|
96
113
|
if (creditKey !== undefined && !/^pgc_[A-Za-z0-9_-]{43}$/.test(String(creditKey))) throw new TypeError("creditKey must be a presign-guard credit key (pgc_…)");
|
|
@@ -99,6 +116,10 @@ export function guardWallet(wallet, {
|
|
|
99
116
|
if (!["stop", "allow"].includes(onError)) throw new TypeError('onError must be "stop" or "allow"');
|
|
100
117
|
if (!["require", "off"].includes(verifyReceipts)) throw new TypeError('verifyReceipts must be "require" or "off"');
|
|
101
118
|
|
|
119
|
+
if (limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
|
|
120
|
+
const limiter = limits === undefined ? null : createLimiter(limits, { store, onOverLimit, onSpend });
|
|
121
|
+
let paused = false;
|
|
122
|
+
|
|
102
123
|
let creditsLeft = null;
|
|
103
124
|
async function check(request) {
|
|
104
125
|
const body = toJson(request);
|
|
@@ -133,13 +154,10 @@ export function guardWallet(wallet, {
|
|
|
133
154
|
return verdict;
|
|
134
155
|
}
|
|
135
156
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const request = checkRequestFor(method, args, { chainId, origin });
|
|
139
|
-
if (!request) return original(args, ...rest);
|
|
140
|
-
const run = () => original(args, ...rest);
|
|
157
|
+
// The verdict for a request, or null when the check could not be done and onError is "allow".
|
|
158
|
+
async function verdictFor(method, request, chainId) {
|
|
141
159
|
if (!SUPPORTED_CHAINS.includes(chainId)) {
|
|
142
|
-
if (onError === "allow") return
|
|
160
|
+
if (onError === "allow") return null;
|
|
143
161
|
throw new PresignBlockedError(`chain ${chainId} is not covered by presign-guard; nothing was signed`, { code: "unsupported_chain", request });
|
|
144
162
|
}
|
|
145
163
|
let verdict;
|
|
@@ -147,7 +165,7 @@ export function guardWallet(wallet, {
|
|
|
147
165
|
verdict = await check(request);
|
|
148
166
|
} catch (err) {
|
|
149
167
|
if (err instanceof PresignBlockedError && err.code === "bad_receipt") throw err;
|
|
150
|
-
if (onError === "allow") return
|
|
168
|
+
if (onError === "allow") return null;
|
|
151
169
|
if (err instanceof PresignBlockedError) throw err;
|
|
152
170
|
throw new PresignBlockedError(`presign check failed (${err.message}); nothing was signed`, { code: "check_failed", request });
|
|
153
171
|
}
|
|
@@ -160,11 +178,61 @@ export function guardWallet(wallet, {
|
|
|
160
178
|
} else if (verdict.verdict !== "green") {
|
|
161
179
|
throw new PresignBlockedError(`not signed: unknown verdict ${verdict.verdict}`, { code: "check_failed", verdict, request });
|
|
162
180
|
}
|
|
163
|
-
return
|
|
181
|
+
return verdict;
|
|
164
182
|
}
|
|
165
183
|
|
|
184
|
+
// Within the limits (or approved by onOverLimit): book, sign, and give it back if signing fails.
|
|
185
|
+
async function withinLimits(method, request, verdict, run) {
|
|
186
|
+
let booked;
|
|
187
|
+
try {
|
|
188
|
+
booked = await limiter.reserve({ method, request, verdict });
|
|
189
|
+
} catch (err) {
|
|
190
|
+
throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
|
|
191
|
+
}
|
|
192
|
+
if (!booked.ok) {
|
|
193
|
+
const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: "over_limit", verdict, request });
|
|
194
|
+
err.reasons = booked.reasons;
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
let result;
|
|
198
|
+
try {
|
|
199
|
+
result = await run();
|
|
200
|
+
} catch (err) {
|
|
201
|
+
await limiter.release(booked.entries).catch((e) => console.warn(`[presign-guard-wallet] could not give back spending: ${e.message}`));
|
|
202
|
+
throw err;
|
|
203
|
+
}
|
|
204
|
+
limiter.spent(booked.entries, result, { verdict });
|
|
205
|
+
return result;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function guarded(method, original, args, rest) {
|
|
209
|
+
if (paused) throw new PresignBlockedError(`wallet is paused; nothing was signed`, { code: "paused" });
|
|
210
|
+
const chainId = args?.chain?.id ?? wallet.chain?.id;
|
|
211
|
+
const run = () => original(args, ...rest);
|
|
212
|
+
const request = checkRequestFor(method, args, { chainId, origin });
|
|
213
|
+
if (!request) {
|
|
214
|
+
// A contract deployment is not checked, but the value it sends still counts.
|
|
215
|
+
if (limiter && method === "sendTransaction") {
|
|
216
|
+
return withinLimits(method, { type: "transaction", chainId, to: null, data: args?.data ?? "0x", value: String(args?.value ?? 0n) }, null, run);
|
|
217
|
+
}
|
|
218
|
+
return run();
|
|
219
|
+
}
|
|
220
|
+
const verdict = await verdictFor(method, request, chainId);
|
|
221
|
+
return limiter ? withinLimits(method, request, verdict, run) : run();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const extras = {
|
|
225
|
+
/** Stop every checked method until resume(). */
|
|
226
|
+
pause: () => { paused = true; },
|
|
227
|
+
resume: () => { paused = false; },
|
|
228
|
+
paused: () => paused,
|
|
229
|
+
/** Per token: the limits, what was spent in the current window and what is left (null without limits). */
|
|
230
|
+
spending: async () => (limiter ? limiter.spending() : null),
|
|
231
|
+
};
|
|
232
|
+
|
|
166
233
|
return new Proxy(wallet, {
|
|
167
234
|
get(target, prop, receiver) {
|
|
235
|
+
if (Object.hasOwn(extras, prop) && !(prop in target)) return extras[prop];
|
|
168
236
|
const value = Reflect.get(target, prop, receiver);
|
|
169
237
|
if (typeof prop !== "string" || !GUARDED.has(prop) || typeof value !== "function") return value;
|
|
170
238
|
return (args, ...rest) => guarded(prop, value.bind(target), args, rest);
|
package/limits.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// Spending limits for presign-guard-wallet: per transaction and per rolling
|
|
2
|
+
// window (default 24h), per token, with a human asked (onOverLimit) for
|
|
3
|
+
// anything over a limit, to an address outside the allow list, or of a token
|
|
4
|
+
// without a limit.
|
|
5
|
+
//
|
|
6
|
+
// What counts as spending:
|
|
7
|
+
// - the native value sent with a transaction (ETH, BNB, POL);
|
|
8
|
+
// - an ERC-20 transfer or transferFrom;
|
|
9
|
+
// - an allowance (approve, increaseAllowance, Permit, Permit2): whoever gets
|
|
10
|
+
// it can spend that amount, so it counts when it is given; an unlimited
|
|
11
|
+
// one or setApprovalForAll is over any limit;
|
|
12
|
+
// - an EIP-3009 payment or Permit2 transfer signature.
|
|
13
|
+
// Transactions are decoded here; typed-data signatures are read from the
|
|
14
|
+
// signed subject of presign-guard's verdict. A signature presign-guard could
|
|
15
|
+
// not decode (or one signed without a verdict) counts as unknown spending.
|
|
16
|
+
//
|
|
17
|
+
// Amounts are kept at 18 decimals so one budget can cover the same token with
|
|
18
|
+
// different decimals on different chains (USDC is 18 on BNB Chain, 6 elsewhere).
|
|
19
|
+
import { decodeFunctionData, formatUnits, parseAbi, parseUnits } from "viem";
|
|
20
|
+
|
|
21
|
+
const SCALE = 18;
|
|
22
|
+
const NATIVE = "native";
|
|
23
|
+
|
|
24
|
+
// USDC (native and bridged) per chain, with decimals. Bridged USDC shares the budget.
|
|
25
|
+
const USDC = {
|
|
26
|
+
1: [["0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", 6]],
|
|
27
|
+
10: [["0x0b2c639c533813f4aa9d7837caf62653d097ff85", 6], ["0x7f5c764cbc14f9669b88837ca1490cca17c31607", 6]],
|
|
28
|
+
56: [["0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d", 18]],
|
|
29
|
+
137: [["0x3c499c542cef5e3811e1192ce70d8cc03d5c3359", 6], ["0x2791bca1f2de4661ed88a30c99a7a9449aa84174", 6]],
|
|
30
|
+
8453: [["0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", 6]],
|
|
31
|
+
42161: [["0xaf88d065e77c8cc2239327c5edb3a432268e5831", 6], ["0xff970a61a04b1ca14834a43f5de4533ebddb5cc8", 6]],
|
|
32
|
+
};
|
|
33
|
+
const NATIVE_SYMBOL = { 1: "ETH", 10: "ETH", 8453: "ETH", 42161: "ETH", 56: "BNB", 137: "POL" };
|
|
34
|
+
export const KNOWN_TOKENS = ["USDC", "ETH", "BNB", "POL"];
|
|
35
|
+
|
|
36
|
+
const ERC20_ABI = parseAbi([
|
|
37
|
+
"function approve(address spender, uint256 amount)",
|
|
38
|
+
"function increaseAllowance(address spender, uint256 addedValue)",
|
|
39
|
+
"function transfer(address to, uint256 amount)",
|
|
40
|
+
"function transferFrom(address from, address to, uint256 amount)",
|
|
41
|
+
"function setApprovalForAll(address operator, bool approved)",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
45
|
+
const lower = (a) => (typeof a === "string" ? a.toLowerCase() : a);
|
|
46
|
+
|
|
47
|
+
export function parseWindow(window) {
|
|
48
|
+
if (window === undefined) return 86_400_000;
|
|
49
|
+
if (typeof window === "number" && window > 0) return window;
|
|
50
|
+
const m = /^(\d+)\s*(m|h|d)$/.exec(String(window));
|
|
51
|
+
if (!m || Number(m[1]) === 0) throw new TypeError('limits.window must be like "24h", "1h", "7d", "30m" or a number of milliseconds');
|
|
52
|
+
return Number(m[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function amount(value, what) {
|
|
56
|
+
if (value === undefined || value === null) return null;
|
|
57
|
+
if (!/^\d+(\.\d+)?$/.test(String(value))) throw new TypeError(`${what} must be a positive number of whole tokens, like "5" or "0.002"`);
|
|
58
|
+
return parseUnits(String(value), SCALE);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// limits config -> { budgets, index, unknownTokens, allow, windowMs }
|
|
62
|
+
export function normalizeLimits(limits) {
|
|
63
|
+
if (!limits || typeof limits !== "object") throw new TypeError("limits must be an object");
|
|
64
|
+
const { tokens = {}, unknownTokens = "ask", allow, window } = limits;
|
|
65
|
+
if (!["stop", "ask", "allow"].includes(unknownTokens)) throw new TypeError('limits.unknownTokens must be "stop", "ask" or "allow"');
|
|
66
|
+
if (allow !== undefined && (!Array.isArray(allow) || allow.some((a) => !ADDRESS_RE.test(a)))) throw new TypeError("limits.allow must be a list of 0x addresses");
|
|
67
|
+
const budgets = new Map();
|
|
68
|
+
const index = new Map(); // "chainId:token" or "*:token" -> { budget, decimals }
|
|
69
|
+
const put = (k, v) => { if (index.has(k)) throw new TypeError(`limits.tokens: ${k} is covered twice`); index.set(k, v); };
|
|
70
|
+
for (const [name, cfg] of Object.entries(tokens)) {
|
|
71
|
+
if (!cfg || typeof cfg !== "object") throw new TypeError(`limits.tokens.${name} must be { perTx, perDay }`);
|
|
72
|
+
const perTx = amount(cfg.perTx, `limits.tokens.${name}.perTx`);
|
|
73
|
+
const perDay = amount(cfg.perDay, `limits.tokens.${name}.perDay`);
|
|
74
|
+
if (perTx === null && perDay === null) throw new TypeError(`limits.tokens.${name} needs perTx, perDay or both`);
|
|
75
|
+
budgets.set(name, { name, perTx, perDay });
|
|
76
|
+
const symbol = name.toUpperCase();
|
|
77
|
+
if (symbol === "USDC") {
|
|
78
|
+
for (const [chain, list] of Object.entries(USDC)) for (const [addr, decimals] of list) put(`${chain}:${addr}`, { budget: name, decimals });
|
|
79
|
+
} else if (["ETH", "BNB", "POL"].includes(symbol)) {
|
|
80
|
+
for (const [chain, s] of Object.entries(NATIVE_SYMBOL)) if (s === symbol) put(`${chain}:${NATIVE}`, { budget: name, decimals: 18 });
|
|
81
|
+
} else {
|
|
82
|
+
const m = /^(?:(\d+):)?(0x[0-9a-fA-F]{40})$/.exec(name);
|
|
83
|
+
if (!m) throw new TypeError(`limits.tokens: "${name}" is not a known token (${KNOWN_TOKENS.join(", ")}), a 0x address or "chainId:0x address"`);
|
|
84
|
+
if (!Number.isInteger(cfg.decimals) || cfg.decimals < 0 || cfg.decimals > 36) throw new TypeError(`limits.tokens.${name}.decimals is required for a token given by address`);
|
|
85
|
+
put(`${m[1] ?? "*"}:${lower(m[2])}`, { budget: name, decimals: cfg.decimals });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { budgets, index, unknownTokens, allow: allow ? new Set(allow.map(lower)) : null, windowMs: parseWindow(window) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Amounts this large are "unlimited" (dapps use 2^256-1, 2^255 or 2^160-1 for Permit2).
|
|
92
|
+
const UNLIMITED = 2n ** 159n;
|
|
93
|
+
const capped = (raw) => (raw >= UNLIMITED ? null : raw);
|
|
94
|
+
|
|
95
|
+
const scaled = (raw, decimals) => (decimals <= SCALE ? raw * 10n ** BigInt(SCALE - decimals) : (raw + 10n ** BigInt(decimals - SCALE) - 1n) / 10n ** BigInt(decimals - SCALE));
|
|
96
|
+
|
|
97
|
+
// What a request spends: items [{ chainId, token, amount (raw bigint, null = unlimited), to }],
|
|
98
|
+
// the addresses that receive value or rights, and whether anything could not be read.
|
|
99
|
+
export function spendFor(request, verdict) {
|
|
100
|
+
const out = { items: [], counterparties: [], unknown: false };
|
|
101
|
+
const chainId = request.chainId;
|
|
102
|
+
if (request.type === "transaction") {
|
|
103
|
+
const to = lower(request.to ?? null);
|
|
104
|
+
const value = BigInt(request.value ?? 0);
|
|
105
|
+
if (value > 0n) out.items.push({ chainId, token: NATIVE, amount: value, to });
|
|
106
|
+
let call = null;
|
|
107
|
+
try { if (request.data && request.data !== "0x") call = decodeFunctionData({ abi: ERC20_ABI, data: request.data }); } catch { /* another contract call */ }
|
|
108
|
+
if (!call) { out.counterparties.push(to); return out; }
|
|
109
|
+
const a = call.args;
|
|
110
|
+
if (call.functionName === "approve" || call.functionName === "increaseAllowance") {
|
|
111
|
+
if (a[1] > 0n) out.items.push({ chainId, token: to, amount: capped(a[1]), to: lower(a[0]) });
|
|
112
|
+
out.counterparties.push(lower(a[0]));
|
|
113
|
+
} else if (call.functionName === "transfer") {
|
|
114
|
+
out.items.push({ chainId, token: to, amount: capped(a[1]), to: lower(a[0]) });
|
|
115
|
+
out.counterparties.push(lower(a[0]));
|
|
116
|
+
} else if (call.functionName === "transferFrom") {
|
|
117
|
+
out.items.push({ chainId, token: to, amount: capped(a[2]), to: lower(a[1]) });
|
|
118
|
+
out.counterparties.push(lower(a[1]));
|
|
119
|
+
} else if (call.functionName === "setApprovalForAll") {
|
|
120
|
+
if (a[1]) out.items.push({ chainId, token: to, amount: null, to: lower(a[0]) });
|
|
121
|
+
out.counterparties.push(lower(a[0]));
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
// Typed data: what presign-guard decoded (and signed).
|
|
126
|
+
const subject = verdict?.subject;
|
|
127
|
+
const verifying = lower(request.typedData?.domain?.verifyingContract ?? null);
|
|
128
|
+
if (!subject || !Array.isArray(subject.grants) || ["unknown_signature", "marketplace_order"].includes(subject.kind)) {
|
|
129
|
+
out.unknown = true;
|
|
130
|
+
out.counterparties.push(verifying);
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
for (const g of subject.grants) {
|
|
134
|
+
out.items.push({ chainId, token: lower(g.token), amount: g.amount === null || g.amount === undefined || g.allForAll || g.unlimited ? null : capped(BigInt(g.amount)), to: lower(g.spender) });
|
|
135
|
+
out.counterparties.push(lower(g.spender));
|
|
136
|
+
}
|
|
137
|
+
if (!subject.grants.length) out.counterparties.push(verifying);
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const fmt = (x) => (x === null ? "unlimited" : formatUnits(x, SCALE));
|
|
142
|
+
const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "a new contract");
|
|
143
|
+
|
|
144
|
+
// Check a request against the limits. Returns { charges: [{ budget, amount }], reasons, hardStop }.
|
|
145
|
+
export function evaluate(policy, spend, used) {
|
|
146
|
+
const reasons = [];
|
|
147
|
+
let hardStop = false;
|
|
148
|
+
const perBudget = new Map(); // budget -> scaled total (null = unlimited)
|
|
149
|
+
const unknownItems = [];
|
|
150
|
+
for (const item of spend.items) {
|
|
151
|
+
const hit = policy.index.get(`${item.chainId}:${item.token}`) ?? policy.index.get(`*:${item.token}`);
|
|
152
|
+
if (!hit) { unknownItems.push(item); continue; }
|
|
153
|
+
const prev = perBudget.has(hit.budget) ? perBudget.get(hit.budget) : 0n;
|
|
154
|
+
perBudget.set(hit.budget, prev === null || item.amount === null ? null : prev + scaled(item.amount, hit.decimals));
|
|
155
|
+
}
|
|
156
|
+
if (unknownItems.length || spend.unknown) {
|
|
157
|
+
if (policy.unknownTokens === "stop") hardStop = true;
|
|
158
|
+
if (policy.unknownTokens !== "allow") {
|
|
159
|
+
for (const item of unknownItems) reasons.push({ code: "unknown_token", token: item.token === NATIVE ? `${NATIVE_SYMBOL[item.chainId] ?? "native"} on chain ${item.chainId}` : item.token, amount: item.amount === null ? "unlimited" : item.amount.toString(), to: item.to, message: `${item.amount === null ? "unlimited" : item.amount.toString()} (raw units) of ${item.token === NATIVE ? "the native coin" : item.token} on chain ${item.chainId}, a token without a limit` });
|
|
160
|
+
if (spend.unknown) reasons.push({ code: "unknown_spend", message: "a signature whose spending could not be read" });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const charges = [];
|
|
164
|
+
for (const [name, total] of perBudget) {
|
|
165
|
+
const b = policy.budgets.get(name);
|
|
166
|
+
const u = used.get(name) ?? 0n;
|
|
167
|
+
if (b.perTx !== null && (total === null || total > b.perTx)) reasons.push({ code: "per_tx", budget: name, amount: fmt(total), limit: fmt(b.perTx), message: `${fmt(total)} ${name} is over the limit of ${fmt(b.perTx)} per transaction` });
|
|
168
|
+
if (b.perDay !== null && (total === null || u + total > b.perDay)) reasons.push({ code: "per_day", budget: name, amount: fmt(total), limit: fmt(b.perDay), used: fmt(u), message: `${fmt(total)} ${name} is over the limit of ${fmt(b.perDay)} per ${windowLabel(policy.windowMs)} (${fmt(u)} used)` });
|
|
169
|
+
// An approved unlimited allowance uses up what is left of the window.
|
|
170
|
+
charges.push({ budget: name, amount: total ?? (b.perDay !== null && b.perDay > u ? b.perDay - u : 0n) });
|
|
171
|
+
}
|
|
172
|
+
if (policy.allow) {
|
|
173
|
+
for (const c of new Set(spend.counterparties)) {
|
|
174
|
+
if (!c || !policy.allow.has(c)) reasons.push({ code: "not_allowed", to: c, message: `${short(c)} is not on the allow list` });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return { charges, reasons, hardStop };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const windowLabel = (ms) => (ms % 3_600_000 === 0 ? `${ms / 3_600_000}h` : `${ms / 60_000}m`);
|
|
181
|
+
|
|
182
|
+
// In memory: gone on a restart. Fine for a single run; use fileStore or your own store otherwise.
|
|
183
|
+
export function memoryStore() {
|
|
184
|
+
let entries = [];
|
|
185
|
+
return {
|
|
186
|
+
async add(entry) { entries.push(entry); },
|
|
187
|
+
async remove(id) { entries = entries.filter((e) => e.id !== id); },
|
|
188
|
+
async list(since) { entries = entries.filter((e) => e.at >= since - 31 * 86_400_000); return entries.filter((e) => e.at >= since); },
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
let seq = 0;
|
|
193
|
+
const newId = () => `${Date.now().toString(36)}-${(seq++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
194
|
+
|
|
195
|
+
// The limiter the wallet uses: one check at a time (so two parallel
|
|
196
|
+
// transactions cannot both fit in the last of a budget), booked before
|
|
197
|
+
// signing and given back when signing fails.
|
|
198
|
+
export function createLimiter(limits, { store = memoryStore(), onOverLimit, onSpend, now = () => Date.now() } = {}) {
|
|
199
|
+
const policy = normalizeLimits(limits);
|
|
200
|
+
if (onOverLimit !== undefined && typeof onOverLimit !== "function") throw new TypeError("onOverLimit must be a function");
|
|
201
|
+
if (onSpend !== undefined && typeof onSpend !== "function") throw new TypeError("onSpend must be a function");
|
|
202
|
+
for (const m of ["add", "remove", "list"]) if (typeof store?.[m] !== "function") throw new TypeError(`store must have add, remove and list (missing ${m})`);
|
|
203
|
+
let queue = Promise.resolve();
|
|
204
|
+
const locked = (fn) => { const run = queue.then(fn, fn); queue = run.catch(() => {}); return run; };
|
|
205
|
+
|
|
206
|
+
async function usedNow() {
|
|
207
|
+
const used = new Map();
|
|
208
|
+
for (const e of await store.list(now() - policy.windowMs + 1)) used.set(e.budget, (used.get(e.budget) ?? 0n) + BigInt(e.amount));
|
|
209
|
+
return used;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
policy,
|
|
214
|
+
// Resolves to { ok: true, entries } or { ok: false, hardStop, reasons, summary }.
|
|
215
|
+
reserve: (info) => locked(async () => {
|
|
216
|
+
const spend = spendFor(info.request, info.verdict);
|
|
217
|
+
const used = await usedNow();
|
|
218
|
+
const result = evaluate(policy, spend, used);
|
|
219
|
+
if (result.reasons.length) {
|
|
220
|
+
const summary = result.reasons.map((r) => r.message).join("; ");
|
|
221
|
+
if (result.hardStop || !onOverLimit) return { ok: false, ...result, summary };
|
|
222
|
+
const approved = (await onOverLimit({ method: info.method, request: info.request, verdict: info.verdict, reasons: result.reasons, summary, spending: await summarize(used) })) === true;
|
|
223
|
+
if (!approved) return { ok: false, ...result, summary, asked: true };
|
|
224
|
+
}
|
|
225
|
+
const entries = result.charges.filter((c) => c.amount > 0n).map((c) => ({ id: newId(), at: now(), budget: c.budget, amount: c.amount.toString(), method: info.method, chainId: info.request.chainId, to: spend.items[0]?.to ?? info.request.to ?? null }));
|
|
226
|
+
for (const e of entries) await store.add(e);
|
|
227
|
+
return { ok: true, entries };
|
|
228
|
+
}),
|
|
229
|
+
release: async (entries) => { for (const e of entries) await store.remove(e.id); },
|
|
230
|
+
spent(entries, result, info) {
|
|
231
|
+
if (!onSpend) return;
|
|
232
|
+
for (const e of entries) {
|
|
233
|
+
try { onSpend({ ...e, amount: formatUnits(BigInt(e.amount), SCALE), result, verdict: info.verdict ?? null, receiptId: info.verdict?.receipt?.request_id ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); }
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
spending: async () => summarize(await usedNow()),
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
async function summarize(used) {
|
|
240
|
+
return [...policy.budgets.values()].map((b) => {
|
|
241
|
+
const u = used.get(b.name) ?? 0n;
|
|
242
|
+
return { token: b.name, perTx: b.perTx === null ? null : fmt(b.perTx), perDay: b.perDay === null ? null : fmt(b.perDay), used: fmt(u), left: b.perDay === null ? null : fmt(b.perDay > u ? b.perDay - u : 0n) };
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "presign-guard-wallet",
|
|
3
|
-
"version": "0.
|
|
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,
|
|
3
|
+
"version": "0.4.0",
|
|
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": {
|
|
7
7
|
".": {
|
|
8
8
|
"types": "./index.d.ts",
|
|
9
9
|
"default": "./index.js"
|
|
10
|
+
},
|
|
11
|
+
"./file-store": {
|
|
12
|
+
"types": "./file-store.d.ts",
|
|
13
|
+
"default": "./file-store.js"
|
|
14
|
+
},
|
|
15
|
+
"./telegram": {
|
|
16
|
+
"types": "./telegram.d.ts",
|
|
17
|
+
"default": "./telegram.js"
|
|
10
18
|
}
|
|
11
19
|
},
|
|
12
20
|
"main": "./index.js",
|
|
@@ -14,6 +22,11 @@
|
|
|
14
22
|
"files": [
|
|
15
23
|
"index.js",
|
|
16
24
|
"index.d.ts",
|
|
25
|
+
"limits.js",
|
|
26
|
+
"file-store.js",
|
|
27
|
+
"file-store.d.ts",
|
|
28
|
+
"telegram.js",
|
|
29
|
+
"telegram.d.ts",
|
|
17
30
|
"README.md",
|
|
18
31
|
"LICENSE"
|
|
19
32
|
],
|
|
@@ -44,7 +57,11 @@
|
|
|
44
57
|
"approvals",
|
|
45
58
|
"permit2",
|
|
46
59
|
"drainer",
|
|
47
|
-
"usdc"
|
|
60
|
+
"usdc",
|
|
61
|
+
"spending-limits",
|
|
62
|
+
"budget",
|
|
63
|
+
"telegram",
|
|
64
|
+
"human-in-the-loop"
|
|
48
65
|
],
|
|
49
66
|
"repository": {
|
|
50
67
|
"type": "git",
|
package/telegram.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { OverLimitInfo } from "./index.js";
|
|
2
|
+
|
|
3
|
+
export interface TelegramApproverOptions {
|
|
4
|
+
/** Bot token from @BotFather. A secret: keep it in an environment variable. */
|
|
5
|
+
token: string;
|
|
6
|
+
/** Your chat with the bot: send it /start, then findTelegramChats({ token }). */
|
|
7
|
+
chatId: string | number;
|
|
8
|
+
/** Telegram user ids allowed to answer. Default: chatId (you, in a private chat). */
|
|
9
|
+
allowedUserIds?: Array<string | number>;
|
|
10
|
+
/** How long the agent waits for your tap. Default 10 minutes; no answer counts as Deny. */
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
/** Name of the agent in the message. Default "Your agent". */
|
|
13
|
+
label?: string;
|
|
14
|
+
fetch?: typeof globalThis.fetch;
|
|
15
|
+
api?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** An onOverLimit for guardWallet: asks you on Telegram with Approve and Deny buttons. */
|
|
19
|
+
export declare function telegramApprover(options: TelegramApproverOptions): (info: OverLimitInfo) => Promise<boolean>;
|
|
20
|
+
|
|
21
|
+
/** The chats that sent your bot a message (send it /start first). */
|
|
22
|
+
export declare function findTelegramChats(options: { token: string; fetch?: typeof globalThis.fetch; api?: string }): Promise<Array<{ chatId: number; type: string; name: string; username: string | null }>>;
|
package/telegram.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// Approve over-limit signatures from your phone, with a Telegram bot.
|
|
2
|
+
//
|
|
3
|
+
// import { telegramApprover } from "presign-guard-wallet/telegram";
|
|
4
|
+
// guardWallet(walletClient, { pay, limits, onOverLimit: telegramApprover({ token, chatId }) });
|
|
5
|
+
//
|
|
6
|
+
// When a signature would cross a limit, the bot sends you a message with what
|
|
7
|
+
// the agent wants to sign, why it is over the limit and presign-guard's verdict,
|
|
8
|
+
// with Approve and Deny buttons. The agent waits for your tap (default 10
|
|
9
|
+
// minutes); no answer in time counts as Deny. Only the people you allow
|
|
10
|
+
// (default: the chat itself, i.e. you in a private chat) can answer.
|
|
11
|
+
//
|
|
12
|
+
// No server needed: the wallet asks Telegram for button taps itself (long
|
|
13
|
+
// polling, getUpdates). So the bot must not have a webhook, and only one
|
|
14
|
+
// process at a time can poll one bot: give each agent process its own bot.
|
|
15
|
+
// The bot token is a secret: keep it in an environment variable.
|
|
16
|
+
|
|
17
|
+
const API = "https://api.telegram.org";
|
|
18
|
+
const escape = (s) => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
19
|
+
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
|
|
20
|
+
|
|
21
|
+
function client(token, fetchImpl, api) {
|
|
22
|
+
if (typeof token !== "string" || !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token)) throw new TypeError("token must be a Telegram bot token (123456:ABC…), from @BotFather");
|
|
23
|
+
return async (method, body, signal) => {
|
|
24
|
+
const res = await fetchImpl(`${api}/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body ?? {}), signal });
|
|
25
|
+
const data = await res.json().catch(() => null);
|
|
26
|
+
if (!data?.ok) {
|
|
27
|
+
const err = new Error(`Telegram ${method} failed: ${data?.description ?? `HTTP ${res.status}`}`);
|
|
28
|
+
err.status = data?.error_code ?? res.status;
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
return data.result;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// One poller per bot token in this process, shared by every waiting request.
|
|
36
|
+
const pollers = new Map();
|
|
37
|
+
function poller(token, call) {
|
|
38
|
+
let p = pollers.get(token);
|
|
39
|
+
if (p) return p;
|
|
40
|
+
p = { waiters: new Map(), offset: undefined, running: false, abort: null };
|
|
41
|
+
pollers.set(token, p);
|
|
42
|
+
p.start = () => {
|
|
43
|
+
if (p.running) return;
|
|
44
|
+
p.running = true;
|
|
45
|
+
(async () => {
|
|
46
|
+
while (p.waiters.size) {
|
|
47
|
+
p.abort = new AbortController();
|
|
48
|
+
let updates;
|
|
49
|
+
try {
|
|
50
|
+
updates = await call("getUpdates", { offset: p.offset, timeout: 25, allowed_updates: ["callback_query"] }, p.abort.signal);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (!p.waiters.size) break; // aborted because nobody waits any more
|
|
53
|
+
if (err.status === 409 || err.status === 401 || err.status === 404) {
|
|
54
|
+
// A webhook, another process polling this bot, or a bad token: nobody can answer.
|
|
55
|
+
for (const w of p.waiters.values()) w.fail(err);
|
|
56
|
+
p.waiters.clear();
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
await new Promise((ok) => setTimeout(ok, 2000)); // network hiccup: try again
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
for (const u of updates) {
|
|
63
|
+
p.offset = u.update_id + 1;
|
|
64
|
+
const q = u.callback_query;
|
|
65
|
+
const m = /^pgw:([a-z0-9]+):(y|n)$/.exec(q?.data ?? "");
|
|
66
|
+
const w = m && p.waiters.get(m[1]);
|
|
67
|
+
if (!w) { if (q?.id && m) call("answerCallbackQuery", { callback_query_id: q.id, text: "This request has already been decided or expired." }).catch(() => {}); continue; }
|
|
68
|
+
if (!w.allowed(q)) { call("answerCallbackQuery", { callback_query_id: q.id, text: "You are not allowed to answer this." }).catch(() => {}); continue; }
|
|
69
|
+
w.decide(m[2] === "y", q);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
p.running = false;
|
|
73
|
+
if (p.waiters.size) p.start(); // someone started waiting while this loop was ending
|
|
74
|
+
})();
|
|
75
|
+
};
|
|
76
|
+
p.stopIfIdle = () => { if (!p.waiters.size) p.abort?.abort(); };
|
|
77
|
+
return p;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function messageFor(info, label) {
|
|
81
|
+
const lines = [`<b>${escape(label)} wants to sign something over your limit</b>`, ""];
|
|
82
|
+
lines.push(escape(info.summary));
|
|
83
|
+
const r = info.request ?? {};
|
|
84
|
+
lines.push("", `<code>${escape(info.method)}</code> · chain ${escape(r.chainId)}${r.to ? ` · to <code>${escape(r.to)}</code>` : ""}`);
|
|
85
|
+
const v = info.verdict?.verdict;
|
|
86
|
+
if (v) {
|
|
87
|
+
const codes = (info.verdict.reasons ?? []).filter((x) => x.severity !== "info").map((x) => x.code).join(", ");
|
|
88
|
+
lines.push(`presign-guard: <b>${escape(v)}</b>${codes ? ` (${escape(codes)})` : ""}`);
|
|
89
|
+
} else lines.push("presign-guard: no verdict for this one");
|
|
90
|
+
const spent = (info.spending ?? []).map((s) => `${escape(s.token)} ${escape(s.used)}${s.perDay ? ` / ${escape(s.perDay)}` : ""}`).join(" · ");
|
|
91
|
+
if (spent) lines.push(`spent this window: ${spent}`);
|
|
92
|
+
return lines.join("\n");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* An onOverLimit for guardWallet that asks you on Telegram.
|
|
97
|
+
* @param {object} o
|
|
98
|
+
* @param {string} o.token bot token from @BotFather (keep it in an env var)
|
|
99
|
+
* @param {string|number} o.chatId your chat with the bot (see findTelegramChats)
|
|
100
|
+
* @param {Array<string|number>} [o.allowedUserIds] who may answer (default: chatId)
|
|
101
|
+
* @param {number} [o.timeoutMs] how long the agent waits (default 10 minutes); no answer = deny
|
|
102
|
+
* @param {string} [o.label] name of the agent in the message (default "Your agent")
|
|
103
|
+
* @param {typeof fetch} [o.fetch]
|
|
104
|
+
* @param {string} [o.api]
|
|
105
|
+
*/
|
|
106
|
+
export function telegramApprover({ token, chatId, allowedUserIds, timeoutMs = 600_000, label = "Your agent", fetch: fetchImpl = globalThis.fetch, api = API } = {}) {
|
|
107
|
+
const call = client(token, fetchImpl, api);
|
|
108
|
+
if (chatId === undefined || chatId === null || chatId === "") throw new TypeError("chatId is required (send /start to your bot, then findTelegramChats({ token }))");
|
|
109
|
+
if (!(timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number of milliseconds");
|
|
110
|
+
const allowedIds = new Set((allowedUserIds ?? [chatId]).map(String));
|
|
111
|
+
|
|
112
|
+
return async function onOverLimit(info) {
|
|
113
|
+
const id = nonce();
|
|
114
|
+
const sent = await call("sendMessage", {
|
|
115
|
+
chat_id: chatId,
|
|
116
|
+
text: messageFor(info, label),
|
|
117
|
+
parse_mode: "HTML",
|
|
118
|
+
disable_web_page_preview: true,
|
|
119
|
+
reply_markup: { inline_keyboard: [[{ text: "Approve", callback_data: `pgw:${id}:y` }, { text: "Deny", callback_data: `pgw:${id}:n` }]] },
|
|
120
|
+
});
|
|
121
|
+
const p = poller(token, call);
|
|
122
|
+
const answer = await new Promise((resolve, reject) => {
|
|
123
|
+
const timer = setTimeout(() => { p.waiters.delete(id); p.stopIfIdle(); resolve({ ok: false, timeout: true }); }, timeoutMs);
|
|
124
|
+
p.waiters.set(id, {
|
|
125
|
+
allowed: (q) => allowedIds.has(String(q.from?.id)) && String(q.message?.chat?.id) === String(chatId),
|
|
126
|
+
decide: (ok, q) => { clearTimeout(timer); p.waiters.delete(id); p.stopIfIdle(); resolve({ ok, q }); },
|
|
127
|
+
fail: (err) => { clearTimeout(timer); reject(err); },
|
|
128
|
+
});
|
|
129
|
+
p.start();
|
|
130
|
+
});
|
|
131
|
+
const who = answer.q?.from?.username ? `@${answer.q.from.username}` : answer.q?.from?.first_name ?? "you";
|
|
132
|
+
const outcome = answer.timeout ? `<b>No answer in ${Math.round(timeoutMs / 60_000) || 1} min: not signed.</b>` : answer.ok ? `<b>Approved by ${escape(who)}: signing.</b>` : `<b>Denied by ${escape(who)}: not signed.</b>`;
|
|
133
|
+
if (answer.q?.id) call("answerCallbackQuery", { callback_query_id: answer.q.id, text: answer.ok ? "Approved" : "Denied" }).catch(() => {});
|
|
134
|
+
call("editMessageText", { chat_id: chatId, message_id: sent.message_id, text: `${messageFor(info, label)}\n\n${outcome}`, parse_mode: "HTML", disable_web_page_preview: true }).catch(() => {});
|
|
135
|
+
return answer.ok === true;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The chats that sent your bot a message (send it /start first). Use the chatId of yours.
|
|
141
|
+
* @returns {Promise<Array<{chatId: number, type: string, name: string, username: string|null}>>}
|
|
142
|
+
*/
|
|
143
|
+
export async function findTelegramChats({ token, fetch: fetchImpl = globalThis.fetch, api = API } = {}) {
|
|
144
|
+
const call = client(token, fetchImpl, api);
|
|
145
|
+
const updates = await call("getUpdates", { timeout: 0, allowed_updates: ["message"] });
|
|
146
|
+
const chats = new Map();
|
|
147
|
+
for (const u of updates) {
|
|
148
|
+
const c = u.message?.chat;
|
|
149
|
+
if (c) chats.set(c.id, { chatId: c.id, type: c.type, name: [c.first_name, c.last_name].filter(Boolean).join(" ") || c.title || "", username: c.username ?? null });
|
|
150
|
+
}
|
|
151
|
+
return [...chats.values()];
|
|
152
|
+
}
|