subetha 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.
subetha/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """subetha — pay for x402 (HTTP 402) APIs privately over SubEtha's zERC20 rail.
3
+
4
+ Wire protocol: docs/PROTOCOL.md in the SubEtha repository (this package is the
5
+ reference implementation written against that spec alone). Payer safety mirrors the
6
+ TypeScript agent tools (docs/AGENT-TOOLS.md)."""
7
+
8
+ from .client import SubethaClient
9
+ from .policy import SpendingPolicy
10
+ from .types import (
11
+ ApprovalRequest,
12
+ Offer,
13
+ Payment,
14
+ PayResult,
15
+ Quote,
16
+ Requirements,
17
+ SCHEME,
18
+ SubethaError,
19
+ )
20
+
21
+ __all__ = [
22
+ "SubethaClient",
23
+ "SpendingPolicy",
24
+ "ApprovalRequest",
25
+ "Offer",
26
+ "Payment",
27
+ "PayResult",
28
+ "Quote",
29
+ "Requirements",
30
+ "SCHEME",
31
+ "SubethaError",
32
+ ]
subetha/_redact.py ADDED
@@ -0,0 +1,22 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Secret redaction, mirroring the TS agent-tools policy: exact known secrets by value,
3
+ signature-grade hex (130+ chars) masked; a 64-hex transaction hash is legitimate output
4
+ and passes through."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+
10
+ _LONG_HEX = re.compile(r"0x[0-9a-fA-F]{130,}")
11
+
12
+
13
+ def make_redactor(secrets: list[str]):
14
+ known = [s for s in secrets if s]
15
+
16
+ def redact(text: str) -> str:
17
+ out = _LONG_HEX.sub("0x[redacted]", text)
18
+ for secret in known:
19
+ out = out.replace(secret, "[redacted-secret]")
20
+ return out
21
+
22
+ return redact
subetha/client.py ADDED
@@ -0,0 +1,337 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """SubethaClient — pay for x402 resources over SubEtha's private zERC20 rail.
3
+
4
+ Wire behavior comes from docs/PROTOCOL.md (the normative spec this module was written
5
+ against); payer safety mirrors the TS agent-tools engine (docs/AGENT-TOOLS.md): spending
6
+ policy at two enforcement points, human approval above a threshold, accounting at the
7
+ irreversibility point, one payment at a time, secrets redacted from every error."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import threading
14
+ import time
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from concurrent.futures import TimeoutError as FutureTimeout
17
+ from typing import Callable, Optional
18
+
19
+ import httpx
20
+ from eth_account import Account
21
+
22
+ from ._redact import make_redactor
23
+ from .policy import SpendingPolicy
24
+ from .rpc import Rpc
25
+ from .signing import sign_burn_auth, sign_permit
26
+ from .types import (
27
+ SCHEME,
28
+ ApprovalRequest,
29
+ Offer,
30
+ Payment,
31
+ PayResult,
32
+ Quote,
33
+ Requirements,
34
+ SubethaError,
35
+ )
36
+ from .wire import (
37
+ decode_payment_required,
38
+ decode_payment_response,
39
+ encode_payment_signature,
40
+ parse_requirements,
41
+ )
42
+
43
+ _RESERVED_HEADER = re.compile(r"^(payment-|x-payment)", re.IGNORECASE)
44
+ _MAX_RESOURCE_BYTES = 64 * 1024
45
+ _EXPIRY_MARGIN_S = 5
46
+
47
+
48
+ class SubethaClient:
49
+ def __init__(
50
+ self,
51
+ *,
52
+ private_key: Optional[str] = None,
53
+ rpc_url: str = "http://127.0.0.1:8545",
54
+ mode: str = "permit",
55
+ policy: Optional[SpendingPolicy] = None,
56
+ approve_above: Optional[int] = None,
57
+ approve_payment: Optional[Callable[[ApprovalRequest], bool]] = None,
58
+ approval_timeout_s: float = 120.0,
59
+ timeout_s: float = 30.0,
60
+ ):
61
+ if mode not in ("permit", "self-transfer"):
62
+ raise SubethaError(f'mode must be "permit" or "self-transfer", got "{mode}"')
63
+ self.mode = mode
64
+ self.policy = policy or SpendingPolicy()
65
+ self.approve_above = approve_above
66
+ self.approve_payment = approve_payment
67
+ self.approval_timeout_s = approval_timeout_s
68
+ self._account = Account.from_key(private_key) if private_key else None
69
+ self._redact = make_redactor([private_key] if private_key else [])
70
+ self._rpc = Rpc(rpc_url, timeout_s)
71
+ self._http = httpx.Client(follow_redirects=False, timeout=timeout_s)
72
+ self._lock = threading.Lock() # one payment at a time
73
+
74
+ @classmethod
75
+ def from_env(cls, env: Optional[dict] = None) -> "SubethaClient":
76
+ """Build from the SUBETHA_* environment (same variable names as the TS tools)."""
77
+ e = env if env is not None else dict(os.environ)
78
+ hosts_raw = e.get("SUBETHA_ALLOWED_HOSTS")
79
+ hosts: list[str] | str
80
+ if hosts_raw == "*":
81
+ hosts = "*"
82
+ elif hosts_raw:
83
+ hosts = [h.strip().lower() for h in hosts_raw.split(",") if h.strip()]
84
+ else:
85
+ hosts = ["localhost", "127.0.0.1"]
86
+ dec = lambda name: int(e[name]) if e.get(name) else None # noqa: E731
87
+ return cls(
88
+ private_key=e.get("SUBETHA_PAYER_PK"),
89
+ rpc_url=e.get("SUBETHA_RPC_URL", "http://127.0.0.1:8545"),
90
+ mode=e.get("SUBETHA_MODE", "permit"),
91
+ policy=SpendingPolicy(
92
+ allowed_hosts=hosts,
93
+ allowed_network=e.get("SUBETHA_ALLOWED_NETWORK", "eip155:31337"),
94
+ allowed_token=e.get("SUBETHA_ALLOWED_TOKEN"),
95
+ max_per_payment=dec("SUBETHA_MAX_PER_PAYMENT"),
96
+ max_total=dec("SUBETHA_MAX_TOTAL"),
97
+ ),
98
+ approve_above=dec("SUBETHA_APPROVE_ABOVE"),
99
+ approval_timeout_s=int(e.get("SUBETHA_APPROVAL_TIMEOUT_MS", "120000")) / 1000,
100
+ timeout_s=int(e.get("SUBETHA_TIMEOUT_MS", "30000")) / 1000,
101
+ )
102
+
103
+ # ------------------------------------------------------------------ helpers
104
+
105
+ def _fail(self, message: str) -> SubethaError:
106
+ return SubethaError(self._redact(message))
107
+
108
+ def _request(self, url: str, method: str, body: Optional[str], headers: dict) -> httpx.Response:
109
+ hdrs = dict(headers)
110
+ if body is not None and not any(k.lower() == "content-type" for k in hdrs):
111
+ hdrs["content-type"] = "application/json"
112
+ try:
113
+ res = self._http.request(method, url, content=body, headers=hdrs)
114
+ except httpx.HTTPError as e:
115
+ raise self._fail(f"request failed: {e}") from None
116
+ if 300 <= res.status_code < 400:
117
+ raise self._fail(
118
+ f"redirect ({res.status_code}) refused: redirects are blocked so a payment cannot be steered off the allowlist"
119
+ )
120
+ return res
121
+
122
+ @staticmethod
123
+ def _bounded(res: httpx.Response) -> tuple[str, bool]:
124
+ raw = res.content
125
+ if len(raw) <= _MAX_RESOURCE_BYTES:
126
+ return raw.decode("utf-8", errors="replace"), False
127
+ return raw[:_MAX_RESOURCE_BYTES].decode("utf-8", errors="ignore"), True
128
+
129
+ def _check_headers(self, headers: Optional[dict]) -> dict:
130
+ for k in headers or {}:
131
+ if _RESERVED_HEADER.match(k):
132
+ raise self._fail(f'header "{k}" is reserved for the x402 protocol')
133
+ return dict(headers or {})
134
+
135
+ def _select_offer(self, url: str, res: httpx.Response) -> Requirements:
136
+ header = res.headers.get("PAYMENT-REQUIRED")
137
+ if not header:
138
+ raise self._fail("402 without a PAYMENT-REQUIRED header")
139
+ doc = decode_payment_required(header)
140
+ candidates = [a for a in doc["accepts"] if isinstance(a, dict) and a.get("scheme") == SCHEME]
141
+ if not candidates:
142
+ raise self._fail("no subetha-zerc20 offer in the 402")
143
+ parsed = [parse_requirements(c) for c in candidates]
144
+ allowed, reasons = self.policy.filter_offers(parsed)
145
+ if not allowed:
146
+ reason = f"spending policy rejected all offers: {'; '.join(reasons) or 'no acceptable offers'}"
147
+ self.policy.record_attempt(url, "rejected", reason)
148
+ raise self._fail(reason)
149
+ return allowed[0]
150
+
151
+ # ------------------------------------------------------------------ approval
152
+
153
+ def _approval_gate(self, url: str, req: Requirements) -> None:
154
+ """Equivalent of the TS applyApprovalGate (PR #34): threshold → callback with a
155
+ bounded wait → offer-bound identity re-check. Refusals raise; approval returns."""
156
+ if self.approve_above is None or req.amount <= self.approve_above:
157
+ return
158
+ snapshot = ApprovalRequest(
159
+ url=url,
160
+ quoted=str(req.amount),
161
+ token=req.asset,
162
+ network=req.network,
163
+ pay_to=req.pay_to,
164
+ challenge_nonce=req.challenge_nonce,
165
+ fee=(req.fee or {}).get("amount") if req.fee else None,
166
+ )
167
+ self.policy.record_attempt(url, "approval-requested", amount=snapshot.quoted)
168
+
169
+ def refuse(reason: str) -> None:
170
+ self.policy.record_attempt(url, "rejected", reason, snapshot.quoted)
171
+ raise self._fail(reason)
172
+
173
+ if self.approve_payment is None:
174
+ refuse(
175
+ f"approval required (quoted {snapshot.quoted} > approve_above={self.approve_above}) but no approval "
176
+ "channel is available — unset the threshold or pass approve_payment"
177
+ )
178
+ # No context manager: `with` would shutdown(wait=True) and defeat the timeout.
179
+ executor = ThreadPoolExecutor(max_workers=1)
180
+ try:
181
+ future = executor.submit(self.approve_payment, snapshot)
182
+ try:
183
+ approved = bool(future.result(timeout=self.approval_timeout_s))
184
+ except FutureTimeout:
185
+ refuse(f"approval timed out after {self.approval_timeout_s}s — payment not made")
186
+ except Exception:
187
+ refuse("approval cancelled (approver raised) — payment not made")
188
+ finally:
189
+ executor.shutdown(wait=False, cancel_futures=True) # orphan worker is harmless
190
+ if not approved:
191
+ refuse("approval declined by human — payment not made")
192
+ # TOCTOU defense: what was approved must be what is about to be paid.
193
+ same = (
194
+ snapshot.quoted == str(req.amount)
195
+ and snapshot.token == req.asset
196
+ and snapshot.network == req.network
197
+ and snapshot.pay_to == req.pay_to
198
+ and snapshot.challenge_nonce == req.challenge_nonce
199
+ )
200
+ if not same:
201
+ refuse("approved offer no longer matches the offer being paid — refusing")
202
+ self.policy.record_attempt(url, "approval-approved", amount=snapshot.quoted)
203
+
204
+ # ------------------------------------------------------------------ payloads
205
+
206
+ def _check_expiry(self, req: Requirements) -> None:
207
+ now = time.time() + _EXPIRY_MARGIN_S
208
+ if req.expires_at <= now:
209
+ raise self._fail(f"offer expired (expiresAt={req.expires_at}) — obtain a fresh 402")
210
+ if self.mode == "permit" and req.deadline is not None and req.deadline <= now:
211
+ raise self._fail(f"permit deadline passed (deadline={req.deadline}) — obtain a fresh 402")
212
+
213
+ def _build_payload(self, req: Requirements) -> tuple[dict, str]:
214
+ """Returns (payload, kind). Accounts the spend at the irreversibility point."""
215
+ if self._account is None:
216
+ raise self._fail("private_key is required to pay (quote works without it)")
217
+ if self.mode == "permit":
218
+ if req.helper is None or req.deadline is None:
219
+ raise self._fail("offer has no helper/deadline — the gasless permit path is not offered (mode='permit' never degrades)")
220
+ token_name = self._rpc.token_name(req.asset)
221
+ nonce = self._rpc.permit_nonce(req.asset, self._account.address)
222
+ permit = sign_permit(
223
+ self._account, token=req.asset, token_name=token_name, chain_id=req.chain_id,
224
+ helper=req.helper, value=req.amount, nonce=nonce, deadline=req.deadline,
225
+ )
226
+ burn_auth = sign_burn_auth(
227
+ self._account, token=req.asset, chain_id=req.chain_id, helper=req.helper,
228
+ burn_address=req.pay_to, value=req.amount, challenge_nonce=req.challenge_nonce, deadline=req.deadline,
229
+ )
230
+ payload = {"challengeNonce": req.challenge_nonce, "payer": self._account.address, "permit": permit, "burnAuthSig": burn_auth}
231
+ self.policy.record_spend(req) # reservation (released on definitive settle rejection)
232
+ return payload, "permit"
233
+ # self-transfer: the burn is money gone the moment it lands
234
+ onchain = self._rpc.chain_id()
235
+ if onchain != req.chain_id:
236
+ raise self._fail(f"RPC chain id {onchain} does not match the offer network {req.network}")
237
+ tx_hash = self._rpc.send_erc20_transfer(
238
+ self._account, token=req.asset, to=req.pay_to, amount=req.amount, chain_id=req.chain_id
239
+ )
240
+ self._rpc.wait_receipt(tx_hash) # raises on revert/timeout — payload never sent
241
+ self.policy.record_spend(req)
242
+ return {"challengeNonce": req.challenge_nonce, "burnTxHash": tx_hash}, "self-transfer"
243
+
244
+ # ------------------------------------------------------------------ public API
245
+
246
+ def quote(self, url: str, method: str = "GET", body: Optional[str] = None) -> Quote:
247
+ reason = self.policy.check_url(url)
248
+ if reason:
249
+ raise self._fail(reason)
250
+ res = self._request(url, method, body, {})
251
+ if res.status_code != 402:
252
+ return Quote(status=res.status_code)
253
+ try:
254
+ req = self._select_offer(url, res)
255
+ except SubethaError as e:
256
+ return Quote(status=402, error=str(e))
257
+ approval_required = self.approve_above is not None and req.amount > self.approve_above
258
+ fee = req.fee or {}
259
+ return Quote(
260
+ status=402,
261
+ offer=Offer(
262
+ quoted=str(req.amount),
263
+ token=req.asset,
264
+ network=req.network,
265
+ gasless=req.helper is not None,
266
+ fee=fee.get("amount"),
267
+ bps=fee.get("bps"),
268
+ list_price=str(req.amount - int(fee["amount"])) if fee.get("amount") else None,
269
+ expires_at=req.expires_at,
270
+ approval_required=True if approval_required else None,
271
+ ),
272
+ )
273
+
274
+ def pay(self, url: str, method: str = "GET", body: Optional[str] = None, headers: Optional[dict] = None) -> PayResult:
275
+ with self._lock:
276
+ extra_headers = self._check_headers(headers)
277
+ reason = self.policy.check_url(url)
278
+ if reason:
279
+ self.policy.record_attempt(url, "rejected", reason)
280
+ raise self._fail(reason)
281
+
282
+ first = self._request(url, method, body, extra_headers)
283
+ if first.status_code != 402:
284
+ text, truncated = self._bounded(first)
285
+ return PayResult(status=first.status_code, resource=text, truncated=truncated)
286
+
287
+ req = self._select_offer(url, first)
288
+ self._approval_gate(url, req)
289
+ self._check_expiry(req)
290
+ try:
291
+ payload, kind = self._build_payload(req)
292
+ except SubethaError as e:
293
+ # RPC/node errors can echo request params (even the raw signed tx) —
294
+ # everything that reaches the caller or the report goes through _fail.
295
+ raise self._fail(str(e)) from None
296
+
297
+ paying_headers = dict(extra_headers)
298
+ paying_headers["PAYMENT-SIGNATURE"] = encode_payment_signature(req.raw, payload)
299
+ second = self._request(url, method, body, paying_headers)
300
+
301
+ if second.status_code == 402 and kind == "permit":
302
+ # definitive settle rejection ⇒ no funds moved ⇒ refund the reservation
303
+ self.policy.release(req)
304
+ detail = ""
305
+ reissued = decode_payment_required(second.headers.get("PAYMENT-REQUIRED", "")) if second.headers.get("PAYMENT-REQUIRED") else None
306
+ if isinstance(reissued, dict) and isinstance(reissued.get("error"), str):
307
+ detail = f": {reissued['error']}"
308
+ # redact BEFORE recording — the report must never carry provider-supplied
309
+ # signature-grade material either
310
+ msg = self._redact(f"settle rejected by the facilitator (no funds moved){detail}")
311
+ self.policy.record_attempt(url, "failed", msg)
312
+ raise SubethaError(msg)
313
+ if second.status_code >= 400:
314
+ # money may have moved (a self-transfer burn definitely did) — keep the accounting
315
+ msg = f"paid request failed with HTTP {second.status_code} (spend kept in the budget on the safe side)"
316
+ self.policy.record_attempt(url, "failed", msg)
317
+ raise self._fail(msg)
318
+
319
+ text, truncated = self._bounded(second)
320
+ settle = decode_payment_response(second.headers.get("PAYMENT-RESPONSE"))
321
+ self.policy.record_payment(url, req)
322
+ return PayResult(
323
+ status=second.status_code,
324
+ resource=text,
325
+ truncated=truncated,
326
+ payment=Payment(
327
+ amount=str(req.amount),
328
+ token=req.asset,
329
+ network=req.network,
330
+ fee=(req.fee or {}).get("amount") if req.fee else None,
331
+ burn_tx_hash=payload.get("burnTxHash"),
332
+ settle=settle,
333
+ ),
334
+ )
335
+
336
+ def report(self) -> dict:
337
+ return self.policy.report()
subetha/policy.py ADDED
@@ -0,0 +1,127 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The spending policy — an equivalent port of the TS agent-tools SpendingPolicy
3
+ (docs/AGENT-TOOLS.md): a hostname allowlist before any request leaves, offer filtering
4
+ (network/token pins, per-payment and total caps) at payment selection, accounting at the
5
+ irreversibility point, and an audit trail of attempts (including approval events)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime, timezone
10
+ from typing import Optional
11
+ from urllib.parse import urlsplit
12
+
13
+ from .types import Requirements
14
+
15
+ _RING = 50
16
+
17
+
18
+ def _now() -> str:
19
+ return datetime.now(timezone.utc).isoformat()
20
+
21
+
22
+ class SpendingPolicy:
23
+ def __init__(
24
+ self,
25
+ *,
26
+ allowed_hosts: list[str] | str = ("localhost", "127.0.0.1"),
27
+ allowed_network: str = "eip155:31337",
28
+ allowed_token: Optional[str] = None,
29
+ max_per_payment: Optional[int] = None,
30
+ max_total: Optional[int] = None,
31
+ ):
32
+ self.allowed_hosts = allowed_hosts if allowed_hosts == "*" else [h.lower() for h in allowed_hosts]
33
+ self.allowed_network = allowed_network
34
+ self.allowed_token = allowed_token
35
+ self.max_per_payment = max_per_payment
36
+ self.max_total = max_total
37
+ self._spent: dict[str, int] = {} # "network|token" -> base units
38
+ self._payments: list[dict] = []
39
+ self._attempts: list[dict] = []
40
+
41
+ # (b) pre-request gate
42
+ def check_url(self, raw_url: str) -> Optional[str]:
43
+ """Returns a refusal reason, or None when the URL is allowed."""
44
+ parts = urlsplit(raw_url)
45
+ if parts.scheme not in ("http", "https"):
46
+ return f"only http/https URLs are allowed (got {parts.scheme or 'none'})"
47
+ if self.allowed_hosts == "*":
48
+ return None
49
+ host = (parts.hostname or "").lower()
50
+ if host not in self.allowed_hosts:
51
+ return (
52
+ f'host "{host}" is not in SUBETHA_ALLOWED_HOSTS ({", ".join(self.allowed_hosts) or "empty"}). '
53
+ 'Add it to the allowlist (or set SUBETHA_ALLOWED_HOSTS=* to allow all) to permit payments to this host.'
54
+ )
55
+ return None
56
+
57
+ @staticmethod
58
+ def _pair_key(network: str, token: str) -> str:
59
+ return f"{network}|{token.lower()}"
60
+
61
+ # (a) selection filter — same rules as the TS paymentPolicy
62
+ def filter_offers(self, offers: list[Requirements]) -> tuple[list[Requirements], list[str]]:
63
+ reasons: list[str] = []
64
+ allowed: list[Requirements] = []
65
+ for req in offers:
66
+ if req.network != self.allowed_network:
67
+ reasons.append(f"offer on {req.network} rejected (SUBETHA_ALLOWED_NETWORK={self.allowed_network})")
68
+ continue
69
+ if self.allowed_token and req.asset.lower() != self.allowed_token.lower():
70
+ reasons.append(f"offer asset {req.asset} rejected (SUBETHA_ALLOWED_TOKEN={self.allowed_token})")
71
+ continue
72
+ if self.max_per_payment is not None and req.amount > self.max_per_payment:
73
+ reasons.append(
74
+ f"offer of {req.amount} exceeds SUBETHA_MAX_PER_PAYMENT={self.max_per_payment}. "
75
+ "Raise the limit to allow this payment."
76
+ )
77
+ continue
78
+ if self.max_total is not None:
79
+ total = self._spent.get(self._pair_key(req.network, req.asset), 0) + req.amount
80
+ if total > self.max_total:
81
+ reasons.append(
82
+ f"paying {req.amount} would bring the session total to {total}, over "
83
+ f"SUBETHA_MAX_TOTAL={self.max_total}. Raise the limit or start a new session."
84
+ )
85
+ continue
86
+ allowed.append(req)
87
+ return allowed, reasons
88
+
89
+ # accounting at the irreversibility point
90
+ def record_spend(self, req: Requirements) -> None:
91
+ key = self._pair_key(req.network, req.asset)
92
+ self._spent[key] = self._spent.get(key, 0) + req.amount
93
+
94
+ def release(self, req: Requirements) -> None:
95
+ """Refund a PERMIT reservation whose settle was definitively rejected."""
96
+ key = self._pair_key(req.network, req.asset)
97
+ current = self._spent.get(key, 0)
98
+ self._spent[key] = current - req.amount if current > req.amount else 0
99
+
100
+ def record_payment(self, url: str, req: Requirements) -> None:
101
+ self._payments.append(
102
+ {"url": url, "amount": str(req.amount), "token": req.asset, "network": req.network, "at": _now()}
103
+ )
104
+ self.record_attempt(url, "paid", amount=str(req.amount))
105
+
106
+ def record_attempt(self, url: str, outcome: str, reason: Optional[str] = None, amount: Optional[str] = None) -> None:
107
+ self._attempts.append({"url": url, "outcome": outcome, "reason": reason, "amount": amount, "at": _now()})
108
+ if len(self._attempts) > _RING:
109
+ self._attempts.pop(0)
110
+
111
+ def report(self) -> dict:
112
+ totals = []
113
+ for key, spent in self._spent.items():
114
+ network, token = key.split("|", 1)
115
+ totals.append({"network": network, "token": token, "spent": str(spent)})
116
+ return {
117
+ "totals": totals,
118
+ "payments": list(self._payments),
119
+ "attempts": list(self._attempts),
120
+ "limits": {
121
+ "per_payment": str(self.max_per_payment) if self.max_per_payment is not None else None,
122
+ "total": str(self.max_total) if self.max_total is not None else None,
123
+ "allowed_hosts": self.allowed_hosts,
124
+ "allowed_network": self.allowed_network,
125
+ "allowed_token": self.allowed_token,
126
+ },
127
+ }
subetha/rpc.py ADDED
@@ -0,0 +1,97 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Minimal JSON-RPC over httpx — everything the client needs from the chain, nothing
3
+ more: eth_call reads for the permit path (token name, permit nonce), and the fixed
4
+ self-transfer transaction recipe (requirements FR1): pending nonce, a9059cbb calldata,
5
+ eth_estimateGas, legacy type-0 gas price, raw send, receipt polling with status==0x1
6
+ required."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Any, Optional
12
+
13
+ import httpx
14
+
15
+ from .types import SubethaError
16
+
17
+ _TRANSFER_SELECTOR = "a9059cbb"
18
+ _NAME_SELECTOR = "0x06fdde03" # name()
19
+ _NONCES_SELECTOR = "0x7ecebe00" # nonces(address)
20
+
21
+
22
+ def erc20_transfer_data(to: str, amount: int) -> str:
23
+ return "0x" + _TRANSFER_SELECTOR + to.removeprefix("0x").lower().rjust(64, "0") + format(amount, "x").rjust(64, "0")
24
+
25
+
26
+ class Rpc:
27
+ def __init__(self, url: str, timeout_s: float = 30.0):
28
+ self.url = url
29
+ self._http = httpx.Client(timeout=timeout_s)
30
+ self._id = 0
31
+
32
+ def _call(self, method: str, params: list[Any]) -> Any:
33
+ self._id += 1
34
+ try:
35
+ res = self._http.post(self.url, json={"jsonrpc": "2.0", "id": self._id, "method": method, "params": params})
36
+ res.raise_for_status()
37
+ body = res.json()
38
+ except httpx.HTTPError as e:
39
+ raise SubethaError(f"RPC {method} failed: {e}") from None
40
+ if "error" in body:
41
+ raise SubethaError(f"RPC {method} error: {body['error'].get('message', body['error'])}")
42
+ return body.get("result")
43
+
44
+ def chain_id(self) -> int:
45
+ return int(self._call("eth_chainId", []), 16)
46
+
47
+ def eth_call(self, to: str, data: str) -> str:
48
+ return self._call("eth_call", [{"to": to, "data": data}, "latest"])
49
+
50
+ def token_name(self, token: str) -> str:
51
+ raw = bytes.fromhex(self.eth_call(token, _NAME_SELECTOR).removeprefix("0x"))
52
+ # ABI string: [offset:32][length:32][utf8...]
53
+ if len(raw) < 64:
54
+ raise SubethaError("token name() returned malformed data")
55
+ length = int.from_bytes(raw[32:64], "big")
56
+ return raw[64 : 64 + length].decode("utf-8")
57
+
58
+ def permit_nonce(self, token: str, owner: str) -> int:
59
+ data = _NONCES_SELECTOR + owner.removeprefix("0x").lower().rjust(64, "0")
60
+ return int(self.eth_call(token, data), 16)
61
+
62
+ def balance_of(self, token: str, owner: str) -> int:
63
+ data = "0x70a08231" + owner.removeprefix("0x").lower().rjust(64, "0")
64
+ return int(self.eth_call(token, data), 16)
65
+
66
+ def eth_balance(self, addr: str) -> int:
67
+ return int(self._call("eth_getBalance", [addr, "latest"]), 16)
68
+
69
+ # --- the fixed self-transfer recipe ------------------------------------------
70
+
71
+ def send_erc20_transfer(self, account: Any, *, token: str, to: str, amount: int, chain_id: int) -> str:
72
+ nonce = int(self._call("eth_getTransactionCount", [account.address, "pending"]), 16)
73
+ data = erc20_transfer_data(to, amount)
74
+ gas = int(self._call("eth_estimateGas", [{"from": account.address, "to": token, "data": data}]), 16)
75
+ gas_price = int(self._call("eth_gasPrice", []), 16)
76
+ tx = {
77
+ "nonce": nonce,
78
+ "gasPrice": gas_price, # legacy type-0 (requirements FR1)
79
+ "gas": gas,
80
+ "to": token,
81
+ "value": 0,
82
+ "data": data,
83
+ "chainId": chain_id,
84
+ }
85
+ signed = account.sign_transaction(tx)
86
+ return self._call("eth_sendRawTransaction", ["0x" + signed.raw_transaction.hex()])
87
+
88
+ def wait_receipt(self, tx_hash: str, timeout_s: float = 60.0, poll_s: float = 0.5) -> dict:
89
+ deadline = time.monotonic() + timeout_s
90
+ while time.monotonic() < deadline:
91
+ receipt: Optional[dict] = self._call("eth_getTransactionReceipt", [tx_hash])
92
+ if receipt is not None:
93
+ if receipt.get("status") != "0x1":
94
+ raise SubethaError(f"burn transaction {tx_hash} reverted — not paying")
95
+ return receipt
96
+ time.sleep(poll_s)
97
+ raise SubethaError(f"burn transaction {tx_hash} not mined within {timeout_s}s — not paying")
subetha/signing.py ADDED
@@ -0,0 +1,116 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """EIP-712 signatures for the subetha-zerc20 permit path (docs/PROTOCOL.md §3.1):
3
+ the EIP-2612 Permit (spender = the PermitBurner helper) and SubEtha's burn-bind
4
+ BurnAuthorization. Both sign and recover directions — recovery exists so the test suite
5
+ proves signature compatibility without a chain."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from eth_account import Account
12
+ from eth_account.messages import encode_typed_data
13
+
14
+ _PERMIT_TYPES = {
15
+ "Permit": [
16
+ {"name": "owner", "type": "address"},
17
+ {"name": "spender", "type": "address"},
18
+ {"name": "value", "type": "uint256"},
19
+ {"name": "nonce", "type": "uint256"},
20
+ {"name": "deadline", "type": "uint256"},
21
+ ]
22
+ }
23
+
24
+ _BURN_AUTH_TYPES = {
25
+ "BurnAuthorization": [
26
+ {"name": "token", "type": "address"},
27
+ {"name": "payer", "type": "address"},
28
+ {"name": "burnAddress", "type": "address"},
29
+ {"name": "value", "type": "uint256"},
30
+ {"name": "challengeNonce", "type": "bytes32"},
31
+ {"name": "deadline", "type": "uint256"},
32
+ ]
33
+ }
34
+
35
+
36
+ def _permit_message(
37
+ *, token: str, token_name: str, chain_id: int, helper: str, payer: str, value: int, nonce: int, deadline: int
38
+ ) -> tuple[dict, dict, dict]:
39
+ domain = {"name": token_name, "version": "1", "chainId": chain_id, "verifyingContract": token}
40
+ message = {"owner": payer, "spender": helper, "value": value, "nonce": nonce, "deadline": deadline}
41
+ return domain, _PERMIT_TYPES, message
42
+
43
+
44
+ def _burn_auth_message(
45
+ *, token: str, chain_id: int, helper: str, payer: str, burn_address: str, value: int, challenge_nonce: str, deadline: int
46
+ ) -> tuple[dict, dict, dict]:
47
+ domain = {"name": "SubEthaPermitBurner", "version": "1", "chainId": chain_id, "verifyingContract": helper}
48
+ message = {
49
+ "token": token,
50
+ "payer": payer,
51
+ "burnAddress": burn_address,
52
+ "value": value,
53
+ "challengeNonce": bytes.fromhex(challenge_nonce.removeprefix("0x")),
54
+ "deadline": deadline,
55
+ }
56
+ return domain, _BURN_AUTH_TYPES, message
57
+
58
+
59
+ def sign_permit(
60
+ account: Any, *, token: str, token_name: str, chain_id: int, helper: str, value: int, nonce: int, deadline: int
61
+ ) -> dict:
62
+ """Returns the wire `permit` object: decimal-string numbers, v int, r/s hex."""
63
+ domain, types, message = _permit_message(
64
+ token=token, token_name=token_name, chain_id=chain_id, helper=helper,
65
+ payer=account.address, value=value, nonce=nonce, deadline=deadline,
66
+ )
67
+ signed = account.sign_typed_data(domain_data=domain, message_types=types, message_data=message)
68
+ return {
69
+ "value": str(value),
70
+ "nonce": str(nonce),
71
+ "deadline": str(deadline),
72
+ "v": signed.v,
73
+ "r": "0x" + signed.r.to_bytes(32, "big").hex(),
74
+ "s": "0x" + signed.s.to_bytes(32, "big").hex(),
75
+ }
76
+
77
+
78
+ def sign_burn_auth(
79
+ account: Any, *, token: str, chain_id: int, helper: str, burn_address: str, value: int, challenge_nonce: str, deadline: int
80
+ ) -> str:
81
+ """Returns the wire `burnAuthSig`: the 65-byte r‖s‖v signature as 0x hex."""
82
+ domain, types, message = _burn_auth_message(
83
+ token=token, chain_id=chain_id, helper=helper, payer=account.address,
84
+ burn_address=burn_address, value=value, challenge_nonce=challenge_nonce, deadline=deadline,
85
+ )
86
+ signed = account.sign_typed_data(domain_data=domain, message_types=types, message_data=message)
87
+ return "0x" + signed.signature.hex()
88
+
89
+
90
+ # --- recovery (test-side proof of signature compatibility) ---------------------------
91
+
92
+ def recover_permit(
93
+ permit: dict, *, token: str, token_name: str, chain_id: int, helper: str, payer: str
94
+ ) -> str:
95
+ domain, types, message = _permit_message(
96
+ token=token, token_name=token_name, chain_id=chain_id, helper=helper,
97
+ payer=payer, value=int(permit["value"]), nonce=int(permit["nonce"]), deadline=int(permit["deadline"]),
98
+ )
99
+ sig = bytes.fromhex(permit["r"].removeprefix("0x")) + bytes.fromhex(permit["s"].removeprefix("0x")) + bytes([permit["v"]])
100
+ return Account.recover_message(
101
+ encode_typed_data(domain_data=domain, message_types=types, message_data=message), signature=sig
102
+ )
103
+
104
+
105
+ def recover_burn_auth(
106
+ burn_auth_sig: str, *, token: str, chain_id: int, helper: str, payer: str, burn_address: str, value: int,
107
+ challenge_nonce: str, deadline: int
108
+ ) -> str:
109
+ domain, types, message = _burn_auth_message(
110
+ token=token, chain_id=chain_id, helper=helper, payer=payer,
111
+ burn_address=burn_address, value=value, challenge_nonce=challenge_nonce, deadline=deadline,
112
+ )
113
+ return Account.recover_message(
114
+ encode_typed_data(domain_data=domain, message_types=types, message_data=message),
115
+ signature=bytes.fromhex(burn_auth_sig.removeprefix("0x")),
116
+ )
subetha/types.py ADDED
@@ -0,0 +1,84 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Public result types (field-equivalent to the TS agent-tools payer, snake_case) and
3
+ scheme constants. docs/PROTOCOL.md is the wire authority."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Optional
9
+
10
+ SCHEME = "subetha-zerc20"
11
+ X402_VERSION = 2
12
+
13
+
14
+ class SubethaError(Exception):
15
+ """All client failures normalize to this (message already redacted)."""
16
+
17
+
18
+ @dataclass
19
+ class Offer:
20
+ quoted: str
21
+ token: str
22
+ network: str
23
+ gasless: bool
24
+ list_price: Optional[str] = None
25
+ fee: Optional[str] = None
26
+ bps: Optional[int] = None
27
+ expires_at: Optional[int] = None
28
+ approval_required: Optional[bool] = None
29
+
30
+
31
+ @dataclass
32
+ class Quote:
33
+ status: int
34
+ offer: Optional[Offer] = None
35
+ error: Optional[str] = None
36
+
37
+
38
+ @dataclass
39
+ class Payment:
40
+ amount: str
41
+ token: str
42
+ network: str
43
+ fee: Optional[str] = None
44
+ burn_tx_hash: Optional[str] = None
45
+ settle: Optional[dict] = None
46
+
47
+
48
+ @dataclass
49
+ class PayResult:
50
+ status: int
51
+ resource: str
52
+ truncated: bool
53
+ payment: Optional[Payment] = None
54
+
55
+
56
+ @dataclass
57
+ class ApprovalRequest:
58
+ """What the human is asked to approve — also the identity the approval is bound to."""
59
+
60
+ url: str
61
+ quoted: str
62
+ token: str
63
+ network: str
64
+ pay_to: str
65
+ challenge_nonce: str
66
+ fee: Optional[str] = None
67
+
68
+
69
+ @dataclass
70
+ class Requirements:
71
+ """Validated view of a subetha-zerc20 PaymentRequirements. `raw` keeps the exact dict
72
+ received in the 402 — the PAYMENT-SIGNATURE envelope must echo it verbatim."""
73
+
74
+ raw: dict[str, Any]
75
+ pay_to: str
76
+ asset: str
77
+ amount: int
78
+ chain_id: int
79
+ network: str
80
+ challenge_nonce: str
81
+ expires_at: int
82
+ helper: Optional[str] = None
83
+ deadline: Optional[int] = None
84
+ fee: Optional[dict] = field(default=None)
subetha/wire.py ADDED
@@ -0,0 +1,104 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """x402 v2 wire encoding for the subetha-zerc20 scheme, implemented from
3
+ docs/PROTOCOL.md: PAYMENT-REQUIRED / PAYMENT-SIGNATURE / PAYMENT-RESPONSE headers
4
+ (base64 JSON) and the PaymentRequirements validation rules."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import binascii
10
+ import json
11
+ import re
12
+ from typing import Any, Optional
13
+
14
+ from .types import SCHEME, X402_VERSION, Requirements, SubethaError
15
+
16
+ _ADDR = re.compile(r"^0x[0-9a-fA-F]{40}$")
17
+ _HEX32 = re.compile(r"^0x[0-9a-fA-F]{64}$")
18
+ _DEC = re.compile(r"^\d+$")
19
+ _NETWORK = re.compile(r"^eip155:(\d+)$")
20
+
21
+
22
+ def _b64_json(header: str) -> Any:
23
+ return json.loads(base64.b64decode(header, validate=True).decode("utf-8"))
24
+
25
+
26
+ def decode_payment_required(header: str) -> dict:
27
+ try:
28
+ doc = _b64_json(header)
29
+ except (ValueError, binascii.Error) as e:
30
+ raise SubethaError(f"PAYMENT-REQUIRED header is not decodable: {e}") from None
31
+ if not isinstance(doc, dict) or not isinstance(doc.get("accepts"), list):
32
+ raise SubethaError("PAYMENT-REQUIRED is missing the accepts list")
33
+ return doc
34
+
35
+
36
+ def parse_requirements(req: dict) -> Requirements:
37
+ """Validate + narrow one subetha-zerc20 offer (PROTOCOL.md §2). Keeps the raw dict —
38
+ the PAYMENT-SIGNATURE envelope echoes it verbatim (PROTOCOL.md §3)."""
39
+ if req.get("scheme") != SCHEME:
40
+ raise SubethaError(f"scheme mismatch: expected {SCHEME}, got {req.get('scheme')}")
41
+ pay_to = req.get("payTo")
42
+ if not isinstance(pay_to, str) or not _ADDR.match(pay_to):
43
+ raise SubethaError(f"payTo is not an address: {pay_to}")
44
+ asset = req.get("asset")
45
+ if not isinstance(asset, str) or not _ADDR.match(asset):
46
+ raise SubethaError(f"asset is not an address: {asset}")
47
+ amount = req.get("amount")
48
+ if not isinstance(amount, str) or not _DEC.match(amount):
49
+ raise SubethaError(f"amount is not a base-unit integer: {amount}")
50
+ network = req.get("network", "")
51
+ m = _NETWORK.match(network) if isinstance(network, str) else None
52
+ if not m:
53
+ raise SubethaError(f"not an eip155 CAIP-2 network id: {network}")
54
+ extra = req.get("extra") or {}
55
+ if not isinstance(extra, dict):
56
+ raise SubethaError("extra malformed (expect an object)")
57
+ nonce = extra.get("challengeNonce")
58
+ if not isinstance(nonce, str) or not _HEX32.match(nonce):
59
+ raise SubethaError("extra.challengeNonce missing or malformed (expect 32-byte hex)")
60
+ expires_at = extra.get("expiresAt")
61
+ if not isinstance(expires_at, int):
62
+ raise SubethaError("extra.expiresAt missing (unix seconds)")
63
+ helper = extra.get("helper")
64
+ if helper is not None and (not isinstance(helper, str) or not _ADDR.match(helper)):
65
+ raise SubethaError("extra.helper is not an address")
66
+ deadline = extra.get("deadline")
67
+ if deadline is not None and not isinstance(deadline, int):
68
+ raise SubethaError("extra.deadline is not a number")
69
+ fee = extra.get("fee")
70
+ if fee is not None:
71
+ if not isinstance(fee, dict) or not isinstance(fee.get("amount"), str) or not _DEC.match(fee["amount"]) or not isinstance(fee.get("bps"), int):
72
+ raise SubethaError("extra.fee malformed (expect { amount: decimal string, bps: number })")
73
+ return Requirements(
74
+ raw=req,
75
+ pay_to=pay_to,
76
+ asset=asset,
77
+ amount=int(amount),
78
+ chain_id=int(m.group(1)),
79
+ network=network,
80
+ challenge_nonce=nonce,
81
+ expires_at=expires_at,
82
+ helper=helper,
83
+ deadline=deadline,
84
+ fee=fee,
85
+ )
86
+
87
+
88
+ def encode_payment_signature(accepted: dict, payload: dict) -> str:
89
+ """PROTOCOL.md §3: { x402Version: 2, accepted: <the offer echoed verbatim>, payload }.
90
+ `accepted` must be the exact dict received in the 402 — the middleware deep-equal
91
+ matches it against its own record."""
92
+ envelope = {"x402Version": X402_VERSION, "accepted": accepted, "payload": payload}
93
+ return base64.b64encode(json.dumps(envelope, separators=(",", ":")).encode("utf-8")).decode("ascii")
94
+
95
+
96
+ def decode_payment_response(header: Optional[str]) -> Optional[dict]:
97
+ """SettleResponse from PAYMENT-RESPONSE; decode failures are non-fatal (None)."""
98
+ if not header:
99
+ return None
100
+ try:
101
+ doc = _b64_json(header)
102
+ return doc if isinstance(doc, dict) else None
103
+ except (ValueError, binascii.Error):
104
+ return None
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: subetha
3
+ Version: 0.1.0
4
+ Summary: Pay for x402 (HTTP 402) APIs privately over SubEtha's zERC20 rail — Python payer client
5
+ Project-URL: Homepage, https://github.com/peaceandwhisky/SubEtha
6
+ Project-URL: Repository, https://github.com/peaceandwhisky/SubEtha
7
+ Project-URL: Issues, https://github.com/peaceandwhisky/SubEtha/issues
8
+ Project-URL: Changelog, https://github.com/peaceandwhisky/SubEtha/blob/main/python/CHANGELOG.md
9
+ Project-URL: Documentation, https://github.com/peaceandwhisky/SubEtha/blob/main/docs/PROTOCOL.md
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: ai-agents,http-402,payments,privacy,x402,zerc20
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Internet :: WWW/HTTP
19
+ Classifier: Topic :: Security :: Cryptography
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: eth-account>=0.13
22
+ Requires-Dist: httpx>=0.27
23
+ Description-Content-Type: text/markdown
24
+
25
+ # subetha (Python) — private x402 payments for Python agents
26
+
27
+ Pay for x402 (HTTP 402) paywalled APIs over SubEtha's zERC20 rail so that **no on-chain
28
+ trail links the payer to the payee**: the burn itself is public (amounts stay
29
+ transparent), but nothing on-chain connects it to the provider's treasury. This is the
30
+ Python counterpart of the TypeScript agent tools
31
+ ([docs/AGENT-TOOLS.md](https://github.com/peaceandwhisky/SubEtha/blob/main/docs/AGENT-TOOLS.md)):
32
+ the same wire protocol
33
+ ([docs/PROTOCOL.md](https://github.com/peaceandwhisky/SubEtha/blob/main/docs/PROTOCOL.md) —
34
+ this package is a reference implementation written against that spec), the same
35
+ spending-policy semantics.
36
+
37
+ ## Status
38
+
39
+ **Experimental (0.x).** The API may change in breaking ways between 0.x minor
40
+ releases while integrations (agent frameworks, plugins) shape it. If you depend on
41
+ this package, **pin a minor**: `subetha>=0.1,<0.2`. Stability will be declared at
42
+ 1.0. Changes are recorded in
43
+ [CHANGELOG.md](https://github.com/peaceandwhisky/SubEtha/blob/main/python/CHANGELOG.md).
44
+
45
+ ## Scope
46
+
47
+ This package is the **payer side only**: decode a 402 offer, decide under an
48
+ operator-configured spending policy, sign, pay, report. That is a deliberate,
49
+ stable boundary — it is also what the API-stability promise will cover at 1.0.
50
+
51
+ The provider, facilitator, and settlement layers are TypeScript and live in the
52
+ [same repository](https://github.com/peaceandwhisky/SubEtha); there is no plan to
53
+ port them. Paying touches no zk code and no BUSL code: this package depends only on
54
+ `httpx` and `eth-account`.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install subetha
60
+ ```
61
+
62
+ For development (from a repository checkout):
63
+
64
+ ```bash
65
+ uv pip install -e python/ # from the repository root
66
+ # or: pip install -e python/
67
+ ```
68
+
69
+ Dependencies: `httpx`, `eth-account` (no web3.py). Python ≥ 3.11.
70
+
71
+ ## Use
72
+
73
+ ```python
74
+ from subetha import SubethaClient, SpendingPolicy
75
+
76
+ client = SubethaClient(
77
+ private_key="0x…", # the paying account (permit: only signs, no gas)
78
+ rpc_url="http://127.0.0.1:8545",
79
+ mode="permit", # gasless (default); or "self-transfer"
80
+ policy=SpendingPolicy(
81
+ allowed_hosts=["127.0.0.1"], # first line of defense — keep it tight
82
+ max_per_payment=100_000, # token base units
83
+ max_total=5_000_000,
84
+ ),
85
+ approve_above=10_000, # optional human-in-the-loop
86
+ approve_payment=lambda info: ask_human(info), # True = approve
87
+ )
88
+
89
+ q = client.quote("http://127.0.0.1:4031/api/complete", method="POST", body='{"prompt":"hi"}')
90
+ print(q.offer.quoted, q.offer.fee, q.offer.approval_required)
91
+
92
+ r = client.pay("http://127.0.0.1:4031/api/complete", method="POST", body='{"prompt":"hi"}')
93
+ print(r.status, r.payment.amount, r.resource)
94
+
95
+ print(client.report()) # totals / payments / attempts (incl. approvals)
96
+ ```
97
+
98
+ `SubethaClient.from_env()` reads the same `SUBETHA_*` variables as the TypeScript tools
99
+ (`SUBETHA_PAYER_PK`, `SUBETHA_RPC_URL`, `SUBETHA_MODE`, `SUBETHA_ALLOWED_HOSTS`,
100
+ `SUBETHA_ALLOWED_NETWORK`, `SUBETHA_ALLOWED_TOKEN`, `SUBETHA_MAX_PER_PAYMENT`,
101
+ `SUBETHA_MAX_TOTAL`, `SUBETHA_APPROVE_ABOVE`, `SUBETHA_APPROVAL_TIMEOUT_MS`,
102
+ `SUBETHA_TIMEOUT_MS`).
103
+
104
+ ### Semantics you can rely on
105
+
106
+ - **Policy before money**: host allowlist before any request; per-payment / total caps
107
+ and network/token pins at offer selection. Refusals raise `SubethaError` with the
108
+ reason; nothing is paid.
109
+ - **Approval**: payments quoted above `approve_above` call `approve_payment` (bounded by
110
+ `approval_timeout_s`, default 120 s). Decline / timeout / a raising callback / no
111
+ callback ⇒ refused. The approval is bound to the exact offer.
112
+ - **Accounting at the point of no return**: a self-transfer burn is counted the moment it
113
+ lands; a permit reservation is released only when settle is definitively rejected.
114
+ - **One payment at a time**; errors are redacted (the key never appears in messages).
115
+ - `mode="permit"` fail-fasts when the offer lacks the gasless path — it never silently
116
+ degrades to a gas-paying transfer.
117
+
118
+ ## Key management & safety
119
+
120
+ This client signs with a raw private key. Treat that as the threat model:
121
+
122
+ - **At runtime the key exists decrypted in process memory.** Encrypted config or
123
+ secret stores protect the key *at rest* — anything that can read your agent
124
+ process (or its crash dumps) can read the key. Plan accordingly.
125
+ - **Use a dedicated hot wallet.** Fund the paying account with small amounts, top it
126
+ up as needed, and keep it separate from any treasury or personal wallet. If it
127
+ leaks, the loss is bounded by the balance and your `max_total`.
128
+ - **The spending policy is the operator's, not the agent's.** Allowlist, caps, and
129
+ `approve_above` are configuration the human sets; agents cannot raise their own
130
+ limits. Keep `allowed_hosts` as tight as your deployment allows.
131
+ - **Redaction is scoped.** This package keeps the key out of its own errors and
132
+ reports; whatever *you* log around it (request dumps, env printouts) is your
133
+ responsibility.
134
+ - Report vulnerabilities privately via
135
+ [GitHub Security Advisories](https://github.com/peaceandwhisky/SubEtha/security/advisories)
136
+ (see [SECURITY.md](https://github.com/peaceandwhisky/SubEtha/blob/main/SECURITY.md)).
137
+
138
+ ## LangChain (Python) example
139
+
140
+ No extra dependency in this package — wrap the client yourself:
141
+
142
+ ```python
143
+ from langchain_core.tools import tool
144
+ from subetha import SubethaClient, SubethaError
145
+
146
+ client = SubethaClient.from_env()
147
+
148
+ @tool
149
+ def subetha_x402_pay(url: str, method: str = "GET", body: str | None = None) -> str:
150
+ """Pay for an x402 resource privately under the configured spending policy."""
151
+ try:
152
+ r = client.pay(url, method=method, body=body)
153
+ return f"HTTP {r.status}; paid {r.payment.amount if r.payment else 0}; {r.resource[:2000]}"
154
+ except SubethaError as e:
155
+ return f"ERROR: {e}" # let the agent read the refusal instead of crashing
156
+ ```
157
+
158
+ ## Tests
159
+
160
+ ```bash
161
+ uv run --project python pytest python/tests -q # unit (no chain needed)
162
+ # cross-language live e2e (real stack + the TypeScript provider/facilitator):
163
+ PERMIT_BURNER_ADDRESS=0x… pnpm --filter @subetha/demo-official exec tsx ../../python/scripts/live-e2e.ts
164
+ ```
165
+
166
+ ## License
167
+
168
+ Apache-2.0 (this package). Note that operating a SubEtha facilitator commercially / in
169
+ production requires a separate use grant from the zERC20 team — see the License section
170
+ of the [repository README](https://github.com/peaceandwhisky/SubEtha#license).
@@ -0,0 +1,12 @@
1
+ subetha/__init__.py,sha256=rDcdGZKIbjAyKG2bxH4Z9o0sU7Yg6eCKqe6jBriPb2Y,738
2
+ subetha/_redact.py,sha256=aLhV-_T224P1LkPznJHxUFdTONKfV_kn4WUGMQKk9XI,622
3
+ subetha/client.py,sha256=Z-Skw2gkNb9hYUOlc9_2Bw26sw4q-5jMhEDCb79dXwE,15742
4
+ subetha/policy.py,sha256=aeSvuqpAH4M_Zi4pEl-cClIeZ42JaaUxYWtFtlsQjns,5705
5
+ subetha/rpc.py,sha256=le0FvtBva7T-9ayB4ZBDrnB7CRdlvidq6MCw7ZhQNSs,4176
6
+ subetha/signing.py,sha256=d_wvNQo9RLmjLXnKTP68AGH7UqjLS1a6uGyIHkCZgOY,4836
7
+ subetha/types.py,sha256=EPoP1byOdEjWNmqO5e2_IW5JLZDY4HkaPzpXtMFVB4w,1865
8
+ subetha/wire.py,sha256=t_21YIHIkQsVbz2BbCtrDeGNZViZeApN3tclQvK__jg,4411
9
+ subetha-0.1.0.dist-info/METADATA,sha256=oCNgWiR-mM5FINySkDol49Ccwk4URsc2bxk9-uSktOM,7677
10
+ subetha-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
11
+ subetha-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ subetha-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.