botsrated 0.1.6__tar.gz → 0.2.0__tar.gz

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.
@@ -0,0 +1,327 @@
1
+ Metadata-Version: 2.5
2
+ Name: botsrated
3
+ Version: 0.2.0
4
+ Summary: Payment guard for x402 agents: checks facts BotsRated measured about a seller before paying (advice-only by default), adds a payment-identifier retry key where supported, and checks on chain, read-only, whether a payment settled once. Not affiliated with Coinbase or the x402 Foundation.
5
+ Project-URL: Homepage, https://botsrated.com
6
+ Project-URL: Repository, https://github.com/botsrated/botsrated
7
+ Project-URL: Issues, https://github.com/botsrated/botsrated/issues
8
+ Project-URL: Security, https://github.com/botsrated/botsrated/blob/main/SECURITY.md
9
+ Project-URL: Terms, https://botsrated.com/terms
10
+ Project-URL: Privacy, https://botsrated.com/privacy
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: agents,base,botsrated,payment-guard,payment-identifier,payments,preflight,usdc,x402
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: httpx<1,>=0.27
16
+ Provides-Extra: x402
17
+ Requires-Dist: x402[evm,httpx]<3,>=2.25; extra == 'x402'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # botsrated (Python)
21
+
22
+ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment check.
23
+
24
+ - **Before your agent signs**, it looks up facts [BotsRated](https://botsrated.com) measured about the seller's host
25
+ and compares them with the payment request on your machine.
26
+ - **While the payment is built**, it adds an x402 `payment-identifier` retry key, only when the seller advertises
27
+ that extension.
28
+ - **After**, it keeps a local record (never the signature) and can read the blockchain, read-only, to see whether
29
+ the payment settled once.
30
+
31
+ It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
32
+
33
+ **Status: 0.2.0 is not released yet. The latest version on PyPI is
34
+ [`botsrated` 0.1.6](https://pypi.org/project/botsrated/), which does not include the payment guard.**
35
+
36
+ **What this does and doesn't do.** This package checks facts BotsRated measured about a seller before your agent signs, adds a retry key to the payment request, and reads the blockchain to see whether a payment already settled. It can't promise that a payment is right, that a seller will deliver, or that you'll never pay twice: a retry key only stops a second charge if the seller supports the x402 `payment-identifier` extension, and on-chain reads can be late or fail. You choose the rules that stop a payment, and you remain responsible for what your agent pays. Provided under the MIT license, "as is", without warranty.
37
+
38
+ **Hosted checks.** By default (`hosted=True`) this package calls BotsRated's free API (`https://botsrated.com/v1/preflight`) and sends it **only the seller's host name** (never the path, query, wallet, amount, nonce, payment header or request body). Those calls are covered by the BotsRated Terms (https://botsrated.com/terms) and Privacy Policy (https://botsrated.com/privacy), not by the MIT license. `hosted=False` turns hosted checks off: nothing is then sent to botsrated.com, and only the local checks, the retry key and the on-chain check (which goes only to the RPCs you set) run.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install "botsrated[x402]"
44
+ ```
45
+
46
+ Runtime dependencies: `httpx>=0.27,<1` (and, with the `x402` extra, `x402[httpx,evm]>=2.25,<3`). The guard only
47
+ uses the hook and extension points of the x402 client you pass in.
48
+
49
+ ## Payment Guard: Start With Dry-Run
50
+
51
+ ```python
52
+ import httpx
53
+ from x402 import x402Client
54
+ from x402.http.clients.httpx import x402AsyncTransport
55
+ from x402.mechanisms.evm import EthAccountSigner
56
+ from x402.mechanisms.evm.exact import ExactEvmScheme
57
+ from botsrated import PaymentGuard
58
+
59
+ client = x402Client()
60
+ client.register("eip155:*", ExactEvmScheme(signer=EthAccountSigner(account)))
61
+
62
+ # Recommended first setting: log what the guard sees, change nothing.
63
+ guard = PaymentGuard(dry_run=True, on_decision=lambda d: print(d.message))
64
+ guard.install(client) # before/after/response hooks (+ the retry-key extension when not in dry-run)
65
+
66
+ http = httpx.AsyncClient(transport=x402AsyncTransport(client, httpx.AsyncHTTPTransport()))
67
+ paid_get = guard.wrap_async_get(http.get) # tells the guard which URL is being paid
68
+ await paid_get("https://seller.example/api")
69
+ ```
70
+
71
+ `x402ClientSync` works too (`guard.install(sync_client)`, then `guard.wrap_get(session.get)` or
72
+ `with guard.request(url): ...`).
73
+
74
+ Importing the guard (`from botsrated import PaymentGuard` or `from botsrated.payment_guard import PaymentGuard`)
75
+ does not load the signing client: `BotsRatedClient`, which can sign BotsRated's own paid lookups, loads only when
76
+ you use it.
77
+
78
+ Always tell the guard the URL being paid (`wrap_async_get`, `wrap_get` or `with guard.request(url):`). Without it
79
+ the guard only knows the host the seller's 402 *claims* (`resource.url`), so it reports `paid_url_unknown` (a
80
+ warning by default; `POLICIES["strict"]` stops the payment).
81
+
82
+ When the log looks right, drop `dry_run`. The zero-config setting (`PaymentGuard()`) is advice only: it reports
83
+ facts and never stops a payment. To stop payments, choose a policy yourself:
84
+
85
+ ```python
86
+ from botsrated import POLICIES, PaymentGuard
87
+
88
+ guard = PaymentGuard(policy=POLICIES["strict"]) # your choice
89
+ ```
90
+
91
+ A stopped payment raises the x402 abort error with text like:
92
+
93
+ > Payment stopped by your payment policy (rule: payToMismatch). Fact: the payTo in this payment request is not among the payTo addresses BotsRated's probes recorded for seller.example on eip155:8453. Receipt: https://botsrated.com/receipt/<id>. This is a measurement, not a finding about the seller. Dispute: https://botsrated.com/disputes
94
+
95
+ ### Rules And Defaults
96
+
97
+ | Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["strict"]` |
98
+ |---|---|---|---|
99
+ | `pay_to_mismatch`: the payTo is not among the payTos BotsRated's probes recorded for the host | `payto_not_observed` | warn | **block** |
100
+ | `pay_to_invalid`: the payTo is not a 20-byte hex address | `payto_invalid` | warn | **block** |
101
+ | `resource_host_mismatch`: the 402's `resource.url` names another host than the URL being paid (checked locally) | `resource_host_mismatch` | warn | **block** |
102
+ | `paid_url_unknown`: the URL being paid is unknown (no `wrap_get` / `guard.request(url)`), so the only host is the 402's own claim | `paid_url_unknown` | warn | **block** |
103
+ | `price_above_observed`: same route, amount above the last amount BotsRated recorded (compared locally) | `price_above_observed` | warn | warn |
104
+ | `not_covered`: BotsRated has no probe record for the host | `not_covered` | info | info |
105
+ | `stale`: BotsRated's latest probe is older than 24 h | `data_stale` | info | info |
106
+ | BotsRated unreachable (3 s timeout) | `botsrated_unreachable` | info (`fail_open=True`) | info unless `fail_open=False` |
107
+ | After payment: the seller did not report a settled payment | `payment_state_unknown` | warn | warn |
108
+
109
+ Each rule takes `"allow"`, `"warn"` or `"block"`, e.g.
110
+ `dataclasses.replace(POLICIES["warn"], pay_to_mismatch="block")`. A custom `PaymentGuardPolicy(...)` leaves
111
+ `paid_url_unknown` at `"warn"` unless you set it: add `paid_url_unknown="block"` (as `POLICIES["strict"]` does) if an
112
+ unknown paid URL should stop the payment. Every decision carries `reasons` (code, effect,
113
+ rule, fact), `facts`, `policy_rule`, `dispute_url` and a `message`. Reason texts state facts only; seller text is
114
+ never echoed except a parsed host name.
115
+
116
+ ### Options
117
+
118
+ | Option | Default | Meaning |
119
+ |---|---|---|
120
+ | `policy` | `POLICIES["warn"]` | Which facts warn and which stop a payment |
121
+ | `dry_run` | `False` | Log decisions, stop nothing, add no retry key. Recommended first setting |
122
+ | `hosted` | `True` | `False`: nothing is sent to botsrated.com |
123
+ | `fail_open` | `True` | `False`: stop the payment when BotsRated can't be reached or the guard errors |
124
+ | `retry_key` | `True` | Add a `payment-identifier` id where the seller advertises it |
125
+ | `onchain` | default RPCs | RPC settings for `payment_state` (`rpcs`, `extra_rpc`, `margin_seconds`, `expiry_tag`, `confirm_tag`), or `False` |
126
+ | `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout and per-host cache |
127
+ | `preflight` | hosted call | Your own lookup `(host) -> (found, body)` |
128
+ | `on_decision` | none | Receives every decision (errors in it are ignored) |
129
+
130
+ ### Fail-Open Or Fail-Closed
131
+
132
+ - **Fail-open (default):** if botsrated.com is down or slow, or the guard itself hits an error, the payment goes
133
+ ahead and the decision says `botsrated_unreachable` (or `hook_error`). Our outage never stops your agent, but
134
+ during an outage you get no seller facts.
135
+ - **Fail-closed (`fail_open=False`):** the same cases stop the payment. Use it only if an unchecked payment is worse
136
+ for you than a missed call.
137
+ - Local checks (`resource_host_mismatch`, `payto_invalid`) and the on-chain check never depend on botsrated.com.
138
+
139
+ ### What The Guard Sends, And To Whom
140
+
141
+ - **botsrated.com:** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
142
+ Never the path, query, wallet, amount, nonce, tx hash, payment header or request body. No install id. Covered by
143
+ the [Terms](https://botsrated.com/terms) and [Privacy Policy](https://botsrated.com/privacy). Turn it off with
144
+ `hosted=False`.
145
+ - **Base RPCs (only when you call `payment_state`; nothing calls them automatically):** JSON-RPC reads that include
146
+ the payer address and the payment's nonce, sent straight from your machine to the RPCs, never to BotsRated.
147
+ See the privacy note under "Did It Settle Once?".
148
+ - No remote configuration, feature flags or auto-update: behavior changes only with a new package version.
149
+
150
+ ### Retry Key (`payment-identifier`)
151
+
152
+ If the seller's 402 advertises the x402 `payment-identifier` extension, the guard adds a random id
153
+ (`pay_` + 128 random bits) through x402's extension mechanism. Nothing else in the payload changes, and the
154
+ seller's 402 is never modified. Ids are never reused across sellers, payTo addresses or routes. Inside
155
+ `with guard.operation(key):` a retry of the same logical operation (same payTo, host and path) reuses the id, so a
156
+ seller that honors the extension can answer a retry from its cache (or refuse a different payload with 409)
157
+ instead of charging again.
158
+
159
+ A retry key only stops a second charge if the seller supports it. In BotsRated's own probes on Oct 24, 2026,
160
+ about 2.2% of seller hosts (81 of 3,739 in our probe database) advertised `payment-identifier` in their 402, and 6
161
+ of them required it.
162
+ Elsewhere the guard adds nothing.
163
+
164
+ ### Did It Settle Once? (Read-Only)
165
+
166
+ ```python
167
+ rec = guard.records()[-1] # pay_to, amount, nonce, valid_before, host; never the signature
168
+ state = guard.payment_state(rec) # or: await guard.apayment_state(rec). Reads the chain; never pays, signs or retries
169
+ ```
170
+
171
+ There are three answers only:
172
+
173
+ - `settled`: two RPCs on different hosts (or two of three, see below) show the EIP-3009 authorization used at Base's `safe` block tag,
174
+ the chain id is 8453, and the transaction receipt has `AuthorizationUsed(from, nonce)` and
175
+ `Transfer(from, payTo, amount)` emitted by the pinned USDC contract `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`.
176
+ - `unknown` (`payment_state_unknown`) with `wait_until`: not settled yet, the RPCs disagree or failed, the blocks
177
+ they read are not yet past `validBefore` plus the margin (`chain_not_past_expiry`), or the record can't be
178
+ checked. **Do not sign a new payment for that purchase before `wait_until`** (the signed authorization stays
179
+ valid until its `validBefore`, plus a margin of at least 30 s).
180
+ - `expired_unsettled`: `validBefore` plus the margin has passed on the clock **and** in the chain: both RPCs show
181
+ the authorization unused at a block (Base's `safe` tag by default) whose timestamp is at or after `validBefore`
182
+ plus the margin. USDC accepts an authorization in any block before `validBefore`, so "unused" only counts in a
183
+ later block. With the default 60 s margin this is usually 1 to 3 minutes after expiry. Only then is a fresh
184
+ payment free of a double-charge risk from the first one.
185
+
186
+ Settings (`onchain={...}`): `margin_seconds` (default 60, minimum 30) is the extra wait after `validBefore`.
187
+ It is clamped, not rejected: a value below 30 (including negative values and `-inf`) is raised to 30, a value above
188
+ 86,400 (1 day, including `inf`) is lowered to 1 day, and NaN or a non-number uses 60.
189
+ `expiry_tag="finalized"` waits for a finalized block past expiry instead (more conservative, usually 20+ minutes).
190
+
191
+ The guard never retries on `unknown`. botsrated.com is never asked; a tx hash the seller reports is only a hint
192
+ that is verified on chain.
193
+
194
+ **Default RPCs** (two operators; both must answer and agree):
195
+
196
+ | RPC | Operator |
197
+ |---|---|
198
+ | `https://mainnet.base.org` | Coinbase (Base public endpoint; rate-limited, not for production load) |
199
+ | `https://base-rpc.publicnode.com` | Allnodes (PublicNode) |
200
+
201
+ ```python
202
+ PaymentGuard(onchain={"rpcs": ["https://your-rpc-1", "https://your-rpc-2"]})
203
+ # Optional third RPC of your own: then 2 of the 3 must answer and agree, and any RPC that sees the
204
+ # authorization used rules out expired_unsettled.
205
+ PaymentGuard(onchain={"extra_rpc": "https://your-own-rpc"})
206
+ ```
207
+
208
+ At most 3 RPCs in total (`rpcs` plus `extra_rpc`): more is a configuration error (`ValueError`), raised when the
209
+ guard is created and by `check_payment_state`, before any RPC is called.
210
+
211
+ **Privacy of on-chain checks.** Each `payment_state()` call sends the payer address, the payment's nonce and your
212
+ IP address to every RPC it uses. With the defaults those are Coinbase (`mainnet.base.org`) and Allnodes
213
+ (`base-rpc.publicnode.com`); anyone holding the nonce can match it to the on-chain transaction and the seller.
214
+ Treat both operators as logging. Pass your own RPCs (`rpcs`, `extra_rpc`) if that matters to you. BotsRated never
215
+ receives these reads.
216
+
217
+ ### What The Guard Can't Do (By Design)
218
+
219
+ - It never signs, never sends or resends a payment, never builds a payment header and never imports a signer.
220
+ - Every hook is wrapped so its return value is discarded. The after-payment and response hooks always return
221
+ `None`, so they can never ask x402 to "recover" (which would sign a fresh payment). The pre-payment hook can only
222
+ return an `AbortResult`. The payment-creation-failure hook is never registered.
223
+ - These limits are enforced by tests in CI: `tests/test_c1_no_repay.py` (fuzzed hook contexts, a grep of the
224
+ guard's source and built wheel for signing, payment-header and retry code, an import allow-list, and a real
225
+ x402 httpx run where the seller fails after payment and exactly one payload is created).
226
+ - **Other hooks can still pay again.** If your own code or another library registers an `on_payment_response` or
227
+ `on_payment_creation_failure` hook on the same x402 client that returns a result with `recovered=True`, x402
228
+ signs and sends a fresh payment. The guard can't stop that, because it happens outside this package. Don't
229
+ return `recovered` from your own hooks unless a new payment is what you want.
230
+
231
+ ## The Pre-Payment Guard (`PrePaymentGuard`)
232
+
233
+ The older, simpler guard (pre-payment check only). Since 0.2.0 it also sends only the host name and is
234
+ advice-only on payTo by default; pass `policy=STRICT_GUARD_POLICY` (or `GuardPolicy(pay_to_mismatch="block")`) to
235
+ stop those payments as before. Since 0.2.0 `STRICT_GUARD_POLICY` also sets `require_request_url=True`, so it stops a
236
+ payment whose real request URL is unknown; use `wrap_get` or `x402_hook_for(url)` with it.
237
+
238
+ ```python
239
+ from x402 import x402ClientSync
240
+ from x402.mechanisms.evm import EthAccountSigner
241
+ from x402.mechanisms.evm.exact import ExactEvmScheme
242
+ from x402.http.clients import x402_requests
243
+ from botsrated import STRICT_GUARD_POLICY, PrePaymentGuard
244
+
245
+ client = x402ClientSync()
246
+ client.register("eip155:*", ExactEvmScheme(signer=EthAccountSigner(account)))
247
+ guard = PrePaymentGuard(policy=STRICT_GUARD_POLICY) # the policy is your choice
248
+ client.on_before_payment_creation(guard.x402_hook)
249
+
250
+ # Tell the guard which URL is actually being paid (since 0.1.5):
251
+ session = x402_requests(client)
252
+ paid_get = guard.wrap_get(session.get) # or: with paying_request(url): session.get(url)
253
+ paid_get("https://seller.example/api")
254
+ ```
255
+
256
+ The 402's `resource.url` is chosen by the seller, so on its own it only says which host the seller
257
+ *claims* to be. When the guard knows the request URL (`guard.wrap_get(...)`, `guard.wrap_async_get(...)`,
258
+ `with paying_request(url):`, `guard.x402_hook_for(url)`, or `guard.decide(..., request_url=url)`), it looks
259
+ up that URL's host and blocks the payment with `resource_url_mismatch` if `resource.url` names a different
260
+ host. That block applies even with `fail_open=True`. Hosts are compared after IDNA (punycode) and trailing-dot
261
+ normalization. The wrappers only see the URL you called, not where redirects ended, so a `resource.url` that
262
+ differs only by a leading `www.` (an apex <-> www redirect) is accepted (since 0.1.6); any other host is blocked. Without a request URL the host is still read from
263
+ `resource.url` (as before 0.1.5); set `GuardPolicy(require_request_url=True)` to block those payments instead.
264
+
265
+ Defaults:
266
+ - A payTo that differs from every payTo BotsRated's own probes saw for the host, on the same network, is a
267
+ **warning** (`payto_not_observed`; it was a block before 0.2.0). The seller's directory listing alone never
268
+ confirms a payTo: with no probe observation, a listing match is noted with `payto_listing_only` and a listing
269
+ mismatch follows the same rule.
270
+ - A price above the last observed price on the same route is a warning.
271
+ - A host that is not covered is allowed.
272
+ - Data older than 24 h is allowed (`data_stale`).
273
+ - If BotsRated cannot be reached (4 s timeout), the payment is allowed (`fail_open`, `botsrated_unreachable`).
274
+ - The minimum valid-402 rate is off.
275
+
276
+ Change these with `GuardPolicy(...)`. Preflight answers are cached for 5 minutes per host.
277
+
278
+ ## Opt-In Paid Lookups With A Budget
279
+
280
+ ```python
281
+ from botsrated import BotsRatedClient, PrePaymentGuard
282
+
283
+ botsrated = BotsRatedClient(budget_usd="0.05", x402_client=client) # signs only the validated quote
284
+ guard = PrePaymentGuard(botsrated, paid_check_at_or_above_usd=0.25)
285
+ client.on_before_payment_creation(guard.x402_hook)
286
+
287
+ botsrated.check("seller.example") # $0.001 (first 100/day free)
288
+ botsrated.report("seller.example") # $0.002 (first 10/day free)
289
+ botsrated.best("web search") # $0.01
290
+ ```
291
+
292
+ `x402_client=` (since 0.1.4) is the recommended mode: the client validates the 402, rebuilds it from
293
+ the allowlisted fields only (scheme, network, asset, amount, payTo, maxTimeoutSeconds, EIP-3009
294
+ `name`/`version`, resource url/description/mimeType; never `extensions`), signs that copy with
295
+ `client.create_payment_payload`, and sends `PAYMENT-SIGNATURE` itself. The signer never sees the raw
296
+ 402. The older `paying_get=x402_requests(client).get` still works, but that session re-reads the 402
297
+ itself, so register the guard on the same x402 client so the re-served 402 is checked again before signing.
298
+
299
+ How paid calls work:
300
+ - Free daily quota: the first 100 `/v1/check` and 10 `/v1/report` calls per client per UTC day are
301
+ served free (200 with `charged: false` and a `free_quota` block). The client asks unpaid first, so
302
+ inside the quota nothing is paid and the budget is untouched; `check()`/`report()` also work without
303
+ a budget until the quota is used up (then `paid_disabled`). `client.last_free_quota` shows what is left.
304
+ - Otherwise the client reads the 402 quote unpaid first. It accepts the quote only if **every** option is `exact` USDC on Base to BotsRated's payTo
305
+ `0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349`, at or below the published price.
306
+ - The amount is reserved from the budget before paying. If the paid call fails or raises, it stays counted
307
+ (the payment may already have settled), so the budget is a hard ceiling.
308
+ - Amounts must be ASCII digits only (`[0-9]+`); since 0.1.5 a quote with e.g. Arabic-Indic or full-width
309
+ digits is refused.
310
+ - Only a one-shot EIP-3009 payment is signed: an option whose `extra` holds anything beyond the token's
311
+ `name`/`version` (e.g. `assetTransferMethod: permit2`, `paymentFlow`), a missing `maxTimeoutSeconds` or one above 600
312
+ (since 0.2.0 a missing value is invalid), or payment extensions in the 402 (e.g. `erc20ApprovalGasSponsoring`;
313
+ only `bazaar` and `payment-identifier` are tolerated, and neither is signed) rejects the quote with `terms_rejected` before anything is paid.
314
+ - With `x402_client=`, if signing fails nothing can settle and the reservation is released (`payment_not_created`).
315
+ - When the guard is registered, it refuses any payment to botsrated.com that the client did not reserve or
316
+ that carries payment extensions, and strips extensions before the x402 signer runs.
317
+
318
+ ## Tests
319
+
320
+ ```bash
321
+ uv run --with pytest --with respx --with pytest-asyncio --with "x402[httpx,evm]" pytest -m "not live"
322
+ ```
323
+
324
+ Security reports: [SECURITY.md](https://github.com/botsrated/botsrated/blob/main/SECURITY.md).
325
+
326
+ License: MIT. BotsRated reports measurements, not endorsements.
327
+ BotsRated is independent and is not affiliated with or endorsed by Coinbase, the x402 Foundation or any seller. "x402" is used only to describe compatibility.
@@ -0,0 +1,308 @@
1
+ # botsrated (Python)
2
+
3
+ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment check.
4
+
5
+ - **Before your agent signs**, it looks up facts [BotsRated](https://botsrated.com) measured about the seller's host
6
+ and compares them with the payment request on your machine.
7
+ - **While the payment is built**, it adds an x402 `payment-identifier` retry key, only when the seller advertises
8
+ that extension.
9
+ - **After**, it keeps a local record (never the signature) and can read the blockchain, read-only, to see whether
10
+ the payment settled once.
11
+
12
+ It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
13
+
14
+ **Status: 0.2.0 is not released yet. The latest version on PyPI is
15
+ [`botsrated` 0.1.6](https://pypi.org/project/botsrated/), which does not include the payment guard.**
16
+
17
+ **What this does and doesn't do.** This package checks facts BotsRated measured about a seller before your agent signs, adds a retry key to the payment request, and reads the blockchain to see whether a payment already settled. It can't promise that a payment is right, that a seller will deliver, or that you'll never pay twice: a retry key only stops a second charge if the seller supports the x402 `payment-identifier` extension, and on-chain reads can be late or fail. You choose the rules that stop a payment, and you remain responsible for what your agent pays. Provided under the MIT license, "as is", without warranty.
18
+
19
+ **Hosted checks.** By default (`hosted=True`) this package calls BotsRated's free API (`https://botsrated.com/v1/preflight`) and sends it **only the seller's host name** (never the path, query, wallet, amount, nonce, payment header or request body). Those calls are covered by the BotsRated Terms (https://botsrated.com/terms) and Privacy Policy (https://botsrated.com/privacy), not by the MIT license. `hosted=False` turns hosted checks off: nothing is then sent to botsrated.com, and only the local checks, the retry key and the on-chain check (which goes only to the RPCs you set) run.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install "botsrated[x402]"
25
+ ```
26
+
27
+ Runtime dependencies: `httpx>=0.27,<1` (and, with the `x402` extra, `x402[httpx,evm]>=2.25,<3`). The guard only
28
+ uses the hook and extension points of the x402 client you pass in.
29
+
30
+ ## Payment Guard: Start With Dry-Run
31
+
32
+ ```python
33
+ import httpx
34
+ from x402 import x402Client
35
+ from x402.http.clients.httpx import x402AsyncTransport
36
+ from x402.mechanisms.evm import EthAccountSigner
37
+ from x402.mechanisms.evm.exact import ExactEvmScheme
38
+ from botsrated import PaymentGuard
39
+
40
+ client = x402Client()
41
+ client.register("eip155:*", ExactEvmScheme(signer=EthAccountSigner(account)))
42
+
43
+ # Recommended first setting: log what the guard sees, change nothing.
44
+ guard = PaymentGuard(dry_run=True, on_decision=lambda d: print(d.message))
45
+ guard.install(client) # before/after/response hooks (+ the retry-key extension when not in dry-run)
46
+
47
+ http = httpx.AsyncClient(transport=x402AsyncTransport(client, httpx.AsyncHTTPTransport()))
48
+ paid_get = guard.wrap_async_get(http.get) # tells the guard which URL is being paid
49
+ await paid_get("https://seller.example/api")
50
+ ```
51
+
52
+ `x402ClientSync` works too (`guard.install(sync_client)`, then `guard.wrap_get(session.get)` or
53
+ `with guard.request(url): ...`).
54
+
55
+ Importing the guard (`from botsrated import PaymentGuard` or `from botsrated.payment_guard import PaymentGuard`)
56
+ does not load the signing client: `BotsRatedClient`, which can sign BotsRated's own paid lookups, loads only when
57
+ you use it.
58
+
59
+ Always tell the guard the URL being paid (`wrap_async_get`, `wrap_get` or `with guard.request(url):`). Without it
60
+ the guard only knows the host the seller's 402 *claims* (`resource.url`), so it reports `paid_url_unknown` (a
61
+ warning by default; `POLICIES["strict"]` stops the payment).
62
+
63
+ When the log looks right, drop `dry_run`. The zero-config setting (`PaymentGuard()`) is advice only: it reports
64
+ facts and never stops a payment. To stop payments, choose a policy yourself:
65
+
66
+ ```python
67
+ from botsrated import POLICIES, PaymentGuard
68
+
69
+ guard = PaymentGuard(policy=POLICIES["strict"]) # your choice
70
+ ```
71
+
72
+ A stopped payment raises the x402 abort error with text like:
73
+
74
+ > Payment stopped by your payment policy (rule: payToMismatch). Fact: the payTo in this payment request is not among the payTo addresses BotsRated's probes recorded for seller.example on eip155:8453. Receipt: https://botsrated.com/receipt/<id>. This is a measurement, not a finding about the seller. Dispute: https://botsrated.com/disputes
75
+
76
+ ### Rules And Defaults
77
+
78
+ | Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["strict"]` |
79
+ |---|---|---|---|
80
+ | `pay_to_mismatch`: the payTo is not among the payTos BotsRated's probes recorded for the host | `payto_not_observed` | warn | **block** |
81
+ | `pay_to_invalid`: the payTo is not a 20-byte hex address | `payto_invalid` | warn | **block** |
82
+ | `resource_host_mismatch`: the 402's `resource.url` names another host than the URL being paid (checked locally) | `resource_host_mismatch` | warn | **block** |
83
+ | `paid_url_unknown`: the URL being paid is unknown (no `wrap_get` / `guard.request(url)`), so the only host is the 402's own claim | `paid_url_unknown` | warn | **block** |
84
+ | `price_above_observed`: same route, amount above the last amount BotsRated recorded (compared locally) | `price_above_observed` | warn | warn |
85
+ | `not_covered`: BotsRated has no probe record for the host | `not_covered` | info | info |
86
+ | `stale`: BotsRated's latest probe is older than 24 h | `data_stale` | info | info |
87
+ | BotsRated unreachable (3 s timeout) | `botsrated_unreachable` | info (`fail_open=True`) | info unless `fail_open=False` |
88
+ | After payment: the seller did not report a settled payment | `payment_state_unknown` | warn | warn |
89
+
90
+ Each rule takes `"allow"`, `"warn"` or `"block"`, e.g.
91
+ `dataclasses.replace(POLICIES["warn"], pay_to_mismatch="block")`. A custom `PaymentGuardPolicy(...)` leaves
92
+ `paid_url_unknown` at `"warn"` unless you set it: add `paid_url_unknown="block"` (as `POLICIES["strict"]` does) if an
93
+ unknown paid URL should stop the payment. Every decision carries `reasons` (code, effect,
94
+ rule, fact), `facts`, `policy_rule`, `dispute_url` and a `message`. Reason texts state facts only; seller text is
95
+ never echoed except a parsed host name.
96
+
97
+ ### Options
98
+
99
+ | Option | Default | Meaning |
100
+ |---|---|---|
101
+ | `policy` | `POLICIES["warn"]` | Which facts warn and which stop a payment |
102
+ | `dry_run` | `False` | Log decisions, stop nothing, add no retry key. Recommended first setting |
103
+ | `hosted` | `True` | `False`: nothing is sent to botsrated.com |
104
+ | `fail_open` | `True` | `False`: stop the payment when BotsRated can't be reached or the guard errors |
105
+ | `retry_key` | `True` | Add a `payment-identifier` id where the seller advertises it |
106
+ | `onchain` | default RPCs | RPC settings for `payment_state` (`rpcs`, `extra_rpc`, `margin_seconds`, `expiry_tag`, `confirm_tag`), or `False` |
107
+ | `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout and per-host cache |
108
+ | `preflight` | hosted call | Your own lookup `(host) -> (found, body)` |
109
+ | `on_decision` | none | Receives every decision (errors in it are ignored) |
110
+
111
+ ### Fail-Open Or Fail-Closed
112
+
113
+ - **Fail-open (default):** if botsrated.com is down or slow, or the guard itself hits an error, the payment goes
114
+ ahead and the decision says `botsrated_unreachable` (or `hook_error`). Our outage never stops your agent, but
115
+ during an outage you get no seller facts.
116
+ - **Fail-closed (`fail_open=False`):** the same cases stop the payment. Use it only if an unchecked payment is worse
117
+ for you than a missed call.
118
+ - Local checks (`resource_host_mismatch`, `payto_invalid`) and the on-chain check never depend on botsrated.com.
119
+
120
+ ### What The Guard Sends, And To Whom
121
+
122
+ - **botsrated.com:** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
123
+ Never the path, query, wallet, amount, nonce, tx hash, payment header or request body. No install id. Covered by
124
+ the [Terms](https://botsrated.com/terms) and [Privacy Policy](https://botsrated.com/privacy). Turn it off with
125
+ `hosted=False`.
126
+ - **Base RPCs (only when you call `payment_state`; nothing calls them automatically):** JSON-RPC reads that include
127
+ the payer address and the payment's nonce, sent straight from your machine to the RPCs, never to BotsRated.
128
+ See the privacy note under "Did It Settle Once?".
129
+ - No remote configuration, feature flags or auto-update: behavior changes only with a new package version.
130
+
131
+ ### Retry Key (`payment-identifier`)
132
+
133
+ If the seller's 402 advertises the x402 `payment-identifier` extension, the guard adds a random id
134
+ (`pay_` + 128 random bits) through x402's extension mechanism. Nothing else in the payload changes, and the
135
+ seller's 402 is never modified. Ids are never reused across sellers, payTo addresses or routes. Inside
136
+ `with guard.operation(key):` a retry of the same logical operation (same payTo, host and path) reuses the id, so a
137
+ seller that honors the extension can answer a retry from its cache (or refuse a different payload with 409)
138
+ instead of charging again.
139
+
140
+ A retry key only stops a second charge if the seller supports it. In BotsRated's own probes on Oct 24, 2026,
141
+ about 2.2% of seller hosts (81 of 3,739 in our probe database) advertised `payment-identifier` in their 402, and 6
142
+ of them required it.
143
+ Elsewhere the guard adds nothing.
144
+
145
+ ### Did It Settle Once? (Read-Only)
146
+
147
+ ```python
148
+ rec = guard.records()[-1] # pay_to, amount, nonce, valid_before, host; never the signature
149
+ state = guard.payment_state(rec) # or: await guard.apayment_state(rec). Reads the chain; never pays, signs or retries
150
+ ```
151
+
152
+ There are three answers only:
153
+
154
+ - `settled`: two RPCs on different hosts (or two of three, see below) show the EIP-3009 authorization used at Base's `safe` block tag,
155
+ the chain id is 8453, and the transaction receipt has `AuthorizationUsed(from, nonce)` and
156
+ `Transfer(from, payTo, amount)` emitted by the pinned USDC contract `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`.
157
+ - `unknown` (`payment_state_unknown`) with `wait_until`: not settled yet, the RPCs disagree or failed, the blocks
158
+ they read are not yet past `validBefore` plus the margin (`chain_not_past_expiry`), or the record can't be
159
+ checked. **Do not sign a new payment for that purchase before `wait_until`** (the signed authorization stays
160
+ valid until its `validBefore`, plus a margin of at least 30 s).
161
+ - `expired_unsettled`: `validBefore` plus the margin has passed on the clock **and** in the chain: both RPCs show
162
+ the authorization unused at a block (Base's `safe` tag by default) whose timestamp is at or after `validBefore`
163
+ plus the margin. USDC accepts an authorization in any block before `validBefore`, so "unused" only counts in a
164
+ later block. With the default 60 s margin this is usually 1 to 3 minutes after expiry. Only then is a fresh
165
+ payment free of a double-charge risk from the first one.
166
+
167
+ Settings (`onchain={...}`): `margin_seconds` (default 60, minimum 30) is the extra wait after `validBefore`.
168
+ It is clamped, not rejected: a value below 30 (including negative values and `-inf`) is raised to 30, a value above
169
+ 86,400 (1 day, including `inf`) is lowered to 1 day, and NaN or a non-number uses 60.
170
+ `expiry_tag="finalized"` waits for a finalized block past expiry instead (more conservative, usually 20+ minutes).
171
+
172
+ The guard never retries on `unknown`. botsrated.com is never asked; a tx hash the seller reports is only a hint
173
+ that is verified on chain.
174
+
175
+ **Default RPCs** (two operators; both must answer and agree):
176
+
177
+ | RPC | Operator |
178
+ |---|---|
179
+ | `https://mainnet.base.org` | Coinbase (Base public endpoint; rate-limited, not for production load) |
180
+ | `https://base-rpc.publicnode.com` | Allnodes (PublicNode) |
181
+
182
+ ```python
183
+ PaymentGuard(onchain={"rpcs": ["https://your-rpc-1", "https://your-rpc-2"]})
184
+ # Optional third RPC of your own: then 2 of the 3 must answer and agree, and any RPC that sees the
185
+ # authorization used rules out expired_unsettled.
186
+ PaymentGuard(onchain={"extra_rpc": "https://your-own-rpc"})
187
+ ```
188
+
189
+ At most 3 RPCs in total (`rpcs` plus `extra_rpc`): more is a configuration error (`ValueError`), raised when the
190
+ guard is created and by `check_payment_state`, before any RPC is called.
191
+
192
+ **Privacy of on-chain checks.** Each `payment_state()` call sends the payer address, the payment's nonce and your
193
+ IP address to every RPC it uses. With the defaults those are Coinbase (`mainnet.base.org`) and Allnodes
194
+ (`base-rpc.publicnode.com`); anyone holding the nonce can match it to the on-chain transaction and the seller.
195
+ Treat both operators as logging. Pass your own RPCs (`rpcs`, `extra_rpc`) if that matters to you. BotsRated never
196
+ receives these reads.
197
+
198
+ ### What The Guard Can't Do (By Design)
199
+
200
+ - It never signs, never sends or resends a payment, never builds a payment header and never imports a signer.
201
+ - Every hook is wrapped so its return value is discarded. The after-payment and response hooks always return
202
+ `None`, so they can never ask x402 to "recover" (which would sign a fresh payment). The pre-payment hook can only
203
+ return an `AbortResult`. The payment-creation-failure hook is never registered.
204
+ - These limits are enforced by tests in CI: `tests/test_c1_no_repay.py` (fuzzed hook contexts, a grep of the
205
+ guard's source and built wheel for signing, payment-header and retry code, an import allow-list, and a real
206
+ x402 httpx run where the seller fails after payment and exactly one payload is created).
207
+ - **Other hooks can still pay again.** If your own code or another library registers an `on_payment_response` or
208
+ `on_payment_creation_failure` hook on the same x402 client that returns a result with `recovered=True`, x402
209
+ signs and sends a fresh payment. The guard can't stop that, because it happens outside this package. Don't
210
+ return `recovered` from your own hooks unless a new payment is what you want.
211
+
212
+ ## The Pre-Payment Guard (`PrePaymentGuard`)
213
+
214
+ The older, simpler guard (pre-payment check only). Since 0.2.0 it also sends only the host name and is
215
+ advice-only on payTo by default; pass `policy=STRICT_GUARD_POLICY` (or `GuardPolicy(pay_to_mismatch="block")`) to
216
+ stop those payments as before. Since 0.2.0 `STRICT_GUARD_POLICY` also sets `require_request_url=True`, so it stops a
217
+ payment whose real request URL is unknown; use `wrap_get` or `x402_hook_for(url)` with it.
218
+
219
+ ```python
220
+ from x402 import x402ClientSync
221
+ from x402.mechanisms.evm import EthAccountSigner
222
+ from x402.mechanisms.evm.exact import ExactEvmScheme
223
+ from x402.http.clients import x402_requests
224
+ from botsrated import STRICT_GUARD_POLICY, PrePaymentGuard
225
+
226
+ client = x402ClientSync()
227
+ client.register("eip155:*", ExactEvmScheme(signer=EthAccountSigner(account)))
228
+ guard = PrePaymentGuard(policy=STRICT_GUARD_POLICY) # the policy is your choice
229
+ client.on_before_payment_creation(guard.x402_hook)
230
+
231
+ # Tell the guard which URL is actually being paid (since 0.1.5):
232
+ session = x402_requests(client)
233
+ paid_get = guard.wrap_get(session.get) # or: with paying_request(url): session.get(url)
234
+ paid_get("https://seller.example/api")
235
+ ```
236
+
237
+ The 402's `resource.url` is chosen by the seller, so on its own it only says which host the seller
238
+ *claims* to be. When the guard knows the request URL (`guard.wrap_get(...)`, `guard.wrap_async_get(...)`,
239
+ `with paying_request(url):`, `guard.x402_hook_for(url)`, or `guard.decide(..., request_url=url)`), it looks
240
+ up that URL's host and blocks the payment with `resource_url_mismatch` if `resource.url` names a different
241
+ host. That block applies even with `fail_open=True`. Hosts are compared after IDNA (punycode) and trailing-dot
242
+ normalization. The wrappers only see the URL you called, not where redirects ended, so a `resource.url` that
243
+ differs only by a leading `www.` (an apex <-> www redirect) is accepted (since 0.1.6); any other host is blocked. Without a request URL the host is still read from
244
+ `resource.url` (as before 0.1.5); set `GuardPolicy(require_request_url=True)` to block those payments instead.
245
+
246
+ Defaults:
247
+ - A payTo that differs from every payTo BotsRated's own probes saw for the host, on the same network, is a
248
+ **warning** (`payto_not_observed`; it was a block before 0.2.0). The seller's directory listing alone never
249
+ confirms a payTo: with no probe observation, a listing match is noted with `payto_listing_only` and a listing
250
+ mismatch follows the same rule.
251
+ - A price above the last observed price on the same route is a warning.
252
+ - A host that is not covered is allowed.
253
+ - Data older than 24 h is allowed (`data_stale`).
254
+ - If BotsRated cannot be reached (4 s timeout), the payment is allowed (`fail_open`, `botsrated_unreachable`).
255
+ - The minimum valid-402 rate is off.
256
+
257
+ Change these with `GuardPolicy(...)`. Preflight answers are cached for 5 minutes per host.
258
+
259
+ ## Opt-In Paid Lookups With A Budget
260
+
261
+ ```python
262
+ from botsrated import BotsRatedClient, PrePaymentGuard
263
+
264
+ botsrated = BotsRatedClient(budget_usd="0.05", x402_client=client) # signs only the validated quote
265
+ guard = PrePaymentGuard(botsrated, paid_check_at_or_above_usd=0.25)
266
+ client.on_before_payment_creation(guard.x402_hook)
267
+
268
+ botsrated.check("seller.example") # $0.001 (first 100/day free)
269
+ botsrated.report("seller.example") # $0.002 (first 10/day free)
270
+ botsrated.best("web search") # $0.01
271
+ ```
272
+
273
+ `x402_client=` (since 0.1.4) is the recommended mode: the client validates the 402, rebuilds it from
274
+ the allowlisted fields only (scheme, network, asset, amount, payTo, maxTimeoutSeconds, EIP-3009
275
+ `name`/`version`, resource url/description/mimeType; never `extensions`), signs that copy with
276
+ `client.create_payment_payload`, and sends `PAYMENT-SIGNATURE` itself. The signer never sees the raw
277
+ 402. The older `paying_get=x402_requests(client).get` still works, but that session re-reads the 402
278
+ itself, so register the guard on the same x402 client so the re-served 402 is checked again before signing.
279
+
280
+ How paid calls work:
281
+ - Free daily quota: the first 100 `/v1/check` and 10 `/v1/report` calls per client per UTC day are
282
+ served free (200 with `charged: false` and a `free_quota` block). The client asks unpaid first, so
283
+ inside the quota nothing is paid and the budget is untouched; `check()`/`report()` also work without
284
+ a budget until the quota is used up (then `paid_disabled`). `client.last_free_quota` shows what is left.
285
+ - Otherwise the client reads the 402 quote unpaid first. It accepts the quote only if **every** option is `exact` USDC on Base to BotsRated's payTo
286
+ `0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349`, at or below the published price.
287
+ - The amount is reserved from the budget before paying. If the paid call fails or raises, it stays counted
288
+ (the payment may already have settled), so the budget is a hard ceiling.
289
+ - Amounts must be ASCII digits only (`[0-9]+`); since 0.1.5 a quote with e.g. Arabic-Indic or full-width
290
+ digits is refused.
291
+ - Only a one-shot EIP-3009 payment is signed: an option whose `extra` holds anything beyond the token's
292
+ `name`/`version` (e.g. `assetTransferMethod: permit2`, `paymentFlow`), a missing `maxTimeoutSeconds` or one above 600
293
+ (since 0.2.0 a missing value is invalid), or payment extensions in the 402 (e.g. `erc20ApprovalGasSponsoring`;
294
+ only `bazaar` and `payment-identifier` are tolerated, and neither is signed) rejects the quote with `terms_rejected` before anything is paid.
295
+ - With `x402_client=`, if signing fails nothing can settle and the reservation is released (`payment_not_created`).
296
+ - When the guard is registered, it refuses any payment to botsrated.com that the client did not reserve or
297
+ that carries payment extensions, and strips extensions before the x402 signer runs.
298
+
299
+ ## Tests
300
+
301
+ ```bash
302
+ uv run --with pytest --with respx --with pytest-asyncio --with "x402[httpx,evm]" pytest -m "not live"
303
+ ```
304
+
305
+ Security reports: [SECURITY.md](https://github.com/botsrated/botsrated/blob/main/SECURITY.md).
306
+
307
+ License: MIT. BotsRated reports measurements, not endorsements.
308
+ BotsRated is independent and is not affiliated with or endorsed by Coinbase, the x402 Foundation or any seller. "x402" is used only to describe compatibility.