@tollxyz/guard 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,381 +1,465 @@
1
- # @tollxyz/guard
2
-
3
- > **New in 0.4.0: spend caps, allowlists, human approval and preview** (`spend` option). Unset, nothing changes.
4
- > See [0.4.0: spend caps, allowlists, approval, preview](#040-spend-caps-allowlists-approval-preview).
5
-
6
- > **0.3.1:** `signTypedData` (viem and ethers) now sends the signing account as `from`, so Toll can say what a Permit2 signature lets someone take.
7
- >
8
- > **What changed in 0.3.0: every signing method is checked.**
9
- > - Messages: viem and ethers `signMessage`, and `request()` for `personal_sign` and `eth_sign`.
10
- > - Typed data: `request()` for `eth_signTypedData_v4` too, any EIP-712 (orders, permits, sign-ins).
11
- > - Batches: viem `sendCalls` (EIP-5792) and `request()` for `wallet_sendCalls`, each call checked.
12
- > - Smart accounts: `guardSmartAccount` wraps a viem bundler client's `sendUserOperation` and `prepareUserOperation`;
13
- > `guard()` picks it for a bundler client.
14
- > - EIP-7702: `onAuthorization` now defaults to `"check"`: Toll reads the authorization and decides (a known, verified
15
- > delegate is WARN medium and goes ahead under `block-high`; an unknown one is BLOCK). `"block"` and `"allow"` stay.
16
- > An authorization Toll cannot read is blocked.
17
- > - A signature for another chain is blocked (before 0.3.0 it went through as unsupported); `onUnsupported: "allow"`
18
- > lets it through.
19
- > - `eth_sign` always fails closed: it can sign any 32 bytes, a transaction included, so when Toll cannot answer it is
20
- > blocked whatever `onUnavailable` says.
21
-
22
- > **Defaults changed in 0.2.0.** A WARN with any `high` or `critical` warning is now blocked (`onWarn: "block-high"`,
23
- > the new default); a WARN with only `medium`/`low` warnings still goes ahead, logged. To keep the 0.1.x behaviour,
24
- > pass `onWarn: "allow"`. New `strict: true` preset: WARN, unavailable and unsupported all block. Any option you pass
25
- > explicitly still wins over the preset (`{ strict: true, onUnavailable: "allow" }` stays fail-open).
26
-
27
- Toll's live pre-sign check in front of an AI agent's wallet. Before the agent signs a transaction, a message, an
28
- EIP-712 signature, a batch, a user operation, an EIP-7702 authorization or an x402 payment on Robinhood Chain, the guard asks [Toll](https://t0ll.xyz/agents/x402#presign) and
29
- gets ALLOW / WARN / BLOCK with the reasons. Zero runtime dependencies, ESM only, Node >= 20.19, with types.
30
-
31
- ```sh
32
- npm install @tollxyz/guard
33
- ```
34
-
35
- ```ts
36
- const wallet = guard(walletClient); // viem WalletClient, viem bundler client or ethers v6 Signer; same methods, checked first
37
- ```
38
-
39
- ```ts
40
- import { guard, TollBlockedError } from "@tollxyz/guard";
41
-
42
- const wallet = guard(walletClient, { onWarn: "block-high", onUnavailable: "allow" });
43
- try {
44
- await wallet.writeContract({ address: token, abi: erc20Abi, functionName: "approve", args: [spender, maxUint256] });
45
- } catch (e) {
46
- if (e instanceof TollBlockedError) console.log(e.codes, e.assessment); // not signed
47
- else throw e;
48
- }
49
- ```
50
-
51
- Run it as an ES module (an `.mjs`/`.mts` file, or `"type": "module"` in package.json).
52
-
53
- Toll states facts, never says safe: ALLOW means none of the checks Toll runs found a reason to stop, nothing more.
54
- Information only, not financial advice.
55
-
56
- ## Gate a buy in one call
57
-
58
- Before your agent even builds the swap, ask for one word with `@tollxyz/sdk`:
59
-
60
- ```ts
61
- import { Toll } from "@tollxyz/sdk";
62
- const toll = new Toll();
63
- const r = await toll.preBuyCheck(token); // Decision: BLOCK / WARN / ALLOW / WAIT, up to 3 reasons
64
- if (r.decision === "BLOCK") throw new Error(r.text); // the owner decides, never the agent
65
- if (r.decision === "WAIT") await sleep(r.pending!.retryAfterS * 1000); // part of the coin is still being read
66
- ```
67
-
68
- It runs the same calibrated rules as the guard's swap check (BLOCK = a finding whose coins rugged at 40% or more
69
- within 24 h, or sells that fail), so the gate and the guard never disagree. Then let `guardViem` / `guardEthers`
70
- check the transaction itself when it is signed.
71
-
72
- ## What is checked
73
-
74
- Every check runs on Toll's server (`POST https://t0ll.xyz/api/tx/check`), so new checks reach you without a package
75
- update. The full list is at <https://t0ll.xyz/agents/x402#presign>: what the calldata or signature does (approvals,
76
- Permit / Permit2, transfers, swaps), unlimited approvals and approvals to a wallet instead of a contract, spenders and
77
- recipients Toll has flagged, a swap that pays someone else, the coin a swap buys (Toll's coin check: who is behind
78
- it), and for x402 the payee against the seller's registered ERC-8004 agentWallet (including `extra.erc8004`).
79
-
80
- The answer is an [ERC-8265](https://github.com/ethereum/ERCs/pull/1753) RiskAssessment:
81
- `{ action, warnings: [{ code, severity, message, "x-toll-evidence" }], scanners, "x-toll": { decoded, link, checked_at, note } }`.
82
- Critical = BLOCK, high or medium = WARN, low or none = ALLOW.
83
-
84
- Robinhood Chain (4663) only for now. A transaction on another chain, or a contract deployment, is not sent to Toll
85
- and goes through (`onUnsupported: "block"` to stop it instead). A signature for another chain is blocked
86
- (`onUnsupported: "allow"` lets it through).
87
-
88
- ## API
89
-
90
- ### `guard(wallet, opts?)`, `guardViem(client, opts?)`, `guardSmartAccount(bundler, opts?)`, `guardEthers(signer, opts?)`
91
-
92
- Returns the same wallet behind a Proxy. Checked first:
93
-
94
- - viem WalletClient: `sendTransaction`, `writeContract` (calldata encoded with your viem's `encodeFunctionData`),
95
- `signTransaction`, `signTypedData`, `signMessage`, `sendCalls`, `signAuthorization`, and `request()` for
96
- `eth_sendTransaction`, `eth_signTransaction`, `personal_sign`, `eth_sign`, `eth_signTypedData_v4` and
97
- `wallet_sendCalls` (every other method passes through)
98
- - viem bundler client (account abstraction): `sendUserOperation`, `prepareUserOperation`. `calls` are checked one by
99
- one as transactions from the smart account's address; a ready `callData` is sent as a user operation with the
100
- account's EntryPoint
101
- - ethers v6 Signer: `sendTransaction`, `signTransaction`, `signTypedData`, `signMessage`, `authorize`
102
-
103
- A batch is checked call by call, in order; the first call blocked stops the whole batch.
104
-
105
- An EIP-7702 authorization sets the wallet's code to another contract, which can then move everything it holds: a
106
- transaction with an `authorizationList` on any method above, viem's `signAuthorization`, ethers' `authorize`, a user
107
- operation's `authorization`. By default (`onAuthorization: "check"`) Toll reads it and decides; if Toll cannot read it
108
- (unreachable, another chain) it is blocked (TollBlockedError, code `eip7702-authorization`). `"block"` refuses every
109
- authorization without asking; `"allow"` lets it through unchecked. The account's own sign methods
110
- (`client.account.sign*`) are not wrapped.
111
-
112
- ```ts
113
- const wallet = guard(walletClient, { origin: "https://app.example" }); // origin: the site asking, for sign-ins
114
- await wallet.signMessage({ message: "Sign in to app.example" }); // checked as personal_sign
115
- await wallet.request({ method: "personal_sign", params: [hexMessage, address] });
116
- await wallet.request({ method: "eth_sign", params: [address, hash] }); // blocked when Toll blocks it, or cannot answer
117
-
118
- const smart = guard(bundlerClient); // detected by sendUserOperation
119
- await smart.sendUserOperation({ calls: [{ to: token, abi: erc20Abi, functionName: "transfer", args: [to, amount] }] });
120
- ```
121
-
122
- Everything else passes through unchanged. Wrap last: `client.extend(...)` or `signer.connect(...)` on the wrapped
123
- wallet returns an unguarded one. viem and ethers are optional peer dependencies, never imported at load time.
124
-
125
- ### `guardX402Fetch(fetch, opts?)`
126
-
127
- Wraps the fetch your x402 client uses. When a 402 arrives, its payment requirement goes to Toll before the client
128
- pays; on BLOCK the 402 never reaches the payer (TollBlockedError is thrown). The paid retry (a request with a
129
- `PAYMENT-SIGNATURE` or `X-PAYMENT` header) and every non-402 answer pass through.
130
-
131
- A 402 can carry its requirement in the `PAYMENT-REQUIRED` header and in the JSON body, and a client pays from the one
132
- it reads (`x402-fetch` v1 reads the body). The guard reads both: when they ask for different payments (payee, amount,
133
- asset or scheme), it blocks without asking Toll (code `x402-forms-differ`).
134
-
135
- ```ts
136
- import { wrapFetchWithPayment } from "x402-fetch";
137
- const pay = wrapFetchWithPayment(guardX402Fetch(fetch, { agentId: 123 }), account);
138
- ```
139
-
140
- `agentId` (the seller's ERC-8004 id, or a function of the URL) is optional.
141
-
142
- ### `checkTx(input, opts?)`
143
-
144
- The raw call. `input`: `{ chainId, from, to, data, value, authorizationList? }` for a transaction,
145
- `{ chainId, from, authorizationList }` for an authorization alone, `{ typedData }` for an EIP-712 request,
146
- `{ message: { kind: "personal_sign" | "eth_sign", data, from? } }` for a message, `{ rpc: { method, params } }` for a
147
- wallet request (`personal_sign`, `eth_sign`, `eth_signTypedData_v4`, `eth_sendTransaction`), `{ userOp, entryPoint? }`
148
- for an ERC-4337 user operation, `{ x402, agentId?, payment? }` for an x402 payment, or several together; `origin` is
149
- the site asking. Returns the RiskAssessment. When a
150
- coin is still being read, Toll answers WARN `coin-not-read` with `Retry-After`: `checkTx` asks once more if the wait
151
- is at most `maxRetryWaitMs` (default 10 s); a coin still not read stays WARN, never ALLOW. Throws
152
- `TollUnavailableError` when Toll cannot answer.
153
-
154
- ### Options
155
-
156
- | Option | Default | |
157
- | --- | --- | --- |
158
- | `strict` | `false` | preset: the defaults of `onWarn`, `onUnavailable` and `onUnsupported` become `"block"`; each one passed explicitly still wins |
159
- | `onWarn` | `"block-high"` | `"block-high"` (blocked when any warning is `high` or `critical`, else allowed and logged), `"allow"` (every WARN goes ahead, logged; the 0.1.x default), `"block"`, or `(assessment) => boolean` (true lets it through) |
160
- | `onBlock` | `"throw"` | `"throw"` (TollBlockedError), or `(assessment) => boolean`, e.g. ask a human; true lets it through |
161
- | `onUnavailable` | `"allow"` (`strict`: `"block"`) | Toll unreachable, timed out, 5xx, 429, or a request it could not read: `"allow"` (fail-open, logged) or `"block"` (fail-closed, TollUnavailableError) |
162
- | `onUnsupported` | `"allow"` (`strict`: `"block"`) | a transaction on another chain, a deployment: `"allow"` or `"block"`. A signature for another chain is blocked unless this is `"allow"` explicitly |
163
- | `onAuthorization` | `"check"` | an EIP-7702 authorization: `"check"` (Toll decides; blocked when Toll cannot read it), `"block"` (TollBlockedError, Toll not asked) or `"allow"` (unchecked, logged) |
164
- | `origin` | none | the site asking for a signature, sent with messages and typed data |
165
- | `onReport` | none | `(report) => void`: every decision, with `assessment`, `decision`, `basis`, `paidUrl` |
166
- | `logger` | `console.warn` | where WARN and unavailable lines go; `false` = silent |
167
- | `timeoutMs` | `15000` | one request to Toll |
168
- | `retry`, `maxRetryWaitMs` | `true`, `10000` | the one retry after Retry-After |
169
- | `baseUrl`, `fetch` | `https://t0ll.xyz`, global fetch | |
170
- | `spend` | none | 0.4.0: caps, allowlists, approval ([below](#040-spend-caps-allowlists-approval-preview)); unset = 0.3.x behaviour |
171
- | `store` | in-process `MemorySpendStore` | where spend counters and paid x402 ids live |
172
- | `failClosed` | `false` | with `spend`: a request whose spend cannot be read is blocked |
173
-
174
- Errors: `TollBlockedError` (`.assessment`, `.codes`, message lists each code and message) and
175
- `TollUnavailableError` (`.reason`, `.status`, `.paidUrl`).
176
-
177
- ## 0.4.0: spend caps, allowlists, approval, preview
178
-
179
- Toll's verdict says whether a request looks safe. `spend` adds your own limits on top: how much the agent may spend
180
- per call and per UTC day, who it may pay, and when a human has to say yes. Without `spend` nothing changes: 0.4.0
181
- behaves exactly like 0.3.x.
182
-
183
- The order for every request:
184
-
185
- 1. **Allowlists** (`allow.to`, `allow.spender`, `allow.payTo`): read from the request itself, before Toll is asked.
186
- Off the list = blocked, and Toll is not called.
187
- 2. **Toll's verdict**: ALLOW / WARN / BLOCK with your `onWarn`, `onBlock`, `onUnavailable` as before. A WARN that
188
- `block-high` blocks is still blocked, however small the amount.
189
- 3. **Caps** (`assets`, `perEndpoint`): per call, then per day. The day amount is reserved.
190
- 4. **Approval** (`approveAbove` + `approve`): above the threshold your `approve` function decides.
191
- 5. **After the send**: the reservation is committed. If the send throws (rejected, nonce too low, RPC down), it is
192
- released, so failures never use up the day cap.
193
-
194
- Caps never relax Toll's verdict, and Toll's ALLOW never lifts a cap: a request must pass both.
195
-
196
- ```ts
197
- import { guard, NATIVE, USDG, TollPolicyError } from "@tollxyz/guard";
198
-
199
- const wallet = guard(walletClient, {
200
- spend: {
201
- // base units: ETH in wei, USDG with 6 decimals
202
- assets: {
203
- [NATIVE]: { perCall: 10n ** 16n, perDay: 5n * 10n ** 16n }, // 0.01 ETH a call, 0.05 ETH a day
204
- [USDG]: { perCall: 20_000_000n, perDay: 100_000_000n }, // 20 USDG a call, 100 USDG a day
205
- },
206
- allow: { spender: ["0xYourRouter..."] }, // approvals only to your router
207
- approveAbove: { [USDG]: 10_000_000n }, // above 10 USDG a human decides
208
- approve: async (req) => {
209
- const ok = await askOnTelegram(`Spend ${req.over[0].amount} of ${req.over[0].asset}?`);
210
- return { approved: ok, approvalRef: ok ? "tg-msg-1234" : undefined };
211
- },
212
- },
213
- failClosed: true, // a contract call whose spend cannot be read is blocked
214
- });
215
-
216
- try {
217
- await wallet.sendTransaction(tx);
218
- } catch (e) {
219
- if (e instanceof TollPolicyError) console.log(e.code, e.amount, e.limit); // "cap-per-day", ...
220
- else throw e;
221
- }
222
- ```
223
-
224
- **What counts as spend.** Only what leaves the wallet in a spend asset. The defaults are native ETH, WETH and USDG on
225
- Robinhood Chain, plus every asset you name in `assets` or `approveAbove`. A sell of any other coin is never capped.
226
-
227
- - Read locally, with no Toll answer needed: the transaction's value, ERC-20 `transfer` / `transferFrom` / `approve` /
228
- `increaseAllowance` on a spend asset, EIP-2612 permits, Permit2 permits, EIP-3009 transfer authorizations, and an
229
- x402 402's amount. So caps hold even when Toll is unreachable.
230
- - Any other contract call (a swap, a router): the amount comes from Toll's simulation (`x-toll.simulation.deltas`).
231
- When the simulation shows more leaving than the call declares, the larger amount counts.
232
- - An approval counts against the per-call cap at its full size (an unlimited approval is over any cap) and must fit
233
- in what is left of the day cap; it is not added to the day total (the later swap is).
234
- - Unknown spend: a contract call with no simulation (Toll unreachable), a raw user operation, a bare EIP-7702
235
- authorization. `onUnknownSpend` decides: `"allow"` by default, `"block"` under `failClosed: true`.
236
-
237
- | `spend` field | |
238
- | --- | --- |
239
- | `assets` | `{ [asset]: { perCall?, perDay? } }`, asset = `"native"` or a token address, amounts in base units |
240
- | `perEndpoint` | x402 caps per URL prefix (origin + path), e.g. `{ "https://api.example.com/v1/": { perDay: 1_000_000n } }` |
241
- | `allow` | `{ to?, spender?, payTo? }`: every recipient (or called contract), approval spender, x402 payee must be listed |
242
- | `approveAbove` | `{ [asset]: amount }`: above it, `approve` must say yes |
243
- | `approve` | `(req) => Promise<{ approved, approvalRef? }>`; no function = denied. `approvalRef` lands in `report.spend.approvalRef` |
244
- | `onUnknownSpend` | `"allow"` (default) or `"block"` (default under `failClosed`) |
245
-
246
- New options next to `spend`: `store` (where counters live, below) and `failClosed`.
247
-
248
- `TollPolicyError` extends `TollBlockedError` (existing `catch` blocks still see a block). `.code` is one of
249
- `not-allowlisted`, `cap-per-call`, `cap-per-day`, `cap-endpoint`, `approval-denied`, `duplicate-payment`,
250
- `unknown-spend`; `.asset`, `.amount`, `.limit` when they apply. The report has `basis: "policy"` and `policy: code`.
251
-
252
- ### Preview, then confirm
253
-
254
- ```ts
255
- import { preview } from "@tollxyz/guard";
256
-
257
- const p = await preview({ chainId: 4663, from, to, data, value }, opts); // same opts as the guard
258
- // p.decision "allowed" | "blocked", p.basis, p.policy, p.spend, p.needsApproval, p.reason
259
- if (p.decision === "allowed") await wallet.sendTransaction({ to, data, value, tollConfirm: p.confirmId });
260
- ```
261
-
262
- `preview` asks Toll and checks every rule, but reserves nothing, calls no `approve` and no `onReport`. Passing its
263
- `confirmId` as `tollConfirm` within 30 seconds reuses that Toll answer (one Toll call instead of two). It is used
264
- once, and only for the identical request; anything else is checked again. The guard strips `tollConfirm` before the
265
- wallet sees the request (viem `sendTransaction` / `signTransaction` / `writeContract`, ethers `sendTransaction` /
266
- `signTransaction`).
267
-
268
- ### x402: payment ids and per-endpoint caps
269
-
270
- With `spend` set, `guardX402Fetch` also:
271
-
272
- - counts a 402's amount against `assets` and `perEndpoint` caps when it is checked. The reservation waits for the
273
- paid retry: committed when the seller answers, released on another 402 or an error, released after `holdMs`
274
- (default 2 minutes) when no paid retry comes.
275
- - never pays the same x402 `payment-identifier` twice. An id is marked paid only when the seller accepts the paid
276
- request (any answer but 402); sending that id again throws `TollPolicyError` `duplicate-payment` (ids are kept
277
- `paymentIdTtlS`, default 1 day). A second send of an id that is still in flight is refused too. After a network
278
- error or timeout the same id may be retried (the seller dedupes it): the retry reuses the reservation of its 402,
279
- so nothing is counted twice. A different id is a new payment.
280
-
281
- ### Where the counters live
282
-
283
- The default store is a `MemorySpendStore` in this process, one per `spend` object. **It resets when the process
284
- restarts and is not shared between processes**: two workers each get the full day cap. For a cap that survives
285
- restarts or spans workers, pass your own `store` implementing `SpendStore`:
286
-
287
- ```ts
288
- interface SpendStore {
289
- reserve(k: string, amt: bigint, limit: bigint, windowStart: number): Promise<{ ok: boolean; id: string; used: bigint }>;
290
- commit(id: string): Promise<void>;
291
- release(id: string): Promise<void>;
292
- paymentSeen(id: string): Promise<boolean>;
293
- markPaid(id: string, ttlS: number): Promise<void>;
294
- }
295
- ```
296
-
297
- A Redis store (example only, not shipped; `reserve` must be atomic, hence the Lua script):
298
-
299
- ```ts
300
- import Redis from "ioredis";
301
- import type { SpendStore } from "@tollxyz/guard";
302
-
303
- const redis = new Redis(process.env.REDIS_URL!);
304
- const RESERVE = `
305
- local used = tonumber(redis.call('GET', KEYS[1]) or '0')
306
- local amt, limit = tonumber(ARGV[1]), tonumber(ARGV[2])
307
- if used + amt > limit then return {0, tostring(used)} end
308
- redis.call('INCRBY', KEYS[1], ARGV[1])
309
- redis.call('EXPIRE', KEYS[1], 172800)
310
- redis.call('SET', KEYS[2], KEYS[1] .. '|' .. ARGV[1], 'EX', 3600)
311
- return {1, tostring(used + amt)}`;
312
- const RELEASE = `
313
- local v = redis.call('GET', KEYS[1])
314
- if not v then return 0 end
315
- local sep = string.find(v, '|', 1, true)
316
- redis.call('DECRBY', string.sub(v, 1, sep - 1), string.sub(v, sep + 1))
317
- redis.call('DEL', KEYS[1])
318
- return 1`;
319
-
320
- export const redisStore: SpendStore = {
321
- async reserve(k, amt, limit, windowStart) {
322
- const id = `toll:res:${crypto.randomUUID()}`;
323
- // amounts as numbers in Lua: fine below 2^53 base units; use string math for larger caps
324
- const [ok, used] = (await redis.eval(RESERVE, 2, `toll:cap:${k}:${windowStart}`, id, amt.toString(), limit.toString())) as [number, string];
325
- return { ok: ok === 1, id: ok === 1 ? id : "", used: BigInt(used) };
326
- },
327
- async commit(id) { await redis.del(id); }, // the amount stays in the day counter
328
- async release(id) { await redis.eval(RELEASE, 1, id); },
329
- async paymentSeen(id) { return (await redis.exists(`toll:paid:${id}`)) === 1; },
330
- async markPaid(id, ttlS) { await redis.set(`toll:paid:${id}`, "1", "EX", ttlS); },
331
- };
332
-
333
- const wallet = guard(walletClient, { spend: { /* ... */ }, store: redisStore });
334
- ```
335
-
336
- ## Fail-open or fail-closed
337
-
338
- The default is fail-open: if Toll cannot answer, the signature goes ahead, with a `[toll-guard] ... NOT checked`
339
- line and an `onReport` call with `basis: "unavailable"`. The agent must never get stuck because of Toll, and the
340
- free route is rate limited per IP (a busy agent will see 429s). If an unchecked signature is worse for you than a
341
- stalled agent, set `onUnavailable: "block"` (or `strict: true`, which also blocks every WARN and unsupported request).
342
-
343
- Two requests fail closed whatever `onUnavailable` says: `eth_sign` (it signs any 32 bytes, a transaction hash
344
- included, so an unchecked one could be anything) and an EIP-7702 authorization under `onAuthorization: "check"`.
345
-
346
- ## Free limit and the paid route
347
-
348
- The check is free, rate limited per IP. The coin a swap buys is read through the same free coins as Toll's coin
349
- check (10 new coins a day per caller, coins already read stay free); past that the coin is not read and the answer
350
- is WARN `coin-over-quota` naming the paid route, `https://t0ll.xyz/api/x402/tx` (0.005 USDG over x402, no daily
351
- limit). The guard never pays: it puts that URL in the log line, in `report.paidUrl` and in `paidUrlOf(assessment)`.
352
-
353
- ## Privacy
354
-
355
- What is sent to Toll: the transaction, EIP-712 request or x402 payment requirement you are about to sign (to, data,
356
- value, chain id, your address as `from`), nothing else. No key, no account, no signature.
357
-
358
- ## ERC-8470 observations
359
-
360
- `read8470(token, opts?)` reads Toll's latest on-chain [ERC-8470](https://github.com/ethereum/ERCs/pull/2121) Launch
361
- Observation of a token on Robinhood Chain (registry `0x730e3c356299c9203cb042f6c0a9274aeabf9af3`, Toll's detector
362
- `0x02593AbFf31f4E8eC1D5c2F297a347C51ef06E5c`) with a plain `eth_call` to `https://rpc.mainnet.chain.robinhood.com`
363
- (`rpcUrl` to change). Returns the observation and its findings, or null when Toll has none for that token. A finding
364
- not read (`type(uint256).max` on chain) is `value: null, notRead: true`, never 0.
365
- `latestFinding8470(token, kind, param?)` reads one finding (kind by name, e.g. `"first-block-share"`, or bytes32).
366
-
367
- ## Specs
368
-
369
- - Pre-sign check: <https://t0ll.xyz/agents/x402#presign>
370
- - ERC-8470 Launch Observations: <https://github.com/ethereum/ERCs/pull/2121>
371
- - x402 Payee Verification: <https://github.com/ethereum/ERCs/pull/2132>
372
- - ERC-8265 RiskAssessment: <https://github.com/ethereum/ERCs/pull/1753>
373
-
374
- ## Develop
375
-
376
- ```sh
377
- npm run build && npm test # unit tests, no network
378
- node scripts/smoke.mjs # one live call with a harmless request (a 0-value transfer)
379
- ```
380
-
381
- MIT.
1
+ # @tollxyz/guard
2
+
3
+ > **New in 0.4.1: ALLOW tickets** (`ticket` option, `appendTicketSuffix`): a single-use, signed ticket for one exact
4
+ > call, for contracts that require one. See [ALLOW tickets](#allow-tickets).
5
+
6
+ > **New in 0.4.0: spend caps, allowlists, human approval and preview** (`spend` option). Unset, nothing changes.
7
+ > See [0.4.0: spend caps, allowlists, approval, preview](#040-spend-caps-allowlists-approval-preview).
8
+
9
+ > **0.3.1:** `signTypedData` (viem and ethers) now sends the signing account as `from`, so Toll can say what a Permit2 signature lets someone take.
10
+ >
11
+ > **What changed in 0.3.0: every signing method is checked.**
12
+ > - Messages: viem and ethers `signMessage`, and `request()` for `personal_sign` and `eth_sign`.
13
+ > - Typed data: `request()` for `eth_signTypedData_v4` too, any EIP-712 (orders, permits, sign-ins).
14
+ > - Batches: viem `sendCalls` (EIP-5792) and `request()` for `wallet_sendCalls`, each call checked.
15
+ > - Smart accounts: `guardSmartAccount` wraps a viem bundler client's `sendUserOperation` and `prepareUserOperation`;
16
+ > `guard()` picks it for a bundler client.
17
+ > - EIP-7702: `onAuthorization` now defaults to `"check"`: Toll reads the authorization and decides (a known, verified
18
+ > delegate is WARN medium and goes ahead under `block-high`; an unknown one is BLOCK). `"block"` and `"allow"` stay.
19
+ > An authorization Toll cannot read is blocked.
20
+ > - A signature for another chain is blocked (before 0.3.0 it went through as unsupported); `onUnsupported: "allow"`
21
+ > lets it through.
22
+ > - `eth_sign` always fails closed: it can sign any 32 bytes, a transaction included, so when Toll cannot answer it is
23
+ > blocked whatever `onUnavailable` says.
24
+
25
+ > **Defaults changed in 0.2.0.** A WARN with any `high` or `critical` warning is now blocked (`onWarn: "block-high"`,
26
+ > the new default); a WARN with only `medium`/`low` warnings still goes ahead, logged. To keep the 0.1.x behaviour,
27
+ > pass `onWarn: "allow"`. New `strict: true` preset: WARN, unavailable and unsupported all block. Any option you pass
28
+ > explicitly still wins over the preset (`{ strict: true, onUnavailable: "allow" }` stays fail-open).
29
+
30
+ Toll's live pre-sign check in front of an AI agent's wallet. Before the agent signs a transaction, a message, an
31
+ EIP-712 signature, a batch, a user operation, an EIP-7702 authorization or an x402 payment on Robinhood Chain, the guard asks [Toll](https://t0ll.xyz/agents/x402#presign) and
32
+ gets ALLOW / WARN / BLOCK with the reasons. Zero runtime dependencies, ESM only, Node >= 20.19, with types.
33
+
34
+ ```sh
35
+ npm install @tollxyz/guard
36
+ ```
37
+
38
+ ```ts
39
+ const wallet = guard(walletClient); // viem WalletClient, viem bundler client or ethers v6 Signer; same methods, checked first
40
+ ```
41
+
42
+ ```ts
43
+ import { guard, TollBlockedError } from "@tollxyz/guard";
44
+
45
+ const wallet = guard(walletClient, { onWarn: "block-high", onUnavailable: "allow" });
46
+ try {
47
+ await wallet.writeContract({ address: token, abi: erc20Abi, functionName: "approve", args: [spender, maxUint256] });
48
+ } catch (e) {
49
+ if (e instanceof TollBlockedError) console.log(e.codes, e.assessment); // not signed
50
+ else throw e;
51
+ }
52
+ ```
53
+
54
+ Run it as an ES module (an `.mjs`/`.mts` file, or `"type": "module"` in package.json).
55
+
56
+ Toll states facts, never says safe: ALLOW means none of the checks Toll runs found a reason to stop, nothing more.
57
+ Information only, not financial advice.
58
+
59
+ ## Gate a buy in one call
60
+
61
+ Before your agent even builds the swap, ask for one word with `@tollxyz/sdk`:
62
+
63
+ ```ts
64
+ import { Toll } from "@tollxyz/sdk";
65
+ const toll = new Toll();
66
+ const r = await toll.preBuyCheck(token); // Decision: BLOCK / WARN / ALLOW / WAIT, up to 3 reasons
67
+ if (r.decision === "BLOCK") throw new Error(r.text); // the owner decides, never the agent
68
+ if (r.decision === "WAIT") await sleep(r.pending!.retryAfterS * 1000); // part of the coin is still being read
69
+ ```
70
+
71
+ It runs the same calibrated rules as the guard's swap check (BLOCK = a finding whose coins rugged at 40% or more
72
+ within 24 h, or sells that fail), so the gate and the guard never disagree. Then let `guardViem` / `guardEthers`
73
+ check the transaction itself when it is signed.
74
+
75
+ ## What is checked
76
+
77
+ Every check runs on Toll's server (`POST https://t0ll.xyz/api/tx/check`), so new checks reach you without a package
78
+ update. The full list is at <https://t0ll.xyz/agents/safety>: what the calldata or signature does (approvals,
79
+ Permit / Permit2, transfers, swaps), unlimited approvals and approvals to a wallet instead of a contract, spenders and
80
+ recipients Toll has flagged, a swap that pays someone else, the coin a swap buys (Toll's coin check: who is behind
81
+ it), the transaction simulated at the current block, what a signature lets someone take (the pull simulated on the
82
+ wallet's real balances, in USD where Toll has a price), instructions aimed at AI agents in token text and in the text
83
+ fields of EIP-712 typed data, a single-pool Uniswap v4 swap quoted on the coin's main pool (`swap-route-worse` when
84
+ that pays more than 3% more), Uniswap v4 position manager calls (`lp-take-to-other`, `lp-mint-to-other`), and for x402
85
+ the payee against the seller's registered ERC-8004 agentWallet (including `extra.erc8004`), an `upto` payment's
86
+ signed maximum and an `auth-capture` payment's escrow, token collector and hold.
87
+
88
+ The answer is an [ERC-8265](https://github.com/ethereum/ERCs/pull/1753) RiskAssessment:
89
+ `{ action, warnings: [{ code, severity, message, "x-toll-evidence" }], scanners, "x-toll": { decoded, link, checked_at, note } }`.
90
+ Critical = BLOCK, high or medium = WARN, low or none = ALLOW.
91
+
92
+ Robinhood Chain (4663) only for now. A transaction on another chain, or a contract deployment, is not sent to Toll
93
+ and goes through (`onUnsupported: "block"` to stop it instead). A signature for another chain is blocked
94
+ (`onUnsupported: "allow"` lets it through).
95
+
96
+ ## API
97
+
98
+ ### `guard(wallet, opts?)`, `guardViem(client, opts?)`, `guardSmartAccount(bundler, opts?)`, `guardEthers(signer, opts?)`
99
+
100
+ Returns the same wallet behind a Proxy. Checked first:
101
+
102
+ - viem WalletClient: `sendTransaction`, `writeContract` (calldata encoded with your viem's `encodeFunctionData`),
103
+ `signTransaction`, `signTypedData`, `signMessage`, `sendCalls`, `signAuthorization`, and `request()` for
104
+ `eth_sendTransaction`, `eth_signTransaction`, `personal_sign`, `eth_sign`, `eth_signTypedData_v4` and
105
+ `wallet_sendCalls` (every other method passes through)
106
+ - viem bundler client (account abstraction): `sendUserOperation`, `prepareUserOperation`. `calls` are checked one by
107
+ one as transactions from the smart account's address; a ready `callData` is sent as a user operation with the
108
+ account's EntryPoint
109
+ - ethers v6 Signer: `sendTransaction`, `signTransaction`, `signTypedData`, `signMessage`, `authorize`
110
+
111
+ A batch is checked call by call, in order; the first call blocked stops the whole batch.
112
+
113
+ An EIP-7702 authorization sets the wallet's code to another contract, which can then move everything it holds: a
114
+ transaction with an `authorizationList` on any method above, viem's `signAuthorization`, ethers' `authorize`, a user
115
+ operation's `authorization`. By default (`onAuthorization: "check"`) Toll reads it and decides; if Toll cannot read it
116
+ (unreachable, another chain) it is blocked (TollBlockedError, code `eip7702-authorization`). `"block"` refuses every
117
+ authorization without asking; `"allow"` lets it through unchecked. The account's own sign methods
118
+ (`client.account.sign*`) are not wrapped.
119
+
120
+ ```ts
121
+ const wallet = guard(walletClient, { origin: "https://app.example" }); // origin: the site asking, for sign-ins
122
+ await wallet.signMessage({ message: "Sign in to app.example" }); // checked as personal_sign
123
+ await wallet.request({ method: "personal_sign", params: [hexMessage, address] });
124
+ await wallet.request({ method: "eth_sign", params: [address, hash] }); // blocked when Toll blocks it, or cannot answer
125
+
126
+ const smart = guard(bundlerClient); // detected by sendUserOperation
127
+ await smart.sendUserOperation({ calls: [{ to: token, abi: erc20Abi, functionName: "transfer", args: [to, amount] }] });
128
+ ```
129
+
130
+ Everything else passes through unchanged. Wrap last: `client.extend(...)` or `signer.connect(...)` on the wrapped
131
+ wallet returns an unguarded one. viem and ethers are optional peer dependencies, never imported at load time.
132
+
133
+ ### `guardX402Fetch(fetch, opts?)`
134
+
135
+ Wraps the fetch your x402 client uses. When a 402 arrives, its payment requirement goes to Toll before the client
136
+ pays; on BLOCK the 402 never reaches the payer (TollBlockedError is thrown). The paid retry (a request with a
137
+ `PAYMENT-SIGNATURE` or `X-PAYMENT` header) and every non-402 answer pass through.
138
+
139
+ A 402 can carry its requirement in the `PAYMENT-REQUIRED` header and in the JSON body, and a client pays from the one
140
+ it reads (`x402-fetch` v1 reads the body). The guard reads both: when they ask for different payments (payee, amount,
141
+ asset or scheme), it blocks without asking Toll (code `x402-forms-differ`).
142
+
143
+ ```ts
144
+ import { wrapFetchWithPayment } from "x402-fetch";
145
+ const pay = wrapFetchWithPayment(guardX402Fetch(fetch, { agentId: 123 }), account);
146
+ ```
147
+
148
+ `agentId` (the seller's ERC-8004 id, or a function of the URL) is optional.
149
+
150
+ ### `checkTx(input, opts?)`
151
+
152
+ The raw call. `input`: `{ chainId, from, to, data, value, authorizationList? }` for a transaction,
153
+ `{ chainId, from, authorizationList }` for an authorization alone, `{ typedData }` for an EIP-712 request,
154
+ `{ message: { kind: "personal_sign" | "eth_sign", data, from? } }` for a message, `{ rpc: { method, params } }` for a
155
+ wallet request (`personal_sign`, `eth_sign`, `eth_signTypedData_v4`, `eth_sendTransaction`), `{ userOp, entryPoint? }`
156
+ for an ERC-4337 user operation, `{ x402, agentId?, payment? }` for an x402 payment, or several together; `origin` is
157
+ the site asking. Returns the RiskAssessment. When a
158
+ coin is still being read, Toll answers WARN `coin-not-read` with `Retry-After`: `checkTx` asks once more if the wait
159
+ is at most `maxRetryWaitMs` (default 10 s); a coin still not read stays WARN, never ALLOW. Throws
160
+ `TollUnavailableError` when Toll cannot answer.
161
+
162
+ ### Options
163
+
164
+ | Option | Default | |
165
+ | --- | --- | --- |
166
+ | `strict` | `false` | preset: the defaults of `onWarn`, `onUnavailable` and `onUnsupported` become `"block"`; each one passed explicitly still wins |
167
+ | `onWarn` | `"block-high"` | `"block-high"` (blocked when any warning is `high` or `critical`, else allowed and logged), `"allow"` (every WARN goes ahead, logged; the 0.1.x default), `"block"`, or `(assessment) => boolean` (true lets it through) |
168
+ | `onBlock` | `"throw"` | `"throw"` (TollBlockedError), or `(assessment) => boolean`, e.g. ask a human; true lets it through |
169
+ | `onUnavailable` | `"allow"` (`strict`: `"block"`) | Toll unreachable, timed out, 5xx, 429, or a request it could not read: `"allow"` (fail-open, logged) or `"block"` (fail-closed, TollUnavailableError) |
170
+ | `onUnsupported` | `"allow"` (`strict`: `"block"`) | a transaction on another chain, a deployment: `"allow"` or `"block"`. A signature for another chain is blocked unless this is `"allow"` explicitly |
171
+ | `onAuthorization` | `"check"` | an EIP-7702 authorization: `"check"` (Toll decides; blocked when Toll cannot read it), `"block"` (TollBlockedError, Toll not asked) or `"allow"` (unchecked, logged) |
172
+ | `origin` | none | the site asking for a signature, sent with messages and typed data |
173
+ | `onReport` | none | `(report) => void`: every decision, with `assessment`, `decision`, `basis`, `paidUrl` |
174
+ | `logger` | `console.warn` | where WARN and unavailable lines go; `false` = silent |
175
+ | `timeoutMs` | `15000` | one request to Toll |
176
+ | `retry`, `maxRetryWaitMs` | `true`, `10000` | the one retry after Retry-After |
177
+ | `baseUrl`, `fetch` | `https://t0ll.xyz`, global fetch | |
178
+ | `spend` | none | 0.4.0: caps, allowlists, approval ([below](#040-spend-caps-allowlists-approval-preview)); unset = 0.3.x behaviour |
179
+ | `store` | in-process `MemorySpendStore` | where spend counters and paid x402 ids live |
180
+ | `failClosed` | `false` | with `spend`: a request whose spend cannot be read is blocked |
181
+ | `ticket` | none | 0.4.1: `true` or `{consumer?, scope?}`: ask Toll for a single-use ALLOW ticket for this exact call; it comes back as `report.ticket` ([below](#allow-tickets)) |
182
+
183
+ Errors: `TollBlockedError` (`.assessment`, `.codes`, message lists each code and message) and
184
+ `TollUnavailableError` (`.reason`, `.status`, `.paidUrl`).
185
+
186
+ ## 0.4.0: spend caps, allowlists, approval, preview
187
+
188
+ Toll's verdict says whether a request looks safe. `spend` adds your own limits on top: how much the agent may spend
189
+ per call and per UTC day, who it may pay, and when a human has to say yes. Without `spend` nothing changes: 0.4.0
190
+ behaves exactly like 0.3.x.
191
+
192
+ The order for every request:
193
+
194
+ 1. **Allowlists** (`allow.to`, `allow.spender`, `allow.payTo`): read from the request itself, before Toll is asked.
195
+ Off the list = blocked, and Toll is not called.
196
+ 2. **Toll's verdict**: ALLOW / WARN / BLOCK with your `onWarn`, `onBlock`, `onUnavailable` as before. A WARN that
197
+ `block-high` blocks is still blocked, however small the amount.
198
+ 3. **Caps** (`assets`, `perEndpoint`): per call, then per day. The day amount is reserved.
199
+ 4. **Approval** (`approveAbove` + `approve`): above the threshold your `approve` function decides.
200
+ 5. **After the send**: the reservation is committed. If the send throws (rejected, nonce too low, RPC down), it is
201
+ released, so failures never use up the day cap.
202
+
203
+ Caps never relax Toll's verdict, and Toll's ALLOW never lifts a cap: a request must pass both.
204
+
205
+ ```ts
206
+ import { guard, NATIVE, USDG, TollPolicyError } from "@tollxyz/guard";
207
+
208
+ const wallet = guard(walletClient, {
209
+ spend: {
210
+ // base units: ETH in wei, USDG with 6 decimals
211
+ assets: {
212
+ [NATIVE]: { perCall: 10n ** 16n, perDay: 5n * 10n ** 16n }, // 0.01 ETH a call, 0.05 ETH a day
213
+ [USDG]: { perCall: 20_000_000n, perDay: 100_000_000n }, // 20 USDG a call, 100 USDG a day
214
+ },
215
+ allow: { spender: ["0xYourRouter..."] }, // approvals only to your router
216
+ approveAbove: { [USDG]: 10_000_000n }, // above 10 USDG a human decides
217
+ approve: async (req) => {
218
+ const ok = await askOnTelegram(`Spend ${req.over[0].amount} of ${req.over[0].asset}?`);
219
+ return { approved: ok, approvalRef: ok ? "tg-msg-1234" : undefined };
220
+ },
221
+ },
222
+ failClosed: true, // a contract call whose spend cannot be read is blocked
223
+ });
224
+
225
+ try {
226
+ await wallet.sendTransaction(tx);
227
+ } catch (e) {
228
+ if (e instanceof TollPolicyError) console.log(e.code, e.amount, e.limit); // "cap-per-day", ...
229
+ else throw e;
230
+ }
231
+ ```
232
+
233
+ **What counts as spend.** Only what leaves the wallet in a spend asset. The defaults are native ETH, WETH and USDG on
234
+ Robinhood Chain, plus every asset you name in `assets` or `approveAbove`. A sell of any other coin is never capped.
235
+
236
+ - Read locally, with no Toll answer needed: the transaction's value, ERC-20 `transfer` / `transferFrom` / `approve` /
237
+ `increaseAllowance` on a spend asset, EIP-2612 permits, Permit2 permits, EIP-3009 transfer authorizations, and an
238
+ x402 402's amount. So caps hold even when Toll is unreachable.
239
+ - Any other contract call (a swap, a router): the amount comes from Toll's simulation (`x-toll.simulation.deltas`).
240
+ When the simulation shows more leaving than the call declares, the larger amount counts.
241
+ - An approval counts against the per-call cap at its full size (an unlimited approval is over any cap) and must fit
242
+ in what is left of the day cap; it is not added to the day total (the later swap is).
243
+ - Unknown spend: a contract call with no simulation (Toll unreachable), a raw user operation, a bare EIP-7702
244
+ authorization. `onUnknownSpend` decides: `"allow"` by default, `"block"` under `failClosed: true`.
245
+
246
+ | `spend` field | |
247
+ | --- | --- |
248
+ | `assets` | `{ [asset]: { perCall?, perDay? } }`, asset = `"native"` or a token address, amounts in base units |
249
+ | `perEndpoint` | x402 caps per URL prefix (origin + path), e.g. `{ "https://api.example.com/v1/": { perDay: 1_000_000n } }` |
250
+ | `allow` | `{ to?, spender?, payTo? }`: every recipient (or called contract), approval spender, x402 payee must be listed |
251
+ | `approveAbove` | `{ [asset]: amount }`: above it, `approve` must say yes |
252
+ | `approve` | `(req) => Promise<{ approved, approvalRef? }>`; no function = denied. `approvalRef` lands in `report.spend.approvalRef` |
253
+ | `onUnknownSpend` | `"allow"` (default) or `"block"` (default under `failClosed`) |
254
+
255
+ New options next to `spend`: `store` (where counters live, below) and `failClosed`.
256
+
257
+ `TollPolicyError` extends `TollBlockedError` (existing `catch` blocks still see a block). `.code` is one of
258
+ `not-allowlisted`, `cap-per-call`, `cap-per-day`, `cap-endpoint`, `approval-denied`, `duplicate-payment`,
259
+ `unknown-spend`; `.asset`, `.amount`, `.limit` when they apply. The report has `basis: "policy"` and `policy: code`.
260
+
261
+ ### Preview, then confirm
262
+
263
+ ```ts
264
+ import { preview } from "@tollxyz/guard";
265
+
266
+ const p = await preview({ chainId: 4663, from, to, data, value }, opts); // same opts as the guard
267
+ // p.decision "allowed" | "blocked", p.basis, p.policy, p.spend, p.needsApproval, p.reason
268
+ if (p.decision === "allowed") await wallet.sendTransaction({ to, data, value, tollConfirm: p.confirmId });
269
+ ```
270
+
271
+ `preview` asks Toll and checks every rule, but reserves nothing, calls no `approve` and no `onReport`. Passing its
272
+ `confirmId` as `tollConfirm` within 30 seconds reuses that Toll answer (one Toll call instead of two). It is used
273
+ once, and only for the identical request; anything else is checked again. The guard strips `tollConfirm` before the
274
+ wallet sees the request (viem `sendTransaction` / `signTransaction` / `writeContract`, ethers `sendTransaction` /
275
+ `signTransaction`).
276
+
277
+ ### x402: payment ids and per-endpoint caps
278
+
279
+ With `spend` set, `guardX402Fetch` also:
280
+
281
+ - counts a 402's amount against `assets` and `perEndpoint` caps when it is checked. The reservation waits for the
282
+ paid retry: committed when the seller answers, released on another 402 or an error, released after `holdMs`
283
+ (default 2 minutes) when no paid retry comes.
284
+ - never pays the same x402 `payment-identifier` twice. An id is marked paid only when the seller accepts the paid
285
+ request (any answer but 402); sending that id again throws `TollPolicyError` `duplicate-payment` (ids are kept
286
+ `paymentIdTtlS`, default 1 day). A second send of an id that is still in flight is refused too. After a network
287
+ error or timeout the same id may be retried (the seller dedupes it): the retry reuses the reservation of its 402,
288
+ so nothing is counted twice. A different id is a new payment.
289
+
290
+ ### Where the counters live
291
+
292
+ The default store is a `MemorySpendStore` in this process, one per `spend` object. **It resets when the process
293
+ restarts and is not shared between processes**: two workers each get the full day cap. For a cap that survives
294
+ restarts or spans workers, pass your own `store` implementing `SpendStore`:
295
+
296
+ ```ts
297
+ interface SpendStore {
298
+ reserve(k: string, amt: bigint, limit: bigint, windowStart: number): Promise<{ ok: boolean; id: string; used: bigint }>;
299
+ commit(id: string): Promise<void>;
300
+ release(id: string): Promise<void>;
301
+ paymentSeen(id: string): Promise<boolean>;
302
+ markPaid(id: string, ttlS: number): Promise<void>;
303
+ }
304
+ ```
305
+
306
+ A Redis store (example only, not shipped; `reserve` must be atomic, hence the Lua script):
307
+
308
+ ```ts
309
+ import Redis from "ioredis";
310
+ import type { SpendStore } from "@tollxyz/guard";
311
+
312
+ const redis = new Redis(process.env.REDIS_URL!);
313
+ const RESERVE = `
314
+ local used = tonumber(redis.call('GET', KEYS[1]) or '0')
315
+ local amt, limit = tonumber(ARGV[1]), tonumber(ARGV[2])
316
+ if used + amt > limit then return {0, tostring(used)} end
317
+ redis.call('INCRBY', KEYS[1], ARGV[1])
318
+ redis.call('EXPIRE', KEYS[1], 172800)
319
+ redis.call('SET', KEYS[2], KEYS[1] .. '|' .. ARGV[1], 'EX', 3600)
320
+ return {1, tostring(used + amt)}`;
321
+ const RELEASE = `
322
+ local v = redis.call('GET', KEYS[1])
323
+ if not v then return 0 end
324
+ local sep = string.find(v, '|', 1, true)
325
+ redis.call('DECRBY', string.sub(v, 1, sep - 1), string.sub(v, sep + 1))
326
+ redis.call('DEL', KEYS[1])
327
+ return 1`;
328
+
329
+ export const redisStore: SpendStore = {
330
+ async reserve(k, amt, limit, windowStart) {
331
+ const id = `toll:res:${crypto.randomUUID()}`;
332
+ // amounts as numbers in Lua: fine below 2^53 base units; use string math for larger caps
333
+ const [ok, used] = (await redis.eval(RESERVE, 2, `toll:cap:${k}:${windowStart}`, id, amt.toString(), limit.toString())) as [number, string];
334
+ return { ok: ok === 1, id: ok === 1 ? id : "", used: BigInt(used) };
335
+ },
336
+ async commit(id) { await redis.del(id); }, // the amount stays in the day counter
337
+ async release(id) { await redis.eval(RELEASE, 1, id); },
338
+ async paymentSeen(id) { return (await redis.exists(`toll:paid:${id}`)) === 1; },
339
+ async markPaid(id, ttlS) { await redis.set(`toll:paid:${id}`, "1", "EX", ttlS); },
340
+ };
341
+
342
+ const wallet = guard(walletClient, { spend: { /* ... */ }, store: redisStore });
343
+ ```
344
+
345
+ ## 0.5.0: mirror the caps into the facilitator budget (coming)
346
+
347
+ guard's caps live in the agent's process. Toll's x402 facilitator (https://x402.t0ll.xyz) is adding per-payer budgets: the
348
+ payer wallet signs its limits once and the facilitator refuses any payment past them where it settles, so a second
349
+ process, a key used elsewhere or a bug in the agent cannot spend past them through it. Budgets are **coming**: the
350
+ facilitator answers `404 budgets_off` until they are switched on. `guardBudget` builds that budget from your `spend`
351
+ policy; guard itself behaves exactly as before.
352
+
353
+ ```ts
354
+ import { guardBudget, USDG } from "@tollxyz/guard";
355
+ import { Toll } from "@tollxyz/sdk"; // 0.7.0 or later
356
+
357
+ const spend = {
358
+ assets: { [USDG]: { perCall: 100_000n, perDay: 1_000_000n } }, // 0.10 / 1.00 USDG
359
+ perEndpoint: { "https://api.example/quotes": { perDay: 250_000n } },
360
+ allow: { payTo: ["0xSellerA...", "0xSellerB..."] },
361
+ };
362
+ const { budget, typedData, notMirrored } = guardBudget(spend, {
363
+ payer: account.address,
364
+ nonce: BigInt(Date.now()), // newer wins
365
+ endpointPayTo: { "https://api.example/quotes": "0xSellerA..." }, // the facilitator sees a payTo, not a URL
366
+ });
367
+ console.log(notMirrored); // guard rules the facilitator cannot hold (they stay enforced by guard)
368
+ await new Toll().setBudget({ budget, signature: await account.signTypedData(typedData) });
369
+ ```
370
+
371
+ | guard | facilitator budget |
372
+ | --- | --- |
373
+ | `assets[USDG].perCall` | `perPayment` (required: pass `perPayment` if the policy has none; 0 refuses everything) |
374
+ | `assets[USDG].perDay` | `perDay` (required, same rule) |
375
+ | `perEndpoint[prefix].perDay` | `payToCaps` entry for that endpoint's payTo (`endpointPayTo`, or a key that is an address); two endpoints on one payTo take the stricter cap |
376
+ | `allow.payTo` | `allowedPayTos` |
377
+ | `perEndpoint[prefix].perCall`, other assets, `allow.to`, `allow.spender`, `approveAbove` | not mirrored, listed in `notMirrored` |
378
+
379
+ `perPayTo` (one day cap for every payTo) and `validUntil` (unix seconds) are options. Days are UTC on both sides. The
380
+ typed data is the facilitator's EIP-712 `Budget` (domain `Toll Facilitator Budget` / `1` / chain 4663, no
381
+ verifyingContract); `BUDGET_DOMAIN` and `BUDGET_TYPES` are exported. guard has no runtime dependencies: posting it is
382
+ `@tollxyz/sdk`'s `setBudget` (or `POST https://x402.t0ll.xyz/budget` with `{ budget, signature }`, amounts as decimal
383
+ strings).
384
+
385
+ ## ALLOW tickets
386
+
387
+ A contract can require a Toll ALLOW ticket before a sensitive call (a router, a module, a Uniswap v4 hook, a
388
+ delegation caveat). The Solidity side is [toll-allow](https://github.com/t0ll-xyz/toll-allow); the full guide is
389
+ https://t0ll.xyz/agents/allow.
390
+
391
+ - A ticket is an EIP-712 verdict signed by Toll for **one exact call** (target, value, data), one account (`from`),
392
+ an optional consumer contract and a 60 second window. It is single use.
393
+ - A BLOCK is never signed. A WARN is signed only when no warning is high or critical (as verdict 1). No ticket
394
+ without `from`, or for a transaction with an EIP-7702 authorization list. When none is issued, `report.ticket` is
395
+ `{ why }`.
396
+ - Toll's production signer on Robinhood Chain (4663) is `0x4A2C93066d94F1E69f3EAd5438c4efDdf80a46ba`
397
+ (`TOLL_ALLOW_SIGNER`). Pin it in your contract, or a `TollSignerSet` you control that includes it.
398
+
399
+ ```ts
400
+ import { enforce, appendTicketSuffix } from "@tollxyz/guard";
401
+
402
+ // 1. check the inner call (what the router will call), bound to your router as the consumer
403
+ const r = await enforce("transaction", () => ({ chainId: 4663, from: me, to: target, data, value }), {
404
+ ticket: { consumer: ROUTER },
405
+ });
406
+ if (!r.ticket || !("signature" in r.ticket)) throw new Error(r.ticket?.why ?? "no ticket");
407
+
408
+ // 2. put the ticket on the calldata: data ‖ abi.encode(ticket, signature) ‖ uint32 len ‖ 0x900bc3e1
409
+ const withTicket = appendTicketSuffix(data, r.ticket.ticket, r.ticket.signature);
410
+ // 3. call the router within 60 s: router.exec(target, withTicket) with the same value, from the same account
411
+ ```
412
+
413
+ `appendTicketSuffix` is byte for byte `TollAllow.encodeSuffix` (tested against toll-allow's vectors). For a v4 hook,
414
+ ask with `scope: "v4swap"` and pass `abi.encode(ticket, signature)` as `hookData`. The same option works on
415
+ `checkTx(input, { ticket })`, where the ticket is in `assessment["x-toll"].ticket`.
416
+
417
+ A ticket is necessary, never sufficient: the contract keeps its own checks (slippage, limits, access control), and
418
+ should keep an owner bypass behind a timelock in case Toll is unreachable.
419
+
420
+ ## Fail-open or fail-closed
421
+
422
+ The default is fail-open: if Toll cannot answer, the signature goes ahead, with a `[toll-guard] ... NOT checked`
423
+ line and an `onReport` call with `basis: "unavailable"`. The agent must never get stuck because of Toll, and the
424
+ free route is rate limited per IP (a busy agent will see 429s). If an unchecked signature is worse for you than a
425
+ stalled agent, set `onUnavailable: "block"` (or `strict: true`, which also blocks every WARN and unsupported request).
426
+
427
+ Two requests fail closed whatever `onUnavailable` says: `eth_sign` (it signs any 32 bytes, a transaction hash
428
+ included, so an unchecked one could be anything) and an EIP-7702 authorization under `onAuthorization: "check"`.
429
+
430
+ ## Free limit and the paid route
431
+
432
+ The check is free, rate limited per IP. The coin a swap buys is read through the same free coins as Toll's coin
433
+ check (10 new coins a day per caller, coins already read stay free); past that the coin is not read and the answer
434
+ is WARN `coin-over-quota` naming the paid route, `https://t0ll.xyz/api/x402/tx` (0.005 USDG over x402, no daily
435
+ limit). The guard never pays: it puts that URL in the log line, in `report.paidUrl` and in `paidUrlOf(assessment)`.
436
+
437
+ ## Privacy
438
+
439
+ What is sent to Toll: the transaction, EIP-712 request or x402 payment requirement you are about to sign (to, data,
440
+ value, chain id, your address as `from`), nothing else. No key, no account, no signature.
441
+
442
+ ## ERC-8470 observations
443
+
444
+ `read8470(token, opts?)` reads Toll's latest on-chain [ERC-8470](https://github.com/ethereum/ERCs/pull/2121) Launch
445
+ Observation of a token on Robinhood Chain (registry `0x730e3c356299c9203cb042f6c0a9274aeabf9af3`, Toll's detector
446
+ `0x02593AbFf31f4E8eC1D5c2F297a347C51ef06E5c`) with a plain `eth_call` to `https://rpc.mainnet.chain.robinhood.com`
447
+ (`rpcUrl` to change). Returns the observation and its findings, or null when Toll has none for that token. A finding
448
+ not read (`type(uint256).max` on chain) is `value: null, notRead: true`, never 0.
449
+ `latestFinding8470(token, kind, param?)` reads one finding (kind by name, e.g. `"first-block-share"`, or bytes32).
450
+
451
+ ## Specs
452
+
453
+ - Pre-sign check: <https://t0ll.xyz/agents/x402#presign>
454
+ - ERC-8470 Launch Observations: <https://github.com/ethereum/ERCs/pull/2121>
455
+ - x402 Payee Verification: <https://github.com/ethereum/ERCs/pull/2132>
456
+ - ERC-8265 RiskAssessment: <https://github.com/ethereum/ERCs/pull/1753>
457
+
458
+ ## Develop
459
+
460
+ ```sh
461
+ npm run build && npm test # unit tests, no network
462
+ node scripts/smoke.mjs # one live call with a harmless request (a 0-value transfer)
463
+ ```
464
+
465
+ MIT.