-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy_tracker.py
More file actions
1490 lines (1240 loc) · 54 KB
/
Copy pathdeploy_tracker.py
File metadata and controls
1490 lines (1240 loc) · 54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""contract-deploy-tracker: Track and analyze smart contract deployments across EVM chains.
Supports Ethereum, Base, Arbitrum, Optimism, and Polygon. Uses Etherscan-compatible
APIs and public RPC endpoints for block scanning and contract analysis.
"""
import csv
import hashlib
import io
import json
import os
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
import click
import requests
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
console = Console()
# ---------------------------------------------------------------------------
# Chain configuration
# ---------------------------------------------------------------------------
CHAINS = {
"ethereum": {
"name": "Ethereum",
"explorer_api": "https://api.etherscan.io/api",
"rpc": "https://eth.llamarpc.com",
"env_key": "ETHERSCAN_API_KEY",
"currency": "ETH",
"chain_id": 1,
},
"base": {
"name": "Base",
"explorer_api": "https://api.basescan.org/api",
"rpc": "https://rpc.ankr.com/base",
"env_key": "BASESCAN_API_KEY",
"currency": "ETH",
"chain_id": 8453,
},
"arbitrum": {
"name": "Arbitrum",
"explorer_api": "https://api.arbiscan.io/api",
"rpc": "https://rpc.ankr.com/arbitrum",
"env_key": "ARBISCAN_API_KEY",
"currency": "ETH",
"chain_id": 42161,
},
"optimism": {
"name": "Optimism",
"explorer_api": "https://api-optimistic.etherscan.io/api",
"rpc": "https://rpc.ankr.com/optimism",
"env_key": "OPSCAN_API_KEY",
"currency": "ETH",
"chain_id": 10,
},
"polygon": {
"name": "Polygon",
"explorer_api": "https://api.polygonscan.com/api",
"rpc": "https://rpc.ankr.com/polygon",
"env_key": "POLYGONSCAN_API_KEY",
"currency": "MATIC",
"chain_id": 137,
},
}
# ---------------------------------------------------------------------------
# Known factory contracts
# ---------------------------------------------------------------------------
KNOWN_FACTORIES = {
"uniswap_v3_pool_deployer": {
"address": "0x1F98431c8aD98523631AE4a59f267346ea31F984",
"label": "Uniswap V3 Pool Deployer",
"type": "create2",
"description": "Deploys Uniswap V3 liquidity pool contracts via CREATE2",
},
"create2_deployer": {
"address": "0x13b0D85CcD8bf66cFc1c8B6E4F4bA0b5B7B4E6E6",
"label": "Create2 Deployer (0x13b0)",
"type": "create2",
"description": "Generic CREATE2 deployer used by many protocols",
},
"safe_proxy_factory": {
"address": "0xa6B71E26C5e0845f74c812102Ca7114b6a511B77",
"label": "Safe ProxyFactory",
"type": "minimal_proxy",
"description": "Deploys Safe (Gnosis) wallet proxy contracts",
},
"eip1167_deployer": {
"address": "0x4e59b44847b379578588920cA78FbF26c0B4956C",
"label": "EIP-1167 Minimal Proxy Deployer",
"type": "minimal_proxy",
"description": "Deploys EIP-1167 minimal proxy (clone) contracts",
},
"uniswap_v2_factory": {
"address": "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f",
"label": "Uniswap V2 Factory",
"type": "create2",
"description": "Deploys Uniswap V2 pair contracts via CREATE2",
},
}
# ---------------------------------------------------------------------------
# EIP-1967 storage slots
# ---------------------------------------------------------------------------
# Implementation slot: bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)
EIP1967_IMPL_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
# Admin slot: bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)
EIP1967_ADMIN_SLOT = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103"
# Beacon slot: bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)
EIP1967_BEACON_SLOT = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50"
# ---------------------------------------------------------------------------
# Rate limiter
# ---------------------------------------------------------------------------
_last_request_times: dict[str, float] = {}
RATE_LIMIT_INTERVAL = 0.2 # 5 requests per second per domain
def _rate_limit(url: str) -> None:
"""Enforce rate limiting per API domain.
Args:
url: Full URL to extract domain from for per-domain limiting.
"""
global _last_request_times
domain = url.split("/")[2] if "/" in url else url
now = time.time()
last = _last_request_times.get(domain, 0.0)
elapsed = now - last
if elapsed < RATE_LIMIT_INTERVAL:
time.sleep(RATE_LIMIT_INTERVAL - elapsed)
_last_request_times[domain] = time.time()
# ---------------------------------------------------------------------------
# Cache system
# ---------------------------------------------------------------------------
def _cache_dir() -> Path:
"""Return cache directory path, creating it if needed.
Returns:
Path to ~/.contract-deploy-cache/
"""
d = Path.home() / ".contract-deploy-cache"
d.mkdir(parents=True, exist_ok=True)
return d
def _cache_key(url: str, params: dict) -> str:
"""Generate deterministic cache key from URL and params.
Args:
url: Request URL.
params: Query parameters dict.
Returns:
SHA-256 hex digest for use as filename.
"""
raw = url + json.dumps(params, sort_keys=True)
return hashlib.sha256(raw.encode()).hexdigest()
def _cache_get(key: str, ttl: int = 300) -> Optional[Any]:
"""Retrieve cached value if it exists and is not expired.
Args:
key: Cache key (SHA-256 hash).
ttl: Time-to-live in seconds (default 300 = 5 minutes).
Returns:
Cached value or None if expired/missing.
"""
path = _cache_dir() / f"{key}.json"
if not path.exists():
return None
try:
data = json.loads(path.read_text())
if time.time() - data.get("ts", 0) > ttl:
# Expired — remove stale cache file
path.unlink(missing_ok=True)
return None
return data.get("value")
except (json.JSONDecodeError, KeyError, OSError):
return None
def _cache_set(key: str, value: Any) -> None:
"""Store a value in the cache with current timestamp.
Args:
key: Cache key.
value: JSON-serializable value to cache.
"""
path = _cache_dir() / f"{key}.json"
try:
path.write_text(json.dumps({"ts": time.time(), "value": value}, default=str))
except OSError as e:
console.print(f"[dim yellow]Warning: cache write failed: {e}[/dim yellow]")
def clear_cache() -> int:
"""Clear all cached data.
Returns:
Number of cache files removed.
"""
cache_dir = _cache_dir()
count = 0
for f in cache_dir.glob("*.json"):
f.unlink()
count += 1
return count
# ---------------------------------------------------------------------------
# Configuration / API key management
# ---------------------------------------------------------------------------
def _get_api_key(chain_cfg: dict) -> str:
"""Get API key for a chain from environment variables.
Checks chain-specific key first (e.g. BASESCAN_API_KEY), then falls back
to generic ETHERSCAN_API_KEY. Returns empty string if neither is set.
Args:
chain_cfg: Chain configuration dict.
Returns:
API key string, or empty string for free-tier usage.
"""
return (
os.environ.get(chain_cfg.get("env_key", ""), "")
or os.environ.get("ETHERSCAN_API_KEY", "")
)
# ---------------------------------------------------------------------------
# HTTP / RPC request helpers
# ---------------------------------------------------------------------------
def etherscan_request(chain_cfg: dict, module: str, action: str,
ttl: int = 300, **kwargs) -> dict:
"""Make an Etherscan-compatible API request with caching and rate limiting.
Constructs the proper URL with module, action, and additional parameters.
Supports all Etherscan v2 API endpoints. Results are cached locally.
Args:
chain_cfg: Chain configuration dict from CHAINS.
module: API module name (e.g. 'contract', 'account', 'proxy').
action: API action (e.g. 'getabi', 'txlist', 'getcontractcreation').
ttl: Cache TTL in seconds (default 300).
**kwargs: Additional query parameters passed to the API.
Returns:
Parsed JSON response as dict. Etherscan format:
{"status": "1", "message": "OK", "result": ...}
Raises:
click.ClickException: On network failure or invalid response.
"""
params = {"module": module, "action": action, **kwargs}
api_key = _get_api_key(chain_cfg)
if api_key:
params["apikey"] = api_key
url = chain_cfg["explorer_api"]
cache_key = _cache_key(url, params)
cached = _cache_get(cache_key, ttl=ttl)
if cached is not None:
return cached
_rate_limit(url)
try:
resp = requests.get(url, params=params, timeout=30)
resp.raise_for_status()
data = resp.json()
except requests.Timeout:
raise click.ClickException(f"Request timed out for {url}")
except requests.ConnectionError as e:
raise click.ClickException(f"Connection error: {e}")
except requests.HTTPError as e:
raise click.ClickException(f"HTTP error: {e}")
except json.JSONDecodeError:
raise click.ClickException(f"Invalid JSON response from {url}")
# Check for Etherscan rate limit message
if isinstance(data.get("result"), str) and "rate limit" in data["result"].lower():
console.print("[yellow]Rate limited by API, waiting 1s...[/yellow]")
time.sleep(1)
_rate_limit(url)
try:
resp = requests.get(url, params=params, timeout=30)
resp.raise_for_status()
data = resp.json()
except Exception as e:
raise click.ClickException(f"Retry failed: {e}")
_cache_set(cache_key, data)
return data
def rpc_request(chain_cfg: dict, method: str, params: list,
ttl: int = 60) -> Any:
"""Make a JSON-RPC request to the chain's public endpoint.
Args:
chain_cfg: Chain configuration dict.
method: RPC method name (e.g. 'eth_blockNumber', 'eth_getCode').
params: Method parameters list.
ttl: Cache TTL in seconds (default 60).
Returns:
The 'result' field from the JSON-RPC response.
Raises:
click.ClickException: On RPC or network error.
"""
url = chain_cfg["rpc"]
cache_key = _cache_key(url, {"method": method, "params": params})
cached = _cache_get(cache_key, ttl=ttl)
if cached is not None:
return cached
_rate_limit(url)
payload = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
try:
resp = requests.post(url, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
except requests.Timeout:
raise click.ClickException(f"RPC request timed out for {url}")
except requests.ConnectionError as e:
raise click.ClickException(f"RPC connection error: {e}")
except json.JSONDecodeError:
raise click.ClickException(f"Invalid JSON from RPC at {url}")
if "error" in data:
err = data["error"]
raise click.ClickException(f"RPC error {err.get('code', '?')}: {err.get('message', 'unknown')}")
result = data.get("result")
if result is not None:
_cache_set(cache_key, result)
return result
# ---------------------------------------------------------------------------
# Chain lookup helper
# ---------------------------------------------------------------------------
def get_chain(name: str) -> dict:
"""Look up chain config by short name.
Args:
name: Chain identifier (e.g. 'ethereum', 'base', 'arb', 'op', 'polygon').
Returns:
Chain configuration dict.
Raises:
click.ClickException: If chain not found.
"""
aliases = {
"eth": "ethereum",
"arb": "arbitrum",
"op": "optimism",
"matic": "polygon",
}
name = aliases.get(name.lower(), name.lower())
if name not in CHAINS:
raise click.ClickException(
f"Unknown chain '{name}'. Available: {', '.join(CHAINS.keys())}"
)
return CHAINS[name]
# ---------------------------------------------------------------------------
# Export helpers
# ---------------------------------------------------------------------------
def export_data(rows: list[dict], fmt: str, output: Optional[str]) -> None:
"""Export data rows to CSV or JSON format.
Args:
rows: List of dicts to export.
fmt: Output format — 'csv' or 'json'.
output: File path to write to, or None for stdout.
"""
if not rows:
console.print("[yellow]No data to export.[/yellow]")
return
if fmt == "json":
text = json.dumps(rows, indent=2, default=str)
elif fmt == "csv":
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
text = buf.getvalue()
else:
raise click.ClickException(f"Unknown export format: '{fmt}'")
if output:
Path(output).write_text(text)
console.print(f"[green]✓ Exported {len(rows)} rows to {output}[/green]")
else:
click.echo(text)
# ---------------------------------------------------------------------------
# Bytecode / contract analysis
# ---------------------------------------------------------------------------
def bytecode_size(bytecode_hex: str) -> int:
"""Calculate bytecode size in bytes from hex string.
Strips 0x prefix and counts hex character pairs.
Args:
bytecode_hex: Hex-encoded bytecode (e.g. '0x6080604052...').
Returns:
Size in bytes.
"""
clean = bytecode_hex.replace("0x", "")
return len(clean) // 2
def is_eip1167_proxy(bytecode_hex: str) -> bool:
"""Detect EIP-1167 minimal proxy (clone) pattern in bytecode.
The minimal proxy bytecode is exactly 45 bytes and starts with
0x363d3d373d3d3d363d73 followed by the implementation address
and ends with 0x5af43d82803e903d91602b57fd5bf3.
Args:
bytecode_hex: Hex-encoded bytecode.
Returns:
True if bytecode matches EIP-1167 pattern.
"""
clean = bytecode_hex.replace("0x", "").lower()
if len(clean) != 90: # 45 bytes = 90 hex chars
return False
prefix = "363d3d373d3d3d363d73"
suffix = "5af43d82803e903d91602b57fd5bf3"
return clean.startswith(prefix) and clean.endswith(suffix)
def extract_eip1167_target(bytecode_hex: str) -> Optional[str]:
"""Extract implementation address from EIP-1167 minimal proxy bytecode.
Args:
bytecode_hex: Hex-encoded bytecode.
Returns:
Checksummed address string, or None if not a minimal proxy.
"""
clean = bytecode_hex.replace("0x", "").lower()
if not is_eip1167_proxy(bytecode_hex):
return None
# Address is bytes 10-29 (20 bytes = 40 hex chars)
addr_hex = clean[20:60]
return "0x" + addr_hex
def detect_proxy(chain_cfg: dict, address: str) -> dict:
"""Detect if a contract is a proxy using EIP-1967 storage slots and bytecode analysis.
Checks:
1. EIP-1967 implementation slot for standard proxy pattern
2. EIP-1967 admin slot for proxy admin
3. EIP-1967 beacon slot for beacon proxies
4. EIP-1167 minimal proxy pattern in bytecode
Args:
chain_cfg: Chain configuration dict.
address: Contract address to check.
Returns:
Dict with keys: is_proxy, proxy_type, implementation, admin, beacon.
"""
result = {
"is_proxy": False,
"proxy_type": None,
"implementation": None,
"admin": None,
"beacon": None,
}
# Check EIP-1967 implementation slot
try:
impl_data = rpc_request(chain_cfg, "eth_getStorageAt", [
address, EIP1967_IMPL_SLOT, "latest"
], ttl=120)
if impl_data and impl_data != "0x" + "0" * 64:
impl_addr = "0x" + impl_data[-40:]
if int(impl_addr, 16) != 0:
result["is_proxy"] = True
result["proxy_type"] = "eip1967"
result["implementation"] = impl_addr
except click.ClickException:
pass
# Check admin slot
try:
admin_data = rpc_request(chain_cfg, "eth_getStorageAt", [
address, EIP1967_ADMIN_SLOT, "latest"
], ttl=120)
if admin_data and admin_data != "0x" + "0" * 64:
admin_addr = "0x" + admin_data[-40:]
if int(admin_addr, 16) != 0:
result["admin"] = admin_addr
except click.ClickException:
pass
# Check beacon slot
try:
beacon_data = rpc_request(chain_cfg, "eth_getStorageAt", [
address, EIP1967_BEACON_SLOT, "latest"
], ttl=120)
if beacon_data and beacon_data != "0x" + "0" * 64:
beacon_addr = "0x" + beacon_data[-40:]
if int(beacon_addr, 16) != 0:
result["is_proxy"] = True
result["proxy_type"] = "beacon"
result["beacon"] = beacon_addr
except click.ClickException:
pass
# Check EIP-1167 minimal proxy via bytecode
if not result["is_proxy"]:
try:
bytecode = get_bytecode(chain_cfg, address)
if is_eip1167_proxy(bytecode):
result["is_proxy"] = True
result["proxy_type"] = "eip1167_minimal"
result["implementation"] = extract_eip1167_target(bytecode)
except click.ClickException:
pass
return result
def get_bytecode(chain_cfg: dict, address: str) -> str:
"""Fetch deployed bytecode at an address via eth_getCode.
Args:
chain_cfg: Chain configuration dict.
address: Contract address.
Returns:
Hex-encoded bytecode string (e.g. '0x6080604052...').
"""
code = rpc_request(chain_cfg, "eth_getCode", [address, "latest"])
return code or "0x"
def check_verification(chain_cfg: dict, address: str) -> dict:
"""Check if a contract is verified on the block explorer.
Uses getabi endpoint to check verification status, and getsourcecode
to retrieve source code if verified.
Args:
chain_cfg: Chain configuration dict.
address: Contract address to check.
Returns:
Dict with 'verified' (bool), 'abi' (parsed or None), 'source_code' (str or None),
'contract_name' (str or None).
"""
result = {"verified": False, "abi": None, "source_code": None, "contract_name": None}
data = etherscan_request(chain_cfg, "contract", "getabi", address=address, ttl=600)
verified = data.get("status") == "1" and data.get("message") == "OK"
result["verified"] = verified
if verified:
try:
result["abi"] = json.loads(data["result"])
except (json.JSONDecodeError, TypeError):
result["abi"] = data["result"]
# Get source code and contract name if verified
if verified:
src_data = etherscan_request(
chain_cfg, "contract", "getsourcecode", address=address, ttl=600
)
if src_data.get("status") == "1" and src_data.get("result"):
src_info = src_data["result"]
if isinstance(src_info, list) and src_info:
src_info = src_info[0]
source = src_info.get("SourceCode", "")
result["contract_name"] = src_info.get("ContractName", "")
if source:
# Handle multi-file sources wrapped in {{ }}
if source.startswith("{{"):
try:
parsed = json.loads(source[1:-1])
sources = parsed.get("sources", {})
combined = ""
for fname, fdata in sources.items():
combined += f"\n// --- {fname} ---\n"
combined += fdata.get("content", "")[:200]
result["source_code"] = combined[:500]
except json.JSONDecodeError:
result["source_code"] = source[:500]
else:
result["source_code"] = source[:500]
return result
def get_contract_creation(chain_cfg: dict, addresses: list[str]) -> list[dict]:
"""Get contract creation info via Etherscan getcontractcreation endpoint.
Args:
chain_cfg: Chain configuration dict.
addresses: List of contract addresses (up to 5 at a time).
Returns:
List of dicts with 'contractAddress', 'contractCreator', 'txHash' keys.
"""
if not addresses:
return []
# Etherscan accepts comma-separated addresses
addr_str = ",".join(addresses[:5])
data = etherscan_request(
chain_cfg, "contract", "getcontractcreation",
contractaddresses=addr_str, ttl=600
)
if data.get("status") == "1" and data.get("result"):
results = data["result"]
if isinstance(results, list):
return results
return []
def get_tx_list(chain_cfg: dict, address: str, startblock: int = 0,
endblock: int = 99999999, page: int = 1,
offset: int = 100) -> list[dict]:
"""Get normal transaction list for an address via Etherscan account/txlist.
Args:
chain_cfg: Chain configuration dict.
address: Wallet or contract address.
startblock: Starting block number (inclusive).
endblock: Ending block number (inclusive).
page: Page number for pagination.
offset: Number of results per page (max 10000).
Returns:
List of transaction dicts from Etherscan API.
"""
data = etherscan_request(
chain_cfg, "account", "txlist",
address=address, startblock=startblock, endblock=endblock,
page=page, offset=offset, sort="desc"
)
if data.get("status") == "1" and data.get("result"):
results = data["result"]
if isinstance(results, list):
return results
return []
def get_internal_txs(chain_cfg: dict, address: str, startblock: int = 0,
endblock: int = 99999999, page: int = 1,
offset: int = 100) -> list[dict]:
"""Get internal transactions for an address via Etherscan.
Internal transactions are contract-to-contract calls that don't
appear in the main transaction list.
Args:
chain_cfg: Chain configuration dict.
address: Wallet or contract address.
startblock: Starting block number.
endblock: Ending block number.
page: Page number.
offset: Results per page.
Returns:
List of internal transaction dicts.
"""
data = etherscan_request(
chain_cfg, "account", "txlistinternal",
address=address, startblock=startblock, endblock=endblock,
page=page, offset=offset, sort="desc"
)
if data.get("status") == "1" and data.get("result"):
results = data["result"]
if isinstance(results, list):
return results
return []
# ---------------------------------------------------------------------------
# Block scanning via RPC
# ---------------------------------------------------------------------------
def get_block_by_number(chain_cfg: dict, block_num: int) -> Optional[dict]:
"""Fetch a block with full transaction objects via eth_getBlockByNumber.
Args:
chain_cfg: Chain configuration dict.
block_num: Block number as integer.
Returns:
Block dict with full transaction objects, or None on failure.
"""
hex_num = hex(block_num)
return rpc_request(chain_cfg, "eth_getBlockByNumber", [hex_num, True])
def get_latest_block(chain_cfg: dict) -> int:
"""Get the latest block number via eth_blockNumber.
Args:
chain_cfg: Chain configuration dict.
Returns:
Latest block number as integer.
"""
result = rpc_request(chain_cfg, "eth_blockNumber", [])
return int(result, 16)
def get_tx_receipt(chain_cfg: dict, tx_hash: str) -> Optional[dict]:
"""Get transaction receipt to find created contract address.
Args:
chain_cfg: Chain configuration dict.
tx_hash: Transaction hash.
Returns:
Receipt dict or None.
"""
return rpc_request(chain_cfg, "eth_getTransactionReceipt", [tx_hash])
def find_creations_in_block(block: dict) -> list[dict]:
"""Find contract creation transactions in a block.
Contract creation transactions have to=null (or empty string).
The created contract address can be found in the transaction receipt.
Args:
block: Block dict from eth_getBlockByNumber with full txs.
Returns:
List of dicts with creation info: hash, from, to, input_len, gas,
value, blockNumber, timestamp.
"""
creations = []
block_number = block.get("number", "0x0")
if isinstance(block_number, str):
block_number = int(block_number, 16)
block_timestamp = block.get("timestamp", "0x0")
if isinstance(block_timestamp, str):
block_timestamp = int(block_timestamp, 16)
for tx in block.get("transactions", []):
to_addr = tx.get("to")
# Contract creation: to is null, None, or empty
if to_addr is None or to_addr == "" or to_addr == "0x":
gas_val = tx.get("gas", "0x0")
if isinstance(gas_val, str):
gas_val = int(gas_val, 16)
value_val = tx.get("value", "0x0")
if isinstance(value_val, str):
value_val = int(value_val, 16)
tx_hash = tx.get("hash", "")
from_addr = tx.get("from", "")
input_data = tx.get("input", "0x")
creations.append({
"hash": tx_hash,
"from": from_addr,
"to": None,
"input_len": len(input_data),
"bytecode_size": bytecode_size(input_data) if input_data else 0,
"gas": gas_val,
"gas_price": int(tx.get("gasPrice", "0x0"), 16) if isinstance(tx.get("gasPrice"), str) else tx.get("gasPrice", 0),
"value": value_val,
"blockNumber": block_number,
"timestamp": block_timestamp,
"tx_index": int(tx.get("transactionIndex", "0x0"), 16) if isinstance(tx.get("transactionIndex"), str) else tx.get("transactionIndex", 0),
})
return creations
# ---------------------------------------------------------------------------
# Rich display helpers
# ---------------------------------------------------------------------------
def make_table(title: str, columns: list[str]) -> Table:
"""Create a styled Rich table.
Args:
title: Table title displayed above.
columns: List of column header names.
Returns:
Configured Rich Table object ready for add_row() calls.
"""
table = Table(title=title, show_lines=True, expand=True, title_style="bold cyan")
for col in columns:
table.add_column(col, overflow="fold")
return table
def truncate_addr(addr: str, n: int = 8) -> str:
"""Truncate an Ethereum address for compact display.
Shows first n and last n characters with ... in between.
Args:
addr: Full Ethereum address (0x...).
n: Number of chars to keep from each end.
Returns:
Truncated address string.
"""
if not addr or len(addr) <= n * 2 + 5:
return addr or ""
return f"{addr[:2 + n]}...{addr[-n:]}"
def format_wei(wei: int) -> str:
"""Format wei value to human-readable ETH.
Args:
wei: Value in wei.
Returns:
Formatted string like '1.234 ETH'.
"""
eth = wei / 10**18
if eth < 0.0001:
return f"{wei} wei"
return f"{eth:.4f} ETH"
def format_timestamp(ts: int) -> str:
"""Format Unix timestamp to ISO date string.
Args:
ts: Unix timestamp in seconds.
Returns:
ISO format datetime string.
"""
if not ts:
return "N/A"
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
# ---------------------------------------------------------------------------
# CLI group
# ---------------------------------------------------------------------------
@click.group()
@click.version_option(version="0.1.0", prog_name="contract-deploy-tracker")
def cli():
"""contract-deploy-tracker — Track and analyze smart contract deployments across EVM chains.
Supports Ethereum, Base, Arbitrum, Optimism, and Polygon.
Uses Etherscan-compatible APIs and public RPC endpoints.
"""
pass
# ---------------------------------------------------------------------------
# recent — scan recent blocks for contract creations
# ---------------------------------------------------------------------------
@cli.command()
@click.option("-c", "--chain", default="ethereum", show_default=True, help="Chain to query.")
@click.option("-n", "--num-blocks", default=10, type=int, show_default=True, help="Number of recent blocks to scan.")
@click.option("--start-block", default=None, type=int, help="Start scanning from this block (overrides --num-blocks).")
@click.option("--export", "export_fmt", type=click.Choice(["csv", "json"]), help="Export format.")
@click.option("-o", "--output", default=None, help="Output file path (stdout if omitted).")
def recent(chain: str, num_blocks: int, start_block: Optional[int],
export_fmt: Optional[str], output: Optional[str]):
"""Scan recent blocks for contract creation transactions.
Uses eth_getBlockByNumber via public RPC to find transactions where
the 'to' field is null, indicating contract deployment.
"""
chain_cfg = get_chain(chain)
console.print(f"[bold]Scanning recent blocks on {chain_cfg['name']}...[/bold]")
latest = get_latest_block(chain_cfg)
console.print(f"Latest block: [cyan]{latest:,}[/cyan]")
if start_block is not None:
blocks_to_scan = latest - start_block + 1
start = start_block
else:
blocks_to_scan = num_blocks
start = latest - num_blocks + 1
console.print(f"Scanning blocks [cyan]{start:,}[/cyan] to [cyan]{latest:,}[/cyan] ({blocks_to_scan} blocks)")
all_creations = []
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
console=console,
) as progress:
task = progress.add_task("Scanning blocks...", total=blocks_to_scan)
for i in range(blocks_to_scan):
block_num = latest - i
progress.update(task, advance=1, description=f"Block {block_num:,}")
block = get_block_by_number(chain_cfg, block_num)
if block:
creations = find_creations_in_block(block)
for c in creations:
c["chain"] = chain
c["explorer"] = chain_cfg["explorer_api"].replace("/api", "")
all_creations.extend(creations)
if export_fmt:
export_data(all_creations, export_fmt, output)
return
if not all_creations:
console.print("[yellow]No contract creations found in scanned blocks.[/yellow]")
return
table = make_table(
f"Contract Creations on {chain_cfg['name']} ({blocks_to_scan} blocks)",
["Block", "Deployer", "Tx Hash", "Gas", "Bytecode Size", "Timestamp"]
)
for c in all_creations:
table.add_row(
f"{c['blockNumber']:,}",
truncate_addr(c["from"]),
truncate_addr(c["hash"]),
f"{c['gas']:,}",
f"{c.get('bytecode_size', 0):,} B",
format_timestamp(c.get("timestamp", 0)),
)
console.print(table)
# Summary
total_gas = sum(c["gas"] for c in all_creations)
unique_deployers = len(set(c["from"] for c in all_creations))
avg_size = sum(c.get("bytecode_size", 0) for c in all_creations) / max(len(all_creations), 1)
console.print(Panel(
f"Total deployments: [green]{len(all_creations)}[/green]\n"
f"Unique deployers: [cyan]{unique_deployers}[/cyan]\n"
f"Total gas used: [yellow]{total_gas:,}[/yellow]\n"
f"Avg bytecode size: [cyan]{avg_size:,.0f} bytes[/cyan]",
title="Summary", expand=False
))
# ---------------------------------------------------------------------------
# deployer — analyze all contracts deployed by an address
# ---------------------------------------------------------------------------
@cli.command()
@click.argument("address")
@click.option("-c", "--chain", default="ethereum", show_default=True, help="Chain to query.")
@click.option("-n", "--limit", default=50, type=int, show_default=True, help="Max transactions to fetch.")
@click.option("--include-internal/--no-internal", default=True, help="Include internal contract creations.")
@click.option("--check-verify/--no-verify", default=False, help="Check verification status (slow, 1 request per contract).")
@click.option("--export", "export_fmt", type=click.Choice(["csv", "json"]), help="Export format.")
@click.option("-o", "--output", default=None, help="Output file path.")
def deployer(address: str, chain: str, limit: int, include_internal: bool,
check_verify: bool, export_fmt: Optional[str], output: Optional[str]):
"""Analyze all contracts deployed by ADDRESS.
Queries Etherscan txlist for direct creations (to=null) and optionally