Skip to content

Commit 3715669

Browse files
committed
download source code from etherscan using official api
1 parent e47f5c1 commit 3715669

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

etherscan.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Download contract source code using Etherscan HTTP json api
2+
3+
import requests
4+
import json
5+
import argparse
6+
7+
ap = argparse.ArgumentParser()
8+
ap.add_argument("--address", type=str, required=True, help="Contract address")
9+
ap.add_argument("--apikey", type=str, required=True, help="Etherscan api key")
10+
ap.add_argument("--output", type=str, default="source.json", help="Output source code as json, suitable for use as solc input ")
11+
12+
args = ap.parse_args()
13+
14+
address = args.address
15+
api_key = args.apikey
16+
output = args.output
17+
18+
if not api_key:
19+
print("Please provide --apikey")
20+
exit(1)
21+
22+
if not address:
23+
print("Please provide --address")
24+
exit(1)
25+
26+
url = f'https://api.etherscan.io/api?module=contract&action=getsourcecode&address={address}&apikey={api_key}'
27+
28+
response = requests.get(url)
29+
# with open('response.txt', 'w') as f:
30+
# f.write(response.text)
31+
32+
data = json.loads(response.text)
33+
34+
if data['status'] == '1':
35+
contract_name = data['result'][0]['ContractName']
36+
source_code = data['result'][0]['SourceCode']
37+
38+
with open(output, 'w') as f:
39+
t = source_code.replace('{{', '{').replace('}}', '}')
40+
f.write(t)
41+
else:
42+
print('Error: Unable to retrieve contract source code')

0 commit comments

Comments
 (0)