web3-systemic-agent 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
src/x402_payment.py ADDED
@@ -0,0 +1,1540 @@
1
+ """
2
+ x402 Protocol Integration and Payment Gatekeeper Module.
3
+
4
+ Provides micropayment gatekeeping for Agent-to-Agent (A2A) and machine-to-machine
5
+ interactions using the x402 payment protocol, supporting Base Sepolia and Base Mainnet
6
+ USDC settlement with local mock simulation and HTTP facilitator adapters.
7
+
8
+ Usage:
9
+ from src.x402_payment import (
10
+ X402Config,
11
+ MockX402Facilitator,
12
+ HTTPX402Facilitator,
13
+ get_x402_facilitator,
14
+ NETWORK_PROFILES,
15
+ get_network_profile,
16
+ parse_x402_header,
17
+ create_eip3009_payment_header,
18
+ QuickAuditRequest,
19
+ build_402_response,
20
+ build_bazaar_discovery_extension,
21
+ CDPFacilitatorAuthProvider,
22
+ CDP_MAINNET_FACILITATOR_URL,
23
+ usdc_to_atomic,
24
+ )
25
+
26
+ config = X402Config(enabled=True, price_per_eval_usdc=0.01)
27
+ facilitator = MockX402Facilitator()
28
+ """
29
+
30
+ import asyncio
31
+ import base64
32
+ import hashlib
33
+ import json
34
+ import logging
35
+ import os
36
+ import secrets
37
+ import sys
38
+ import time
39
+ from typing import Dict, Any, Optional, Union
40
+ import httpx
41
+ from cryptography.hazmat.primitives import hashes, serialization
42
+ from cryptography.hazmat.primitives.asymmetric import ec, ed25519, utils
43
+ from fastapi.responses import JSONResponse
44
+ from pydantic import BaseModel, Field, field_validator
45
+ from web3 import Web3
46
+
47
+ # Ensure module search paths support running directly or as a package
48
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
49
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
50
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
51
+ for _p in (_ROOT_DIR, _SRC_DIR):
52
+ if _p not in sys.path:
53
+ sys.path.insert(0, _p)
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ try:
58
+ from src.schemas import (
59
+ PaymentReceipt,
60
+ ConditionRulePayload,
61
+ FinalAgentResponse,
62
+ PreflightRequest,
63
+ PreflightVerdict,
64
+ DeepAuditRequest,
65
+ )
66
+ except ImportError:
67
+ from schemas import (
68
+ PaymentReceipt,
69
+ ConditionRulePayload,
70
+ FinalAgentResponse,
71
+ PreflightRequest,
72
+ PreflightVerdict,
73
+ DeepAuditRequest,
74
+ )
75
+
76
+ try:
77
+ from x402 import (
78
+ x402ClientSync,
79
+ x402ResourceServerSync,
80
+ ResourceConfig,
81
+ FacilitatorConfig,
82
+ PaymentRequirements,
83
+ PaymentRequired,
84
+ PaymentPayload,
85
+ )
86
+ from x402.http import HTTPFacilitatorClientSync
87
+ from x402.http.facilitator_client_base import AuthHeaders
88
+ from x402.mechanisms.evm.exact import (
89
+ ExactEvmClientScheme,
90
+ ExactEvmServerScheme,
91
+ )
92
+ HAS_X402_SDK = True
93
+ except ImportError as exc:
94
+ HAS_X402_SDK = False
95
+ logger.warning("x402 SDK import failed: %s", exc)
96
+
97
+ try:
98
+ from x402.extensions.bazaar import (
99
+ declare_discovery_extension,
100
+ OutputConfig,
101
+ bazaar_resource_server_extension,
102
+ )
103
+ HAS_X402_BAZAAR = True
104
+ except ImportError as exc:
105
+ HAS_X402_BAZAAR = False
106
+ declare_discovery_extension = None # type: ignore[assignment]
107
+ OutputConfig = None # type: ignore[assignment]
108
+ bazaar_resource_server_extension = None # type: ignore[assignment]
109
+ logger.warning("x402 bazaar extension import failed: %s", exc)
110
+
111
+ # Protocol Constants
112
+ USDC_DECIMALS: int = 6
113
+ DEFAULT_X402_PRICE_TOKEN_CHECK_USDC: float = 0.005
114
+ DEFAULT_X402_PRICE_PREFLIGHT_USDC: float = 0.01
115
+ DEFAULT_X402_PRICE_USDC: float = 0.015
116
+ DEFAULT_X402_PRICE_DEEP_AUDIT_USDC: float = 0.25
117
+ DEFAULT_X402_NETWORK: str = "eip155:84532" # Base Sepolia
118
+ DEFAULT_PAY_TO_ADDRESS: str = "0x0000000000000000000000000000000000000001"
119
+ DEFAULT_FACILITATOR_URL: str = "https://x402.org/facilitator"
120
+ CDP_MAINNET_FACILITATOR_URL: str = "https://api.cdp.coinbase.com/platform/v2/x402"
121
+ BASE_SEPOLIA_USDC: str = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
122
+ BASE_MAINNET_USDC: str = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
123
+ ARBITRUM_ONE_USDC: str = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"
124
+
125
+ NETWORK_PROFILES: Dict[str, Dict[str, Any]] = {
126
+ "eip155:84532": {
127
+ "chain_id": 84532,
128
+ "name": "Base Sepolia",
129
+ "is_testnet": True,
130
+ "usdc_address": BASE_SEPOLIA_USDC,
131
+ "default_rpc": "https://sepolia.base.org",
132
+ "token_name": "USDC",
133
+ "token_version": "2",
134
+ },
135
+ "eip155:8453": {
136
+ "chain_id": 8453,
137
+ "name": "Base Mainnet",
138
+ "is_testnet": False,
139
+ "usdc_address": BASE_MAINNET_USDC,
140
+ "default_rpc": "https://mainnet.base.org",
141
+ "token_name": "USD Coin",
142
+ "token_version": "2",
143
+ },
144
+ "eip155:42161": {
145
+ "chain_id": 42161,
146
+ "name": "Arbitrum One",
147
+ "is_testnet": False,
148
+ "usdc_address": ARBITRUM_ONE_USDC,
149
+ "default_rpc": "https://arb1.arbitrum.io/rpc",
150
+ "token_name": "USD Coin",
151
+ "token_version": "2",
152
+ },
153
+ }
154
+
155
+
156
+ def get_network_profile(network: str) -> Dict[str, Any]:
157
+ """
158
+ Looks up CAIP-2 network identifier in NETWORK_PROFILES.
159
+ Raises ValueError if unsupported. Returns a copy of the profile dictionary.
160
+ """
161
+ key = str(network or "").strip()
162
+ if key not in NETWORK_PROFILES:
163
+ raise ValueError(f"Unsupported CAIP-2 network: {network}")
164
+ return dict(NETWORK_PROFILES[key])
165
+
166
+
167
+ def _get_public_api_url() -> str:
168
+ """Resolves the public API base URL from environment variables with Render fallback."""
169
+ return (
170
+ os.getenv("PUBLIC_API_URL")
171
+ or os.getenv("WEB3_AGENT_URL")
172
+ or "https://web3-systemic-agent.onrender.com"
173
+ ).rstrip("/")
174
+
175
+
176
+ def _get_token_name(network: str) -> str:
177
+ """Resolves the EIP-712 token domain name for a CAIP-2 network identifier."""
178
+ return str(NETWORK_PROFILES.get(network, {}).get("token_name", "USDC"))
179
+
180
+
181
+ def usdc_to_atomic(amount_usdc: float) -> int:
182
+ """Converts a floating-point USDC amount into integer atomic units (6 decimals)."""
183
+ return int(round(amount_usdc * (10 ** USDC_DECIMALS)))
184
+
185
+
186
+ def atomic_to_usdc(amount_atomic: int) -> float:
187
+ """Converts atomic USDC units into a floating-point amount rounded to 6 decimal places."""
188
+ return round(amount_atomic / (10 ** USDC_DECIMALS), USDC_DECIMALS)
189
+
190
+
191
+ class X402Config(BaseModel):
192
+ """
193
+ Configuration for x402 payment gatekeeper, resolved from environment variables or explicit kwargs.
194
+ """
195
+ enabled: bool = Field(default=False, description="Whether x402 payment gatekeeper is active")
196
+ price_per_token_check_usdc: float = Field(default=DEFAULT_X402_PRICE_TOKEN_CHECK_USDC, ge=0.0, description="Price per fast token/honeypot check in USDC")
197
+ price_per_eval_usdc: float = Field(default=DEFAULT_X402_PRICE_USDC, ge=0.0, description="Price per evaluation in USDC")
198
+ price_per_preflight_usdc: float = Field(default=DEFAULT_X402_PRICE_PREFLIGHT_USDC, ge=0.0, description="Price per preflight check in USDC")
199
+ price_per_deep_audit_usdc: float = Field(default=DEFAULT_X402_PRICE_DEEP_AUDIT_USDC, ge=0.0, description="Price per deep source/proxy audit in USDC")
200
+ network: str = Field(default=DEFAULT_X402_NETWORK, description="CAIP-2 network identifier")
201
+ pay_to_address: str = Field(default=DEFAULT_PAY_TO_ADDRESS, description="Recipient EVM address")
202
+ facilitator_url: str = Field(default=DEFAULT_FACILITATOR_URL, description="Facilitator service URL")
203
+ asset: str = Field(default="USDC", description="Token symbol or contract address")
204
+ use_live_facilitator: bool = Field(default=False, description="Whether to route micropayments to a live HTTP facilitator")
205
+ cdp_api_key_id: Optional[str] = Field(default=None, description="Coinbase CDP API Key ID")
206
+ cdp_api_key_secret: Optional[str] = Field(default=None, description="Coinbase CDP API Key Secret")
207
+
208
+ def __init__(self, **data: Any):
209
+ if "enabled" not in data:
210
+ env_val = os.getenv("X402_ENABLED", "false").strip().lower()
211
+ data["enabled"] = env_val in ("true", "1", "yes")
212
+ if "price_per_token_check_usdc" not in data:
213
+ env_val = os.getenv("X402_PRICE_TOKEN_CHECK")
214
+ if env_val:
215
+ try:
216
+ data["price_per_token_check_usdc"] = float(env_val)
217
+ except (ValueError, TypeError):
218
+ pass
219
+ if "price_per_eval_usdc" not in data:
220
+ env_val = os.getenv("X402_PRICE_EVALUATE")
221
+ if env_val:
222
+ try:
223
+ data["price_per_eval_usdc"] = float(env_val)
224
+ except (ValueError, TypeError):
225
+ pass
226
+ if "price_per_preflight_usdc" not in data:
227
+ env_val = os.getenv("X402_PRICE_PREFLIGHT")
228
+ if env_val:
229
+ try:
230
+ data["price_per_preflight_usdc"] = float(env_val)
231
+ except (ValueError, TypeError):
232
+ pass
233
+ if "price_per_deep_audit_usdc" not in data:
234
+ env_val = os.getenv("X402_PRICE_DEEP_AUDIT")
235
+ if env_val:
236
+ try:
237
+ data["price_per_deep_audit_usdc"] = float(env_val)
238
+ except (ValueError, TypeError):
239
+ pass
240
+ if "network" not in data:
241
+ data["network"] = os.getenv("X402_NETWORK", DEFAULT_X402_NETWORK)
242
+ if "pay_to_address" not in data:
243
+ data["pay_to_address"] = os.getenv("PAY_TO_ADDRESS", DEFAULT_PAY_TO_ADDRESS)
244
+ if "asset" not in data:
245
+ data["asset"] = os.getenv("X402_ASSET", "USDC")
246
+ if "use_live_facilitator" not in data:
247
+ env_live = os.getenv("X402_USE_LIVE_FACILITATOR", "false").strip().lower()
248
+ data["use_live_facilitator"] = env_live in ("true", "1", "yes")
249
+
250
+ if "cdp_api_key_id" not in data:
251
+ raw_id = os.getenv("CDP_API_KEY_ID")
252
+ data["cdp_api_key_id"] = raw_id.strip() if raw_id and raw_id.strip() else None
253
+ elif not data["cdp_api_key_id"] or not str(data["cdp_api_key_id"]).strip():
254
+ data["cdp_api_key_id"] = None
255
+ else:
256
+ data["cdp_api_key_id"] = str(data["cdp_api_key_id"]).strip()
257
+
258
+ if "cdp_api_key_secret" not in data:
259
+ raw_secret = os.getenv("CDP_API_KEY_SECRET")
260
+ data["cdp_api_key_secret"] = raw_secret.strip() if raw_secret and raw_secret.strip() else None
261
+ elif not data["cdp_api_key_secret"] or not str(data["cdp_api_key_secret"]).strip():
262
+ data["cdp_api_key_secret"] = None
263
+ else:
264
+ data["cdp_api_key_secret"] = str(data["cdp_api_key_secret"]).strip()
265
+
266
+ is_mainnet_cdp = (
267
+ data.get("network") == "eip155:8453"
268
+ and bool(data.get("cdp_api_key_id"))
269
+ and bool(data.get("cdp_api_key_secret"))
270
+ )
271
+
272
+ if "facilitator_url" not in data:
273
+ env_fac = os.getenv("FACILITATOR_URL")
274
+ if is_mainnet_cdp:
275
+ if not env_fac or env_fac.rstrip("/") == DEFAULT_FACILITATOR_URL.rstrip("/"):
276
+ data["facilitator_url"] = CDP_MAINNET_FACILITATOR_URL
277
+ else:
278
+ data["facilitator_url"] = env_fac
279
+ elif env_fac:
280
+ data["facilitator_url"] = env_fac
281
+ else:
282
+ data["facilitator_url"] = DEFAULT_FACILITATOR_URL
283
+ else:
284
+ if is_mainnet_cdp and str(data.get("facilitator_url", "")).rstrip("/") == DEFAULT_FACILITATOR_URL.rstrip("/"):
285
+ data["facilitator_url"] = CDP_MAINNET_FACILITATOR_URL
286
+
287
+ raw_addr = data.get("pay_to_address", DEFAULT_PAY_TO_ADDRESS)
288
+ if Web3.is_address(raw_addr):
289
+ data["pay_to_address"] = Web3.to_checksum_address(raw_addr)
290
+
291
+ super().__init__(**data)
292
+
293
+ @field_validator("pay_to_address")
294
+ @classmethod
295
+ def normalize_pay_to(cls, v: str) -> str:
296
+ if Web3.is_address(v):
297
+ return Web3.to_checksum_address(v)
298
+ return v
299
+
300
+ def has_cdp_credentials(self) -> bool:
301
+ """Returns True if both CDP API key ID and secret are configured."""
302
+ return bool(self.cdp_api_key_id and self.cdp_api_key_secret)
303
+
304
+ @property
305
+ def chain_id(self) -> int:
306
+ """Returns numeric EVM chain ID resolved from network CAIP-2 profile or string."""
307
+ if self.network in NETWORK_PROFILES:
308
+ return int(NETWORK_PROFILES[self.network]["chain_id"])
309
+ if self.network.startswith("eip155:"):
310
+ try:
311
+ return int(self.network.split(":")[1])
312
+ except (ValueError, IndexError):
313
+ pass
314
+ return 84532
315
+
316
+ @property
317
+ def usdc_contract_address(self) -> str:
318
+ """Returns active USDC contract address for the configured network."""
319
+ if self.network in NETWORK_PROFILES:
320
+ return str(NETWORK_PROFILES[self.network]["usdc_address"])
321
+ return BASE_SEPOLIA_USDC
322
+
323
+ @property
324
+ def is_testnet(self) -> bool:
325
+ """Returns whether the active network profile is a testnet."""
326
+ if self.network in NETWORK_PROFILES:
327
+ return bool(NETWORK_PROFILES[self.network]["is_testnet"])
328
+ return True
329
+
330
+
331
+ class CDPFacilitatorAuthProvider:
332
+ """
333
+ Authentication provider for Coinbase Developer Platform (CDP) x402 Facilitator.
334
+ Generates required Bearer JWT (EdDSA / ES256) and CDP key ID headers across facilitator endpoints.
335
+ Falls back gracefully to raw bearer token when api_key_secret is not a cryptographic key.
336
+ """
337
+
338
+ def __init__(self, api_key_id: str, api_key_secret: str):
339
+ self.api_key_id = str(api_key_id or "").strip().strip("'\"")
340
+ self.api_key_secret = str(api_key_secret or "").strip().strip("'\"")
341
+ if self.api_key_secret.startswith("{") and self.api_key_secret.endswith("}"):
342
+ try:
343
+ parsed = json.loads(self.api_key_secret)
344
+ if isinstance(parsed, dict):
345
+ self.api_key_id = self.api_key_id or str(
346
+ parsed.get("id") or parsed.get("name") or parsed.get("apiKeyId") or ""
347
+ ).strip()
348
+ self.api_key_secret = str(
349
+ parsed.get("secret") or parsed.get("privateKey") or parsed.get("apiKeySecret") or self.api_key_secret
350
+ ).strip()
351
+ except Exception:
352
+ pass
353
+
354
+ def _build_bearer_token(
355
+ self,
356
+ method: str,
357
+ path: str,
358
+ host: str = "api.cdp.coinbase.com",
359
+ ) -> str:
360
+ """
361
+ Builds a Coinbase CDP signed JWT Bearer token for the given method and path.
362
+ """
363
+ secret_clean = self.api_key_secret.replace("\\n", "\n").strip().strip("'\"")
364
+ key = None
365
+ alg = None
366
+
367
+ if secret_clean.startswith("-----BEGIN"):
368
+ try:
369
+ loaded = serialization.load_pem_private_key(secret_clean.encode("utf-8"), password=None)
370
+ if isinstance(loaded, ec.EllipticCurvePrivateKey):
371
+ key = loaded
372
+ alg = "ES256"
373
+ elif isinstance(loaded, ed25519.Ed25519PrivateKey):
374
+ key = loaded
375
+ alg = "EdDSA"
376
+ except Exception:
377
+ pass
378
+ else:
379
+ try:
380
+ b64_str = "".join(secret_clean.split())
381
+ if len(b64_str) % 4 != 0:
382
+ b64_str += "=" * ((4 - len(b64_str) % 4) % 4)
383
+ raw = base64.b64decode(b64_str)
384
+ try:
385
+ loaded = serialization.load_der_private_key(raw, password=None)
386
+ if isinstance(loaded, ed25519.Ed25519PrivateKey):
387
+ key = loaded
388
+ alg = "EdDSA"
389
+ elif isinstance(loaded, ec.EllipticCurvePrivateKey):
390
+ key = loaded
391
+ alg = "ES256"
392
+ except Exception:
393
+ pass
394
+
395
+ if key is None:
396
+ if len(raw) == 64:
397
+ key = ed25519.Ed25519PrivateKey.from_private_bytes(raw[:32])
398
+ alg = "EdDSA"
399
+ elif len(raw) == 32:
400
+ key = ed25519.Ed25519PrivateKey.from_private_bytes(raw)
401
+ alg = "EdDSA"
402
+ elif len(raw) == 48:
403
+ key = ed25519.Ed25519PrivateKey.from_private_bytes(raw[-32:])
404
+ alg = "EdDSA"
405
+ except Exception:
406
+ pass
407
+
408
+ if key is None or alg is None:
409
+ return f"Bearer {self.api_key_secret}"
410
+
411
+ try:
412
+ now = int(time.time())
413
+ uri_str = f"{method.upper()} {host}{path}"
414
+ header = {
415
+ "alg": alg,
416
+ "typ": "JWT",
417
+ "kid": self.api_key_id,
418
+ "nonce": secrets.token_hex(16),
419
+ }
420
+ payload = {
421
+ "iss": "cdp",
422
+ "sub": self.api_key_id,
423
+ "nbf": now,
424
+ "exp": now + 120,
425
+ "uri": uri_str,
426
+ "uris": [uri_str],
427
+ }
428
+
429
+ h_b64 = base64.urlsafe_b64encode(json.dumps(header, separators=(",", ":")).encode("utf-8")).rstrip(b"=").decode("ascii")
430
+ p_b64 = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode("utf-8")).rstrip(b"=").decode("ascii")
431
+ signing_input = f"{h_b64}.{p_b64}".encode("ascii")
432
+
433
+ if isinstance(key, ed25519.Ed25519PrivateKey):
434
+ sig = key.sign(signing_input)
435
+ elif isinstance(key, ec.EllipticCurvePrivateKey):
436
+ der_sig = key.sign(signing_input, ec.ECDSA(hashes.SHA256()))
437
+ r, s = utils.decode_dss_signature(der_sig)
438
+ sig = r.to_bytes(32, "big") + s.to_bytes(32, "big")
439
+ else:
440
+ return f"Bearer {self.api_key_secret}"
441
+
442
+ s_b64 = base64.urlsafe_b64encode(sig).rstrip(b"=").decode("ascii")
443
+ return f"Bearer {h_b64}.{p_b64}.{s_b64}"
444
+ except Exception as exc:
445
+ logger.warning("CDP JWT generation failed, falling back to raw bearer: %s", exc)
446
+ return f"Bearer {self.api_key_secret}"
447
+
448
+ def get_auth_headers(self) -> Any:
449
+ verify_token = self._build_bearer_token("POST", "/platform/v2/x402/verify")
450
+ settle_token = self._build_bearer_token("POST", "/platform/v2/x402/settle")
451
+ supported_token = self._build_bearer_token("GET", "/platform/v2/x402/supported")
452
+ bazaar_token = self._build_bearer_token("GET", "/platform/v2/x402/discovery/resources")
453
+
454
+ verify_headers = {
455
+ "Authorization": verify_token,
456
+ "X-CDP-API-KEY-ID": self.api_key_id,
457
+ }
458
+ settle_headers = {
459
+ "Authorization": settle_token,
460
+ "X-CDP-API-KEY-ID": self.api_key_id,
461
+ }
462
+ supported_headers = {
463
+ "Authorization": supported_token,
464
+ "X-CDP-API-KEY-ID": self.api_key_id,
465
+ }
466
+ bazaar_headers = {
467
+ "Authorization": bazaar_token,
468
+ "X-CDP-API-KEY-ID": self.api_key_id,
469
+ }
470
+
471
+ if HAS_X402_SDK:
472
+ try:
473
+ from x402.http.facilitator_client_base import AuthHeaders
474
+ return AuthHeaders(
475
+ verify=verify_headers,
476
+ settle=settle_headers,
477
+ supported=supported_headers,
478
+ bazaar=bazaar_headers,
479
+ )
480
+ except ImportError:
481
+ pass
482
+ return {
483
+ "verify": verify_headers,
484
+ "settle": settle_headers,
485
+ "supported": supported_headers,
486
+ "bazaar": bazaar_headers,
487
+ }
488
+
489
+
490
+ class QuickAuditRequest(BaseModel):
491
+ """Simplified payload schema for automated agent queries to /audit."""
492
+ target_address: Optional[str] = Field(default=None, description="Hex EVM smart contract address to audit")
493
+ address: Optional[str] = Field(default=None, description="Alias for target_address")
494
+ contract_address: Optional[str] = Field(default=None, description="Alias for target_address")
495
+ chain_id: int = Field(default=8453, description="EVM Chain ID (8453 Base Mainnet, 84532 Base Sepolia, 42161 Arbitrum One)")
496
+ proposal_description: str = Field(
497
+ default="Audit smart contract for administrative backdoors, honeypot traps, or unauthorized privilege escalation.",
498
+ description="Natural language intent or audit context",
499
+ )
500
+ policy_prompt: str = Field(
501
+ default="Audit contract and calldata for unauthorized privilege escalation, proxy upgrades, honeypot traps, or treasury drainage.",
502
+ description="Security policy prompt",
503
+ )
504
+ calldata: str = Field(default="0x", description="Optional transaction hex calldata")
505
+ risk_threshold: float = Field(default=7.0, ge=0.0, le=10.0, description="Risk score threshold")
506
+
507
+
508
+ class TokenCheckRequest(BaseModel):
509
+ """Simplified payload schema for fast token/honeypot checks on /token/check."""
510
+ address: Optional[str] = Field(default=None, description="Hex EVM token contract address to check")
511
+ token_address: Optional[str] = Field(default=None, description="Alias for address")
512
+ target_address: Optional[str] = Field(default=None, description="Alias for address")
513
+ chain_id: int = Field(default=8453, description="EVM Chain ID (8453 Base Mainnet, 84532 Base Sepolia, 42161 Arbitrum One)")
514
+ include_source_status: bool = Field(default=True, description="Whether to check verified source status")
515
+
516
+ @field_validator("address", "token_address", "target_address")
517
+ @classmethod
518
+ def validate_and_normalize_address(cls, v: Optional[str]) -> Optional[str]:
519
+ if v is None or v == "":
520
+ return None
521
+ if not Web3.is_address(v):
522
+ raise ValueError(f"Invalid Ethereum address: {v}")
523
+ return Web3.to_checksum_address(v)
524
+
525
+
526
+ def build_bazaar_discovery_extension(endpoint: str = "/evaluate", method: str = "POST") -> Dict[str, Any]:
527
+ """
528
+ Constructs an x402 Bazaar auto-discovery extension declaring input/output JSON schemas
529
+ and sample payloads for Agent-to-Agent discovery.
530
+ """
531
+ clean_ep = str(endpoint or "/evaluate").rstrip("/")
532
+ http_method = (method or "POST").strip().upper()
533
+ default_rule_sample = {
534
+ "rule_id": "example-audit-01",
535
+ "chain_id": 8453,
536
+ "deterministic": {
537
+ "target_address": "0x4200000000000000000000000000000000000006",
538
+ "min_value_wei": 0,
539
+ "required_function_selectors": ["0xf2fde38b"],
540
+ "check_native_balance": False,
541
+ },
542
+ "semantic": {
543
+ "enabled": True,
544
+ "policy_prompt": "Audit transaction calldata and governance proposal for security risks",
545
+ "risk_threshold": 7.0,
546
+ },
547
+ "context_metadata": {
548
+ "calldata": "0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
549
+ "proposal_description": "DAO Governance yield optimization parameter update",
550
+ "tx_value_wei": 0,
551
+ },
552
+ }
553
+ if clean_ep.endswith("/token/check"):
554
+ sample_input = {
555
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
556
+ "chain_id": 8453,
557
+ }
558
+ sample_output_example = {
559
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
560
+ "chain_id": 8453,
561
+ "is_contract": True,
562
+ "is_honeypot": False,
563
+ "severity": "CLEAN",
564
+ "llm_invoked": False,
565
+ }
566
+ input_schema = TokenCheckRequest.model_json_schema()
567
+ output_schema = {
568
+ "type": "object",
569
+ "properties": {
570
+ "address": {"type": "string"},
571
+ "chain_id": {"type": "integer"},
572
+ "is_contract": {"type": "boolean"},
573
+ "is_honeypot": {"type": "boolean"},
574
+ "severity": {"type": "string"},
575
+ "honeypot_flags": {"type": "array", "items": {"type": "string"}},
576
+ "llm_invoked": {"type": "boolean"},
577
+ },
578
+ }
579
+ elif clean_ep.endswith("/preflight"):
580
+ sample_input = {
581
+ "chain_id": 8453,
582
+ "to_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
583
+ "calldata": "0x095ea7b30000000000000000000000001111111111111111111111111111111111111111ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
584
+ "value_wei": 0,
585
+ "run_simulation": True,
586
+ }
587
+ sample_output_example = {
588
+ "verdict": "BLOCK",
589
+ "risk_score": 7.5,
590
+ "chain_id": 8453,
591
+ "llm_invoked": False,
592
+ }
593
+ input_schema = PreflightRequest.model_json_schema()
594
+ output_schema = PreflightVerdict.model_json_schema()
595
+ elif clean_ep.endswith("/audit/deep"):
596
+ sample_input = {
597
+ "target_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
598
+ "chain_id": 8453,
599
+ "proposal_description": "Deep audit of EIP-1967 proxy implementation and verified Solidity source code.",
600
+ "resolve_proxy": True,
601
+ "fetch_verified_source": True,
602
+ }
603
+ sample_output_example = {
604
+ "rule_id": "deep-audit-01",
605
+ "chain_id": 8453,
606
+ "llm_invoked": True,
607
+ }
608
+ input_schema = DeepAuditRequest.model_json_schema()
609
+ output_schema = FinalAgentResponse.model_json_schema()
610
+ elif clean_ep.endswith("/audit"):
611
+ sample_input = {
612
+ "target_address": "0x4200000000000000000000000000000000000006",
613
+ "chain_id": 8453,
614
+ "proposal_description": "Audit smart contract for administrative backdoors, honeypot traps, or unauthorized privilege escalation.",
615
+ "calldata": "0x",
616
+ }
617
+ sample_output_example = {
618
+ "rule_id": "example-audit-01",
619
+ "chain_id": 8453,
620
+ "llm_invoked": True,
621
+ }
622
+ input_schema = QuickAuditRequest.model_json_schema()
623
+ output_schema = FinalAgentResponse.model_json_schema()
624
+ elif clean_ep.endswith("/rules/evaluate-batch"):
625
+ sample_input = [default_rule_sample]
626
+ sample_output_example = [{"rule_id": "example-audit-01", "chain_id": 8453, "llm_invoked": True}]
627
+ input_schema = {
628
+ "type": "array",
629
+ "items": ConditionRulePayload.model_json_schema(),
630
+ "minItems": 1,
631
+ "maxItems": 50,
632
+ }
633
+ output_schema = {
634
+ "type": "array",
635
+ "items": FinalAgentResponse.model_json_schema(),
636
+ }
637
+ elif clean_ep.endswith("/rules/enqueue"):
638
+ sample_input = default_rule_sample
639
+ sample_output_example = {"job_id": "job-example-01", "status": "QUEUED"}
640
+ input_schema = ConditionRulePayload.model_json_schema()
641
+ output_schema = {
642
+ "type": "object",
643
+ "properties": {
644
+ "job_id": {"type": "string"},
645
+ "status": {"type": "string"},
646
+ "payment": {"type": "object"},
647
+ },
648
+ "required": ["job_id", "status"],
649
+ }
650
+ else:
651
+ sample_input = default_rule_sample
652
+ sample_output_example = {
653
+ "rule_id": "example-audit-01",
654
+ "chain_id": 8453,
655
+ "llm_invoked": True,
656
+ }
657
+ input_schema = ConditionRulePayload.model_json_schema()
658
+ output_schema = FinalAgentResponse.model_json_schema()
659
+
660
+ if HAS_X402_SDK and HAS_X402_BAZAAR:
661
+ try:
662
+ res = declare_discovery_extension(
663
+ input=sample_input,
664
+ input_schema=input_schema,
665
+ body_type="json",
666
+ output=OutputConfig(
667
+ example=sample_output_example,
668
+ schema=output_schema,
669
+ ),
670
+ )
671
+ if isinstance(res, dict) and "bazaar" in res:
672
+ if isinstance(res["bazaar"], dict) and "info" in res["bazaar"]:
673
+ if isinstance(res["bazaar"]["info"], dict) and "input" in res["bazaar"]["info"]:
674
+ if isinstance(res["bazaar"]["info"]["input"], dict):
675
+ res["bazaar"]["info"]["input"]["method"] = http_method
676
+ return res
677
+ except Exception as exc:
678
+ logger.warning("Failed to generate bazaar discovery extension via SDK: %s", exc)
679
+
680
+ return {
681
+ "bazaar": {
682
+ "info": {
683
+ "input": {
684
+ "type": "http",
685
+ "method": http_method,
686
+ "bodyType": "json",
687
+ "body": sample_input,
688
+ },
689
+ "output": {
690
+ "type": "json",
691
+ "example": sample_output_example,
692
+ },
693
+ },
694
+ "schema": {
695
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
696
+ "type": "object",
697
+ "properties": {
698
+ "input": {
699
+ "type": "object",
700
+ "properties": {
701
+ "type": {"type": "string", "const": "http"},
702
+ "method": {"type": "string", "enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]},
703
+ "bodyType": {"type": "string", "enum": ["json", "form-data", "text"]},
704
+ "body": input_schema,
705
+ },
706
+ "required": ["type", "method", "bodyType", "body"],
707
+ "additionalProperties": False,
708
+ },
709
+ "output": {
710
+ "type": "object",
711
+ "properties": {
712
+ "type": {"type": "string"},
713
+ "example": output_schema,
714
+ },
715
+ "required": ["type"],
716
+ },
717
+ },
718
+ "required": ["input"],
719
+ "input": input_schema,
720
+ "output": output_schema,
721
+ },
722
+ }
723
+ }
724
+
725
+
726
+ def parse_x402_header(header_value: Optional[str], default_network: Optional[str] = DEFAULT_X402_NETWORK) -> Dict[str, Any]:
727
+ """
728
+ Parses an X-PAYMENT or PAYMENT-SIGNATURE header containing raw JSON or base64-encoded JSON.
729
+ Supports both legacy flat headers and nested x402 v2 EIP-3009 payload envelopes.
730
+ Normalizes aliases and validates required fields: payment_id, payer_address, amount_atomic, and signature.
731
+ """
732
+ if not header_value or not isinstance(header_value, str) or not header_value.strip():
733
+ raise ValueError("Missing or empty payment header")
734
+
735
+ clean_val = header_value.strip()
736
+ data = None
737
+
738
+ if clean_val.startswith("{"):
739
+ try:
740
+ data = json.loads(clean_val)
741
+ except Exception:
742
+ pass
743
+
744
+ if data is None:
745
+ try:
746
+ missing_padding = len(clean_val) % 4
747
+ padded = clean_val + ("=" * (4 - missing_padding) if missing_padding else "")
748
+ decoded = base64.b64decode(padded).decode("utf-8")
749
+ data = json.loads(decoded)
750
+ except Exception as exc:
751
+ raise ValueError(f"Invalid payment header: {exc}")
752
+
753
+ if not isinstance(data, dict):
754
+ raise ValueError("Payment header must encode a JSON object")
755
+
756
+ payload_dict = data.get("payload") if isinstance(data.get("payload"), dict) else {}
757
+ auth_dict = payload_dict.get("authorization") if isinstance(payload_dict.get("authorization"), dict) else {}
758
+ accepted_dict = data.get("accepted") if isinstance(data.get("accepted"), dict) else {}
759
+
760
+ payment_id = data.get("payment_id") or data.get("nonce") or data.get("id") or auth_dict.get("nonce")
761
+ if not payment_id or not str(payment_id).strip():
762
+ raise ValueError("Missing payment_id or nonce")
763
+ payment_id = str(payment_id).strip()
764
+
765
+ payer = data.get("payer_address") or data.get("payer") or data.get("from") or auth_dict.get("from")
766
+ if not payer or not isinstance(payer, str) or not Web3.is_address(payer):
767
+ raise ValueError(f"Invalid or missing payer address: {payer}")
768
+ payer_address = Web3.to_checksum_address(payer)
769
+
770
+ signature = data.get("signature") or payload_dict.get("signature")
771
+ if not signature or not isinstance(signature, str) or not signature.strip():
772
+ raise ValueError("Missing signature in payment header")
773
+ signature = signature.strip()
774
+
775
+ amount_atomic = data.get("amount_atomic")
776
+ if amount_atomic is None:
777
+ amount_atomic = data.get("value")
778
+ if amount_atomic is None:
779
+ amount_atomic = data.get("amount")
780
+ if amount_atomic is None:
781
+ amount_atomic = auth_dict.get("value")
782
+ if amount_atomic is None:
783
+ amount_atomic = accepted_dict.get("amount")
784
+
785
+ if amount_atomic is None and "amount_usdc" in data:
786
+ amount_atomic = usdc_to_atomic(float(data["amount_usdc"]))
787
+
788
+ if amount_atomic is None:
789
+ raise ValueError("Missing payment amount")
790
+
791
+ try:
792
+ if isinstance(amount_atomic, str) and amount_atomic.startswith("0x"):
793
+ amount_atomic = int(amount_atomic, 16)
794
+ else:
795
+ amount_atomic = int(amount_atomic)
796
+ except (ValueError, TypeError):
797
+ raise ValueError(f"Invalid amount_atomic: {amount_atomic}")
798
+
799
+ if amount_atomic < 0:
800
+ raise ValueError("Payment amount cannot be negative")
801
+
802
+ amount_usdc = float(data.get("amount_usdc", amount_atomic / (10 ** USDC_DECIMALS)))
803
+ network = data.get("network") or accepted_dict.get("network") or default_network
804
+
805
+ result = {
806
+ "payment_id": payment_id,
807
+ "payer_address": payer_address,
808
+ "amount_atomic": amount_atomic,
809
+ "amount_usdc": amount_usdc,
810
+ "signature": signature,
811
+ "network": network,
812
+ }
813
+
814
+ # Pass through additional context fields (e.g. simulate_settle_error, payload, accepted, x402Version)
815
+ for k, v in data.items():
816
+ if k not in result:
817
+ result[k] = v
818
+
819
+ return result
820
+
821
+
822
+ def create_eip3009_payment_header(
823
+ account: Any,
824
+ pay_to_address: str,
825
+ amount_atomic: int,
826
+ network: str = DEFAULT_X402_NETWORK,
827
+ usdc_address: Optional[str] = None,
828
+ as_base64: bool = False,
829
+ ) -> str:
830
+ """
831
+ Constructs an EIP-712 / EIP-3009 transferWithAuthorization signed payment header dictionary
832
+ using the official x402 SDK (ExactEvmClientScheme) in < 5ms without requiring network calls.
833
+ Returns JSON string (or Base64-encoded JSON if as_base64=True).
834
+ """
835
+ if not HAS_X402_SDK:
836
+ raise RuntimeError("x402 SDK is required to create EIP-3009 payment headers")
837
+
838
+ checksum_pay_to = Web3.to_checksum_address(pay_to_address)
839
+ token_address = usdc_address
840
+ if not token_address:
841
+ try:
842
+ profile = get_network_profile(network)
843
+ token_address = profile["usdc_address"]
844
+ except Exception:
845
+ token_address = BASE_SEPOLIA_USDC
846
+ checksum_token = Web3.to_checksum_address(token_address)
847
+
848
+ cli = x402ClientSync()
849
+ cli.register(network, ExactEvmClientScheme(account))
850
+
851
+ token_name = "USDC"
852
+ token_version = "2"
853
+ try:
854
+ prof = get_network_profile(network)
855
+ token_name = prof.get("token_name", "USDC")
856
+ token_version = prof.get("token_version", "2")
857
+ except Exception:
858
+ pass
859
+
860
+ req = PaymentRequirements(
861
+ scheme="exact",
862
+ network=network,
863
+ asset=checksum_token,
864
+ amount=str(amount_atomic),
865
+ pay_to=checksum_pay_to,
866
+ max_timeout_seconds=300,
867
+ extra={"name": token_name, "version": token_version},
868
+ )
869
+ payment_required = PaymentRequired(x402_version=2, accepts=[req])
870
+ payload_obj = cli.create_payment_payload(payment_required)
871
+ payload_dict = payload_obj.model_dump()
872
+
873
+ auth = payload_dict.get("payload", {}).get("authorization", {})
874
+ sig = payload_dict.get("payload", {}).get("signature", "")
875
+ payment_id = auth.get("nonce", "")
876
+ payer_address = Web3.to_checksum_address(auth.get("from", getattr(account, "address", "")))
877
+ amount = int(auth.get("value", amount_atomic))
878
+ amount_usdc = atomic_to_usdc(amount)
879
+
880
+ header_dict = {
881
+ "x402Version": payload_dict.get("x402Version", 2),
882
+ "payment_id": payment_id,
883
+ "payer_address": payer_address,
884
+ "amount_atomic": amount,
885
+ "amount_usdc": amount_usdc,
886
+ "network": network,
887
+ "signature": sig,
888
+ "payload": payload_dict.get("payload"),
889
+ "accepted": payload_dict.get("accepted"),
890
+ }
891
+ if payload_dict.get("extensions") is not None:
892
+ header_dict["extensions"] = payload_dict["extensions"]
893
+ if header_dict.get("extensions") is None:
894
+ header_dict["extensions"] = build_bazaar_discovery_extension("/evaluate")
895
+
896
+ json_str = json.dumps(header_dict)
897
+ if as_base64:
898
+ return base64.b64encode(json_str.encode("utf-8")).decode("utf-8")
899
+ return json_str
900
+
901
+
902
+ class VerificationResult(BaseModel):
903
+ valid: bool
904
+ reason: Optional[str] = None
905
+ payment_id: str
906
+ payer_address: str
907
+ amount_atomic: int
908
+ amount_usdc: float
909
+
910
+
911
+ class SettlementResult(BaseModel):
912
+ settled: bool
913
+ tx_hash: Optional[str] = None
914
+ error: Optional[str] = None
915
+
916
+
917
+ class MockX402Facilitator:
918
+ """
919
+ In-memory mock facilitator for unit tests and local development.
920
+ Tracks verify and settle calls and generates deterministic transaction hashes.
921
+ """
922
+
923
+ def __init__(self):
924
+ self.verify_calls: int = 0
925
+ self.settle_calls: int = 0
926
+
927
+ async def verify(
928
+ self,
929
+ payment_data: Dict[str, Any],
930
+ required_atomic: int,
931
+ config: X402Config,
932
+ ) -> VerificationResult:
933
+ self.verify_calls += 1
934
+ payment_id = str(payment_data.get("payment_id", ""))
935
+ payer_address = str(payment_data.get("payer_address", ""))
936
+ amount_atomic = int(payment_data.get("amount_atomic", 0))
937
+ amount_usdc = float(payment_data.get("amount_usdc", amount_atomic / (10 ** USDC_DECIMALS)))
938
+ sig = str(payment_data.get("signature", "")).strip()
939
+
940
+ if not sig or sig.lower() in ("invalid", "0xinvalid"):
941
+ return VerificationResult(
942
+ valid=False,
943
+ reason="Invalid signature",
944
+ payment_id=payment_id,
945
+ payer_address=payer_address,
946
+ amount_atomic=amount_atomic,
947
+ amount_usdc=amount_usdc,
948
+ )
949
+
950
+ if amount_atomic < required_atomic:
951
+ return VerificationResult(
952
+ valid=False,
953
+ reason=f"Insufficient payment amount: {amount_atomic} < {required_atomic}",
954
+ payment_id=payment_id,
955
+ payer_address=payer_address,
956
+ amount_atomic=amount_atomic,
957
+ amount_usdc=amount_usdc,
958
+ )
959
+
960
+ net = payment_data.get("network")
961
+ if net and net != config.network:
962
+ return VerificationResult(
963
+ valid=False,
964
+ reason="Network mismatch",
965
+ payment_id=payment_id,
966
+ payer_address=payer_address,
967
+ amount_atomic=amount_atomic,
968
+ amount_usdc=amount_usdc,
969
+ )
970
+
971
+ return VerificationResult(
972
+ valid=True,
973
+ reason=None,
974
+ payment_id=payment_id,
975
+ payer_address=payer_address,
976
+ amount_atomic=amount_atomic,
977
+ amount_usdc=amount_usdc,
978
+ )
979
+
980
+ async def settle(
981
+ self,
982
+ payment_data: Dict[str, Any],
983
+ required_atomic: int,
984
+ config: X402Config,
985
+ ) -> SettlementResult:
986
+ self.settle_calls += 1
987
+ if payment_data.get("simulate_settle_error"):
988
+ return SettlementResult(
989
+ settled=False,
990
+ error="Simulated facilitator settlement error",
991
+ )
992
+ payment_id = str(payment_data.get("payment_id", ""))
993
+ tx_hash = "0x" + hashlib.sha256(payment_id.encode("utf-8")).hexdigest()
994
+ return SettlementResult(
995
+ settled=True,
996
+ tx_hash=tx_hash,
997
+ )
998
+
999
+
1000
+ class HTTPX402Facilitator:
1001
+ """
1002
+ Production-grade HTTP facilitator adapter communicating with a remote x402 facilitator node.
1003
+ Supports both standard HTTP REST facilitator endpoints and EIP-3009 on-chain settlement via x402 SDK.
1004
+ """
1005
+
1006
+ def __init__(
1007
+ self,
1008
+ facilitator_url: Optional[str] = None,
1009
+ timeout: float = 10.0,
1010
+ client: Optional[httpx.AsyncClient] = None,
1011
+ ):
1012
+ self.facilitator_url = facilitator_url
1013
+ self.timeout = timeout
1014
+ self.client = client
1015
+
1016
+ def _verify_eip3009_sync(
1017
+ self,
1018
+ payload_obj: Any,
1019
+ req: Any,
1020
+ facilitator_url: str,
1021
+ network: str,
1022
+ payment_id: str,
1023
+ payer_address: str,
1024
+ amount_atomic: int,
1025
+ amount_usdc: float,
1026
+ auth_provider: Any = None,
1027
+ ) -> VerificationResult:
1028
+ try:
1029
+ fac_cfg = FacilitatorConfig(url=facilitator_url, auth_provider=auth_provider) if auth_provider else FacilitatorConfig(url=facilitator_url)
1030
+ fac = HTTPFacilitatorClientSync(fac_cfg)
1031
+ srv = x402ResourceServerSync(fac)
1032
+ srv.register(network, ExactEvmServerScheme())
1033
+ if hasattr(srv, "register_extension") and HAS_X402_SDK and HAS_X402_BAZAAR:
1034
+ try:
1035
+ srv.register_extension(bazaar_resource_server_extension)
1036
+ except Exception as ext_err:
1037
+ logger.debug("Could not register bazaar extension on srv: %s", ext_err)
1038
+ srv.initialize()
1039
+
1040
+ v = srv.verify_payment(payload_obj, req)
1041
+ is_valid = getattr(v, "is_valid", False)
1042
+ if hasattr(v, "verify") and hasattr(v.verify, "is_valid"):
1043
+ is_valid = bool(v.verify.is_valid)
1044
+
1045
+ if is_valid:
1046
+ return VerificationResult(
1047
+ valid=True,
1048
+ reason=None,
1049
+ payment_id=payment_id,
1050
+ payer_address=payer_address,
1051
+ amount_atomic=amount_atomic,
1052
+ amount_usdc=amount_usdc,
1053
+ )
1054
+ else:
1055
+ invalid_reason = (
1056
+ getattr(v, "invalid_reason", None)
1057
+ or (getattr(v.verify, "invalid_reason", None) if hasattr(v, "verify") else None)
1058
+ or "Payment verification rejected"
1059
+ )
1060
+ invalid_msg = (
1061
+ getattr(v, "invalid_message", None)
1062
+ or (getattr(v.verify, "invalid_message", None) if hasattr(v, "verify") else None)
1063
+ )
1064
+ reason_str = f"{invalid_reason}: {invalid_msg}" if invalid_msg else str(invalid_reason)
1065
+ return VerificationResult(
1066
+ valid=False,
1067
+ reason=reason_str,
1068
+ payment_id=payment_id,
1069
+ payer_address=payer_address,
1070
+ amount_atomic=amount_atomic,
1071
+ amount_usdc=amount_usdc,
1072
+ )
1073
+ except Exception as exc:
1074
+ return VerificationResult(
1075
+ valid=False,
1076
+ reason=f"Facilitator verification connection error: {str(exc)}",
1077
+ payment_id=payment_id,
1078
+ payer_address=payer_address,
1079
+ amount_atomic=amount_atomic,
1080
+ amount_usdc=amount_usdc,
1081
+ )
1082
+
1083
+ def _build_resource_and_extensions(
1084
+ self, payment_data: Dict[str, Any]
1085
+ ) -> tuple[Dict[str, Any], Dict[str, Any]]:
1086
+ endpoint = str(payment_data.get("endpoint") or "/evaluate")
1087
+ full_resource_url = (
1088
+ endpoint
1089
+ if endpoint.startswith("http://") or endpoint.startswith("https://")
1090
+ else f"{_get_public_api_url()}{endpoint if endpoint.startswith('/') else '/' + endpoint}"
1091
+ )
1092
+ default_resource_obj = {
1093
+ "url": full_resource_url,
1094
+ "description": f"Web3 Security & Governance Audit for {endpoint} — EVM Pre-Transaction Security Firewall, Calldata Decoder & DAO Proposal Risk Auditor (Base, Ethereum, Arbitrum, Optimism)",
1095
+ "mimeType": "application/json",
1096
+ "serviceName": "Web3 Systemic Agent",
1097
+ "tags": ["web3-security", "smart-contract-audit", "honeypot-detector", "dao-governance", "base", "evm"],
1098
+ }
1099
+ if isinstance(payment_data.get("resource"), dict) and payment_data["resource"].get("url"):
1100
+ resource_obj = payment_data["resource"]
1101
+ else:
1102
+ resource_obj = default_resource_obj
1103
+
1104
+ if isinstance(payment_data.get("extensions"), dict) and "bazaar" in payment_data["extensions"]:
1105
+ extensions_dict = payment_data["extensions"]
1106
+ else:
1107
+ extensions_dict = build_bazaar_discovery_extension(endpoint)
1108
+
1109
+ return resource_obj, extensions_dict
1110
+
1111
+ def _settle_eip3009_sync(
1112
+ self,
1113
+ payload_obj: Any,
1114
+ req: Any,
1115
+ facilitator_url: str,
1116
+ network: str,
1117
+ auth_provider: Any = None,
1118
+ declared_extensions: Optional[Dict[str, Any]] = None,
1119
+ ) -> SettlementResult:
1120
+ try:
1121
+ fac_cfg = FacilitatorConfig(url=facilitator_url, auth_provider=auth_provider) if auth_provider else FacilitatorConfig(url=facilitator_url)
1122
+ fac = HTTPFacilitatorClientSync(fac_cfg)
1123
+ srv = x402ResourceServerSync(fac)
1124
+ srv.register(network, ExactEvmServerScheme())
1125
+ if hasattr(srv, "register_extension") and HAS_X402_SDK and HAS_X402_BAZAAR:
1126
+ try:
1127
+ srv.register_extension(bazaar_resource_server_extension)
1128
+ except Exception as ext_err:
1129
+ logger.debug("Could not register bazaar extension on srv: %s", ext_err)
1130
+ srv.initialize()
1131
+
1132
+ try:
1133
+ s = srv.settle_payment(payload_obj, req, declared_extensions=declared_extensions)
1134
+ except TypeError:
1135
+ s = srv.settle_payment(payload_obj, req)
1136
+ settle_success = getattr(s, "success", False)
1137
+ if not settle_success and hasattr(s, "settle"):
1138
+ settle_success = getattr(s.settle, "success", False)
1139
+
1140
+ if not settle_success:
1141
+ err_reason = getattr(s, "error_reason", "unknown")
1142
+ err_msg = getattr(s, "error_message", "Unknown settlement error")
1143
+ return SettlementResult(
1144
+ settled=False,
1145
+ error=f"{err_reason}: {err_msg}",
1146
+ )
1147
+
1148
+ tx_hash = (
1149
+ getattr(s, "transaction", None)
1150
+ or (getattr(s.settle, "transaction", None) if hasattr(s, "settle") else None)
1151
+ )
1152
+ return SettlementResult(
1153
+ settled=True,
1154
+ tx_hash=tx_hash,
1155
+ )
1156
+ except Exception as exc:
1157
+ return SettlementResult(
1158
+ settled=False,
1159
+ error=f"Facilitator settlement error: {str(exc)}",
1160
+ )
1161
+
1162
+ async def verify(
1163
+ self,
1164
+ payment_data: Dict[str, Any],
1165
+ required_atomic: int,
1166
+ config: X402Config,
1167
+ ) -> VerificationResult:
1168
+ payment_id = str(payment_data.get("payment_id", ""))
1169
+ payer_address = str(payment_data.get("payer_address", ""))
1170
+ amount_atomic = int(payment_data.get("amount_atomic", 0))
1171
+ amount_usdc = float(payment_data.get("amount_usdc", amount_atomic / (10 ** USDC_DECIMALS)))
1172
+ resource_obj, extensions_dict = self._build_resource_and_extensions(payment_data)
1173
+
1174
+ is_eip3009 = (
1175
+ self.client is None
1176
+ and HAS_X402_SDK
1177
+ and isinstance(payment_data.get("payload"), dict)
1178
+ and "authorization" in payment_data["payload"]
1179
+ )
1180
+
1181
+ if is_eip3009:
1182
+ if amount_atomic < required_atomic:
1183
+ return VerificationResult(
1184
+ valid=False,
1185
+ reason=f"Insufficient payment amount: {amount_atomic} < {required_atomic}",
1186
+ payment_id=payment_id,
1187
+ payer_address=payer_address,
1188
+ amount_atomic=amount_atomic,
1189
+ amount_usdc=amount_usdc,
1190
+ )
1191
+
1192
+ net = payment_data.get("network")
1193
+ if net and net != config.network:
1194
+ return VerificationResult(
1195
+ valid=False,
1196
+ reason="Network mismatch",
1197
+ payment_id=payment_id,
1198
+ payer_address=payer_address,
1199
+ amount_atomic=amount_atomic,
1200
+ amount_usdc=amount_usdc,
1201
+ )
1202
+
1203
+ base_url = (self.facilitator_url or config.facilitator_url).rstrip("/")
1204
+ accepted_data = payment_data.get("accepted")
1205
+ if isinstance(accepted_data, dict):
1206
+ req = PaymentRequirements.model_validate(accepted_data)
1207
+ else:
1208
+ token_name = _get_token_name(config.network)
1209
+ req = PaymentRequirements(
1210
+ scheme="exact",
1211
+ network=config.network,
1212
+ asset=config.usdc_contract_address,
1213
+ amount=str(amount_atomic),
1214
+ pay_to=config.pay_to_address,
1215
+ max_timeout_seconds=300,
1216
+ extra={"name": token_name, "version": "2"},
1217
+ )
1218
+
1219
+ payload_dict = {
1220
+ "x402Version": payment_data.get("x402Version", 2),
1221
+ "payload": payment_data["payload"],
1222
+ "resource": resource_obj,
1223
+ "extensions": extensions_dict,
1224
+ }
1225
+ if isinstance(accepted_data, dict):
1226
+ payload_dict["accepted"] = accepted_data
1227
+ else:
1228
+ payload_dict["accepted"] = req.model_dump(by_alias=True)
1229
+
1230
+ payload_obj = PaymentPayload.model_validate(payload_dict)
1231
+
1232
+ auth_provider = (
1233
+ CDPFacilitatorAuthProvider(config.cdp_api_key_id, config.cdp_api_key_secret)
1234
+ if config.has_cdp_credentials()
1235
+ else None
1236
+ )
1237
+
1238
+ return await asyncio.to_thread(
1239
+ self._verify_eip3009_sync,
1240
+ payload_obj=payload_obj,
1241
+ req=req,
1242
+ facilitator_url=base_url,
1243
+ network=config.network,
1244
+ payment_id=payment_id,
1245
+ payer_address=payer_address,
1246
+ amount_atomic=amount_atomic,
1247
+ amount_usdc=amount_usdc,
1248
+ auth_provider=auth_provider,
1249
+ )
1250
+
1251
+ base_url = (self.facilitator_url or config.facilitator_url).rstrip("/")
1252
+ url = f"{base_url}/verify"
1253
+ req_dict = payment_data.get("accepted")
1254
+ if not isinstance(req_dict, dict):
1255
+ token_name = _get_token_name(config.network)
1256
+ req_dict = {
1257
+ "scheme": "exact",
1258
+ "network": config.network,
1259
+ "asset": config.usdc_contract_address,
1260
+ "amount": str(required_atomic),
1261
+ "payTo": config.pay_to_address,
1262
+ "maxTimeoutSeconds": 300,
1263
+ "extra": {"name": token_name, "version": "2"},
1264
+ }
1265
+
1266
+ payment_payload_dict = {
1267
+ "x402Version": payment_data.get("x402Version", 2),
1268
+ "payload": payment_data.get("payload") if isinstance(payment_data.get("payload"), dict) else {
1269
+ "authorization": payment_data.get("authorization", {}),
1270
+ "signature": payment_data.get("signature", ""),
1271
+ },
1272
+ "accepted": req_dict,
1273
+ "resource": resource_obj,
1274
+ "extensions": extensions_dict,
1275
+ }
1276
+
1277
+ payload = {
1278
+ "x402Version": payment_data.get("x402Version", 2),
1279
+ "paymentPayload": payment_payload_dict,
1280
+ "paymentRequirements": req_dict,
1281
+ }
1282
+ headers = {}
1283
+ if config.has_cdp_credentials():
1284
+ auth_provider = CDPFacilitatorAuthProvider(config.cdp_api_key_id, config.cdp_api_key_secret)
1285
+ auth_hdrs = auth_provider.get_auth_headers()
1286
+ verify_hdrs = auth_hdrs.verify if hasattr(auth_hdrs, "verify") else auth_hdrs.get("verify", {})
1287
+ headers.update(verify_hdrs)
1288
+
1289
+ try:
1290
+ if self.client is not None:
1291
+ resp = await self.client.post(url, json=payload, headers=headers if headers else None, timeout=self.timeout)
1292
+ else:
1293
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
1294
+ resp = await client.post(url, json=payload, headers=headers if headers else None)
1295
+ if resp.status_code == 200:
1296
+ data = resp.json()
1297
+ is_valid = data.get("isValid", data.get("valid", False))
1298
+ if isinstance(data.get("verify"), dict):
1299
+ is_valid = data["verify"].get("isValid", data["verify"].get("valid", is_valid))
1300
+ invalid_reason = data.get("invalidReason", data.get("reason"))
1301
+ return VerificationResult(
1302
+ valid=bool(is_valid),
1303
+ reason=invalid_reason,
1304
+ payment_id=payment_id,
1305
+ payer_address=payer_address,
1306
+ amount_atomic=amount_atomic,
1307
+ amount_usdc=amount_usdc,
1308
+ )
1309
+ else:
1310
+ return VerificationResult(
1311
+ valid=False,
1312
+ reason=f"Facilitator verification returned status {resp.status_code}: {resp.text}",
1313
+ payment_id=payment_id,
1314
+ payer_address=payer_address,
1315
+ amount_atomic=amount_atomic,
1316
+ amount_usdc=amount_usdc,
1317
+ )
1318
+ except Exception as exc:
1319
+ return VerificationResult(
1320
+ valid=False,
1321
+ reason=f"Facilitator verification connection error: {str(exc)}",
1322
+ payment_id=payment_id,
1323
+ payer_address=payer_address,
1324
+ amount_atomic=amount_atomic,
1325
+ amount_usdc=amount_usdc,
1326
+ )
1327
+
1328
+ async def settle(
1329
+ self,
1330
+ payment_data: Dict[str, Any],
1331
+ required_atomic: int,
1332
+ config: X402Config,
1333
+ ) -> SettlementResult:
1334
+ resource_obj, extensions_dict = self._build_resource_and_extensions(payment_data)
1335
+
1336
+ is_eip3009 = (
1337
+ self.client is None
1338
+ and HAS_X402_SDK
1339
+ and isinstance(payment_data.get("payload"), dict)
1340
+ and "authorization" in payment_data["payload"]
1341
+ )
1342
+
1343
+ if is_eip3009:
1344
+ base_url = (self.facilitator_url or config.facilitator_url).rstrip("/")
1345
+ accepted_data = payment_data.get("accepted")
1346
+ if isinstance(accepted_data, dict):
1347
+ req = PaymentRequirements.model_validate(accepted_data)
1348
+ else:
1349
+ amount_atomic = int(payment_data.get("amount_atomic", required_atomic))
1350
+ token_name = _get_token_name(config.network)
1351
+ req = PaymentRequirements(
1352
+ scheme="exact",
1353
+ network=config.network,
1354
+ asset=config.usdc_contract_address,
1355
+ amount=str(amount_atomic),
1356
+ pay_to=config.pay_to_address,
1357
+ max_timeout_seconds=300,
1358
+ extra={"name": token_name, "version": "2"},
1359
+ )
1360
+
1361
+ payload_dict = {
1362
+ "x402Version": payment_data.get("x402Version", 2),
1363
+ "payload": payment_data["payload"],
1364
+ "resource": resource_obj,
1365
+ "extensions": extensions_dict,
1366
+ }
1367
+ if isinstance(accepted_data, dict):
1368
+ payload_dict["accepted"] = accepted_data
1369
+ else:
1370
+ payload_dict["accepted"] = req.model_dump(by_alias=True)
1371
+
1372
+ payload_obj = PaymentPayload.model_validate(payload_dict)
1373
+
1374
+ auth_provider = (
1375
+ CDPFacilitatorAuthProvider(config.cdp_api_key_id, config.cdp_api_key_secret)
1376
+ if config.has_cdp_credentials()
1377
+ else None
1378
+ )
1379
+
1380
+ return await asyncio.to_thread(
1381
+ self._settle_eip3009_sync,
1382
+ payload_obj=payload_obj,
1383
+ req=req,
1384
+ facilitator_url=base_url,
1385
+ network=config.network,
1386
+ auth_provider=auth_provider,
1387
+ declared_extensions=extensions_dict,
1388
+ )
1389
+
1390
+ base_url = (self.facilitator_url or config.facilitator_url).rstrip("/")
1391
+ url = f"{base_url}/settle"
1392
+ req_dict = payment_data.get("accepted")
1393
+ if not isinstance(req_dict, dict):
1394
+ amount_atomic = int(payment_data.get("amount_atomic", required_atomic))
1395
+ token_name = _get_token_name(config.network)
1396
+ req_dict = {
1397
+ "scheme": "exact",
1398
+ "network": config.network,
1399
+ "asset": config.usdc_contract_address,
1400
+ "amount": str(amount_atomic),
1401
+ "payTo": config.pay_to_address,
1402
+ "maxTimeoutSeconds": 300,
1403
+ "extra": {"name": token_name, "version": "2"},
1404
+ }
1405
+
1406
+ payment_payload_dict = {
1407
+ "x402Version": payment_data.get("x402Version", 2),
1408
+ "payload": payment_data.get("payload") if isinstance(payment_data.get("payload"), dict) else {
1409
+ "authorization": payment_data.get("authorization", {}),
1410
+ "signature": payment_data.get("signature", ""),
1411
+ },
1412
+ "accepted": req_dict,
1413
+ "resource": resource_obj,
1414
+ "extensions": extensions_dict,
1415
+ }
1416
+
1417
+ payload = {
1418
+ "x402Version": payment_data.get("x402Version", 2),
1419
+ "paymentPayload": payment_payload_dict,
1420
+ "paymentRequirements": req_dict,
1421
+ }
1422
+ headers = {}
1423
+ if config.has_cdp_credentials():
1424
+ auth_provider = CDPFacilitatorAuthProvider(config.cdp_api_key_id, config.cdp_api_key_secret)
1425
+ auth_hdrs = auth_provider.get_auth_headers()
1426
+ settle_hdrs = auth_hdrs.settle if hasattr(auth_hdrs, "settle") else auth_hdrs.get("settle", {})
1427
+ headers.update(settle_hdrs)
1428
+
1429
+ try:
1430
+ if self.client is not None:
1431
+ resp = await self.client.post(url, json=payload, headers=headers if headers else None, timeout=self.timeout)
1432
+ else:
1433
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
1434
+ resp = await client.post(url, json=payload, headers=headers if headers else None)
1435
+ if resp.status_code == 200:
1436
+ data = resp.json()
1437
+ settled = data.get("success", data.get("settled", False))
1438
+ if isinstance(data.get("settle"), dict):
1439
+ settled = data["settle"].get("success", data["settle"].get("settled", settled))
1440
+ tx_hash = data.get("transaction", data.get("tx_hash"))
1441
+ if isinstance(data.get("settle"), dict) and not tx_hash:
1442
+ tx_hash = data["settle"].get("transaction", data["settle"].get("tx_hash"))
1443
+ return SettlementResult(
1444
+ settled=bool(settled),
1445
+ tx_hash=tx_hash,
1446
+ error=data.get("errorMessage", data.get("error")),
1447
+ )
1448
+ else:
1449
+ return SettlementResult(
1450
+ settled=False,
1451
+ error=f"Facilitator settlement returned status {resp.status_code}: {resp.text}",
1452
+ )
1453
+ except Exception as exc:
1454
+ return SettlementResult(
1455
+ settled=False,
1456
+ error=f"Facilitator settlement connection error: {str(exc)}",
1457
+ )
1458
+
1459
+
1460
+ def get_x402_facilitator(
1461
+ config: Optional[X402Config] = None,
1462
+ ) -> Union[HTTPX402Facilitator, MockX402Facilitator]:
1463
+ """
1464
+ Returns an appropriate x402 facilitator instance based on config.
1465
+ Returns HTTPX402Facilitator if config.use_live_facilitator is True,
1466
+ otherwise MockX402Facilitator.
1467
+ """
1468
+ cfg = config or X402Config()
1469
+ if cfg.use_live_facilitator:
1470
+ return HTTPX402Facilitator(facilitator_url=cfg.facilitator_url)
1471
+ return MockX402Facilitator()
1472
+
1473
+
1474
+ def build_402_response(
1475
+ config: X402Config,
1476
+ endpoint: str,
1477
+ required_usdc: float,
1478
+ reason: str = "Payment Required",
1479
+ ) -> JSONResponse:
1480
+ """
1481
+ Constructs a compliant HTTP 402 Payment Required response containing x402 payment scheme metadata
1482
+ and Bazaar auto-discovery extensions.
1483
+ """
1484
+ required_atomic = usdc_to_atomic(required_usdc)
1485
+ token_name = _get_token_name(config.network)
1486
+ full_resource_url = (
1487
+ endpoint
1488
+ if endpoint.startswith("http://") or endpoint.startswith("https://")
1489
+ else f"{_get_public_api_url()}{endpoint if endpoint.startswith('/') else '/' + endpoint}"
1490
+ )
1491
+ resource_obj = {
1492
+ "url": full_resource_url,
1493
+ "description": f"Web3 Security & Governance Audit for {endpoint} — EVM Pre-Transaction Security Firewall, Calldata Decoder & DAO Proposal Risk Auditor (Base, Ethereum, Arbitrum, Optimism)",
1494
+ "mimeType": "application/json",
1495
+ "serviceName": "Web3 Systemic Agent",
1496
+ "tags": ["web3-security", "smart-contract-audit", "honeypot-detector", "dao-governance", "base", "evm"],
1497
+ }
1498
+ body = {
1499
+ "x402Version": 2,
1500
+ "error": "PaymentRequired",
1501
+ "message": reason,
1502
+ "resource": resource_obj,
1503
+ "accepts": [
1504
+ {
1505
+ "scheme": "exact",
1506
+ "network": config.network,
1507
+ "amount": str(required_atomic),
1508
+ "maxAmountRequired": str(required_atomic),
1509
+ "amount_usdc": round(required_usdc, 6),
1510
+ "asset": config.usdc_contract_address,
1511
+ "usdcAddress": config.usdc_contract_address,
1512
+ "payTo": config.pay_to_address,
1513
+ "maxTimeoutSeconds": 300,
1514
+ "resource": resource_obj,
1515
+ "url": full_resource_url,
1516
+ "description": resource_obj["description"],
1517
+ "mimeType": "application/json",
1518
+ "discoverable": True,
1519
+ "extra": {"name": token_name, "version": "2"},
1520
+ }
1521
+ ],
1522
+ "extensions": build_bazaar_discovery_extension(endpoint),
1523
+ }
1524
+ b64_payment_required = base64.b64encode(json.dumps(body).encode("utf-8")).decode("utf-8")
1525
+ headers = {
1526
+ "X-PAYMENT-REQUIRED": "true",
1527
+ "Payment-Required": b64_payment_required,
1528
+ }
1529
+ logger.info(
1530
+ "TELEMETRY | event=x402_probe endpoint=%s amount_usdc=%s network=%s reason=%r",
1531
+ endpoint,
1532
+ round(required_usdc, 6),
1533
+ config.network,
1534
+ reason,
1535
+ )
1536
+ return JSONResponse(
1537
+ status_code=402,
1538
+ content=body,
1539
+ headers=headers,
1540
+ )