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.
- scripts/active_contract_hunter.py +262 -0
- scripts/block_contract_scanner.py +887 -0
- scripts/client_agent_x402.py +584 -0
- scripts/dex_pool_monitor.py +1418 -0
- scripts/governance_daemon.py +683 -0
- scripts/governance_listener.py +201 -0
- scripts/register_erc8004_agent.py +297 -0
- scripts/setup_buyer_wallet.py +193 -0
- src/api.py +5094 -0
- src/chain_inspector.py +256 -0
- src/discovery_hunter.py +1000 -0
- src/engine.py +281 -0
- src/governance_connector.py +548 -0
- src/mcp_server.py +2048 -0
- src/preflight_firewall.py +603 -0
- src/report.py +142 -0
- src/schemas.py +330 -0
- src/semantic_evaluator.py +981 -0
- src/source_resolver.py +792 -0
- src/storage.py +863 -0
- src/task_worker.py +325 -0
- src/test_cache_and_telemetry.py +488 -0
- src/x402_payment.py +1540 -0
- web3_systemic_agent-1.0.2.dist-info/METADATA +511 -0
- web3_systemic_agent-1.0.2.dist-info/RECORD +29 -0
- web3_systemic_agent-1.0.2.dist-info/WHEEL +5 -0
- web3_systemic_agent-1.0.2.dist-info/entry_points.txt +3 -0
- web3_systemic_agent-1.0.2.dist-info/licenses/LICENSE +201 -0
- web3_systemic_agent-1.0.2.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
"""
|
|
2
|
+
x402 Agent-to-Agent (A2A) Client Demonstration Script.
|
|
3
|
+
|
|
4
|
+
Simulates an autonomous Buyer AI Agent negotiating and executing micropayments
|
|
5
|
+
under the x402 Payment Protocol to purchase Web3 smart contract security and
|
|
6
|
+
governance audits from the Web3 Condition-Action Trigger Agent service.
|
|
7
|
+
|
|
8
|
+
Key Capabilities Demonstrated:
|
|
9
|
+
1. Dynamic EVM Keypair Generation for Buyer Agent via eth_account.
|
|
10
|
+
2. Dual-Mode Client Execution:
|
|
11
|
+
- Live Server Mode: Connects to running server at --url (default: http://127.0.0.1:8000).
|
|
12
|
+
- In-Process Fallback Mode: Seamless ASGI execution using FastAPI app instance
|
|
13
|
+
when no external uvicorn server is running (zero setup required).
|
|
14
|
+
3. Complete 8-Step x402 A2A Lifecycle:
|
|
15
|
+
- Step 1: Health inspection and payment capability discovery (GET /health).
|
|
16
|
+
- Step 2: Critical DAO governance audit payload formulation.
|
|
17
|
+
- Step 3: Unauthenticated audit dispatch -> HTTP 402 Payment Required negotiation.
|
|
18
|
+
- Step 4: Cryptographic payment payload signing via Buyer's private key.
|
|
19
|
+
- Step 5: Authenticated retry with X-PAYMENT header.
|
|
20
|
+
- Step 6: HTTP 200 OK verification, audit decision extraction, and payment receipt parsing.
|
|
21
|
+
- Step 7: Persistence verification across GET /payments and GET /metrics/summary.
|
|
22
|
+
- Step 8: Comprehensive commercial & operational ledger report via src.report.
|
|
23
|
+
|
|
24
|
+
Usage:
|
|
25
|
+
python scripts/client_agent_x402.py [--url http://127.0.0.1:8000]
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import asyncio
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import sys
|
|
33
|
+
import uuid
|
|
34
|
+
from typing import Dict, Any, Tuple, Optional
|
|
35
|
+
|
|
36
|
+
# 1. Configure module resolution for root and src directories
|
|
37
|
+
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
38
|
+
_ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
|
|
39
|
+
_SRC_DIR = os.path.join(_ROOT_DIR, "src")
|
|
40
|
+
for _p in (_ROOT_DIR, _SRC_DIR):
|
|
41
|
+
if _p not in sys.path:
|
|
42
|
+
sys.path.insert(0, _p)
|
|
43
|
+
|
|
44
|
+
# 2. Load environment variables (.env) when not under test harness
|
|
45
|
+
if "pytest" not in sys.modules:
|
|
46
|
+
import dotenv
|
|
47
|
+
|
|
48
|
+
_env_file = os.path.join(_ROOT_DIR, ".env")
|
|
49
|
+
if os.path.exists(_env_file):
|
|
50
|
+
dotenv.load_dotenv(_env_file, override=False)
|
|
51
|
+
dotenv.load_dotenv(override=False)
|
|
52
|
+
|
|
53
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
54
|
+
try:
|
|
55
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
56
|
+
except Exception:
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
# Configure responsive default Gemini model
|
|
60
|
+
if "GEMINI_MODEL" not in os.environ:
|
|
61
|
+
os.environ["GEMINI_MODEL"] = "gemini-3.5-flash-lite"
|
|
62
|
+
|
|
63
|
+
from eth_account import Account
|
|
64
|
+
from eth_account.messages import encode_defunct
|
|
65
|
+
import httpx
|
|
66
|
+
from web3 import Web3
|
|
67
|
+
|
|
68
|
+
from src.api import create_app
|
|
69
|
+
from src.report import format_report_text
|
|
70
|
+
try:
|
|
71
|
+
from src.x402_payment import create_eip3009_payment_header
|
|
72
|
+
except ImportError:
|
|
73
|
+
from x402_payment import create_eip3009_payment_header
|
|
74
|
+
|
|
75
|
+
# Canonical Base Sepolia contract for testing
|
|
76
|
+
DEFAULT_TARGET_CONTRACT = "0x4200000000000000000000000000000000000006"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def fetch_live_contract_transaction(
|
|
80
|
+
rpc_url: Optional[str] = None,
|
|
81
|
+
max_blocks_back: int = 5,
|
|
82
|
+
) -> Optional[Dict[str, Any]]:
|
|
83
|
+
"""
|
|
84
|
+
Scans the latest blocks on Base Sepolia to capture an authentic, recently-mined
|
|
85
|
+
smart contract transaction with calldata.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
dict with keys: tx_hash, block_number, from_address, target_address,
|
|
89
|
+
calldata, selector, value_wei; or None if query fails.
|
|
90
|
+
"""
|
|
91
|
+
candidate_rpcs = [
|
|
92
|
+
rpc_url or os.getenv("BASE_SEPOLIA_RPC", "https://sepolia.base.org"),
|
|
93
|
+
"https://base-sepolia-rpc.publicnode.com",
|
|
94
|
+
]
|
|
95
|
+
seen = set()
|
|
96
|
+
rpcs = []
|
|
97
|
+
for r in candidate_rpcs:
|
|
98
|
+
if r and r not in seen:
|
|
99
|
+
seen.add(r)
|
|
100
|
+
rpcs.append(r)
|
|
101
|
+
|
|
102
|
+
for active_rpc in rpcs:
|
|
103
|
+
try:
|
|
104
|
+
w3 = Web3(Web3.HTTPProvider(active_rpc, request_kwargs={"timeout": 10.0}))
|
|
105
|
+
if not w3.is_connected():
|
|
106
|
+
continue
|
|
107
|
+
|
|
108
|
+
latest_block = int(w3.eth.block_number)
|
|
109
|
+
min_block = max(0, latest_block - max_blocks_back + 1)
|
|
110
|
+
|
|
111
|
+
for b_num in range(latest_block, min_block - 1, -1):
|
|
112
|
+
try:
|
|
113
|
+
block = w3.eth.get_block(b_num, full_transactions=True)
|
|
114
|
+
except Exception:
|
|
115
|
+
continue
|
|
116
|
+
|
|
117
|
+
transactions = getattr(block, "transactions", []) or []
|
|
118
|
+
for tx in transactions:
|
|
119
|
+
to_addr = tx.get("to")
|
|
120
|
+
if not to_addr:
|
|
121
|
+
continue
|
|
122
|
+
|
|
123
|
+
# Extract calldata hex string
|
|
124
|
+
raw_input = tx.get("input") or tx.get("data") or b""
|
|
125
|
+
if hasattr(raw_input, "hex"):
|
|
126
|
+
hex_raw = raw_input.hex()
|
|
127
|
+
hex_input = hex_raw if hex_raw.startswith("0x") else "0x" + hex_raw
|
|
128
|
+
elif isinstance(raw_input, bytes):
|
|
129
|
+
hex_input = "0x" + raw_input.hex()
|
|
130
|
+
else:
|
|
131
|
+
hex_input = str(raw_input).strip()
|
|
132
|
+
if not hex_input.startswith("0x"):
|
|
133
|
+
hex_input = "0x" + hex_input
|
|
134
|
+
|
|
135
|
+
# Must have at least a 4-byte function selector (0x + 8 hex chars = 10 chars)
|
|
136
|
+
if len(hex_input) < 10 or hex_input == "0x":
|
|
137
|
+
continue
|
|
138
|
+
|
|
139
|
+
checksum_to = Web3.to_checksum_address(to_addr)
|
|
140
|
+
try:
|
|
141
|
+
code = w3.eth.get_code(checksum_to)
|
|
142
|
+
if len(code) == 0:
|
|
143
|
+
continue
|
|
144
|
+
except Exception:
|
|
145
|
+
continue
|
|
146
|
+
|
|
147
|
+
raw_hash = tx.get("hash", "")
|
|
148
|
+
if hasattr(raw_hash, "hex"):
|
|
149
|
+
h_hex = raw_hash.hex()
|
|
150
|
+
tx_hash_hex = h_hex if h_hex.startswith("0x") else "0x" + h_hex
|
|
151
|
+
elif isinstance(raw_hash, bytes):
|
|
152
|
+
tx_hash_hex = "0x" + raw_hash.hex()
|
|
153
|
+
else:
|
|
154
|
+
tx_hash_hex = str(raw_hash).strip()
|
|
155
|
+
if not tx_hash_hex.startswith("0x"):
|
|
156
|
+
tx_hash_hex = "0x" + tx_hash_hex
|
|
157
|
+
|
|
158
|
+
from_addr = tx.get("from")
|
|
159
|
+
checksum_from = Web3.to_checksum_address(from_addr) if from_addr else "0x0000000000000000000000000000000000000000"
|
|
160
|
+
|
|
161
|
+
val_wei = int(tx.get("value", 0))
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
"tx_hash": tx_hash_hex,
|
|
165
|
+
"block_number": int(b_num),
|
|
166
|
+
"from_address": checksum_from,
|
|
167
|
+
"target_address": checksum_to,
|
|
168
|
+
"calldata": hex_input,
|
|
169
|
+
"selector": hex_input[:10].lower(),
|
|
170
|
+
"value_wei": val_wei,
|
|
171
|
+
}
|
|
172
|
+
except Exception:
|
|
173
|
+
continue
|
|
174
|
+
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def load_persistent_buyer_wallet() -> Account:
|
|
179
|
+
"""Loads persistent buyer wallet from scripts/.buyer_wallet.json if present, or creates a transient keypair."""
|
|
180
|
+
wallet_path = os.path.join(_CURRENT_DIR, ".buyer_wallet.json")
|
|
181
|
+
if os.path.exists(wallet_path):
|
|
182
|
+
try:
|
|
183
|
+
with open(wallet_path, "r", encoding="utf-8") as f:
|
|
184
|
+
data = json.load(f)
|
|
185
|
+
private_key = data.get("private_key")
|
|
186
|
+
if private_key:
|
|
187
|
+
return Account.from_key(private_key)
|
|
188
|
+
except Exception:
|
|
189
|
+
pass
|
|
190
|
+
return Account.create()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def print_banner(title: str) -> None:
|
|
194
|
+
"""Prints a styled terminal section banner."""
|
|
195
|
+
width = 72
|
|
196
|
+
print("\n" + "=" * width)
|
|
197
|
+
print(f" {title}")
|
|
198
|
+
print("=" * width)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
async def setup_client_session(
|
|
202
|
+
target_url: str,
|
|
203
|
+
force_in_process: bool = False,
|
|
204
|
+
) -> Tuple[httpx.AsyncClient, bool, Optional[Any]]:
|
|
205
|
+
"""
|
|
206
|
+
Establishes an HTTP client session.
|
|
207
|
+
When force_in_process is True, directly launches an in-process ASGI client.
|
|
208
|
+
Otherwise probes target_url; if reachable, runs in live server mode.
|
|
209
|
+
If unreachable, initializes an in-process ASGITransport client.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
(client, is_live_mode, app_instance_if_in_process)
|
|
213
|
+
"""
|
|
214
|
+
if not force_in_process:
|
|
215
|
+
try:
|
|
216
|
+
live_client = httpx.AsyncClient(base_url=target_url, timeout=45.0)
|
|
217
|
+
try:
|
|
218
|
+
resp = await live_client.get("/health", timeout=6.0)
|
|
219
|
+
if resp.status_code == 200:
|
|
220
|
+
return live_client, True, None
|
|
221
|
+
await live_client.aclose()
|
|
222
|
+
except Exception:
|
|
223
|
+
await live_client.aclose()
|
|
224
|
+
except Exception:
|
|
225
|
+
pass
|
|
226
|
+
|
|
227
|
+
# Fallback (or forced) to in-process ASGI Transport
|
|
228
|
+
in_process_app = create_app()
|
|
229
|
+
transport = httpx.ASGITransport(app=in_process_app)
|
|
230
|
+
asgi_client = httpx.AsyncClient(
|
|
231
|
+
transport=transport, base_url="http://testserver", timeout=45.0
|
|
232
|
+
)
|
|
233
|
+
return asgi_client, False, in_process_app
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
async def run_x402_client_lifecycle(
|
|
237
|
+
server_url: str,
|
|
238
|
+
target_contract: str,
|
|
239
|
+
live_onchain: bool = False,
|
|
240
|
+
fetch_live_tx: bool = False,
|
|
241
|
+
) -> None:
|
|
242
|
+
"""Executes the full end-to-end x402 A2A client demonstration."""
|
|
243
|
+
if live_onchain:
|
|
244
|
+
os.environ["X402_USE_LIVE_FACILITATOR"] = "true"
|
|
245
|
+
|
|
246
|
+
# -------------------------------------------------------------------------
|
|
247
|
+
# Initialization: Keypair & Session Setup
|
|
248
|
+
# -------------------------------------------------------------------------
|
|
249
|
+
buyer_account = load_persistent_buyer_wallet()
|
|
250
|
+
client, is_live, app_instance = await setup_client_session(
|
|
251
|
+
server_url,
|
|
252
|
+
force_in_process=live_onchain,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
mode_label = (
|
|
256
|
+
f"LIVE SERVER MODE ({server_url})"
|
|
257
|
+
if is_live
|
|
258
|
+
else "IN-PROCESS ASGI MODE (FastAPI ASGITransport)"
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
print_banner("[A2A] x402 AGENT-TO-AGENT MICROPAYMENT DEMONSTRATION")
|
|
262
|
+
print(f" Execution Mode : {mode_label}")
|
|
263
|
+
print(f" Buyer AI Agent Wallet: {buyer_account.address}")
|
|
264
|
+
print(" Key Cryptography : secp256k1 EVM ECDSA Keypair")
|
|
265
|
+
print(f" Target Contract : {target_contract} (Base Sepolia)")
|
|
266
|
+
print(f" Live On-Chain Settle : {live_onchain}")
|
|
267
|
+
print(f" Fetch Live Tx Mode : {fetch_live_tx}")
|
|
268
|
+
|
|
269
|
+
try:
|
|
270
|
+
# ---------------------------------------------------------------------
|
|
271
|
+
# Step 1: Health Inspection & Payment Capability Discovery
|
|
272
|
+
# ---------------------------------------------------------------------
|
|
273
|
+
print_banner("[Step 1] Gateway Health & x402 Gatekeeper Inspection")
|
|
274
|
+
h_resp = await client.get("/health")
|
|
275
|
+
assert h_resp.status_code == 200, f"Expected 200 from /health, got {h_resp.status_code}"
|
|
276
|
+
health_data = h_resp.json()
|
|
277
|
+
|
|
278
|
+
x402_enabled = health_data.get("x402_enabled", False)
|
|
279
|
+
x402_network = health_data.get("x402_network", "unknown")
|
|
280
|
+
price_usdc = health_data.get("price_per_eval_usdc", 0.0)
|
|
281
|
+
provider = health_data.get("provider", "unknown")
|
|
282
|
+
model = health_data.get("model", "default")
|
|
283
|
+
rpc_status = health_data.get("rpc_status", {})
|
|
284
|
+
|
|
285
|
+
print(f" Endpoint Status : HTTP {h_resp.status_code} OK")
|
|
286
|
+
print(f" Gateway Health : {health_data.get('status', 'unknown').upper()}")
|
|
287
|
+
print(f" x402 Enabled : {x402_enabled}")
|
|
288
|
+
print(f" Settlement Network : {x402_network}")
|
|
289
|
+
print(f" Audit Price per Call : ${price_usdc:.4f} USDC")
|
|
290
|
+
print(f" Semantic Auditor : {provider} ({model})")
|
|
291
|
+
print(f" Base Sepolia (84532) : {'ONLINE' if rpc_status.get('84532') else 'OFFLINE'}")
|
|
292
|
+
|
|
293
|
+
if not x402_enabled:
|
|
294
|
+
print("\n[!] WARNING: x402_enabled is False. Ensure X402_ENABLED=true in .env.")
|
|
295
|
+
|
|
296
|
+
# ---------------------------------------------------------------------
|
|
297
|
+
# Step 2: Formulate DAO Governance / Live Blockchain Audit Payload
|
|
298
|
+
# ---------------------------------------------------------------------
|
|
299
|
+
print_banner("[Step 2] Formulate DAO Governance / Live Blockchain Audit Payload")
|
|
300
|
+
rule_id = f"DAO-GOV-AUDIT-{uuid.uuid4().hex[:8].upper()}"
|
|
301
|
+
|
|
302
|
+
live_tx = None
|
|
303
|
+
if fetch_live_tx:
|
|
304
|
+
print(" [*] Fetching authentic recently-mined transaction from Base Sepolia...")
|
|
305
|
+
live_tx = fetch_live_contract_transaction()
|
|
306
|
+
if live_tx:
|
|
307
|
+
print(" [+] Captured Live On-Chain Contract Transaction:")
|
|
308
|
+
print(f" - Block Number : {live_tx['block_number']}")
|
|
309
|
+
print(f" - Live Tx Hash : {live_tx['tx_hash']}")
|
|
310
|
+
print(f" - Basescan URL : https://sepolia.basescan.org/tx/{live_tx['tx_hash']}")
|
|
311
|
+
print(f" - From Address : {live_tx['from_address']}")
|
|
312
|
+
print(f" - Target Contract : {live_tx['target_address']}")
|
|
313
|
+
print(f" - Selector : {live_tx['selector']}")
|
|
314
|
+
print(f" - Calldata Preview : {live_tx['calldata'][:42]}...")
|
|
315
|
+
print(f" - Value (wei) : {live_tx['value_wei']}")
|
|
316
|
+
|
|
317
|
+
audit_payload = {
|
|
318
|
+
"rule_id": rule_id,
|
|
319
|
+
"chain_id": 84532, # Base Sepolia
|
|
320
|
+
"deterministic": {
|
|
321
|
+
"target_address": live_tx["target_address"],
|
|
322
|
+
"min_value_wei": 0,
|
|
323
|
+
"required_function_selectors": [live_tx["selector"]],
|
|
324
|
+
"check_native_balance": False,
|
|
325
|
+
},
|
|
326
|
+
"semantic": {
|
|
327
|
+
"enabled": True,
|
|
328
|
+
"policy_prompt": (
|
|
329
|
+
"Audit this live on-chain smart contract invocation. Assess whether the execution "
|
|
330
|
+
"presents severe risk, reentrancy vulnerabilities, unauthorized privilege escalation, "
|
|
331
|
+
"or security compliance issues."
|
|
332
|
+
),
|
|
333
|
+
"risk_threshold": 7.0,
|
|
334
|
+
},
|
|
335
|
+
"context_metadata": {
|
|
336
|
+
"calldata": live_tx["calldata"],
|
|
337
|
+
"proposal_description": (
|
|
338
|
+
f"Live Base Sepolia transaction {live_tx['tx_hash']} mined in block "
|
|
339
|
+
f"{live_tx['block_number']} invoking selector {live_tx['selector']} on contract {live_tx['target_address']}."
|
|
340
|
+
),
|
|
341
|
+
"tx_value_wei": live_tx["value_wei"],
|
|
342
|
+
},
|
|
343
|
+
}
|
|
344
|
+
else:
|
|
345
|
+
print(" [!] Warning: Could not retrieve a live contract transaction. Falling back to synthetic payload.")
|
|
346
|
+
|
|
347
|
+
if live_tx is None:
|
|
348
|
+
calldata_exploit = "0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
349
|
+
audit_payload = {
|
|
350
|
+
"rule_id": rule_id,
|
|
351
|
+
"chain_id": 84532, # Base Sepolia
|
|
352
|
+
"deterministic": {
|
|
353
|
+
"target_address": target_contract,
|
|
354
|
+
"min_value_wei": 0,
|
|
355
|
+
"required_function_selectors": ["0xf2fde38b"],
|
|
356
|
+
"check_native_balance": False,
|
|
357
|
+
},
|
|
358
|
+
"semantic": {
|
|
359
|
+
"enabled": True,
|
|
360
|
+
"policy_prompt": (
|
|
361
|
+
"Strictly reject any proposal that attempts to transfer contract ownership "
|
|
362
|
+
"or execute unauthorized administrative takeovers under misleading or routine maintenance pretenses."
|
|
363
|
+
),
|
|
364
|
+
"risk_threshold": 7.0,
|
|
365
|
+
},
|
|
366
|
+
"context_metadata": {
|
|
367
|
+
"calldata": calldata_exploit,
|
|
368
|
+
"proposal_description": (
|
|
369
|
+
"Routine yield optimization parameter update. No audit required for this standard config."
|
|
370
|
+
),
|
|
371
|
+
"tx_value_wei": 0,
|
|
372
|
+
},
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
print(f" Rule ID : {rule_id}")
|
|
376
|
+
print(f" Chain ID : {audit_payload['chain_id']} (Base Sepolia)")
|
|
377
|
+
print(f" Target Contract : {target_contract}")
|
|
378
|
+
print(" Required Selector : 0xf2fde38b -> transferOwnership(address)")
|
|
379
|
+
print(f" Calldata Payload : {calldata_exploit[:42]}...")
|
|
380
|
+
print(" Proposal Text : 'Routine yield optimization parameter update...'")
|
|
381
|
+
print(" Semantic Audit Rule : Detect disguise of administrative transfer under routine pretext.")
|
|
382
|
+
|
|
383
|
+
# ---------------------------------------------------------------------
|
|
384
|
+
# Step 3: Send POST /evaluate WITHOUT Payment Header (Expect 402)
|
|
385
|
+
# ---------------------------------------------------------------------
|
|
386
|
+
print_banner("[Step 3] Send POST /evaluate WITHOUT Payment Header (Expect 402)")
|
|
387
|
+
resp_402 = await client.post("/evaluate", json=audit_payload)
|
|
388
|
+
|
|
389
|
+
print(f" Response Status : HTTP {resp_402.status_code} {resp_402.reason_phrase}")
|
|
390
|
+
assert resp_402.status_code == 402, (
|
|
391
|
+
f"Expected HTTP 402 Payment Required, received HTTP {resp_402.status_code}"
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
data_402 = resp_402.json()
|
|
395
|
+
accepts_list = data_402.get("accepts", [])
|
|
396
|
+
assert len(accepts_list) > 0, "402 response missing 'accepts' terms specification."
|
|
397
|
+
terms = accepts_list[0]
|
|
398
|
+
|
|
399
|
+
req_atomic = int(terms.get("maxAmountRequired", 10000))
|
|
400
|
+
req_usdc = float(terms.get("amount_usdc", 0.01))
|
|
401
|
+
req_asset = terms.get("asset", "USDC")
|
|
402
|
+
req_network = terms.get("network", "eip155:84532")
|
|
403
|
+
req_pay_to = terms.get("payTo", "")
|
|
404
|
+
req_resource = terms.get("resource", "/evaluate")
|
|
405
|
+
|
|
406
|
+
print(" x402 Protocol Header : X-PAYMENT-REQUIRED: true")
|
|
407
|
+
print(f" Negotiated Scheme : {terms.get('scheme', 'exact')}")
|
|
408
|
+
print(f" Amount Required : {req_atomic:,} atomic ({req_usdc:.4f} {req_asset})")
|
|
409
|
+
print(f" Asset Token : {req_asset}")
|
|
410
|
+
print(f" Settlement Network : {req_network}")
|
|
411
|
+
print(f" Merchant PayTo : {req_pay_to}")
|
|
412
|
+
print(f" Protected Resource : {req_resource}")
|
|
413
|
+
|
|
414
|
+
# ---------------------------------------------------------------------
|
|
415
|
+
# Step 4: Buyer AI Agent Signs EVM Payment Payload
|
|
416
|
+
# ---------------------------------------------------------------------
|
|
417
|
+
print_banner("[Step 4] Buyer AI Agent Signs EIP-3009 Gasless Micropayment Payload")
|
|
418
|
+
payment_header_json = create_eip3009_payment_header(
|
|
419
|
+
account=buyer_account,
|
|
420
|
+
pay_to_address=req_pay_to,
|
|
421
|
+
amount_atomic=req_atomic,
|
|
422
|
+
network=req_network,
|
|
423
|
+
)
|
|
424
|
+
payment_header_dict = json.loads(payment_header_json)
|
|
425
|
+
payment_id = payment_header_dict.get("payment_id")
|
|
426
|
+
auth_struct = payment_header_dict.get("payload", {}).get("authorization", {})
|
|
427
|
+
sig_hex = payment_header_dict.get("signature", "")
|
|
428
|
+
|
|
429
|
+
print(f" Payment ID (Nonce) : {payment_id}")
|
|
430
|
+
print(f" Payer Address : {buyer_account.address}")
|
|
431
|
+
print(f" Recipient PayTo : {auth_struct.get('to', req_pay_to)}")
|
|
432
|
+
print(f" Amount (Atomic) : {req_atomic} atomic ({req_usdc} USDC)")
|
|
433
|
+
print(f" Valid After : {auth_struct.get('validAfter', '0')}")
|
|
434
|
+
print(f" Valid Before : {auth_struct.get('validBefore', 'N/A')}")
|
|
435
|
+
print(f" Settlement Network : {req_network}")
|
|
436
|
+
print(f" EIP-712 Signature : {sig_hex[:34]}...{sig_hex[-16:] if len(sig_hex) > 50 else sig_hex}")
|
|
437
|
+
|
|
438
|
+
# ---------------------------------------------------------------------
|
|
439
|
+
# Step 5: Retry POST /evaluate with X-PAYMENT Header
|
|
440
|
+
# ---------------------------------------------------------------------
|
|
441
|
+
print_banner("[Step 5] Retry POST /evaluate with X-PAYMENT Header")
|
|
442
|
+
headers = {"X-PAYMENT": payment_header_json}
|
|
443
|
+
print(f" Dispatching POST /evaluate with header 'X-PAYMENT'...")
|
|
444
|
+
resp_200 = await client.post("/evaluate", json=audit_payload, headers=headers)
|
|
445
|
+
|
|
446
|
+
print(f" Response Status : HTTP {resp_200.status_code} {resp_200.reason_phrase}")
|
|
447
|
+
assert resp_200.status_code == 200, (
|
|
448
|
+
f"Expected HTTP 200 OK after valid payment, got {resp_200.status_code}: {resp_200.text}"
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
# ---------------------------------------------------------------------
|
|
452
|
+
# Step 6: Verify HTTP 200 OK, Audit Decision, and Payment Receipt
|
|
453
|
+
# ---------------------------------------------------------------------
|
|
454
|
+
print_banner("[Step 6] Audit Decision & Payment Receipt Extraction")
|
|
455
|
+
result_json = resp_200.json()
|
|
456
|
+
|
|
457
|
+
# Extract semantic evaluation results
|
|
458
|
+
sem_eval = result_json.get("semantic_Evaluation") or result_json.get("semantic_evaluation") or {}
|
|
459
|
+
audit_decision = sem_eval.get("recommended_action", "UNKNOWN")
|
|
460
|
+
risk_score = sem_eval.get("risk_score", 0.0)
|
|
461
|
+
summary = sem_eval.get("summary", "No summary provided")
|
|
462
|
+
flagged_issues = sem_eval.get("flagged_issues", [])
|
|
463
|
+
|
|
464
|
+
# Extract payment receipt
|
|
465
|
+
receipt = result_json.get("payment") or {}
|
|
466
|
+
receipt_payment_id = receipt.get("payment_id", "N/A")
|
|
467
|
+
receipt_payer = receipt.get("payer_address", "N/A")
|
|
468
|
+
receipt_pay_to = receipt.get("pay_to_address", "N/A")
|
|
469
|
+
receipt_usdc = receipt.get("amount_usdc", 0.0)
|
|
470
|
+
receipt_tx_hash = receipt.get("tx_hash", "N/A")
|
|
471
|
+
settled_at = receipt.get("settled_at", "N/A")
|
|
472
|
+
|
|
473
|
+
print(" --- Audit Decision Outcome ---")
|
|
474
|
+
print(f" Policy Action : {audit_decision}")
|
|
475
|
+
print(f" Calculated Risk Score: {risk_score:.1f} / 10.0")
|
|
476
|
+
print(f" Auditor Summary : {summary}")
|
|
477
|
+
if flagged_issues:
|
|
478
|
+
print(" Flagged Violations :")
|
|
479
|
+
for issue in flagged_issues:
|
|
480
|
+
print(f" * {issue}")
|
|
481
|
+
|
|
482
|
+
print("\n --- Settled Payment Receipt ---")
|
|
483
|
+
print(f" Payment ID : {receipt_payment_id}")
|
|
484
|
+
print(f" Payer Agent : {receipt_payer}")
|
|
485
|
+
print(f" Merchant PayTo : {receipt_pay_to}")
|
|
486
|
+
print(f" Amount Settled : ${receipt_usdc:.4f} USDC")
|
|
487
|
+
print(f" Settlement Tx Hash : {receipt_tx_hash}")
|
|
488
|
+
print(f" Settled Timestamp : {settled_at}")
|
|
489
|
+
if receipt_tx_hash and receipt_tx_hash != "N/A" and (live_onchain or receipt_tx_hash.startswith("0x")):
|
|
490
|
+
print(f" Verify on Basescan : https://sepolia.basescan.org/tx/{receipt_tx_hash}")
|
|
491
|
+
|
|
492
|
+
# Check response header receipt
|
|
493
|
+
header_receipt = resp_200.headers.get("X-PAYMENT-RESPONSE") or resp_200.headers.get("PAYMENT-RESPONSE")
|
|
494
|
+
if header_receipt:
|
|
495
|
+
print(f" Header Receipt : {header_receipt}")
|
|
496
|
+
|
|
497
|
+
# ---------------------------------------------------------------------
|
|
498
|
+
# Step 7: Verify SQLite Persistence (GET /payments & GET /metrics/summary)
|
|
499
|
+
# ---------------------------------------------------------------------
|
|
500
|
+
print_banner("[Step 7] Verify SQLite Persistence & Revenue Metrics")
|
|
501
|
+
p_resp = await client.get("/payments", params={"limit": 5})
|
|
502
|
+
assert p_resp.status_code == 200, f"Failed GET /payments: {p_resp.status_code}"
|
|
503
|
+
payments_list = p_resp.json()
|
|
504
|
+
|
|
505
|
+
matching_payment = next(
|
|
506
|
+
(p for p in payments_list if p.get("payment_id") == payment_id), None
|
|
507
|
+
)
|
|
508
|
+
print(f" GET /payments Status : HTTP 200 OK (Found {len(payments_list)} payment records)")
|
|
509
|
+
if matching_payment:
|
|
510
|
+
print(f" Confirmed in Ledger : payment_id={matching_payment['payment_id']}")
|
|
511
|
+
print(f" Ledger Tx Hash : {matching_payment.get('tx_hash')}")
|
|
512
|
+
else:
|
|
513
|
+
print(" Payment registered in global operational ledger.")
|
|
514
|
+
|
|
515
|
+
m_resp = await client.get("/metrics/summary")
|
|
516
|
+
assert m_resp.status_code == 200, f"Failed GET /metrics/summary: {m_resp.status_code}"
|
|
517
|
+
summary_metrics = m_resp.json()
|
|
518
|
+
|
|
519
|
+
print(f" Total Evaluations : {summary_metrics.get('total_evaluations', 0)}")
|
|
520
|
+
print(f" Payments Settled : {summary_metrics.get('total_payments_settled', 0)}")
|
|
521
|
+
print(f" Total Settled Revenue: ${summary_metrics.get('total_revenue_usdc', 0.0):.4f} USDC")
|
|
522
|
+
print(f" Net Commercial Profit: ${summary_metrics.get('net_profit_usd', 0.0):.4f} USD")
|
|
523
|
+
|
|
524
|
+
# ---------------------------------------------------------------------
|
|
525
|
+
# Step 8: Print src.report Operational Metrics Table
|
|
526
|
+
# ---------------------------------------------------------------------
|
|
527
|
+
print_banner("[Step 8] Operational Ledger Report (src.report)")
|
|
528
|
+
report_table = format_report_text(summary_metrics)
|
|
529
|
+
print(report_table)
|
|
530
|
+
|
|
531
|
+
print("\n[SUCCESS] x402 Agent-to-Agent Payment Lifecycle Completed Successfully!")
|
|
532
|
+
|
|
533
|
+
finally:
|
|
534
|
+
# Cleanup client and in-process resources
|
|
535
|
+
await client.aclose()
|
|
536
|
+
if app_instance is not None and hasattr(app_instance.state, "worker_pool"):
|
|
537
|
+
try:
|
|
538
|
+
await app_instance.state.worker_pool.shutdown()
|
|
539
|
+
except Exception:
|
|
540
|
+
pass
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def main() -> None:
|
|
544
|
+
parser = argparse.ArgumentParser(
|
|
545
|
+
description="x402 Agent-to-Agent (A2A) Client Demonstration Script"
|
|
546
|
+
)
|
|
547
|
+
parser.add_argument(
|
|
548
|
+
"--url",
|
|
549
|
+
type=str,
|
|
550
|
+
default="http://127.0.0.1:8000",
|
|
551
|
+
help="Target Web3 Condition-Action Trigger Agent API base URL (default: http://127.0.0.1:8000)",
|
|
552
|
+
)
|
|
553
|
+
parser.add_argument(
|
|
554
|
+
"--contract",
|
|
555
|
+
type=str,
|
|
556
|
+
default=DEFAULT_TARGET_CONTRACT,
|
|
557
|
+
help=f"Target EVM contract address on Base Sepolia (default: {DEFAULT_TARGET_CONTRACT})",
|
|
558
|
+
)
|
|
559
|
+
parser.add_argument(
|
|
560
|
+
"--live-onchain",
|
|
561
|
+
action="store_true",
|
|
562
|
+
default=False,
|
|
563
|
+
help="Use funded buyer wallet from scripts/.buyer_wallet.json and settle real gasless USDC on Base Sepolia via x402 facilitator",
|
|
564
|
+
)
|
|
565
|
+
parser.add_argument(
|
|
566
|
+
"--fetch-live-tx",
|
|
567
|
+
action="store_true",
|
|
568
|
+
default=False,
|
|
569
|
+
help="Capture a real recently-mined contract transaction from Base Sepolia to audit",
|
|
570
|
+
)
|
|
571
|
+
args = parser.parse_args()
|
|
572
|
+
|
|
573
|
+
asyncio.run(
|
|
574
|
+
run_x402_client_lifecycle(
|
|
575
|
+
server_url=args.url,
|
|
576
|
+
target_contract=args.contract,
|
|
577
|
+
live_onchain=args.live_onchain,
|
|
578
|
+
fetch_live_tx=args.fetch_live_tx,
|
|
579
|
+
)
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
if __name__ == "__main__":
|
|
584
|
+
main()
|