-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
providers.py
1378 lines (1098 loc) · 45.2 KB
/
providers.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 atexit
import ctypes
import logging
import platform
import shutil
import sys
import time
from abc import ABC
from concurrent.futures import ThreadPoolExecutor
from logging import FileHandler, Formatter, Logger, getLogger
from pathlib import Path
from signal import SIGINT, SIGTERM, signal
from subprocess import DEVNULL, PIPE, Popen
from typing import Any, Dict, Iterator, List, Optional, cast
from eth_typing import HexStr
from eth_utils import add_0x_prefix, is_hex, to_hex
from evm_trace import CallTreeNode, TraceFrame
from hexbytes import HexBytes
from pydantic import Field, root_validator, validator
from web3 import Web3
from web3.eth import TxParams
from web3.exceptions import BlockNotFound
from web3.exceptions import ContractLogicError as Web3ContractLogicError
from web3.exceptions import TimeExhausted
from web3.types import RPCEndpoint
from ape.api.config import PluginConfig
from ape.api.networks import LOCAL_NETWORK_NAME, NetworkAPI
from ape.api.query import BlockTransactionQuery
from ape.api.transactions import ReceiptAPI, TransactionAPI
from ape.exceptions import (
APINotImplementedError,
BlockNotFoundError,
ContractLogicError,
ProviderError,
ProviderNotConnectedError,
RPCTimeoutError,
SubprocessError,
SubprocessTimeoutError,
TransactionError,
TransactionNotFoundError,
VirtualMachineError,
)
from ape.logging import LogLevel, logger
from ape.types import AddressType, BlockID, ContractCode, ContractLog, LogFilter, SnapshotID
from ape.utils import (
EMPTY_BYTES32,
BaseInterfaceModel,
JoinableQueue,
abstractmethod,
cached_property,
gas_estimation_error_message,
raises_not_implemented,
run_until_complete,
spawn,
)
class BlockAPI(BaseInterfaceModel):
"""
An abstract class representing a block and its attributes.
"""
# NOTE: All fields in this class (and it's subclasses) should not be `Optional`
# except the edge cases noted below
num_transactions: int = 0
hash: Optional[Any] = None # NOTE: pending block does not have a hash
number: Optional[int] = None # NOTE: pending block does not have a number
parent_hash: Any = Field(
EMPTY_BYTES32, alias="parentHash"
) # NOTE: genesis block has no parent hash
size: int
timestamp: int
@root_validator(pre=True)
def convert_parent_hash(cls, data):
parent_hash = data.get("parent_hash", data.get("parentHash")) or EMPTY_BYTES32
data["parentHash"] = parent_hash
return data
@validator("hash", "parent_hash", pre=True)
def validate_hexbytes(cls, value):
# NOTE: pydantic treats these values as bytes and throws an error
if value and not isinstance(value, HexBytes):
raise ValueError(f"Hash `{value}` is not a valid Hexbytes.")
return value
@cached_property
def transactions(self) -> List[TransactionAPI]:
query = BlockTransactionQuery(columns=["*"], block_id=self.hash)
return cast(List[TransactionAPI], list(self.query_manager.query(query)))
class ProviderAPI(BaseInterfaceModel):
"""
An abstraction of a connection to a network in an ecosystem. Example ``ProviderAPI``
implementations include the `ape-infura <https://github.com/ApeWorX/ape-infura>`__
plugin or the `ape-hardhat <https://github.com/ApeWorX/ape-hardhat>`__ plugin.
"""
name: str
"""The name of the provider (should be the plugin name)."""
network: NetworkAPI
"""A reference to the network this provider provides."""
provider_settings: dict
"""The settings for the provider, as overrides to the configuration."""
data_folder: Path
"""The path to the ``.ape`` directory."""
request_header: dict
"""A header to set on HTTP/RPC requests."""
cached_chain_id: Optional[int] = None
"""Implementation providers may use this to cache and re-use chain ID."""
block_page_size: int = 100
"""
The amount of blocks to fetch in a response, as a default.
This is particularly useful for querying logs across a block range.
"""
concurrency: int = 4
"""
How many parallel threads to use when fetching logs.
"""
@property
@abstractmethod
def is_connected(self) -> bool:
"""
``True`` if currently connected to the provider. ``False`` otherwise.
"""
@abstractmethod
def connect(self):
"""
Connect a to a provider, such as start-up a process or create an HTTP connection.
"""
@abstractmethod
def disconnect(self):
"""
Disconnect from a provider, such as tear-down a process or quit an HTTP session.
"""
@abstractmethod
def update_settings(self, new_settings: dict):
"""
Change a provider's setting, such as configure a new port to run on.
May require a reconnect.
Args:
new_settings (dict): The new provider settings.
"""
@property
@abstractmethod
def chain_id(self) -> int:
"""
The blockchain ID.
See `ChainList <https://chainlist.org/>`__ for a comprehensive list of IDs.
"""
@abstractmethod
def get_balance(self, address: str) -> int:
"""
Get the balance of an account.
Args:
address (str): The address of the account.
Returns:
int: The account balance.
"""
@abstractmethod
def get_code(self, address: AddressType) -> ContractCode:
"""
Get the bytes a contract.
Args:
address (``AddressType``): The address of the contract.
Returns:
:class:`~ape.types.ContractCode`: The contract bytecode.
"""
@raises_not_implemented
def get_storage_at(self, address: str, slot: int) -> bytes: # type: ignore[empty-body]
"""
Gets the raw value of a storage slot of a contract.
Args:
address (str): The address of the contract.
slot (int): Storage slot to read the value of.
Returns:
bytes: The value of the storage slot.
"""
@abstractmethod
def get_nonce(self, address: AddressType) -> int:
"""
Get the number of times an account has transacted.
Args:
address (``AddressType``): The address of the account.
Returns:
int
"""
@abstractmethod
def estimate_gas_cost(self, txn: TransactionAPI) -> int:
"""
Estimate the cost of gas for a transaction.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`):
The transaction to estimate the gas for.
Returns:
int: The estimated cost of gas to execute the transaction
reported in the fee-currency's smallest unit, e.g. Wei.
"""
@property
@abstractmethod
def gas_price(self) -> int:
"""
The price for what it costs to transact
(pre-`EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__).
"""
@property
def max_gas(self) -> int:
"""
The max gas limit value you can use.
"""
# TODO: Make abstract
return 0
@property
def config(self) -> PluginConfig:
"""
The provider's configuration.
"""
return self.config_manager.get_config(self.name)
@property
def priority_fee(self) -> int:
"""
A miner tip to incentivize them to include your transaction in a block.
Raises:
NotImplementedError: When the provider does not implement
`EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__ typed transactions.
"""
raise APINotImplementedError("priority_fee is not implemented by this provider")
@property
def supports_tracing(self) -> bool:
"""
``True`` when the provider can provide transaction traces.
"""
return False
@property
def base_fee(self) -> int:
"""
The minimum value required to get your transaction included on the next block.
Only providers that implement `EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__
will use this property.
Raises:
NotImplementedError: When this provider does not implement
`EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__.
"""
raise APINotImplementedError("base_fee is not implemented by this provider")
@abstractmethod
def get_block(self, block_id: BlockID) -> BlockAPI:
"""
Get a block.
Args:
block_id (:class:`~ape.types.BlockID`): The ID of the block to get.
Can be ``"latest"``, ``"earliest"``, ``"pending"``, a block hash or a block number.
Raises:
:class:`~ape.exceptions.BlockNotFoundError`: Likely the exception raised when a block
is not found (depends on implementation).
Returns:
:class:`~ape.types.BlockID`: The block for the given ID.
"""
@abstractmethod
def send_call(self, txn: TransactionAPI, **kwargs) -> bytes: # Return value of function
"""
Execute a new transaction call immediately without creating a
transaction on the blockchain.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction
to send as a call.
Returns:
str: The result of the transaction call.
"""
@abstractmethod
def get_receipt(self, txn_hash: str) -> ReceiptAPI:
"""
Get the information about a transaction from a transaction hash.
Args:
txn_hash (str): The hash of the transaction to retrieve.
Returns:
:class:`~api.providers.ReceiptAPI`:
The receipt of the transaction with the given hash.
"""
@abstractmethod
def get_transactions_by_block(self, block_id: BlockID) -> Iterator[TransactionAPI]:
"""
Get the information about a set of transactions from a block.
Args:
block_id (:class:`~ape.types.BlockID`): The ID of the block.
Returns:
Iterator[:class: `~ape.api.transactions.TransactionAPI`]
"""
@abstractmethod
def send_transaction(self, txn: TransactionAPI) -> ReceiptAPI:
"""
Send a transaction to the network.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to send.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
"""
@abstractmethod
def get_contract_logs(self, log_filter: LogFilter) -> Iterator[ContractLog]:
"""
Get logs from contracts.
Args:
log_filter (:class:`~ape.types.LogFilter`): A mapping of event ABIs to
topic filters. Defaults to getting all events.
Returns:
Iterator[:class:`~ape.types.ContractLog`]
"""
@raises_not_implemented
def snapshot(self) -> SnapshotID: # type: ignore[empty-body]
"""
Defined to make the ``ProviderAPI`` interchangeable with a
:class:`~ape.api.providers.TestProviderAPI`, as in
:class:`ape.managers.chain.ChainManager`.
Raises:
NotImplementedError: Unless overridden.
"""
@raises_not_implemented
def revert(self, snapshot_id: SnapshotID): # type: ignore[empty-body]
"""
Defined to make the ``ProviderAPI`` interchangeable with a
:class:`~ape.api.providers.TestProviderAPI`, as in
:class:`ape.managers.chain.ChainManager`.
Raises:
NotImplementedError: Unless overridden.
"""
@raises_not_implemented
def set_timestamp(self, new_timestamp: int): # type: ignore[empty-body]
"""
Defined to make the ``ProviderAPI`` interchangeable with a
:class:`~ape.api.providers.TestProviderAPI`, as in
:class:`ape.managers.chain.ChainManager`.
Raises:
NotImplementedError: Unless overridden.
"""
@raises_not_implemented
def mine(self, num_blocks: int = 1): # type: ignore[empty-body]
"""
Defined to make the ``ProviderAPI`` interchangeable with a
:class:`~ape.api.providers.TestProviderAPI`, as in
:class:`ape.managers.chain.ChainManager`.
Raises:
NotImplementedError: Unless overridden.
"""
@raises_not_implemented
def set_balance(self, address: AddressType, amount: int): # type: ignore[empty-body]
"""
Change the balance of an account.
Args:
address (AddressType): An address on the network.
amount (int): The balance to set in the address.
"""
def __repr__(self) -> str:
try:
chain_id = self.chain_id
except Exception as err:
logger.error(str(err))
chain_id = None
return f"<{self.name} chain_id={self.chain_id}>" if chain_id else f"<{self.name}>"
@raises_not_implemented
def set_code( # type: ignore[empty-body]
self, address: AddressType, code: ContractCode
) -> bool:
"""
Change the code of a smart contract, for development purposes.
Test providers implement this method when they support it.
Args:
address (AddressType): An address on the network.
code (:class:`~ape.types.ContractCode`): The new bytecode.
"""
@raises_not_implemented
def unlock_account(self, address: AddressType) -> bool: # type: ignore[empty-body]
"""
Ask the provider to allow an address to submit transactions without validating
signatures. This feature is intended to be subclassed by a
:class:`~ape.api.providers.TestProviderAPI` so that during a fork-mode test,
a transaction can be submitted by an arbitrary account or contract without a private key.
Raises:
NotImplementedError: When this provider does not support unlocking an account.
Args:
address (``AddressType``): The address to unlock.
Returns:
bool: ``True`` if successfully unlocked account and ``False`` otherwise.
"""
@raises_not_implemented
def get_transaction_trace( # type: ignore[empty-body]
self, txn_hash: str
) -> Iterator[TraceFrame]:
"""
Provide a detailed description of opcodes.
Args:
txn_hash (str): The hash of a transaction to trace.
Returns:
Iterator(TraceFrame): Transaction execution trace object.
"""
@raises_not_implemented
def get_call_tree(self, txn_hash: str) -> CallTreeNode: # type: ignore[empty-body]
"""
Create a tree structure of calls for a transaction.
Args:
txn_hash (str): The hash of a transaction to trace.
Returns:
CallTreeNode: Transaction execution call-tree objects.
"""
def prepare_transaction(self, txn: TransactionAPI) -> TransactionAPI:
"""
Set default values on the transaction.
Raises:
:class:`~ape.exceptions.TransactionError`: When given negative required confirmations.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to prepare.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
"""
# NOTE: Use "expected value" for Chain ID, so if it doesn't match actual, we raise
txn.chain_id = self.network.chain_id
from ape_ethereum.transactions import StaticFeeTransaction, TransactionType
txn_type = TransactionType(txn.type)
if (
txn_type == TransactionType.STATIC
and isinstance(txn, StaticFeeTransaction)
and txn.gas_price is None
):
txn.gas_price = self.gas_price
elif txn_type == TransactionType.DYNAMIC:
if txn.max_priority_fee is None:
txn.max_priority_fee = self.priority_fee
if txn.max_fee is None:
txn.max_fee = self.base_fee + txn.max_priority_fee
# else: Assume user specified the correct amount or txn will fail and waste gas
gas_limit = txn.gas_limit or self.network.gas_limit
if isinstance(gas_limit, str) and gas_limit.isnumeric():
txn.gas_limit = int(gas_limit)
elif isinstance(gas_limit, str) and is_hex(gas_limit):
txn.gas_limit = int(gas_limit, 16)
elif gas_limit == "max":
txn.gas_limit = self.max_gas
elif gas_limit in ("auto", None):
txn.gas_limit = self.estimate_gas_cost(txn)
else:
txn.gas_limit = gas_limit
assert txn.gas_limit not in ("auto", "max")
# else: Assume user specified the correct amount or txn will fail and waste gas
if txn.required_confirmations is None:
txn.required_confirmations = self.network.required_confirmations
elif not isinstance(txn.required_confirmations, int) or txn.required_confirmations < 0:
raise TransactionError(message="'required_confirmations' must be a positive integer.")
return txn
def get_virtual_machine_error(self, exception: Exception) -> VirtualMachineError:
"""
Get a virtual machine error from an error returned from your RPC.
If from a contract revert / assert statement, you will be given a
special :class:`~ape.exceptions.ContractLogicError` that can be
checked in ``ape.reverts()`` tests.
**NOTE**: The default implementation is based on ``geth`` output.
``ProviderAPI`` implementations override when needed.
Args:
exception (Exception): The error returned from your RPC client.
Returns:
:class:`~ape.exceptions.VirtualMachineError`: An error representing what
went wrong in the call.
"""
if isinstance(exception, Web3ContractLogicError):
# This happens from `assert` or `require` statements.
message = str(exception).split(":")[-1].strip()
if message == "execution reverted":
# Reverted without an error message
raise ContractLogicError()
return ContractLogicError(revert_message=message)
if not len(exception.args):
return VirtualMachineError(base_err=exception)
err_data = exception.args[0] if (hasattr(exception, "args") and exception.args) else None
if not isinstance(err_data, dict):
return VirtualMachineError(base_err=exception)
err_msg = err_data.get("message")
if not err_msg:
return VirtualMachineError(base_err=exception)
return VirtualMachineError(message=str(err_msg), code=err_data.get("code"))
class TestProviderAPI(ProviderAPI):
"""
An API for providers that have development functionality, such as snapshotting.
"""
@cached_property
def test_config(self) -> PluginConfig:
return self.config_manager.get_config("test")
@abstractmethod
def snapshot(self) -> SnapshotID:
"""
Record the current state of the blockchain with intent to later
call the method :meth:`~ape.managers.chain.ChainManager.revert`
to go back to this point. This method is for local networks only.
Returns:
:class:`~ape.types.SnapshotID`: The snapshot ID.
"""
@abstractmethod
def revert(self, snapshot_id: SnapshotID):
"""
Regress the current call using the given snapshot ID.
Allows developers to go back to a previous state.
Args:
snapshot_id (str): The snapshot ID.
"""
@abstractmethod
def set_timestamp(self, new_timestamp: int):
"""
Change the pending timestamp.
Args:
new_timestamp (int): The timestamp to set.
Returns:
int: The new timestamp.
"""
@abstractmethod
def mine(self, num_blocks: int = 1):
"""
Advance by the given number of blocks.
Args:
num_blocks (int): The number of blocks allotted to mine. Defaults to ``1``.
"""
class Web3Provider(ProviderAPI, ABC):
"""
A base provider mixin class that uses the
`web3.py <https://web3py.readthedocs.io/en/stable/>`__ python package.
"""
_web3: Optional[Web3] = None
_client_version: Optional[str] = None
@property
def web3(self) -> Web3:
"""
Access to the ``web3`` object as if you did ``Web3(HTTPProvider(uri))``.
"""
if not self._web3:
raise ProviderNotConnectedError()
return self._web3
@property
def client_version(self) -> str:
if not self._web3:
return ""
# NOTE: Gets reset to `None` on `connect()` and `disconnect()`.
if self._client_version is None:
self._client_version = self.web3.clientVersion
return self._client_version
@property
def base_fee(self) -> int:
block = self.get_block("latest")
if not hasattr(block, "base_fee"):
raise APINotImplementedError("No base fee found in block.")
else:
base_fee = block.base_fee # type: ignore
if base_fee is None:
# Non-EIP-1559 chains or we time-travelled pre-London fork.
raise APINotImplementedError("base_fee is not implemented by this provider.")
return base_fee
@property
def is_connected(self) -> bool:
if self._web3 is None:
return False
return run_until_complete(self._web3.is_connected())
@property
def max_gas(self) -> int:
block = self.web3.eth.get_block("latest")
return block["gasLimit"]
@cached_property
def supports_tracing(self) -> bool:
try:
self.get_call_tree(None)
except APINotImplementedError:
return False
except Exception:
return True
return True
def update_settings(self, new_settings: dict):
self.disconnect()
self.provider_settings.update(new_settings)
self.connect()
def estimate_gas_cost(self, txn: TransactionAPI, **kwargs) -> int:
"""
Estimate the cost of gas for a transaction.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`):
The transaction to estimate the gas for.
kwargs:
* ``block_identifier`` (:class:`~ape.types.BlockID`): The block ID
to use when estimating the transaction. Useful for
checking a past estimation cost of a transaction.
* ``state_overrides`` (Dict): Modify the state of the blockchain
prior to estimation.
Returns:
int: The estimated cost of gas to execute the transaction
reported in the fee-currency's smallest unit, e.g. Wei. If the
provider's network has been configured with a gas limit override, it
will be returned. If the gas limit configuration is "max" this will
return the block maximum gas limit.
"""
txn_dict = txn.dict()
# NOTE: "auto" means to enter this method, so remove it from dict
if "gas" in txn_dict and txn_dict["gas"] == "auto":
txn_dict.pop("gas")
# Also pop these, they are overriden by "auto"
txn_dict.pop("maxFeePerGas", None)
txn_dict.pop("maxPriorityFeePerGas", None)
try:
block_id = kwargs.pop("block_identifier", None)
txn_params = cast(TxParams, txn_dict)
return self.web3.eth.estimate_gas(txn_params, block_identifier=block_id)
except ValueError as err:
tx_error = self.get_virtual_machine_error(err)
# If this is the cause of a would-be revert,
# raise ContractLogicError so that we can confirm tx-reverts.
if isinstance(tx_error, ContractLogicError):
raise tx_error from err
message = gas_estimation_error_message(tx_error)
raise TransactionError(base_err=tx_error, message=message) from err
@property
def chain_id(self) -> int:
default_chain_id = None
if self.network.name not in (
"adhoc",
LOCAL_NETWORK_NAME,
) and not self.network.name.endswith("-fork"):
# If using a live network, the chain ID is hardcoded.
default_chain_id = self.network.chain_id
try:
if hasattr(self.web3, "eth"):
return self.web3.eth.chain_id
except ProviderNotConnectedError:
if default_chain_id is not None:
return default_chain_id
raise # Original error
if default_chain_id is not None:
return default_chain_id
raise ProviderNotConnectedError()
@property
def gas_price(self) -> int:
return self._web3.eth.generate_gas_price() # type: ignore
@property
def priority_fee(self) -> int:
return self.web3.eth.max_priority_fee
def get_block(self, block_id: BlockID) -> BlockAPI:
if isinstance(block_id, str) and block_id.isnumeric():
block_id = int(block_id)
try:
block_data = dict(self.web3.eth.get_block(block_id))
except BlockNotFound as err:
raise BlockNotFoundError(block_id) from err
return self.network.ecosystem.decode_block(block_data)
def get_nonce(self, address: str, **kwargs) -> int:
"""
Get the number of times an account has transacted.
Args:
address (str): The address of the account.
kwargs:
* ``block_identifier`` (:class:`~ape.types.BlockID`): The block ID
for checking a previous account nonce.
Returns:
int
"""
block_id = kwargs.pop("block_identifier", None)
return self.web3.eth.get_transaction_count(address, block_identifier=block_id)
def get_balance(self, address: str) -> int:
return self.web3.eth.get_balance(address)
def get_code(self, address: AddressType) -> ContractCode:
return self.web3.eth.get_code(address)
def get_storage_at(self, address: str, slot: int, **kwargs) -> bytes:
"""
Gets the raw value of a storage slot of a contract.
Args:
address (str): The address of the contract.
slot (int): Storage slot to read the value of.
kwargs:
* ``block_identifier`` (:class:`~ape.types.BlockID`): The block ID
for checking previous contract storage values.
Returns:
bytes: The value of the storage slot.
"""
block_id = kwargs.pop("block_identifier", None)
try:
return self.web3.eth.get_storage_at(address, slot, block_identifier=block_id)
except ValueError as err:
if "RPC Endpoint has not been implemented" in str(err):
raise APINotImplementedError(str(err)) from err
raise # Raise original error
def send_call(self, txn: TransactionAPI, **kwargs) -> bytes:
"""
Execute a new transaction call immediately without creating a
transaction on the block chain.
Args:
txn: :class:`~ape.api.transactions.TransactionAPI`
kwargs:
* ``block_identifier`` (:class:`~ape.types.BlockID`): The block ID
to use to send a call at a historical point of a contract.
checking a past estimation cost of a transaction.
* ``state_overrides`` (Dict): Modify the state of the blockchain
prior to sending the call, for testing purposes.
* ``show_trace`` (bool): Set to ``True`` to display the call's
trace. Defaults to ``False``.
* ``show_gas_report (bool): Set to ``True`` to display the call's
gas report. Defaults to ``False``.
* ``skip_trace`` (bool): Set to ``True`` to skip the trace no matter
what. This is useful if you are making a more background contract call
of some sort, such as proxy-checking, and you are running a global
call-tracer such as using the ``--gas`` flag in tests.
Returns:
str: The result of the transaction call.
"""
skip_trace = kwargs.pop("skip_trace", False)
if skip_trace:
return self._send_call(txn, **kwargs)
track_gas = self.chain_manager._reports.track_gas
show_trace = kwargs.pop("show_trace", False)
show_gas = kwargs.pop("show_gas_report", False)
needs_trace = track_gas or show_trace or show_gas
if not needs_trace or not self.provider.supports_tracing or not txn.receiver:
return self._send_call(txn, **kwargs)
# The user is requesting information related to a call's trace,
# such as gas usage data.
try:
with self.chain_manager.isolate():
return self._send_call_as_txn(
txn, track_gas=track_gas, show_trace=show_trace, show_gas=show_gas, **kwargs
)
except APINotImplementedError:
return self._send_call(txn, **kwargs)
def _send_call_as_txn(
self,
txn: TransactionAPI,
track_gas: bool = False,
show_trace: bool = False,
show_gas: bool = False,
**kwargs,
) -> bytes:
account = self.account_manager.test_accounts[0]
receipt = account.call(txn)
call_tree = receipt.call_tree
if not call_tree:
return self._send_call(txn, **kwargs)
if track_gas:
receipt.track_gas()
if show_trace:
self.chain_manager._reports.show_trace(call_tree)
if show_gas:
self.chain_manager._reports.show_gas(call_tree)
return call_tree.returndata
def _send_call(self, txn: TransactionAPI, **kwargs) -> bytes:
arguments = self._prepare_call(txn, **kwargs)
return self._eth_call(arguments)
def _eth_call(self, arguments: List) -> bytes:
try:
result = self._make_request("eth_call", arguments)
except Exception as err:
raise self.get_virtual_machine_error(err) from err
return HexBytes(result)
def _prepare_call(self, txn: TransactionAPI, **kwargs) -> List:
txn_dict = txn.dict()
fields_to_convert = ("data", "chainId", "value")
for field in fields_to_convert:
value = txn_dict.get(field)
if value is not None and not isinstance(value, str):
txn_dict[field] = to_hex(value)
# Remove unneeded properties
txn_dict.pop("gas", None)
txn_dict.pop("gasLimit", None)
txn_dict.pop("maxFeePerGas", None)
txn_dict.pop("maxPriorityFeePerGas", None)
block_identifier = kwargs.pop("block_identifier", "latest")
if isinstance(block_identifier, int):
block_identifier = to_hex(block_identifier)
arguments = [txn_dict, block_identifier]
if "state_override" in kwargs:
arguments.append(kwargs["state_override"])
return arguments
def get_receipt(
self, txn_hash: str, required_confirmations: int = 0, timeout: Optional[int] = None
) -> ReceiptAPI:
"""
Get the information about a transaction from a transaction hash.
Args:
txn_hash (str): The hash of the transaction to retrieve.
required_confirmations (int): The amount of block confirmations
to wait before returning the receipt. Defaults to ``0``.
timeout (Optional[int]): The amount of time to wait for a receipt
before timing out. Defaults ``None``.
Raises:
:class:`~ape.exceptions.TransactionNotFoundError`: Likely the exception raised
when the transaction receipt is not found (depends on implementation).
Returns:
:class:`~api.providers.ReceiptAPI`:
The receipt of the transaction with the given hash.
"""
if required_confirmations < 0:
raise TransactionError(message="Required confirmations cannot be negative.")
timeout = (
timeout if timeout is not None else self.provider.network.transaction_acceptance_timeout
)
try:
receipt_data = self.web3.eth.wait_for_transaction_receipt(
HexBytes(txn_hash), timeout=timeout
)
except TimeExhausted as err:
raise TransactionNotFoundError(txn_hash) from err
txn = dict(self.web3.eth.get_transaction(HexStr(txn_hash)))
receipt = self.network.ecosystem.decode_receipt(
{
"provider": self,
"required_confirmations": required_confirmations,
**txn,
**receipt_data,
}
)
return receipt.await_confirmations()
def get_transactions_by_block(self, block_id: BlockID) -> Iterator:
if isinstance(block_id, str):