Skip to content

Commit 2dced98

Browse files
aleexharrisfselmokclowes
authored
Make AsyncWeb3 Generic (#3761)
* fix: Made function params Optional, as None is the default input * feat: Made AsyncWeb3 class Generic to fix type errors when importing Web3 * refactor: remove unnecessary noqa: E501 uses * fix: remove `Optional` where it isn't optional * fix: Use `Optional` where appropriate * chore: add newsfragment for #3761 * fix: Removed where it isn't optional * Remove unnecessary changes --------- Co-authored-by: fselmo <[email protected]> Co-authored-by: kclowes <[email protected]>
1 parent 4ccd2bd commit 2dced98

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+378
-331
lines changed

ens/async_ens.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@
7272
AsyncContract,
7373
AsyncContractFunction,
7474
)
75-
from web3.main import AsyncWeb3 # noqa: F401
75+
from web3.main import ( # noqa: F401
76+
AsyncWeb3,
77+
)
7678
from web3.middleware.base import ( # noqa: F401
7779
Middleware,
7880
)
@@ -96,12 +98,12 @@ class AsyncENS(BaseENS):
9698
"""
9799

98100
# mypy types
99-
w3: "AsyncWeb3"
101+
w3: "AsyncWeb3[Any]"
100102

101103
def __init__(
102104
self,
103-
provider: "AsyncBaseProvider" = None,
104-
addr: ChecksumAddress = None,
105+
provider: Optional["AsyncBaseProvider"] = None,
106+
addr: Optional[ChecksumAddress] = None,
105107
middleware: Optional[Sequence[Tuple["Middleware", str]]] = None,
106108
) -> None:
107109
"""
@@ -123,7 +125,9 @@ def __init__(
123125
)
124126

125127
@classmethod
126-
def from_web3(cls, w3: "AsyncWeb3", addr: ChecksumAddress = None) -> "AsyncENS":
128+
def from_web3(
129+
cls, w3: "AsyncWeb3[Any]", addr: ChecksumAddress = None
130+
) -> "AsyncENS":
127131
"""
128132
Generate an AsyncENS instance with web3
129133

ens/base_ens.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838

3939

4040
class BaseENS:
41-
w3: Union["AsyncWeb3", "Web3"] = None
41+
w3: Union["AsyncWeb3[Any]", "Web3"] = None
4242
ens: Union["Contract", "AsyncContract"] = None
4343
_resolver_contract: Union[Type["Contract"], Type["AsyncContract"]] = None
4444
_reverse_resolver_contract: Union[Type["Contract"], Type["AsyncContract"]] = None

ens/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ def is_valid_ens_name(ens_name: str) -> bool:
302302
def init_async_web3(
303303
provider: "AsyncBaseProvider" = None,
304304
middleware: Optional[Sequence[Tuple["Middleware", str]]] = (),
305-
) -> "AsyncWeb3":
305+
) -> "AsyncWeb3[Any]":
306306
from web3 import (
307307
AsyncWeb3 as AsyncWeb3Main,
308308
)
@@ -327,6 +327,7 @@ def init_async_web3(
327327
)
328328
)
329329

330+
async_w3: "AsyncWeb3[Any]"
330331
if provider is default:
331332
async_w3 = AsyncWeb3Main(
332333
middleware=middleware, ens=None, modules={"eth": (AsyncEthMain)}

newsfragments/3761.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make `AsyncWeb3` with respect to the provider it is instantiated with, fixing static type issues.

tests/core/contracts/test_contract_call_interface.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,8 @@ def test_call_get_byte_array_non_strict(non_strict_arrays_contract, call):
238238
"args,expected",
239239
[
240240
([b"1"], [b"1"]),
241-
(["0xDe"], [b"\xDe"]),
242-
(["0xDe", "0xDe"], [b"\xDe", b"\xDe"]),
241+
(["0xDe"], [b"\xde"]),
242+
(["0xDe", "0xDe"], [b"\xde", b"\xde"]),
243243
],
244244
)
245245
def test_set_byte_array(arrays_contract, call, transact, args, expected):
@@ -257,8 +257,8 @@ def test_set_byte_array(arrays_contract, call, transact, args, expected):
257257
"args,expected",
258258
[
259259
([b"1"], [b"1"]),
260-
(["0xDe"], [b"\xDe"]),
261-
(["0xDe", "0xDe"], [b"\xDe", b"\xDe"]),
260+
(["0xDe"], [b"\xde"]),
261+
(["0xDe", "0xDe"], [b"\xde", b"\xde"]),
262262
],
263263
)
264264
def test_set_byte_array_non_strict(
@@ -1503,7 +1503,7 @@ async def test_async_set_byte_array_non_strict(
15031503

15041504

15051505
@pytest.mark.asyncio
1506-
@pytest.mark.parametrize("args,expected", [([b"1"], [b"1"]), (["0xDe"], [b"\xDe"])])
1506+
@pytest.mark.parametrize("args,expected", [([b"1"], [b"1"]), (["0xDe"], [b"\xde"])])
15071507
async def test_async_set_byte_array_strict_by_default(
15081508
async_arrays_contract, async_call, async_transact, args, expected
15091509
):

tests/core/utilities/test_abi.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,8 @@ def test_get_tuple_type_str_parts(
249249
[
250250
(
251251
["bool[2]", "bytes"],
252-
[[True, False], b"\x00\xFF"],
253-
[("bool[2]", [("bool", True), ("bool", False)]), ("bytes", b"\x00\xFF")],
252+
[[True, False], b"\x00\xff"],
253+
[("bool[2]", [("bool", True), ("bool", False)]), ("bytes", b"\x00\xff")],
254254
),
255255
(
256256
["uint256[]"],
@@ -337,7 +337,7 @@ def test_map_abi_data(
337337

338338
@pytest.mark.parametrize("arg", (6, 7, 9, 12, 20, 30))
339339
def test_exact_length_bytes_encoder_raises_on_non_multiples_of_8_bit_size(
340-
arg: Tuple[int, ...]
340+
arg: Tuple[int, ...],
341341
) -> None:
342342
with pytest.raises(Web3ValueError, match="multiple of 8"):
343343
_ = ExactLengthBytesEncoder(None, data_byte_size=2, value_bit_size=arg)

tests/core/web3-module/test_conversions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def test_to_int_hexstr(val, expected):
159159
(b"\x01", "0x01"),
160160
(b"\x10", "0x10"),
161161
(b"\x01\x00", "0x0100"),
162-
(b"\x00\x0F", "0x000f"),
162+
(b"\x00\x0f", "0x000f"),
163163
(b"", "0x"),
164164
(0, "0x0"),
165165
(1, "0x1"),

web3/_utils/abi.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -852,7 +852,7 @@ def _named_subtree(
852852

853853
def recursive_dict_to_namedtuple(data: Dict[str, Any]) -> Tuple[Any, ...]:
854854
def _dict_to_namedtuple(
855-
value: Union[Dict[str, Any], List[Any]]
855+
value: Union[Dict[str, Any], List[Any]],
856856
) -> Union[Tuple[Any, ...], List[Any]]:
857857
if not isinstance(value, dict):
858858
return value
@@ -864,7 +864,7 @@ def _dict_to_namedtuple(
864864

865865

866866
def abi_decoded_namedtuple_factory(
867-
fields: Tuple[Any, ...]
867+
fields: Tuple[Any, ...],
868868
) -> Callable[..., Tuple[Any, ...]]:
869869
class ABIDecodedNamedTuple(namedtuple("ABIDecodedNamedTuple", fields, rename=True)): # type: ignore # noqa: E501
870870
def __new__(self, args: Any) -> "ABIDecodedNamedTuple":
@@ -877,9 +877,9 @@ def __new__(self, args: Any) -> "ABIDecodedNamedTuple":
877877

878878

879879
async def async_data_tree_map(
880-
async_w3: "AsyncWeb3",
880+
async_w3: "AsyncWeb3[Any]",
881881
func: Callable[
882-
["AsyncWeb3", TypeStr, Any], Coroutine[Any, Any, Tuple[TypeStr, Any]]
882+
["AsyncWeb3[Any]", TypeStr, Any], Coroutine[Any, Any, Tuple[TypeStr, Any]]
883883
],
884884
data_tree: Any,
885885
) -> "ABITypedData":
@@ -902,7 +902,7 @@ async def async_map_to_typed_data(elements: Any) -> "ABITypedData":
902902

903903
@reject_recursive_repeats
904904
async def async_recursive_map(
905-
async_w3: "AsyncWeb3",
905+
async_w3: "AsyncWeb3[Any]",
906906
func: Callable[[Any], Coroutine[Any, Any, TReturn]],
907907
data: Any,
908908
) -> TReturn:

web3/_utils/async_transactions.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from typing import (
22
TYPE_CHECKING,
3+
Any,
34
Dict,
45
Optional,
56
Union,
@@ -46,13 +47,13 @@
4647

4748
# unused vars present in these funcs because they all need to have the same signature
4849
async def _estimate_gas(
49-
async_w3: "AsyncWeb3", tx: TxParams, _defaults: Dict[str, Union[bytes, int]]
50+
async_w3: "AsyncWeb3[Any]", tx: TxParams, _defaults: Dict[str, Union[bytes, int]]
5051
) -> int:
5152
return await async_w3.eth.estimate_gas(tx)
5253

5354

5455
async def _max_fee_per_gas(
55-
async_w3: "AsyncWeb3", tx: TxParams, defaults: Dict[str, Union[bytes, int]]
56+
async_w3: "AsyncWeb3[Any]", tx: TxParams, defaults: Dict[str, Union[bytes, int]]
5657
) -> Wei:
5758
block = await async_w3.eth.get_block("latest")
5859
max_priority_fee = tx.get(
@@ -62,13 +63,13 @@ async def _max_fee_per_gas(
6263

6364

6465
async def _max_priority_fee_gas(
65-
async_w3: "AsyncWeb3", _tx: TxParams, _defaults: Dict[str, Union[bytes, int]]
66+
async_w3: "AsyncWeb3[Any]", _tx: TxParams, _defaults: Dict[str, Union[bytes, int]]
6667
) -> Wei:
6768
return await async_w3.eth.max_priority_fee
6869

6970

7071
async def _chain_id(
71-
async_w3: "AsyncWeb3", _tx: TxParams, _defaults: Dict[str, Union[bytes, int]]
72+
async_w3: "AsyncWeb3[Any]", _tx: TxParams, _defaults: Dict[str, Union[bytes, int]]
7273
) -> int:
7374
return await async_w3.eth.chain_id
7475

@@ -92,7 +93,7 @@ async def get_block_gas_limit(
9293

9394

9495
async def get_buffered_gas_estimate(
95-
async_w3: "AsyncWeb3", transaction: TxParams, gas_buffer: int = 100000
96+
async_w3: "AsyncWeb3[Any]", transaction: TxParams, gas_buffer: int = 100000
9697
) -> int:
9798
gas_estimate_transaction = cast(TxParams, dict(**transaction))
9899

@@ -110,7 +111,9 @@ async def get_buffered_gas_estimate(
110111
return min(gas_limit, gas_estimate + gas_buffer)
111112

112113

113-
async def async_fill_nonce(async_w3: "AsyncWeb3", transaction: TxParams) -> TxParams:
114+
async def async_fill_nonce(
115+
async_w3: "AsyncWeb3[Any]", transaction: TxParams
116+
) -> TxParams:
114117
if "from" in transaction and "nonce" not in transaction:
115118
tx_count = await async_w3.eth.get_transaction_count(
116119
cast(ChecksumAddress, transaction["from"]),
@@ -121,7 +124,7 @@ async def async_fill_nonce(async_w3: "AsyncWeb3", transaction: TxParams) -> TxPa
121124

122125

123126
async def async_fill_transaction_defaults(
124-
async_w3: "AsyncWeb3", transaction: TxParams
127+
async_w3: "AsyncWeb3[Any]", transaction: TxParams
125128
) -> TxParams:
126129
"""
127130
If async_w3 is None, fill as much as possible while offline
@@ -165,7 +168,7 @@ async def async_fill_transaction_defaults(
165168

166169

167170
async def async_get_required_transaction(
168-
async_w3: "AsyncWeb3", transaction_hash: _Hash32
171+
async_w3: "AsyncWeb3[Any]", transaction_hash: _Hash32
169172
) -> TxData:
170173
current_transaction = await async_w3.eth.get_transaction(transaction_hash)
171174
if not current_transaction:
@@ -176,7 +179,7 @@ async def async_get_required_transaction(
176179

177180

178181
async def async_replace_transaction(
179-
async_w3: "AsyncWeb3", current_transaction: TxData, new_transaction: TxParams
182+
async_w3: "AsyncWeb3[Any]", current_transaction: TxData, new_transaction: TxParams
180183
) -> HexBytes:
181184
new_transaction = prepare_replacement_transaction(
182185
async_w3, current_transaction, new_transaction

web3/_utils/batching.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@
7171

7272

7373
class RequestBatcher(Generic[TFunc]):
74-
def __init__(self, web3: Union["AsyncWeb3", "Web3"]) -> None:
74+
def __init__(self, web3: Union["AsyncWeb3[Any]", "Web3"]) -> None:
7575
self.web3 = web3
7676
self._requests_info: List[BatchRequestInformation] = []
7777
self._async_requests_info: List[

0 commit comments

Comments
 (0)