botsrated 0.2.0__tar.gz → 0.2.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: botsrated
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
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
5
  Project-URL: Homepage, https://botsrated.com
6
6
  Project-URL: Repository, https://github.com/botsrated/botsrated
@@ -30,7 +30,7 @@ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment che
30
30
 
31
31
  It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
32
32
 
33
- **Status: 0.2.0 is not released yet. The latest version on PyPI is
33
+ **Status: 0.2.1 is not released yet. The latest version on PyPI is
34
34
  [`botsrated` 0.1.6](https://pypi.org/project/botsrated/), which does not include the payment guard.**
35
35
 
36
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.
@@ -46,7 +46,20 @@ pip install "botsrated[x402]"
46
46
  Runtime dependencies: `httpx>=0.27,<1` (and, with the `x402` extra, `x402[httpx,evm]>=2.25,<3`). The guard only
47
47
  uses the hook and extension points of the x402 client you pass in.
48
48
 
49
- ## Payment Guard: Start With Dry-Run
49
+ ## Payment Guard: Pick A Preset
50
+
51
+ You set the thresholds. The guard compares the payment with facts BotsRated measured and, when the preflight included
52
+ one, a receipt link. It does not return a score or a grade.
53
+
54
+ Pick a named preset. The zero-config call (`PaymentGuard()`) is `warn`: advice only, it never stops a payment.
55
+ Dry-run is optional: it logs `would_block` and still never stops a payment.
56
+
57
+ | Name | How to select it | What you get |
58
+ |---|---|---|
59
+ | `warn` | `PaymentGuard()` or `preset="warn"` or `policy=POLICIES["warn"]` | Advice only. The default. |
60
+ | `carefulBuyer` | `preset="carefulBuyer"` or `policy=POLICIES["carefulBuyer"]` | Same rule effects as `POLICIES["strict"]`. Stops when the payTo wasn't observed, is invalid, the host mismatches, or the paid URL is unknown. |
61
+ | `strict` | `policy=POLICIES["strict"]` | The same stops as `carefulBuyer`. |
62
+ | `dry-run-only` | `dry_run_only(...)`, `preset="dry-run-only"`, or `PaymentGuard(**PRESETS["dry-run-only"])` | Logs `would_block` and never stops a payment. No retry key. `preset="dry-run-only"` and `dry_run_only()` force dry-run. |
50
63
 
51
64
  ```python
52
65
  import httpx
@@ -54,17 +67,21 @@ from x402 import x402Client
54
67
  from x402.http.clients.httpx import x402AsyncTransport
55
68
  from x402.mechanisms.evm import EthAccountSigner
56
69
  from x402.mechanisms.evm.exact import ExactEvmScheme
57
- from botsrated import PaymentGuard
70
+ from botsrated import POLICIES, PaymentGuard, dry_run_only
58
71
 
59
72
  client = x402Client()
60
73
  client.register("eip155:*", ExactEvmScheme(signer=EthAccountSigner(account)))
61
74
 
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)
75
+ # Install one of these. `guard` stops payments; `looking` only logs.
76
+ # 1. Pick a named preset. This one stops the four cases above.
77
+ guard = PaymentGuard(preset="carefulBuyer", on_decision=lambda d: print(d.message, d.facts))
65
78
 
79
+ # 2. Or look first: log would_block for those same stops, and never stop a payment.
80
+ looking = dry_run_only(policy=POLICIES["carefulBuyer"], on_decision=lambda d: print(d.would_block, d.message))
81
+
82
+ looking.install(client) # before/after/response hooks (+ the retry-key extension when not in dry-run)
66
83
  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
84
+ paid_get = looking.wrap_async_get(http.get) # tells the guard which URL is being paid
68
85
  await paid_get("https://seller.example/api")
69
86
  ```
70
87
 
@@ -77,16 +94,12 @@ you use it.
77
94
 
78
95
  Always tell the guard the URL being paid (`wrap_async_get`, `wrap_get` or `with guard.request(url):`). Without it
79
96
  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:
97
+ warning by default; `POLICIES["carefulBuyer"]` and `POLICIES["strict"]` stop the payment).
84
98
 
85
- ```python
86
- from botsrated import POLICIES, PaymentGuard
87
-
88
- guard = PaymentGuard(policy=POLICIES["strict"]) # your choice
89
- ```
99
+ `POLICIES["carefulBuyer"]` is `POLICIES["strict"]` (one rule table, two names). A price above the last observed
100
+ amount still warns. An uncovered host and a stale probe stay informational. To stop payments on your own mix,
101
+ pass a policy yourself: `dataclasses.replace(POLICIES["carefulBuyer"], price_above_observed="block")`. An explicit
102
+ `policy=` replaces the preset's rule table.
90
103
 
91
104
  A stopped payment raises the x402 abort error with text like:
92
105
 
@@ -94,7 +107,7 @@ A stopped payment raises the x402 abort error with text like:
94
107
 
95
108
  ### Rules And Defaults
96
109
 
97
- | Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["strict"]` |
110
+ | Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["carefulBuyer"]` / `POLICIES["strict"]` |
98
111
  |---|---|---|---|
99
112
  | `pay_to_mismatch`: the payTo is not among the payTos BotsRated's probes recorded for the host | `payto_not_observed` | warn | **block** |
100
113
  | `pay_to_invalid`: the payTo is not a 20-byte hex address | `payto_invalid` | warn | **block** |
@@ -108,17 +121,40 @@ A stopped payment raises the x402 abort error with text like:
108
121
 
109
122
  Each rule takes `"allow"`, `"warn"` or `"block"`, e.g.
110
123
  `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,
124
+ `paid_url_unknown` at `"warn"` unless you set it: add `paid_url_unknown="block"` (as `POLICIES["carefulBuyer"]` /
125
+ `POLICIES["strict"]` do) if an unknown paid URL should stop the payment. Every decision carries `reasons` (code, effect,
113
126
  rule, fact), `facts`, `policy_rule`, `dispute_url` and a `message`. Reason texts state facts only; seller text is
114
127
  never echoed except a parsed host name.
115
128
 
129
+ ### Facts Bundle
130
+
131
+ `decision.facts` is the bundle the guard compared. It is measurements plus a receipt link. It has no score and no grade.
132
+
133
+ | Field | What it is |
134
+ |---|---|
135
+ | `covered` | Whether BotsRated has a probe record for the host |
136
+ | `host` | Host that was looked up (only the host name was sent) |
137
+ | `known_pay_tos` | payTo addresses BotsRated's probes recorded |
138
+ | `listing_pay_to` | payTo from a directory listing, when present. A listing is not a probe observation |
139
+ | `observed_network` | Network the probes recorded |
140
+ | `observed_amount` | Last amount recorded on the probed route, in atomic units |
141
+ | `stale` | True when the latest probe is older than 24 hours |
142
+ | `receipt_url` | `https://botsrated.com/receipt/...` when the preflight included a receipt on botsrated.com |
143
+
144
+ `reasons` lists each fact (`code`, `effect` of `info`, `warn` or `block`, `rule`, `fact`). `dispute_url` is
145
+ https://botsrated.com/disputes. `would_block` is true when a rule's effect is `block`, including in dry-run, where
146
+ `action` stays `allow`.
147
+
148
+ The hosted preflight body is larger (see the MCP facts bundle in the repository README). The guard keeps this
149
+ smaller local bundle and does not copy a score out of it, because the response has none.
150
+
116
151
  ### Options
117
152
 
118
153
  | Option | Default | Meaning |
119
154
  |---|---|---|
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 |
155
+ | `preset` | omitted (behaves as `warn`) | `warn`, `carefulBuyer`, or `dry-run-only`. `dry-run-only` forces dry-run |
156
+ | `policy` | `POLICIES["warn"]` | Which facts warn and which stop a payment. Replaces the preset's rule table when set |
157
+ | `dry_run` | `False` | Log decisions, stop nothing, add no retry key. Forced on for preset `dry-run-only` |
122
158
  | `hosted` | `True` | `False`: nothing is sent to botsrated.com |
123
159
  | `fail_open` | `True` | `False`: stop the payment when BotsRated can't be reached or the guard errors |
124
160
  | `retry_key` | `True` | Add a `payment-identifier` id where the seller advertises it |
@@ -284,8 +320,8 @@ botsrated = BotsRatedClient(budget_usd="0.05", x402_client=client) # signs onl
284
320
  guard = PrePaymentGuard(botsrated, paid_check_at_or_above_usd=0.25)
285
321
  client.on_before_payment_creation(guard.x402_hook)
286
322
 
287
- botsrated.check("seller.example") # $0.001 (first 100/day free)
288
- botsrated.report("seller.example") # $0.002 (first 10/day free)
323
+ botsrated.check("seller.example") # $0.001 (first 25 per UTC day free)
324
+ botsrated.report("seller.example") # $0.002 (first 3 per UTC day free)
289
325
  botsrated.best("web search") # $0.01
290
326
  ```
291
327
 
@@ -297,10 +333,11 @@ the allowlisted fields only (scheme, network, asset, amount, payTo, maxTimeoutSe
297
333
  itself, so register the guard on the same x402 client so the re-served 402 is checked again before signing.
298
334
 
299
335
  How paid calls work:
300
- - Free daily quota: the first 100 `/v1/check` and 10 `/v1/report` calls per client per UTC day are
336
+ - Free daily quota (`FREE_DAILY_QUOTA`): the first 25 `/v1/check` and 3 `/v1/report` calls per client per UTC day are
301
337
  served free (200 with `charged: false` and a `free_quota` block). The client asks unpaid first, so
302
338
  inside the quota nothing is paid and the budget is untouched; `check()`/`report()` also work without
303
339
  a budget until the quota is used up (then `paid_disabled`). `client.last_free_quota` shows what is left.
340
+ `/v1/best` has no free quota. Preflight stays free and unlimited.
304
341
  - 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
342
  `0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349`, at or below the published price.
306
343
  - The amount is reserved from the budget before paying. If the paid call fails or raises, it stays counted
@@ -11,7 +11,7 @@ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment che
11
11
 
12
12
  It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
13
13
 
14
- **Status: 0.2.0 is not released yet. The latest version on PyPI is
14
+ **Status: 0.2.1 is not released yet. The latest version on PyPI is
15
15
  [`botsrated` 0.1.6](https://pypi.org/project/botsrated/), which does not include the payment guard.**
16
16
 
17
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.
@@ -27,7 +27,20 @@ pip install "botsrated[x402]"
27
27
  Runtime dependencies: `httpx>=0.27,<1` (and, with the `x402` extra, `x402[httpx,evm]>=2.25,<3`). The guard only
28
28
  uses the hook and extension points of the x402 client you pass in.
29
29
 
30
- ## Payment Guard: Start With Dry-Run
30
+ ## Payment Guard: Pick A Preset
31
+
32
+ You set the thresholds. The guard compares the payment with facts BotsRated measured and, when the preflight included
33
+ one, a receipt link. It does not return a score or a grade.
34
+
35
+ Pick a named preset. The zero-config call (`PaymentGuard()`) is `warn`: advice only, it never stops a payment.
36
+ Dry-run is optional: it logs `would_block` and still never stops a payment.
37
+
38
+ | Name | How to select it | What you get |
39
+ |---|---|---|
40
+ | `warn` | `PaymentGuard()` or `preset="warn"` or `policy=POLICIES["warn"]` | Advice only. The default. |
41
+ | `carefulBuyer` | `preset="carefulBuyer"` or `policy=POLICIES["carefulBuyer"]` | Same rule effects as `POLICIES["strict"]`. Stops when the payTo wasn't observed, is invalid, the host mismatches, or the paid URL is unknown. |
42
+ | `strict` | `policy=POLICIES["strict"]` | The same stops as `carefulBuyer`. |
43
+ | `dry-run-only` | `dry_run_only(...)`, `preset="dry-run-only"`, or `PaymentGuard(**PRESETS["dry-run-only"])` | Logs `would_block` and never stops a payment. No retry key. `preset="dry-run-only"` and `dry_run_only()` force dry-run. |
31
44
 
32
45
  ```python
33
46
  import httpx
@@ -35,17 +48,21 @@ from x402 import x402Client
35
48
  from x402.http.clients.httpx import x402AsyncTransport
36
49
  from x402.mechanisms.evm import EthAccountSigner
37
50
  from x402.mechanisms.evm.exact import ExactEvmScheme
38
- from botsrated import PaymentGuard
51
+ from botsrated import POLICIES, PaymentGuard, dry_run_only
39
52
 
40
53
  client = x402Client()
41
54
  client.register("eip155:*", ExactEvmScheme(signer=EthAccountSigner(account)))
42
55
 
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)
56
+ # Install one of these. `guard` stops payments; `looking` only logs.
57
+ # 1. Pick a named preset. This one stops the four cases above.
58
+ guard = PaymentGuard(preset="carefulBuyer", on_decision=lambda d: print(d.message, d.facts))
46
59
 
60
+ # 2. Or look first: log would_block for those same stops, and never stop a payment.
61
+ looking = dry_run_only(policy=POLICIES["carefulBuyer"], on_decision=lambda d: print(d.would_block, d.message))
62
+
63
+ looking.install(client) # before/after/response hooks (+ the retry-key extension when not in dry-run)
47
64
  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
65
+ paid_get = looking.wrap_async_get(http.get) # tells the guard which URL is being paid
49
66
  await paid_get("https://seller.example/api")
50
67
  ```
51
68
 
@@ -58,16 +75,12 @@ you use it.
58
75
 
59
76
  Always tell the guard the URL being paid (`wrap_async_get`, `wrap_get` or `with guard.request(url):`). Without it
60
77
  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:
78
+ warning by default; `POLICIES["carefulBuyer"]` and `POLICIES["strict"]` stop the payment).
65
79
 
66
- ```python
67
- from botsrated import POLICIES, PaymentGuard
68
-
69
- guard = PaymentGuard(policy=POLICIES["strict"]) # your choice
70
- ```
80
+ `POLICIES["carefulBuyer"]` is `POLICIES["strict"]` (one rule table, two names). A price above the last observed
81
+ amount still warns. An uncovered host and a stale probe stay informational. To stop payments on your own mix,
82
+ pass a policy yourself: `dataclasses.replace(POLICIES["carefulBuyer"], price_above_observed="block")`. An explicit
83
+ `policy=` replaces the preset's rule table.
71
84
 
72
85
  A stopped payment raises the x402 abort error with text like:
73
86
 
@@ -75,7 +88,7 @@ A stopped payment raises the x402 abort error with text like:
75
88
 
76
89
  ### Rules And Defaults
77
90
 
78
- | Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["strict"]` |
91
+ | Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["carefulBuyer"]` / `POLICIES["strict"]` |
79
92
  |---|---|---|---|
80
93
  | `pay_to_mismatch`: the payTo is not among the payTos BotsRated's probes recorded for the host | `payto_not_observed` | warn | **block** |
81
94
  | `pay_to_invalid`: the payTo is not a 20-byte hex address | `payto_invalid` | warn | **block** |
@@ -89,17 +102,40 @@ A stopped payment raises the x402 abort error with text like:
89
102
 
90
103
  Each rule takes `"allow"`, `"warn"` or `"block"`, e.g.
91
104
  `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,
105
+ `paid_url_unknown` at `"warn"` unless you set it: add `paid_url_unknown="block"` (as `POLICIES["carefulBuyer"]` /
106
+ `POLICIES["strict"]` do) if an unknown paid URL should stop the payment. Every decision carries `reasons` (code, effect,
94
107
  rule, fact), `facts`, `policy_rule`, `dispute_url` and a `message`. Reason texts state facts only; seller text is
95
108
  never echoed except a parsed host name.
96
109
 
110
+ ### Facts Bundle
111
+
112
+ `decision.facts` is the bundle the guard compared. It is measurements plus a receipt link. It has no score and no grade.
113
+
114
+ | Field | What it is |
115
+ |---|---|
116
+ | `covered` | Whether BotsRated has a probe record for the host |
117
+ | `host` | Host that was looked up (only the host name was sent) |
118
+ | `known_pay_tos` | payTo addresses BotsRated's probes recorded |
119
+ | `listing_pay_to` | payTo from a directory listing, when present. A listing is not a probe observation |
120
+ | `observed_network` | Network the probes recorded |
121
+ | `observed_amount` | Last amount recorded on the probed route, in atomic units |
122
+ | `stale` | True when the latest probe is older than 24 hours |
123
+ | `receipt_url` | `https://botsrated.com/receipt/...` when the preflight included a receipt on botsrated.com |
124
+
125
+ `reasons` lists each fact (`code`, `effect` of `info`, `warn` or `block`, `rule`, `fact`). `dispute_url` is
126
+ https://botsrated.com/disputes. `would_block` is true when a rule's effect is `block`, including in dry-run, where
127
+ `action` stays `allow`.
128
+
129
+ The hosted preflight body is larger (see the MCP facts bundle in the repository README). The guard keeps this
130
+ smaller local bundle and does not copy a score out of it, because the response has none.
131
+
97
132
  ### Options
98
133
 
99
134
  | Option | Default | Meaning |
100
135
  |---|---|---|
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 |
136
+ | `preset` | omitted (behaves as `warn`) | `warn`, `carefulBuyer`, or `dry-run-only`. `dry-run-only` forces dry-run |
137
+ | `policy` | `POLICIES["warn"]` | Which facts warn and which stop a payment. Replaces the preset's rule table when set |
138
+ | `dry_run` | `False` | Log decisions, stop nothing, add no retry key. Forced on for preset `dry-run-only` |
103
139
  | `hosted` | `True` | `False`: nothing is sent to botsrated.com |
104
140
  | `fail_open` | `True` | `False`: stop the payment when BotsRated can't be reached or the guard errors |
105
141
  | `retry_key` | `True` | Add a `payment-identifier` id where the seller advertises it |
@@ -265,8 +301,8 @@ botsrated = BotsRatedClient(budget_usd="0.05", x402_client=client) # signs onl
265
301
  guard = PrePaymentGuard(botsrated, paid_check_at_or_above_usd=0.25)
266
302
  client.on_before_payment_creation(guard.x402_hook)
267
303
 
268
- botsrated.check("seller.example") # $0.001 (first 100/day free)
269
- botsrated.report("seller.example") # $0.002 (first 10/day free)
304
+ botsrated.check("seller.example") # $0.001 (first 25 per UTC day free)
305
+ botsrated.report("seller.example") # $0.002 (first 3 per UTC day free)
270
306
  botsrated.best("web search") # $0.01
271
307
  ```
272
308
 
@@ -278,10 +314,11 @@ the allowlisted fields only (scheme, network, asset, amount, payTo, maxTimeoutSe
278
314
  itself, so register the guard on the same x402 client so the re-served 402 is checked again before signing.
279
315
 
280
316
  How paid calls work:
281
- - Free daily quota: the first 100 `/v1/check` and 10 `/v1/report` calls per client per UTC day are
317
+ - Free daily quota (`FREE_DAILY_QUOTA`): the first 25 `/v1/check` and 3 `/v1/report` calls per client per UTC day are
282
318
  served free (200 with `charged: false` and a `free_quota` block). The client asks unpaid first, so
283
319
  inside the quota nothing is paid and the budget is untouched; `check()`/`report()` also work without
284
320
  a budget until the quota is used up (then `paid_disabled`). `client.last_free_quota` shows what is left.
321
+ `/v1/best` has no free quota. Preflight stays free and unlimited.
285
322
  - 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
323
  `0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349`, at or below the published price.
287
324
  - The amount is reserved from the budget before paying. If the paid call fails or raises, it stays counted
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "botsrated"
3
- version = "0.2.0"
3
+ version = "0.2.1"
4
4
  description = "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
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -14,11 +14,13 @@ from botsrated.onchain import (
14
14
  )
15
15
  from botsrated.payment_guard import (
16
16
  POLICIES,
17
+ PRESETS,
17
18
  GuardDecision,
18
19
  GuardFacts,
19
20
  GuardReason,
20
21
  PaymentGuard,
21
22
  PaymentGuardPolicy,
23
+ dry_run_only,
22
24
  )
23
25
  from botsrated.util import (
24
26
  BASE_MAINNET,
@@ -110,6 +112,7 @@ __all__ = [
110
112
  "FREE_DAILY_QUOTA",
111
113
  "PAID_ROUTE_MAX_ATOMIC",
112
114
  "POLICIES",
115
+ "PRESETS",
113
116
  "PRIVACY_URL",
114
117
  "STRICT_GUARD_POLICY",
115
118
  "TERMS_URL",
@@ -134,6 +137,7 @@ __all__ = [
134
137
  "acheck_payment_state",
135
138
  "check_payment_state",
136
139
  "current_request_url",
140
+ "dry_run_only",
137
141
  "evaluate_payment",
138
142
  "facts_from",
139
143
  "host_of",
@@ -42,8 +42,8 @@ __all__ = [
42
42
  BOTSRATED_PAY_TO = "0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349"
43
43
  # Published prices (since 2026-10-23) in atomic USDC. Quotes above these are refused.
44
44
  PAID_ROUTE_MAX_ATOMIC: dict[str, int] = {"check": 1000, "report": 2000, "best": 10000}
45
- # Free calls per client (IP) per UTC day. Inside the quota BotsRated answers 200 with charged: false, no 402.
46
- FREE_DAILY_QUOTA: dict[str, int] = {"check": 100, "report": 10, "best": 0}
45
+ # Free calls per client (IP) per UTC day: 25 checks, 3 reports. Inside the quota BotsRated answers 200 with charged: false, no 402.
46
+ FREE_DAILY_QUOTA: dict[str, int] = {"check": 25, "report": 3, "best": 0}
47
47
  # Longest payment authorization window accepted for a BotsRated payment.
48
48
  MAX_TIMEOUT_SECONDS = 600
49
49
  # EIP-3009 needs only the token's EIP-712 domain name/version. Any other ``extra`` key (e.g.
@@ -254,11 +254,11 @@ class BotsRatedClient:
254
254
  return result
255
255
 
256
256
  def check(self, url_or_host: str) -> dict[str, Any]:
257
- """Paid ($0.001; first 100/day free). Facts, paid test-buys and recent receipts for one host."""
257
+ """Paid ($0.001; first 25 per UTC day free). Facts, paid test-buys and recent receipts for one host."""
258
258
  return self._paid(f"/v1/check?host={quote(host_of(url_or_host), safe='')}", "check")
259
259
 
260
260
  def report(self, url_or_host: str) -> dict[str, Any]:
261
- """Paid ($0.002; first 10/day free). Full receipt history for one host."""
261
+ """Paid ($0.002; first 3 per UTC day free). Full receipt history for one host."""
262
262
  return self._paid(f"/v1/report/{quote(host_of(url_or_host), safe='')}", "report")
263
263
 
264
264
  def best(self, task: str, sort: str | None = None, max_price_usd: float | None = None) -> dict[str, Any]:
@@ -221,7 +221,7 @@ class PrePaymentGuard:
221
221
  policy: What to block or warn on.
222
222
  fail_open: Allow the payment when BotsRated is unreachable. Default True.
223
223
  paid_check_at_or_above_usd: Run a check for payments at or above this: free within the daily quota
224
- (100/day), then a $0.001 paid check with a paid-enabled client (skipped otherwise).
224
+ (25 per UTC day), then a $0.001 paid check with a paid-enabled client (skipped otherwise).
225
225
  on_decision: Called with every decision.
226
226
  """
227
227
 
@@ -4,7 +4,8 @@ What it does, and nothing more:
4
4
 
5
5
  - Before your agent signs: looks up facts BotsRated measured about the seller's HOST (only the host name is sent to
6
6
  botsrated.com) and compares them locally with the payment request. Advice-only by default: it reports facts and
7
- stops a payment only when you choose a blocking policy (e.g. ``POLICIES["strict"]``).
7
+ stops a payment only when you choose a blocking policy (e.g. ``POLICIES["carefulBuyer"]``, an alias of
8
+ ``POLICIES["strict"]``).
8
9
  - While the payload is built: adds a random x402 ``payment-identifier`` retry key, only when the seller advertises
9
10
  that extension, through x402's extension mechanism.
10
11
  - After: records the payment locally (never the signature) and offers a read-only on-chain check of whether it
@@ -71,18 +72,35 @@ class PaymentGuardPolicy:
71
72
  price_above_observed: RuleEffect = "warn" # same route, amount above the last one recorded
72
73
  resource_host_mismatch: RuleEffect = "warn" # 402 resource.url names another host (checked locally)
73
74
  # The URL being paid is unknown to the guard (no ``guard.request(url)`` / ``wrap_get``), so the host comes only
74
- # from the seller's own 402. Advice by default; POLICIES["strict"] blocks.
75
+ # from the seller's own 402. Advice by default; POLICIES["strict"] / POLICIES["carefulBuyer"] block.
75
76
  paid_url_unknown: RuleEffect = "warn"
76
77
  not_covered: RuleEffect = "allow" # reported as info
77
78
  stale: RuleEffect = "allow" # reported as info
78
79
 
79
80
 
81
+ _WARN = PaymentGuardPolicy()
82
+ # Stops a payment when the payTo wasn't observed, is invalid, the 402 names another host, or the URL being paid is
83
+ # unknown (use guard.request(url) or wrap_get). A price above the last observed amount still warns.
84
+ _STRICT = PaymentGuardPolicy(pay_to_mismatch="block", pay_to_invalid="block", resource_host_mismatch="block", paid_url_unknown="block")
85
+
86
+ # Rule-effect tables. Choosing one is your decision; the zero-config default is POLICIES["warn"].
80
87
  POLICIES: dict[str, PaymentGuardPolicy] = {
81
88
  # Advice only: never stops a payment. The default.
82
- "warn": PaymentGuardPolicy(),
83
- # Stops a payment when the payTo was not recorded by BotsRated's probes, is not an address, the 402 names another
84
- # host, or the URL being paid is unknown (use guard.request(url) or wrap_get).
85
- "strict": PaymentGuardPolicy(pay_to_mismatch="block", pay_to_invalid="block", resource_host_mismatch="block", paid_url_unknown="block"),
89
+ "warn": _WARN,
90
+ # Same effects as "carefulBuyer".
91
+ "strict": _STRICT,
92
+ # Friendly alias of "strict". Stops when the payTo wasn't observed, is invalid, the host mismatches, or the paid
93
+ # URL is unknown.
94
+ "carefulBuyer": _STRICT,
95
+ }
96
+
97
+ # Named ways to start the guard. Unpack one into PaymentGuard(...), or pass its name as preset=.
98
+ # carefulBuyer is the stricter rule table. "dry-run-only" is advice: it does not add a new rule.
99
+ PRESETS: dict[str, dict[str, Any]] = {
100
+ "warn": {"policy": POLICIES["warn"]},
101
+ "carefulBuyer": {"policy": POLICIES["carefulBuyer"]},
102
+ # Log would_block, never stop a payment, add no retry key. The rule table stays warn unless you pass another.
103
+ "dry-run-only": {"dry_run": True, "policy": POLICIES["warn"]},
86
104
  }
87
105
 
88
106
  _RULE_NAMES = {
@@ -106,6 +124,8 @@ class GuardReason:
106
124
 
107
125
  @dataclass
108
126
  class GuardFacts:
127
+ """Facts the guard compared: measurements and, when present, a receipt link. No score and no grade."""
128
+
109
129
  covered: bool
110
130
  host: str
111
131
  known_pay_tos: list[str] = field(default_factory=list)
@@ -342,8 +362,12 @@ class PaymentGuard:
342
362
  """Payment guard. Zero-config: advice only, hosted host-name lookup, fail-open, retry key where advertised.
343
363
 
344
364
  Args:
365
+ preset: ``warn`` (advice only), ``carefulBuyer`` (same stops as ``POLICIES["strict"]``), or ``dry-run-only``
366
+ (log ``would_block``, never stop a payment). ``dry-run-only`` forces dry-run even when ``dry_run=False``.
367
+ An explicit ``policy`` replaces the preset's rule table. The zero-config default is ``warn``.
345
368
  policy: Which facts warn or stop a payment. Default ``POLICIES["warn"]`` (advice only).
346
- dry_run: Log decisions and change nothing (no payment stopped, no retry key added). Recommended first setting.
369
+ dry_run: Log decisions and change nothing (no payment stopped, no retry key added). Ignored when
370
+ ``preset`` is ``dry-run-only`` (that preset always dry-runs).
347
371
  hosted: Call BotsRated's free hosted preflight. With False nothing is sent to botsrated.com.
348
372
  fail_open: When BotsRated can't be reached (or the guard errors): True allows (default), False stops.
349
373
  retry_key: Add a ``payment-identifier`` id where the seller advertises it. Default True.
@@ -357,6 +381,7 @@ class PaymentGuard:
357
381
  def __init__(
358
382
  self,
359
383
  *,
384
+ preset: str | None = None,
360
385
  policy: PaymentGuardPolicy | None = None,
361
386
  dry_run: bool = False,
362
387
  hosted: bool = True,
@@ -371,11 +396,16 @@ class PaymentGuard:
371
396
  preflight: Callable[[str], tuple[bool, dict[str, Any]]] | None = None,
372
397
  on_decision: Callable[[GuardDecision], None] | None = None,
373
398
  ) -> None:
374
- self.policy = policy or POLICIES["warn"]
375
- self.dry_run = dry_run
399
+ if preset is not None and preset not in PRESETS:
400
+ raise ValueError(f'Unknown payment guard preset "{preset}". Expected warn, carefulBuyer, or dry-run-only.')
401
+ named = PRESETS[preset] if preset is not None else {}
402
+ # An explicit policy replaces the preset's rule table. dry-run-only forces advice even if dry_run=False.
403
+ self.preset = preset
404
+ self.policy = policy if policy is not None else named.get("policy", POLICIES["warn"])
405
+ self.dry_run = True if preset == "dry-run-only" else dry_run
376
406
  self.hosted = hosted
377
407
  self.fail_open = fail_open
378
- self.retry_key = retry_key and not dry_run
408
+ self.retry_key = retry_key and not self.dry_run
379
409
  if onchain: # configuration errors (more than 3 RPCs) surface here, not mid-payment
380
410
  rpc_list_of(onchain.get("rpcs", DEFAULT_BASE_RPCS), onchain.get("extra_rpc"))
381
411
  self.onchain = onchain
@@ -822,6 +852,17 @@ class PaymentGuard:
822
852
  return out
823
853
 
824
854
 
855
+ def dry_run_only(**kwargs: Any) -> PaymentGuard:
856
+ """Named preset ``dry-run-only``. Logs ``would_block`` and never stops a payment, even if ``policy`` would.
857
+
858
+ Dry-run is forced; passing ``dry_run=False`` does not turn it off. The rule table stays ``POLICIES["warn"]``
859
+ unless you pass ``policy`` (for example ``POLICIES["carefulBuyer"]``, to log the stops that preset would make).
860
+ """
861
+ kwargs.pop("dry_run", None)
862
+ kwargs["preset"] = "dry-run-only"
863
+ return PaymentGuard(**kwargs)
864
+
865
+
825
866
  def decision_as_dict(d: GuardDecision) -> dict[str, Any]:
826
867
  """JSON-friendly view of a decision (for logging)."""
827
868
  out = asdict(d)
@@ -6,7 +6,7 @@ import re
6
6
  from typing import Any
7
7
  from urllib.parse import urlsplit
8
8
 
9
- VERSION = "0.2.0"
9
+ VERSION = "0.2.1"
10
10
  # Sent on hosted BotsRated calls. No install id, wallet or other user identifier.
11
11
  USER_AGENT = f"botsrated-python/{VERSION}"
12
12
  BOTSRATED_BASE_URL = "https://botsrated.com"
@@ -227,7 +227,7 @@ def test_free_quota_answer_is_not_charged(found, free_check):
227
227
  m.get("/v1/check").respond(200, json=free_check)
228
228
  c = BotsRatedClient(budget_usd="0.005", paying_get=lambda u: pytest.fail("must not pay"))
229
229
  out = c.check("www.ax1.vc")
230
- assert out["charged"] is False and out["free_quota"]["limit"] == 100
230
+ assert out["charged"] is False and out["free_quota"]["limit"] == 100 # 2026-10-23 capture; current quota is FREE_DAILY_QUOTA["check"]
231
231
  assert c.budget.spent_atomic == 0 and c.budget.remaining_atomic == 5000
232
232
  assert c.last_free_quota["remaining"] == out["free_quota"]["remaining"]
233
233
  # works without a paid config while the quota lasts
@@ -13,6 +13,7 @@ import pytest
13
13
 
14
14
  from botsrated import (
15
15
  POLICIES,
16
+ PRESETS,
16
17
  STRICT_GUARD_POLICY,
17
18
  USER_AGENT,
18
19
  VERSION,
@@ -20,6 +21,7 @@ from botsrated import (
20
21
  PaymentGuard,
21
22
  PaymentGuardPolicy,
22
23
  PrePaymentGuard,
24
+ dry_run_only,
23
25
  evaluate_payment,
24
26
  facts_from,
25
27
  )
@@ -149,6 +151,110 @@ def test_botsrated_note_only_for_real_botsrated_request(found):
149
151
  def test_policies_expose_paid_url_unknown():
150
152
  assert POLICIES["warn"].paid_url_unknown == "warn"
151
153
  assert POLICIES["strict"].paid_url_unknown == "block"
154
+ assert POLICIES["carefulBuyer"].paid_url_unknown == "block"
155
+
156
+
157
+ def _policy_table() -> dict:
158
+ return json.loads((Path(__file__).resolve().parents[2] / "fixtures" / "payment-guard-policies.json").read_text())
159
+
160
+
161
+ def _effects(table: dict, name: str) -> dict:
162
+ spec = table["presets"][name]
163
+ return table["presets"]["strict"] if spec == "strict" else spec
164
+
165
+
166
+ def test_careful_buyer_matches_the_shared_rule_table():
167
+ from dataclasses import fields
168
+
169
+ table = _policy_table()
170
+ assert POLICIES["carefulBuyer"] is POLICIES["strict"]
171
+ assert {f.name for f in fields(PaymentGuardPolicy)} == set(table["pythonFields"].values())
172
+ for name in ("warn", "strict", "carefulBuyer"):
173
+ for field, py_name in table["pythonFields"].items():
174
+ assert getattr(POLICIES[name], py_name) == _effects(table, name)[field]
175
+ assert PRESETS["carefulBuyer"]["policy"] is POLICIES["carefulBuyer"]
176
+ assert PRESETS["dry-run-only"] == {"dry_run": True, "policy": POLICIES["warn"]}
177
+
178
+
179
+ def test_careful_buyer_stops_the_four_strict_cases(found):
180
+ pytest.importorskip("x402")
181
+ url = found["latest_probe"]["url"]
182
+ seen = []
183
+ g, _ = guard_with(found, preset="carefulBuyer", on_decision=seen.append)
184
+ with g.request(url):
185
+ out = g.before_payment_creation(ctx(url, req(found, payTo=DEAD)))
186
+ assert out is not None and seen[0].policy_rule == "payToMismatch"
187
+ assert seen[0].facts.covered is True and seen[0].facts.host == "blockrun.ai"
188
+ assert seen[0].facts.receipt_url == found["latest_probe"]["receipt_url"]
189
+ assert not hasattr(seen[0].facts, "score") and not hasattr(seen[0].facts, "grade")
190
+
191
+ with g.request(url):
192
+ assert g.before_payment_creation(ctx(url, req(found, payTo="junk"))) is not None
193
+ assert seen[1].policy_rule == "payToInvalid"
194
+
195
+ with g.request(url):
196
+ assert g.before_payment_creation(ctx("https://other.example/x", req(found))) is not None
197
+ assert seen[2].policy_rule == "resourceHostMismatch"
198
+
199
+ assert g.before_payment_creation(ctx(url, req(found))) is not None
200
+ assert seen[3].policy_rule == "paidUrlUnknown"
201
+
202
+ with g.request(url):
203
+ assert g.before_payment_creation(ctx(url, req(found, amount="999999"))) is None
204
+ assert seen[4].action == "allow" and not seen[4].would_block
205
+ assert any(r.code == "price_above_observed" and r.effect == "warn" for r in seen[4].reasons)
206
+
207
+ uncovered, _ = guard_with(
208
+ found,
209
+ answer=lambda r: httpx.Response(404, json={"error": {"code": "host_not_covered"}}),
210
+ policy=POLICIES["carefulBuyer"],
211
+ on_decision=seen.append,
212
+ )
213
+ with uncovered.request("https://x.example/a"):
214
+ assert uncovered.before_payment_creation(ctx("https://x.example/a", req(found))) is None
215
+ assert seen[5].action == "allow"
216
+ assert any(r.code == "not_covered" and r.effect == "info" for r in seen[5].reasons)
217
+
218
+
219
+ def test_dry_run_only_logs_would_block_and_never_stops(found):
220
+ pytest.importorskip("x402")
221
+ url = found["latest_probe"]["url"]
222
+ seen = []
223
+ rec = Recorder(lambda r: httpx.Response(200, json=found))
224
+ g = dry_run_only(policy=POLICIES["carefulBuyer"], dry_run=False, http=httpx.Client(transport=httpx.MockTransport(rec)), on_decision=seen.append)
225
+ assert g.dry_run is True and g.preset == "dry-run-only"
226
+ with g.request(url):
227
+ assert g.before_payment_creation(ctx(url, req(found, payTo=DEAD))) is None
228
+ assert seen[0].action == "allow" and seen[0].would_block and seen[0].dry_run and seen[0].policy_rule == "payToMismatch"
229
+ assert seen[0].message.startswith("Dry run: your payment policy would stop this payment")
230
+ calls: list[str] = []
231
+ client = SimpleNamespace(
232
+ on_before_payment_creation=lambda h: calls.append("before"),
233
+ on_after_payment_creation=lambda h: calls.append("after"),
234
+ on_payment_response=lambda h: calls.append("response"),
235
+ register_extension=lambda e: calls.append("extension"),
236
+ )
237
+ g.install(client, asynchronous=False)
238
+ assert calls == ["before", "after", "response"]
239
+
240
+ forced, _ = guard_with(found, preset="dry-run-only", dry_run=False, policy=POLICIES["carefulBuyer"], on_decision=seen.append)
241
+ assert forced.dry_run is True
242
+ with forced.request(url):
243
+ assert forced.before_payment_creation(ctx(url, req(found, payTo=DEAD))) is None
244
+ assert seen[1].action == "allow" and seen[1].would_block and seen[1].dry_run
245
+
246
+ spread = PaymentGuard(**{**PRESETS["dry-run-only"], "http": httpx.Client(transport=httpx.MockTransport(rec)), "on_decision": seen.append})
247
+ with spread.request(url):
248
+ assert spread.before_payment_creation(ctx(url, req(found, payTo=DEAD))) is None
249
+ assert seen[2].action == "allow" and seen[2].dry_run and not seen[2].would_block
250
+ assert any(r.code == "payto_not_observed" and r.effect == "warn" for r in seen[2].reasons)
251
+
252
+
253
+ def test_unknown_preset_is_a_configuration_error_and_zero_config_stays_warn():
254
+ with pytest.raises(ValueError, match='Unknown payment guard preset "nope"'):
255
+ PaymentGuard(preset="nope", hosted=False)
256
+ g = PaymentGuard(hosted=False)
257
+ assert g.preset is None and g.dry_run is False and g.policy is POLICIES["warn"]
152
258
 
153
259
 
154
260
  def test_no_lookup_says_no_seller_facts_were_checked(found):
File without changes
File without changes
File without changes