forked from ethereum/web3.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheth_module.py
3516 lines (3094 loc) · 134 KB
/
eth_module.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 json
import math
import pytest
from random import (
randint,
)
from typing import (
TYPE_CHECKING,
Callable,
Union,
cast,
)
from eth_typing import (
BlockNumber,
ChecksumAddress,
HexAddress,
HexStr,
)
from eth_utils import (
is_boolean,
is_bytes,
is_checksum_address,
is_dict,
is_integer,
is_list_like,
is_same_address,
is_string,
)
from eth_utils.toolz import (
assoc,
)
from hexbytes import (
HexBytes,
)
from web3._utils.empty import (
empty,
)
from web3._utils.ens import (
ens_addresses,
)
from web3._utils.method_formatters import (
to_hex_if_integer,
)
from web3._utils.module_testing.module_testing_utils import (
assert_contains_log,
async_mock_offchain_lookup_request_response,
mine_pending_block,
mock_offchain_lookup_request_response,
)
from web3._utils.type_conversion import (
to_hex_if_bytes,
)
from web3.exceptions import (
BlockNotFound,
ContractLogicError,
InvalidAddress,
InvalidTransaction,
MultipleFailedRequests,
NameNotFound,
OffchainLookup,
TimeExhausted,
TooManyRequests,
TransactionNotFound,
TransactionTypeMismatch,
ValidationError,
)
from web3.middleware import (
async_geth_poa_middleware,
)
from web3.middleware.fixture import (
async_construct_error_generator_middleware,
async_construct_result_generator_middleware,
construct_error_generator_middleware,
)
from web3.types import ( # noqa: F401
BlockData,
FilterParams,
LogReceipt,
Nonce,
RPCEndpoint,
SyncStatus,
TxParams,
Wei,
)
UNKNOWN_ADDRESS = ChecksumAddress(
HexAddress(HexStr("0xdEADBEeF00000000000000000000000000000000"))
)
UNKNOWN_HASH = HexStr(
"0xdeadbeef00000000000000000000000000000000000000000000000000000000"
)
# "test offchain lookup" as an abi-encoded string
OFFCHAIN_LOOKUP_TEST_DATA = "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001474657374206f6666636861696e206c6f6f6b7570000000000000000000000000" # noqa: E501
# "web3py" as an abi-encoded string
WEB3PY_AS_HEXBYTES = "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000067765623370790000000000000000000000000000000000000000000000000000" # noqa: E501
if TYPE_CHECKING:
from web3 import Web3 # noqa: F401
from web3.contract import Contract # noqa: F401
from _pytest.monkeypatch import MonkeyPatch # noqa: F401
class AsyncEthModuleTest:
@pytest.mark.asyncio
async def test_eth_gas_price(self, async_w3: "Web3") -> None:
gas_price = await async_w3.eth.gas_price # type: ignore
assert gas_price > 0
@pytest.mark.asyncio
async def test_is_connected(self, async_w3: "Web3") -> None:
is_connected = await async_w3.is_connected() # type: ignore
assert is_connected is True
@pytest.mark.asyncio
async def test_eth_send_transaction_legacy(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"gasPrice": await async_w3.eth.gas_price, # type: ignore
}
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert is_same_address(txn["from"], cast(ChecksumAddress, txn_params["from"]))
assert is_same_address(txn["to"], cast(ChecksumAddress, txn_params["to"]))
assert txn["value"] == 1
assert txn["gas"] == 21000
assert txn["gasPrice"] == txn_params["gasPrice"]
@pytest.mark.asyncio
async def test_eth_send_transaction(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxFeePerGas": async_w3.to_wei(3, "gwei"),
"maxPriorityFeePerGas": async_w3.to_wei(1, "gwei"),
}
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert is_same_address(txn["from"], cast(ChecksumAddress, txn_params["from"]))
assert is_same_address(txn["to"], cast(ChecksumAddress, txn_params["to"]))
assert txn["value"] == 1
assert txn["gas"] == 21000
assert txn["maxFeePerGas"] == txn_params["maxFeePerGas"]
assert txn["maxPriorityFeePerGas"] == txn_params["maxPriorityFeePerGas"]
assert txn["gasPrice"] == txn_params["maxFeePerGas"]
@pytest.mark.asyncio
async def test_eth_send_transaction_default_fees(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
}
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert is_same_address(txn["from"], cast(ChecksumAddress, txn_params["from"]))
assert is_same_address(txn["to"], cast(ChecksumAddress, txn_params["to"]))
assert txn["value"] == 1
assert txn["gas"] == 21000
assert txn["maxPriorityFeePerGas"] == 1 * 10**9
assert txn["maxFeePerGas"] >= 1 * 10**9
assert txn["gasPrice"] == txn["maxFeePerGas"]
@pytest.mark.asyncio
async def test_eth_send_transaction_hex_fees(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxFeePerGas": hex(250 * 10**9),
"maxPriorityFeePerGas": hex(2 * 10**9),
}
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert is_same_address(txn["from"], cast(ChecksumAddress, txn_params["from"]))
assert is_same_address(txn["to"], cast(ChecksumAddress, txn_params["to"]))
assert txn["value"] == 1
assert txn["gas"] == 21000
assert txn["maxFeePerGas"] == 250 * 10**9
assert txn["maxPriorityFeePerGas"] == 2 * 10**9
@pytest.mark.asyncio
async def test_eth_send_transaction_no_gas(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"maxFeePerGas": Wei(250 * 10**9),
"maxPriorityFeePerGas": Wei(2 * 10**9),
}
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert is_same_address(txn["from"], cast(ChecksumAddress, txn_params["from"]))
assert is_same_address(txn["to"], cast(ChecksumAddress, txn_params["to"]))
assert txn["value"] == 1
assert txn["gas"] == 121000 # 21000 + buffer
@pytest.mark.asyncio
async def test_eth_send_transaction_with_gas_price(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"gasPrice": Wei(1),
"maxFeePerGas": Wei(250 * 10**9),
"maxPriorityFeePerGas": Wei(2 * 10**9),
}
with pytest.raises(TransactionTypeMismatch):
await async_w3.eth.send_transaction(txn_params) # type: ignore
@pytest.mark.asyncio
async def test_eth_send_transaction_no_priority_fee(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxFeePerGas": Wei(250 * 10**9),
}
with pytest.raises(
InvalidTransaction, match="maxPriorityFeePerGas must be defined"
):
await async_w3.eth.send_transaction(txn_params) # type: ignore
@pytest.mark.asyncio
async def test_eth_send_transaction_no_max_fee(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
maxPriorityFeePerGas = async_w3.to_wei(2, "gwei")
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxPriorityFeePerGas": maxPriorityFeePerGas,
}
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert is_same_address(txn["from"], cast(ChecksumAddress, txn_params["from"]))
assert is_same_address(txn["to"], cast(ChecksumAddress, txn_params["to"]))
assert txn["value"] == 1
assert txn["gas"] == 21000
block = await async_w3.eth.get_block("latest") # type: ignore
assert txn["maxFeePerGas"] == maxPriorityFeePerGas + 2 * block["baseFeePerGas"]
@pytest.mark.asyncio
async def test_eth_send_transaction_max_fee_less_than_tip(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxFeePerGas": Wei(1 * 10**9),
"maxPriorityFeePerGas": Wei(2 * 10**9),
}
with pytest.raises(
InvalidTransaction, match="maxFeePerGas must be >= maxPriorityFeePerGas"
):
await async_w3.eth.send_transaction(txn_params) # type: ignore
@pytest.mark.asyncio
async def test_validation_middleware_chain_id_mismatch(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
wrong_chain_id = 1234567890
actual_chain_id = await async_w3.eth.chain_id # type: ignore
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": Wei(21000),
"maxFeePerGas": async_w3.to_wei(2, "gwei"),
"maxPriorityFeePerGas": async_w3.to_wei(1, "gwei"),
"chainId": wrong_chain_id,
}
with pytest.raises(
ValidationError,
match=f"The transaction declared chain ID {wrong_chain_id}, "
f"but the connected node is on {actual_chain_id}",
):
await async_w3.eth.send_transaction(txn_params) # type: ignore
@pytest.mark.asyncio
async def test_geth_poa_middleware(self, async_w3: "Web3") -> None:
return_block_with_long_extra_data = (
await async_construct_result_generator_middleware(
{
RPCEndpoint("eth_getBlockByNumber"): lambda *_: {
"extraData": "0x" + "ff" * 33
},
}
)
)
async_w3.middleware_onion.inject(async_geth_poa_middleware, "poa", layer=0)
async_w3.middleware_onion.inject(
return_block_with_long_extra_data, "extradata", layer=0
)
block = await async_w3.eth.get_block("latest") # type: ignore
assert "extraData" not in block
assert block.proofOfAuthorityData == b"\xff" * 33
# clean up
async_w3.middleware_onion.remove("poa")
async_w3.middleware_onion.remove("extradata")
@pytest.mark.asyncio
async def test_eth_send_raw_transaction(self, async_w3: "Web3") -> None:
# private key 0x3c2ab4e8f17a7dea191b8c991522660126d681039509dc3bb31af7c9bdb63518
# This is an unfunded account, but the transaction has a 0 gas price, so is
# valid. It never needs to be mined, we just want the transaction hash back
# to confirm.
# tx = {'to': '0x0000000000000000000000000000000000000000', 'value': 0, 'nonce': 1, 'gas': 21000, 'gasPrice': 0, 'chainId': 131277322940537} # noqa: E501
# NOTE: nonce=1 to make txn unique from the non-async version of this test
raw_txn = HexBytes(
"0xf8650180825208940000000000000000000000000000000000000000808086eecac466e115a0ffdd42d7dee4ac85427468bc616812e49432e285e4e8f5cd9381163ac3b28108a04ec6b0d89ecbd5e89b0399f336ad50f283fafd70e86593250bf5a2adfb93d17e" # noqa: E501
)
expected_hash = HexStr(
"0x52b0ff9cb472f25872fa8ec6a62fa59454fc2ae7901cfcc6cc89d096f49b8fc1"
)
txn_hash = await async_w3.eth.send_raw_transaction(raw_txn) # type: ignore
assert txn_hash == async_w3.to_bytes(hexstr=expected_hash)
@pytest.mark.asyncio
async def test_gas_price_strategy_middleware(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
}
two_gwei_in_wei = async_w3.to_wei(2, "gwei")
def gas_price_strategy(w3: "Web3", txn: TxParams) -> Wei:
return two_gwei_in_wei
async_w3.eth.set_gas_price_strategy(gas_price_strategy)
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
assert txn["gasPrice"] == two_gwei_in_wei
async_w3.eth.set_gas_price_strategy(None) # reset strategy
@pytest.mark.asyncio
@pytest.mark.parametrize(
"max_fee", (1000000000, None), ids=["with_max_fee", "without_max_fee"]
)
async def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn(
self,
async_w3: "Web3",
unlocked_account_dual_type: ChecksumAddress,
max_fee: Wei,
) -> None:
max_priority_fee = async_w3.to_wei(1, "gwei")
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxPriorityFeePerGas": max_priority_fee,
}
if max_fee is not None:
txn_params = assoc(txn_params, "maxFeePerGas", max_fee)
def gas_price_strategy(w3: "Web3", txn: TxParams) -> Wei:
return async_w3.to_wei(2, "gwei")
async_w3.eth.set_gas_price_strategy(gas_price_strategy)
txn_hash = await async_w3.eth.send_transaction(txn_params) # type: ignore
txn = await async_w3.eth.get_transaction(txn_hash) # type: ignore
latest_block = await async_w3.eth.get_block("latest") # type: ignore
assert (
txn["maxFeePerGas"] == max_fee
if max_fee is not None
else 2 * latest_block["baseFeePerGas"] + max_priority_fee
)
assert txn["maxPriorityFeePerGas"] == max_priority_fee
assert txn["gasPrice"] == txn["maxFeePerGas"]
async_w3.eth.set_gas_price_strategy(None) # reset strategy
@pytest.mark.asyncio
async def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip(
self,
async_w3: "Web3",
unlocked_account_dual_type: ChecksumAddress,
) -> None:
txn_params: TxParams = {
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
"gas": 21000,
"maxFeePerGas": Wei(1000000000),
}
def gas_price_strategy(_w3: "Web3", _txn: TxParams) -> Wei:
return async_w3.to_wei(2, "gwei")
async_w3.eth.set_gas_price_strategy(gas_price_strategy)
with pytest.raises(
InvalidTransaction, match="maxPriorityFeePerGas must be defined"
):
await async_w3.eth.send_transaction(txn_params) # type: ignore
async_w3.eth.set_gas_price_strategy(None) # reset strategy
@pytest.mark.asyncio
async def test_eth_estimate_gas(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
gas_estimate = await async_w3.eth.estimate_gas(
{ # type: ignore
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
}
)
assert is_integer(gas_estimate)
assert gas_estimate > 0
@pytest.mark.asyncio
async def test_eth_fee_history(self, async_w3: "Web3") -> None:
fee_history = await async_w3.eth.fee_history(1, "latest", [50]) # type: ignore
assert is_list_like(fee_history["baseFeePerGas"])
assert is_list_like(fee_history["gasUsedRatio"])
assert is_integer(fee_history["oldestBlock"])
assert fee_history["oldestBlock"] >= 0
assert is_list_like(fee_history["reward"])
assert is_list_like(fee_history["reward"][0])
@pytest.mark.asyncio
async def test_eth_fee_history_with_integer(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
fee_history = await async_w3.eth.fee_history( # type: ignore
1, empty_block["number"], [50]
)
assert is_list_like(fee_history["baseFeePerGas"])
assert is_list_like(fee_history["gasUsedRatio"])
assert is_integer(fee_history["oldestBlock"])
assert fee_history["oldestBlock"] >= 0
assert is_list_like(fee_history["reward"])
assert is_list_like(fee_history["reward"][0])
@pytest.mark.asyncio
async def test_eth_fee_history_no_reward_percentiles(
self, async_w3: "Web3"
) -> None:
fee_history = await async_w3.eth.fee_history(1, "latest") # type: ignore
assert is_list_like(fee_history["baseFeePerGas"])
assert is_list_like(fee_history["gasUsedRatio"])
assert is_integer(fee_history["oldestBlock"])
assert fee_history["oldestBlock"] >= 0
@pytest.mark.asyncio
async def test_eth_max_priority_fee(self, async_w3: "Web3") -> None:
max_priority_fee = await async_w3.eth.max_priority_fee # type: ignore
assert is_integer(max_priority_fee)
@pytest.mark.asyncio
async def test_eth_max_priority_fee_with_fee_history_calculation(
self, async_w3: "Web3"
) -> None:
fail_max_prio_middleware = await async_construct_error_generator_middleware(
{RPCEndpoint("eth_maxPriorityFeePerGas"): lambda *_: ""}
)
async_w3.middleware_onion.add(
fail_max_prio_middleware, name="fail_max_prio_middleware"
)
with pytest.warns(
UserWarning,
match="There was an issue with the method eth_maxPriorityFeePerGas. "
"Calculating using eth_feeHistory.",
):
max_priority_fee = await async_w3.eth.max_priority_fee # type: ignore
assert is_integer(max_priority_fee)
async_w3.middleware_onion.remove("fail_max_prio_middleware") # clean up
@pytest.mark.asyncio
async def test_eth_getBlockByHash(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
block = await async_w3.eth.get_block(empty_block["hash"]) # type: ignore
assert block["hash"] == empty_block["hash"]
@pytest.mark.asyncio
async def test_eth_getBlockByHash_not_found(self, async_w3: "Web3") -> None:
with pytest.raises(BlockNotFound):
await async_w3.eth.get_block(UNKNOWN_HASH) # type: ignore
@pytest.mark.asyncio
async def test_eth_getBlockByHash_pending(self, async_w3: "Web3") -> None:
block = await async_w3.eth.get_block("pending") # type: ignore
assert block["hash"] is None
@pytest.mark.asyncio
async def test_eth_getBlockByNumber_with_integer(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
block = await async_w3.eth.get_block(empty_block["number"]) # type: ignore
assert block["number"] == empty_block["number"]
@pytest.mark.asyncio
async def test_eth_getBlockByNumber_latest(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
current_block_number = await async_w3.eth.block_number # type: ignore
block = await async_w3.eth.get_block("latest") # type: ignore
assert block["number"] == current_block_number
@pytest.mark.asyncio
async def test_eth_getBlockByNumber_not_found(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
with pytest.raises(BlockNotFound):
await async_w3.eth.get_block(BlockNumber(12345)) # type: ignore
@pytest.mark.asyncio
async def test_eth_getBlockByNumber_pending(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
current_block_number = await async_w3.eth.block_number # type: ignore
block = await async_w3.eth.get_block("pending") # type: ignore
assert block["number"] == current_block_number + 1
@pytest.mark.asyncio
async def test_eth_getBlockByNumber_earliest(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
genesis_block = await async_w3.eth.get_block(BlockNumber(0)) # type: ignore
block = await async_w3.eth.get_block("earliest") # type: ignore
assert block["number"] == 0
assert block["hash"] == genesis_block["hash"]
@pytest.mark.asyncio
@pytest.mark.xfail(reason="Integration test suite not yet set up for PoS")
async def test_eth_getBlockByNumber_safe(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
block = await async_w3.eth.get_block("safe") # type: ignore
assert block is not None
assert isinstance(block["number"], int)
@pytest.mark.asyncio
@pytest.mark.xfail(reason="Integration test suite not yet set up for PoS")
async def test_eth_getBlockByNumber_finalized(
self, async_w3: "Web3", empty_block: BlockData
) -> None:
block = await async_w3.eth.get_block("finalized") # type: ignore
assert block is not None
assert isinstance(block["number"], int)
@pytest.mark.asyncio
async def test_eth_getBlockByNumber_full_transactions(
self, async_w3: "Web3", block_with_txn: BlockData
) -> None:
block = await async_w3.eth.get_block( # type: ignore
block_with_txn["number"], True
)
transaction = block["transactions"][0]
assert transaction["hash"] == block_with_txn["transactions"][0]
@pytest.mark.asyncio
async def test_eth_get_raw_transaction(
self, async_w3: "Web3", mined_txn_hash: HexStr
) -> None:
raw_transaction = await async_w3.eth.get_raw_transaction( # type: ignore
mined_txn_hash
)
assert is_bytes(raw_transaction)
@pytest.mark.asyncio
async def test_eth_get_raw_transaction_raises_error(self, async_w3: "Web3") -> None:
with pytest.raises(
TransactionNotFound, match=f"Transaction with hash: '{UNKNOWN_HASH}'"
):
await async_w3.eth.get_raw_transaction(UNKNOWN_HASH) # type: ignore
@pytest.mark.asyncio
async def test_eth_get_raw_transaction_by_block(
self,
async_w3: "Web3",
block_with_txn: BlockData,
unlocked_account_dual_type: ChecksumAddress,
) -> None:
# eth_getRawTransactionByBlockNumberAndIndex: block identifier
# send a txn to make sure pending block has at least one txn
await async_w3.eth.send_transaction( # type: ignore
{
"from": unlocked_account_dual_type,
"to": unlocked_account_dual_type,
"value": Wei(1),
}
)
pending_block = await async_w3.eth.get_block("pending") # type: ignore
last_pending_txn_index = len(pending_block["transactions"]) - 1
raw_txn = await async_w3.eth.get_raw_transaction_by_block( # type: ignore
"pending", last_pending_txn_index
)
assert is_bytes(raw_txn)
# eth_getRawTransactionByBlockNumberAndIndex: block number
block_with_txn_number = block_with_txn["number"]
raw_transaction = await async_w3.eth.get_raw_transaction_by_block( # type: ignore # noqa: E501
block_with_txn_number, 0
)
assert is_bytes(raw_transaction)
# eth_getRawTransactionByBlockHashAndIndex: block hash
block_with_txn_hash = block_with_txn["hash"]
raw_transaction = await async_w3.eth.get_raw_transaction_by_block( # type: ignore # noqa: E501
block_with_txn_hash, 0
)
assert is_bytes(raw_transaction)
@pytest.mark.asyncio
@pytest.mark.parametrize("unknown_block_num_or_hash", (1234567899999, UNKNOWN_HASH))
async def test_eth_get_raw_transaction_by_block_raises_error(
self, async_w3: "Web3", unknown_block_num_or_hash: Union[int, HexBytes]
) -> None:
with pytest.raises(
TransactionNotFound,
match=(
f"Transaction index: 0 on block id: "
f"{to_hex_if_integer(unknown_block_num_or_hash)!r} "
f"not found."
),
):
await async_w3.eth.get_raw_transaction_by_block( # type: ignore
unknown_block_num_or_hash, 0
)
@pytest.mark.asyncio
async def test_eth_get_raw_transaction_by_block_raises_error_block_identifier(
self, async_w3: "Web3"
) -> None:
unknown_identifier = "unknown"
with pytest.raises(
ValueError,
match=(
"Value did not match any of the recognized block identifiers: "
f"{unknown_identifier}"
),
):
await async_w3.eth.get_raw_transaction_by_block(
unknown_identifier, 0 # type: ignore
)
@pytest.mark.asyncio
async def test_eth_get_balance(self, async_w3: "Web3") -> None:
coinbase = await async_w3.eth.coinbase # type: ignore
with pytest.raises(InvalidAddress):
await async_w3.eth.get_balance( # type: ignore
ChecksumAddress(HexAddress(HexStr(coinbase.lower())))
)
balance = await async_w3.eth.get_balance(coinbase) # type: ignore
assert is_integer(balance)
assert balance >= 0
@pytest.mark.asyncio
async def test_eth_get_code(
self, async_w3: "Web3", math_contract_address: ChecksumAddress
) -> None:
code = await async_w3.eth.get_code(math_contract_address) # type: ignore
assert isinstance(code, HexBytes)
assert len(code) > 0
@pytest.mark.asyncio
async def test_eth_get_code_invalid_address(
self, async_w3: "Web3", math_contract: "Contract"
) -> None:
with pytest.raises(InvalidAddress):
await async_w3.eth.get_code( # type: ignore
ChecksumAddress(HexAddress(HexStr(math_contract.address.lower())))
)
@pytest.mark.asyncio
async def test_eth_get_code_with_block_identifier(
self, async_w3: "Web3", emitter_contract: "Contract"
) -> None:
block_id = await async_w3.eth.block_number # type: ignore
code = await async_w3.eth.get_code( # type: ignore
emitter_contract.address, block_id
)
assert isinstance(code, HexBytes)
assert len(code) > 0
@pytest.mark.asyncio
async def test_eth_get_transaction_count(
self, async_w3: "Web3", unlocked_account_dual_type: ChecksumAddress
) -> None:
transaction_count = await async_w3.eth.get_transaction_count(unlocked_account_dual_type) # type: ignore # noqa E501
assert is_integer(transaction_count)
assert transaction_count >= 0
@pytest.mark.asyncio
async def test_eth_call(self, async_w3: "Web3", math_contract: "Contract") -> None:
coinbase = await async_w3.eth.coinbase # type: ignore
txn_params = math_contract._prepare_transaction(
fn_name="add",
fn_args=(7, 11),
transaction={"from": coinbase, "to": math_contract.address},
)
call_result = await async_w3.eth.call(txn_params) # type: ignore
assert is_string(call_result)
(result,) = async_w3.codec.decode(["uint256"], call_result)
assert result == 18
@pytest.mark.asyncio
async def test_eth_call_with_override(
self, async_w3: "Web3", revert_contract: "Contract"
) -> None:
coinbase = await async_w3.eth.coinbase # type: ignore
txn_params = revert_contract._prepare_transaction(
fn_name="normalFunction",
transaction={"from": coinbase, "to": revert_contract.address},
)
call_result = await async_w3.eth.call(txn_params) # type: ignore
(result,) = async_w3.codec.decode(["bool"], call_result)
assert result is True
# override runtime bytecode: `normalFunction` returns `false`
override_code = HexStr(
"0x6080604052348015600f57600080fd5b5060043610603c5760003560e01c8063185c38a4146041578063c06a97cb146049578063d67e4b84146051575b600080fd5b60476071565b005b604f60df565b005b605760e4565b604051808215151515815260200191505060405180910390f35b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f46756e6374696f6e20686173206265656e2072657665727465642e000000000081525060200191505060405180910390fd5b600080fd5b60008090509056fea2646970667358221220bb71e9e9a2e271cd0fbe833524a3ea67df95f25ea13aef5b0a761fa52b538f1064736f6c63430006010033" # noqa: E501
)
call_result = await async_w3.eth.call( # type: ignore
txn_params, "latest", {revert_contract.address: {"code": override_code}}
)
(result,) = async_w3.codec.decode(["bool"], call_result)
assert result is False
@pytest.mark.asyncio
async def test_eth_call_with_0_result(
self, async_w3: "Web3", math_contract: "Contract"
) -> None:
coinbase = await async_w3.eth.coinbase # type: ignore
txn_params = math_contract._prepare_transaction(
fn_name="add",
fn_args=(0, 0),
transaction={"from": coinbase, "to": math_contract.address},
)
call_result = await async_w3.eth.call(txn_params) # type: ignore
assert is_string(call_result)
(result,) = async_w3.codec.decode(["uint256"], call_result)
assert result == 0
@pytest.mark.asyncio
async def test_eth_call_revert_with_msg(
self,
async_w3: "Web3",
revert_contract: "Contract",
unlocked_account: ChecksumAddress,
) -> None:
with pytest.raises(
ContractLogicError, match="execution reverted: Function has been reverted"
):
txn_params = revert_contract._prepare_transaction(
fn_name="revertWithMessage",
transaction={
"from": unlocked_account,
"to": revert_contract.address,
},
)
await async_w3.eth.call(txn_params) # type: ignore
@pytest.mark.asyncio
async def test_eth_call_revert_without_msg(
self,
async_w3: "Web3",
revert_contract: "Contract",
unlocked_account: ChecksumAddress,
) -> None:
with pytest.raises(ContractLogicError, match="execution reverted"):
txn_params = revert_contract._prepare_transaction(
fn_name="revertWithoutMessage",
transaction={
"from": unlocked_account,
"to": revert_contract.address,
},
)
await async_w3.eth.call(txn_params) # type: ignore
@pytest.mark.asyncio
async def test_eth_call_offchain_lookup(
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
unlocked_account: ChecksumAddress,
monkeypatch: "MonkeyPatch",
) -> None:
normalized_contract_address = to_hex_if_bytes(
async_offchain_lookup_contract.address
).lower()
async_mock_offchain_lookup_request_response(
monkeypatch,
mocked_request_url=f"https://web3.py/gateway/{normalized_contract_address}/{OFFCHAIN_LOOKUP_TEST_DATA}.json", # noqa: E501
mocked_json_data=WEB3PY_AS_HEXBYTES,
)
response_caller = await async_offchain_lookup_contract.caller().testOffchainLookup( # noqa: E501 type: ignore
OFFCHAIN_LOOKUP_TEST_DATA
)
response_function_call = await async_offchain_lookup_contract.functions.testOffchainLookup( # noqa: E501 type: ignore
OFFCHAIN_LOOKUP_TEST_DATA
).call()
assert async_w3.codec.decode(["string"], response_caller)[0] == "web3py"
assert async_w3.codec.decode(["string"], response_function_call)[0] == "web3py"
@pytest.mark.asyncio
async def test_eth_call_offchain_lookup_raises_when_ccip_read_is_disabled(
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
) -> None:
# test AsyncContractCaller
with pytest.raises(OffchainLookup):
await async_offchain_lookup_contract.caller(
ccip_read_enabled=False
).testOffchainLookup( # noqa: E501 type: ignore
OFFCHAIN_LOOKUP_TEST_DATA
)
# test AsyncContractFunction call
with pytest.raises(OffchainLookup):
await async_offchain_lookup_contract.functions.testOffchainLookup(
OFFCHAIN_LOOKUP_TEST_DATA
).call(ccip_read_enabled=False)
# test global flag on the provider
async_w3.provider.global_ccip_read_enabled = False
with pytest.raises(OffchainLookup):
await async_offchain_lookup_contract.functions.testOffchainLookup( # noqa: E501 type: ignore
OFFCHAIN_LOOKUP_TEST_DATA
).call()
async_w3.provider.global_ccip_read_enabled = True # cleanup
@pytest.mark.asyncio
async def test_eth_call_offchain_lookup_call_flag_overrides_provider_flag(
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
unlocked_account: ChecksumAddress,
monkeypatch: "MonkeyPatch",
) -> None:
normalized_contract_address = to_hex_if_bytes(
async_offchain_lookup_contract.address
).lower()
async_mock_offchain_lookup_request_response(
monkeypatch,
mocked_request_url=f"https://web3.py/gateway/{normalized_contract_address}/{OFFCHAIN_LOOKUP_TEST_DATA}.json", # noqa: E501
mocked_json_data=WEB3PY_AS_HEXBYTES,
)
async_w3.provider.global_ccip_read_enabled = False
response = await async_offchain_lookup_contract.functions.testOffchainLookup(
# noqa: E501 type: ignore
OFFCHAIN_LOOKUP_TEST_DATA
).call(ccip_read_enabled=True)
assert async_w3.codec.decode(["string"], response)[0] == "web3py"
async_w3.provider.global_ccip_read_enabled = True # cleanup
@pytest.mark.asyncio
@pytest.mark.parametrize("max_redirects", range(-1, 4))
async def test_eth_call_offchain_lookup_raises_if_max_redirects_is_less_than_4(
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
max_redirects: int,
) -> None:
default_max_redirects = async_w3.provider.ccip_read_max_redirects
async_w3.provider.ccip_read_max_redirects = max_redirects
with pytest.raises(ValueError, match="at least 4"):
await async_offchain_lookup_contract.caller().testOffchainLookup(
OFFCHAIN_LOOKUP_TEST_DATA
)
async_w3.provider.ccip_read_max_redirects = default_max_redirects # cleanup
@pytest.mark.asyncio
async def test_eth_call_offchain_lookup_raises_for_improperly_formatted_rest_request_response( # noqa: E501
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
unlocked_account: ChecksumAddress,
monkeypatch: "MonkeyPatch",
) -> None:
normalized_contract_address = to_hex_if_bytes(
async_offchain_lookup_contract.address
).lower()
async_mock_offchain_lookup_request_response(
monkeypatch,
mocked_request_url=f"https://web3.py/gateway/{normalized_contract_address}/{OFFCHAIN_LOOKUP_TEST_DATA}.json", # noqa: E501
mocked_json_data=WEB3PY_AS_HEXBYTES,
json_data_field="not_data",
)
with pytest.raises(ValidationError, match="missing 'data' field"):
await async_offchain_lookup_contract.caller().testOffchainLookup(
OFFCHAIN_LOOKUP_TEST_DATA
)
@pytest.mark.asyncio
@pytest.mark.parametrize("status_code_non_4xx_error", [100, 300, 500, 600])
async def test_eth_call_offchain_lookup_tries_next_url_for_non_4xx_error_status_and_tests_POST( # noqa: E501
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
unlocked_account: ChecksumAddress,
monkeypatch: "MonkeyPatch",
status_code_non_4xx_error: int,
) -> None:
normalized_contract_address = to_hex_if_bytes(
async_offchain_lookup_contract.address
).lower()
# The next url in our test contract doesn't contain '{data}', triggering
# the POST request logic. The idea here is to return a bad status for the
# first url (GET) and a success status for the second call (POST) to test
# both that we move on to the next url with non-4xx status and that the
# POST logic is also working as expected.
async_mock_offchain_lookup_request_response(
monkeypatch,
mocked_request_url=f"https://web3.py/gateway/{normalized_contract_address}/{OFFCHAIN_LOOKUP_TEST_DATA}.json", # noqa: E501
mocked_status_code=status_code_non_4xx_error,
mocked_json_data=WEB3PY_AS_HEXBYTES,
)
async_mock_offchain_lookup_request_response(
monkeypatch,
http_method="POST",
mocked_request_url=f"https://web3.py/gateway/{normalized_contract_address}.json", # noqa: E501
mocked_status_code=200,
mocked_json_data=WEB3PY_AS_HEXBYTES,
sender=normalized_contract_address,
calldata=OFFCHAIN_LOOKUP_TEST_DATA,
)
response = await async_offchain_lookup_contract.caller().testOffchainLookup(
OFFCHAIN_LOOKUP_TEST_DATA
)
assert async_w3.codec.decode(["string"], response)[0] == "web3py"
@pytest.mark.asyncio
async def test_eth_call_offchain_lookup_calls_raise_for_status_for_4xx_status_code(
self,
async_w3: "Web3",
async_offchain_lookup_contract: "Contract",
unlocked_account: ChecksumAddress,
monkeypatch: "MonkeyPatch",
) -> None:
normalized_contract_address = to_hex_if_bytes(
async_offchain_lookup_contract.address