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,1000 @@
1
+ """
2
+ Active Multi-Channel Contract Hunter for Web3 Condition-Action Trigger Agent.
3
+
4
+ Continuously and autonomously discovers newly deployed contracts, newly minted DEX pools,
5
+ freshly listed tokens, and active DAO governance proposals across 5 zero-API-key, zero-gas
6
+ discovery channels:
7
+ 1. "base_blocks": Base Mainnet block contract deployments (scan_recent_blocks).
8
+ 2. "dex_pools": Aerodrome & Uniswap v3 PoolCreated events on Base (scan_pool_events).
9
+ 3. "geckoterminal_base": GeckoTerminal public New Pools API for Base.
10
+ 4. "dexscreener_base": DexScreener public Latest Token Profiles API filtered to Base.
11
+ 5. "snapshot_daos": Active Snapshot DAO governance proposals with on-chain targets.
12
+
13
+ Each discovered target is deduplicated via a bounded FIFO cache, triaged deterministically
14
+ on-chain at zero LLM cost (bytecode extraction, 4-byte selectors, honeypot signatures),
15
+ and escalated to Stage 2 semantic auditing only when high-risk indicators are present
16
+ (when require_high_risk_for_llm=True).
17
+
18
+ Usage Examples:
19
+ import asyncio
20
+ from src.discovery_hunter import ActiveContractHunter
21
+
22
+ async def main():
23
+ hunter = ActiveContractHunter()
24
+ summary = await hunter.run_hunt_cycle(limit_per_channel=2, dry_run=True)
25
+ print(summary["total_audited"], summary["high_risk_count"])
26
+
27
+ asyncio.run(main())
28
+ """
29
+
30
+ import asyncio
31
+ import logging
32
+ import os
33
+ import sys
34
+ import time
35
+ from typing import Any, Dict, List, Optional, Tuple
36
+
37
+ # Guarded dotenv loading: skipped during pytest execution or if python-dotenv not installed
38
+ if "pytest" not in sys.modules:
39
+ try:
40
+ import dotenv
41
+ _CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
42
+ _PARENT_ROOT = os.path.abspath(os.path.join(_CURRENT_SCRIPT_DIR, ".."))
43
+ _env_file = os.path.join(_PARENT_ROOT, ".env")
44
+ if os.path.exists(_env_file):
45
+ dotenv.load_dotenv(_env_file, override=False)
46
+ dotenv.load_dotenv(override=False)
47
+ except ImportError:
48
+ pass
49
+
50
+ # Ensure module search paths support running directly or as a package
51
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
52
+ _ROOT_DIR = (
53
+ os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
54
+ if os.path.basename(_CURRENT_DIR) == "src"
55
+ else _CURRENT_DIR
56
+ )
57
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
58
+ for _p in (_ROOT_DIR, _SRC_DIR):
59
+ if _p not in sys.path:
60
+ sys.path.insert(0, _p)
61
+
62
+ try:
63
+ import httpx
64
+ except ImportError:
65
+ httpx = None # type: ignore
66
+
67
+ from web3 import AsyncHTTPProvider, AsyncWeb3, Web3
68
+
69
+ try:
70
+ from src.chain_inspector import ChainInspector
71
+ from src.engine import ConditionAgentEngine
72
+ from src.governance_connector import (
73
+ GovernanceAuditReport,
74
+ GovernanceProposal,
75
+ SnapshotGovernanceConnector,
76
+ WebhookAlertDispatcher,
77
+ get_curated_dao_proposals,
78
+ )
79
+ from src.schemas import (
80
+ ChainId,
81
+ ConditionRulePayload,
82
+ DeterministicCondition,
83
+ FinalAgentResponse,
84
+ SemanticCondition,
85
+ )
86
+ from src.semantic_evaluator import MockSemanticEvaluator
87
+ from src.storage import AgentStorage
88
+ except ImportError:
89
+ from chain_inspector import ChainInspector
90
+ from engine import ConditionAgentEngine
91
+ from governance_connector import (
92
+ GovernanceAuditReport,
93
+ GovernanceProposal,
94
+ SnapshotGovernanceConnector,
95
+ WebhookAlertDispatcher,
96
+ get_curated_dao_proposals,
97
+ )
98
+ from schemas import (
99
+ ChainId,
100
+ ConditionRulePayload,
101
+ DeterministicCondition,
102
+ FinalAgentResponse,
103
+ SemanticCondition,
104
+ )
105
+ from semantic_evaluator import MockSemanticEvaluator
106
+ from storage import AgentStorage
107
+
108
+ from scripts.block_contract_scanner import (
109
+ audit_discovered_contracts,
110
+ create_mock_w3 as create_mock_block_w3,
111
+ extract_selectors_from_bytecode,
112
+ is_high_risk_signature,
113
+ scan_recent_blocks,
114
+ )
115
+ from scripts.dex_pool_monitor import (
116
+ HONEYPOT_SELECTORS,
117
+ analyze_bytecode_honeypot,
118
+ audit_discovered_pools,
119
+ get_curated_mock_pools,
120
+ get_latest_block_number,
121
+ scan_pool_events,
122
+ )
123
+
124
+ logger = logging.getLogger(__name__)
125
+
126
+ CHAIN_ID_BASE_MAINNET = 8453
127
+ DEFAULT_BASE_RPC = "https://mainnet.base.org"
128
+
129
+ GECKOTERMINAL_NEW_POOLS_URL = (
130
+ "https://api.geckoterminal.com/api/v2/networks/base/new_pools"
131
+ )
132
+ GECKOTERMINAL_HEADERS = {"Accept": "application/json;version=20230302"}
133
+ DEXSCREENER_TOKEN_PROFILES_URL = (
134
+ "https://api.dexscreener.com/token-profiles/latest/v1"
135
+ )
136
+
137
+ SUPPORTED_CHANNELS: Tuple[str, ...] = (
138
+ "base_blocks",
139
+ "dex_pools",
140
+ "geckoterminal_base",
141
+ "dexscreener_base",
142
+ "snapshot_daos",
143
+ )
144
+
145
+ # Deterministic bytecode fixtures for offline dry-run simulations
146
+ _BENIGN_ERC20_BYTECODE = bytes.fromhex(
147
+ "608060405234801561001057600080fd5b50"
148
+ "8063a9059cbb1461003057" # transfer(address,uint256)
149
+ "8063095ea7b31461005057" # approve(address,uint256)
150
+ "806370a082311461007057" # balanceOf(address)
151
+ "600080fd"
152
+ )
153
+ _HONEYPOT_UPGRADEABLE_BYTECODE = bytes.fromhex(
154
+ "608060405234801561001057600080fd5b50"
155
+ "806340af12751461003057" # setBlacklist(address,bool)
156
+ "80631e3dd19f1461005057" # setTax(uint256)
157
+ "80633659cfe61461007057" # upgradeTo(address)
158
+ "8063f2fde38b1461009057" # transferOwnership(address)
159
+ "600080fd"
160
+ )
161
+
162
+
163
+ def _to_bytecode_bytes(bytecode: Any) -> bytes:
164
+ """Normalizes hex string or bytes bytecode into raw bytes."""
165
+ if not bytecode:
166
+ return b""
167
+ if isinstance(bytecode, (bytes, bytearray)):
168
+ return bytes(bytecode)
169
+ if isinstance(bytecode, str):
170
+ cleaned = bytecode[2:] if bytecode.startswith("0x") else bytecode
171
+ if not cleaned:
172
+ return b""
173
+ try:
174
+ return bytes.fromhex(cleaned)
175
+ except ValueError:
176
+ return b""
177
+ return b""
178
+
179
+
180
+ def _extract_geckoterminal_token_address(item: Dict[str, Any]) -> Optional[str]:
181
+ """Extracts and validates a checksummed Base token address from a GeckoTerminal pool item."""
182
+ if not isinstance(item, dict):
183
+ return None
184
+
185
+ candidates: List[str] = []
186
+ relationships = item.get("relationships")
187
+ if isinstance(relationships, dict):
188
+ base_token = relationships.get("base_token")
189
+ if isinstance(base_token, dict):
190
+ bt_data = base_token.get("data")
191
+ if isinstance(bt_data, dict):
192
+ bt_id = bt_data.get("id")
193
+ if isinstance(bt_id, str):
194
+ candidates.append(bt_id[5:] if bt_id.startswith("base_") else bt_id)
195
+
196
+ attrs = item.get("attributes")
197
+ if isinstance(attrs, dict):
198
+ for key in ("base_token_address", "address"):
199
+ val = attrs.get(key)
200
+ if isinstance(val, str):
201
+ candidates.append(val)
202
+
203
+ for raw in candidates:
204
+ raw_clean = raw.strip()
205
+ if Web3.is_address(raw_clean):
206
+ return Web3.to_checksum_address(raw_clean)
207
+ return None
208
+
209
+
210
+ class ActiveContractHunter:
211
+ """
212
+ Autonomous Multi-Channel Contract Hunter discovering real smart contracts,
213
+ DEX tokens, and DAO governance payloads across 5 zero-cost channels.
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ engine: Optional[ConditionAgentEngine] = None,
219
+ storage: Optional[AgentStorage] = None,
220
+ rpc_url: Optional[str] = None,
221
+ http_client: Optional[Any] = None,
222
+ require_high_risk_for_llm: bool = True,
223
+ webhook_url: Optional[str] = None,
224
+ public_api_url: Optional[str] = None,
225
+ max_seen_cache: int = 2048,
226
+ ):
227
+ self.storage = storage if storage is not None else AgentStorage()
228
+ self.engine = engine
229
+ self.rpc_url = (
230
+ rpc_url
231
+ or os.getenv("RPC_URL_8453")
232
+ or DEFAULT_BASE_RPC
233
+ )
234
+ self.http_client = http_client
235
+ self.require_high_risk_for_llm = bool(require_high_risk_for_llm)
236
+ self.webhook_url = (
237
+ webhook_url
238
+ or os.getenv("ALERT_WEBHOOK_URL")
239
+ or os.getenv("WEBHOOK_URL")
240
+ or ""
241
+ ).strip() or None
242
+ self.public_api_url = (
243
+ public_api_url
244
+ or os.getenv("PUBLIC_API_URL")
245
+ or "https://web3-systemic-agent.onrender.com"
246
+ ).rstrip("/")
247
+ self.max_seen_cache = max(1, int(max_seen_cache))
248
+ self._seen_targets: Dict[str, float] = {}
249
+
250
+ def _is_seen(self, key: str) -> bool:
251
+ return key in self._seen_targets
252
+
253
+ def _mark_seen(self, key: str) -> None:
254
+ if key in self._seen_targets:
255
+ self._seen_targets[key] = time.time()
256
+ return
257
+ while len(self._seen_targets) >= self.max_seen_cache:
258
+ oldest_key = next(iter(self._seen_targets))
259
+ self._seen_targets.pop(oldest_key, None)
260
+ self._seen_targets[key] = time.time()
261
+
262
+ def _get_engine(self, dry_run: bool = False) -> ConditionAgentEngine:
263
+ if dry_run:
264
+ return ConditionAgentEngine(
265
+ rpc_url=self.rpc_url,
266
+ semantic_evaluator=MockSemanticEvaluator(),
267
+ storage=self.storage,
268
+ )
269
+ if self.engine is None:
270
+ self.engine = ConditionAgentEngine(
271
+ rpc_url=self.rpc_url,
272
+ storage=self.storage,
273
+ )
274
+ return self.engine
275
+
276
+ async def _http_get_json(
277
+ self,
278
+ url: str,
279
+ headers: Optional[Dict[str, str]] = None,
280
+ ) -> Any:
281
+ """Performs an async HTTP GET returning parsed JSON using injected or fresh httpx client."""
282
+ if self.http_client is not None:
283
+ resp = await self.http_client.get(url, headers=headers)
284
+ resp.raise_for_status()
285
+ return resp.json()
286
+
287
+ if httpx is None:
288
+ raise RuntimeError("httpx is required for live HTTP discovery channels")
289
+
290
+ async with httpx.AsyncClient(timeout=10.0) as client:
291
+ resp = await client.get(url, headers=headers)
292
+ resp.raise_for_status()
293
+ return resp.json()
294
+
295
+ async def _fetch_base_bytecode(self, checksum_addr: str) -> bytes:
296
+ """Resolves bytecode from ChainInspector cache or Base Mainnet RPC."""
297
+ cache_key = f"{CHAIN_ID_BASE_MAINNET}:{checksum_addr}"
298
+ if cache_key in ChainInspector._bytecode_cache:
299
+ return ChainInspector._bytecode_cache[cache_key]
300
+
301
+ inspector = ChainInspector(chain_id=CHAIN_ID_BASE_MAINNET, rpc_url=self.rpc_url)
302
+ for url in inspector.rpc_urls:
303
+ try:
304
+ w3 = inspector._get_or_create_w3(
305
+ CHAIN_ID_BASE_MAINNET, url, use_cache=inspector.use_cache
306
+ )
307
+ code = await w3.eth.get_code(checksum_addr)
308
+ code_bytes = _to_bytecode_bytes(code)
309
+ ChainInspector._set_bytecode_cache(cache_key, code_bytes)
310
+ return code_bytes
311
+ except Exception as exc:
312
+ logger.warning(f"RPC get_code failed for {checksum_addr} at {url}: {exc}")
313
+ return b""
314
+
315
+ def _build_token_rule_payload(
316
+ self,
317
+ checksum_addr: str,
318
+ bytecode_bytes: bytes,
319
+ analysis: Dict[str, Any],
320
+ selectors: List[Dict[str, Any]],
321
+ channel: str,
322
+ source_prefix: str,
323
+ label: str,
324
+ extra_context: Optional[Dict[str, Any]] = None,
325
+ ) -> Tuple[ConditionRulePayload, bool]:
326
+ """Builds a ConditionRulePayload for a discovered token with risk-gated LLM escalation."""
327
+ honeypot_flags: List[str] = list(analysis.get("honeypot_flags", []))
328
+ is_honeypot = bool(analysis.get("is_honeypot", False))
329
+ signatures = [s.get("signature", "") for s in selectors]
330
+ high_risk_sigs = [sig for sig in signatures if is_high_risk_signature(sig)]
331
+ has_risk_flags = bool(is_honeypot or honeypot_flags or high_risk_sigs)
332
+ semantic_enabled = bool(has_risk_flags) if self.require_high_risk_for_llm else True
333
+
334
+ matched_selector = "0x"
335
+ matched_signature = "erc20_transfer"
336
+ for s in selectors:
337
+ sig = s.get("signature", "")
338
+ if "transferOwnership" in sig or "upgradeTo" in sig:
339
+ matched_selector = s["selector"]
340
+ matched_signature = sig
341
+ break
342
+ if matched_selector == "0x":
343
+ for s in selectors:
344
+ if s.get("selector") in HONEYPOT_SELECTORS or is_high_risk_signature(s.get("signature", "")):
345
+ matched_selector = s["selector"]
346
+ matched_signature = s["signature"]
347
+ break
348
+ if matched_selector == "0x" and selectors:
349
+ matched_selector = selectors[0]["selector"]
350
+ matched_signature = selectors[0]["signature"]
351
+
352
+ threat_summary = (
353
+ f"CRITICAL RISK INDICATORS: {', '.join(honeypot_flags + high_risk_sigs)}"
354
+ if has_risk_flags
355
+ else "Standard token bytecode without honeypot or privileged admin patterns."
356
+ )
357
+
358
+ prompt = (
359
+ f"Audit newly discovered Base token {label} ({checksum_addr}) from channel {channel}. "
360
+ f"Bytecode size: {len(bytecode_bytes)} bytes. "
361
+ f"Honeypot flags: {', '.join(honeypot_flags) if honeypot_flags else 'None'}. "
362
+ f"Privileged signatures: {', '.join(high_risk_sigs) if high_risk_sigs else 'None'}. "
363
+ f"Evaluate blacklist traps, arbitrary transfer taxes, upgradeable proxy backdoors, and rugpull risk."
364
+ )
365
+
366
+ context_metadata: Dict[str, Any] = {
367
+ "channel": channel,
368
+ "target_token": checksum_addr,
369
+ "token_label": label,
370
+ "honeypot_flags": honeypot_flags,
371
+ "is_honeypot_suspect": is_honeypot,
372
+ "high_risk_signatures": high_risk_sigs,
373
+ "selectors_found": [s.get("selector") for s in selectors],
374
+ "signatures_found": signatures,
375
+ "bytecode_length": len(bytecode_bytes),
376
+ "calldata": matched_selector,
377
+ "calldata_analysis": {
378
+ "selector": matched_selector,
379
+ "signature": matched_signature,
380
+ },
381
+ "proposal_title": f"{channel}: {label} ({checksum_addr})",
382
+ "proposal_description": (
383
+ f"Token discovered via {channel}. Address: {checksum_addr}. {threat_summary}"
384
+ ),
385
+ }
386
+ if extra_context:
387
+ context_metadata.update(extra_context)
388
+
389
+ payload = ConditionRulePayload(
390
+ rule_id=f"{source_prefix}-{checksum_addr.lower()[:12]}",
391
+ chain_id=ChainId.BASE_MAINNET,
392
+ deterministic=DeterministicCondition(
393
+ target_address=checksum_addr,
394
+ min_value_wei=0,
395
+ required_function_selectors=None,
396
+ check_native_balance=False,
397
+ ),
398
+ semantic=SemanticCondition(
399
+ enabled=semantic_enabled,
400
+ policy_prompt=prompt,
401
+ risk_threshold=7.0,
402
+ ),
403
+ context_metadata=context_metadata,
404
+ )
405
+ return payload, is_honeypot
406
+
407
+ async def _audit_discovered_token(
408
+ self,
409
+ token_address: str,
410
+ channel: str,
411
+ source: str,
412
+ source_prefix: str,
413
+ label: str,
414
+ active_engine: ConditionAgentEngine,
415
+ bytecode_override: Optional[bytes] = None,
416
+ extra_context: Optional[Dict[str, Any]] = None,
417
+ ) -> Optional[Dict[str, Any]]:
418
+ """Executes deterministic triage and conditional Stage 2 audit for a discovered token."""
419
+ if not Web3.is_address(token_address):
420
+ return None
421
+ checksum_addr = Web3.to_checksum_address(token_address)
422
+ seen_key = checksum_addr.lower()
423
+ if self._is_seen(seen_key):
424
+ return None
425
+
426
+ if bytecode_override is not None:
427
+ bytecode_bytes = _to_bytecode_bytes(bytecode_override)
428
+ ChainInspector._set_bytecode_cache(
429
+ f"{CHAIN_ID_BASE_MAINNET}:{checksum_addr}", bytecode_bytes
430
+ )
431
+ else:
432
+ bytecode_bytes = await self._fetch_base_bytecode(checksum_addr)
433
+
434
+ if not bytecode_bytes or bytecode_bytes == b"\x00":
435
+ return None
436
+
437
+ self._mark_seen(seen_key)
438
+
439
+ analysis = analyze_bytecode_honeypot(bytecode_bytes)
440
+ selectors = extract_selectors_from_bytecode(bytecode_bytes)
441
+ payload, is_honeypot = self._build_token_rule_payload(
442
+ checksum_addr=checksum_addr,
443
+ bytecode_bytes=bytecode_bytes,
444
+ analysis=analysis,
445
+ selectors=selectors,
446
+ channel=channel,
447
+ source_prefix=source_prefix,
448
+ label=label,
449
+ extra_context=extra_context,
450
+ )
451
+
452
+ try:
453
+ response = await active_engine.process_rule(payload, source=source)
454
+ except Exception as exc:
455
+ logger.error(f"[{channel}] Audit failed for {checksum_addr}: {exc}")
456
+ return None
457
+
458
+ sem = response.semantic_Evaluation
459
+ if is_honeypot:
460
+ decision = "REJECT"
461
+ risk_score = max(float(sem.risk_score) if sem else 9.0, 9.0)
462
+ elif sem is not None:
463
+ decision = sem.recommended_action
464
+ risk_score = float(sem.risk_score)
465
+ else:
466
+ decision = "APPROVE" if response.deterministic_check.passed else "REJECT"
467
+ risk_score = 0.0 if response.deterministic_check.passed else 10.0
468
+
469
+ flags = list(analysis.get("honeypot_flags", []))
470
+ for s in selectors:
471
+ sig = s.get("signature", "")
472
+ if is_high_risk_signature(sig) and sig not in flags:
473
+ flags.append(sig)
474
+
475
+ return {
476
+ "channel": channel,
477
+ "target": checksum_addr,
478
+ "target_address": checksum_addr,
479
+ "label": label,
480
+ "risk_score": risk_score,
481
+ "decision": decision,
482
+ "llm_invoked": bool(response.llm_invoked),
483
+ "flags": flags,
484
+ "source": source,
485
+ "rule_id": payload.rule_id,
486
+ "response": response,
487
+ }
488
+
489
+ async def hunt_base_blocks(
490
+ self,
491
+ blocks: int = 2,
492
+ limit: int = 2,
493
+ w3: Optional[Any] = None,
494
+ dry_run: bool = False,
495
+ engine: Optional[ConditionAgentEngine] = None,
496
+ ) -> List[Dict[str, Any]]:
497
+ """Channel 1: Scans recent Base Mainnet blocks for new smart contract deployments."""
498
+ if limit <= 0:
499
+ return []
500
+
501
+ active_engine = engine or self._get_engine(dry_run=dry_run)
502
+ if w3 is not None:
503
+ target_w3 = w3
504
+ elif dry_run:
505
+ target_w3 = create_mock_block_w3()
506
+ else:
507
+ target_w3 = AsyncWeb3(AsyncHTTPProvider(self.rpc_url))
508
+
509
+ try:
510
+ discovered = await scan_recent_blocks(
511
+ w3=target_w3, num_blocks=blocks, limit=limit
512
+ )
513
+ except Exception as exc:
514
+ logger.warning(f"[base_blocks] Failed to scan blocks: {exc}")
515
+ return []
516
+
517
+ unseen: List[Dict[str, Any]] = []
518
+ for item in discovered:
519
+ addr = item.get("contract_address")
520
+ if not addr or not Web3.is_address(addr):
521
+ continue
522
+ chk = Web3.to_checksum_address(addr)
523
+ if self._is_seen(chk.lower()):
524
+ continue
525
+ self._mark_seen(chk.lower())
526
+ unseen.append(item)
527
+ if len(unseen) >= limit:
528
+ break
529
+
530
+ if not unseen:
531
+ return []
532
+
533
+ audited = await audit_discovered_contracts(
534
+ unseen,
535
+ engine=active_engine,
536
+ rpc_url=self.rpc_url,
537
+ require_high_risk_for_llm=self.require_high_risk_for_llm,
538
+ )
539
+
540
+ results: List[Dict[str, Any]] = []
541
+ for r in audited:
542
+ resp: FinalAgentResponse = r["response"]
543
+ addr = r["contract_address"]
544
+ high_risk_sigs = [
545
+ s["signature"]
546
+ for s in r.get("selectors", [])
547
+ if is_high_risk_signature(s.get("signature", ""))
548
+ ]
549
+ results.append({
550
+ "channel": "base_blocks",
551
+ "target": addr,
552
+ "target_address": addr,
553
+ "label": f"Block {r.get('block_number')} Deploy",
554
+ "risk_score": float(r.get("risk_score", 0.0)),
555
+ "decision": r.get("recommendation", "APPROVE"),
556
+ "llm_invoked": bool(resp.llm_invoked),
557
+ "flags": high_risk_sigs,
558
+ "source": "block_scanner",
559
+ "rule_id": resp.rule_id,
560
+ "response": resp,
561
+ })
562
+ return results
563
+
564
+ async def hunt_dex_pools(
565
+ self,
566
+ blocks: int = 20,
567
+ limit: int = 2,
568
+ w3: Optional[Any] = None,
569
+ dry_run: bool = False,
570
+ engine: Optional[ConditionAgentEngine] = None,
571
+ ) -> List[Dict[str, Any]]:
572
+ """Channel 2: Monitors Aerodrome & Uniswap v3 PoolCreated events on Base Mainnet."""
573
+ if limit <= 0:
574
+ return []
575
+
576
+ active_engine = engine or self._get_engine(dry_run=dry_run)
577
+
578
+ if dry_run and w3 is None:
579
+ discovered = get_curated_mock_pools()
580
+ else:
581
+ target_w3 = w3 if w3 is not None else AsyncWeb3(AsyncHTTPProvider(self.rpc_url))
582
+ try:
583
+ latest_block = await get_latest_block_number(target_w3)
584
+ from_block = max(0, latest_block - max(1, blocks) + 1)
585
+ discovered = await scan_pool_events(
586
+ target_w3, from_block=from_block, to_block=latest_block, limit=max(limit * 2, limit)
587
+ )
588
+ except Exception as exc:
589
+ logger.warning(f"[dex_pools] Failed to scan DEX pool events: {exc}")
590
+ return []
591
+
592
+ unseen: List[Dict[str, Any]] = []
593
+ for item in discovered:
594
+ tok = item.get("target_token")
595
+ if not tok or not Web3.is_address(tok):
596
+ continue
597
+ chk = Web3.to_checksum_address(tok)
598
+ if self._is_seen(chk.lower()):
599
+ continue
600
+ self._mark_seen(chk.lower())
601
+ unseen.append(item)
602
+ if len(unseen) >= limit:
603
+ break
604
+
605
+ if not unseen:
606
+ return []
607
+
608
+ audited = await audit_discovered_pools(
609
+ unseen, engine=active_engine, rpc_url=self.rpc_url
610
+ )
611
+
612
+ results: List[Dict[str, Any]] = []
613
+ for r in audited:
614
+ resp: FinalAgentResponse = r["response"]
615
+ tok = r["target_token"]
616
+ results.append({
617
+ "channel": "dex_pools",
618
+ "target": tok,
619
+ "target_address": tok,
620
+ "label": f"{r.get('dex', 'DEX')} {r.get('pair', '')}".strip(),
621
+ "risk_score": float(r.get("risk_score", 0.0)),
622
+ "decision": r.get("decision", "APPROVE"),
623
+ "llm_invoked": bool(resp.llm_invoked),
624
+ "flags": list(r.get("honeypot_flags", [])),
625
+ "source": "dex_pool_monitor",
626
+ "rule_id": resp.rule_id,
627
+ "response": resp,
628
+ })
629
+ return results
630
+
631
+ async def hunt_geckoterminal_base(
632
+ self,
633
+ limit: int = 3,
634
+ dry_run: bool = False,
635
+ engine: Optional[ConditionAgentEngine] = None,
636
+ ) -> List[Dict[str, Any]]:
637
+ """Channel 3: Queries GeckoTerminal New Pools public API for newly listed Base tokens."""
638
+ if limit <= 0:
639
+ return []
640
+
641
+ active_engine = engine or self._get_engine(dry_run=dry_run)
642
+
643
+ if dry_run:
644
+ synthetic_items = [
645
+ {
646
+ "id": "base_0xaa11111111111111111111111111111111111111",
647
+ "attributes": {"name": "BASECLEAN / WETH", "address": "0xaa11111111111111111111111111111111111111"},
648
+ "relationships": {
649
+ "base_token": {"data": {"id": "base_0x9a11111111111111111111111111111111111111"}}
650
+ },
651
+ "_mock_bytecode": _BENIGN_ERC20_BYTECODE,
652
+ },
653
+ {
654
+ "id": "base_0xaa22222222222222222222222222222222222222",
655
+ "attributes": {"name": "RUGPEPE / USDC", "address": "0xaa22222222222222222222222222222222222222"},
656
+ "relationships": {
657
+ "base_token": {"data": {"id": "base_0x9a22222222222222222222222222222222222222"}}
658
+ },
659
+ "_mock_bytecode": _HONEYPOT_UPGRADEABLE_BYTECODE,
660
+ },
661
+ ]
662
+ items = synthetic_items[:limit]
663
+ else:
664
+ try:
665
+ payload = await self._http_get_json(
666
+ GECKOTERMINAL_NEW_POOLS_URL, headers=GECKOTERMINAL_HEADERS
667
+ )
668
+ items = payload.get("data", []) if isinstance(payload, dict) else []
669
+ except Exception as exc:
670
+ logger.warning(f"[geckoterminal_base] API fetch failed: {exc}")
671
+ return []
672
+
673
+ results: List[Dict[str, Any]] = []
674
+ for item in items:
675
+ if len(results) >= limit:
676
+ break
677
+ token_addr = _extract_geckoterminal_token_address(item)
678
+ if not token_addr:
679
+ continue
680
+
681
+ attrs = item.get("attributes") if isinstance(item.get("attributes"), dict) else {}
682
+ pool_name = str(attrs.get("name") or f"Pool {token_addr[:10]}")
683
+ pool_addr = str(attrs.get("address") or "")
684
+ bytecode_override = item.get("_mock_bytecode") if dry_run else None
685
+
686
+ audited = await self._audit_discovered_token(
687
+ token_address=token_addr,
688
+ channel="geckoterminal_base",
689
+ source="hunter_geckoterminal",
690
+ source_prefix="hunter-gt",
691
+ label=pool_name,
692
+ active_engine=active_engine,
693
+ bytecode_override=bytecode_override,
694
+ extra_context={"pool_address": pool_addr, "pool_name": pool_name},
695
+ )
696
+ if audited is not None:
697
+ results.append(audited)
698
+
699
+ return results
700
+
701
+ async def hunt_dexscreener_base(
702
+ self,
703
+ limit: int = 3,
704
+ dry_run: bool = False,
705
+ engine: Optional[ConditionAgentEngine] = None,
706
+ ) -> List[Dict[str, Any]]:
707
+ """Channel 4: Queries DexScreener Latest Token Profiles filtered to Base chain."""
708
+ if limit <= 0:
709
+ return []
710
+
711
+ active_engine = engine or self._get_engine(dry_run=dry_run)
712
+
713
+ if dry_run:
714
+ raw_items = [
715
+ {
716
+ "chainId": "solana",
717
+ "tokenAddress": "So11111111111111111111111111111111111111112",
718
+ "description": "Filtered non-EVM chain item",
719
+ },
720
+ {
721
+ "chainId": "base",
722
+ "tokenAddress": "0x8b11111111111111111111111111111111111111",
723
+ "header": "SafeBaseToken",
724
+ "description": "Standard ERC-20 liquidity token on Base",
725
+ "_mock_bytecode": _BENIGN_ERC20_BYTECODE,
726
+ },
727
+ {
728
+ "chainId": "base",
729
+ "tokenAddress": "0x8b22222222222222222222222222222222222222",
730
+ "header": "HoneypotProxyToken",
731
+ "description": "Newly boosted Base token with hidden tax/upgrade",
732
+ "_mock_bytecode": _HONEYPOT_UPGRADEABLE_BYTECODE,
733
+ },
734
+ ]
735
+ else:
736
+ try:
737
+ payload = await self._http_get_json(DEXSCREENER_TOKEN_PROFILES_URL)
738
+ if isinstance(payload, list):
739
+ raw_items = payload
740
+ elif isinstance(payload, dict):
741
+ raw_items = payload.get("profiles") or payload.get("data") or []
742
+ else:
743
+ raw_items = []
744
+ except Exception as exc:
745
+ logger.warning(f"[dexscreener_base] API fetch failed: {exc}")
746
+ return []
747
+
748
+ results: List[Dict[str, Any]] = []
749
+ for item in raw_items:
750
+ if len(results) >= limit:
751
+ break
752
+ if not isinstance(item, dict):
753
+ continue
754
+ if str(item.get("chainId", "")).lower() != "base":
755
+ continue
756
+
757
+ token_addr = str(item.get("tokenAddress") or "").strip()
758
+ if not Web3.is_address(token_addr):
759
+ continue
760
+
761
+ label = str(
762
+ item.get("header")
763
+ or item.get("symbol")
764
+ or item.get("url")
765
+ or f"DexScreener {token_addr[:10]}"
766
+ )
767
+ bytecode_override = item.get("_mock_bytecode") if dry_run else None
768
+
769
+ audited = await self._audit_discovered_token(
770
+ token_address=token_addr,
771
+ channel="dexscreener_base",
772
+ source="hunter_dexscreener",
773
+ source_prefix="hunter-ds",
774
+ label=label,
775
+ active_engine=active_engine,
776
+ bytecode_override=bytecode_override,
777
+ extra_context={
778
+ "dexscreener_url": item.get("url"),
779
+ "profile_description": item.get("description"),
780
+ },
781
+ )
782
+ if audited is not None:
783
+ results.append(audited)
784
+
785
+ return results
786
+
787
+ async def hunt_snapshot_daos(
788
+ self,
789
+ limit: int = 2,
790
+ dry_run: bool = False,
791
+ engine: Optional[ConditionAgentEngine] = None,
792
+ ) -> List[Dict[str, Any]]:
793
+ """Channel 5: Fetches Snapshot DAO proposals with on-chain targets and audits them."""
794
+ if limit <= 0:
795
+ return []
796
+
797
+ active_engine = engine or self._get_engine(dry_run=dry_run)
798
+ connector = SnapshotGovernanceConnector(default_chain_id=ChainId.BASE_MAINNET)
799
+
800
+ if dry_run:
801
+ proposals = get_curated_dao_proposals(
802
+ default_chain_id=ChainId.BASE_MAINNET, limit=max(limit, 3)
803
+ )
804
+ else:
805
+ try:
806
+ proposals = await connector.fetch_proposals(
807
+ limit=limit, use_curated_fallback=True
808
+ )
809
+ except Exception as exc:
810
+ logger.warning(f"[snapshot_daos] Fetch failed: {exc}")
811
+ return []
812
+
813
+ results: List[Dict[str, Any]] = []
814
+ for prop in proposals:
815
+ if len(results) >= limit:
816
+ break
817
+ seen_key = f"snapshot:{prop.proposal_id.lower()}"
818
+ if self._is_seen(seen_key):
819
+ continue
820
+ self._mark_seen(seen_key)
821
+
822
+ if dry_run:
823
+ chain_val = (
824
+ prop.chain_id.value
825
+ if hasattr(prop.chain_id, "value")
826
+ else int(prop.chain_id)
827
+ )
828
+ ChainInspector._set_bytecode_cache(
829
+ f"{chain_val}:{prop.target_address}", _BENIGN_ERC20_BYTECODE
830
+ )
831
+
832
+ payload = connector.proposal_to_rule_payload(prop)
833
+ try:
834
+ resp = await active_engine.process_rule(payload, source="hunter_snapshot")
835
+ except Exception as exc:
836
+ logger.error(f"[snapshot_daos] Audit failed for {prop.proposal_id}: {exc}")
837
+ continue
838
+
839
+ sem = resp.semantic_Evaluation
840
+ decision = (
841
+ sem.recommended_action
842
+ if sem is not None
843
+ else ("APPROVE" if resp.deterministic_check.passed else "REJECT")
844
+ )
845
+ risk_score = (
846
+ float(sem.risk_score)
847
+ if sem is not None
848
+ else (0.0 if resp.deterministic_check.passed else 10.0)
849
+ )
850
+ flags = list(sem.flagged_issues) if sem else []
851
+
852
+ results.append({
853
+ "channel": "snapshot_daos",
854
+ "target": f"{prop.space_id}:{prop.proposal_id}",
855
+ "target_address": prop.target_address,
856
+ "label": prop.title,
857
+ "risk_score": risk_score,
858
+ "decision": decision,
859
+ "llm_invoked": bool(resp.llm_invoked),
860
+ "flags": flags,
861
+ "source": "hunter_snapshot",
862
+ "rule_id": payload.rule_id,
863
+ "response": resp,
864
+ "proposal": prop,
865
+ })
866
+
867
+ return results
868
+
869
+ async def _dispatch_high_risk_alerts(self, results: List[Dict[str, Any]]) -> int:
870
+ """Safely dispatches webhook alerts for findings with risk_score >= 8.0 or decision == REJECT."""
871
+ if not self.webhook_url:
872
+ return 0
873
+
874
+ high_risk_items = [
875
+ r for r in results
876
+ if float(r.get("risk_score", 0.0)) >= 8.0 or r.get("decision") == "REJECT"
877
+ ]
878
+ if not high_risk_items:
879
+ return 0
880
+
881
+ sent = 0
882
+ try:
883
+ dispatcher = WebhookAlertDispatcher(
884
+ webhook_url=self.webhook_url,
885
+ public_api_url=self.public_api_url,
886
+ client=self.http_client,
887
+ )
888
+ for item in high_risk_items:
889
+ resp = item.get("response")
890
+ if not isinstance(resp, FinalAgentResponse):
891
+ continue
892
+ target_addr = item.get("target_address") or "0x0000000000000000000000000000000000000000"
893
+ if not Web3.is_address(str(target_addr)):
894
+ target_addr = "0x0000000000000000000000000000000000000000"
895
+ proposal = item.get("proposal")
896
+ if not isinstance(proposal, GovernanceProposal):
897
+ proposal = GovernanceProposal(
898
+ proposal_id=str(item.get("rule_id") or item.get("target")),
899
+ space_id=f"hunter:{item.get('channel', 'unknown')}",
900
+ title=str(item.get("label") or item.get("target")),
901
+ body=(
902
+ f"Autonomous discovery alert on channel {item.get('channel')}. "
903
+ f"Flags: {', '.join(item.get('flags', [])) or 'High risk detected'}."
904
+ ),
905
+ author="0x0000000000000000000000000000000000000000",
906
+ state="active",
907
+ created=int(time.time()),
908
+ target_address=Web3.to_checksum_address(target_addr),
909
+ calldata="0x",
910
+ tx_value_wei=0,
911
+ chain_id=ChainId.BASE_MAINNET,
912
+ )
913
+ report = GovernanceAuditReport(
914
+ proposal=proposal,
915
+ rule_id=str(item.get("rule_id") or resp.rule_id),
916
+ agent_response=resp,
917
+ alert_level="CRITICAL",
918
+ )
919
+ if await dispatcher.dispatch_alert(report):
920
+ sent += 1
921
+ except Exception as exc:
922
+ logger.warning(f"Failed to dispatch high-risk webhook alert: {exc}")
923
+ return sent
924
+
925
+ async def run_hunt_cycle(
926
+ self,
927
+ channels: Optional[List[str]] = None,
928
+ limit_per_channel: int = 2,
929
+ dry_run: bool = False,
930
+ ) -> Dict[str, Any]:
931
+ """
932
+ Orchestrates one complete discovery & audit cycle across the selected channels.
933
+ Returns a structured summary dictionary with per-channel breakdowns and flat results.
934
+ """
935
+ selected = list(SUPPORTED_CHANNELS) if channels is None else list(channels)
936
+ for ch in selected:
937
+ if ch not in SUPPORTED_CHANNELS:
938
+ raise ValueError(
939
+ f"Unsupported discovery channel '{ch}'. Supported: {', '.join(SUPPORTED_CHANNELS)}"
940
+ )
941
+
942
+ active_engine = self._get_engine(dry_run=dry_run)
943
+
944
+ channel_runners = {
945
+ "base_blocks": lambda: self.hunt_base_blocks(
946
+ blocks=2, limit=limit_per_channel, dry_run=dry_run, engine=active_engine
947
+ ),
948
+ "dex_pools": lambda: self.hunt_dex_pools(
949
+ blocks=20, limit=limit_per_channel, dry_run=dry_run, engine=active_engine
950
+ ),
951
+ "geckoterminal_base": lambda: self.hunt_geckoterminal_base(
952
+ limit=limit_per_channel, dry_run=dry_run, engine=active_engine
953
+ ),
954
+ "dexscreener_base": lambda: self.hunt_dexscreener_base(
955
+ limit=limit_per_channel, dry_run=dry_run, engine=active_engine
956
+ ),
957
+ "snapshot_daos": lambda: self.hunt_snapshot_daos(
958
+ limit=limit_per_channel, dry_run=dry_run, engine=active_engine
959
+ ),
960
+ }
961
+
962
+ async def _safe_run(channel_name: str) -> Tuple[str, List[Dict[str, Any]]]:
963
+ try:
964
+ items = await channel_runners[channel_name]()
965
+ return channel_name, items
966
+ except Exception as exc:
967
+ logger.warning(f"[{channel_name}] Channel hunt failed: {exc}")
968
+ return channel_name, []
969
+
970
+ channel_outputs = await asyncio.gather(*(_safe_run(ch) for ch in selected))
971
+
972
+ by_channel: Dict[str, Dict[str, Any]] = {}
973
+ all_results: List[Dict[str, Any]] = []
974
+ high_risk_count = 0
975
+
976
+ for ch, ch_results in channel_outputs:
977
+ ch_high = sum(
978
+ 1
979
+ for r in ch_results
980
+ if float(r.get("risk_score", 0.0)) >= 8.0 or r.get("decision") == "REJECT"
981
+ )
982
+ high_risk_count += ch_high
983
+ by_channel[ch] = {
984
+ "discovered": len(ch_results),
985
+ "audited": len(ch_results),
986
+ "high_risk": ch_high,
987
+ "results": ch_results,
988
+ }
989
+ all_results.extend(ch_results)
990
+
991
+ if self.webhook_url and high_risk_count > 0:
992
+ await self._dispatch_high_risk_alerts(all_results)
993
+
994
+ return {
995
+ "total_discovered": len(all_results),
996
+ "total_audited": len(all_results),
997
+ "high_risk_count": high_risk_count,
998
+ "by_channel": by_channel,
999
+ "results": all_results,
1000
+ }