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,887 @@
1
+ """
2
+ Autonomous On-Chain Block Scanner and Security Auditor for Base Mainnet.
3
+
4
+ Engine 1 of the Web3 Condition-Action Trigger Agent.
5
+ Scans newly produced EVM blocks on Base Mainnet (Chain ID 8453) in real-time or batch mode,
6
+ detects smart contract deployments (tx.to is None), extracts deployed bytecode and 4-byte
7
+ function selectors, executes deterministic and semantic risk audits, displays an ASCII table,
8
+ and persists audit reports to the SQLite ledger (AgentStorage).
9
+
10
+ Usage Examples:
11
+ # 1. Run dry-run simulation (offline, zero external network dependency, cost zero):
12
+ python scripts/block_contract_scanner.py --dry-run
13
+
14
+ # 2. Scan the last 10 blocks on Base Mainnet with a limit of 5 contracts:
15
+ python scripts/block_contract_scanner.py --blocks 10 --limit 5
16
+
17
+ # 3. Run continuous monitoring loop polling every ~2 seconds:
18
+ python scripts/block_contract_scanner.py --continuous
19
+
20
+ # 4. Custom RPC endpoint override:
21
+ python scripts/block_contract_scanner.py --rpc-url https://mainnet.base.org --blocks 20
22
+ """
23
+
24
+ import argparse
25
+ import asyncio
26
+ import inspect
27
+ import logging
28
+ import os
29
+ import re
30
+ import sys
31
+ import time
32
+ from typing import Dict, Any, Optional, List, Union
33
+ from unittest.mock import AsyncMock, MagicMock
34
+
35
+ # Guarded dotenv loading: skipped during pytest execution or if python-dotenv not installed
36
+ if "pytest" not in sys.modules:
37
+ try:
38
+ import dotenv
39
+ _CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
40
+ _PARENT_ROOT = os.path.abspath(os.path.join(_CURRENT_SCRIPT_DIR, ".."))
41
+ _env_file = os.path.join(_PARENT_ROOT, ".env")
42
+ if os.path.exists(_env_file):
43
+ dotenv.load_dotenv(_env_file, override=False)
44
+ dotenv.load_dotenv(override=False)
45
+ except ImportError:
46
+ pass
47
+
48
+ # Ensure module search paths support running directly or as a package
49
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
50
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
51
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
52
+ for _p in (_ROOT_DIR, _SRC_DIR):
53
+ if _p not in sys.path:
54
+ sys.path.insert(0, _p)
55
+
56
+ from web3 import AsyncWeb3, AsyncHTTPProvider, Web3
57
+ from web3.exceptions import Web3Exception
58
+
59
+ try:
60
+ from src.schemas import (
61
+ ChainId,
62
+ ConditionRulePayload,
63
+ DeterministicCondition,
64
+ SemanticCondition,
65
+ FinalAgentResponse,
66
+ )
67
+ from src.chain_inspector import ChainInspector
68
+ from src.engine import ConditionAgentEngine
69
+ from src.semantic_evaluator import (
70
+ MockSemanticEvaluator,
71
+ get_semantic_evaluator,
72
+ )
73
+ from src.storage import AgentStorage
74
+ except ImportError:
75
+ from schemas import (
76
+ ChainId,
77
+ ConditionRulePayload,
78
+ DeterministicCondition,
79
+ SemanticCondition,
80
+ FinalAgentResponse,
81
+ )
82
+ from chain_inspector import ChainInspector
83
+ from engine import ConditionAgentEngine
84
+ from semantic_evaluator import (
85
+ MockSemanticEvaluator,
86
+ get_semantic_evaluator,
87
+ )
88
+ from storage import AgentStorage
89
+
90
+ logger = logging.getLogger("block_contract_scanner")
91
+
92
+ DEFAULT_BASE_RPC = "https://mainnet.base.org"
93
+ CHAIN_ID_BASE_MAINNET = 8453
94
+
95
+ # Known 4-byte EVM function selectors mapped to canonical signatures
96
+ KNOWN_SELECTORS: Dict[str, str] = {
97
+ # ERC-20 & ERC-721 Standards
98
+ "0xa9059cbb": "transfer(address,uint256)",
99
+ "0x095ea7b3": "approve(address,uint256)",
100
+ "0x23b872dd": "transferFrom(address,address,uint256)",
101
+ "0x70a08231": "balanceOf(address)",
102
+ "0x18160ddd": "totalSupply()",
103
+ "0x313ce567": "decimals()",
104
+ "0x06fdde03": "name()",
105
+ "0x95d89b41": "symbol()",
106
+ # Ownership & Privileged Access Control
107
+ "0xf2fde38b": "transferOwnership(address)",
108
+ "0x715018a6": "renounceOwnership()",
109
+ "0x8da5cb5b": "owner()",
110
+ # Minting & Burning
111
+ "0x40c10f19": "mint(address,uint256)",
112
+ "0xa0712d68": "mint(uint256)",
113
+ "0x42966c68": "burn(uint256)",
114
+ "0x79cc6790": "burnFrom(address,uint256)",
115
+ # Upgradability & Proxies
116
+ "0x3659cfe6": "upgradeTo(address)",
117
+ "0x4f1ef286": "upgradeToAndCall(address,bytes)",
118
+ "0x52d19004": "implementation()",
119
+ # Pausability
120
+ "0x4fbee1e3": "pause()",
121
+ "0x8456cb59": "unpause()",
122
+ "0x5c975abb": "paused()",
123
+ # Destruction / High Risk
124
+ "0x83197ef0": "destroy(address)",
125
+ "0x41c0e1b5": "kill()",
126
+ "0x00f714ce": "selfdestruct()",
127
+ # Vaults / Wrapped Assets
128
+ "0xd0e30db0": "deposit()",
129
+ "0x2e1a7d4d": "withdraw(uint256)",
130
+ }
131
+
132
+ HIGH_RISK_KEYWORDS = (
133
+ "transferownership",
134
+ "renounceownership",
135
+ "upgradeto",
136
+ "destroy",
137
+ "kill",
138
+ "selfdestruct",
139
+ "mint",
140
+ "pause",
141
+ )
142
+
143
+ DISPATCHER_REGEX = re.compile(r"(?:63|8063|8263)([0-9a-fA-F]{8})14", re.IGNORECASE)
144
+
145
+
146
+ def extract_selectors_from_bytecode(
147
+ bytecode: Union[bytes, str],
148
+ tx_input: Optional[Union[bytes, str]] = None,
149
+ ) -> List[Dict[str, str]]:
150
+ """
151
+ Extracts 4-byte function selectors from smart contract bytecode and deployment calldata.
152
+ Identifies known signatures and flags privileged or high-risk capabilities.
153
+ """
154
+ if isinstance(bytecode, bytes):
155
+ bytecode_hex = bytecode.hex()
156
+ else:
157
+ bytecode_hex = bytecode[2:] if bytecode.startswith("0x") else bytecode
158
+
159
+ found: Dict[str, Dict[str, str]] = {}
160
+ bytecode_lower = bytecode_hex.lower()
161
+
162
+ # 1. Search known selectors directly within bytecode
163
+ for sel_hex, sig in KNOWN_SELECTORS.items():
164
+ clean_sel = sel_hex[2:].lower()
165
+ if clean_sel in bytecode_lower:
166
+ found[sel_hex] = {
167
+ "selector": sel_hex,
168
+ "signature": sig,
169
+ "known": True,
170
+ }
171
+
172
+ # 2. Extract selectors from standard EVM dispatcher opcodes (PUSH4 <sel> EQ)
173
+ for m in DISPATCHER_REGEX.findall(bytecode_hex):
174
+ sel_hex = f"0x{m.lower()}"
175
+ if sel_hex not in found:
176
+ sig = KNOWN_SELECTORS.get(sel_hex, f"unknown({sel_hex})")
177
+ found[sel_hex] = {
178
+ "selector": sel_hex,
179
+ "signature": sig,
180
+ "known": sel_hex in KNOWN_SELECTORS,
181
+ }
182
+
183
+ # 3. If deployment calldata (tx_input) is provided, inspect initialization calldata
184
+ if tx_input:
185
+ if isinstance(tx_input, bytes):
186
+ input_hex = tx_input.hex()
187
+ else:
188
+ input_hex = tx_input[2:] if tx_input.startswith("0x") else tx_input
189
+ input_lower = input_hex.lower()
190
+ for sel_hex, sig in KNOWN_SELECTORS.items():
191
+ clean_sel = sel_hex[2:].lower()
192
+ if clean_sel in input_lower and sel_hex not in found:
193
+ found[sel_hex] = {
194
+ "selector": sel_hex,
195
+ "signature": sig,
196
+ "known": True,
197
+ }
198
+
199
+ return list(found.values())
200
+
201
+
202
+ def is_high_risk_signature(signature: str) -> bool:
203
+ """Checks whether a function signature indicates admin control or contract termination."""
204
+ sig_lower = signature.lower()
205
+ return any(kw in sig_lower for kw in HIGH_RISK_KEYWORDS)
206
+
207
+
208
+ def create_deployment_rule_payload(
209
+ contract_address: str,
210
+ tx_hash: str,
211
+ block_number: int,
212
+ deployer: str,
213
+ selectors: List[Dict[str, str]],
214
+ bytecode_length: int,
215
+ require_high_risk_for_llm: bool = False,
216
+ ) -> ConditionRulePayload:
217
+ """
218
+ Constructs a validated ConditionRulePayload for evaluating a newly discovered smart contract.
219
+ """
220
+ checksummed_address = Web3.to_checksum_address(contract_address)
221
+ signatures = [s["signature"] for s in selectors]
222
+ high_risk_found = [s["signature"] for s in selectors if is_high_risk_signature(s["signature"])]
223
+ semantic_enabled = bool(high_risk_found) if require_high_risk_for_llm else True
224
+
225
+ # Determine priority selector for deterministic calldata analysis
226
+ matched_selector = "0x"
227
+ matched_signature = "deployment"
228
+ if high_risk_found:
229
+ for s in selectors:
230
+ if is_high_risk_signature(s["signature"]):
231
+ matched_selector = s["selector"]
232
+ matched_signature = s["signature"]
233
+ break
234
+ elif selectors:
235
+ matched_selector = selectors[0]["selector"]
236
+ matched_signature = selectors[0]["signature"]
237
+
238
+ proposal_desc = (
239
+ f"Audit newly deployed contract at block {block_number} by {deployer}. "
240
+ f"Contract Address: {checksummed_address}. Bytecode size: {bytecode_length} bytes. "
241
+ f"Detected function signatures: {', '.join(signatures) if signatures else 'None'}. "
242
+ )
243
+ if high_risk_found:
244
+ proposal_desc += f"CRITICAL: Contains privileged capabilities: {', '.join(high_risk_found)}."
245
+
246
+ prompt = (
247
+ f"Audit newly deployed smart contract at {checksummed_address} on Base Mainnet. "
248
+ f"Block: {block_number}, Deployer: {deployer}. "
249
+ f"Identified function selectors: {', '.join(signatures) if signatures else 'None'}. "
250
+ f"Assess decentralization risk, admin backdoor risks, unconstrained minting or self-destruction capabilities."
251
+ )
252
+
253
+ rule_id = f"block-deploy-{contract_address.lower()[:10]}"
254
+
255
+ return ConditionRulePayload(
256
+ rule_id=rule_id,
257
+ chain_id=ChainId.BASE_MAINNET,
258
+ deterministic=DeterministicCondition(
259
+ target_address=checksummed_address,
260
+ min_value_wei=0,
261
+ required_function_selectors=None,
262
+ check_native_balance=False,
263
+ ),
264
+ semantic=SemanticCondition(
265
+ enabled=semantic_enabled,
266
+ policy_prompt=prompt,
267
+ risk_threshold=7.0,
268
+ ),
269
+ context_metadata={
270
+ "contract_address": checksummed_address,
271
+ "tx_hash": tx_hash,
272
+ "block_number": block_number,
273
+ "deployer": deployer,
274
+ "calldata": matched_selector,
275
+ "calldata_analysis": {
276
+ "selector": matched_selector,
277
+ "signature": matched_signature,
278
+ },
279
+ "proposal_title": f"Contract Deployment: {checksummed_address}",
280
+ "proposal_description": proposal_desc,
281
+ "selectors_found": [s["selector"] for s in selectors],
282
+ "signatures_found": signatures,
283
+ "bytecode_length": bytecode_length,
284
+ },
285
+ )
286
+
287
+
288
+ async def get_latest_block_number(w3: AsyncWeb3) -> int:
289
+ """Safely retrieves the latest block number supporting Web3 properties, callables, or mocks."""
290
+ bn_target = getattr(w3.eth, "block_number", None)
291
+ if inspect.isawaitable(bn_target):
292
+ val = await bn_target
293
+ elif callable(bn_target):
294
+ res = bn_target()
295
+ val = await res if inspect.isawaitable(res) else res
296
+ else:
297
+ val = bn_target
298
+ return int(val)
299
+
300
+
301
+ async def scan_recent_blocks(
302
+ w3: AsyncWeb3,
303
+ num_blocks: int = 5,
304
+ limit: int = 10,
305
+ start_block: Optional[int] = None,
306
+ ) -> List[Dict[str, Any]]:
307
+ """
308
+ Scans the latest num_blocks blocks on Base Mainnet for contract creation transactions.
309
+
310
+ Filters transactions where tx.to is None (contract creation), retrieves receipts,
311
+ and returns metadata for non-empty deployed contracts up to `limit`.
312
+
313
+ Parameters:
314
+ w3: An active AsyncWeb3 connection instance.
315
+ num_blocks: Number of blocks to scan backwards from latest (default: 5).
316
+ limit: Maximum number of deployed contracts to discover (default: 10).
317
+ start_block: Optional explicit starting block number (defaults to latest block).
318
+
319
+ Returns:
320
+ List of dictionaries with discovered contract deployment metadata.
321
+ """
322
+ if limit <= 0 or num_blocks <= 0:
323
+ return []
324
+
325
+ try:
326
+ if start_block is None:
327
+ latest_block_num = await get_latest_block_number(w3)
328
+ else:
329
+ latest_block_num = start_block
330
+ except Exception as exc:
331
+ logger.error(f"Failed to fetch latest block number: {exc}")
332
+ return []
333
+
334
+ from_block = max(0, latest_block_num - num_blocks + 1)
335
+ logger.info(f"Scanning blocks {from_block} to {latest_block_num} (total {num_blocks} blocks, limit {limit})...")
336
+
337
+ discovered: List[Dict[str, Any]] = []
338
+
339
+ # Iterate from newest to oldest block
340
+ for b_num in range(latest_block_num, from_block - 1, -1):
341
+ if len(discovered) >= limit:
342
+ break
343
+
344
+ try:
345
+ block = await w3.eth.get_block(b_num, full_transactions=True)
346
+ except Exception as exc:
347
+ logger.warning(f"Could not retrieve block {b_num}: {exc}")
348
+ continue
349
+
350
+ if not block:
351
+ continue
352
+
353
+ raw_txs = block.get("transactions", []) if isinstance(block, dict) else getattr(block, "transactions", [])
354
+
355
+ for tx in raw_txs:
356
+ if len(discovered) >= limit:
357
+ break
358
+
359
+ # In EVM, contract creation transactions have tx.to is None
360
+ to_addr = tx.get("to") if isinstance(tx, dict) else getattr(tx, "to", None)
361
+ if to_addr is not None:
362
+ continue
363
+
364
+ # Extract transaction hash
365
+ tx_h = tx.get("hash") if isinstance(tx, dict) else getattr(tx, "hash", None)
366
+ if not tx_h:
367
+ continue
368
+
369
+ tx_hash_str = tx_h.hex() if hasattr(tx_h, "hex") else str(tx_h)
370
+ from_addr = tx.get("from") if isinstance(tx, dict) else getattr(tx, "from", "")
371
+ tx_input = tx.get("input") if isinstance(tx, dict) else getattr(tx, "input", "0x")
372
+
373
+ try:
374
+ receipt = await w3.eth.get_transaction_receipt(tx_h)
375
+ except Exception as exc:
376
+ logger.warning(f"Failed to fetch transaction receipt for {tx_hash_str}: {exc}")
377
+ continue
378
+
379
+ if not receipt:
380
+ continue
381
+
382
+ contract_addr = (
383
+ receipt.get("contractAddress")
384
+ if isinstance(receipt, dict)
385
+ else getattr(receipt, "contractAddress", None)
386
+ )
387
+
388
+ if not contract_addr or not Web3.is_address(contract_addr):
389
+ continue
390
+
391
+ checksummed_addr = Web3.to_checksum_address(contract_addr)
392
+
393
+ # Verify bytecode exists and is non-empty
394
+ try:
395
+ bytecode = await w3.eth.get_code(checksummed_addr)
396
+ except Exception as exc:
397
+ logger.warning(f"Failed to fetch bytecode for {checksummed_addr}: {exc}")
398
+ continue
399
+
400
+ if not bytecode or bytecode in (b"", b"\x00", "0x", "0x0"):
401
+ continue
402
+
403
+ discovered.append({
404
+ "block_number": b_num,
405
+ "tx_hash": tx_hash_str,
406
+ "contract_address": checksummed_addr,
407
+ "deployer": from_addr,
408
+ "bytecode": bytecode,
409
+ "tx_input": tx_input,
410
+ })
411
+ logger.info(f"Discovered contract deployment: {checksummed_addr} at block {b_num}")
412
+
413
+ return discovered
414
+
415
+
416
+ async def audit_discovered_contracts(
417
+ contracts: List[Dict[str, Any]],
418
+ engine: ConditionAgentEngine,
419
+ rpc_url: Optional[str] = None,
420
+ require_high_risk_for_llm: bool = False,
421
+ ) -> List[Dict[str, Any]]:
422
+ """
423
+ Executes deterministic bytecode inspection and semantic risk audits on discovered contracts.
424
+ Persists evaluation results to the SQLite ledger via AgentStorage.
425
+ """
426
+ results: List[Dict[str, Any]] = []
427
+
428
+ for item in contracts:
429
+ contract_addr = item["contract_address"]
430
+ bytecode = item["bytecode"]
431
+ tx_input = item.get("tx_input")
432
+ block_num = item["block_number"]
433
+ tx_hash = item["tx_hash"]
434
+ deployer = item.get("deployer", "0x0000000000000000000000000000000000000000")
435
+
436
+ # 1. Extract function selectors
437
+ selectors = extract_selectors_from_bytecode(bytecode, tx_input)
438
+
439
+ # 2. Populate ChainInspector bytecode cache to guarantee zero redundant network RPC calls
440
+ bytecode_bytes = bytecode if isinstance(bytecode, bytes) else bytes.fromhex(
441
+ bytecode[2:] if bytecode.startswith("0x") else bytecode
442
+ )
443
+ ChainInspector._set_bytecode_cache(f"{CHAIN_ID_BASE_MAINNET}:{contract_addr}", bytecode_bytes)
444
+
445
+ # 3. Build validated payload
446
+ payload = create_deployment_rule_payload(
447
+ contract_address=contract_addr,
448
+ tx_hash=tx_hash,
449
+ block_number=block_num,
450
+ deployer=deployer,
451
+ selectors=selectors,
452
+ bytecode_length=len(bytecode_bytes),
453
+ require_high_risk_for_llm=require_high_risk_for_llm,
454
+ )
455
+
456
+ # 4. Execute two-stage ConditionAgentEngine audit
457
+ try:
458
+ response = await engine.process_rule(payload, source="block_scanner")
459
+ except Exception as exc:
460
+ logger.error(f"Audit failed for contract {contract_addr}: {exc}")
461
+ continue
462
+
463
+ sem = response.semantic_Evaluation
464
+ decision = sem.recommended_action if sem else ("APPROVE" if response.deterministic_check.passed else "REJECT")
465
+ risk_score = sem.risk_score if sem else (0.0 if response.deterministic_check.passed else 10.0)
466
+
467
+ results.append({
468
+ "block_number": block_num,
469
+ "tx_hash": tx_hash,
470
+ "contract_address": contract_addr,
471
+ "deployer": deployer,
472
+ "selectors": selectors,
473
+ "recommendation": decision,
474
+ "risk_score": risk_score,
475
+ "payload": payload,
476
+ "response": response,
477
+ })
478
+
479
+ return results
480
+
481
+
482
+ def print_scan_table(results: List[Dict[str, Any]]) -> None:
483
+ """
484
+ Renders an ASCII table displaying audited contract deployment results:
485
+ Bloco, Tx Hash, Endereço do Contrato, Seletores Encontrados, Recomendação, Score de Risco.
486
+ """
487
+ headers = [
488
+ "Bloco",
489
+ "Tx Hash",
490
+ "Endereço do Contrato",
491
+ "Seletores Encontrados",
492
+ "Recomendação",
493
+ "Score de Risco",
494
+ ]
495
+ rows = []
496
+ for r in results:
497
+ block = str(r.get("block_number", "N/A"))
498
+ tx_hash = str(r.get("tx_hash", "N/A"))
499
+ if len(tx_hash) > 18:
500
+ tx_hash_display = f"{tx_hash[:10]}...{tx_hash[-6:]}"
501
+ else:
502
+ tx_hash_display = tx_hash
503
+
504
+ contract_addr = str(r.get("contract_address", "N/A"))
505
+
506
+ selectors = r.get("selectors", [])
507
+ if isinstance(selectors, list):
508
+ sel_strs = []
509
+ for s in selectors:
510
+ if isinstance(s, dict):
511
+ sig = s.get("signature", s.get("selector", ""))
512
+ sig_name = sig.split("(")[0] if "(" in sig else sig
513
+ sel_strs.append(sig_name)
514
+ else:
515
+ sel_strs.append(str(s))
516
+ selectors_display = ", ".join(sel_strs) if sel_strs else "None"
517
+ else:
518
+ selectors_display = str(selectors)
519
+
520
+ if len(selectors_display) > 32:
521
+ selectors_display = selectors_display[:29] + "..."
522
+
523
+ recommendation = str(r.get("recommendation", "N/A"))
524
+ risk_score = r.get("risk_score")
525
+ score_display = f"{float(risk_score):.1f}" if risk_score is not None else "N/A"
526
+
527
+ rows.append([
528
+ block,
529
+ tx_hash_display,
530
+ contract_addr,
531
+ selectors_display,
532
+ recommendation,
533
+ score_display,
534
+ ])
535
+
536
+ col_widths = [len(h) for h in headers]
537
+ for row in rows:
538
+ for idx, val in enumerate(row):
539
+ col_widths[idx] = max(col_widths[idx], len(val))
540
+
541
+ separator = "+" + "+".join("-" * (w + 2) for w in col_widths) + "+"
542
+ header_str = "|" + "|".join(f" {headers[i].ljust(col_widths[i])} " for i in range(len(headers))) + "|"
543
+
544
+ print("\n" + separator)
545
+ print(header_str)
546
+ print(separator)
547
+ if rows:
548
+ for row in rows:
549
+ row_str = "|" + "|".join(f" {row[i].ljust(col_widths[i])} " for i in range(len(row))) + "|"
550
+ print(row_str)
551
+ else:
552
+ empty_notice = "Nenhum contrato detectado nos blocos selecionados."
553
+ total_w = sum(col_widths) + 3 * len(col_widths) - 1
554
+ print(f"| {empty_notice.ljust(total_w - 2)} |")
555
+ print(separator + "\n")
556
+
557
+
558
+ def create_mock_w3() -> Any:
559
+ """
560
+ Creates an AsyncWeb3 mock simulating Base Mainnet blocks and contract deployments.
561
+ Used for --dry-run and offline unit tests with zero external RPC dependency.
562
+ """
563
+ # Sample contracts for realistic auditing simulation:
564
+ # 1. Admin proxy with transferOwnership, upgradeTo, and destroy (high risk)
565
+ bytecode_admin = bytes.fromhex(
566
+ "608060405234801561001057600080fd5b50"
567
+ "8063f2fde38b1461003057" # transferOwnership
568
+ "80633659cfe61461005057" # upgradeTo
569
+ "806383197ef01461007057" # destroy
570
+ "600080fd"
571
+ )
572
+ # 2. Standard ERC-20 token (low risk)
573
+ bytecode_erc20 = bytes.fromhex(
574
+ "608060405234801561001057600080fd5b50"
575
+ "8063a9059cbb1461003057" # transfer
576
+ "8063095ea7b31461005057" # approve
577
+ "806370a082311461007057" # balanceOf
578
+ "600080fd"
579
+ )
580
+ # 3. Mintable Token with pause (medium risk)
581
+ bytecode_mintable = bytes.fromhex(
582
+ "608060405234801561001057600080fd5b50"
583
+ "806340c10f191461003057" # mint
584
+ "80634fbee1e31461005057" # pause
585
+ "600080fd"
586
+ )
587
+
588
+ contracts_db = {
589
+ "0x1111111111111111111111111111111111111111": bytecode_admin,
590
+ "0x2222222222222222222222222222222222222222": bytecode_erc20,
591
+ "0x3333333333333333333333333333333333333333": bytecode_mintable,
592
+ }
593
+
594
+ mock_receipts = {
595
+ "0xaaa1111111111111111111111111111111111111111111111111111111111111": {
596
+ "contractAddress": "0x1111111111111111111111111111111111111111",
597
+ "status": 1,
598
+ },
599
+ "0xbbb2222222222222222222222222222222222222222222222222222222222222": {
600
+ "contractAddress": "0x2222222222222222222222222222222222222222",
601
+ "status": 1,
602
+ },
603
+ "0xccc3333333333333333333333333333333333333333333333333333333333333": {
604
+ "contractAddress": "0x3333333333333333333333333333333333333333",
605
+ "status": 1,
606
+ },
607
+ }
608
+
609
+ mock_blocks = {
610
+ 23419500: {
611
+ "number": 23419500,
612
+ "transactions": [
613
+ {
614
+ "hash": "0xaaa1111111111111111111111111111111111111111111111111111111111111",
615
+ "from": "0xDeployer111111111111111111111111111111111",
616
+ "to": None,
617
+ "input": "0x60806040...",
618
+ },
619
+ {
620
+ "hash": "0x9990000000000000000000000000000000000000000000000000000000000000",
621
+ "from": "0xUserA",
622
+ "to": "0xUserB", # Standard transfer, not contract creation
623
+ "input": "0x",
624
+ },
625
+ ],
626
+ },
627
+ 23419501: {
628
+ "number": 23419501,
629
+ "transactions": [
630
+ {
631
+ "hash": "0xbbb2222222222222222222222222222222222222222222222222222222222222",
632
+ "from": "0xDeployer222222222222222222222222222222222",
633
+ "to": None,
634
+ "input": "0x60806040...",
635
+ },
636
+ {
637
+ "hash": "0xccc3333333333333333333333333333333333333333333333333333333333333",
638
+ "from": "0xDeployer333333333333333333333333333333333",
639
+ "to": None,
640
+ "input": "0x60806040...",
641
+ },
642
+ ],
643
+ },
644
+ }
645
+
646
+ class MockEth:
647
+ def __init__(self):
648
+ pass
649
+
650
+ @property
651
+ def block_number(self):
652
+ async def _bn():
653
+ return 23419501
654
+ return _bn()
655
+
656
+ async def get_block(self, block_identifier, full_transactions=True):
657
+ b_num = int(block_identifier) if str(block_identifier).isdigit() else 23419501
658
+ return mock_blocks.get(b_num, {"number": b_num, "transactions": []})
659
+
660
+ async def get_transaction_receipt(self, tx_hash):
661
+ tx_h_str = tx_hash.hex() if hasattr(tx_hash, "hex") else str(tx_hash)
662
+ return mock_receipts.get(tx_h_str, None)
663
+
664
+ async def get_code(self, addr):
665
+ chk = Web3.to_checksum_address(addr) if Web3.is_address(addr) else addr
666
+ return contracts_db.get(chk, b"")
667
+
668
+ class MockW3:
669
+ def __init__(self):
670
+ self.eth = MockEth()
671
+
672
+ async def is_connected(self):
673
+ return True
674
+
675
+ return MockW3()
676
+
677
+
678
+ async def run_continuous_scanner(
679
+ w3: AsyncWeb3,
680
+ engine: ConditionAgentEngine,
681
+ limit: int = 10,
682
+ poll_interval: float = 2.0,
683
+ max_iterations: Optional[int] = None,
684
+ rpc_url: Optional[str] = None,
685
+ ) -> None:
686
+ """
687
+ Executes real-time monitoring loop polling new blocks every ~poll_interval seconds.
688
+ """
689
+ print(f"[*] Starting continuous contract deployment scanner on Base Mainnet (poll: {poll_interval}s)...")
690
+ print("[*] Press Ctrl+C to stop.\n")
691
+
692
+ last_scanned_block: Optional[int] = None
693
+ iteration = 0
694
+
695
+ try:
696
+ while True:
697
+ try:
698
+ current_block = await get_latest_block_number(w3)
699
+ if last_scanned_block is None:
700
+ blocks_to_check = 1
701
+ start_b = current_block
702
+ elif current_block > last_scanned_block:
703
+ blocks_to_check = current_block - last_scanned_block
704
+ start_b = current_block
705
+ else:
706
+ await asyncio.sleep(poll_interval)
707
+ iteration += 1
708
+ if max_iterations is not None and iteration >= max_iterations:
709
+ break
710
+ continue
711
+
712
+ discovered = await scan_recent_blocks(
713
+ w3=w3,
714
+ num_blocks=blocks_to_check,
715
+ limit=limit,
716
+ start_block=start_b,
717
+ )
718
+
719
+ if discovered:
720
+ results = await audit_discovered_contracts(discovered, engine, rpc_url=rpc_url)
721
+ print_scan_table(results)
722
+ else:
723
+ print(f"[{time.strftime('%X')}] Checked block {current_block}: No new contract deployments.")
724
+
725
+ last_scanned_block = current_block
726
+
727
+ except asyncio.CancelledError:
728
+ break
729
+ except Exception as exc:
730
+ logger.error(f"Error in continuous scanner loop: {exc}")
731
+
732
+ iteration += 1
733
+ if max_iterations is not None and iteration >= max_iterations:
734
+ break
735
+
736
+ await asyncio.sleep(poll_interval)
737
+
738
+ except KeyboardInterrupt:
739
+ print("\n[*] Scanner stopped by user.")
740
+
741
+
742
+ async def run_scanner(
743
+ blocks: int = 5,
744
+ limit: int = 10,
745
+ dry_run: bool = False,
746
+ continuous: bool = False,
747
+ rpc_url: Optional[str] = None,
748
+ storage: Optional[AgentStorage] = None,
749
+ max_continuous_iterations: Optional[int] = None,
750
+ ) -> List[Dict[str, Any]]:
751
+ """
752
+ Orchestrates the block scanner workflow based on CLI flags.
753
+ """
754
+ resolved_rpc = rpc_url or os.getenv("RPC_URL_8453") or DEFAULT_BASE_RPC
755
+
756
+ print("=" * 72)
757
+ print("Web3 Condition-Action Trigger Agent: Base Mainnet Contract Scanner")
758
+ print("=" * 72)
759
+ print(f"[*] Target Network: Base Mainnet (Chain ID: {CHAIN_ID_BASE_MAINNET})")
760
+ print(f"[*] Mode: {'DRY-RUN (Simulated)' if dry_run else 'LIVE ON-CHAIN'}")
761
+ print(f"[*] Blocks to inspect: {blocks} | Limit: {limit} contracts")
762
+ if not dry_run:
763
+ print(f"[*] RPC Endpoint: {resolved_rpc}")
764
+ print("=" * 72 + "\n")
765
+
766
+ storage_instance = storage if storage is not None else AgentStorage()
767
+
768
+ if dry_run:
769
+ print("[*] Running with simulated mock Web3 provider and MockSemanticEvaluator...")
770
+ evaluator = MockSemanticEvaluator()
771
+ engine = ConditionAgentEngine(
772
+ rpc_url=resolved_rpc,
773
+ semantic_evaluator=evaluator,
774
+ storage=storage_instance,
775
+ )
776
+ w3 = create_mock_w3()
777
+ else:
778
+ w3 = AsyncWeb3(AsyncHTTPProvider(resolved_rpc))
779
+ try:
780
+ connected = await w3.is_connected()
781
+ if not connected:
782
+ print(f"[!] Warning: Could not connect to RPC at {resolved_rpc}. Continuing anyway...")
783
+ except Exception as exc:
784
+ print(f"[!] Warning: Connection check failed: {exc}")
785
+
786
+ engine = ConditionAgentEngine(
787
+ rpc_url=resolved_rpc,
788
+ storage=storage_instance,
789
+ )
790
+
791
+ if continuous:
792
+ await run_continuous_scanner(
793
+ w3=w3,
794
+ engine=engine,
795
+ limit=limit,
796
+ poll_interval=2.0,
797
+ max_iterations=max_continuous_iterations,
798
+ rpc_url=resolved_rpc,
799
+ )
800
+ return []
801
+
802
+ print(f"[*] Scanning recent {blocks} blocks for contract deployments...")
803
+ discovered = await scan_recent_blocks(
804
+ w3=w3,
805
+ num_blocks=blocks,
806
+ limit=limit,
807
+ )
808
+
809
+ if not discovered:
810
+ print(f"[*] No contract deployments detected in the scanned {blocks} blocks.")
811
+ print("[*] Tip: Use --blocks 50 or --continuous to catch new deployments on Base.")
812
+ print_scan_table([])
813
+ return []
814
+
815
+ print(f"[*] Discovered {len(discovered)} contract deployments. Executing audits...")
816
+ results = await audit_discovered_contracts(discovered, engine, rpc_url=resolved_rpc)
817
+ print_scan_table(results)
818
+
819
+ # Print summary metrics
820
+ high_risks = [r for r in results if r["recommendation"] == "REJECT"]
821
+ manual_reviews = [r for r in results if r["recommendation"] == "MANUAL_REVIEW"]
822
+ approvals = [r for r in results if r["recommendation"] == "APPROVE"]
823
+
824
+ print(f"[*] Audit Summary: Total: {len(results)} | Approved: {len(approvals)} | Manual Review: {len(manual_reviews)} | Rejected: {len(high_risks)}")
825
+ print(f"[*] Evaluation records persisted to SQLite ledger: {storage_instance.db_path}\n")
826
+
827
+ return results
828
+
829
+
830
+ def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
831
+ """Parses command line arguments."""
832
+ parser = argparse.ArgumentParser(
833
+ description="Autonomous On-Chain Block Scanner for New Smart Contracts on Base Mainnet."
834
+ )
835
+ parser.add_argument(
836
+ "--blocks",
837
+ type=int,
838
+ default=5,
839
+ help="Number of recent blocks to scan backwards from latest (default: 5)",
840
+ )
841
+ parser.add_argument(
842
+ "--limit",
843
+ type=int,
844
+ default=10,
845
+ help="Maximum number of contracts to discover and audit (default: 10)",
846
+ )
847
+ parser.add_argument(
848
+ "--dry-run",
849
+ action="store_true",
850
+ default=False,
851
+ help="Run in dry-run mode using synthetic block data with zero external network dependency",
852
+ )
853
+ parser.add_argument(
854
+ "--continuous",
855
+ action="store_true",
856
+ default=False,
857
+ help="Run continuously in an async loop polling new blocks every ~2 seconds",
858
+ )
859
+ parser.add_argument(
860
+ "--rpc-url",
861
+ type=str,
862
+ default=None,
863
+ help="Custom RPC endpoint URL (overrides RPC_URL_8453 and default https://mainnet.base.org)",
864
+ )
865
+ return parser.parse_args(args)
866
+
867
+
868
+ def main() -> None:
869
+ """CLI script entrypoint."""
870
+ args = parse_args()
871
+ logging.basicConfig(
872
+ level=logging.INFO,
873
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
874
+ )
875
+ asyncio.run(
876
+ run_scanner(
877
+ blocks=args.blocks,
878
+ limit=args.limit,
879
+ dry_run=args.dry_run,
880
+ continuous=args.continuous,
881
+ rpc_url=args.rpc_url,
882
+ )
883
+ )
884
+
885
+
886
+ if __name__ == "__main__":
887
+ main()