uvd-x402-sdk 0.2.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.
- uvd_x402_sdk/__init__.py +169 -0
- uvd_x402_sdk/client.py +527 -0
- uvd_x402_sdk/config.py +249 -0
- uvd_x402_sdk/decorators.py +325 -0
- uvd_x402_sdk/exceptions.py +254 -0
- uvd_x402_sdk/integrations/__init__.py +74 -0
- uvd_x402_sdk/integrations/django_integration.py +237 -0
- uvd_x402_sdk/integrations/fastapi_integration.py +330 -0
- uvd_x402_sdk/integrations/flask_integration.py +259 -0
- uvd_x402_sdk/integrations/lambda_integration.py +320 -0
- uvd_x402_sdk/models.py +397 -0
- uvd_x402_sdk/networks/__init__.py +54 -0
- uvd_x402_sdk/networks/base.py +348 -0
- uvd_x402_sdk/networks/evm.py +235 -0
- uvd_x402_sdk/networks/near.py +397 -0
- uvd_x402_sdk/networks/solana.py +269 -0
- uvd_x402_sdk/networks/stellar.py +129 -0
- uvd_x402_sdk/response.py +439 -0
- uvd_x402_sdk-0.2.0.dist-info/LICENSE +21 -0
- uvd_x402_sdk-0.2.0.dist-info/METADATA +776 -0
- uvd_x402_sdk-0.2.0.dist-info/RECORD +23 -0
- uvd_x402_sdk-0.2.0.dist-info/WHEEL +5 -0
- uvd_x402_sdk-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Stellar network configuration.
|
|
3
|
+
|
|
4
|
+
Stellar uses Soroban smart contracts for USDC transfers:
|
|
5
|
+
1. User signs a SorobanAuthorizationEntry (XDR format)
|
|
6
|
+
2. Authorization contains transfer function invocation
|
|
7
|
+
3. Facilitator wraps in fee-bump transaction
|
|
8
|
+
4. Facilitator pays all XLM fees - user pays ZERO XLM
|
|
9
|
+
|
|
10
|
+
Stellar USDC Details:
|
|
11
|
+
- Uses SAC (Soroban Asset Contract) for the Circle-issued USDC
|
|
12
|
+
- 7 decimals (stroops), different from other chains (6 decimals)
|
|
13
|
+
- Freighter wallet required for signing (Bitget doesn't support Stellar)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from uvd_x402_sdk.networks.base import (
|
|
17
|
+
NetworkConfig,
|
|
18
|
+
NetworkType,
|
|
19
|
+
register_network,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# Stellar Mainnet
|
|
23
|
+
STELLAR = NetworkConfig(
|
|
24
|
+
name="stellar",
|
|
25
|
+
display_name="Stellar",
|
|
26
|
+
network_type=NetworkType.STELLAR,
|
|
27
|
+
chain_id=0, # Non-EVM, no chain ID
|
|
28
|
+
# Soroban Asset Contract (SAC) for USDC
|
|
29
|
+
usdc_address="CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75",
|
|
30
|
+
usdc_decimals=7, # Stellar uses 7 decimals (stroops)
|
|
31
|
+
usdc_domain_name="", # Not applicable for Stellar
|
|
32
|
+
usdc_domain_version="",
|
|
33
|
+
rpc_url="https://horizon.stellar.org",
|
|
34
|
+
enabled=True,
|
|
35
|
+
extra_config={
|
|
36
|
+
# Network passphrase for signing
|
|
37
|
+
"network_passphrase": "Public Global Stellar Network ; September 2015",
|
|
38
|
+
# Soroban RPC endpoint (different from Horizon)
|
|
39
|
+
"soroban_rpc_url": "https://mainnet.sorobanrpc.com",
|
|
40
|
+
# Block explorer
|
|
41
|
+
"explorer_url": "https://stellar.expert/explorer/public",
|
|
42
|
+
# Circle USDC issuer (G... address)
|
|
43
|
+
"usdc_issuer": "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN",
|
|
44
|
+
# Default ledger validity (~5 minutes, ~60 ledgers)
|
|
45
|
+
"default_ledger_validity": 60,
|
|
46
|
+
},
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
# Register Stellar network
|
|
50
|
+
register_network(STELLAR)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# =============================================================================
|
|
54
|
+
# Stellar-specific utilities
|
|
55
|
+
# =============================================================================
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def stroops_to_usd(stroops: int) -> float:
|
|
59
|
+
"""
|
|
60
|
+
Convert stroops (7 decimals) to USD amount.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
stroops: Amount in stroops
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
USD amount
|
|
67
|
+
"""
|
|
68
|
+
return stroops / 10_000_000
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def usd_to_stroops(usd: float) -> int:
|
|
72
|
+
"""
|
|
73
|
+
Convert USD amount to stroops (7 decimals).
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
usd: USD amount
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Amount in stroops
|
|
80
|
+
"""
|
|
81
|
+
return int(usd * 10_000_000)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_valid_stellar_address(address: str) -> bool:
|
|
85
|
+
"""
|
|
86
|
+
Validate a Stellar public key format.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
address: Stellar address to validate
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
True if valid G... address (56 characters, starts with G)
|
|
93
|
+
"""
|
|
94
|
+
return (
|
|
95
|
+
isinstance(address, str)
|
|
96
|
+
and len(address) == 56
|
|
97
|
+
and address.startswith("G")
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def is_valid_contract_address(address: str) -> bool:
|
|
102
|
+
"""
|
|
103
|
+
Validate a Soroban contract address format.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
address: Contract address to validate
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
True if valid C... address (56 characters, starts with C)
|
|
110
|
+
"""
|
|
111
|
+
return (
|
|
112
|
+
isinstance(address, str)
|
|
113
|
+
and len(address) == 56
|
|
114
|
+
and address.startswith("C")
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def calculate_expiration_ledger(current_ledger: int, validity_ledgers: int = 60) -> int:
|
|
119
|
+
"""
|
|
120
|
+
Calculate expiration ledger for authorization.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
current_ledger: Current ledger sequence from RPC
|
|
124
|
+
validity_ledgers: Number of ledgers the auth is valid (~5 minutes at 5s/ledger)
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
Expiration ledger number
|
|
128
|
+
"""
|
|
129
|
+
return current_ledger + validity_ledgers
|
uvd_x402_sdk/response.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HTTP 402 response helpers.
|
|
3
|
+
|
|
4
|
+
This module provides utilities for creating standard 402 Payment Required
|
|
5
|
+
responses that are compatible with both x402 v1 and v2 protocols.
|
|
6
|
+
|
|
7
|
+
v1 Response:
|
|
8
|
+
- JSON body with payment requirements
|
|
9
|
+
- X-Accept-Payment header
|
|
10
|
+
|
|
11
|
+
v2 Response:
|
|
12
|
+
- PAYMENT-REQUIRED header (base64-encoded JSON)
|
|
13
|
+
- PAYMENT-SIGNATURE header
|
|
14
|
+
- accepts array with multiple payment options
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from decimal import Decimal
|
|
18
|
+
from typing import Dict, List, Optional, Any, Union, Literal
|
|
19
|
+
|
|
20
|
+
from uvd_x402_sdk.config import X402Config
|
|
21
|
+
from uvd_x402_sdk.models import Payment402Response, PaymentOption, PaymentRequirementsV2
|
|
22
|
+
from uvd_x402_sdk.networks import (
|
|
23
|
+
get_network,
|
|
24
|
+
list_networks,
|
|
25
|
+
NetworkType,
|
|
26
|
+
get_supported_network_names,
|
|
27
|
+
to_caip2_network,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_402_response(
|
|
32
|
+
amount_usd: Union[Decimal, float, str],
|
|
33
|
+
config: X402Config,
|
|
34
|
+
message: Optional[str] = None,
|
|
35
|
+
resource_description: Optional[str] = None,
|
|
36
|
+
) -> Dict[str, Any]:
|
|
37
|
+
"""
|
|
38
|
+
Create a standard 402 Payment Required response body.
|
|
39
|
+
|
|
40
|
+
This response tells the client what payment is required and provides
|
|
41
|
+
all necessary information to create a payment authorization.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
amount_usd: Required payment amount in USD
|
|
45
|
+
config: X402Config with recipient addresses
|
|
46
|
+
message: Optional custom message (default: generated)
|
|
47
|
+
resource_description: Optional description of what's being purchased
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Dictionary suitable for JSON response body
|
|
51
|
+
|
|
52
|
+
Example:
|
|
53
|
+
>>> config = X402Config(recipient_evm="0x...")
|
|
54
|
+
>>> response_body = create_402_response(
|
|
55
|
+
... amount_usd=Decimal("10.00"),
|
|
56
|
+
... config=config,
|
|
57
|
+
... message="Payment required for API access"
|
|
58
|
+
... )
|
|
59
|
+
>>> return JSONResponse(status_code=402, content=response_body)
|
|
60
|
+
"""
|
|
61
|
+
amount = Decimal(str(amount_usd))
|
|
62
|
+
|
|
63
|
+
# Build recipients map
|
|
64
|
+
recipients: Dict[str, str] = {}
|
|
65
|
+
if config.recipient_evm:
|
|
66
|
+
recipients["evm"] = config.recipient_evm
|
|
67
|
+
if config.recipient_solana:
|
|
68
|
+
recipients["solana"] = config.recipient_solana
|
|
69
|
+
if config.recipient_near:
|
|
70
|
+
recipients["near"] = config.recipient_near
|
|
71
|
+
if config.recipient_stellar:
|
|
72
|
+
recipients["stellar"] = config.recipient_stellar
|
|
73
|
+
|
|
74
|
+
# Get supported chain IDs and network names
|
|
75
|
+
supported_chains: List[Union[int, str]] = []
|
|
76
|
+
|
|
77
|
+
for network_name in config.supported_networks:
|
|
78
|
+
network = get_network(network_name)
|
|
79
|
+
if network and network.enabled and config.is_network_enabled(network_name):
|
|
80
|
+
if network.network_type == NetworkType.EVM and network.chain_id > 0:
|
|
81
|
+
supported_chains.append(network.chain_id)
|
|
82
|
+
else:
|
|
83
|
+
# Non-EVM networks: include name
|
|
84
|
+
supported_chains.append(network_name)
|
|
85
|
+
|
|
86
|
+
# Default message
|
|
87
|
+
if not message:
|
|
88
|
+
message = f"Payment of ${amount} USDC required"
|
|
89
|
+
if resource_description:
|
|
90
|
+
message += f" for {resource_description}"
|
|
91
|
+
|
|
92
|
+
response = Payment402Response(
|
|
93
|
+
error="Payment required",
|
|
94
|
+
recipient=config.recipient_evm, # Default for backward compatibility
|
|
95
|
+
recipients=recipients if recipients else None,
|
|
96
|
+
facilitator=config.facilitator_solana,
|
|
97
|
+
amount=str(amount),
|
|
98
|
+
token="USDC",
|
|
99
|
+
supportedChains=supported_chains,
|
|
100
|
+
message=message,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
return response.model_dump(exclude_none=True, by_alias=True)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def create_402_headers(
|
|
107
|
+
accept_payment: str = "x402 USDC 1.0",
|
|
108
|
+
) -> Dict[str, str]:
|
|
109
|
+
"""
|
|
110
|
+
Create headers for a 402 response.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
accept_payment: Value for X-Accept-Payment header
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
Dictionary of headers
|
|
117
|
+
"""
|
|
118
|
+
return {
|
|
119
|
+
"Content-Type": "application/json",
|
|
120
|
+
"X-Accept-Payment": accept_payment,
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def payment_required_response(
|
|
125
|
+
amount_usd: Union[Decimal, float, str],
|
|
126
|
+
config: X402Config,
|
|
127
|
+
message: Optional[str] = None,
|
|
128
|
+
) -> tuple:
|
|
129
|
+
"""
|
|
130
|
+
Create a complete 402 response (body, headers, status code).
|
|
131
|
+
|
|
132
|
+
Useful for frameworks that accept tuple responses.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
amount_usd: Required payment amount
|
|
136
|
+
config: X402Config with recipient addresses
|
|
137
|
+
message: Optional custom message
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
Tuple of (body_dict, headers_dict, status_code)
|
|
141
|
+
|
|
142
|
+
Example (Flask):
|
|
143
|
+
>>> @app.route("/api/resource")
|
|
144
|
+
>>> def resource():
|
|
145
|
+
... if not has_payment:
|
|
146
|
+
... body, headers, status = payment_required_response(
|
|
147
|
+
... amount_usd="1.00", config=config
|
|
148
|
+
... )
|
|
149
|
+
... return body, status, headers
|
|
150
|
+
"""
|
|
151
|
+
body = create_402_response(amount_usd, config, message)
|
|
152
|
+
headers = create_402_headers()
|
|
153
|
+
return body, headers, 402
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class Payment402Builder:
|
|
157
|
+
"""
|
|
158
|
+
Builder class for constructing 402 responses with fluent API.
|
|
159
|
+
|
|
160
|
+
Example:
|
|
161
|
+
>>> response = (
|
|
162
|
+
... Payment402Builder(config)
|
|
163
|
+
... .amount(Decimal("5.00"))
|
|
164
|
+
... .message("Premium feature access required")
|
|
165
|
+
... .networks(["base", "solana"])
|
|
166
|
+
... .build()
|
|
167
|
+
... )
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def __init__(self, config: X402Config) -> None:
|
|
171
|
+
self._config = config
|
|
172
|
+
self._amount: Decimal = Decimal("1.00")
|
|
173
|
+
self._message: Optional[str] = None
|
|
174
|
+
self._description: Optional[str] = None
|
|
175
|
+
self._networks: Optional[List[str]] = None
|
|
176
|
+
self._extra_data: Dict[str, Any] = {}
|
|
177
|
+
|
|
178
|
+
def amount(self, usd: Union[Decimal, float, str]) -> "Payment402Builder":
|
|
179
|
+
"""Set the required payment amount in USD."""
|
|
180
|
+
self._amount = Decimal(str(usd))
|
|
181
|
+
return self
|
|
182
|
+
|
|
183
|
+
def message(self, msg: str) -> "Payment402Builder":
|
|
184
|
+
"""Set the payment message."""
|
|
185
|
+
self._message = msg
|
|
186
|
+
return self
|
|
187
|
+
|
|
188
|
+
def description(self, desc: str) -> "Payment402Builder":
|
|
189
|
+
"""Set the resource description."""
|
|
190
|
+
self._description = desc
|
|
191
|
+
return self
|
|
192
|
+
|
|
193
|
+
def networks(self, network_names: List[str]) -> "Payment402Builder":
|
|
194
|
+
"""Limit to specific networks."""
|
|
195
|
+
self._networks = network_names
|
|
196
|
+
return self
|
|
197
|
+
|
|
198
|
+
def extra(self, key: str, value: Any) -> "Payment402Builder":
|
|
199
|
+
"""Add extra data to the response."""
|
|
200
|
+
self._extra_data[key] = value
|
|
201
|
+
return self
|
|
202
|
+
|
|
203
|
+
def build(self) -> Dict[str, Any]:
|
|
204
|
+
"""Build the response body."""
|
|
205
|
+
# Create modified config if networks are limited
|
|
206
|
+
if self._networks:
|
|
207
|
+
limited_config = X402Config(
|
|
208
|
+
facilitator_url=self._config.facilitator_url,
|
|
209
|
+
recipient_evm=self._config.recipient_evm,
|
|
210
|
+
recipient_solana=self._config.recipient_solana,
|
|
211
|
+
recipient_near=self._config.recipient_near,
|
|
212
|
+
recipient_stellar=self._config.recipient_stellar,
|
|
213
|
+
facilitator_solana=self._config.facilitator_solana,
|
|
214
|
+
supported_networks=self._networks,
|
|
215
|
+
)
|
|
216
|
+
else:
|
|
217
|
+
limited_config = self._config
|
|
218
|
+
|
|
219
|
+
response = create_402_response(
|
|
220
|
+
amount_usd=self._amount,
|
|
221
|
+
config=limited_config,
|
|
222
|
+
message=self._message,
|
|
223
|
+
resource_description=self._description,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# Add extra data
|
|
227
|
+
response.update(self._extra_data)
|
|
228
|
+
|
|
229
|
+
return response
|
|
230
|
+
|
|
231
|
+
def build_tuple(self) -> tuple:
|
|
232
|
+
"""Build complete response tuple (body, headers, status)."""
|
|
233
|
+
return self.build(), create_402_headers(), 402
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# =============================================================================
|
|
237
|
+
# x402 v2 Response Helpers
|
|
238
|
+
# =============================================================================
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def create_402_response_v2(
|
|
242
|
+
amount_usd: Union[Decimal, float, str],
|
|
243
|
+
config: X402Config,
|
|
244
|
+
resource: str = "",
|
|
245
|
+
description: str = "",
|
|
246
|
+
networks: Optional[List[str]] = None,
|
|
247
|
+
) -> Dict[str, Any]:
|
|
248
|
+
"""
|
|
249
|
+
Create an x402 v2 format 402 response with accepts array.
|
|
250
|
+
|
|
251
|
+
x402 v2 uses CAIP-2 network identifiers and allows clients to
|
|
252
|
+
choose from multiple payment options.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
amount_usd: Required payment amount in USD
|
|
256
|
+
config: X402Config with recipient addresses
|
|
257
|
+
resource: Resource URL being purchased
|
|
258
|
+
description: Human-readable description
|
|
259
|
+
networks: List of networks to offer (default: all enabled)
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
Dictionary suitable for JSON response body
|
|
263
|
+
|
|
264
|
+
Example:
|
|
265
|
+
>>> response = create_402_response_v2(
|
|
266
|
+
... amount_usd=Decimal("5.00"),
|
|
267
|
+
... config=config,
|
|
268
|
+
... resource="/api/premium",
|
|
269
|
+
... description="Premium API access",
|
|
270
|
+
... )
|
|
271
|
+
"""
|
|
272
|
+
amount = Decimal(str(amount_usd))
|
|
273
|
+
|
|
274
|
+
# Determine which networks to include
|
|
275
|
+
if networks:
|
|
276
|
+
network_list = networks
|
|
277
|
+
else:
|
|
278
|
+
network_list = config.supported_networks
|
|
279
|
+
|
|
280
|
+
# Build accepts array
|
|
281
|
+
accepts: List[Dict[str, Any]] = []
|
|
282
|
+
|
|
283
|
+
for network_name in network_list:
|
|
284
|
+
network = get_network(network_name)
|
|
285
|
+
if not network or not network.enabled:
|
|
286
|
+
continue
|
|
287
|
+
if not config.is_network_enabled(network_name):
|
|
288
|
+
continue
|
|
289
|
+
|
|
290
|
+
# Get CAIP-2 format network ID
|
|
291
|
+
caip2_network = to_caip2_network(network_name)
|
|
292
|
+
if not caip2_network:
|
|
293
|
+
continue
|
|
294
|
+
|
|
295
|
+
# Get recipient for this network
|
|
296
|
+
recipient = config.get_recipient(network_name)
|
|
297
|
+
if not recipient:
|
|
298
|
+
continue
|
|
299
|
+
|
|
300
|
+
# Calculate amount in token base units
|
|
301
|
+
token_amount = network.get_token_amount(float(amount))
|
|
302
|
+
|
|
303
|
+
option: Dict[str, Any] = {
|
|
304
|
+
"network": caip2_network,
|
|
305
|
+
"asset": network.usdc_address,
|
|
306
|
+
"amount": str(token_amount),
|
|
307
|
+
"payTo": recipient,
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
# Add EIP-712 domain for EVM chains
|
|
311
|
+
if network.network_type == NetworkType.EVM:
|
|
312
|
+
option["extra"] = {
|
|
313
|
+
"name": network.usdc_domain_name,
|
|
314
|
+
"version": network.usdc_domain_version,
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
accepts.append(option)
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
"x402Version": 2,
|
|
321
|
+
"scheme": "exact",
|
|
322
|
+
"resource": resource or config.resource_url or "/api/resource",
|
|
323
|
+
"description": description or config.description,
|
|
324
|
+
"mimeType": "application/json",
|
|
325
|
+
"maxTimeoutSeconds": 60,
|
|
326
|
+
"accepts": accepts,
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def create_402_headers_v2(
|
|
331
|
+
requirements: Dict[str, Any],
|
|
332
|
+
) -> Dict[str, str]:
|
|
333
|
+
"""
|
|
334
|
+
Create headers for an x402 v2 402 response.
|
|
335
|
+
|
|
336
|
+
The PAYMENT-REQUIRED header contains base64-encoded JSON of the
|
|
337
|
+
payment requirements.
|
|
338
|
+
|
|
339
|
+
Args:
|
|
340
|
+
requirements: Payment requirements dictionary
|
|
341
|
+
|
|
342
|
+
Returns:
|
|
343
|
+
Dictionary of headers
|
|
344
|
+
"""
|
|
345
|
+
import base64
|
|
346
|
+
import json
|
|
347
|
+
|
|
348
|
+
requirements_json = json.dumps(requirements, separators=(',', ':'))
|
|
349
|
+
requirements_b64 = base64.b64encode(requirements_json.encode()).decode()
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
"Content-Type": "application/json",
|
|
353
|
+
"PAYMENT-REQUIRED": requirements_b64,
|
|
354
|
+
"X-Accept-Payment": "x402 USDC 2.0",
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def payment_required_response_v2(
|
|
359
|
+
amount_usd: Union[Decimal, float, str],
|
|
360
|
+
config: X402Config,
|
|
361
|
+
resource: str = "",
|
|
362
|
+
description: str = "",
|
|
363
|
+
networks: Optional[List[str]] = None,
|
|
364
|
+
) -> tuple:
|
|
365
|
+
"""
|
|
366
|
+
Create a complete x402 v2 402 response (body, headers, status code).
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
amount_usd: Required payment amount
|
|
370
|
+
config: X402Config with recipient addresses
|
|
371
|
+
resource: Resource URL
|
|
372
|
+
description: Description
|
|
373
|
+
networks: Networks to offer
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
Tuple of (body_dict, headers_dict, status_code)
|
|
377
|
+
"""
|
|
378
|
+
body = create_402_response_v2(amount_usd, config, resource, description, networks)
|
|
379
|
+
headers = create_402_headers_v2(body)
|
|
380
|
+
return body, headers, 402
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
class Payment402BuilderV2:
|
|
384
|
+
"""
|
|
385
|
+
Builder class for constructing x402 v2 402 responses.
|
|
386
|
+
|
|
387
|
+
Example:
|
|
388
|
+
>>> response = (
|
|
389
|
+
... Payment402BuilderV2(config)
|
|
390
|
+
... .amount(Decimal("5.00"))
|
|
391
|
+
... .resource("/api/premium")
|
|
392
|
+
... .description("Premium feature access")
|
|
393
|
+
... .networks(["base", "solana", "near"])
|
|
394
|
+
... .build()
|
|
395
|
+
... )
|
|
396
|
+
"""
|
|
397
|
+
|
|
398
|
+
def __init__(self, config: X402Config) -> None:
|
|
399
|
+
self._config = config
|
|
400
|
+
self._amount: Decimal = Decimal("1.00")
|
|
401
|
+
self._resource: str = ""
|
|
402
|
+
self._description: str = ""
|
|
403
|
+
self._networks: Optional[List[str]] = None
|
|
404
|
+
|
|
405
|
+
def amount(self, usd: Union[Decimal, float, str]) -> "Payment402BuilderV2":
|
|
406
|
+
"""Set the required payment amount in USD."""
|
|
407
|
+
self._amount = Decimal(str(usd))
|
|
408
|
+
return self
|
|
409
|
+
|
|
410
|
+
def resource(self, url: str) -> "Payment402BuilderV2":
|
|
411
|
+
"""Set the resource URL."""
|
|
412
|
+
self._resource = url
|
|
413
|
+
return self
|
|
414
|
+
|
|
415
|
+
def description(self, desc: str) -> "Payment402BuilderV2":
|
|
416
|
+
"""Set the resource description."""
|
|
417
|
+
self._description = desc
|
|
418
|
+
return self
|
|
419
|
+
|
|
420
|
+
def networks(self, network_names: List[str]) -> "Payment402BuilderV2":
|
|
421
|
+
"""Limit to specific networks."""
|
|
422
|
+
self._networks = network_names
|
|
423
|
+
return self
|
|
424
|
+
|
|
425
|
+
def build(self) -> Dict[str, Any]:
|
|
426
|
+
"""Build the v2 response body."""
|
|
427
|
+
return create_402_response_v2(
|
|
428
|
+
amount_usd=self._amount,
|
|
429
|
+
config=self._config,
|
|
430
|
+
resource=self._resource,
|
|
431
|
+
description=self._description,
|
|
432
|
+
networks=self._networks,
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
def build_with_headers(self) -> tuple:
|
|
436
|
+
"""Build complete response with headers (body, headers, status)."""
|
|
437
|
+
body = self.build()
|
|
438
|
+
headers = create_402_headers_v2(body)
|
|
439
|
+
return body, headers, 402
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Ultravioleta DAO
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|