plug402 0.1.0__py3-none-any.whl
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.
- plug402/__init__.py +51 -0
- plug402/_engine.py +526 -0
- plug402/errors.py +88 -0
- plug402/httpx.py +136 -0
- plug402/ledger.py +294 -0
- plug402/policy.py +527 -0
- plug402/py.typed +0 -0
- plug402/requests.py +146 -0
- plug402/signers.py +35 -0
- plug402/web3.py +145 -0
- plug402-0.1.0.dist-info/METADATA +244 -0
- plug402-0.1.0.dist-info/RECORD +14 -0
- plug402-0.1.0.dist-info/WHEEL +4 -0
- plug402-0.1.0.dist-info/licenses/LICENSE +202 -0
plug402/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""plug402: x402 payments for the Python HTTP client and keys you already use.
|
|
2
|
+
|
|
3
|
+
The core (this module) has no third-party dependencies: the spend policy,
|
|
4
|
+
receipts, ledgers and errors. The add-ons need extras:
|
|
5
|
+
|
|
6
|
+
- ``plug402.httpx`` (``plug402[httpx]``): ``X402Auth`` for ``httpx.Client`` and ``httpx.AsyncClient``.
|
|
7
|
+
- ``plug402.requests`` (``plug402[requests]``): ``X402Adapter`` and ``x402_session``.
|
|
8
|
+
- ``plug402.web3`` (``plug402[web3]``): ``w3.x402`` for web3.py.
|
|
9
|
+
- ``plug402.signers``: ``from_local_account`` (``plug402[evm]``) and
|
|
10
|
+
``from_solders_keypair`` (``plug402[svm]``).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from .errors import DeniedEntry, PaymentDenied, PaymentError, PaymentFailed
|
|
14
|
+
from .ledger import JsonlLedger, Ledger, MemoryLedger, Receipt, origin_of
|
|
15
|
+
from .policy import (
|
|
16
|
+
ApprovalRequest,
|
|
17
|
+
Approve,
|
|
18
|
+
Choice,
|
|
19
|
+
Decision,
|
|
20
|
+
LimitRule,
|
|
21
|
+
Policy,
|
|
22
|
+
PolicyError,
|
|
23
|
+
State,
|
|
24
|
+
choose,
|
|
25
|
+
evaluate,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"ApprovalRequest",
|
|
32
|
+
"Approve",
|
|
33
|
+
"Choice",
|
|
34
|
+
"Decision",
|
|
35
|
+
"DeniedEntry",
|
|
36
|
+
"JsonlLedger",
|
|
37
|
+
"Ledger",
|
|
38
|
+
"LimitRule",
|
|
39
|
+
"MemoryLedger",
|
|
40
|
+
"PaymentDenied",
|
|
41
|
+
"PaymentError",
|
|
42
|
+
"PaymentFailed",
|
|
43
|
+
"Policy",
|
|
44
|
+
"PolicyError",
|
|
45
|
+
"Receipt",
|
|
46
|
+
"State",
|
|
47
|
+
"__version__",
|
|
48
|
+
"choose",
|
|
49
|
+
"evaluate",
|
|
50
|
+
"origin_of",
|
|
51
|
+
]
|
plug402/_engine.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"""The payment engine shared by the httpx, requests and web3.py add-ons.
|
|
2
|
+
|
|
3
|
+
It sits between a ``402`` response and the official ``x402`` client:
|
|
4
|
+
|
|
5
|
+
1. read the ``PaymentRequired`` document (v2 header or v1 body) as raw JSON;
|
|
6
|
+
2. decide every ``accepts`` entry with the plug402 spend policy, in the
|
|
7
|
+
server's order (spec 3.1, 3.2), and pick one, asking the approval callback
|
|
8
|
+
when needed; ``PaymentDenied`` if nothing can be paid;
|
|
9
|
+
3. write a ``pending`` receipt while holding the ledger lock (spec 3.3);
|
|
10
|
+
4. hand the official ``x402Client`` / ``x402ClientSync`` a ``PaymentRequired``
|
|
11
|
+
whose ``accepts`` holds **only the approved entry**, so the official
|
|
12
|
+
selection can pick nothing else, and the official scheme mechanism
|
|
13
|
+
(``ExactEvmScheme`` / ``ExactSvmScheme``) signs it;
|
|
14
|
+
5. after the paid retry, mark the receipt ``settled`` or ``failed`` from
|
|
15
|
+
``PAYMENT-RESPONSE``.
|
|
16
|
+
|
|
17
|
+
Defence in depth: every official client built here carries a
|
|
18
|
+
``before_payment_creation`` hook (the official hook that runs before the
|
|
19
|
+
scheme's ``create_payment_payload``, i.e. before anything is signed) that
|
|
20
|
+
aborts unless the engine issued a single-use permit for exactly that
|
|
21
|
+
requirement. Using the official client directly, or a second signing attempt
|
|
22
|
+
for the same 402, is refused.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import inspect
|
|
28
|
+
import json
|
|
29
|
+
import time
|
|
30
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
31
|
+
from contextvars import ContextVar
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from datetime import datetime, timezone
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from x402 import x402Client, x402ClientSync
|
|
37
|
+
from x402.http.constants import PAYMENT_REQUIRED_HEADER
|
|
38
|
+
from x402.http.utils import safe_base64_decode
|
|
39
|
+
from x402.http.x402_http_client import x402HTTPClientSync
|
|
40
|
+
from x402.schemas import AbortResult, PaymentRequired, PaymentRequiredV1
|
|
41
|
+
|
|
42
|
+
from .errors import DeniedEntry, PaymentDenied, PaymentError
|
|
43
|
+
from .ledger import Ledger, MemoryLedger, Receipt, format_ts, new_receipt_id
|
|
44
|
+
from .policy import (
|
|
45
|
+
ApprovalRequest,
|
|
46
|
+
Approve,
|
|
47
|
+
Decision,
|
|
48
|
+
Policy,
|
|
49
|
+
choose,
|
|
50
|
+
evaluate,
|
|
51
|
+
normalize_requirement,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
GetHeader = Callable[[str], "str | None"]
|
|
55
|
+
|
|
56
|
+
# ----------------------------------------------------------------------------
|
|
57
|
+
# Signers
|
|
58
|
+
# ----------------------------------------------------------------------------
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _signer_kind(signer: Any) -> tuple[str, Any]:
|
|
62
|
+
"""Classify a signer as ``"evm"`` or ``"svm"`` and wrap raw keys in official signers."""
|
|
63
|
+
try:
|
|
64
|
+
from eth_account.signers.base import BaseAccount
|
|
65
|
+
except ImportError: # pragma: no cover - eth-account not installed
|
|
66
|
+
BaseAccount = None # type: ignore[assignment,misc]
|
|
67
|
+
if BaseAccount is not None and isinstance(signer, BaseAccount):
|
|
68
|
+
from x402.mechanisms.evm.signers import EthAccountSigner
|
|
69
|
+
|
|
70
|
+
return "evm", EthAccountSigner(signer) # type: ignore[arg-type]
|
|
71
|
+
try:
|
|
72
|
+
from solders.keypair import Keypair
|
|
73
|
+
except ImportError: # pragma: no cover - solders not installed
|
|
74
|
+
Keypair = None # type: ignore[assignment,misc]
|
|
75
|
+
if Keypair is not None and isinstance(signer, Keypair):
|
|
76
|
+
from x402.mechanisms.svm.signers import KeypairSigner
|
|
77
|
+
|
|
78
|
+
return "svm", KeypairSigner(signer)
|
|
79
|
+
|
|
80
|
+
# Look the attributes up statically: classifying a signer must not touch its key.
|
|
81
|
+
def has(name: str) -> bool:
|
|
82
|
+
return inspect.getattr_static(signer, name, None) is not None
|
|
83
|
+
|
|
84
|
+
if has("sign_typed_data") and has("address"):
|
|
85
|
+
return "evm", signer
|
|
86
|
+
if has("keypair") and has("address"):
|
|
87
|
+
return "svm", signer
|
|
88
|
+
raise TypeError(
|
|
89
|
+
"unsupported signer: pass an eth-account LocalAccount, a solders Keypair, "
|
|
90
|
+
"or an official x402 client signer (EthAccountSigner, KeypairSigner)"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ----------------------------------------------------------------------------
|
|
95
|
+
# The signing permit (checked by the official before_payment_creation hook)
|
|
96
|
+
# ----------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class _Permit:
|
|
101
|
+
key: tuple[str, str, str, str, str]
|
|
102
|
+
used: bool = False
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
_PERMIT: ContextVar[_Permit | None] = ContextVar("plug402_permit", default=None)
|
|
106
|
+
|
|
107
|
+
POLICY_ABORT_REASON = "plug402: not approved by the spend policy"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _requirement_key(req: Any) -> tuple[str, str, str, str, str]:
|
|
111
|
+
return (str(req.scheme), str(req.network), str(req.asset), str(req.get_amount()), str(req.pay_to))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _policy_guard(ctx: Any) -> AbortResult | None:
|
|
115
|
+
"""Official ``before_payment_creation`` hook: abort unless plug402 issued a permit."""
|
|
116
|
+
permit = _PERMIT.get()
|
|
117
|
+
if permit is None or permit.used or permit.key != _requirement_key(ctx.selected_requirements):
|
|
118
|
+
return AbortResult(reason=POLICY_ABORT_REASON)
|
|
119
|
+
permit.used = True
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ----------------------------------------------------------------------------
|
|
124
|
+
# Reading the 402
|
|
125
|
+
# ----------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class Offer:
|
|
130
|
+
"""The raw ``PaymentRequired`` document of a 402 response."""
|
|
131
|
+
|
|
132
|
+
version: int
|
|
133
|
+
doc: Mapping[str, Any]
|
|
134
|
+
accepts: Sequence[Any]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def read_offer(get_header: GetHeader, body: bytes | None) -> Offer | None:
|
|
138
|
+
"""Read the v2 ``PAYMENT-REQUIRED`` header, else a v1 JSON body.
|
|
139
|
+
|
|
140
|
+
Same order as the official ``x402HTTPClient.get_payment_required_response``.
|
|
141
|
+
Returns ``None`` for a 402 that carries no x402 payment requirements.
|
|
142
|
+
"""
|
|
143
|
+
header = get_header(PAYMENT_REQUIRED_HEADER)
|
|
144
|
+
if isinstance(header, str) and header:
|
|
145
|
+
try:
|
|
146
|
+
doc = json.loads(safe_base64_decode(header))
|
|
147
|
+
except Exception as e:
|
|
148
|
+
raise PaymentError("malformed PAYMENT-REQUIRED header") from e
|
|
149
|
+
if not isinstance(doc, dict):
|
|
150
|
+
raise PaymentError("PAYMENT-REQUIRED header is not a JSON object")
|
|
151
|
+
version = doc.get("x402Version", 2)
|
|
152
|
+
elif body:
|
|
153
|
+
try:
|
|
154
|
+
doc = json.loads(body)
|
|
155
|
+
except (ValueError, UnicodeDecodeError):
|
|
156
|
+
return None
|
|
157
|
+
if not isinstance(doc, dict) or doc.get("x402Version") != 1:
|
|
158
|
+
return None
|
|
159
|
+
version = 1
|
|
160
|
+
else:
|
|
161
|
+
return None
|
|
162
|
+
if version not in (1, 2) or isinstance(version, bool):
|
|
163
|
+
raise PaymentError(f"unsupported x402Version: {version!r}")
|
|
164
|
+
accepts = doc.get("accepts")
|
|
165
|
+
if not isinstance(accepts, list):
|
|
166
|
+
raise PaymentError("PaymentRequired has no accepts array")
|
|
167
|
+
return Offer(version=version, doc=doc, accepts=accepts)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _extra(raw: Any) -> Mapping[str, Any]:
|
|
171
|
+
extra = raw.get("extra") if isinstance(raw, Mapping) else None
|
|
172
|
+
if isinstance(extra, str): # v1 servers sometimes send extra as a JSON string
|
|
173
|
+
try:
|
|
174
|
+
extra = json.loads(extra)
|
|
175
|
+
except ValueError:
|
|
176
|
+
return {}
|
|
177
|
+
return extra if isinstance(extra, Mapping) else {}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _typed(offer: Offer, index: int) -> PaymentRequired | PaymentRequiredV1:
|
|
181
|
+
"""The official model of the document, narrowed to the one entry ``index``."""
|
|
182
|
+
narrowed = {**offer.doc, "accepts": [offer.accepts[index]]}
|
|
183
|
+
if offer.version == 1:
|
|
184
|
+
return PaymentRequiredV1.model_validate(narrowed)
|
|
185
|
+
return PaymentRequired.model_validate(narrowed)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ----------------------------------------------------------------------------
|
|
189
|
+
# One payment in flight
|
|
190
|
+
# ----------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Payment:
|
|
194
|
+
"""A signed payment: the headers for the retry and its pending receipt."""
|
|
195
|
+
|
|
196
|
+
def __init__(self, engine: Engine, receipt: Receipt, headers: dict[str, str]) -> None:
|
|
197
|
+
self._engine = engine
|
|
198
|
+
self.receipt = receipt
|
|
199
|
+
self.headers = headers
|
|
200
|
+
self._done = False
|
|
201
|
+
|
|
202
|
+
def complete(self, status_code: int, get_header: GetHeader) -> Receipt:
|
|
203
|
+
"""Update the receipt from the paid response (spec 3.3).
|
|
204
|
+
|
|
205
|
+
- ``settled`` when ``PAYMENT-RESPONSE`` says ``success: true``, whatever
|
|
206
|
+
the HTTP status (money moved);
|
|
207
|
+
- stays ``pending`` and records the transaction for ``success: false``
|
|
208
|
+
with ``errorReason: "settlement_pending"`` (non-terminal in x402);
|
|
209
|
+
- ``failed`` for any other ``success: false``, and for a non-2xx
|
|
210
|
+
response (a second ``402`` included) without ``PAYMENT-RESPONSE``;
|
|
211
|
+
- stays ``pending`` on a 2xx response without ``PAYMENT-RESPONSE``.
|
|
212
|
+
|
|
213
|
+
A pending receipt keeps counting against the limits.
|
|
214
|
+
"""
|
|
215
|
+
if self._done:
|
|
216
|
+
return self.receipt
|
|
217
|
+
self._done = True
|
|
218
|
+
try:
|
|
219
|
+
settle = self._engine.http.get_payment_settle_response(get_header)
|
|
220
|
+
except Exception:
|
|
221
|
+
settle = None
|
|
222
|
+
if settle is None:
|
|
223
|
+
if 200 <= status_code < 300:
|
|
224
|
+
return self.receipt
|
|
225
|
+
return self._update("failed", None)
|
|
226
|
+
tx = settle.transaction or None
|
|
227
|
+
if settle.success:
|
|
228
|
+
return self._update("settled", tx)
|
|
229
|
+
if settle.error_reason == "settlement_pending":
|
|
230
|
+
return self._update("pending", tx) if tx else self.receipt
|
|
231
|
+
return self._update("failed", tx)
|
|
232
|
+
|
|
233
|
+
def fail(self) -> Receipt:
|
|
234
|
+
"""Mark the receipt ``failed`` (transport error before any response)."""
|
|
235
|
+
if self._done:
|
|
236
|
+
return self.receipt
|
|
237
|
+
self._done = True
|
|
238
|
+
return self._update("failed", None)
|
|
239
|
+
|
|
240
|
+
def _update(self, status: str, tx: str | None) -> Receipt:
|
|
241
|
+
self.receipt = self.receipt.with_status(status, tx) # type: ignore[arg-type]
|
|
242
|
+
self._engine.ledger.put(self.receipt)
|
|
243
|
+
return self.receipt
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# ----------------------------------------------------------------------------
|
|
247
|
+
# The engine
|
|
248
|
+
# ----------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class Engine:
|
|
252
|
+
"""Policy, ledger, approval callback and official x402 clients for one add-on.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
signers: One signer or a list (at most one EVM and one SVM signer):
|
|
256
|
+
an eth-account ``LocalAccount``, a solders ``Keypair``, or an
|
|
257
|
+
official ``EthAccountSigner`` / ``KeypairSigner``.
|
|
258
|
+
policy: A :class:`~plug402.Policy`, a policy dict, or a path to a JSON file.
|
|
259
|
+
ledger: Where receipts go; a new :class:`~plug402.MemoryLedger` by default.
|
|
260
|
+
approve: Approval callback for ``ask`` decisions; ``None`` refuses them.
|
|
261
|
+
svm_rpc_url: Solana RPC endpoint for the official SVM scheme (mint
|
|
262
|
+
metadata and, when the server sends none, a recent blockhash).
|
|
263
|
+
clock: Returns the current time in seconds (tests).
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
def __init__(
|
|
267
|
+
self,
|
|
268
|
+
signers: Any,
|
|
269
|
+
policy: Policy | Mapping[str, Any] | str,
|
|
270
|
+
ledger: Ledger | None = None,
|
|
271
|
+
approve: Approve | None = None,
|
|
272
|
+
*,
|
|
273
|
+
svm_rpc_url: str | None = None,
|
|
274
|
+
clock: Callable[[], float] | None = None,
|
|
275
|
+
) -> None:
|
|
276
|
+
self.policy = Policy.load(policy)
|
|
277
|
+
self.ledger: Ledger = ledger if ledger is not None else MemoryLedger()
|
|
278
|
+
self.approve = approve
|
|
279
|
+
self._clock = clock or time.time
|
|
280
|
+
self._svm_rpc_url = svm_rpc_url
|
|
281
|
+
if signers is None:
|
|
282
|
+
signers = []
|
|
283
|
+
if not isinstance(signers, (list, tuple)):
|
|
284
|
+
signers = [signers]
|
|
285
|
+
self._signers: dict[str, Any] = {}
|
|
286
|
+
for s in signers:
|
|
287
|
+
kind, wrapped = _signer_kind(s)
|
|
288
|
+
if kind in self._signers:
|
|
289
|
+
raise ValueError(f"more than one {kind.upper()} signer given; pass one per chain family")
|
|
290
|
+
self._signers[kind] = wrapped
|
|
291
|
+
if not self._signers:
|
|
292
|
+
raise ValueError("at least one signer is required")
|
|
293
|
+
self._sync_client: x402ClientSync | None = None
|
|
294
|
+
self._async_client: x402Client | None = None
|
|
295
|
+
self.http = x402HTTPClientSync(self.sync_client)
|
|
296
|
+
|
|
297
|
+
# -- official clients --------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
def _build(self, client: Any) -> Any:
|
|
300
|
+
# plug402's policy replaces the official spend controls (default-asset
|
|
301
|
+
# allowlist and $1 cap): the policy is default-deny and explicit.
|
|
302
|
+
client.set_spend_controls(False)
|
|
303
|
+
if "evm" in self._signers:
|
|
304
|
+
from x402.mechanisms.evm.exact import register_exact_evm_client
|
|
305
|
+
|
|
306
|
+
register_exact_evm_client(client, self._signers["evm"])
|
|
307
|
+
if "svm" in self._signers:
|
|
308
|
+
from x402.mechanisms.svm.exact import register_exact_svm_client
|
|
309
|
+
|
|
310
|
+
register_exact_svm_client(client, self._signers["svm"], rpc_url=self._svm_rpc_url)
|
|
311
|
+
client.on_before_payment_creation(_policy_guard)
|
|
312
|
+
return client
|
|
313
|
+
|
|
314
|
+
@property
|
|
315
|
+
def sync_client(self) -> x402ClientSync:
|
|
316
|
+
"""The official sync client (guarded: it signs only with a plug402 permit)."""
|
|
317
|
+
if self._sync_client is None:
|
|
318
|
+
self._sync_client = self._build(x402ClientSync())
|
|
319
|
+
return self._sync_client
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def async_client(self) -> x402Client:
|
|
323
|
+
"""The official async client (guarded: it signs only with a plug402 permit)."""
|
|
324
|
+
if self._async_client is None:
|
|
325
|
+
self._async_client = self._build(x402Client())
|
|
326
|
+
return self._async_client
|
|
327
|
+
|
|
328
|
+
# -- policy -------------------------------------------------------------------
|
|
329
|
+
|
|
330
|
+
def _now(self) -> datetime:
|
|
331
|
+
return datetime.fromtimestamp(self._clock(), tz=timezone.utc)
|
|
332
|
+
|
|
333
|
+
def _cannot_pay(self, offer: Offer, index: int, decision: Decision) -> str | None:
|
|
334
|
+
"""Why this client cannot pay an entry the policy allows or asks about, or ``None``.
|
|
335
|
+
|
|
336
|
+
The answer becomes ``unsupported`` with this text as its detail (spec 3.2, step 1).
|
|
337
|
+
"""
|
|
338
|
+
req = decision.requirement
|
|
339
|
+
if req is None or req.network is None: # the policy denies these before we get here
|
|
340
|
+
return "not a payable requirement"
|
|
341
|
+
if req.scheme != "exact":
|
|
342
|
+
return f"scheme {req.scheme!r} is not implemented"
|
|
343
|
+
extra = _extra(offer.accepts[index])
|
|
344
|
+
family = req.network.split(":", 1)[0]
|
|
345
|
+
if family == "eip155":
|
|
346
|
+
if "evm" not in self._signers:
|
|
347
|
+
return "no EVM signer configured"
|
|
348
|
+
if extra.get("assetTransferMethod") not in (None, "eip3009"): # null counts as absent
|
|
349
|
+
return "only the EIP-3009 transfer method is implemented"
|
|
350
|
+
elif family == "solana":
|
|
351
|
+
if "svm" not in self._signers:
|
|
352
|
+
return "no Solana signer configured"
|
|
353
|
+
# The official Python client (x402 2.29) builds one TransferChecked of the full
|
|
354
|
+
# amount to payTo's existing token account: it ignores splits and ATA creation, so
|
|
355
|
+
# such a payment would not be the one the server asked for (spec 3.2, step 1).
|
|
356
|
+
if extra.get("splits") not in (None, []):
|
|
357
|
+
return "extra.splits is not implemented by the official x402 Python client"
|
|
358
|
+
if extra.get("ataCreationRequired") is True:
|
|
359
|
+
return "extra.ataCreationRequired is not implemented by the official x402 Python client"
|
|
360
|
+
from x402.mechanisms.svm.utils import resolve_transaction_version
|
|
361
|
+
|
|
362
|
+
try: # the official client builds versions 0 and 1; refuse what it cannot build
|
|
363
|
+
resolve_transaction_version(dict(extra))
|
|
364
|
+
except ValueError as e:
|
|
365
|
+
return f"Solana transaction version: {e}"
|
|
366
|
+
else:
|
|
367
|
+
return f"no signer for chain family {family!r}"
|
|
368
|
+
try:
|
|
369
|
+
_typed(offer, index)
|
|
370
|
+
except Exception as e:
|
|
371
|
+
return f"the official x402 SDK rejects the entry ({type(e).__name__})"
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
def _client_check(self, offer: Offer, index: int, d: Decision) -> Decision:
|
|
375
|
+
if d.decision == "deny":
|
|
376
|
+
return d
|
|
377
|
+
why = self._cannot_pay(offer, index, d)
|
|
378
|
+
if why is None:
|
|
379
|
+
return d
|
|
380
|
+
return Decision("deny", "unsupported", d.requirement, d.rule, detail=why)
|
|
381
|
+
|
|
382
|
+
def _decide_all(self, offer: Offer, origin: str, now: datetime) -> list[Decision]:
|
|
383
|
+
decisions = evaluate(
|
|
384
|
+
self.policy,
|
|
385
|
+
offer.accepts,
|
|
386
|
+
offer.version,
|
|
387
|
+
lambda network, asset: self.ledger.state(network, asset, now),
|
|
388
|
+
origin=origin,
|
|
389
|
+
)
|
|
390
|
+
return [self._client_check(offer, i, d) for i, d in enumerate(decisions)]
|
|
391
|
+
|
|
392
|
+
def _decide_one(self, offer: Offer, index: int, now: datetime) -> Decision:
|
|
393
|
+
raw = offer.accepts[index]
|
|
394
|
+
req = normalize_requirement(raw, offer.version)
|
|
395
|
+
state = None
|
|
396
|
+
if req is not None and req.network is not None:
|
|
397
|
+
state = self.ledger.state(req.network, req.asset, now)
|
|
398
|
+
return self._client_check(offer, index, self.policy.decide(raw, state, offer.version))
|
|
399
|
+
|
|
400
|
+
@staticmethod
|
|
401
|
+
def _denied(decisions: Sequence[Decision]) -> list[DeniedEntry]:
|
|
402
|
+
return [DeniedEntry(i, d.reason, d.detail) for i, d in enumerate(decisions)]
|
|
403
|
+
|
|
404
|
+
def _reserve(
|
|
405
|
+
self, offer: Offer, index: int, decision: Decision, origin: str, now: datetime, human: bool
|
|
406
|
+
) -> Receipt:
|
|
407
|
+
req = decision.requirement
|
|
408
|
+
assert req is not None and req.network is not None
|
|
409
|
+
receipt = Receipt(
|
|
410
|
+
id=new_receipt_id(),
|
|
411
|
+
ts=format_ts(now),
|
|
412
|
+
origin=origin,
|
|
413
|
+
network=req.network,
|
|
414
|
+
asset=req.asset,
|
|
415
|
+
amount=str(req.amount),
|
|
416
|
+
pay_to=req.pay_to,
|
|
417
|
+
scheme=req.scheme,
|
|
418
|
+
x402_version=offer.version,
|
|
419
|
+
decision="ask" if human else "allow",
|
|
420
|
+
approved_by="human" if human else "policy",
|
|
421
|
+
status="pending",
|
|
422
|
+
)
|
|
423
|
+
self.ledger.put(receipt)
|
|
424
|
+
return receipt
|
|
425
|
+
|
|
426
|
+
def _approval_request(self, decision: Decision, origin: str) -> ApprovalRequest:
|
|
427
|
+
req = decision.requirement
|
|
428
|
+
assert req is not None and req.network is not None
|
|
429
|
+
return ApprovalRequest(
|
|
430
|
+
network=req.network,
|
|
431
|
+
asset=req.asset,
|
|
432
|
+
amount=str(req.amount),
|
|
433
|
+
pay_to=req.pay_to,
|
|
434
|
+
scheme=req.scheme,
|
|
435
|
+
origin=origin,
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
def _start(self, offer: Offer, origin: str) -> tuple[Receipt | None, list[Decision], int | None]:
|
|
439
|
+
"""Decide; reserve if allowed. Returns (receipt, decisions, ask_index)."""
|
|
440
|
+
with self.ledger.lock():
|
|
441
|
+
now = self._now()
|
|
442
|
+
decisions = self._decide_all(offer, origin, now)
|
|
443
|
+
choice = choose(decisions)
|
|
444
|
+
if choice.action == "pay":
|
|
445
|
+
assert choice.index is not None
|
|
446
|
+
receipt = self._reserve(offer, choice.index, decisions[choice.index], origin, now, False)
|
|
447
|
+
return receipt, decisions, choice.index
|
|
448
|
+
if choice.action == "deny":
|
|
449
|
+
raise PaymentDenied(self._denied(decisions))
|
|
450
|
+
if self.approve is None:
|
|
451
|
+
raise PaymentDenied(self._denied(decisions), approval="no-callback")
|
|
452
|
+
return None, decisions, choice.index
|
|
453
|
+
|
|
454
|
+
def _after_approval(
|
|
455
|
+
self, offer: Offer, origin: str, decisions: list[Decision], index: int, approved: object
|
|
456
|
+
) -> Receipt:
|
|
457
|
+
if approved is not True:
|
|
458
|
+
raise PaymentDenied(self._denied(decisions), approval="rejected")
|
|
459
|
+
with self.ledger.lock(): # the state may have moved while the human decided
|
|
460
|
+
now = self._now()
|
|
461
|
+
d = self._decide_one(offer, index, now)
|
|
462
|
+
if d.decision == "deny":
|
|
463
|
+
decisions = list(decisions)
|
|
464
|
+
decisions[index] = d
|
|
465
|
+
raise PaymentDenied(self._denied(decisions))
|
|
466
|
+
return self._reserve(offer, index, d, origin, now, True)
|
|
467
|
+
|
|
468
|
+
# -- sync and async entry points ----------------------------------------------
|
|
469
|
+
|
|
470
|
+
def pay_sync(self, origin: str, get_header: GetHeader, body: bytes | None) -> Payment | None:
|
|
471
|
+
"""Decide, reserve and sign (sync). ``None`` when the 402 is not x402."""
|
|
472
|
+
offer = read_offer(get_header, body)
|
|
473
|
+
if offer is None:
|
|
474
|
+
return None
|
|
475
|
+
receipt, decisions, index = self._start(offer, origin)
|
|
476
|
+
assert index is not None
|
|
477
|
+
if receipt is None:
|
|
478
|
+
assert self.approve is not None
|
|
479
|
+
result = self.approve(self._approval_request(decisions[index], origin))
|
|
480
|
+
if inspect.isawaitable(result):
|
|
481
|
+
close = getattr(result, "close", None)
|
|
482
|
+
if callable(close):
|
|
483
|
+
close()
|
|
484
|
+
raise TypeError("an async approval callback needs the async httpx client")
|
|
485
|
+
receipt = self._after_approval(offer, origin, decisions, index, result)
|
|
486
|
+
typed = _typed(offer, index)
|
|
487
|
+
token = _PERMIT.set(_Permit(_requirement_key(typed.accepts[0])))
|
|
488
|
+
try:
|
|
489
|
+
payload = self.sync_client.create_payment_payload(typed)
|
|
490
|
+
except Exception as e:
|
|
491
|
+
Payment(self, receipt, {}).fail()
|
|
492
|
+
raise PaymentError(f"could not create the payment: {e}") from e
|
|
493
|
+
finally:
|
|
494
|
+
_PERMIT.reset(token)
|
|
495
|
+
return Payment(self, receipt, self.http.encode_payment_signature_header(payload))
|
|
496
|
+
|
|
497
|
+
async def pay_async(self, origin: str, get_header: GetHeader, body: bytes | None) -> Payment | None:
|
|
498
|
+
"""Decide, reserve and sign (async). ``None`` when the 402 is not x402."""
|
|
499
|
+
offer = read_offer(get_header, body)
|
|
500
|
+
if offer is None:
|
|
501
|
+
return None
|
|
502
|
+
receipt, decisions, index = self._start(offer, origin)
|
|
503
|
+
assert index is not None
|
|
504
|
+
if receipt is None:
|
|
505
|
+
assert self.approve is not None
|
|
506
|
+
result = self.approve(self._approval_request(decisions[index], origin))
|
|
507
|
+
if inspect.isawaitable(result):
|
|
508
|
+
result = await result
|
|
509
|
+
receipt = self._after_approval(offer, origin, decisions, index, result)
|
|
510
|
+
typed = _typed(offer, index)
|
|
511
|
+
token = _PERMIT.set(_Permit(_requirement_key(typed.accepts[0])))
|
|
512
|
+
try:
|
|
513
|
+
payload = await self.async_client.create_payment_payload(typed)
|
|
514
|
+
except Exception as e:
|
|
515
|
+
Payment(self, receipt, {}).fail()
|
|
516
|
+
raise PaymentError(f"could not create the payment: {e}") from e
|
|
517
|
+
finally:
|
|
518
|
+
_PERMIT.reset(token)
|
|
519
|
+
return Payment(self, receipt, self.http.encode_payment_signature_header(payload))
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def has_payment_header(get_header: GetHeader) -> bool:
|
|
523
|
+
"""Whether a request already carries a payment (then plug402 does not pay)."""
|
|
524
|
+
from x402.http.constants import PAYMENT_SIGNATURE_HEADER, X_PAYMENT_HEADER
|
|
525
|
+
|
|
526
|
+
return bool(get_header(PAYMENT_SIGNATURE_HEADER) or get_header(X_PAYMENT_HEADER))
|
plug402/errors.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Errors raised by plug402 (no third-party dependencies)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
__all__ = ["DeniedEntry", "PaymentDenied", "PaymentError", "PaymentFailed"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PaymentError(Exception):
|
|
12
|
+
"""Base class for every error plug402 raises about a payment."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class DeniedEntry:
|
|
17
|
+
"""Why one entry of ``accepts`` was not paid.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
index: Position of the entry in the server's ``accepts`` list.
|
|
21
|
+
reason: A reason code from spec section 3 (for example ``"over-daily"``):
|
|
22
|
+
``"needs-approval"`` for an entry that needed an approval it did not
|
|
23
|
+
get, ``"unsupported"`` for an entry this client cannot pay (no
|
|
24
|
+
signer for its chain family, or a scheme, transfer method, payment
|
|
25
|
+
flow or Solana transaction version it does not implement), and
|
|
26
|
+
``"insecure-origin"`` for every entry of a non-loopback ``http:``
|
|
27
|
+
request when the policy does not set ``allowHttp``.
|
|
28
|
+
detail: Optional free text (set for some ``"unsupported"`` entries).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
index: int
|
|
32
|
+
reason: str
|
|
33
|
+
detail: str | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PaymentDenied(PaymentError):
|
|
37
|
+
"""Nothing was paid: no entry of ``accepts`` was allowed (spec section 3.2, step 4).
|
|
38
|
+
|
|
39
|
+
Raised before anything is signed. ``entries`` holds, for every entry the
|
|
40
|
+
server offered, its index and reason code.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
entries: One :class:`DeniedEntry` per entry of ``accepts``, in the server's order.
|
|
44
|
+
approval: ``"rejected"`` when the approval callback said no,
|
|
45
|
+
``"no-callback"`` when an entry needed approval and no callback was
|
|
46
|
+
given, otherwise ``None``.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
entries: list[DeniedEntry],
|
|
52
|
+
approval: Literal["rejected", "no-callback"] | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
self.entries = list(entries)
|
|
55
|
+
self.approval = approval
|
|
56
|
+
if self.entries:
|
|
57
|
+
detail = ", ".join(
|
|
58
|
+
f"#{e.index}: {e.reason}" + (f" ({e.detail})" if e.detail else "") for e in self.entries
|
|
59
|
+
)
|
|
60
|
+
else:
|
|
61
|
+
detail = "the server offered no payment options"
|
|
62
|
+
suffix = f" (approval {approval})" if approval else ""
|
|
63
|
+
super().__init__(f"payment denied by the spend policy: {detail}{suffix}")
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def reasons(self) -> list[str]:
|
|
67
|
+
"""The reason codes, in the server's order."""
|
|
68
|
+
return [e.reason for e in self.entries]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class PaymentFailed(PaymentError):
|
|
72
|
+
"""A payment was signed and sent, but the server did not accept it.
|
|
73
|
+
|
|
74
|
+
Raised when the paid retry comes back ``402`` again. The request is never
|
|
75
|
+
paid a second time automatically (spec section 2). The receipt is marked
|
|
76
|
+
``failed``.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
status_code: HTTP status of the paid retry.
|
|
80
|
+
receipt_id: Id of the receipt written for this payment.
|
|
81
|
+
response: The HTTP response object of the paid retry (httpx or requests).
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(self, message: str, *, status_code: int, receipt_id: str, response: object = None):
|
|
85
|
+
super().__init__(message)
|
|
86
|
+
self.status_code = status_code
|
|
87
|
+
self.receipt_id = receipt_id
|
|
88
|
+
self.response = response
|