plug402 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.
@@ -0,0 +1,22 @@
1
+ # secrets
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+ *.key
6
+ *.pem
7
+ keys/
8
+
9
+ # build output
10
+ node_modules/
11
+ dist/
12
+ target/
13
+ build/
14
+ .gradle/
15
+ __pycache__/
16
+ *.egg-info/
17
+ .venv/
18
+ .pytest_cache/
19
+
20
+ # local receipts
21
+ *.receipts.jsonl
22
+ .DS_Store
plug402-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
plug402-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,244 @@
1
+ Metadata-Version: 2.5
2
+ Name: plug402
3
+ Version: 0.1.0
4
+ Summary: x402 payments for the Python HTTP client and keys you already use (httpx, requests, web3.py, eth-account, solders), under a spend policy you control.
5
+ Project-URL: Homepage, https://github.com/samuelsramko/plug402
6
+ Project-URL: Source, https://github.com/samuelsramko/plug402/tree/main/python
7
+ Project-URL: Issues, https://github.com/samuelsramko/plug402/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: eth-account,http-402,httpx,payments,requests,solana,usdc,web3,x402
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
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 :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Office/Business :: Financial
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: all
25
+ Requires-Dist: httpx>=0.28.1; extra == 'all'
26
+ Requires-Dist: requests>=2.33; extra == 'all'
27
+ Requires-Dist: web3>=7.15; extra == 'all'
28
+ Requires-Dist: x402<3,>=2.29; extra == 'all'
29
+ Requires-Dist: x402[evm]<3,>=2.29; extra == 'all'
30
+ Requires-Dist: x402[svm]<3,>=2.29; extra == 'all'
31
+ Provides-Extra: evm
32
+ Requires-Dist: x402[evm]<3,>=2.29; extra == 'evm'
33
+ Provides-Extra: httpx
34
+ Requires-Dist: httpx>=0.28.1; extra == 'httpx'
35
+ Requires-Dist: x402<3,>=2.29; extra == 'httpx'
36
+ Provides-Extra: requests
37
+ Requires-Dist: requests>=2.33; extra == 'requests'
38
+ Requires-Dist: x402<3,>=2.29; extra == 'requests'
39
+ Provides-Extra: svm
40
+ Requires-Dist: x402[svm]<3,>=2.29; extra == 'svm'
41
+ Provides-Extra: web3
42
+ Requires-Dist: requests>=2.33; extra == 'web3'
43
+ Requires-Dist: web3>=7.15; extra == 'web3'
44
+ Requires-Dist: x402[evm]<3,>=2.29; extra == 'web3'
45
+ Description-Content-Type: text/markdown
46
+
47
+ # plug402 for Python
48
+
49
+ **x402 payments for the HTTP client and keys you already use**: `httpx`, `requests`, web3.py, eth-account and solders, under a **spend policy** you control.
50
+
51
+ When a request comes back `402 Payment Required`, plug402 reads the payment requirements, checks every offered option against your policy, signs the allowed one with your existing key through the official [`x402`](https://pypi.org/project/x402/) package, retries the request once with the payment, and writes a **receipt**.
52
+
53
+ > Status: **v0.1 in development.** Not yet published to PyPI. Testnets only. x402 v2 (and v1 responses), scheme `exact`, EVM (EIP-3009) and Solana.
54
+
55
+ ## Install
56
+
57
+ ```sh
58
+ pip install "plug402[httpx,evm]" # httpx + an eth-account key
59
+ pip install "plug402[requests,svm]" # requests + a solders keypair
60
+ pip install "plug402[web3]" # w3.x402 for web3.py
61
+ pip install "plug402[all]" # everything
62
+ ```
63
+
64
+ | Extra | Gives you | Pulls in |
65
+ |---|---|---|
66
+ | (none) | policy, receipts, ledgers, errors | nothing: the core has no dependencies |
67
+ | `httpx` | `plug402.httpx.X402Auth` | `x402`, `httpx` |
68
+ | `requests` | `plug402.requests.X402Adapter`, `x402_session` | `x402`, `requests` |
69
+ | `web3` | `plug402.web3.X402Module` (`w3.x402`) | `x402[evm]`, `web3`, `requests` |
70
+ | `evm` | EVM signing (eth-account) | `x402[evm]` |
71
+ | `svm` | Solana signing (solders) | `x402[svm]` |
72
+
73
+ Python 3.10 or newer.
74
+
75
+ ## A policy
76
+
77
+ Nothing is paid unless a limit rule covers it (default deny). Amounts are atomic units as decimal strings (USDC has 6 decimals: `"100000"` is 0.10 USDC).
78
+
79
+ ```json
80
+ {
81
+ "version": 1,
82
+ "networks": ["eip155:84532", "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"],
83
+ "payTo": null,
84
+ "limits": [
85
+ { "network": "eip155:84532", "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
86
+ "maxPerRequest": "100000", "maxPerDay": "1000000", "askAbove": "50000" },
87
+ { "network": "solana:*", "asset": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
88
+ "maxPerRequest": "200000" }
89
+ ],
90
+ "maxPaymentsPerMinute": 30
91
+ }
92
+ ```
93
+
94
+ Pass it as a path, a dict, or a `plug402.Policy`. The full contract, including the decision table, is in [`spec/README.md`](../spec/README.md) and [`spec/policy.schema.json`](../spec/policy.schema.json).
95
+
96
+ A few rules beyond the limits:
97
+
98
+ - **HTTPS only by default.** A request to a non-loopback `http:` origin is never paid unless the policy sets `"allowHttp": true` (`http://localhost`, `127.0.0.1` and `::1` are fine).
99
+ - **Recipients.** With a `payTo` allowlist, the main recipient and every `extra.splits[].payTo` must be on it.
100
+ - **What v0.1 pays.** Scheme `exact`, EIP-3009 on EVM (Permit2 and other transfer methods are refused), the x402 payment flows `authorization`, `upfront` and `escrow`, and Solana transaction versions 0 and 1. Solana payments with `extra.splits` or `ataCreationRequired: true` are refused as `unsupported`: the official `x402` Python client (2.29) builds a single transfer to an existing token account and cannot build them.
101
+
102
+ ## httpx
103
+
104
+ `X402Auth` is an `httpx.Auth`, so it works with `httpx.Client` and `httpx.AsyncClient`, new or existing, for every request or just one.
105
+
106
+ ```python
107
+ import httpx
108
+ from eth_account import Account
109
+ from plug402.httpx import X402Auth
110
+
111
+ account = Account.from_key(TEST_KEY) # your existing eth-account LocalAccount
112
+ auth = X402Auth(account, "policy.json")
113
+
114
+ with httpx.Client(auth=auth) as client:
115
+ r = client.get("https://api.example.com/paid")
116
+
117
+ async with httpx.AsyncClient(auth=auth) as client:
118
+ r = await client.get("https://api.example.com/paid")
119
+ ```
120
+
121
+ ## requests
122
+
123
+ ```python
124
+ from plug402.requests import x402_session
125
+
126
+ session = x402_session(account, "policy.json") # a new Session
127
+ session = x402_session(account, "policy.json", session=s) # or mount on yours
128
+ r = session.get("https://api.example.com/paid")
129
+ ```
130
+
131
+ `X402Adapter` subclasses the official `x402HTTPAdapter`; mount it yourself with `session.mount("https://", X402Adapter(account, "policy.json"))` if you prefer.
132
+
133
+ ## web3.py
134
+
135
+ ```python
136
+ from web3 import Web3
137
+ from plug402.web3 import X402Module
138
+
139
+ w3 = Web3(Web3.HTTPProvider(RPC_URL))
140
+ w3.attach_modules({"x402": X402Module})
141
+ w3.x402.configure(account=account, policy="policy.json")
142
+
143
+ r = w3.x402.get("https://api.example.com/paid")
144
+ session = w3.x402.client() # a requests.Session that pays 402s
145
+
146
+ # or in one step
147
+ w3 = Web3(provider, external_modules={
148
+ "x402": X402Module.with_config(account=account, policy="policy.json"),
149
+ })
150
+ ```
151
+
152
+ Signing is local (EIP-712 via the official `EthAccountSigner`); the web3 provider is never asked to sign or send anything.
153
+
154
+ ## Solana (solders)
155
+
156
+ ```python
157
+ from solders.keypair import Keypair
158
+ from plug402.httpx import X402Auth
159
+
160
+ keypair = Keypair.from_base58_string(TEST_KEY)
161
+ auth = X402Auth([account, keypair], "policy.json", svm_rpc_url="https://api.devnet.solana.com")
162
+ ```
163
+
164
+ Give at most one EVM and one Solana signer. `plug402.signers.from_local_account(acct)` and `from_solders_keypair(kp)` wrap your keys in the official `EthAccountSigner` / `KeypairSigner`. Every add-on also accepts the raw account or keypair, or an official signer. The official Solana scheme reads the token mint over RPC (`svm_rpc_url`, or the network's public default).
165
+
166
+ ## Approval above a threshold
167
+
168
+ When the policy says `ask` (an amount above `askAbove`), plug402 calls your callback with read-only data and pays only if it returns `True`:
169
+
170
+ ```python
171
+ from plug402 import ApprovalRequest
172
+
173
+ def approve(req: ApprovalRequest) -> bool:
174
+ return input(f"Pay {req.amount} of {req.asset} on {req.network} to {req.pay_to} for {req.origin}? ") == "y"
175
+
176
+ auth = X402Auth(account, "policy.json", approve=approve)
177
+ ```
178
+
179
+ With `httpx.AsyncClient` the callback may be `async`. Without a callback, `ask` is refused.
180
+
181
+ ## Receipts
182
+
183
+ Every payment gets a receipt in a ledger: an in-memory one by default, or a JSON Lines file.
184
+
185
+ ```python
186
+ from plug402 import JsonlLedger
187
+
188
+ auth = X402Auth(account, "policy.json", JsonlLedger("payments.receipts.jsonl"))
189
+ for receipt in auth.ledger.receipts():
190
+ print(receipt.to_dict())
191
+ ```
192
+
193
+ ```json
194
+ {"v":1,"id":"…","ts":"2026-11-30T12:00:00.000Z","origin":"https://api.example.com","network":"eip155:84532",
195
+ "asset":"0x036C…","amount":"10000","payTo":"0x…","scheme":"exact","x402Version":2,
196
+ "decision":"allow","approvedBy":"policy","status":"settled","transaction":"0x…"}
197
+ ```
198
+
199
+ A receipt is written `pending` before the paid request is sent, so concurrent requests count it against the limits. Then:
200
+
201
+ - `settled` when `PAYMENT-RESPONSE` says `success: true`, whatever the HTTP status (money moved);
202
+ - `failed` when it says `success: false`, on a non-2xx response without `PAYMENT-RESPONSE` (a second `402` included), or on a transport error before any response;
203
+ - still `pending` (and still counting) on `success: false` with `errorReason: "settlement_pending"` (the transaction is recorded) and on a 2xx response without `PAYMENT-RESPONSE`.
204
+
205
+ `ts` is when the payment was decided and never changes; `network` is always CAIP-2, also for v1 payments, so v1 and v2 share one budget. The JSONL file is append-only (the last line per `id` wins) and is created with mode `0600`.
206
+
207
+ Receipts hold the **origin only** (scheme, host, port). They never hold the full URL, query, headers, bodies, signatures, payloads or keys.
208
+
209
+ ## Errors and limits
210
+
211
+ | Error | When | Signed? |
212
+ |---|---|---|
213
+ | `PaymentDenied` | no offered entry is allowed (or approved); `.entries` gives `(index, reason)` for every entry, `.approval` says `"rejected"` or `"no-callback"` | never |
214
+ | `PaymentFailed` | the paid retry came back `402` again; `.receipt_id`, `.response` | once, never twice |
215
+ | `PaymentError` | a malformed `402`, or the payment could not be created | — |
216
+
217
+ Reason codes come from the spec: `invalid-requirement`, `scheme-not-allowed`, `unsupported`, `network-not-allowed`, `payto-not-allowed`, `no-limit`, `over-per-request`, `over-daily`, `rate-limited`, `needs-approval`, and `insecure-origin`. `unsupported` also covers entries this client cannot pay (no signer for the chain family, a scheme, transfer method, payment flow or Solana transaction version it does not implement); those carry a free-text `detail`, e.g. `DeniedEntry(index=0, reason="unsupported", detail="no Solana signer configured")`.
218
+
219
+ A request is retried **once**. A `402` without x402 payment requirements is returned to you unchanged. A request that already carries a payment header is not paid again.
220
+
221
+ ## How "nothing is signed before the policy allows it" holds
222
+
223
+ 1. plug402 reads the `402` itself, decides every entry with the policy, and picks one (asking you if needed). On a deny it raises `PaymentDenied` and the official client is never called.
224
+ 2. It hands the official `x402Client`/`x402ClientSync` a `PaymentRequired` that contains **only the approved entry**, so the official selection cannot pick anything else.
225
+ 3. Every official client plug402 builds carries a `before_payment_creation` hook, the official hook that runs before the scheme's `create_payment_payload`. It aborts unless plug402 issued a single-use permit for exactly that requirement. Calling the official client directly, or trying to sign twice for one `402`, is refused.
226
+
227
+ plug402's policy replaces the official SDK's own spend controls (default-asset allowlist and $1 cap), which it turns off on the clients it builds: the plug402 policy is explicit and default-deny.
228
+
229
+ ## Development
230
+
231
+ ```sh
232
+ cd python
233
+ uv venv .venv && uv pip install --python .venv/bin/python -e ".[all]" pytest ruff build
234
+ .venv/bin/python -m pytest # offline: policy, selection, signing vectors, mock x402 server
235
+ .venv/bin/ruff check src tests && .venv/bin/ruff format --check src tests
236
+ ```
237
+
238
+ Tests are offline: an in-process mock x402 server (v1 and v2, EVM and Solana) and the shared vectors in `spec/vectors/`. Tests use public test keys only (Anvil/Hardhat account #0, and a Solana keypair from a seed of 32 `0x01` bytes).
239
+
240
+ End-to-end tests against Base Sepolia and Solana devnet run only with `PLUG402_E2E=1`, with keys and endpoints in a git-ignored `.env` under the names every language uses: `PLUG402_E2E_EVM_PRIVATE_KEY`, `PLUG402_E2E_EVM_URL`, `PLUG402_E2E_SOLANA_SECRET_KEY`, `PLUG402_E2E_SVM_URL` and, optionally, `PLUG402_E2E_SOLANA_RPC_URL` (see `tests/test_e2e.py`). Never use a key that holds real funds.
241
+
242
+ ## License
243
+
244
+ Apache-2.0.
@@ -0,0 +1,198 @@
1
+ # plug402 for Python
2
+
3
+ **x402 payments for the HTTP client and keys you already use**: `httpx`, `requests`, web3.py, eth-account and solders, under a **spend policy** you control.
4
+
5
+ When a request comes back `402 Payment Required`, plug402 reads the payment requirements, checks every offered option against your policy, signs the allowed one with your existing key through the official [`x402`](https://pypi.org/project/x402/) package, retries the request once with the payment, and writes a **receipt**.
6
+
7
+ > Status: **v0.1 in development.** Not yet published to PyPI. Testnets only. x402 v2 (and v1 responses), scheme `exact`, EVM (EIP-3009) and Solana.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pip install "plug402[httpx,evm]" # httpx + an eth-account key
13
+ pip install "plug402[requests,svm]" # requests + a solders keypair
14
+ pip install "plug402[web3]" # w3.x402 for web3.py
15
+ pip install "plug402[all]" # everything
16
+ ```
17
+
18
+ | Extra | Gives you | Pulls in |
19
+ |---|---|---|
20
+ | (none) | policy, receipts, ledgers, errors | nothing: the core has no dependencies |
21
+ | `httpx` | `plug402.httpx.X402Auth` | `x402`, `httpx` |
22
+ | `requests` | `plug402.requests.X402Adapter`, `x402_session` | `x402`, `requests` |
23
+ | `web3` | `plug402.web3.X402Module` (`w3.x402`) | `x402[evm]`, `web3`, `requests` |
24
+ | `evm` | EVM signing (eth-account) | `x402[evm]` |
25
+ | `svm` | Solana signing (solders) | `x402[svm]` |
26
+
27
+ Python 3.10 or newer.
28
+
29
+ ## A policy
30
+
31
+ Nothing is paid unless a limit rule covers it (default deny). Amounts are atomic units as decimal strings (USDC has 6 decimals: `"100000"` is 0.10 USDC).
32
+
33
+ ```json
34
+ {
35
+ "version": 1,
36
+ "networks": ["eip155:84532", "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"],
37
+ "payTo": null,
38
+ "limits": [
39
+ { "network": "eip155:84532", "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
40
+ "maxPerRequest": "100000", "maxPerDay": "1000000", "askAbove": "50000" },
41
+ { "network": "solana:*", "asset": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
42
+ "maxPerRequest": "200000" }
43
+ ],
44
+ "maxPaymentsPerMinute": 30
45
+ }
46
+ ```
47
+
48
+ Pass it as a path, a dict, or a `plug402.Policy`. The full contract, including the decision table, is in [`spec/README.md`](../spec/README.md) and [`spec/policy.schema.json`](../spec/policy.schema.json).
49
+
50
+ A few rules beyond the limits:
51
+
52
+ - **HTTPS only by default.** A request to a non-loopback `http:` origin is never paid unless the policy sets `"allowHttp": true` (`http://localhost`, `127.0.0.1` and `::1` are fine).
53
+ - **Recipients.** With a `payTo` allowlist, the main recipient and every `extra.splits[].payTo` must be on it.
54
+ - **What v0.1 pays.** Scheme `exact`, EIP-3009 on EVM (Permit2 and other transfer methods are refused), the x402 payment flows `authorization`, `upfront` and `escrow`, and Solana transaction versions 0 and 1. Solana payments with `extra.splits` or `ataCreationRequired: true` are refused as `unsupported`: the official `x402` Python client (2.29) builds a single transfer to an existing token account and cannot build them.
55
+
56
+ ## httpx
57
+
58
+ `X402Auth` is an `httpx.Auth`, so it works with `httpx.Client` and `httpx.AsyncClient`, new or existing, for every request or just one.
59
+
60
+ ```python
61
+ import httpx
62
+ from eth_account import Account
63
+ from plug402.httpx import X402Auth
64
+
65
+ account = Account.from_key(TEST_KEY) # your existing eth-account LocalAccount
66
+ auth = X402Auth(account, "policy.json")
67
+
68
+ with httpx.Client(auth=auth) as client:
69
+ r = client.get("https://api.example.com/paid")
70
+
71
+ async with httpx.AsyncClient(auth=auth) as client:
72
+ r = await client.get("https://api.example.com/paid")
73
+ ```
74
+
75
+ ## requests
76
+
77
+ ```python
78
+ from plug402.requests import x402_session
79
+
80
+ session = x402_session(account, "policy.json") # a new Session
81
+ session = x402_session(account, "policy.json", session=s) # or mount on yours
82
+ r = session.get("https://api.example.com/paid")
83
+ ```
84
+
85
+ `X402Adapter` subclasses the official `x402HTTPAdapter`; mount it yourself with `session.mount("https://", X402Adapter(account, "policy.json"))` if you prefer.
86
+
87
+ ## web3.py
88
+
89
+ ```python
90
+ from web3 import Web3
91
+ from plug402.web3 import X402Module
92
+
93
+ w3 = Web3(Web3.HTTPProvider(RPC_URL))
94
+ w3.attach_modules({"x402": X402Module})
95
+ w3.x402.configure(account=account, policy="policy.json")
96
+
97
+ r = w3.x402.get("https://api.example.com/paid")
98
+ session = w3.x402.client() # a requests.Session that pays 402s
99
+
100
+ # or in one step
101
+ w3 = Web3(provider, external_modules={
102
+ "x402": X402Module.with_config(account=account, policy="policy.json"),
103
+ })
104
+ ```
105
+
106
+ Signing is local (EIP-712 via the official `EthAccountSigner`); the web3 provider is never asked to sign or send anything.
107
+
108
+ ## Solana (solders)
109
+
110
+ ```python
111
+ from solders.keypair import Keypair
112
+ from plug402.httpx import X402Auth
113
+
114
+ keypair = Keypair.from_base58_string(TEST_KEY)
115
+ auth = X402Auth([account, keypair], "policy.json", svm_rpc_url="https://api.devnet.solana.com")
116
+ ```
117
+
118
+ Give at most one EVM and one Solana signer. `plug402.signers.from_local_account(acct)` and `from_solders_keypair(kp)` wrap your keys in the official `EthAccountSigner` / `KeypairSigner`. Every add-on also accepts the raw account or keypair, or an official signer. The official Solana scheme reads the token mint over RPC (`svm_rpc_url`, or the network's public default).
119
+
120
+ ## Approval above a threshold
121
+
122
+ When the policy says `ask` (an amount above `askAbove`), plug402 calls your callback with read-only data and pays only if it returns `True`:
123
+
124
+ ```python
125
+ from plug402 import ApprovalRequest
126
+
127
+ def approve(req: ApprovalRequest) -> bool:
128
+ return input(f"Pay {req.amount} of {req.asset} on {req.network} to {req.pay_to} for {req.origin}? ") == "y"
129
+
130
+ auth = X402Auth(account, "policy.json", approve=approve)
131
+ ```
132
+
133
+ With `httpx.AsyncClient` the callback may be `async`. Without a callback, `ask` is refused.
134
+
135
+ ## Receipts
136
+
137
+ Every payment gets a receipt in a ledger: an in-memory one by default, or a JSON Lines file.
138
+
139
+ ```python
140
+ from plug402 import JsonlLedger
141
+
142
+ auth = X402Auth(account, "policy.json", JsonlLedger("payments.receipts.jsonl"))
143
+ for receipt in auth.ledger.receipts():
144
+ print(receipt.to_dict())
145
+ ```
146
+
147
+ ```json
148
+ {"v":1,"id":"…","ts":"2026-11-30T12:00:00.000Z","origin":"https://api.example.com","network":"eip155:84532",
149
+ "asset":"0x036C…","amount":"10000","payTo":"0x…","scheme":"exact","x402Version":2,
150
+ "decision":"allow","approvedBy":"policy","status":"settled","transaction":"0x…"}
151
+ ```
152
+
153
+ A receipt is written `pending` before the paid request is sent, so concurrent requests count it against the limits. Then:
154
+
155
+ - `settled` when `PAYMENT-RESPONSE` says `success: true`, whatever the HTTP status (money moved);
156
+ - `failed` when it says `success: false`, on a non-2xx response without `PAYMENT-RESPONSE` (a second `402` included), or on a transport error before any response;
157
+ - still `pending` (and still counting) on `success: false` with `errorReason: "settlement_pending"` (the transaction is recorded) and on a 2xx response without `PAYMENT-RESPONSE`.
158
+
159
+ `ts` is when the payment was decided and never changes; `network` is always CAIP-2, also for v1 payments, so v1 and v2 share one budget. The JSONL file is append-only (the last line per `id` wins) and is created with mode `0600`.
160
+
161
+ Receipts hold the **origin only** (scheme, host, port). They never hold the full URL, query, headers, bodies, signatures, payloads or keys.
162
+
163
+ ## Errors and limits
164
+
165
+ | Error | When | Signed? |
166
+ |---|---|---|
167
+ | `PaymentDenied` | no offered entry is allowed (or approved); `.entries` gives `(index, reason)` for every entry, `.approval` says `"rejected"` or `"no-callback"` | never |
168
+ | `PaymentFailed` | the paid retry came back `402` again; `.receipt_id`, `.response` | once, never twice |
169
+ | `PaymentError` | a malformed `402`, or the payment could not be created | — |
170
+
171
+ Reason codes come from the spec: `invalid-requirement`, `scheme-not-allowed`, `unsupported`, `network-not-allowed`, `payto-not-allowed`, `no-limit`, `over-per-request`, `over-daily`, `rate-limited`, `needs-approval`, and `insecure-origin`. `unsupported` also covers entries this client cannot pay (no signer for the chain family, a scheme, transfer method, payment flow or Solana transaction version it does not implement); those carry a free-text `detail`, e.g. `DeniedEntry(index=0, reason="unsupported", detail="no Solana signer configured")`.
172
+
173
+ A request is retried **once**. A `402` without x402 payment requirements is returned to you unchanged. A request that already carries a payment header is not paid again.
174
+
175
+ ## How "nothing is signed before the policy allows it" holds
176
+
177
+ 1. plug402 reads the `402` itself, decides every entry with the policy, and picks one (asking you if needed). On a deny it raises `PaymentDenied` and the official client is never called.
178
+ 2. It hands the official `x402Client`/`x402ClientSync` a `PaymentRequired` that contains **only the approved entry**, so the official selection cannot pick anything else.
179
+ 3. Every official client plug402 builds carries a `before_payment_creation` hook, the official hook that runs before the scheme's `create_payment_payload`. It aborts unless plug402 issued a single-use permit for exactly that requirement. Calling the official client directly, or trying to sign twice for one `402`, is refused.
180
+
181
+ plug402's policy replaces the official SDK's own spend controls (default-asset allowlist and $1 cap), which it turns off on the clients it builds: the plug402 policy is explicit and default-deny.
182
+
183
+ ## Development
184
+
185
+ ```sh
186
+ cd python
187
+ uv venv .venv && uv pip install --python .venv/bin/python -e ".[all]" pytest ruff build
188
+ .venv/bin/python -m pytest # offline: policy, selection, signing vectors, mock x402 server
189
+ .venv/bin/ruff check src tests && .venv/bin/ruff format --check src tests
190
+ ```
191
+
192
+ Tests are offline: an in-process mock x402 server (v1 and v2, EVM and Solana) and the shared vectors in `spec/vectors/`. Tests use public test keys only (Anvil/Hardhat account #0, and a Solana keypair from a seed of 32 `0x01` bytes).
193
+
194
+ End-to-end tests against Base Sepolia and Solana devnet run only with `PLUG402_E2E=1`, with keys and endpoints in a git-ignored `.env` under the names every language uses: `PLUG402_E2E_EVM_PRIVATE_KEY`, `PLUG402_E2E_EVM_URL`, `PLUG402_E2E_SOLANA_SECRET_KEY`, `PLUG402_E2E_SVM_URL` and, optionally, `PLUG402_E2E_SOLANA_RPC_URL` (see `tests/test_e2e.py`). Never use a key that holds real funds.
195
+
196
+ ## License
197
+
198
+ Apache-2.0.