-
Notifications
You must be signed in to change notification settings - Fork 157
/
ethereum_client.py
1994 lines (1796 loc) · 80.2 KB
/
ethereum_client.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
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
import os
from enum import Enum
from functools import cached_property, wraps
from logging import getLogger
from typing import (
Any,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
Union,
cast,
)
import eth_abi
from eth_abi.exceptions import DecodingError
from eth_account import Account
from eth_account.signers.local import LocalAccount
from eth_typing import URI, BlockNumber, ChecksumAddress, Hash32, HexAddress, HexStr
from hexbytes import HexBytes
from web3 import HTTPProvider, Web3
from web3._utils.abi import map_abi_data
from web3._utils.method_formatters import (
block_formatter,
receipt_formatter,
trace_list_result_formatter,
transaction_result_formatter,
)
from web3._utils.normalizers import BASE_RETURN_NORMALIZERS
from web3.contract.contract import ContractFunction
from web3.exceptions import (
BlockNotFound,
TimeExhausted,
TransactionNotFound,
Web3Exception,
)
from web3.middleware import geth_poa_middleware, simple_cache_middleware
from web3.types import (
BlockData,
BlockIdentifier,
BlockTrace,
FilterParams,
FilterTrace,
LogReceipt,
Nonce,
TraceFilterParams,
TxData,
TxParams,
TxReceipt,
Wei,
)
from gnosis.eth.utils import (
fast_is_checksum_address,
fast_to_checksum_address,
mk_contract_address,
mk_contract_address_2,
)
from gnosis.util import cache, chunks
from ..util.http import prepare_http_session
from .constants import (
ERC20_721_TRANSFER_TOPIC,
GAS_CALL_DATA_BYTE,
GAS_CALL_DATA_ZERO_BYTE,
NULL_ADDRESS,
SAFE_SINGLETON_FACTORY_ADDRESS,
)
from .contracts import get_erc20_contract, get_erc721_contract
from .ethereum_network import EthereumNetwork, EthereumNetworkNotSupported
from .exceptions import (
BatchCallFunctionFailed,
ChainIdIsRequired,
ContractAlreadyDeployed,
FromAddressNotFound,
GasLimitExceeded,
InsufficientFunds,
InvalidERC20Info,
InvalidERC721Info,
InvalidNonce,
NonceTooHigh,
NonceTooLow,
ReplacementTransactionUnderpriced,
SenderAccountNotFoundInNode,
TransactionAlreadyImported,
TransactionGasPriceTooLow,
TransactionQueueLimitReached,
UnknownAccount,
)
from .typing import BalanceDict, EthereumData, EthereumHash, LogReceiptDecoded
from .utils import decode_string_or_bytes32
logger = getLogger(__name__)
def tx_with_exception_handling(func):
"""
Parity / OpenEthereum
- https://github.com/openethereum/openethereum/blob/main/rpc/src/v1/helpers/errors.rs
Geth
- https://github.com/ethereum/go-ethereum/blob/master/core/error.go
- https://github.com/ethereum/go-ethereum/blob/master/core/tx_pool.go
Comparison
- https://gist.github.com/kunal365roy/3c37ac9d1c3aaf31140f7c5faa083932
:param func:
:return:
"""
error_with_exception: Dict[str, Exception] = {
"EIP-155": ChainIdIsRequired,
"Transaction with the same hash was already imported": TransactionAlreadyImported,
"replacement transaction underpriced": ReplacementTransactionUnderpriced, # https://github.com/ethereum/go-ethereum/blob/eaccdba4ab310e3fb98edbc4b340b5e7c4d767fd/core/tx_pool.go#L72
"There is another transaction with same nonce in the queue": ReplacementTransactionUnderpriced, # https://github.com/openethereum/openethereum/blob/f1dc6821689c7f47d8fd07dfc0a2c5ad557b98ec/crates/rpc/src/v1/helpers/errors.rs#L374
"There are too many transactions in the queue. Your transaction was dropped due to limit. Try increasing "
"the fee": TransactionQueueLimitReached, # https://github.com/openethereum/openethereum/blob/f1dc6821689c7f47d8fd07dfc0a2c5ad557b98ec/crates/rpc/src/v1/helpers/errors.rs#L380
"txpool is full": TransactionQueueLimitReached, # https://github.com/ethereum/go-ethereum/blob/eaccdba4ab310e3fb98edbc4b340b5e7c4d767fd/core/tx_pool.go#L68
"transaction underpriced": TransactionGasPriceTooLow, # https://github.com/ethereum/go-ethereum/blob/eaccdba4ab310e3fb98edbc4b340b5e7c4d767fd/core/tx_pool.go#L64
"Transaction gas price is too low": TransactionGasPriceTooLow, # https://github.com/openethereum/openethereum/blob/f1dc6821689c7f47d8fd07dfc0a2c5ad557b98ec/crates/rpc/src/v1/helpers/errors.rs#L386
"from not found": FromAddressNotFound,
"correct nonce": InvalidNonce,
"nonce too low": NonceTooLow, # https://github.com/ethereum/go-ethereum/blob/bbfb1e4008a359a8b57ec654330c0e674623e52f/core/error.go#L46
"nonce too high": NonceTooHigh, # https://github.com/ethereum/go-ethereum/blob/bbfb1e4008a359a8b57ec654330c0e674623e52f/core/error.go#L46
"insufficient funds": InsufficientFunds, # https://github.com/openethereum/openethereum/blob/f1dc6821689c7f47d8fd07dfc0a2c5ad557b98ec/crates/rpc/src/v1/helpers/errors.rs#L389
"doesn't have enough funds": InsufficientFunds,
"sender account not recognized": SenderAccountNotFoundInNode,
"unknown account": UnknownAccount,
"exceeds block gas limit": GasLimitExceeded, # Geth
"exceeds current gas limit": GasLimitExceeded, # https://github.com/openethereum/openethereum/blob/f1dc6821689c7f47d8fd07dfc0a2c5ad557b98ec/crates/rpc/src/v1/helpers/errors.rs#L392
}
@wraps(func)
def with_exception_handling(*args, **kwargs):
try:
return func(*args, **kwargs)
except (Web3Exception, ValueError) as exc:
str_exc = str(exc).lower()
for reason, custom_exception in error_with_exception.items():
if reason.lower() in str_exc:
raise custom_exception(str(exc)) from exc
raise exc
return with_exception_handling
class EthereumTxSent(NamedTuple):
tx_hash: bytes
tx: TxParams
contract_address: Optional[ChecksumAddress]
class Erc20Info(NamedTuple):
name: str
symbol: str
decimals: int
class Erc721Info(NamedTuple):
name: str
symbol: str
class TokenBalance(NamedTuple):
token_address: str
balance: int
class TxSpeed(Enum):
SLOWEST = 0
VERY_SLOW = 1
SLOW = 2
NORMAL = 3
FAST = 4
VERY_FAST = 5
FASTEST = 6
class EthereumClientProvider:
def __new__(cls):
if not hasattr(cls, "instance"):
try:
from django.conf import settings
ethereum_node_url = settings.ETHEREUM_NODE_URL
except ModuleNotFoundError:
ethereum_node_url = os.environ.get("ETHEREUM_NODE_URL")
cls.instance = EthereumClient(
ethereum_node_url,
provider_timeout=int(os.environ.get("ETHEREUM_RPC_TIMEOUT", 10)),
slow_provider_timeout=int(
os.environ.get("ETHEREUM_RPC_SLOW_TIMEOUT", 60)
),
retry_count=int(os.environ.get("ETHEREUM_RPC_RETRY_COUNT", 1)),
batch_request_max_size=int(
os.environ.get("ETHEREUM_RPC_BATCH_REQUEST_MAX_SIZE", 500)
),
)
return cls.instance
class EthereumClientManager:
def __init__(self, ethereum_client: "EthereumClient"):
self.ethereum_client = ethereum_client
self.ethereum_node_url = ethereum_client.ethereum_node_url
self.w3 = ethereum_client.w3
self.slow_w3 = ethereum_client.slow_w3
self.http_session = ethereum_client.http_session
self.timeout = ethereum_client.timeout
self.slow_timeout = ethereum_client.slow_timeout
class BatchCallManager(EthereumClientManager):
def batch_call_custom(
self,
payloads: Iterable[Dict[str, Any]],
raise_exception: bool = True,
block_identifier: Optional[BlockIdentifier] = "latest",
batch_size: Optional[int] = None,
) -> List[Optional[Any]]:
"""
Do batch requests of multiple contract calls (`eth_call`)
:param payloads: Iterable of Dictionaries with at least {'data': '<hex-string>',
'output_type': <solidity-output-type>, 'to': '<checksummed-address>'}. `from` can also be provided and if
`fn_name` is provided it will be used for debugging purposes
:param raise_exception: If False, exception will not be raised if there's any problem and instead `None` will
be returned as the value
:param block_identifier: `latest` by default
:param batch_size: If `payload` length is bigger than size, it will be split into smaller chunks before
sending to the server
:return: List with the ABI decoded return values
:raises: ValueError if raise_exception=True
"""
if not payloads:
return []
queries = []
for i, payload in enumerate(payloads):
assert "data" in payload, "`data` not present"
assert "to" in payload, "`to` not present"
assert "output_type" in payload, "`output-type` not present"
query_params = {"to": payload["to"], "data": payload["data"]} # Balance of
if "from" in payload:
query_params["from"] = payload["from"]
queries.append(
{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [
query_params,
hex(block_identifier)
if isinstance(block_identifier, int)
else block_identifier,
],
"id": i,
}
)
batch_size = batch_size or self.ethereum_client.batch_request_max_size
all_results = []
for chunk in chunks(queries, batch_size):
response = self.http_session.post(
self.ethereum_node_url, json=chunk, timeout=self.slow_timeout
)
if not response.ok:
raise ConnectionError(
f"Error connecting to {self.ethereum_node_url}: {response.text}"
)
results = response.json()
# If there's an error some nodes return a json instead of a list
if isinstance(results, dict) and "error" in results:
logger.error(
"Batch call custom problem with payload=%s, result=%s)",
chunk,
results,
)
raise ValueError(f"Batch request error: {results}")
all_results.extend(results)
return_values: List[Optional[Any]] = []
errors = []
for payload, result in zip(
payloads, sorted(all_results, key=lambda x: x["id"])
):
if "error" in result:
fn_name = payload.get("fn_name", HexBytes(payload["data"]).hex())
errors.append(f'`{fn_name}`: {result["error"]}')
return_values.append(None)
else:
output_type = payload["output_type"]
try:
decoded_values = eth_abi.decode(
output_type, HexBytes(result["result"])
)
normalized_data = map_abi_data(
BASE_RETURN_NORMALIZERS, output_type, decoded_values
)
if len(normalized_data) == 1:
return_values.append(normalized_data[0])
else:
return_values.append(normalized_data)
except (DecodingError, OverflowError):
fn_name = payload.get("fn_name", HexBytes(payload["data"]).hex())
errors.append(f"`{fn_name}`: DecodingError, cannot decode")
return_values.append(None)
if errors and raise_exception:
raise BatchCallFunctionFailed(f"Errors returned {errors}")
else:
return return_values
def batch_call(
self,
contract_functions: Iterable[ContractFunction],
from_address: Optional[ChecksumAddress] = None,
raise_exception: bool = True,
block_identifier: Optional[BlockIdentifier] = "latest",
) -> List[Optional[Any]]:
"""
Do batch requests of multiple contract calls
:param contract_functions: Iterable of contract functions using web3.py contracts. For instance, a valid
argument would be [erc20_contract.functions.balanceOf(address), erc20_contract.functions.decimals()]
:param from_address: Use this address as `from` in every call if provided
:param block_identifier: `latest` by default
:param raise_exception: If False, exception will not be raised if there's any problem and instead `None` will
be returned as the value.
:return: List with the ABI decoded return values
"""
if not contract_functions:
return []
payloads = []
params: TxParams = {"gas": Wei(0), "gasPrice": Wei(0)}
for _, contract_function in enumerate(contract_functions):
if not contract_function.address:
raise ValueError(
f"Missing address for batch_call in `{contract_function.fn_name}`"
)
payload = {
"to": contract_function.address,
"data": contract_function.build_transaction(params)["data"],
"output_type": [
output["type"] for output in contract_function.abi["outputs"]
],
"fn_name": contract_function.fn_name, # For debugging purposes
}
if from_address:
payload["from"] = from_address
payloads.append(payload)
return self.batch_call_custom(
payloads, raise_exception=raise_exception, block_identifier=block_identifier
)
def batch_call_same_function(
self,
contract_function: ContractFunction,
contract_addresses: Sequence[ChecksumAddress],
from_address: Optional[ChecksumAddress] = None,
raise_exception: bool = True,
block_identifier: Optional[BlockIdentifier] = "latest",
) -> List[Optional[Any]]:
"""
Do batch requests using the same function to multiple address. ``batch_call`` could be used to achieve that,
but generating the ContractFunction is slow, so this function allows to use the same contract_function for
multiple addresses
:param contract_function:
:param contract_addresses:
:param from_address:
:param raise_exception:
:param block_identifier:
:return:
"""
assert contract_function, "Contract function is required"
if not contract_addresses:
return []
contract_function.address = NULL_ADDRESS # It's required by web3.py
params: TxParams = {"gas": Wei(0), "gasPrice": Wei(0)}
data = contract_function.build_transaction(params)["data"]
output_type = [output["type"] for output in contract_function.abi["outputs"]]
fn_name = contract_function.fn_name
payloads = []
for contract_address in contract_addresses:
payload = {
"to": contract_address,
"data": data,
"output_type": output_type,
"fn_name": fn_name, # For debugging purposes
}
if from_address:
payload["from"] = from_address
payloads.append(payload)
return self.batch_call_custom(
payloads, raise_exception=raise_exception, block_identifier=block_identifier
)
class Erc20Manager(EthereumClientManager):
"""
Manager for ERC20 operations
"""
# keccak('Transfer(address,address,uint256)')
# ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
TRANSFER_TOPIC = HexBytes(ERC20_721_TRANSFER_TOPIC)
def decode_logs(self, logs: Sequence[LogReceipt]):
decoded_logs = []
for log in logs:
decoded = self._decode_transfer_log(log["data"], log["topics"])
if decoded:
log_copy = dict(log)
log_copy["args"] = decoded
decoded_logs.append(log_copy)
return decoded_logs
def _decode_transfer_log(
self, data: EthereumData, topics: Sequence[bytes]
) -> Optional[Dict[str, Any]]:
topics_len = len(topics)
if topics_len and topics[0] == self.TRANSFER_TOPIC:
if topics_len == 1:
# Not standard Transfer(address from, address to, uint256 unknown)
# 1 topic (transfer topic)
try:
_from, to, unknown = eth_abi.decode(
["address", "address", "uint256"], HexBytes(data)
)
return {"from": _from, "to": to, "unknown": unknown}
except DecodingError:
logger.warning(
"Cannot decode Transfer event `address from, address to, uint256 unknown` from data=%s",
data.hex() if isinstance(data, bytes) else data,
)
return None
elif topics_len == 3:
# ERC20 Transfer(address indexed from, address indexed to, uint256 value)
# 3 topics (transfer topic + from + to)
try:
value_data = HexBytes(data)
value = eth_abi.decode(["uint256"], value_data)[0]
except DecodingError:
logger.warning(
"Cannot decode Transfer event `uint256 value` from data=%s",
value_data.hex(),
)
return None
try:
from_to_data = b"".join(topics[1:])
_from, to = (
fast_to_checksum_address(address)
for address in eth_abi.decode(
["address", "address"], from_to_data
)
)
return {"from": _from, "to": to, "value": value}
except DecodingError:
logger.warning(
"Cannot decode Transfer event `address from, address to` from topics=%s",
HexBytes(from_to_data).hex(),
)
return None
elif topics_len == 4:
# ERC712 Transfer(address indexed from, address indexed to, uint256 indexed tokenId)
# 4 topics (transfer topic + from + to + tokenId)
try:
from_to_token_id_data = b"".join(topics[1:])
_from, to, token_id = eth_abi.decode(
["address", "address", "uint256"], from_to_token_id_data
)
_from, to = [
fast_to_checksum_address(address) for address in (_from, to)
]
return {"from": _from, "to": to, "tokenId": token_id}
except DecodingError:
logger.warning(
"Cannot decode Transfer event `address from, address to` from topics=%s",
HexBytes(from_to_token_id_data).hex(),
)
return None
return None
def get_balance(
self, address: ChecksumAddress, token_address: ChecksumAddress
) -> int:
"""
Get balance of address for `erc20_address`
:param address: owner address
:param token_address: erc20 token address
:return: balance
"""
return (
get_erc20_contract(self.w3, token_address)
.functions.balanceOf(address)
.call()
)
def get_balances(
self, address: ChecksumAddress, token_addresses: Sequence[ChecksumAddress]
) -> List[BalanceDict]:
"""
Get balances for Ether and tokens for an `address`
:param address: Owner address checksummed
:param token_addresses: token addresses to check
:return: ``List[BalanceDict]``
"""
balances = self.ethereum_client.batch_call_same_function(
get_erc20_contract(self.ethereum_client.w3).functions.balanceOf(address),
token_addresses,
raise_exception=False,
)
return_balances = [
{
"token_address": token_address,
"balance": balance
if isinstance(balance, int)
else 0, # A `revert` with bytes can be returned
}
for token_address, balance in zip(token_addresses, balances)
]
# Add ether balance response
return [
{
"token_address": None,
"balance": self.ethereum_client.get_balance(address),
}
] + return_balances
def get_name(self, erc20_address: ChecksumAddress) -> str:
erc20 = get_erc20_contract(self.w3, erc20_address)
data = erc20.functions.name().build_transaction(
{"gas": Wei(0), "gasPrice": Wei(0)}
)["data"]
result = self.w3.eth.call({"to": erc20_address, "data": data})
return decode_string_or_bytes32(result)
def get_symbol(self, erc20_address: ChecksumAddress) -> str:
erc20 = get_erc20_contract(self.w3, erc20_address)
data = erc20.functions.symbol().build_transaction(
{"gas": Wei(0), "gasPrice": Wei(0)}
)["data"]
result = self.w3.eth.call({"to": erc20_address, "data": data})
return decode_string_or_bytes32(result)
def get_decimals(self, erc20_address: ChecksumAddress) -> int:
erc20 = get_erc20_contract(self.w3, erc20_address)
return erc20.functions.decimals().call()
def get_info(self, erc20_address: ChecksumAddress) -> Erc20Info:
"""
Get erc20 information (`name`, `symbol` and `decimals`). Use batching to get
all info in the same request.
:param erc20_address:
:return: Erc20Info
:raises: InvalidERC20Info
"""
erc20 = get_erc20_contract(self.w3, erc20_address)
params: TxParams = {
"gas": Wei(0),
"gasPrice": Wei(0),
} # Prevent executing tx, we are just interested on `data`
datas = [
erc20.functions.name().build_transaction(params)["data"],
erc20.functions.symbol().build_transaction(params)["data"],
erc20.functions.decimals().build_transaction(params)["data"],
]
payload = [
{
"id": i,
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{"to": erc20_address, "data": data}, "latest"],
}
for i, data in enumerate(datas)
]
response = self.http_session.post(
self.ethereum_client.ethereum_node_url,
json=payload,
timeout=self.slow_timeout,
)
if not response.ok:
raise InvalidERC20Info(response.content)
try:
response_json = sorted(response.json(), key=lambda x: x["id"])
errors = [r["error"] for r in response_json if "error" in r]
if errors:
raise InvalidERC20Info(f"{erc20_address} - {errors}")
results = [HexBytes(r["result"]) for r in response_json]
name = decode_string_or_bytes32(results[0])
symbol = decode_string_or_bytes32(results[1])
decimals = eth_abi.decode(["uint8"], results[2])[0]
return Erc20Info(name, symbol, decimals)
except (Web3Exception, DecodingError, ValueError) as e:
raise InvalidERC20Info from e
def get_total_transfer_history(
self,
addresses: Optional[Sequence[ChecksumAddress]] = None,
from_block: BlockIdentifier = BlockNumber(0),
to_block: Optional[BlockIdentifier] = None,
token_address: Optional[ChecksumAddress] = None,
) -> List[LogReceiptDecoded]:
"""
Get events for erc20 and erc721 transfers from and to an `address`. We decode it manually.
Example of an erc20 event:
.. code-block:: python
{'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('0x4d0f25313603e554e3b040667f7f391982babbd195c7ae57a8c84048189f7794'),
'blockHash': HexBytes('0x90fa67d848a0eaf3be625235dae28815389f5292d4465c48d1139f0c207f8d42'),
'blockNumber': 791,
'address': '0xf7d0Bd47BF3214494E7F5B40E392A25cb4788620',
'data': '0x000000000000000000000000000000000000000000000000002001f716742000',
'topics': [HexBytes('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'),
HexBytes('0x000000000000000000000000f5984365fca2e3bc7d2e020abb2c701df9070eb7'),
HexBytes('0x0000000000000000000000001df62f291b2e969fb0849d99d9ce41e2f137006e')],
'type': 'mined'
'args': {'from': '0xf5984365FcA2e3bc7D2E020AbB2c701DF9070eB7',
'to': '0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e',
'value': 9009360000000000
}
}
An example of an erc721 event
{'address': '0x6631FcbB50677DfC6c02CCDcc03a8f68Db427a64',
'blockHash': HexBytes('0x95c71c6c9373e9a8ca2c767dda1cd5083eb6addcce36fc216c9e1f458d6970f9'),
'blockNumber': 5341681,
'data': '0x',
'logIndex': 0,
'removed': False,
'topics': [HexBytes('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'),
HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'),
HexBytes('0x000000000000000000000000b5239c032ab9fb5abfc3903e770a4b6a9095542c'),
HexBytes('0x0000000000000000000000000000000000000000000000000000000000000063')],
'transactionHash': HexBytes('0xce8c8af0503e6f8a421345c10cdf92834c95186916a3f5b1437d2bba63d2db9e'),
'transactionIndex': 0,
'transactionLogIndex': '0x0',
'type': 'mined',
'args': {'from': '0x0000000000000000000000000000000000000000',
'to': '0xb5239C032AB9fB5aBFc3903e770A4B6a9095542C',
'tokenId': 99
}
}
An example of unknown transfer event (no indexed parts), could be a ERC20 or ERC721 transfer:
{'address': '0x6631FcbB50677DfC6c02CCDcc03a8f68Db427a64',
'blockHash': HexBytes('0x95c71c6c9373e9a8ca2c767dda1cd5083eb6addcce36fc216c9e1f458d6970f9'),
'blockNumber': 5341681,
'data': '0x',
'logIndex': 0,
'removed': False,
'topics': [HexBytes('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'),
HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'),
HexBytes('0x000000000000000000000000b5239c032ab9fb5abfc3903e770a4b6a9095542c'),
HexBytes('0x0000000000000000000000000000000000000000000000000000000000000063')],
'transactionHash': HexBytes('0xce8c8af0503e6f8a421345c10cdf92834c95186916a3f5b1437d2bba63d2db9e'),
'transactionIndex': 0,
'transactionLogIndex': '0x0',
'type': 'mined',
'args': {'from': '0x0000000000000000000000000000000000000000',
'to': '0xb5239C032AB9fB5aBFc3903e770A4B6a9095542C',
'unknown': 99
}
}
:param addresses: Search events `from` and `to` these `addresses`. If not, every transfer event within the
range will be retrieved
:param from_block: Block to start querying from
:param to_block: Block to stop querying from
:param token_address: Address of the token
:return: List of events sorted by blockNumber
"""
topic_0 = self.TRANSFER_TOPIC.hex()
if addresses:
addresses_encoded = [
HexBytes(eth_abi.encode(["address"], [address])).hex()
for address in addresses
]
# Topics for transfer `to` and `from` an address
all_topics = [
[topic_0, addresses_encoded], # Topics from
[topic_0, None, addresses_encoded], # Topics to
]
else:
all_topics = [[topic_0]] # All transfer events
parameters: FilterParams = {"fromBlock": from_block}
if to_block:
parameters["toBlock"] = to_block
if token_address:
parameters["address"] = token_address
erc20_events = []
# Do the request to `eth_getLogs`
for topics in all_topics:
parameters["topics"] = topics
# Decode events. Just pick valid ERC20 Transfer events (ERC721 `Transfer` has the same signature)
for event in self.slow_w3.eth.get_logs(parameters):
event["args"] = self._decode_transfer_log(
event["data"], event["topics"]
)
if event["args"]:
erc20_events.append(LogReceiptDecoded(event))
erc20_events.sort(key=lambda x: x["blockNumber"])
return erc20_events
def get_transfer_history(
self,
from_block: int,
to_block: Optional[int] = None,
from_address: Optional[str] = None,
to_address: Optional[str] = None,
token_address: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""
DON'T USE, it will fail in some cases until they fix https://github.com/ethereum/web3.py/issues/1351
Get events for erc20/erc721 transfers. At least one of `from_address`, `to_address` or `token_address` must be
defined. Example of decoded event:
.. code-block:: python
{
"args": {
"from": "0x1Ce67Ea59377A163D47DFFc9BaAB99423BE6EcF1",
"to": "0xaE9E15896fd32E59C7d89ce7a95a9352D6ebD70E",
"value": 15000000000000000
},
"event": "Transfer",
"logIndex": 42,
"transactionIndex": 60,
"transactionHash": "0x71d6d83fef3347bad848e83dfa0ab28296e2953de946ee152ea81c6dfb42d2b3",
"address": "0xfecA834E7da9D437645b474450688DA9327112a5",
"blockHash": "0x054de9a496fc7d10303068cbc7ee3e25181a3b26640497859a5e49f0342e7db2",
"blockNumber": 7265022
}
:param from_block: Block to start querying from
:param to_block: Block to stop querying from
:param from_address: Address sending the erc20 transfer
:param to_address: Address receiving the erc20 transfer
:param token_address: Address of the token
:return: List of events (decoded)
:throws: ReadTimeout
"""
assert (
from_address or to_address or token_address
), "At least one parameter must be provided"
erc20 = get_erc20_contract(self.slow_w3)
argument_filters = {}
if from_address:
argument_filters["from"] = from_address
if to_address:
argument_filters["to"] = to_address
return erc20.events.Transfer.create_filter(
fromBlock=from_block,
toBlock=to_block,
address=token_address,
argument_filters=argument_filters,
).get_all_entries()
def send_tokens(
self,
to: str,
amount: int,
erc20_address: ChecksumAddress,
private_key: str,
nonce: Optional[int] = None,
gas_price: Optional[int] = None,
gas: Optional[int] = None,
) -> bytes:
"""
Send tokens to address
:param to:
:param amount:
:param erc20_address:
:param private_key:
:param nonce:
:param gas_price:
:param gas:
:return: tx_hash
"""
erc20 = get_erc20_contract(self.w3, erc20_address)
account = Account.from_key(private_key)
tx_options: TxParams = {"from": account.address}
if nonce:
tx_options["nonce"] = Nonce(nonce)
if gas_price:
tx_options["gasPrice"] = Wei(gas_price)
if gas:
tx_options["gas"] = Wei(gas)
tx = erc20.functions.transfer(to, amount).build_transaction(tx_options)
return self.ethereum_client.send_unsigned_transaction(
tx, private_key=private_key
)
class Erc721Manager(EthereumClientManager):
# keccak('Transfer(address,address,uint256)')
# ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
TRANSFER_TOPIC = Erc20Manager.TRANSFER_TOPIC
def get_balance(
self, address: ChecksumAddress, token_address: ChecksumAddress
) -> int:
"""
Get balance of address for `erc20_address`
:param address: owner address
:param token_address: erc721 token address
:return: balance
"""
return (
get_erc721_contract(self.w3, token_address)
.functions.balanceOf(address)
.call()
)
def get_balances(
self, address: ChecksumAddress, token_addresses: Sequence[ChecksumAddress]
) -> List[TokenBalance]:
"""
Get balances for tokens for an `address`. If there's a problem with a token_address `0` will be
returned for balance
:param address: Owner address checksummed
:param token_addresses: token addresses to check
:return:
"""
function = get_erc721_contract(self.ethereum_client.w3).functions.balanceOf(
address
)
balances = self.ethereum_client.batch_call_same_function(
function,
token_addresses,
raise_exception=False,
)
return [
TokenBalance(token_address, balance if isinstance(balance, int) else 0)
for (token_address, balance) in zip(token_addresses, balances)
]
def get_info(self, token_address: ChecksumAddress) -> Erc721Info:
"""
Get erc721 information (`name`, `symbol`). Use batching to get
all info in the same request.
:param token_address:
:return: Erc721Info
"""
erc721_contract = get_erc721_contract(self.w3, token_address)
try:
name, symbol = cast(
List[str],
self.ethereum_client.batch_call(
[
erc721_contract.functions.name(),
erc721_contract.functions.symbol(),
]
),
)
return Erc721Info(name, symbol)
except (DecodingError, ValueError): # Not all the ERC721 have metadata
raise InvalidERC721Info
def get_owners(
self, token_addresses_with_token_ids: Sequence[Tuple[ChecksumAddress, int]]
) -> List[Optional[ChecksumAddress]]:
"""
:param token_addresses_with_token_ids: Tuple(token_address: str, token_id: int)
:return: List of owner addresses, `None` if not found
"""
return [
ChecksumAddress(HexAddress(HexStr(owner)))
if isinstance(owner, str)
else None
for owner in self.ethereum_client.batch_call(
[
get_erc721_contract(
self.ethereum_client.w3, token_address
).functions.ownerOf(token_id)
for token_address, token_id in token_addresses_with_token_ids
],
raise_exception=False,
)
]
def get_token_uris(
self, token_addresses_with_token_ids: Sequence[Tuple[ChecksumAddress, int]]
) -> List[Optional[str]]:
"""
:param token_addresses_with_token_ids: Tuple(token_address: str, token_id: int)
:return: List of token_uris, `None` if not found
"""
return [
token_uri if isinstance(token_uri, str) else None
for token_uri in self.ethereum_client.batch_call(
[
get_erc721_contract(
self.ethereum_client.w3, token_address
).functions.tokenURI(token_id)
for token_address, token_id in token_addresses_with_token_ids
],
raise_exception=False,
)
]
class TracingManager(EthereumClientManager):
def filter_out_errored_traces(
self, internal_txs: Sequence[Dict[str, Any]]
) -> Sequence[Dict[str, Any]]:
"""
Filter out errored transactions (traces that are errored or that have an errored parent)
:param internal_txs: Traces for the SAME ethereum tx, sorted ascending by `trace_address`
`sorted(t, key = lambda i: i['traceAddress'])`. It's the default output from methods returning `traces` like
`trace_block` or `trace_transaction`
:return: List of not errored traces
"""
new_list = []
errored_trace_address: Optional[List[int]] = None
for internal_tx in internal_txs:
if internal_tx.get("error") is not None:
errored_trace_address = internal_tx["traceAddress"]
elif (
errored_trace_address is not None
and internal_tx["traceAddress"][: len(errored_trace_address)]
== errored_trace_address
):
continue
else:
new_list.append(internal_tx)
return new_list
def get_previous_trace(
self,
tx_hash: EthereumHash,
trace_address: Sequence[int],
number_traces: int = 1,
skip_delegate_calls: bool = False,
) -> Optional[Dict[str, Any]]:
"""
:param tx_hash:
:param trace_address:
:param number_traces: Number of traces to skip, by default get the immediately previous one
:param skip_delegate_calls: If True filter out delegate calls
:return: Parent trace for a trace
:raises: ``ValueError`` if tracing is not supported
"""
if len(trace_address) < number_traces:
return None
trace_address = trace_address[:-number_traces]
traces = reversed(self.trace_transaction(tx_hash))
for trace in traces:
if trace_address == trace["traceAddress"]:
if (
skip_delegate_calls
and trace["action"].get("callType") == "delegatecall"
):
trace_address = trace_address[:-1]
else:
return trace
def get_next_traces(
self,
tx_hash: EthereumHash,
trace_address: Sequence[int],
remove_delegate_calls: bool = False,
remove_calls: bool = False,
) -> List[FilterTrace]:
"""
:param tx_hash: