web3 7.14.1__py3-none-any.whl → 8.0.0b1__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 (99) hide show
  1. ens/_normalization.py +23 -29
  2. ens/async_ens.py +30 -24
  3. ens/base_ens.py +2 -3
  4. ens/ens.py +18 -20
  5. ens/utils.py +6 -10
  6. web3/__init__.py +0 -4
  7. web3/_utils/abi.py +38 -40
  8. web3/_utils/async_transactions.py +6 -9
  9. web3/_utils/batching.py +11 -15
  10. web3/_utils/blocks.py +1 -2
  11. web3/_utils/caching/caching_utils.py +12 -17
  12. web3/_utils/caching/request_caching_validation.py +7 -9
  13. web3/_utils/compat/__init__.py +2 -2
  14. web3/_utils/contract_sources/compile_contracts.py +4 -6
  15. web3/_utils/contracts.py +25 -29
  16. web3/_utils/datatypes.py +6 -10
  17. web3/_utils/decorators.py +1 -3
  18. web3/_utils/encoding.py +10 -14
  19. web3/_utils/ens.py +4 -5
  20. web3/_utils/events.py +19 -24
  21. web3/_utils/filters.py +23 -29
  22. web3/_utils/formatters.py +8 -13
  23. web3/_utils/http_session_manager.py +11 -22
  24. web3/_utils/math.py +1 -2
  25. web3/_utils/method_formatters.py +41 -43
  26. web3/_utils/module.py +3 -6
  27. web3/_utils/module_testing/eth_module.py +7 -9
  28. web3/_utils/module_testing/go_ethereum_admin_module.py +1 -2
  29. web3/_utils/module_testing/module_testing_utils.py +9 -5
  30. web3/_utils/module_testing/persistent_connection_provider.py +3 -7
  31. web3/_utils/module_testing/utils.py +32 -21
  32. web3/_utils/normalizers.py +21 -24
  33. web3/_utils/rpc_abi.py +8 -11
  34. web3/_utils/threads.py +3 -4
  35. web3/_utils/transactions.py +3 -6
  36. web3/_utils/type_conversion.py +2 -6
  37. web3/_utils/utility_methods.py +5 -7
  38. web3/_utils/validation.py +6 -8
  39. web3/_utils/windows.py +1 -4
  40. web3/beacon/async_beacon.py +50 -54
  41. web3/beacon/beacon.py +50 -54
  42. web3/contract/async_contract.py +38 -46
  43. web3/contract/base_contract.py +70 -75
  44. web3/contract/contract.py +39 -43
  45. web3/contract/utils.py +47 -51
  46. web3/datastructures.py +10 -15
  47. web3/eth/async_eth.py +64 -70
  48. web3/eth/base_eth.py +40 -44
  49. web3/eth/eth.py +50 -66
  50. web3/exceptions.py +8 -13
  51. web3/gas_strategies/rpc.py +1 -7
  52. web3/gas_strategies/time_based.py +2 -3
  53. web3/geth.py +17 -17
  54. web3/main.py +43 -52
  55. web3/manager.py +32 -35
  56. web3/method.py +22 -29
  57. web3/middleware/base.py +5 -8
  58. web3/middleware/filter.py +41 -46
  59. web3/middleware/formatting.py +5 -6
  60. web3/middleware/names.py +1 -3
  61. web3/middleware/signing.py +3 -4
  62. web3/middleware/stalecheck.py +1 -2
  63. web3/middleware/validation.py +1 -2
  64. web3/module.py +11 -14
  65. web3/providers/__init__.py +0 -4
  66. web3/providers/async_base.py +21 -27
  67. web3/providers/auto.py +9 -20
  68. web3/providers/base.py +12 -17
  69. web3/providers/eth_tester/defaults.py +4 -8
  70. web3/providers/eth_tester/main.py +4 -8
  71. web3/providers/eth_tester/middleware.py +2 -4
  72. web3/providers/ipc.py +6 -10
  73. web3/providers/persistent/async_ipc.py +4 -7
  74. web3/providers/persistent/persistent.py +22 -25
  75. web3/providers/persistent/persistent_connection.py +2 -4
  76. web3/providers/persistent/request_processor.py +11 -32
  77. web3/providers/persistent/subscription_container.py +5 -8
  78. web3/providers/persistent/subscription_manager.py +13 -19
  79. web3/providers/persistent/websocket.py +15 -12
  80. web3/providers/rpc/async_rpc.py +10 -16
  81. web3/providers/rpc/rpc.py +17 -20
  82. web3/providers/rpc/utils.py +2 -3
  83. web3/scripts/release/test_package.py +1 -4
  84. web3/testing.py +1 -5
  85. web3/tracing.py +9 -13
  86. web3/types.py +51 -58
  87. web3/utils/abi.py +28 -33
  88. web3/utils/async_exception_handling.py +1 -2
  89. web3/utils/caching.py +6 -10
  90. web3/utils/exception_handling.py +1 -2
  91. web3/utils/subscriptions.py +30 -34
  92. {web3-7.14.1.dist-info → web3-8.0.0b1.dist-info}/METADATA +10 -9
  93. web3-8.0.0b1.dist-info/RECORD +170 -0
  94. {web3-7.14.1.dist-info → web3-8.0.0b1.dist-info}/WHEEL +1 -1
  95. ens/specs/.DS_Store +0 -0
  96. web3/providers/legacy_websocket.py +0 -159
  97. web3-7.14.1.dist-info/RECORD +0 -172
  98. {web3-7.14.1.dist-info → web3-8.0.0b1.dist-info}/licenses/LICENSE +0 -0
  99. {web3-7.14.1.dist-info → web3-8.0.0b1.dist-info}/top_level.txt +0 -0
web3/_utils/formatters.py CHANGED
@@ -1,13 +1,8 @@
1
- from collections.abc import (
2
- Mapping,
3
- )
4
1
  from typing import (
5
2
  Any,
6
3
  Callable,
7
- Dict,
8
4
  Iterable,
9
- Optional,
10
- Tuple,
5
+ Mapping,
11
6
  TypeVar,
12
7
  )
13
8
 
@@ -97,8 +92,8 @@ def static_return(value: TValue) -> Callable[..., TValue]:
97
92
  return inner
98
93
 
99
94
 
100
- def static_result(value: TValue) -> Callable[..., Dict[str, TValue]]:
101
- def inner(*args: Any, **kwargs: Any) -> Dict[str, TValue]:
95
+ def static_result(value: TValue) -> Callable[..., dict[str, TValue]]:
96
+ def inner(*args: Any, **kwargs: Any) -> dict[str, TValue]:
102
97
  return {"result": value}
103
98
 
104
99
  return inner
@@ -107,8 +102,8 @@ def static_result(value: TValue) -> Callable[..., Dict[str, TValue]]:
107
102
  @curry
108
103
  @to_dict
109
104
  def apply_key_map(
110
- key_mappings: Dict[Any, Any], value: Dict[Any, Any]
111
- ) -> Iterable[Tuple[Any, Any]]:
105
+ key_mappings: dict[Any, Any], value: dict[Any, Any]
106
+ ) -> Iterable[tuple[Any, Any]]:
112
107
  for key, item in value.items():
113
108
  if key in key_mappings:
114
109
  yield key_mappings[key], item
@@ -130,8 +125,8 @@ def is_array_of_dicts(value: Any) -> bool:
130
125
 
131
126
  @curry
132
127
  def remove_key_if(
133
- key: Any, remove_if: Callable[[Dict[Any, Any]], bool], input_dict: Dict[Any, Any]
134
- ) -> Dict[Any, Any]:
128
+ key: Any, remove_if: Callable[[dict[Any, Any]], bool], input_dict: dict[Any, Any]
129
+ ) -> dict[Any, Any]:
135
130
  if key in input_dict and remove_if(input_dict):
136
131
  return dissoc(input_dict, key)
137
132
  else:
@@ -152,7 +147,7 @@ def apply_error_formatters(
152
147
  def apply_null_result_formatters(
153
148
  null_result_formatters: Callable[..., Any],
154
149
  response: RPCResponse,
155
- params: Optional[Any] = None,
150
+ params: Any | None = None,
156
151
  ) -> RPCResponse:
157
152
  if null_result_formatters:
158
153
  formatted_resp = pipe(params, null_result_formatters)
@@ -8,10 +8,6 @@ import threading
8
8
  import time
9
9
  from typing import (
10
10
  Any,
11
- Dict,
12
- List,
13
- Optional,
14
- Union,
15
11
  )
16
12
 
17
13
  from aiohttp import (
@@ -50,11 +46,9 @@ class HTTPSessionManager:
50
46
  self,
51
47
  cache_size: int = 100,
52
48
  session_pool_max_workers: int = 5,
53
- explicit_session: Optional[requests.Session] = None,
54
49
  ) -> None:
55
50
  self.session_cache = SimpleCache(cache_size)
56
51
  self.session_pool = ThreadPoolExecutor(max_workers=session_pool_max_workers)
57
- self._explicit_session = explicit_session
58
52
 
59
53
  @staticmethod
60
54
  def get_default_http_endpoint() -> URI:
@@ -64,13 +58,8 @@ class HTTPSessionManager:
64
58
  self,
65
59
  endpoint_uri: URI,
66
60
  session: requests.Session = None,
67
- request_timeout: Optional[float] = None,
61
+ request_timeout: float | None = None,
68
62
  ) -> requests.Session:
69
- # If an explicit session was provided at init time, always use it
70
- # regardless of which thread is making the request
71
- if self._explicit_session is not None:
72
- return self._explicit_session
73
-
74
63
  # cache key should have a unique thread identifier
75
64
  cache_key = generate_cache_key(f"{threading.get_ident()}:{endpoint_uri}")
76
65
 
@@ -119,7 +108,7 @@ class HTTPSessionManager:
119
108
 
120
109
  def json_make_get_request(
121
110
  self, endpoint_uri: URI, *args: Any, **kwargs: Any
122
- ) -> Dict[str, Any]:
111
+ ) -> dict[str, Any]:
123
112
  response = self.get_response_from_get_request(endpoint_uri, *args, **kwargs)
124
113
  response.raise_for_status()
125
114
  return response.json()
@@ -135,13 +124,13 @@ class HTTPSessionManager:
135
124
 
136
125
  def json_make_post_request(
137
126
  self, endpoint_uri: URI, *args: Any, **kwargs: Any
138
- ) -> Dict[str, Any]:
127
+ ) -> dict[str, Any]:
139
128
  response = self.get_response_from_post_request(endpoint_uri, *args, **kwargs)
140
129
  response.raise_for_status()
141
130
  return response.json()
142
131
 
143
132
  def make_post_request(
144
- self, endpoint_uri: URI, data: Union[bytes, Dict[str, Any]], **kwargs: Any
133
+ self, endpoint_uri: URI, data: bytes | dict[str, Any], **kwargs: Any
145
134
  ) -> bytes:
146
135
  kwargs.setdefault("timeout", DEFAULT_HTTP_TIMEOUT)
147
136
  kwargs.setdefault("stream", False)
@@ -171,7 +160,7 @@ class HTTPSessionManager:
171
160
  raise TimeExhausted
172
161
  return response_body
173
162
 
174
- def _close_evicted_sessions(self, evicted_sessions: List[requests.Session]) -> None:
163
+ def _close_evicted_sessions(self, evicted_sessions: list[requests.Session]) -> None:
175
164
  for evicted_session in evicted_sessions:
176
165
  evicted_session.close()
177
166
  self.logger.debug("Closed evicted session: %s", evicted_session)
@@ -181,8 +170,8 @@ class HTTPSessionManager:
181
170
  async def async_cache_and_return_session(
182
171
  self,
183
172
  endpoint_uri: URI,
184
- session: Optional[ClientSession] = None,
185
- request_timeout: Optional[ClientTimeout] = None,
173
+ session: ClientSession | None = None,
174
+ request_timeout: ClientTimeout | None = None,
186
175
  ) -> ClientSession:
187
176
  # cache key should have a unique thread identifier
188
177
  cache_key = generate_cache_key(f"{id(asyncio.get_event_loop())}:{endpoint_uri}")
@@ -291,7 +280,7 @@ class HTTPSessionManager:
291
280
 
292
281
  async def async_json_make_get_request(
293
282
  self, endpoint_uri: URI, *args: Any, **kwargs: Any
294
- ) -> Dict[str, Any]:
283
+ ) -> dict[str, Any]:
295
284
  response = await self.async_get_response_from_get_request(
296
285
  endpoint_uri, *args, **kwargs
297
286
  )
@@ -310,7 +299,7 @@ class HTTPSessionManager:
310
299
 
311
300
  async def async_json_make_post_request(
312
301
  self, endpoint_uri: URI, *args: Any, **kwargs: Any
313
- ) -> Dict[str, Any]:
302
+ ) -> dict[str, Any]:
314
303
  response = await self.async_get_response_from_post_request(
315
304
  endpoint_uri, *args, **kwargs
316
305
  )
@@ -318,7 +307,7 @@ class HTTPSessionManager:
318
307
  return await response.json()
319
308
 
320
309
  async def async_make_post_request(
321
- self, endpoint_uri: URI, data: Union[bytes, Dict[str, Any]], **kwargs: Any
310
+ self, endpoint_uri: URI, data: bytes | dict[str, Any], **kwargs: Any
322
311
  ) -> bytes:
323
312
  response = await self.async_get_response_from_post_request(
324
313
  endpoint_uri, data=data, **kwargs
@@ -327,7 +316,7 @@ class HTTPSessionManager:
327
316
  return await response.read()
328
317
 
329
318
  async def _async_close_evicted_sessions(
330
- self, timeout: float, evicted_sessions: List[ClientSession]
319
+ self, timeout: float, evicted_sessions: list[ClientSession]
331
320
  ) -> None:
332
321
  await asyncio.sleep(timeout)
333
322
 
web3/_utils/math.py CHANGED
@@ -1,5 +1,4 @@
1
1
  from typing import (
2
- Optional,
3
2
  Sequence,
4
3
  )
5
4
 
@@ -10,7 +9,7 @@ from web3.exceptions import (
10
9
 
11
10
 
12
11
  def percentile(
13
- values: Optional[Sequence[int]] = None, percentile: Optional[float] = None
12
+ values: Sequence[int] | None = None, percentile: float | None = None
14
13
  ) -> float:
15
14
  """Calculates a simplified weighted average percentile"""
16
15
  if values in [None, tuple(), []] or len(values) < 1:
@@ -5,10 +5,8 @@ from typing import (
5
5
  Any,
6
6
  Callable,
7
7
  Collection,
8
- Dict,
9
8
  Iterable,
10
9
  NoReturn,
11
- Tuple,
12
10
  TypeVar,
13
11
  Union,
14
12
  cast,
@@ -136,7 +134,7 @@ is_not_null = complement(is_null)
136
134
 
137
135
  @curry
138
136
  def to_hexbytes(
139
- num_bytes: int, val: Union[str, int, bytes], variable_length: bool = False
137
+ num_bytes: int, val: str | int | bytes, variable_length: bool = False
140
138
  ) -> HexBytes:
141
139
  if isinstance(val, (str, int, bytes)):
142
140
  result = HexBytes(val)
@@ -161,8 +159,8 @@ def is_attrdict(val: Any) -> bool:
161
159
  @curry
162
160
  def type_aware_apply_formatters_to_dict(
163
161
  formatters: Formatters,
164
- value: Union[AttributeDict[str, Any], Dict[str, Any]],
165
- ) -> Union[ReadableAttributeDict[str, Any], Dict[str, Any]]:
162
+ value: AttributeDict[str, Any] | dict[str, Any],
163
+ ) -> ReadableAttributeDict[str, Any] | dict[str, Any]:
166
164
  """
167
165
  Preserve ``AttributeDict`` types if original ``value`` was an ``AttributeDict``.
168
166
  """
@@ -172,7 +170,7 @@ def type_aware_apply_formatters_to_dict(
172
170
  if isinstance(value, BaseModel):
173
171
  value = value.model_dump(by_alias=True)
174
172
 
175
- formatted_dict: Dict[str, Any] = apply_formatters_to_dict(formatters, dict(value))
173
+ formatted_dict: dict[str, Any] = apply_formatters_to_dict(formatters, dict(value))
176
174
  return (
177
175
  AttributeDict.recursive(formatted_dict)
178
176
  if is_attrdict(value)
@@ -183,8 +181,8 @@ def type_aware_apply_formatters_to_dict(
183
181
  def type_aware_apply_formatters_to_dict_keys_and_values(
184
182
  key_formatters: Callable[[Any], Any],
185
183
  value_formatters: Callable[[Any], Any],
186
- dict_like_object: Union[AttributeDict[str, Any], Dict[str, Any]],
187
- ) -> Union[ReadableAttributeDict[str, Any], Dict[str, Any]]:
184
+ dict_like_object: AttributeDict[str, Any] | dict[str, Any],
185
+ ) -> ReadableAttributeDict[str, Any] | dict[str, Any]:
188
186
  """
189
187
  Preserve ``AttributeDict`` types if original ``value`` was an ``AttributeDict``.
190
188
  """
@@ -205,7 +203,7 @@ def apply_list_to_array_formatter(formatter: Any) -> Callable[..., Any]:
205
203
  return to_list(apply_formatter_to_array(formatter))
206
204
 
207
205
 
208
- def storage_key_to_hexstr(value: Union[bytes, int, str]) -> HexStr:
206
+ def storage_key_to_hexstr(value: bytes | int | str) -> HexStr:
209
207
  if not isinstance(value, (bytes, int, str)):
210
208
  raise Web3ValueError(
211
209
  f"Storage key must be one of bytes, int, str, got {type(value)}"
@@ -555,7 +553,7 @@ transaction_param_formatter = compose(
555
553
 
556
554
 
557
555
  call_without_override: Callable[
558
- [Tuple[TxParams, BlockIdentifier]], Tuple[Dict[str, Any], int]
556
+ [tuple[TxParams, BlockIdentifier]], tuple[dict[str, Any], int]
559
557
  ] = apply_formatters_to_sequence(
560
558
  [
561
559
  transaction_param_formatter,
@@ -573,8 +571,8 @@ state_override_formatter = type_aware_apply_formatters_to_dict(
573
571
  )
574
572
 
575
573
  call_with_override: Callable[
576
- [Tuple[TxParams, BlockIdentifier, StateOverrideParams]],
577
- Tuple[Dict[str, Any], int, Dict[str, Any]],
574
+ [tuple[TxParams, BlockIdentifier, StateOverrideParams]],
575
+ tuple[dict[str, Any], int, dict[str, Any]],
578
576
  ] = apply_formatters_to_sequence(
579
577
  [
580
578
  transaction_param_formatter,
@@ -589,10 +587,10 @@ call_with_override: Callable[
589
587
 
590
588
 
591
589
  estimate_gas_without_block_id: Callable[
592
- [Dict[str, Any]], Dict[str, Any]
590
+ [dict[str, Any]], dict[str, Any]
593
591
  ] = apply_formatter_at_index(transaction_param_formatter, 0)
594
592
  estimate_gas_with_block_id: Callable[
595
- [Tuple[Dict[str, Any], BlockIdentifier]], Tuple[Dict[str, Any], int]
593
+ [tuple[dict[str, Any], BlockIdentifier]], tuple[dict[str, Any], int]
596
594
  ] = apply_formatters_to_sequence(
597
595
  [
598
596
  transaction_param_formatter,
@@ -600,8 +598,8 @@ estimate_gas_with_block_id: Callable[
600
598
  ]
601
599
  )
602
600
  estimate_gas_with_override: Callable[
603
- [Tuple[Dict[str, Any], BlockIdentifier, StateOverrideParams]],
604
- Tuple[Dict[str, Any], int, Dict[str, Any]],
601
+ [tuple[dict[str, Any], BlockIdentifier, StateOverrideParams]],
602
+ tuple[dict[str, Any], int, dict[str, Any]],
605
603
  ] = apply_formatters_to_sequence(
606
604
  [
607
605
  transaction_param_formatter,
@@ -617,7 +615,7 @@ estimate_gas_with_override: Callable[
617
615
  # -- eth_simulateV1 -- #
618
616
 
619
617
  block_state_calls_formatter: Callable[
620
- [Dict[str, Any]], Dict[str, Any]
618
+ [dict[str, Any]], dict[str, Any]
621
619
  ] = apply_formatter_to_array(
622
620
  apply_formatters_to_dict(
623
621
  {
@@ -635,8 +633,8 @@ block_state_calls_formatter: Callable[
635
633
  )
636
634
 
637
635
  simulate_v1_request_formatter: Callable[
638
- [Tuple[Dict[str, Any], bool, bool], BlockIdentifier],
639
- Tuple[SimulateV1Payload, BlockIdentifier],
636
+ [tuple[dict[str, Any], bool, bool], BlockIdentifier],
637
+ tuple[SimulateV1Payload, BlockIdentifier],
640
638
  ] = apply_formatters_to_sequence(
641
639
  [
642
640
  # payload
@@ -691,7 +689,7 @@ GETH_WALLETS_FORMATTER = {
691
689
 
692
690
  geth_wallets_formatter = type_aware_apply_formatters_to_dict(GETH_WALLETS_FORMATTER)
693
691
 
694
- PYTHONIC_REQUEST_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
692
+ PYTHONIC_REQUEST_FORMATTERS: dict[RPCEndpoint, Callable[..., Any]] = {
695
693
  # Eth
696
694
  RPC.eth_feeHistory: compose(
697
695
  apply_formatter_at_index(to_hex_if_integer, 0),
@@ -795,8 +793,8 @@ def has_pretrace_keys(val: Any) -> bool:
795
793
 
796
794
  @curry
797
795
  def pretrace_formatter(
798
- resp: Union[AttributeDict[str, Any], Dict[str, Any]],
799
- ) -> Union[ReadableAttributeDict[str, Any], Dict[str, Any]]:
796
+ resp: AttributeDict[str, Any] | dict[str, Any],
797
+ ) -> ReadableAttributeDict[str, Any] | dict[str, Any]:
800
798
  return type_aware_apply_formatters_to_dict_keys_and_values(
801
799
  apply_formatter_if(is_address, to_checksum_address),
802
800
  apply_formatter_if(
@@ -892,7 +890,7 @@ TRACE_RESULT_FORMATTERS = apply_formatter_if(
892
890
  )
893
891
 
894
892
  # result formatters for the trace field
895
- TRACE_FORMATTERS: Callable[[TValue], Union[Any, TValue]] = apply_formatter_if(
893
+ TRACE_FORMATTERS: Callable[[TValue], Any | TValue] = apply_formatter_if(
896
894
  is_not_null,
897
895
  type_aware_apply_formatters_to_dict(
898
896
  {
@@ -921,7 +919,7 @@ common_tracing_result_formatter = type_aware_apply_formatters_to_dict(
921
919
 
922
920
 
923
921
  # -- eth_subscribe -- #
924
- def subscription_formatter(value: Any) -> Union[HexBytes, HexStr, Dict[str, Any]]:
922
+ def subscription_formatter(value: Any) -> HexBytes | HexStr | dict[str, Any]:
925
923
  if is_hexstr(value):
926
924
  # subscription id from the original subscription request
927
925
  return HexStr(value)
@@ -980,7 +978,7 @@ def subscription_formatter(value: Any) -> Union[HexBytes, HexStr, Dict[str, Any]
980
978
  return value
981
979
 
982
980
 
983
- PYTHONIC_RESULT_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
981
+ PYTHONIC_RESULT_FORMATTERS: dict[RPCEndpoint, Callable[..., Any]] = {
984
982
  # Eth
985
983
  RPC.eth_accounts: apply_list_to_array_formatter(to_checksum_address),
986
984
  RPC.eth_blobBaseFee: to_integer_if_hex,
@@ -1068,7 +1066,7 @@ PYTHONIC_RESULT_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1068
1066
  ),
1069
1067
  }
1070
1068
 
1071
- METHOD_NORMALIZERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1069
+ METHOD_NORMALIZERS: dict[RPCEndpoint, Callable[..., Any]] = {
1072
1070
  RPC.eth_getLogs: apply_formatter_at_index(FILTER_PARAM_NORMALIZERS, 0),
1073
1071
  RPC.eth_newFilter: apply_formatter_at_index(FILTER_PARAM_NORMALIZERS, 0),
1074
1072
  }
@@ -1086,7 +1084,7 @@ ABI_REQUEST_FORMATTERS: Formatters = abi_request_formatters(
1086
1084
  )
1087
1085
 
1088
1086
 
1089
- ERROR_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1087
+ ERROR_FORMATTERS: dict[RPCEndpoint, Callable[..., Any]] = {
1090
1088
  RPC.eth_estimateGas: raise_contract_logic_error_on_revert,
1091
1089
  RPC.eth_call: raise_contract_logic_error_on_revert,
1092
1090
  RPC.eth_getTransactionReceipt: raise_transaction_indexing_error_if_indexing,
@@ -1096,7 +1094,7 @@ ERROR_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1096
1094
 
1097
1095
  @to_tuple
1098
1096
  def combine_formatters(
1099
- formatter_maps: Collection[Dict[RPCEndpoint, Callable[..., TReturn]]],
1097
+ formatter_maps: Collection[dict[RPCEndpoint, Callable[..., TReturn]]],
1100
1098
  method_name: RPCEndpoint,
1101
1099
  ) -> Iterable[Callable[..., TReturn]]:
1102
1100
  for formatter_map in formatter_maps:
@@ -1118,7 +1116,7 @@ def get_request_formatters(method_name: RPCEndpoint) -> Callable[[RPCResponse],
1118
1116
  return compose(*formatters)
1119
1117
 
1120
1118
 
1121
- def raise_block_not_found(params: Tuple[BlockIdentifier, bool]) -> NoReturn:
1119
+ def raise_block_not_found(params: tuple[BlockIdentifier, bool]) -> NoReturn:
1122
1120
  try:
1123
1121
  block_identifier = params[0]
1124
1122
  message = f"Block with id: {block_identifier!r} not found."
@@ -1129,7 +1127,7 @@ def raise_block_not_found(params: Tuple[BlockIdentifier, bool]) -> NoReturn:
1129
1127
 
1130
1128
 
1131
1129
  def raise_block_not_found_for_uncle_at_index(
1132
- params: Tuple[BlockIdentifier, Union[HexStr, int]],
1130
+ params: tuple[BlockIdentifier, HexStr | int],
1133
1131
  ) -> NoReturn:
1134
1132
  try:
1135
1133
  block_identifier = params[0]
@@ -1144,7 +1142,7 @@ def raise_block_not_found_for_uncle_at_index(
1144
1142
  raise BlockNotFound(message)
1145
1143
 
1146
1144
 
1147
- def raise_transaction_not_found(params: Tuple[_Hash32]) -> NoReturn:
1145
+ def raise_transaction_not_found(params: tuple[_Hash32]) -> NoReturn:
1148
1146
  try:
1149
1147
  transaction_hash = params[0]
1150
1148
  message = f"Transaction with hash: {transaction_hash!r} not found."
@@ -1155,7 +1153,7 @@ def raise_transaction_not_found(params: Tuple[_Hash32]) -> NoReturn:
1155
1153
 
1156
1154
 
1157
1155
  def raise_transaction_not_found_with_index(
1158
- params: Tuple[BlockIdentifier, int],
1156
+ params: tuple[BlockIdentifier, int],
1159
1157
  ) -> NoReturn:
1160
1158
  try:
1161
1159
  block_identifier = params[0]
@@ -1170,7 +1168,7 @@ def raise_transaction_not_found_with_index(
1170
1168
  raise TransactionNotFound(message)
1171
1169
 
1172
1170
 
1173
- NULL_RESULT_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1171
+ NULL_RESULT_FORMATTERS: dict[RPCEndpoint, Callable[..., Any]] = {
1174
1172
  RPC.eth_getBlockByHash: raise_block_not_found,
1175
1173
  RPC.eth_getBlockByNumber: raise_block_not_found,
1176
1174
  RPC.eth_getBlockReceipts: raise_block_not_found,
@@ -1194,14 +1192,14 @@ def filter_wrapper(
1194
1192
  module: Union["AsyncEth", "Eth"],
1195
1193
  method: RPCEndpoint,
1196
1194
  filter_id: HexStr,
1197
- ) -> Union[
1198
- AsyncBlockFilter,
1199
- AsyncTransactionFilter,
1200
- AsyncLogFilter,
1201
- BlockFilter,
1202
- TransactionFilter,
1203
- LogFilter,
1204
- ]:
1195
+ ) -> (
1196
+ AsyncBlockFilter
1197
+ | AsyncTransactionFilter
1198
+ | AsyncLogFilter
1199
+ | BlockFilter
1200
+ | TransactionFilter
1201
+ | LogFilter
1202
+ ):
1205
1203
  if method == RPC.eth_newBlockFilter:
1206
1204
  if module.is_async:
1207
1205
  return AsyncBlockFilter(filter_id, eth_module=cast("AsyncEth", module))
@@ -1227,7 +1225,7 @@ def filter_wrapper(
1227
1225
  )
1228
1226
 
1229
1227
 
1230
- FILTER_RESULT_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1228
+ FILTER_RESULT_FORMATTERS: dict[RPCEndpoint, Callable[..., Any]] = {
1231
1229
  RPC.eth_newPendingTransactionFilter: filter_wrapper,
1232
1230
  RPC.eth_newBlockFilter: filter_wrapper,
1233
1231
  RPC.eth_newFilter: filter_wrapper,
@@ -1238,7 +1236,7 @@ FILTER_RESULT_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
1238
1236
  def apply_module_to_formatters(
1239
1237
  formatters: Iterable[Callable[..., TReturn]],
1240
1238
  module: "Module",
1241
- method_name: Union[RPCEndpoint, Callable[..., RPCEndpoint]],
1239
+ method_name: RPCEndpoint | Callable[..., RPCEndpoint],
1242
1240
  ) -> Iterable[Callable[..., TReturn]]:
1243
1241
  for f in formatters:
1244
1242
  yield partial(f, module, method_name)
web3/_utils/module.py CHANGED
@@ -5,9 +5,6 @@ from io import (
5
5
  from typing import (
6
6
  TYPE_CHECKING,
7
7
  Any,
8
- Dict,
9
- List,
10
- Optional,
11
8
  Sequence,
12
9
  Union,
13
10
  )
@@ -24,7 +21,7 @@ if TYPE_CHECKING:
24
21
  from web3.main import BaseWeb3 # noqa: F401
25
22
 
26
23
 
27
- def _validate_init_params_and_return_if_found(module_class: Any) -> List[str]:
24
+ def _validate_init_params_and_return_if_found(module_class: Any) -> list[str]:
28
25
  init_params_raw = list(inspect.signature(module_class.__init__).parameters)
29
26
  module_init_params = [
30
27
  param for param in init_params_raw if param not in ["self", "args", "kwargs"]
@@ -42,8 +39,8 @@ def _validate_init_params_and_return_if_found(module_class: Any) -> List[str]:
42
39
 
43
40
  def attach_modules(
44
41
  parent_module: Union["BaseWeb3", "Module"],
45
- module_definitions: Dict[str, Any],
46
- w3: Optional[Union["BaseWeb3", "Module"]] = None,
42
+ module_definitions: dict[str, Any],
43
+ w3: Union["BaseWeb3", "Module"] | None = None,
47
44
  ) -> None:
48
45
  for module_name, module_info in module_definitions.items():
49
46
  module_info_is_list_like = isinstance(module_info, Sequence)
@@ -10,8 +10,6 @@ from typing import (
10
10
  TYPE_CHECKING,
11
11
  Any,
12
12
  Callable,
13
- List,
14
- Type,
15
13
  Union,
16
14
  cast,
17
15
  )
@@ -660,7 +658,7 @@ class AsyncEthModuleTest:
660
658
 
661
659
  @pytest.mark.asyncio
662
660
  async def test_ExtraDataToPOAMiddleware(
663
- self, async_w3: "AsyncWeb3[Any]", request_mocker: Type[RequestMocker]
661
+ self, async_w3: "AsyncWeb3[Any]", request_mocker: type[RequestMocker]
664
662
  ) -> None:
665
663
  async_w3.middleware_onion.inject(ExtraDataToPOAMiddleware, "poa", layer=0)
666
664
  extra_data = f"0x{'ff' * 33}"
@@ -1011,7 +1009,7 @@ class AsyncEthModuleTest:
1011
1009
 
1012
1010
  @pytest.mark.asyncio
1013
1011
  async def test_eth_max_priority_fee_with_fee_history_calculation(
1014
- self, async_w3: "AsyncWeb3[Any]", request_mocker: Type[RequestMocker]
1012
+ self, async_w3: "AsyncWeb3[Any]", request_mocker: type[RequestMocker]
1015
1013
  ) -> None:
1016
1014
  async with request_mocker(
1017
1015
  async_w3,
@@ -1206,7 +1204,7 @@ class AsyncEthModuleTest:
1206
1204
  async def test_eth_get_raw_transaction_by_block_raises_error(
1207
1205
  self,
1208
1206
  async_w3: "AsyncWeb3[Any]",
1209
- unknown_block_num_or_hash: Union[int, HexBytes],
1207
+ unknown_block_num_or_hash: int | HexBytes,
1210
1208
  ) -> None:
1211
1209
  with pytest.raises(
1212
1210
  TransactionNotFound,
@@ -1519,7 +1517,7 @@ class AsyncEthModuleTest:
1519
1517
  async_w3: "AsyncWeb3[Any]",
1520
1518
  async_panic_errors_contract: "AsyncContract",
1521
1519
  panic_error: str,
1522
- params: List[Any],
1520
+ params: list[Any],
1523
1521
  ) -> None:
1524
1522
  method = getattr(
1525
1523
  async_panic_errors_contract.functions,
@@ -2697,7 +2695,7 @@ class EthModuleTest:
2697
2695
  assert is_integer(max_priority_fee)
2698
2696
 
2699
2697
  def test_eth_max_priority_fee_with_fee_history_calculation(
2700
- self, w3: "Web3", request_mocker: Type[RequestMocker]
2698
+ self, w3: "Web3", request_mocker: type[RequestMocker]
2701
2699
  ) -> None:
2702
2700
  with request_mocker(
2703
2701
  w3,
@@ -4171,7 +4169,7 @@ class EthModuleTest:
4171
4169
  w3: "Web3",
4172
4170
  panic_errors_contract: "Contract",
4173
4171
  panic_error: str,
4174
- params: List[Any],
4172
+ params: list[Any],
4175
4173
  ) -> None:
4176
4174
  method = getattr(
4177
4175
  panic_errors_contract.functions,
@@ -5016,7 +5014,7 @@ class EthModuleTest:
5016
5014
 
5017
5015
  @pytest.mark.parametrize("unknown_block_num_or_hash", (1234567899999, UNKNOWN_HASH))
5018
5016
  def test_eth_get_raw_transaction_by_block_raises_error(
5019
- self, w3: "Web3", unknown_block_num_or_hash: Union[int, HexBytes]
5017
+ self, w3: "Web3", unknown_block_num_or_hash: int | HexBytes
5020
5018
  ) -> None:
5021
5019
  with pytest.raises(
5022
5020
  TransactionNotFound,
@@ -2,7 +2,6 @@ import pytest
2
2
  from typing import (
3
3
  TYPE_CHECKING,
4
4
  Any,
5
- List,
6
5
  )
7
6
 
8
7
  from web3.datastructures import (
@@ -83,7 +82,7 @@ class GoEthereumAsyncAdminModuleTest:
83
82
  @pytest.mark.asyncio
84
83
  async def test_async_nodes(self, async_w3: "AsyncWeb3[Any]") -> None:
85
84
  nodes = await async_w3.geth.admin.peers()
86
- assert isinstance(nodes, List)
85
+ assert isinstance(nodes, list)
87
86
 
88
87
  @pytest.mark.asyncio
89
88
  async def test_admin_peers(self, async_w3: "AsyncWeb3[Any]") -> None:
@@ -3,7 +3,6 @@ from typing import (
3
3
  TYPE_CHECKING,
4
4
  Any,
5
5
  Collection,
6
- Dict,
7
6
  Generator,
8
7
  Literal,
9
8
  Sequence,
@@ -25,6 +24,9 @@ from hexbytes import (
25
24
  HexBytes,
26
25
  )
27
26
  import requests
27
+ from websockets.protocol import (
28
+ State,
29
+ )
28
30
 
29
31
  from web3._utils.http import (
30
32
  DEFAULT_HTTP_TIMEOUT,
@@ -77,7 +79,7 @@ def mock_offchain_lookup_request_response(
77
79
  status_code = mocked_status_code
78
80
 
79
81
  @staticmethod
80
- def json() -> Dict[str, str]:
82
+ def json() -> dict[str, str]:
81
83
  return {json_data_field: mocked_json_data} # noqa: E704
82
84
 
83
85
  @staticmethod
@@ -127,7 +129,7 @@ def async_mock_offchain_lookup_request_response(
127
129
  return self
128
130
 
129
131
  @staticmethod
130
- async def json() -> Dict[str, str]:
132
+ async def json() -> dict[str, str]:
131
133
  return {json_data_field: mocked_json_data} # noqa: E704
132
134
 
133
135
  @staticmethod
@@ -160,10 +162,12 @@ def async_mock_offchain_lookup_request_response(
160
162
 
161
163
 
162
164
  class WebSocketMessageStreamMock:
163
- closed: bool = False
165
+ state: State = State.OPEN
164
166
 
165
167
  def __init__(
166
- self, messages: Collection[bytes] = None, raise_exception: Exception = None
168
+ self,
169
+ messages: Collection[bytes] = None,
170
+ raise_exception: Exception = None,
167
171
  ) -> None:
168
172
  self.queue = asyncio.Queue() # type: ignore # py38 issue
169
173
  for msg in messages or []:
@@ -6,12 +6,8 @@ from dataclasses import (
6
6
  from typing import (
7
7
  TYPE_CHECKING,
8
8
  Any,
9
- Dict,
10
9
  Generator,
11
- List,
12
10
  Sequence,
13
- Tuple,
14
- Union,
15
11
  cast,
16
12
  )
17
13
 
@@ -306,8 +302,8 @@ class PersistentConnectionProviderTest:
306
302
  async def test_async_eth_subscribe_syncing_mocked(
307
303
  self,
308
304
  async_w3: "AsyncWeb3[Any]",
309
- subscription_params: Tuple[Any, ...],
310
- ws_subscription_response: Dict[str, Any],
305
+ subscription_params: tuple[Any, ...],
306
+ ws_subscription_response: dict[str, Any],
311
307
  expected_formatted_result: Any,
312
308
  ) -> None:
313
309
  sub_id = await async_w3.eth.subscribe(*subscription_params)
@@ -966,7 +962,7 @@ class PersistentConnectionProviderTest:
966
962
  async_w3: "AsyncWeb3[Any]",
967
963
  ) -> None:
968
964
  async def unsubscribe_subs(
969
- subs: List[Union[NewHeadsSubscription, LogsSubscription]],
965
+ subs: list[NewHeadsSubscription | LogsSubscription],
970
966
  ) -> None:
971
967
  for sub in subs:
972
968
  await sub.unsubscribe()