uvd-x402-sdk 0.2.2__py3-none-any.whl → 0.2.3__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/response.py CHANGED
@@ -1,439 +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
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