web3 7.0.0b3__py3-none-any.whl → 7.0.0b5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. ens/_normalization.py +1 -3
  2. ens/async_ens.py +12 -9
  3. ens/contract_data.py +2 -2
  4. ens/ens.py +8 -5
  5. ens/exceptions.py +19 -27
  6. ens/specs/nf.json +1 -1
  7. ens/specs/normalization_spec.json +1 -1
  8. ens/utils.py +17 -10
  9. web3/__init__.py +2 -7
  10. web3/_utils/abi.py +30 -29
  11. web3/_utils/async_transactions.py +7 -4
  12. web3/_utils/blocks.py +6 -2
  13. web3/_utils/caching.py +7 -3
  14. web3/_utils/compat/__init__.py +0 -3
  15. web3/_utils/contract_sources/compile_contracts.py +1 -1
  16. web3/_utils/contracts.py +17 -17
  17. web3/_utils/datatypes.py +5 -1
  18. web3/_utils/decorators.py +6 -1
  19. web3/_utils/empty.py +1 -1
  20. web3/_utils/encoding.py +15 -10
  21. web3/_utils/error_formatters_utils.py +5 -3
  22. web3/_utils/events.py +38 -36
  23. web3/_utils/fee_utils.py +2 -4
  24. web3/_utils/filters.py +23 -18
  25. web3/_utils/formatters.py +2 -2
  26. web3/_utils/math.py +3 -2
  27. web3/_utils/method_formatters.py +24 -28
  28. web3/_utils/module.py +2 -1
  29. web3/_utils/module_testing/__init__.py +0 -3
  30. web3/_utils/module_testing/eth_module.py +494 -432
  31. web3/_utils/module_testing/module_testing_utils.py +1 -3
  32. web3/_utils/module_testing/utils.py +14 -7
  33. web3/_utils/normalizers.py +3 -3
  34. web3/_utils/request.py +4 -4
  35. web3/_utils/rpc_abi.py +5 -19
  36. web3/_utils/threads.py +8 -7
  37. web3/_utils/transactions.py +14 -12
  38. web3/_utils/type_conversion.py +5 -1
  39. web3/_utils/validation.py +12 -10
  40. web3/contract/async_contract.py +23 -18
  41. web3/contract/base_contract.py +69 -74
  42. web3/contract/contract.py +25 -19
  43. web3/contract/utils.py +11 -6
  44. web3/datastructures.py +22 -12
  45. web3/eth/async_eth.py +38 -32
  46. web3/eth/base_eth.py +7 -3
  47. web3/eth/eth.py +20 -15
  48. web3/exceptions.py +83 -78
  49. web3/gas_strategies/time_based.py +2 -4
  50. web3/geth.py +1 -191
  51. web3/main.py +6 -6
  52. web3/manager.py +128 -68
  53. web3/method.py +13 -5
  54. web3/middleware/base.py +4 -2
  55. web3/middleware/filter.py +45 -23
  56. web3/middleware/formatting.py +6 -3
  57. web3/middleware/names.py +4 -1
  58. web3/middleware/signing.py +8 -4
  59. web3/middleware/stalecheck.py +2 -1
  60. web3/providers/eth_tester/defaults.py +1 -49
  61. web3/providers/eth_tester/main.py +41 -15
  62. web3/providers/eth_tester/middleware.py +13 -9
  63. web3/providers/ipc.py +7 -3
  64. web3/providers/persistent/async_ipc.py +6 -7
  65. web3/providers/persistent/persistent.py +11 -1
  66. web3/providers/persistent/request_processor.py +7 -7
  67. web3/providers/persistent/websocket.py +3 -3
  68. web3/providers/rpc/async_rpc.py +24 -7
  69. web3/providers/rpc/rpc.py +30 -17
  70. web3/providers/rpc/utils.py +1 -10
  71. web3/testing.py +4 -4
  72. web3/tools/benchmark/main.py +13 -9
  73. web3/tools/benchmark/node.py +2 -8
  74. web3/tools/benchmark/utils.py +1 -1
  75. web3/tracing.py +9 -5
  76. web3/types.py +20 -23
  77. {web3-7.0.0b3.dist-info → web3-7.0.0b5.dist-info}/METADATA +13 -28
  78. {web3-7.0.0b3.dist-info → web3-7.0.0b5.dist-info}/RECORD +81 -82
  79. web3/_utils/module_testing/go_ethereum_personal_module.py +0 -300
  80. {web3-7.0.0b3.dist-info → web3-7.0.0b5.dist-info}/LICENSE +0 -0
  81. {web3-7.0.0b3.dist-info → web3-7.0.0b5.dist-info}/WHEEL +0 -0
  82. {web3-7.0.0b3.dist-info → web3-7.0.0b5.dist-info}/top_level.txt +0 -0
ens/utils.py CHANGED
@@ -35,6 +35,11 @@ from hexbytes import (
35
35
  HexBytes,
36
36
  )
37
37
 
38
+ from ens.exceptions import (
39
+ ENSTypeError,
40
+ ENSValueError,
41
+ )
42
+
38
43
  from .constants import (
39
44
  ACCEPTABLE_STALE_HOURS,
40
45
  AUCTION_START_GAS_CONSTANT,
@@ -77,7 +82,7 @@ def Web3() -> Type["_Web3"]:
77
82
 
78
83
 
79
84
  def init_web3(
80
- provider: "BaseProvider" = cast("BaseProvider", default),
85
+ provider: "BaseProvider" = None,
81
86
  middleware: Optional[Sequence[Tuple["Middleware", str]]] = None,
82
87
  ) -> "_Web3":
83
88
  from web3 import (
@@ -87,6 +92,7 @@ def init_web3(
87
92
  Eth as EthMain,
88
93
  )
89
94
 
95
+ provider = provider or cast("BaseProvider", default)
90
96
  if provider is default:
91
97
  w3 = Web3Main(ens=None, modules={"eth": (EthMain)})
92
98
  else:
@@ -135,7 +141,7 @@ def normalize_name(name: str) -> str:
135
141
 
136
142
 
137
143
  def ens_encode_name(name: str) -> bytes:
138
- """
144
+ r"""
139
145
  Encode a name according to DNS standards specified in section 3.1
140
146
  of RFC1035 with the following validations:
141
147
 
@@ -199,17 +205,17 @@ def sha3_text(val: Union[str, bytes]) -> HexBytes:
199
205
  def label_to_hash(label: str) -> HexBytes:
200
206
  label = normalize_name(label)
201
207
  if "." in label:
202
- raise ValueError(f"Cannot generate hash for label {label!r} with a '.'")
208
+ raise ENSValueError(f"Cannot generate hash for label {label!r} with a '.'")
203
209
  return Web3().keccak(text=label)
204
210
 
205
211
 
206
212
  def normal_name_to_hash(name: str) -> HexBytes:
207
213
  """
208
- This method will not normalize the name. 'normal' name here means the name
209
- should already be normalized before calling this method.
214
+ Hashes a pre-normalized name.
215
+ The normalization of the name is a prerequisite and is not handled by this function.
210
216
 
211
- :param name: the name to hash - should already be normalized
212
- :return: namehash the hash of the name
217
+ :param str name: A normalized name string to be hashed.
218
+ :return: namehash - the hash of the name
213
219
  :rtype: HexBytes
214
220
  """
215
221
  node = EMPTY_SHA3_BYTES
@@ -264,7 +270,7 @@ def assert_signer_in_modifier_kwargs(modifier_kwargs: Any) -> ChecksumAddress:
264
270
 
265
271
  _modifier_type, modifier_dict = dict(modifier_kwargs).popitem()
266
272
  if "from" not in modifier_dict:
267
- raise TypeError(ERR_MSG)
273
+ raise ENSTypeError(ERR_MSG)
268
274
 
269
275
  return modifier_dict["from"]
270
276
 
@@ -300,7 +306,7 @@ def get_abi_output_types(abi: "ABIFunction") -> List[str]:
300
306
 
301
307
 
302
308
  def init_async_web3(
303
- provider: "AsyncBaseProvider" = cast("AsyncBaseProvider", default),
309
+ provider: "AsyncBaseProvider" = None,
304
310
  middleware: Optional[Sequence[Tuple["Middleware", str]]] = (),
305
311
  ) -> "AsyncWeb3":
306
312
  from web3 import (
@@ -313,8 +319,9 @@ def init_async_web3(
313
319
  StalecheckMiddlewareBuilder,
314
320
  )
315
321
 
322
+ provider = provider or cast("AsyncBaseProvider", default)
316
323
  middleware = list(middleware)
317
- for i, (mw, name) in enumerate(middleware):
324
+ for i, (_mw, name) in enumerate(middleware):
318
325
  if name == "ens_name_to_address":
319
326
  middleware.pop(i)
320
327
 
web3/__init__.py CHANGED
@@ -1,14 +1,9 @@
1
1
  from eth_account import Account # noqa: E402
2
2
  import sys
3
3
 
4
- if sys.version_info.major == 3 and sys.version_info.minor < 8:
5
- import pkg_resources
4
+ from importlib.metadata import version
6
5
 
7
- __version__ = pkg_resources.get_distribution("web3").version
8
- else:
9
- from importlib.metadata import version
10
-
11
- __version__ = version("web3")
6
+ __version__ = version("web3")
12
7
 
13
8
 
14
9
  from web3.main import (
web3/_utils/abi.py CHANGED
@@ -80,6 +80,9 @@ from web3._utils.formatters import (
80
80
  from web3.exceptions import (
81
81
  FallbackNotFound,
82
82
  MismatchedABI,
83
+ Web3AttributeError,
84
+ Web3TypeError,
85
+ Web3ValueError,
83
86
  )
84
87
  from web3.types import (
85
88
  ABI,
@@ -187,7 +190,8 @@ def filter_by_argument_name(
187
190
  ]
188
191
 
189
192
 
190
- class AddressEncoder(encoding.AddressEncoder):
193
+ # type ignored because subclassing encoding.AddressEncoder which has type Any
194
+ class AddressEncoder(encoding.AddressEncoder): # type: ignore[misc]
191
195
  @classmethod
192
196
  def validate_value(cls, value: Any) -> None:
193
197
  if is_ens_name(value):
@@ -196,7 +200,8 @@ class AddressEncoder(encoding.AddressEncoder):
196
200
  super().validate_value(value)
197
201
 
198
202
 
199
- class AcceptsHexStrEncoder(encoding.BaseEncoder):
203
+ # type ignored because subclassing encoding.BytesEncoder which has type Any
204
+ class AcceptsHexStrEncoder(encoding.BaseEncoder): # type: ignore[misc]
200
205
  subencoder_cls: Type[encoding.BaseEncoder] = None
201
206
  is_strict: bool = None
202
207
  is_big_endian: bool = False
@@ -227,7 +232,7 @@ class AcceptsHexStrEncoder(encoding.BaseEncoder):
227
232
  @classmethod
228
233
  def get_subencoder_class(cls) -> Type[encoding.BaseEncoder]:
229
234
  if cls.subencoder_cls is None:
230
- raise AttributeError(f"No subencoder class is set. {cls.__name__}")
235
+ raise Web3AttributeError(f"No subencoder class is set. {cls.__name__}")
231
236
  return cls.subencoder_cls
232
237
 
233
238
  def validate_value(self, value: Any) -> None:
@@ -287,20 +292,20 @@ class ExactLengthBytesEncoder(BytesEncoder):
287
292
  def validate(self) -> None:
288
293
  super().validate()
289
294
  if self.value_bit_size is None:
290
- raise ValueError("`value_bit_size` may not be none")
295
+ raise Web3ValueError("`value_bit_size` may not be none")
291
296
  if self.data_byte_size is None:
292
- raise ValueError("`data_byte_size` may not be none")
297
+ raise Web3ValueError("`data_byte_size` may not be none")
293
298
  if self.is_big_endian is None:
294
- raise ValueError("`is_big_endian` may not be none")
299
+ raise Web3ValueError("`is_big_endian` may not be none")
295
300
 
296
301
  if self.value_bit_size % 8 != 0:
297
- raise ValueError(
302
+ raise Web3ValueError(
298
303
  f"Invalid value bit size: {self.value_bit_size}. "
299
304
  "Must be a multiple of 8"
300
305
  )
301
306
 
302
307
  if self.value_bit_size > self.data_byte_size * 8:
303
- raise ValueError("Value byte size exceeds data size")
308
+ raise Web3ValueError("Value byte size exceeds data size")
304
309
 
305
310
  @parse_type_str("bytes")
306
311
  def from_type_str(
@@ -308,9 +313,7 @@ class ExactLengthBytesEncoder(BytesEncoder):
308
313
  ) -> "ExactLengthBytesEncoder":
309
314
  subencoder_cls = cls.get_subencoder_class()
310
315
  subencoder = subencoder_cls.from_type_str(abi_type.to_type_str(), registry)
311
- # type ignored b/c @parse_type_str decorator turns it into a classmethod,
312
- # so mypy thinks cls(...) is a call to __call__, but actually calls __init__
313
- return cls( # type: ignore
316
+ return cls(
314
317
  subencoder,
315
318
  value_bit_size=abi_type.sub * 8,
316
319
  data_byte_size=abi_type.sub,
@@ -327,7 +330,8 @@ class StrictByteStringEncoder(AcceptsHexStrEncoder):
327
330
  is_strict = True
328
331
 
329
332
 
330
- class TextStringEncoder(encoding.TextStringEncoder):
333
+ # type ignored because subclassing encoding.TextStringEncoder which has type Any
334
+ class TextStringEncoder(encoding.TextStringEncoder): # type: ignore[misc]
331
335
  @classmethod
332
336
  def validate_value(cls, value: Any) -> None:
333
337
  if is_bytes(value):
@@ -394,7 +398,7 @@ def merge_args_and_kwargs(
394
398
  """
395
399
  # Ensure the function is being applied to the correct number of args
396
400
  if len(args) + len(kwargs) != len(function_abi.get("inputs", [])):
397
- raise TypeError(
401
+ raise Web3TypeError(
398
402
  f"Incorrect argument count. Expected '{len(function_abi['inputs'])}'"
399
403
  f". Got '{len(args) + len(kwargs)}'"
400
404
  )
@@ -410,7 +414,7 @@ def merge_args_and_kwargs(
410
414
  # Check for duplicate args
411
415
  duplicate_args = kwarg_names.intersection(args_as_kwargs.keys())
412
416
  if duplicate_args:
413
- raise TypeError(
417
+ raise Web3TypeError(
414
418
  f"{function_abi.get('name')}() got multiple values for argument(s) "
415
419
  f"'{', '.join(duplicate_args)}'"
416
420
  )
@@ -419,11 +423,11 @@ def merge_args_and_kwargs(
419
423
  unknown_args = kwarg_names.difference(sorted_arg_names)
420
424
  if unknown_args:
421
425
  if function_abi.get("name"):
422
- raise TypeError(
426
+ raise Web3TypeError(
423
427
  f"{function_abi.get('name')}() got unexpected keyword argument(s)"
424
428
  f" '{', '.join(unknown_args)}'"
425
429
  )
426
- raise TypeError(
430
+ raise Web3TypeError(
427
431
  f"Type: '{function_abi.get('type')}' got unexpected keyword argument(s)"
428
432
  f" '{', '.join(unknown_args)}'"
429
433
  )
@@ -497,7 +501,7 @@ def _align_abi_input(arg_abi: ABIFunctionParams, arg: Any) -> Tuple[Any, ...]:
497
501
  aligned_arg = arg
498
502
 
499
503
  if not is_list_like(aligned_arg):
500
- raise TypeError(
504
+ raise Web3TypeError(
501
505
  f'Expected non-string sequence for "{arg_abi.get("type")}" '
502
506
  f"component type: got {aligned_arg}"
503
507
  )
@@ -528,9 +532,7 @@ def get_aligned_abi_inputs(
528
532
  args = tuple(args[abi["name"]] for abi in input_abis)
529
533
 
530
534
  return (
531
- # typed dict cannot be used w/ a normal Dict
532
- # https://github.com/python/mypy/issues/4976
533
- tuple(collapse_if_tuple(abi) for abi in input_abis), # type: ignore
535
+ tuple(collapse_if_tuple(abi) for abi in input_abis),
534
536
  type(args)(_align_abi_input(abi, arg) for abi, arg in zip(input_abis, args)),
535
537
  )
536
538
 
@@ -542,7 +544,7 @@ def get_constructor_abi(contract_abi: ABI) -> ABIFunction:
542
544
  elif len(candidates) == 0:
543
545
  return None
544
546
  elif len(candidates) > 1:
545
- raise ValueError("Found multiple constructors.")
547
+ raise Web3ValueError("Found multiple constructors.")
546
548
  return None
547
549
 
548
550
 
@@ -564,7 +566,7 @@ STATIC_TYPES = list(
564
566
  )
565
567
 
566
568
  BASE_TYPE_REGEX = "|".join(
567
- (_type + "(?![a-z0-9])" for _type in itertools.chain(STATIC_TYPES, DYNAMIC_TYPES))
569
+ _type + "(?![a-z0-9])" for _type in itertools.chain(STATIC_TYPES, DYNAMIC_TYPES)
568
570
  )
569
571
 
570
572
  SUB_TYPE_REGEX = r"\[" "[0-9]*" r"\]"
@@ -630,14 +632,14 @@ END_BRACKETS_OF_ARRAY_TYPE_REGEX = r"\[[^]]*\]$"
630
632
 
631
633
  def sub_type_of_array_type(abi_type: TypeStr) -> str:
632
634
  if not is_array_type(abi_type):
633
- raise ValueError(f"Cannot parse subtype of nonarray abi-type: {abi_type}")
635
+ raise Web3ValueError(f"Cannot parse subtype of nonarray abi-type: {abi_type}")
634
636
 
635
- return re.sub(END_BRACKETS_OF_ARRAY_TYPE_REGEX, "", abi_type, 1)
637
+ return re.sub(END_BRACKETS_OF_ARRAY_TYPE_REGEX, "", abi_type, count=1)
636
638
 
637
639
 
638
640
  def length_of_array_type(abi_type: TypeStr) -> int:
639
641
  if not is_array_type(abi_type):
640
- raise ValueError(f"Cannot parse length of nonarray abi-type: {abi_type}")
642
+ raise Web3ValueError(f"Cannot parse length of nonarray abi-type: {abi_type}")
641
643
 
642
644
  inner_brackets = (
643
645
  re.search(END_BRACKETS_OF_ARRAY_TYPE_REGEX, abi_type).group(0).strip("[]")
@@ -705,8 +707,8 @@ def map_abi_data(
705
707
  data: Sequence[Any],
706
708
  ) -> Any:
707
709
  """
708
- This function will apply normalizers to your data, in the
709
- context of the relevant types. Each normalizer is in the format:
710
+ Applies normalizers to your data, in the context of the relevant types.
711
+ Each normalizer is in the format:
710
712
 
711
713
  def normalizer(datatype, data):
712
714
  # Conditionally modify data
@@ -772,7 +774,7 @@ def data_tree_map(
772
774
 
773
775
  class ABITypedData(namedtuple("ABITypedData", "abi_type, data")):
774
776
  """
775
- This class marks data as having a certain ABI-type.
777
+ Marks data as having a certain ABI-type.
776
778
 
777
779
  >>> a1 = ABITypedData(['address', addr1])
778
780
  >>> a2 = ABITypedData(['address', addr2])
@@ -1029,7 +1031,6 @@ async def async_map_if_collection(
1029
1031
  Apply an awaitable method to each element of a collection or value of a dictionary.
1030
1032
  If the value is not a collection, return it unmodified.
1031
1033
  """
1032
-
1033
1034
  datatype = type(value)
1034
1035
  if isinstance(value, Mapping):
1035
1036
  return datatype({key: await func(val) for key, val in value.values()})
@@ -24,6 +24,9 @@ from web3._utils.utility_methods import (
24
24
  from web3.constants import (
25
25
  DYNAMIC_FEE_TXN_PARAMS,
26
26
  )
27
+ from web3.exceptions import (
28
+ Web3ValueError,
29
+ )
27
30
  from web3.types import (
28
31
  BlockIdentifier,
29
32
  TxData,
@@ -87,7 +90,7 @@ async def get_buffered_gas_estimate(
87
90
  gas_limit = await get_block_gas_limit(async_w3.eth)
88
91
 
89
92
  if gas_estimate > gas_limit:
90
- raise ValueError(
93
+ raise Web3ValueError(
91
94
  "Contract does not appear to be deployable within the "
92
95
  f"current network gas limits. Estimated: {gas_estimate}. "
93
96
  f"Current gas limit: {gas_limit}"
@@ -110,7 +113,7 @@ async def async_fill_transaction_defaults(
110
113
  async_w3: "AsyncWeb3", transaction: TxParams
111
114
  ) -> TxParams:
112
115
  """
113
- if async_w3 is None, fill as much as possible while offline
116
+ If async_w3 is None, fill as much as possible while offline
114
117
  """
115
118
  strategy_based_gas_price = async_w3.eth.generate_gas_price(transaction)
116
119
 
@@ -134,7 +137,7 @@ async def async_fill_transaction_defaults(
134
137
 
135
138
  if callable(default_getter):
136
139
  if async_w3 is None:
137
- raise ValueError(
140
+ raise Web3ValueError(
138
141
  f"You must specify a '{key}' value in the transaction"
139
142
  )
140
143
  if key == "gasPrice":
@@ -155,7 +158,7 @@ async def async_get_required_transaction(
155
158
  ) -> TxData:
156
159
  current_transaction = await async_w3.eth.get_transaction(transaction_hash)
157
160
  if not current_transaction:
158
- raise ValueError(
161
+ raise Web3ValueError(
159
162
  f"Supplied transaction with hash {transaction_hash!r} does not exist"
160
163
  )
161
164
  return current_transaction
web3/_utils/blocks.py CHANGED
@@ -15,6 +15,10 @@ from eth_utils.toolz import (
15
15
  curry,
16
16
  )
17
17
 
18
+ from web3.exceptions import (
19
+ Web3TypeError,
20
+ Web3ValueError,
21
+ )
18
22
  from web3.types import (
19
23
  RPCEndpoint,
20
24
  )
@@ -32,7 +36,7 @@ def is_predefined_block_number(value: Any) -> bool:
32
36
  elif is_integer(value):
33
37
  return False
34
38
  else:
35
- raise TypeError(f"unrecognized block reference: {value!r}")
39
+ raise Web3TypeError(f"unrecognized block reference: {value!r}")
36
40
 
37
41
  return value_text in {"latest", "pending", "earliest", "safe", "finalized"}
38
42
 
@@ -70,6 +74,6 @@ def select_method_for_block_identifier(
70
74
  elif is_hex_encoded_block_number(value):
71
75
  return if_number
72
76
  else:
73
- raise ValueError(
77
+ raise Web3ValueError(
74
78
  f"Value did not match any of the recognized block identifiers: {value}"
75
79
  )
web3/_utils/caching.py CHANGED
@@ -23,6 +23,10 @@ from eth_utils import (
23
23
  to_bytes,
24
24
  )
25
25
 
26
+ from web3.exceptions import (
27
+ Web3TypeError,
28
+ )
29
+
26
30
  if TYPE_CHECKING:
27
31
  from web3.providers import ( # noqa: F401
28
32
  AsyncBaseProvider,
@@ -51,11 +55,11 @@ def generate_cache_key(value: Any) -> str:
51
55
  elif is_boolean(value) or is_null(value) or is_number(value):
52
56
  return generate_cache_key(repr(value))
53
57
  elif is_dict(value):
54
- return generate_cache_key(((key, value[key]) for key in sorted(value.keys())))
58
+ return generate_cache_key((key, value[key]) for key in sorted(value.keys()))
55
59
  elif is_list_like(value) or isinstance(value, collections.abc.Generator):
56
- return generate_cache_key("".join((generate_cache_key(item) for item in value)))
60
+ return generate_cache_key("".join(generate_cache_key(item) for item in value))
57
61
  else:
58
- raise TypeError(
62
+ raise Web3TypeError(
59
63
  f"Cannot generate cache key for value {value} of type {type(value)}"
60
64
  )
61
65
 
@@ -9,9 +9,6 @@
9
9
  # imported from `typing`
10
10
 
11
11
  from typing_extensions import (
12
- Literal, # py38
13
12
  NotRequired, # py311
14
- Protocol, # py38
15
- TypedDict, # py38
16
13
  Self, # py311
17
14
  )
@@ -116,7 +116,7 @@ contracts_in_file = {}
116
116
 
117
117
  def compile_files(file_list: List[str]) -> None:
118
118
  for filename in file_list:
119
- with open(os.path.join(os.getcwd(), filename), "r") as f:
119
+ with open(os.path.join(os.getcwd(), filename)) as f:
120
120
  dot_sol_file = f.readlines()
121
121
 
122
122
  contract_names = []
web3/_utils/contracts.py CHANGED
@@ -75,8 +75,10 @@ from web3._utils.normalizers import (
75
75
  abi_string_to_text,
76
76
  )
77
77
  from web3.exceptions import (
78
- BlockNumberOutofRange,
78
+ BlockNumberOutOfRange,
79
+ Web3TypeError,
79
80
  Web3ValidationError,
81
+ Web3ValueError,
80
82
  )
81
83
  from web3.types import (
82
84
  ABI,
@@ -136,9 +138,9 @@ def find_matching_event_abi(
136
138
  if len(event_abi_candidates) == 1:
137
139
  return event_abi_candidates[0]
138
140
  elif not event_abi_candidates:
139
- raise ValueError("No matching events found")
141
+ raise Web3ValueError("No matching events found")
140
142
  else:
141
- raise ValueError("Multiple events found")
143
+ raise Web3ValueError("Multiple events found")
142
144
 
143
145
 
144
146
  def find_matching_fn_abi(
@@ -159,7 +161,7 @@ def find_matching_fn_abi(
159
161
  return get_receive_func_abi(abi)
160
162
 
161
163
  if not is_text(fn_identifier):
162
- raise TypeError("Unsupported function identifier")
164
+ raise Web3TypeError("Unsupported function identifier")
163
165
 
164
166
  name_filter = functools.partial(filter_by_name, fn_identifier)
165
167
  arg_count_filter = functools.partial(filter_by_argument_count, num_arguments)
@@ -217,7 +219,7 @@ def encode_abi(
217
219
  argument_types = get_abi_input_types(abi)
218
220
 
219
221
  if not check_if_arguments_can_be_encoded(abi, w3.codec, arguments, {}):
220
- raise TypeError(
222
+ raise Web3TypeError(
221
223
  "One or more arguments could not be encoded to the necessary "
222
224
  f"ABI type. Expected types are: {', '.join(argument_types)}"
223
225
  )
@@ -274,7 +276,7 @@ def prepare_transaction(
274
276
  prepared_transaction = cast(TxParams, dict(**transaction))
275
277
 
276
278
  if "data" in prepared_transaction:
277
- raise ValueError("Transaction parameter may not contain a 'data' key")
279
+ raise Web3ValueError("Transaction parameter may not contain a 'data' key")
278
280
 
279
281
  if address:
280
282
  prepared_transaction.setdefault("to", address)
@@ -317,7 +319,7 @@ def encode_transaction_data(
317
319
  kwargs,
318
320
  )
319
321
  else:
320
- raise TypeError("Unsupported function identifier")
322
+ raise Web3TypeError("Unsupported function identifier")
321
323
 
322
324
  return add_0x_prefix(encode_abi(w3, fn_abi, fn_arguments, fn_selector))
323
325
 
@@ -327,8 +329,7 @@ def decode_transaction_data(
327
329
  data: HexStr,
328
330
  normalizers: Sequence[Callable[[TypeStr, Any], Tuple[TypeStr, Any]]] = None,
329
331
  ) -> Dict[str, Any]:
330
- # type ignored b/c expects data arg to be HexBytes
331
- data = HexBytes(data) # type: ignore
332
+ data = HexBytes(data)
332
333
  types = get_abi_input_types(fn_abi)
333
334
  abi_codec = ABICodec(default_registry)
334
335
  decoded = abi_codec.decode(types, HexBytes(data[4:]))
@@ -373,9 +374,7 @@ def get_function_info(
373
374
  if fn_abi is None:
374
375
  fn_abi = find_matching_fn_abi(contract_abi, abi_codec, fn_name, args, kwargs)
375
376
 
376
- # typed dict cannot be used w/ a normal Dict
377
- # https://github.com/python/mypy/issues/4976
378
- fn_selector = encode_hex(function_abi_to_4byte_selector(fn_abi)) # type: ignore
377
+ fn_selector = encode_hex(function_abi_to_4byte_selector(fn_abi))
379
378
 
380
379
  fn_arguments = merge_args_and_kwargs(fn_abi, args, kwargs)
381
380
 
@@ -385,7 +384,8 @@ def get_function_info(
385
384
 
386
385
 
387
386
  def validate_payable(transaction: TxParams, abi: ABIFunction) -> None:
388
- """Raise Web3ValidationError if non-zero ether
387
+ """
388
+ Raise Web3ValidationError if non-zero ether
389
389
  is sent to a non-payable function.
390
390
  """
391
391
  if "value" in transaction:
@@ -424,7 +424,7 @@ def parse_block_identifier(
424
424
  ):
425
425
  return w3.eth.get_block(block_identifier)["number"]
426
426
  else:
427
- raise BlockNumberOutofRange
427
+ raise BlockNumberOutOfRange
428
428
 
429
429
 
430
430
  def parse_block_identifier_int(w3: "Web3", block_identifier_int: int) -> BlockNumber:
@@ -434,7 +434,7 @@ def parse_block_identifier_int(w3: "Web3", block_identifier_int: int) -> BlockNu
434
434
  last_block = w3.eth.get_block("latest")["number"]
435
435
  block_num = last_block + block_identifier_int + 1
436
436
  if block_num < 0:
437
- raise BlockNumberOutofRange
437
+ raise BlockNumberOutOfRange
438
438
  return BlockNumber(block_num)
439
439
 
440
440
 
@@ -453,7 +453,7 @@ async def async_parse_block_identifier(
453
453
  requested_block = await async_w3.eth.get_block(block_identifier)
454
454
  return requested_block["number"]
455
455
  else:
456
- raise BlockNumberOutofRange
456
+ raise BlockNumberOutOfRange
457
457
 
458
458
 
459
459
  async def async_parse_block_identifier_int(
@@ -466,5 +466,5 @@ async def async_parse_block_identifier_int(
466
466
  last_block_num = last_block["number"]
467
467
  block_num = last_block_num + block_identifier_int + 1
468
468
  if block_num < 0:
469
- raise BlockNumberOutofRange
469
+ raise BlockNumberOutOfRange
470
470
  return BlockNumber(block_num)
web3/_utils/datatypes.py CHANGED
@@ -14,10 +14,14 @@ from eth_utils.toolz import (
14
14
  concat,
15
15
  )
16
16
 
17
+ from web3.exceptions import (
18
+ Web3AttributeError,
19
+ )
20
+
17
21
 
18
22
  def verify_attr(class_name: str, key: str, namespace: Collection[str]) -> None:
19
23
  if key not in namespace:
20
- raise AttributeError(
24
+ raise Web3AttributeError(
21
25
  f"Property {key} not found on {class_name} class. "
22
26
  f"`{class_name}.factory` only accepts keyword arguments which are "
23
27
  f"present on the {class_name} class"
web3/_utils/decorators.py CHANGED
@@ -8,6 +8,10 @@ from typing import (
8
8
  )
9
9
  import warnings
10
10
 
11
+ from web3.exceptions import (
12
+ Web3ValueError,
13
+ )
14
+
11
15
  TFunc = TypeVar("TFunc", bound=Callable[..., Any])
12
16
 
13
17
 
@@ -24,7 +28,7 @@ def reject_recursive_repeats(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
24
28
  thread_id = threading.get_ident()
25
29
  thread_local_args = (thread_id,) + arg_instances
26
30
  if thread_local_args in to_wrap.__already_called: # type: ignore
27
- raise ValueError(f"Recursively called {to_wrap} with {args!r}")
31
+ raise Web3ValueError(f"Recursively called {to_wrap} with {args!r}")
28
32
  to_wrap.__already_called[thread_local_args] = True # type: ignore
29
33
  try:
30
34
  wrapped_val = to_wrap(*args)
@@ -50,6 +54,7 @@ def deprecated_for(replace_message: str) -> Callable[..., Any]:
50
54
  warnings.warn(
51
55
  f"{to_wrap.__name__} is deprecated in favor of {replace_message}",
52
56
  category=DeprecationWarning,
57
+ stacklevel=2,
53
58
  )
54
59
  return to_wrap(*args, **kwargs)
55
60
 
web3/_utils/empty.py CHANGED
@@ -1,4 +1,4 @@
1
- from web3._utils.compat import (
1
+ from typing import (
2
2
  Literal,
3
3
  )
4
4
 
web3/_utils/encoding.py CHANGED
@@ -55,6 +55,10 @@ from web3._utils.validation import (
55
55
  from web3.datastructures import (
56
56
  AttributeDict,
57
57
  )
58
+ from web3.exceptions import (
59
+ Web3TypeError,
60
+ Web3ValueError,
61
+ )
58
62
 
59
63
 
60
64
  def hex_encode_abi_type(
@@ -90,7 +94,7 @@ def hex_encode_abi_type(
90
94
  elif is_string_type(abi_type):
91
95
  return to_hex(text=value)
92
96
  else:
93
- raise ValueError(f"Unsupported ABI type: {abi_type}")
97
+ raise Web3ValueError(f"Unsupported ABI type: {abi_type}")
94
98
 
95
99
 
96
100
  def to_hex_twos_compliment(value: Any, bit_size: int) -> HexStr:
@@ -169,7 +173,7 @@ def hexstr_if_str(
169
173
  if isinstance(hexstr_or_primitive, str):
170
174
  (primitive, hexstr) = (None, hexstr_or_primitive)
171
175
  if remove_0x_prefix(HexStr(hexstr)) and not is_hex(hexstr):
172
- raise ValueError(
176
+ raise Web3ValueError(
173
177
  "when sending a str, it must be a hex string. "
174
178
  f"Got: {hexstr_or_primitive!r}"
175
179
  )
@@ -210,12 +214,12 @@ class FriendlyJsonSerde:
210
214
  except TypeError as full_exception:
211
215
  if hasattr(obj, "items"):
212
216
  item_errors = "; ".join(self._json_mapping_errors(obj))
213
- raise TypeError(
217
+ raise Web3TypeError(
214
218
  f"dict had unencodable value at keys: {{{item_errors}}}"
215
219
  )
216
220
  elif is_list_like(obj):
217
221
  element_errors = "; ".join(self._json_list_errors(obj))
218
- raise TypeError(
222
+ raise Web3TypeError(
219
223
  f"list had unencodable value at index: [{element_errors}]"
220
224
  )
221
225
  else:
@@ -237,19 +241,22 @@ class FriendlyJsonSerde:
237
241
  try:
238
242
  return self._friendly_json_encode(obj, cls=cls)
239
243
  except TypeError as exc:
240
- raise TypeError(f"Could not encode to JSON: {exc}")
244
+ raise Web3TypeError(f"Could not encode to JSON: {exc}")
241
245
 
242
246
 
243
247
  def to_4byte_hex(hex_or_str_or_bytes: Union[HexStr, str, bytes, int]) -> HexStr:
244
248
  size_of_4bytes = 4 * 8
245
249
  byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes)
246
250
  if len(byte_str) > 4:
247
- raise ValueError(f"expected value of size 4 bytes. Got: {len(byte_str)} bytes")
251
+ raise Web3ValueError(
252
+ f"expected value of size 4 bytes. Got: {len(byte_str)} bytes"
253
+ )
248
254
  hex_str = encode_hex(byte_str)
249
255
  return pad_hex(hex_str, size_of_4bytes)
250
256
 
251
257
 
252
- class DynamicArrayPackedEncoder(BaseArrayEncoder):
258
+ # type ignored because subclassing BaseArrayEncoder which has type Any
259
+ class DynamicArrayPackedEncoder(BaseArrayEncoder): # type: ignore[misc]
253
260
  is_dynamic = True
254
261
 
255
262
  def encode(self, value: Sequence[Any]) -> bytes:
@@ -291,9 +298,7 @@ class Web3JsonEncoder(json.JSONEncoder):
291
298
  def default(self, obj: Any) -> Union[Dict[Any, Any], HexStr]:
292
299
  if isinstance(obj, AttributeDict):
293
300
  return obj.__dict__
294
- elif isinstance(obj, HexBytes):
295
- return HexStr(obj.hex())
296
- elif isinstance(obj, bytes):
301
+ elif isinstance(obj, (HexBytes, bytes)):
297
302
  return to_hex(obj)
298
303
  return json.JSONEncoder.default(self, obj)
299
304