forked from ApeWorX/ape
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecosystem.py
More file actions
1610 lines (1325 loc) · 60.2 KB
/
Copy pathecosystem.py
File metadata and controls
1610 lines (1325 loc) · 60.2 KB
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 re
from collections.abc import Iterator, Sequence
from decimal import Decimal
from functools import cached_property
from typing import TYPE_CHECKING, Any, ClassVar, cast
import rlp # type: ignore
from cchecksum import to_checksum_address
from eth_abi import decode, encode
from eth_abi.exceptions import InsufficientDataBytes, NonEmptyPaddingBytes
from eth_pydantic_types import HexBytes
from eth_typing import Hash32, HexStr
from eth_utils import (
add_0x_prefix,
encode_hex,
humanize_hash,
is_0x_prefixed,
is_hex,
is_hex_address,
keccak,
to_bytes,
to_hex,
)
from ethpm_types.abi import ABIType, ConstructorABI, EventABI, MethodABI
from pydantic import Field, computed_field, field_validator, model_validator
from pydantic_settings import SettingsConfigDict
from ape.api.config import PluginConfig
from ape.api.networks import EcosystemAPI
from ape.api.providers import BlockAPI
from ape.contracts.base import ContractCall
from ape.exceptions import (
ApeException,
APINotImplementedError,
ConversionError,
CustomError,
DecodingError,
SignatureError,
)
from ape.logging import logger
from ape.managers.config import merge_configs
from ape.types.address import AddressType, RawAddress
from ape.types.basic import HexInt
from ape.types.events import ContractLog
from ape.types.gas import AutoGasLimit, GasLimit
from ape.types.signatures import TransactionSignature
from ape.types.units import CurrencyValueComparable
from ape.utils.abi import LogInputABICollection, Struct, StructParser, is_array, returns_array
from ape.utils.basemodel import _assert_not_ipython_check, only_raise_attribute_error
from ape.utils.misc import (
DEFAULT_LIVE_NETWORK_BASE_FEE_MULTIPLIER,
DEFAULT_LOCAL_TRANSACTION_ACCEPTANCE_TIMEOUT,
DEFAULT_MAX_RETRIES_TX,
DEFAULT_TRANSACTION_ACCEPTANCE_TIMEOUT,
DEFAULT_TRANSACTION_TYPE,
EMPTY_BYTES32,
LOCAL_NETWORK_NAME,
ZERO_ADDRESS,
)
from ape_ethereum.proxies import (
GET_APP_ABI,
IMPLEMENTATION_ABI,
MASTER_COPY_ABI,
PROXY_TYPE_ABI,
ProxyInfo,
ProxyType,
)
from ape_ethereum.trace import _REVERT_PREFIX, Trace, TransactionTrace
from ape_ethereum.transactions import (
AccessListTransaction,
BaseTransaction,
DynamicFeeTransaction,
Receipt,
SetCodeTransaction,
SharedBlobReceipt,
SharedBlobTransaction,
StaticFeeTransaction,
TransactionStatusEnum,
TransactionType,
)
from ape_ethereum.utils import strip_compiler_metadata, strip_push_data
if TYPE_CHECKING:
from ethpm_types import ContractType
from ape.api.trace import TraceAPI
from ape.api.transactions import ReceiptAPI, TransactionAPI
NETWORKS = {
# chain_id, network_id
"mainnet": (1, 1),
"sepolia": (11155111, 11155111),
"holesky": (17000, 17000),
}
BLUEPRINT_HEADER = HexBytes("0xfe71")
class NetworkConfig(PluginConfig):
"""
The Ethereum network config base class for each
network, e.g. ``"mainnet"``, ```"local"``, etc.
"""
required_confirmations: int = 0
"""
The amount of blocks to wait before
considering a transaction 'confirmed'.
"""
default_provider: str | None = "node"
"""
The default provider to use. If set to ``None``, ape will rely on
an external plugin supplying the provider implementation, such as
``ape-hardhat`` supplying forked-network providers.
"""
block_time: int = 0
"""
Approximate amount of time for a block to be
added to the network.
"""
transaction_acceptance_timeout: int = DEFAULT_TRANSACTION_ACCEPTANCE_TIMEOUT
"""
The amount tof time before failing when sending a
transaction and it leaving the mempool.
"""
default_transaction_type: TransactionType = TransactionType.DYNAMIC
"""
The default type of transaction to use.
"""
max_receipt_retries: int = DEFAULT_MAX_RETRIES_TX
"""
Maximum number of retries when getting a receipt
from a transaction before failing.
"""
gas_limit: GasLimit = AutoGasLimit()
"""
The gas limit override to use for the network. If set to ``"auto"``, ape will
estimate gas limits based on the transaction. If set to ``"max"`` the gas limit
will be set to the maximum block gas limit for the network. Otherwise an ``int``
can be used to specify an explicit gas limit amount (either base 10 or 16).
The default for local networks is ``"max"``, otherwise ``"auto"``.
"""
base_fee_multiplier: float = 1.0
"""A multiplier to apply to a transaction base fee."""
is_mainnet: bool | None = None
"""
Set to ``True`` to declare as a mainnet or ``False`` to ensure
it isn't detected as one.
"""
request_headers: dict = {}
"""Optionally config extra request headers whenever using this network."""
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_ETHEREUM_")
@field_validator("gas_limit", mode="before")
@classmethod
def validate_gas_limit(cls, value):
if isinstance(value, dict):
value = value.get("auto", {})
return AutoGasLimit.model_validate(value)
elif value == "auto":
return AutoGasLimit()
elif value in ("auto", "max") or isinstance(value, AutoGasLimit):
return value
elif isinstance(value, int):
return value
elif isinstance(value, str) and value.isnumeric():
return int(value)
elif isinstance(value, str) and is_hex(value):
if is_0x_prefixed(value):
return int(value, 16)
# Else, we don't know if it is base 10 or 16.
raise ValueError("Gas limit hex str must include '0x' prefix.")
raise ValueError(f"Invalid gas limit '{value}'")
class ForkedNetworkConfig(NetworkConfig):
upstream_provider: str | None = None
"""
The provider to use as the upstream-provider for this forked network.
"""
def create_local_network_config(
default_provider: str | None = None, use_fork: bool = False, **kwargs
):
if "gas_limit" not in kwargs:
kwargs["gas_limit"] = "max"
return create_network_config(
base_fee_multiplier=1.0,
default_provider=default_provider,
required_confirmations=0,
transaction_acceptance_timeout=DEFAULT_LOCAL_TRANSACTION_ACCEPTANCE_TIMEOUT,
cls=ForkedNetworkConfig if use_fork else NetworkConfig,
**kwargs,
)
def create_network_config(
required_confirmations: int = 2,
base_fee_multiplier: float = DEFAULT_LIVE_NETWORK_BASE_FEE_MULTIPLIER,
cls: type = NetworkConfig,
**kwargs,
) -> NetworkConfig:
return cls(
base_fee_multiplier=base_fee_multiplier,
required_confirmations=required_confirmations,
**kwargs,
)
class BaseEthereumConfig(PluginConfig):
"""
L2 plugins should use this as their config base-class.
"""
DEFAULT_TRANSACTION_TYPE: ClassVar[int] = TransactionType.DYNAMIC.value
DEFAULT_LOCAL_GAS_LIMIT: ClassVar[GasLimit] = "max"
NETWORKS: ClassVar[dict[str, tuple[int, int]]] = NETWORKS
default_network: str = LOCAL_NETWORK_NAME
_forked_configs: dict[str, ForkedNetworkConfig] = {}
_custom_networks: dict[str, NetworkConfig] = {}
# NOTE: This gets appended to Ape's root User-Agent string.
request_headers: dict = {}
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_ETHEREUM_")
@model_validator(mode="before")
@classmethod
def load_network_configs(cls, values):
cfg_forks: dict[str, ForkedNetworkConfig] = {}
custom_networks = {}
for name, obj in values.items():
if name.startswith("_"):
continue
net_name = name.replace("-", "_")
key = net_name.replace("_fork", "")
if net_name.endswith("_fork"):
key = net_name.replace("_fork", "")
default_fork_model = create_local_network_config(
use_fork=True,
default_transaction_type=cls.DEFAULT_TRANSACTION_TYPE,
gas_limit=cls.DEFAULT_LOCAL_GAS_LIMIT,
).model_dump(by_alias=True)
data = merge_configs(default_fork_model, obj)
cfg_forks[key] = ForkedNetworkConfig.model_validate(data)
elif (
key != LOCAL_NETWORK_NAME
and key not in cls.NETWORKS
and isinstance(obj, dict)
and key not in ("request_headers",)
):
# Custom network.
default_network_model = create_network_config(
default_transaction_type=cls.DEFAULT_TRANSACTION_TYPE
).model_dump(by_alias=True)
data = merge_configs(default_network_model, obj)
custom_networks[name] = NetworkConfig.model_validate(data)
values["_forked_configs"] = {**cfg_forks, **values.get("_forked_configs", {})}
return {**values, **custom_networks}
@computed_field # type: ignore[misc]
@cached_property
def local(self) -> NetworkConfig:
default_config = create_local_network_config(
default_provider="test",
default_transaction_type=self.DEFAULT_TRANSACTION_TYPE,
gas_limit=self.DEFAULT_LOCAL_GAS_LIMIT,
)
configured_local: dict[str, Any] | NetworkConfig | None = PluginConfig.get(
self, LOCAL_NETWORK_NAME
)
if configured_local is None:
return default_config
if isinstance(configured_local, NetworkConfig):
configured_local = configured_local.model_dump(by_alias=True)
if not isinstance(configured_local, dict):
return default_config
return NetworkConfig.model_validate(
merge_configs(default_config.model_dump(by_alias=True), configured_local)
)
@only_raise_attribute_error
def __getattr__(self, key: str) -> Any:
_assert_not_ipython_check(key)
net_key = key.replace("-", "_")
if net_key.endswith("_fork"):
return self._get_forked_config(net_key)
try:
return super().__getattr__(key)
except AttributeError:
return NetworkConfig(default_transaction_type=self.DEFAULT_TRANSACTION_TYPE)
def __contains__(self, key: str) -> bool:
net_key = key.replace("-", "_")
if net_key.endswith("_fork"):
return self._get_forked_config(net_key) is not None
return super().__contains__(key)
def get(self, key: str, default: Any | None = None) -> Any:
net_key = key.replace("-", "_")
if net_key.endswith("_fork"):
if cfg := self._get_forked_config(net_key):
return cfg
result: Any
if result := super().get(key, default=default):
return result
# Handle weird base-class differences.
try:
return self.__getattr__(key)
except AttributeError:
return default
def _get_forked_config(self, name: str) -> ForkedNetworkConfig | None:
live_key: str = name.replace("_fork", "")
if self._forked_configs.get(live_key):
return self._forked_configs[live_key]
live_cfg: Any
if live_cfg := self.get(live_key):
if isinstance(live_cfg, NetworkConfig):
fork_cfg = create_local_network_config(
use_fork=True,
default_transaction_type=self.DEFAULT_TRANSACTION_TYPE,
gas_limit=self.DEFAULT_LOCAL_GAS_LIMIT,
)
self._forked_configs[live_key] = fork_cfg
return fork_cfg
return None
def _get_custom_network(self, name: str) -> NetworkConfig:
return self._custom_networks.get(name, NetworkConfig())
class EthereumConfig(BaseEthereumConfig):
mainnet: NetworkConfig = create_network_config(block_time=13)
holesky: NetworkConfig = create_network_config(block_time=13)
sepolia: NetworkConfig = create_network_config(block_time=15)
class Block(BlockAPI):
"""
Class for representing a block on a chain.
"""
gas_limit: HexInt = Field(alias="gasLimit")
gas_used: HexInt = Field(alias="gasUsed")
base_fee: HexInt = Field(default=0, alias="baseFeePerGas")
difficulty: HexInt = 0
total_difficulty: HexInt = Field(default=0, alias="totalDifficulty")
uncles: list[HexBytes] = []
# Type re-declares.
hash: HexBytes | None = None
parent_hash: HexBytes = Field(
default=EMPTY_BYTES32, alias="parentHash"
) # NOTE: genesis block has no parent hash
@computed_field() # type: ignore[misc]
@property
def size(self) -> int:
if self._size is not None:
# The size was provided with the rest of the model
# (normal).
return self._size
number = self.number
if number is None:
raise APINotImplementedError()
# Try to get it from the provider.
elif provider := self.network_manager.active_provider:
block = provider.get_block(number)
size = block._size
if size is not None and size > -1:
self._size = size
return size
raise APINotImplementedError()
class Ethereum(EcosystemAPI):
# NOTE: `default_transaction_type` should be overridden
# if the chain doesn't support EIP-1559.
fee_token_symbol: str = "ETH"
@property
def config(self) -> EthereumConfig:
return cast(EthereumConfig, super().config)
@property
def default_transaction_type(self) -> TransactionType:
if provider := self.network_manager.active_provider:
# Check connected network first.
networks_to_check = [provider.network.name, self.default_network_name]
else:
networks_to_check = [self.default_network_name]
for name in networks_to_check:
network = self.get_network(name)
ecosystem_config = network.ecosystem_config
ecosystem_default = ecosystem_config.get(
"default_transaction_type", DEFAULT_TRANSACTION_TYPE
)
result: int = network.config.get("default_transaction_type", ecosystem_default)
return TransactionType(result)
return TransactionType(DEFAULT_TRANSACTION_TYPE)
@classmethod
def decode_address(cls, raw_address: RawAddress) -> AddressType:
return to_checksum_address(HexBytes(raw_address)[-20:].rjust(20, b"\x00"))
@classmethod
def encode_address(cls, address: AddressType) -> RawAddress:
return f"{address}"
def decode_transaction_type(self, transaction_type_id: Any) -> type["TransactionAPI"]:
if isinstance(transaction_type_id, TransactionType):
tx_type = transaction_type_id
elif isinstance(transaction_type_id, int):
tx_type = TransactionType(transaction_type_id)
else:
# Using hex or alike.
tx_type = self.conversion_manager.convert(transaction_type_id, int)
if tx_type is TransactionType.STATIC:
return StaticFeeTransaction
elif tx_type is TransactionType.ACCESS_LIST:
return AccessListTransaction
elif tx_type is TransactionType.SET_CODE:
return SetCodeTransaction
return DynamicFeeTransaction
def encode_contract_blueprint(
self, contract_type: "ContractType", *args, **kwargs
) -> "TransactionAPI":
# EIP-5202 implementation.
bytes_obj = contract_type.deployment_bytecode
contract_bytes = (bytes_obj.to_bytes() or b"") if bytes_obj else b""
header = kwargs.pop("header", BLUEPRINT_HEADER)
blueprint_bytecode = header + b"\x00" + contract_bytes
len_bytes = len(blueprint_bytecode).to_bytes(2, "big")
return_data_size = kwargs.pop("return_data_size", HexBytes("0x61"))
return_instructions = kwargs.pop("return_instructions", HexBytes("0x3d81600a3d39f3"))
deploy_bytecode = HexBytes(
return_data_size + len_bytes + return_instructions + blueprint_bytecode
)
converted_kwargs = self.conversion_manager.convert_method_kwargs(kwargs)
return self.encode_deployment(
deploy_bytecode, contract_type.constructor, **converted_kwargs
)
def get_proxy_info(self, address: AddressType) -> ProxyInfo | None:
contract_code = self.chain_manager.get_code(address)
code_bytes = HexBytes(contract_code)
if not code_bytes:
return None
code = code_bytes.hex()
patterns = {
ProxyType.Minimal: r"^363d3d373d3d3d363d73(.{40})5af43d82803e903d91602b57fd5bf3",
ProxyType.ZeroAge: r"^3d3d3d3d363d3d37363d73(.{40})5af43d3d93803e602a57fd5bf3",
ProxyType.Clones: r"^36603057343d52307f830d2d700a97af574b186c80d40429385d24241565b08a7c559ba283a964d9b160203da23d3df35b3d3d3d3d363d3d37363d73(.{40})5af43d3d93803e605b57fd5bf3",
ProxyType.Vyper: r"^366000600037611000600036600073(.{40})5af4602c57600080fd5b6110006000f3",
ProxyType.VyperBeta: r"^366000600037611000600036600073(.{40})5af41558576110006000f3",
ProxyType.CWIA: r"^3d3d3d3d363d3d3761.{4}603736393661.{4}013d73(.{40})5af43d3d93803e603557fd5bf3.*",
ProxyType.OldCWIA: r"^363d3d3761.{4}603836393d3d3d3661.{4}013d73(.{40})5af43d82803e903d91603657fd5bf3.*",
ProxyType.SudoswapCWIA: r"^3d3d3d3d363d3d37605160353639366051013d73(.{40})5af43d3d93803e603357fd5bf3.*",
ProxyType.SoladyCWIA: r"36602c57343d527f9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff593da1005b363d3d373d3d3d3d61.{4}806062363936013d73(.{40})5af43d3d93803e606057fd5bf3.*",
ProxyType.SplitsCWIA: r"36602f57343d527f9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff60203da13d3df35b3d3d3d3d363d3d3761.{4}606736393661.{4}013d73(.{40})5af43d3d93803e606557fd5bf3.*",
ProxyType.SoladyPush0: r"^5f5f365f5f37365f73(.{40})5af43d5f5f3e6029573d5ffd5b3d5ff3",
ProxyType.SetCode: r"^ef0100(.{40})$",
}
for type_, pattern in patterns.items():
if match := re.match(pattern, code):
target = self.conversion_manager.convert(match.group(1), AddressType)
return ProxyInfo(type=type_, target=target)
# eip-897 delegate proxy, read `proxyType()` and `implementation()`.
# Proxy type 1 is a forwarding proxy and may not have an executable
# DELEGATECALL opcode, so handle EIP-897 before the opcode gate.
eip897_pattern = b"\x63" + self.get_method_selector(PROXY_TYPE_ABI)
if eip897_pattern.hex() in code:
try:
proxy_type = ContractCall(PROXY_TYPE_ABI, address)(skip_trace=True)
if proxy_type not in (1, 2):
raise ValueError(f"ProxyType '{proxy_type}' not permitted by EIP-897.")
target = ContractCall(IMPLEMENTATION_ABI, address)(skip_trace=True)
# avoid recursion
if target != ZERO_ADDRESS:
return ProxyInfo(type=ProxyType.Delegate, target=target, abi=IMPLEMENTATION_ABI)
except (ApeException, ValueError):
pass
# Remaining proxy types delegate calls to their implementation. If
# runtime bytecode has no executable DELEGATECALL opcode, avoid storage
# probes and calls entirely.
opcodes = strip_push_data(strip_compiler_metadata(code_bytes))
if 0xF4 not in opcodes:
return None
sequence_pattern = r"363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3"
if re.match(sequence_pattern, code):
# the implementation is stored in the slot matching proxy address
slot = self.provider.get_storage(address, address)
target = self.conversion_manager.convert(slot[-20:], AddressType)
return ProxyInfo(type=ProxyType.Sequence, target=target)
# Safe >1.0.0 provides `masterCopy()`, which is also stored in slot 0.
# Check the bytecode marker first to avoid unrelated storage checks and calls.
master_copy_selector = self.get_method_selector(MASTER_COPY_ABI).hex()
safe_master_copy_markers = (
# Safe v1.1.0 through v1.4.1 compares calldata against a padded PUSH32.
f"7f{master_copy_selector}{'00' * 28}",
# Optimized builds may reconstruct the same padded selector with PUSH4 + SHL.
"63530ca43760e11b14",
# Safe v1.5.0+ compares the first 4 calldata bytes against a PUSH4.
f"63{master_copy_selector}",
)
if any(marker in code for marker in safe_master_copy_markers):
try:
slot_0 = self.provider.get_storage(address, 0)
target = self.conversion_manager.convert(slot_0[-20:], AddressType)
# NOTE: `target` is set in initialized proxies
if target != ZERO_ADDRESS and target == ContractCall(MASTER_COPY_ABI, address)(
skip_trace=True
):
return ProxyInfo(type=ProxyType.GnosisSafe, target=target, abi=MASTER_COPY_ABI)
except ApeException:
pass
def str_to_slot(text):
return int(to_hex(keccak(text=text)), 16)
slots = {
ProxyType.Standard: str_to_slot("eip1967.proxy.implementation") - 1,
ProxyType.Beacon: str_to_slot("eip1967.proxy.beacon") - 1,
ProxyType.OpenZeppelin: str_to_slot("org.zeppelinos.proxy.implementation"),
ProxyType.UUPS: str_to_slot("PROXIABLE"),
}
get_storage_supported = True
for _type, slot in slots.items():
try:
# TODO perf: use a batch call here when ape adds support
storage = self.provider.get_storage(address, slot)
except NotImplementedError:
# Break early on not-implemented error rather than attempting
# to try more proxy types.
get_storage_supported = False
break
if sum(storage) == 0:
continue
target = self.conversion_manager.convert(storage[-20:], AddressType)
# read `target.implementation()`
if _type == ProxyType.Beacon:
target = ContractCall(IMPLEMENTATION_ABI, target)(skip_trace=True)
return ProxyInfo(type=_type, target=target, abi=IMPLEMENTATION_ABI)
# aragonOS AppProxyUpgradeable: kernel + appId stored at fixed slots; the
# implementation is resolved through Kernel.getApp(APP_BASES_NAMESPACE, appId).
if get_storage_supported:
kernel_storage = self.provider.get_storage(
address, str_to_slot("aragonOS.appStorage.kernel")
)
if sum(kernel_storage) != 0:
kernel = self.conversion_manager.convert(kernel_storage[-20:], AddressType)
app_id = self.provider.get_storage(
address, str_to_slot("aragonOS.appStorage.appId")
)
if sum(app_id) != 0:
try:
target = ContractCall(GET_APP_ABI, kernel)(
keccak(text="base"), bytes(app_id), skip_trace=True
)
if target != ZERO_ADDRESS:
return ProxyInfo(
type=ProxyType.AragonAppUpgradeable,
target=target,
abi=GET_APP_ABI,
)
except ApeException:
pass
return None
def decode_receipt(self, data: dict) -> "ReceiptAPI":
status = data.get("status")
if status is not None:
status = self.conversion_manager.convert(status, int)
status = TransactionStatusEnum(status)
hash_key_choices = (
"hash",
"txHash",
"txn_hash",
"txnHash",
"transactionHash",
"transaction_hash",
)
txn_hash = next((data[choice] for choice in hash_key_choices if choice in data), None)
if txn_hash and isinstance(txn_hash, bytes):
txn_hash = to_hex(txn_hash)
data_bytes = data.get("data")
if data_bytes and isinstance(data_bytes, str):
data["data"] = HexBytes(data_bytes)
elif "input" in data and isinstance(data["input"], str):
data["input"] = HexBytes(data["input"])
block_number = data.get("block_number", data.get("blockNumber"))
if block_number is None:
raise ValueError("Missing block number.")
receipt_kwargs = {
"block_number": block_number,
"contract_address": data.get("contract_address", data.get("contractAddress")),
"gas_limit": data.get("gas", data.get("gas_limit", data.get("gasLimit"))) or 0,
"gas_price": data.get("gas_price", data.get("gasPrice")) or 0,
"gas_used": data.get("gas_used", data.get("gasUsed")) or 0,
"logs": data.get("logs", []),
"status": status,
"txn_hash": txn_hash,
"transaction": self.create_transaction(**data),
}
receipt_cls: type[Receipt]
if data.get("type") == 3:
receipt_cls = SharedBlobReceipt
blob_gas_price = data.get("blob_gas_price")
if blob_gas_price is None:
blob_gas_price = data.get("blobGasPrice")
receipt_kwargs["blobGasPrice"] = blob_gas_price
receipt_kwargs["blobGasUsed"] = data.get("blob_gas_used", data.get("blobGasUsed")) or 0
else:
receipt_cls = Receipt
error = receipt_kwargs.pop("error", None)
receipt = receipt_cls.model_validate(receipt_kwargs)
receipt.error = error
return receipt
def decode_block(self, data: dict) -> BlockAPI:
data["hash"] = HexBytes(data["hash"]) if data.get("hash") else None
if "gas_limit" in data:
data["gasLimit"] = data.pop("gas_limit")
if "gas_used" in data:
data["gasUsed"] = data.pop("gas_used")
if "parent_hash" in data:
data["parentHash"] = HexBytes(data.pop("parent_hash"))
if "transaction_ids" in data:
data["transactions"] = data.pop("transaction_ids")
if "total_difficulty" in data:
data["totalDifficulty"] = data.pop("total_difficulty") or 0
elif "totalDifficulty" in data:
data["totalDifficulty"] = data.pop("totalDifficulty") or 0
if "base_fee" in data:
data["baseFeePerGas"] = data.pop("base_fee")
elif "baseFee" in data:
data["baseFeePerGas"] = data.pop("baseFee")
if "transactions" in data:
data["num_transactions"] = len(data["transactions"])
return Block.model_validate(data)
def _python_type_for_abi_type(self, abi_type: ABIType) -> type | Sequence:
# NOTE: An array can be an array of tuples, so we start with an array check
if str(abi_type.type).endswith("]"):
# remove one layer of the potential onion of array
abi_type_str = str(abi_type.type)
last_bracket_pos = abi_type_str.rfind("[")
new_type = abi_type_str[:last_bracket_pos] if last_bracket_pos != -1 else abi_type_str
# create a new type with the inner type of array
new_abi_type = ABIType(type=new_type, **abi_type.model_dump(exclude={"type"}))
# NOTE: type for static and dynamic array is a single item list
# containing the type of the array
return [self._python_type_for_abi_type(new_abi_type)]
if abi_type.components is not None:
return tuple(self._python_type_for_abi_type(c) for c in abi_type.components)
if abi_type.type == "address":
return AddressType
elif abi_type.type == "bool":
return bool
elif abi_type.type == "string":
return str
elif "bytes" in abi_type.type:
return bytes
elif "int" in abi_type.type:
return int
elif "fixed" in abi_type.type:
return Decimal
raise ConversionError(f"Unable to convert '{abi_type}'.")
def encode_calldata(self, abi: ConstructorABI | MethodABI, *args) -> HexBytes:
if not abi.inputs:
return HexBytes("")
parser = StructParser(abi)
arguments = parser.encode_input(args)
input_types = [i.canonical_type for i in abi.inputs]
python_types = tuple(self._python_type_for_abi_type(i) for i in abi.inputs)
converted_args = self.conversion_manager.convert(arguments, python_types)
encoded_calldata = encode(input_types, converted_args)
return HexBytes(encoded_calldata)
def decode_calldata(self, abi: ConstructorABI | MethodABI, calldata: bytes) -> dict:
raw_input_types = [i.canonical_type for i in abi.inputs]
input_types = [parse_type(i.model_dump()) for i in abi.inputs]
try:
raw_input_values = decode(raw_input_types, calldata, strict=False)
except (InsufficientDataBytes, OverflowError, NonEmptyPaddingBytes) as err:
raise DecodingError(str(err)) from err
input_values = [
self.decode_primitive_value(v, t)
for v, t in zip(raw_input_values, input_types, strict=True)
]
arguments = {}
index = 0
for i, v in zip(abi.inputs, input_values, strict=True):
name = i.name or f"{index}"
arguments[name] = v
index += 1
return arguments
def decode_returndata(self, abi: MethodABI, raw_data: bytes) -> tuple[Any, ...]:
output_types_str_ls = [o.canonical_type for o in abi.outputs]
if raw_data:
try:
vm_return_values = decode(output_types_str_ls, raw_data, strict=False)
except (InsufficientDataBytes, NonEmptyPaddingBytes) as err:
raise DecodingError(str(err)) from err
else:
# Use all zeroes.
vm_return_values = tuple([0 for _ in output_types_str_ls])
if not vm_return_values:
return vm_return_values
elif not isinstance(vm_return_values, (tuple, list)):
vm_return_values = (vm_return_values,)
output_types = [parse_type(o.model_dump()) for o in abi.outputs]
output_values = [
self.decode_primitive_value(v, t)
for v, t in zip(vm_return_values, output_types, strict=True)
]
parser = StructParser(abi)
output_values = parser.decode_output(output_values)
if issubclass(type(output_values), Struct):
return (output_values,)
elif (
returns_array(abi)
and isinstance(output_values, (list, tuple))
and len(output_values) == 1
):
# Array of structs or tuples: don't convert to list
# Array of anything else: convert to single list
if issubclass(type(output_values[0]), Struct):
return ([output_values[0]],)
else:
try:
return ([o for o in output_values[0]],) # type: ignore[union-attr]
except Exception:
# On-chains transaction data errors.
return (output_values,)
elif returns_array(abi):
# Tuple with single item as the array.
return (output_values,)
return tuple(output_values)
def _enrich_value(self, value: Any, **kwargs) -> Any:
if isinstance(value, bytes):
try:
string_value = value.strip(b"\x00").decode("utf8")
return f'"{string_value}"'
except UnicodeDecodeError:
# Truncate bytes if very long.
if len(value) > 24:
return f"{add_0x_prefix(HexStr(humanize_hash(cast(Hash32, value))))}"
hex_str = to_hex(value)
if is_hex_address(hex_str):
return self._enrich_value(hex_str, **kwargs)
return hex_str
elif isinstance(value, str) and is_hex_address(value):
address = self.decode_address(value)
return self._enrich_contract_id(address, **kwargs)
elif isinstance(value, str):
# Surround non-address strings with quotes.
return f'"{value}"'
elif isinstance(value, int):
return int(value) # Eliminate int-base classes.
elif isinstance(value, (list, tuple)):
return [self._enrich_value(v, **kwargs) for v in value]
elif isinstance(value, Struct):
return {k: self._enrich_value(v, **kwargs) for k, v in value.items()}
return value
def decode_primitive_value(
self, value: Any, output_type: str | tuple | list
) -> str | HexBytes | int | tuple | list:
if output_type == "address":
try:
return self.decode_address(value)
except InsufficientDataBytes as err:
raise DecodingError() from err
elif isinstance(value, bytes):
return HexBytes(value)
elif isinstance(value, int) and not isinstance(value, bool):
# Wrap integers in a special type that allows us to compare
# them with currency-value strings.
return CurrencyValueComparable(value)
elif isinstance(output_type, str) and is_array(output_type):
sub_type = "[".join(output_type.split("[")[:-1])
if not isinstance(value, (list, tuple)):
value = (value,)
return [self.decode_primitive_value(v, sub_type) for v in value]
elif isinstance(output_type, tuple):
return tuple(
[self.decode_primitive_value(v, t) for v, t in zip(value, output_type, strict=True)]
)
elif (
isinstance(output_type, list)
and len(output_type) == 1
and isinstance(value, (list, tuple))
):
return tuple([self.decode_primitive_value(v, output_type[0]) for v in value])
return value
def encode_deployment(
self, deployment_bytecode: HexBytes, abi: ConstructorABI, *args, **kwargs
) -> BaseTransaction:
kwargs["abi"] = abi
txn = self.create_transaction(**kwargs)
data = HexBytes(deployment_bytecode)
# Encode args, if there are any
if abi and args:
data = HexBytes(data + self.encode_calldata(abi, *args))
txn.data = data
return cast(BaseTransaction, txn)
def encode_transaction(
self,
address: AddressType,
abi: MethodABI,
*args,
**kwargs,
) -> BaseTransaction:
kwargs["abi"] = abi
txn = self.create_transaction(receiver=address, **kwargs)
# Add method ID
txn.data = self.get_method_selector(abi)
txn.data = HexBytes(txn.data + self.encode_calldata(abi, *args))
return cast(BaseTransaction, txn)
def create_transaction(self, **kwargs) -> "TransactionAPI":
"""
Returns a transaction using the given constructor kwargs.
**NOTE**: This generally should not be called by the user since this API method is used as a
hook for Ecosystems to customize how transactions are created.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
"""
# Handle all aliases.
tx_data = dict(kwargs)
tx_data = _correct_key(
"max_priority_fee",
tx_data,
("max_priority_fee_per_gas", "maxPriorityFeePerGas", "maxPriorityFee"),
)
tx_data = _correct_key("max_fee", tx_data, ("max_fee_per_gas", "maxFeePerGas", "maxFee"))
tx_data = _correct_key("gas", tx_data, ("gas_limit", "gasLimit"))
tx_data = _correct_key("gas_price", tx_data, ("gasPrice",))
tx_data = _correct_key(
"type",
tx_data,
("txType", "tx_type", "txnType", "txn_type", "transactionType", "transaction_type"),
)
tx_data = _correct_key("maxFeePerBlobGas", tx_data, ("max_fee_per_blob_gas",))
tx_data = _correct_key("blobVersionedHashes", tx_data, ("blob_versioned_hashes",))
# Handle unique value specifications, such as "1 ether".
if "value" in tx_data and not isinstance(tx_data["value"], int):
value = tx_data["value"] or 0 # Convert None to 0.
tx_data["value"] = self.conversion_manager.convert(value, int)
# None is not allowed, the user likely means `b""`.
if "data" in tx_data and tx_data["data"] is None:
tx_data["data"] = b""
# Deduce the transaction type.
transaction_types: dict[TransactionType, type[TransactionAPI]] = {
TransactionType.STATIC: StaticFeeTransaction,
TransactionType.ACCESS_LIST: AccessListTransaction,
TransactionType.DYNAMIC: DynamicFeeTransaction,
TransactionType.SHARED_BLOB: SharedBlobTransaction,
TransactionType.SET_CODE: SetCodeTransaction,
}
if "type" in tx_data:
# It might be `None` in the given data dict.
if tx_data["type"] is None:
# Explicit `None` means used default.
version = self.default_transaction_type
elif isinstance(tx_data["type"], TransactionType):
version = tx_data["type"]
elif isinstance(tx_data["type"], int):
version = TransactionType(tx_data["type"])
else:
# Using hex values or alike.
version = TransactionType(self.conversion_manager.convert(tx_data["type"], int))
# NOTE: Determine these in reverse order
elif "authorizationList" in tx_data:
version = TransactionType.SET_CODE
elif "maxFeePerBlobGas" in tx_data or "blobVersionedHashes" in tx_data:
version = TransactionType.SHARED_BLOB