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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
src/source_resolver.py ADDED
@@ -0,0 +1,792 @@
1
+ """
2
+ Proxy & Verified Source Resolver for Web3 Condition-Action Trigger Agent.
3
+
4
+ Provides automated resolution of smart contract source code and proxy implementation state:
5
+ 1. EIP-1967 storage slot inspection (implementation, admin, and beacon slots).
6
+ 2. On-chain probing for administrative owner() and paused() contract state.
7
+ 3. Multi-provider verified source code retrieval (Sourcify API with zero API keys,
8
+ and Etherscan v2 API fallback for multi-file standard JSON and single-file sources).
9
+ 4. Automated 4-byte selector extraction from implementation bytecode.
10
+ 5. Generation of high-risk security warnings (unverified source, upgradeable proxy, paused state).
11
+
12
+ Typical usage:
13
+ resolver = ContractSourceResolver()
14
+ audit_context = await resolver.resolve_full_audit_context(
15
+ chain_id=8453,
16
+ target_address="0x..."
17
+ )
18
+ print(audit_context["proxy_info"]["is_proxy"])
19
+ print(audit_context["source_info"]["verified"])
20
+ print(audit_context["security_warnings"])
21
+ """
22
+
23
+ import asyncio
24
+ import json
25
+ import logging
26
+ import os
27
+ import re
28
+ import sys
29
+ import time
30
+ from typing import Dict, Any, Optional, List, Tuple, Union
31
+
32
+ import httpx
33
+ from web3 import Web3, AsyncWeb3
34
+ from web3.exceptions import Web3Exception
35
+
36
+ # Ensure module search paths support running directly or as a package
37
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
38
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
39
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
40
+ _SCRIPTS_DIR = os.path.join(_ROOT_DIR, "scripts")
41
+ for _p in (_ROOT_DIR, _SRC_DIR, _SCRIPTS_DIR):
42
+ if _p not in sys.path:
43
+ sys.path.insert(0, _p)
44
+
45
+ try:
46
+ from src.chain_inspector import ChainInspector
47
+ except ImportError:
48
+ from chain_inspector import ChainInspector
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ # Standard EIP-1967 storage slots
53
+ EIP1967_IMPLEMENTATION_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
54
+ EIP1967_ADMIN_SLOT = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103"
55
+ EIP1967_BEACON_SLOT = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50"
56
+
57
+ # Standard 4-byte function selectors
58
+ SELECTOR_OWNER = "0x8da5cb5b" # owner()
59
+ SELECTOR_PAUSED = "0x5c975abb" # paused()
60
+ SELECTOR_IMPLEMENTATION = "0x5c60da1b" # implementation()
61
+
62
+ # Maximum character budget for source code input into downstream LLM prompts
63
+ MAX_SOURCE_CHARS = 24000
64
+
65
+ # Canonical EVM dispatcher opcode pattern (PUSH4 <sel> EQ)
66
+ DISPATCHER_REGEX = re.compile(r"(?:63|8063|8263)([0-9a-fA-F]{8})14", re.IGNORECASE)
67
+
68
+ KNOWN_SELECTORS: Dict[str, str] = {
69
+ # ERC20 / ERC721 Standard
70
+ "0xa9059cbb": "transfer(address,uint256)",
71
+ "0x095ea7b3": "approve(address,uint256)",
72
+ "0x23b872dd": "transferFrom(address,address,uint256)",
73
+ "0x70a08231": "balanceOf(address)",
74
+ "0x18160ddd": "totalSupply()",
75
+ "0xdd62ed3e": "allowance(address,address)",
76
+ # Ownership & Access Control
77
+ "0x8da5cb5b": "owner()",
78
+ "0xf2fde38b": "transferOwnership(address)",
79
+ "0x715018a6": "renounceOwnership()",
80
+ # Minting & Burning
81
+ "0x40c10f19": "mint(address,uint256)",
82
+ "0xa0712d68": "mint(uint256)",
83
+ "0x42966c68": "burn(uint256)",
84
+ "0x79cc6790": "burnFrom(address,uint256)",
85
+ # Upgradability & Proxies
86
+ "0x3659cfe6": "upgradeTo(address)",
87
+ "0x4f1ef286": "upgradeToAndCall(address,bytes)",
88
+ "0x52d19004": "implementation()",
89
+ "0x5c60da1b": "implementation()",
90
+ # Pausability
91
+ "0x4fbee1e3": "pause()",
92
+ "0x8456cb59": "unpause()",
93
+ "0x5c975abb": "paused()",
94
+ # Destruction / High Risk
95
+ "0x83197ef0": "destroy(address)",
96
+ "0x41c0e1b5": "kill()",
97
+ "0x00f714ce": "selfdestruct()",
98
+ # Vaults / Wrapped Assets
99
+ "0xd0e30db0": "deposit()",
100
+ "0x2e1a7d4d": "withdraw(uint256)",
101
+ }
102
+
103
+
104
+ def _extract_address_from_word(raw_bytes_or_hex: Union[bytes, str]) -> Optional[str]:
105
+ """
106
+ Parses a 32-byte storage word or eth_call return value.
107
+ If the last 20 bytes are non-zero and represent a valid EVM address,
108
+ returns Web3.to_checksum_address("0x" + addr_hex). Otherwise returns None.
109
+ """
110
+ if raw_bytes_or_hex is None:
111
+ return None
112
+
113
+ if isinstance(raw_bytes_or_hex, (bytes, bytearray)):
114
+ hex_str = raw_bytes_or_hex.hex()
115
+ else:
116
+ hex_str = str(raw_bytes_or_hex).strip()
117
+ if hex_str.startswith(("0x", "0X")):
118
+ hex_str = hex_str[2:]
119
+
120
+ hex_str = hex_str.strip()
121
+ if len(hex_str) < 40:
122
+ return None
123
+
124
+ addr_hex = hex_str[-40:]
125
+ try:
126
+ if int(addr_hex, 16) == 0:
127
+ return None
128
+ return Web3.to_checksum_address("0x" + addr_hex)
129
+ except Exception:
130
+ return None
131
+
132
+
133
+ def _sol_sort_key(item: Tuple[str, str]) -> Tuple[int, str]:
134
+ """Sort key prioritizing primary contract code over libraries, interfaces, and mocks."""
135
+ path, _ = item
136
+ lower = path.lower()
137
+ is_aux = (
138
+ "/interfaces/" in lower
139
+ or "/libraries/" in lower
140
+ or "/interface/" in lower
141
+ or "/library/" in lower
142
+ or "/node_modules/" in lower
143
+ or "/mock/" in lower
144
+ or "/mocks/" in lower
145
+ or os.path.basename(lower).startswith("i")
146
+ or "interface" in lower
147
+ or "library" in lower
148
+ )
149
+ return (1 if is_aux else 0, path)
150
+
151
+
152
+ def _format_and_truncate_sol_files(
153
+ sol_files: List[Tuple[str, str]], max_chars: int = MAX_SOURCE_CHARS
154
+ ) -> Tuple[str, bool]:
155
+ """Formats multiple Solidity files with comment banners and truncates cleanly at max_chars."""
156
+ formatted_parts: List[str] = []
157
+ total_chars = 0
158
+ truncated = False
159
+
160
+ for path, content in sol_files:
161
+ header = f"// File: {path}\n"
162
+ body = content.strip()
163
+ block = f"{header}{body}\n\n"
164
+
165
+ if total_chars + len(block) > max_chars:
166
+ remaining = max_chars - total_chars - len(header) - 30
167
+ if remaining > 50:
168
+ truncated_body = body[:remaining] + "\n// ... [TRUNCATED]"
169
+ formatted_parts.append(f"{header}{truncated_body}\n\n")
170
+ truncated = True
171
+ break
172
+ else:
173
+ formatted_parts.append(block)
174
+ total_chars += len(block)
175
+
176
+ combined = "".join(formatted_parts).strip()
177
+ if len(combined) > max_chars:
178
+ combined = combined[:max_chars]
179
+ truncated = True
180
+
181
+ return combined, truncated
182
+
183
+
184
+ def _extract_contract_names(
185
+ sol_files: List[Tuple[str, str]], initial_names: Optional[List[str]] = None
186
+ ) -> List[str]:
187
+ """Extracts contract, interface, and library names from Solidity files."""
188
+ names: List[str] = []
189
+ if initial_names:
190
+ for n in initial_names:
191
+ if n and n not in names:
192
+ names.append(n)
193
+
194
+ for path, content in sol_files:
195
+ base = os.path.basename(path)
196
+ if base.endswith(".sol"):
197
+ base = base[:-4]
198
+ if base and base not in names:
199
+ names.append(base)
200
+ for c in re.findall(r"\b(?:contract|interface|library)\s+([A-Za-z0-9_]+)\b", content):
201
+ if c not in names:
202
+ names.append(c)
203
+ return names
204
+
205
+
206
+ def extract_selectors_from_bytecode(
207
+ bytecode: Union[bytes, str],
208
+ tx_input: Optional[Union[bytes, str]] = None,
209
+ ) -> List[Dict[str, Any]]:
210
+ """
211
+ Extracts 4-byte function selectors from smart contract bytecode and deployment calldata.
212
+ Identifies known signatures and flags privileged or high-risk capabilities.
213
+ """
214
+ if not bytecode:
215
+ return []
216
+
217
+ if isinstance(bytecode, bytes):
218
+ bytecode_hex = bytecode.hex()
219
+ else:
220
+ bytecode_hex = bytecode[2:] if bytecode.startswith(("0x", "0X")) else bytecode
221
+
222
+ found: Dict[str, Dict[str, Any]] = {}
223
+ bytecode_lower = bytecode_hex.lower()
224
+
225
+ # 1. Search known selectors directly within bytecode
226
+ for sel_hex, sig in KNOWN_SELECTORS.items():
227
+ clean_sel = sel_hex[2:].lower()
228
+ if clean_sel in bytecode_lower:
229
+ found[sel_hex] = {
230
+ "selector": sel_hex,
231
+ "signature": sig,
232
+ "known": True,
233
+ }
234
+
235
+ # 2. Extract selectors from standard EVM dispatcher opcodes (PUSH4 <sel> EQ)
236
+ for m in DISPATCHER_REGEX.findall(bytecode_hex):
237
+ sel_hex = f"0x{m.lower()}"
238
+ if sel_hex not in found:
239
+ sig = KNOWN_SELECTORS.get(sel_hex, f"unknown({sel_hex})")
240
+ found[sel_hex] = {
241
+ "selector": sel_hex,
242
+ "signature": sig,
243
+ "known": sel_hex in KNOWN_SELECTORS,
244
+ }
245
+
246
+ # 3. If tx_input is provided, inspect initialization calldata
247
+ if tx_input:
248
+ if isinstance(tx_input, bytes):
249
+ input_hex = tx_input.hex()
250
+ else:
251
+ input_hex = tx_input[2:] if tx_input.startswith(("0x", "0X")) else tx_input
252
+ input_lower = input_hex.lower()
253
+ for sel_hex, sig in KNOWN_SELECTORS.items():
254
+ clean_sel = sel_hex[2:].lower()
255
+ if clean_sel in input_lower and sel_hex not in found:
256
+ found[sel_hex] = {
257
+ "selector": sel_hex,
258
+ "signature": sig,
259
+ "known": True,
260
+ }
261
+
262
+ return list(found.values())
263
+
264
+
265
+ class ContractSourceResolver:
266
+ """
267
+ Resolves smart contract source code and proxy implementation state.
268
+ Supports EIP-1967 proxy patterns (storage slot inspection), owner/paused state probing,
269
+ and multi-provider verified source code retrieval (Sourcify and Etherscan v2 API).
270
+ """
271
+
272
+ def __init__(
273
+ self,
274
+ rpc_url: Optional[Union[str, List[str]]] = None,
275
+ http_client: Optional[httpx.AsyncClient] = None,
276
+ timeout: float = 8.0,
277
+ source_cache_ttl_seconds: float = 3600.0,
278
+ source_cache_max_entries: int = 512,
279
+ ):
280
+ self.rpc_url = rpc_url
281
+ self.http_client = http_client
282
+ self.timeout = timeout
283
+ self.source_cache_ttl_seconds = source_cache_ttl_seconds
284
+ self.source_cache_max_entries = source_cache_max_entries
285
+ self._source_cache: Dict[str, Tuple[float, Dict[str, Any]]] = {}
286
+
287
+ @staticmethod
288
+ def _copy_source_result(result: Dict[str, Any]) -> Dict[str, Any]:
289
+ """Return a shallow copy of a source result dict with a copied contract_names list."""
290
+ copied = dict(result)
291
+ if "contract_names" in copied and isinstance(copied["contract_names"], list):
292
+ copied["contract_names"] = list(copied["contract_names"])
293
+ return copied
294
+
295
+ def _store_source_cache(self, cache_key: str, result: Dict[str, Any]) -> None:
296
+ """Cache a verified source result using bounded FIFO eviction."""
297
+ if (
298
+ result.get("verified") is True
299
+ and self.source_cache_ttl_seconds > 0
300
+ and self.source_cache_max_entries > 0
301
+ ):
302
+ while (
303
+ len(self._source_cache) >= self.source_cache_max_entries
304
+ and cache_key not in self._source_cache
305
+ ):
306
+ oldest_key = next(iter(self._source_cache))
307
+ self._source_cache.pop(oldest_key, None)
308
+ self._source_cache[cache_key] = (
309
+ time.monotonic(),
310
+ self._copy_source_result(result),
311
+ )
312
+
313
+ async def _get_request(
314
+ self, url: str, params: Optional[Dict[str, Any]] = None
315
+ ) -> Optional[httpx.Response]:
316
+ """Internal helper for performing async HTTP GET requests with fallback client management."""
317
+ try:
318
+ if self.http_client is not None:
319
+ return await self.http_client.get(url, params=params, timeout=self.timeout)
320
+ else:
321
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
322
+ return await client.get(url, params=params)
323
+ except Exception as exc:
324
+ logger.debug(f"HTTP GET request to {url} failed: {exc}")
325
+ return None
326
+
327
+ async def resolve_proxy_and_state(
328
+ self, chain_id: int, target_address: str
329
+ ) -> Dict[str, Any]:
330
+ """
331
+ Inspects on-chain storage slots and runtime state for proxy patterns, admin ownership,
332
+ and paused status using AsyncWeb3.
333
+ """
334
+ checksum_addr = Web3.to_checksum_address(target_address)
335
+
336
+ try:
337
+ rpc_urls = ChainInspector.resolve_rpc_urls(chain_id, self.rpc_url)
338
+ except Exception as exc:
339
+ logger.warning(f"Failed to resolve RPC URLs for chain {chain_id}: {exc}")
340
+ return {
341
+ "target_address": checksum_addr,
342
+ "chain_id": chain_id,
343
+ "is_proxy": False,
344
+ "implementation_address": None,
345
+ "admin_address": None,
346
+ "beacon_address": None,
347
+ "owner_address": None,
348
+ "is_paused": None,
349
+ "effective_audit_address": checksum_addr,
350
+ "implementation_bytecode_size": 0,
351
+ "rpc_error": str(exc),
352
+ }
353
+
354
+ last_exc: Optional[Exception] = None
355
+ for i, url in enumerate(rpc_urls):
356
+ try:
357
+ w3 = ChainInspector._get_or_create_w3(chain_id, url)
358
+
359
+ # Concurrent storage slot reads for EIP-1967 pointers
360
+ slots_res = await asyncio.gather(
361
+ w3.eth.get_storage_at(checksum_addr, EIP1967_IMPLEMENTATION_SLOT),
362
+ w3.eth.get_storage_at(checksum_addr, EIP1967_ADMIN_SLOT),
363
+ w3.eth.get_storage_at(checksum_addr, EIP1967_BEACON_SLOT),
364
+ return_exceptions=True,
365
+ )
366
+
367
+ # If all 3 slot reads failed with exceptions, treat as RPC network failure
368
+ if all(isinstance(r, Exception) for r in slots_res):
369
+ raise slots_res[0]
370
+
371
+ impl_raw, admin_raw, beacon_raw = slots_res
372
+ impl_addr = (
373
+ _extract_address_from_word(impl_raw)
374
+ if not isinstance(impl_raw, Exception)
375
+ else None
376
+ )
377
+ admin_addr = (
378
+ _extract_address_from_word(admin_raw)
379
+ if not isinstance(admin_raw, Exception)
380
+ else None
381
+ )
382
+ beacon_addr = (
383
+ _extract_address_from_word(beacon_raw)
384
+ if not isinstance(beacon_raw, Exception)
385
+ else None
386
+ )
387
+
388
+ is_proxy = False
389
+ if impl_addr:
390
+ is_proxy = True
391
+ elif beacon_addr:
392
+ try:
393
+ beacon_call_res = await w3.eth.call({
394
+ "to": beacon_addr,
395
+ "data": SELECTOR_IMPLEMENTATION,
396
+ })
397
+ beacon_impl = _extract_address_from_word(beacon_call_res)
398
+ if beacon_impl:
399
+ impl_addr = beacon_impl
400
+ is_proxy = True
401
+ except Exception as b_exc:
402
+ logger.debug(
403
+ f"Calling implementation() on beacon {beacon_addr} failed: {b_exc}"
404
+ )
405
+
406
+ # Probe owner() and paused() on target contract
407
+ owner_addr: Optional[str] = None
408
+ is_paused: Optional[bool] = None
409
+
410
+ probe_res = await asyncio.gather(
411
+ w3.eth.call({"to": checksum_addr, "data": SELECTOR_OWNER}),
412
+ w3.eth.call({"to": checksum_addr, "data": SELECTOR_PAUSED}),
413
+ return_exceptions=True,
414
+ )
415
+ owner_raw, paused_raw = probe_res[0], probe_res[1]
416
+
417
+ if not isinstance(owner_raw, Exception):
418
+ owner_addr = _extract_address_from_word(owner_raw)
419
+
420
+ if not isinstance(paused_raw, Exception):
421
+ if isinstance(paused_raw, (bytes, bytearray)):
422
+ is_paused = bool(int.from_bytes(paused_raw, byteorder="big") != 0)
423
+ elif isinstance(paused_raw, str):
424
+ clean = paused_raw.strip()
425
+ if clean.startswith(("0x", "0X")):
426
+ clean = clean[2:]
427
+ if clean:
428
+ is_paused = bool(int(clean, 16) != 0)
429
+
430
+ # If is_proxy and implementation_address, fetch runtime bytecode
431
+ impl_code: Optional[bytes] = None
432
+ if is_proxy and impl_addr:
433
+ try:
434
+ code_res = await w3.eth.get_code(impl_addr)
435
+ if isinstance(code_res, (bytes, bytearray)):
436
+ impl_code = bytes(code_res)
437
+ elif isinstance(code_res, str):
438
+ clean = code_res.strip()
439
+ if clean.startswith(("0x", "0X")):
440
+ clean = clean[2:]
441
+ impl_code = bytes.fromhex(clean) if clean else b""
442
+ if impl_code is not None:
443
+ ChainInspector._set_bytecode_cache(
444
+ f"{chain_id}:{impl_addr}", impl_code
445
+ )
446
+ except Exception as c_exc:
447
+ logger.warning(
448
+ f"Failed to fetch implementation bytecode for {impl_addr}: {c_exc}"
449
+ )
450
+
451
+ return {
452
+ "target_address": checksum_addr,
453
+ "chain_id": chain_id,
454
+ "is_proxy": bool(is_proxy),
455
+ "implementation_address": impl_addr,
456
+ "admin_address": admin_addr,
457
+ "beacon_address": beacon_addr,
458
+ "owner_address": owner_addr,
459
+ "is_paused": is_paused,
460
+ "effective_audit_address": impl_addr or checksum_addr,
461
+ "implementation_bytecode_size": len(impl_code) if impl_code else 0,
462
+ "rpc_error": None,
463
+ }
464
+
465
+ except Exception as exc:
466
+ logger.warning(
467
+ f"RPC call failed for URL {url} (index {i}, chain {chain_id}): {exc}"
468
+ )
469
+ last_exc = exc
470
+ continue
471
+
472
+ # All RPC endpoints failed
473
+ return {
474
+ "target_address": checksum_addr,
475
+ "chain_id": chain_id,
476
+ "is_proxy": False,
477
+ "implementation_address": None,
478
+ "admin_address": None,
479
+ "beacon_address": None,
480
+ "owner_address": None,
481
+ "is_paused": None,
482
+ "effective_audit_address": checksum_addr,
483
+ "implementation_bytecode_size": 0,
484
+ "rpc_error": str(last_exc) if last_exc else "All RPC URLs failed",
485
+ }
486
+
487
+ async def fetch_verified_source(
488
+ self, chain_id: int, address: str
489
+ ) -> Dict[str, Any]:
490
+ """
491
+ Retrieves verified Solidity source code using Sourcify (free, no API key) with
492
+ fallback to Etherscan v2 API when API keys are configured.
493
+ """
494
+ checksum_addr = Web3.to_checksum_address(address)
495
+ cache_key = f"{chain_id}:{checksum_addr.lower()}"
496
+
497
+ cached_entry = self._source_cache.get(cache_key)
498
+ if cached_entry is not None:
499
+ cached_ts, cached_result = cached_entry
500
+ if (
501
+ self.source_cache_ttl_seconds > 0
502
+ and (time.monotonic() - cached_ts) < self.source_cache_ttl_seconds
503
+ ):
504
+ logger.debug("Source cache hit for %s", cache_key)
505
+ return self._copy_source_result(cached_result)
506
+ self._source_cache.pop(cache_key, None)
507
+
508
+ # ---------------------------------------------------------
509
+ # Step 1: Sourcify API (Free, zero API key required)
510
+ # ---------------------------------------------------------
511
+ sourcify_url = f"https://sourcify.dev/server/files/any/{chain_id}/{checksum_addr}"
512
+ resp = await self._get_request(sourcify_url)
513
+ if resp is not None and resp.status_code == 200:
514
+ try:
515
+ data = resp.json()
516
+ raw_files = data.get("files") if isinstance(data, dict) else (data if isinstance(data, list) else None)
517
+ sol_files: List[Tuple[str, str]] = []
518
+
519
+ if isinstance(raw_files, list):
520
+ for f in raw_files:
521
+ if isinstance(f, dict):
522
+ name = f.get("name") or f.get("path") or ""
523
+ content = f.get("content", "")
524
+ if (name.endswith(".sol") or ".sol" in name.lower()) and content:
525
+ sol_files.append((name, content))
526
+ elif isinstance(raw_files, dict):
527
+ for path, f in raw_files.items():
528
+ if isinstance(f, dict):
529
+ content = f.get("content", "")
530
+ else:
531
+ content = str(f)
532
+ if (path.endswith(".sol") or ".sol" in path.lower()) and content:
533
+ sol_files.append((path, content))
534
+
535
+ if sol_files:
536
+ sol_files.sort(key=_sol_sort_key)
537
+ contract_names = _extract_contract_names(sol_files)
538
+ combined_source, truncated = _format_and_truncate_sol_files(
539
+ sol_files, MAX_SOURCE_CHARS
540
+ )
541
+
542
+ result = {
543
+ "verified": True,
544
+ "provider": "sourcify",
545
+ "match_status": data.get("status", "full") if isinstance(data, dict) else "full",
546
+ "address": checksum_addr,
547
+ "files_count": len(sol_files),
548
+ "contract_names": contract_names,
549
+ "source_code": combined_source,
550
+ "truncated": truncated,
551
+ }
552
+ self._store_source_cache(cache_key, result)
553
+ return result
554
+ except Exception as exc:
555
+ logger.debug(f"Failed to parse Sourcify response for {checksum_addr}: {exc}")
556
+
557
+ # ---------------------------------------------------------
558
+ # Step 2: Etherscan v2 API Fallback
559
+ # ---------------------------------------------------------
560
+ api_key = (
561
+ os.getenv(f"ETHERSCAN_API_KEY_{chain_id}")
562
+ or (os.getenv("BASESCAN_API_KEY") if chain_id in (8453, 84532) else None)
563
+ or os.getenv("ETHERSCAN_API_KEY")
564
+ or os.getenv("BASESCAN_API_KEY")
565
+ )
566
+
567
+ if api_key:
568
+ etherscan_params = {
569
+ "chainid": chain_id,
570
+ "module": "contract",
571
+ "action": "getsourcecode",
572
+ "address": checksum_addr,
573
+ "apikey": api_key,
574
+ }
575
+ eth_resp = await self._get_request(
576
+ "https://api.etherscan.io/v2/api", params=etherscan_params
577
+ )
578
+ if eth_resp is not None and eth_resp.status_code == 200:
579
+ try:
580
+ eth_data = eth_resp.json()
581
+ if eth_data.get("status") == "1" and eth_data.get("result"):
582
+ results = eth_data.get("result")
583
+ if isinstance(results, list) and len(results) > 0:
584
+ first_res = results[0]
585
+ raw_source = first_res.get("SourceCode", "").strip()
586
+ contract_name = first_res.get("ContractName", "").strip()
587
+
588
+ if raw_source and raw_source != "Contract source code not verified":
589
+ # Try parsing Standard JSON Input format (double or single braced)
590
+ parsed_json = None
591
+ if raw_source.startswith("{{") and raw_source.endswith("}}"):
592
+ try:
593
+ parsed_json = json.loads(raw_source[1:-1])
594
+ except Exception:
595
+ pass
596
+ elif raw_source.startswith("{") and raw_source.endswith("}"):
597
+ try:
598
+ parsed_json = json.loads(raw_source)
599
+ except Exception:
600
+ pass
601
+
602
+ if parsed_json and isinstance(parsed_json, dict):
603
+ sources = parsed_json.get("sources", parsed_json)
604
+ sol_files: List[Tuple[str, str]] = []
605
+ if isinstance(sources, dict):
606
+ for f_path, f_info in sources.items():
607
+ if isinstance(f_info, dict):
608
+ c = f_info.get("content", "")
609
+ else:
610
+ c = str(f_info)
611
+ if (f_path.endswith(".sol") or ".sol" in f_path.lower()) and c:
612
+ sol_files.append((f_path, c))
613
+
614
+ if sol_files:
615
+ sol_files.sort(key=_sol_sort_key)
616
+ contract_names = _extract_contract_names(
617
+ sol_files,
618
+ initial_names=[contract_name] if contract_name else None,
619
+ )
620
+ combined_source, truncated = _format_and_truncate_sol_files(
621
+ sol_files, MAX_SOURCE_CHARS
622
+ )
623
+
624
+ result = {
625
+ "verified": True,
626
+ "provider": "etherscan_v2",
627
+ "match_status": "full",
628
+ "address": checksum_addr,
629
+ "files_count": len(sol_files),
630
+ "contract_names": contract_names,
631
+ "source_code": combined_source,
632
+ "truncated": truncated,
633
+ }
634
+ self._store_source_cache(cache_key, result)
635
+ return result
636
+
637
+ # Single-file raw Solidity source
638
+ contract_names = [contract_name] if contract_name else []
639
+ for c_name in re.findall(
640
+ r"\b(?:contract|interface|library)\s+([A-Za-z0-9_]+)\b",
641
+ raw_source,
642
+ ):
643
+ if c_name not in contract_names:
644
+ contract_names.append(c_name)
645
+
646
+ truncated = False
647
+ if len(raw_source) > MAX_SOURCE_CHARS:
648
+ combined_source = (
649
+ raw_source[:MAX_SOURCE_CHARS] + "\n// ... [TRUNCATED]"
650
+ )
651
+ if len(combined_source) > MAX_SOURCE_CHARS:
652
+ combined_source = combined_source[:MAX_SOURCE_CHARS]
653
+ truncated = True
654
+ else:
655
+ combined_source = raw_source
656
+
657
+ result = {
658
+ "verified": True,
659
+ "provider": "etherscan_v2",
660
+ "match_status": "full",
661
+ "address": checksum_addr,
662
+ "files_count": 1,
663
+ "contract_names": contract_names,
664
+ "source_code": combined_source,
665
+ "truncated": truncated,
666
+ }
667
+ self._store_source_cache(cache_key, result)
668
+ return result
669
+ except Exception as exc:
670
+ logger.debug(f"Failed to parse Etherscan response for {checksum_addr}: {exc}")
671
+
672
+ # ---------------------------------------------------------
673
+ # Step 3: Unverified Fallback
674
+ # ---------------------------------------------------------
675
+ return {
676
+ "verified": False,
677
+ "provider": None,
678
+ "address": checksum_addr,
679
+ "files_count": 0,
680
+ "contract_names": [],
681
+ "source_code": "",
682
+ "truncated": False,
683
+ }
684
+
685
+ async def resolve_full_audit_context(
686
+ self,
687
+ chain_id: int,
688
+ target_address: str,
689
+ resolve_proxy: bool = True,
690
+ fetch_source: bool = True,
691
+ ) -> Dict[str, Any]:
692
+ """
693
+ Coordinates full audit context resolution: proxy status, storage state,
694
+ verified source code, function selector extraction, and security warnings.
695
+ """
696
+ checksum_addr = Web3.to_checksum_address(target_address)
697
+
698
+ if resolve_proxy:
699
+ proxy_info = await self.resolve_proxy_and_state(chain_id, checksum_addr)
700
+ else:
701
+ proxy_info = {
702
+ "target_address": checksum_addr,
703
+ "chain_id": chain_id,
704
+ "is_proxy": False,
705
+ "implementation_address": None,
706
+ "admin_address": None,
707
+ "beacon_address": None,
708
+ "owner_address": None,
709
+ "is_paused": None,
710
+ "effective_audit_address": checksum_addr,
711
+ "implementation_bytecode_size": 0,
712
+ "rpc_error": None,
713
+ }
714
+
715
+ effective_audit_address = (
716
+ proxy_info.get("effective_audit_address") or checksum_addr
717
+ )
718
+
719
+ if fetch_source:
720
+ source_info = await self.fetch_verified_source(
721
+ chain_id, effective_audit_address
722
+ )
723
+ # If proxy and implementation source is not verified, check if proxy itself has source
724
+ if (
725
+ proxy_info.get("is_proxy")
726
+ and not source_info.get("verified")
727
+ and effective_audit_address != checksum_addr
728
+ ):
729
+ proxy_source = await self.fetch_verified_source(
730
+ chain_id, checksum_addr
731
+ )
732
+ if proxy_source.get("verified"):
733
+ source_info = proxy_source
734
+ else:
735
+ source_info = {
736
+ "verified": False,
737
+ "provider": None,
738
+ "address": effective_audit_address,
739
+ "files_count": 0,
740
+ "contract_names": [],
741
+ "source_code": "",
742
+ "truncated": False,
743
+ }
744
+
745
+ # Extract 4-byte selectors from implementation bytecode (if proxy)
746
+ effective_selectors: List[Dict[str, Any]] = []
747
+ target_code: Optional[bytes] = None
748
+
749
+ if proxy_info.get("is_proxy") and proxy_info.get("implementation_address"):
750
+ impl_key = f"{chain_id}:{proxy_info['implementation_address']}"
751
+ target_code = ChainInspector._bytecode_cache.get(impl_key)
752
+
753
+ if not target_code:
754
+ target_key = f"{chain_id}:{checksum_addr}"
755
+ target_code = ChainInspector._bytecode_cache.get(target_key)
756
+
757
+ if target_code:
758
+ effective_selectors = extract_selectors_from_bytecode(target_code)
759
+
760
+ security_warnings: List[str] = []
761
+ if not source_info.get("verified"):
762
+ security_warnings.append("Unverified contract source code")
763
+ if proxy_info.get("is_proxy"):
764
+ security_warnings.append("Upgradeable EIP-1967 proxy detected")
765
+ if proxy_info.get("is_paused") is True:
766
+ security_warnings.append("Contract is currently in paused state")
767
+ if proxy_info.get("admin_address"):
768
+ security_warnings.append(
769
+ f"Proxy admin configured: {proxy_info['admin_address']}"
770
+ )
771
+ if proxy_info.get("beacon_address"):
772
+ security_warnings.append(
773
+ f"Beacon proxy detected: {proxy_info['beacon_address']}"
774
+ )
775
+ if source_info.get("truncated"):
776
+ security_warnings.append(
777
+ "Verified source code truncated to character limit"
778
+ )
779
+ if proxy_info.get("rpc_error"):
780
+ security_warnings.append(
781
+ f"RPC error during proxy/state resolution: {proxy_info['rpc_error']}"
782
+ )
783
+
784
+ return {
785
+ "target_address": checksum_addr,
786
+ "chain_id": chain_id,
787
+ "effective_audit_address": effective_audit_address,
788
+ "proxy_info": proxy_info,
789
+ "source_info": source_info,
790
+ "effective_selectors": effective_selectors,
791
+ "security_warnings": security_warnings,
792
+ }