@tollxyz/guard 0.4.1 → 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,420 +1,465 @@
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/x402#presign>: 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), and for x402 the payee against the seller's registered ERC-8004 agentWallet (including `extra.erc8004`).
82
-
83
- The answer is an [ERC-8265](https://github.com/ethereum/ERCs/pull/1753) RiskAssessment:
84
- `{ action, warnings: [{ code, severity, message, "x-toll-evidence" }], scanners, "x-toll": { decoded, link, checked_at, note } }`.
85
- Critical = BLOCK, high or medium = WARN, low or none = ALLOW.
86
-
87
- Robinhood Chain (4663) only for now. A transaction on another chain, or a contract deployment, is not sent to Toll
88
- and goes through (`onUnsupported: "block"` to stop it instead). A signature for another chain is blocked
89
- (`onUnsupported: "allow"` lets it through).
90
-
91
- ## API
92
-
93
- ### `guard(wallet, opts?)`, `guardViem(client, opts?)`, `guardSmartAccount(bundler, opts?)`, `guardEthers(signer, opts?)`
94
-
95
- Returns the same wallet behind a Proxy. Checked first:
96
-
97
- - viem WalletClient: `sendTransaction`, `writeContract` (calldata encoded with your viem's `encodeFunctionData`),
98
- `signTransaction`, `signTypedData`, `signMessage`, `sendCalls`, `signAuthorization`, and `request()` for
99
- `eth_sendTransaction`, `eth_signTransaction`, `personal_sign`, `eth_sign`, `eth_signTypedData_v4` and
100
- `wallet_sendCalls` (every other method passes through)
101
- - viem bundler client (account abstraction): `sendUserOperation`, `prepareUserOperation`. `calls` are checked one by
102
- one as transactions from the smart account's address; a ready `callData` is sent as a user operation with the
103
- account's EntryPoint
104
- - ethers v6 Signer: `sendTransaction`, `signTransaction`, `signTypedData`, `signMessage`, `authorize`
105
-
106
- A batch is checked call by call, in order; the first call blocked stops the whole batch.
107
-
108
- An EIP-7702 authorization sets the wallet's code to another contract, which can then move everything it holds: a
109
- transaction with an `authorizationList` on any method above, viem's `signAuthorization`, ethers' `authorize`, a user
110
- operation's `authorization`. By default (`onAuthorization: "check"`) Toll reads it and decides; if Toll cannot read it
111
- (unreachable, another chain) it is blocked (TollBlockedError, code `eip7702-authorization`). `"block"` refuses every
112
- authorization without asking; `"allow"` lets it through unchecked. The account's own sign methods
113
- (`client.account.sign*`) are not wrapped.
114
-
115
- ```ts
116
- const wallet = guard(walletClient, { origin: "https://app.example" }); // origin: the site asking, for sign-ins
117
- await wallet.signMessage({ message: "Sign in to app.example" }); // checked as personal_sign
118
- await wallet.request({ method: "personal_sign", params: [hexMessage, address] });
119
- await wallet.request({ method: "eth_sign", params: [address, hash] }); // blocked when Toll blocks it, or cannot answer
120
-
121
- const smart = guard(bundlerClient); // detected by sendUserOperation
122
- await smart.sendUserOperation({ calls: [{ to: token, abi: erc20Abi, functionName: "transfer", args: [to, amount] }] });
123
- ```
124
-
125
- Everything else passes through unchanged. Wrap last: `client.extend(...)` or `signer.connect(...)` on the wrapped
126
- wallet returns an unguarded one. viem and ethers are optional peer dependencies, never imported at load time.
127
-
128
- ### `guardX402Fetch(fetch, opts?)`
129
-
130
- Wraps the fetch your x402 client uses. When a 402 arrives, its payment requirement goes to Toll before the client
131
- pays; on BLOCK the 402 never reaches the payer (TollBlockedError is thrown). The paid retry (a request with a
132
- `PAYMENT-SIGNATURE` or `X-PAYMENT` header) and every non-402 answer pass through.
133
-
134
- A 402 can carry its requirement in the `PAYMENT-REQUIRED` header and in the JSON body, and a client pays from the one
135
- it reads (`x402-fetch` v1 reads the body). The guard reads both: when they ask for different payments (payee, amount,
136
- asset or scheme), it blocks without asking Toll (code `x402-forms-differ`).
137
-
138
- ```ts
139
- import { wrapFetchWithPayment } from "x402-fetch";
140
- const pay = wrapFetchWithPayment(guardX402Fetch(fetch, { agentId: 123 }), account);
141
- ```
142
-
143
- `agentId` (the seller's ERC-8004 id, or a function of the URL) is optional.
144
-
145
- ### `checkTx(input, opts?)`
146
-
147
- The raw call. `input`: `{ chainId, from, to, data, value, authorizationList? }` for a transaction,
148
- `{ chainId, from, authorizationList }` for an authorization alone, `{ typedData }` for an EIP-712 request,
149
- `{ message: { kind: "personal_sign" | "eth_sign", data, from? } }` for a message, `{ rpc: { method, params } }` for a
150
- wallet request (`personal_sign`, `eth_sign`, `eth_signTypedData_v4`, `eth_sendTransaction`), `{ userOp, entryPoint? }`
151
- for an ERC-4337 user operation, `{ x402, agentId?, payment? }` for an x402 payment, or several together; `origin` is
152
- the site asking. Returns the RiskAssessment. When a
153
- coin is still being read, Toll answers WARN `coin-not-read` with `Retry-After`: `checkTx` asks once more if the wait
154
- is at most `maxRetryWaitMs` (default 10 s); a coin still not read stays WARN, never ALLOW. Throws
155
- `TollUnavailableError` when Toll cannot answer.
156
-
157
- ### Options
158
-
159
- | Option | Default | |
160
- | --- | --- | --- |
161
- | `strict` | `false` | preset: the defaults of `onWarn`, `onUnavailable` and `onUnsupported` become `"block"`; each one passed explicitly still wins |
162
- | `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) |
163
- | `onBlock` | `"throw"` | `"throw"` (TollBlockedError), or `(assessment) => boolean`, e.g. ask a human; true lets it through |
164
- | `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) |
165
- | `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 |
166
- | `onAuthorization` | `"check"` | an EIP-7702 authorization: `"check"` (Toll decides; blocked when Toll cannot read it), `"block"` (TollBlockedError, Toll not asked) or `"allow"` (unchecked, logged) |
167
- | `origin` | none | the site asking for a signature, sent with messages and typed data |
168
- | `onReport` | none | `(report) => void`: every decision, with `assessment`, `decision`, `basis`, `paidUrl` |
169
- | `logger` | `console.warn` | where WARN and unavailable lines go; `false` = silent |
170
- | `timeoutMs` | `15000` | one request to Toll |
171
- | `retry`, `maxRetryWaitMs` | `true`, `10000` | the one retry after Retry-After |
172
- | `baseUrl`, `fetch` | `https://t0ll.xyz`, global fetch | |
173
- | `spend` | none | 0.4.0: caps, allowlists, approval ([below](#040-spend-caps-allowlists-approval-preview)); unset = 0.3.x behaviour |
174
- | `store` | in-process `MemorySpendStore` | where spend counters and paid x402 ids live |
175
- | `failClosed` | `false` | with `spend`: a request whose spend cannot be read is blocked |
176
- | `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)) |
177
-
178
- Errors: `TollBlockedError` (`.assessment`, `.codes`, message lists each code and message) and
179
- `TollUnavailableError` (`.reason`, `.status`, `.paidUrl`).
180
-
181
- ## 0.4.0: spend caps, allowlists, approval, preview
182
-
183
- Toll's verdict says whether a request looks safe. `spend` adds your own limits on top: how much the agent may spend
184
- 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
185
- behaves exactly like 0.3.x.
186
-
187
- The order for every request:
188
-
189
- 1. **Allowlists** (`allow.to`, `allow.spender`, `allow.payTo`): read from the request itself, before Toll is asked.
190
- Off the list = blocked, and Toll is not called.
191
- 2. **Toll's verdict**: ALLOW / WARN / BLOCK with your `onWarn`, `onBlock`, `onUnavailable` as before. A WARN that
192
- `block-high` blocks is still blocked, however small the amount.
193
- 3. **Caps** (`assets`, `perEndpoint`): per call, then per day. The day amount is reserved.
194
- 4. **Approval** (`approveAbove` + `approve`): above the threshold your `approve` function decides.
195
- 5. **After the send**: the reservation is committed. If the send throws (rejected, nonce too low, RPC down), it is
196
- released, so failures never use up the day cap.
197
-
198
- Caps never relax Toll's verdict, and Toll's ALLOW never lifts a cap: a request must pass both.
199
-
200
- ```ts
201
- import { guard, NATIVE, USDG, TollPolicyError } from "@tollxyz/guard";
202
-
203
- const wallet = guard(walletClient, {
204
- spend: {
205
- // base units: ETH in wei, USDG with 6 decimals
206
- assets: {
207
- [NATIVE]: { perCall: 10n ** 16n, perDay: 5n * 10n ** 16n }, // 0.01 ETH a call, 0.05 ETH a day
208
- [USDG]: { perCall: 20_000_000n, perDay: 100_000_000n }, // 20 USDG a call, 100 USDG a day
209
- },
210
- allow: { spender: ["0xYourRouter..."] }, // approvals only to your router
211
- approveAbove: { [USDG]: 10_000_000n }, // above 10 USDG a human decides
212
- approve: async (req) => {
213
- const ok = await askOnTelegram(`Spend ${req.over[0].amount} of ${req.over[0].asset}?`);
214
- return { approved: ok, approvalRef: ok ? "tg-msg-1234" : undefined };
215
- },
216
- },
217
- failClosed: true, // a contract call whose spend cannot be read is blocked
218
- });
219
-
220
- try {
221
- await wallet.sendTransaction(tx);
222
- } catch (e) {
223
- if (e instanceof TollPolicyError) console.log(e.code, e.amount, e.limit); // "cap-per-day", ...
224
- else throw e;
225
- }
226
- ```
227
-
228
- **What counts as spend.** Only what leaves the wallet in a spend asset. The defaults are native ETH, WETH and USDG on
229
- Robinhood Chain, plus every asset you name in `assets` or `approveAbove`. A sell of any other coin is never capped.
230
-
231
- - Read locally, with no Toll answer needed: the transaction's value, ERC-20 `transfer` / `transferFrom` / `approve` /
232
- `increaseAllowance` on a spend asset, EIP-2612 permits, Permit2 permits, EIP-3009 transfer authorizations, and an
233
- x402 402's amount. So caps hold even when Toll is unreachable.
234
- - Any other contract call (a swap, a router): the amount comes from Toll's simulation (`x-toll.simulation.deltas`).
235
- When the simulation shows more leaving than the call declares, the larger amount counts.
236
- - An approval counts against the per-call cap at its full size (an unlimited approval is over any cap) and must fit
237
- in what is left of the day cap; it is not added to the day total (the later swap is).
238
- - Unknown spend: a contract call with no simulation (Toll unreachable), a raw user operation, a bare EIP-7702
239
- authorization. `onUnknownSpend` decides: `"allow"` by default, `"block"` under `failClosed: true`.
240
-
241
- | `spend` field | |
242
- | --- | --- |
243
- | `assets` | `{ [asset]: { perCall?, perDay? } }`, asset = `"native"` or a token address, amounts in base units |
244
- | `perEndpoint` | x402 caps per URL prefix (origin + path), e.g. `{ "https://api.example.com/v1/": { perDay: 1_000_000n } }` |
245
- | `allow` | `{ to?, spender?, payTo? }`: every recipient (or called contract), approval spender, x402 payee must be listed |
246
- | `approveAbove` | `{ [asset]: amount }`: above it, `approve` must say yes |
247
- | `approve` | `(req) => Promise<{ approved, approvalRef? }>`; no function = denied. `approvalRef` lands in `report.spend.approvalRef` |
248
- | `onUnknownSpend` | `"allow"` (default) or `"block"` (default under `failClosed`) |
249
-
250
- New options next to `spend`: `store` (where counters live, below) and `failClosed`.
251
-
252
- `TollPolicyError` extends `TollBlockedError` (existing `catch` blocks still see a block). `.code` is one of
253
- `not-allowlisted`, `cap-per-call`, `cap-per-day`, `cap-endpoint`, `approval-denied`, `duplicate-payment`,
254
- `unknown-spend`; `.asset`, `.amount`, `.limit` when they apply. The report has `basis: "policy"` and `policy: code`.
255
-
256
- ### Preview, then confirm
257
-
258
- ```ts
259
- import { preview } from "@tollxyz/guard";
260
-
261
- const p = await preview({ chainId: 4663, from, to, data, value }, opts); // same opts as the guard
262
- // p.decision "allowed" | "blocked", p.basis, p.policy, p.spend, p.needsApproval, p.reason
263
- if (p.decision === "allowed") await wallet.sendTransaction({ to, data, value, tollConfirm: p.confirmId });
264
- ```
265
-
266
- `preview` asks Toll and checks every rule, but reserves nothing, calls no `approve` and no `onReport`. Passing its
267
- `confirmId` as `tollConfirm` within 30 seconds reuses that Toll answer (one Toll call instead of two). It is used
268
- once, and only for the identical request; anything else is checked again. The guard strips `tollConfirm` before the
269
- wallet sees the request (viem `sendTransaction` / `signTransaction` / `writeContract`, ethers `sendTransaction` /
270
- `signTransaction`).
271
-
272
- ### x402: payment ids and per-endpoint caps
273
-
274
- With `spend` set, `guardX402Fetch` also:
275
-
276
- - counts a 402's amount against `assets` and `perEndpoint` caps when it is checked. The reservation waits for the
277
- paid retry: committed when the seller answers, released on another 402 or an error, released after `holdMs`
278
- (default 2 minutes) when no paid retry comes.
279
- - never pays the same x402 `payment-identifier` twice. An id is marked paid only when the seller accepts the paid
280
- request (any answer but 402); sending that id again throws `TollPolicyError` `duplicate-payment` (ids are kept
281
- `paymentIdTtlS`, default 1 day). A second send of an id that is still in flight is refused too. After a network
282
- error or timeout the same id may be retried (the seller dedupes it): the retry reuses the reservation of its 402,
283
- so nothing is counted twice. A different id is a new payment.
284
-
285
- ### Where the counters live
286
-
287
- The default store is a `MemorySpendStore` in this process, one per `spend` object. **It resets when the process
288
- restarts and is not shared between processes**: two workers each get the full day cap. For a cap that survives
289
- restarts or spans workers, pass your own `store` implementing `SpendStore`:
290
-
291
- ```ts
292
- interface SpendStore {
293
- reserve(k: string, amt: bigint, limit: bigint, windowStart: number): Promise<{ ok: boolean; id: string; used: bigint }>;
294
- commit(id: string): Promise<void>;
295
- release(id: string): Promise<void>;
296
- paymentSeen(id: string): Promise<boolean>;
297
- markPaid(id: string, ttlS: number): Promise<void>;
298
- }
299
- ```
300
-
301
- A Redis store (example only, not shipped; `reserve` must be atomic, hence the Lua script):
302
-
303
- ```ts
304
- import Redis from "ioredis";
305
- import type { SpendStore } from "@tollxyz/guard";
306
-
307
- const redis = new Redis(process.env.REDIS_URL!);
308
- const RESERVE = `
309
- local used = tonumber(redis.call('GET', KEYS[1]) or '0')
310
- local amt, limit = tonumber(ARGV[1]), tonumber(ARGV[2])
311
- if used + amt > limit then return {0, tostring(used)} end
312
- redis.call('INCRBY', KEYS[1], ARGV[1])
313
- redis.call('EXPIRE', KEYS[1], 172800)
314
- redis.call('SET', KEYS[2], KEYS[1] .. '|' .. ARGV[1], 'EX', 3600)
315
- return {1, tostring(used + amt)}`;
316
- const RELEASE = `
317
- local v = redis.call('GET', KEYS[1])
318
- if not v then return 0 end
319
- local sep = string.find(v, '|', 1, true)
320
- redis.call('DECRBY', string.sub(v, 1, sep - 1), string.sub(v, sep + 1))
321
- redis.call('DEL', KEYS[1])
322
- return 1`;
323
-
324
- export const redisStore: SpendStore = {
325
- async reserve(k, amt, limit, windowStart) {
326
- const id = `toll:res:${crypto.randomUUID()}`;
327
- // amounts as numbers in Lua: fine below 2^53 base units; use string math for larger caps
328
- const [ok, used] = (await redis.eval(RESERVE, 2, `toll:cap:${k}:${windowStart}`, id, amt.toString(), limit.toString())) as [number, string];
329
- return { ok: ok === 1, id: ok === 1 ? id : "", used: BigInt(used) };
330
- },
331
- async commit(id) { await redis.del(id); }, // the amount stays in the day counter
332
- async release(id) { await redis.eval(RELEASE, 1, id); },
333
- async paymentSeen(id) { return (await redis.exists(`toll:paid:${id}`)) === 1; },
334
- async markPaid(id, ttlS) { await redis.set(`toll:paid:${id}`, "1", "EX", ttlS); },
335
- };
336
-
337
- const wallet = guard(walletClient, { spend: { /* ... */ }, store: redisStore });
338
- ```
339
-
340
- ## ALLOW tickets
341
-
342
- A contract can require a Toll ALLOW ticket before a sensitive call (a router, a module, a Uniswap v4 hook, a
343
- delegation caveat). The Solidity side is [toll-allow](https://github.com/t0ll-xyz/toll-allow); the full guide is
344
- https://t0ll.xyz/agents/allow.
345
-
346
- - A ticket is an EIP-712 verdict signed by Toll for **one exact call** (target, value, data), one account (`from`),
347
- an optional consumer contract and a 60 second window. It is single use.
348
- - A BLOCK is never signed. A WARN is signed only when no warning is high or critical (as verdict 1). No ticket
349
- without `from`, or for a transaction with an EIP-7702 authorization list. When none is issued, `report.ticket` is
350
- `{ why }`.
351
- - Toll's production signer on Robinhood Chain (4663) is `0x4A2C93066d94F1E69f3EAd5438c4efDdf80a46ba`
352
- (`TOLL_ALLOW_SIGNER`). Pin it in your contract, or a `TollSignerSet` you control that includes it.
353
-
354
- ```ts
355
- import { enforce, appendTicketSuffix } from "@tollxyz/guard";
356
-
357
- // 1. check the inner call (what the router will call), bound to your router as the consumer
358
- const r = await enforce("transaction", () => ({ chainId: 4663, from: me, to: target, data, value }), {
359
- ticket: { consumer: ROUTER },
360
- });
361
- if (!r.ticket || !("signature" in r.ticket)) throw new Error(r.ticket?.why ?? "no ticket");
362
-
363
- // 2. put the ticket on the calldata: data ‖ abi.encode(ticket, signature) ‖ uint32 len ‖ 0x900bc3e1
364
- const withTicket = appendTicketSuffix(data, r.ticket.ticket, r.ticket.signature);
365
- // 3. call the router within 60 s: router.exec(target, withTicket) with the same value, from the same account
366
- ```
367
-
368
- `appendTicketSuffix` is byte for byte `TollAllow.encodeSuffix` (tested against toll-allow's vectors). For a v4 hook,
369
- ask with `scope: "v4swap"` and pass `abi.encode(ticket, signature)` as `hookData`. The same option works on
370
- `checkTx(input, { ticket })`, where the ticket is in `assessment["x-toll"].ticket`.
371
-
372
- A ticket is necessary, never sufficient: the contract keeps its own checks (slippage, limits, access control), and
373
- should keep an owner bypass behind a timelock in case Toll is unreachable.
374
-
375
- ## Fail-open or fail-closed
376
-
377
- The default is fail-open: if Toll cannot answer, the signature goes ahead, with a `[toll-guard] ... NOT checked`
378
- line and an `onReport` call with `basis: "unavailable"`. The agent must never get stuck because of Toll, and the
379
- free route is rate limited per IP (a busy agent will see 429s). If an unchecked signature is worse for you than a
380
- stalled agent, set `onUnavailable: "block"` (or `strict: true`, which also blocks every WARN and unsupported request).
381
-
382
- Two requests fail closed whatever `onUnavailable` says: `eth_sign` (it signs any 32 bytes, a transaction hash
383
- included, so an unchecked one could be anything) and an EIP-7702 authorization under `onAuthorization: "check"`.
384
-
385
- ## Free limit and the paid route
386
-
387
- The check is free, rate limited per IP. The coin a swap buys is read through the same free coins as Toll's coin
388
- check (10 new coins a day per caller, coins already read stay free); past that the coin is not read and the answer
389
- is WARN `coin-over-quota` naming the paid route, `https://t0ll.xyz/api/x402/tx` (0.005 USDG over x402, no daily
390
- limit). The guard never pays: it puts that URL in the log line, in `report.paidUrl` and in `paidUrlOf(assessment)`.
391
-
392
- ## Privacy
393
-
394
- What is sent to Toll: the transaction, EIP-712 request or x402 payment requirement you are about to sign (to, data,
395
- value, chain id, your address as `from`), nothing else. No key, no account, no signature.
396
-
397
- ## ERC-8470 observations
398
-
399
- `read8470(token, opts?)` reads Toll's latest on-chain [ERC-8470](https://github.com/ethereum/ERCs/pull/2121) Launch
400
- Observation of a token on Robinhood Chain (registry `0x730e3c356299c9203cb042f6c0a9274aeabf9af3`, Toll's detector
401
- `0x02593AbFf31f4E8eC1D5c2F297a347C51ef06E5c`) with a plain `eth_call` to `https://rpc.mainnet.chain.robinhood.com`
402
- (`rpcUrl` to change). Returns the observation and its findings, or null when Toll has none for that token. A finding
403
- not read (`type(uint256).max` on chain) is `value: null, notRead: true`, never 0.
404
- `latestFinding8470(token, kind, param?)` reads one finding (kind by name, e.g. `"first-block-share"`, or bytes32).
405
-
406
- ## Specs
407
-
408
- - Pre-sign check: <https://t0ll.xyz/agents/x402#presign>
409
- - ERC-8470 Launch Observations: <https://github.com/ethereum/ERCs/pull/2121>
410
- - x402 Payee Verification: <https://github.com/ethereum/ERCs/pull/2132>
411
- - ERC-8265 RiskAssessment: <https://github.com/ethereum/ERCs/pull/1753>
412
-
413
- ## Develop
414
-
415
- ```sh
416
- npm run build && npm test # unit tests, no network
417
- node scripts/smoke.mjs # one live call with a harmless request (a 0-value transfer)
418
- ```
419
-
420
- 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.