@onecraft/wallet 0.0.0-stage → 0.1.145

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 (248) hide show
  1. package/.claude-plugin/marketplace.json +20 -0
  2. package/.openclaw/AGENTS.md +100 -0
  3. package/.openclaw/extensions/agent-wallet/README.md +195 -0
  4. package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
  5. package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
  6. package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
  7. package/.openclaw/extensions/agent-wallet/package.json +49 -0
  8. package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
  9. package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
  10. package/CHANGELOG.md +1232 -0
  11. package/LICENSE +104 -0
  12. package/README.md +193 -2
  13. package/VERSION +1 -0
  14. package/agent-wallet/.env.example +63 -0
  15. package/agent-wallet/AGENTS.md +130 -0
  16. package/agent-wallet/CARD_VAULT.md +640 -0
  17. package/agent-wallet/README.md +615 -0
  18. package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
  19. package/agent-wallet/agent_wallet/__init__.py +16 -0
  20. package/agent-wallet/agent_wallet/approval.py +165 -0
  21. package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
  22. package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
  23. package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
  24. package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
  25. package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
  26. package/agent-wallet/agent_wallet/bootstrap.py +194 -0
  27. package/agent-wallet/agent_wallet/card_catalog.py +243 -0
  28. package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
  29. package/agent-wallet/agent_wallet/card_vault.py +331 -0
  30. package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
  31. package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
  32. package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
  33. package/agent-wallet/agent_wallet/config.py +719 -0
  34. package/agent-wallet/agent_wallet/connector_cli.py +198 -0
  35. package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
  36. package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
  37. package/agent-wallet/agent_wallet/connectors/client.py +308 -0
  38. package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
  39. package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
  40. package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
  41. package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
  42. package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
  43. package/agent-wallet/agent_wallet/exceptions.py +10 -0
  44. package/agent-wallet/agent_wallet/file_ops.py +34 -0
  45. package/agent-wallet/agent_wallet/http_client.py +25 -0
  46. package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
  47. package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
  48. package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
  49. package/agent-wallet/agent_wallet/keystore.py +503 -0
  50. package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
  51. package/agent-wallet/agent_wallet/models.py +66 -0
  52. package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
  53. package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
  54. package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
  55. package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
  56. package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
  57. package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
  58. package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
  59. package/agent-wallet/agent_wallet/providers/bags.py +202 -0
  60. package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
  61. package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
  62. package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
  63. package/agent-wallet/agent_wallet/providers/imd.py +720 -0
  64. package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
  65. package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
  66. package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
  67. package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
  68. package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
  69. package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
  70. package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
  71. package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
  72. package/agent-wallet/agent_wallet/solana_stake.py +103 -0
  73. package/agent-wallet/agent_wallet/solana_tx.py +93 -0
  74. package/agent-wallet/agent_wallet/spending_limits.py +119 -0
  75. package/agent-wallet/agent_wallet/telemetry.py +481 -0
  76. package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
  77. package/agent-wallet/agent_wallet/update_check.py +190 -0
  78. package/agent-wallet/agent_wallet/user_wallets.py +573 -0
  79. package/agent-wallet/agent_wallet/validation.py +31 -0
  80. package/agent-wallet/agent_wallet/vault_executor.py +456 -0
  81. package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
  82. package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
  83. package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
  84. package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
  85. package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
  86. package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
  87. package/agent-wallet/examples/bootstrap_wallet.py +21 -0
  88. package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
  89. package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
  90. package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
  91. package/agent-wallet/openclaw.plugin.json +118 -0
  92. package/agent-wallet/pyproject.toml +36 -0
  93. package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
  94. package/agent-wallet/scripts/build_release_bundle.py +210 -0
  95. package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
  96. package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
  97. package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
  98. package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
  99. package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
  100. package/agent-wallet/scripts/security_utils.py +37 -0
  101. package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
  102. package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
  103. package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
  104. package/bin/lib/boot-key.mjs +184 -0
  105. package/bin/lib/evm-daemon.mjs +389 -0
  106. package/bin/lib/host-detection.mjs +259 -0
  107. package/bin/lib/integrations.mjs +578 -0
  108. package/bin/lib/release-python.mjs +9 -0
  109. package/bin/lib/update-transaction.mjs +235 -0
  110. package/bin/openclaw-agent-wallet.mjs +3354 -0
  111. package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
  112. package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
  113. package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
  114. package/claude-code/plugins/agent-wallet/README.md +134 -0
  115. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
  116. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
  117. package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
  118. package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
  119. package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
  120. package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
  121. package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
  122. package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
  123. package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
  124. package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
  125. package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
  126. package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
  127. package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
  128. package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
  129. package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
  130. package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
  131. package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
  132. package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
  133. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
  134. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
  135. package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
  136. package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
  137. package/codex/plugins/agent-wallet/.mcp.json +15 -0
  138. package/codex/plugins/agent-wallet/README.md +158 -0
  139. package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
  140. package/codex/plugins/agent-wallet/server.py +1797 -0
  141. package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
  142. package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
  143. package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  144. package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
  145. package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  146. package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
  147. package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
  148. package/connectors/AGENTS.md +37 -0
  149. package/connectors/DEVELOPER_GUIDE.md +131 -0
  150. package/connectors/README.md +139 -0
  151. package/connectors/READ_ONLY_BETA.md +54 -0
  152. package/connectors/RELEASING.md +48 -0
  153. package/connectors/conformance/README.md +31 -0
  154. package/connectors/conformance/package.json +54 -0
  155. package/connectors/conformance/scripts/sync-license.mjs +3 -0
  156. package/connectors/conformance/scripts/sync-spec.mjs +16 -0
  157. package/connectors/conformance/src/cli.ts +43 -0
  158. package/connectors/conformance/src/index.ts +7 -0
  159. package/connectors/conformance/src/runner.ts +314 -0
  160. package/connectors/conformance/src/types.ts +27 -0
  161. package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
  162. package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
  163. package/connectors/conformance/test/runner.test.mjs +151 -0
  164. package/connectors/conformance/tsconfig.json +17 -0
  165. package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
  166. package/connectors/examples/reference-crypto-data/README.md +51 -0
  167. package/connectors/examples/reference-crypto-data/conformance.json +11 -0
  168. package/connectors/examples/reference-crypto-data/connector.json +95 -0
  169. package/connectors/examples/reference-crypto-data/package.json +21 -0
  170. package/connectors/examples/reference-crypto-data/railway.toml +9 -0
  171. package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
  172. package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
  173. package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
  174. package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
  175. package/connectors/package-lock.json +561 -0
  176. package/connectors/package.json +19 -0
  177. package/connectors/scripts/smoke-packed-packages.mjs +121 -0
  178. package/connectors/sdk-typescript/README.md +47 -0
  179. package/connectors/sdk-typescript/package.json +49 -0
  180. package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
  181. package/connectors/sdk-typescript/src/connector.ts +204 -0
  182. package/connectors/sdk-typescript/src/errors.ts +11 -0
  183. package/connectors/sdk-typescript/src/http.ts +116 -0
  184. package/connectors/sdk-typescript/src/index.ts +26 -0
  185. package/connectors/sdk-typescript/src/types.ts +101 -0
  186. package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
  187. package/connectors/sdk-typescript/tsconfig.json +21 -0
  188. package/connectors/spec/connector-manifest.schema.json +340 -0
  189. package/connectors/spec/connector-protocol.md +159 -0
  190. package/connectors/spec/transaction-intent.schema.json +281 -0
  191. package/connectors/templates/read-only/.env.example +1 -0
  192. package/connectors/templates/read-only/Dockerfile +11 -0
  193. package/connectors/templates/read-only/README.md +33 -0
  194. package/connectors/templates/read-only/conformance.json +11 -0
  195. package/connectors/templates/read-only/connector.json +64 -0
  196. package/connectors/templates/read-only/package.json +21 -0
  197. package/connectors/templates/read-only/railway.toml +9 -0
  198. package/connectors/templates/read-only/src/connector.ts +61 -0
  199. package/connectors/templates/read-only/src/server.ts +14 -0
  200. package/connectors/templates/read-only/test/connector.test.mjs +62 -0
  201. package/connectors/templates/read-only/tsconfig.json +17 -0
  202. package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
  203. package/cursor/plugins/agent-wallet/README.md +62 -0
  204. package/cursor/plugins/agent-wallet/mcp.json +16 -0
  205. package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
  206. package/cursor/plugins/agent-wallet/server.py +33 -0
  207. package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
  208. package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  209. package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
  210. package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  211. package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
  212. package/hermes/plugins/agent_wallet/README.md +54 -0
  213. package/hermes/plugins/agent_wallet/__init__.py +55 -0
  214. package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
  215. package/hermes/plugins/agent_wallet/schemas.py +211 -0
  216. package/hermes/plugins/agent_wallet/tools.py +622 -0
  217. package/install-from-github.sh +139 -0
  218. package/integrations/hedera/treasury-guard/README.md +92 -0
  219. package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
  220. package/integrations/hedera/treasury-guard/package-lock.json +880 -0
  221. package/integrations/hedera/treasury-guard/package.json +8 -0
  222. package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
  223. package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
  224. package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
  225. package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
  226. package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
  227. package/mcp/README.md +39 -0
  228. package/mcp/scripts/run_mcp.sh +37 -0
  229. package/mcp/server.py +33 -0
  230. package/package.json +106 -4
  231. package/scripts/check_release_version.mjs +72 -0
  232. package/scripts/version_targets.mjs +60 -0
  233. package/setup.sh +87 -0
  234. package/wdk-evm-wallet/.env.example +38 -0
  235. package/wdk-evm-wallet/README.md +254 -0
  236. package/wdk-evm-wallet/bootstrap.sh +8 -0
  237. package/wdk-evm-wallet/package-lock.json +2359 -0
  238. package/wdk-evm-wallet/package.json +43 -0
  239. package/wdk-evm-wallet/run-local.sh +12 -0
  240. package/wdk-evm-wallet/src/config.js +461 -0
  241. package/wdk-evm-wallet/src/imd.js +231 -0
  242. package/wdk-evm-wallet/src/json.js +35 -0
  243. package/wdk-evm-wallet/src/local_vault.js +407 -0
  244. package/wdk-evm-wallet/src/network_state.js +96 -0
  245. package/wdk-evm-wallet/src/pending_transactions.js +148 -0
  246. package/wdk-evm-wallet/src/server.js +849 -0
  247. package/wdk-evm-wallet/src/shutdown.js +63 -0
  248. package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
@@ -0,0 +1,1972 @@
1
+ """x402 discovery, preview, and buyer execution helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import time
10
+ from types import SimpleNamespace
11
+ from typing import Any
12
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
13
+
14
+ from agent_wallet.config import normalize_solana_network, resolve_solana_rpc_url
15
+ from agent_wallet.exceptions import ProviderError
16
+ from agent_wallet.http_client import get_client
17
+ from agent_wallet.wallet_layer.base import AgentWalletBackend
18
+
19
+ CDP_BAZAAR_DISCOVERY_BASE_URL = "https://api.cdp.coinbase.com/platform/v2/x402/discovery"
20
+ AGENTIC_MARKET_API_BASE_URL = "https://api.agentic.market/v1"
21
+ # Static, non-secret partner identifier Laso Finance asked us to send on every
22
+ # request to laso.finance (the /cards flow). Laso ignores unrecognized values.
23
+ LASO_PARTNER_HOST = "laso.finance"
24
+ LASO_PARTNER_HEADERS = {"X-Laso-Partner": "zyMjC5KIn9fKaypAz2VR"}
25
+ X402_EXECUTE_TIMEOUT_SECONDS = 45.0
26
+ DISCOVERY_CACHE_TTL_SECONDS = 300.0
27
+ _DISCOVERY_CACHE_MAX_ENTRIES = 64
28
+ # Discovery responses cached as JSON text so hits hand out independent copies.
29
+ # Long-lived only inside the resident read worker; cold CLI runs start empty.
30
+ _discovery_cache: dict[str, tuple[float, str]] = {}
31
+ SOLANA_CAIP_BY_NETWORK = {
32
+ "mainnet": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
33
+ }
34
+ EVM_CAIP_BY_NETWORK = {
35
+ "ethereum": "eip155:1",
36
+ "base": "eip155:8453",
37
+ }
38
+ # x402 v1 requirements carry legacy network names instead of CAIP-2 ids.
39
+ LEGACY_NETWORK_TO_CAIP = {
40
+ "ethereum": "eip155:1",
41
+ "base": "eip155:8453",
42
+ "solana": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
43
+ }
44
+ _USDC_IDENTIFIERS = {
45
+ "usdc",
46
+ "usd coin",
47
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
48
+ "0x036cbd53842c5426634e7929541ec2318f3dcf7e",
49
+ "epjfwdd5aufqssqem2qn1xzybapc8g4wegkgkzwytdt1v",
50
+ }
51
+ log = logging.getLogger("agent_wallet.x402")
52
+
53
+
54
+ def _backend_chain(backend: AgentWalletBackend) -> str:
55
+ chain = _trim(getattr(backend, "chain", "")).lower()
56
+ if chain:
57
+ return chain
58
+ try:
59
+ capabilities = backend.get_capabilities()
60
+ except Exception:
61
+ return ""
62
+ return _trim(getattr(capabilities, "chain", "")).lower()
63
+
64
+
65
+ def _backend_network(backend: AgentWalletBackend) -> str:
66
+ return _trim(getattr(backend, "network", "")).lower()
67
+
68
+
69
+ def _backend_solana_sdk_rpc_url(backend: AgentWalletBackend) -> str | None:
70
+ candidates = getattr(backend, "rpc_urls", None)
71
+ if isinstance(candidates, list):
72
+ for candidate in candidates:
73
+ text = _trim(candidate)
74
+ if text.startswith(("http://", "https://")):
75
+ return text
76
+ primary = _trim(getattr(backend, "rpc_url", None))
77
+ if primary.startswith(("http://", "https://")):
78
+ return primary
79
+ network = _backend_network(backend)
80
+ fallback = resolve_solana_rpc_url(normalize_solana_network(network or "mainnet"), "")
81
+ return _trim(fallback) or None
82
+
83
+
84
+ def _trim(value: Any) -> str:
85
+ return str(value or "").strip()
86
+
87
+
88
+ def _canonical_json_text(payload: Any) -> str:
89
+ return json.dumps(payload, sort_keys=True, separators=(",", ":"))
90
+
91
+
92
+ def _hash_text(text: str) -> str:
93
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
94
+
95
+
96
+ def _normalize_discovery_provider(value: Any) -> str:
97
+ provider = _trim(value).lower() or "auto"
98
+ aliases = {
99
+ "bazaar": "cdp_bazaar",
100
+ "cdp": "cdp_bazaar",
101
+ "agentic": "agentic_market",
102
+ "agenticmarket": "agentic_market",
103
+ "market": "agentic_market",
104
+ }
105
+ provider = aliases.get(provider, provider)
106
+ if provider not in {"auto", "cdp_bazaar", "agentic_market"}:
107
+ raise ProviderError("x402-discovery", f"Unsupported discovery provider: {provider}")
108
+ return provider
109
+
110
+
111
+ def _normalize_http_method(value: Any) -> str:
112
+ method = _trim(value).upper() or "GET"
113
+ if method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}:
114
+ raise ProviderError("x402-http", f"Unsupported HTTP method: {method}")
115
+ return method
116
+
117
+
118
+ def _normalize_headers(value: Any) -> dict[str, str]:
119
+ if value is None:
120
+ return {}
121
+ if not isinstance(value, dict):
122
+ raise ProviderError("x402-http", "headers must be an object when provided.")
123
+ headers: dict[str, str] = {}
124
+ for key, raw_value in value.items():
125
+ name = _trim(key)
126
+ if not name:
127
+ raise ProviderError("x402-http", "headers must not contain empty names.")
128
+ headers[name] = str(raw_value)
129
+ return headers
130
+
131
+
132
+ def _normalize_query_params(value: Any) -> dict[str, str]:
133
+ if value is None:
134
+ return {}
135
+ if not isinstance(value, dict):
136
+ raise ProviderError("x402-http", "query must be an object when provided.")
137
+ params: dict[str, str] = {}
138
+ for key, raw_value in value.items():
139
+ name = _trim(key)
140
+ if not name:
141
+ raise ProviderError("x402-http", "query must not contain empty names.")
142
+ params[name] = str(raw_value)
143
+ return params
144
+
145
+
146
+ def _append_query(url: str, query: dict[str, str]) -> str:
147
+ if not query:
148
+ return url
149
+ parts = urlsplit(url)
150
+ merged = dict(parse_qsl(parts.query, keep_blank_values=True))
151
+ merged.update(query)
152
+ return urlunsplit(
153
+ (parts.scheme, parts.netloc, parts.path, urlencode(merged, doseq=True), parts.fragment)
154
+ )
155
+
156
+
157
+ def _request_host(url: str) -> str:
158
+ try:
159
+ return _trim(urlsplit(url).netloc).lower()
160
+ except Exception:
161
+ return ""
162
+
163
+
164
+ def _response_text(response: Any) -> str:
165
+ try:
166
+ text = response.text
167
+ except Exception:
168
+ return ""
169
+ return str(text or "")
170
+
171
+
172
+ def _parse_json_response(response: Any, *, provider: str, operation: str) -> Any:
173
+ body = _response_text(response)
174
+ if not body.strip():
175
+ raise ProviderError(provider, f"{operation} returned an empty response body.")
176
+ try:
177
+ return response.json()
178
+ except ValueError as exc:
179
+ snippet = body.strip().replace("\n", " ")[:200]
180
+ detail = f": {snippet}" if snippet else ""
181
+ raise ProviderError(provider, f"{operation} returned invalid JSON{detail}") from exc
182
+
183
+
184
+ def _decode_payment_required(header_value: str) -> dict[str, Any]:
185
+ raw = _trim(header_value)
186
+ if not raw:
187
+ raise ProviderError("x402-http", "PAYMENT-REQUIRED header is empty.")
188
+ decoded_bytes: bytes | None = None
189
+ for decoder in (base64.b64decode, base64.urlsafe_b64decode):
190
+ try:
191
+ padding = "=" * (-len(raw) % 4)
192
+ decoded_bytes = decoder(raw + padding)
193
+ break
194
+ except Exception:
195
+ continue
196
+ if decoded_bytes is None:
197
+ raise ProviderError("x402-http", "PAYMENT-REQUIRED header is not valid base64.")
198
+ try:
199
+ payload = json.loads(decoded_bytes.decode("utf-8"))
200
+ except Exception as exc:
201
+ raise ProviderError("x402-http", "PAYMENT-REQUIRED header is not valid JSON.") from exc
202
+ if isinstance(payload, list):
203
+ accepts = payload
204
+ x402_version = None
205
+ elif isinstance(payload, dict):
206
+ accepts = payload.get("accepts")
207
+ x402_version = payload.get("x402Version")
208
+ else:
209
+ raise ProviderError("x402-http", "PAYMENT-REQUIRED payload must decode to JSON.")
210
+ extensions = payload.get("extensions") if isinstance(payload, dict) else None
211
+ extensions = extensions if isinstance(extensions, dict) else {}
212
+ # Auth-only routes advertise an empty accepts[] plus a Sign-In-With-X challenge.
213
+ if not isinstance(accepts, list) or (not accepts and _siwx_declaration(extensions) is None):
214
+ raise ProviderError("x402-http", "PAYMENT-REQUIRED payload does not contain accepts[].")
215
+ return {
216
+ "x402_version": x402_version,
217
+ "accepts": accepts,
218
+ "extensions": extensions,
219
+ "raw": payload,
220
+ "encoded": raw,
221
+ }
222
+
223
+
224
+ SIWX_EXTENSION_KEY = "sign-in-with-x"
225
+
226
+
227
+ def _siwx_declaration(extensions: Any) -> dict[str, Any] | None:
228
+ """Return the merchant's Sign-In-With-X challenge, if it declares one."""
229
+ if not isinstance(extensions, dict):
230
+ return None
231
+ declaration = extensions.get(SIWX_EXTENSION_KEY)
232
+ if not isinstance(declaration, dict) or not isinstance(declaration.get("info"), dict):
233
+ return None
234
+ chains = declaration.get("supportedChains")
235
+ if not isinstance(chains, list) or not chains:
236
+ return None
237
+ return declaration
238
+
239
+
240
+ def _siwx_signature_type(backend: AgentWalletBackend) -> str | None:
241
+ chain = _backend_chain(backend)
242
+ if chain == "evm":
243
+ return "eip191"
244
+ if chain == "solana":
245
+ return "ed25519"
246
+ return None
247
+
248
+
249
+ def _siwx_summary(extensions: Any, backend: AgentWalletBackend) -> dict[str, Any] | None:
250
+ declaration = _siwx_declaration(extensions)
251
+ if declaration is None:
252
+ return None
253
+ chains = [chain for chain in declaration["supportedChains"] if isinstance(chain, dict)]
254
+ signature_type = _siwx_signature_type(backend)
255
+ info = declaration["info"]
256
+ return {
257
+ "declared": True,
258
+ "domain": info.get("domain") if isinstance(info.get("domain"), str) else None,
259
+ "chain_ids": [chain.get("chainId") for chain in chains if isinstance(chain.get("chainId"), str)],
260
+ "signature_types": sorted({chain.get("type") for chain in chains if isinstance(chain.get("type"), str)}),
261
+ "wallet_compatible": any(chain.get("type") == signature_type for chain in chains),
262
+ }
263
+
264
+
265
+ def _caip_network(value: Any) -> str:
266
+ """Map a requirement network to CAIP-2 form, passing CAIP ids through."""
267
+ network = _trim(value)
268
+ if ":" in network:
269
+ return network
270
+ return LEGACY_NETWORK_TO_CAIP.get(network.lower(), network)
271
+
272
+
273
+ def _decode_payment_required_body(response: Any) -> dict[str, Any] | None:
274
+ """Parse a legacy x402 v1 402 response whose requirements live in the JSON body.
275
+
276
+ Returns the same shape as _decode_payment_required, with `encoded` set to a
277
+ base64 form the x402 SDK can decode (it detects the version from the JSON).
278
+ """
279
+ try:
280
+ payload = response.json()
281
+ except Exception:
282
+ return None
283
+ if not isinstance(payload, dict) or payload.get("x402Version") != 1:
284
+ return None
285
+ accepts = payload.get("accepts")
286
+ if not isinstance(accepts, list) or not accepts:
287
+ return None
288
+ encoded = base64.b64encode(json.dumps(payload).encode("utf-8")).decode("ascii")
289
+ return {
290
+ "x402_version": 1,
291
+ "accepts": accepts,
292
+ "raw": payload,
293
+ "encoded": encoded,
294
+ }
295
+
296
+
297
+ def _extract_requirement_extra(requirement: dict[str, Any]) -> dict[str, Any]:
298
+ extra = requirement.get("extra")
299
+ return dict(extra) if isinstance(extra, dict) else {}
300
+
301
+
302
+ def _requirement_field(requirement: Any, field_name: str) -> Any:
303
+ if isinstance(requirement, dict):
304
+ aliases = {
305
+ "pay_to": ("pay_to", "payTo"),
306
+ "max_timeout_seconds": ("max_timeout_seconds", "maxTimeoutSeconds"),
307
+ "amount": ("amount", "maxAmountRequired"),
308
+ }
309
+ for candidate in aliases.get(field_name, (field_name,)):
310
+ if candidate in requirement:
311
+ return requirement.get(candidate)
312
+ return None
313
+ value = getattr(requirement, field_name, None)
314
+ if value is None and field_name == "amount":
315
+ # v1 SDK models expose the amount as max_amount_required / get_amount().
316
+ getter = getattr(requirement, "get_amount", None)
317
+ if callable(getter):
318
+ return getter()
319
+ return value
320
+
321
+
322
+ def _requirement_amount(requirement: dict[str, Any]) -> str:
323
+ # x402 v2 uses "amount"; v1 uses "maxAmountRequired".
324
+ return _trim(requirement.get("amount") or requirement.get("maxAmountRequired"))
325
+
326
+
327
+ def _looks_like_usdc(requirement: dict[str, Any]) -> bool:
328
+ asset = _trim(requirement.get("asset")).lower()
329
+ if asset in _USDC_IDENTIFIERS:
330
+ return True
331
+ extra = _extract_requirement_extra(requirement)
332
+ return _trim(extra.get("name")).lower() in _USDC_IDENTIFIERS
333
+
334
+
335
+ def _normalize_amount_hint(requirement: dict[str, Any]) -> str | None:
336
+ amount = _requirement_amount(requirement)
337
+ if not amount.isdigit():
338
+ return None
339
+ if _looks_like_usdc(requirement):
340
+ raw = int(amount)
341
+ whole = raw // 1_000_000
342
+ fraction = raw % 1_000_000
343
+ if fraction:
344
+ return f"{whole}.{fraction:06d}".rstrip("0").rstrip(".")
345
+ return f"{whole}"
346
+ return None
347
+
348
+
349
+ def normalize_payment_requirement(
350
+ requirement: dict[str, Any],
351
+ *,
352
+ source: str,
353
+ resource_url: str | None = None,
354
+ ) -> dict[str, Any]:
355
+ extra = _extract_requirement_extra(requirement)
356
+ amount = _requirement_amount(requirement)
357
+ return {
358
+ "scheme": _trim(requirement.get("scheme")).lower() or None,
359
+ "network": _trim(requirement.get("network")) or None,
360
+ "asset": _trim(requirement.get("asset")) or None,
361
+ "amount": amount or None,
362
+ "amount_display": _normalize_amount_hint(requirement),
363
+ "pay_to": _trim(requirement.get("payTo")) or None,
364
+ "max_timeout_seconds": requirement.get("maxTimeoutSeconds"),
365
+ "resource_url": resource_url,
366
+ "extra": extra,
367
+ "source": source,
368
+ "raw": requirement,
369
+ }
370
+
371
+
372
+ def _normalize_cdp_resource(item: dict[str, Any]) -> dict[str, Any]:
373
+ metadata = item.get("metadata")
374
+ metadata_dict = dict(metadata) if isinstance(metadata, dict) else {}
375
+ accepts = item.get("accepts") if isinstance(item.get("accepts"), list) else []
376
+ resource = _trim(item.get("resource"))
377
+ return {
378
+ "discovery_provider": "cdp_bazaar",
379
+ "resource": resource,
380
+ "type": _trim(item.get("type")) or "http",
381
+ "x402_version": item.get("x402Version"),
382
+ "description": _trim(item.get("description") or metadata_dict.get("description")) or None,
383
+ "last_updated": item.get("lastUpdated"),
384
+ "accepts": [
385
+ normalize_payment_requirement(requirement, source="cdp_bazaar", resource_url=resource)
386
+ for requirement in accepts
387
+ if isinstance(requirement, dict)
388
+ ],
389
+ "metadata": metadata_dict,
390
+ "raw": item,
391
+ }
392
+
393
+
394
+ def _normalize_agentic_service(service: dict[str, Any]) -> dict[str, Any]:
395
+ endpoints = service.get("endpoints") if isinstance(service.get("endpoints"), list) else []
396
+ normalized_endpoints: list[dict[str, Any]] = []
397
+ accepts: list[dict[str, Any]] = []
398
+ for endpoint in endpoints:
399
+ if not isinstance(endpoint, dict):
400
+ continue
401
+ pricing = endpoint.get("pricing") if isinstance(endpoint.get("pricing"), dict) else {}
402
+ normalized = {
403
+ "url": _trim(endpoint.get("url")) or None,
404
+ "description": _trim(endpoint.get("description")) or None,
405
+ "method": _normalize_http_method(endpoint.get("method")),
406
+ "pricing": {
407
+ "amount": _trim(pricing.get("amount")) or None,
408
+ "currency": _trim(pricing.get("currency")) or None,
409
+ "network": _trim(pricing.get("network")) or None,
410
+ },
411
+ }
412
+ normalized_endpoints.append(normalized)
413
+ amount_text = _trim(pricing.get("amount"))
414
+ currency = _trim(pricing.get("currency")).lower()
415
+ network = _trim(pricing.get("network")).lower()
416
+ if amount_text and currency == "usdc":
417
+ accepts.append(
418
+ {
419
+ "scheme": "exact",
420
+ "network": EVM_CAIP_BY_NETWORK.get(network, SOLANA_CAIP_BY_NETWORK.get(network, network)),
421
+ "asset": "USDC",
422
+ "amount": amount_text,
423
+ "amount_display": amount_text,
424
+ "pay_to": None,
425
+ "max_timeout_seconds": None,
426
+ "resource_url": normalized["url"],
427
+ "extra": {
428
+ "marketplace": "agentic_market",
429
+ "pricingCurrency": pricing.get("currency"),
430
+ "pricingNetwork": pricing.get("network"),
431
+ },
432
+ "source": "agentic_market",
433
+ "raw": endpoint,
434
+ }
435
+ )
436
+ return {
437
+ "discovery_provider": "agentic_market",
438
+ "service_id": _trim(service.get("id")) or None,
439
+ "service_name": _trim(service.get("name")) or None,
440
+ "description": _trim(service.get("description")) or None,
441
+ "domain": _trim(service.get("domain")) or None,
442
+ "category": _trim(service.get("category")) or None,
443
+ "networks": [str(item) for item in service.get("networks") or []],
444
+ "integration_type": _trim(service.get("integrationType")) or None,
445
+ "is_new": bool(service.get("isNew")),
446
+ "endpoints": normalized_endpoints,
447
+ "accepts": accepts,
448
+ "raw": service,
449
+ }
450
+
451
+
452
+ def _wallet_caip_networks(backend: AgentWalletBackend) -> list[str]:
453
+ chain = _backend_chain(backend)
454
+ network = _backend_network(backend)
455
+ if chain == "evm":
456
+ caip = EVM_CAIP_BY_NETWORK.get(network)
457
+ return [caip] if caip else []
458
+ if chain == "solana":
459
+ caip = SOLANA_CAIP_BY_NETWORK.get(network)
460
+ return [caip] if caip else []
461
+ return []
462
+
463
+
464
+ def _solana_exact_execution_supported(backend: AgentWalletBackend) -> bool:
465
+ return (
466
+ _backend_chain(backend) == "solana"
467
+ and _backend_network(backend) == "mainnet"
468
+ and getattr(backend, "signer", None) is not None
469
+ )
470
+
471
+
472
+ def _evm_exact_execution_supported(backend: AgentWalletBackend) -> bool:
473
+ return (
474
+ _backend_chain(backend) == "evm"
475
+ and _backend_network(backend) == "base"
476
+ and callable(getattr(backend, "sign_x402_evm_exact_typed_data", None))
477
+ )
478
+
479
+
480
+ def _evm_payment_requirement_supported(requirement: dict[str, Any]) -> bool:
481
+ scheme = _trim(requirement.get("scheme")).lower()
482
+ extra = _extract_requirement_extra(requirement)
483
+ if scheme == "exact":
484
+ transfer_method = _trim(extra.get("assetTransferMethod")).lower()
485
+ return transfer_method in {"", "eip3009", "transferwithauthorization"}
486
+ if scheme == "upto":
487
+ # The upto Permit2 payload needs the facilitator's address up front;
488
+ # without it the SDK signer raises instead of falling back cleanly.
489
+ return bool(_trim(extra.get("facilitatorAddress")))
490
+ return False
491
+
492
+
493
+ def _wallet_x402_support_summary(backend: AgentWalletBackend) -> dict[str, Any]:
494
+ chain = _backend_chain(backend)
495
+ network = _backend_network(backend)
496
+ supported_networks = _wallet_caip_networks(backend)
497
+ planned_execution_networks = {
498
+ "eip155:8453",
499
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
500
+ }
501
+ execution_modes: list[str] = []
502
+ if _solana_exact_execution_supported(backend):
503
+ execution_modes.append("solana_exact")
504
+ if _evm_exact_execution_supported(backend):
505
+ execution_modes.append("evm_exact")
506
+ return {
507
+ "chain": chain,
508
+ "network": network,
509
+ "supported_caip_networks": supported_networks,
510
+ "wallet_type_supported": chain in {"evm", "solana"},
511
+ "execution_available": bool(execution_modes),
512
+ "execution_modes": execution_modes,
513
+ "planned_execution_networks": sorted(planned_execution_networks),
514
+ }
515
+
516
+
517
+ def _requirement_compatibility(requirement: dict[str, Any], backend: AgentWalletBackend) -> dict[str, Any]:
518
+ wallet_summary = _wallet_x402_support_summary(backend)
519
+ network = _caip_network(requirement.get("network"))
520
+ scheme = _trim(requirement.get("scheme")).lower()
521
+ wallet_network_matches = network in wallet_summary["supported_caip_networks"]
522
+ chain = _backend_chain(backend)
523
+ planned_execution_supported = False
524
+ currently_executable = False
525
+ if chain == "solana":
526
+ planned_execution_supported = scheme == "exact" and network in set(
527
+ wallet_summary["planned_execution_networks"]
528
+ )
529
+ currently_executable = (
530
+ planned_execution_supported
531
+ and wallet_network_matches
532
+ and _solana_exact_execution_supported(backend)
533
+ )
534
+ elif chain == "evm":
535
+ planned_execution_supported = (
536
+ scheme in {"exact", "upto"}
537
+ and network in set(wallet_summary["planned_execution_networks"])
538
+ and _evm_payment_requirement_supported(requirement)
539
+ )
540
+ currently_executable = (
541
+ planned_execution_supported
542
+ and wallet_network_matches
543
+ and _evm_exact_execution_supported(backend)
544
+ )
545
+ if currently_executable:
546
+ reason = (
547
+ "Executable now through the local Solana exact buyer flow."
548
+ if chain == "solana"
549
+ else f"Executable now through the local EVM {scheme or 'exact'} buyer flow."
550
+ )
551
+ elif chain == "evm" and scheme == "exact" and not _evm_payment_requirement_supported(requirement):
552
+ reason = "This EVM exact payment requires a transfer method that is not enabled in the current wallet runtime."
553
+ elif chain == "evm" and scheme == "upto" and not _evm_payment_requirement_supported(requirement):
554
+ reason = "This EVM upto payment is missing a facilitatorAddress in its extra data, so it cannot be signed."
555
+ elif planned_execution_supported and wallet_network_matches:
556
+ if chain == "solana" and getattr(backend, "read_only", False):
557
+ reason = (
558
+ "Signer not loaded in this read-only preview context by "
559
+ "design (avoids unnecessary key material access on cheap "
560
+ "preview calls) -- the real x402_pay_request call loads "
561
+ "the signer and can still succeed here."
562
+ )
563
+ else:
564
+ reason = "Wallet network matches, but this backend does not yet expose a supported x402 signer path."
565
+ elif planned_execution_supported:
566
+ reason = "Planned execution path exists, but the requirement targets a different network than the active wallet."
567
+ else:
568
+ reason = "Unsupported scheme or network for the planned execution path."
569
+ return {
570
+ "wallet_type_supported": wallet_summary["wallet_type_supported"],
571
+ "wallet_network_matches": wallet_network_matches,
572
+ "planned_execution_supported": planned_execution_supported,
573
+ "currently_executable": currently_executable,
574
+ "reason": reason,
575
+ }
576
+
577
+
578
+ def _select_preferred_requirement(
579
+ requirements: list[dict[str, Any]],
580
+ backend: AgentWalletBackend,
581
+ ) -> dict[str, Any] | None:
582
+ compatible: list[dict[str, Any]] = []
583
+ exact_match: list[dict[str, Any]] = []
584
+ for requirement in requirements:
585
+ compatibility = _requirement_compatibility(requirement, backend)
586
+ if not compatibility["planned_execution_supported"]:
587
+ continue
588
+ compatible.append(requirement)
589
+ if compatibility["wallet_network_matches"]:
590
+ exact_match.append(requirement)
591
+ candidates = exact_match or compatible
592
+ if not candidates:
593
+ return None
594
+
595
+ def sort_key(item: dict[str, Any]) -> tuple[int, int, int]:
596
+ # Prefer upto over exact: upto settles for actual usage against a
597
+ # signed cap, which fits metered/usage-priced endpoints better than
598
+ # exact's fixed charge. Ties within a scheme still favor the cheapest
599
+ # declared amount.
600
+ scheme_rank = 0 if _trim(item.get("scheme")).lower() == "upto" else 1
601
+ amount = _trim(item.get("amount"))
602
+ if amount.isdigit():
603
+ return (scheme_rank, 0, int(amount))
604
+ return (scheme_rank, 1, 0)
605
+
606
+ return sorted(candidates, key=sort_key)[0]
607
+
608
+
609
+ def _build_request_metadata(
610
+ *,
611
+ url: str,
612
+ method: str = "GET",
613
+ headers: dict[str, Any] | None = None,
614
+ query: dict[str, Any] | None = None,
615
+ json_body: Any | None = None,
616
+ text_body: str | None = None,
617
+ ) -> dict[str, Any]:
618
+ request_url = _trim(url)
619
+ if not request_url:
620
+ raise ProviderError("x402-http", "url is required.")
621
+ http_method = _normalize_http_method(method)
622
+ normalized_headers = _normalize_headers(headers)
623
+ normalized_query = _normalize_query_params(query)
624
+ if json_body is not None and text_body is not None:
625
+ raise ProviderError("x402-http", "Provide either json_body or text_body, not both.")
626
+ final_url = _append_query(request_url, normalized_query)
627
+ body_hash = None
628
+ content_type = None
629
+ if json_body is not None:
630
+ body_hash = _hash_text(_canonical_json_text(json_body))
631
+ content_type = normalized_headers.get("Content-Type") or normalized_headers.get("content-type")
632
+ if not content_type:
633
+ normalized_headers["Content-Type"] = "application/json"
634
+ elif text_body is not None:
635
+ body_hash = _hash_text(text_body)
636
+ content_type = normalized_headers.get("Content-Type") or normalized_headers.get("content-type")
637
+ request_fingerprint = _hash_text(
638
+ _canonical_json_text(
639
+ {
640
+ "method": http_method,
641
+ "url": final_url,
642
+ "body_hash": body_hash,
643
+ }
644
+ )
645
+ )
646
+ return {
647
+ "url": final_url,
648
+ "host": _request_host(final_url),
649
+ "method": http_method,
650
+ "headers": normalized_headers,
651
+ "query": normalized_query,
652
+ "json_body": json_body,
653
+ "text_body": text_body,
654
+ "body_hash": body_hash,
655
+ "content_type": content_type,
656
+ "request_fingerprint": request_fingerprint,
657
+ }
658
+
659
+
660
+ async def _send_request(
661
+ *,
662
+ client: Any,
663
+ request: dict[str, Any],
664
+ extra_headers: dict[str, str] | None = None,
665
+ timeout: float | None = None,
666
+ ) -> Any:
667
+ headers = dict(request["headers"])
668
+ if extra_headers:
669
+ headers.update(extra_headers)
670
+ host = _trim(request.get("host")).lower().split(":", 1)[0]
671
+ if host == LASO_PARTNER_HOST or host.endswith("." + LASO_PARTNER_HOST):
672
+ headers.update(LASO_PARTNER_HEADERS)
673
+ return await client.request(
674
+ request["method"],
675
+ request["url"],
676
+ headers=headers,
677
+ json=request["json_body"] if request["json_body"] is not None else None,
678
+ content=request["text_body"] if request["text_body"] is not None else None,
679
+ timeout=timeout,
680
+ **({"follow_redirects": False} if host == LASO_PARTNER_HOST else {}),
681
+ )
682
+
683
+
684
+ def _build_x402_action_payload(
685
+ *,
686
+ backend: AgentWalletBackend,
687
+ request: dict[str, Any],
688
+ wallet_summary: dict[str, Any],
689
+ address: str | None,
690
+ status_code: int,
691
+ selected_payment: dict[str, Any] | None,
692
+ accepted_payments: list[dict[str, Any]] | None = None,
693
+ ) -> dict[str, Any]:
694
+ return {
695
+ "asset_type": "x402-request",
696
+ "source": "x402-http",
697
+ "chain": _backend_chain(backend),
698
+ "network": _backend_network(backend),
699
+ "x402_network": selected_payment.get("network") if isinstance(selected_payment, dict) else None,
700
+ "x402_scheme": selected_payment.get("scheme") if isinstance(selected_payment, dict) else None,
701
+ "x402_asset": selected_payment.get("asset") if isinstance(selected_payment, dict) else None,
702
+ "x402_amount": selected_payment.get("amount") if isinstance(selected_payment, dict) else None,
703
+ "x402_amount_display": selected_payment.get("amount_display")
704
+ if isinstance(selected_payment, dict)
705
+ else None,
706
+ "x402_pay_to": selected_payment.get("pay_to") if isinstance(selected_payment, dict) else None,
707
+ "request_url": request["url"],
708
+ "method": request["method"],
709
+ "request_fingerprint": request["request_fingerprint"],
710
+ "body_hash": request["body_hash"],
711
+ "content_type": request["content_type"],
712
+ "wallet": {
713
+ **wallet_summary,
714
+ "address": address,
715
+ },
716
+ "status_code": status_code,
717
+ "selected_payment": selected_payment,
718
+ "accepted_payments": accepted_payments,
719
+ "payment_required": selected_payment is not None,
720
+ }
721
+
722
+
723
+ def _response_preview(response: Any) -> Any:
724
+ try:
725
+ return response.json()
726
+ except Exception:
727
+ return _response_text(response)[:2000]
728
+
729
+
730
+ def _parse_payment_required_response(
731
+ response: Any,
732
+ *,
733
+ backend: AgentWalletBackend,
734
+ request: dict[str, Any],
735
+ address: str | None,
736
+ wallet_summary: dict[str, Any],
737
+ ) -> dict[str, Any]:
738
+ payment_required = response.headers.get("PAYMENT-REQUIRED")
739
+ if payment_required:
740
+ decoded = _decode_payment_required(payment_required)
741
+ else:
742
+ decoded = _decode_payment_required_body(response)
743
+ if decoded is None:
744
+ raise ProviderError(
745
+ "x402-http",
746
+ "Server returned HTTP 402 without a PAYMENT-REQUIRED header or an x402 v1 JSON body.",
747
+ details={"status_code": response.status_code, "url": request["url"]},
748
+ )
749
+ normalized_accepts = [
750
+ normalize_payment_requirement(requirement, source="payment_required", resource_url=request["url"])
751
+ for requirement in decoded["accepts"]
752
+ if isinstance(requirement, dict)
753
+ ]
754
+ compatibility = [
755
+ {
756
+ **requirement,
757
+ "compatibility": _requirement_compatibility(requirement, backend),
758
+ }
759
+ for requirement in normalized_accepts
760
+ ]
761
+ selected = _select_preferred_requirement(normalized_accepts, backend)
762
+ preview = _build_x402_action_payload(
763
+ backend=backend,
764
+ request=request,
765
+ wallet_summary=wallet_summary,
766
+ address=address,
767
+ status_code=response.status_code,
768
+ selected_payment=selected,
769
+ accepted_payments=compatibility,
770
+ )
771
+ siwx = _siwx_summary(decoded.get("extensions"), backend)
772
+ siwx_available = bool(siwx and siwx["wallet_compatible"])
773
+ preview.update(
774
+ {
775
+ "execute_available": siwx_available or bool(
776
+ isinstance(selected, dict)
777
+ and _requirement_compatibility(selected, backend)["currently_executable"]
778
+ ),
779
+ # Execute signs in first; it pays only if the sign-in does not grant access.
780
+ "siwx": siwx,
781
+ "siwx_available": siwx_available,
782
+ "x402_version": decoded["x402_version"],
783
+ "response_headers": {
784
+ "payment-required": decoded["encoded"],
785
+ "content-type": response.headers.get("content-type"),
786
+ },
787
+ }
788
+ )
789
+ return preview
790
+
791
+
792
+ def _validate_payment_requirement(
793
+ selected: dict[str, Any] | None,
794
+ *,
795
+ backend: AgentWalletBackend,
796
+ request_url: str,
797
+ ) -> dict[str, Any]:
798
+ if not isinstance(selected, dict):
799
+ raise ProviderError(
800
+ "x402-validate",
801
+ "This endpoint returned HTTP 402 but no compatible payment option was found for the active wallet.",
802
+ details={
803
+ "request_url": request_url,
804
+ "wallet_chain": _backend_chain(backend),
805
+ "wallet_network": _backend_network(backend),
806
+ },
807
+ )
808
+
809
+ scheme = _trim(selected.get("scheme")).lower()
810
+ if scheme not in {"exact", "upto"}:
811
+ raise ProviderError(
812
+ "x402-validate",
813
+ f"Unsupported x402 payment scheme '{scheme or 'unknown'}'. Only 'exact' and 'upto' are supported.",
814
+ details={"request_url": request_url, "selected_payment": selected},
815
+ )
816
+
817
+ if not _trim(selected.get("pay_to")):
818
+ raise ProviderError(
819
+ "x402-validate",
820
+ "Payment destination (payTo) is missing from the x402 requirement.",
821
+ details={"request_url": request_url, "selected_payment": selected},
822
+ )
823
+
824
+ compatibility = _requirement_compatibility(selected, backend)
825
+ if compatibility["currently_executable"]:
826
+ return selected
827
+
828
+ chain = _backend_chain(backend) or "unknown"
829
+ network = _backend_network(backend) or "unknown"
830
+ requirement_network = _caip_network(selected.get("network")) or "unknown"
831
+ if chain == "solana" and requirement_network not in SOLANA_CAIP_BY_NETWORK.values():
832
+ message = (
833
+ f"This endpoint requires payment on {requirement_network}, but the active wallet is Solana ({network})."
834
+ )
835
+ elif chain == "evm" and requirement_network not in EVM_CAIP_BY_NETWORK.values():
836
+ message = (
837
+ f"This endpoint requires payment on {requirement_network}, but the active wallet is EVM ({network})."
838
+ )
839
+ else:
840
+ message = str(compatibility["reason"])
841
+
842
+ raise ProviderError(
843
+ "x402-validate",
844
+ message,
845
+ details={
846
+ "request_url": request_url,
847
+ "selected_payment": selected,
848
+ "compatibility": compatibility,
849
+ },
850
+ )
851
+
852
+
853
+ def _validate_request_execution_policy(
854
+ *,
855
+ request: dict[str, Any],
856
+ backend: AgentWalletBackend,
857
+ ) -> None:
858
+ host = _trim(request.get("host")).lower()
859
+ if host == "x402.alchemy.com":
860
+ headers = request.get("headers")
861
+ has_auth = isinstance(headers, dict) and any(
862
+ str(key).strip().lower() == "authorization" and str(value).strip()
863
+ for key, value in headers.items()
864
+ )
865
+ if not has_auth:
866
+ raise ProviderError(
867
+ "x402-validate",
868
+ (
869
+ "Alchemy's x402 gateway needs wallet-auth headers in addition to the payment challenge. "
870
+ "The generic x402 tool does not mint Alchemy SIWE/SIWS auth tokens yet, so this endpoint "
871
+ "is not safe to execute through the generic flow."
872
+ ),
873
+ details={
874
+ "request_url": request.get("url"),
875
+ "host": host,
876
+ "wallet_chain": _backend_chain(backend),
877
+ "wallet_network": _backend_network(backend),
878
+ "hint": "Use a dedicated Alchemy agent gateway integration or authenticated CLI flow.",
879
+ },
880
+ )
881
+
882
+ def _select_sdk_payment_requirement(
883
+ payment_required: Any,
884
+ *,
885
+ selected_payment: dict[str, Any],
886
+ ) -> Any:
887
+ accepts = getattr(payment_required, "accepts", None)
888
+ if not isinstance(accepts, list) or not accepts:
889
+ raise ProviderError("x402-http", "Decoded x402 payment payload does not contain accepts[].")
890
+
891
+ selected_raw = selected_payment.get("raw") if isinstance(selected_payment, dict) else None
892
+ if isinstance(selected_raw, dict):
893
+ for requirement in accepts:
894
+ model_dump = getattr(requirement, "model_dump", None)
895
+ if callable(model_dump):
896
+ dumped = model_dump(by_alias=True, exclude_none=True)
897
+ if dumped == selected_raw:
898
+ return requirement
899
+
900
+ for requirement in accepts:
901
+ if (
902
+ _trim(_requirement_field(requirement, "scheme")).lower()
903
+ == _trim(selected_payment.get("scheme")).lower()
904
+ and _trim(_requirement_field(requirement, "network"))
905
+ == _trim(selected_payment.get("network"))
906
+ and _trim(_requirement_field(requirement, "asset"))
907
+ == _trim(selected_payment.get("asset"))
908
+ and _trim(_requirement_field(requirement, "amount"))
909
+ == _trim(selected_payment.get("amount"))
910
+ and _trim(_requirement_field(requirement, "pay_to"))
911
+ == _trim(selected_payment.get("pay_to"))
912
+ ):
913
+ return requirement
914
+
915
+ if len(accepts) == 1:
916
+ return accepts[0]
917
+
918
+ raise ProviderError(
919
+ "x402-http",
920
+ "Could not match the selected x402 payment back to the decoded PAYMENT-REQUIRED payload.",
921
+ details={
922
+ "selected_payment": selected_payment,
923
+ "accepts_count": len(accepts),
924
+ },
925
+ )
926
+
927
+
928
+ # The `upto` Permit2 signature authorizes the (merchant + facilitator) pair to
929
+ # settle any amount in [0, cap] until `max_timeout_seconds` elapses, with no
930
+ # on-chain check beyond the deadline itself. A merchant-declared timeout with
931
+ # no upper bound would extend that facilitator-discretion window indefinitely,
932
+ # so cap it defensively before signing. `exact` amounts are fixed in the
933
+ # signature, so this cap only applies to `upto`.
934
+ MAX_UPTO_DEADLINE_SECONDS = 7 * 24 * 60 * 60 # 7 days
935
+
936
+
937
+ def _cap_upto_deadline(requirement: Any) -> Any:
938
+ if _trim(getattr(requirement, "scheme", "")).lower() != "upto":
939
+ return requirement
940
+ timeout = getattr(requirement, "max_timeout_seconds", None)
941
+ if not isinstance(timeout, int) or timeout <= MAX_UPTO_DEADLINE_SECONDS:
942
+ return requirement
943
+ return requirement.model_copy(update={"max_timeout_seconds": MAX_UPTO_DEADLINE_SECONDS})
944
+
945
+
946
+ def _build_selected_payment_required_payload(
947
+ payment_required: Any,
948
+ *,
949
+ selected_payment: dict[str, Any],
950
+ ) -> Any:
951
+ selected_requirement = _select_sdk_payment_requirement(
952
+ payment_required,
953
+ selected_payment=selected_payment,
954
+ )
955
+ selected_requirement = _cap_upto_deadline(selected_requirement)
956
+ return payment_required.model_copy(update={"accepts": [selected_requirement]})
957
+
958
+
959
+ def _load_x402_common_sdk() -> dict[str, Any]:
960
+ try:
961
+ from x402 import x402Client
962
+ from x402.http.x402_http_client_base import x402HTTPClientBase
963
+ from x402.http.utils import decode_payment_required_header
964
+ except ImportError as exc:
965
+ raise ProviderError(
966
+ "x402-sdk",
967
+ "x402 execution requires the x402 Python package with HTTP client support.",
968
+ details={"hint": 'Install dependencies so `x402[httpx]` is available in the wallet runtime.'},
969
+ ) from exc
970
+ return {
971
+ "x402Client": x402Client,
972
+ "x402HTTPClientBase": x402HTTPClientBase,
973
+ "decode_payment_required_header": decode_payment_required_header,
974
+ }
975
+
976
+
977
+ def _load_x402_solana_sdk() -> dict[str, Any]:
978
+ sdk = _load_x402_common_sdk()
979
+ try:
980
+ from x402.mechanisms.svm.exact import register_exact_svm_client
981
+ except ImportError as exc:
982
+ raise ProviderError(
983
+ "x402-sdk",
984
+ "x402 Solana execution requires SVM support.",
985
+ details={"hint": 'Install dependencies so `x402[httpx,svm]` is available in the wallet runtime.'},
986
+ ) from exc
987
+ sdk.update(
988
+ {
989
+ "register_exact_svm_client": register_exact_svm_client,
990
+ }
991
+ )
992
+ return sdk
993
+
994
+
995
+ def _load_x402_evm_sdk() -> dict[str, Any]:
996
+ sdk = _load_x402_common_sdk()
997
+ try:
998
+ from x402.mechanisms.evm.exact import register_exact_evm_client
999
+ except ImportError as exc:
1000
+ raise ProviderError(
1001
+ "x402-sdk",
1002
+ "x402 EVM execution requires EVM support.",
1003
+ details={"hint": 'Install dependencies so `x402[httpx,evm]` is available in the wallet runtime.'},
1004
+ ) from exc
1005
+ try:
1006
+ from x402.mechanisms.evm.upto import UptoEvmScheme
1007
+ except ImportError as exc:
1008
+ raise ProviderError(
1009
+ "x402-sdk",
1010
+ "x402 EVM upto-scheme execution requires the upto mechanism module.",
1011
+ details={"hint": 'Install dependencies so `x402[httpx,evm]` is available in the wallet runtime.'},
1012
+ ) from exc
1013
+ sdk.update(
1014
+ {
1015
+ "register_exact_evm_client": register_exact_evm_client,
1016
+ "UptoEvmScheme": UptoEvmScheme,
1017
+ }
1018
+ )
1019
+ return sdk
1020
+
1021
+
1022
+ def _load_x402_sdk() -> dict[str, Any]:
1023
+ return _load_x402_common_sdk()
1024
+
1025
+
1026
+ def _load_x402_siwx_sdk() -> dict[str, Any]:
1027
+ try:
1028
+ from x402.extensions.sign_in_with_x import (
1029
+ SIGN_IN_WITH_X,
1030
+ CreateSIWxClientExtensionOptions,
1031
+ create_siwx_client_extension,
1032
+ )
1033
+ except ImportError as exc:
1034
+ raise ProviderError(
1035
+ "x402-sdk",
1036
+ "x402 sign-in-with-x execution requires the SIWx extension module.",
1037
+ details={"hint": 'Install dependencies so `x402[httpx,evm,svm]` is available in the wallet runtime.'},
1038
+ ) from exc
1039
+ return {
1040
+ "SIGN_IN_WITH_X": SIGN_IN_WITH_X,
1041
+ "CreateSIWxClientExtensionOptions": CreateSIWxClientExtensionOptions,
1042
+ "create_siwx_client_extension": create_siwx_client_extension,
1043
+ }
1044
+
1045
+
1046
+ async def _maybe_attach_siwx_header(
1047
+ *,
1048
+ payment_required: Any,
1049
+ signer: Any,
1050
+ headers: dict[str, str],
1051
+ request_url: str,
1052
+ ) -> dict[str, str]:
1053
+ """Attach a Sign-In-With-X header when the merchant declares that extension.
1054
+
1055
+ *request_url* is the URL the header will be sent to: the SDK refuses to
1056
+ sign a challenge whose domain/uri is bound to a different origin.
1057
+ Best-effort: any failure to build the SIWx credential leaves *headers*
1058
+ unchanged, matching the upstream SDK's on_payment_required hook contract
1059
+ (which swallows exceptions the same way).
1060
+ """
1061
+ extensions = getattr(payment_required, "extensions", None) or {}
1062
+ if not extensions:
1063
+ return headers
1064
+ try:
1065
+ sdk = _load_x402_siwx_sdk()
1066
+ except ProviderError:
1067
+ log.warning("x402 SIWx challenge ignored: the SDK sign-in-with-x extension is unavailable")
1068
+ return headers
1069
+ if sdk["SIGN_IN_WITH_X"] not in extensions:
1070
+ return headers
1071
+ extension = sdk["create_siwx_client_extension"](
1072
+ sdk["CreateSIWxClientExtensionOptions"](signers=[signer])
1073
+ )
1074
+ context = SimpleNamespace(payment_required=payment_required, request_url=request_url)
1075
+ try:
1076
+ result = await extension.transport_hooks.http.on_payment_required(None, context)
1077
+ except Exception as exc:
1078
+ log.warning(
1079
+ "x402 SIWx header build failed; continuing without it",
1080
+ extra={"error_type": type(exc).__name__, "error": str(exc) or None},
1081
+ )
1082
+ return headers
1083
+ siwx_headers = getattr(result, "headers", None) if result is not None else None
1084
+ if not siwx_headers:
1085
+ log.warning(
1086
+ "x402 SIWx challenge could not be signed by the active wallet; continuing without it",
1087
+ extra={"request_url": request_url},
1088
+ )
1089
+ return headers
1090
+ return {**headers, **siwx_headers}
1091
+
1092
+
1093
+ async def _build_x402_wallet_signer(backend: AgentWalletBackend) -> Any:
1094
+ chain = _backend_chain(backend)
1095
+ if chain == "solana":
1096
+ return _build_solana_sdk_signer(backend)
1097
+ if chain == "evm":
1098
+ address = await backend.get_address()
1099
+ if not isinstance(address, str) or not address.strip():
1100
+ raise ProviderError("x402-evm", "The active EVM backend did not resolve a payer address.")
1101
+ return _build_evm_sdk_signer(backend, address.strip())
1102
+ raise ProviderError("x402-http", "Only Solana and EVM wallets can sign in with x402.", details={"chain": chain})
1103
+
1104
+
1105
+ async def _build_siwx_headers(
1106
+ *,
1107
+ backend: AgentWalletBackend,
1108
+ payment_required_header: str,
1109
+ request_url: str,
1110
+ ) -> dict[str, str]:
1111
+ """Sign the merchant's SIWx challenge once; reused for the sign-in and paid retries.
1112
+
1113
+ The server records a nonce only when it grants access, so an unaccepted
1114
+ sign-in leaves the same header valid to accompany the payment.
1115
+ """
1116
+ extensions = _decode_payment_required(payment_required_header).get("extensions")
1117
+ if _siwx_declaration(extensions) is None:
1118
+ return {}
1119
+ try:
1120
+ signer = await _build_x402_wallet_signer(backend)
1121
+ except ProviderError as exc:
1122
+ log.warning("x402 SIWx signer unavailable; continuing without sign-in", extra={"error": str(exc)})
1123
+ return {}
1124
+ return await _maybe_attach_siwx_header(
1125
+ payment_required=SimpleNamespace(extensions=extensions),
1126
+ signer=signer,
1127
+ headers={},
1128
+ request_url=request_url,
1129
+ )
1130
+
1131
+
1132
+ def _build_solana_sdk_signer(backend: AgentWalletBackend) -> Any:
1133
+ signer = getattr(backend, "signer", None)
1134
+ if signer is None or not hasattr(signer, "export_keypair_bytes"):
1135
+ raise ProviderError(
1136
+ "x402-solana",
1137
+ "The active Solana backend does not expose a local signer for x402 payments.",
1138
+ )
1139
+ try:
1140
+ from solders.keypair import Keypair
1141
+ except ImportError as exc:
1142
+ raise ProviderError(
1143
+ "x402-solana",
1144
+ "Solders is required for Solana x402 signing.",
1145
+ ) from exc
1146
+
1147
+ class _OpenClawSolanaX402Signer:
1148
+ def __init__(self, wallet_signer: Any):
1149
+ self._wallet_signer = wallet_signer
1150
+ self._keypair = Keypair.from_bytes(wallet_signer.export_keypair_bytes())
1151
+
1152
+ @property
1153
+ def address(self) -> str:
1154
+ return str(self._wallet_signer.address)
1155
+
1156
+ @property
1157
+ def keypair(self) -> Any:
1158
+ return self._keypair
1159
+
1160
+ def sign_transaction(self, tx: Any) -> Any:
1161
+ tx.sign([self._keypair])
1162
+ return tx
1163
+
1164
+ return _OpenClawSolanaX402Signer(signer)
1165
+
1166
+
1167
+ def _build_evm_sdk_signer(backend: AgentWalletBackend, address: str) -> Any:
1168
+ sign_typed_data = getattr(backend, "sign_x402_evm_exact_typed_data", None)
1169
+ if not callable(sign_typed_data):
1170
+ raise ProviderError(
1171
+ "x402-evm",
1172
+ "The active EVM backend does not expose an x402 exact typed-data signer.",
1173
+ )
1174
+
1175
+ class _NoEthAccountSentinel:
1176
+ """Truthy placeholder with neither `.sign_message` nor `.address`.
1177
+
1178
+ x402's SIWx sign_evm_message() treats a signer with `.account` unset
1179
+ but both `.sign_message` and `.address` present as an eth_account-style
1180
+ wallet, and calls `.sign_message(SignableMessage)` positionally instead
1181
+ of our keyword-based `sign_message(message=..., account=...)`. Exposing
1182
+ a benign `.account` here short-circuits that fallback so the SDK
1183
+ reaches our intended call path.
1184
+ """
1185
+
1186
+ class _OpenClawEvmX402Signer:
1187
+ def __init__(self, wallet_backend: AgentWalletBackend, wallet_address: str):
1188
+ self._wallet_backend = wallet_backend
1189
+ self._address = wallet_address
1190
+ self.account = _NoEthAccountSentinel()
1191
+
1192
+ @property
1193
+ def address(self) -> str:
1194
+ return self._address
1195
+
1196
+ async def sign_message(self, *, message: str, account: Any = None) -> str:
1197
+ return await self._wallet_backend.sign_message(message)
1198
+
1199
+ def sign_typed_data(
1200
+ self,
1201
+ domain: Any,
1202
+ types: dict[str, list[Any]],
1203
+ primary_type: str,
1204
+ message: dict[str, Any],
1205
+ ) -> bytes:
1206
+ normalized_types: dict[str, list[dict[str, str]]] = {}
1207
+ for type_name, fields in types.items():
1208
+ normalized_types[type_name] = [
1209
+ {
1210
+ "name": _trim(getattr(field, "name", "")),
1211
+ "type": _trim(getattr(field, "type", "")),
1212
+ }
1213
+ for field in fields
1214
+ ]
1215
+ domain_payload = {
1216
+ "name": getattr(domain, "name", None),
1217
+ "version": getattr(domain, "version", None),
1218
+ "chainId": getattr(domain, "chain_id", None),
1219
+ "verifyingContract": getattr(domain, "verifying_contract", None),
1220
+ }
1221
+ return self._wallet_backend.sign_x402_evm_exact_typed_data(
1222
+ domain=domain_payload,
1223
+ types=normalized_types,
1224
+ primary_type=primary_type,
1225
+ message=message,
1226
+ )
1227
+
1228
+ return _OpenClawEvmX402Signer(backend, address)
1229
+
1230
+
1231
+ def _bind_sdk_spend_limit(client: Any, selected_payment: dict[str, Any]) -> None:
1232
+ """Bound the SDK to the already policy-checked canonical USDC requirement.
1233
+
1234
+ New SDKs default to $1 independently of the wallet's approval policy.
1235
+ Older SDKs have no spend-controls API. Leave other assets on SDK defaults.
1236
+ """
1237
+ setter = getattr(client, "set_spend_controls", None)
1238
+ if not callable(setter):
1239
+ return
1240
+ network = _trim(selected_payment.get("network"))
1241
+ asset = _trim(selected_payment.get("asset"))
1242
+ amount = _trim(selected_payment.get("amount"))
1243
+ canonical_usdc = {
1244
+ "eip155:8453": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
1245
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
1246
+ }
1247
+ expected = canonical_usdc.get(network)
1248
+ matches = bool(expected) and (asset.lower() == expected if network.startswith("eip155:") else asset == expected)
1249
+ if not matches or not amount.isascii() or not amount.isdigit():
1250
+ return
1251
+ setter({"allowed_assets": [{"network": network, "asset": asset, "max_amount_per_payment": amount}]})
1252
+
1253
+
1254
+ async def _create_payment_headers(
1255
+ *,
1256
+ backend: AgentWalletBackend,
1257
+ payment_required_header: str,
1258
+ selected_payment: dict[str, Any],
1259
+ siwx_headers: dict[str, str] | None = None,
1260
+ ) -> dict[str, str]:
1261
+ chain = _backend_chain(backend)
1262
+ if chain == "solana":
1263
+ sdk = _load_x402_solana_sdk()
1264
+ payment_required = sdk["decode_payment_required_header"](payment_required_header)
1265
+ selected_payload = _build_selected_payment_required_payload(
1266
+ payment_required,
1267
+ selected_payment=selected_payment,
1268
+ )
1269
+ client = sdk["x402Client"]()
1270
+ _bind_sdk_spend_limit(client, selected_payment)
1271
+ sdk_rpc_url = _backend_solana_sdk_rpc_url(backend)
1272
+ if not sdk_rpc_url:
1273
+ raise ProviderError(
1274
+ "x402-solana",
1275
+ "No direct Solana RPC URL is available for the x402 SDK signer path.",
1276
+ details={"network": _backend_network(backend)},
1277
+ )
1278
+ solana_signer = _build_solana_sdk_signer(backend)
1279
+ sdk["register_exact_svm_client"](
1280
+ client,
1281
+ solana_signer,
1282
+ networks=str(selected_payment["network"]),
1283
+ rpc_url=sdk_rpc_url,
1284
+ )
1285
+ try:
1286
+ payment_payload = await client.create_payment_payload(selected_payload)
1287
+ except Exception as exc:
1288
+ raise ProviderError(
1289
+ "x402-solana",
1290
+ "Failed to build the Solana x402 payment payload.",
1291
+ details={
1292
+ "network": _backend_network(backend),
1293
+ "sdk_rpc_url": sdk_rpc_url,
1294
+ "error_type": type(exc).__name__,
1295
+ "error": str(exc) or None,
1296
+ },
1297
+ ) from exc
1298
+ headers = sdk["x402HTTPClientBase"]().encode_payment_signature_header(payment_payload)
1299
+ return {**headers, **(siwx_headers or {})}
1300
+
1301
+ if chain == "evm":
1302
+ sdk = _load_x402_evm_sdk()
1303
+ payment_required = sdk["decode_payment_required_header"](payment_required_header)
1304
+ selected_payload = _build_selected_payment_required_payload(
1305
+ payment_required,
1306
+ selected_payment=selected_payment,
1307
+ )
1308
+ client = sdk["x402Client"]()
1309
+ _bind_sdk_spend_limit(client, selected_payment)
1310
+ address = await backend.get_address()
1311
+ if not isinstance(address, str) or not address.strip():
1312
+ raise ProviderError("x402-evm", "The active EVM backend did not resolve a payer address.")
1313
+ evm_signer = _build_evm_sdk_signer(backend, address.strip())
1314
+ network = str(selected_payment["network"])
1315
+ sdk["register_exact_evm_client"](client, evm_signer, networks=network)
1316
+ # `upto` reuses the same typed-data signer as `exact`; registering both
1317
+ # lets the SDK settle whichever scheme the merchant's accepted
1318
+ # requirement (already narrowed to one entry above) turns out to use.
1319
+ client.register(network, sdk["UptoEvmScheme"](evm_signer))
1320
+ payment_payload = await client.create_payment_payload(selected_payload)
1321
+ headers = sdk["x402HTTPClientBase"]().encode_payment_signature_header(payment_payload)
1322
+ return {**headers, **(siwx_headers or {})}
1323
+
1324
+ raise ProviderError(
1325
+ "x402-http",
1326
+ "Only Solana and EVM buyer flows are executable in this milestone.",
1327
+ details={"chain": chain},
1328
+ )
1329
+
1330
+
1331
+ def _extract_settlement_header(response: Any) -> dict[str, Any]:
1332
+ sdk = _load_x402_sdk()
1333
+ settle = sdk["x402HTTPClientBase"]().get_payment_settle_response(
1334
+ lambda name: response.headers.get(name)
1335
+ )
1336
+ return settle.model_dump(by_alias=True, exclude_none=True)
1337
+
1338
+
1339
+ def _extract_settlement_header_safe(response: Any) -> dict[str, Any] | None:
1340
+ try:
1341
+ return _extract_settlement_header(response)
1342
+ except Exception as exc:
1343
+ log.warning(
1344
+ "x402 settlement header parse failed",
1345
+ extra={
1346
+ "status_code": getattr(response, "status_code", None),
1347
+ "payment_response": response.headers.get("PAYMENT-RESPONSE")
1348
+ if hasattr(response, "headers")
1349
+ else None,
1350
+ "x_payment_response": response.headers.get("X-PAYMENT-RESPONSE")
1351
+ if hasattr(response, "headers")
1352
+ else None,
1353
+ "error_type": type(exc).__name__,
1354
+ "error": str(exc) or None,
1355
+ },
1356
+ )
1357
+ return None
1358
+
1359
+
1360
+ def _log_x402_execute(
1361
+ *,
1362
+ request: dict[str, Any],
1363
+ selected_payment: dict[str, Any] | None,
1364
+ response: Any,
1365
+ settlement: dict[str, Any] | None,
1366
+ ) -> None:
1367
+ log.info(
1368
+ "x402 execute completed",
1369
+ extra={
1370
+ "url": request.get("url"),
1371
+ "method": request.get("method"),
1372
+ "request_fingerprint": request.get("request_fingerprint"),
1373
+ "x402_network": selected_payment.get("network") if isinstance(selected_payment, dict) else None,
1374
+ "x402_asset": selected_payment.get("asset") if isinstance(selected_payment, dict) else None,
1375
+ "x402_amount": selected_payment.get("amount") if isinstance(selected_payment, dict) else None,
1376
+ "x402_pay_to": selected_payment.get("pay_to") if isinstance(selected_payment, dict) else None,
1377
+ "status_code": getattr(response, "status_code", None),
1378
+ "transaction": settlement.get("transaction") if isinstance(settlement, dict) else None,
1379
+ "confirmed": bool(settlement and settlement.get("success")),
1380
+ },
1381
+ )
1382
+
1383
+
1384
+ def _discovery_cache_get(cache_key: str) -> dict[str, Any] | None:
1385
+ entry = _discovery_cache.get(cache_key)
1386
+ if entry is None:
1387
+ return None
1388
+ expires_at, payload_text = entry
1389
+ if expires_at <= time.monotonic():
1390
+ _discovery_cache.pop(cache_key, None)
1391
+ return None
1392
+ return json.loads(payload_text)
1393
+
1394
+
1395
+ def _discovery_cache_set(cache_key: str, payload: dict[str, Any]) -> None:
1396
+ try:
1397
+ payload_text = json.dumps(payload)
1398
+ except (TypeError, ValueError):
1399
+ return
1400
+ if len(_discovery_cache) >= _DISCOVERY_CACHE_MAX_ENTRIES:
1401
+ for stale_key in sorted(_discovery_cache, key=lambda key: _discovery_cache[key][0])[
1402
+ : len(_discovery_cache) - _DISCOVERY_CACHE_MAX_ENTRIES + 1
1403
+ ]:
1404
+ _discovery_cache.pop(stale_key, None)
1405
+ _discovery_cache[cache_key] = (time.monotonic() + DISCOVERY_CACHE_TTL_SECONDS, payload_text)
1406
+
1407
+
1408
+ async def search_services(
1409
+ *,
1410
+ query: str | None = None,
1411
+ discovery_provider: str = "auto",
1412
+ network: str | None = None,
1413
+ asset: str | None = None,
1414
+ scheme: str | None = None,
1415
+ max_usd_price: str | None = None,
1416
+ limit: int = 10,
1417
+ ) -> dict[str, Any]:
1418
+ provider = _normalize_discovery_provider(discovery_provider)
1419
+ if provider == "auto":
1420
+ provider = "cdp_bazaar"
1421
+ if limit <= 0:
1422
+ raise ProviderError("x402-discovery", "limit must be greater than zero.")
1423
+ cache_key = _canonical_json_text(
1424
+ {
1425
+ "op": "search_services",
1426
+ "provider": provider,
1427
+ "query": _trim(query),
1428
+ "network": _trim(network),
1429
+ "asset": _trim(asset),
1430
+ "scheme": _trim(scheme),
1431
+ "max_usd_price": _trim(max_usd_price),
1432
+ "limit": limit,
1433
+ }
1434
+ )
1435
+ cached = _discovery_cache_get(cache_key)
1436
+ if cached is not None:
1437
+ return cached
1438
+ result = await _search_services_uncached(
1439
+ query=query,
1440
+ provider=provider,
1441
+ network=network,
1442
+ asset=asset,
1443
+ scheme=scheme,
1444
+ max_usd_price=max_usd_price,
1445
+ limit=limit,
1446
+ )
1447
+ _discovery_cache_set(cache_key, result)
1448
+ return result
1449
+
1450
+
1451
+ async def _search_services_uncached(
1452
+ *,
1453
+ query: str | None,
1454
+ provider: str,
1455
+ network: str | None,
1456
+ asset: str | None,
1457
+ scheme: str | None,
1458
+ max_usd_price: str | None,
1459
+ limit: int,
1460
+ ) -> dict[str, Any]:
1461
+ client = get_client()
1462
+
1463
+ if provider == "cdp_bazaar":
1464
+ if query and _trim(query):
1465
+ # CDP rejects empty filter values with HTTP 400, so omit unset params
1466
+ # entirely instead of sending them as blank strings.
1467
+ search_params: dict[str, Any] = {"query": _trim(query), "limit": min(limit, 20)}
1468
+ for name, value in (
1469
+ ("network", network),
1470
+ ("asset", asset),
1471
+ ("scheme", scheme),
1472
+ ("maxUsdPrice", max_usd_price),
1473
+ ):
1474
+ if _trim(value):
1475
+ search_params[name] = _trim(value)
1476
+ response = await client.get(
1477
+ f"{CDP_BAZAAR_DISCOVERY_BASE_URL}/search",
1478
+ params=search_params,
1479
+ )
1480
+ payload = _parse_json_response(
1481
+ response, provider="x402-cdp-bazaar", operation="CDP Bazaar search"
1482
+ )
1483
+ resources = payload.get("resources") if isinstance(payload, dict) else None
1484
+ if not isinstance(resources, list):
1485
+ raise ProviderError("x402-cdp-bazaar", "Unexpected CDP Bazaar search response.")
1486
+ items = [_normalize_cdp_resource(item) for item in resources if isinstance(item, dict)]
1487
+ return {
1488
+ "discovery_provider": provider,
1489
+ "query": _trim(query),
1490
+ "count": len(items),
1491
+ "partial_results": bool(payload.get("partialResults")),
1492
+ "search_method": payload.get("searchMethod"),
1493
+ "items": items,
1494
+ }
1495
+
1496
+ response = await client.get(
1497
+ f"{CDP_BAZAAR_DISCOVERY_BASE_URL}/resources",
1498
+ params={"type": "http", "limit": min(limit, 1000), "offset": 0},
1499
+ )
1500
+ payload = _parse_json_response(
1501
+ response, provider="x402-cdp-bazaar", operation="CDP Bazaar resources"
1502
+ )
1503
+ resources = payload.get("items") if isinstance(payload, dict) else None
1504
+ if not isinstance(resources, list):
1505
+ raise ProviderError("x402-cdp-bazaar", "Unexpected CDP Bazaar resources response.")
1506
+ items = [_normalize_cdp_resource(item) for item in resources if isinstance(item, dict)]
1507
+ return {
1508
+ "discovery_provider": provider,
1509
+ "query": "",
1510
+ "count": len(items),
1511
+ "pagination": payload.get("pagination") if isinstance(payload, dict) else None,
1512
+ "items": items,
1513
+ }
1514
+
1515
+ endpoint = "/services/search" if query and _trim(query) else "/services/"
1516
+ params = {"q": _trim(query)} if query and _trim(query) else None
1517
+ response = await client.get(f"{AGENTIC_MARKET_API_BASE_URL}{endpoint}", params=params)
1518
+ payload = _parse_json_response(
1519
+ response, provider="x402-agentic-market", operation="Agentic Market search"
1520
+ )
1521
+ services = payload.get("services") if isinstance(payload, dict) else None
1522
+ if not isinstance(services, list):
1523
+ raise ProviderError("x402-agentic-market", "Unexpected Agentic Market response.")
1524
+ normalized = [
1525
+ _normalize_agentic_service(service)
1526
+ for service in services
1527
+ if isinstance(service, dict)
1528
+ ]
1529
+ if network:
1530
+ needle = _trim(network).lower()
1531
+ normalized = [
1532
+ item
1533
+ for item in normalized
1534
+ if needle in {entry.lower() for entry in item.get("networks") or []}
1535
+ ]
1536
+ if scheme:
1537
+ needle = _trim(scheme).lower()
1538
+ normalized = [
1539
+ item
1540
+ for item in normalized
1541
+ if any(_trim(req.get("scheme")).lower() == needle for req in item.get("accepts") or [])
1542
+ ]
1543
+ if asset:
1544
+ needle = _trim(asset).lower()
1545
+ normalized = [
1546
+ item
1547
+ for item in normalized
1548
+ if any(_trim(req.get("asset")).lower() == needle for req in item.get("accepts") or [])
1549
+ ]
1550
+ return {
1551
+ "discovery_provider": provider,
1552
+ "query": _trim(query),
1553
+ "count": len(normalized[:limit]),
1554
+ "items": normalized[:limit],
1555
+ }
1556
+
1557
+
1558
+ async def get_service_details(
1559
+ *,
1560
+ reference: str,
1561
+ discovery_provider: str = "auto",
1562
+ ) -> dict[str, Any]:
1563
+ ref = _trim(reference)
1564
+ if not ref:
1565
+ raise ProviderError("x402-discovery", "reference is required.")
1566
+ provider = _normalize_discovery_provider(discovery_provider)
1567
+ if provider == "auto":
1568
+ provider = (
1569
+ "cdp_bazaar" if ref.startswith("http://") or ref.startswith("https://") else "agentic_market"
1570
+ )
1571
+
1572
+ if provider == "cdp_bazaar":
1573
+
1574
+ def _match(items: list[dict[str, Any]]) -> dict[str, Any] | None:
1575
+ exact = next((item for item in items if item.get("resource") == ref), None)
1576
+ if exact is not None:
1577
+ return exact
1578
+ needle = ref.lower()
1579
+ return next(
1580
+ (
1581
+ item
1582
+ for item in items
1583
+ if needle in _trim(item.get("resource")).lower()
1584
+ or needle in _trim(item.get("description")).lower()
1585
+ ),
1586
+ None,
1587
+ )
1588
+
1589
+ # Server-side search covers the full Bazaar catalog; a plain resource
1590
+ # listing only ever returns the first page, so use it as a last resort.
1591
+ queries = [ref]
1592
+ if ref.startswith(("http://", "https://")):
1593
+ netloc = _trim(urlsplit(ref).netloc)
1594
+ if netloc and netloc != ref:
1595
+ queries.append(netloc)
1596
+ exact: dict[str, Any] | None = None
1597
+ for candidate_query in queries:
1598
+ results = await search_services(
1599
+ query=candidate_query, discovery_provider="cdp_bazaar", limit=20
1600
+ )
1601
+ exact = _match(results["items"])
1602
+ if exact is not None:
1603
+ break
1604
+ if exact is None:
1605
+ resources = await search_services(discovery_provider="cdp_bazaar", limit=200)
1606
+ exact = _match(resources["items"])
1607
+ if exact is None:
1608
+ raise ProviderError("x402-cdp-bazaar", f"No Bazaar resource matched: {ref}")
1609
+ return {"discovery_provider": provider, "service": exact}
1610
+
1611
+ query = ref
1612
+ if ref.startswith("http://") or ref.startswith("https://"):
1613
+ query = urlsplit(ref).netloc or ref
1614
+ services = await search_services(query=query, discovery_provider="agentic_market", limit=20)
1615
+ needle = ref.lower()
1616
+ exact = next(
1617
+ (
1618
+ item
1619
+ for item in services["items"]
1620
+ if needle
1621
+ in {
1622
+ _trim(item.get("service_id")).lower(),
1623
+ _trim(item.get("domain")).lower(),
1624
+ _trim(item.get("service_name")).lower(),
1625
+ }
1626
+ ),
1627
+ None,
1628
+ )
1629
+ if exact is None and services["items"]:
1630
+ exact = services["items"][0]
1631
+ if exact is None:
1632
+ raise ProviderError("x402-agentic-market", f"No Agentic Market service matched: {ref}")
1633
+ return {"discovery_provider": provider, "service": exact}
1634
+
1635
+
1636
+ async def preview_request(
1637
+ *,
1638
+ backend: AgentWalletBackend,
1639
+ url: str,
1640
+ method: str = "GET",
1641
+ headers: dict[str, Any] | None = None,
1642
+ query: dict[str, Any] | None = None,
1643
+ json_body: Any | None = None,
1644
+ text_body: str | None = None,
1645
+ ) -> dict[str, Any]:
1646
+ request = _build_request_metadata(
1647
+ url=url,
1648
+ method=method,
1649
+ headers=headers,
1650
+ query=query,
1651
+ json_body=json_body,
1652
+ text_body=text_body,
1653
+ )
1654
+ client = get_client()
1655
+ response = await _send_request(client=client, request=request)
1656
+ wallet_summary = _wallet_x402_support_summary(backend)
1657
+ address = await backend.get_address()
1658
+ preview: dict[str, Any] = {
1659
+ "mode": "preview",
1660
+ **_build_x402_action_payload(
1661
+ backend=backend,
1662
+ request=request,
1663
+ wallet_summary=wallet_summary,
1664
+ address=address,
1665
+ status_code=response.status_code,
1666
+ selected_payment=None,
1667
+ ),
1668
+ "execute_available": False,
1669
+ "request": {
1670
+ "url": request["url"],
1671
+ "method": request["method"],
1672
+ "request_fingerprint": request["request_fingerprint"],
1673
+ "query": request["query"],
1674
+ "body_hash": request["body_hash"],
1675
+ "content_type": request["content_type"],
1676
+ },
1677
+ }
1678
+
1679
+ if response.status_code != 402:
1680
+ preview.update(
1681
+ {
1682
+ "payment_required": False,
1683
+ "response_preview": _response_preview(response),
1684
+ "response_headers": {
1685
+ "content-type": response.headers.get("content-type"),
1686
+ },
1687
+ }
1688
+ )
1689
+ return preview
1690
+
1691
+ payment_preview = _parse_payment_required_response(
1692
+ response,
1693
+ backend=backend,
1694
+ request=request,
1695
+ address=address,
1696
+ wallet_summary=wallet_summary,
1697
+ )
1698
+ payment_preview["mode"] = "preview"
1699
+ payment_preview["request"] = {
1700
+ "url": request["url"],
1701
+ "method": request["method"],
1702
+ "request_fingerprint": request["request_fingerprint"],
1703
+ "query": request["query"],
1704
+ "body_hash": request["body_hash"],
1705
+ "content_type": request["content_type"],
1706
+ }
1707
+ return payment_preview
1708
+
1709
+
1710
+ def _reusable_approved_preview(
1711
+ approved_preview: Any,
1712
+ *,
1713
+ request: dict[str, Any],
1714
+ ) -> dict[str, Any] | None:
1715
+ """Return an approval-time preview usable instead of a fresh unpaid probe.
1716
+
1717
+ Reuse is only safe when the preview describes exactly this request
1718
+ (fingerprint covers method, final URL, and body hash) and still carries the
1719
+ encoded PAYMENT-REQUIRED challenge plus a selected payment. Anything else
1720
+ falls back to a fresh probe.
1721
+ """
1722
+ if not isinstance(approved_preview, dict):
1723
+ return None
1724
+ if not approved_preview.get("payment_required"):
1725
+ return None
1726
+ if _trim(approved_preview.get("request_fingerprint")) != request["request_fingerprint"]:
1727
+ return None
1728
+ if not isinstance(approved_preview.get("selected_payment"), dict):
1729
+ return None
1730
+ header = dict(approved_preview.get("response_headers") or {}).get("payment-required")
1731
+ if not isinstance(header, str) or not header.strip():
1732
+ return None
1733
+ return dict(approved_preview)
1734
+
1735
+
1736
+ #: USD amount below which an x402 payment never requires host/session/
1737
+ #: permission approval, regardless of network (including mainnet) -- the
1738
+ #: same rationale as in-person card payments skipping a signature/PIN below
1739
+ #: a floor limit. Only ever applies when the payment asset is confidently
1740
+ #: identified as USDC (see _looks_like_usdc); any other asset always
1741
+ #: requires approval, since its USD value can't be determined here.
1742
+ DE_MINIMIS_USD_THRESHOLD = 2.0
1743
+
1744
+
1745
+ def de_minimis_usd_amount(preview: dict[str, Any]) -> float | None:
1746
+ """Return *preview*'s payment amount in USD, or None if it isn't confidently USDC.
1747
+
1748
+ ``x402_amount_display`` is only populated by normalize_payment_requirement
1749
+ when the asset is recognized as USDC (see _looks_like_usdc) -- for any
1750
+ other asset it's None, since its USD value is unknown here.
1751
+ """
1752
+ amount_display = preview.get("x402_amount_display")
1753
+ if not isinstance(amount_display, str) or not amount_display.strip():
1754
+ return None
1755
+ try:
1756
+ return float(amount_display)
1757
+ except ValueError:
1758
+ return None
1759
+
1760
+
1761
+ def is_de_minimis_payment(
1762
+ preview: dict[str, Any],
1763
+ *,
1764
+ threshold_usd: float | None = None,
1765
+ ) -> bool:
1766
+ """Whether *preview*'s payment is small enough to skip approval entirely.
1767
+
1768
+ threshold_usd defaults to the current DE_MINIMIS_USD_THRESHOLD, read at
1769
+ call time (not bound at import time) so tests can monkeypatch the module
1770
+ attribute directly.
1771
+ """
1772
+ usd_amount = de_minimis_usd_amount(preview)
1773
+ if usd_amount is None:
1774
+ return False
1775
+ effective_threshold = DE_MINIMIS_USD_THRESHOLD if threshold_usd is None else threshold_usd
1776
+ return usd_amount < effective_threshold
1777
+
1778
+
1779
+ async def resolve_payment_preview(
1780
+ *,
1781
+ backend: AgentWalletBackend,
1782
+ url: str,
1783
+ method: str = "GET",
1784
+ headers: dict[str, Any] | None = None,
1785
+ query: dict[str, Any] | None = None,
1786
+ json_body: Any | None = None,
1787
+ text_body: str | None = None,
1788
+ approved_preview: dict[str, Any] | None = None,
1789
+ ) -> dict[str, Any]:
1790
+ """Return the payment preview for this exact request.
1791
+
1792
+ Reuses *approved_preview* when it still matches (same fingerprint check
1793
+ ``pay_and_fetch`` applies before deciding whether to skip a fresh probe),
1794
+ otherwise makes a fresh unpaid probe. Callers that need a summary to bind
1795
+ an approval token to -- before paying -- can call this instead of
1796
+ duplicating the reuse-or-probe logic ``pay_and_fetch`` already has.
1797
+ """
1798
+ request = _build_request_metadata(
1799
+ url=url,
1800
+ method=method,
1801
+ headers=headers,
1802
+ query=query,
1803
+ json_body=json_body,
1804
+ text_body=text_body,
1805
+ )
1806
+ reused = _reusable_approved_preview(approved_preview, request=request)
1807
+ if reused is not None:
1808
+ return reused
1809
+ return await preview_request(
1810
+ backend=backend,
1811
+ url=url,
1812
+ method=method,
1813
+ headers=headers,
1814
+ query=query,
1815
+ json_body=json_body,
1816
+ text_body=text_body,
1817
+ )
1818
+
1819
+
1820
+ async def pay_and_fetch(
1821
+ *,
1822
+ backend: AgentWalletBackend,
1823
+ url: str,
1824
+ method: str = "GET",
1825
+ headers: dict[str, Any] | None = None,
1826
+ query: dict[str, Any] | None = None,
1827
+ json_body: Any | None = None,
1828
+ text_body: str | None = None,
1829
+ approved_preview: dict[str, Any] | None = None,
1830
+ require_approved_preview: bool = False,
1831
+ ) -> dict[str, Any]:
1832
+ request = _build_request_metadata(
1833
+ url=url,
1834
+ method=method,
1835
+ headers=headers,
1836
+ query=query,
1837
+ json_body=json_body,
1838
+ text_body=text_body,
1839
+ )
1840
+ preview = _reusable_approved_preview(approved_preview, request=request)
1841
+ if require_approved_preview and preview is None:
1842
+ raise ProviderError("x402-http", "The approved payment quote no longer matches this request; no payment was attempted.")
1843
+ reused_approved_preview = preview is not None
1844
+ if preview is None:
1845
+ preview = await preview_request(
1846
+ backend=backend,
1847
+ url=url,
1848
+ method=method,
1849
+ headers=headers,
1850
+ query=query,
1851
+ json_body=json_body,
1852
+ text_body=text_body,
1853
+ )
1854
+ if not preview.get("payment_required") and not preview.get("siwx_available"):
1855
+ executed = dict(preview)
1856
+ executed["mode"] = "execute"
1857
+ executed["paid"] = False
1858
+ executed["broadcasted"] = False
1859
+ executed["confirmed"] = False
1860
+ return executed
1861
+
1862
+ payment_required_header = (
1863
+ dict(preview.get("response_headers") or {}).get("payment-required")
1864
+ )
1865
+ if not isinstance(payment_required_header, str) or not payment_required_header.strip():
1866
+ raise ProviderError("x402-http", "Missing PAYMENT-REQUIRED header in preview state.")
1867
+
1868
+ client = get_client()
1869
+ siwx_headers: dict[str, str] = {}
1870
+ if preview.get("siwx_available"):
1871
+ # Same order as the upstream SDK client: prove wallet ownership first, so
1872
+ # auth-only routes and resources this wallet already paid for cost nothing.
1873
+ siwx_headers = await _build_siwx_headers(
1874
+ backend=backend,
1875
+ payment_required_header=payment_required_header,
1876
+ request_url=request["url"],
1877
+ )
1878
+ if siwx_headers:
1879
+ response = await _send_request(
1880
+ client=client,
1881
+ request=request,
1882
+ extra_headers=siwx_headers,
1883
+ timeout=X402_EXECUTE_TIMEOUT_SECONDS,
1884
+ )
1885
+ if response.status_code != 402:
1886
+ _log_x402_execute(request=request, selected_payment=None, response=response, settlement=None)
1887
+ executed = dict(preview)
1888
+ executed.update(
1889
+ {
1890
+ "mode": "execute",
1891
+ "paid": False,
1892
+ "broadcasted": False,
1893
+ "confirmed": False,
1894
+ "siwx_authenticated": True,
1895
+ "reused_approved_preview": reused_approved_preview,
1896
+ "status_code": response.status_code,
1897
+ "response_preview": _response_preview(response),
1898
+ "response_headers": {"content-type": response.headers.get("content-type")},
1899
+ }
1900
+ )
1901
+ return executed
1902
+ if not preview.get("payment_required"):
1903
+ raise ProviderError(
1904
+ "x402-http",
1905
+ "Sign-In-With-X did not grant access and this endpoint offers no compatible payment option.",
1906
+ details={"request_url": request["url"], "siwx_attempted": bool(siwx_headers)},
1907
+ )
1908
+
1909
+ selected_payment = _validate_payment_requirement(
1910
+ preview.get("selected_payment")
1911
+ if isinstance(preview.get("selected_payment"), dict)
1912
+ else None,
1913
+ backend=backend,
1914
+ request_url=str(preview.get("request_url") or url),
1915
+ )
1916
+
1917
+ _validate_request_execution_policy(request=request, backend=backend)
1918
+ payment_headers = await _create_payment_headers(
1919
+ backend=backend,
1920
+ payment_required_header=payment_required_header,
1921
+ selected_payment=selected_payment,
1922
+ siwx_headers=siwx_headers,
1923
+ )
1924
+ response = await _send_request(
1925
+ client=client,
1926
+ request=request,
1927
+ extra_headers=payment_headers,
1928
+ timeout=X402_EXECUTE_TIMEOUT_SECONDS,
1929
+ )
1930
+ settlement = _extract_settlement_header_safe(response)
1931
+ _log_x402_execute(
1932
+ request=request,
1933
+ selected_payment=selected_payment,
1934
+ response=response,
1935
+ settlement=settlement,
1936
+ )
1937
+
1938
+ executed = dict(preview)
1939
+ executed.update(
1940
+ {
1941
+ "mode": "execute",
1942
+ "paid": True,
1943
+ "reused_approved_preview": reused_approved_preview,
1944
+ "broadcasted": bool(settlement and settlement.get("transaction")),
1945
+ "confirmed": bool(settlement and settlement.get("success")),
1946
+ "payment_settlement": settlement,
1947
+ "status_code": response.status_code,
1948
+ "response_preview": _response_preview(response),
1949
+ "response_headers": {
1950
+ "content-type": response.headers.get("content-type"),
1951
+ "payment-response": response.headers.get("PAYMENT-RESPONSE")
1952
+ or response.headers.get("X-PAYMENT-RESPONSE"),
1953
+ },
1954
+ }
1955
+ )
1956
+ if response.status_code == 402:
1957
+ message = "The paid x402 retry still returned HTTP 402."
1958
+ if reused_approved_preview:
1959
+ message += (
1960
+ " The payment was signed from the approved preview quote; the server may have"
1961
+ " re-priced the endpoint since then. Run x402_preview_request again and retry."
1962
+ )
1963
+ raise ProviderError(
1964
+ "x402-http",
1965
+ message,
1966
+ details={
1967
+ "request_url": request["url"],
1968
+ "selected_payment": selected_payment,
1969
+ "response_preview": executed["response_preview"],
1970
+ },
1971
+ )
1972
+ return executed