x402-payee-guard 0.1.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.
- x402_payee_guard-0.1.0/LICENSE +21 -0
- x402_payee_guard-0.1.0/PKG-INFO +173 -0
- x402_payee_guard-0.1.0/README.md +143 -0
- x402_payee_guard-0.1.0/pyproject.toml +40 -0
- x402_payee_guard-0.1.0/src/x402_payee_guard/__init__.py +30 -0
- x402_payee_guard-0.1.0/src/x402_payee_guard/guard.py +295 -0
- x402_payee_guard-0.1.0/src/x402_payee_guard/py.typed +0 -0
- x402_payee_guard-0.1.0/tests/test_guard.py +186 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Veriql
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: x402-payee-guard
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Screen the payee before your x402 agent pays: blocks sanctioned, drainer and stablecoin-frozen addresses with one line on x402Client.
|
|
5
|
+
Project-URL: Homepage, https://veriql.app
|
|
6
|
+
Project-URL: Documentation, https://veriql.app/openapi.json
|
|
7
|
+
Project-URL: x402scan listing, https://www.x402scan.com/server/b43a466b-e90b-41bf-a7a8-1502cde22f10
|
|
8
|
+
Author: Veriql
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agent-payments,ai-agents,compliance,ofac,payee-screening,sanctions,stablecoin,usdc,usdt,x402
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
21
|
+
Classifier: Topic :: Security
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: x402>=2.20
|
|
25
|
+
Provides-Extra: httpx
|
|
26
|
+
Requires-Dist: x402[httpx]>=2.20; extra == 'httpx'
|
|
27
|
+
Provides-Extra: requests
|
|
28
|
+
Requires-Dist: x402[requests]>=2.20; extra == 'requests'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# x402-payee-guard
|
|
32
|
+
|
|
33
|
+
Screen the payee before your x402 agent pays.
|
|
34
|
+
|
|
35
|
+
An x402 client pays whatever `payTo` address a 402 response names. An agent
|
|
36
|
+
that finds sellers on its own will, sooner or later, be handed an address it
|
|
37
|
+
has never seen. This package adds one hook to the official
|
|
38
|
+
[x402 Python SDK](https://pypi.org/project/x402/): before the client signs a
|
|
39
|
+
payment, it looks up the `payTo` address and aborts the payment when the
|
|
40
|
+
address is
|
|
41
|
+
|
|
42
|
+
- on the US Treasury OFAC SDN sanctions list,
|
|
43
|
+
- a known drainer, phishing or scam address, or
|
|
44
|
+
- frozen by a stablecoin issuer (Tether or Circle; EVM and Tron addresses) —
|
|
45
|
+
USDT or USDC sent there can never be moved out again.
|
|
46
|
+
|
|
47
|
+
EVM, Bitcoin, Solana and Tron addresses are accepted.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from x402 import x402ClientSync
|
|
51
|
+
from x402_payee_guard import guard_payees
|
|
52
|
+
|
|
53
|
+
client = x402ClientSync()
|
|
54
|
+
# client.register("eip155:*", ExactEvmScheme(signer=...)) # your usual setup
|
|
55
|
+
guard_payees(client)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
That's it. Every payment the client creates afterwards is screened first. A
|
|
59
|
+
`do_not_pay` payee makes the client raise `x402.PaymentAbortedError` instead of
|
|
60
|
+
signing.
|
|
61
|
+
|
|
62
|
+
## Cost and who runs the lookup — please read
|
|
63
|
+
|
|
64
|
+
The lookup is [Veriql](https://veriql.app)'s `/api/v1/payee` endpoint, and
|
|
65
|
+
**each uncached lookup costs USD 0.01**, paid over x402 in USDC on Base from the
|
|
66
|
+
same wallet your client already pays with. This package is made by Veriql,
|
|
67
|
+
which runs that endpoint.
|
|
68
|
+
|
|
69
|
+
- Answers are cached per address: `no_known_risk` for 1 hour, `do_not_pay` for
|
|
70
|
+
24 hours (both configurable), so an agent that pays the same seller all day
|
|
71
|
+
pays for one lookup an hour.
|
|
72
|
+
- The guard's own USD 0.01 payment to Veriql is not screened again.
|
|
73
|
+
- Pass `trusted=[...]` for sellers you already know; they are never looked up.
|
|
74
|
+
- Prefer another provider or your own list? Pass `fetcher=` and nothing is
|
|
75
|
+
sent to Veriql (see below).
|
|
76
|
+
|
|
77
|
+
## Install
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install "x402-payee-guard[requests]" # for x402ClientSync
|
|
81
|
+
pip install "x402-payee-guard[httpx]" # for the async x402Client
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Python 3.10+. The only dependency is `x402` (2.20 or newer).
|
|
85
|
+
|
|
86
|
+
## Async client
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from x402 import x402Client
|
|
90
|
+
from x402.http.clients import x402HttpxClient
|
|
91
|
+
from x402_payee_guard import guard_payees
|
|
92
|
+
|
|
93
|
+
client = x402Client()
|
|
94
|
+
# client.register("eip155:*", ExactEvmScheme(signer=...))
|
|
95
|
+
guard_payees(client)
|
|
96
|
+
|
|
97
|
+
async with x402HttpxClient(client) as http:
|
|
98
|
+
r = await http.get("https://seller.example/paid-endpoint")
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Options
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
guard = guard_payees(
|
|
105
|
+
client,
|
|
106
|
+
allow_ttl=3600, # seconds a no_known_risk answer is reused
|
|
107
|
+
block_ttl=86400, # seconds a do_not_pay answer is reused
|
|
108
|
+
trusted=["0x..."], # never looked up
|
|
109
|
+
on_incomplete="allow", # or "block" when not every check could answer
|
|
110
|
+
on_error="allow", # or "block" when the lookup itself fails
|
|
111
|
+
on_decision=lambda verdict, allowed: print(verdict.verdict, allowed),
|
|
112
|
+
timeout=20.0,
|
|
113
|
+
)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Option | Default | Meaning |
|
|
117
|
+
|---|---|---|
|
|
118
|
+
| `allow_ttl` | `3600` | Cache lifetime of a `no_known_risk` answer, in seconds. `0` disables. |
|
|
119
|
+
| `block_ttl` | `86400` | Cache lifetime of a `do_not_pay` answer. |
|
|
120
|
+
| `trusted` | `()` | Addresses never looked up. EVM addresses match case-insensitively. |
|
|
121
|
+
| `on_incomplete` | `"allow"` | What to do when some checks could not answer. |
|
|
122
|
+
| `on_error` | `"allow"` | What to do when the lookup fails (network, unpaid, bad response). Errors are never cached. |
|
|
123
|
+
| `on_decision` | `None` | Callback `(Verdict, allowed: bool)` for your logs or metrics. |
|
|
124
|
+
| `fetcher` | `None` | Replace the HTTP lookup: `address -> Verdict` (an `async` function for the async client). |
|
|
125
|
+
| `endpoint` | Veriql `/api/v1/payee` | Lookup URL, if you run a compatible service. |
|
|
126
|
+
| `timeout` | `20.0` | HTTP timeout for the lookup, in seconds. |
|
|
127
|
+
|
|
128
|
+
The defaults fail open: a network blip never stops your agent from paying. For
|
|
129
|
+
a treasury agent, `on_incomplete="block", on_error="block"` fails closed.
|
|
130
|
+
|
|
131
|
+
## Verdicts
|
|
132
|
+
|
|
133
|
+
| Verdict | Meaning | Guard |
|
|
134
|
+
|---|---|---|
|
|
135
|
+
| `do_not_pay` | At least one check found the address (sanctioned, listed, or frozen). | blocks |
|
|
136
|
+
| `no_known_risk` | Every applicable check answered and none found it. | allows |
|
|
137
|
+
| `incomplete` | Some checks could not answer. | `on_incomplete` |
|
|
138
|
+
| `error` | The lookup itself failed. | `on_error` |
|
|
139
|
+
|
|
140
|
+
`no_known_risk` means none of these lists has the address today. It is not a
|
|
141
|
+
promise about the seller.
|
|
142
|
+
|
|
143
|
+
You can also call the guard directly, for example before an ordinary transfer:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
v = guard.check("0x...") # or: await guard.acheck("0x...")
|
|
147
|
+
if v.blocked:
|
|
148
|
+
print(v.reasons)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Your own lookup
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from x402_payee_guard import Verdict, guard_payees
|
|
155
|
+
|
|
156
|
+
DENY = {"0x...", "0x..."}
|
|
157
|
+
|
|
158
|
+
def my_lookup(address: str) -> Verdict:
|
|
159
|
+
return Verdict(address, "do_not_pay" if address.lower() in DENY else "no_known_risk")
|
|
160
|
+
|
|
161
|
+
guard_payees(client, fetcher=my_lookup)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Links
|
|
165
|
+
|
|
166
|
+
- API description: [veriql.app/openapi.json](https://veriql.app/openapi.json)
|
|
167
|
+
- x402scan listing: [x402scan.com/server/b43a466b-e90b-41bf-a7a8-1502cde22f10](https://www.x402scan.com/server/b43a466b-e90b-41bf-a7a8-1502cde22f10)
|
|
168
|
+
- Free browser check for one address: [veriql.app](https://veriql.app)
|
|
169
|
+
- Read the freeze lists yourself, no API: [`stablecoin-freeze-check`](https://pypi.org/project/stablecoin-freeze-check/)
|
|
170
|
+
|
|
171
|
+
## License
|
|
172
|
+
|
|
173
|
+
MIT
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# x402-payee-guard
|
|
2
|
+
|
|
3
|
+
Screen the payee before your x402 agent pays.
|
|
4
|
+
|
|
5
|
+
An x402 client pays whatever `payTo` address a 402 response names. An agent
|
|
6
|
+
that finds sellers on its own will, sooner or later, be handed an address it
|
|
7
|
+
has never seen. This package adds one hook to the official
|
|
8
|
+
[x402 Python SDK](https://pypi.org/project/x402/): before the client signs a
|
|
9
|
+
payment, it looks up the `payTo` address and aborts the payment when the
|
|
10
|
+
address is
|
|
11
|
+
|
|
12
|
+
- on the US Treasury OFAC SDN sanctions list,
|
|
13
|
+
- a known drainer, phishing or scam address, or
|
|
14
|
+
- frozen by a stablecoin issuer (Tether or Circle; EVM and Tron addresses) —
|
|
15
|
+
USDT or USDC sent there can never be moved out again.
|
|
16
|
+
|
|
17
|
+
EVM, Bitcoin, Solana and Tron addresses are accepted.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from x402 import x402ClientSync
|
|
21
|
+
from x402_payee_guard import guard_payees
|
|
22
|
+
|
|
23
|
+
client = x402ClientSync()
|
|
24
|
+
# client.register("eip155:*", ExactEvmScheme(signer=...)) # your usual setup
|
|
25
|
+
guard_payees(client)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
That's it. Every payment the client creates afterwards is screened first. A
|
|
29
|
+
`do_not_pay` payee makes the client raise `x402.PaymentAbortedError` instead of
|
|
30
|
+
signing.
|
|
31
|
+
|
|
32
|
+
## Cost and who runs the lookup — please read
|
|
33
|
+
|
|
34
|
+
The lookup is [Veriql](https://veriql.app)'s `/api/v1/payee` endpoint, and
|
|
35
|
+
**each uncached lookup costs USD 0.01**, paid over x402 in USDC on Base from the
|
|
36
|
+
same wallet your client already pays with. This package is made by Veriql,
|
|
37
|
+
which runs that endpoint.
|
|
38
|
+
|
|
39
|
+
- Answers are cached per address: `no_known_risk` for 1 hour, `do_not_pay` for
|
|
40
|
+
24 hours (both configurable), so an agent that pays the same seller all day
|
|
41
|
+
pays for one lookup an hour.
|
|
42
|
+
- The guard's own USD 0.01 payment to Veriql is not screened again.
|
|
43
|
+
- Pass `trusted=[...]` for sellers you already know; they are never looked up.
|
|
44
|
+
- Prefer another provider or your own list? Pass `fetcher=` and nothing is
|
|
45
|
+
sent to Veriql (see below).
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install "x402-payee-guard[requests]" # for x402ClientSync
|
|
51
|
+
pip install "x402-payee-guard[httpx]" # for the async x402Client
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Python 3.10+. The only dependency is `x402` (2.20 or newer).
|
|
55
|
+
|
|
56
|
+
## Async client
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from x402 import x402Client
|
|
60
|
+
from x402.http.clients import x402HttpxClient
|
|
61
|
+
from x402_payee_guard import guard_payees
|
|
62
|
+
|
|
63
|
+
client = x402Client()
|
|
64
|
+
# client.register("eip155:*", ExactEvmScheme(signer=...))
|
|
65
|
+
guard_payees(client)
|
|
66
|
+
|
|
67
|
+
async with x402HttpxClient(client) as http:
|
|
68
|
+
r = await http.get("https://seller.example/paid-endpoint")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Options
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
guard = guard_payees(
|
|
75
|
+
client,
|
|
76
|
+
allow_ttl=3600, # seconds a no_known_risk answer is reused
|
|
77
|
+
block_ttl=86400, # seconds a do_not_pay answer is reused
|
|
78
|
+
trusted=["0x..."], # never looked up
|
|
79
|
+
on_incomplete="allow", # or "block" when not every check could answer
|
|
80
|
+
on_error="allow", # or "block" when the lookup itself fails
|
|
81
|
+
on_decision=lambda verdict, allowed: print(verdict.verdict, allowed),
|
|
82
|
+
timeout=20.0,
|
|
83
|
+
)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
| Option | Default | Meaning |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| `allow_ttl` | `3600` | Cache lifetime of a `no_known_risk` answer, in seconds. `0` disables. |
|
|
89
|
+
| `block_ttl` | `86400` | Cache lifetime of a `do_not_pay` answer. |
|
|
90
|
+
| `trusted` | `()` | Addresses never looked up. EVM addresses match case-insensitively. |
|
|
91
|
+
| `on_incomplete` | `"allow"` | What to do when some checks could not answer. |
|
|
92
|
+
| `on_error` | `"allow"` | What to do when the lookup fails (network, unpaid, bad response). Errors are never cached. |
|
|
93
|
+
| `on_decision` | `None` | Callback `(Verdict, allowed: bool)` for your logs or metrics. |
|
|
94
|
+
| `fetcher` | `None` | Replace the HTTP lookup: `address -> Verdict` (an `async` function for the async client). |
|
|
95
|
+
| `endpoint` | Veriql `/api/v1/payee` | Lookup URL, if you run a compatible service. |
|
|
96
|
+
| `timeout` | `20.0` | HTTP timeout for the lookup, in seconds. |
|
|
97
|
+
|
|
98
|
+
The defaults fail open: a network blip never stops your agent from paying. For
|
|
99
|
+
a treasury agent, `on_incomplete="block", on_error="block"` fails closed.
|
|
100
|
+
|
|
101
|
+
## Verdicts
|
|
102
|
+
|
|
103
|
+
| Verdict | Meaning | Guard |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| `do_not_pay` | At least one check found the address (sanctioned, listed, or frozen). | blocks |
|
|
106
|
+
| `no_known_risk` | Every applicable check answered and none found it. | allows |
|
|
107
|
+
| `incomplete` | Some checks could not answer. | `on_incomplete` |
|
|
108
|
+
| `error` | The lookup itself failed. | `on_error` |
|
|
109
|
+
|
|
110
|
+
`no_known_risk` means none of these lists has the address today. It is not a
|
|
111
|
+
promise about the seller.
|
|
112
|
+
|
|
113
|
+
You can also call the guard directly, for example before an ordinary transfer:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
v = guard.check("0x...") # or: await guard.acheck("0x...")
|
|
117
|
+
if v.blocked:
|
|
118
|
+
print(v.reasons)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Your own lookup
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from x402_payee_guard import Verdict, guard_payees
|
|
125
|
+
|
|
126
|
+
DENY = {"0x...", "0x..."}
|
|
127
|
+
|
|
128
|
+
def my_lookup(address: str) -> Verdict:
|
|
129
|
+
return Verdict(address, "do_not_pay" if address.lower() in DENY else "no_known_risk")
|
|
130
|
+
|
|
131
|
+
guard_payees(client, fetcher=my_lookup)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Links
|
|
135
|
+
|
|
136
|
+
- API description: [veriql.app/openapi.json](https://veriql.app/openapi.json)
|
|
137
|
+
- x402scan listing: [x402scan.com/server/b43a466b-e90b-41bf-a7a8-1502cde22f10](https://www.x402scan.com/server/b43a466b-e90b-41bf-a7a8-1502cde22f10)
|
|
138
|
+
- Free browser check for one address: [veriql.app](https://veriql.app)
|
|
139
|
+
- Read the freeze lists yourself, no API: [`stablecoin-freeze-check`](https://pypi.org/project/stablecoin-freeze-check/)
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "x402-payee-guard"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Screen the payee before your x402 agent pays: blocks sanctioned, drainer and stablecoin-frozen addresses with one line on x402Client."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{ name = "Veriql" }]
|
|
14
|
+
keywords = ["x402", "ai-agents", "agent-payments", "usdc", "usdt", "ofac", "sanctions", "compliance", "payee-screening", "stablecoin"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Office/Business :: Financial",
|
|
25
|
+
"Topic :: Security",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = ["x402>=2.20"]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
httpx = ["x402[httpx]>=2.20"]
|
|
32
|
+
requests = ["x402[requests]>=2.20"]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://veriql.app"
|
|
36
|
+
Documentation = "https://veriql.app/openapi.json"
|
|
37
|
+
"x402scan listing" = "https://www.x402scan.com/server/b43a466b-e90b-41bf-a7a8-1502cde22f10"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/x402_payee_guard"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Screen the payee before your x402 agent pays.
|
|
2
|
+
|
|
3
|
+
from x402_payee_guard import guard_payees
|
|
4
|
+
guard_payees(client) # client = x402Client() or x402ClientSync()
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .guard import (
|
|
8
|
+
DEFAULT_ENDPOINT,
|
|
9
|
+
DO_NOT_PAY,
|
|
10
|
+
ERROR,
|
|
11
|
+
INCOMPLETE,
|
|
12
|
+
NO_KNOWN_RISK,
|
|
13
|
+
PayeeGuard,
|
|
14
|
+
Verdict,
|
|
15
|
+
guard_payees,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"DEFAULT_ENDPOINT",
|
|
22
|
+
"DO_NOT_PAY",
|
|
23
|
+
"ERROR",
|
|
24
|
+
"INCOMPLETE",
|
|
25
|
+
"NO_KNOWN_RISK",
|
|
26
|
+
"PayeeGuard",
|
|
27
|
+
"Verdict",
|
|
28
|
+
"guard_payees",
|
|
29
|
+
"__version__",
|
|
30
|
+
]
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Payee screening for x402 clients.
|
|
2
|
+
|
|
3
|
+
Registers a before-payment hook on an x402 client. Before the client signs a
|
|
4
|
+
payment, the hook looks up the address it is about to pay (``payTo``) and
|
|
5
|
+
aborts the payment when that address is sanctioned, a known drainer or scam
|
|
6
|
+
address, or frozen by a stablecoin issuer.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextvars
|
|
12
|
+
import logging
|
|
13
|
+
import re
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Any, Awaitable, Callable, Iterable, Optional, Union
|
|
18
|
+
|
|
19
|
+
from x402 import AbortResult
|
|
20
|
+
|
|
21
|
+
log = logging.getLogger("x402_payee_guard")
|
|
22
|
+
|
|
23
|
+
DEFAULT_ENDPOINT = "https://veriql.app/api/v1/payee"
|
|
24
|
+
|
|
25
|
+
DO_NOT_PAY = "do_not_pay"
|
|
26
|
+
NO_KNOWN_RISK = "no_known_risk"
|
|
27
|
+
INCOMPLETE = "incomplete"
|
|
28
|
+
ERROR = "error"
|
|
29
|
+
|
|
30
|
+
_EVM = re.compile(r"^0x[0-9a-fA-F]{40}$")
|
|
31
|
+
|
|
32
|
+
# True while the guard itself is paying for a check, so the check's own
|
|
33
|
+
# payment is not screened again (that would recurse forever).
|
|
34
|
+
_IN_CHECK: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
|
35
|
+
"x402_payee_guard_in_check", default=False
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Verdict:
|
|
41
|
+
"""Result of one payee lookup."""
|
|
42
|
+
|
|
43
|
+
address: str
|
|
44
|
+
verdict: str
|
|
45
|
+
reasons: list[str] = field(default_factory=list)
|
|
46
|
+
cached: bool = False
|
|
47
|
+
raw: Optional[dict] = None
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def blocked(self) -> bool:
|
|
51
|
+
return self.verdict == DO_NOT_PAY
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
Decision = Callable[[Verdict, bool], None]
|
|
55
|
+
SyncFetcher = Callable[[str], Verdict]
|
|
56
|
+
AsyncFetcher = Callable[[str], Awaitable[Verdict]]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _key(address: str) -> str:
|
|
60
|
+
a = address.strip()
|
|
61
|
+
return a.lower() if _EVM.match(a) else a
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parse(address: str, body: Any) -> Verdict:
|
|
65
|
+
result = body.get("result") if isinstance(body, dict) else None
|
|
66
|
+
if not isinstance(result, dict) or result.get("verdict") not in (
|
|
67
|
+
DO_NOT_PAY,
|
|
68
|
+
NO_KNOWN_RISK,
|
|
69
|
+
INCOMPLETE,
|
|
70
|
+
):
|
|
71
|
+
return Verdict(address, ERROR, ["unexpected response from payee check"], raw=body)
|
|
72
|
+
reasons = [str(r) for r in (result.get("reasons") or [])]
|
|
73
|
+
return Verdict(address, result["verdict"], reasons, raw=result)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _http_reason(status: int) -> str:
|
|
77
|
+
if status == 402:
|
|
78
|
+
return (
|
|
79
|
+
"payee check was not paid (HTTP 402): the client wallet needs USDC "
|
|
80
|
+
"on Base for the USD 0.01 lookup"
|
|
81
|
+
)
|
|
82
|
+
return f"payee check returned HTTP {status}"
|
|
83
|
+
|
|
84
|
+
def _payee_of(ctx: Any) -> tuple[Optional[str], Optional[str]]:
|
|
85
|
+
req = getattr(ctx, "selected_requirements", None)
|
|
86
|
+
pay_to = getattr(req, "pay_to", None)
|
|
87
|
+
url = None
|
|
88
|
+
pr = getattr(ctx, "payment_required", None)
|
|
89
|
+
res = getattr(pr, "resource", None)
|
|
90
|
+
if res is not None:
|
|
91
|
+
url = res if isinstance(res, str) else getattr(res, "url", None)
|
|
92
|
+
if url is None:
|
|
93
|
+
url = getattr(req, "resource", None) # x402 v1 keeps it on the requirement
|
|
94
|
+
return pay_to, url
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class PayeeGuard:
|
|
98
|
+
"""Screens the payee of every x402 payment a client makes.
|
|
99
|
+
|
|
100
|
+
Use :func:`guard_payees` to create one and attach it to a client.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
client: an ``x402Client`` (async) or ``x402ClientSync``. The guard pays
|
|
104
|
+
for its own lookups through this client.
|
|
105
|
+
endpoint: payee-check URL. Defaults to Veriql's ``/api/v1/payee``
|
|
106
|
+
(USD 0.01 per lookup, paid over x402).
|
|
107
|
+
allow_ttl: seconds a ``no_known_risk`` answer is reused for the same
|
|
108
|
+
address. Default 3600.
|
|
109
|
+
block_ttl: seconds a ``do_not_pay`` answer is reused. Default 86400.
|
|
110
|
+
trusted: addresses that are never looked up (your own sellers, say).
|
|
111
|
+
on_incomplete: ``"allow"`` (default) or ``"block"`` when not every
|
|
112
|
+
check could answer.
|
|
113
|
+
on_error: ``"allow"`` (default) or ``"block"`` when the lookup itself
|
|
114
|
+
fails (network error, lookup not paid, bad response).
|
|
115
|
+
on_decision: optional callback ``(verdict, allowed)`` for logging.
|
|
116
|
+
fetcher: optional replacement for the HTTP lookup, ``address -> Verdict``
|
|
117
|
+
(async for an async client). Useful for tests or another provider.
|
|
118
|
+
timeout: HTTP timeout in seconds for the lookup. Default 20.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
def __init__(
|
|
122
|
+
self,
|
|
123
|
+
client: Any,
|
|
124
|
+
*,
|
|
125
|
+
endpoint: str = DEFAULT_ENDPOINT,
|
|
126
|
+
allow_ttl: float = 3600,
|
|
127
|
+
block_ttl: float = 86400,
|
|
128
|
+
trusted: Iterable[str] = (),
|
|
129
|
+
on_incomplete: str = "allow",
|
|
130
|
+
on_error: str = "allow",
|
|
131
|
+
on_decision: Optional[Decision] = None,
|
|
132
|
+
fetcher: Optional[Union[SyncFetcher, AsyncFetcher]] = None,
|
|
133
|
+
timeout: float = 20.0,
|
|
134
|
+
) -> None:
|
|
135
|
+
for name, value in (("on_incomplete", on_incomplete), ("on_error", on_error)):
|
|
136
|
+
if value not in ("allow", "block"):
|
|
137
|
+
raise ValueError(f"{name} must be 'allow' or 'block', got {value!r}")
|
|
138
|
+
self.client = client
|
|
139
|
+
self.endpoint = endpoint
|
|
140
|
+
self.allow_ttl = allow_ttl
|
|
141
|
+
self.block_ttl = block_ttl
|
|
142
|
+
self.trusted = {_key(a) for a in trusted}
|
|
143
|
+
self.on_incomplete = on_incomplete
|
|
144
|
+
self.on_error = on_error
|
|
145
|
+
self.on_decision = on_decision
|
|
146
|
+
self.timeout = timeout
|
|
147
|
+
self._fetcher = fetcher
|
|
148
|
+
self._cache: dict[str, tuple[Verdict, float]] = {}
|
|
149
|
+
self._lock = threading.Lock()
|
|
150
|
+
self.is_async = not _is_sync_client(client)
|
|
151
|
+
|
|
152
|
+
# ---------------------------------------------------------------- cache
|
|
153
|
+
|
|
154
|
+
def _cached(self, key: str) -> Optional[Verdict]:
|
|
155
|
+
with self._lock:
|
|
156
|
+
hit = self._cache.get(key)
|
|
157
|
+
if hit is None:
|
|
158
|
+
return None
|
|
159
|
+
verdict, expires = hit
|
|
160
|
+
if time.monotonic() >= expires:
|
|
161
|
+
del self._cache[key]
|
|
162
|
+
return None
|
|
163
|
+
return Verdict(verdict.address, verdict.verdict, list(verdict.reasons), True, verdict.raw)
|
|
164
|
+
|
|
165
|
+
def _store(self, v: Verdict) -> None:
|
|
166
|
+
ttl = {DO_NOT_PAY: self.block_ttl, NO_KNOWN_RISK: self.allow_ttl}.get(v.verdict)
|
|
167
|
+
if ttl and ttl > 0:
|
|
168
|
+
with self._lock:
|
|
169
|
+
self._cache[_key(v.address)] = (v, time.monotonic() + ttl)
|
|
170
|
+
|
|
171
|
+
def clear_cache(self) -> None:
|
|
172
|
+
with self._lock:
|
|
173
|
+
self._cache.clear()
|
|
174
|
+
|
|
175
|
+
# ------------------------------------------------------------- decision
|
|
176
|
+
|
|
177
|
+
def _allowed(self, v: Verdict) -> bool:
|
|
178
|
+
if v.verdict == DO_NOT_PAY:
|
|
179
|
+
return False
|
|
180
|
+
if v.verdict == INCOMPLETE:
|
|
181
|
+
return self.on_incomplete == "allow"
|
|
182
|
+
if v.verdict == ERROR:
|
|
183
|
+
return self.on_error == "allow"
|
|
184
|
+
return True
|
|
185
|
+
|
|
186
|
+
def _decide(self, v: Verdict) -> Optional[AbortResult]:
|
|
187
|
+
allowed = self._allowed(v)
|
|
188
|
+
if self.on_decision is not None:
|
|
189
|
+
try:
|
|
190
|
+
self.on_decision(v, allowed)
|
|
191
|
+
except Exception: # a logging callback must never break a payment
|
|
192
|
+
log.exception("on_decision callback failed")
|
|
193
|
+
if allowed:
|
|
194
|
+
if v.verdict in (INCOMPLETE, ERROR):
|
|
195
|
+
log.warning("payee %s: %s (%s), paying anyway", v.address, v.verdict, "; ".join(v.reasons))
|
|
196
|
+
return None
|
|
197
|
+
why = "; ".join(v.reasons) or v.verdict
|
|
198
|
+
log.warning("payee %s blocked: %s", v.address, why)
|
|
199
|
+
return AbortResult(reason=f"payee_guard:{v.verdict}:{v.address}: {why}")
|
|
200
|
+
|
|
201
|
+
def _skip(self, pay_to: Optional[str], url: Optional[str]) -> bool:
|
|
202
|
+
if _IN_CHECK.get():
|
|
203
|
+
return True
|
|
204
|
+
if not pay_to:
|
|
205
|
+
return True
|
|
206
|
+
if url and str(url).split("?")[0].rstrip("/") == self.endpoint.rstrip("/"):
|
|
207
|
+
return True
|
|
208
|
+
return _key(pay_to) in self.trusted
|
|
209
|
+
|
|
210
|
+
# --------------------------------------------------------- sync lookups
|
|
211
|
+
|
|
212
|
+
def check(self, address: str) -> Verdict:
|
|
213
|
+
"""Look up one address (sync client). Uses and fills the cache."""
|
|
214
|
+
hit = self._cached(_key(address))
|
|
215
|
+
if hit is not None:
|
|
216
|
+
return hit
|
|
217
|
+
token = _IN_CHECK.set(True)
|
|
218
|
+
try:
|
|
219
|
+
v = self._fetcher(address) if self._fetcher else self._http_sync(address)
|
|
220
|
+
except Exception as e: # network errors, payment errors
|
|
221
|
+
v = Verdict(address, ERROR, [f"{type(e).__name__}: {e}"])
|
|
222
|
+
finally:
|
|
223
|
+
_IN_CHECK.reset(token)
|
|
224
|
+
self._store(v)
|
|
225
|
+
return v
|
|
226
|
+
|
|
227
|
+
def _http_sync(self, address: str) -> Verdict:
|
|
228
|
+
from x402.http.clients import x402_requests
|
|
229
|
+
|
|
230
|
+
session = x402_requests(self.client)
|
|
231
|
+
try:
|
|
232
|
+
r = session.get(self.endpoint, params={"address": address}, timeout=self.timeout)
|
|
233
|
+
finally:
|
|
234
|
+
session.close()
|
|
235
|
+
if r.status_code != 200:
|
|
236
|
+
return Verdict(address, ERROR, [_http_reason(r.status_code)])
|
|
237
|
+
return _parse(address, r.json())
|
|
238
|
+
|
|
239
|
+
def hook_sync(self, ctx: Any) -> Optional[AbortResult]:
|
|
240
|
+
pay_to, url = _payee_of(ctx)
|
|
241
|
+
if self._skip(pay_to, url):
|
|
242
|
+
return None
|
|
243
|
+
return self._decide(self.check(pay_to))
|
|
244
|
+
|
|
245
|
+
# -------------------------------------------------------- async lookups
|
|
246
|
+
|
|
247
|
+
async def acheck(self, address: str) -> Verdict:
|
|
248
|
+
"""Look up one address (async client). Uses and fills the cache."""
|
|
249
|
+
hit = self._cached(_key(address))
|
|
250
|
+
if hit is not None:
|
|
251
|
+
return hit
|
|
252
|
+
token = _IN_CHECK.set(True)
|
|
253
|
+
try:
|
|
254
|
+
v = await self._fetcher(address) if self._fetcher else await self._http_async(address)
|
|
255
|
+
except Exception as e:
|
|
256
|
+
v = Verdict(address, ERROR, [f"{type(e).__name__}: {e}"])
|
|
257
|
+
finally:
|
|
258
|
+
_IN_CHECK.reset(token)
|
|
259
|
+
self._store(v)
|
|
260
|
+
return v
|
|
261
|
+
|
|
262
|
+
async def _http_async(self, address: str) -> Verdict:
|
|
263
|
+
from x402.http.clients import x402HttpxClient
|
|
264
|
+
|
|
265
|
+
async with x402HttpxClient(self.client, timeout=self.timeout) as http:
|
|
266
|
+
r = await http.get(self.endpoint, params={"address": address})
|
|
267
|
+
if r.status_code != 200:
|
|
268
|
+
return Verdict(address, ERROR, [_http_reason(r.status_code)])
|
|
269
|
+
return _parse(address, r.json())
|
|
270
|
+
|
|
271
|
+
async def hook_async(self, ctx: Any) -> Optional[AbortResult]:
|
|
272
|
+
pay_to, url = _payee_of(ctx)
|
|
273
|
+
if self._skip(pay_to, url):
|
|
274
|
+
return None
|
|
275
|
+
return self._decide(await self.acheck(pay_to))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _is_sync_client(client: Any) -> bool:
|
|
279
|
+
try:
|
|
280
|
+
from x402 import x402ClientSync
|
|
281
|
+
except ImportError: # pragma: no cover
|
|
282
|
+
return False
|
|
283
|
+
return isinstance(client, x402ClientSync)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def guard_payees(client: Any, **options: Any) -> PayeeGuard:
|
|
287
|
+
"""Attach payee screening to an x402 client and return the guard.
|
|
288
|
+
|
|
289
|
+
Works with ``x402Client`` (async) and ``x402ClientSync``. Every payment the
|
|
290
|
+
client creates afterwards is screened first; a ``do_not_pay`` payee makes
|
|
291
|
+
the client raise ``PaymentAbortedError`` instead of paying.
|
|
292
|
+
"""
|
|
293
|
+
guard = PayeeGuard(client, **options)
|
|
294
|
+
client.on_before_payment_creation(guard.hook_async if guard.is_async else guard.hook_sync)
|
|
295
|
+
return guard
|
|
File without changes
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from x402 import PaymentAbortedError, x402Client, x402ClientSync
|
|
5
|
+
from x402.schemas import PaymentRequired, PaymentRequirements, ResourceInfo
|
|
6
|
+
|
|
7
|
+
from x402_payee_guard import DEFAULT_ENDPOINT, PayeeGuard, Verdict, guard_payees
|
|
8
|
+
from x402_payee_guard.guard import _parse
|
|
9
|
+
|
|
10
|
+
BAD = "0xbad0000000000000000000000000000000000bad"
|
|
11
|
+
GOOD = "0xabcdef000000000000000000000000000000abcd"
|
|
12
|
+
VERIQL_PAYTO = "0x3333333333333333333333333333333333333333"
|
|
13
|
+
USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FakeScheme:
|
|
17
|
+
scheme = "exact"
|
|
18
|
+
|
|
19
|
+
def __init__(self):
|
|
20
|
+
self.signed = []
|
|
21
|
+
|
|
22
|
+
def create_payment_payload(self, requirements):
|
|
23
|
+
self.signed.append(requirements.pay_to)
|
|
24
|
+
return {"signature": "0xfake", "payTo": requirements.pay_to}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def pr(pay_to, url="https://seller.example/api/data"):
|
|
28
|
+
return PaymentRequired(
|
|
29
|
+
x402_version=2,
|
|
30
|
+
resource=ResourceInfo(url=url),
|
|
31
|
+
accepts=[
|
|
32
|
+
PaymentRequirements(
|
|
33
|
+
scheme="exact",
|
|
34
|
+
network="eip155:8453",
|
|
35
|
+
asset=USDC_BASE,
|
|
36
|
+
amount="1000",
|
|
37
|
+
pay_to=pay_to,
|
|
38
|
+
max_timeout_seconds=60,
|
|
39
|
+
extra={},
|
|
40
|
+
)
|
|
41
|
+
],
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Lookup:
|
|
46
|
+
def __init__(self, answers):
|
|
47
|
+
self.answers = answers
|
|
48
|
+
self.calls = []
|
|
49
|
+
|
|
50
|
+
def __call__(self, address):
|
|
51
|
+
self.calls.append(address)
|
|
52
|
+
a = self.answers.get(address.lower())
|
|
53
|
+
if isinstance(a, Exception):
|
|
54
|
+
raise a
|
|
55
|
+
return Verdict(address, a or "no_known_risk", ["test reason"] if a == "do_not_pay" else [])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def sync_client(answers, **opts):
|
|
59
|
+
client = x402ClientSync().set_spend_controls(False)
|
|
60
|
+
scheme = FakeScheme()
|
|
61
|
+
client.register("eip155:8453", scheme)
|
|
62
|
+
lookup = Lookup(answers)
|
|
63
|
+
guard = guard_payees(client, fetcher=lookup, **opts)
|
|
64
|
+
return client, scheme, lookup, guard
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_blocks_do_not_pay_before_signing():
|
|
68
|
+
client, scheme, lookup, _ = sync_client({BAD: "do_not_pay"})
|
|
69
|
+
with pytest.raises(PaymentAbortedError) as e:
|
|
70
|
+
client.create_payment_payload(pr(BAD))
|
|
71
|
+
assert "payee_guard:do_not_pay" in str(e.value)
|
|
72
|
+
assert scheme.signed == []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_allows_no_known_risk():
|
|
76
|
+
client, scheme, lookup, _ = sync_client({GOOD: "no_known_risk"})
|
|
77
|
+
client.create_payment_payload(pr(GOOD))
|
|
78
|
+
assert scheme.signed == [GOOD]
|
|
79
|
+
assert lookup.calls == [GOOD]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_cache_reuses_answer_case_insensitive_evm():
|
|
83
|
+
client, scheme, lookup, _ = sync_client({GOOD: "no_known_risk"})
|
|
84
|
+
client.create_payment_payload(pr(GOOD))
|
|
85
|
+
mixed = "0x" + GOOD[2:].upper()
|
|
86
|
+
assert mixed != GOOD
|
|
87
|
+
client.create_payment_payload(pr(mixed))
|
|
88
|
+
assert len(lookup.calls) == 1
|
|
89
|
+
assert len(scheme.signed) == 2
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_block_answers_are_cached_too():
|
|
93
|
+
client, scheme, lookup, _ = sync_client({BAD: "do_not_pay"})
|
|
94
|
+
for _ in range(2):
|
|
95
|
+
with pytest.raises(PaymentAbortedError):
|
|
96
|
+
client.create_payment_payload(pr(BAD))
|
|
97
|
+
assert len(lookup.calls) == 1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_trusted_payee_is_never_looked_up():
|
|
101
|
+
client, scheme, lookup, _ = sync_client({}, trusted=["0x" + GOOD[2:].upper()])
|
|
102
|
+
client.create_payment_payload(pr(GOOD))
|
|
103
|
+
assert lookup.calls == []
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_incomplete_policy():
|
|
107
|
+
client, scheme, lookup, _ = sync_client({GOOD: "incomplete"})
|
|
108
|
+
client.create_payment_payload(pr(GOOD)) # default: allow
|
|
109
|
+
client, scheme, lookup, _ = sync_client({GOOD: "incomplete"}, on_incomplete="block")
|
|
110
|
+
with pytest.raises(PaymentAbortedError):
|
|
111
|
+
client.create_payment_payload(pr(GOOD))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_error_policy_and_errors_not_cached():
|
|
115
|
+
client, scheme, lookup, _ = sync_client({GOOD: RuntimeError("down")})
|
|
116
|
+
client.create_payment_payload(pr(GOOD))
|
|
117
|
+
client.create_payment_payload(pr(GOOD))
|
|
118
|
+
assert len(lookup.calls) == 2 # errors are retried, not cached
|
|
119
|
+
client, scheme, lookup, _ = sync_client({GOOD: RuntimeError("down")}, on_error="block")
|
|
120
|
+
with pytest.raises(PaymentAbortedError) as e:
|
|
121
|
+
client.create_payment_payload(pr(GOOD))
|
|
122
|
+
assert "payee_guard:error" in str(e.value)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_paying_the_check_endpoint_is_not_screened():
|
|
126
|
+
client, scheme, lookup, _ = sync_client({VERIQL_PAYTO: "do_not_pay"})
|
|
127
|
+
client.create_payment_payload(pr(VERIQL_PAYTO, url=DEFAULT_ENDPOINT))
|
|
128
|
+
assert lookup.calls == []
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_nested_payment_inside_lookup_does_not_recurse():
|
|
132
|
+
client = x402ClientSync().set_spend_controls(False)
|
|
133
|
+
scheme = FakeScheme()
|
|
134
|
+
client.register("eip155:8453", scheme)
|
|
135
|
+
calls = []
|
|
136
|
+
|
|
137
|
+
def lookup(address):
|
|
138
|
+
calls.append(address)
|
|
139
|
+
# the real lookup pays for itself through the same client
|
|
140
|
+
client.create_payment_payload(pr(VERIQL_PAYTO, url="https://elsewhere.example/check"))
|
|
141
|
+
return Verdict(address, "no_known_risk")
|
|
142
|
+
|
|
143
|
+
guard_payees(client, fetcher=lookup)
|
|
144
|
+
client.create_payment_payload(pr(GOOD))
|
|
145
|
+
assert calls == [GOOD]
|
|
146
|
+
assert scheme.signed == [VERIQL_PAYTO, GOOD]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def test_async_client():
|
|
150
|
+
async def run():
|
|
151
|
+
client = x402Client().set_spend_controls(False)
|
|
152
|
+
scheme = FakeScheme()
|
|
153
|
+
client.register("eip155:8453", scheme)
|
|
154
|
+
calls = []
|
|
155
|
+
|
|
156
|
+
async def lookup(address):
|
|
157
|
+
calls.append(address)
|
|
158
|
+
return Verdict(address, "do_not_pay" if address == BAD else "no_known_risk", ["sanctioned"])
|
|
159
|
+
|
|
160
|
+
guard = guard_payees(client, fetcher=lookup)
|
|
161
|
+
assert guard.is_async
|
|
162
|
+
await client.create_payment_payload(pr(GOOD))
|
|
163
|
+
with pytest.raises(PaymentAbortedError):
|
|
164
|
+
await client.create_payment_payload(pr(BAD))
|
|
165
|
+
return calls, scheme.signed
|
|
166
|
+
|
|
167
|
+
calls, signed = asyncio.run(run())
|
|
168
|
+
assert calls == [GOOD, BAD]
|
|
169
|
+
assert signed == [GOOD]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def test_on_decision_callback_and_bad_option():
|
|
173
|
+
seen = []
|
|
174
|
+
client, scheme, lookup, _ = sync_client({BAD: "do_not_pay"}, on_decision=lambda v, ok: seen.append((v.verdict, ok)))
|
|
175
|
+
with pytest.raises(PaymentAbortedError):
|
|
176
|
+
client.create_payment_payload(pr(BAD))
|
|
177
|
+
assert seen == [("do_not_pay", False)]
|
|
178
|
+
with pytest.raises(ValueError):
|
|
179
|
+
PayeeGuard(x402ClientSync(), on_error="maybe")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def test_parse_envelope():
|
|
183
|
+
body = {"ok": True, "result": {"address": BAD, "verdict": "do_not_pay", "reasons": ["OFAC SDN"], "checks": []}}
|
|
184
|
+
v = _parse(BAD, body)
|
|
185
|
+
assert v.blocked and v.reasons == ["OFAC SDN"]
|
|
186
|
+
assert _parse(BAD, {"weird": 1}).verdict == "error"
|