x402-algorand 0.1.0__tar.gz

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.
Files changed (101) hide show
  1. x402_algorand-0.1.0/PKG-INFO +14 -0
  2. x402_algorand-0.1.0/pyproject.toml +24 -0
  3. x402_algorand-0.1.0/setup.cfg +4 -0
  4. x402_algorand-0.1.0/x402/__init__.py +224 -0
  5. x402_algorand-0.1.0/x402/client.py +347 -0
  6. x402_algorand-0.1.0/x402/client_base.py +410 -0
  7. x402_algorand-0.1.0/x402/extensions/__init__.py +68 -0
  8. x402_algorand-0.1.0/x402/extensions/bazaar/__init__.py +135 -0
  9. x402_algorand-0.1.0/x402/extensions/bazaar/facilitator.py +322 -0
  10. x402_algorand-0.1.0/x402/extensions/bazaar/facilitator_client.py +245 -0
  11. x402_algorand-0.1.0/x402/extensions/bazaar/resource_service.py +271 -0
  12. x402_algorand-0.1.0/x402/extensions/bazaar/server.py +114 -0
  13. x402_algorand-0.1.0/x402/extensions/bazaar/types.py +158 -0
  14. x402_algorand-0.1.0/x402/extensions/bazaar/v1/__init__.py +19 -0
  15. x402_algorand-0.1.0/x402/extensions/bazaar/v1/facilitator.py +277 -0
  16. x402_algorand-0.1.0/x402/facilitator.py +352 -0
  17. x402_algorand-0.1.0/x402/facilitator_base.py +570 -0
  18. x402_algorand-0.1.0/x402/http/__init__.py +128 -0
  19. x402_algorand-0.1.0/x402/http/clients/__init__.py +68 -0
  20. x402_algorand-0.1.0/x402/http/clients/httpx.py +327 -0
  21. x402_algorand-0.1.0/x402/http/clients/requests.py +314 -0
  22. x402_algorand-0.1.0/x402/http/constants.py +15 -0
  23. x402_algorand-0.1.0/x402/http/facilitator_client.py +484 -0
  24. x402_algorand-0.1.0/x402/http/facilitator_client_base.py +224 -0
  25. x402_algorand-0.1.0/x402/http/middleware/__init__.py +72 -0
  26. x402_algorand-0.1.0/x402/http/middleware/fastapi.py +462 -0
  27. x402_algorand-0.1.0/x402/http/middleware/flask.py +527 -0
  28. x402_algorand-0.1.0/x402/http/paywall/__init__.py +529 -0
  29. x402_algorand-0.1.0/x402/http/paywall/avm_paywall_template.py +2 -0
  30. x402_algorand-0.1.0/x402/http/paywall/evm_paywall_template.py +2 -0
  31. x402_algorand-0.1.0/x402/http/paywall/svm_paywall_template.py +2 -0
  32. x402_algorand-0.1.0/x402/http/types.py +213 -0
  33. x402_algorand-0.1.0/x402/http/utils.py +127 -0
  34. x402_algorand-0.1.0/x402/http/x402_http_client.py +248 -0
  35. x402_algorand-0.1.0/x402/http/x402_http_client_base.py +151 -0
  36. x402_algorand-0.1.0/x402/http/x402_http_server.py +383 -0
  37. x402_algorand-0.1.0/x402/http/x402_http_server_base.py +728 -0
  38. x402_algorand-0.1.0/x402/interfaces.py +314 -0
  39. x402_algorand-0.1.0/x402/mechanisms/avm/__init__.py +158 -0
  40. x402_algorand-0.1.0/x402/mechanisms/avm/constants.py +181 -0
  41. x402_algorand-0.1.0/x402/mechanisms/avm/exact/__init__.py +64 -0
  42. x402_algorand-0.1.0/x402/mechanisms/avm/exact/client.py +213 -0
  43. x402_algorand-0.1.0/x402/mechanisms/avm/exact/facilitator.py +437 -0
  44. x402_algorand-0.1.0/x402/mechanisms/avm/exact/register.py +135 -0
  45. x402_algorand-0.1.0/x402/mechanisms/avm/exact/server.py +197 -0
  46. x402_algorand-0.1.0/x402/mechanisms/avm/exact/v1/__init__.py +20 -0
  47. x402_algorand-0.1.0/x402/mechanisms/avm/exact/v1/client.py +87 -0
  48. x402_algorand-0.1.0/x402/mechanisms/avm/exact/v1/facilitator.py +203 -0
  49. x402_algorand-0.1.0/x402/mechanisms/avm/signer.py +174 -0
  50. x402_algorand-0.1.0/x402/mechanisms/avm/types.py +138 -0
  51. x402_algorand-0.1.0/x402/mechanisms/avm/utils.py +649 -0
  52. x402_algorand-0.1.0/x402/mechanisms/evm/__init__.py +184 -0
  53. x402_algorand-0.1.0/x402/mechanisms/evm/constants.py +287 -0
  54. x402_algorand-0.1.0/x402/mechanisms/evm/eip712.py +251 -0
  55. x402_algorand-0.1.0/x402/mechanisms/evm/erc6492.py +103 -0
  56. x402_algorand-0.1.0/x402/mechanisms/evm/exact/__init__.py +25 -0
  57. x402_algorand-0.1.0/x402/mechanisms/evm/exact/client.py +127 -0
  58. x402_algorand-0.1.0/x402/mechanisms/evm/exact/facilitator.py +407 -0
  59. x402_algorand-0.1.0/x402/mechanisms/evm/exact/register.py +139 -0
  60. x402_algorand-0.1.0/x402/mechanisms/evm/exact/server.py +160 -0
  61. x402_algorand-0.1.0/x402/mechanisms/evm/exact/v1/__init__.py +15 -0
  62. x402_algorand-0.1.0/x402/mechanisms/evm/exact/v1/client.py +131 -0
  63. x402_algorand-0.1.0/x402/mechanisms/evm/exact/v1/facilitator.py +364 -0
  64. x402_algorand-0.1.0/x402/mechanisms/evm/signer.py +178 -0
  65. x402_algorand-0.1.0/x402/mechanisms/evm/signers.py +433 -0
  66. x402_algorand-0.1.0/x402/mechanisms/evm/types.py +131 -0
  67. x402_algorand-0.1.0/x402/mechanisms/evm/utils.py +293 -0
  68. x402_algorand-0.1.0/x402/mechanisms/evm/verify.py +161 -0
  69. x402_algorand-0.1.0/x402/mechanisms/svm/__init__.py +152 -0
  70. x402_algorand-0.1.0/x402/mechanisms/svm/constants.py +133 -0
  71. x402_algorand-0.1.0/x402/mechanisms/svm/exact/__init__.py +23 -0
  72. x402_algorand-0.1.0/x402/mechanisms/svm/exact/client.py +209 -0
  73. x402_algorand-0.1.0/x402/mechanisms/svm/exact/facilitator.py +363 -0
  74. x402_algorand-0.1.0/x402/mechanisms/svm/exact/register.py +135 -0
  75. x402_algorand-0.1.0/x402/mechanisms/svm/exact/server.py +148 -0
  76. x402_algorand-0.1.0/x402/mechanisms/svm/exact/v1/__init__.py +13 -0
  77. x402_algorand-0.1.0/x402/mechanisms/svm/exact/v1/client.py +201 -0
  78. x402_algorand-0.1.0/x402/mechanisms/svm/exact/v1/facilitator.py +339 -0
  79. x402_algorand-0.1.0/x402/mechanisms/svm/signer.py +128 -0
  80. x402_algorand-0.1.0/x402/mechanisms/svm/signers.py +313 -0
  81. x402_algorand-0.1.0/x402/mechanisms/svm/types.py +55 -0
  82. x402_algorand-0.1.0/x402/mechanisms/svm/utils.py +351 -0
  83. x402_algorand-0.1.0/x402/py.typed +0 -0
  84. x402_algorand-0.1.0/x402/schemas/__init__.py +173 -0
  85. x402_algorand-0.1.0/x402/schemas/base.py +49 -0
  86. x402_algorand-0.1.0/x402/schemas/config.py +64 -0
  87. x402_algorand-0.1.0/x402/schemas/errors.py +81 -0
  88. x402_algorand-0.1.0/x402/schemas/extensions.py +32 -0
  89. x402_algorand-0.1.0/x402/schemas/helpers.py +274 -0
  90. x402_algorand-0.1.0/x402/schemas/hooks.py +213 -0
  91. x402_algorand-0.1.0/x402/schemas/payments.py +95 -0
  92. x402_algorand-0.1.0/x402/schemas/responses.py +98 -0
  93. x402_algorand-0.1.0/x402/schemas/v1.py +96 -0
  94. x402_algorand-0.1.0/x402/schemas/views.py +90 -0
  95. x402_algorand-0.1.0/x402/server.py +445 -0
  96. x402_algorand-0.1.0/x402/server_base.py +601 -0
  97. x402_algorand-0.1.0/x402_algorand.egg-info/PKG-INFO +14 -0
  98. x402_algorand-0.1.0/x402_algorand.egg-info/SOURCES.txt +99 -0
  99. x402_algorand-0.1.0/x402_algorand.egg-info/dependency_links.txt +1 -0
  100. x402_algorand-0.1.0/x402_algorand.egg-info/requires.txt +4 -0
  101. x402_algorand-0.1.0/x402_algorand.egg-info/top_level.txt +1 -0
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: x402-algorand
3
+ Version: 0.1.0
4
+ Summary: Algorand AVM extensions for the x402 payment protocol.
5
+ Author-email: AI Economy Team <team@aieconomy.com>
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: py-algorand-sdk>=2.0.0
12
+ Requires-Dist: pydantic>=2.0.0
13
+ Requires-Dist: fastapi>=0.95.0
14
+ Requires-Dist: httpx>=0.20.0
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "x402-algorand"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name="AI Economy Team", email="team@aieconomy.com" },
10
+ ]
11
+ description = "Algorand AVM extensions for the x402 payment protocol."
12
+ requires-python = ">=3.9"
13
+ license = { text = "MIT" }
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "py-algorand-sdk>=2.0.0",
21
+ "pydantic>=2.0.0",
22
+ "fastapi>=0.95.0",
23
+ "httpx>=0.20.0"
24
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,224 @@
1
+ """x402 Python SDK - Payment protocol implementation.
2
+
3
+ This SDK provides client-side, server-side, and facilitator components
4
+ for implementing the x402 payment protocol.
5
+
6
+ Both async (default) and sync variants are available:
7
+ - x402Client / x402ClientSync
8
+ - x402ResourceServer / x402ResourceServerSync
9
+ - x402Facilitator / x402FacilitatorSync
10
+
11
+ Quick Start (Async - Recommended):
12
+ ```python
13
+ from x402 import x402Client, x402ResourceServer, x402Facilitator
14
+
15
+ # Client-side: Create payment payloads
16
+ client = x402Client()
17
+ client.register("eip155:8453", ExactEvmScheme(signer=my_signer))
18
+ payload = await client.create_payment_payload(payment_required)
19
+
20
+ # Server-side: Protect resources
21
+ server = x402ResourceServer(facilitator_client)
22
+ server.register("eip155:8453", ExactEvmServerScheme())
23
+ server.initialize()
24
+ result = await server.verify_payment(payload, requirements)
25
+
26
+ # Facilitator: Verify and settle payments
27
+ facilitator = x402Facilitator()
28
+ facilitator.register(["eip155:8453"], ExactEvmFacilitatorScheme(wallet))
29
+ result = await facilitator.verify(payload, requirements)
30
+ ```
31
+
32
+ Quick Start (Sync):
33
+ ```python
34
+ from x402 import x402ClientSync, x402ResourceServerSync, x402FacilitatorSync
35
+
36
+ # Client-side: Create payment payloads
37
+ client = x402ClientSync()
38
+ client.register("eip155:8453", ExactEvmScheme(signer=my_signer))
39
+ payload = client.create_payment_payload(payment_required)
40
+
41
+ # Server-side: Protect resources
42
+ server = x402ResourceServerSync(facilitator_client)
43
+ server.register("eip155:8453", ExactEvmServerScheme())
44
+ server.initialize()
45
+ result = server.verify_payment(payload, requirements)
46
+
47
+ # Facilitator: Verify and settle payments
48
+ facilitator = x402FacilitatorSync()
49
+ facilitator.register(["eip155:8453"], ExactEvmFacilitatorScheme(wallet))
50
+ result = facilitator.verify(payload, requirements)
51
+ ```
52
+ """
53
+
54
+ # Core components - Async (default)
55
+ from .client import (
56
+ SchemeRegistration,
57
+ default_payment_selector,
58
+ max_amount,
59
+ prefer_network,
60
+ prefer_scheme,
61
+ x402Client,
62
+ x402ClientConfig,
63
+ x402ClientSync,
64
+ )
65
+ from .facilitator import x402Facilitator, x402FacilitatorSync
66
+
67
+ # Interfaces (for implementing custom schemes)
68
+ from .interfaces import (
69
+ SchemeNetworkClient,
70
+ SchemeNetworkClientV1,
71
+ SchemeNetworkFacilitator,
72
+ SchemeNetworkFacilitatorV1,
73
+ SchemeNetworkServer,
74
+ )
75
+
76
+ # Types (re-export commonly used types)
77
+ from .schemas import (
78
+ # Base
79
+ X402_VERSION,
80
+ # Hooks
81
+ AbortResult,
82
+ AssetAmount,
83
+ # Config
84
+ FacilitatorConfig,
85
+ Money,
86
+ Network,
87
+ # Errors
88
+ NoMatchingRequirementsError,
89
+ PaymentAbortedError,
90
+ PaymentCreatedContext,
91
+ PaymentCreationContext,
92
+ PaymentCreationFailureContext,
93
+ PaymentError,
94
+ # V2 Payments
95
+ PaymentPayload,
96
+ # V1 Legacy
97
+ PaymentPayloadV1,
98
+ PaymentRequired,
99
+ PaymentRequiredV1,
100
+ PaymentRequirements,
101
+ PaymentRequirementsV1,
102
+ PaywallConfig,
103
+ Price,
104
+ RecoveredPayloadResult,
105
+ RecoveredSettleResult,
106
+ RecoveredVerifyResult,
107
+ ResourceConfig,
108
+ ResourceInfo,
109
+ RoutesConfig,
110
+ SchemeNotFoundError,
111
+ SettleContext,
112
+ SettleError,
113
+ SettleFailureContext,
114
+ # Responses
115
+ SettleResponse,
116
+ SettleResultContext,
117
+ SupportedKind,
118
+ SupportedResponse,
119
+ VerifyContext,
120
+ VerifyError,
121
+ VerifyFailureContext,
122
+ VerifyResponse,
123
+ VerifyResultContext,
124
+ # Helpers
125
+ derive_network_pattern,
126
+ detect_version,
127
+ find_schemes_by_network,
128
+ match_payload_to_requirements,
129
+ matches_network_pattern,
130
+ parse_payment_payload,
131
+ parse_payment_required,
132
+ )
133
+ from .server import (
134
+ FacilitatorClient,
135
+ FacilitatorClientSync,
136
+ x402ResourceServer,
137
+ x402ResourceServerSync,
138
+ )
139
+
140
+ __version__ = "0.1.0"
141
+
142
+ __all__ = [
143
+ # Version
144
+ "__version__",
145
+ # Core components - Async (default)
146
+ "x402Client",
147
+ "x402ResourceServer",
148
+ "x402Facilitator",
149
+ # Core components - Sync
150
+ "x402ClientSync",
151
+ "x402ResourceServerSync",
152
+ "x402FacilitatorSync",
153
+ # Config types
154
+ "SchemeRegistration",
155
+ "x402ClientConfig",
156
+ # Protocols
157
+ "FacilitatorClient",
158
+ "FacilitatorClientSync",
159
+ # Policies
160
+ "default_payment_selector",
161
+ "prefer_network",
162
+ "prefer_scheme",
163
+ "max_amount",
164
+ # Interfaces
165
+ "SchemeNetworkClient",
166
+ "SchemeNetworkClientV1",
167
+ "SchemeNetworkServer",
168
+ "SchemeNetworkFacilitator",
169
+ "SchemeNetworkFacilitatorV1",
170
+ # Types - Base
171
+ "X402_VERSION",
172
+ "Network",
173
+ "Money",
174
+ "Price",
175
+ "AssetAmount",
176
+ # Types - V2 Payments
177
+ "ResourceInfo",
178
+ "PaymentRequirements",
179
+ "PaymentRequired",
180
+ "PaymentPayload",
181
+ # Types - V1 Legacy
182
+ "PaymentRequirementsV1",
183
+ "PaymentRequiredV1",
184
+ "PaymentPayloadV1",
185
+ # Types - Responses
186
+ "VerifyResponse",
187
+ "SettleResponse",
188
+ "SupportedKind",
189
+ "SupportedResponse",
190
+ # Types - Config
191
+ "ResourceConfig",
192
+ "FacilitatorConfig",
193
+ "PaywallConfig",
194
+ "RoutesConfig",
195
+ # Types - Hooks
196
+ "AbortResult",
197
+ "RecoveredPayloadResult",
198
+ "RecoveredVerifyResult",
199
+ "RecoveredSettleResult",
200
+ "VerifyContext",
201
+ "VerifyResultContext",
202
+ "VerifyFailureContext",
203
+ "SettleContext",
204
+ "SettleResultContext",
205
+ "SettleFailureContext",
206
+ "PaymentCreationContext",
207
+ "PaymentCreatedContext",
208
+ "PaymentCreationFailureContext",
209
+ # Types - Errors
210
+ "PaymentError",
211
+ "VerifyError",
212
+ "SettleError",
213
+ "SchemeNotFoundError",
214
+ "NoMatchingRequirementsError",
215
+ "PaymentAbortedError",
216
+ # Types - Helpers
217
+ "detect_version",
218
+ "match_payload_to_requirements",
219
+ "matches_network_pattern",
220
+ "derive_network_pattern",
221
+ "find_schemes_by_network",
222
+ "parse_payment_required",
223
+ "parse_payment_payload",
224
+ ]
@@ -0,0 +1,347 @@
1
+ """x402Client - Client-side component for creating payment payloads.
2
+
3
+ Provides both async (x402Client) and sync (x402ClientSync) implementations.
4
+ Async is the default with full async hook support.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ from typing import Any
11
+
12
+ from typing_extensions import Self
13
+
14
+ # Re-export from client_base for external use
15
+ from .client_base import (
16
+ AfterPaymentCreationHook,
17
+ BeforePaymentCreationHook,
18
+ OnPaymentCreationFailureHook,
19
+ PaymentRequirementsSelector,
20
+ SchemeRegistration,
21
+ SyncAfterPaymentCreationHook,
22
+ SyncBeforePaymentCreationHook,
23
+ SyncOnPaymentCreationFailureHook,
24
+ default_payment_selector,
25
+ max_amount,
26
+ prefer_network,
27
+ prefer_scheme,
28
+ x402ClientBase,
29
+ x402ClientConfig,
30
+ )
31
+ from .schemas import (
32
+ PaymentPayload,
33
+ PaymentPayloadV1,
34
+ PaymentRequired,
35
+ PaymentRequiredV1,
36
+ ResourceInfo,
37
+ )
38
+
39
+ __all__ = [
40
+ "x402Client",
41
+ "x402ClientSync",
42
+ "x402ClientConfig",
43
+ "SchemeRegistration",
44
+ "default_payment_selector",
45
+ "prefer_network",
46
+ "prefer_scheme",
47
+ "max_amount",
48
+ ]
49
+
50
+
51
+ # ============================================================================
52
+ # Async Client (Default)
53
+ # ============================================================================
54
+
55
+
56
+ class x402Client(x402ClientBase):
57
+ """Async client-side component for creating payment payloads.
58
+
59
+ Supports both sync and async hooks (auto-detected).
60
+ Use x402ClientSync for sync-only environments.
61
+
62
+ Example:
63
+ ```python
64
+ from x402 import x402Client
65
+ from x402.mechanisms.evm.exact import ExactEvmScheme
66
+
67
+ client = x402Client()
68
+ client.register("eip155:8453", ExactEvmScheme(signer=my_signer))
69
+ client.register_policy(prefer_network("eip155:8453"))
70
+
71
+ # Create payment payload from 402 response
72
+ payload = await client.create_payment_payload(payment_required)
73
+ ```
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ payment_requirements_selector: PaymentRequirementsSelector | None = None,
79
+ ) -> None:
80
+ """Initialize async x402Client."""
81
+ super().__init__(payment_requirements_selector)
82
+ # Type the hook lists properly
83
+ self._before_payment_creation_hooks: list[BeforePaymentCreationHook] = []
84
+ self._after_payment_creation_hooks: list[AfterPaymentCreationHook] = []
85
+ self._on_payment_creation_failure_hooks: list[OnPaymentCreationFailureHook] = []
86
+
87
+ # ========================================================================
88
+ # Factory Methods
89
+ # ========================================================================
90
+
91
+ @classmethod
92
+ def from_config(cls, config: x402ClientConfig) -> x402Client:
93
+ """Create a new x402Client instance from a configuration object."""
94
+ client = cls(config.payment_requirements_selector)
95
+ for scheme in config.schemes:
96
+ if scheme.x402_version == 1:
97
+ client.register_v1(scheme.network, scheme.client) # type: ignore[arg-type]
98
+ else:
99
+ client.register(scheme.network, scheme.client) # type: ignore[arg-type]
100
+ for policy in config.policies or []:
101
+ client.register_policy(policy)
102
+ return client
103
+
104
+ # ========================================================================
105
+ #
106
+
107
+ # ========================================================================
108
+
109
+ def on_before_payment_creation(self, hook: BeforePaymentCreationHook) -> Self:
110
+ """Register hook before payment creation. Return AbortResult to abort."""
111
+ self._before_payment_creation_hooks.append(hook)
112
+ return self
113
+
114
+ def on_after_payment_creation(self, hook: AfterPaymentCreationHook) -> Self:
115
+ """Register hook after successful payment creation."""
116
+ self._after_payment_creation_hooks.append(hook)
117
+ return self
118
+
119
+ def on_payment_creation_failure(self, hook: OnPaymentCreationFailureHook) -> Self:
120
+ """Register hook on failure. Return RecoveredPayloadResult to recover."""
121
+ self._on_payment_creation_failure_hooks.append(hook)
122
+ return self
123
+
124
+ # ========================================================================
125
+ # Payment Creation (Async)
126
+ # ========================================================================
127
+
128
+ async def create_payment_payload(
129
+ self,
130
+ payment_required: PaymentRequired | PaymentRequiredV1,
131
+ resource: ResourceInfo | None = None,
132
+ extensions: dict[str, Any] | None = None,
133
+ ) -> PaymentPayload | PaymentPayloadV1:
134
+ """Create a payment payload for the given 402 response.
135
+
136
+ Args:
137
+ payment_required: The 402 response from the server.
138
+ resource: Optional resource info to include.
139
+ extensions: Optional extensions to include.
140
+
141
+ Returns:
142
+ PaymentPayload (V2) or PaymentPayloadV1 (V1).
143
+
144
+ Raises:
145
+ NoMatchingRequirementsError: If no requirements match registered schemes.
146
+ SchemeNotFoundError: If scheme not found for selected requirement.
147
+ PaymentAbortedError: If a before hook aborts the operation.
148
+ """
149
+ version = payment_required.x402_version
150
+
151
+ if version == 1:
152
+ return await self._create_payment_payload_v1(
153
+ payment_required, # type: ignore[arg-type]
154
+ )
155
+ else:
156
+ return await self._create_payment_payload_v2(
157
+ payment_required, # type: ignore[arg-type]
158
+ resource,
159
+ extensions,
160
+ )
161
+
162
+ async def _create_payment_payload_v2(
163
+ self,
164
+ payment_required: PaymentRequired,
165
+ resource: ResourceInfo | None,
166
+ extensions: dict[str, Any] | None,
167
+ ) -> PaymentPayload:
168
+ """Create V2 payment payload using generator."""
169
+ gen = self._create_payment_payload_v2_core(payment_required, resource, extensions)
170
+ result = None
171
+ try:
172
+ while True:
173
+ _, hook, ctx = gen.send(result)
174
+ result = await self._execute_hook(hook, ctx)
175
+ except StopIteration as e:
176
+ return e.value
177
+
178
+ async def _create_payment_payload_v1(
179
+ self,
180
+ payment_required: PaymentRequiredV1,
181
+ ) -> PaymentPayloadV1:
182
+ """Create V1 payment payload using generator."""
183
+ gen = self._create_payment_payload_v1_core(payment_required)
184
+ result = None
185
+ try:
186
+ while True:
187
+ _, hook, ctx = gen.send(result)
188
+ result = await self._execute_hook(hook, ctx)
189
+ except StopIteration as e:
190
+ return e.value
191
+
192
+ async def _execute_hook(self, hook: Any, context: Any) -> Any:
193
+ """Execute hook, auto-detecting sync/async."""
194
+ result = hook(context)
195
+ if asyncio.iscoroutine(result) or asyncio.isfuture(result):
196
+ return await result
197
+ return result
198
+
199
+
200
+ # ============================================================================
201
+ # Sync Client
202
+ # ============================================================================
203
+
204
+
205
+ class x402ClientSync(x402ClientBase):
206
+ """Sync client-side component for creating payment payloads.
207
+
208
+ Only supports sync hooks. For async hook support, use x402Client.
209
+
210
+ Example:
211
+ ```python
212
+ from x402 import x402ClientSync
213
+ from x402.mechanisms.evm.exact import ExactEvmScheme
214
+
215
+ client = x402ClientSync()
216
+ client.register("eip155:8453", ExactEvmScheme(signer=my_signer))
217
+
218
+ # Create payment payload from 402 response
219
+ payload = client.create_payment_payload(payment_required)
220
+ ```
221
+ """
222
+
223
+ def __init__(
224
+ self,
225
+ payment_requirements_selector: PaymentRequirementsSelector | None = None,
226
+ ) -> None:
227
+ """Initialize sync x402Client."""
228
+ super().__init__(payment_requirements_selector)
229
+ # Type the hook lists for sync-only
230
+ self._before_payment_creation_hooks: list[SyncBeforePaymentCreationHook] = []
231
+ self._after_payment_creation_hooks: list[SyncAfterPaymentCreationHook] = []
232
+ self._on_payment_creation_failure_hooks: list[SyncOnPaymentCreationFailureHook] = []
233
+
234
+ # ========================================================================
235
+ # Factory Methods
236
+ # ========================================================================
237
+
238
+ @classmethod
239
+ def from_config(cls, config: x402ClientConfig) -> x402ClientSync:
240
+ """Create a new x402ClientSync instance from a configuration object."""
241
+ client = cls(config.payment_requirements_selector)
242
+ for scheme in config.schemes:
243
+ if scheme.x402_version == 1:
244
+ client.register_v1(scheme.network, scheme.client) # type: ignore[arg-type]
245
+ else:
246
+ client.register(scheme.network, scheme.client) # type: ignore[arg-type]
247
+ for policy in config.policies or []:
248
+ client.register_policy(policy)
249
+ return client
250
+
251
+ # ========================================================================
252
+ # Hook Registration
253
+ # ========================================================================
254
+
255
+ def on_before_payment_creation(self, hook: SyncBeforePaymentCreationHook) -> Self:
256
+ """Register hook before payment creation. Return AbortResult to abort."""
257
+ self._before_payment_creation_hooks.append(hook)
258
+ return self
259
+
260
+ def on_after_payment_creation(self, hook: SyncAfterPaymentCreationHook) -> Self:
261
+ """Register hook after successful payment creation."""
262
+ self._after_payment_creation_hooks.append(hook)
263
+ return self
264
+
265
+ def on_payment_creation_failure(self, hook: SyncOnPaymentCreationFailureHook) -> Self:
266
+ """Register hook on failure. Return RecoveredPayloadResult to recover."""
267
+ self._on_payment_creation_failure_hooks.append(hook)
268
+ return self
269
+
270
+ # ========================================================================
271
+ # Payment Creation (Sync)
272
+ # ========================================================================
273
+
274
+ def create_payment_payload(
275
+ self,
276
+ payment_required: PaymentRequired | PaymentRequiredV1,
277
+ resource: ResourceInfo | None = None,
278
+ extensions: dict[str, Any] | None = None,
279
+ ) -> PaymentPayload | PaymentPayloadV1:
280
+ """Create a payment payload for the given 402 response.
281
+
282
+ Args:
283
+ payment_required: The 402 response from the server.
284
+ resource: Optional resource info to include.
285
+ extensions: Optional extensions to include.
286
+
287
+ Returns:
288
+ PaymentPayload (V2) or PaymentPayloadV1 (V1).
289
+
290
+ Raises:
291
+ NoMatchingRequirementsError: If no requirements match registered schemes.
292
+ SchemeNotFoundError: If scheme not found for selected requirement.
293
+ PaymentAbortedError: If a before hook aborts the operation.
294
+ """
295
+ version = payment_required.x402_version
296
+
297
+ if version == 1:
298
+ return self._create_payment_payload_v1(
299
+ payment_required, # type: ignore[arg-type]
300
+ )
301
+ else:
302
+ return self._create_payment_payload_v2(
303
+ payment_required, # type: ignore[arg-type]
304
+ resource,
305
+ extensions,
306
+ )
307
+
308
+ def _create_payment_payload_v2(
309
+ self,
310
+ payment_required: PaymentRequired,
311
+ resource: ResourceInfo | None,
312
+ extensions: dict[str, Any] | None,
313
+ ) -> PaymentPayload:
314
+ """Create V2 payment payload using generator."""
315
+ gen = self._create_payment_payload_v2_core(payment_required, resource, extensions)
316
+ result = None
317
+ try:
318
+ while True:
319
+ _, hook, ctx = gen.send(result)
320
+ result = self._execute_hook_sync(hook, ctx)
321
+ except StopIteration as e:
322
+ return e.value
323
+
324
+ def _create_payment_payload_v1(
325
+ self,
326
+ payment_required: PaymentRequiredV1,
327
+ ) -> PaymentPayloadV1:
328
+ """Create V1 payment payload using generator."""
329
+ gen = self._create_payment_payload_v1_core(payment_required)
330
+ result = None
331
+ try:
332
+ while True:
333
+ _, hook, ctx = gen.send(result)
334
+ result = self._execute_hook_sync(hook, ctx)
335
+ except StopIteration as e:
336
+ return e.value
337
+
338
+ def _execute_hook_sync(self, hook: Any, context: Any) -> Any:
339
+ """Execute hook synchronously. Raises if async hook detected."""
340
+ result = hook(context)
341
+ if asyncio.iscoroutine(result):
342
+ result.close() # Prevent warning
343
+ raise TypeError(
344
+ "Async hooks are not supported in x402ClientSync. "
345
+ "Use x402Client for async hook support."
346
+ )
347
+ return result