-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgeth.py
210 lines (171 loc) · 6.1 KB
/
geth.py
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
import time
import json
import requests
from utils import say
def get_transaction_count(ep, address, mode='latest'):
nonce_hex = geth_request(
ep=ep,
method='eth_getTransactionCount',
params=[address, mode]
)
return int(nonce_hex, base=16)
def get_transaction_receipt(ep, tx_hash, timeout=0, poll_latency=0):
if not tx_hash.startswith('0x'):
tx_hash = '0x' + tx_hash
kwargs = {
'ep': ep,
'method': 'eth_getTransactionReceipt',
'params': [tx_hash],
'none_ok': True
}
result = geth_request(**kwargs)
if result or not poll_latency:
return result
counter = timeout/poll_latency
while counter and not result:
time.sleep(poll_latency)
result = geth_request(**kwargs)
# print(f"Kwargs={kwargs} result={result} poll_latency={poll_latency}")
counter -= 1
return result
def get_gas_price(ep):
return int(geth_request(ep=ep, method='eth_gasPrice'), base=16)
def get_balance(ep, address, mode='latest'):
balance_hex = geth_request(
ep=ep,
method='eth_getBalance',
params=[address, mode]
)
return int(balance_hex, base=16)
def get_chainid(ep):
return int(geth_request(ep=ep, method='eth_chainId'), base=16)
def get_blocknumber(ep):
return int(geth_request(ep=ep, method='eth_blockNumber'), base=16)
def get_batchnumber(ep):
return int(geth_request(ep=ep, method='zkevm_batchNumber'), base=16)
def get_block(ep, block_number):
return geth_request(
ep=ep, method='eth_getBlockByNumber', params=[hex(block_number), True])
def get_lastverifiedbatch(ep):
return int(
geth_request(ep=ep, method='zkevm_verifiedBatchNumber'), base=16)
def get_lastvirtualbatch(ep):
return int(geth_request(ep=ep, method='zkevm_virtualBatchNumber'), base=16)
def send_raw_transaction(ep, tx):
tx_bytes = tx.hex()
if not tx_bytes.startswith('0x'):
tx_bytes = '0x' + tx_bytes
return geth_request(
ep=ep,
method='eth_sendRawTransaction',
params=[tx_bytes]
)
def endpoint_request(
method='GET', endpoint=None, path='/', url=None, params=None, body=None,
data=None, headers=None, auth=None, max_attempts=10, trhottle_cooldown=10,
error_handler={}, debug=False
):
if not path.startswith('/'):
path = f'/{path}'
# IF URL is provided (it must be full URL) it's used disregarding
# whatever is the value for endpoint and path
if url:
kwargs = {'method': method, 'url': url}
else:
kwargs = {'method': method, 'url': f'{endpoint}{path}'}
if params:
kwargs['params'] = params
if body:
kwargs['data'] = json.dumps(body)
elif data:
kwargs['data'] = data
if headers:
kwargs['headers'] = headers
if auth:
kwargs['auth'] = auth
if debug:
say(f'kwargs:{kwargs}')
for attempt in range(1, max_attempts+1):
try:
req = requests.request(**kwargs)
try:
content = req.json()
except ValueError:
content = req.reason
rcode = req.status_code
if debug:
say(f'rcode:{rcode} content:{content}')
if rcode in error_handler:
function = error_handler.get(rcode)
function()
raise requests.exceptions.HTTPError(
f'Handle attempt: {rcode}: {content} for url {req.url}')
if rcode == 429:
time.sleep(trhottle_cooldown)
raise requests.exceptions.HTTPError(
f'Throttled!! {rcode}: {content} for url {req.url}')
if rcode >= 500:
raise requests.exceptions.HTTPError(
f'{rcode} Error: {content} for url {req.url}')
return rcode, content
except requests.exceptions.RequestException as e:
if attempt < max_attempts:
say(e)
time.sleep(attempt*attempt)
else:
say(e)
raise
def geth_request(ep, method, params=[], retries=3, debug=False, none_ok=False):
(rcode, content) = endpoint_request(
method='POST', endpoint='Unused', url=ep,
body={'jsonrpc': '2.0', 'method': method, 'params': params, 'id': 1},
headers={'Content-Type': 'application/json'},
debug=False
)
if rcode == 200:
if r := content.get('result'):
return r
elif r_err := content.get('error'):
raise ValueError(r_err)
elif none_ok and content.get('result', False) is None:
return None
else:
say(
f"geth_request ep={ep} method={method} params={params} "
f"retries={retries} answer={content}")
return None
else:
say(
f"utils.geth_request rcode=={rcode} content={content}")
return None
def geth_request_multi(ep, requests, retries=5, map_from_id='number'):
(rcode, content) = endpoint_request(
method='POST', endpoint='Unused', url=ep, body=requests,
headers={'Content-Type': 'application/json'},
)
if rcode == 200:
result = []
for c in content:
if r := c.get('result'):
# The id has been set to batch number when querying
if map_from_id:
r[map_from_id] = c.get('id')
result.append(r)
elif c.get('error') and retries:
retry_in = (10-retries)*2
say(
f"RETRY for geth_request ep={ep} "
f"retries={retries} answer={c} sleep={retry_in}")
time.sleep(retry_in)
return geth_request_multi(
ep, requests, retries-1, map_from_id=map_from_id)
else:
say(
f"geth_request ep={ep} request={requests} "
f"retries={retries} answer={c}")
return None
return result
else:
say(
f"utils.geth_request rcode=={rcode} content={content}")
return None