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
uvd_x402_sdk/config.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SDK configuration classes.
|
|
3
|
+
|
|
4
|
+
This module provides configuration management for the x402 SDK,
|
|
5
|
+
including facilitator settings, recipient addresses, and timeouts.
|
|
6
|
+
|
|
7
|
+
Supports:
|
|
8
|
+
- x402 v1 and v2 protocols
|
|
9
|
+
- Multi-network payment options
|
|
10
|
+
- Per-network recipient configuration
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Dict, List, Optional, Any, Literal
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class NetworkRecipientConfig:
|
|
20
|
+
"""
|
|
21
|
+
Configuration for a specific network's recipient address.
|
|
22
|
+
|
|
23
|
+
Use this to specify different recipient addresses for different networks.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
recipient: str
|
|
27
|
+
enabled: bool = True
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# Alias for backward compatibility
|
|
31
|
+
NetworkConfig = NetworkRecipientConfig
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class MultiPaymentConfig:
|
|
36
|
+
"""
|
|
37
|
+
Configuration for multi-payment support.
|
|
38
|
+
|
|
39
|
+
Allows users to offer multiple networks for payment acceptance.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
networks: List[str] = field(default_factory=list)
|
|
43
|
+
default_network: Optional[str] = None
|
|
44
|
+
|
|
45
|
+
def __post_init__(self) -> None:
|
|
46
|
+
if self.networks and not self.default_network:
|
|
47
|
+
self.default_network = self.networks[0]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class X402Config:
|
|
52
|
+
"""
|
|
53
|
+
Main SDK configuration.
|
|
54
|
+
|
|
55
|
+
Attributes:
|
|
56
|
+
facilitator_url: URL of the x402 facilitator service
|
|
57
|
+
recipient_evm: Default recipient address for EVM chains
|
|
58
|
+
recipient_solana: Recipient address for Solana/SVM chains (also used for Fogo)
|
|
59
|
+
recipient_near: Recipient account for NEAR
|
|
60
|
+
recipient_stellar: Recipient address for Stellar
|
|
61
|
+
facilitator_solana: Solana/SVM facilitator address (fee payer)
|
|
62
|
+
verify_timeout: Timeout for verify requests (seconds)
|
|
63
|
+
settle_timeout: Timeout for settle requests (seconds)
|
|
64
|
+
supported_networks: List of enabled network names
|
|
65
|
+
network_configs: Per-network recipient overrides
|
|
66
|
+
resource_url: Resource URL sent to facilitator
|
|
67
|
+
description: Description sent to facilitator
|
|
68
|
+
x402_version: Protocol version to use (1, 2, or "auto")
|
|
69
|
+
multi_payment: Multi-payment configuration for accepting multiple networks
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
facilitator_url: str = "https://facilitator.ultravioletadao.xyz"
|
|
73
|
+
|
|
74
|
+
# Recipient addresses per network type
|
|
75
|
+
recipient_evm: str = ""
|
|
76
|
+
recipient_solana: str = "" # Also used for Fogo and other SVM chains
|
|
77
|
+
recipient_near: str = ""
|
|
78
|
+
recipient_stellar: str = ""
|
|
79
|
+
|
|
80
|
+
# Solana/SVM facilitator (fee payer) - same for all SVM chains
|
|
81
|
+
facilitator_solana: str = "F742C4VfFLQ9zRQyithoj5229ZgtX2WqKCSFKgH2EThq"
|
|
82
|
+
|
|
83
|
+
# Timeouts
|
|
84
|
+
verify_timeout: float = 30.0
|
|
85
|
+
settle_timeout: float = 55.0 # Must be < Lambda timeout (60s)
|
|
86
|
+
|
|
87
|
+
# Network configuration - All 15 networks (14 enabled by default)
|
|
88
|
+
supported_networks: List[str] = field(default_factory=lambda: [
|
|
89
|
+
# EVM chains (11 total, 10 enabled)
|
|
90
|
+
"base", "ethereum", "polygon", "arbitrum", "optimism",
|
|
91
|
+
"avalanche", "celo", "hyperevm", "unichain", "monad",
|
|
92
|
+
# bsc disabled: Binance-Peg USDC doesn't support ERC-3009
|
|
93
|
+
# SVM chains (2 total, 2 enabled)
|
|
94
|
+
"solana", "fogo",
|
|
95
|
+
# NEAR (1 total, 1 enabled)
|
|
96
|
+
"near",
|
|
97
|
+
# Stellar (1 total, 1 enabled)
|
|
98
|
+
"stellar",
|
|
99
|
+
])
|
|
100
|
+
|
|
101
|
+
# Per-network recipient overrides
|
|
102
|
+
network_configs: Dict[str, NetworkRecipientConfig] = field(default_factory=dict)
|
|
103
|
+
|
|
104
|
+
# Facilitator request metadata
|
|
105
|
+
resource_url: str = ""
|
|
106
|
+
description: str = "x402 payment"
|
|
107
|
+
|
|
108
|
+
# x402 protocol version: 1, 2, or "auto" (detect from payload)
|
|
109
|
+
x402_version: Literal[1, 2, "auto"] = "auto"
|
|
110
|
+
|
|
111
|
+
# Multi-payment configuration
|
|
112
|
+
multi_payment: Optional[MultiPaymentConfig] = None
|
|
113
|
+
|
|
114
|
+
def __post_init__(self) -> None:
|
|
115
|
+
"""Validate configuration after initialization."""
|
|
116
|
+
if not self.facilitator_url:
|
|
117
|
+
raise ValueError("facilitator_url is required")
|
|
118
|
+
|
|
119
|
+
# At least one recipient is required
|
|
120
|
+
if not any([
|
|
121
|
+
self.recipient_evm,
|
|
122
|
+
self.recipient_solana,
|
|
123
|
+
self.recipient_near,
|
|
124
|
+
self.recipient_stellar,
|
|
125
|
+
]):
|
|
126
|
+
raise ValueError("At least one recipient address is required")
|
|
127
|
+
|
|
128
|
+
@classmethod
|
|
129
|
+
def from_env(cls) -> "X402Config":
|
|
130
|
+
"""
|
|
131
|
+
Create configuration from environment variables.
|
|
132
|
+
|
|
133
|
+
Environment variables:
|
|
134
|
+
X402_FACILITATOR_URL: Facilitator URL
|
|
135
|
+
X402_RECIPIENT_EVM: EVM recipient address
|
|
136
|
+
X402_RECIPIENT_SOLANA: Solana recipient address
|
|
137
|
+
X402_RECIPIENT_NEAR: NEAR recipient account
|
|
138
|
+
X402_RECIPIENT_STELLAR: Stellar recipient address
|
|
139
|
+
X402_FACILITATOR_SOLANA: Solana fee payer address
|
|
140
|
+
X402_VERIFY_TIMEOUT: Verify request timeout
|
|
141
|
+
X402_SETTLE_TIMEOUT: Settle request timeout
|
|
142
|
+
X402_RESOURCE_URL: Resource URL for facilitator
|
|
143
|
+
X402_DESCRIPTION: Description for facilitator
|
|
144
|
+
"""
|
|
145
|
+
return cls(
|
|
146
|
+
facilitator_url=os.environ.get(
|
|
147
|
+
"X402_FACILITATOR_URL",
|
|
148
|
+
"https://facilitator.ultravioletadao.xyz",
|
|
149
|
+
),
|
|
150
|
+
recipient_evm=os.environ.get("X402_RECIPIENT_EVM", ""),
|
|
151
|
+
recipient_solana=os.environ.get("X402_RECIPIENT_SOLANA", ""),
|
|
152
|
+
recipient_near=os.environ.get("X402_RECIPIENT_NEAR", ""),
|
|
153
|
+
recipient_stellar=os.environ.get("X402_RECIPIENT_STELLAR", ""),
|
|
154
|
+
facilitator_solana=os.environ.get(
|
|
155
|
+
"X402_FACILITATOR_SOLANA",
|
|
156
|
+
"F742C4VfFLQ9zRQyithoj5229ZgtX2WqKCSFKgH2EThq",
|
|
157
|
+
),
|
|
158
|
+
verify_timeout=float(os.environ.get("X402_VERIFY_TIMEOUT", "30")),
|
|
159
|
+
settle_timeout=float(os.environ.get("X402_SETTLE_TIMEOUT", "55")),
|
|
160
|
+
resource_url=os.environ.get("X402_RESOURCE_URL", ""),
|
|
161
|
+
description=os.environ.get("X402_DESCRIPTION", "x402 payment"),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def get_recipient(self, network: str) -> str:
|
|
165
|
+
"""
|
|
166
|
+
Get recipient address for a specific network.
|
|
167
|
+
|
|
168
|
+
First checks network_configs for overrides, then falls back to
|
|
169
|
+
network-type default.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
network: Network name (e.g., 'base', 'solana', 'fogo')
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
Recipient address for the network
|
|
176
|
+
"""
|
|
177
|
+
# Check for network-specific override
|
|
178
|
+
if network in self.network_configs:
|
|
179
|
+
return self.network_configs[network].recipient
|
|
180
|
+
|
|
181
|
+
# Fall back to network-type default
|
|
182
|
+
from uvd_x402_sdk.networks import get_network, NetworkType
|
|
183
|
+
|
|
184
|
+
network_config = get_network(network)
|
|
185
|
+
if not network_config:
|
|
186
|
+
return self.recipient_evm # Default to EVM
|
|
187
|
+
|
|
188
|
+
# SVM chains (Solana, Fogo, etc.) use the same recipient
|
|
189
|
+
if NetworkType.is_svm(network_config.network_type):
|
|
190
|
+
return self.recipient_solana
|
|
191
|
+
elif network_config.network_type == NetworkType.NEAR:
|
|
192
|
+
return self.recipient_near
|
|
193
|
+
elif network_config.network_type == NetworkType.STELLAR:
|
|
194
|
+
return self.recipient_stellar
|
|
195
|
+
else:
|
|
196
|
+
return self.recipient_evm
|
|
197
|
+
|
|
198
|
+
def is_network_enabled(self, network: str) -> bool:
|
|
199
|
+
"""
|
|
200
|
+
Check if a network is enabled.
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
network: Network name
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
True if network is in supported_networks and not disabled
|
|
207
|
+
"""
|
|
208
|
+
if network not in self.supported_networks:
|
|
209
|
+
return False
|
|
210
|
+
|
|
211
|
+
# Check network-specific config
|
|
212
|
+
if network in self.network_configs:
|
|
213
|
+
return self.network_configs[network].enabled
|
|
214
|
+
|
|
215
|
+
return True
|
|
216
|
+
|
|
217
|
+
def get_supported_chain_ids(self) -> List[int]:
|
|
218
|
+
"""
|
|
219
|
+
Get list of supported EVM chain IDs.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
List of chain IDs for enabled EVM networks
|
|
223
|
+
"""
|
|
224
|
+
from uvd_x402_sdk.networks import get_network, NetworkType
|
|
225
|
+
|
|
226
|
+
chain_ids = []
|
|
227
|
+
for network_name in self.supported_networks:
|
|
228
|
+
network = get_network(network_name)
|
|
229
|
+
if network and network.network_type == NetworkType.EVM and network.chain_id > 0:
|
|
230
|
+
if self.is_network_enabled(network_name):
|
|
231
|
+
chain_ids.append(network.chain_id)
|
|
232
|
+
|
|
233
|
+
return chain_ids
|
|
234
|
+
|
|
235
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
236
|
+
"""Convert configuration to dictionary."""
|
|
237
|
+
return {
|
|
238
|
+
"facilitator_url": self.facilitator_url,
|
|
239
|
+
"recipient_evm": self.recipient_evm,
|
|
240
|
+
"recipient_solana": self.recipient_solana,
|
|
241
|
+
"recipient_near": self.recipient_near,
|
|
242
|
+
"recipient_stellar": self.recipient_stellar,
|
|
243
|
+
"facilitator_solana": self.facilitator_solana,
|
|
244
|
+
"verify_timeout": self.verify_timeout,
|
|
245
|
+
"settle_timeout": self.settle_timeout,
|
|
246
|
+
"supported_networks": self.supported_networks,
|
|
247
|
+
"resource_url": self.resource_url,
|
|
248
|
+
"description": self.description,
|
|
249
|
+
}
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Decorators for protecting endpoints with x402 payments.
|
|
3
|
+
|
|
4
|
+
These decorators provide a clean, declarative way to require payment
|
|
5
|
+
for specific endpoints across different web frameworks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from functools import wraps
|
|
10
|
+
from typing import Any, Callable, Optional, TypeVar, Union, Dict
|
|
11
|
+
|
|
12
|
+
from uvd_x402_sdk.config import X402Config
|
|
13
|
+
from uvd_x402_sdk.client import X402Client
|
|
14
|
+
from uvd_x402_sdk.exceptions import (
|
|
15
|
+
X402Error,
|
|
16
|
+
PaymentRequiredError,
|
|
17
|
+
InvalidPayloadError,
|
|
18
|
+
)
|
|
19
|
+
from uvd_x402_sdk.response import create_402_response, create_402_headers
|
|
20
|
+
|
|
21
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
22
|
+
|
|
23
|
+
# Global client instance (set by configure_x402)
|
|
24
|
+
_global_client: Optional[X402Client] = None
|
|
25
|
+
_global_config: Optional[X402Config] = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def configure_x402(
|
|
29
|
+
config: Optional[X402Config] = None,
|
|
30
|
+
recipient_address: Optional[str] = None,
|
|
31
|
+
facilitator_url: str = "https://facilitator.ultravioletadao.xyz",
|
|
32
|
+
**kwargs: Any,
|
|
33
|
+
) -> None:
|
|
34
|
+
"""
|
|
35
|
+
Configure the global x402 client for decorator usage.
|
|
36
|
+
|
|
37
|
+
Call this once during application startup to set up the x402 client
|
|
38
|
+
that decorators will use.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
config: Full X402Config object
|
|
42
|
+
recipient_address: Default recipient for EVM chains
|
|
43
|
+
facilitator_url: Facilitator service URL
|
|
44
|
+
**kwargs: Additional config parameters
|
|
45
|
+
|
|
46
|
+
Example:
|
|
47
|
+
>>> from uvd_x402_sdk import configure_x402
|
|
48
|
+
>>> configure_x402(
|
|
49
|
+
... recipient_address="0xYourWallet...",
|
|
50
|
+
... facilitator_url="https://facilitator.ultravioletadao.xyz"
|
|
51
|
+
... )
|
|
52
|
+
"""
|
|
53
|
+
global _global_client, _global_config
|
|
54
|
+
|
|
55
|
+
if config:
|
|
56
|
+
_global_config = config
|
|
57
|
+
else:
|
|
58
|
+
_global_config = X402Config(
|
|
59
|
+
facilitator_url=facilitator_url,
|
|
60
|
+
recipient_evm=recipient_address or "",
|
|
61
|
+
**kwargs,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
_global_client = X402Client(config=_global_config)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_x402_client() -> X402Client:
|
|
68
|
+
"""Get the global x402 client instance."""
|
|
69
|
+
if _global_client is None:
|
|
70
|
+
raise RuntimeError(
|
|
71
|
+
"x402 not configured. Call configure_x402() during application startup."
|
|
72
|
+
)
|
|
73
|
+
return _global_client
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_x402_config() -> X402Config:
|
|
77
|
+
"""Get the global x402 config instance."""
|
|
78
|
+
if _global_config is None:
|
|
79
|
+
raise RuntimeError(
|
|
80
|
+
"x402 not configured. Call configure_x402() during application startup."
|
|
81
|
+
)
|
|
82
|
+
return _global_config
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def require_payment(
|
|
86
|
+
amount_usd: Union[Decimal, float, str],
|
|
87
|
+
amount_callback: Optional[Callable[..., Decimal]] = None,
|
|
88
|
+
networks: Optional[list] = None,
|
|
89
|
+
message: Optional[str] = None,
|
|
90
|
+
inject_result: bool = True,
|
|
91
|
+
header_name: str = "X-PAYMENT",
|
|
92
|
+
) -> Callable[[F], F]:
|
|
93
|
+
"""
|
|
94
|
+
Decorator that requires x402 payment for an endpoint.
|
|
95
|
+
|
|
96
|
+
This is the main decorator for protecting endpoints with payments.
|
|
97
|
+
It handles the complete payment flow:
|
|
98
|
+
1. Check for X-PAYMENT header
|
|
99
|
+
2. If missing, return 402 Payment Required
|
|
100
|
+
3. If present, verify and settle payment
|
|
101
|
+
4. Optionally inject PaymentResult into function
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
amount_usd: Fixed payment amount in USD (or use amount_callback)
|
|
105
|
+
amount_callback: Callable that returns dynamic amount based on request
|
|
106
|
+
networks: Limit to specific networks (default: all enabled)
|
|
107
|
+
message: Custom message for 402 response
|
|
108
|
+
inject_result: Whether to inject PaymentResult as 'payment_result' kwarg
|
|
109
|
+
header_name: Header name for payment (default: X-PAYMENT)
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
Decorated function
|
|
113
|
+
|
|
114
|
+
Example (Flask):
|
|
115
|
+
>>> @app.route("/api/premium")
|
|
116
|
+
>>> @require_payment(amount_usd=Decimal("1.00"))
|
|
117
|
+
>>> def premium_endpoint(payment_result=None):
|
|
118
|
+
... return {"message": f"Paid by {payment_result.payer_address}"}
|
|
119
|
+
|
|
120
|
+
Example (Dynamic pricing):
|
|
121
|
+
>>> def calculate_price(request):
|
|
122
|
+
... items = request.json.get("items", 1)
|
|
123
|
+
... return Decimal(str(items * 0.10))
|
|
124
|
+
>>>
|
|
125
|
+
>>> @require_payment(amount_callback=calculate_price)
|
|
126
|
+
>>> def dynamic_endpoint(payment_result=None):
|
|
127
|
+
... return {"message": "Success"}
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def decorator(func: F) -> F:
|
|
131
|
+
@wraps(func)
|
|
132
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
133
|
+
# Get client and config
|
|
134
|
+
client = get_x402_client()
|
|
135
|
+
config = get_x402_config()
|
|
136
|
+
|
|
137
|
+
# Framework-agnostic request extraction
|
|
138
|
+
# This will be overridden by framework-specific integrations
|
|
139
|
+
request = _extract_request(*args, **kwargs)
|
|
140
|
+
payment_header = _get_header(request, header_name)
|
|
141
|
+
|
|
142
|
+
# Determine amount
|
|
143
|
+
if amount_callback:
|
|
144
|
+
required_amount = Decimal(str(amount_callback(request)))
|
|
145
|
+
else:
|
|
146
|
+
required_amount = Decimal(str(amount_usd))
|
|
147
|
+
|
|
148
|
+
# No payment header - return 402
|
|
149
|
+
if not payment_header:
|
|
150
|
+
response_body = create_402_response(
|
|
151
|
+
amount_usd=required_amount,
|
|
152
|
+
config=config,
|
|
153
|
+
message=message,
|
|
154
|
+
)
|
|
155
|
+
return _create_402_response(response_body)
|
|
156
|
+
|
|
157
|
+
# Process payment
|
|
158
|
+
try:
|
|
159
|
+
result = client.process_payment(
|
|
160
|
+
x_payment_header=payment_header,
|
|
161
|
+
expected_amount_usd=required_amount,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
# Inject result if requested
|
|
165
|
+
if inject_result:
|
|
166
|
+
kwargs["payment_result"] = result
|
|
167
|
+
|
|
168
|
+
return func(*args, **kwargs)
|
|
169
|
+
|
|
170
|
+
except X402Error as e:
|
|
171
|
+
# Return appropriate error response
|
|
172
|
+
return _create_error_response(e, required_amount, config)
|
|
173
|
+
|
|
174
|
+
return wrapper # type: ignore
|
|
175
|
+
|
|
176
|
+
return decorator
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# Alias for backward compatibility and preference
|
|
180
|
+
x402_required = require_payment
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _extract_request(*args: Any, **kwargs: Any) -> Any:
|
|
184
|
+
"""
|
|
185
|
+
Extract request object from function arguments.
|
|
186
|
+
|
|
187
|
+
This is a framework-agnostic implementation that works with:
|
|
188
|
+
- Flask (request from flask.globals)
|
|
189
|
+
- FastAPI/Starlette (request in kwargs)
|
|
190
|
+
- Django (request as first arg)
|
|
191
|
+
- AWS Lambda (event dict as first arg)
|
|
192
|
+
"""
|
|
193
|
+
# Check kwargs first
|
|
194
|
+
if "request" in kwargs:
|
|
195
|
+
return kwargs["request"]
|
|
196
|
+
|
|
197
|
+
# Check first positional arg
|
|
198
|
+
if args:
|
|
199
|
+
return args[0]
|
|
200
|
+
|
|
201
|
+
# Try Flask global
|
|
202
|
+
try:
|
|
203
|
+
from flask import request
|
|
204
|
+
return request
|
|
205
|
+
except ImportError:
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
# No request found
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _get_header(request: Any, header_name: str) -> Optional[str]:
|
|
213
|
+
"""
|
|
214
|
+
Get header value from request object.
|
|
215
|
+
|
|
216
|
+
Handles different frameworks' request objects.
|
|
217
|
+
"""
|
|
218
|
+
if request is None:
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
# Dict-like (AWS Lambda event)
|
|
222
|
+
if isinstance(request, dict):
|
|
223
|
+
headers = request.get("headers", {})
|
|
224
|
+
# Lambda headers can be case-sensitive or not
|
|
225
|
+
return headers.get(header_name) or headers.get(header_name.lower())
|
|
226
|
+
|
|
227
|
+
# Flask/Werkzeug
|
|
228
|
+
if hasattr(request, "headers"):
|
|
229
|
+
headers = request.headers
|
|
230
|
+
if hasattr(headers, "get"):
|
|
231
|
+
return headers.get(header_name)
|
|
232
|
+
|
|
233
|
+
# Django
|
|
234
|
+
if hasattr(request, "META"):
|
|
235
|
+
# Django uses HTTP_X_PAYMENT format
|
|
236
|
+
django_header = f"HTTP_{header_name.replace('-', '_').upper()}"
|
|
237
|
+
return request.META.get(django_header)
|
|
238
|
+
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _create_402_response(body: Dict[str, Any]) -> Any:
|
|
243
|
+
"""
|
|
244
|
+
Create a 402 response appropriate for the current framework.
|
|
245
|
+
|
|
246
|
+
This is a fallback that returns a tuple. Framework-specific
|
|
247
|
+
integrations override this.
|
|
248
|
+
"""
|
|
249
|
+
# Try Flask
|
|
250
|
+
try:
|
|
251
|
+
from flask import jsonify, make_response
|
|
252
|
+
response = make_response(jsonify(body), 402)
|
|
253
|
+
for key, value in create_402_headers().items():
|
|
254
|
+
response.headers[key] = value
|
|
255
|
+
return response
|
|
256
|
+
except ImportError:
|
|
257
|
+
pass
|
|
258
|
+
|
|
259
|
+
# Try FastAPI/Starlette
|
|
260
|
+
try:
|
|
261
|
+
from starlette.responses import JSONResponse
|
|
262
|
+
return JSONResponse(
|
|
263
|
+
status_code=402,
|
|
264
|
+
content=body,
|
|
265
|
+
headers=create_402_headers(),
|
|
266
|
+
)
|
|
267
|
+
except ImportError:
|
|
268
|
+
pass
|
|
269
|
+
|
|
270
|
+
# Try Django
|
|
271
|
+
try:
|
|
272
|
+
from django.http import JsonResponse
|
|
273
|
+
response = JsonResponse(body, status=402)
|
|
274
|
+
for key, value in create_402_headers().items():
|
|
275
|
+
response[key] = value
|
|
276
|
+
return response
|
|
277
|
+
except ImportError:
|
|
278
|
+
pass
|
|
279
|
+
|
|
280
|
+
# Fallback: return dict (for AWS Lambda or raw WSGI)
|
|
281
|
+
return {
|
|
282
|
+
"statusCode": 402,
|
|
283
|
+
"headers": {
|
|
284
|
+
"Content-Type": "application/json",
|
|
285
|
+
**create_402_headers(),
|
|
286
|
+
},
|
|
287
|
+
"body": body,
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _create_error_response(
|
|
292
|
+
error: X402Error,
|
|
293
|
+
amount: Decimal,
|
|
294
|
+
config: X402Config,
|
|
295
|
+
) -> Any:
|
|
296
|
+
"""Create an error response for x402 errors."""
|
|
297
|
+
# Payment verification/settlement failed - return 402
|
|
298
|
+
if isinstance(error, (PaymentRequiredError, InvalidPayloadError)):
|
|
299
|
+
body = create_402_response(amount_usd=amount, config=config)
|
|
300
|
+
body["error"] = error.message
|
|
301
|
+
body["details"] = error.details
|
|
302
|
+
return _create_402_response(body)
|
|
303
|
+
|
|
304
|
+
# Other errors - return 400
|
|
305
|
+
body = error.to_dict()
|
|
306
|
+
|
|
307
|
+
try:
|
|
308
|
+
from flask import jsonify, make_response
|
|
309
|
+
return make_response(jsonify(body), 400)
|
|
310
|
+
except ImportError:
|
|
311
|
+
pass
|
|
312
|
+
|
|
313
|
+
try:
|
|
314
|
+
from starlette.responses import JSONResponse
|
|
315
|
+
return JSONResponse(status_code=400, content=body)
|
|
316
|
+
except ImportError:
|
|
317
|
+
pass
|
|
318
|
+
|
|
319
|
+
try:
|
|
320
|
+
from django.http import JsonResponse
|
|
321
|
+
return JsonResponse(body, status=400)
|
|
322
|
+
except ImportError:
|
|
323
|
+
pass
|
|
324
|
+
|
|
325
|
+
return {"statusCode": 400, "body": body}
|