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.
@@ -0,0 +1,201 @@
1
+ """
2
+ Governance Listener and Autonomous Security Scanner.
3
+
4
+ Polls DAO proposals from Snapshot or loads curated proposals, executes two-stage
5
+ deterministic bytecode and semantic LLM audits, displays an ASCII audit table,
6
+ and prints cumulative operational and financial metrics.
7
+
8
+ Usage:
9
+ python scripts/governance_listener.py --curated
10
+ python scripts/governance_listener.py --limit 3
11
+ """
12
+
13
+ import argparse
14
+ import asyncio
15
+ import logging
16
+ import os
17
+ import sys
18
+ from typing import List, Optional
19
+
20
+ if "pytest" not in sys.modules:
21
+ try:
22
+ import dotenv
23
+ dotenv.load_dotenv(override=False)
24
+ except ImportError:
25
+ pass
26
+
27
+ # Ensure module search paths support running directly or as a package
28
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
29
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
30
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
31
+ for _p in (_ROOT_DIR, _SRC_DIR):
32
+ if _p not in sys.path:
33
+ sys.path.insert(0, _p)
34
+
35
+ try:
36
+ from src.schemas import ChainId
37
+ from src.engine import ConditionAgentEngine
38
+ from src.semantic_evaluator import MockSemanticEvaluator
39
+ from src.governance_connector import (
40
+ SnapshotGovernanceConnector,
41
+ GovernanceProposal,
42
+ GovernanceAuditReport,
43
+ WebhookAlertDispatcher,
44
+ get_curated_dao_proposals,
45
+ )
46
+ from src.report import generate_report, format_report_text
47
+ except ImportError:
48
+ from schemas import ChainId
49
+ from engine import ConditionAgentEngine
50
+ from semantic_evaluator import MockSemanticEvaluator
51
+ from governance_connector import (
52
+ SnapshotGovernanceConnector,
53
+ GovernanceProposal,
54
+ GovernanceAuditReport,
55
+ WebhookAlertDispatcher,
56
+ get_curated_dao_proposals,
57
+ )
58
+ from report import generate_report, format_report_text
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+
63
+ def print_audit_table(reports: List[GovernanceAuditReport]) -> None:
64
+ """
65
+ Renders an ASCII table of audited proposals displaying ID, space, alert level,
66
+ decision, risk score, token usage, and USD evaluation cost.
67
+ """
68
+ headers = ["Proposal ID", "Space", "Alert Level", "Decision", "Score", "Tokens", "Cost USD"]
69
+ rows = []
70
+ for r in reports:
71
+ prop_id = r.proposal.proposal_id[:16]
72
+ space = r.proposal.space_id[:22]
73
+ alert = r.alert_level
74
+ sem = r.agent_response.semantic_Evaluation
75
+ decision = sem.recommended_action if sem else "SKIPPED"
76
+ score = f"{sem.risk_score:.1f}" if sem else "N/A"
77
+ tokens = str(sem.input_tokens + sem.output_tokens) if sem else "0"
78
+ cost = f"${sem.estimated_cost_usd:.6f}" if sem else "$0.000000"
79
+ rows.append([prop_id, space, alert, decision, score, tokens, cost])
80
+
81
+ col_widths = [len(h) for h in headers]
82
+ for row in rows:
83
+ for idx, val in enumerate(row):
84
+ col_widths[idx] = max(col_widths[idx], len(val))
85
+
86
+ separator = "+" + "+".join("-" * (w + 2) for w in col_widths) + "+"
87
+ header_str = "|" + "|".join(f" {headers[i].ljust(col_widths[i])} " for i in range(len(headers))) + "|"
88
+
89
+ print("\n" + separator)
90
+ print(header_str)
91
+ print(separator)
92
+ for row in rows:
93
+ row_str = "|" + "|".join(f" {row[i].ljust(col_widths[i])} " for i in range(len(row))) + "|"
94
+ print(row_str)
95
+ print(separator + "\n")
96
+
97
+
98
+ async def run_listener(
99
+ limit: int = 3,
100
+ curated: bool = False,
101
+ spaces: Optional[List[str]] = None,
102
+ webhook_url: Optional[str] = None,
103
+ public_api_url: Optional[str] = None,
104
+ min_alert_level: str = "WARNING",
105
+ ) -> int:
106
+ """
107
+ Executes governance listener scan on Base Sepolia.
108
+ """
109
+ print(f"[*] Initializing ConditionAgentEngine on Base Sepolia (curated={curated}, limit={limit})...")
110
+ if curated:
111
+ evaluator = MockSemanticEvaluator()
112
+ engine = ConditionAgentEngine(semantic_evaluator=evaluator)
113
+ else:
114
+ engine = ConditionAgentEngine()
115
+ connector = SnapshotGovernanceConnector(default_chain_id=ChainId.BASE_SEPOLIA)
116
+
117
+ if curated:
118
+ print("[*] Loading deterministic curated DAO proposals...")
119
+ proposals = get_curated_dao_proposals(default_chain_id=ChainId.BASE_SEPOLIA, limit=limit)
120
+ reports = await connector.audit_proposals(engine=engine, proposals=proposals)
121
+ else:
122
+ target_spaces = spaces or connector.DEFAULT_SPACES
123
+ print(f"[*] Polling Snapshot proposals for spaces: {', '.join(target_spaces)}...")
124
+ reports = await connector.audit_proposals(engine=engine, spaces=target_spaces, limit=limit)
125
+
126
+ print(f"[+] Successfully audited {len(reports)} proposals.")
127
+ print_audit_table(reports)
128
+
129
+ active_webhook = webhook_url or os.getenv("ALERT_WEBHOOK_URL")
130
+ if active_webhook:
131
+ dispatcher = WebhookAlertDispatcher(webhook_url=active_webhook, public_api_url=public_api_url)
132
+ sent_count = await dispatcher.dispatch_batch(reports, min_alert_level=min_alert_level)
133
+ print(f"[+] Dispatched {sent_count} webhook alert(s) (min_level={min_alert_level}).")
134
+
135
+ print("=" * 60)
136
+ print("OPERATIONAL & FINANCIAL LEDGER METRICS")
137
+ print("=" * 60)
138
+ metrics = await generate_report(db_path=engine.storage.db_path)
139
+ print(format_report_text(metrics))
140
+
141
+ return 0
142
+
143
+
144
+ def main() -> None:
145
+ parser = argparse.ArgumentParser(
146
+ description="Autonomous DAO Governance Listener & Security Scanner"
147
+ )
148
+ parser.add_argument(
149
+ "--limit",
150
+ type=int,
151
+ default=3,
152
+ help="Maximum number of proposals to inspect (default: 3)",
153
+ )
154
+ parser.add_argument(
155
+ "--curated",
156
+ action="store_true",
157
+ default=False,
158
+ help="Use deterministic curated DAO test proposals",
159
+ )
160
+ parser.add_argument(
161
+ "--space",
162
+ action="append",
163
+ dest="spaces",
164
+ help="Snapshot space identifier (e.g. 'arbitrumfoundation.eth'). Can be specified multiple times.",
165
+ )
166
+ parser.add_argument(
167
+ "--webhook-url",
168
+ type=str,
169
+ default=None,
170
+ help="Optional Discord/Slack/HTTP webhook URL for threat notifications",
171
+ )
172
+ parser.add_argument(
173
+ "--public-url",
174
+ type=str,
175
+ default=None,
176
+ help="Public API base URL included in x402 alert links",
177
+ )
178
+ parser.add_argument(
179
+ "--min-alert-level",
180
+ type=str,
181
+ default="WARNING",
182
+ choices=["INFO", "WARNING", "CRITICAL"],
183
+ help="Minimum alert severity to trigger webhook dispatch (default: WARNING)",
184
+ )
185
+
186
+ args = parser.parse_args()
187
+ exit_code = asyncio.run(
188
+ run_listener(
189
+ limit=args.limit,
190
+ curated=args.curated,
191
+ spaces=args.spaces,
192
+ webhook_url=args.webhook_url,
193
+ public_api_url=args.public_url,
194
+ min_alert_level=args.min_alert_level,
195
+ )
196
+ )
197
+ sys.exit(exit_code)
198
+
199
+
200
+ if __name__ == "__main__":
201
+ main()
@@ -0,0 +1,297 @@
1
+ """
2
+ ERC-8004 ("Trustless Agents") On-Chain Identity Manifest & Calldata Generator.
3
+
4
+ Generates, validates, and ABI-encodes the ERC-8004 registration manifest
5
+ (`https://eips.ethereum.org/EIPS/eip-8004#registration-v1`) for indexing the
6
+ Web3 Systemic Agent on Base Mainnet (`8004scan.io` / `8004agents.ai`), including
7
+ A2A, MCP streamable-http, x402 discovery, and REST security endpoints.
8
+
9
+ Also encodes the manifest as a self-contained `data:application/json;base64,...`
10
+ `agentURI` and generates the exact ABI calldata (`0xf2c298be` = `register(string)`)
11
+ ready for submission to an ERC-8004 Identity Registry contract.
12
+
13
+ Usage Examples:
14
+ # 1. Dry-run generation, validation, and calldata inspection:
15
+ python scripts/register_erc8004_agent.py --dry-run
16
+
17
+ # 2. Custom public URL and payout wallet saved to JSON file:
18
+ python scripts/register_erc8004_agent.py \\
19
+ --public-url https://web3-systemic-agent.onrender.com \\
20
+ --pay-to 0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63 \\
21
+ --output erc8004-registration.json
22
+ """
23
+
24
+ import argparse
25
+ import base64
26
+ import json
27
+ import os
28
+ import sys
29
+ from typing import Any, Dict, List, Optional
30
+
31
+ from web3 import Web3
32
+
33
+ # Guarded dotenv loading: skipped during pytest execution or if python-dotenv not installed
34
+ if "pytest" not in sys.modules:
35
+ try:
36
+ import dotenv
37
+ _CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
38
+ _PARENT_ROOT = os.path.abspath(os.path.join(_CURRENT_SCRIPT_DIR, ".."))
39
+ _env_file = os.path.join(_PARENT_ROOT, ".env")
40
+ if os.path.exists(_env_file):
41
+ dotenv.load_dotenv(_env_file, override=False)
42
+ dotenv.load_dotenv(override=False)
43
+ except ImportError:
44
+ pass
45
+
46
+ DEFAULT_PUBLIC_URL = "https://web3-systemic-agent.onrender.com"
47
+ DEFAULT_PAY_TO_ADDRESS = "0x2b7F1fd931f7f28f89e0f688Dd5Bb7a620c24b63"
48
+ ERC8004_TYPE_URI = "https://eips.ethereum.org/EIPS/eip-8004#registration-v1"
49
+ REGISTER_SELECTOR = "0xf2c298be" # keccak256("register(string)")[:4]
50
+
51
+
52
+ def build_erc8004_registration_json(
53
+ public_url: str,
54
+ pay_to_address: str,
55
+ version: str = "1.0.2",
56
+ ) -> Dict[str, Any]:
57
+ """
58
+ Builds a canonical ERC-8004 ("Trustless Agents") registration JSON manifest
59
+ describing the agent's A2A, MCP, x402, and REST endpoints on Base Mainnet.
60
+ """
61
+ base_url = str(public_url or "").strip().rstrip("/")
62
+ if not base_url.startswith(("https://", "http://")):
63
+ raise ValueError(f"Invalid public_url '{public_url}': must start with http:// or https://")
64
+
65
+ if not pay_to_address or not Web3.is_address(pay_to_address):
66
+ raise ValueError(f"Invalid pay_to_address '{pay_to_address}': expected valid EVM address")
67
+ checksum_pay_to = Web3.to_checksum_address(pay_to_address)
68
+
69
+ return {
70
+ "type": ERC8004_TYPE_URI,
71
+ "name": "Web3 Systemic Agent",
72
+ "description": (
73
+ "Autonomous Web3 Security & Governance Auditor with a Two-Stage Hybrid Pipeline "
74
+ "(deterministic on-chain bytecode/proxy/preflight gatekeeping + Gemini LLM semantic "
75
+ "audits) monetized via gasless x402 EIP-3009 USDC micropayments on Base."
76
+ ),
77
+ "version": str(version),
78
+ "image": f"{base_url}/icon.svg",
79
+ "active": True,
80
+ "endpoints": [
81
+ {
82
+ "name": "A2A",
83
+ "endpoint": f"{base_url}/.well-known/agent-card.json",
84
+ "version": "0.3.0",
85
+ },
86
+ {
87
+ "name": "MCP",
88
+ "endpoint": f"{base_url}/mcp",
89
+ "transport": "streamable-http",
90
+ "version": "2024-11-05",
91
+ },
92
+ {
93
+ "name": "x402",
94
+ "endpoint": f"{base_url}/.well-known/x402",
95
+ "version": "2.0",
96
+ },
97
+ {
98
+ "name": "REST-token-check",
99
+ "endpoint": f"{base_url}/token/check",
100
+ "methods": ["GET", "POST"],
101
+ "price_usdc": "0.005",
102
+ },
103
+ {
104
+ "name": "REST-preflight",
105
+ "endpoint": f"{base_url}/preflight",
106
+ "methods": ["GET", "POST"],
107
+ "price_usdc": "0.01",
108
+ },
109
+ {
110
+ "name": "REST-audit",
111
+ "endpoint": f"{base_url}/audit",
112
+ "methods": ["GET", "POST"],
113
+ "price_usdc": "0.015",
114
+ },
115
+ {
116
+ "name": "REST-evaluate",
117
+ "endpoint": f"{base_url}/evaluate",
118
+ "methods": ["GET", "POST"],
119
+ "price_usdc": "0.015",
120
+ },
121
+ {
122
+ "name": "REST-audit-deep",
123
+ "endpoint": f"{base_url}/audit/deep",
124
+ "methods": ["GET", "POST"],
125
+ "price_usdc": "0.25",
126
+ },
127
+ {
128
+ "name": "REST-feed-recent",
129
+ "endpoint": f"{base_url}/feed/recent",
130
+ "methods": ["GET"],
131
+ "price_usdc": "0",
132
+ },
133
+ ],
134
+ "registrations": [],
135
+ "supportedTrust": ["reputation"],
136
+ "x402Support": True,
137
+ "paymentWallet": checksum_pay_to,
138
+ }
139
+
140
+
141
+ def validate_erc8004_registration_json(reg_json: Dict[str, Any]) -> None:
142
+ """Validates required ERC-8004 registration fields, endpoint URLs, and payout wallet."""
143
+ required_keys = (
144
+ "type",
145
+ "name",
146
+ "description",
147
+ "image",
148
+ "endpoints",
149
+ "registrations",
150
+ "supportedTrust",
151
+ "x402Support",
152
+ "paymentWallet",
153
+ )
154
+ for key in required_keys:
155
+ if key not in reg_json:
156
+ raise ValueError(f"Missing required ERC-8004 field: '{key}'")
157
+
158
+ if reg_json["type"] != ERC8004_TYPE_URI:
159
+ raise ValueError(f"Unexpected ERC-8004 type: {reg_json['type']}")
160
+ if not isinstance(reg_json["endpoints"], list) or len(reg_json["endpoints"]) < 3:
161
+ raise ValueError("ERC-8004 'endpoints' must be a non-empty list of endpoint definitions")
162
+ if not isinstance(reg_json["registrations"], list):
163
+ raise ValueError("ERC-8004 'registrations' must be a list")
164
+ if not isinstance(reg_json["supportedTrust"], list) or not reg_json["supportedTrust"]:
165
+ raise ValueError("ERC-8004 'supportedTrust' must be a non-empty list")
166
+ if not isinstance(reg_json["x402Support"], bool):
167
+ raise ValueError("ERC-8004 'x402Support' must be a boolean")
168
+
169
+ wallet = reg_json["paymentWallet"]
170
+ if not isinstance(wallet, str) or not Web3.is_address(wallet):
171
+ raise ValueError(f"Invalid ERC-8004 paymentWallet: {wallet}")
172
+ if wallet != Web3.to_checksum_address(wallet):
173
+ raise ValueError("ERC-8004 paymentWallet must be EIP-55 checksummed")
174
+
175
+ endpoint_urls = [str(ep.get("endpoint", "")) for ep in reg_json["endpoints"] if isinstance(ep, dict)]
176
+ required_suffixes = (
177
+ "/.well-known/agent-card.json",
178
+ "/mcp",
179
+ "/.well-known/x402",
180
+ "/token/check",
181
+ "/preflight",
182
+ "/audit",
183
+ "/evaluate",
184
+ "/audit/deep",
185
+ "/feed/recent",
186
+ )
187
+ for suffix in required_suffixes:
188
+ if not any(url.endswith(suffix) for url in endpoint_urls):
189
+ raise ValueError(f"Missing required endpoint ending with '{suffix}'")
190
+
191
+
192
+ def encode_agent_uri_data(reg_json: Dict[str, Any]) -> str:
193
+ """
194
+ Encodes the ERC-8004 registration JSON as a `data:application/json;base64,...` URI
195
+ ready to pass into `register(string agentURI)`.
196
+ """
197
+ compact_json = json.dumps(reg_json, separators=(",", ":"), ensure_ascii=False)
198
+ b64_bytes = base64.b64encode(compact_json.encode("utf-8"))
199
+ return f"data:application/json;base64,{b64_bytes.decode('ascii')}"
200
+
201
+
202
+ def encode_register_calldata(agent_uri: str) -> str:
203
+ """
204
+ ABI-encodes `register(string agentURI)` using selector `0xf2c298be`
205
+ (`keccak256("register(string)")[:4]`).
206
+ """
207
+ uri_bytes = agent_uri.encode("utf-8")
208
+ offset_word = (32).to_bytes(32, "big")
209
+ length_word = len(uri_bytes).to_bytes(32, "big")
210
+ pad_len = (32 - (len(uri_bytes) % 32)) % 32
211
+ padded_uri = uri_bytes + (b"\x00" * pad_len)
212
+ payload_bytes = offset_word + length_word + padded_uri
213
+ return f"{REGISTER_SELECTOR}{payload_bytes.hex()}"
214
+
215
+
216
+ def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
217
+ """Parses CLI arguments for scripts/register_erc8004_agent.py."""
218
+ parser = argparse.ArgumentParser(
219
+ description="Generate and validate ERC-8004 Trustless Agent registration manifest & calldata."
220
+ )
221
+ parser.add_argument(
222
+ "--dry-run",
223
+ action="store_true",
224
+ default=False,
225
+ help="Generate, validate, and print ERC-8004 manifest summary without broadcasting on-chain",
226
+ )
227
+ parser.add_argument(
228
+ "--public-url",
229
+ type=str,
230
+ default=os.getenv("PUBLIC_API_URL") or DEFAULT_PUBLIC_URL,
231
+ help=f"Public agent HTTPS base URL (default: {DEFAULT_PUBLIC_URL})",
232
+ )
233
+ parser.add_argument(
234
+ "--pay-to",
235
+ type=str,
236
+ default=os.getenv("PAY_TO_ADDRESS") or DEFAULT_PAY_TO_ADDRESS,
237
+ help=f"Agent x402 recipient wallet address (default: {DEFAULT_PAY_TO_ADDRESS})",
238
+ )
239
+ parser.add_argument(
240
+ "--version",
241
+ type=str,
242
+ default="1.0.2",
243
+ help="Agent semantic version string (default: 1.0.2)",
244
+ )
245
+ parser.add_argument(
246
+ "--output",
247
+ type=str,
248
+ default=None,
249
+ help="Optional output file path to write the formatted ERC-8004 JSON manifest",
250
+ )
251
+ return parser.parse_args(args)
252
+
253
+
254
+ def main() -> int:
255
+ """CLI entrypoint."""
256
+ args = parse_args()
257
+ reg_json = build_erc8004_registration_json(
258
+ public_url=args.public_url,
259
+ pay_to_address=args.pay_to,
260
+ version=args.version,
261
+ )
262
+ validate_erc8004_registration_json(reg_json)
263
+
264
+ agent_uri = encode_agent_uri_data(reg_json)
265
+ calldata = encode_register_calldata(agent_uri)
266
+
267
+ print("=" * 72)
268
+ print("Web3 Systemic Agent: ERC-8004 Registration Manifest")
269
+ print("=" * 72)
270
+ print(f"[*] Mode : {'DRY-RUN (Validation & Encoding)' if args.dry_run else 'GENERATE'}")
271
+ print(f"[*] Type : {reg_json['type']}")
272
+ print(f"[*] Name : {reg_json['name']} (v{reg_json['version']})")
273
+ print(f"[*] Public URL : {args.public_url.rstrip('/')}")
274
+ print(f"[*] Payment Wallet: {reg_json['paymentWallet']}")
275
+ print(f"[*] x402 Support : {reg_json['x402Support']} | Trust: {', '.join(reg_json['supportedTrust'])}")
276
+ print(f"[*] Endpoints : {len(reg_json['endpoints'])} registered")
277
+ for ep in reg_json["endpoints"]:
278
+ print(f" - {ep['name']:18s} -> {ep['endpoint']}")
279
+ print(f"[*] agentURI len : {len(agent_uri)} chars (data:application/json;base64,...)")
280
+ print(f"[*] Calldata sel : {REGISTER_SELECTOR} (register(string))")
281
+ print(f"[*] Calldata hex : {calldata[:74]}... ({len(calldata)} chars)")
282
+
283
+ if args.output:
284
+ out_dir = os.path.dirname(os.path.abspath(args.output))
285
+ if out_dir:
286
+ os.makedirs(out_dir, exist_ok=True)
287
+ with open(args.output, "w", encoding="utf-8") as fh:
288
+ json.dump(reg_json, fh, indent=2, ensure_ascii=False)
289
+ fh.write("\n")
290
+ print(f"[*] Saved ERC-8004 manifest JSON to: {args.output}")
291
+
292
+ print("[*] ERC-8004 validation PASSED.")
293
+ return 0
294
+
295
+
296
+ if __name__ == "__main__":
297
+ sys.exit(main())
@@ -0,0 +1,193 @@
1
+ """
2
+ Utility Script: Setup & Inspect Persistent Buyer Wallet for Base Sepolia.
3
+
4
+ Generates or loads a persistent buyer testnet keypair stored in
5
+ `scripts/.buyer_wallet.json`, connects to the Base Sepolia testnet,
6
+ queries both ETH and native USDC balances, and provides funding instructions
7
+ for the Circle USDC Faucet and Base Sepolia ETH faucets.
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import sys
13
+ from typing import Dict, Any
14
+
15
+ # Ensure UTF-8 output across standard streams
16
+ if hasattr(sys.stdout, "reconfigure"):
17
+ try:
18
+ sys.stdout.reconfigure(encoding="utf-8")
19
+ except Exception:
20
+ pass
21
+
22
+ # Configure root directory and environment
23
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
24
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
25
+ if _ROOT_DIR not in sys.path:
26
+ sys.path.insert(0, _ROOT_DIR)
27
+
28
+ from eth_account import Account
29
+ from web3 import Web3
30
+
31
+ # Base Sepolia Configuration Constants
32
+ DEFAULT_RPC = "https://sepolia.base.org"
33
+ BASE_SEPOLIA_CHAIN_ID = 84532
34
+ USDC_CONTRACT_ADDRESS = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
35
+ WALLET_FILE = os.path.join(_CURRENT_DIR, ".buyer_wallet.json")
36
+
37
+ # Minimal ERC-20 ABI for querying balanceOf
38
+ USDC_ABI = [
39
+ {
40
+ "constant": True,
41
+ "inputs": [{"name": "_owner", "type": "address"}],
42
+ "name": "balanceOf",
43
+ "outputs": [{"name": "balance", "type": "uint256"}],
44
+ "type": "function",
45
+ }
46
+ ]
47
+
48
+
49
+ def load_env_if_present() -> None:
50
+ """Loads root .env variables if present without polluting during test import."""
51
+ try:
52
+ import dotenv
53
+ env_path = os.path.join(_ROOT_DIR, ".env")
54
+ if os.path.exists(env_path):
55
+ dotenv.load_dotenv(env_path, override=False)
56
+ except Exception:
57
+ pass
58
+
59
+
60
+ def load_or_create_buyer_wallet(wallet_path: str = WALLET_FILE) -> Dict[str, str]:
61
+ """
62
+ Loads an existing buyer keypair from wallet_path or generates a new one.
63
+
64
+ Returns:
65
+ dict: Containing 'address' (checksummed) and 'private_key' (hex string).
66
+ """
67
+ if os.path.exists(wallet_path):
68
+ try:
69
+ with open(wallet_path, "r", encoding="utf-8") as f:
70
+ data = json.load(f)
71
+ address = data.get("address")
72
+ private_key = data.get("private_key")
73
+ if address and private_key:
74
+ # Validate keypair consistency
75
+ account = Account.from_key(private_key)
76
+ checksum_address = Web3.to_checksum_address(account.address)
77
+ return {
78
+ "address": checksum_address,
79
+ "private_key": private_key,
80
+ "created": False,
81
+ }
82
+ except Exception as e:
83
+ print(f"[!] Warning reading existing wallet file ({e}). Generating new wallet.")
84
+
85
+ # Generate new keypair
86
+ account = Account.create()
87
+ raw_key = account.key.hex()
88
+ private_key = raw_key if raw_key.startswith("0x") else f"0x{raw_key}"
89
+ wallet_data = {
90
+ "address": Web3.to_checksum_address(account.address),
91
+ "private_key": private_key,
92
+ }
93
+
94
+ with open(wallet_path, "w", encoding="utf-8") as f:
95
+ json.dump(wallet_data, f, indent=2)
96
+
97
+ wallet_data["created"] = True
98
+ return wallet_data
99
+
100
+
101
+ def inspect_buyer_balances(address: str, rpc_url: str = None) -> Dict[str, Any]:
102
+ """
103
+ Connects to Base Sepolia RPC and retrieves ETH and native USDC balances.
104
+
105
+ Args:
106
+ address: EVM address to inspect.
107
+ rpc_url: Optional RPC endpoint; defaults to BASE_SEPOLIA_RPC env or DEFAULT_RPC.
108
+
109
+ Returns:
110
+ dict: Balances and network status.
111
+ """
112
+ effective_rpc = rpc_url or os.getenv("BASE_SEPOLIA_RPC", DEFAULT_RPC)
113
+ w3 = Web3(Web3.HTTPProvider(effective_rpc))
114
+ if not w3.is_connected():
115
+ return {
116
+ "connected": False,
117
+ "error": f"Failed to connect to Base Sepolia RPC at {effective_rpc}",
118
+ }
119
+
120
+ checksum_addr = Web3.to_checksum_address(address)
121
+ usdc_addr = Web3.to_checksum_address(USDC_CONTRACT_ADDRESS)
122
+
123
+ # 1. Inspect ETH Balance
124
+ eth_balance_wei = w3.eth.get_balance(checksum_addr)
125
+ eth_balance = float(w3.from_wei(eth_balance_wei, "ether"))
126
+
127
+ # 2. Inspect USDC Balance (6 decimals)
128
+ contract = w3.eth.contract(address=usdc_addr, abi=USDC_ABI)
129
+ usdc_units = contract.functions.balanceOf(checksum_addr).call()
130
+ usdc_balance = usdc_units / 1_000_000.0
131
+
132
+ return {
133
+ "connected": True,
134
+ "chain_id": w3.eth.chain_id,
135
+ "block_number": w3.eth.block_number,
136
+ "eth_balance_wei": eth_balance_wei,
137
+ "eth_balance": eth_balance,
138
+ "usdc_units": usdc_units,
139
+ "usdc_balance": usdc_balance,
140
+ }
141
+
142
+
143
+ def main() -> None:
144
+ """Main execution flow for buyer wallet setup and inspection."""
145
+ load_env_if_present()
146
+ rpc_url = os.getenv("BASE_SEPOLIA_RPC", DEFAULT_RPC)
147
+
148
+ width = 74
149
+ print("=" * width)
150
+ print(" Web3 Buyer Agent Wallet Setup & Inspection (Base Sepolia)")
151
+ print("=" * width)
152
+
153
+ wallet_info = load_or_create_buyer_wallet()
154
+ address = wallet_info["address"]
155
+ was_created = wallet_info.get("created", False)
156
+
157
+ if was_created:
158
+ print(f"[+] Created new buyer wallet keypair.")
159
+ else:
160
+ print(f"[*] Loaded existing buyer wallet keypair.")
161
+
162
+ print(f" File: {WALLET_FILE}")
163
+ print(f" Address: {address}")
164
+ print("-" * width)
165
+
166
+ print(f"[*] Connecting to Base Sepolia RPC ({rpc_url})...")
167
+ status = inspect_buyer_balances(address, rpc_url=rpc_url)
168
+
169
+ if not status.get("connected"):
170
+ print(f"[!] Error: {status.get('error')}")
171
+ return
172
+
173
+ print(f"[+] Connected to Base Sepolia (Chain ID: {status['chain_id']}, Block: {status['block_number']})")
174
+ print(f" - ETH Balance: {status['eth_balance']:.6f} ETH ({status['eth_balance_wei']} wei)")
175
+ print(f" - USDC Balance: {status['usdc_balance']:.4f} USDC ({status['usdc_units']} atomic units)")
176
+ print("-" * width)
177
+
178
+ print("Funding Instructions for Circle Faucet & Gas:")
179
+ print(" 1. Circle USDC Faucet (Free Base Sepolia USDC):")
180
+ print(" URL: https://faucet.circle.com/")
181
+ print(" Network: Select 'Base Sepolia'")
182
+ print(" Token: Select 'USDC'")
183
+ print(f" Address: {address}")
184
+ print()
185
+ print(" 2. Base Sepolia Gas Faucets (Free Testnet ETH for transaction fees):")
186
+ print(" - Chainlink: https://faucets.chain.link/base-sepolia")
187
+ print(" - Alchemy: https://www.alchemy.com/faucets/base-sepolia")
188
+ print(" - Superchain:https://superchainfaucet.com/base-sepolia")
189
+ print("=" * width)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()