usdf 0.1.2__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.
usdf/x402.py ADDED
@@ -0,0 +1,555 @@
1
+ """Pay per request with no account (x402 v2, "exact" scheme), in USDF through Permit2 or in USDG
2
+ through an EIP-3009 authorization, with nothing but an EIP-712 signer. No payment library is needed:
3
+ the gateway publishes what it accepts in the 402's PAYMENT-REQUIRED header (base64 JSON), the payer
4
+ signs one of the accepts and retries with PAYMENT-SIGNATURE. Shapes follow gateway/src/x402.ts.
5
+
6
+ A signer is anything with ``address`` and ``sign_typed_data(typed_data) -> "0x..."`` where
7
+ ``typed_data`` is the full EIP-712 message ({"types", "primaryType", "domain", "message"}), the shape
8
+ eth-account's ``Account.sign_typed_data(key, full_message=...)`` and ``eth_signTypedData_v4`` take.
9
+ ``wallet_signer(wallet)`` turns an eth-account account (or a private key) into one.
10
+
11
+ The 402 is written by whatever server answers at the base URL (a mistyped USDF_BASE_URL, a proxy, a
12
+ hostname that changed hands), so nothing in it is taken on trust but the payee when that server is the
13
+ gateway itself (GATEWAY_ORIGIN, over TLS): an accept is signed only when it names Robinhood Chain, USDF
14
+ through Permit2 or USDG through EIP-3009 under USDG's own EIP-712 domain, a payee the gateway names
15
+ (``X402.payees``: its own 402, else its GET /v1/config, else GATEWAY_PAYEE) or the caller pinned, a
16
+ validity window of at most an hour, and an amount within the payer's cap (``check_accept``). The one approval is sent only for USDF, only to Permit2, and only through an RPC on
17
+ chain 4663; the allowance is read only from an RPC that answers for chain 4663.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import inspect
24
+ import json
25
+ import os
26
+ import re
27
+ import time
28
+ import urllib.parse
29
+ import urllib.request
30
+ from typing import Any, Dict, Iterable, List, Optional, Protocol, Sequence, Union
31
+
32
+ from .errors import USDFError
33
+
34
+ PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3"
35
+ X402_EXACT_PERMIT2_PROXY = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001"
36
+
37
+ # ── What this SDK pays, and to whom ──────────────────────────────────────────
38
+
39
+ CHAIN_ID = 4663
40
+ NETWORK = f"eip155:{CHAIN_ID}"
41
+ USDF_ADDRESS = "0x4A35a5eC2A50A4d2957B2F2366E017f526cAB318"
42
+ USDG_ADDRESS = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"
43
+ USDG_DOMAIN = {"name": "Global Dollar", "version": "1"}
44
+ # The gateway. Its own 402 names the payee, its live custody hot wallet, and GET /v1/config publishes the same
45
+ # (``x402.pay_to``). A payee is taken from a 402 as it stands only when the 402 comes from here.
46
+ GATEWAY_ORIGIN = "https://api.usdf.fi"
47
+ # Where the gateway publishes its payee: always the gateway's own, never the base URL's (a server there that is
48
+ # not the gateway would vouch for itself).
49
+ GATEWAY_CONFIG_URL = GATEWAY_ORIGIN + "/v1/config"
50
+ # The last-resort payee: the gateway's custody hot wallet since the key rotation of 2026-10-26, signed for when
51
+ # a 402 from another base URL names it and the gateway's /v1/config does not answer. The hot wallet it replaced
52
+ # (0x52Fe...9F05, whose key was exposed) is no constant here: it is paid only while the gateway itself names it,
53
+ # which the gateway does until the rotation's flip and never after (its 402 and its /v1/config both read the
54
+ # live HOT_ADDRESS). Another payee is paid only when the caller names it (``pay_to=``, or USDF_PAY_TO), for
55
+ # example a self-hosted gateway; then only that payee, whatever the gateway names.
56
+ GATEWAY_PAYEE = "0x13009Bd7116f8C955f92409467743ee67AB1990b"
57
+ # How long the payee the gateway's /v1/config publishes is kept (the gateway caches it as long).
58
+ PAYEE_TTL_SECONDS = 300
59
+ # The chain's public RPC: where the allowance is read when no ``rpc_url`` (USDF_RPC_URL) is given.
60
+ PUBLIC_RPC_URL = "https://rpc.mainnet.chain.robinhood.com"
61
+ # Default cap on one payment, in base units: 1 USDF. The exact scheme pays the quote up front, which is the
62
+ # request's worst case at its max_tokens (the gateway charges what it used and refunds the rest); the dearest
63
+ # model on the sheet quotes 0.80 USDF for a short prompt at its default output budget. Raise it with
64
+ # ``max_amount`` (or USDF_MAX_AMOUNT), or lower max_tokens.
65
+ DEFAULT_MAX_AMOUNT = 1_000_000
66
+ # The longest validity window signed (the gateway asks for 300 seconds).
67
+ MAX_VALIDITY_SECONDS = 3600
68
+
69
+ _ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$")
70
+
71
+
72
+ class PaymentLimits:
73
+ """The cap on one payment (base units) and the payees a payment may go to (lowercased). ``pinned`` is
74
+ False while the payees are the default (GATEWAY_PAYEE) and the gateway's word may add to them
75
+ (``X402.payees``); True when they are final: the caller's, or the gateway's once resolved."""
76
+
77
+ def __init__(self, max_amount: int, pay_to: Sequence[str], pinned: bool = True):
78
+ self.max_amount = max_amount
79
+ self.pay_to = tuple(pay_to)
80
+ self.pinned = pinned
81
+
82
+ def __repr__(self) -> str:
83
+ return f"PaymentLimits(max_amount={self.max_amount}, pay_to={list(self.pay_to)}, pinned={self.pinned})"
84
+
85
+
86
+ def _refuse(code: str, message: str) -> USDFError:
87
+ return USDFError(402, message, "payment_refused", code)
88
+
89
+
90
+ def _fmt_units(u: int) -> str:
91
+ return f"{u // 1_000_000}.{u % 1_000_000:06d}"
92
+
93
+
94
+ def payment_limits(max_amount: Union[int, str, None] = None, pay_to: Union[str, Sequence[str], None] = None) -> PaymentLimits:
95
+ """The limits in force: the arguments, else USDF_MAX_AMOUNT and USDF_PAY_TO, else 1 USDF to the gateway's payee
96
+ (GATEWAY_PAYEE, to which ``X402.payees`` adds the payee the gateway names; a ``pay_to`` named here is pinned)."""
97
+ raw_max = max_amount if max_amount is not None else os.environ.get("USDF_MAX_AMOUNT") or None
98
+ cap = DEFAULT_MAX_AMOUNT
99
+ if raw_max is not None and str(raw_max).strip() != "":
100
+ s = str(raw_max).strip()
101
+ if isinstance(raw_max, bool) or not re.match(r"^\d+$", s):
102
+ raise USDFError(400, f'max_amount is a whole number of base units (1 USDF = 1000000), not "{s}"', "invalid_request_error", "invalid_max_amount")
103
+ cap = int(s)
104
+ named = pay_to if pay_to is not None else os.environ.get("USDF_PAY_TO") or None
105
+ raw_pay = named if named is not None else GATEWAY_PAYEE
106
+ payees = [str(a).strip() for a in (raw_pay.split(",") if isinstance(raw_pay, str) else list(raw_pay)) if str(a).strip()]
107
+ if not payees:
108
+ raise USDFError(400, "pay_to names no payee", "invalid_request_error", "invalid_pay_to")
109
+ for a in payees:
110
+ if not _ADDRESS.match(a):
111
+ raise USDFError(400, f"pay_to {a} is not an address", "invalid_request_error", "invalid_pay_to")
112
+ return PaymentLimits(cap, list(dict.fromkeys(a.lower() for a in payees)), pinned=named is not None)
113
+
114
+
115
+ def _addresses(values: Iterable[Any]) -> List[str]:
116
+ out: List[str] = []
117
+ for v in values:
118
+ a = str(v if v is not None else "").strip()
119
+ if _ADDRESS.match(a) and a.lower() not in out:
120
+ out.append(a.lower())
121
+ return out
122
+
123
+
124
+ def named_payees(required: Any) -> List[str]:
125
+ """The payees a 402 names (its accepts' payTo), lowercased."""
126
+ accepts = required.get("accepts") if isinstance(required, dict) else None
127
+ return _addresses(a.get("payTo") for a in (accepts if isinstance(accepts, list) else []) if isinstance(a, dict))
128
+
129
+
130
+ def published_payees(config: Any) -> List[str]:
131
+ """The payee(s) the gateway's GET /v1/config publishes (``x402.pay_to``: an address, or a list), lowercased;
132
+ [] for anything else."""
133
+ x = config.get("x402") if isinstance(config, dict) else None
134
+ raw = x.get("pay_to") if isinstance(x, dict) else None
135
+ return _addresses(raw if isinstance(raw, list) else [raw])
136
+
137
+
138
+ def is_gateway_origin(base_url: str) -> bool:
139
+ """True when the base URL is the gateway's own (GATEWAY_ORIGIN: https, the same host and port)."""
140
+ try:
141
+ u, g = urllib.parse.urlsplit(base_url), urllib.parse.urlsplit(GATEWAY_ORIGIN)
142
+ port = u.port or (443 if u.scheme == "https" else None)
143
+ return u.scheme == g.scheme and (u.hostname or "") == g.hostname and port == (g.port or 443)
144
+ except ValueError:
145
+ return False
146
+
147
+
148
+ def with_gateway_payees(limits: PaymentLimits, payees: Iterable[str]) -> PaymentLimits:
149
+ """The limits with the payees the gateway names added, final from then on; pinned limits as they are."""
150
+ if limits.pinned:
151
+ return limits
152
+ return PaymentLimits(limits.max_amount, list(dict.fromkeys([*limits.pay_to, *_addresses(payees)])), pinned=True)
153
+
154
+
155
+ def known_asset(accept: Dict[str, Any]) -> Optional[str]:
156
+ """"USDF" or "USDG" when the accept names that token on chain 4663 with its own transfer method, else None."""
157
+ if not isinstance(accept, dict) or accept.get("network") != NETWORK:
158
+ return None
159
+ asset = str(accept.get("asset") or "").lower()
160
+ method = transfer_method(accept)
161
+ if asset == USDF_ADDRESS.lower() and method == "permit2":
162
+ return "USDF"
163
+ if asset == USDG_ADDRESS.lower() and method == "eip3009":
164
+ return "USDG"
165
+ return None
166
+
167
+
168
+ def _check_shape(accept: Dict[str, Any]) -> Any:
169
+ """What any payment must be: the exact scheme on chain 4663, USDF through Permit2 or USDG through
170
+ EIP-3009 under USDG's own domain, a positive whole amount, a window of at most an hour."""
171
+ if not isinstance(accept, dict) or accept.get("scheme") != "exact":
172
+ raise _refuse("untrusted_scheme", f'the gateway asked for an x402 "{(accept or {}).get("scheme")}" payment; this SDK signs "exact" payments only')
173
+ if accept.get("network") != NETWORK:
174
+ raise _refuse("untrusted_network", f"the gateway asked for payment on {accept.get('network')}; this SDK pays on Robinhood Chain ({NETWORK}) only")
175
+ asset = known_asset(accept)
176
+ if asset is None:
177
+ raise _refuse("untrusted_asset", f"the gateway asked for {accept.get('asset')} through {transfer_method(accept)}; this SDK pays USDF ({USDF_ADDRESS}) through Permit2 or USDG ({USDG_ADDRESS}) through EIP-3009 only")
178
+ extra = accept.get("extra") or {}
179
+ if asset == "USDG" and (extra.get("name") != USDG_DOMAIN["name"] or extra.get("version") != USDG_DOMAIN["version"]):
180
+ raise _refuse("untrusted_domain", f'USDG signs under the EIP-712 domain "{USDG_DOMAIN["name"]}" version "{USDG_DOMAIN["version"]}"; the gateway sent "{extra.get("name")}" version "{extra.get("version")}"')
181
+ raw = accept.get("amount")
182
+ amount = int(raw) if isinstance(raw, (str, int)) and not isinstance(raw, bool) and re.match(r"^\d+$", str(raw)) else None
183
+ if amount is None or amount == 0:
184
+ raise _refuse("untrusted_amount", f"the payment amount {raw} is not a positive whole number of base units")
185
+ window = accept.get("maxTimeoutSeconds") or 300
186
+ if not isinstance(window, int) or isinstance(window, bool) or window <= 0 or window > MAX_VALIDITY_SECONDS:
187
+ raise _refuse("untrusted_timeout", f"the gateway asked for an authorization valid {accept.get('maxTimeoutSeconds')} seconds; at most {MAX_VALIDITY_SECONDS} is signed")
188
+ return asset, amount
189
+
190
+
191
+ def check_accept(accept: Dict[str, Any], limits: Optional[PaymentLimits] = None) -> str:
192
+ """Raises USDFError (type "payment_refused") unless this SDK would sign the accept under these limits:
193
+ the payee and the cap on one payment, on top of the chain, token, domain, amount and window. Returns
194
+ the asset it pays."""
195
+ limits = limits or payment_limits()
196
+ asset, amount = _check_shape(accept)
197
+ payee = str(accept.get("payTo") or "")
198
+ if not _ADDRESS.match(payee) or payee.lower() not in limits.pay_to:
199
+ raise _refuse("untrusted_payee", f"the gateway asked for payment to {payee}, which is not the expected payee ({', '.join(limits.pay_to)}); to pay another gateway, name its payee with pay_to (or USDF_PAY_TO)")
200
+ if amount > limits.max_amount:
201
+ raise _refuse("amount_over_limit", f"the gateway quotes {_fmt_units(amount)} {asset} for this request, over the {_fmt_units(limits.max_amount)} cap on one payment; lower max_tokens, or raise max_amount (USDF_MAX_AMOUNT, in base units)")
202
+ return asset
203
+
204
+ EIP712_DOMAIN_FULL = [
205
+ {"name": "name", "type": "string"},
206
+ {"name": "version", "type": "string"},
207
+ {"name": "chainId", "type": "uint256"},
208
+ {"name": "verifyingContract", "type": "address"},
209
+ ]
210
+ # Permit2's domain has no version.
211
+ EIP712_DOMAIN_NO_VERSION = [
212
+ {"name": "name", "type": "string"},
213
+ {"name": "chainId", "type": "uint256"},
214
+ {"name": "verifyingContract", "type": "address"},
215
+ ]
216
+
217
+ PERMIT2_WITNESS_TYPES = {
218
+ "PermitWitnessTransferFrom": [
219
+ {"name": "permitted", "type": "TokenPermissions"},
220
+ {"name": "spender", "type": "address"},
221
+ {"name": "nonce", "type": "uint256"},
222
+ {"name": "deadline", "type": "uint256"},
223
+ {"name": "witness", "type": "Witness"},
224
+ ],
225
+ "TokenPermissions": [{"name": "token", "type": "address"}, {"name": "amount", "type": "uint256"}],
226
+ "Witness": [{"name": "to", "type": "address"}, {"name": "validAfter", "type": "uint256"}],
227
+ }
228
+
229
+ AUTHORIZATION_TYPES = {
230
+ "TransferWithAuthorization": [
231
+ {"name": "from", "type": "address"},
232
+ {"name": "to", "type": "address"},
233
+ {"name": "value", "type": "uint256"},
234
+ {"name": "validAfter", "type": "uint256"},
235
+ {"name": "validBefore", "type": "uint256"},
236
+ {"name": "nonce", "type": "bytes32"},
237
+ ]
238
+ }
239
+
240
+
241
+ class Signer(Protocol):
242
+ address: str
243
+
244
+ def sign_typed_data(self, typed_data: Dict[str, Any]) -> str: ...
245
+
246
+
247
+ def _bytes32_as_bytes(typed_data: Dict[str, Any]) -> Dict[str, Any]:
248
+ """eth-account takes bytes32 values as bytes."""
249
+ msg = json.loads(json.dumps(typed_data))
250
+ for name, fields in msg["types"].items():
251
+ if name != msg["primaryType"]:
252
+ continue
253
+ for f in fields:
254
+ if f["type"] == "bytes32" and isinstance(msg["message"].get(f["name"]), str):
255
+ msg["message"][f["name"]] = bytes.fromhex(msg["message"][f["name"]][2:])
256
+ return msg
257
+
258
+
259
+ def _hex(sig: Any) -> str:
260
+ h = sig.hex() if hasattr(sig, "hex") else str(sig)
261
+ return h if h.startswith("0x") else "0x" + h
262
+
263
+
264
+ class EthAccountSigner:
265
+ """An eth-account account (``Account.from_key(...)``) or private key as a Signer."""
266
+
267
+ def __init__(self, account_or_key: Any):
268
+ from eth_account import Account # type: ignore
269
+
270
+ self._account = Account.from_key(account_or_key) if isinstance(account_or_key, (str, bytes)) else account_or_key
271
+ self.address = self._account.address
272
+
273
+ def sign_typed_data(self, typed_data: Dict[str, Any]) -> str:
274
+ from eth_account import Account # type: ignore
275
+
276
+ msg = _bytes32_as_bytes(typed_data)
277
+ key = getattr(self._account, "key", None)
278
+ signed = Account.sign_typed_data(key, full_message=msg) if key is not None else self._account.sign_typed_data(full_message=msg)
279
+ return _hex(signed.signature)
280
+
281
+
282
+ def eth_account_signer(private_key: Any) -> EthAccountSigner:
283
+ return EthAccountSigner(private_key)
284
+
285
+
286
+ def wallet_signer(wallet: Any) -> Signer:
287
+ """A wallet as a Signer: an eth-account account (``Account.from_key(...)``), a private key, or any
288
+ object with ``address`` and ``sign_typed_data(typed_data) -> "0x..."`` taking the full EIP-712
289
+ message (the shape ``eth_signTypedData_v4`` takes)."""
290
+ if isinstance(wallet, (str, bytes)) or hasattr(wallet, "key"):
291
+ return EthAccountSigner(wallet)
292
+ fn = getattr(wallet, "sign_typed_data", None)
293
+ if not callable(fn) or not getattr(wallet, "address", None):
294
+ raise TypeError("wallet needs an address and sign_typed_data (an eth-account account, a private key, or a Signer)")
295
+ try:
296
+ params = inspect.signature(fn).parameters
297
+ except (TypeError, ValueError):
298
+ params = {}
299
+ if "full_message" in params:
300
+
301
+ class _Keyword:
302
+ address = wallet.address
303
+
304
+ def sign_typed_data(self, typed_data: Dict[str, Any]) -> str:
305
+ return _hex(fn(full_message=_bytes32_as_bytes(typed_data)).signature)
306
+
307
+ return _Keyword()
308
+ return wallet
309
+
310
+
311
+ # ── JSON-RPC: the allowance read and the one approval ────────────────────────
312
+
313
+
314
+ def rpc_call(rpc_url: str, method: str, params: List[Any], timeout: float = 30.0) -> Any:
315
+ """One JSON-RPC call over the standard library."""
316
+ body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode("utf-8")
317
+ req = urllib.request.Request(rpc_url, data=body, method="POST", headers={"content-type": "application/json", "accept": "application/json", "user-agent": "usdf-sdk-py"})
318
+ with urllib.request.urlopen(req, timeout=timeout) as res:
319
+ j = json.loads(res.read().decode("utf-8"))
320
+ if not isinstance(j, dict) or j.get("error"):
321
+ raise RuntimeError(f"rpc {method}: {(j or {}).get('error')}")
322
+ return j.get("result")
323
+
324
+
325
+ def rpc_chain_id(rpc_url: str) -> int:
326
+ """The chain an RPC answers for (eth_chainId)."""
327
+ return int(str(rpc_call(rpc_url, "eth_chainId", [])), 16)
328
+
329
+
330
+ def read_permit2_allowance(rpc_url: str, token: str, owner: str) -> int:
331
+ """USDF ``allowance(owner, Permit2)``."""
332
+ return decode_uint256(str(rpc_call(rpc_url, "eth_call", [permit2_allowance_call(token, owner), "latest"])))
333
+
334
+
335
+ def approve_permit2(wallet: Any, rpc_url: str, token: str, amount: Optional[int] = None, timeout: float = 120.0) -> str:
336
+ """The one transaction a USDF payer ever sends: ``approve(Permit2, amount)`` on USDF (unlimited by
337
+ default), signed locally with the eth-account key and sent through ``rpc_url``; waits until mined. Any
338
+ other token, or an RPC on another chain than 4663, is refused before anything is signed."""
339
+ if str(token).lower() != USDF_ADDRESS.lower():
340
+ raise _refuse("untrusted_asset", f"the one approval this SDK sends is USDF ({USDF_ADDRESS}) to Permit2, not {token}")
341
+ from eth_account import Account # type: ignore
342
+
343
+ account = Account.from_key(wallet) if isinstance(wallet, (str, bytes)) else wallet
344
+ if not hasattr(account, "sign_transaction"):
345
+ raise USDFError(402, "approving USDF to Permit2 needs an account that signs transactions (an eth-account account); approve once, or pay in USDG", "payment_required", "permit2_allowance_required")
346
+ call = permit2_approval_call(token, _UINT256_MAX if amount is None else amount)
347
+ chain_id = rpc_chain_id(rpc_url)
348
+ if chain_id != CHAIN_ID:
349
+ raise _refuse("wrong_chain", f"the RPC at {rpc_url} answers for chain {chain_id}, not Robinhood Chain ({CHAIN_ID}); the approval is sent on {CHAIN_ID} only")
350
+ nonce = int(str(rpc_call(rpc_url, "eth_getTransactionCount", [account.address, "pending"])), 16)
351
+ gas = int(str(rpc_call(rpc_url, "eth_estimateGas", [{"from": account.address, "to": call["to"], "data": call["data"]}])), 16)
352
+ block = rpc_call(rpc_url, "eth_getBlockByNumber", ["latest", False]) or {}
353
+ base_fee = int(str(block.get("baseFeePerGas") or "0x0"), 16)
354
+ try:
355
+ tip = int(str(rpc_call(rpc_url, "eth_maxPriorityFeePerGas", [])), 16)
356
+ except Exception:
357
+ tip = 0
358
+ from eth_utils import to_checksum_address # type: ignore # installed with eth-account
359
+
360
+ tx = {"chainId": chain_id, "type": 2, "nonce": nonce, "to": to_checksum_address(call["to"]), "data": call["data"], "value": 0, "gas": gas * 12 // 10, "maxPriorityFeePerGas": tip, "maxFeePerGas": base_fee * 2 + tip}
361
+ signed = account.sign_transaction(tx)
362
+ raw = getattr(signed, "raw_transaction", None) or getattr(signed, "rawTransaction")
363
+ tx_hash = str(rpc_call(rpc_url, "eth_sendRawTransaction", [_hex(raw)]))
364
+ deadline = time.time() + timeout
365
+ while time.time() < deadline:
366
+ r = rpc_call(rpc_url, "eth_getTransactionReceipt", [tx_hash])
367
+ if r:
368
+ if str(r.get("status")) != "0x1":
369
+ raise USDFError(402, f"the Permit2 approval {tx_hash} reverted", "payment_required", "permit2_approval_failed")
370
+ return tx_hash
371
+ time.sleep(1.0)
372
+ raise USDFError(402, f"the Permit2 approval {tx_hash} was not mined within the wait; pay again once it is", "payment_required", "permit2_approval_pending")
373
+
374
+
375
+ # ── Header codecs (base64 of UTF-8 JSON, as the x402 packages encode them) ───
376
+
377
+ _B64 = re.compile(r"^[A-Za-z0-9+/]+={0,2}$")
378
+
379
+
380
+ def decode_payment_required(header: str) -> Dict[str, Any]:
381
+ if not _B64.match(header or ""):
382
+ raise USDFError(402, "PAYMENT-REQUIRED header is not base64", "payment_required", "x402")
383
+ v = json.loads(base64.b64decode(header).decode("utf-8"))
384
+ if not isinstance(v, dict) or v.get("x402Version") != 2 or not v.get("accepts"):
385
+ raise USDFError(402, "PAYMENT-REQUIRED header is not an x402 v2 requirement", "payment_required", "x402")
386
+ return v
387
+
388
+
389
+ def encode_payment_signature(payload: Dict[str, Any]) -> str:
390
+ return base64.b64encode(json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).decode("ascii")
391
+
392
+
393
+ def decode_payment_response(header: str) -> Dict[str, Any]:
394
+ if not _B64.match(header or ""):
395
+ raise USDFError(502, "PAYMENT-RESPONSE header is not base64", "upstream_error")
396
+ return json.loads(base64.b64decode(header).decode("utf-8"))
397
+
398
+
399
+ # ── Choosing and signing an accept ───────────────────────────────────────────
400
+
401
+
402
+ def transfer_method(accept: Dict[str, Any]) -> str:
403
+ extra = accept.get("extra") or {}
404
+ return "permit2" if extra.get("assetTransferMethod") == "permit2" else "eip3009"
405
+
406
+
407
+ def choose_accept(required: Dict[str, Any], asset: Optional[str] = None) -> Dict[str, Any]:
408
+ """The accept to pay, among those this SDK pays at all (USDF through Permit2 or USDG through EIP-3009
409
+ on chain 4663; an accept on another chain or in another token is never chosen): the one in ``asset``,
410
+ or with no preference the first the gateway lists. ``check_accept`` then holds it to the payee and cap."""
411
+ accepts = list(required.get("accepts") or [])
412
+ payable = [a for a in accepts if isinstance(a, dict) and a.get("scheme") == "exact" and known_asset(a) is not None]
413
+ if not payable:
414
+ if accepts:
415
+ _check_shape(accepts[0]) # why the first offer is not payable (another chain, another token)
416
+ raise _refuse("untrusted_asset", f"the gateway offered nothing this SDK pays: USDF (Permit2) or USDG (EIP-3009) on {NETWORK}")
417
+ if asset is None:
418
+ return payable[0]
419
+ want = asset.upper()
420
+ for a in payable:
421
+ if known_asset(a) == want:
422
+ return a
423
+ raise USDFError(402, f"the gateway offered no {asset} payment", "payment_required", "x402")
424
+
425
+
426
+ def chain_id_of(network: str) -> int:
427
+ m = re.match(r"^eip155:(\d+)$", network)
428
+ if not m:
429
+ raise USDFError(402, f"not an EVM network: {network}", "payment_required", "x402")
430
+ return int(m.group(1))
431
+
432
+
433
+ def sign_exact_payment(required: Dict[str, Any], accept: Dict[str, Any], signer: Signer, now: Optional[int] = None, limits: Optional[PaymentLimits] = None) -> Dict[str, Any]:
434
+ """Signs one accept for the quoted amount and returns the x402 v2 payload (the envelope the
435
+ PAYMENT-SIGNATURE header carries). Permit2: a witness transfer to the gateway's payee through the
436
+ x402 exact proxy, random uint256 nonce, deadline now + maxTimeoutSeconds. EIP-3009: a
437
+ transferWithAuthorization on the token under its own domain, random bytes32 nonce. Neither costs gas.
438
+ Nothing is signed unless ``check_accept`` passes under ``limits`` (default: ``payment_limits()``)."""
439
+ check_accept(accept, limits)
440
+ now = int(time.time()) if now is None else now
441
+ chain_id = chain_id_of(accept["network"])
442
+ expiry = str(now + int(accept.get("maxTimeoutSeconds") or 300))
443
+ if transfer_method(accept) == "permit2":
444
+ auth = {
445
+ "from": signer.address,
446
+ "permitted": {"token": accept["asset"], "amount": str(accept["amount"])},
447
+ "spender": X402_EXACT_PERMIT2_PROXY,
448
+ "nonce": str(int.from_bytes(os.urandom(32), "big")),
449
+ "deadline": expiry,
450
+ "witness": {"to": accept["payTo"], "validAfter": "0"},
451
+ }
452
+ typed = {
453
+ "types": {"EIP712Domain": EIP712_DOMAIN_NO_VERSION, **PERMIT2_WITNESS_TYPES},
454
+ "primaryType": "PermitWitnessTransferFrom",
455
+ "domain": {"name": "Permit2", "chainId": chain_id, "verifyingContract": PERMIT2_ADDRESS},
456
+ "message": {
457
+ "permitted": {"token": auth["permitted"]["token"], "amount": int(auth["permitted"]["amount"])},
458
+ "spender": auth["spender"],
459
+ "nonce": int(auth["nonce"]),
460
+ "deadline": int(auth["deadline"]),
461
+ "witness": {"to": auth["witness"]["to"], "validAfter": 0},
462
+ },
463
+ }
464
+ signature = signer.sign_typed_data(typed)
465
+ return {"x402Version": 2, "resource": required.get("resource"), "accepted": accept, "payload": {"signature": signature, "permit2Authorization": auth}}
466
+ extra = accept.get("extra") or {}
467
+ name, version = extra.get("name"), extra.get("version")
468
+ if not isinstance(name, str) or not isinstance(version, str):
469
+ raise USDFError(402, f"the {accept['asset']} accept carries no EIP-712 domain (name, version)", "payment_required", "x402")
470
+ auth = {
471
+ "from": signer.address,
472
+ "to": accept["payTo"],
473
+ "value": str(accept["amount"]),
474
+ "validAfter": "0",
475
+ "validBefore": expiry,
476
+ "nonce": "0x" + os.urandom(32).hex(),
477
+ }
478
+ typed = {
479
+ "types": {"EIP712Domain": EIP712_DOMAIN_FULL, **AUTHORIZATION_TYPES},
480
+ "primaryType": "TransferWithAuthorization",
481
+ "domain": {"name": name, "version": version, "chainId": chain_id, "verifyingContract": accept["asset"]},
482
+ "message": {"from": auth["from"], "to": auth["to"], "value": int(auth["value"]), "validAfter": 0, "validBefore": int(auth["validBefore"]), "nonce": auth["nonce"]},
483
+ }
484
+ signature = signer.sign_typed_data(typed)
485
+ return {"x402Version": 2, "resource": required.get("resource"), "accepted": accept, "payload": {"signature": signature, "authorization": auth}}
486
+
487
+
488
+ # ── The one transaction a USDF payer ever sends: approve USDF to Permit2 ────
489
+
490
+ _UINT256_MAX = (1 << 256) - 1
491
+
492
+
493
+ def _pad32(hex_value: str) -> str:
494
+ return hex_value[2:].lower().rjust(64, "0") if hex_value.startswith("0x") else hex_value.lower().rjust(64, "0")
495
+
496
+
497
+ def permit2_approval_call(token: str, amount: int = _UINT256_MAX) -> Dict[str, Any]:
498
+ """``approve(PERMIT2, amount)`` on the token as calldata for any transaction sender. Unlimited by default."""
499
+ return {"to": token, "data": "0x095ea7b3" + _pad32(PERMIT2_ADDRESS) + _pad32(hex(amount)), "value": 0}
500
+
501
+
502
+ def permit2_allowance_call(token: str, owner: str) -> Dict[str, str]:
503
+ """``allowance(owner, PERMIT2)`` on the token as an eth_call; decode the result with decode_uint256."""
504
+ return {"to": token, "data": "0xdd62ed3e" + _pad32(owner) + _pad32(PERMIT2_ADDRESS)}
505
+
506
+
507
+ def decode_uint256(hex_value: str) -> int:
508
+ h = hex_value[2:] if hex_value.startswith("0x") else hex_value
509
+ return int(h, 16) if h else 0
510
+
511
+
512
+ __all__: List[str] = [
513
+ "PERMIT2_ADDRESS",
514
+ "X402_EXACT_PERMIT2_PROXY",
515
+ "CHAIN_ID",
516
+ "NETWORK",
517
+ "USDF_ADDRESS",
518
+ "USDG_ADDRESS",
519
+ "USDG_DOMAIN",
520
+ "GATEWAY_PAYEE",
521
+ "GATEWAY_ORIGIN",
522
+ "GATEWAY_CONFIG_URL",
523
+ "PAYEE_TTL_SECONDS",
524
+ "PUBLIC_RPC_URL",
525
+ "DEFAULT_MAX_AMOUNT",
526
+ "MAX_VALIDITY_SECONDS",
527
+ "PaymentLimits",
528
+ "payment_limits",
529
+ "named_payees",
530
+ "published_payees",
531
+ "is_gateway_origin",
532
+ "with_gateway_payees",
533
+ "known_asset",
534
+ "check_accept",
535
+ "rpc_chain_id",
536
+ "PERMIT2_WITNESS_TYPES",
537
+ "AUTHORIZATION_TYPES",
538
+ "Signer",
539
+ "EthAccountSigner",
540
+ "eth_account_signer",
541
+ "wallet_signer",
542
+ "rpc_call",
543
+ "read_permit2_allowance",
544
+ "approve_permit2",
545
+ "decode_payment_required",
546
+ "encode_payment_signature",
547
+ "decode_payment_response",
548
+ "transfer_method",
549
+ "choose_accept",
550
+ "chain_id_of",
551
+ "sign_exact_payment",
552
+ "permit2_approval_call",
553
+ "permit2_allowance_call",
554
+ "decode_uint256",
555
+ ]