From a57d13f70453cf9a91ea9cca646babcc2571a363 Mon Sep 17 00:00:00 2001 From: Harmouch101 Date: Tue, 22 Feb 2022 09:49:17 +0200 Subject: [PATCH 1/2] :memo: replace all instances of Web3 with w3 Signed-off-by: Harmouch101 --- conftest.py | 22 +- docs/examples.rst | 24 +- ens/main.py | 18 +- ethpm/_utils/chains.py | 4 +- ethpm/contract.py | 6 +- ethpm/uri.py | 6 +- newsfragments/1183.breaking-change.rst | 1 + tests/core/admin-module/test_admin_addPeer.py | 12 +- .../core/admin-module/test_admin_nodeInfo.py | 12 +- tests/core/admin-module/test_admin_peers.py | 6 +- tests/core/contracts/conftest.py | 108 +- tests/core/contracts/test_concise_contract.py | 28 +- .../test_contract_ambiguous_functions.py | 14 +- .../contracts/test_contract_attributes.py | 12 +- .../test_contract_buildTransaction.py | 38 +- .../contracts/test_contract_call_interface.py | 136 +-- .../test_contract_caller_interface.py | 58 +- .../test_contract_class_construction.py | 14 +- .../contracts/test_contract_constructor.py | 80 +- .../test_contract_constructor_encoding.py | 8 +- .../contracts/test_contract_deployment.py | 24 +- .../contracts/test_contract_estimateGas.py | 56 +- .../test_contract_events_buildFilter.py | 24 +- tests/core/contracts/test_contract_init.py | 18 +- .../test_contract_method_abi_decoding.py | 8 +- .../test_contract_method_abi_encoding.py | 12 +- ...st_contract_method_to_argument_matching.py | 32 +- .../test_contract_transact_interface.py | 116 +-- .../contracts/test_contract_util_functions.py | 6 +- .../contracts/test_extracting_event_data.py | 100 +- .../test_extracting_event_data_old.py | 26 +- .../core/contracts/test_implicit_contract.py | 14 +- tests/core/eth-module/conftest.py | 8 +- tests/core/eth-module/test_accounts.py | 4 +- tests/core/eth-module/test_block_api.py | 26 +- .../eth-module/test_default_account_api.py | 50 +- tests/core/eth-module/test_eth_contract.py | 14 +- tests/core/eth-module/test_eth_mining.py | 12 +- tests/core/eth-module/test_eth_properties.py | 16 +- tests/core/eth-module/test_gas_pricing.py | 38 +- tests/core/eth-module/test_iban.py | 20 +- tests/core/eth-module/test_poa.py | 28 +- tests/core/eth-module/test_transactions.py | 66 +- tests/core/filtering/conftest.py | 18 +- .../core/filtering/test_basic_filter_tests.py | 20 +- ...est_contract_createFilter_topic_merging.py | 2 +- .../filtering/test_contract_data_filters.py | 32 +- tests/core/filtering/test_contract_getLogs.py | 16 +- .../test_contract_on_event_filtering.py | 30 +- .../test_contract_past_event_filtering.py | 12 +- .../filtering/test_contract_topic_filters.py | 36 +- .../test_existing_filter_instance.py | 24 +- .../test_filter_against_latest_blocks.py | 14 +- ...est_filter_against_pending_transactions.py | 44 +- .../test_filter_against_transaction_logs.py | 20 +- .../test_filters_against_many_blocks.py | 56 +- tests/core/filtering/test_utils_functions.py | 12 +- .../test_rpc_gas_pricing_strategies.py | 8 +- .../core/manager/test_response_formatters.py | 24 +- .../middleware/test_gas_price_strategy.py | 20 +- .../middleware/test_http_request_retry.py | 14 +- tests/core/mining-module/conftest.py | 10 +- tests/core/pm-module/test_ens_integration.py | 8 +- tests/core/providers/test_http_provider.py | 12 +- tests/core/providers/test_provider.py | 8 +- .../core/testing-module/test_testing_mine.py | 20 +- .../test_testing_snapshot_and_revert.py | 46 +- .../testing-module/test_testing_timeTravel.py | 8 +- tests/core/txpool-module/conftest.py | 10 +- tests/core/utilities/conftest.py | 2 +- tests/core/utilities/test_abi_is_encodable.py | 8 +- tests/core/utilities/test_attach_modules.py | 2 +- .../test_construct_event_data_set.py | 4 +- .../test_construct_event_filter_params.py | 8 +- .../utilities/test_construct_event_topics.py | 4 +- .../utilities/test_event_filter_builder.py | 12 +- tests/core/utilities/test_event_interface.py | 12 +- tests/core/utilities/test_fee_utils.py | 12 +- .../test_prepare_transaction_replacement.py | 42 +- .../test_valid_transaction_params.py | 12 +- tests/core/web3-module/test_api.py | 4 +- tests/core/web3-module/test_attach_modules.py | 66 +- tests/core/web3-module/test_clientVersion.py | 4 +- tests/core/web3-module/test_providers.py | 6 +- tests/ens/conftest.py | 2 +- tests/ens/test_ens.py | 8 +- tests/ens/test_setup_address.py | 4 +- tests/ens/test_setup_name.py | 10 +- tests/integration/common.py | 2 +- tests/integration/conftest.py | 12 +- tests/integration/generate_fixtures/common.py | 26 +- .../generate_fixtures/go_ethereum.py | 86 +- tests/integration/go_ethereum/common.py | 28 +- tests/integration/go_ethereum/conftest.py | 36 +- .../go_ethereum/test_goethereum_http.py | 34 +- .../go_ethereum/test_goethereum_ipc.py | 14 +- .../go_ethereum/test_goethereum_ws.py | 18 +- tests/integration/test_ethereum_tester.py | 264 ++--- web3/_utils/async_transactions.py | 6 +- web3/_utils/contracts.py | 20 +- web3/_utils/ens.py | 2 +- web3/_utils/module_testing/eth_module.py | 972 +++++++++--------- .../go_ethereum_admin_module.py | 68 +- .../go_ethereum_personal_module.py | 92 +- .../go_ethereum_txpool_module.py | 12 +- web3/_utils/module_testing/net_module.py | 20 +- web3/_utils/module_testing/version_module.py | 8 +- web3/_utils/module_testing/web3_module.py | 24 +- web3/_utils/transactions.py | 50 +- web3/contract.py | 208 ++-- web3/eth.py | 12 +- web3/gas_strategies/rpc.py | 4 +- web3/gas_strategies/time_based.py | 8 +- web3/manager.py | 16 +- web3/method.py | 2 +- web3/middleware/__init__.py | 8 +- web3/middleware/attrdict.py | 2 +- web3/middleware/buffered_gas_estimate.py | 8 +- web3/middleware/cache.py | 14 +- web3/middleware/exception_handling.py | 2 +- web3/middleware/exception_retry_request.py | 6 +- web3/middleware/gas_price_strategy.py | 12 +- web3/middleware/geth_poa.py | 4 +- .../simulate_unmined_transaction.py | 2 +- web3/middleware/stalecheck.py | 4 +- web3/middleware/validation.py | 4 +- web3/module.py | 10 +- web3/parity.py | 4 +- web3/pm.py | 18 +- web3/providers/async_base.py | 8 +- web3/providers/base.py | 8 +- web3/providers/eth_tester/middleware.py | 14 +- web3/testing.py | 10 +- web3/tools/benchmark/main.py | 8 +- 134 files changed, 2131 insertions(+), 2130 deletions(-) create mode 100644 newsfragments/1183.breaking-change.rst diff --git a/conftest.py b/conftest.py index 28aaa762c6..17ccc39dd6 100644 --- a/conftest.py +++ b/conftest.py @@ -47,18 +47,18 @@ def is_testrpc_provider(provider): @pytest.fixture() def skip_if_testrpc(): - def _skip_if_testrpc(web3): - if is_testrpc_provider(web3.provider): + def _skip_if_testrpc(w3): + if is_testrpc_provider(w3.provider): pytest.skip() return _skip_if_testrpc @pytest.fixture() def wait_for_miner_start(): - def _wait_for_miner_start(web3, timeout=60): + def _wait_for_miner_start(w3, timeout=60): poll_delay_counter = PollDelayCounter() with Timeout(timeout) as timeout: - while not web3.eth.mining or not web3.eth.hashrate: + while not w3.eth.mining or not w3.eth.hashrate: time.sleep(poll_delay_counter()) timeout.check() return _wait_for_miner_start @@ -66,24 +66,24 @@ def _wait_for_miner_start(web3, timeout=60): @pytest.fixture(scope="module") def wait_for_block(): - def _wait_for_block(web3, block_number=1, timeout=None): + def _wait_for_block(w3, block_number=1, timeout=None): if not timeout: - timeout = (block_number - web3.eth.block_number) * 3 + timeout = (block_number - w3.eth.block_number) * 3 poll_delay_counter = PollDelayCounter() with Timeout(timeout) as timeout: - while web3.eth.block_number < block_number: - web3.manager.request_blocking("evm_mine", []) + while w3.eth.block_number < block_number: + w3.manager.request_blocking("evm_mine", []) timeout.sleep(poll_delay_counter()) return _wait_for_block @pytest.fixture(scope="module") def wait_for_transaction(): - def _wait_for_transaction(web3, txn_hash, timeout=120): + def _wait_for_transaction(w3, txn_hash, timeout=120): poll_delay_counter = PollDelayCounter() with Timeout(timeout) as timeout: while True: - txn_receipt = web3.eth.get_transaction_receipt(txn_hash) + txn_receipt = w3.eth.get_transaction_receipt(txn_hash) if txn_receipt is not None: break time.sleep(poll_delay_counter()) @@ -94,7 +94,7 @@ def _wait_for_transaction(web3, txn_hash, timeout=120): @pytest.fixture() -def web3(): +def w3(): provider = EthereumTesterProvider() return Web3(provider) diff --git a/docs/examples.rst b/docs/examples.rst index 05dd4b7a27..e54ed70d43 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -865,7 +865,7 @@ The script can be run with: ``python ./eventscanner.py `` because it cannot correctly throttle and decrease the `eth_getLogs` block number range. """ - def __init__(self, web3: Web3, contract: Contract, state: EventScannerState, events: List, filters: {}, + def __init__(self, w3: Web3, contract: Contract, state: EventScannerState, events: List, filters: {}, max_chunk_scan_size: int = 10000, max_request_retries: int = 30, request_retry_seconds: float = 3.0): """ :param contract: Contract @@ -878,7 +878,7 @@ The script can be run with: ``python ./eventscanner.py `` self.logger = logger self.contract = contract - self.web3 = web3 + self.w3 = w3 self.state = state self.events = events self.filters = filters @@ -903,7 +903,7 @@ The script can be run with: ``python ./eventscanner.py `` def get_block_timestamp(self, block_num) -> datetime.datetime: """Get Ethereum block timestamp""" try: - block_info = self.web3.eth.getBlock(block_num) + block_info = self.w3.eth.getBlock(block_num) except BlockNotFound: # Block was not mined yet, # minor chain reorganisation? @@ -931,7 +931,7 @@ The script can be run with: ``python ./eventscanner.py `` # Do not scan all the way to the final block, as this # block might not be mined yet - return self.web3.eth.blockNumber - 1 + return self.w3.eth.blockNumber - 1 def get_last_scanned_block(self) -> int: return self.state.get_last_scanned_block() @@ -964,7 +964,7 @@ The script can be run with: ``python ./eventscanner.py `` # Callable that takes care of the underlying web3 call def _fetch_events(_start_block, _end_block): - return _fetch_events_for_all_contracts(self.web3, + return _fetch_events_for_all_contracts(self.w3, event_type, self.filters, from_block=_start_block, @@ -1133,7 +1133,7 @@ The script can be run with: ``python ./eventscanner.py `` def _fetch_events_for_all_contracts( - web3, + w3, event, argument_filters: dict, from_block: int, @@ -1158,7 +1158,7 @@ The script can be run with: ``python ./eventscanner.py `` # it might have Solidity ABI encoding v1 or v2. # We just assume the default that you set on Web3 object here. # More information here https://eth-abi.readthedocs.io/en/latest/index.html - codec: ABICodec = web3.codec + codec: ABICodec = w3.codec # Here we need to poke a bit into Web3 internals, as this # functionality is not exposed by default. @@ -1179,7 +1179,7 @@ The script can be run with: ``python ./eventscanner.py `` # Call JSON-RPC API on your Ethereum node. # get_logs() returns raw AttributedDict entries - logs = web3.eth.get_logs(event_filter_params) + logs = w3.eth.get_logs(event_filter_params) # Convert raw binary data to Python proxy objects as described by ABI all_events = [] @@ -1358,19 +1358,19 @@ The script can be run with: ``python ./eventscanner.py `` # throttle down. provider.middlewares.clear() - web3 = Web3(provider) + w3 = Web3(provider) # Prepare stub ERC-20 contract object abi = json.loads(ABI) - ERC20 = web3.eth.contract(abi=abi) + ERC20 = w3.eth.contract(abi=abi) # Restore/create our persistent state state = JSONifiedState() state.restore() - # chain_id: int, web3: Web3, abi: dict, state: EventScannerState, events: List, filters: {}, max_chunk_scan_size: int=10000 + # chain_id: int, w3: Web3, abi: dict, state: EventScannerState, events: List, filters: {}, max_chunk_scan_size: int=10000 scanner = EventScanner( - web3=web3, + w3=w3, contract=ERC20, state=state, events=[ERC20.events.Transfer], diff --git a/ens/main.py b/ens/main.py index 2c8360682a..928a3106a4 100644 --- a/ens/main.py +++ b/ens/main.py @@ -112,23 +112,23 @@ def __init__( :param hex-string addr: the address of the ENS registry on-chain. If not provided, ENS.py will default to the mainnet ENS registry address. """ - self.web3 = init_web3(provider, middlewares) + self.w3 = init_web3(provider, middlewares) ens_addr = addr if addr else ENS_MAINNET_ADDR - self.ens = self.web3.eth.contract(abi=abis.ENS, address=ens_addr) - self._resolverContract = self.web3.eth.contract(abi=abis.RESOLVER) + self.ens = self.w3.eth.contract(abi=abis.ENS, address=ens_addr) + self._resolverContract = self.w3.eth.contract(abi=abis.RESOLVER) @classmethod - def fromWeb3(cls, web3: 'Web3', addr: ChecksumAddress = None) -> 'ENS': + def fromWeb3(cls, w3: 'Web3', addr: ChecksumAddress = None) -> 'ENS': """ Generate an ENS instance with web3 - :param `web3.Web3` web3: to infer connection information + :param `web3.Web3` w3: to infer connection information :param hex-string addr: the address of the ENS registry on-chain. If not provided, ENS.py will default to the mainnet ENS registry address. """ - provider = web3.manager.provider - middlewares = web3.middleware_onion.middlewares + provider = w3.manager.provider + middlewares = w3.middleware_onion.middlewares return cls(provider, addr=addr, middlewares=middlewares) def address(self, name: str) -> Optional[ChecksumAddress]: @@ -333,7 +333,7 @@ def setup_owner( def _assert_control(self, account: ChecksumAddress, name: str, parent_owned: Optional[str] = None) -> None: - if not address_in(account, self.web3.eth.accounts): + if not address_in(account, self.w3.eth.accounts): raise UnauthorizedError( "in order to modify %r, you must control account %r, which owns %r" % ( name, account, parent_owned or name @@ -410,4 +410,4 @@ def _setup_reverse( def _reverse_registrar(self) -> 'Contract': addr = self.ens.caller.owner(normal_name_to_hash(REVERSE_REGISTRAR_DOMAIN)) - return self.web3.eth.contract(address=addr, abi=abis.REVERSE_REGISTRAR) + return self.w3.eth.contract(address=addr, abi=abis.REVERSE_REGISTRAR) diff --git a/ethpm/_utils/chains.py b/ethpm/_utils/chains.py index cbdaee7a61..3928a6b529 100644 --- a/ethpm/_utils/chains.py +++ b/ethpm/_utils/chains.py @@ -30,8 +30,8 @@ from web3 import Web3 # noqa: F401 -def get_genesis_block_hash(web3: "Web3") -> HexBytes: - return web3.eth.get_block(BlockNumber(0))["hash"] +def get_genesis_block_hash(w3: "Web3") -> HexBytes: + return w3.eth.get_block(BlockNumber(0))["hash"] BLOCK = "block" diff --git a/ethpm/contract.py b/ethpm/contract.py index 92dfa2faaf..d9b226d392 100644 --- a/ethpm/contract.py +++ b/ethpm/contract.py @@ -60,7 +60,7 @@ def __init__(self, address: bytes, **kwargs: Any) -> None: @classmethod def factory( - cls, web3: "Web3", class_name: str = None, **kwargs: Any + cls, w3: "Web3", class_name: str = None, **kwargs: Any ) -> Contract: dep_link_refs = kwargs.get("unlinked_references") bytecode = kwargs.get("bytecode") @@ -69,7 +69,7 @@ def factory( if not is_prelinked_bytecode(to_bytes(hexstr=bytecode), dep_link_refs): needs_bytecode_linking = True kwargs = assoc(kwargs, "needs_bytecode_linking", needs_bytecode_linking) - return super(LinkableContract, cls).factory(web3, class_name, **kwargs) + return super(LinkableContract, cls).factory(w3, class_name, **kwargs) @classmethod def constructor(cls, *args: Any, **kwargs: Any) -> ContractConstructor: @@ -98,7 +98,7 @@ def link_bytecode(cls, attr_dict: Dict[str, str]) -> Type["LinkableContract"]: cls.bytecode_runtime, cls.linked_references, attr_dict ) linked_class = cls.factory( - cls.web3, bytecode_runtime=runtime, bytecode=bytecode + cls.w3, bytecode_runtime=runtime, bytecode=bytecode ) if linked_class.needs_bytecode_linking: raise BytecodeLinkingError( diff --git a/ethpm/uri.py b/ethpm/uri.py index 35c8288399..45de062618 100644 --- a/ethpm/uri.py +++ b/ethpm/uri.py @@ -120,15 +120,15 @@ def create_latest_block_uri(w3: "Web3", from_blocks_ago: int = 3) -> URI: @curry -def check_if_chain_matches_chain_uri(web3: "Web3", blockchain_uri: URI) -> bool: +def check_if_chain_matches_chain_uri(w3: "Web3", blockchain_uri: URI) -> bool: chain_id, resource_type, resource_hash = parse_BIP122_uri(blockchain_uri) - genesis_block = web3.eth.get_block("earliest") + genesis_block = w3.eth.get_block("earliest") if encode_hex(genesis_block["hash"]) != chain_id: return False if resource_type == BLOCK: - resource = web3.eth.get_block(resource_hash) + resource = w3.eth.get_block(resource_hash) else: raise ValueError(f"Unsupported resource type: {resource_type}") diff --git a/newsfragments/1183.breaking-change.rst b/newsfragments/1183.breaking-change.rst new file mode 100644 index 0000000000..2486e9fd65 --- /dev/null +++ b/newsfragments/1183.breaking-change.rst @@ -0,0 +1 @@ +Audit ``.rst`` and ``.py`` files and convert all Web3 instance variable names to ``w3`` to avoid confusion with the ``web3`` module. \ No newline at end of file diff --git a/tests/core/admin-module/test_admin_addPeer.py b/tests/core/admin-module/test_admin_addPeer.py index 92b7be1505..896821ef95 100644 --- a/tests/core/admin-module/test_admin_addPeer.py +++ b/tests/core/admin-module/test_admin_addPeer.py @@ -1,20 +1,20 @@ import pytest -def test_admin_addPeer(web3, skip_if_testrpc): - skip_if_testrpc(web3) +def test_admin_addPeer(w3, skip_if_testrpc): + skip_if_testrpc(w3) with pytest.warns(DeprecationWarning): - result = web3.geth.admin.addPeer( + result = w3.geth.admin.addPeer( 'enode://44826a5d6a55f88a18298bca4773fca5749cdc3a5c9f308aa7d810e9b31123f3e7c5fba0b1d70aac5308426f47df2a128a6747040a3815cc7dd7167d03be320d@127.0.0.1:30304', # noqa: E501 ) assert result is True -def test_admin_add_peer(web3, skip_if_testrpc): - skip_if_testrpc(web3) +def test_admin_add_peer(w3, skip_if_testrpc): + skip_if_testrpc(w3) - result = web3.geth.admin.add_peer( + result = w3.geth.admin.add_peer( 'enode://44826a5d6a55f88a18298bca4773fca5749cdc3a5c9f308aa7d810e9b31123f3e7c5fba0b1d70aac5308426f47df2a128a6747040a3815cc7dd7167d03be320d@127.0.0.1:30304', # noqa: E501 ) assert result is True diff --git a/tests/core/admin-module/test_admin_nodeInfo.py b/tests/core/admin-module/test_admin_nodeInfo.py index 52977a76cb..7c209418aa 100644 --- a/tests/core/admin-module/test_admin_nodeInfo.py +++ b/tests/core/admin-module/test_admin_nodeInfo.py @@ -1,20 +1,20 @@ import pytest -def test_admin_nodeInfo(web3, skip_if_testrpc): - skip_if_testrpc(web3) +def test_admin_nodeInfo(w3, skip_if_testrpc): + skip_if_testrpc(w3) with pytest.warns(DeprecationWarning): - node_info = web3.geth.admin.nodeInfo + node_info = w3.geth.admin.nodeInfo assert 'enode' in node_info assert 'id' in node_info -def test_admin_node_info(web3, skip_if_testrpc): - skip_if_testrpc(web3) +def test_admin_node_info(w3, skip_if_testrpc): + skip_if_testrpc(w3) - node_info = web3.geth.admin.node_info + node_info = w3.geth.admin.node_info assert 'enode' in node_info assert 'id' in node_info diff --git a/tests/core/admin-module/test_admin_peers.py b/tests/core/admin-module/test_admin_peers.py index 38766a04e9..fb207327b6 100644 --- a/tests/core/admin-module/test_admin_peers.py +++ b/tests/core/admin-module/test_admin_peers.py @@ -1,4 +1,4 @@ -def test_admin_peers(web3, skip_if_testrpc): - skip_if_testrpc(web3) +def test_admin_peers(w3, skip_if_testrpc): + skip_if_testrpc(w3) - assert web3.geth.admin.peers == [] + assert w3.geth.admin.peers == [] diff --git a/tests/core/contracts/conftest.py b/tests/core/contracts/conftest.py index a36d08ff78..2941572be8 100644 --- a/tests/core/contracts/conftest.py +++ b/tests/core/contracts/conftest.py @@ -91,8 +91,8 @@ def NESTED_TUPLE_CONTRACT(NESTED_TUPLE_CODE, NESTED_TUPLE_RUNTIME, NESTED_TUPLE_ @pytest.fixture() -def NestedTupleContract(web3, NESTED_TUPLE_CONTRACT): - return web3.eth.contract(**NESTED_TUPLE_CONTRACT) +def NestedTupleContract(w3, NESTED_TUPLE_CONTRACT): + return w3.eth.contract(**NESTED_TUPLE_CONTRACT) CONTRACT_TUPLE_SOURCE = """ @@ -138,8 +138,8 @@ def TUPLE_CONTRACT(TUPLE_CODE, TUPLE_RUNTIME, TUPLE_ABI): @pytest.fixture() -def TupleContract(web3, TUPLE_CONTRACT): - return web3.eth.contract(**TUPLE_CONTRACT) +def TupleContract(w3, TUPLE_CONTRACT): + return w3.eth.contract(**TUPLE_CONTRACT) CONTRACT_CODE = "0x606060405261022e806100126000396000f360606040523615610074576000357c01000000000000000000000000000000000000000000000000000000009004806316216f391461007657806361bc221a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d578063dcf537b11461014057610074565b005b610083600480505061016c565b6040518082815260200191505060405180910390f35b6100a6600480505061017f565b6040518082815260200191505060405180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea565b6040518082815260200191505060405180910390f35b61012a6004805050610201565b6040518082815260200191505060405180910390f35b6101566004808035906020019091905050610217565b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90565b60006000505481565b6000816000600082828250540192505081905550600060005054905080507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b60006007820290508050809050610229565b91905056" # noqa: E501 @@ -167,8 +167,8 @@ def MATH_ABI(): @pytest.fixture() -def MathContract(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME): - return web3.eth.contract( +def MathContract(w3, MATH_ABI, MATH_CODE, MATH_RUNTIME): + return w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, @@ -196,11 +196,11 @@ def SIMPLE_CONSTRUCTOR_ABI(): @pytest.fixture() -def SimpleConstructorContract(web3, +def SimpleConstructorContract(w3, SIMPLE_CONSTRUCTOR_CODE, SIMPLE_CONSTRUCTOR_RUNTIME, SIMPLE_CONSTRUCTOR_ABI): - return web3.eth.contract( + return w3.eth.contract( abi=SIMPLE_CONSTRUCTOR_ABI, bytecode=SIMPLE_CONSTRUCTOR_CODE, bytecode_runtime=SIMPLE_CONSTRUCTOR_RUNTIME, @@ -228,11 +228,11 @@ def WITH_CONSTRUCTOR_ARGUMENTS_ABI(): @pytest.fixture() -def WithConstructorArgumentsContract(web3, +def WithConstructorArgumentsContract(w3, WITH_CONSTRUCTOR_ARGUMENTS_CODE, WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME, WITH_CONSTRUCTOR_ARGUMENTS_ABI): - return web3.eth.contract( + return w3.eth.contract( abi=WITH_CONSTRUCTOR_ARGUMENTS_ABI, bytecode=WITH_CONSTRUCTOR_ARGUMENTS_CODE, bytecode_runtime=WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME, @@ -272,11 +272,11 @@ def WITH_CONSTRUCTOR_ADDRESS_ABI(): @pytest.fixture() -def WithConstructorAddressArgumentsContract(web3, +def WithConstructorAddressArgumentsContract(w3, WITH_CONSTRUCTOR_ADDRESS_CODE, WITH_CONSTRUCTOR_ADDRESS_RUNTIME, WITH_CONSTRUCTOR_ADDRESS_ABI): - return web3.eth.contract( + return w3.eth.contract( abi=WITH_CONSTRUCTOR_ADDRESS_ABI, bytecode=WITH_CONSTRUCTOR_ADDRESS_CODE, bytecode_runtime=WITH_CONSTRUCTOR_ADDRESS_RUNTIME, @@ -284,8 +284,8 @@ def WithConstructorAddressArgumentsContract(web3, @pytest.fixture() -def AddressReflectorContract(web3): - return web3.eth.contract( +def AddressReflectorContract(w3): + return w3.eth.contract( abi=json.loads('[{"constant":true,"inputs":[{"name":"arg","type":"address"}],"name":"reflect","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"name":"arg","type":"address[]"}],"name":"reflect","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"pure","type":"function"}]'), # noqa: 501 bytecode="6060604052341561000f57600080fd5b6101ca8061001e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630b816c1614610048578063c04d11fc146100c157600080fd5b341561005357600080fd5b61007f600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610170565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100cc57600080fd5b61011960048080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509190505061017a565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561015c578082015181840152602081019050610141565b505050509050019250505060405180910390f35b6000819050919050565b61018261018a565b819050919050565b6020604051908101604052806000815250905600a165627a7a723058206b15d98a803b91327d94f943e9712291539701b2f7370e10f5873633941484930029", # noqa: 501 bytecode_runtime="60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630b816c1614610048578063c04d11fc146100c157600080fd5b341561005357600080fd5b61007f600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610170565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100cc57600080fd5b61011960048080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509190505061017a565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561015c578082015181840152602081019050610141565b505050509050019250505060405180910390f35b6000819050919050565b61018261018a565b819050919050565b6020604051908101604052806000815250905600a165627a7a723058206b15d98a803b91327d94f943e9712291539701b2f7370e10f5873633941484930029", # noqa: 501 @@ -324,8 +324,8 @@ def STRING_CONTRACT(STRING_CODE, STRING_RUNTIME, STRING_ABI): @pytest.fixture() -def StringContract(web3, STRING_CONTRACT): - return web3.eth.contract(**STRING_CONTRACT) +def StringContract(w3, STRING_CONTRACT): + return w3.eth.contract(**STRING_CONTRACT) CONTRACT_BYTES_CODE = "60606040526040805190810160405280600281526020017f01230000000000000000000000000000000000000000000000000000000000008152506000908051906020019061004f929190610096565b50341561005b57600080fd5b604051610723380380610723833981016040528080518201919050505b806001908051906020019061008e929190610116565b505b506101bb565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100d757805160ff1916838001178555610105565b82800160010185558215610105579182015b828111156101045782518255916020019190600101906100e9565b5b5090506101129190610196565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061015757805160ff1916838001178555610185565b82800160010185558215610185579182015b82811115610184578251825591602001919060010190610169565b5b5090506101929190610196565b5090565b6101b891905b808211156101b457600081600090555060010161019c565b5090565b90565b610559806101ca6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063209652551461005f57806330de3cee146100ee5780633fa4f2451461017d578063439970aa1461020c575b600080fd5b341561006a57600080fd5b610072610269565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b35780820151818401525b602081019050610097565b50505050905090810190601f1680156100e05780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156100f957600080fd5b610101610312565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101425780820151818401525b602081019050610126565b50505050905090810190601f16801561016f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561018857600080fd5b6101906103bb565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101d15780820151818401525b6020810190506101b5565b50505050905090810190601f1680156101fe5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561021757600080fd5b610267600480803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610459565b005b610271610474565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103075780601f106102dc57610100808354040283529160200191610307565b820191906000526020600020905b8154815290600101906020018083116102ea57829003601f168201915b505050505090505b90565b61031a610474565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103b05780601f10610385576101008083540402835291602001916103b0565b820191906000526020600020905b81548152906001019060200180831161039357829003601f168201915b505050505090505b90565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104515780601f1061042657610100808354040283529160200191610451565b820191906000526020600020905b81548152906001019060200180831161043457829003601f168201915b505050505081565b806001908051906020019061046f929190610488565b505b50565b602060405190810160405280600081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106104c957805160ff19168380011785556104f7565b828001600101855582156104f7579182015b828111156104f65782518255916020019190600101906104db565b5b5090506105049190610508565b5090565b61052a91905b8082111561052657600081600090555060010161050e565b5090565b905600a165627a7a723058203ff916ee91add6247b20793745d1c6a8d8dcaa49d8c84fbbabb5c966fd9b6fc90029" # noqa: E501 @@ -360,8 +360,8 @@ def BYTES_CONTRACT(BYTES_CODE, BYTES_RUNTIME, BYTES_ABI): @pytest.fixture() -def BytesContract(web3, BYTES_CONTRACT): - return web3.eth.contract(**BYTES_CONTRACT) +def BytesContract(w3, BYTES_CONTRACT): + return w3.eth.contract(**BYTES_CONTRACT) CONTRACT_BYTES32_CODE = "60606040527f0123012301230123012301230123012301230123012301230123012301230123600090600019169055341561003957600080fd5b6040516020806101e2833981016040528080519060200190919050505b80600181600019169055505b505b61016f806100736000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063209652551461005f57806330de3cee146100905780633fa4f245146100c157806358825b10146100f2575b600080fd5b341561006a57600080fd5b610072610119565b60405180826000191660001916815260200191505060405180910390f35b341561009b57600080fd5b6100a3610124565b60405180826000191660001916815260200191505060405180910390f35b34156100cc57600080fd5b6100d461012e565b60405180826000191660001916815260200191505060405180910390f35b34156100fd57600080fd5b610117600480803560001916906020019091905050610134565b005b600060015490505b90565b6000805490505b90565b60015481565b80600181600019169055505b505600a165627a7a7230582043b15c20378b1603d330561258ccf291d08923a4c25fa8af0d590a010a6322180029" # noqa: E501 @@ -396,8 +396,8 @@ def BYTES32_CONTRACT(BYTES32_CODE, BYTES32_RUNTIME, BYTES32_ABI): @pytest.fixture() -def Bytes32Contract(web3, BYTES32_CONTRACT): - return web3.eth.contract(**BYTES32_CONTRACT) +def Bytes32Contract(w3, BYTES32_CONTRACT): + return w3.eth.contract(**BYTES32_CONTRACT) @pytest.fixture() @@ -491,29 +491,29 @@ def EVENT_CONTRACT( @pytest.fixture() -def EventContract(web3_empty, EVENT_CONTRACT): - web3 = web3_empty - return web3.eth.contract(**EVENT_CONTRACT) +def EventContract(w3_empty, EVENT_CONTRACT): + w3 = w3_empty + return w3.eth.contract(**EVENT_CONTRACT) @pytest.fixture() def event_contract( - web3_empty, + w3_empty, EventContract, wait_for_transaction, wait_for_block, address_conversion_func): - web3 = web3_empty + w3 = w3_empty - wait_for_block(web3) + wait_for_block(w3) deploy_txn_hash = EventContract.constructor().transact({ - 'from': web3.eth.coinbase, 'gas': 1000000 + 'from': w3.eth.coinbase, 'gas': 1000000 }) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == EventContract.bytecode_runtime event_contract = EventContract(address=contract_address) assert event_contract.address == contract_address @@ -548,30 +548,30 @@ def INDEXED_EVENT_CONTRACT( @pytest.fixture() -def IndexedEventContract(web3_empty, INDEXED_EVENT_CONTRACT): - web3 = web3_empty - return web3.eth.contract(**INDEXED_EVENT_CONTRACT) +def IndexedEventContract(w3_empty, INDEXED_EVENT_CONTRACT): + w3 = w3_empty + return w3.eth.contract(**INDEXED_EVENT_CONTRACT) @pytest.fixture() def indexed_event( - web3_empty, + w3_empty, IndexedEventContract, wait_for_transaction, wait_for_block, address_conversion_func): - web3 = web3_empty + w3 = w3_empty - wait_for_block(web3) + wait_for_block(w3) deploy_txn_hash = IndexedEventContract.constructor().transact({ - 'from': web3.eth.coinbase, + 'from': w3.eth.coinbase, 'gas': 1000000 }) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == IndexedEventContract.bytecode_runtime indexed_event_contract = IndexedEventContract(address=contract_address) assert indexed_event_contract.address == contract_address @@ -654,8 +654,8 @@ def ARRAYS_CONTRACT(ARRAYS_CODE, @pytest.fixture() -def ArraysContract(web3, ARRAYS_CONTRACT): - return web3.eth.contract(**ARRAYS_CONTRACT) +def ArraysContract(w3, ARRAYS_CONTRACT): + return w3.eth.contract(**ARRAYS_CONTRACT) @pytest.fixture() @@ -707,8 +707,8 @@ def PAYABLE_TESTER_CONTRACT(PAYABLE_TESTER_CODE, @pytest.fixture() -def PayableTesterContract(web3, PAYABLE_TESTER_CONTRACT): - return web3.eth.contract(**PAYABLE_TESTER_CONTRACT) +def PayableTesterContract(w3, PAYABLE_TESTER_CONTRACT): + return w3.eth.contract(**PAYABLE_TESTER_CONTRACT) # no matter the function selector, this will return back the 32 bytes of data supplied @@ -752,8 +752,8 @@ def PayableTesterContract(web3, PAYABLE_TESTER_CONTRACT): @pytest.fixture -def FixedReflectionContract(web3): - return web3.eth.contract(abi=CONTRACT_FIXED_ABI, bytecode=CONTRACT_REFLECTION_CODE) +def FixedReflectionContract(w3): + return w3.eth.contract(abi=CONTRACT_FIXED_ABI, bytecode=CONTRACT_REFLECTION_CODE) @pytest.fixture() @@ -783,8 +783,8 @@ def FALLBACK_FUNCTION_CONTRACT(FALLBACK_FUNCTION_CODE, @pytest.fixture() -def FallbackFunctionContract(web3, FALLBACK_FUNCTION_CONTRACT): - return web3.eth.contract(**FALLBACK_FUNCTION_CONTRACT) +def FallbackFunctionContract(w3, FALLBACK_FUNCTION_CONTRACT): + return w3.eth.contract(**FALLBACK_FUNCTION_CONTRACT) @pytest.fixture() @@ -814,8 +814,8 @@ def RECEIVE_FUNCTION_CONTRACT(RECEIVE_FUNCTION_CODE, @pytest.fixture() -def NoReceiveFunctionContract(web3, NO_RECEIVE_FUNCTION_CONTRACT): - return web3.eth.contract(**NO_RECEIVE_FUNCTION_CONTRACT) +def NoReceiveFunctionContract(w3, NO_RECEIVE_FUNCTION_CONTRACT): + return w3.eth.contract(**NO_RECEIVE_FUNCTION_CONTRACT) @pytest.fixture() @@ -845,8 +845,8 @@ def NO_RECEIVE_FUNCTION_CONTRACT(NO_RECEIVE_FUNCTION_CODE, @pytest.fixture() -def ReceiveFunctionContract(web3, RECEIVE_FUNCTION_CONTRACT): - return web3.eth.contract(**RECEIVE_FUNCTION_CONTRACT) +def ReceiveFunctionContract(w3, RECEIVE_FUNCTION_CONTRACT): + return w3.eth.contract(**RECEIVE_FUNCTION_CONTRACT) CONTRACT_CALLER_TESTER_SOURCE = """ @@ -908,8 +908,8 @@ def CALLER_TESTER_CONTRACT(CALLER_TESTER_CODE, @pytest.fixture() -def CallerTesterContract(web3, CALLER_TESTER_CONTRACT): - return web3.eth.contract(**CALLER_TESTER_CONTRACT) +def CallerTesterContract(w3, CALLER_TESTER_CONTRACT): + return w3.eth.contract(**CALLER_TESTER_CONTRACT) @pytest.fixture() @@ -939,8 +939,8 @@ def REVERT_FUNCTION_CONTRACT(REVERT_CONTRACT_CODE, @pytest.fixture() -def RevertContract(web3, REVERT_FUNCTION_CONTRACT): - return web3.eth.contract(**REVERT_FUNCTION_CONTRACT) +def RevertContract(w3, REVERT_FUNCTION_CONTRACT): + return w3.eth.contract(**REVERT_FUNCTION_CONTRACT) class LogFunctions: diff --git a/tests/core/contracts/test_concise_contract.py b/tests/core/contracts/test_concise_contract.py index 82cb5a3693..c54e4932f1 100644 --- a/tests/core/contracts/test_concise_contract.py +++ b/tests/core/contracts/test_concise_contract.py @@ -14,13 +14,13 @@ ) -def deploy(web3, Contract, args=None): +def deploy(w3, Contract, args=None): args = args or [] deploy_txn = Contract.constructor(*args).transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None contract = Contract(address=deploy_receipt['contractAddress']) - assert len(web3.eth.get_code(contract.address)) > 0 + assert len(w3.eth.get_code(contract.address)) > 0 return contract @@ -31,11 +31,11 @@ def EMPTY_ADDR(address_conversion_func): @pytest.fixture() -def zero_address_contract(web3, WithConstructorAddressArgumentsContract, EMPTY_ADDR): +def zero_address_contract(w3, WithConstructorAddressArgumentsContract, EMPTY_ADDR): deploy_txn = WithConstructorAddressArgumentsContract.constructor( EMPTY_ADDR, ).transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None _address_contract = WithConstructorAddressArgumentsContract( address=deploy_receipt['contractAddress'], @@ -81,26 +81,26 @@ def test_concisecontract_returns_none_for_0addr(zero_address_contract): assert result is None -def test_class_construction_sets_class_vars(web3, +def test_class_construction_sets_class_vars(w3, MATH_ABI, MATH_CODE, MATH_RUNTIME, some_address, ): - MathContract = web3.eth.contract( + MathContract = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) classic = MathContract(some_address) - assert classic.web3 == web3 + assert classic.w3 == w3 assert classic.bytecode == decode_hex(MATH_CODE) assert classic.bytecode_runtime == decode_hex(MATH_RUNTIME) -def test_conciscecontract_keeps_custom_normalizers_on_base(web3, MATH_ABI): - base_contract = web3.eth.contract(abi=MATH_ABI) +def test_conciscecontract_keeps_custom_normalizers_on_base(w3, MATH_ABI): + base_contract = w3.eth.contract(abi=MATH_ABI) # give different normalizers to this base instance base_contract._return_data_normalizers = base_contract._return_data_normalizers + tuple([None]) @@ -116,10 +116,10 @@ def test_conciscecontract_keeps_custom_normalizers_on_base(web3, MATH_ABI): def test_conciscecontract_function_collision( - web3, + w3, StringContract): - contract = deploy(web3, StringContract, args=["blarg"]) + contract = deploy(w3, StringContract, args=["blarg"]) def getValue(): assert 'getValue' in [ @@ -138,7 +138,7 @@ def getValue(): concise_contract.getValue() -def test_concisecontract_deprecation_warning(web3, StringContract): - contract = deploy(web3, StringContract, args=["blarg"]) +def test_concisecontract_deprecation_warning(w3, StringContract): + contract = deploy(w3, StringContract, args=["blarg"]) with pytest.warns(DeprecationWarning): ConciseContract(contract) diff --git a/tests/core/contracts/test_contract_ambiguous_functions.py b/tests/core/contracts/test_contract_ambiguous_functions.py index dfbff370e5..69e15e4ff6 100644 --- a/tests/core/contracts/test_contract_ambiguous_functions.py +++ b/tests/core/contracts/test_contract_ambiguous_functions.py @@ -40,14 +40,14 @@ @pytest.fixture() -def string_contract(web3, StringContract, address_conversion_func): +def string_contract(w3, StringContract, address_conversion_func): deploy_txn = StringContract.constructor("Caqalai").transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None contract_address = address_conversion_func(deploy_receipt['contractAddress']) contract = StringContract(address=contract_address) assert contract.address == contract_address - assert len(web3.eth.get_code(contract.address)) > 0 + assert len(w3.eth.get_code(contract.address)) > 0 return contract @@ -123,8 +123,8 @@ def string_contract(web3, StringContract, address_conversion_func): ), ), ) -def test_find_or_get_functions_by_type(web3, method, args, repr_func, expected): - contract = web3.eth.contract(abi=AMBIGUOUS_CONTRACT_ABI) +def test_find_or_get_functions_by_type(w3, method, args, repr_func, expected): + contract = w3.eth.contract(abi=AMBIGUOUS_CONTRACT_ABI) function = getattr(contract, method)(*args) assert repr_func(function) == expected @@ -170,8 +170,8 @@ def test_find_or_get_functions_by_type(web3, method, args, repr_func, expected): ), ) ) -def test_functions_error_messages(web3, method, args, expected_message, expected_error): - contract = web3.eth.contract(abi=AMBIGUOUS_CONTRACT_ABI) +def test_functions_error_messages(w3, method, args, expected_message, expected_error): + contract = w3.eth.contract(abi=AMBIGUOUS_CONTRACT_ABI) with pytest.raises(expected_error, match=expected_message): getattr(contract, method)(*args) diff --git a/tests/core/contracts/test_contract_attributes.py b/tests/core/contracts/test_contract_attributes.py index db360357fe..25fffa4a6c 100644 --- a/tests/core/contracts/test_contract_attributes.py +++ b/tests/core/contracts/test_contract_attributes.py @@ -15,8 +15,8 @@ def abi(): 'attribute', ('functions', 'events', 'caller') ) -def test_getattr(web3, abi, attribute): - contract = web3.eth.contract(abi=abi) +def test_getattr(w3, abi, attribute): + contract = w3.eth.contract(abi=abi) contract_attribute = getattr(contract, attribute) assert getattr(contract_attribute, "Increased") @@ -28,8 +28,8 @@ def test_getattr(web3, abi, attribute): ('caller', ABIFunctionNotFound), ) ) -def test_getattr_raises_error(web3, abi, attribute, error): - contract = web3.eth.contract(abi=abi) +def test_getattr_raises_error(w3, abi, attribute, error): + contract = w3.eth.contract(abi=abi) contract_attribute = getattr(contract, attribute) with pytest.raises(error): @@ -40,8 +40,8 @@ def test_getattr_raises_error(web3, abi, attribute, error): 'attribute', ('functions', 'events', 'caller') ) -def test_hasattr(web3, abi, attribute): - contract = web3.eth.contract(abi=abi) +def test_hasattr(w3, abi, attribute): + contract = w3.eth.contract(abi=abi) contract_attribute = getattr(contract, attribute) assert hasattr(contract_attribute, "Increased") is True diff --git a/tests/core/contracts/test_contract_buildTransaction.py b/tests/core/contracts/test_contract_buildTransaction.py index 4713061e99..13b6727ed0 100644 --- a/tests/core/contracts/test_contract_buildTransaction.py +++ b/tests/core/contracts/test_contract_buildTransaction.py @@ -10,9 +10,9 @@ @pytest.fixture() -def math_contract(web3, MathContract, address_conversion_func): +def math_contract(w3, MathContract, address_conversion_func): deploy_txn = MathContract.constructor().transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None math_contract_address = address_conversion_func(deploy_receipt['contractAddress']) _math_contract = MathContract(address=math_contract_address) @@ -21,9 +21,9 @@ def math_contract(web3, MathContract, address_conversion_func): @pytest.fixture() -def fallback_function_contract(web3, FallbackFunctionContract, address_conversion_func): +def fallback_function_contract(w3, FallbackFunctionContract, address_conversion_func): deploy_txn = FallbackFunctionContract.constructor().transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None fallback_contract_address = address_conversion_func(deploy_receipt['contractAddress']) _fallback_contract = FallbackFunctionContract(address=fallback_contract_address) @@ -32,9 +32,9 @@ def fallback_function_contract(web3, FallbackFunctionContract, address_conversio @pytest.fixture() -def payable_tester_contract(web3, PayableTesterContract, address_conversion_func): +def payable_tester_contract(w3, PayableTesterContract, address_conversion_func): deploy_txn = PayableTesterContract.constructor().transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None payable_tester_address = address_conversion_func(deploy_receipt['contractAddress']) _payable_tester = PayableTesterContract(address=payable_tester_address) @@ -43,7 +43,7 @@ def payable_tester_contract(web3, PayableTesterContract, address_conversion_func def test_build_transaction_not_paying_to_nonpayable_function( - web3, + w3, payable_tester_contract, buildTransaction): txn = buildTransaction(contract=payable_tester_contract, @@ -59,7 +59,7 @@ def test_build_transaction_not_paying_to_nonpayable_function( def test_build_transaction_paying_to_nonpayable_function( - web3, + w3, payable_tester_contract, buildTransaction): with pytest.raises(ValidationError): @@ -68,7 +68,7 @@ def test_build_transaction_paying_to_nonpayable_function( tx_params={'value': 1}) -def test_build_transaction_with_contract_no_arguments(web3, math_contract, buildTransaction): +def test_build_transaction_with_contract_no_arguments(w3, math_contract, buildTransaction): txn = buildTransaction(contract=math_contract, contract_function='increment') assert dissoc(txn, 'gas') == { 'to': math_contract.address, @@ -80,7 +80,7 @@ def test_build_transaction_with_contract_no_arguments(web3, math_contract, build } -def test_build_transaction_with_contract_fallback_function(web3, fallback_function_contract): +def test_build_transaction_with_contract_fallback_function(w3, fallback_function_contract): txn = fallback_function_contract.fallback.buildTransaction() assert dissoc(txn, 'gas') == { 'to': fallback_function_contract.address, @@ -93,7 +93,7 @@ def test_build_transaction_with_contract_fallback_function(web3, fallback_functi def test_build_transaction_with_contract_class_method( - web3, + w3, MathContract, math_contract, buildTransaction): @@ -113,7 +113,7 @@ def test_build_transaction_with_contract_class_method( def test_build_transaction_with_contract_default_account_is_set( - web3, + w3, math_contract, buildTransaction): txn = buildTransaction(contract=math_contract, contract_function='increment') @@ -127,10 +127,10 @@ def test_build_transaction_with_contract_default_account_is_set( } -def test_build_transaction_with_gas_price_strategy_set(web3, math_contract, buildTransaction): - def my_gas_price_strategy(web3, transaction_params): +def test_build_transaction_with_gas_price_strategy_set(w3, math_contract, buildTransaction): + def my_gas_price_strategy(w3, transaction_params): return 5 - web3.eth.set_gas_price_strategy(my_gas_price_strategy) + w3.eth.set_gas_price_strategy(my_gas_price_strategy) txn = buildTransaction(contract=math_contract, contract_function='increment') assert dissoc(txn, 'gas') == { 'to': math_contract.address, @@ -141,7 +141,7 @@ def my_gas_price_strategy(web3, transaction_params): } -def test_build_transaction_with_contract_data_supplied_errors(web3, +def test_build_transaction_with_contract_data_supplied_errors(w3, math_contract, buildTransaction): with pytest.raises(ValueError): @@ -150,7 +150,7 @@ def test_build_transaction_with_contract_data_supplied_errors(web3, tx_params={'data': '0x000'}) -def test_build_transaction_with_contract_to_address_supplied_errors(web3, +def test_build_transaction_with_contract_to_address_supplied_errors(w3, math_contract, buildTransaction): with pytest.raises(ValueError): @@ -213,7 +213,7 @@ def test_build_transaction_with_contract_to_address_supplied_errors(web3, 'With Value', ] ) -def test_build_transaction_with_contract_with_arguments(web3, skip_if_testrpc, math_contract, +def test_build_transaction_with_contract_with_arguments(w3, skip_if_testrpc, math_contract, transaction_args, method_args, method_kwargs, @@ -221,7 +221,7 @@ def test_build_transaction_with_contract_with_arguments(web3, skip_if_testrpc, m skip_testrpc, buildTransaction): if skip_testrpc: - skip_if_testrpc(web3) + skip_if_testrpc(w3) txn = buildTransaction(contract=math_contract, contract_function='increment', diff --git a/tests/core/contracts/test_contract_call_interface.py b/tests/core/contracts/test_contract_call_interface.py index 1c6b0d91d2..218e558894 100644 --- a/tests/core/contracts/test_contract_call_interface.py +++ b/tests/core/contracts/test_contract_call_interface.py @@ -37,42 +37,42 @@ ) -def deploy(web3, Contract, apply_func=identity, args=None): +def deploy(w3, Contract, apply_func=identity, args=None): args = args or [] deploy_txn = Contract.constructor(*args).transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None address = apply_func(deploy_receipt['contractAddress']) contract = Contract(address=address) assert contract.address == address - assert len(web3.eth.get_code(contract.address)) > 0 + assert len(w3.eth.get_code(contract.address)) > 0 return contract @pytest.fixture() -def address_reflector_contract(web3, AddressReflectorContract, address_conversion_func): - return deploy(web3, AddressReflectorContract, address_conversion_func) +def address_reflector_contract(w3, AddressReflectorContract, address_conversion_func): + return deploy(w3, AddressReflectorContract, address_conversion_func) @pytest.fixture() -def math_contract(web3, MathContract, address_conversion_func): - return deploy(web3, MathContract, address_conversion_func) +def math_contract(w3, MathContract, address_conversion_func): + return deploy(w3, MathContract, address_conversion_func) @pytest.fixture() -def string_contract(web3, StringContract, address_conversion_func): - return deploy(web3, StringContract, address_conversion_func, args=["Caqalai"]) +def string_contract(w3, StringContract, address_conversion_func): + return deploy(w3, StringContract, address_conversion_func, args=["Caqalai"]) @pytest.fixture() -def arrays_contract(web3, ArraysContract, address_conversion_func): +def arrays_contract(w3, ArraysContract, address_conversion_func): # bytes_32 = [keccak('0'), keccak('1')] bytes32_array = [ b'\x04HR\xb2\xa6p\xad\xe5@~x\xfb(c\xc5\x1d\xe9\xfc\xb9eB\xa0q\x86\xfe:\xed\xa6\xbb\x8a\x11m', # noqa: E501 b'\xc8\x9e\xfd\xaaT\xc0\xf2\x0cz\xdfa(\x82\xdf\tP\xf5\xa9Qc~\x03\x07\xcd\xcbLg/)\x8b\x8b\xc6', # noqa: E501 ] byte_arr = [b'\xff', b'\xff', b'\xff', b'\xff'] - return deploy(web3, ArraysContract, address_conversion_func, args=[bytes32_array, byte_arr]) + return deploy(w3, ArraysContract, address_conversion_func, args=[bytes32_array, byte_arr]) @pytest.fixture() @@ -92,9 +92,9 @@ def strict_arrays_contract(w3_strict_abi, StrictArraysContract, address_conversi @pytest.fixture() -def address_contract(web3, WithConstructorAddressArgumentsContract, address_conversion_func): +def address_contract(w3, WithConstructorAddressArgumentsContract, address_conversion_func): return deploy( - web3, + w3, WithConstructorAddressArgumentsContract, address_conversion_func, args=["0xd3CdA913deB6f67967B99D67aCDFa1712C293601"] @@ -102,30 +102,30 @@ def address_contract(web3, WithConstructorAddressArgumentsContract, address_conv @pytest.fixture(params=[b'\x04\x06', '0x0406', '0406']) -def bytes_contract(web3, BytesContract, request, address_conversion_func): +def bytes_contract(w3, BytesContract, request, address_conversion_func): if is_text(request.param) and request.param[:2] != '0x': with pytest.warns( DeprecationWarning, match='in v6 it will be invalid to pass a hex string without the "0x" prefix' ): - return deploy(web3, BytesContract, address_conversion_func, args=[request.param]) + return deploy(w3, BytesContract, address_conversion_func, args=[request.param]) else: - return deploy(web3, BytesContract, address_conversion_func, args=[request.param]) + return deploy(w3, BytesContract, address_conversion_func, args=[request.param]) @pytest.fixture() -def fixed_reflection_contract(web3, FixedReflectionContract, address_conversion_func): - return deploy(web3, FixedReflectionContract, address_conversion_func) +def fixed_reflection_contract(w3, FixedReflectionContract, address_conversion_func): + return deploy(w3, FixedReflectionContract, address_conversion_func) @pytest.fixture() -def payable_tester_contract(web3, PayableTesterContract, address_conversion_func): - return deploy(web3, PayableTesterContract, address_conversion_func) +def payable_tester_contract(w3, PayableTesterContract, address_conversion_func): + return deploy(w3, PayableTesterContract, address_conversion_func) @pytest.fixture() -def revert_contract(web3, RevertContract, address_conversion_func): - return deploy(web3, RevertContract, address_conversion_func) +def revert_contract(w3, RevertContract, address_conversion_func): + return deploy(w3, RevertContract, address_conversion_func) @pytest.fixture() @@ -141,25 +141,25 @@ def call_transaction(): '0406040604060406040604060406040604060406040604060406040604060406', HexBytes('0406040604060406040604060406040604060406040604060406040604060406'), ]) -def bytes32_contract(web3, Bytes32Contract, request, address_conversion_func): +def bytes32_contract(w3, Bytes32Contract, request, address_conversion_func): if is_text(request.param) and request.param[:2] != '0x': with pytest.warns(DeprecationWarning): - return deploy(web3, Bytes32Contract, address_conversion_func, args=[request.param]) + return deploy(w3, Bytes32Contract, address_conversion_func, args=[request.param]) else: - return deploy(web3, Bytes32Contract, address_conversion_func, args=[request.param]) + return deploy(w3, Bytes32Contract, address_conversion_func, args=[request.param]) @pytest.fixture() -def undeployed_math_contract(web3, MathContract, address_conversion_func): +def undeployed_math_contract(w3, MathContract, address_conversion_func): empty_address = address_conversion_func("0x000000000000000000000000000000000000dEaD") _undeployed_math_contract = MathContract(address=empty_address) return _undeployed_math_contract @pytest.fixture() -def mismatched_math_contract(web3, StringContract, MathContract, address_conversion_func): +def mismatched_math_contract(w3, StringContract, MathContract, address_conversion_func): deploy_txn = StringContract.constructor("Caqalai").transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None address = address_conversion_func(deploy_receipt['contractAddress']) _mismatched_math_contract = MathContract(address=address) @@ -167,31 +167,31 @@ def mismatched_math_contract(web3, StringContract, MathContract, address_convers @pytest.fixture() -def fallback_function_contract(web3, FallbackFunctionContract, address_conversion_func): - return deploy(web3, FallbackFunctionContract, address_conversion_func) +def fallback_function_contract(w3, FallbackFunctionContract, address_conversion_func): + return deploy(w3, FallbackFunctionContract, address_conversion_func) @pytest.fixture() -def receive_function_contract(web3, ReceiveFunctionContract, address_conversion_func): - return deploy(web3, ReceiveFunctionContract, address_conversion_func) +def receive_function_contract(w3, ReceiveFunctionContract, address_conversion_func): + return deploy(w3, ReceiveFunctionContract, address_conversion_func) @pytest.fixture() -def no_receive_function_contract(web3, NoReceiveFunctionContract, address_conversion_func): - return deploy(web3, NoReceiveFunctionContract, address_conversion_func) +def no_receive_function_contract(w3, NoReceiveFunctionContract, address_conversion_func): + return deploy(w3, NoReceiveFunctionContract, address_conversion_func) @pytest.fixture() -def tuple_contract(web3, TupleContract, address_conversion_func): - return deploy(web3, TupleContract, address_conversion_func) +def tuple_contract(w3, TupleContract, address_conversion_func): + return deploy(w3, TupleContract, address_conversion_func) @pytest.fixture() -def nested_tuple_contract(web3, NestedTupleContract, address_conversion_func): - return deploy(web3, NestedTupleContract, address_conversion_func) +def nested_tuple_contract(w3, NestedTupleContract, address_conversion_func): + return deploy(w3, NestedTupleContract, address_conversion_func) -def test_invalid_address_in_deploy_arg(web3, WithConstructorAddressArgumentsContract): +def test_invalid_address_in_deploy_arg(w3, WithConstructorAddressArgumentsContract): with pytest.raises(InvalidAddress): WithConstructorAddressArgumentsContract.constructor( "0xd3cda913deb6f67967b99d67acdfa1712c293601", @@ -352,12 +352,12 @@ def test_call_read_address_variable(address_contract, call): assert result == "0xd3CdA913deB6f67967B99D67aCDFa1712C293601" -def test_init_with_ens_name_arg(web3, WithConstructorAddressArgumentsContract, call): +def test_init_with_ens_name_arg(w3, WithConstructorAddressArgumentsContract, call): with contract_ens_addresses( WithConstructorAddressArgumentsContract, [("arg-name.eth", "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413")], ): - address_contract = deploy(web3, WithConstructorAddressArgumentsContract, args=[ + address_contract = deploy(w3, WithConstructorAddressArgumentsContract, args=[ "arg-name.eth", ]) @@ -517,7 +517,7 @@ def test_call_fallback_function(fallback_function_contract): ({'data': '0x477a5c98'}, 'receive', 'fallback'), ({'value': 2}, 'receive', 'receive'), )) -def test_call_receive_fallback_function(web3, +def test_call_receive_fallback_function(w3, tx_params, expected, call, @@ -535,7 +535,7 @@ def test_call_receive_fallback_function(web3, assert initial_value == '' to = {'to': contract.address} merged = {**to, **tx_params} - web3.eth.send_transaction(merged) + w3.eth.send_transaction(merged) final_value = call(contract=contract, contract_function='getText') assert final_value == expected @@ -545,14 +545,14 @@ def test_call_nonexistent_receive_function(fallback_function_contract): fallback_function_contract.receive.call() -def test_throws_error_if_block_out_of_range(web3, math_contract): - web3.provider.make_request(method='evm_mine', params=[20]) +def test_throws_error_if_block_out_of_range(w3, math_contract): + w3.provider.make_request(method='evm_mine', params=[20]) with pytest.raises(BlockNumberOutofRange): math_contract.functions.counter().call(block_identifier=-50) -def test_accepts_latest_block(web3, math_contract): - web3.provider.make_request(method='evm_mine', params=[5]) +def test_accepts_latest_block(w3, math_contract): + w3.provider.make_request(method='evm_mine', params=[5]) math_contract.functions.increment().transact() late = math_contract.functions.counter().call(block_identifier='latest') @@ -562,10 +562,10 @@ def test_accepts_latest_block(web3, math_contract): assert pend == 1 -def test_accepts_block_hash_as_identifier(web3, math_contract): - blocks = web3.provider.make_request(method='evm_mine', params=[5]) +def test_accepts_block_hash_as_identifier(w3, math_contract): + blocks = w3.provider.make_request(method='evm_mine', params=[5]) math_contract.functions.increment().transact() - more_blocks = web3.provider.make_request(method='evm_mine', params=[5]) + more_blocks = w3.provider.make_request(method='evm_mine', params=[5]) old = math_contract.functions.counter().call(block_identifier=blocks['result'][2]) new = math_contract.functions.counter().call(block_identifier=more_blocks['result'][2]) @@ -574,11 +574,11 @@ def test_accepts_block_hash_as_identifier(web3, math_contract): assert new == 1 -def test_neg_block_indexes_from_the_end(web3, math_contract): - web3.provider.make_request(method='evm_mine', params=[5]) +def test_neg_block_indexes_from_the_end(w3, math_contract): + w3.provider.make_request(method='evm_mine', params=[5]) math_contract.functions.increment().transact() math_contract.functions.increment().transact() - web3.provider.make_request(method='evm_mine', params=[5]) + w3.provider.make_request(method='evm_mine', params=[5]) output1 = math_contract.functions.counter().call(block_identifier=-7) output2 = math_contract.functions.counter().call(block_identifier=-6) @@ -587,9 +587,9 @@ def test_neg_block_indexes_from_the_end(web3, math_contract): assert output2 == 2 -def test_returns_data_from_specified_block(web3, math_contract): - start_num = web3.eth.get_block('latest').number - web3.provider.make_request(method='evm_mine', params=[5]) +def test_returns_data_from_specified_block(w3, math_contract): + start_num = w3.eth.get_block('latest').number + w3.provider.make_request(method='evm_mine', params=[5]) math_contract.functions.increment().transact() math_contract.functions.increment().transact() @@ -635,38 +635,38 @@ def test_function_1_match_identifier_wrong_args_encoding(arrays_contract): arrays_contract.functions.setBytes32Value('dog').call() -def test_function_multiple_match_identifiers_no_correct_number_of_args(web3): +def test_function_multiple_match_identifiers_no_correct_number_of_args(w3): MULTIPLE_FUNCTIONS = json.loads('[{"constant":false,"inputs":[],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"bytes32"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"uint256"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"uint8"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"int8"}],"name":"a","outputs":[],"type":"function"}]') # noqa: E501 - Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS) + Contract = w3.eth.contract(abi=MULTIPLE_FUNCTIONS) regex = message_regex + diagnosis_arg_regex with pytest.raises(ValidationError, match=regex): Contract.functions.a(100, 'dog').call() -def test_function_multiple_match_identifiers_no_correct_encoding_of_args(web3): +def test_function_multiple_match_identifiers_no_correct_encoding_of_args(w3): MULTIPLE_FUNCTIONS = json.loads('[{"constant":false,"inputs":[],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"bytes32"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"uint256"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"uint8"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"int8"}],"name":"a","outputs":[],"type":"function"}]') # noqa: E501 - Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS) + Contract = w3.eth.contract(abi=MULTIPLE_FUNCTIONS) regex = message_regex + diagnosis_encoding_regex with pytest.raises(ValidationError, match=regex): Contract.functions.a('dog').call() -def test_function_multiple_possible_encodings(web3): +def test_function_multiple_possible_encodings(w3): MULTIPLE_FUNCTIONS = json.loads('[{"constant":false,"inputs":[],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"bytes32"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"uint256"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"uint8"}],"name":"a","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"","type":"int8"}],"name":"a","outputs":[],"type":"function"}]') # noqa: E501 - Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS) + Contract = w3.eth.contract(abi=MULTIPLE_FUNCTIONS) regex = message_regex + diagnosis_ambiguous_encoding with pytest.raises(ValidationError, match=regex): Contract.functions.a(100).call() -def test_function_no_abi(web3): - contract = web3.eth.contract() +def test_function_no_abi(w3): + contract = w3.eth.contract() with pytest.raises(NoABIFound): contract.functions.thisFunctionDoesNotExist().call() -def test_call_abi_no_functions(web3): - contract = web3.eth.contract(abi=[]) +def test_call_abi_no_functions(w3): + contract = w3.eth.contract(abi=[]) with pytest.raises(NoABIFunctionsFound): contract.functions.thisFunctionDoesNotExist().call() @@ -704,7 +704,7 @@ def test_call_sending_ether_to_nonpayable_function(payable_tester_contract, call ('reflect_short_u', Decimal('25.5')), ), ) -def test_reflect_fixed_value(web3, fixed_reflection_contract, function, value): +def test_reflect_fixed_value(w3, fixed_reflection_contract, function, value): contract_func = fixed_reflection_contract.functions[function] reflected = contract_func(value).call({'gas': 420000}) assert reflected == value @@ -741,7 +741,7 @@ def test_reflect_fixed_value(web3, fixed_reflection_contract, function, value): ('reflect', 0, "Ambiguous argument encoding"), ), ) -def test_invalid_fixed_value_reflections(web3, fixed_reflection_contract, function, value, error): +def test_invalid_fixed_value_reflections(w3, fixed_reflection_contract, function, value, error): contract_func = fixed_reflection_contract.functions[function] with pytest.raises(ValidationError, match=error): contract_func(value).call({'gas': 420000}) diff --git a/tests/core/contracts/test_contract_caller_interface.py b/tests/core/contracts/test_contract_caller_interface.py index 45c4ac7c6a..9553766115 100644 --- a/tests/core/contracts/test_contract_caller_interface.py +++ b/tests/core/contracts/test_contract_caller_interface.py @@ -11,40 +11,40 @@ ) -def deploy(web3, Contract, apply_func=identity, args=None): +def deploy(w3, Contract, apply_func=identity, args=None): args = args or [] deploy_txn = Contract.constructor(*args).transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None address = apply_func(deploy_receipt['contractAddress']) contract = Contract(address=address) assert contract.address == address - assert len(web3.eth.get_code(contract.address)) > 0 + assert len(w3.eth.get_code(contract.address)) > 0 return contract @pytest.fixture() -def address(web3): - return web3.eth.accounts[1] +def address(w3): + return w3.eth.accounts[1] @pytest.fixture() -def math_contract(web3, MathContract, address_conversion_func): - return deploy(web3, MathContract, address_conversion_func) +def math_contract(w3, MathContract, address_conversion_func): + return deploy(w3, MathContract, address_conversion_func) @pytest.fixture() -def caller_tester_contract(web3, CallerTesterContract, address_conversion_func): - return deploy(web3, CallerTesterContract, address_conversion_func) +def caller_tester_contract(w3, CallerTesterContract, address_conversion_func): + return deploy(w3, CallerTesterContract, address_conversion_func) @pytest.fixture() -def transaction_dict(web3, address): +def transaction_dict(w3, address): return { 'from': address, 'gas': 210000, - 'maxFeePerGas': web3.toWei(1, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(1, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), 'value': 12345, } @@ -59,26 +59,26 @@ def test_caller_with_parens(math_contract): assert result == 8 -def test_caller_with_no_abi(web3): - contract = web3.eth.contract() +def test_caller_with_no_abi(w3): + contract = w3.eth.contract() with pytest.raises(NoABIFound): contract.caller.thisFunctionDoesNotExist() -def test_caller_with_no_abi_and_parens(web3): - contract = web3.eth.contract() +def test_caller_with_no_abi_and_parens(w3): + contract = w3.eth.contract() with pytest.raises(NoABIFound): contract.caller().thisFunctionDoesNotExist() -def test_caller_with_empty_abi_and_parens(web3): - contract = web3.eth.contract(abi=[]) +def test_caller_with_empty_abi_and_parens(w3): + contract = w3.eth.contract(abi=[]) with pytest.raises(NoABIFunctionsFound): contract.caller().thisFunctionDoesNotExist() -def test_caller_with_empty_abi(web3): - contract = web3.eth.contract(abi=[]) +def test_caller_with_empty_abi(w3): + contract = w3.eth.contract(abi=[]) with pytest.raises(NoABIFunctionsFound): contract.caller.thisFunctionDoesNotExist() @@ -99,11 +99,11 @@ def test_caller_with_a_nonexistent_function(math_contract): contract.caller.thisFunctionDoesNotExist() -def test_caller_with_block_identifier(web3, math_contract): - start_num = web3.eth.get_block('latest').number +def test_caller_with_block_identifier(w3, math_contract): + start_num = w3.eth.get_block('latest').number assert math_contract.caller.counter() == 0 - web3.provider.make_request(method='evm_mine', params=[5]) + w3.provider.make_request(method='evm_mine', params=[5]) math_contract.functions.increment().transact() math_contract.functions.increment().transact() @@ -114,14 +114,14 @@ def test_caller_with_block_identifier(web3, math_contract): assert output2 == 2 -def test_caller_with_block_identifier_and_transaction_dict(web3, +def test_caller_with_block_identifier_and_transaction_dict(w3, caller_tester_contract, transaction_dict, address): - start_num = web3.eth.get_block('latest').number + start_num = w3.eth.get_block('latest').number assert caller_tester_contract.caller.counter() == 0 - web3.provider.make_request(method='evm_mine', params=[5]) + w3.provider.make_request(method='evm_mine', params=[5]) caller_tester_contract.functions.increment().transact() block_id = start_num + 6 @@ -140,7 +140,7 @@ def test_caller_with_block_identifier_and_transaction_dict(web3, assert counter == 1 -def test_caller_with_transaction_keyword(web3, +def test_caller_with_transaction_keyword(w3, caller_tester_contract, transaction_dict, address): @@ -153,7 +153,7 @@ def test_caller_with_transaction_keyword(web3, assert value == transaction_dict['value'] -def test_caller_with_dict_but_no_transaction_keyword(web3, +def test_caller_with_dict_but_no_transaction_keyword(w3, caller_tester_contract, transaction_dict, address): @@ -166,7 +166,7 @@ def test_caller_with_dict_but_no_transaction_keyword(web3, assert value == transaction_dict['value'] -def test_caller_with_args_and_no_transaction_keyword(web3, +def test_caller_with_args_and_no_transaction_keyword(w3, caller_tester_contract, transaction_dict, address): diff --git a/tests/core/contracts/test_contract_class_construction.py b/tests/core/contracts/test_contract_class_construction.py index 1f5557081d..1eea5d246a 100644 --- a/tests/core/contracts/test_contract_class_construction.py +++ b/tests/core/contracts/test_contract_class_construction.py @@ -13,17 +13,17 @@ ) -def test_class_construction_sets_class_vars(web3, +def test_class_construction_sets_class_vars(w3, MATH_ABI, MATH_CODE, MATH_RUNTIME): - MathContract = web3.eth.contract( + MathContract = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) - assert MathContract.web3 == web3 + assert MathContract.w3 == w3 assert MathContract.bytecode == decode_hex(MATH_CODE) assert MathContract.bytecode_runtime == decode_hex(MATH_RUNTIME) @@ -33,21 +33,21 @@ def test_error_to_instantiate_base_class(): Contract() -def test_abi_as_json_string(web3, MATH_ABI, some_address): +def test_abi_as_json_string(w3, MATH_ABI, some_address): abi_str = json.dumps(MATH_ABI) - MathContract = web3.eth.contract(abi=abi_str) + MathContract = w3.eth.contract(abi=abi_str) assert MathContract.abi == MATH_ABI math = MathContract(some_address) assert math.abi == MATH_ABI -def test_error_to_call_non_existent_fallback(web3, +def test_error_to_call_non_existent_fallback(w3, MATH_ABI, MATH_CODE, MATH_RUNTIME): - math_contract = web3.eth.contract( + math_contract = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, diff --git a/tests/core/contracts/test_contract_constructor.py b/tests/core/contracts/test_contract_constructor.py index b762853092..36ae246de8 100644 --- a/tests/core/contracts/test_contract_constructor.py +++ b/tests/core/contracts/test_contract_constructor.py @@ -15,33 +15,33 @@ def test_contract_constructor_abi_encoding_with_no_constructor_fn(MathContract, assert deploy_data == MATH_CODE -def test_contract_constructor_gas_estimate_no_constructor(web3, MathContract): +def test_contract_constructor_gas_estimate_no_constructor(w3, MathContract): gas_estimate = MathContract.constructor().estimateGas() deploy_txn = MathContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 -def test_contract_constructor_gas_estimate_with_block_id(web3, MathContract): +def test_contract_constructor_gas_estimate_with_block_id(w3, MathContract): block_identifier = None gas_estimate = MathContract.constructor().estimateGas(block_identifier=block_identifier) deploy_txn = MathContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 def test_contract_constructor_gas_estimate_with_constructor_without_arguments( - web3, + w3, SimpleConstructorContract): gas_estimate = SimpleConstructorContract.constructor().estimateGas() deploy_txn = SimpleConstructorContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 @@ -57,7 +57,7 @@ def test_contract_constructor_gas_estimate_with_constructor_without_arguments( ), ) def test_contract_constructor_gas_estimate_with_constructor_with_arguments( - web3, + w3, WithConstructorArgumentsContract, constructor_args, constructor_kwargs): @@ -66,14 +66,14 @@ def test_contract_constructor_gas_estimate_with_constructor_with_arguments( deploy_txn = WithConstructorArgumentsContract.constructor( *constructor_args, **constructor_kwargs).transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 def test_contract_constructor_gas_estimate_with_constructor_with_address_argument( - web3, + w3, WithConstructorAddressArgumentsContract, address_conversion_func): gas_estimate = WithConstructorAddressArgumentsContract.constructor( @@ -81,43 +81,43 @@ def test_contract_constructor_gas_estimate_with_constructor_with_address_argumen deploy_txn = WithConstructorAddressArgumentsContract.constructor( address_conversion_func("0x16D9983245De15E7A9A73bC586E01FF6E08dE737")).transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 def test_contract_constructor_transact_no_constructor( - web3, + w3, MathContract, MATH_RUNTIME, address_conversion_func): deploy_txn = MathContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = address_conversion_func(txn_receipt['contractAddress']) - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(MATH_RUNTIME) def test_contract_constructor_transact_with_constructor_without_arguments( - web3, + w3, SimpleConstructorContract, SIMPLE_CONSTRUCTOR_RUNTIME, address_conversion_func): deploy_txn = SimpleConstructorContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = address_conversion_func(txn_receipt['contractAddress']) - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(SIMPLE_CONSTRUCTOR_RUNTIME) @@ -131,7 +131,7 @@ def test_contract_constructor_transact_with_constructor_without_arguments( ), ) def test_contract_constructor_transact_with_constructor_with_arguments( - web3, + w3, WithConstructorArgumentsContract, WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME, constructor_args, @@ -142,13 +142,13 @@ def test_contract_constructor_transact_with_constructor_with_arguments( deploy_txn = WithConstructorArgumentsContract.constructor( *constructor_args, **constructor_kwargs).transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = address_conversion_func(txn_receipt['contractAddress']) - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME) assert expected_a == WithConstructorArgumentsContract( address=contract_address).functions.data_a().call() @@ -157,16 +157,16 @@ def test_contract_constructor_transact_with_constructor_with_arguments( def test_contract_constructor_transact_with_constructor_with_address_arguments( - web3, + w3, WithConstructorAddressArgumentsContract, WITH_CONSTRUCTOR_ADDRESS_RUNTIME, address_conversion_func): deploy_txn = WithConstructorAddressArgumentsContract.constructor(TEST_ADDRESS).transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = address_conversion_func(txn_receipt['contractAddress']) - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(WITH_CONSTRUCTOR_ADDRESS_RUNTIME) assert TEST_ADDRESS == WithConstructorAddressArgumentsContract( address=contract_address).functions.testAddr().call() @@ -178,37 +178,37 @@ def test_contract_constructor_build_transaction_to_field_error(MathContract): def test_contract_constructor_build_transaction_no_constructor( - web3, + w3, MathContract, address_conversion_func): txn_hash = MathContract.constructor().transact( - {'from': address_conversion_func(web3.eth.accounts[0])} + {'from': address_conversion_func(w3.eth.accounts[0])} ) - txn = web3.eth.get_transaction(txn_hash) - nonce = web3.eth.get_transaction_count(web3.eth.coinbase) + txn = w3.eth.get_transaction(txn_hash) + nonce = w3.eth.get_transaction_count(w3.eth.coinbase) unsent_txn = MathContract.constructor().buildTransaction({'nonce': nonce}) assert txn['data'] == unsent_txn['data'] - new_txn_hash = web3.eth.send_transaction(unsent_txn) - new_txn = web3.eth.get_transaction(new_txn_hash) + new_txn_hash = w3.eth.send_transaction(unsent_txn) + new_txn = w3.eth.get_transaction(new_txn_hash) assert new_txn['data'] == unsent_txn['data'] assert new_txn['nonce'] == nonce def test_contract_constructor_build_transaction_with_constructor_without_argument( - web3, + w3, MathContract, address_conversion_func): txn_hash = MathContract.constructor().transact( - {'from': address_conversion_func(web3.eth.accounts[0])} + {'from': address_conversion_func(w3.eth.accounts[0])} ) - txn = web3.eth.get_transaction(txn_hash) - nonce = web3.eth.get_transaction_count(web3.eth.coinbase) + txn = w3.eth.get_transaction(txn_hash) + nonce = w3.eth.get_transaction_count(w3.eth.coinbase) unsent_txn = MathContract.constructor().buildTransaction({'nonce': nonce}) assert txn['data'] == unsent_txn['data'] - new_txn_hash = web3.eth.send_transaction(unsent_txn) - new_txn = web3.eth.get_transaction(new_txn_hash) + new_txn_hash = w3.eth.send_transaction(unsent_txn) + new_txn = w3.eth.get_transaction(new_txn_hash) assert new_txn['data'] == unsent_txn['data'] assert new_txn['nonce'] == nonce @@ -223,22 +223,22 @@ def test_contract_constructor_build_transaction_with_constructor_without_argumen ), ) def test_contract_constructor_build_transaction_with_constructor_with_argument( - web3, + w3, WithConstructorArgumentsContract, constructor_args, constructor_kwargs, address_conversion_func): txn_hash = WithConstructorArgumentsContract.constructor( *constructor_args, **constructor_kwargs).transact( - {'from': address_conversion_func(web3.eth.accounts[0])} + {'from': address_conversion_func(w3.eth.accounts[0])} ) - txn = web3.eth.get_transaction(txn_hash) - nonce = web3.eth.get_transaction_count(web3.eth.coinbase) + txn = w3.eth.get_transaction(txn_hash) + nonce = w3.eth.get_transaction_count(w3.eth.coinbase) unsent_txn = WithConstructorArgumentsContract.constructor( *constructor_args, **constructor_kwargs).buildTransaction({'nonce': nonce}) assert txn['data'] == unsent_txn['data'] - new_txn_hash = web3.eth.send_transaction(unsent_txn) - new_txn = web3.eth.get_transaction(new_txn_hash) + new_txn_hash = w3.eth.send_transaction(unsent_txn) + new_txn = w3.eth.get_transaction(new_txn_hash) assert new_txn['data'] == unsent_txn['data'] assert new_txn['nonce'] == nonce diff --git a/tests/core/contracts/test_contract_constructor_encoding.py b/tests/core/contracts/test_contract_constructor_encoding.py index 3711dfaf9a..7966c5f301 100644 --- a/tests/core/contracts/test_contract_constructor_encoding.py +++ b/tests/core/contracts/test_contract_constructor_encoding.py @@ -53,15 +53,15 @@ def test_error_if_invalid_arguments_supplied(WithConstructorArgumentsContract, a '0x61626364', ), ) -def test_contract_constructor_encoding_encoding(web3, WithConstructorArgumentsContract, bytes_arg): +def test_contract_constructor_encoding_encoding(w3, WithConstructorArgumentsContract, bytes_arg): deploy_data = WithConstructorArgumentsContract._encode_constructor_data([1234, bytes_arg]) encoded_args = '0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000' # noqa: E501 - expected_ending = encode_hex(web3.codec.encode_abi(['uint256', 'bytes32'], [1234, b'abcd'])) + expected_ending = encode_hex(w3.codec.encode_abi(['uint256', 'bytes32'], [1234, b'abcd'])) assert expected_ending == encoded_args assert deploy_data.endswith(remove_0x_prefix(expected_ending)) -def test_contract_constructor_encoding_encoding_warning(web3, WithConstructorArgumentsContract): +def test_contract_constructor_encoding_encoding_warning(w3, WithConstructorArgumentsContract): with pytest.warns( DeprecationWarning, match='in v6 it will be invalid to pass a hex string without the \"0x\" prefix' @@ -70,7 +70,7 @@ def test_contract_constructor_encoding_encoding_warning(web3, WithConstructorArg encoded_args = '0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000' # noqa: E501 expected_ending = encode_hex( - web3.codec.encode_abi(['uint256', 'bytes32'], [1234, b'abcd']) + w3.codec.encode_abi(['uint256', 'bytes32'], [1234, b'abcd']) ) assert expected_ending == encoded_args assert deploy_data.endswith(remove_0x_prefix(expected_ending)) diff --git a/tests/core/contracts/test_contract_deployment.py b/tests/core/contracts/test_contract_deployment.py index 20027ea701..f0b2e80d81 100644 --- a/tests/core/contracts/test_contract_deployment.py +++ b/tests/core/contracts/test_contract_deployment.py @@ -10,36 +10,36 @@ ) -def test_contract_deployment_no_constructor(web3, MathContract, +def test_contract_deployment_no_constructor(w3, MathContract, MATH_RUNTIME): deploy_txn = MathContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(MATH_RUNTIME) -def test_contract_deployment_with_constructor_without_args(web3, +def test_contract_deployment_with_constructor_without_args(w3, SimpleConstructorContract, SIMPLE_CONSTRUCTOR_RUNTIME): deploy_txn = SimpleConstructorContract.constructor().transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(SIMPLE_CONSTRUCTOR_RUNTIME) -def test_contract_deployment_with_constructor_with_arguments(web3, +def test_contract_deployment_with_constructor_with_arguments(w3, WithConstructorArgumentsContract, WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME): with pytest.warns( @@ -48,13 +48,13 @@ def test_contract_deployment_with_constructor_with_arguments(web3, ): deploy_txn = WithConstructorArgumentsContract.constructor(1234, 'abcd').transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME) @@ -90,18 +90,18 @@ def test_contract_deployment_with_constructor_with_arguments_strict_error(w3_str WithConstructorArgumentsContractStrict.constructor(1234, 'abcd').transact() -def test_contract_deployment_with_constructor_with_address_argument(web3, +def test_contract_deployment_with_constructor_with_address_argument(w3, WithConstructorAddressArgumentsContract, # noqa: E501 WITH_CONSTRUCTOR_ADDRESS_RUNTIME): # noqa: E501 deploy_txn = WithConstructorAddressArgumentsContract.constructor( "0x16D9983245De15E7A9A73bC586E01FF6E08dE737", ).transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + txn_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] - blockchain_code = web3.eth.get_code(contract_address) + blockchain_code = w3.eth.get_code(contract_address) assert blockchain_code == decode_hex(WITH_CONSTRUCTOR_ADDRESS_RUNTIME) diff --git a/tests/core/contracts/test_contract_estimateGas.py b/tests/core/contracts/test_contract_estimateGas.py index e3226f02fa..704e746028 100644 --- a/tests/core/contracts/test_contract_estimateGas.py +++ b/tests/core/contracts/test_contract_estimateGas.py @@ -6,28 +6,28 @@ @pytest.fixture(autouse=True) -def wait_for_first_block(web3, wait_for_block): - wait_for_block(web3) +def wait_for_first_block(w3, wait_for_block): + wait_for_block(w3) @pytest.fixture() -def math_contract(web3, +def math_contract(w3, MATH_ABI, MATH_CODE, MATH_RUNTIME, wait_for_transaction, address_conversion_func): - MathContract = web3.eth.contract( + MathContract = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) - deploy_txn = MathContract.constructor().transact({'from': web3.eth.coinbase}) - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_txn = MathContract.constructor().transact({'from': w3.eth.coinbase}) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None contract_address = address_conversion_func(deploy_receipt['contractAddress']) - web3.isAddress(contract_address) + w3.isAddress(contract_address) _math_contract = MathContract(address=contract_address) assert _math_contract.address == contract_address @@ -35,23 +35,23 @@ def math_contract(web3, @pytest.fixture() -def fallback_function_contract(web3, +def fallback_function_contract(w3, FALLBACK_FUNCTION_ABI, FALLBACK_FUNCTION_CODE, FALLBACK_FUNCTION_RUNTIME, wait_for_transaction, address_conversion_func): - fallback_contract = web3.eth.contract( + fallback_contract = w3.eth.contract( abi=FALLBACK_FUNCTION_ABI, bytecode=FALLBACK_FUNCTION_CODE, bytecode_runtime=FALLBACK_FUNCTION_RUNTIME ) - deploy_txn = fallback_contract.constructor().transact({'from': web3.eth.coinbase}) - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_txn = fallback_contract.constructor().transact({'from': w3.eth.coinbase}) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None contract_address = address_conversion_func(deploy_receipt['contractAddress']) - web3.isAddress(contract_address) + w3.isAddress(contract_address) _fallback_function_contract = fallback_contract(address=contract_address) assert _fallback_function_contract.address == contract_address @@ -59,9 +59,9 @@ def fallback_function_contract(web3, @pytest.fixture() -def payable_tester_contract(web3, PayableTesterContract, address_conversion_func): - deploy_txn = PayableTesterContract.constructor().transact({'from': web3.eth.coinbase}) - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) +def payable_tester_contract(w3, PayableTesterContract, address_conversion_func): + deploy_txn = PayableTesterContract.constructor().transact({'from': w3.eth.coinbase}) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None payable_tester_address = address_conversion_func(deploy_receipt['contractAddress']) @@ -71,7 +71,7 @@ def payable_tester_contract(web3, PayableTesterContract, address_conversion_func return _payable_tester -def test_contract_estimateGas(web3, math_contract, estimateGas, transact): +def test_contract_estimateGas(w3, math_contract, estimateGas, transact): gas_estimate = estimateGas(contract=math_contract, contract_function='increment') @@ -79,24 +79,24 @@ def test_contract_estimateGas(web3, math_contract, estimateGas, transact): contract=math_contract, contract_function='increment') - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 -def test_contract_fallback_estimateGas(web3, fallback_function_contract): +def test_contract_fallback_estimateGas(w3, fallback_function_contract): gas_estimate = fallback_function_contract.fallback.estimateGas() txn_hash = fallback_function_contract.fallback.transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 -def test_contract_estimateGas_with_arguments(web3, math_contract, estimateGas, transact): +def test_contract_estimateGas_with_arguments(w3, math_contract, estimateGas, transact): gas_estimate = estimateGas(contract=math_contract, contract_function='add', func_args=[5, 6]) @@ -105,14 +105,14 @@ def test_contract_estimateGas_with_arguments(web3, math_contract, estimateGas, t contract=math_contract, contract_function='add', func_args=[5, 6]) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 def test_estimateGas_not_sending_ether_to_nonpayable_function( - web3, + w3, payable_tester_contract, estimateGas, transact): @@ -123,14 +123,14 @@ def test_estimateGas_not_sending_ether_to_nonpayable_function( contract=payable_tester_contract, contract_function='doNoValueCall') - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 def test_estimateGas_sending_ether_to_nonpayable_function( - web3, + w3, payable_tester_contract, estimateGas): with pytest.raises(ValidationError): @@ -139,22 +139,22 @@ def test_estimateGas_sending_ether_to_nonpayable_function( tx_params={'value': 1}) -def test_estimateGas_accepts_latest_block(web3, math_contract, transact): +def test_estimateGas_accepts_latest_block(w3, math_contract, transact): gas_estimate = math_contract.functions.counter().estimateGas(block_identifier='latest') txn_hash = transact( contract=math_contract, contract_function='increment') - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) gas_used = txn_receipt.get('gasUsed') assert abs(gas_estimate - gas_used) < 21000 -def test_estimateGas_block_identifier_unique_estimates(web3, math_contract, transact): +def test_estimateGas_block_identifier_unique_estimates(w3, math_contract, transact): txn_hash = transact(contract=math_contract, contract_function="increment") - web3.eth.wait_for_transaction_receipt(txn_hash) + w3.eth.wait_for_transaction_receipt(txn_hash) latest_gas_estimate = math_contract.functions.counter().estimateGas( block_identifier="latest" diff --git a/tests/core/contracts/test_contract_events_buildFilter.py b/tests/core/contracts/test_contract_events_buildFilter.py index 02fade01c3..f8e98c3beb 100644 --- a/tests/core/contracts/test_contract_events_buildFilter.py +++ b/tests/core/contracts/test_contract_events_buildFilter.py @@ -11,19 +11,19 @@ CONTRACT_ABI = json.loads('[{"constant":false,"inputs":[],"name":"return13","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"constant":true,"inputs":[],"name":"counter","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"amt","type":"uint256"}],"name":"increment","outputs":[{"name":"result","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"a","type":"int256"},{"name":"b","type":"int256"}],"name":"add","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"constant":false,"inputs":[],"name":"increment","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"a","type":"int256"}],"name":"multiply7","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"value","type":"uint256"}],"name":"Increased","type":"event"}]') # noqa: E501 -def test_build_filter_topic_signature(web3): - contract = web3.eth.contract(abi=CONTRACT_ABI) +def test_build_filter_topic_signature(w3): + contract = w3.eth.contract(abi=CONTRACT_ABI) filter_builder = contract.events.Increased.build_filter() filter_builder.args['value'].match_any(100, 200, 300) - _filter = filter_builder.deploy(web3) + _filter = filter_builder.deploy(w3) assert _filter.filter_params == { 'topics': ( HexBytes(keccak(text="Increased(uint256)")).hex(),)} assert _filter.data_filter_set == (('uint256', (100, 200, 300)),) -def test_build_filter_resetting_build_filter_properties(web3): - contract = web3.eth.contract(abi=CONTRACT_ABI) +def test_build_filter_resetting_build_filter_properties(w3): + contract = w3.eth.contract(abi=CONTRACT_ABI) filter_builder = contract.events.Increased.build_filter() # Address is setable from undeployed contract class filter_builder.address = b'\x10' * 40 @@ -38,26 +38,26 @@ def test_build_filter_resetting_build_filter_properties(web3): filter_builder.toBlock = 50 -def test_build_filter_argument_match_single_can_only_be_set_once(web3): - contract = web3.eth.contract(abi=CONTRACT_ABI) +def test_build_filter_argument_match_single_can_only_be_set_once(w3): + contract = w3.eth.contract(abi=CONTRACT_ABI) filter_builder = contract.events.Increased.build_filter() filter_builder.args['value'].match_single(100) with pytest.raises(ValueError): filter_builder.args['value'].match_single(200) -def test_build_filter_argument_match_any_can_only_be_set_once(web3): - contract = web3.eth.contract(abi=CONTRACT_ABI) +def test_build_filter_argument_match_any_can_only_be_set_once(w3): + contract = w3.eth.contract(abi=CONTRACT_ABI) filter_builder = contract.events.Increased.build_filter() filter_builder.args['value'].match_any(100, 200) with pytest.raises(ValueError): filter_builder.args['value'].match_any(200, 300) -def test_deployed_build_filter_can_have_no_values_set(web3): - contract = web3.eth.contract(abi=CONTRACT_ABI) +def test_deployed_build_filter_can_have_no_values_set(w3): + contract = w3.eth.contract(abi=CONTRACT_ABI) filter_builder = contract.events.Increased.build_filter() - filter_builder.deploy(web3) + filter_builder.deploy(w3) with pytest.raises(ValueError): filter_builder.address = b'\x00' * 40 with pytest.raises(ValueError): diff --git a/tests/core/contracts/test_contract_init.py b/tests/core/contracts/test_contract_init.py index cdf202205f..230ff7c384 100644 --- a/tests/core/contracts/test_contract_init.py +++ b/tests/core/contracts/test_contract_init.py @@ -12,9 +12,9 @@ @pytest.fixture() def math_addr(MathContract, address_conversion_func): - web3 = MathContract.web3 - deploy_txn = MathContract.constructor().transact({'from': web3.eth.coinbase}) - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + w3 = MathContract.w3 + deploy_txn = MathContract.constructor().transact({'from': w3.eth.coinbase}) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None return address_conversion_func(deploy_receipt['contractAddress']) @@ -28,27 +28,27 @@ def test_contract_with_unset_address(MathContract): def test_contract_with_name_address(MathContract, math_addr): with contract_ens_addresses(MathContract, [('thedao.eth', math_addr)]): mc = MathContract(address='thedao.eth') - caller = mc.web3.eth.coinbase + caller = mc.w3.eth.coinbase assert mc.address == 'thedao.eth' assert mc.functions.return13().call({'from': caller}) == 13 def test_contract_with_name_address_from_eth_contract( - web3, + w3, MATH_ABI, MATH_CODE, MATH_RUNTIME, math_addr, ): - with ens_addresses(web3, [('thedao.eth', math_addr)]): - mc = web3.eth.contract( + with ens_addresses(w3, [('thedao.eth', math_addr)]): + mc = w3.eth.contract( address='thedao.eth', abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) - caller = mc.web3.eth.coinbase + caller = mc.w3.eth.coinbase assert mc.address == 'thedao.eth' assert mc.functions.return13().call({'from': caller}) == 13 @@ -58,7 +58,7 @@ def test_contract_with_name_address_changing(MathContract, math_addr): with contract_ens_addresses(MathContract, [('thedao.eth', math_addr)]): mc = MathContract(address='thedao.eth') - caller = mc.web3.eth.coinbase + caller = mc.w3.eth.coinbase assert mc.address == 'thedao.eth' # what happens when name returns no address at all diff --git a/tests/core/contracts/test_contract_method_abi_decoding.py b/tests/core/contracts/test_contract_method_abi_decoding.py index fafe12a9bb..a6c0f1b6be 100644 --- a/tests/core/contracts/test_contract_method_abi_decoding.py +++ b/tests/core/contracts/test_contract_method_abi_decoding.py @@ -81,8 +81,8 @@ ), ), ) -def test_contract_abi_decoding(web3, abi, data, method, expected): - contract = web3.eth.contract(abi=abi) +def test_contract_abi_decoding(w3, abi, data, method, expected): + contract = w3.eth.contract(abi=abi) func, params = contract.decode_function_input(data) assert func.fn_name == method assert params == expected @@ -108,8 +108,8 @@ def test_contract_abi_decoding(web3, abi, data, method, expected): ), ), ) -def test_contract_abi_encoding_kwargs(web3, abi, method, expected, data): - contract = web3.eth.contract(abi=abi) +def test_contract_abi_encoding_kwargs(w3, abi, method, expected, data): + contract = w3.eth.contract(abi=abi) func, params = contract.decode_function_input(data) assert func.fn_name == method assert params == expected diff --git a/tests/core/contracts/test_contract_method_abi_encoding.py b/tests/core/contracts/test_contract_method_abi_encoding.py index 19ba0f517f..efe4aa5b64 100644 --- a/tests/core/contracts/test_contract_method_abi_encoding.py +++ b/tests/core/contracts/test_contract_method_abi_encoding.py @@ -56,14 +56,14 @@ ), ), ) -def test_contract_abi_encoding(web3, abi, arguments, data, expected): - contract = web3.eth.contract(abi=abi) +def test_contract_abi_encoding(w3, abi, arguments, data, expected): + contract = w3.eth.contract(abi=abi) actual = contract.encodeABI('a', arguments, data=data) assert actual == expected -def test_contract_abi_encoding_warning(web3): - contract = web3.eth.contract(abi=ABI_C) +def test_contract_abi_encoding_warning(w3): + contract = w3.eth.contract(abi=ABI_C) with pytest.warns( DeprecationWarning, @@ -74,8 +74,8 @@ def test_contract_abi_encoding_warning(web3): assert actual == '0x9f3fab586100000000000000000000000000000000000000000000000000000000000000' # noqa: E501 -def test_contract_abi_encoding_kwargs(web3): - contract = web3.eth.contract(abi=ABI_D) +def test_contract_abi_encoding_kwargs(w3): + contract = w3.eth.contract(abi=ABI_D) kwargs = { 'b': [ '0x5595c210956e7721f9b692e702708556aa9aabb14ea163e96afa56ffbe9fa809', diff --git a/tests/core/contracts/test_contract_method_to_argument_matching.py b/tests/core/contracts/test_contract_method_to_argument_matching.py index 3560687df7..8f80dbf6c6 100644 --- a/tests/core/contracts/test_contract_method_to_argument_matching.py +++ b/tests/core/contracts/test_contract_method_to_argument_matching.py @@ -93,16 +93,16 @@ ''') -def test_finds_single_function_without_args(web3): - Contract = web3.eth.contract(abi=SINGLE_FN_NO_ARGS) +def test_finds_single_function_without_args(w3): + Contract = w3.eth.contract(abi=SINGLE_FN_NO_ARGS) abi = Contract._find_matching_fn_abi('a', []) assert abi['name'] == 'a' assert abi['inputs'] == [] -def test_finds_single_function_with_args(web3): - Contract = web3.eth.contract(abi=SINGLE_FN_ONE_ARG) +def test_finds_single_function_with_args(w3): + Contract = w3.eth.contract(abi=SINGLE_FN_ONE_ARG) abi = Contract._find_matching_fn_abi('a', [1234]) assert abi['name'] == 'a' @@ -110,22 +110,22 @@ def test_finds_single_function_with_args(web3): assert abi['inputs'][0]['type'] == 'uint256' -def test_finds_fallback_function(web3): - Contract = web3.eth.contract(abi=FALLBACK_FUNCTION) +def test_finds_fallback_function(w3): + Contract = w3.eth.contract(abi=FALLBACK_FUNCTION) abi = Contract._find_matching_fn_abi(FallbackFn, []) assert abi['type'] == 'fallback' -def test_finds_receive_function(web3): - Contract = web3.eth.contract(abi=RECEIVE_FUNCTION) +def test_finds_receive_function(w3): + Contract = w3.eth.contract(abi=RECEIVE_FUNCTION) abi = Contract._find_matching_fn_abi(ReceiveFn, []) assert abi['type'] == 'receive' -def test_error_when_no_function_name_match(web3): - Contract = web3.eth.contract(abi=SINGLE_FN_NO_ARGS) +def test_error_when_no_function_name_match(w3): + Contract = w3.eth.contract(abi=SINGLE_FN_NO_ARGS) with pytest.raises(ValidationError): Contract._find_matching_fn_abi('no_function_name', [1234]) @@ -144,8 +144,8 @@ def test_error_when_no_function_name_match(web3): ([[(-1, True), (2, False)]], ['(int256,bool)[]']), ) ) -def test_finds_function_with_matching_args(web3, arguments, expected_types): - Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS) +def test_finds_function_with_matching_args(w3, arguments, expected_types): + Contract = w3.eth.contract(abi=MULTIPLE_FUNCTIONS) abi = Contract._find_matching_fn_abi('a', arguments) assert abi['name'] == 'a' @@ -153,8 +153,8 @@ def test_finds_function_with_matching_args(web3, arguments, expected_types): assert set(get_abi_input_types(abi)) == set(expected_types) -def test_finds_function_with_matching_args_deprecation_warning(web3): - Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS) +def test_finds_function_with_matching_args_deprecation_warning(w3): + Contract = w3.eth.contract(abi=MULTIPLE_FUNCTIONS) with pytest.warns(DeprecationWarning): abi = Contract._find_matching_fn_abi('a', ['']) @@ -163,8 +163,8 @@ def test_finds_function_with_matching_args_deprecation_warning(web3): assert set(get_abi_input_types(abi)) == set(['bytes32']) -def test_error_when_duplicate_match(web3): - Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS) +def test_error_when_duplicate_match(w3): + Contract = w3.eth.contract(abi=MULTIPLE_FUNCTIONS) with pytest.raises(ValidationError): Contract._find_matching_fn_abi('a', [100]) diff --git a/tests/core/contracts/test_contract_transact_interface.py b/tests/core/contracts/test_contract_transact_interface.py index 0e506be5f7..32a6c48414 100644 --- a/tests/core/contracts/test_contract_transact_interface.py +++ b/tests/core/contracts/test_contract_transact_interface.py @@ -15,61 +15,61 @@ ) -def deploy(web3, Contract, apply_func=identity, args=None): +def deploy(w3, Contract, apply_func=identity, args=None): args = args or [] deploy_txn = Contract.constructor(*args).transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) assert deploy_receipt is not None address = apply_func(deploy_receipt['contractAddress']) contract = Contract(address=address) assert contract.address == address - assert len(web3.eth.get_code(contract.address)) > 0 + assert len(w3.eth.get_code(contract.address)) > 0 return contract @pytest.fixture() -def math_contract(web3, MathContract, address_conversion_func): - return deploy(web3, MathContract, address_conversion_func) +def math_contract(w3, MathContract, address_conversion_func): + return deploy(w3, MathContract, address_conversion_func) @pytest.fixture() -def string_contract(web3, StringContract, address_conversion_func): - return deploy(web3, StringContract, address_conversion_func, args=["Caqalai"]) +def string_contract(w3, StringContract, address_conversion_func): + return deploy(w3, StringContract, address_conversion_func, args=["Caqalai"]) @pytest.fixture() -def fallback_function_contract(web3, FallbackFunctionContract, address_conversion_func): - return deploy(web3, FallbackFunctionContract, address_conversion_func) +def fallback_function_contract(w3, FallbackFunctionContract, address_conversion_func): + return deploy(w3, FallbackFunctionContract, address_conversion_func) @pytest.fixture() -def arrays_contract(web3, ArraysContract, address_conversion_func): +def arrays_contract(w3, ArraysContract, address_conversion_func): # bytes_32 = [keccak('0'), keccak('1')] bytes32_array = [ b'\x04HR\xb2\xa6p\xad\xe5@~x\xfb(c\xc5\x1d\xe9\xfc\xb9eB\xa0q\x86\xfe:\xed\xa6\xbb\x8a\x11m', # noqa: E501 b'\xc8\x9e\xfd\xaaT\xc0\xf2\x0cz\xdfa(\x82\xdf\tP\xf5\xa9Qc~\x03\x07\xcd\xcbLg/)\x8b\x8b\xc6', # noqa: E501 ] byte_arr = [b'\xff', b'\xff', b'\xff', b'\xff'] - return deploy(web3, ArraysContract, address_conversion_func, args=[bytes32_array, byte_arr]) + return deploy(w3, ArraysContract, address_conversion_func, args=[bytes32_array, byte_arr]) @pytest.fixture() -def payable_tester_contract(web3, PayableTesterContract, address_conversion_func): - return deploy(web3, PayableTesterContract, address_conversion_func) +def payable_tester_contract(w3, PayableTesterContract, address_conversion_func): + return deploy(w3, PayableTesterContract, address_conversion_func) @pytest.fixture() -def receive_function_contract(web3, ReceiveFunctionContract, address_conversion_func): - return deploy(web3, ReceiveFunctionContract, address_conversion_func) +def receive_function_contract(w3, ReceiveFunctionContract, address_conversion_func): + return deploy(w3, ReceiveFunctionContract, address_conversion_func) -def test_transacting_with_contract_no_arguments(web3, math_contract, transact, call): +def test_transacting_with_contract_no_arguments(w3, math_contract, transact, call): initial_value = call(contract=math_contract, contract_function='counter') txn_hash = transact(contract=math_contract, contract_function='increment') - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=math_contract, @@ -79,7 +79,7 @@ def test_transacting_with_contract_no_arguments(web3, math_contract, transact, c def test_transact_not_sending_ether_to_nonpayable_function( - web3, + w3, payable_tester_contract, transact, call): @@ -89,7 +89,7 @@ def test_transact_not_sending_ether_to_nonpayable_function( assert initial_value is False txn_hash = transact(contract=payable_tester_contract, contract_function='doNoValueCall') - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=payable_tester_contract, @@ -99,7 +99,7 @@ def test_transact_not_sending_ether_to_nonpayable_function( def test_transact_sending_ether_to_nonpayable_function( - web3, + w3, payable_tester_contract, transact, call): @@ -111,7 +111,7 @@ def test_transact_sending_ether_to_nonpayable_function( txn_hash = transact(contract=payable_tester_contract, contract_function='doNoValueCall', tx_params={'value': 1}) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=payable_tester_contract, @@ -127,7 +127,7 @@ def test_transact_sending_ether_to_nonpayable_function( (tuple(), {'amt': 5}), ), ) -def test_transacting_with_contract_with_arguments(web3, +def test_transacting_with_contract_with_arguments(w3, math_contract, transact, call, @@ -141,7 +141,7 @@ def test_transacting_with_contract_with_arguments(web3, func_args=transact_args, func_kwargs=transact_kwargs) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=math_contract, @@ -150,41 +150,41 @@ def test_transacting_with_contract_with_arguments(web3, assert final_value - initial_value == 5 -def test_deploy_when_default_account_is_set(web3, +def test_deploy_when_default_account_is_set(w3, wait_for_transaction, STRING_CONTRACT): - web3.eth.default_account = web3.eth.accounts[1] - assert web3.eth.default_account is not empty + w3.eth.default_account = w3.eth.accounts[1] + assert w3.eth.default_account is not empty - StringContract = web3.eth.contract(**STRING_CONTRACT) + StringContract = w3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.constructor("Caqalai").transact() - web3.eth.wait_for_transaction_receipt(deploy_txn) - txn_after = web3.eth.get_transaction(deploy_txn) - assert txn_after['from'] == web3.eth.default_account + w3.eth.wait_for_transaction_receipt(deploy_txn) + txn_after = w3.eth.get_transaction(deploy_txn) + assert txn_after['from'] == w3.eth.default_account -def test_transact_when_default_account_is_set(web3, +def test_transact_when_default_account_is_set(w3, wait_for_transaction, math_contract, transact): - web3.eth.default_account = web3.eth.accounts[1] - assert web3.eth.default_account is not empty + w3.eth.default_account = w3.eth.accounts[1] + assert w3.eth.default_account is not empty txn_hash = transact(contract=math_contract, contract_function='increment') - wait_for_transaction(web3, txn_hash) - txn_after = web3.eth.get_transaction(txn_hash) - assert txn_after['from'] == web3.eth.default_account + wait_for_transaction(w3, txn_hash) + txn_after = w3.eth.get_transaction(txn_hash) + assert txn_after['from'] == w3.eth.default_account -def test_transacting_with_contract_with_string_argument(web3, string_contract, transact, call): +def test_transacting_with_contract_with_string_argument(w3, string_contract, transact, call): # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = transact(contract=string_contract, contract_function='setValue', func_args=["ÄLÄMÖLÖ".encode('utf8')]) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=string_contract, @@ -193,7 +193,7 @@ def test_transacting_with_contract_with_string_argument(web3, string_contract, t assert final_value == "ÄLÄMÖLÖ" -def test_transacting_with_contract_with_bytes32_array_argument(web3, +def test_transacting_with_contract_with_bytes32_array_argument(w3, arrays_contract, transact, call): @@ -206,7 +206,7 @@ def test_transacting_with_contract_with_bytes32_array_argument(web3, txn_hash = transact(contract=arrays_contract, contract_function="setBytes32Value", func_args=[new_bytes32_array]) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=arrays_contract, @@ -214,12 +214,12 @@ def test_transacting_with_contract_with_bytes32_array_argument(web3, assert final_value == new_bytes32_array -def test_transacting_with_contract_with_byte_array_argument(web3, arrays_contract, transact, call): +def test_transacting_with_contract_with_byte_array_argument(w3, arrays_contract, transact, call): new_byte_array = [b'\x03', b'\x03', b'\x03', b'\x03', b'\x03', b'\x03'] txn_hash = transact(contract=arrays_contract, contract_function='setByteValue', func_args=[new_byte_array]) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=arrays_contract, @@ -227,20 +227,20 @@ def test_transacting_with_contract_with_byte_array_argument(web3, arrays_contrac assert final_value == new_byte_array -def test_transacting_with_contract_respects_explicit_gas(web3, +def test_transacting_with_contract_respects_explicit_gas(w3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call, transact): - skip_if_testrpc(web3) + skip_if_testrpc(w3) - wait_for_block(web3) + wait_for_block(w3) - StringContract = web3.eth.contract(**STRING_CONTRACT) + StringContract = w3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.constructor("Caqalai").transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn, 30) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) @@ -250,31 +250,31 @@ def test_transacting_with_contract_respects_explicit_gas(web3, contract_function='setValue', func_args=[to_bytes(text="ÄLÄMÖLÖ")], tx_kwargs={'gas': 200000}) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash, 30) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash, 30) assert txn_receipt is not None final_value = call(contract=string_contract, contract_function='getValue') assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ") - txn = web3.eth.get_transaction(txn_hash) + txn = w3.eth.get_transaction(txn_hash) assert txn['gas'] == 200000 -def test_auto_gas_computation_when_transacting(web3, +def test_auto_gas_computation_when_transacting(w3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call, transact): - skip_if_testrpc(web3) + skip_if_testrpc(w3) - wait_for_block(web3) + wait_for_block(w3) - StringContract = web3.eth.contract(**STRING_CONTRACT) + StringContract = w3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.constructor("Caqalai").transact() - deploy_receipt = web3.eth.wait_for_transaction_receipt(deploy_txn, 30) + deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) @@ -285,22 +285,22 @@ def test_auto_gas_computation_when_transacting(web3, txn_hash = transact(contract=string_contract, contract_function="setValue", func_args=[to_bytes(text="ÄLÄMÖLÖ")]) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash, 30) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash, 30) assert txn_receipt is not None final_value = call(contract=string_contract, contract_function='getValue') assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ") - txn = web3.eth.get_transaction(txn_hash) + txn = w3.eth.get_transaction(txn_hash) assert txn['gas'] == gas_estimate + 100000 -def test_fallback_transacting_with_contract(web3, fallback_function_contract, call): +def test_fallback_transacting_with_contract(w3, fallback_function_contract, call): initial_value = call(contract=fallback_function_contract, contract_function='getData') txn_hash = fallback_function_contract.fallback.transact() - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt is not None final_value = call(contract=fallback_function_contract, diff --git a/tests/core/contracts/test_contract_util_functions.py b/tests/core/contracts/test_contract_util_functions.py index 382a0e4d6f..af252824cb 100644 --- a/tests/core/contracts/test_contract_util_functions.py +++ b/tests/core/contracts/test_contract_util_functions.py @@ -8,6 +8,6 @@ # This test is necessary because transaction calls allow negative block indexes, although # get_block() does not allow negative block identifiers. Support for negative block identifier # will likely be removed in v5. -def test_parse_block_identifier_int(web3): - last_num = web3.eth.get_block('latest').number - assert 0 == parse_block_identifier_int(web3, -1 - last_num) +def test_parse_block_identifier_int(w3): + last_num = w3.eth.get_block('latest').number + assert 0 == parse_block_identifier_int(w3, -1 - last_num) diff --git a/tests/core/contracts/test_extracting_event_data.py b/tests/core/contracts/test_extracting_event_data.py index 3f80248f70..42a5744972 100644 --- a/tests/core/contracts/test_extracting_event_data.py +++ b/tests/core/contracts/test_extracting_event_data.py @@ -24,18 +24,18 @@ @pytest.fixture() -def Emitter(web3, EMITTER): - return web3.eth.contract(**EMITTER) +def Emitter(w3, EMITTER): + return w3.eth.contract(**EMITTER) @pytest.fixture() -def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) +def emitter(w3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): + wait_for_block(w3) deploy_txn_hash = Emitter.constructor().transact({'gas': 10000000}) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == Emitter.bytecode_runtime _emitter = Emitter(address=contract_address) assert _emitter.address == contract_address @@ -43,26 +43,26 @@ def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_convers @pytest.fixture() -def EventContract(web3, EVENT_CONTRACT): - return web3.eth.contract(**EVENT_CONTRACT) +def EventContract(w3, EVENT_CONTRACT): + return w3.eth.contract(**EVENT_CONTRACT) @pytest.fixture() def event_contract( - web3, + w3, EventContract, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) + wait_for_block(w3) deploy_txn_hash = EventContract.constructor().transact({ - 'from': web3.eth.coinbase, 'gas': 1000000 + 'from': w3.eth.coinbase, 'gas': 1000000 }) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == EventContract.bytecode_runtime event_contract = EventContract(address=contract_address) assert event_contract.address == contract_address @@ -70,26 +70,26 @@ def event_contract( @pytest.fixture() -def IndexedEventContract(web3, INDEXED_EVENT_CONTRACT): - return web3.eth.contract(**INDEXED_EVENT_CONTRACT) +def IndexedEventContract(w3, INDEXED_EVENT_CONTRACT): + return w3.eth.contract(**INDEXED_EVENT_CONTRACT) @pytest.fixture() def indexed_event_contract( - web3, + w3, IndexedEventContract, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) + wait_for_block(w3) deploy_txn_hash = IndexedEventContract.constructor().transact({ - 'from': web3.eth.coinbase, 'gas': 1000000 + 'from': w3.eth.coinbase, 'gas': 1000000 }) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == IndexedEventContract.bytecode_runtime indexed_event_contract = IndexedEventContract(address=contract_address) assert indexed_event_contract.address == contract_address @@ -98,7 +98,7 @@ def indexed_event_contract( @pytest.fixture() def dup_txn_receipt( - web3, + w3, indexed_event_contract, wait_for_transaction, event_contract): @@ -106,11 +106,11 @@ def dup_txn_receipt( emitter_fn = indexed_event_contract.functions.logTwoEvents txn_hash = emitter_fn(12345).transact() - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) event_contract_fn = event_contract.functions.logTwoEvents dup_txn_hash = event_contract_fn(12345).transact() - return wait_for_transaction(web3, dup_txn_hash) + return wait_for_transaction(w3, dup_txn_hash) @pytest.mark.parametrize( @@ -150,7 +150,7 @@ def dup_txn_receipt( ), ) ) -def test_event_data_extraction(web3, +def test_event_data_extraction(w3, emitter, wait_for_transaction, emitter_log_topics, @@ -162,7 +162,7 @@ def test_event_data_extraction(web3, emitter_fn = emitter.functions[contract_fn] event_id = getattr(emitter_event_ids, event_name) txn_hash = emitter_fn(event_id, *call_args).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] @@ -177,7 +177,7 @@ def test_event_data_extraction(web3, else: assert event_topic in log_entry['topics'] - event_data = get_event_data(web3.codec, event_abi, log_entry) + event_data = get_event_data(w3.codec, event_abi, log_entry) assert event_data['args'] == expected_args assert event_data['blockHash'] == txn_receipt['blockHash'] @@ -205,7 +205,7 @@ def test_event_data_extraction(web3, ), ) ) -def test_event_data_extraction_bytes(web3, +def test_event_data_extraction_bytes(w3, emitter, wait_for_transaction, emitter_log_topics, @@ -213,7 +213,7 @@ def test_event_data_extraction_bytes(web3, expected_args): emitter_fn = emitter.functions.logListArgs txn_hash = emitter_fn(*call_args).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] @@ -225,7 +225,7 @@ def test_event_data_extraction_bytes(web3, assert event_topic in log_entry['topics'] - event_data = get_event_data(web3.codec, event_abi, log_entry) + event_data = get_event_data(w3.codec, event_abi, log_entry) assert event_data['args'] == expected_args assert event_data['blockHash'] == txn_receipt['blockHash'] @@ -235,7 +235,7 @@ def test_event_data_extraction_bytes(web3, assert event_data['event'] == event_name -def test_event_data_extraction_bytes_with_warning(web3, +def test_event_data_extraction_bytes_with_warning(w3, emitter, wait_for_transaction, emitter_log_topics): @@ -244,7 +244,7 @@ def test_event_data_extraction_bytes_with_warning(web3, match='in v6 it will be invalid to pass a hex string without the "0x" prefix' ): txn_hash = emitter.functions.logListArgs(['13'], ['54']).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] @@ -256,7 +256,7 @@ def test_event_data_extraction_bytes_with_warning(web3, assert event_topic in log_entry['topics'] - event_data = get_event_data(web3.codec, event_abi, log_entry) + event_data = get_event_data(w3.codec, event_abi, log_entry) expected_args = { 'arg0': b']\x0b\xf6sp\xbe\xa2L\xa9is\xe4\xab\xb7\xfa+nVJpgt\xa7\x8f:\xa4\x9f\xdb\x93\xf0\x8f\xae', # noqa: E501 'arg1': [b'T\x00'] @@ -288,7 +288,7 @@ def test_event_data_extraction_bytes_strict_with_errors(strict_emitter, emitter_fn(*call_args).transact() -def test_dynamic_length_argument_extraction(web3, +def test_dynamic_length_argument_extraction(w3, emitter, wait_for_transaction, emitter_log_topics, @@ -296,7 +296,7 @@ def test_dynamic_length_argument_extraction(web3, string_0 = "this-is-the-first-string-which-exceeds-32-bytes-in-length" string_1 = "this-is-the-second-string-which-exceeds-32-bytes-in-length" txn_hash = emitter.functions.logDynamicArgs(string_0, string_1).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] @@ -306,10 +306,10 @@ def test_dynamic_length_argument_extraction(web3, event_topic = emitter_log_topics.LogDynamicArgs assert event_topic in log_entry['topics'] - string_0_topic = web3.keccak(text=string_0) + string_0_topic = w3.keccak(text=string_0) assert string_0_topic in log_entry['topics'] - event_data = get_event_data(web3.codec, event_abi, log_entry) + event_data = get_event_data(w3.codec, event_abi, log_entry) expected_args = { "arg0": string_0_topic, @@ -576,7 +576,7 @@ def test_argument_extraction_strict_bytes_types(w3_strict_abi, ) ) def test_event_rich_log( - web3, + w3, emitter, emitter_event_ids, wait_for_transaction, @@ -595,7 +595,7 @@ def test_event_rich_log( # Some tests do not rely on the event_id. Rather than changing this test too much, # bypass this here and just call the function with the provided args. txn_hash = emitter_fn(*call_args).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) event_instance = emitter.events[event_name]() @@ -626,14 +626,14 @@ def test_event_rich_log( @pytest.mark.parametrize('process_receipt', (True, False)) def test_event_rich_log_with_byte_args( - web3, + w3, emitter, emitter_event_ids, wait_for_transaction, process_receipt): txn_hash = emitter.functions.logListArgs([b'13'], [b'54']).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) event_instance = emitter.events.LogListArgs() @@ -662,7 +662,7 @@ def test_event_rich_log_with_byte_args( def test_receipt_processing_with_discard_flag( - web3, + w3, event_contract, indexed_event_contract, dup_txn_receipt, @@ -675,7 +675,7 @@ def test_receipt_processing_with_discard_flag( def test_receipt_processing_with_ignore_flag( - web3, + w3, event_contract, indexed_event_contract, dup_txn_receipt, @@ -704,7 +704,7 @@ def test_receipt_processing_with_ignore_flag( def test_receipt_processing_with_warn_flag( - web3, + w3, indexed_event_contract, dup_txn_receipt): @@ -716,7 +716,7 @@ def test_receipt_processing_with_warn_flag( def test_receipt_processing_with_strict_flag( - web3, + w3, indexed_event_contract, dup_txn_receipt): @@ -727,7 +727,7 @@ def test_receipt_processing_with_strict_flag( def test_receipt_processing_with_invalid_flag( - web3, + w3, indexed_event_contract, dup_txn_receipt): @@ -738,7 +738,7 @@ def test_receipt_processing_with_invalid_flag( def test_receipt_processing_with_no_flag( - web3, + w3, indexed_event_contract, dup_txn_receipt): @@ -750,7 +750,7 @@ def test_receipt_processing_with_no_flag( def test_single_log_processing_with_errors( - web3, + w3, indexed_event_contract, dup_txn_receipt): event_instance = indexed_event_contract.events.LogSingleWithIndex() @@ -759,12 +759,12 @@ def test_single_log_processing_with_errors( event_instance.processLog(dup_txn_receipt['logs'][0]) -def test_get_all_entries_with_nested_tuple_event(web3, emitter): +def test_get_all_entries_with_nested_tuple_event(w3, emitter): struct_args_filter = emitter.events.LogStructArgs.createFilter(fromBlock=0) tx_hash = emitter.functions.logStruct(1, (2, 3, (4, ))).transact({'gas': 100000}) - web3.eth.wait_for_transaction_receipt(tx_hash) - txn_receipt = web3.eth.get_transaction_receipt(tx_hash) + w3.eth.wait_for_transaction_receipt(tx_hash) + txn_receipt = w3.eth.get_transaction_receipt(tx_hash) entries = struct_args_filter.get_all_entries() diff --git a/tests/core/contracts/test_extracting_event_data_old.py b/tests/core/contracts/test_extracting_event_data_old.py index 1fae5c406d..14369dcc1a 100644 --- a/tests/core/contracts/test_extracting_event_data_old.py +++ b/tests/core/contracts/test_extracting_event_data_old.py @@ -10,18 +10,18 @@ @pytest.fixture() -def Emitter(web3, EMITTER): - return web3.eth.contract(**EMITTER) +def Emitter(w3, EMITTER): + return w3.eth.contract(**EMITTER) @pytest.fixture() -def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) +def emitter(w3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): + wait_for_block(w3) deploy_txn_hash = Emitter.constructor().transact({'gas': 10000000}) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == Emitter.bytecode_runtime _emitter = Emitter(address=contract_address) assert _emitter.address == contract_address @@ -65,7 +65,7 @@ def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_convers ), ) ) -def test_event_data_extraction(web3, +def test_event_data_extraction(w3, emitter, wait_for_transaction, emitter_log_topics, @@ -77,7 +77,7 @@ def test_event_data_extraction(web3, function = getattr(emitter.functions, contract_fn) event_id = getattr(emitter_event_ids, event_name) txn_hash = function(event_id, *call_args).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] @@ -92,7 +92,7 @@ def test_event_data_extraction(web3, else: assert event_topic in log_entry['topics'] - event_data = get_event_data(web3.codec, event_abi, log_entry) + event_data = get_event_data(w3.codec, event_abi, log_entry) assert event_data['args'] == expected_args assert event_data['blockHash'] == txn_receipt['blockHash'] @@ -102,7 +102,7 @@ def test_event_data_extraction(web3, assert event_data['event'] == event_name -def test_dynamic_length_argument_extraction(web3, +def test_dynamic_length_argument_extraction(w3, emitter, wait_for_transaction, emitter_log_topics, @@ -110,7 +110,7 @@ def test_dynamic_length_argument_extraction(web3, string_0 = "this-is-the-first-string-which-exceeds-32-bytes-in-length" string_1 = "this-is-the-second-string-which-exceeds-32-bytes-in-length" txn_hash = emitter.functions.logDynamicArgs(string_0, string_1).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] @@ -120,10 +120,10 @@ def test_dynamic_length_argument_extraction(web3, event_topic = emitter_log_topics.LogDynamicArgs assert event_topic in log_entry['topics'] - string_0_topic = web3.keccak(text=string_0) + string_0_topic = w3.keccak(text=string_0) assert string_0_topic in log_entry['topics'] - event_data = get_event_data(web3.codec, event_abi, log_entry) + event_data = get_event_data(w3.codec, event_abi, log_entry) expected_args = { "arg0": string_0_topic, diff --git a/tests/core/contracts/test_implicit_contract.py b/tests/core/contracts/test_implicit_contract.py index 6701c0f175..1cc864a38c 100644 --- a/tests/core/contracts/test_implicit_contract.py +++ b/tests/core/contracts/test_implicit_contract.py @@ -10,20 +10,20 @@ @pytest.fixture() -def math_contract(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME, address_conversion_func): +def math_contract(w3, MATH_ABI, MATH_CODE, MATH_RUNTIME, address_conversion_func): # Deploy math contract # NOTE Must use non-specialized contract factory or else deploy() doesn't work - MathContract = web3.eth.contract( + MathContract = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) tx_hash = MathContract.constructor().transact() - tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash) + tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) math_address = address_conversion_func(tx_receipt['contractAddress']) # Return interactive contract instance at deployed address # TODO Does parent class not implement 'deploy()' for a reason? - MathContract = web3.eth.contract( + MathContract = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, @@ -36,9 +36,9 @@ def math_contract(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME, address_conversion_fu @pytest.fixture() -def get_transaction_count(web3): +def get_transaction_count(w3): def get_transaction_count(blocknum_or_label): - block = web3.eth.get_block(blocknum_or_label) + block = w3.eth.get_block(blocknum_or_label) # Return the blocknum if we requested this via labels # so we can directly query the block next time (using the same API call) # Either way, return the number of transactions in the given block @@ -62,7 +62,7 @@ def test_implicitcontract_call_default(math_contract, get_transaction_count): assert get_transaction_count("pending") == (blocknum, 0) -def test_implicitcontract_transact_default(web3, math_contract, get_transaction_count): +def test_implicitcontract_transact_default(w3, math_contract, get_transaction_count): # Use to verify correct operation later on with pytest.warns(DeprecationWarning, match='deprecated in favor of classic contract syntax'): start_count = math_contract.counter() diff --git a/tests/core/eth-module/conftest.py b/tests/core/eth-module/conftest.py index 1da778510f..de445279c3 100644 --- a/tests/core/eth-module/conftest.py +++ b/tests/core/eth-module/conftest.py @@ -8,13 +8,13 @@ def account_password(): @pytest.fixture -def extra_accounts(web3, account_password): - num_accounts_to_create = 10 - len(web3.eth.accounts) +def extra_accounts(w3, account_password): + num_accounts_to_create = 10 - len(w3.eth.accounts) for i in range(num_accounts_to_create): - web3.personal.newAccount(account_password) + w3.personal.newAccount(account_password) - return web3.eth.accounts + return w3.eth.accounts CONTRACT_CODE = b"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000000000000000000000000000000000000000000000009004806316216f391461007657806361bc221a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d578063dcf537b11461014057610074565b005b610083600480505061016c565b6040518082815260200191505060405180910390f35b6100a6600480505061017f565b6040518082815260200191505060405180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea565b6040518082815260200191505060405180910390f35b61012a6004805050610201565b6040518082815260200191505060405180910390f35b6101566004808035906020019091905050610217565b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90565b60006000505481565b6000816000600082828250540192505081905550600060005054905080507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b60006007820290508050809050610229565b91905056" # noqa: E501 diff --git a/tests/core/eth-module/test_accounts.py b/tests/core/eth-module/test_accounts.py index 3c2056eb4a..34d24b086d 100644 --- a/tests/core/eth-module/test_accounts.py +++ b/tests/core/eth-module/test_accounts.py @@ -75,9 +75,9 @@ def web3js_password(): @pytest.fixture(params=['instance', 'class']) -def acct(request, web3): +def acct(request, w3): if request.param == 'instance': - return web3.eth.account + return w3.eth.account elif request.param == 'class': return Account raise Exception('Unreachable!') diff --git a/tests/core/eth-module/test_block_api.py b/tests/core/eth-module/test_block_api.py index 2ea7d0a8dc..c26b5a2e30 100644 --- a/tests/core/eth-module/test_block_api.py +++ b/tests/core/eth-module/test_block_api.py @@ -9,30 +9,30 @@ @pytest.fixture(autouse=True) -def wait_for_first_block(web3, wait_for_block): - wait_for_block(web3) +def wait_for_first_block(w3, wait_for_block): + wait_for_block(w3) -def test_uses_default_block(web3, extra_accounts, +def test_uses_default_block(w3, extra_accounts, wait_for_transaction): - assert(web3.eth.default_block == 'latest') - web3.eth.default_block = web3.eth.block_number - assert(web3.eth.default_block == web3.eth.block_number) + assert(w3.eth.default_block == 'latest') + w3.eth.default_block = w3.eth.block_number + assert(w3.eth.default_block == w3.eth.block_number) -def test_uses_defaultBlock_with_warning(web3, extra_accounts, +def test_uses_defaultBlock_with_warning(w3, extra_accounts, wait_for_transaction): with pytest.warns(DeprecationWarning): - assert web3.eth.defaultBlock == 'latest' + assert w3.eth.defaultBlock == 'latest' with pytest.warns(DeprecationWarning): - web3.eth.defaultBlock = web3.eth.block_number + w3.eth.defaultBlock = w3.eth.block_number with pytest.warns(DeprecationWarning): - assert(web3.eth.defaultBlock == web3.eth.block_number) + assert(w3.eth.defaultBlock == w3.eth.block_number) -def test_get_block_formatters_with_null_values(web3): +def test_get_block_formatters_with_null_values(w3): null_values_block = { 'baseFeePerGas': None, 'extraData': None, @@ -58,7 +58,7 @@ def test_get_block_formatters_with_null_values(web3): RPC.eth_getBlockByNumber: lambda *_: null_values_block, }) - web3.middleware_onion.inject(result_middleware, 'result_middleware', layer=0) + w3.middleware_onion.inject(result_middleware, 'result_middleware', layer=0) - received_block = web3.eth.get_block('pending') + received_block = w3.eth.get_block('pending') assert received_block == null_values_block diff --git a/tests/core/eth-module/test_default_account_api.py b/tests/core/eth-module/test_default_account_api.py index 6f544af8be..c8cf76bd52 100644 --- a/tests/core/eth-module/test_default_account_api.py +++ b/tests/core/eth-module/test_default_account_api.py @@ -2,75 +2,75 @@ @pytest.fixture(autouse=True) -def wait_for_first_block(web3, wait_for_block): - wait_for_block(web3) +def wait_for_first_block(w3, wait_for_block): + wait_for_block(w3) -def test_uses_default_account_when_set(web3, extra_accounts, +def test_uses_default_account_when_set(w3, extra_accounts, wait_for_transaction): - web3.eth.default_account = extra_accounts[2] - assert web3.eth.default_account == extra_accounts[2] + w3.eth.default_account = extra_accounts[2] + assert w3.eth.default_account == extra_accounts[2] - txn_hash = web3.eth.send_transaction({ + txn_hash = w3.eth.send_transaction({ "to": extra_accounts[1], "value": 1234, }) - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) - txn = web3.eth.get_transaction(txn_hash) + txn = w3.eth.get_transaction(txn_hash) assert txn['from'] == extra_accounts[2] -def test_uses_defaultAccount_when_set_with_warning(web3, extra_accounts, +def test_uses_defaultAccount_when_set_with_warning(w3, extra_accounts, wait_for_transaction): with pytest.warns(DeprecationWarning): - web3.eth.defaultAccount = extra_accounts[2] + w3.eth.defaultAccount = extra_accounts[2] with pytest.warns(DeprecationWarning): - assert web3.eth.defaultAccount == extra_accounts[2] + assert w3.eth.defaultAccount == extra_accounts[2] - txn_hash = web3.eth.send_transaction({ + txn_hash = w3.eth.send_transaction({ "to": extra_accounts[1], "value": 1234, }) - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) - txn = web3.eth.get_transaction(txn_hash) + txn = w3.eth.get_transaction(txn_hash) assert txn['from'] == extra_accounts[2] -def test_uses_given_from_address_when_provided(web3, extra_accounts, +def test_uses_given_from_address_when_provided(w3, extra_accounts, wait_for_transaction): - web3.eth.default_account = extra_accounts[2] - txn_hash = web3.eth.send_transaction({ + w3.eth.default_account = extra_accounts[2] + txn_hash = w3.eth.send_transaction({ "from": extra_accounts[5], "to": extra_accounts[1], "value": 1234, }) - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) - txn = web3.eth.get_transaction(txn_hash) + txn = w3.eth.get_transaction(txn_hash) assert txn['from'] == extra_accounts[5] -def test_uses_given_from_address_when_provided_with_warning(web3, extra_accounts, +def test_uses_given_from_address_when_provided_with_warning(w3, extra_accounts, wait_for_transaction): with pytest.warns(DeprecationWarning): - web3.eth.defaultAccount = extra_accounts[2] + w3.eth.defaultAccount = extra_accounts[2] with pytest.warns(DeprecationWarning): - assert web3.eth.defaultAccount == extra_accounts[2] + assert w3.eth.defaultAccount == extra_accounts[2] - txn_hash = web3.eth.send_transaction({ + txn_hash = w3.eth.send_transaction({ "from": extra_accounts[5], "to": extra_accounts[1], "value": 1234, }) - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) - txn = web3.eth.get_transaction(txn_hash) + txn = w3.eth.get_transaction(txn_hash) assert txn['from'] == extra_accounts[5] diff --git a/tests/core/eth-module/test_eth_contract.py b/tests/core/eth-module/test_eth_contract.py index 50a2ed9e46..fdb0a4f7e2 100644 --- a/tests/core/eth-module/test_eth_contract.py +++ b/tests/core/eth-module/test_eth_contract.py @@ -26,18 +26,18 @@ ((), {'address': NON_CHECKSUM_ADDRESS}, ValueError), ) ) -def test_contract_address_validation(web3, args, kwargs, expected): +def test_contract_address_validation(w3, args, kwargs, expected): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): - web3.eth.contract(*args, **kwargs) + w3.eth.contract(*args, **kwargs) return # run without errors - web3.eth.contract(*args, **kwargs) + w3.eth.contract(*args, **kwargs) -def test_set_contract_factory(web3): +def test_set_contract_factory(w3): factoryClass = Mock() - web3.eth.set_contract_factory(factoryClass) - web3.eth.contract(contract_name='myname') - factoryClass.factory.assert_called_once_with(web3, contract_name='myname') + w3.eth.set_contract_factory(factoryClass) + w3.eth.contract(contract_name='myname') + factoryClass.factory.assert_called_once_with(w3, contract_name='myname') diff --git a/tests/core/eth-module/test_eth_mining.py b/tests/core/eth-module/test_eth_mining.py index cd4f831eb9..9daf8205ba 100644 --- a/tests/core/eth-module/test_eth_mining.py +++ b/tests/core/eth-module/test_eth_mining.py @@ -1,9 +1,9 @@ -def test_mining_property_tester(web3): - assert web3.eth.mining is False +def test_mining_property_tester(w3): + assert w3.eth.mining is False -def test_mining_property_ipc_and_rpc(web3, wait_for_miner_start, skip_if_testrpc): - skip_if_testrpc(web3) +def test_mining_property_ipc_and_rpc(w3, wait_for_miner_start, skip_if_testrpc): + skip_if_testrpc(w3) - wait_for_miner_start(web3) - assert web3.eth.mining is True + wait_for_miner_start(w3) + assert w3.eth.mining is True diff --git a/tests/core/eth-module/test_eth_properties.py b/tests/core/eth-module/test_eth_properties.py index 596a853539..9f89391ad6 100644 --- a/tests/core/eth-module/test_eth_properties.py +++ b/tests/core/eth-module/test_eth_properties.py @@ -1,19 +1,19 @@ import pytest -def test_eth_protocol_version(web3): - assert web3.eth.protocol_version == '63' +def test_eth_protocol_version(w3): + assert w3.eth.protocol_version == '63' -def test_eth_protocolVersion(web3): +def test_eth_protocolVersion(w3): with pytest.warns(DeprecationWarning): - assert web3.eth.protocolVersion == '63' + assert w3.eth.protocolVersion == '63' -def test_eth_chain_id(web3): - assert web3.eth.chain_id == 61 +def test_eth_chain_id(w3): + assert w3.eth.chain_id == 61 -def test_eth_chainId(web3): +def test_eth_chainId(w3): with pytest.warns(DeprecationWarning): - assert web3.eth.chainId == 61 + assert w3.eth.chainId == 61 diff --git a/tests/core/eth-module/test_gas_pricing.py b/tests/core/eth-module/test_gas_pricing.py index b93d668a2b..abecffd20c 100644 --- a/tests/core/eth-module/test_gas_pricing.py +++ b/tests/core/eth-module/test_gas_pricing.py @@ -4,48 +4,48 @@ ) -def test_get_set_gas_price(web3): - assert web3.eth.gas_price > 0 +def test_get_set_gas_price(w3): + assert w3.eth.gas_price > 0 -def test_get_set_gasPrice(web3): +def test_get_set_gasPrice(w3): with pytest.warns(DeprecationWarning): - assert web3.eth.gasPrice > 0 + assert w3.eth.gasPrice > 0 -def test_no_gas_price_strategy_returns_none(web3): - assert web3.eth.generate_gas_price() is None +def test_no_gas_price_strategy_returns_none(w3): + assert w3.eth.generate_gas_price() is None -def test_generateGasPrice_deprecated(web3): +def test_generateGasPrice_deprecated(w3): with pytest.warns(DeprecationWarning, match='generateGasPrice is deprecated in favor of generate_gas_price'): - gas_price = web3.eth.generateGasPrice() + gas_price = w3.eth.generateGasPrice() assert gas_price is None -def test_set_gas_price_strategy(web3): - def my_gas_price_strategy(web3, transaction_params): +def test_set_gas_price_strategy(w3): + def my_gas_price_strategy(w3, transaction_params): return 5 - web3.eth.set_gas_price_strategy(my_gas_price_strategy) - assert web3.eth.generate_gas_price() == 5 + w3.eth.set_gas_price_strategy(my_gas_price_strategy) + assert w3.eth.generate_gas_price() == 5 -def test_setGasPriceStrategy_deprecated(web3): +def test_setGasPriceStrategy_deprecated(w3): my_gas_price_strategy = Mock(return_value=5) with pytest.warns(DeprecationWarning, match="setGasPriceStrategy is deprecated in favor of " "set_gas_price_strategy"): - web3.eth.setGasPriceStrategy(my_gas_price_strategy) - assert web3.eth.generate_gas_price() == 5 + w3.eth.setGasPriceStrategy(my_gas_price_strategy) + assert w3.eth.generate_gas_price() == 5 -def test_gas_price_strategy_calls(web3): +def test_gas_price_strategy_calls(w3): transaction = { 'to': '0x0', 'value': 1000000000 } my_gas_price_strategy = Mock(return_value=5) - web3.eth.set_gas_price_strategy(my_gas_price_strategy) - assert web3.eth.generate_gas_price(transaction) == 5 - my_gas_price_strategy.assert_called_once_with(web3, transaction) + w3.eth.set_gas_price_strategy(my_gas_price_strategy) + assert w3.eth.generate_gas_price(transaction) == 5 + my_gas_price_strategy.assert_called_once_with(w3, transaction) diff --git a/tests/core/eth-module/test_iban.py b/tests/core/eth-module/test_iban.py index 7e4068cea6..71580bb5a3 100644 --- a/tests/core/eth-module/test_iban.py +++ b/tests/core/eth-module/test_iban.py @@ -14,8 +14,8 @@ ), ) ) -def test_createIndirect(value, expected, web3): - actual = web3.eth.iban.createIndirect(value).toString() +def test_createIndirect(value, expected, w3): + actual = w3.eth.iban.createIndirect(value).toString() assert actual == expected @@ -56,14 +56,14 @@ def test_createIndirect(value, expected, web3): ), ), ) -def test_fromAddress(value, expected, web3): +def test_fromAddress(value, expected, w3): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): - web3.eth.iban.fromAddress(value).toString() + w3.eth.iban.fromAddress(value).toString() return - actual = web3.eth.iban.fromAddress(value).toString() + actual = w3.eth.iban.fromAddress(value).toString() assert actual == expected @@ -140,11 +140,11 @@ def test_fromAddress(value, expected, web3): ), ), ) -def test_isValid(value, expected, web3): - actual = web3.eth.iban.isValid(value) +def test_isValid(value, expected, w3): + actual = w3.eth.iban.isValid(value) assert actual is expected - iban = web3.eth.iban(value) + iban = w3.eth.iban(value) assert iban.isValid() is expected @@ -157,6 +157,6 @@ def test_isValid(value, expected, web3): ), ) ) -def test_toAddress(value, expected, web3): - actual = web3.eth.iban(value).address() +def test_toAddress(value, expected, w3): + actual = w3.eth.iban(value).address() assert actual == expected diff --git a/tests/core/eth-module/test_poa.py b/tests/core/eth-module/test_poa.py index 8be9346dfe..ecb60f84d0 100644 --- a/tests/core/eth-module/test_poa.py +++ b/tests/core/eth-module/test_poa.py @@ -11,40 +11,40 @@ # In the spec, a block with extra data longer than 32 bytes is invalid -def test_long_extra_data(web3): +def test_long_extra_data(w3): return_block_with_long_extra_data = construct_fixture_middleware({ 'eth_getBlockByNumber': {'extraData': '0x' + 'ff' * 33}, }) - web3.middleware_onion.inject(return_block_with_long_extra_data, layer=0) + w3.middleware_onion.inject(return_block_with_long_extra_data, layer=0) with pytest.raises(ExtraDataLengthError): - web3.eth.get_block('latest') + w3.eth.get_block('latest') -def test_full_extra_data(web3): +def test_full_extra_data(w3): return_block_with_long_extra_data = construct_fixture_middleware({ 'eth_getBlockByNumber': {'extraData': '0x' + 'ff' * 32}, }) - web3.middleware_onion.inject(return_block_with_long_extra_data, layer=0) - block = web3.eth.get_block('latest') + w3.middleware_onion.inject(return_block_with_long_extra_data, layer=0) + block = w3.eth.get_block('latest') assert block.extraData == b'\xff' * 32 -def test_geth_proof_of_authority(web3): +def test_geth_proof_of_authority(w3): return_block_with_long_extra_data = construct_fixture_middleware({ 'eth_getBlockByNumber': {'extraData': '0x' + 'ff' * 33}, }) - web3.middleware_onion.inject(geth_poa_middleware, layer=0) - web3.middleware_onion.inject(return_block_with_long_extra_data, layer=0) - block = web3.eth.get_block('latest') + w3.middleware_onion.inject(geth_poa_middleware, layer=0) + w3.middleware_onion.inject(return_block_with_long_extra_data, layer=0) + block = w3.eth.get_block('latest') assert 'extraData' not in block assert block.proofOfAuthorityData == b'\xff' * 33 -def test_returns_none_response(web3): +def test_returns_none_response(w3): return_none_response = construct_fixture_middleware({ 'eth_getBlockByNumber': None, }) - web3.middleware_onion.inject(geth_poa_middleware, layer=0) - web3.middleware_onion.inject(return_none_response, layer=0) + w3.middleware_onion.inject(geth_poa_middleware, layer=0) + w3.middleware_onion.inject(return_none_response, layer=0) with pytest.raises(BlockNotFound): - web3.eth.get_block(100000000000) + w3.eth.get_block(100000000000) diff --git a/tests/core/eth-module/test_transactions.py b/tests/core/eth-module/test_transactions.py index 5e8c5c7493..9dbfd087f1 100644 --- a/tests/core/eth-module/test_transactions.py +++ b/tests/core/eth-module/test_transactions.py @@ -58,12 +58,12 @@ 'storage_keys_dynamic_fee_txn', ], ) -def test_eth_tester_send_transaction_validation(web3, transaction): +def test_eth_tester_send_transaction_validation(w3, transaction): # Test that eth-tester transaction param validation does not throw for properly formatted # transactions. This is especially important because we have key mapping differences # (camelCase to snake_case) mitigated by providers/eth-tester/middleware. - txn_hash = web3.eth.send_transaction(transaction) - receipt = web3.eth.wait_for_transaction_receipt(txn_hash, timeout=RECEIPT_TIMEOUT) + txn_hash = w3.eth.send_transaction(transaction) + receipt = w3.eth.wait_for_transaction_receipt(txn_hash, timeout=RECEIPT_TIMEOUT) assert receipt.get('blockNumber') is not None @@ -71,27 +71,27 @@ def test_eth_tester_send_transaction_validation(web3, transaction): 'make_chain_id, expect_success', ( ( - lambda web3: web3.eth.chain_id, + lambda w3: w3.eth.chain_id, True, ), pytest.param( - lambda web3: 999999999999, + lambda w3: 999999999999, False, ), ), ) -def test_send_transaction_with_valid_chain_id(web3, make_chain_id, expect_success): +def test_send_transaction_with_valid_chain_id(w3, make_chain_id, expect_success): transaction = { - 'to': web3.eth.accounts[1], - 'chainId': make_chain_id(web3), + 'to': w3.eth.accounts[1], + 'chainId': make_chain_id(w3), } if expect_success: - txn_hash = web3.eth.send_transaction(transaction) - receipt = web3.eth.wait_for_transaction_receipt(txn_hash, timeout=RECEIPT_TIMEOUT) + txn_hash = w3.eth.send_transaction(transaction) + receipt = w3.eth.wait_for_transaction_receipt(txn_hash, timeout=RECEIPT_TIMEOUT) assert receipt.get('blockNumber') is not None else: with pytest.raises(ValidationError) as exc_info: - web3.eth.send_transaction(transaction) + w3.eth.send_transaction(transaction) assert 'chain ID' in str(exc_info.value) @@ -109,57 +109,57 @@ def test_send_transaction_with_valid_chain_id(web3, make_chain_id, expect_succes ), ) ) -def test_send_transaction_with_invalid_ens_names(web3, to, _from): - with ens_addresses(web3, [ - ('registered-name-1.eth', web3.eth.accounts[1]), +def test_send_transaction_with_invalid_ens_names(w3, to, _from): + with ens_addresses(w3, [ + ('registered-name-1.eth', w3.eth.accounts[1]), ]): transaction = { 'to': to, - 'chainId': web3.eth.chain_id, + 'chainId': w3.eth.chain_id, 'from': _from, } with pytest.raises(NameNotFound): - web3.eth.send_transaction(transaction) + w3.eth.send_transaction(transaction) -def test_send_transaction_with_ens_names(web3): - with ens_addresses(web3, [ - ('registered-name-1.eth', web3.eth.accounts[1]), - ('registered-name-2.eth', web3.eth.accounts[0]) +def test_send_transaction_with_ens_names(w3): + with ens_addresses(w3, [ + ('registered-name-1.eth', w3.eth.accounts[1]), + ('registered-name-2.eth', w3.eth.accounts[0]) ]): transaction = { 'to': 'registered-name-1.eth', - 'chainId': web3.eth.chain_id, + 'chainId': w3.eth.chain_id, 'from': 'registered-name-2.eth', } - txn_hash = web3.eth.send_transaction(transaction) - receipt = web3.eth.wait_for_transaction_receipt(txn_hash, timeout=RECEIPT_TIMEOUT) + txn_hash = w3.eth.send_transaction(transaction) + receipt = w3.eth.wait_for_transaction_receipt(txn_hash, timeout=RECEIPT_TIMEOUT) assert receipt.get('blockNumber') is not None -def test_wait_for_missing_receipt(web3): +def test_wait_for_missing_receipt(w3): with pytest.raises(TimeExhausted): - web3.eth.wait_for_transaction_receipt(b'\0' * 32, timeout=RECEIPT_TIMEOUT) + w3.eth.wait_for_transaction_receipt(b'\0' * 32, timeout=RECEIPT_TIMEOUT) -def test_passing_string_to_to_hex(web3): +def test_passing_string_to_to_hex(w3): with pytest.raises(TimeExhausted): transaction_hash = '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060' - web3.eth.wait_for_transaction_receipt(transaction_hash, timeout=RECEIPT_TIMEOUT) + w3.eth.wait_for_transaction_receipt(transaction_hash, timeout=RECEIPT_TIMEOUT) -def test_unmined_transaction_wait_for_receipt(web3): - web3.middleware_onion.add(unmined_receipt_simulator_middleware) - txn_hash = web3.eth.send_transaction({ - 'from': web3.eth.coinbase, +def test_unmined_transaction_wait_for_receipt(w3): + w3.middleware_onion.add(unmined_receipt_simulator_middleware) + txn_hash = w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'value': 123457 }) with pytest.raises(TransactionNotFound): - web3.eth.get_transaction_receipt(txn_hash) + w3.eth.get_transaction_receipt(txn_hash) - txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash) + txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) assert txn_receipt['transactionHash'] == txn_hash assert txn_receipt['blockHash'] is not None diff --git a/tests/core/filtering/conftest.py b/tests/core/filtering/conftest.py index cce7d08c95..35e579df1e 100644 --- a/tests/core/filtering/conftest.py +++ b/tests/core/filtering/conftest.py @@ -25,7 +25,7 @@ scope='function', params=[True, False], ids=["local_filter_middleware", "node_based_filter"]) -def web3(request): +def w3(request): use_filter_middleware = request.param provider = EthereumTesterProvider() w3 = Web3(provider) @@ -35,8 +35,8 @@ def web3(request): @pytest.fixture(autouse=True) -def wait_for_mining_start(web3, wait_for_block): - wait_for_block(web3) +def wait_for_mining_start(w3, wait_for_block): + wait_for_block(w3) @pytest.fixture() @@ -66,18 +66,18 @@ def EMITTER(EMITTER_CODE, @pytest.fixture() -def Emitter(web3, EMITTER): - return web3.eth.contract(**EMITTER) +def Emitter(w3, EMITTER): + return w3.eth.contract(**EMITTER) @pytest.fixture() -def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) +def emitter(w3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): + wait_for_block(w3) deploy_txn_hash = Emitter.constructor().transact({'gas': 10000000}) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == Emitter.bytecode_runtime _emitter = Emitter(address=contract_address) assert _emitter.address == contract_address diff --git a/tests/core/filtering/test_basic_filter_tests.py b/tests/core/filtering/test_basic_filter_tests.py index c9309d909f..3a0d267502 100644 --- a/tests/core/filtering/test_basic_filter_tests.py +++ b/tests/core/filtering/test_basic_filter_tests.py @@ -1,40 +1,40 @@ def test_filtering_sequential_blocks_with_bounded_range( - web3, + w3, emitter, Emitter, wait_for_transaction): builder = emitter.events.LogNoArguments.build_filter() builder.fromBlock = "latest" - initial_block_number = web3.eth.block_number + initial_block_number = w3.eth.block_number builder.toBlock = initial_block_number + 100 - filter_ = builder.deploy(web3) + filter_ = builder.deploy(w3) for i in range(100): emitter.functions.logNoArgs(which=1).transact() - assert web3.eth.block_number == initial_block_number + 100 + assert w3.eth.block_number == initial_block_number + 100 assert len(filter_.get_new_entries()) == 100 def test_filtering_starting_block_range( - web3, + w3, emitter, Emitter, wait_for_transaction): for i in range(10): emitter.functions.logNoArgs(which=1).transact() builder = emitter.events.LogNoArguments.build_filter() - filter_ = builder.deploy(web3) - initial_block_number = web3.eth.block_number + filter_ = builder.deploy(w3) + initial_block_number = w3.eth.block_number for i in range(10): emitter.functions.logNoArgs(which=1).transact() - assert web3.eth.block_number == initial_block_number + 10 + assert w3.eth.block_number == initial_block_number + 10 assert len(filter_.get_new_entries()) == 10 -def test_requesting_results_with_no_new_blocks(web3, emitter): +def test_requesting_results_with_no_new_blocks(w3, emitter): builder = emitter.events.LogNoArguments.build_filter() - filter_ = builder.deploy(web3) + filter_ = builder.deploy(w3) assert len(filter_.get_new_entries()) == 0 diff --git a/tests/core/filtering/test_contract_createFilter_topic_merging.py b/tests/core/filtering/test_contract_createFilter_topic_merging.py index 61ed78c173..2b15532465 100644 --- a/tests/core/filtering/test_contract_createFilter_topic_merging.py +++ b/tests/core/filtering/test_contract_createFilter_topic_merging.py @@ -2,7 +2,7 @@ def test_merged_topic_list_event( - web3, + w3, emitter, emitter_event_ids, wait_for_transaction): diff --git a/tests/core/filtering/test_contract_data_filters.py b/tests/core/filtering/test_contract_data_filters.py index 6efb78c724..4c2f5eeafe 100644 --- a/tests/core/filtering/test_contract_data_filters.py +++ b/tests/core/filtering/test_contract_data_filters.py @@ -24,7 +24,7 @@ scope="module", params=[True, False], ids=["local_filter_middleware", "node_based_filter"]) -def web3(request): +def w3(request): use_filter_middleware = request.param provider = EthereumTesterProvider() w3 = Web3(provider) @@ -60,18 +60,18 @@ def EMITTER(EMITTER_CODE, @pytest.fixture(scope="module") -def Emitter(web3, EMITTER): - return web3.eth.contract(**EMITTER) +def Emitter(w3, EMITTER): + return w3.eth.contract(**EMITTER) @pytest.fixture(scope="module") -def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) +def emitter(w3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): + wait_for_block(w3) deploy_txn_hash = Emitter.constructor().transact({'gas': 10000000}) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == Emitter.bytecode_runtime _emitter = Emitter(address=contract_address) assert _emitter.address == contract_address @@ -131,7 +131,7 @@ def array_values(draw): @given(vals=dynamic_values()) @settings(max_examples=5, deadline=None) def test_data_filters_with_dynamic_arguments( - web3, + w3, wait_for_transaction, create_filter, emitter, @@ -140,7 +140,7 @@ def test_data_filters_with_dynamic_arguments( if api_style == 'build_filter': filter_builder = emitter.events.LogDynamicArgs.build_filter() filter_builder.args['arg1'].match_single(vals['matching']) - event_filter = filter_builder.deploy(web3) + event_filter = filter_builder.deploy(w3) else: event_filter = create_filter(emitter, [ 'LogDynamicArgs', { @@ -157,7 +157,7 @@ def test_data_filters_with_dynamic_arguments( ] for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 1 @@ -168,7 +168,7 @@ def test_data_filters_with_dynamic_arguments( @given(vals=fixed_values()) @settings(max_examples=5, deadline=None) def test_data_filters_with_fixed_arguments( - web3, + w3, emitter, wait_for_transaction, create_filter, @@ -181,7 +181,7 @@ def test_data_filters_with_fixed_arguments( filter_builder.args['arg1'].match_single(vals['matching'][1]) filter_builder.args['arg2'].match_single(vals['matching'][2]) filter_builder.args['arg3'].match_single(vals['matching'][3]) - event_filter = filter_builder.deploy(web3) + event_filter = filter_builder.deploy(w3) else: event_filter = create_filter(emitter, [ 'LogQuadrupleArg', { @@ -210,7 +210,7 @@ def test_data_filters_with_fixed_arguments( })) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 1 @@ -222,7 +222,7 @@ def test_data_filters_with_fixed_arguments( @given(vals=array_values()) @settings(max_examples=5, deadline=None) def test_data_filters_with_list_arguments( - web3, + w3, emitter, wait_for_transaction, call_as_instance, @@ -235,7 +235,7 @@ def test_data_filters_with_list_arguments( if api_style == 'build_filter': filter_builder = emitter.events.LogListArgs.build_filter() filter_builder.args['arg1'].match_single(matching) - event_filter = filter_builder.deploy(web3) + event_filter = filter_builder.deploy(w3) txn_hashes = [] txn_hashes.append(emitter.functions.logListArgs( @@ -252,7 +252,7 @@ def test_data_filters_with_list_arguments( arg1=non_matching).transact({'maxFeePerGas': 10 ** 9, 'maxPriorityFeePerGas': 10 ** 9})) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 2 diff --git a/tests/core/filtering/test_contract_getLogs.py b/tests/core/filtering/test_contract_getLogs.py index 8badd8ca00..ac9b30ca18 100644 --- a/tests/core/filtering/test_contract_getLogs.py +++ b/tests/core/filtering/test_contract_getLogs.py @@ -10,7 +10,7 @@ def test_contract_get_available_events( def test_contract_getLogs_all( - web3, + w3, emitter, wait_for_transaction, emitter_event_ids, @@ -19,7 +19,7 @@ def test_contract_getLogs_all( event_id = emitter_event_ids.LogNoArguments txn_hash = contract.functions.logNoArgs(event_id).transact() - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = list(contract.events.LogNoArguments.getLogs()) assert len(log_entries) == 1 @@ -27,7 +27,7 @@ def test_contract_getLogs_all( def test_contract_getLogs_range( - web3, + w3, emitter, wait_for_transaction, emitter_event_ids, @@ -35,11 +35,11 @@ def test_contract_getLogs_range( contract = emitter event_id = emitter_event_ids.LogNoArguments - assert web3.eth.block_number == 2 + assert w3.eth.block_number == 2 txn_hash = contract.functions.logNoArgs(event_id).transact() # Mined as block 3 - wait_for_transaction(web3, txn_hash) - assert web3.eth.block_number == 3 + wait_for_transaction(w3, txn_hash) + assert w3.eth.block_number == 3 log_entries = list(contract.events.LogNoArguments.getLogs()) assert len(log_entries) == 1 @@ -52,7 +52,7 @@ def test_contract_getLogs_range( def test_contract_getLogs_argument_filter( - web3, + w3, emitter, wait_for_transaction, emitter_event_ids): @@ -77,7 +77,7 @@ def test_contract_getLogs_argument_filter( emitter.functions.logTriple(event_id, 1, 3, 1).transact() ) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) all_logs = contract.events.LogTripleWithIndex.getLogs(fromBlock=1) assert len(all_logs) == 4 diff --git a/tests/core/filtering/test_contract_on_event_filtering.py b/tests/core/filtering/test_contract_on_event_filtering.py index 9c2174d153..044bb0eec2 100644 --- a/tests/core/filtering/test_contract_on_event_filtering.py +++ b/tests/core/filtering/test_contract_on_event_filtering.py @@ -6,7 +6,7 @@ @pytest.mark.parametrize('call_as_instance', (True, False)) -def test_create_filter_address_parameter(web3, emitter, Emitter, call_as_instance): +def test_create_filter_address_parameter(w3, emitter, Emitter, call_as_instance): if call_as_instance: event_filter = emitter.events.LogNoArguments.createFilter(fromBlock="latest") else: @@ -23,7 +23,7 @@ def test_create_filter_address_parameter(web3, emitter, Emitter, call_as_instanc @pytest.mark.parametrize('call_as_instance', (True, False)) @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_on_filter_using_get_entries_interface( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -38,12 +38,12 @@ def test_on_filter_using_get_entries_interface( contract = Emitter if api_style == 'build_filter': - event_filter = contract.events.LogNoArguments.build_filter().deploy(web3) + event_filter = contract.events.LogNoArguments.build_filter().deploy(w3) else: event_filter = create_filter(emitter, ['LogNoArguments', {}]) txn_hash = emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact() - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 1 @@ -57,7 +57,7 @@ def test_on_filter_using_get_entries_interface( @pytest.mark.parametrize('call_as_instance', (True, False)) @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_on_sync_filter_with_event_name_and_single_argument( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -74,7 +74,7 @@ def test_on_sync_filter_with_event_name_and_single_argument( if api_style == 'build_filter': builder = contract.events.LogTripleWithIndex.build_filter() builder.args['arg1'].match_single(2) - event_filter = builder.deploy(web3) + event_filter = builder.deploy(w3) else: event_filter = create_filter(contract, ['LogTripleWithIndex', {'filter': { 'arg1': 2, @@ -92,7 +92,7 @@ def test_on_sync_filter_with_event_name_and_single_argument( emitter.functions.logTriple(event_id, 12345, 2, 54321).transact() ) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) seen_logs = event_filter.get_new_entries() assert len(seen_logs) == 2 @@ -102,7 +102,7 @@ def test_on_sync_filter_with_event_name_and_single_argument( @pytest.mark.parametrize('call_as_instance', (True, False)) @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_on_sync_filter_with_event_name_and_non_indexed_argument( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -120,7 +120,7 @@ def test_on_sync_filter_with_event_name_and_non_indexed_argument( builder = contract.events.LogTripleWithIndex.build_filter() builder.args['arg0'].match_single(1) builder.args['arg1'].match_single(2) - event_filter = builder.deploy(web3) + event_filter = builder.deploy(w3) else: event_filter = create_filter(contract, ['LogTripleWithIndex', {'filter': { 'arg0': 1, @@ -139,7 +139,7 @@ def test_on_sync_filter_with_event_name_and_non_indexed_argument( emitter.functions.logTriple(event_id, 12345, 2, 54321).transact() ) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) seen_logs = event_filter.get_new_entries() assert len(seen_logs) == 1 @@ -155,10 +155,10 @@ def test_on_sync_filter_with_event_name_and_non_indexed_argument( assert old_logs[0]['transactionHash'] == txn_hashes[1] -def test_filter_with_contract_address(web3, emitter, emitter_event_ids, wait_for_transaction): - event_filter = web3.eth.filter(filter_params={'address': emitter.address}) +def test_filter_with_contract_address(w3, emitter, emitter_event_ids, wait_for_transaction): + event_filter = w3.eth.filter(filter_params={'address': emitter.address}) txn_hash = emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact() - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) seen_logs = event_filter.get_new_entries() assert len(seen_logs) == 1 assert seen_logs[0]['transactionHash'] == txn_hash @@ -166,7 +166,7 @@ def test_filter_with_contract_address(web3, emitter, emitter_event_ids, wait_for @pytest.mark.parametrize('call_as_instance', (True, False)) def test_on_sync_filter_with_topic_filter_options_on_old_apis( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -199,7 +199,7 @@ def test_on_sync_filter_with_topic_filter_options_on_old_apis( emitter.functions.logTriple(event_id, 1, 2, 1).transact() ) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) seen_logs = event_filter.get_new_entries() assert len(seen_logs) == 4 diff --git a/tests/core/filtering/test_contract_past_event_filtering.py b/tests/core/filtering/test_contract_past_event_filtering.py index 85009ef824..5686ab7e22 100644 --- a/tests/core/filtering/test_contract_past_event_filtering.py +++ b/tests/core/filtering/test_contract_past_event_filtering.py @@ -8,7 +8,7 @@ @pytest.mark.parametrize('call_as_instance', (True, False)) @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_on_filter_using_get_all_entries_interface( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -25,13 +25,13 @@ def test_on_filter_using_get_all_entries_interface( if api_style == 'build_filter': builder = contract.events.LogNoArguments.build_filter() builder.fromBlock = "latest" - event_filter = builder.deploy(web3) + event_filter = builder.deploy(w3) else: event_filter = create_filter( contract, ["LogNoArguments", {"fromBlock": "latest"}]) txn_hash = emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact() - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_all_entries() @@ -48,7 +48,7 @@ def test_on_filter_using_get_all_entries_interface( @pytest.mark.parametrize('call_as_instance', (True, False)) @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_get_all_entries_returned_block_data( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -58,7 +58,7 @@ def test_get_all_entries_returned_block_data( create_filter, ): txn_hash = emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact() - txn_receipt = wait_for_transaction(web3, txn_hash) + txn_receipt = wait_for_transaction(w3, txn_hash) if call_as_instance: contract = emitter @@ -68,7 +68,7 @@ def test_get_all_entries_returned_block_data( if api_style == 'build_filter': builder = contract.events.LogNoArguments.build_filter() builder.fromBlock = txn_receipt["blockNumber"] - event_filter = builder.deploy(web3) + event_filter = builder.deploy(w3) else: event_filter = create_filter(contract, [ "LogNoArguments", {"fromBlock": txn_receipt["blockNumber"]}]) diff --git a/tests/core/filtering/test_contract_topic_filters.py b/tests/core/filtering/test_contract_topic_filters.py index 6e55ed74ac..f51f5b4670 100644 --- a/tests/core/filtering/test_contract_topic_filters.py +++ b/tests/core/filtering/test_contract_topic_filters.py @@ -24,7 +24,7 @@ scope='module', params=[True, False], ids=["local_filter_middleware", "node_based_filter"]) -def web3(request): +def w3(request): use_filter_middleware = request.param provider = EthereumTesterProvider() w3 = Web3(provider) @@ -34,8 +34,8 @@ def web3(request): @pytest.fixture(autouse=True) -def wait_for_mining_start(web3, wait_for_block): - wait_for_block(web3) +def wait_for_mining_start(w3, wait_for_block): + wait_for_block(w3) @pytest.fixture(scope="module") @@ -65,18 +65,18 @@ def EMITTER(EMITTER_CODE, @pytest.fixture(scope="module") -def Emitter(web3, EMITTER): - return web3.eth.contract(**EMITTER) +def Emitter(w3, EMITTER): + return w3.eth.contract(**EMITTER) @pytest.fixture(scope="module") -def emitter(web3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): - wait_for_block(web3) +def emitter(w3, Emitter, wait_for_transaction, wait_for_block, address_conversion_func): + wait_for_block(w3) deploy_txn_hash = Emitter.constructor().transact({'gas': 10000000}) - deploy_receipt = wait_for_transaction(web3, deploy_txn_hash) + deploy_receipt = wait_for_transaction(w3, deploy_txn_hash) contract_address = address_conversion_func(deploy_receipt['contractAddress']) - bytecode = web3.eth.get_code(contract_address) + bytecode = w3.eth.get_code(contract_address) assert bytecode == Emitter.bytecode_runtime _emitter = Emitter(address=contract_address) assert _emitter.address == contract_address @@ -138,7 +138,7 @@ def array_values(draw): @given(vals=dynamic_values()) @settings(max_examples=5, deadline=None) def test_topic_filters_with_dynamic_arguments( - web3, + w3, emitter, wait_for_transaction, create_filter, @@ -147,7 +147,7 @@ def test_topic_filters_with_dynamic_arguments( if api_style == 'build_filter': filter_builder = emitter.events.LogDynamicArgs.build_filter() filter_builder.args['arg0'].match_single(vals['matching']) - event_filter = filter_builder.deploy(web3) + event_filter = filter_builder.deploy(w3) else: event_filter = create_filter(emitter, [ 'LogDynamicArgs', { @@ -168,7 +168,7 @@ def test_topic_filters_with_dynamic_arguments( ] for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 1 @@ -180,7 +180,7 @@ def test_topic_filters_with_dynamic_arguments( @given(vals=fixed_values()) @settings(max_examples=5, deadline=None) def test_topic_filters_with_fixed_arguments( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -194,7 +194,7 @@ def test_topic_filters_with_fixed_arguments( filter_builder.args['arg1'].match_single(vals['matching'][1]) filter_builder.args['arg2'].match_single(vals['matching'][2]) filter_builder.args['arg3'].match_single(vals['matching'][3]) - event_filter = filter_builder.deploy(web3) + event_filter = filter_builder.deploy(w3) else: event_filter = create_filter(emitter, [ 'LogQuadrupleWithIndex', { @@ -223,7 +223,7 @@ def test_topic_filters_with_fixed_arguments( })) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 1 @@ -235,7 +235,7 @@ def test_topic_filters_with_fixed_arguments( @given(vals=array_values()) @settings(max_examples=5, deadline=None) def test_topic_filters_with_list_arguments( - web3, + w3, emitter, wait_for_transaction, call_as_instance, @@ -247,7 +247,7 @@ def test_topic_filters_with_list_arguments( if api_style == 'build_filter': filter_builder = emitter.events.LogListArgs.build_filter() filter_builder.args['arg0'].match_single(matching) - event_filter = filter_builder.deploy(web3) + event_filter = filter_builder.deploy(w3) txn_hashes = [] txn_hashes.append(emitter.functions.logListArgs( arg0=matching, @@ -257,7 +257,7 @@ def test_topic_filters_with_list_arguments( arg1=non_matching).transact({'maxFeePerGas': 10 ** 9, 'maxPriorityFeePerGas': 10 ** 9})) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) log_entries = event_filter.get_new_entries() assert len(log_entries) == 1 diff --git a/tests/core/filtering/test_existing_filter_instance.py b/tests/core/filtering/test_existing_filter_instance.py index 217d6c51aa..fef675a5ce 100644 --- a/tests/core/filtering/test_existing_filter_instance.py +++ b/tests/core/filtering/test_existing_filter_instance.py @@ -9,27 +9,27 @@ @pytest.fixture() -def filter_id(web3): - if not isinstance(web3.provider, EthereumTesterProvider): - web3.provider = EthereumTesterProvider() +def filter_id(w3): + if not isinstance(w3.provider, EthereumTesterProvider): + w3.provider = EthereumTesterProvider() - block_filter = web3.eth.filter("latest") + block_filter = w3.eth.filter("latest") return block_filter.filter_id -def test_instantiate_existing_filter(web3, sleep_interval, wait_for_block, filter_id): +def test_instantiate_existing_filter(w3, sleep_interval, wait_for_block, filter_id): with pytest.raises(TypeError): - web3.eth.filter('latest', filter_id) + w3.eth.filter('latest', filter_id) with pytest.raises(TypeError): - web3.eth.filter('latest', filter_id=filter_id) + w3.eth.filter('latest', filter_id=filter_id) with pytest.raises(TypeError): - web3.eth.filter(filter_params='latest', filter_id=filter_id) + w3.eth.filter(filter_params='latest', filter_id=filter_id) - block_filter = web3.eth.filter(filter_id=filter_id) + block_filter = w3.eth.filter(filter_id=filter_id) - current_block = web3.eth.block_number + current_block = w3.eth.block_number - wait_for_block(web3, current_block + 3) + wait_for_block(w3, current_block + 3) found_block_hashes = [] with Timeout(5) as timeout: @@ -40,6 +40,6 @@ def test_instantiate_existing_filter(web3, sleep_interval, wait_for_block, filte assert len(found_block_hashes) == 3 expected_block_hashes = [ - web3.eth.get_block(n + 1).hash for n in range(current_block, current_block + 3) + w3.eth.get_block(n + 1).hash for n in range(current_block, current_block + 3) ] assert found_block_hashes == expected_block_hashes diff --git a/tests/core/filtering/test_filter_against_latest_blocks.py b/tests/core/filtering/test_filter_against_latest_blocks.py index 728424bafc..b12e76b580 100644 --- a/tests/core/filtering/test_filter_against_latest_blocks.py +++ b/tests/core/filtering/test_filter_against_latest_blocks.py @@ -6,15 +6,15 @@ ) -def test_sync_filter_against_latest_blocks(web3, sleep_interval, wait_for_block): - if not isinstance(web3.provider, EthereumTesterProvider): - web3.provider = EthereumTesterProvider() +def test_sync_filter_against_latest_blocks(w3, sleep_interval, wait_for_block): + if not isinstance(w3.provider, EthereumTesterProvider): + w3.provider = EthereumTesterProvider() - txn_filter = web3.eth.filter("latest") + txn_filter = w3.eth.filter("latest") - current_block = web3.eth.block_number + current_block = w3.eth.block_number - wait_for_block(web3, current_block + 3) + wait_for_block(w3, current_block + 3) found_block_hashes = [] with Timeout(5) as timeout: @@ -25,6 +25,6 @@ def test_sync_filter_against_latest_blocks(web3, sleep_interval, wait_for_block) assert len(found_block_hashes) == 3 expected_block_hashes = [ - web3.eth.get_block(n + 1).hash for n in range(current_block, current_block + 3) + w3.eth.get_block(n + 1).hash for n in range(current_block, current_block + 3) ] assert found_block_hashes == expected_block_hashes diff --git a/tests/core/filtering/test_filter_against_pending_transactions.py b/tests/core/filtering/test_filter_against_pending_transactions.py index e3162a9b8c..aebdb7fea7 100644 --- a/tests/core/filtering/test_filter_against_pending_transactions.py +++ b/tests/core/filtering/test_filter_against_pending_transactions.py @@ -10,30 +10,30 @@ ) -@pytest.mark.skip(reason="fixture 'web3_empty' not found") +@pytest.mark.skip(reason="fixture 'w3_empty' not found") @flaky(max_runs=3) -def test_sync_filter_against_pending_transactions(web3_empty, +def test_sync_filter_against_pending_transactions(w3_empty, wait_for_transaction, skip_if_testrpc ): - web3 = web3_empty - skip_if_testrpc(web3) + w3 = w3_empty + skip_if_testrpc(w3) - txn_filter = web3.eth.filter("pending") + txn_filter = w3.eth.filter("pending") - txn_1_hash = web3.eth.send_transaction({ - 'from': web3.eth.coinbase, + txn_1_hash = w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'value': 12345, }) - txn_2_hash = web3.eth.send_transaction({ - 'from': web3.eth.coinbase, + txn_2_hash = w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'value': 54321, }) - wait_for_transaction(web3, txn_1_hash) - wait_for_transaction(web3, txn_2_hash) + wait_for_transaction(w3, txn_1_hash) + wait_for_transaction(w3, txn_2_hash) with Timeout(5) as timeout: while not txn_filter.get_new_entries(): @@ -45,32 +45,32 @@ def test_sync_filter_against_pending_transactions(web3_empty, assert txn_2_hash in seen_txns -@pytest.mark.skip(reason="fixture 'web3_empty' not found") +@pytest.mark.skip(reason="fixture 'w3_empty' not found") @flaky(max_runs=3) -def test_async_filter_against_pending_transactions(web3_empty, +def test_async_filter_against_pending_transactions(w3_empty, wait_for_transaction, skip_if_testrpc ): - web3 = web3_empty - skip_if_testrpc(web3) + w3 = w3_empty + skip_if_testrpc(w3) seen_txns = [] - txn_filter = web3.eth.filter("pending") + txn_filter = w3.eth.filter("pending") txn_filter.watch(seen_txns.append) - txn_1_hash = web3.eth.send_transaction({ - 'from': web3.eth.coinbase, + txn_1_hash = w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'value': 12345, }) - txn_2_hash = web3.eth.send_transaction({ - 'from': web3.eth.coinbase, + txn_2_hash = w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'value': 54321, }) - wait_for_transaction(web3, txn_1_hash) - wait_for_transaction(web3, txn_2_hash) + wait_for_transaction(w3, txn_1_hash) + wait_for_transaction(w3, txn_2_hash) with Timeout(5) as timeout: while not seen_txns: diff --git a/tests/core/filtering/test_filter_against_transaction_logs.py b/tests/core/filtering/test_filter_against_transaction_logs.py index b0c13a03ca..664ec64b95 100644 --- a/tests/core/filtering/test_filter_against_transaction_logs.py +++ b/tests/core/filtering/test_filter_against_transaction_logs.py @@ -10,23 +10,23 @@ ) -@pytest.mark.skip(reason="fixture 'web3_empty' not found") +@pytest.mark.skip(reason="fixture 'w3_empty' not found") @flaky(max_runs=3) -def test_sync_filter_against_log_events(web3_empty, +def test_sync_filter_against_log_events(w3_empty, emitter, wait_for_transaction, emitter_log_topics, emitter_event_ids ): - web3 = web3_empty + w3 = w3_empty - txn_filter = web3.eth.filter({}) + txn_filter = w3.eth.filter({}) txn_hashes = [] txn_hashes.append(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact()) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) with Timeout(5) as timeout: while not txn_filter.get_new_entries(): @@ -37,18 +37,18 @@ def test_sync_filter_against_log_events(web3_empty, assert set(txn_hashes) == set(log['transactionHash'] for log in seen_logs) -@pytest.mark.skip(reason="fixture 'web3_empty' not found") +@pytest.mark.skip(reason="fixture 'w3_empty' not found") @flaky(max_runs=3) -def test_async_filter_against_log_events(web3_empty, +def test_async_filter_against_log_events(w3_empty, emitter, wait_for_transaction, emitter_log_topics, emitter_event_ids ): - web3 = web3_empty + w3 = w3_empty seen_logs = [] - txn_filter = web3.eth.filter({}) + txn_filter = w3.eth.filter({}) txn_filter.watch(seen_logs.append) txn_hashes = [] @@ -56,7 +56,7 @@ def test_async_filter_against_log_events(web3_empty, txn_hashes.append(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact()) for txn_hash in txn_hashes: - wait_for_transaction(web3, txn_hash) + wait_for_transaction(w3, txn_hash) with Timeout(5) as timeout: while not seen_logs: diff --git a/tests/core/filtering/test_filters_against_many_blocks.py b/tests/core/filtering/test_filters_against_many_blocks.py index ced0ff4117..397dda579a 100644 --- a/tests/core/filtering/test_filters_against_many_blocks.py +++ b/tests/core/filtering/test_filters_against_many_blocks.py @@ -7,11 +7,11 @@ @to_tuple -def deploy_contracts(web3, contract, wait_for_transaction): +def deploy_contracts(w3, contract, wait_for_transaction): for i in range(25): tx_hash = contract.constructor().transact() - wait_for_transaction(web3, tx_hash) - yield web3.eth.get_transaction_receipt(tx_hash)['contractAddress'] + wait_for_transaction(w3, tx_hash) + yield w3.eth.get_transaction_receipt(tx_hash)['contractAddress'] def pad_with_transactions(w3): @@ -34,7 +34,7 @@ def single_transaction(w3): @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_event_filter_new_events( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -50,43 +50,43 @@ def test_event_filter_new_events( if api_style == 'build_filter': builder = emitter.events.LogNoArguments.build_filter() builder.fromBlock = 'latest' - event_filter = builder.deploy(web3) + event_filter = builder.deploy(w3) else: event_filter = emitter.events.LogNoArguments().createFilter(fromBlock='latest') expected_match_counter = 0 - while web3.eth.block_number < 50: + while w3.eth.block_number < 50: is_match = bool(random.randint(0, 1)) if is_match: expected_match_counter += 1 - wait_for_transaction(web3, matching_transact()) - pad_with_transactions(web3) + wait_for_transaction(w3, matching_transact()) + pad_with_transactions(w3) continue non_matching_transact() - pad_with_transactions(web3) + pad_with_transactions(w3) assert len(event_filter.get_new_entries()) == expected_match_counter @pytest.mark.xfail(reason="Suspected eth-tester bug") -def test_block_filter(web3): - block_filter = web3.eth.filter("latest") +def test_block_filter(w3): + block_filter = w3.eth.filter("latest") - while web3.eth.block_number < 50: - pad_with_transactions(web3) + while w3.eth.block_number < 50: + pad_with_transactions(w3) - assert len(block_filter.get_new_entries()) == web3.eth.block_number + assert len(block_filter.get_new_entries()) == w3.eth.block_number -def test_transaction_filter_with_mining(web3): +def test_transaction_filter_with_mining(w3): - transaction_filter = web3.eth.filter("pending") + transaction_filter = w3.eth.filter("pending") transaction_counter = 0 while transaction_counter < 100: - single_transaction(web3) + single_transaction(w3) transaction_counter += 1 assert len(transaction_filter.get_new_entries()) == transaction_counter @@ -94,14 +94,14 @@ def test_transaction_filter_with_mining(web3): @pytest.mark.xfail(reason="Suspected eth-tester bug") def test_transaction_filter_without_mining( - web3): + w3): - web3.providers[0].ethereum_tester.auto_mine_transactions = False - transaction_filter = web3.eth.filter("pending") + w3.providers[0].ethereum_tester.auto_mine_transactions = False + transaction_filter = w3.eth.filter("pending") transaction_counter = 0 - transact_once = single_transaction(web3) + transact_once = single_transaction(w3) while transaction_counter < 100: next(transact_once) transaction_counter += 1 @@ -111,7 +111,7 @@ def test_transaction_filter_without_mining( @pytest.mark.parametrize('api_style', ('v4', 'build_filter')) def test_event_filter_new_events_many_deployed_contracts( - web3, + w3, emitter, Emitter, wait_for_transaction, @@ -122,13 +122,13 @@ def test_event_filter_new_events_many_deployed_contracts( matching_transact = emitter.functions.logNoArgs( which=1).transact - deployed_contract_addresses = deploy_contracts(web3, Emitter, wait_for_transaction) + deployed_contract_addresses = deploy_contracts(w3, Emitter, wait_for_transaction) def gen_non_matching_transact(): while True: contract_address = deployed_contract_addresses[ random.randint(0, len(deployed_contract_addresses) - 1)] - yield web3.eth.contract( + yield w3.eth.contract( address=contract_address, abi=Emitter.abi).functions.logNoArgs(which=1).transact non_matching_transact = gen_non_matching_transact() @@ -136,20 +136,20 @@ def gen_non_matching_transact(): if api_style == 'build_filter': builder = emitter.events.LogNoArguments.build_filter() builder.fromBlock = "latest" - event_filter = builder.deploy(web3) + event_filter = builder.deploy(w3) else: event_filter = emitter.events.LogNoArguments().createFilter(fromBlock='latest') expected_match_counter = 0 - while web3.eth.block_number < 50: + while w3.eth.block_number < 50: is_match = bool(random.randint(0, 1)) if is_match: expected_match_counter += 1 matching_transact() - pad_with_transactions(web3) + pad_with_transactions(w3) continue next(non_matching_transact)() - pad_with_transactions(web3) + pad_with_transactions(w3) assert len(event_filter.get_new_entries()) == expected_match_counter diff --git a/tests/core/filtering/test_utils_functions.py b/tests/core/filtering/test_utils_functions.py index 6d6b5a4383..54ea2c12d7 100644 --- a/tests/core/filtering/test_utils_functions.py +++ b/tests/core/filtering/test_utils_functions.py @@ -128,10 +128,10 @@ ), ) ) -def test_match_fn_with_various_data_types(web3, data, expected, match_data_and_abi): +def test_match_fn_with_various_data_types(w3, data, expected, match_data_and_abi): abi_types, match_data = zip(*match_data_and_abi) - encoded_data = web3.codec.encode_abi(abi_types, data) - assert match_fn(web3.codec, match_data_and_abi, encoded_data) == expected + encoded_data = w3.codec.encode_abi(abi_types, data) + assert match_fn(w3.codec, match_data_and_abi, encoded_data) == expected @pytest.mark.parametrize( @@ -224,13 +224,13 @@ def test_encode_abi_with_wrong_types_strict(w3_strict_abi, w3_strict_abi.codec.encode_abi(abi_type, data) -def test_wrong_type_match_data(web3): +def test_wrong_type_match_data(w3): data = ("hello", "goodbye") match_data_and_abi = ( ("string", (50505050,)), ("string", (50505050,)), ) abi_types, match_data = zip(*match_data_and_abi) - encoded_data = web3.codec.encode_abi(abi_types, data) + encoded_data = w3.codec.encode_abi(abi_types, data) with pytest.raises(ValueError): - match_fn(web3.codec, match_data_and_abi, encoded_data) + match_fn(w3.codec, match_data_and_abi, encoded_data) diff --git a/tests/core/gas-strategies/test_rpc_gas_pricing_strategies.py b/tests/core/gas-strategies/test_rpc_gas_pricing_strategies.py index 76e44ff705..7b54d72c79 100644 --- a/tests/core/gas-strategies/test_rpc_gas_pricing_strategies.py +++ b/tests/core/gas-strategies/test_rpc_gas_pricing_strategies.py @@ -3,12 +3,12 @@ ) -def test_default_rpc_gas_price_strategy(web3): - assert rpc_gas_price_strategy(web3, { +def test_default_rpc_gas_price_strategy(w3): + assert rpc_gas_price_strategy(w3, { 'to': '0x0', 'value': 1 }) == 10 ** 9 -def test_default_rpc_gas_price_strategy_callable_without_transaction(web3): - assert rpc_gas_price_strategy(web3) == 10 ** 9 +def test_default_rpc_gas_price_strategy_callable_without_transaction(w3): + assert rpc_gas_price_strategy(w3) == 10 ** 9 diff --git a/tests/core/manager/test_response_formatters.py b/tests/core/manager/test_response_formatters.py index df8e563b5f..65b3771104 100644 --- a/tests/core/manager/test_response_formatters.py +++ b/tests/core/manager/test_response_formatters.py @@ -107,17 +107,17 @@ def raise_contract_logic_error(response): ), ], ) -def test_formatted_response_raises_errors(web3, +def test_formatted_response_raises_errors(w3, response, params, error_formatters, null_result_formatters, error): with pytest.raises(error): - web3.manager.formatted_response(response, - params, - error_formatters, - null_result_formatters) + w3.manager.formatted_response(response, + params, + error_formatters, + null_result_formatters) @pytest.mark.parametrize( @@ -166,7 +166,7 @@ def test_formatted_response_raises_errors(web3, ], ) def test_formatted_response_raises_correct_error_message(response, - web3, + w3, params, error_formatters, null_result_formatters, @@ -174,7 +174,7 @@ def test_formatted_response_raises_correct_error_message(response, error_message): with pytest.raises(error, match=error_message): - web3.manager.formatted_response(response, params, error_formatters, null_result_formatters) + w3.manager.formatted_response(response, params, error_formatters, null_result_formatters) @pytest.mark.parametrize( @@ -199,14 +199,14 @@ def test_formatted_response_raises_correct_error_message(response, ], ) def test_formatted_response(response, - web3, + w3, params, error_formatters, null_result_formatters, expected): - formatted_resp = web3.manager.formatted_response(response, - params, - error_formatters, - null_result_formatters) + formatted_resp = w3.manager.formatted_response(response, + params, + error_formatters, + null_result_formatters) assert formatted_resp == expected diff --git a/tests/core/middleware/test_gas_price_strategy.py b/tests/core/middleware/test_gas_price_strategy.py index e3a2562cbe..4a4a2d3ab4 100644 --- a/tests/core/middleware/test_gas_price_strategy.py +++ b/tests/core/middleware/test_gas_price_strategy.py @@ -9,23 +9,23 @@ @pytest.fixture -def the_gas_price_strategy_middleware(web3): - make_request, web3 = Mock(), Mock() - initialized = gas_price_strategy_middleware(make_request, web3) - initialized.web3 = web3 +def the_gas_price_strategy_middleware(w3): + make_request, w3 = Mock(), Mock() + initialized = gas_price_strategy_middleware(make_request, w3) + initialized.w3 = w3 initialized.make_request = make_request return initialized def test_gas_price_generated(the_gas_price_strategy_middleware): - the_gas_price_strategy_middleware.web3.eth.generate_gas_price.return_value = 5 + the_gas_price_strategy_middleware.w3.eth.generate_gas_price.return_value = 5 method = 'eth_sendTransaction' params = ({ 'to': '0x0', 'value': 1, },) the_gas_price_strategy_middleware(method, params) - the_gas_price_strategy_middleware.web3.eth.generate_gas_price.assert_called_once_with({ + the_gas_price_strategy_middleware.w3.eth.generate_gas_price.assert_called_once_with({ 'to': '0x0', 'value': 1, }) @@ -37,7 +37,7 @@ def test_gas_price_generated(the_gas_price_strategy_middleware): def test_gas_price_not_overridden(the_gas_price_strategy_middleware): - the_gas_price_strategy_middleware.web3.eth.generate_gas_price.return_value = 5 + the_gas_price_strategy_middleware.w3.eth.generate_gas_price.return_value = 5 method = 'eth_sendTransaction' params = ({ 'to': '0x0', @@ -53,7 +53,7 @@ def test_gas_price_not_overridden(the_gas_price_strategy_middleware): def test_gas_price_not_set_without_gas_price_strategy(the_gas_price_strategy_middleware): - the_gas_price_strategy_middleware.web3.eth.generate_gas_price.return_value = None + the_gas_price_strategy_middleware.w3.eth.generate_gas_price.return_value = None method = 'eth_sendTransaction' params = ({ 'to': '0x0', @@ -64,6 +64,6 @@ def test_gas_price_not_set_without_gas_price_strategy(the_gas_price_strategy_mid def test_not_generate_gas_price_when_not_send_transaction_rpc(the_gas_price_strategy_middleware): - the_gas_price_strategy_middleware.web3.getGasPriceStrategy = Mock() + the_gas_price_strategy_middleware.w3.getGasPriceStrategy = Mock() the_gas_price_strategy_middleware('eth_getBalance', []) - the_gas_price_strategy_middleware.web3.getGasPriceStrategy.assert_not_called() + the_gas_price_strategy_middleware.w3.getGasPriceStrategy.assert_not_called() diff --git a/tests/core/middleware/test_http_request_retry.py b/tests/core/middleware/test_http_request_retry.py index 7558a9df1c..c11324908b 100644 --- a/tests/core/middleware/test_http_request_retry.py +++ b/tests/core/middleware/test_http_request_retry.py @@ -24,11 +24,11 @@ @pytest.fixture def exception_retry_request_setup(): - web3 = Mock() + w3 = Mock() provider = HTTPProvider() errors = (ConnectionError, HTTPError, Timeout, TooManyRedirects) - setup = exception_retry_middleware(provider.make_request, web3, errors, 5) - setup.web3 = web3 + setup = exception_retry_middleware(provider.make_request, w3, errors, 5) + setup.w3 = w3 return setup @@ -68,11 +68,11 @@ def test_valid_method_retried(make_post_request_mock, exception_retry_request_se def test_is_strictly_default_http_middleware(): - web3 = HTTPProvider() - assert 'http_retry_request' in web3.middlewares + w3 = HTTPProvider() + assert 'http_retry_request' in w3.middlewares - web3 = IPCProvider() - assert 'http_retry_request' not in web3.middlewares + w3 = IPCProvider() + assert 'http_retry_request' not in w3.middlewares @patch('web3.providers.rpc.make_post_request', side_effect=ConnectionError) diff --git a/tests/core/mining-module/conftest.py b/tests/core/mining-module/conftest.py index 4e6ab94eb8..359e0741ea 100644 --- a/tests/core/mining-module/conftest.py +++ b/tests/core/mining-module/conftest.py @@ -2,12 +2,12 @@ @pytest.fixture(autouse=True) -def always_wait_for_mining_start(web3, +def always_wait_for_mining_start(w3, wait_for_miner_start, skip_if_testrpc): - skip_if_testrpc(web3) + skip_if_testrpc(w3) - wait_for_miner_start(web3) + wait_for_miner_start(w3) - assert web3.eth.mining - assert web3.eth.hashrate + assert w3.eth.mining + assert w3.eth.hashrate diff --git a/tests/core/pm-module/test_ens_integration.py b/tests/core/pm-module/test_ens_integration.py index 163dcae8ff..c6bd38b519 100644 --- a/tests/core/pm-module/test_ens_integration.py +++ b/tests/core/pm-module/test_ens_integration.py @@ -116,19 +116,19 @@ def ens_setup(deployer): @pytest.fixture def ens(ens_setup, mocker): mocker.patch('web3.middleware.stalecheck._isfresh', return_value=True) - ens_setup.web3.eth.default_account = ens_setup.web3.eth.coinbase - ens_setup.web3.enable_unstable_package_management_api() + ens_setup.w3.eth.default_account = ens_setup.w3.eth.coinbase + ens_setup.w3.enable_unstable_package_management_api() return ens_setup def test_ens_must_be_set_before_ens_methods_can_be_used(ens): - w3 = ens.web3 + w3 = ens.w3 with pytest.raises(InvalidAddress): w3.pm.set_registry("tester.eth") def test_web3_ens(ens): - w3 = ens.web3 + w3 = ens.w3 ns = ENS.fromWeb3(w3, ens.ens.address) w3.ens = ns registry = SimpleRegistry.deploy_new_instance(w3) diff --git a/tests/core/providers/test_http_provider.py b/tests/core/providers/test_http_provider.py index f0e28c43aa..7ae1ec62f9 100644 --- a/tests/core/providers/test_http_provider.py +++ b/tests/core/providers/test_http_provider.py @@ -18,15 +18,15 @@ def test_no_args(): provider = HTTPProvider() - web3 = Web3(provider) - assert web3.manager.provider == provider + w3 = Web3(provider) + assert w3.manager.provider == provider def test_init_kwargs(): provider = HTTPProvider(endpoint_uri=URI, request_kwargs={'timeout': 60}) - web3 = Web3(provider) - assert web3.manager.provider == provider + w3 = Web3(provider) + assert w3.manager.provider == provider def test_user_provided_session(): @@ -36,8 +36,8 @@ def test_user_provided_session(): session.mount('https://', adapter) provider = HTTPProvider(endpoint_uri=URI, session=session) - web3 = Web3(provider) - assert web3.manager.provider == provider + w3 = Web3(provider) + assert w3.manager.provider == provider session = request._get_session(URI) adapter = session.get_adapter(URI) diff --git a/tests/core/providers/test_provider.py b/tests/core/providers/test_provider.py index d71744fb3a..7845d75f03 100644 --- a/tests/core/providers/test_provider.py +++ b/tests/core/providers/test_provider.py @@ -19,8 +19,8 @@ def test_isConnected_connected(): """ Web3.isConnected() returns True when connected to a node. """ - web3 = Web3(ConnectedProvider()) - assert web3.isConnected() is True + w3 = Web3(ConnectedProvider()) + assert w3.isConnected() is True def test_isConnected_disconnected(): @@ -28,8 +28,8 @@ def test_isConnected_disconnected(): Web3.isConnected() returns False when configured with a provider that's not connected to a node. """ - web3 = Web3(DisconnectedProvider()) - assert web3.isConnected() is False + w3 = Web3(DisconnectedProvider()) + assert w3.isConnected() is False def test_autoprovider_detection(): diff --git a/tests/core/testing-module/test_testing_mine.py b/tests/core/testing-module/test_testing_mine.py index b5e59451b4..40a52634fa 100644 --- a/tests/core/testing-module/test_testing_mine.py +++ b/tests/core/testing-module/test_testing_mine.py @@ -1,22 +1,22 @@ -def test_testing_mine_single_block(web3): - web3.testing.mine() +def test_testing_mine_single_block(w3): + w3.testing.mine() - before_mining_block = web3.eth.get_block("latest") + before_mining_block = w3.eth.get_block("latest") - web3.testing.mine() + w3.testing.mine() - after_mining_block = web3.eth.get_block("latest") + after_mining_block = w3.eth.get_block("latest") assert after_mining_block['number'] - before_mining_block['number'] == 1 -def test_testing_mine_multiple_blocks(web3): - web3.testing.mine() +def test_testing_mine_multiple_blocks(w3): + w3.testing.mine() - before_mining_block = web3.eth.get_block("latest") + before_mining_block = w3.eth.get_block("latest") - web3.testing.mine(5) + w3.testing.mine(5) - after_mining_block = web3.eth.get_block("latest") + after_mining_block = w3.eth.get_block("latest") assert after_mining_block['number'] - before_mining_block['number'] == 5 diff --git a/tests/core/testing-module/test_testing_snapshot_and_revert.py b/tests/core/testing-module/test_testing_snapshot_and_revert.py index 8f54dfbc13..5c3df21084 100644 --- a/tests/core/testing-module/test_testing_snapshot_and_revert.py +++ b/tests/core/testing-module/test_testing_snapshot_and_revert.py @@ -1,46 +1,46 @@ -def test_snapshot_revert_to_latest_snapshot(web3): - web3.testing.mine(5) +def test_snapshot_revert_to_latest_snapshot(w3): + w3.testing.mine(5) - block_before_snapshot = web3.eth.get_block("latest") + block_before_snapshot = w3.eth.get_block("latest") - web3.testing.snapshot() + w3.testing.snapshot() - block_after_snapshot = web3.eth.get_block("latest") + block_after_snapshot = w3.eth.get_block("latest") - web3.testing.mine(3) + w3.testing.mine(3) - block_after_mining = web3.eth.get_block("latest") + block_after_mining = w3.eth.get_block("latest") - web3.testing.revert() + w3.testing.revert() - block_after_revert = web3.eth.get_block("latest") + block_after_revert = w3.eth.get_block("latest") assert block_after_mining['number'] > block_before_snapshot['number'] assert block_before_snapshot['hash'] == block_after_snapshot['hash'] assert block_after_snapshot['hash'] == block_after_revert['hash'] -def test_snapshot_revert_to_specific(web3): - web3.testing.mine(5) +def test_snapshot_revert_to_specific(w3): + w3.testing.mine(5) - block_before_snapshot = web3.eth.get_block("latest") + block_before_snapshot = w3.eth.get_block("latest") - snapshot_idx = web3.testing.snapshot() + snapshot_idx = w3.testing.snapshot() - block_after_snapshot = web3.eth.get_block("latest") + block_after_snapshot = w3.eth.get_block("latest") - web3.testing.mine() - web3.testing.snapshot() - web3.testing.mine() - web3.testing.snapshot() - web3.testing.mine() - web3.testing.snapshot() + w3.testing.mine() + w3.testing.snapshot() + w3.testing.mine() + w3.testing.snapshot() + w3.testing.mine() + w3.testing.snapshot() - block_after_mining = web3.eth.get_block("latest") + block_after_mining = w3.eth.get_block("latest") - web3.testing.revert(snapshot_idx) + w3.testing.revert(snapshot_idx) - block_after_revert = web3.eth.get_block("latest") + block_after_revert = w3.eth.get_block("latest") assert block_after_mining['number'] > block_before_snapshot['number'] assert block_before_snapshot['hash'] == block_after_snapshot['hash'] diff --git a/tests/core/testing-module/test_testing_timeTravel.py b/tests/core/testing-module/test_testing_timeTravel.py index 2a135cee44..2f65f47b36 100644 --- a/tests/core/testing-module/test_testing_timeTravel.py +++ b/tests/core/testing-module/test_testing_timeTravel.py @@ -1,9 +1,9 @@ -def test_time_traveling(web3): - current_block_time = web3.eth.get_block("pending")['timestamp'] +def test_time_traveling(w3): + current_block_time = w3.eth.get_block("pending")['timestamp'] time_travel_to = current_block_time + 12345 - web3.testing.timeTravel(time_travel_to) + w3.testing.timeTravel(time_travel_to) - latest_block_time = web3.eth.get_block("pending")['timestamp'] + latest_block_time = w3.eth.get_block("pending")['timestamp'] assert latest_block_time >= time_travel_to diff --git a/tests/core/txpool-module/conftest.py b/tests/core/txpool-module/conftest.py index 0d64d61fa8..6b15c8989c 100644 --- a/tests/core/txpool-module/conftest.py +++ b/tests/core/txpool-module/conftest.py @@ -2,12 +2,12 @@ @pytest.fixture(autouse=True) -def skip_testrpc_and_wait_for_mining_start(web3, +def skip_testrpc_and_wait_for_mining_start(w3, wait_for_miner_start, skip_if_testrpc): - skip_if_testrpc(web3) + skip_if_testrpc(w3) - wait_for_miner_start(web3) + wait_for_miner_start(w3) - assert web3.eth.mining - assert web3.eth.hashrate + assert w3.eth.mining + assert w3.eth.hashrate diff --git a/tests/core/utilities/conftest.py b/tests/core/utilities/conftest.py index 49bc15d4fb..8274f13e5c 100644 --- a/tests/core/utilities/conftest.py +++ b/tests/core/utilities/conftest.py @@ -9,6 +9,6 @@ @pytest.fixture(scope="module") -def web3(): +def w3(): provider = EthereumTesterProvider() return Web3(provider) diff --git a/tests/core/utilities/test_abi_is_encodable.py b/tests/core/utilities/test_abi_is_encodable.py index 958c8e631a..5bf1178cf2 100644 --- a/tests/core/utilities/test_abi_is_encodable.py +++ b/tests/core/utilities/test_abi_is_encodable.py @@ -64,8 +64,8 @@ ((b'\x80', 0), '(string,int128)', False), ), ) -def test_is_encodable(web3, value, _type, expected): - actual = web3.is_encodable(_type, value) +def test_is_encodable(w3, value, _type, expected): + actual = w3.is_encodable(_type, value) assert actual is expected @@ -78,12 +78,12 @@ def test_is_encodable(web3, value, _type, expected): ('12', 'bytes', True), # no 0x prefix, can be decoded as hex ) ) -def test_is_encodable_warnings(web3, value, _type, expected): +def test_is_encodable_warnings(w3, value, _type, expected): with pytest.warns( DeprecationWarning, match='in v6 it will be invalid to pass a hex string without the "0x" prefix' ): - actual = web3.is_encodable(_type, value) + actual = w3.is_encodable(_type, value) assert actual is expected diff --git a/tests/core/utilities/test_attach_modules.py b/tests/core/utilities/test_attach_modules.py index 4d151cc73a..bc65b64847 100644 --- a/tests/core/utilities/test_attach_modules.py +++ b/tests/core/utilities/test_attach_modules.py @@ -169,7 +169,7 @@ def test_attach_external_modules_that_do_not_inherit_from_module_class( assert is_integer(w3.eth.chain_id) -def test_attach_modules_for_module_with_more_than_one_init_argument(web3, module_many_init_args): +def test_attach_modules_for_module_with_more_than_one_init_argument(w3, module_many_init_args): with pytest.raises( UnsupportedOperation, match=( diff --git a/tests/core/utilities/test_construct_event_data_set.py b/tests/core/utilities/test_construct_event_data_set.py index 6cbc7d73fd..5f5ad8a78c 100644 --- a/tests/core/utilities/test_construct_event_data_set.py +++ b/tests/core/utilities/test_construct_event_data_set.py @@ -77,8 +77,8 @@ def hex_and_pad(i): ), ) ) -def test_construct_event_data_set(web3, arguments, expected): - actual = construct_event_data_set(EVENT_1_ABI, web3.codec, arguments) +def test_construct_event_data_set(w3, arguments, expected): + actual = construct_event_data_set(EVENT_1_ABI, w3.codec, arguments) assert actual == expected diff --git a/tests/core/utilities/test_construct_event_filter_params.py b/tests/core/utilities/test_construct_event_filter_params.py index 882d04ef5b..5300b6ea60 100644 --- a/tests/core/utilities/test_construct_event_filter_params.py +++ b/tests/core/utilities/test_construct_event_filter_params.py @@ -46,8 +46,8 @@ }), ), ) -def test_construct_event_filter_params(web3, event_abi, fn_kwargs, expected): - _, actual = construct_event_filter_params(event_abi, web3.codec, **fn_kwargs) +def test_construct_event_filter_params(w3, event_abi, fn_kwargs, expected): + _, actual = construct_event_filter_params(event_abi, w3.codec, **fn_kwargs) assert actual == expected @@ -68,7 +68,7 @@ def hex_and_pad(i): ]), ), ) -def test_construct_event_filter_params_for_data_filters(event_abi, web3, fn_kwargs, +def test_construct_event_filter_params_for_data_filters(event_abi, w3, fn_kwargs, expected): - actual, _ = construct_event_filter_params(event_abi, web3.codec, **fn_kwargs) + actual, _ = construct_event_filter_params(event_abi, w3.codec, **fn_kwargs) assert actual == expected diff --git a/tests/core/utilities/test_construct_event_topics.py b/tests/core/utilities/test_construct_event_topics.py index 0931ba2cda..a76941a306 100644 --- a/tests/core/utilities/test_construct_event_topics.py +++ b/tests/core/utilities/test_construct_event_topics.py @@ -83,8 +83,8 @@ def hex_and_pad(i): ), ) ) -def test_construct_event_topics(web3, arguments, expected): - actual = construct_event_topic_set(EVENT_1_ABI, web3.codec, arguments) +def test_construct_event_topics(w3, arguments, expected): + actual = construct_event_topic_set(EVENT_1_ABI, w3.codec, arguments) assert actual == expected diff --git a/tests/core/utilities/test_event_filter_builder.py b/tests/core/utilities/test_event_filter_builder.py index 08ac40339e..93bb1dd7fd 100644 --- a/tests/core/utilities/test_event_filter_builder.py +++ b/tests/core/utilities/test_event_filter_builder.py @@ -43,21 +43,21 @@ def test_match_single_string_type_properties_data_arg(value): @given(st.text()) -def test_match_single_string_type_properties_topic_arg(web3, value): - topic_filter = TopicArgumentFilter(arg_type="string", abi_codec=web3.codec) +def test_match_single_string_type_properties_topic_arg(w3, value): + topic_filter = TopicArgumentFilter(arg_type="string", abi_codec=w3.codec) topic_filter.match_single(value) @given(st.lists(elements=st.text(), max_size=10, min_size=0)) -def test_match_any_string_type_properties(web3, values): - topic_filter = TopicArgumentFilter(arg_type="string", abi_codec=web3.codec) +def test_match_any_string_type_properties(w3, values): + topic_filter = TopicArgumentFilter(arg_type="string", abi_codec=w3.codec) topic_filter.match_any(*values) assert len(topic_filter.match_values) == len(values) @given(st.lists(elements=st.binary(), max_size=10, min_size=0)) -def test_match_any_bytes_type_properties(web3, values): - topic_filter = TopicArgumentFilter(arg_type="bytes", abi_codec=web3.codec) +def test_match_any_bytes_type_properties(w3, values): + topic_filter = TopicArgumentFilter(arg_type="bytes", abi_codec=w3.codec) topic_filter.match_any(*values) assert len(topic_filter.match_values) == len(values) diff --git a/tests/core/utilities/test_event_interface.py b/tests/core/utilities/test_event_interface.py index 4f72ccd5fb..7a87fdb1ea 100644 --- a/tests/core/utilities/test_event_interface.py +++ b/tests/core/utilities/test_event_interface.py @@ -16,19 +16,19 @@ } -def test_access_event_with_no_abi(web3): - contract = web3.eth.contract() +def test_access_event_with_no_abi(w3): + contract = w3.eth.contract() with pytest.raises(NoABIEventsFound): contract.events.thisEventDoesNotExist() -def test_access_event_abi_with_no_events(web3): - contract = web3.eth.contract(abi=[]) +def test_access_event_abi_with_no_events(w3): + contract = w3.eth.contract(abi=[]) with pytest.raises(NoABIEventsFound): contract.events.thisEventDoesNotExist() -def test_access_nonexistent_event(web3): - contract = web3.eth.contract(abi=[EVENT_1_ABI]) +def test_access_nonexistent_event(w3): + contract = w3.eth.contract(abi=[EVENT_1_ABI]) with pytest.raises(MismatchedABI): contract.events.thisEventDoesNotExist() diff --git a/tests/core/utilities/test_fee_utils.py b/tests/core/utilities/test_fee_utils.py index 106b247a24..79f14913ff 100644 --- a/tests/core/utilities/test_fee_utils.py +++ b/tests/core/utilities/test_fee_utils.py @@ -39,7 +39,7 @@ ) # Test fee_utils indirectly by mocking eth_feeHistory results and checking against expected output def test_fee_utils_indirectly( - web3, fee_history_rewards, expected_max_prio_calc + w3, fee_history_rewards, expected_max_prio_calc ) -> None: fail_max_prio_middleware = construct_error_generator_middleware( {RPCEndpoint("eth_maxPriorityFeePerGas"): lambda *_: ''} @@ -48,18 +48,18 @@ def test_fee_utils_indirectly( {RPCEndpoint('eth_feeHistory'): lambda *_: {'reward': fee_history_rewards}} ) - web3.middleware_onion.add(fail_max_prio_middleware, 'fail_max_prio') - web3.middleware_onion.inject(fee_history_result_middleware, 'fee_history_result', layer=0) + w3.middleware_onion.add(fail_max_prio_middleware, 'fail_max_prio') + w3.middleware_onion.inject(fee_history_result_middleware, 'fee_history_result', layer=0) with pytest.warns( UserWarning, match="There was an issue with the method eth_maxPriorityFeePerGas. Calculating using " "eth_feeHistory." ): - max_priority_fee = web3.eth.max_priority_fee + max_priority_fee = w3.eth.max_priority_fee assert is_integer(max_priority_fee) assert max_priority_fee == expected_max_prio_calc # clean up - web3.middleware_onion.remove('fail_max_prio') - web3.middleware_onion.remove('fee_history_result') + w3.middleware_onion.remove('fail_max_prio') + w3.middleware_onion.remove('fee_history_result') diff --git a/tests/core/utilities/test_prepare_transaction_replacement.py b/tests/core/utilities/test_prepare_transaction_replacement.py index ffef3e7af0..cb0a84fd2e 100644 --- a/tests/core/utilities/test_prepare_transaction_replacement.py +++ b/tests/core/utilities/test_prepare_transaction_replacement.py @@ -12,14 +12,14 @@ } -def test_prepare_transaction_replacement(web3): +def test_prepare_transaction_replacement(w3): current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = { 'value': 1, 'nonce': 2, } replacement_transaction = prepare_replacement_transaction( - web3, current_transaction, new_transaction) + w3, current_transaction, new_transaction) assert replacement_transaction == { 'value': 1, @@ -28,13 +28,13 @@ def test_prepare_transaction_replacement(web3): } -def test_prepare_transaction_replacement_without_nonce_sets_correct_nonce(web3): +def test_prepare_transaction_replacement_without_nonce_sets_correct_nonce(w3): current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = { 'value': 1, } replacement_transaction = prepare_replacement_transaction( - web3, current_transaction, new_transaction) + w3, current_transaction, new_transaction) assert replacement_transaction == { 'value': 1, 'nonce': 2, @@ -42,15 +42,15 @@ def test_prepare_transaction_replacement_without_nonce_sets_correct_nonce(web3): } -def test_prepare_transaction_replacement_already_mined_raises(web3): +def test_prepare_transaction_replacement_already_mined_raises(w3): with pytest.raises(ValueError): prepare_replacement_transaction( - web3, {'blockHash': '0xa1a1a1', 'hash': '0x0'}, {'value': 2}) + w3, {'blockHash': '0xa1a1a1', 'hash': '0x0'}, {'value': 2}) -def test_prepare_transaction_replacement_nonce_mismatch_raises(web3): +def test_prepare_transaction_replacement_nonce_mismatch_raises(w3): with pytest.raises(ValueError): - prepare_replacement_transaction(web3, { + prepare_replacement_transaction(w3, { 'blockHash': None, 'hash': '0x0', 'nonce': 1, @@ -59,7 +59,7 @@ def test_prepare_transaction_replacement_nonce_mismatch_raises(web3): }) -def test_prepare_transaction_replacement_not_higher_gas_price_raises(web3): +def test_prepare_transaction_replacement_not_higher_gas_price_raises(w3): current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = { 'value': 1, @@ -67,31 +67,31 @@ def test_prepare_transaction_replacement_not_higher_gas_price_raises(web3): } with pytest.raises(ValueError): prepare_replacement_transaction( - web3, current_transaction, new_transaction) + w3, current_transaction, new_transaction) # Also raises when equal to the current transaction new_transaction['gasPrice'] = 10 with pytest.raises(ValueError): - prepare_replacement_transaction(web3, current_transaction, new_transaction) + prepare_replacement_transaction(w3, current_transaction, new_transaction) -def test_prepare_transaction_replacement_gas_price_defaulting(web3): +def test_prepare_transaction_replacement_gas_price_defaulting(w3): current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = { 'value': 2, } replacement_transaction = prepare_replacement_transaction( - web3, current_transaction, new_transaction) + w3, current_transaction, new_transaction) assert replacement_transaction['gasPrice'] == 12 -def test_prepare_transaction_replacement_gas_price_defaulting_when_strategy_higer(web3): +def test_prepare_transaction_replacement_gas_price_defaulting_when_strategy_higer(w3): - def higher_gas_price_strategy(web3, txn): + def higher_gas_price_strategy(w3, txn): return 20 - web3.eth.set_gas_price_strategy(higher_gas_price_strategy) + w3.eth.set_gas_price_strategy(higher_gas_price_strategy) current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = { @@ -99,17 +99,17 @@ def higher_gas_price_strategy(web3, txn): } replacement_transaction = prepare_replacement_transaction( - web3, current_transaction, new_transaction) + w3, current_transaction, new_transaction) assert replacement_transaction['gasPrice'] == 20 -def test_prepare_transaction_replacement_gas_price_defaulting_when_strategy_lower(web3): +def test_prepare_transaction_replacement_gas_price_defaulting_when_strategy_lower(w3): - def lower_gas_price_strategy(web3, txn): + def lower_gas_price_strategy(w3, txn): return 5 - web3.eth.set_gas_price_strategy(lower_gas_price_strategy) + w3.eth.set_gas_price_strategy(lower_gas_price_strategy) current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = { @@ -117,6 +117,6 @@ def lower_gas_price_strategy(web3, txn): } replacement_transaction = prepare_replacement_transaction( - web3, current_transaction, new_transaction) + w3, current_transaction, new_transaction) assert replacement_transaction['gasPrice'] == 12 diff --git a/tests/core/utilities/test_valid_transaction_params.py b/tests/core/utilities/test_valid_transaction_params.py index 4424efa00b..0ae866bce1 100644 --- a/tests/core/utilities/test_valid_transaction_params.py +++ b/tests/core/utilities/test_valid_transaction_params.py @@ -136,16 +136,16 @@ def test_extract_valid_transaction_params_includes_invalid(): } -def test_fill_transaction_defaults_for_all_params(web3): - default_transaction = fill_transaction_defaults(web3, {}) +def test_fill_transaction_defaults_for_all_params(w3): + default_transaction = fill_transaction_defaults(w3, {}) assert default_transaction == { - 'chainId': web3.eth.chain_id, + 'chainId': w3.eth.chain_id, 'data': b'', - 'gas': web3.eth.estimate_gas({}), + 'gas': w3.eth.estimate_gas({}), 'maxFeePerGas': ( - web3.eth.max_priority_fee + (2 * web3.eth.get_block('latest')['baseFeePerGas']) + w3.eth.max_priority_fee + (2 * w3.eth.get_block('latest')['baseFeePerGas']) ), - 'maxPriorityFeePerGas': web3.eth.max_priority_fee, + 'maxPriorityFeePerGas': w3.eth.max_priority_fee, 'value': 0, } diff --git a/tests/core/web3-module/test_api.py b/tests/core/web3-module/test_api.py index d5ccdd84cb..97bbd32f1b 100644 --- a/tests/core/web3-module/test_api.py +++ b/tests/core/web3-module/test_api.py @@ -1,2 +1,2 @@ -def test_web3_api(web3): - assert web3.api.startswith("6") +def test_web3_api(w3): + assert w3.api.startswith("6") diff --git a/tests/core/web3-module/test_attach_modules.py b/tests/core/web3-module/test_attach_modules.py index 35f575cb06..42b453b3d4 100644 --- a/tests/core/web3-module/test_attach_modules.py +++ b/tests/core/web3-module/test_attach_modules.py @@ -8,8 +8,8 @@ ) -def test_attach_modules(web3, module1, module2, module3, module4): - web3.attach_modules({ +def test_attach_modules(w3, module1, module2, module3, module4): + w3.attach_modules({ 'module1': module1, 'module2': (module2, { 'submodule1': (module3, { @@ -19,30 +19,30 @@ def test_attach_modules(web3, module1, module2, module3, module4): }) # assert module1 attached - assert hasattr(web3, 'module1') - assert web3.module1.a == 'a' - assert web3.module1.b == 'b' + assert hasattr(w3, 'module1') + assert w3.module1.a == 'a' + assert w3.module1.b == 'b' # assert module2 + submodules attached - assert hasattr(web3, 'module2') - assert web3.module2.c == 'c' - assert web3.module2.d() == 'd' + assert hasattr(w3, 'module2') + assert w3.module2.c == 'c' + assert w3.module2.d() == 'd' - assert hasattr(web3.module2, 'submodule1') - assert web3.module2.submodule1.e == 'e' - assert hasattr(web3.module2.submodule1, 'submodule2') - assert web3.module2.submodule1.submodule2.f == 'f' + assert hasattr(w3.module2, 'submodule1') + assert w3.module2.submodule1.e == 'e' + assert hasattr(w3.module2.submodule1, 'submodule2') + assert w3.module2.submodule1.submodule2.f == 'f' # assert default modules intact - assert hasattr(web3, 'geth') - assert hasattr(web3, 'eth') - assert is_integer(web3.eth.chain_id) + assert hasattr(w3, 'geth') + assert hasattr(w3, 'eth') + assert is_integer(w3.eth.chain_id) def test_attach_modules_that_do_not_inherit_from_module_class( - web3, module1_unique, module2_unique, module3_unique, module4_unique, + w3, module1_unique, module2_unique, module3_unique, module4_unique, ): - web3.attach_modules( + w3.attach_modules( { 'module1': module1_unique, 'module2': (module2_unique, { @@ -54,28 +54,28 @@ def test_attach_modules_that_do_not_inherit_from_module_class( ) # assert module1 attached - assert hasattr(web3, 'module1') - assert web3.module1.a == 'a' - assert web3.module1.b() == 'b' - assert web3.module1.return_eth_chain_id == web3.eth.chain_id + assert hasattr(w3, 'module1') + assert w3.module1.a == 'a' + assert w3.module1.b() == 'b' + assert w3.module1.return_eth_chain_id == w3.eth.chain_id # assert module2 + submodules attached - assert hasattr(web3, 'module2') - assert web3.module2.c == 'c' - assert web3.module2.d() == 'd' + assert hasattr(w3, 'module2') + assert w3.module2.c == 'c' + assert w3.module2.d() == 'd' - assert hasattr(web3.module2, 'submodule1') - assert web3.module2.submodule1.e == 'e' - assert hasattr(web3.module2.submodule1, 'submodule2') - assert web3.module2.submodule1.submodule2.f == 'f' + assert hasattr(w3.module2, 'submodule1') + assert w3.module2.submodule1.e == 'e' + assert hasattr(w3.module2.submodule1, 'submodule2') + assert w3.module2.submodule1.submodule2.f == 'f' # assert default modules intact - assert hasattr(web3, 'geth') - assert hasattr(web3, 'eth') - assert is_integer(web3.eth.chain_id) + assert hasattr(w3, 'geth') + assert hasattr(w3, 'eth') + assert is_integer(w3.eth.chain_id) -def test_attach_modules_for_module_with_more_than_one_init_argument(web3, module_many_init_args): +def test_attach_modules_for_module_with_more_than_one_init_argument(w3, module_many_init_args): with pytest.raises( UnsupportedOperation, match=( @@ -83,4 +83,4 @@ def test_attach_modules_for_module_with_more_than_one_init_argument(web3, module "__init__\\(\\) method. More than one argument found for ModuleManyArgs: \\['a', 'b']" ) ): - web3.attach_modules({'module_should_fail': module_many_init_args}) + w3.attach_modules({'module_should_fail': module_many_init_args}) diff --git a/tests/core/web3-module/test_clientVersion.py b/tests/core/web3-module/test_clientVersion.py index 4f2783adcf..2d117b1af2 100644 --- a/tests/core/web3-module/test_clientVersion.py +++ b/tests/core/web3-module/test_clientVersion.py @@ -1,2 +1,2 @@ -def test_web3_clientVersion(web3): - assert web3.clientVersion.startswith("EthereumTester/") +def test_web3_clientVersion(w3): + assert w3.clientVersion.startswith("EthereumTester/") diff --git a/tests/core/web3-module/test_providers.py b/tests/core/web3-module/test_providers.py index 92069c71a9..c4612d77d8 100644 --- a/tests/core/web3-module/test_providers.py +++ b/tests/core/web3-module/test_providers.py @@ -7,12 +7,12 @@ ) -def test_set_provider(web3): +def test_set_provider(w3): provider = EthereumTesterProvider() - web3.provider = provider + w3.provider = provider - assert web3.provider == provider + assert w3.provider == provider def test_auto_provider_none(): diff --git a/tests/ens/conftest.py b/tests/ens/conftest.py index 88c58cd2f6..7a3d2044dd 100644 --- a/tests/ens/conftest.py +++ b/tests/ens/conftest.py @@ -220,7 +220,7 @@ def ens_setup(): @pytest.fixture def ens(ens_setup, mocker): mocker.patch('web3.middleware.stalecheck._isfresh', return_value=True) - ens_setup.web3.eth.default_account = ens_setup.web3.eth.coinbase + ens_setup.w3.eth.default_account = ens_setup.w3.eth.coinbase return ens_setup diff --git a/tests/ens/test_ens.py b/tests/ens/test_ens.py index d4febe2c1a..ae552f2785 100644 --- a/tests/ens/test_ens.py +++ b/tests/ens/test_ens.py @@ -4,9 +4,9 @@ ) -def test_fromWeb3_inherits_web3_middlewares(web3): +def test_fromWeb3_inherits_web3_middlewares(w3): test_middleware = pythonic_middleware - web3.middleware_onion.add(test_middleware, 'test_middleware') + w3.middleware_onion.add(test_middleware, 'test_middleware') - ns = ENS.fromWeb3(web3) - assert ns.web3.middleware_onion.get('test_middleware') == test_middleware + ns = ENS.fromWeb3(w3) + assert ns.w3.middleware_onion.get('test_middleware') == test_middleware diff --git a/tests/ens/test_setup_address.py b/tests/ens/test_setup_address.py index fb5df1d309..326161989b 100644 --- a/tests/ens/test_setup_address.py +++ b/tests/ens/test_setup_address.py @@ -112,7 +112,7 @@ def test_set_address_equivalence(ens, name, equivalent, TEST_ADDRESS): ], ) def test_set_address_noop(ens, set_address): - eth = ens.web3.eth + eth = ens.w3.eth owner = ens.owner('tester.eth') ens.setup_address('noop.tester.eth', set_address) starting_transactions = eth.get_transaction_count(owner) @@ -152,7 +152,7 @@ def getowner(name): def test_set_resolver_leave_default(ens, TEST_ADDRESS): owner = ens.owner('tester.eth') ens.setup_address('leave-default-resolver.tester.eth', TEST_ADDRESS) - eth = ens.web3.eth + eth = ens.w3.eth num_transactions = eth.get_transaction_count(owner) ens.setup_address( diff --git a/tests/ens/test_setup_name.py b/tests/ens/test_setup_name.py index a550ebfb64..26fb0a7e3b 100644 --- a/tests/ens/test_setup_name.py +++ b/tests/ens/test_setup_name.py @@ -55,7 +55,7 @@ def TEST_ADDRESS(address_conversion_func): ], ) def test_setup_name(ens, name, normalized_name, namehash_hex): - address = ens.web3.eth.accounts[3] + address = ens.w3.eth.accounts[3] assert not ens.name(address) owner = ens.owner('tester.eth') @@ -84,7 +84,7 @@ def test_cannot_set_name_on_mismatch_address(ens, TEST_ADDRESS): def test_setup_name_default_address(ens): name = 'reverse-defaults-to-forward.tester.eth' owner = ens.owner('tester.eth') - new_resolution = ens.web3.eth.accounts[-1] + new_resolution = ens.w3.eth.accounts[-1] ens.setup_address(name, new_resolution) assert not ens.name(new_resolution) assert ens.owner(name) == owner @@ -96,7 +96,7 @@ def test_setup_name_default_address(ens): def test_setup_name_default_to_owner(ens): name = 'reverse-defaults-to-owner.tester.eth' - new_owner = ens.web3.eth.accounts[-1] + new_owner = ens.w3.eth.accounts[-1] ens.setup_owner(name, new_owner) assert not ens.name(new_owner) assert ens.owner(name) == new_owner @@ -118,10 +118,10 @@ def test_setup_name_unauthorized(ens, TEST_ADDRESS): def test_setup_reverse_dict_unmodified(ens): # setup owner = ens.owner('tester.eth') - eth = ens.web3.eth + eth = ens.w3.eth start_count = eth.get_transaction_count(owner) - address = ens.web3.eth.accounts[3] + address = ens.w3.eth.accounts[3] transact = {} ens.setup_name('tester.eth', address, transact=transact) diff --git a/tests/integration/common.py b/tests/integration/common.py index e97aabae0c..218d9a4291 100644 --- a/tests/integration/common.py +++ b/tests/integration/common.py @@ -9,7 +9,7 @@ class MiscWebsocketTest: - def test_websocket_max_size_error(self, web3, endpoint_uri): + def test_websocket_max_size_error(self, w3, endpoint_uri): w3 = Web3(Web3.WebsocketProvider( endpoint_uri=endpoint_uri, websocket_kwargs={'max_size': 1}) ) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index dd254c6876..c9671aa285 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -16,22 +16,22 @@ @pytest.fixture(scope="module") -def math_contract_factory(web3): - contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) +def math_contract_factory(w3): + contract_factory = w3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) return contract_factory @pytest.fixture(scope="module") -def emitter_contract_factory(web3): - contract_factory = web3.eth.contract( +def emitter_contract_factory(w3): + contract_factory = w3.eth.contract( abi=CONTRACT_EMITTER_ABI, bytecode=CONTRACT_EMITTER_CODE ) return contract_factory @pytest.fixture(scope="module") -def revert_contract_factory(web3): - contract_factory = web3.eth.contract( +def revert_contract_factory(w3): + contract_factory = w3.eth.contract( abi=_REVERT_CONTRACT_ABI, bytecode=REVERT_CONTRACT_BYTECODE ) return contract_factory diff --git a/tests/integration/generate_fixtures/common.py b/tests/integration/generate_fixtures/common.py index 49ac85b8a2..d7d20a8964 100644 --- a/tests/integration/generate_fixtures/common.py +++ b/tests/integration/generate_fixtures/common.py @@ -201,15 +201,15 @@ def get_process(run_command): return proc -def mine_block(web3): - origin_block_number = web3.eth.block_number +def mine_block(w3): + origin_block_number = w3.eth.block_number start_time = time.time() - web3.geth.miner.start(1) + w3.geth.miner.start(1) while time.time() < start_time + 120: - block_number = web3.eth.block_number + block_number = w3.eth.block_number if block_number > origin_block_number: - web3.geth.miner.stop() + w3.geth.miner.stop() return block_number else: time.sleep(0.1) @@ -217,16 +217,16 @@ def mine_block(web3): raise ValueError("No block mined during wait period") -def mine_transaction_hash(web3, txn_hash): +def mine_transaction_hash(w3, txn_hash): start_time = time.time() - web3.geth.miner.start(1) + w3.geth.miner.start(1) while time.time() < start_time + 120: try: - receipt = web3.eth.get_transaction_receipt(txn_hash) + receipt = w3.eth.get_transaction_receipt(txn_hash) except TransactionNotFound: continue if receipt is not None: - web3.geth.miner.stop() + w3.geth.miner.stop() return receipt else: time.sleep(0.1) @@ -234,11 +234,11 @@ def mine_transaction_hash(web3, txn_hash): raise ValueError("Math contract deploy transaction not mined during wait period") -def deploy_contract(web3, name, factory): - web3.geth.personal.unlock_account(web3.eth.coinbase, KEYFILE_PW) - deploy_txn_hash = factory.constructor().transact({'from': web3.eth.coinbase}) +def deploy_contract(w3, name, factory): + w3.geth.personal.unlock_account(w3.eth.coinbase, KEYFILE_PW) + deploy_txn_hash = factory.constructor().transact({'from': w3.eth.coinbase}) print('{0}_CONTRACT_DEPLOY_HASH: '.format(name.upper()), deploy_txn_hash) - deploy_receipt = mine_transaction_hash(web3, deploy_txn_hash) + deploy_receipt = mine_transaction_hash(w3, deploy_txn_hash) print('{0}_CONTRACT_DEPLOY_TRANSACTION_MINED'.format(name.upper())) contract_address = deploy_receipt['contractAddress'] assert is_checksum_address(contract_address) diff --git a/tests/integration/generate_fixtures/go_ethereum.py b/tests/integration/generate_fixtures/go_ethereum.py index 41ff0682e0..d6d55b7ee2 100644 --- a/tests/integration/generate_fixtures/go_ethereum.py +++ b/tests/integration/generate_fixtures/go_ethereum.py @@ -136,11 +136,11 @@ def generate_go_ethereum_fixture(destination_dir): geth_port=geth_port): common.wait_for_socket(geth_ipc_path) - web3 = Web3(Web3.IPCProvider(geth_ipc_path)) - chain_data = setup_chain_state(web3) + w3 = Web3(Web3.IPCProvider(geth_ipc_path)) + chain_data = setup_chain_state(w3) # close geth by exiting context # must be closed before copying data dir - verify_chain_state(web3, chain_data) + verify_chain_state(w3, chain_data) # verify that chain state is still valid after closing # and re-opening geth @@ -152,8 +152,8 @@ def generate_go_ethereum_fixture(destination_dir): geth_port=geth_port): common.wait_for_socket(geth_ipc_path) - web3 = Web3(Web3.IPCProvider(geth_ipc_path)) - verify_chain_state(web3, chain_data) + w3 = Web3(Web3.IPCProvider(geth_ipc_path)) + verify_chain_state(w3, chain_data) static_data = { 'raw_txn_account': common.RAW_TXN_ACCOUNT, @@ -166,29 +166,29 @@ def generate_go_ethereum_fixture(destination_dir): shutil.make_archive(destination_dir, 'zip', datadir) -def verify_chain_state(web3, chain_data): - receipt = web3.eth.wait_for_transaction_receipt(chain_data['mined_txn_hash']) - latest = web3.eth.get_block('latest') +def verify_chain_state(w3, chain_data): + receipt = w3.eth.wait_for_transaction_receipt(chain_data['mined_txn_hash']) + latest = w3.eth.get_block('latest') assert receipt.blockNumber <= latest.number -def mine_transaction_hash(web3, txn_hash): - web3.geth.miner.start(1) +def mine_transaction_hash(w3, txn_hash): + w3.geth.miner.start(1) try: - return web3.eth.wait_for_transaction_receipt(txn_hash, timeout=120) + return w3.eth.wait_for_transaction_receipt(txn_hash, timeout=120) finally: - web3.geth.miner.stop() + w3.geth.miner.stop() -def mine_block(web3): - origin_block_number = web3.eth.block_number +def mine_block(w3): + origin_block_number = w3.eth.block_number start_time = time.time() - web3.geth.miner.start(1) + w3.geth.miner.start(1) while time.time() < start_time + 120: - block_number = web3.eth.block_number + block_number = w3.eth.block_number if block_number > origin_block_number: - web3.geth.miner.stop() + w3.geth.miner.stop() return block_number else: time.sleep(0.1) @@ -196,77 +196,77 @@ def mine_block(web3): raise ValueError("No block mined during wait period") -def setup_chain_state(web3): - coinbase = web3.eth.coinbase +def setup_chain_state(w3): + coinbase = w3.eth.coinbase assert is_same_address(coinbase, common.COINBASE) # # Math Contract # - math_contract_factory = web3.eth.contract( + math_contract_factory = w3.eth.contract( abi=MATH_ABI, bytecode=MATH_BYTECODE, ) - math_deploy_receipt = common.deploy_contract(web3, 'math', math_contract_factory) + math_deploy_receipt = common.deploy_contract(w3, 'math', math_contract_factory) assert is_dict(math_deploy_receipt) # # Emitter Contract # - emitter_contract_factory = web3.eth.contract( + emitter_contract_factory = w3.eth.contract( abi=CONTRACT_EMITTER_ABI, bytecode=CONTRACT_EMITTER_CODE, ) - emitter_deploy_receipt = common.deploy_contract(web3, 'emitter', emitter_contract_factory) + emitter_deploy_receipt = common.deploy_contract(w3, 'emitter', emitter_contract_factory) emitter_contract = emitter_contract_factory(emitter_deploy_receipt['contractAddress']) txn_hash_with_log = emitter_contract.functions.logDouble( which=EMITTER_ENUM['LogDoubleWithIndex'], arg0=12345, arg1=54321, ).transact({ - 'from': web3.eth.coinbase, + 'from': w3.eth.coinbase, }) print('TXN_HASH_WITH_LOG:', txn_hash_with_log) - txn_receipt_with_log = mine_transaction_hash(web3, txn_hash_with_log) - block_with_log = web3.eth.get_block(txn_receipt_with_log['blockHash']) + txn_receipt_with_log = mine_transaction_hash(w3, txn_hash_with_log) + block_with_log = w3.eth.get_block(txn_receipt_with_log['blockHash']) print('BLOCK_HASH_WITH_LOG:', block_with_log['hash']) # # Revert Contract # - revert_contract_factory = web3.eth.contract( + revert_contract_factory = w3.eth.contract( abi=_REVERT_CONTRACT_ABI, bytecode=REVERT_CONTRACT_BYTECODE, ) - revert_deploy_receipt = common.deploy_contract(web3, 'revert', revert_contract_factory) + revert_deploy_receipt = common.deploy_contract(w3, 'revert', revert_contract_factory) revert_contract = revert_contract_factory(revert_deploy_receipt['contractAddress']) txn_hash_normal_function = revert_contract.functions.normalFunction().transact( - {'gas': 320000, 'from': web3.eth.coinbase} + {'gas': 320000, 'from': w3.eth.coinbase} ) print('TXN_HASH_REVERT_NORMAL:', txn_hash_normal_function) txn_hash_revert_with_msg = revert_contract.functions.revertWithMessage().transact( - {'gas': 320000, 'from': web3.eth.coinbase} + {'gas': 320000, 'from': w3.eth.coinbase} ) print('TXN_HASH_REVERT_WITH_MSG:', txn_hash_revert_with_msg) - txn_receipt_revert_with_msg = common.mine_transaction_hash(web3, txn_hash_revert_with_msg) - block_hash_revert_with_msg = web3.eth.get_block(txn_receipt_revert_with_msg['blockHash']) + txn_receipt_revert_with_msg = common.mine_transaction_hash(w3, txn_hash_revert_with_msg) + block_hash_revert_with_msg = w3.eth.get_block(txn_receipt_revert_with_msg['blockHash']) print('BLOCK_HASH_REVERT_WITH_MSG:', block_hash_revert_with_msg['hash']) txn_hash_revert_with_no_msg = revert_contract.functions.revertWithoutMessage().transact( - {'gas': 320000, 'from': web3.eth.coinbase} + {'gas': 320000, 'from': w3.eth.coinbase} ) print('TXN_HASH_REVERT_WITH_NO_MSG:', txn_hash_revert_with_no_msg) - txn_receipt_revert_with_no_msg = common.mine_transaction_hash(web3, txn_hash_revert_with_no_msg) - block_hash_revert_no_msg = web3.eth.get_block(txn_receipt_revert_with_no_msg['blockHash']) + txn_receipt_revert_with_no_msg = common.mine_transaction_hash(w3, txn_hash_revert_with_no_msg) + block_hash_revert_no_msg = w3.eth.get_block(txn_receipt_revert_with_no_msg['blockHash']) print('BLOCK_HASH_REVERT_NO_MSG:', block_hash_revert_no_msg['hash']) # # Empty Block # - empty_block_number = mine_block(web3) + empty_block_number = mine_block(w3) print('MINED_EMPTY_BLOCK') - empty_block = web3.eth.get_block(empty_block_number) + empty_block = w3.eth.get_block(empty_block_number) assert is_dict(empty_block) assert not empty_block['transactions'] print('EMPTY_BLOCK_HASH:', empty_block['hash']) @@ -274,18 +274,18 @@ def setup_chain_state(web3): # # Block with Transaction # - web3.geth.personal.unlock_account(coinbase, common.KEYFILE_PW) - web3.geth.miner.start(1) - mined_txn_hash = web3.eth.send_transaction({ + w3.geth.personal.unlock_account(coinbase, common.KEYFILE_PW) + w3.geth.miner.start(1) + mined_txn_hash = w3.eth.send_transaction({ 'from': coinbase, 'to': coinbase, 'value': 1, 'gas': 21000, - 'gas_price': web3.eth.gas_price, + 'gas_price': w3.eth.gas_price, }) - mined_txn_receipt = mine_transaction_hash(web3, mined_txn_hash) + mined_txn_receipt = mine_transaction_hash(w3, mined_txn_hash) print('MINED_TXN_HASH:', mined_txn_hash) - block_with_txn = web3.eth.get_block(mined_txn_receipt['blockHash']) + block_with_txn = w3.eth.get_block(mined_txn_receipt['blockHash']) print('BLOCK_WITH_TXN_HASH:', block_with_txn['hash']) geth_fixture = { diff --git a/tests/integration/go_ethereum/common.py b/tests/integration/go_ethereum/common.py index 86448bff46..914160dd04 100644 --- a/tests/integration/go_ethereum/common.py +++ b/tests/integration/go_ethereum/common.py @@ -21,34 +21,34 @@ def _check_web3_clientVersion(self, client_version): class GoEthereumEthModuleTest(EthModuleTest): @pytest.mark.xfail(reason='eth_signTypedData has not been released in geth') - def test_eth_sign_typed_data(self, web3, unlocked_account_dual_type): - super().test_eth_sign_typed_data(web3, unlocked_account_dual_type) + def test_eth_sign_typed_data(self, w3, unlocked_account_dual_type): + super().test_eth_sign_typed_data(w3, unlocked_account_dual_type) @pytest.mark.xfail(reason='eth_signTypedData has not been released in geth') - def test_eth_signTypedData_deprecated(self, web3, unlocked_account_dual_type): - super().test_eth_signTypedData_deprecated(web3, unlocked_account_dual_type) + def test_eth_signTypedData_deprecated(self, w3, unlocked_account_dual_type): + super().test_eth_signTypedData_deprecated(w3, unlocked_account_dual_type) @pytest.mark.xfail(reason='eth_signTypedData has not been released in geth') - def test_invalid_eth_sign_typed_data(self, web3, unlocked_account_dual_type): - super().test_invalid_eth_sign_typed_data(web3, unlocked_account_dual_type) + def test_invalid_eth_sign_typed_data(self, w3, unlocked_account_dual_type): + super().test_invalid_eth_sign_typed_data(w3, unlocked_account_dual_type) @pytest.mark.xfail(reason='eth_protocolVersion was removed in Geth 1.10.0') - def test_eth_protocol_version(self, web3): - super().test_eth_protocol_version(web3) + def test_eth_protocol_version(self, w3): + super().test_eth_protocol_version(w3) @pytest.mark.xfail(reason='eth_protocolVersion was removed in Geth 1.10.0') - def test_eth_protocolVersion(self, web3): - super().test_eth_protocolVersion(web3) + def test_eth_protocolVersion(self, w3): + super().test_eth_protocolVersion(w3) class GoEthereumVersionModuleTest(VersionModuleTest): @pytest.mark.xfail(reason='eth_protocolVersion was removed in Geth 1.10.0') - def test_eth_protocol_version(self, web3): - super().test_eth_protocol_version(web3) + def test_eth_protocol_version(self, w3): + super().test_eth_protocol_version(w3) @pytest.mark.xfail(reason='eth_protocolVersion was removed in Geth 1.10.0') - def test_eth_protocolVersion(self, web3): - super().test_eth_protocolVersion(web3) + def test_eth_protocolVersion(self, w3): + super().test_eth_protocolVersion(w3) class GoEthereumNetModuleTest(NetModuleTest): diff --git a/tests/integration/go_ethereum/conftest.py b/tests/integration/go_ethereum/conftest.py index 59934890c7..06870f95e3 100644 --- a/tests/integration/go_ethereum/conftest.py +++ b/tests/integration/go_ethereum/conftest.py @@ -130,8 +130,8 @@ def geth_process(geth_binary, datadir, genesis_file, geth_command_arguments): @pytest.fixture(scope='module') -def coinbase(web3): - return web3.eth.coinbase +def coinbase(w3): + return w3.eth.coinbase @pytest.fixture(scope="module") @@ -140,7 +140,7 @@ def math_contract_deploy_txn_hash(geth_fixture_data): @pytest.fixture(scope="module") -def math_contract(web3, math_contract_factory, geth_fixture_data): +def math_contract(w3, math_contract_factory, geth_fixture_data): return math_contract_factory(address=geth_fixture_data['math_address']) @@ -150,7 +150,7 @@ def math_contract_address(math_contract, address_conversion_func): @pytest.fixture(scope="module") -def emitter_contract(web3, emitter_contract_factory, geth_fixture_data): +def emitter_contract(w3, emitter_contract_factory, geth_fixture_data): return emitter_contract_factory(address=geth_fixture_data['emitter_address']) @@ -160,10 +160,10 @@ def emitter_contract_address(emitter_contract, address_conversion_func): @pytest.fixture -def unlocked_account(web3, unlockable_account, unlockable_account_pw): - web3.geth.personal.unlock_account(unlockable_account, unlockable_account_pw) +def unlocked_account(w3, unlockable_account, unlockable_account_pw): + w3.geth.personal.unlock_account(unlockable_account, unlockable_account_pw) yield unlockable_account - web3.geth.personal.lock_account(unlockable_account) + w3.geth.personal.lock_account(unlockable_account) @pytest.fixture(scope='module') @@ -172,7 +172,7 @@ def unlockable_account_pw(geth_fixture_data): @pytest.fixture(scope="module") -def unlockable_account(web3, coinbase): +def unlockable_account(w3, coinbase): yield coinbase @@ -182,10 +182,10 @@ def unlockable_account_dual_type(unlockable_account, address_conversion_func): @pytest.fixture -def unlocked_account_dual_type(web3, unlockable_account_dual_type, unlockable_account_pw): - web3.geth.personal.unlock_account(unlockable_account_dual_type, unlockable_account_pw) +def unlocked_account_dual_type(w3, unlockable_account_dual_type, unlockable_account_pw): + w3.geth.personal.unlock_account(unlockable_account_dual_type, unlockable_account_pw) yield unlockable_account_dual_type - web3.geth.personal.lock_account(unlockable_account_dual_type) + w3.geth.personal.lock_account(unlockable_account_dual_type) @pytest.fixture(scope="module") @@ -196,15 +196,15 @@ def funded_account_for_raw_txn(geth_fixture_data): @pytest.fixture(scope="module") -def empty_block(web3, geth_fixture_data): - block = web3.eth.get_block(geth_fixture_data['empty_block_hash']) +def empty_block(w3, geth_fixture_data): + block = w3.eth.get_block(geth_fixture_data['empty_block_hash']) assert is_dict(block) return block @pytest.fixture(scope="module") -def block_with_txn(web3, geth_fixture_data): - block = web3.eth.get_block(geth_fixture_data['block_with_txn_hash']) +def block_with_txn(w3, geth_fixture_data): + block = w3.eth.get_block(geth_fixture_data['block_with_txn_hash']) assert is_dict(block) return block @@ -215,8 +215,8 @@ def mined_txn_hash(geth_fixture_data): @pytest.fixture(scope="module") -def block_with_txn_with_log(web3, geth_fixture_data): - block = web3.eth.get_block(geth_fixture_data['block_hash_with_log']) +def block_with_txn_with_log(w3, geth_fixture_data): + block = w3.eth.get_block(geth_fixture_data['block_hash_with_log']) assert is_dict(block) return block @@ -237,5 +237,5 @@ def block_hash_revert_with_msg(geth_fixture_data): @pytest.fixture(scope="module") -def revert_contract(web3, revert_contract_factory, geth_fixture_data): +def revert_contract(w3, revert_contract_factory, geth_fixture_data): return revert_contract_factory(address=geth_fixture_data['revert_address']) diff --git a/tests/integration/go_ethereum/test_goethereum_http.py b/tests/integration/go_ethereum/test_goethereum_http.py index a3ea078cac..53a624faad 100644 --- a/tests/integration/go_ethereum/test_goethereum_http.py +++ b/tests/integration/go_ethereum/test_goethereum_http.py @@ -90,16 +90,16 @@ def geth_command_arguments(rpc_port, @pytest.fixture(scope="module") -def web3(geth_process, endpoint_uri): +def w3(geth_process, endpoint_uri): wait_for_http(endpoint_uri) - _web3 = Web3(Web3.HTTPProvider(endpoint_uri)) - return _web3 + _w3 = Web3(Web3.HTTPProvider(endpoint_uri)) + return _w3 @pytest_asyncio.fixture(scope="module") async def async_w3(geth_process, endpoint_uri): await wait_for_aiohttp(endpoint_uri) - _web3 = Web3( + _w3 = Web3( AsyncHTTPProvider(endpoint_uri), middlewares=[ async_buffered_gas_estimate_middleware, @@ -115,7 +115,7 @@ async def async_w3(geth_process, endpoint_uri): ) } ) - return _web3 + return _w3 class TestGoEthereumTest(GoEthereumTest): @@ -124,37 +124,37 @@ class TestGoEthereumTest(GoEthereumTest): class TestGoEthereumAdminModuleTest(GoEthereumAdminModuleTest): @pytest.mark.xfail(reason="running geth with the --nodiscover flag doesn't allow peer addition") - def test_admin_peers(self, web3: "Web3") -> None: - super().test_admin_peers(web3) + def test_admin_peers(self, w3: "Web3") -> None: + super().test_admin_peers(w3) - def test_admin_start_stop_rpc(self, web3: "Web3") -> None: + def test_admin_start_stop_rpc(self, w3: "Web3") -> None: # This test causes all tests after it to fail on CI if it's allowed to run pytest.xfail(reason='Only one RPC endpoint is allowed to be active at any time') - super().test_admin_start_stop_rpc(web3) + super().test_admin_start_stop_rpc(w3) - def test_admin_start_stop_ws(self, web3: "Web3") -> None: + def test_admin_start_stop_ws(self, w3: "Web3") -> None: # This test causes all tests after it to fail on CI if it's allowed to run pytest.xfail(reason='Only one WS endpoint is allowed to be active at any time') - super().test_admin_start_stop_ws(web3) + super().test_admin_start_stop_ws(w3) class TestGoEthereumAsyncAdminModuleTest(GoEthereumAsyncAdminModuleTest): @pytest.mark.asyncio @pytest.mark.xfail(reason="running geth with the --nodiscover flag doesn't allow peer addition") - async def test_admin_peers(self, web3: "Web3") -> None: - await super().test_admin_peers(web3) + async def test_admin_peers(self, w3: "Web3") -> None: + await super().test_admin_peers(w3) @pytest.mark.asyncio - async def test_admin_start_stop_rpc(self, web3: "Web3") -> None: + async def test_admin_start_stop_rpc(self, w3: "Web3") -> None: # This test causes all tests after it to fail on CI if it's allowed to run pytest.xfail(reason='Only one RPC endpoint is allowed to be active at any time') - await super().test_admin_start_stop_rpc(web3) + await super().test_admin_start_stop_rpc(w3) @pytest.mark.asyncio - async def test_admin_start_stop_ws(self, web3: "Web3") -> None: + async def test_admin_start_stop_ws(self, w3: "Web3") -> None: # This test causes all tests after it to fail on CI if it's allowed to run pytest.xfail(reason='Only one WS endpoint is allowed to be active at any time') - await super().test_admin_start_stop_ws(web3) + await super().test_admin_start_stop_ws(w3) class TestGoEthereumEthModuleTest(GoEthereumEthModuleTest): diff --git a/tests/integration/go_ethereum/test_goethereum_ipc.py b/tests/integration/go_ethereum/test_goethereum_ipc.py index 367cda1929..6799e08f0d 100644 --- a/tests/integration/go_ethereum/test_goethereum_ipc.py +++ b/tests/integration/go_ethereum/test_goethereum_ipc.py @@ -52,10 +52,10 @@ def geth_ipc_path(datadir): @pytest.fixture(scope="module") -def web3(geth_process, geth_ipc_path): +def w3(geth_process, geth_ipc_path): wait_for_socket(geth_ipc_path) - _web3 = Web3(Web3.IPCProvider(geth_ipc_path, timeout=30)) - return _web3 + _w3 = Web3(Web3.IPCProvider(geth_ipc_path, timeout=30)) + return _w3 class TestGoEthereumTest(GoEthereumTest): @@ -64,12 +64,12 @@ class TestGoEthereumTest(GoEthereumTest): class TestGoEthereumAdminModuleTest(GoEthereumAdminModuleTest): @pytest.mark.xfail(reason="running geth with the --nodiscover flag doesn't allow peer addition") - def test_admin_peers(web3): - super().test_admin_peers(web3) + def test_admin_peers(w3): + super().test_admin_peers(w3) @pytest.mark.xfail(reason="websockets aren't enabled with our IPC flags") - def test_admin_start_stop_ws(web3): - super().test_admin_start_stop_ws(web3) + def test_admin_start_stop_ws(w3): + super().test_admin_start_stop_ws(w3) class TestGoEthereumEthModuleTest(GoEthereumEthModuleTest): diff --git a/tests/integration/go_ethereum/test_goethereum_ws.py b/tests/integration/go_ethereum/test_goethereum_ws.py index 9014f4fc1d..647681ede8 100644 --- a/tests/integration/go_ethereum/test_goethereum_ws.py +++ b/tests/integration/go_ethereum/test_goethereum_ws.py @@ -64,11 +64,11 @@ def geth_command_arguments(geth_binary, @pytest.fixture(scope="module") -def web3(geth_process, endpoint_uri): +def w3(geth_process, endpoint_uri): event_loop = asyncio.new_event_loop() event_loop.run_until_complete(wait_for_ws(endpoint_uri)) - _web3 = Web3(Web3.WebsocketProvider(endpoint_uri, websocket_timeout=30)) - return _web3 + _w3 = Web3(Web3.WebsocketProvider(endpoint_uri, websocket_timeout=30)) + return _w3 class TestGoEthereumTest(GoEthereumTest): @@ -77,17 +77,17 @@ class TestGoEthereumTest(GoEthereumTest): class TestGoEthereumAdminModuleTest(GoEthereumAdminModuleTest): @pytest.mark.xfail(reason="running geth with the --nodiscover flag doesn't allow peer addition") - def test_admin_peers(self, web3: "Web3") -> None: - super().test_admin_peers(web3) + def test_admin_peers(self, w3: "Web3") -> None: + super().test_admin_peers(w3) - def test_admin_start_stop_ws(self, web3: "Web3") -> None: + def test_admin_start_stop_ws(self, w3: "Web3") -> None: # This test inconsistently causes all tests after it to fail on CI if it's allowed to run pytest.xfail(reason='Only one WebSocket endpoint is allowed to be active at any time') - super().test_admin_start_stop_ws(web3) + super().test_admin_start_stop_ws(w3) - def test_admin_start_stop_rpc(self, web3: "Web3") -> None: + def test_admin_start_stop_rpc(self, w3: "Web3") -> None: pytest.xfail(reason="This test inconsistently causes all tests after it on CI to fail if it's allowed to run") # noqa: E501 - super().test_admin_start_stop_ws(web3) + super().test_admin_start_stop_ws(w3) class TestGoEthereumEthModuleTest(GoEthereumEthModuleTest): diff --git a/tests/integration/test_ethereum_tester.py b/tests/integration/test_ethereum_tester.py index 5d9297e723..1e992121a7 100644 --- a/tests/integration/test_ethereum_tester.py +++ b/tests/integration/test_ethereum_tester.py @@ -45,23 +45,23 @@ def eth_tester_provider(eth_tester): @pytest.fixture(scope="module") -def web3(eth_tester_provider): - _web3 = Web3(eth_tester_provider) - return _web3 +def w3(eth_tester_provider): + _w3 = Web3(eth_tester_provider) + return _w3 # # Math Contract Setup # @pytest.fixture(scope="module") -def math_contract_deploy_txn_hash(web3, math_contract_factory): - deploy_txn_hash = math_contract_factory.constructor().transact({'from': web3.eth.coinbase}) +def math_contract_deploy_txn_hash(w3, math_contract_factory): + deploy_txn_hash = math_contract_factory.constructor().transact({'from': w3.eth.coinbase}) return deploy_txn_hash @pytest.fixture(scope="module") -def math_contract(web3, math_contract_factory, math_contract_deploy_txn_hash): - deploy_receipt = web3.eth.wait_for_transaction_receipt(math_contract_deploy_txn_hash) +def math_contract(w3, math_contract_factory, math_contract_deploy_txn_hash): + deploy_receipt = w3.eth.wait_for_transaction_receipt(math_contract_deploy_txn_hash) assert is_dict(deploy_receipt) contract_address = deploy_receipt['contractAddress'] assert is_checksum_address(contract_address) @@ -78,14 +78,14 @@ def math_contract_address(math_contract, address_conversion_func): @pytest.fixture(scope="module") -def emitter_contract_deploy_txn_hash(web3, emitter_contract_factory): - deploy_txn_hash = emitter_contract_factory.constructor().transact({'from': web3.eth.coinbase}) +def emitter_contract_deploy_txn_hash(w3, emitter_contract_factory): + deploy_txn_hash = emitter_contract_factory.constructor().transact({'from': w3.eth.coinbase}) return deploy_txn_hash @pytest.fixture(scope="module") -def emitter_contract(web3, emitter_contract_factory, emitter_contract_deploy_txn_hash): - deploy_receipt = web3.eth.wait_for_transaction_receipt(emitter_contract_deploy_txn_hash) +def emitter_contract(w3, emitter_contract_factory, emitter_contract_deploy_txn_hash): + deploy_receipt = w3.eth.wait_for_transaction_receipt(emitter_contract_deploy_txn_hash) assert is_dict(deploy_receipt) contract_address = deploy_receipt['contractAddress'] assert is_checksum_address(contract_address) @@ -98,24 +98,24 @@ def emitter_contract_address(emitter_contract, address_conversion_func): @pytest.fixture(scope="module") -def empty_block(web3): - web3.testing.mine() - block = web3.eth.get_block("latest") +def empty_block(w3): + w3.testing.mine() + block = w3.eth.get_block("latest") assert not block['transactions'] return block @pytest.fixture(scope="module") -def block_with_txn(web3): - txn_hash = web3.eth.send_transaction({ - 'from': web3.eth.coinbase, - 'to': web3.eth.coinbase, +def block_with_txn(w3): + txn_hash = w3.eth.send_transaction({ + 'from': w3.eth.coinbase, + 'to': w3.eth.coinbase, 'value': 1, 'gas': 21000, 'gas_price': 1000000000, # needs to be greater than base_fee post London }) - txn = web3.eth.get_transaction(txn_hash) - block = web3.eth.get_block(txn['blockNumber']) + txn = w3.eth.get_transaction(txn_hash) + block = w3.eth.get_block(txn['blockNumber']) return block @@ -125,14 +125,14 @@ def mined_txn_hash(block_with_txn): @pytest.fixture(scope="module") -def block_with_txn_with_log(web3, emitter_contract): +def block_with_txn_with_log(w3, emitter_contract): txn_hash = emitter_contract.functions.logDouble( which=EMITTER_ENUM['LogDoubleWithIndex'], arg0=12345, arg1=54321, ).transact({ - 'from': web3.eth.coinbase, + 'from': w3.eth.coinbase, }) - txn = web3.eth.get_transaction(txn_hash) - block = web3.eth.get_block(txn['blockNumber']) + txn = w3.eth.get_transaction(txn_hash) + block = w3.eth.get_block(txn['blockNumber']) return block @@ -145,14 +145,14 @@ def txn_hash_with_log(block_with_txn_with_log): # Revert Contract Setup # @pytest.fixture(scope="module") -def revert_contract_deploy_txn_hash(web3, revert_contract_factory): - deploy_txn_hash = revert_contract_factory.constructor().transact({'from': web3.eth.coinbase}) +def revert_contract_deploy_txn_hash(w3, revert_contract_factory): + deploy_txn_hash = revert_contract_factory.constructor().transact({'from': w3.eth.coinbase}) return deploy_txn_hash @pytest.fixture(scope="module") -def revert_contract(web3, revert_contract_factory, revert_contract_deploy_txn_hash): - deploy_receipt = web3.eth.wait_for_transaction_receipt(revert_contract_deploy_txn_hash) +def revert_contract(w3, revert_contract_factory, revert_contract_deploy_txn_hash): + deploy_receipt = w3.eth.wait_for_transaction_receipt(revert_contract_deploy_txn_hash) assert is_dict(deploy_receipt) contract_address = deploy_receipt['contractAddress'] assert is_checksum_address(contract_address) @@ -163,27 +163,27 @@ def revert_contract(web3, revert_contract_factory, revert_contract_deploy_txn_ha @pytest.fixture(scope='module') -def unlockable_account_pw(web3): +def unlockable_account_pw(w3): return 'web3-testing' @pytest.fixture(scope='module') -def unlockable_account(web3, unlockable_account_pw): - account = web3.geth.personal.import_raw_key(UNLOCKABLE_PRIVATE_KEY, unlockable_account_pw) - web3.eth.send_transaction({ - 'from': web3.eth.coinbase, +def unlockable_account(w3, unlockable_account_pw): + account = w3.geth.personal.import_raw_key(UNLOCKABLE_PRIVATE_KEY, unlockable_account_pw) + w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': account, - 'value': web3.toWei(10, 'ether'), + 'value': w3.toWei(10, 'ether'), 'gas': 21000, }) yield account @pytest.fixture -def unlocked_account(web3, unlockable_account, unlockable_account_pw): - web3.geth.personal.unlock_account(unlockable_account, unlockable_account_pw) +def unlocked_account(w3, unlockable_account, unlockable_account_pw): + w3.geth.personal.unlock_account(unlockable_account, unlockable_account_pw) yield unlockable_account - web3.geth.personal.lock_account(unlockable_account) + w3.geth.personal.lock_account(unlockable_account) @pytest.fixture() @@ -192,19 +192,19 @@ def unlockable_account_dual_type(unlockable_account, address_conversion_func): @pytest.fixture -def unlocked_account_dual_type(web3, unlockable_account_dual_type, unlockable_account_pw): - web3.geth.personal.unlock_account(unlockable_account_dual_type, unlockable_account_pw) +def unlocked_account_dual_type(w3, unlockable_account_dual_type, unlockable_account_pw): + w3.geth.personal.unlock_account(unlockable_account_dual_type, unlockable_account_pw) yield unlockable_account_dual_type - web3.geth.personal.lock_account(unlockable_account_dual_type) + w3.geth.personal.lock_account(unlockable_account_dual_type) @pytest.fixture(scope="module") -def funded_account_for_raw_txn(web3): +def funded_account_for_raw_txn(w3): account = '0x39EEed73fb1D3855E90Cbd42f348b3D7b340aAA6' - web3.eth.send_transaction({ - 'from': web3.eth.coinbase, + w3.eth.send_transaction({ + 'from': w3.eth.coinbase, 'to': account, - 'value': web3.toWei(10, 'ether'), + 'value': w3.toWei(10, 'ether'), 'gas': 21000, 'gas_price': 1, }) @@ -291,96 +291,96 @@ class TestEthereumTesterEthModule(EthModuleTest): ) def test_eth_getBlockByHash_pending( - self, web3: "Web3" + self, w3: "Web3" ) -> None: - block = web3.eth.get_block('pending') + block = w3.eth.get_block('pending') assert block['hash'] is not None @pytest.mark.xfail(reason='eth_feeHistory is not implemented on eth-tester') - def test_eth_fee_history(self, web3: "Web3"): - super().test_eth_fee_history(web3) + def test_eth_fee_history(self, w3: "Web3"): + super().test_eth_fee_history(w3) @pytest.mark.xfail(reason='eth_feeHistory is not implemented on eth-tester') - def test_eth_fee_history_with_integer(self, web3: "Web3"): - super().test_eth_fee_history_with_integer(web3) + def test_eth_fee_history_with_integer(self, w3: "Web3"): + super().test_eth_fee_history_with_integer(w3) @pytest.mark.xfail(reason='eth_feeHistory is not implemented on eth-tester') - def test_eth_fee_history_no_reward_percentiles(self, web3: "Web3"): - super().test_eth_fee_history_no_reward_percentiles(web3) + def test_eth_fee_history_no_reward_percentiles(self, w3: "Web3"): + super().test_eth_fee_history_no_reward_percentiles(w3) @disable_auto_mine - def test_eth_get_transaction_receipt_unmined(self, eth_tester, web3, unlocked_account): - super().test_eth_get_transaction_receipt_unmined(web3, unlocked_account) + def test_eth_get_transaction_receipt_unmined(self, eth_tester, w3, unlocked_account): + super().test_eth_get_transaction_receipt_unmined(w3, unlocked_account) @disable_auto_mine - def test_eth_replace_transaction_legacy(self, eth_tester, web3, unlocked_account): - super().test_eth_replace_transaction_legacy(web3, unlocked_account) + def test_eth_replace_transaction_legacy(self, eth_tester, w3, unlocked_account): + super().test_eth_replace_transaction_legacy(w3, unlocked_account) @disable_auto_mine - def test_eth_replace_transaction(self, eth_tester, web3, unlocked_account): - super().test_eth_replace_transaction(web3, unlocked_account) + def test_eth_replace_transaction(self, eth_tester, w3, unlocked_account): + super().test_eth_replace_transaction(w3, unlocked_account) @disable_auto_mine @pytest.mark.xfail(reason='py-evm does not raise on EIP-1559 transaction underpriced') # TODO: This might also be an issue in py-evm worth looking into. See reason above. - def test_eth_replace_transaction_underpriced(self, eth_tester, web3, unlocked_account): - super().test_eth_replace_transaction_underpriced(web3, unlocked_account) + def test_eth_replace_transaction_underpriced(self, eth_tester, w3, unlocked_account): + super().test_eth_replace_transaction_underpriced(w3, unlocked_account) @disable_auto_mine - def test_eth_replaceTransaction_deprecated(self, eth_tester, web3, unlocked_account): - super().test_eth_replaceTransaction_deprecated(web3, unlocked_account) + def test_eth_replaceTransaction_deprecated(self, eth_tester, w3, unlocked_account): + super().test_eth_replaceTransaction_deprecated(w3, unlocked_account) @disable_auto_mine - def test_eth_replace_transaction_incorrect_nonce(self, eth_tester, web3, unlocked_account): - super().test_eth_replace_transaction_incorrect_nonce(web3, unlocked_account) + def test_eth_replace_transaction_incorrect_nonce(self, eth_tester, w3, unlocked_account): + super().test_eth_replace_transaction_incorrect_nonce(w3, unlocked_account) @disable_auto_mine - def test_eth_replace_transaction_gas_price_too_low(self, eth_tester, web3, unlocked_account): - super().test_eth_replace_transaction_gas_price_too_low(web3, unlocked_account) + def test_eth_replace_transaction_gas_price_too_low(self, eth_tester, w3, unlocked_account): + super().test_eth_replace_transaction_gas_price_too_low(w3, unlocked_account) @disable_auto_mine def test_eth_replace_transaction_gas_price_defaulting_minimum(self, eth_tester, - web3, + w3, unlocked_account): - super().test_eth_replace_transaction_gas_price_defaulting_minimum(web3, unlocked_account) + super().test_eth_replace_transaction_gas_price_defaulting_minimum(w3, unlocked_account) @disable_auto_mine def test_eth_replace_transaction_gas_price_defaulting_strategy_higher(self, eth_tester, - web3, + w3, unlocked_account): super().test_eth_replace_transaction_gas_price_defaulting_strategy_higher( - web3, unlocked_account + w3, unlocked_account ) @disable_auto_mine def test_eth_replace_transaction_gas_price_defaulting_strategy_lower(self, eth_tester, - web3, + w3, unlocked_account): super().test_eth_replace_transaction_gas_price_defaulting_strategy_lower( - web3, unlocked_account + w3, unlocked_account ) @disable_auto_mine - def test_eth_modifyTransaction_deprecated(self, eth_tester, web3, unlocked_account): - super().test_eth_modifyTransaction_deprecated(web3, unlocked_account) + def test_eth_modifyTransaction_deprecated(self, eth_tester, w3, unlocked_account): + super().test_eth_modifyTransaction_deprecated(w3, unlocked_account) @disable_auto_mine - def test_eth_modify_transaction_legacy(self, eth_tester, web3, unlocked_account): - super().test_eth_modify_transaction_legacy(web3, unlocked_account) + def test_eth_modify_transaction_legacy(self, eth_tester, w3, unlocked_account): + super().test_eth_modify_transaction_legacy(w3, unlocked_account) @disable_auto_mine - def test_eth_modify_transaction(self, eth_tester, web3, unlocked_account): - super().test_eth_modify_transaction(web3, unlocked_account) + def test_eth_modify_transaction(self, eth_tester, w3, unlocked_account): + super().test_eth_modify_transaction(w3, unlocked_account) @disable_auto_mine - def test_eth_call_old_contract_state(self, eth_tester, web3, math_contract, unlocked_account): + def test_eth_call_old_contract_state(self, eth_tester, w3, math_contract, unlocked_account): # For now, ethereum tester cannot give call results in the pending block. # Once that feature is added, then delete the except/else blocks. try: - super().test_eth_call_old_contract_state(web3, math_contract, unlocked_account) + super().test_eth_call_old_contract_state(w3, math_contract, unlocked_account) except AssertionError as err: if str(err) == "pending call result was 0 instead of 1": pass @@ -390,47 +390,47 @@ def test_eth_call_old_contract_state(self, eth_tester, web3, math_contract, unlo raise AssertionError("eth-tester was unexpectedly able to give the pending call result") @pytest.mark.xfail(reason='json-rpc method is not implemented on eth-tester') - def test_eth_get_storage_at(self, web3, emitter_contract_address): - super().test_eth_get_storage_at(web3, emitter_contract_address) + def test_eth_get_storage_at(self, w3, emitter_contract_address): + super().test_eth_get_storage_at(w3, emitter_contract_address) @pytest.mark.xfail(reason='json-rpc method is not implemented on eth-tester') - def test_eth_getStorageAt_deprecated(self, web3, emitter_contract_address): - super().test_eth_getStorageAt_deprecated(web3, emitter_contract_address) + def test_eth_getStorageAt_deprecated(self, w3, emitter_contract_address): + super().test_eth_getStorageAt_deprecated(w3, emitter_contract_address) @pytest.mark.xfail(reason='json-rpc method is not implemented on eth-tester') - def test_eth_get_storage_at_ens_name(self, web3, emitter_contract_address): - super().test_eth_get_storage_at_ens_name(web3, emitter_contract_address) + def test_eth_get_storage_at_ens_name(self, w3, emitter_contract_address): + super().test_eth_get_storage_at_ens_name(w3, emitter_contract_address) def test_eth_estimate_gas_with_block(self, - web3, + w3, unlocked_account_dual_type): super().test_eth_estimate_gas_with_block( - web3, unlocked_account_dual_type + w3, unlocked_account_dual_type ) - def test_eth_chain_id(self, web3): - chain_id = web3.eth.chain_id + def test_eth_chain_id(self, w3): + chain_id = w3.eth.chain_id assert is_integer(chain_id) assert chain_id == 61 - def test_eth_chainId(self, web3): + def test_eth_chainId(self, w3): with pytest.warns(DeprecationWarning): - chain_id = web3.eth.chainId + chain_id = w3.eth.chainId assert is_integer(chain_id) assert chain_id == 61 @disable_auto_mine def test_eth_wait_for_transaction_receipt_unmined(self, eth_tester, - web3, + w3, unlocked_account_dual_type): - super().test_eth_wait_for_transaction_receipt_unmined(web3, unlocked_account_dual_type) + super().test_eth_wait_for_transaction_receipt_unmined(w3, unlocked_account_dual_type) @pytest.mark.xfail(raises=TypeError, reason="call override param not implemented on eth-tester") - def test_eth_call_with_override(self, web3, revert_contract): - super().test_eth_call_with_override(web3, revert_contract) + def test_eth_call_with_override(self, w3, revert_contract): + super().test_eth_call_with_override(w3, revert_contract) - def test_eth_call_revert_with_msg(self, web3, revert_contract, unlocked_account): + def test_eth_call_revert_with_msg(self, w3, revert_contract, unlocked_account): with pytest.raises(TransactionFailed, match='execution reverted: Function has been reverted'): txn_params = revert_contract._prepare_transaction( @@ -440,9 +440,9 @@ def test_eth_call_revert_with_msg(self, web3, revert_contract, unlocked_account) "to": revert_contract.address, }, ) - web3.eth.call(txn_params) + w3.eth.call(txn_params) - def test_eth_call_revert_without_msg(self, web3, revert_contract, unlocked_account): + def test_eth_call_revert_without_msg(self, w3, revert_contract, unlocked_account): with pytest.raises(TransactionFailed, match="execution reverted"): txn_params = revert_contract._prepare_transaction( fn_name="revertWithoutMessage", @@ -451,9 +451,9 @@ def test_eth_call_revert_without_msg(self, web3, revert_contract, unlocked_accou "to": revert_contract.address, }, ) - web3.eth.call(txn_params) + w3.eth.call(txn_params) - def test_eth_estimate_gas_revert_with_msg(self, web3, revert_contract, unlocked_account): + def test_eth_estimate_gas_revert_with_msg(self, w3, revert_contract, unlocked_account): with pytest.raises(TransactionFailed, match='execution reverted: Function has been reverted'): txn_params = revert_contract._prepare_transaction( @@ -463,9 +463,9 @@ def test_eth_estimate_gas_revert_with_msg(self, web3, revert_contract, unlocked_ "to": revert_contract.address, }, ) - web3.eth.estimate_gas(txn_params) + w3.eth.estimate_gas(txn_params) - def test_eth_estimate_gas_revert_without_msg(self, web3, revert_contract, unlocked_account): + def test_eth_estimate_gas_revert_without_msg(self, w3, revert_contract, unlocked_account): with pytest.raises(TransactionFailed, match="execution reverted"): txn_params = revert_contract._prepare_transaction( fn_name="revertWithoutMessage", @@ -474,60 +474,60 @@ def test_eth_estimate_gas_revert_without_msg(self, web3, revert_contract, unlock "to": revert_contract.address, }, ) - web3.eth.estimate_gas(txn_params) + w3.eth.estimate_gas(txn_params) @disable_auto_mine - def test_eth_send_transaction(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction(web3, unlocked_account) + def test_eth_send_transaction(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction(w3, unlocked_account) @disable_auto_mine - def test_eth_send_transaction_legacy(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction_legacy(web3, unlocked_account) + def test_eth_send_transaction_legacy(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction_legacy(w3, unlocked_account) @disable_auto_mine - def test_eth_send_raw_transaction(self, eth_tester, web3, unlocked_account): - super().test_eth_send_raw_transaction(web3, unlocked_account) + def test_eth_send_raw_transaction(self, eth_tester, w3, unlocked_account): + super().test_eth_send_raw_transaction(w3, unlocked_account) @disable_auto_mine @pytest.mark.parametrize("max_fee", (1000000000, None), ids=["with_max_fee", "without_max_fee"]) def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( - self, eth_tester, web3, unlocked_account, max_fee, + self, eth_tester, w3, unlocked_account, max_fee, ): super().test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( - web3, unlocked_account, max_fee + w3, unlocked_account, max_fee ) @disable_auto_mine def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( - self, eth_tester, web3, unlocked_account + self, eth_tester, w3, unlocked_account ): super().test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( - web3, unlocked_account, + w3, unlocked_account, ) @disable_auto_mine - def test_eth_sendTransaction_deprecated(self, eth_tester, web3, unlocked_account): - super().test_eth_sendTransaction_deprecated(web3, unlocked_account) + def test_eth_sendTransaction_deprecated(self, eth_tester, w3, unlocked_account): + super().test_eth_sendTransaction_deprecated(w3, unlocked_account) @pytest.mark.xfail(raises=ValueError, reason="eth-tester does not have miner_start support") - def test_eth_send_transaction_with_nonce(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction_with_nonce(web3, unlocked_account) + def test_eth_send_transaction_with_nonce(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction_with_nonce(w3, unlocked_account) @disable_auto_mine - def test_eth_send_transaction_default_fees(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction_default_fees(web3, unlocked_account) + def test_eth_send_transaction_default_fees(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction_default_fees(w3, unlocked_account) @disable_auto_mine - def test_eth_send_transaction_hex_fees(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction_hex_fees(web3, unlocked_account) + def test_eth_send_transaction_hex_fees(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction_hex_fees(w3, unlocked_account) @disable_auto_mine - def test_eth_send_transaction_no_gas(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction_no_gas(web3, unlocked_account) + def test_eth_send_transaction_no_gas(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction_no_gas(w3, unlocked_account) @disable_auto_mine - def test_eth_send_transaction_no_max_fee(self, eth_tester, web3, unlocked_account): - super().test_eth_send_transaction_no_max_fee(web3, unlocked_account) + def test_eth_send_transaction_no_max_fee(self, eth_tester, w3, unlocked_account): + super().test_eth_send_transaction_no_max_fee(w3, unlocked_account) class TestEthereumTesterVersionModule(VersionModuleTest): @@ -551,19 +551,19 @@ class TestEthereumTesterPersonalModule(GoEthereumPersonalModuleTest): # Test overridden here since eth-tester returns False rather than None for failed unlock def test_personal_unlock_account_failure(self, - web3, + w3, unlockable_account_dual_type): - result = web3.geth.personal.unlock_account(unlockable_account_dual_type, 'bad-password') + result = w3.geth.personal.unlock_account(unlockable_account_dual_type, 'bad-password') assert result is False def test_personal_unlockAccount_failure_deprecated(self, - web3, + w3, unlockable_account_dual_type): with pytest.warns(DeprecationWarning, match="unlockAccount is deprecated in favor of unlock_account"): - result = web3.geth.personal.unlockAccount(unlockable_account_dual_type, 'bad-password') + result = w3.geth.personal.unlockAccount(unlockable_account_dual_type, 'bad-password') assert result is False @pytest.mark.xfail(raises=ValueError, reason="list_wallets not implemented in eth-tester") - def test_personal_list_wallets(self, web3: "Web3") -> None: - super().test_personal_list_wallets(web3) + def test_personal_list_wallets(self, w3: "Web3") -> None: + super().test_personal_list_wallets(w3) diff --git a/web3/_utils/async_transactions.py b/web3/_utils/async_transactions.py index be5fa6c391..116fdf8898 100644 --- a/web3/_utils/async_transactions.py +++ b/web3/_utils/async_transactions.py @@ -24,13 +24,13 @@ async def get_block_gas_limit( async def get_buffered_gas_estimate( - web3: "Web3", transaction: TxParams, gas_buffer: int = 100000 + w3: "Web3", transaction: TxParams, gas_buffer: int = 100000 ) -> int: gas_estimate_transaction = cast(TxParams, dict(**transaction)) - gas_estimate = await web3.eth.estimate_gas(gas_estimate_transaction) # type: ignore + gas_estimate = await w3.eth.estimate_gas(gas_estimate_transaction) # type: ignore - gas_limit = await get_block_gas_limit(web3.eth) # type: ignore + gas_limit = await get_block_gas_limit(w3.eth) # type: ignore if gas_estimate > gas_limit: raise ValueError( diff --git a/web3/_utils/contracts.py b/web3/_utils/contracts.py index c7d6f45829..97a0b1d17c 100644 --- a/web3/_utils/contracts.py +++ b/web3/_utils/contracts.py @@ -164,11 +164,11 @@ def find_matching_fn_abi( def encode_abi( - web3: "Web3", abi: ABIFunction, arguments: Sequence[Any], data: Optional[HexStr] = None + w3: "Web3", abi: ABIFunction, arguments: Sequence[Any], data: Optional[HexStr] = None ) -> HexStr: argument_types = get_abi_input_types(abi) - if not check_if_arguments_can_be_encoded(abi, web3.codec, arguments, {}): + if not check_if_arguments_can_be_encoded(abi, w3.codec, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( @@ -177,7 +177,7 @@ def encode_abi( ) normalizers = [ - abi_ens_resolver(web3), + abi_ens_resolver(w3), abi_address_to_hex, abi_bytes_to_bytes, abi_string_to_text, @@ -187,7 +187,7 @@ def encode_abi( argument_types, arguments, ) - encoded_arguments = web3.codec.encode_abi( + encoded_arguments = w3.codec.encode_abi( argument_types, normalized_arguments, ) @@ -200,7 +200,7 @@ def encode_abi( def prepare_transaction( address: ChecksumAddress, - web3: "Web3", + w3: "Web3", fn_identifier: Union[str, Type[FallbackFn], Type[ReceiveFn]], contract_abi: Optional[ABI] = None, fn_abi: Optional[ABIFunction] = None, @@ -215,7 +215,7 @@ def prepare_transaction( TODO: add new prepare_deploy_transaction API """ if fn_abi is None: - fn_abi = find_matching_fn_abi(contract_abi, web3.codec, fn_identifier, fn_args, fn_kwargs) + fn_abi = find_matching_fn_abi(contract_abi, w3.codec, fn_identifier, fn_args, fn_kwargs) validate_payable(transaction, fn_abi) @@ -231,7 +231,7 @@ def prepare_transaction( prepared_transaction.setdefault('to', address) prepared_transaction['data'] = encode_transaction_data( - web3, + w3, fn_identifier, contract_abi, fn_abi, @@ -242,7 +242,7 @@ def prepare_transaction( def encode_transaction_data( - web3: "Web3", + w3: "Web3", fn_identifier: Union[str, Type[FallbackFn], Type[ReceiveFn]], contract_abi: Optional[ABI] = None, fn_abi: Optional[ABIFunction] = None, @@ -256,12 +256,12 @@ def encode_transaction_data( elif is_text(fn_identifier): fn_abi, fn_selector, fn_arguments = get_function_info( # type ignored b/c fn_id here is always str b/c FallbackFn is handled above - fn_identifier, web3.codec, contract_abi, fn_abi, args, kwargs, # type: ignore + fn_identifier, w3.codec, contract_abi, fn_abi, args, kwargs, # type: ignore ) else: raise TypeError("Unsupported function identifier") - return add_0x_prefix(encode_abi(web3, fn_abi, fn_arguments, fn_selector)) + return add_0x_prefix(encode_abi(w3, fn_abi, fn_arguments, fn_selector)) def get_fallback_function_info( diff --git a/web3/_utils/ens.py b/web3/_utils/ens.py index 73040b239d..f924d306d7 100644 --- a/web3/_utils/ens.py +++ b/web3/_utils/ens.py @@ -76,5 +76,5 @@ def contract_ens_addresses( with contract_ens_addresses(mycontract, [('resolve-as-1s.eth', '0x111...111')]): # any contract call or transaction in here would only resolve the above ENS pair """ - with ens_addresses(contract.web3, name_addr_pairs): + with ens_addresses(contract.w3, name_addr_pairs): yield diff --git a/web3/_utils/module_testing/eth_module.py b/web3/_utils/module_testing/eth_module.py index 30a504a293..a2e4b66ea9 100644 --- a/web3/_utils/module_testing/eth_module.py +++ b/web3/_utils/module_testing/eth_module.py @@ -80,15 +80,15 @@ from web3.contract import Contract # noqa: F401 -def mine_pending_block(web3: "Web3") -> None: +def mine_pending_block(w3: "Web3") -> None: timeout = 10 - web3.geth.miner.start() # type: ignore + w3.geth.miner.start() # type: ignore start = time.time() while time.time() < start + timeout: - if len(web3.eth.get_block('pending')['transactions']) == 0: + if len(w3.eth.get_block('pending')['transactions']) == 0: break - web3.geth.miner.stop() # type: ignore + w3.geth.miner.stop() # type: ignore def _assert_contains_log( @@ -358,7 +358,7 @@ async def test_gas_price_strategy_middleware( } two_gwei_in_wei = async_w3.toWei(2, 'gwei') - def gas_price_strategy(web3: "Web3", txn: TxParams) -> Wei: + def gas_price_strategy(w3: "Web3", txn: TxParams) -> Wei: return two_gwei_in_wei async_w3.eth.set_gas_price_strategy(gas_price_strategy) @@ -389,7 +389,7 @@ async def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( if max_fee is not None: txn_params = assoc(txn_params, "maxFeePerGas", max_fee) - def gas_price_strategy(web3: "Web3", txn: TxParams) -> Wei: + def gas_price_strategy(w3: "Web3", txn: TxParams) -> Wei: return async_w3.toWei(2, 'gwei') async_w3.eth.set_gas_price_strategy(gas_price_strategy) @@ -416,7 +416,7 @@ async def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( 'maxFeePerGas': Wei(1000000000), } - def gas_price_strategy(_web3: "Web3", _txn: TxParams) -> Wei: + def gas_price_strategy(_w3: "Web3", _txn: TxParams) -> Wei: return async_w3.toWei(2, 'gwei') async_w3.eth.set_gas_price_strategy(gas_price_strategy) @@ -1155,23 +1155,23 @@ def test_async_provider_default_block( class EthModuleTest: - def test_eth_protocol_version(self, web3: "Web3") -> None: + def test_eth_protocol_version(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning, match="This method has been deprecated in some clients"): - protocol_version = web3.eth.protocol_version + protocol_version = w3.eth.protocol_version assert is_string(protocol_version) assert protocol_version.isdigit() - def test_eth_protocolVersion(self, web3: "Web3") -> None: + def test_eth_protocolVersion(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - protocol_version = web3.eth.protocolVersion + protocol_version = w3.eth.protocolVersion assert is_string(protocol_version) assert protocol_version.isdigit() - def test_eth_syncing(self, web3: "Web3") -> None: - syncing = web3.eth.syncing + def test_eth_syncing(self, w3: "Web3") -> None: + syncing = w3.eth.syncing assert is_boolean(syncing) or is_dict(syncing) @@ -1187,32 +1187,32 @@ def test_eth_syncing(self, web3: "Web3") -> None: assert is_integer(sync_dict['currentBlock']) assert is_integer(sync_dict['highestBlock']) - def test_eth_coinbase(self, web3: "Web3") -> None: - coinbase = web3.eth.coinbase + def test_eth_coinbase(self, w3: "Web3") -> None: + coinbase = w3.eth.coinbase assert is_checksum_address(coinbase) - def test_eth_mining(self, web3: "Web3") -> None: - mining = web3.eth.mining + def test_eth_mining(self, w3: "Web3") -> None: + mining = w3.eth.mining assert is_boolean(mining) - def test_eth_hashrate(self, web3: "Web3") -> None: - hashrate = web3.eth.hashrate + def test_eth_hashrate(self, w3: "Web3") -> None: + hashrate = w3.eth.hashrate assert is_integer(hashrate) assert hashrate >= 0 - def test_eth_chain_id(self, web3: "Web3") -> None: - chain_id = web3.eth.chain_id + def test_eth_chain_id(self, w3: "Web3") -> None: + chain_id = w3.eth.chain_id # chain id value from geth fixture genesis file assert chain_id == 131277322940537 - def test_eth_chainId(self, web3: "Web3") -> None: + def test_eth_chainId(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - chain_id = web3.eth.chainId + chain_id = w3.eth.chainId # chain id value from geth fixture genesis file assert chain_id == 131277322940537 - def test_eth_fee_history(self, web3: "Web3") -> None: - fee_history = web3.eth.fee_history(1, 'latest', [50]) + def test_eth_fee_history(self, w3: "Web3") -> None: + fee_history = w3.eth.fee_history(1, 'latest', [50]) assert is_list_like(fee_history['baseFeePerGas']) assert is_list_like(fee_history['gasUsedRatio']) assert is_integer(fee_history['oldestBlock']) @@ -1221,9 +1221,9 @@ def test_eth_fee_history(self, web3: "Web3") -> None: assert is_list_like(fee_history['reward'][0]) def test_eth_fee_history_with_integer(self, - web3: "Web3", + w3: "Web3", empty_block: BlockData) -> None: - fee_history = web3.eth.fee_history(1, empty_block['number'], [50]) + fee_history = w3.eth.fee_history(1, empty_block['number'], [50]) assert is_list_like(fee_history['baseFeePerGas']) assert is_list_like(fee_history['gasUsedRatio']) assert is_integer(fee_history['oldestBlock']) @@ -1231,46 +1231,46 @@ def test_eth_fee_history_with_integer(self, assert is_list_like(fee_history['reward']) assert is_list_like(fee_history['reward'][0]) - def test_eth_fee_history_no_reward_percentiles(self, web3: "Web3") -> None: - fee_history = web3.eth.fee_history(1, 'latest') + def test_eth_fee_history_no_reward_percentiles(self, w3: "Web3") -> None: + fee_history = w3.eth.fee_history(1, 'latest') assert is_list_like(fee_history['baseFeePerGas']) assert is_list_like(fee_history['gasUsedRatio']) assert is_integer(fee_history['oldestBlock']) assert fee_history['oldestBlock'] >= 0 - def test_eth_gas_price(self, web3: "Web3") -> None: - gas_price = web3.eth.gas_price + def test_eth_gas_price(self, w3: "Web3") -> None: + gas_price = w3.eth.gas_price assert is_integer(gas_price) assert gas_price > 0 - def test_eth_gasPrice_deprecated(self, web3: "Web3") -> None: + def test_eth_gasPrice_deprecated(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - gas_price = web3.eth.gasPrice + gas_price = w3.eth.gasPrice assert is_integer(gas_price) assert gas_price > 0 - def test_eth_max_priority_fee(self, web3: "Web3") -> None: - max_priority_fee = web3.eth.max_priority_fee + def test_eth_max_priority_fee(self, w3: "Web3") -> None: + max_priority_fee = w3.eth.max_priority_fee assert is_integer(max_priority_fee) - def test_eth_max_priority_fee_with_fee_history_calculation(self, web3: "Web3") -> None: + def test_eth_max_priority_fee_with_fee_history_calculation(self, w3: "Web3") -> None: fail_max_prio_middleware = construct_error_generator_middleware( {RPCEndpoint("eth_maxPriorityFeePerGas"): lambda *_: ''} ) - web3.middleware_onion.add(fail_max_prio_middleware, name='fail_max_prio_middleware') + w3.middleware_onion.add(fail_max_prio_middleware, name='fail_max_prio_middleware') with pytest.warns( UserWarning, match="There was an issue with the method eth_maxPriorityFeePerGas. Calculating using " "eth_feeHistory." ): - max_priority_fee = web3.eth.max_priority_fee + max_priority_fee = w3.eth.max_priority_fee assert is_integer(max_priority_fee) - web3.middleware_onion.remove('fail_max_prio_middleware') # clean up + w3.middleware_onion.remove('fail_max_prio_middleware') # clean up - def test_eth_accounts(self, web3: "Web3") -> None: - accounts = web3.eth.accounts + def test_eth_accounts(self, w3: "Web3") -> None: + accounts = w3.eth.accounts assert is_list_like(accounts) assert len(accounts) != 0 assert all(( @@ -1278,50 +1278,50 @@ def test_eth_accounts(self, web3: "Web3") -> None: for account in accounts )) - assert web3.eth.coinbase in accounts + assert w3.eth.coinbase in accounts - def test_eth_block_number(self, web3: "Web3") -> None: - block_number = web3.eth.block_number + def test_eth_block_number(self, w3: "Web3") -> None: + block_number = w3.eth.block_number assert is_integer(block_number) assert block_number >= 0 - def test_eth_get_block_number(self, web3: "Web3") -> None: - block_number = web3.eth.get_block_number() + def test_eth_get_block_number(self, w3: "Web3") -> None: + block_number = w3.eth.get_block_number() assert is_integer(block_number) assert block_number >= 0 - def test_eth_blockNumber(self, web3: "Web3") -> None: + def test_eth_blockNumber(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - block_number = web3.eth.blockNumber + block_number = w3.eth.blockNumber assert is_integer(block_number) assert block_number >= 0 - def test_eth_get_balance(self, web3: "Web3") -> None: - coinbase = web3.eth.coinbase + def test_eth_get_balance(self, w3: "Web3") -> None: + coinbase = w3.eth.coinbase with pytest.raises(InvalidAddress): - web3.eth.get_balance(ChecksumAddress(HexAddress(HexStr(coinbase.lower())))) + w3.eth.get_balance(ChecksumAddress(HexAddress(HexStr(coinbase.lower())))) - balance = web3.eth.get_balance(coinbase) + balance = w3.eth.get_balance(coinbase) assert is_integer(balance) assert balance >= 0 - def test_eth_getBalance_deprecated(self, web3: "Web3") -> None: - coinbase = web3.eth.coinbase + def test_eth_getBalance_deprecated(self, w3: "Web3") -> None: + coinbase = w3.eth.coinbase with pytest.warns(DeprecationWarning, match='getBalance is deprecated in favor of get_balance'): - balance = web3.eth.getBalance(coinbase) + balance = w3.eth.getBalance(coinbase) assert is_integer(balance) assert balance >= 0 - def test_eth_get_balance_with_block_identifier(self, web3: "Web3") -> None: - miner_address = web3.eth.get_block(1)['miner'] - genesis_balance = web3.eth.get_balance(miner_address, 0) - later_balance = web3.eth.get_balance(miner_address, 1) + def test_eth_get_balance_with_block_identifier(self, w3: "Web3") -> None: + miner_address = w3.eth.get_block(1)['miner'] + genesis_balance = w3.eth.get_balance(miner_address, 0) + later_balance = w3.eth.get_balance(miner_address, 1) assert is_integer(genesis_balance) assert is_integer(later_balance) @@ -1332,201 +1332,201 @@ def test_eth_get_balance_with_block_identifier(self, web3: "Web3") -> None: ('not-an-address.eth', False) ]) def test_eth_get_balance_with_ens_name( - self, web3: "Web3", address: ChecksumAddress, expect_success: bool + self, w3: "Web3", address: ChecksumAddress, expect_success: bool ) -> None: - with ens_addresses(web3, {'test-address.eth': web3.eth.accounts[0]}): + with ens_addresses(w3, {'test-address.eth': w3.eth.accounts[0]}): if expect_success: - balance = web3.eth.get_balance(address) + balance = w3.eth.get_balance(address) assert is_integer(balance) assert balance >= 0 else: with pytest.raises(NameNotFound): - web3.eth.get_balance(address) + w3.eth.get_balance(address) def test_eth_get_storage_at( - self, web3: "Web3", emitter_contract_address: ChecksumAddress + self, w3: "Web3", emitter_contract_address: ChecksumAddress ) -> None: - storage = web3.eth.get_storage_at(emitter_contract_address, 0) + storage = w3.eth.get_storage_at(emitter_contract_address, 0) assert isinstance(storage, HexBytes) def test_eth_getStorageAt_deprecated( - self, web3: "Web3", emitter_contract_address: ChecksumAddress + self, w3: "Web3", emitter_contract_address: ChecksumAddress ) -> None: with pytest.warns(DeprecationWarning): - storage = web3.eth.getStorageAt(emitter_contract_address, 0) + storage = w3.eth.getStorageAt(emitter_contract_address, 0) assert isinstance(storage, HexBytes) def test_eth_get_storage_at_ens_name( - self, web3: "Web3", emitter_contract_address: ChecksumAddress + self, w3: "Web3", emitter_contract_address: ChecksumAddress ) -> None: - with ens_addresses(web3, {'emitter.eth': emitter_contract_address}): - storage = web3.eth.get_storage_at('emitter.eth', 0) + with ens_addresses(w3, {'emitter.eth': emitter_contract_address}): + storage = w3.eth.get_storage_at('emitter.eth', 0) assert isinstance(storage, HexBytes) - def test_eth_get_storage_at_invalid_address(self, web3: "Web3") -> None: - coinbase = web3.eth.coinbase + def test_eth_get_storage_at_invalid_address(self, w3: "Web3") -> None: + coinbase = w3.eth.coinbase with pytest.raises(InvalidAddress): - web3.eth.get_storage_at(ChecksumAddress(HexAddress(HexStr(coinbase.lower()))), 0) + w3.eth.get_storage_at(ChecksumAddress(HexAddress(HexStr(coinbase.lower()))), 0) def test_eth_get_transaction_count( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - transaction_count = web3.eth.get_transaction_count(unlocked_account_dual_type) + transaction_count = w3.eth.get_transaction_count(unlocked_account_dual_type) assert is_integer(transaction_count) assert transaction_count >= 0 def test_eth_getTransactionCount_deprecated( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: with pytest.warns(DeprecationWarning): - transaction_count = web3.eth.getTransactionCount(unlocked_account_dual_type) + transaction_count = w3.eth.getTransactionCount(unlocked_account_dual_type) assert is_integer(transaction_count) assert transaction_count >= 0 def test_eth_get_transaction_count_ens_name( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - with ens_addresses(web3, {'unlocked-acct-dual-type.eth': unlocked_account_dual_type}): - transaction_count = web3.eth.get_transaction_count('unlocked-acct-dual-type.eth') + with ens_addresses(w3, {'unlocked-acct-dual-type.eth': unlocked_account_dual_type}): + transaction_count = w3.eth.get_transaction_count('unlocked-acct-dual-type.eth') assert is_integer(transaction_count) assert transaction_count >= 0 - def test_eth_get_transaction_count_invalid_address(self, web3: "Web3") -> None: - coinbase = web3.eth.coinbase + def test_eth_get_transaction_count_invalid_address(self, w3: "Web3") -> None: + coinbase = w3.eth.coinbase with pytest.raises(InvalidAddress): - web3.eth.get_transaction_count(ChecksumAddress(HexAddress(HexStr(coinbase.lower())))) + w3.eth.get_transaction_count(ChecksumAddress(HexAddress(HexStr(coinbase.lower())))) def test_eth_getBlockTransactionCountByHash_empty_block( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - transaction_count = web3.eth.get_block_transaction_count(empty_block['hash']) + transaction_count = w3.eth.get_block_transaction_count(empty_block['hash']) assert is_integer(transaction_count) assert transaction_count == 0 def test_eth_getBlockTransactionCountByNumber_empty_block( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - transaction_count = web3.eth.get_block_transaction_count(empty_block['number']) + transaction_count = w3.eth.get_block_transaction_count(empty_block['number']) assert is_integer(transaction_count) assert transaction_count == 0 def test_eth_getBlockTransactionCountByHash_block_with_txn( - self, web3: "Web3", block_with_txn: BlockData + self, w3: "Web3", block_with_txn: BlockData ) -> None: - transaction_count = web3.eth.get_block_transaction_count(block_with_txn['hash']) + transaction_count = w3.eth.get_block_transaction_count(block_with_txn['hash']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getBlockTransactionCountByNumber_block_with_txn( - self, web3: "Web3", block_with_txn: BlockData + self, w3: "Web3", block_with_txn: BlockData ) -> None: - transaction_count = web3.eth.get_block_transaction_count(block_with_txn['number']) + transaction_count = w3.eth.get_block_transaction_count(block_with_txn['number']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getBlockTransactionCountByHash_block_with_txn_deprecated( - self, web3: "Web3", block_with_txn: BlockData + self, w3: "Web3", block_with_txn: BlockData ) -> None: with pytest.warns( DeprecationWarning, match="getBlockTransactionCount is deprecated in favor of get_block_transaction_count" ): - transaction_count = web3.eth.getBlockTransactionCount(block_with_txn['hash']) + transaction_count = w3.eth.getBlockTransactionCount(block_with_txn['hash']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getBlockTransactionCountByNumber_block_with_txn_deprecated( - self, web3: "Web3", block_with_txn: BlockData + self, w3: "Web3", block_with_txn: BlockData ) -> None: with pytest.warns( DeprecationWarning, match="getBlockTransactionCount is deprecated in favor of get_block_transaction_count" ): - transaction_count = web3.eth.getBlockTransactionCount(block_with_txn['number']) + transaction_count = w3.eth.getBlockTransactionCount(block_with_txn['number']) assert is_integer(transaction_count) assert transaction_count >= 1 - def test_eth_getUncleCountByBlockHash(self, web3: "Web3", empty_block: BlockData) -> None: - uncle_count = web3.eth.get_uncle_count(empty_block['hash']) + def test_eth_getUncleCountByBlockHash(self, w3: "Web3", empty_block: BlockData) -> None: + uncle_count = w3.eth.get_uncle_count(empty_block['hash']) assert is_integer(uncle_count) assert uncle_count == 0 def test_eth_getUncleCountByBlockHash_deprecated(self, - web3: "Web3", + w3: "Web3", empty_block: BlockData) -> None: with pytest.warns(DeprecationWarning, match='getUncleCount is deprecated in favor of get_uncle_count'): - uncle_count = web3.eth.getUncleCount(empty_block['hash']) + uncle_count = w3.eth.getUncleCount(empty_block['hash']) assert is_integer(uncle_count) assert uncle_count == 0 - def test_eth_getUncleCountByBlockNumber(self, web3: "Web3", empty_block: BlockData) -> None: - uncle_count = web3.eth.get_uncle_count(empty_block['number']) + def test_eth_getUncleCountByBlockNumber(self, w3: "Web3", empty_block: BlockData) -> None: + uncle_count = w3.eth.get_uncle_count(empty_block['number']) assert is_integer(uncle_count) assert uncle_count == 0 def test_eth_getUncleCountByBlockNumber_deprecated(self, - web3: "Web3", + w3: "Web3", empty_block: BlockData) -> None: with pytest.warns(DeprecationWarning, match='getUncleCount is deprecated in favor of get_uncle_count'): - uncle_count = web3.eth.getUncleCount(empty_block['number']) + uncle_count = w3.eth.getUncleCount(empty_block['number']) assert is_integer(uncle_count) assert uncle_count == 0 - def test_eth_get_code(self, web3: "Web3", math_contract_address: ChecksumAddress) -> None: - code = web3.eth.get_code(math_contract_address) + def test_eth_get_code(self, w3: "Web3", math_contract_address: ChecksumAddress) -> None: + code = w3.eth.get_code(math_contract_address) assert isinstance(code, HexBytes) assert len(code) > 0 def test_eth_getCode_deprecated(self, - web3: "Web3", + w3: "Web3", math_contract_address: ChecksumAddress) -> None: with pytest.warns(DeprecationWarning, match='getCode is deprecated in favor of get_code'): - code = web3.eth.getCode(math_contract_address) + code = w3.eth.getCode(math_contract_address) assert isinstance(code, HexBytes) assert len(code) > 0 def test_eth_get_code_ens_address( - self, web3: "Web3", math_contract_address: ChecksumAddress + self, w3: "Web3", math_contract_address: ChecksumAddress ) -> None: with ens_addresses( - web3, {'mathcontract.eth': math_contract_address} + w3, {'mathcontract.eth': math_contract_address} ): - code = web3.eth.get_code('mathcontract.eth') + code = w3.eth.get_code('mathcontract.eth') assert isinstance(code, HexBytes) assert len(code) > 0 - def test_eth_get_code_invalid_address(self, web3: "Web3", math_contract: "Contract") -> None: + def test_eth_get_code_invalid_address(self, w3: "Web3", math_contract: "Contract") -> None: with pytest.raises(InvalidAddress): - web3.eth.get_code(ChecksumAddress(HexAddress(HexStr(math_contract.address.lower())))) + w3.eth.get_code(ChecksumAddress(HexAddress(HexStr(math_contract.address.lower())))) def test_eth_get_code_with_block_identifier( - self, web3: "Web3", emitter_contract: "Contract" + self, w3: "Web3", emitter_contract: "Contract" ) -> None: - code = web3.eth.get_code(emitter_contract.address, block_identifier=web3.eth.block_number) + code = w3.eth.get_code(emitter_contract.address, block_identifier=w3.eth.block_number) assert isinstance(code, HexBytes) assert len(code) > 0 - def test_eth_sign(self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress) -> None: - signature = web3.eth.sign( + def test_eth_sign(self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress) -> None: + signature = w3.eth.sign( unlocked_account_dual_type, text='Message tö sign. Longer than hash!' ) assert is_bytes(signature) assert len(signature) == 32 + 32 + 1 # test other formats - hexsign = web3.eth.sign( + hexsign = w3.eth.sign( unlocked_account_dual_type, hexstr=HexStr( '0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821' @@ -1534,27 +1534,27 @@ def test_eth_sign(self, web3: "Web3", unlocked_account_dual_type: ChecksumAddres ) assert hexsign == signature - intsign = web3.eth.sign( + intsign = w3.eth.sign( unlocked_account_dual_type, 0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821 ) assert intsign == signature - bytessign = web3.eth.sign( + bytessign = w3.eth.sign( unlocked_account_dual_type, b'Message t\xc3\xb6 sign. Longer than hash!' ) assert bytessign == signature - new_signature = web3.eth.sign( + new_signature = w3.eth.sign( unlocked_account_dual_type, text='different message is different' ) assert new_signature != signature def test_eth_sign_ens_names( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - with ens_addresses(web3, {'unlocked-acct.eth': unlocked_account_dual_type}): - signature = web3.eth.sign( + with ens_addresses(w3, {'unlocked-acct.eth': unlocked_account_dual_type}): + signature = w3.eth.sign( 'unlocked-acct.eth', text='Message tö sign. Longer than hash!' ) assert is_bytes(signature) @@ -1562,7 +1562,7 @@ def test_eth_sign_ens_names( def test_eth_sign_typed_data( self, - web3: "Web3", + w3: "Web3", unlocked_account_dual_type: ChecksumAddress, skip_if_testrpc: Callable[["Web3"], None], ) -> None: @@ -1605,8 +1605,8 @@ def test_eth_sign_typed_data( } } ''' - skip_if_testrpc(web3) - signature = HexBytes(web3.eth.sign_typed_data( + skip_if_testrpc(w3) + signature = HexBytes(w3.eth.sign_typed_data( unlocked_account_dual_type, json.loads(validJSONMessage) )) @@ -1614,7 +1614,7 @@ def test_eth_sign_typed_data( def test_eth_signTypedData_deprecated( self, - web3: "Web3", + w3: "Web3", unlocked_account_dual_type: ChecksumAddress, skip_if_testrpc: Callable[["Web3"], None], ) -> None: @@ -1657,8 +1657,8 @@ def test_eth_signTypedData_deprecated( } } ''' - skip_if_testrpc(web3) - signature = HexBytes(web3.eth.signTypedData( + skip_if_testrpc(w3) + signature = HexBytes(w3.eth.signTypedData( unlocked_account_dual_type, json.loads(validJSONMessage) )) @@ -1666,11 +1666,11 @@ def test_eth_signTypedData_deprecated( def test_invalid_eth_sign_typed_data( self, - web3: "Web3", + w3: "Web3", unlocked_account_dual_type: ChecksumAddress, skip_if_testrpc: Callable[["Web3"], None] ) -> None: - skip_if_testrpc(web3) + skip_if_testrpc(w3) invalid_typed_message = ''' { "types": { @@ -1712,14 +1712,14 @@ def test_invalid_eth_sign_typed_data( ''' with pytest.raises(ValueError, match=r".*Expected 2 items for array type Person\[2\], got 1 items.*"): - web3.eth.sign_typed_data( + w3.eth.sign_typed_data( unlocked_account_dual_type, json.loads(invalid_typed_message) ) def test_eth_sign_transaction_legacy( self, - web3: "Web3", + w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { @@ -1727,11 +1727,11 @@ def test_eth_sign_transaction_legacy( 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.eth.gas_price, + 'gasPrice': w3.eth.gas_price, 'nonce': Nonce(0), } - result = web3.eth.sign_transaction(txn_params) - signatory_account = web3.eth.account.recover_transaction(result['raw']) + result = w3.eth.sign_transaction(txn_params) + signatory_account = w3.eth.account.recover_transaction(result['raw']) assert unlocked_account == signatory_account assert result['tx']['to'] == txn_params['to'] assert result['tx']['value'] == txn_params['value'] @@ -1741,7 +1741,7 @@ def test_eth_sign_transaction_legacy( def test_eth_sign_transaction( self, - web3: "Web3", + w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { @@ -1749,12 +1749,12 @@ def test_eth_sign_transaction( 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(2, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), 'nonce': Nonce(0), } - result = web3.eth.sign_transaction(txn_params) - signatory_account = web3.eth.account.recover_transaction(result['raw']) + result = w3.eth.sign_transaction(txn_params) + signatory_account = w3.eth.account.recover_transaction(result['raw']) assert unlocked_account == signatory_account assert result['tx']['to'] == txn_params['to'] assert result['tx']['value'] == txn_params['value'] @@ -1765,7 +1765,7 @@ def test_eth_sign_transaction( def test_eth_sign_transaction_hex_fees( self, - web3: "Web3", + w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { @@ -1773,12 +1773,12 @@ def test_eth_sign_transaction_hex_fees( 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': hex(web3.toWei(2, 'gwei')), - 'maxPriorityFeePerGas': hex(web3.toWei(1, 'gwei')), + 'maxFeePerGas': hex(w3.toWei(2, 'gwei')), + 'maxPriorityFeePerGas': hex(w3.toWei(1, 'gwei')), 'nonce': Nonce(0), } - result = web3.eth.sign_transaction(txn_params) - signatory_account = web3.eth.account.recover_transaction(result['raw']) + result = w3.eth.sign_transaction(txn_params) + signatory_account = w3.eth.account.recover_transaction(result['raw']) assert unlocked_account == signatory_account assert result['tx']['to'] == txn_params['to'] assert result['tx']['value'] == txn_params['value'] @@ -1790,20 +1790,20 @@ def test_eth_sign_transaction_hex_fees( assert result['tx']['nonce'] == txn_params['nonce'] def test_eth_signTransaction_deprecated(self, - web3: "Web3", + w3: "Web3", unlocked_account: ChecksumAddress) -> None: txn_params: TxParams = { 'from': unlocked_account, 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.eth.gas_price, + 'gasPrice': w3.eth.gas_price, 'nonce': Nonce(0), } with pytest.warns(DeprecationWarning, match='signTransaction is deprecated in favor of sign_transaction'): - result = web3.eth.signTransaction(txn_params) - signatory_account = web3.eth.account.recover_transaction(result['raw']) + result = w3.eth.signTransaction(txn_params) + signatory_account = w3.eth.account.recover_transaction(result['raw']) assert unlocked_account == signatory_account assert result['tx']['to'] == txn_params['to'] assert result['tx']['value'] == txn_params['value'] @@ -1812,20 +1812,20 @@ def test_eth_signTransaction_deprecated(self, assert result['tx']['nonce'] == txn_params['nonce'] def test_eth_sign_transaction_ens_names( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: - with ens_addresses(web3, {'unlocked-account.eth': unlocked_account}): + with ens_addresses(w3, {'unlocked-account.eth': unlocked_account}): txn_params: TxParams = { 'from': 'unlocked-account.eth', 'to': 'unlocked-account.eth', 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(2, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), 'nonce': Nonce(0), } - result = web3.eth.sign_transaction(txn_params) - signatory_account = web3.eth.account.recover_transaction(result['raw']) + result = w3.eth.sign_transaction(txn_params) + signatory_account = w3.eth.account.recover_transaction(result['raw']) assert unlocked_account == signatory_account assert result['tx']['to'] == unlocked_account assert result['tx']['value'] == txn_params['value'] @@ -1835,7 +1835,7 @@ def test_eth_sign_transaction_ens_names( assert result['tx']['nonce'] == txn_params['nonce'] def test_eth_send_transaction_addr_checksum_required( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: non_checksum_addr = unlocked_account.lower() txn_params: TxParams = { @@ -1843,30 +1843,30 @@ def test_eth_send_transaction_addr_checksum_required( 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(2, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } with pytest.raises(InvalidAddress): invalid_params = cast(TxParams, dict(txn_params, **{'from': non_checksum_addr})) - web3.eth.send_transaction(invalid_params) + w3.eth.send_transaction(invalid_params) with pytest.raises(InvalidAddress): invalid_params = cast(TxParams, dict(txn_params, **{'to': non_checksum_addr})) - web3.eth.send_transaction(invalid_params) + w3.eth.send_transaction(invalid_params) def test_eth_send_transaction_legacy( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.toWei(1, 'gwei'), # post-london needs to be more than the base fee + 'gasPrice': w3.toWei(1, 'gwei'), # post-london needs to be more than the base fee } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -1875,18 +1875,18 @@ def test_eth_send_transaction_legacy( assert txn['gasPrice'] == txn_params['gasPrice'] def test_eth_send_transaction( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(3, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(3, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -1897,20 +1897,20 @@ def test_eth_send_transaction( assert txn['gasPrice'] == txn_params['maxFeePerGas'] def test_eth_sendTransaction_deprecated( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(3, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(3, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } with pytest.warns(DeprecationWarning, match="sendTransaction is deprecated in favor of send_transaction"): - txn_hash = web3.eth.sendTransaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.sendTransaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -1921,9 +1921,9 @@ def test_eth_sendTransaction_deprecated( assert txn['gasPrice'] == txn_params['maxFeePerGas'] def test_eth_send_transaction_with_nonce( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: - mine_pending_block(web3) # gives an accurate transaction count after mining + mine_pending_block(w3) # gives an accurate transaction count after mining txn_params: TxParams = { 'from': unlocked_account, @@ -1931,12 +1931,12 @@ def test_eth_send_transaction_with_nonce( 'value': Wei(1), 'gas': 21000, # unique maxFeePerGas to ensure transaction hash different from other tests - 'maxFeePerGas': web3.toWei(4.321, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), - 'nonce': web3.eth.get_transaction_count(unlocked_account), + 'maxFeePerGas': w3.toWei(4.321, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), + 'nonce': w3.eth.get_transaction_count(unlocked_account), } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -1948,7 +1948,7 @@ def test_eth_send_transaction_with_nonce( assert txn['gasPrice'] == txn_params['maxFeePerGas'] def test_eth_send_transaction_default_fees( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -1956,8 +1956,8 @@ def test_eth_send_transaction_default_fees( 'value': Wei(1), 'gas': 21000, } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -1968,7 +1968,7 @@ def test_eth_send_transaction_default_fees( assert txn['gasPrice'] == txn['maxFeePerGas'] def test_eth_send_transaction_hex_fees( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -1978,8 +1978,8 @@ def test_eth_send_transaction_hex_fees( 'maxFeePerGas': hex(250 * 10**9), 'maxPriorityFeePerGas': hex(2 * 10**9), } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -1989,7 +1989,7 @@ def test_eth_send_transaction_hex_fees( assert txn['maxPriorityFeePerGas'] == 2 * 10**9 def test_eth_send_transaction_no_gas( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -1998,8 +1998,8 @@ def test_eth_send_transaction_no_gas( 'maxFeePerGas': Wei(250 * 10**9), 'maxPriorityFeePerGas': Wei(2 * 10**9), } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -2007,7 +2007,7 @@ def test_eth_send_transaction_no_gas( assert txn['gas'] == 121000 # 21000 + buffer def test_eth_send_transaction_with_gas_price( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -2019,10 +2019,10 @@ def test_eth_send_transaction_with_gas_price( 'maxPriorityFeePerGas': Wei(2 * 10**9), } with pytest.raises(TransactionTypeMismatch): - web3.eth.send_transaction(txn_params) + w3.eth.send_transaction(txn_params) def test_eth_send_transaction_no_priority_fee( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -2032,12 +2032,12 @@ def test_eth_send_transaction_no_priority_fee( 'maxFeePerGas': Wei(250 * 10**9), } with pytest.raises(InvalidTransaction, match='maxPriorityFeePerGas must be defined'): - web3.eth.send_transaction(txn_params) + w3.eth.send_transaction(txn_params) def test_eth_send_transaction_no_max_fee( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - maxPriorityFeePerGas = web3.toWei(2, 'gwei') + maxPriorityFeePerGas = w3.toWei(2, 'gwei') txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, @@ -2045,19 +2045,19 @@ def test_eth_send_transaction_no_max_fee( 'gas': 21000, 'maxPriorityFeePerGas': maxPriorityFeePerGas, } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) assert is_same_address(txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(txn['to'], cast(ChecksumAddress, txn_params['to'])) assert txn['value'] == 1 assert txn['gas'] == 21000 - block = web3.eth.get_block('latest') + block = w3.eth.get_block('latest') assert txn['maxFeePerGas'] == maxPriorityFeePerGas + 2 * block['baseFeePerGas'] def test_eth_send_transaction_max_fee_less_than_tip( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -2070,21 +2070,21 @@ def test_eth_send_transaction_max_fee_less_than_tip( with pytest.raises( InvalidTransaction, match="maxFeePerGas must be >= maxPriorityFeePerGas" ): - web3.eth.send_transaction(txn_params) + w3.eth.send_transaction(txn_params) def test_validation_middleware_chain_id_mismatch( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: wrong_chain_id = 1234567890 - actual_chain_id = web3.eth.chain_id + actual_chain_id = w3.eth.chain_id txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': Wei(21000), - 'maxFeePerGas': web3.toWei(2, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), 'chainId': wrong_chain_id, } @@ -2093,7 +2093,7 @@ def test_validation_middleware_chain_id_mismatch( match=f'The transaction declared chain ID {wrong_chain_id}, ' f'but the connected node is on {actual_chain_id}' ): - web3.eth.send_transaction(txn_params) + w3.eth.send_transaction(txn_params) @pytest.mark.parametrize( "max_fee", @@ -2101,9 +2101,9 @@ def test_validation_middleware_chain_id_mismatch( ids=["with_max_fee", "without_max_fee"] ) def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress, max_fee: Wei + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress, max_fee: Wei ) -> None: - max_priority_fee = web3.toWei(1, 'gwei') + max_priority_fee = w3.toWei(1, 'gwei') txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, @@ -2114,23 +2114,23 @@ def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( if max_fee is not None: txn_params = assoc(txn_params, "maxFeePerGas", max_fee) - def gas_price_strategy(_web3: "Web3", _txn: TxParams) -> Wei: - return web3.toWei(2, 'gwei') - web3.eth.set_gas_price_strategy(gas_price_strategy) + def gas_price_strategy(_w3: "Web3", _txn: TxParams) -> Wei: + return w3.toWei(2, 'gwei') + w3.eth.set_gas_price_strategy(gas_price_strategy) - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) - latest_block = web3.eth.get_block('latest') + latest_block = w3.eth.get_block('latest') assert txn['maxFeePerGas'] == max_fee if max_fee is not None \ else 2 * latest_block['baseFeePerGas'] + max_priority_fee assert txn['maxPriorityFeePerGas'] == max_priority_fee assert txn['gasPrice'] == txn['maxFeePerGas'] - web3.eth.set_gas_price_strategy(None) # reset strategy + w3.eth.set_gas_price_strategy(None) # reset strategy def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress, + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress, ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -2140,30 +2140,30 @@ def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( 'maxFeePerGas': Wei(1000000000), } - def gas_price_strategy(_web3: "Web3", _txn: TxParams) -> Wei: - return web3.toWei(2, 'gwei') - web3.eth.set_gas_price_strategy(gas_price_strategy) + def gas_price_strategy(_w3: "Web3", _txn: TxParams) -> Wei: + return w3.toWei(2, 'gwei') + w3.eth.set_gas_price_strategy(gas_price_strategy) with pytest.raises(InvalidTransaction, match="maxPriorityFeePerGas must be defined"): - web3.eth.send_transaction(txn_params) + w3.eth.send_transaction(txn_params) - web3.eth.set_gas_price_strategy(None) # reset strategy + w3.eth.set_gas_price_strategy(None) # reset strategy def test_eth_replace_transaction_legacy( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.toWei(1, 'gwei'), # must be greater than base_fee post London + 'gasPrice': w3.toWei(1, 'gwei'), # must be greater than base_fee post London } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - txn_params['gasPrice'] = web3.toWei(2, 'gwei') - replace_txn_hash = web3.eth.replace_transaction(txn_hash, txn_params) - replace_txn = web3.eth.get_transaction(replace_txn_hash) + txn_params['gasPrice'] = w3.toWei(2, 'gwei') + replace_txn_hash = w3.eth.replace_transaction(txn_hash, txn_params) + replace_txn = w3.eth.get_transaction(replace_txn_hash) assert is_same_address(replace_txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(replace_txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -2172,10 +2172,10 @@ def test_eth_replace_transaction_legacy( assert replace_txn['gasPrice'] == txn_params['gasPrice'] def test_eth_replace_transaction( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - two_gwei_in_wei = web3.toWei(2, 'gwei') - three_gwei_in_wei = web3.toWei(3, 'gwei') + two_gwei_in_wei = w3.toWei(2, 'gwei') + three_gwei_in_wei = w3.toWei(3, 'gwei') txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -2183,15 +2183,15 @@ def test_eth_replace_transaction( 'value': Wei(1), 'gas': 21000, 'maxFeePerGas': two_gwei_in_wei, - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) txn_params['maxFeePerGas'] = three_gwei_in_wei txn_params['maxPriorityFeePerGas'] = two_gwei_in_wei - replace_txn_hash = web3.eth.replace_transaction(txn_hash, txn_params) - replace_txn = web3.eth.get_transaction(replace_txn_hash) + replace_txn_hash = w3.eth.replace_transaction(txn_hash, txn_params) + replace_txn = w3.eth.get_transaction(replace_txn_hash) assert is_same_address(replace_txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(replace_txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -2201,30 +2201,30 @@ def test_eth_replace_transaction( assert replace_txn['maxPriorityFeePerGas'] == two_gwei_in_wei def test_eth_replace_transaction_underpriced( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(3, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(2, 'gwei'), + 'maxFeePerGas': w3.toWei(3, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(2, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - one_gwei_in_wei = web3.toWei(1, 'gwei') + one_gwei_in_wei = w3.toWei(1, 'gwei') txn_params['maxFeePerGas'] = one_gwei_in_wei txn_params['maxPriorityFeePerGas'] = one_gwei_in_wei with pytest.raises(ValueError, match="replacement transaction underpriced"): - web3.eth.replace_transaction(txn_hash, txn_params) + w3.eth.replace_transaction(txn_hash, txn_params) def test_eth_replaceTransaction_deprecated( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - two_gwei_in_wei = web3.toWei(2, 'gwei') - three_gwei_in_wei = web3.toWei(3, 'gwei') + two_gwei_in_wei = w3.toWei(2, 'gwei') + three_gwei_in_wei = w3.toWei(3, 'gwei') txn_params: TxParams = { 'from': unlocked_account_dual_type, @@ -2232,9 +2232,9 @@ def test_eth_replaceTransaction_deprecated( 'value': Wei(1), 'gas': 21000, 'maxFeePerGas': two_gwei_in_wei, - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) txn_params['maxFeePerGas'] = three_gwei_in_wei txn_params['maxPriorityFeePerGas'] = two_gwei_in_wei @@ -2242,8 +2242,8 @@ def test_eth_replaceTransaction_deprecated( DeprecationWarning, match="replaceTransaction is deprecated in favor of replace_transaction" ): - replace_txn_hash = web3.eth.replaceTransaction(txn_hash, txn_params) - replace_txn = web3.eth.get_transaction(replace_txn_hash) + replace_txn_hash = w3.eth.replaceTransaction(txn_hash, txn_params) + replace_txn = w3.eth.get_transaction(replace_txn_hash) assert is_same_address(replace_txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(replace_txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -2253,85 +2253,85 @@ def test_eth_replaceTransaction_deprecated( assert replace_txn['maxPriorityFeePerGas'] == two_gwei_in_wei def test_eth_replace_transaction_non_existing_transaction( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(3, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(3, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } with pytest.raises(TransactionNotFound): - web3.eth.replace_transaction( + w3.eth.replace_transaction( HexStr('0x98e8cc09b311583c5079fa600f6c2a3bea8611af168c52e4b60b5b243a441997'), txn_params ) def test_eth_replace_transaction_already_mined( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(2, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) try: - web3.geth.miner.start() # type: ignore - web3.eth.wait_for_transaction_receipt(txn_hash, timeout=10) + w3.geth.miner.start() # type: ignore + w3.eth.wait_for_transaction_receipt(txn_hash, timeout=10) finally: - web3.geth.miner.stop() # type: ignore + w3.geth.miner.stop() # type: ignore - txn_params['maxFeePerGas'] = web3.toWei(3, 'gwei') - txn_params['maxPriorityFeePerGas'] = web3.toWei(2, 'gwei') + txn_params['maxFeePerGas'] = w3.toWei(3, 'gwei') + txn_params['maxPriorityFeePerGas'] = w3.toWei(2, 'gwei') with pytest.raises(ValueError, match="Supplied transaction with hash"): - web3.eth.replace_transaction(txn_hash, txn_params) + w3.eth.replace_transaction(txn_hash, txn_params) def test_eth_replace_transaction_incorrect_nonce( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account, 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(2, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) - txn = web3.eth.get_transaction(txn_hash) + txn_hash = w3.eth.send_transaction(txn_params) + txn = w3.eth.get_transaction(txn_hash) - txn_params['maxFeePerGas'] = web3.toWei(3, 'gwei') - txn_params['maxPriorityFeePerGas'] = web3.toWei(2, 'gwei') + txn_params['maxFeePerGas'] = w3.toWei(3, 'gwei') + txn_params['maxPriorityFeePerGas'] = w3.toWei(2, 'gwei') txn_params['nonce'] = Nonce(txn['nonce'] + 1) with pytest.raises(ValueError): - web3.eth.replace_transaction(txn_hash, txn_params) + w3.eth.replace_transaction(txn_hash, txn_params) def test_eth_replace_transaction_gas_price_too_low( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.toWei(2, 'gwei'), + 'gasPrice': w3.toWei(2, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - txn_params['gasPrice'] = web3.toWei(1, 'gwei') + txn_params['gasPrice'] = w3.toWei(1, 'gwei') with pytest.raises(ValueError): - web3.eth.replace_transaction(txn_hash, txn_params) + w3.eth.replace_transaction(txn_hash, txn_params) def test_eth_replace_transaction_gas_price_defaulting_minimum( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: - gas_price = web3.toWei(1, 'gwei') + gas_price = w3.toWei(1, 'gwei') txn_params: TxParams = { 'from': unlocked_account, @@ -2340,43 +2340,43 @@ def test_eth_replace_transaction_gas_price_defaulting_minimum( 'gas': 21000, 'gasPrice': gas_price, } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) txn_params.pop('gasPrice') - replace_txn_hash = web3.eth.replace_transaction(txn_hash, txn_params) - replace_txn = web3.eth.get_transaction(replace_txn_hash) + replace_txn_hash = w3.eth.replace_transaction(txn_hash, txn_params) + replace_txn = w3.eth.get_transaction(replace_txn_hash) assert replace_txn['gasPrice'] == math.ceil(gas_price * 1.125) # minimum gas price def test_eth_replace_transaction_gas_price_defaulting_strategy_higher( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account, 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.toWei(1, 'gwei'), + 'gasPrice': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - two_gwei_in_wei = web3.toWei(2, 'gwei') + two_gwei_in_wei = w3.toWei(2, 'gwei') - def higher_gas_price_strategy(web3: "Web3", txn: TxParams) -> Wei: + def higher_gas_price_strategy(w3: "Web3", txn: TxParams) -> Wei: return two_gwei_in_wei - web3.eth.set_gas_price_strategy(higher_gas_price_strategy) + w3.eth.set_gas_price_strategy(higher_gas_price_strategy) txn_params.pop('gasPrice') - replace_txn_hash = web3.eth.replace_transaction(txn_hash, txn_params) - replace_txn = web3.eth.get_transaction(replace_txn_hash) + replace_txn_hash = w3.eth.replace_transaction(txn_hash, txn_params) + replace_txn = w3.eth.get_transaction(replace_txn_hash) assert replace_txn['gasPrice'] == two_gwei_in_wei # Strategy provides higher gas price - web3.eth.set_gas_price_strategy(None) # reset strategy + w3.eth.set_gas_price_strategy(None) # reset strategy def test_eth_replace_transaction_gas_price_defaulting_strategy_lower( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: - gas_price = web3.toWei(2, 'gwei') + gas_price = w3.toWei(2, 'gwei') txn_params: TxParams = { 'from': unlocked_account, @@ -2385,36 +2385,36 @@ def test_eth_replace_transaction_gas_price_defaulting_strategy_lower( 'gas': 21000, 'gasPrice': gas_price, } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - def lower_gas_price_strategy(web3: "Web3", txn: TxParams) -> Wei: - return web3.toWei(1, 'gwei') + def lower_gas_price_strategy(w3: "Web3", txn: TxParams) -> Wei: + return w3.toWei(1, 'gwei') - web3.eth.set_gas_price_strategy(lower_gas_price_strategy) + w3.eth.set_gas_price_strategy(lower_gas_price_strategy) txn_params.pop('gasPrice') - replace_txn_hash = web3.eth.replace_transaction(txn_hash, txn_params) - replace_txn = web3.eth.get_transaction(replace_txn_hash) + replace_txn_hash = w3.eth.replace_transaction(txn_hash, txn_params) + replace_txn = w3.eth.get_transaction(replace_txn_hash) # Strategy provides lower gas price - minimum preferred assert replace_txn['gasPrice'] == math.ceil(gas_price * 1.125) - web3.eth.set_gas_price_strategy(None) # reset strategy + w3.eth.set_gas_price_strategy(None) # reset strategy def test_eth_modify_transaction_legacy( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account, 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.toWei(1, 'gwei'), # must be greater than base_fee post London + 'gasPrice': w3.toWei(1, 'gwei'), # must be greater than base_fee post London } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - modified_txn_hash = web3.eth.modify_transaction( + modified_txn_hash = w3.eth.modify_transaction( txn_hash, gasPrice=(cast(int, txn_params['gasPrice']) * 2), value=2 ) - modified_txn = web3.eth.get_transaction(modified_txn_hash) + modified_txn = w3.eth.get_transaction(modified_txn_hash) assert is_same_address(modified_txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(modified_txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -2423,25 +2423,25 @@ def test_eth_modify_transaction_legacy( assert modified_txn['gasPrice'] == cast(int, txn_params['gasPrice']) * 2 def test_eth_modify_transaction( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account, 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei'), - 'maxFeePerGas': web3.toWei(2, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei'), + 'maxFeePerGas': w3.toWei(2, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) - modified_txn_hash = web3.eth.modify_transaction( + modified_txn_hash = w3.eth.modify_transaction( txn_hash, value=2, maxPriorityFeePerGas=(cast(Wei, txn_params['maxPriorityFeePerGas']) * 2), maxFeePerGas=(cast(Wei, txn_params['maxFeePerGas']) * 2), ) - modified_txn = web3.eth.get_transaction(modified_txn_hash) + modified_txn = w3.eth.get_transaction(modified_txn_hash) assert is_same_address(modified_txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(modified_txn['to'], cast(ChecksumAddress, txn_params['to'])) @@ -2452,23 +2452,23 @@ def test_eth_modify_transaction( assert modified_txn['maxFeePerGas'] == cast(Wei, txn_params['maxFeePerGas']) * 2 def test_eth_modifyTransaction_deprecated( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: txn_params: TxParams = { 'from': unlocked_account, 'to': unlocked_account, 'value': Wei(1), 'gas': 21000, - 'gasPrice': web3.toWei(1, 'gwei'), + 'gasPrice': w3.toWei(1, 'gwei'), } - txn_hash = web3.eth.send_transaction(txn_params) + txn_hash = w3.eth.send_transaction(txn_params) with pytest.warns( DeprecationWarning, match="modifyTransaction is deprecated in favor of modify_transaction"): - modified_txn_hash = web3.eth.modifyTransaction( + modified_txn_hash = w3.eth.modifyTransaction( txn_hash, gasPrice=(cast(int, txn_params['gasPrice']) * 2), value=2 ) - modified_txn = web3.eth.get_transaction(modified_txn_hash) + modified_txn = w3.eth.get_transaction(modified_txn_hash) assert is_same_address(modified_txn['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(modified_txn['to'], cast(ChecksumAddress, txn_params['to'])) assert modified_txn['value'] == 2 @@ -2476,13 +2476,13 @@ def test_eth_modifyTransaction_deprecated( assert modified_txn['gasPrice'] == cast(int, txn_params['gasPrice']) * 2 def test_eth_send_raw_transaction( - self, web3: "Web3", unlocked_account: ChecksumAddress + self, w3: "Web3", unlocked_account: ChecksumAddress ) -> None: - signed_tx = web3.eth.account.sign_transaction( + signed_tx = w3.eth.account.sign_transaction( { 'to': '0x0000000000000000000000000000000000000000', 'value': 0, - 'nonce': web3.eth.get_transaction_count(unlocked_account), + 'nonce': w3.eth.get_transaction_count(unlocked_account), 'gas': 21000, 'maxFeePerGas': 1000000000, 'maxPriorityFeePerGas': 1000000000, @@ -2491,62 +2491,62 @@ def test_eth_send_raw_transaction( # unlocked_account private key: '0x392f63a79b1ff8774845f3fa69de4a13800a59e7083f5187f1558f0797ad0f01' ) - txn_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction) + txn_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) assert txn_hash == signed_tx.hash def test_eth_call( - self, web3: "Web3", math_contract: "Contract" + self, w3: "Web3", math_contract: "Contract" ) -> None: - coinbase = web3.eth.coinbase + coinbase = w3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(7, 11), transaction={'from': coinbase, 'to': math_contract.address}, ) - call_result = web3.eth.call(txn_params) + call_result = w3.eth.call(txn_params) assert is_string(call_result) - result = web3.codec.decode_single('uint256', call_result) + result = w3.codec.decode_single('uint256', call_result) assert result == 18 def test_eth_call_with_override( - self, web3: "Web3", revert_contract: "Contract" + self, w3: "Web3", revert_contract: "Contract" ) -> None: - coinbase = web3.eth.coinbase + coinbase = w3.eth.coinbase txn_params = revert_contract._prepare_transaction( fn_name='normalFunction', transaction={'from': coinbase, 'to': revert_contract.address}, ) - call_result = web3.eth.call(txn_params) - result = web3.codec.decode_single('bool', call_result) + call_result = w3.eth.call(txn_params) + result = w3.codec.decode_single('bool', call_result) assert result is True # override runtime bytecode: `normalFunction` returns `false` override_code = '0x6080604052348015600f57600080fd5b5060043610603c5760003560e01c8063185c38a4146041578063c06a97cb146049578063d67e4b84146051575b600080fd5b60476071565b005b604f60df565b005b605760e4565b604051808215151515815260200191505060405180910390f35b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f46756e6374696f6e20686173206265656e2072657665727465642e000000000081525060200191505060405180910390fd5b600080fd5b60008090509056fea2646970667358221220bb71e9e9a2e271cd0fbe833524a3ea67df95f25ea13aef5b0a761fa52b538f1064736f6c63430006010033' # noqa: E501 - call_result = web3.eth.call( + call_result = w3.eth.call( txn_params, 'latest', {revert_contract.address: {'code': override_code}} ) - result = web3.codec.decode_single('bool', call_result) + result = w3.codec.decode_single('bool', call_result) assert result is False def test_eth_call_with_0_result( - self, web3: "Web3", math_contract: "Contract" + self, w3: "Web3", math_contract: "Contract" ) -> None: - coinbase = web3.eth.coinbase + coinbase = w3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(0, 0), transaction={'from': coinbase, 'to': math_contract.address}, ) - call_result = web3.eth.call(txn_params) + call_result = w3.eth.call(txn_params) assert is_string(call_result) - result = web3.codec.decode_single('uint256', call_result) + result = w3.codec.decode_single('uint256', call_result) assert result == 0 def test_eth_call_revert_with_msg( self, - web3: "Web3", + w3: "Web3", revert_contract: "Contract", unlocked_account: ChecksumAddress, ) -> None: @@ -2559,11 +2559,11 @@ def test_eth_call_revert_with_msg( "to": revert_contract.address, }, ) - web3.eth.call(txn_params) + w3.eth.call(txn_params) def test_eth_call_revert_without_msg( self, - web3: "Web3", + w3: "Web3", revert_contract: "Contract", unlocked_account: ChecksumAddress, ) -> None: @@ -2575,11 +2575,11 @@ def test_eth_call_revert_without_msg( "to": revert_contract.address, }, ) - web3.eth.call(txn_params) + w3.eth.call(txn_params) def test_eth_estimate_gas_revert_with_msg( self, - web3: "Web3", + w3: "Web3", revert_contract: "Contract", unlocked_account: ChecksumAddress, ) -> None: @@ -2592,11 +2592,11 @@ def test_eth_estimate_gas_revert_with_msg( "to": revert_contract.address, }, ) - web3.eth.estimate_gas(txn_params) + w3.eth.estimate_gas(txn_params) def test_eth_estimate_gas_revert_without_msg( self, - web3: "Web3", + w3: "Web3", revert_contract: "Contract", unlocked_account: ChecksumAddress, ) -> None: @@ -2608,12 +2608,12 @@ def test_eth_estimate_gas_revert_without_msg( "to": revert_contract.address, }, ) - web3.eth.estimate_gas(txn_params) + w3.eth.estimate_gas(txn_params) def test_eth_estimate_gas( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - gas_estimate = web3.eth.estimate_gas({ + gas_estimate = w3.eth.estimate_gas({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), @@ -2622,11 +2622,11 @@ def test_eth_estimate_gas( assert gas_estimate > 0 def test_eth_estimateGas_deprecated( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: with pytest.warns(DeprecationWarning, match="estimateGas is deprecated in favor of estimate_gas"): - gas_estimate = web3.eth.estimateGas({ + gas_estimate = w3.eth.estimateGas({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), @@ -2635,9 +2635,9 @@ def test_eth_estimateGas_deprecated( assert gas_estimate > 0 def test_eth_estimate_gas_with_block( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - gas_estimate = web3.eth.estimate_gas({ + gas_estimate = w3.eth.estimate_gas({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), @@ -2646,141 +2646,141 @@ def test_eth_estimate_gas_with_block( assert gas_estimate > 0 def test_eth_getBlock_deprecated( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: with pytest.warns(DeprecationWarning, match="getBlock is deprecated in favor of get_block"): - block = web3.eth.getBlock(empty_block['hash']) + block = w3.eth.getBlock(empty_block['hash']) assert block['hash'] == empty_block['hash'] def test_eth_getBlockByHash( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - block = web3.eth.get_block(empty_block['hash']) + block = w3.eth.get_block(empty_block['hash']) assert block['hash'] == empty_block['hash'] def test_eth_getBlockByHash_not_found( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: with pytest.raises(BlockNotFound): - web3.eth.get_block(UNKNOWN_HASH) + w3.eth.get_block(UNKNOWN_HASH) def test_eth_getBlockByHash_pending( - self, web3: "Web3" + self, w3: "Web3" ) -> None: - block = web3.eth.get_block('pending') + block = w3.eth.get_block('pending') assert block['hash'] is None def test_eth_getBlockByNumber_with_integer( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - block = web3.eth.get_block(empty_block['number']) + block = w3.eth.get_block(empty_block['number']) assert block['number'] == empty_block['number'] def test_eth_getBlockByNumber_with_integer_deprecated( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: with pytest.warns(DeprecationWarning, match="getBlock is deprecated in favor of get_block"): - block = web3.eth.getBlock(empty_block['number']) + block = w3.eth.getBlock(empty_block['number']) assert block['number'] == empty_block['number'] def test_eth_getBlockByNumber_latest( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - current_block_number = web3.eth.block_number - block = web3.eth.get_block('latest') + current_block_number = w3.eth.block_number + block = w3.eth.get_block('latest') assert block['number'] == current_block_number def test_eth_getBlockByNumber_not_found( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: with pytest.raises(BlockNotFound): - web3.eth.get_block(BlockNumber(12345)) + w3.eth.get_block(BlockNumber(12345)) def test_eth_getBlockByNumber_pending( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - current_block_number = web3.eth.block_number - block = web3.eth.get_block('pending') + current_block_number = w3.eth.block_number + block = w3.eth.get_block('pending') assert block['number'] == current_block_number + 1 def test_eth_getBlockByNumber_earliest( - self, web3: "Web3", empty_block: BlockData + self, w3: "Web3", empty_block: BlockData ) -> None: - genesis_block = web3.eth.get_block(BlockNumber(0)) - block = web3.eth.get_block('earliest') + genesis_block = w3.eth.get_block(BlockNumber(0)) + block = w3.eth.get_block('earliest') assert block['number'] == 0 assert block['hash'] == genesis_block['hash'] def test_eth_getBlockByNumber_full_transactions( - self, web3: "Web3", block_with_txn: BlockData + self, w3: "Web3", block_with_txn: BlockData ) -> None: - block = web3.eth.get_block(block_with_txn['number'], True) + block = w3.eth.get_block(block_with_txn['number'], True) transaction = block['transactions'][0] assert transaction['hash'] == block_with_txn['transactions'][0] # type: ignore def test_eth_getTransactionByHash( - self, web3: "Web3", mined_txn_hash: HexStr + self, w3: "Web3", mined_txn_hash: HexStr ) -> None: - transaction = web3.eth.get_transaction(mined_txn_hash) + transaction = w3.eth.get_transaction(mined_txn_hash) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByHash_deprecated( - self, web3: "Web3", mined_txn_hash: HexStr + self, w3: "Web3", mined_txn_hash: HexStr ) -> None: with pytest.warns(DeprecationWarning, match='getTransaction is deprecated in favor of get_transaction'): - transaction = web3.eth.getTransaction(mined_txn_hash) + transaction = w3.eth.getTransaction(mined_txn_hash) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByHash_contract_creation( - self, web3: "Web3", math_contract_deploy_txn_hash: HexStr + self, w3: "Web3", math_contract_deploy_txn_hash: HexStr ) -> None: - transaction = web3.eth.get_transaction(math_contract_deploy_txn_hash) + transaction = w3.eth.get_transaction(math_contract_deploy_txn_hash) assert is_dict(transaction) assert transaction['to'] is None, "to field is %r" % transaction['to'] def test_eth_getTransactionByBlockHashAndIndex( - self, web3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr + self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: - transaction = web3.eth.get_transaction_by_block(block_with_txn['hash'], 0) + transaction = w3.eth.get_transaction_by_block(block_with_txn['hash'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByBlockHashAndIndex_deprecated( - self, web3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr + self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: with pytest.warns( DeprecationWarning, match='getTransactionByBlock is deprecated in favor of get_transaction_by_block' ): - transaction = web3.eth.getTransactionByBlock(block_with_txn['hash'], 0) + transaction = w3.eth.getTransactionByBlock(block_with_txn['hash'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByBlockNumberAndIndex( - self, web3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr + self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: - transaction = web3.eth.get_transaction_by_block(block_with_txn['number'], 0) + transaction = w3.eth.get_transaction_by_block(block_with_txn['number'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByBlockNumberAndIndex_deprecated( - self, web3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr + self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: with pytest.warns( DeprecationWarning, match='getTransactionByBlock is deprecated in favor of get_transaction_by_block' ): - transaction = web3.eth.getTransactionByBlock(block_with_txn['number'], 0) + transaction = w3.eth.getTransactionByBlock(block_with_txn['number'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_get_transaction_receipt_mined( - self, web3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr + self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: - receipt = web3.eth.get_transaction_receipt(mined_txn_hash) + receipt = w3.eth.get_transaction_receipt(mined_txn_hash) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn['number'] assert receipt['blockHash'] == block_with_txn['hash'] @@ -2795,12 +2795,12 @@ def test_eth_get_transaction_receipt_mined( assert effective_gas_price > 0 def test_eth_getTransactionReceipt_mined_deprecated( - self, web3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr + self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: with pytest.warns( DeprecationWarning, match="getTransactionReceipt is deprecated in favor of get_transaction_receipt"): - receipt = web3.eth.getTransactionReceipt(mined_txn_hash) + receipt = w3.eth.getTransactionReceipt(mined_txn_hash) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn['number'] assert receipt['blockHash'] == block_with_txn['hash'] @@ -2811,27 +2811,27 @@ def test_eth_getTransactionReceipt_mined_deprecated( assert is_checksum_address(receipt['from']) def test_eth_get_transaction_receipt_unmined( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - txn_hash = web3.eth.send_transaction({ + txn_hash = w3.eth.send_transaction({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(3, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei') + 'maxFeePerGas': w3.toWei(3, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei') }) with pytest.raises(TransactionNotFound): - web3.eth.get_transaction_receipt(txn_hash) + w3.eth.get_transaction_receipt(txn_hash) def test_eth_get_transaction_receipt_with_log_entry( self, - web3: "Web3", + w3: "Web3", block_with_txn_with_log: BlockData, emitter_contract: "Contract", txn_hash_with_log: HexStr, ) -> None: - receipt = web3.eth.get_transaction_receipt(txn_hash_with_log) + receipt = w3.eth.get_transaction_receipt(txn_hash_with_log) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn_with_log['number'] assert receipt['blockHash'] == block_with_txn_with_log['hash'] @@ -2850,11 +2850,11 @@ def test_eth_get_transaction_receipt_with_log_entry( def test_eth_wait_for_transaction_receipt_mined( self, - web3: "Web3", + w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr ) -> None: - receipt = web3.eth.wait_for_transaction_receipt(mined_txn_hash) + receipt = w3.eth.wait_for_transaction_receipt(mined_txn_hash) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn['number'] assert receipt['blockHash'] == block_with_txn['hash'] @@ -2869,31 +2869,31 @@ def test_eth_wait_for_transaction_receipt_mined( assert effective_gas_price > 0 def test_eth_wait_for_transaction_receipt_unmined( - self, web3: "Web3", unlocked_account_dual_type: ChecksumAddress + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: - txn_hash = web3.eth.send_transaction({ + txn_hash = w3.eth.send_transaction({ 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), 'gas': 21000, - 'maxFeePerGas': web3.toWei(3, 'gwei'), - 'maxPriorityFeePerGas': web3.toWei(1, 'gwei') + 'maxFeePerGas': w3.toWei(3, 'gwei'), + 'maxPriorityFeePerGas': w3.toWei(1, 'gwei') }) timeout = 2 with pytest.raises(TimeExhausted) as exc_info: - web3.eth.wait_for_transaction_receipt(txn_hash, timeout=timeout) + w3.eth.wait_for_transaction_receipt(txn_hash, timeout=timeout) assert (_ in str(exc_info) for _ in [repr(txn_hash), timeout]) def test_eth_wait_for_transaction_receipt_with_log_entry( self, - web3: "Web3", + w3: "Web3", block_with_txn_with_log: BlockData, emitter_contract: "Contract", txn_hash_with_log: HexStr, ) -> None: - receipt = web3.eth.wait_for_transaction_receipt(txn_hash_with_log) + receipt = w3.eth.wait_for_transaction_receipt(txn_hash_with_log) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn_with_log['number'] assert receipt['blockHash'] == block_with_txn_with_log['hash'] @@ -2910,78 +2910,78 @@ def test_eth_wait_for_transaction_receipt_with_log_entry( assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log) - def test_eth_getUncleByBlockHashAndIndex(self, web3: "Web3") -> None: + def test_eth_getUncleByBlockHashAndIndex(self, w3: "Web3") -> None: # TODO: how do we make uncles.... pass - def test_eth_getUncleByBlockNumberAndIndex(self, web3: "Web3") -> None: + def test_eth_getUncleByBlockNumberAndIndex(self, w3: "Web3") -> None: # TODO: how do we make uncles.... pass - def test_eth_newFilter(self, web3: "Web3") -> None: - filter = web3.eth.filter({}) + def test_eth_newFilter(self, w3: "Web3") -> None: + filter = w3.eth.filter({}) - changes = web3.eth.get_filter_changes(filter.filter_id) + changes = w3.eth.get_filter_changes(filter.filter_id) assert is_list_like(changes) assert not changes - logs = web3.eth.get_filter_logs(filter.filter_id) + logs = w3.eth.get_filter_logs(filter.filter_id) assert is_list_like(logs) assert not logs - result = web3.eth.uninstall_filter(filter.filter_id) + result = w3.eth.uninstall_filter(filter.filter_id) assert result is True - def test_eth_newFilter_deprecated(self, web3: "Web3") -> None: - filter = web3.eth.filter({}) + def test_eth_newFilter_deprecated(self, w3: "Web3") -> None: + filter = w3.eth.filter({}) - changes = web3.eth.get_filter_changes(filter.filter_id) + changes = w3.eth.get_filter_changes(filter.filter_id) assert is_list_like(changes) assert not changes with pytest.warns(DeprecationWarning, match="getFilterLogs is deprecated in favor of get_filter_logs"): - logs = web3.eth.getFilterLogs(filter.filter_id) + logs = w3.eth.getFilterLogs(filter.filter_id) assert is_list_like(logs) assert not logs - result = web3.eth.uninstall_filter(filter.filter_id) + result = w3.eth.uninstall_filter(filter.filter_id) assert result is True - def test_eth_newBlockFilter(self, web3: "Web3") -> None: - filter = web3.eth.filter('latest') + def test_eth_newBlockFilter(self, w3: "Web3") -> None: + filter = w3.eth.filter('latest') assert is_string(filter.filter_id) - changes = web3.eth.get_filter_changes(filter.filter_id) + changes = w3.eth.get_filter_changes(filter.filter_id) assert is_list_like(changes) assert not changes # TODO: figure out why this fails in go-ethereum - # logs = web3.eth.get_filter_logs(filter.filter_id) + # logs = w3.eth.get_filter_logs(filter.filter_id) # assert is_list_like(logs) # assert not logs - result = web3.eth.uninstall_filter(filter.filter_id) + result = w3.eth.uninstall_filter(filter.filter_id) assert result is True - def test_eth_newPendingTransactionFilter(self, web3: "Web3") -> None: - filter = web3.eth.filter('pending') + def test_eth_newPendingTransactionFilter(self, w3: "Web3") -> None: + filter = w3.eth.filter('pending') assert is_string(filter.filter_id) - changes = web3.eth.get_filter_changes(filter.filter_id) + changes = w3.eth.get_filter_changes(filter.filter_id) assert is_list_like(changes) assert not changes # TODO: figure out why this fails in go-ethereum - # logs = web3.eth.get_filter_logs(filter.filter_id) + # logs = w3.eth.get_filter_logs(filter.filter_id) # assert is_list_like(logs) # assert not logs - result = web3.eth.uninstall_filter(filter.filter_id) + result = w3.eth.uninstall_filter(filter.filter_id) assert result is True def test_eth_get_logs_without_logs( - self, web3: "Web3", block_with_txn_with_log: BlockData + self, w3: "Web3", block_with_txn_with_log: BlockData ) -> None: # Test with block range @@ -2989,7 +2989,7 @@ def test_eth_get_logs_without_logs( "fromBlock": BlockNumber(0), "toBlock": BlockNumber(block_with_txn_with_log['number'] - 1), } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) assert len(result) == 0 # the range is wrong @@ -2997,7 +2997,7 @@ def test_eth_get_logs_without_logs( "fromBlock": block_with_txn_with_log['number'], "toBlock": BlockNumber(block_with_txn_with_log['number'] - 1), } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) assert len(result) == 0 # Test with `address` @@ -3007,7 +3007,7 @@ def test_eth_get_logs_without_logs( "fromBlock": BlockNumber(0), "address": UNKNOWN_ADDRESS, } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) assert len(result) == 0 # Test with multiple `address` @@ -3017,12 +3017,12 @@ def test_eth_get_logs_without_logs( "fromBlock": BlockNumber(0), "address": [UNKNOWN_ADDRESS, UNKNOWN_ADDRESS], } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) assert len(result) == 0 def test_eth_get_logs_with_logs( self, - web3: "Web3", + w3: "Web3", block_with_txn_with_log: BlockData, emitter_contract_address: ChecksumAddress, txn_hash_with_log: HexStr, @@ -3035,7 +3035,7 @@ def test_eth_get_logs_with_logs( "fromBlock": block_with_txn_with_log['number'], "toBlock": block_with_txn_with_log['number'], } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) _assert_contains_log( result, block_with_txn_with_log, @@ -3047,7 +3047,7 @@ def test_eth_get_logs_with_logs( filter_params = { "fromBlock": BlockNumber(0), } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) _assert_contains_log( result, block_with_txn_with_log, @@ -3065,7 +3065,7 @@ def test_eth_get_logs_with_logs( def test_eth_get_logs_with_logs_topic_args( self, - web3: "Web3", + w3: "Web3", block_with_txn_with_log: BlockData, emitter_contract_address: ChecksumAddress, txn_hash_with_log: HexStr, @@ -3080,7 +3080,7 @@ def test_eth_get_logs_with_logs_topic_args( HexStr('0x000000000000000000000000000000000000000000000000000000000000d431')], } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) _assert_contains_log( result, block_with_txn_with_log, @@ -3095,7 +3095,7 @@ def test_eth_get_logs_with_logs_topic_args( HexStr('0x057bc32826fbe161da1c110afcdcae7c109a8b69149f727fc37a603c60ef94ca'), None], } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) _assert_contains_log( result, block_with_txn_with_log, @@ -3103,20 +3103,20 @@ def test_eth_get_logs_with_logs_topic_args( txn_hash_with_log ) - def test_eth_get_logs_with_logs_none_topic_args(self, web3: "Web3") -> None: + def test_eth_get_logs_with_logs_none_topic_args(self, w3: "Web3") -> None: # Test with None overflowing filter_params: FilterParams = { "fromBlock": BlockNumber(0), "topics": [None, None, None], } - result = web3.eth.get_logs(filter_params) + result = w3.eth.get_logs(filter_params) assert len(result) == 0 def test_eth_call_old_contract_state( - self, web3: "Web3", math_contract: "Contract", unlocked_account: ChecksumAddress + self, w3: "Web3", math_contract: "Contract", unlocked_account: ChecksumAddress ) -> None: - start_block = web3.eth.get_block('latest') + start_block = w3.eth.get_block('latest') block_num = start_block["number"] block_hash = start_block["hash"] @@ -3142,113 +3142,113 @@ def test_eth_call_old_contract_state( if pending_call_result != 1: raise AssertionError("pending call result was %d instead of 1" % pending_call_result) - def test_eth_uninstallFilter_deprecated(self, web3: "Web3") -> None: - filter = web3.eth.filter({}) + def test_eth_uninstallFilter_deprecated(self, w3: "Web3") -> None: + filter = w3.eth.filter({}) assert is_string(filter.filter_id) with pytest.warns(DeprecationWarning, match="uninstallFilter is deprecated in favor of uninstall_filter"): - success = web3.eth.uninstallFilter(filter.filter_id) + success = w3.eth.uninstallFilter(filter.filter_id) assert success is True with pytest.warns(DeprecationWarning, match="uninstallFilter is deprecated in favor of uninstall_filter"): - failure = web3.eth.uninstallFilter(filter.filter_id) + failure = w3.eth.uninstallFilter(filter.filter_id) assert failure is False - def test_eth_uninstall_filter(self, web3: "Web3") -> None: - filter = web3.eth.filter({}) + def test_eth_uninstall_filter(self, w3: "Web3") -> None: + filter = w3.eth.filter({}) assert is_string(filter.filter_id) - success = web3.eth.uninstall_filter(filter.filter_id) + success = w3.eth.uninstall_filter(filter.filter_id) assert success is True - failure = web3.eth.uninstall_filter(filter.filter_id) + failure = w3.eth.uninstall_filter(filter.filter_id) assert failure is False def test_eth_getTransactionFromBlock_deprecation( - self, web3: "Web3", block_with_txn: BlockData + self, w3: "Web3", block_with_txn: BlockData ) -> None: with pytest.raises(DeprecationWarning): - web3.eth.getTransactionFromBlock(block_with_txn['hash'], 0) + w3.eth.getTransactionFromBlock(block_with_txn['hash'], 0) - def test_eth_getCompilers_deprecation(self, web3: "Web3") -> None: + def test_eth_getCompilers_deprecation(self, w3: "Web3") -> None: with pytest.raises(DeprecationWarning): - web3.eth.getCompilers() + w3.eth.getCompilers() - def test_eth_submit_hashrate(self, web3: "Web3") -> None: + def test_eth_submit_hashrate(self, w3: "Web3") -> None: # node_id from EIP 1474: https://github.com/ethereum/EIPs/pull/1474/files node_id = HexStr('59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c') - result = web3.eth.submit_hashrate(5000, node_id) + result = w3.eth.submit_hashrate(5000, node_id) assert result is True - def test_eth_submitHashrate_deprecated(self, web3: "Web3") -> None: + def test_eth_submitHashrate_deprecated(self, w3: "Web3") -> None: # node_id from EIP 1474: https://github.com/ethereum/EIPs/pull/1474/files node_id = HexStr('59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c') with pytest.warns(DeprecationWarning, match='submitHashrate is deprecated in favor of submit_hashrate'): - result = web3.eth.submitHashrate(5000, node_id) + result = w3.eth.submitHashrate(5000, node_id) assert result is True - def test_eth_submit_work(self, web3: "Web3") -> None: + def test_eth_submit_work(self, w3: "Web3") -> None: nonce = 1 pow_hash = HexStr('0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef') mix_digest = HexStr('0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000') - result = web3.eth.submit_work(nonce, pow_hash, mix_digest) + result = w3.eth.submit_work(nonce, pow_hash, mix_digest) assert result is False - def test_eth_submitWork_deprecated(self, web3: "Web3") -> None: + def test_eth_submitWork_deprecated(self, w3: "Web3") -> None: nonce = 1 pow_hash = HexStr('0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef') mix_digest = HexStr('0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000') with pytest.warns(DeprecationWarning, match="submitWork is deprecated in favor of submit_work"): - result = web3.eth.submitWork(nonce, pow_hash, mix_digest) + result = w3.eth.submitWork(nonce, pow_hash, mix_digest) assert result is False def test_eth_get_raw_transaction( - self, web3: "Web3", mined_txn_hash: HexStr + self, w3: "Web3", mined_txn_hash: HexStr ) -> None: - raw_transaction = web3.eth.get_raw_transaction(mined_txn_hash) + raw_transaction = w3.eth.get_raw_transaction(mined_txn_hash) assert is_bytes(raw_transaction) - def test_eth_get_raw_transaction_raises_error(self, web3: "Web3") -> None: + def test_eth_get_raw_transaction_raises_error(self, w3: "Web3") -> None: with pytest.raises(TransactionNotFound, match=f"Transaction with hash: '{UNKNOWN_HASH}'"): - web3.eth.get_raw_transaction(UNKNOWN_HASH) + w3.eth.get_raw_transaction(UNKNOWN_HASH) def test_eth_get_raw_transaction_by_block( - self, web3: "Web3", + self, w3: "Web3", unlocked_account_dual_type: ChecksumAddress, block_with_txn: BlockData, ) -> None: # eth_getRawTransactionByBlockNumberAndIndex: block identifier # send a txn to make sure pending block has at least one txn - web3.eth.send_transaction( + w3.eth.send_transaction( { 'from': unlocked_account_dual_type, 'to': unlocked_account_dual_type, 'value': Wei(1), } ) - last_pending_txn_index = len(web3.eth.get_block('pending')['transactions']) - 1 - raw_transaction = web3.eth.get_raw_transaction_by_block('pending', last_pending_txn_index) + last_pending_txn_index = len(w3.eth.get_block('pending')['transactions']) - 1 + raw_transaction = w3.eth.get_raw_transaction_by_block('pending', last_pending_txn_index) assert is_bytes(raw_transaction) # eth_getRawTransactionByBlockNumberAndIndex: block number block_with_txn_number = block_with_txn['number'] assert is_integer(block_with_txn_number) - raw_transaction = web3.eth.get_raw_transaction_by_block(block_with_txn_number, 0) + raw_transaction = w3.eth.get_raw_transaction_by_block(block_with_txn_number, 0) assert is_bytes(raw_transaction) # eth_getRawTransactionByBlockHashAndIndex: block hash block_with_txn_hash = block_with_txn['hash'] assert is_bytes(block_with_txn_hash) - raw_transaction = web3.eth.get_raw_transaction_by_block(block_with_txn_hash, 0) + raw_transaction = w3.eth.get_raw_transaction_by_block(block_with_txn_hash, 0) assert is_bytes(raw_transaction) @pytest.mark.parametrize('unknown_block_num_or_hash', (1234567899999, UNKNOWN_HASH)) def test_eth_get_raw_transaction_by_block_raises_error( - self, web3: "Web3", unknown_block_num_or_hash: Union[int, HexBytes] + self, w3: "Web3", unknown_block_num_or_hash: Union[int, HexBytes] ) -> None: with pytest.raises( TransactionNotFound, match=( @@ -3256,10 +3256,10 @@ def test_eth_get_raw_transaction_by_block_raises_error( f"{to_hex_if_integer(unknown_block_num_or_hash)!r} not found." ) ): - web3.eth.get_raw_transaction_by_block(unknown_block_num_or_hash, 0) + w3.eth.get_raw_transaction_by_block(unknown_block_num_or_hash, 0) def test_eth_get_raw_transaction_by_block_raises_error_block_identifier( - self, web3: "Web3" + self, w3: "Web3" ) -> None: unknown_identifier = "unknown" with pytest.raises( @@ -3267,39 +3267,39 @@ def test_eth_get_raw_transaction_by_block_raises_error_block_identifier( f"Value did not match any of the recognized block identifiers: {unknown_identifier}" ) ): - web3.eth.get_raw_transaction_by_block(unknown_identifier, 0) # type: ignore + w3.eth.get_raw_transaction_by_block(unknown_identifier, 0) # type: ignore def test_default_account( self, - web3: "Web3", + w3: "Web3", unlocked_account_dual_type: ChecksumAddress ) -> None: # check defaults to empty - default_account = web3.eth.default_account + default_account = w3.eth.default_account assert default_account is empty # check setter - web3.eth.default_account = unlocked_account_dual_type - default_account = web3.eth.default_account + w3.eth.default_account = unlocked_account_dual_type + default_account = w3.eth.default_account assert default_account == unlocked_account_dual_type # reset to default - web3.eth.default_account = empty + w3.eth.default_account = empty def test_default_block( self, - web3: "Web3", + w3: "Web3", ) -> None: # check defaults to 'latest' - default_block = web3.eth.default_block + default_block = w3.eth.default_block assert default_block == 'latest' # check setter - web3.eth.default_block = BlockNumber(12345) - default_block = web3.eth.default_block + w3.eth.default_block = BlockNumber(12345) + default_block = w3.eth.default_block assert default_block == BlockNumber(12345) # reset to default - web3.eth.default_block = 'latest' + w3.eth.default_block = 'latest' diff --git a/web3/_utils/module_testing/go_ethereum_admin_module.py b/web3/_utils/module_testing/go_ethereum_admin_module.py index 9a88f0bafe..38505deec7 100644 --- a/web3/_utils/module_testing/go_ethereum_admin_module.py +++ b/web3/_utils/module_testing/go_ethereum_admin_module.py @@ -16,17 +16,17 @@ class GoEthereumAdminModuleTest: - def test_add_peer(self, web3: "Web3") -> None: - result = web3.geth.admin.add_peer( + def test_add_peer(self, w3: "Web3") -> None: + result = w3.geth.admin.add_peer( EnodeURI('enode://f1a6b0bdbf014355587c3018454d070ac57801f05d3b39fe85da574f002a32e929f683d72aa5a8318382e4d3c7a05c9b91687b0d997a39619fb8a6e7ad88e512@1.1.1.1:30303'),) # noqa: E501 assert result is True - def test_admin_datadir(self, web3: "Web3", datadir: str) -> None: - result = web3.geth.admin.datadir() + def test_admin_datadir(self, w3: "Web3", datadir: str) -> None: + result = w3.geth.admin.datadir() assert result == datadir - def test_admin_node_info(self, web3: "Web3") -> None: - result = web3.geth.admin.node_info() + def test_admin_node_info(self, w3: "Web3") -> None: + result = w3.geth.admin.node_info() expected = AttributeDict({ 'id': '', 'name': '', @@ -39,55 +39,55 @@ def test_admin_node_info(self, web3: "Web3") -> None: # Test that result gives at least the keys that are listed in `expected` assert not set(expected.keys()).difference(result.keys()) - def test_admin_peers(self, web3: "Web3") -> None: - enode = web3.geth.admin.node_info()['enode'] - web3.geth.admin.add_peer(enode) - result = web3.geth.admin.peers() + def test_admin_peers(self, w3: "Web3") -> None: + enode = w3.geth.admin.node_info()['enode'] + w3.geth.admin.add_peer(enode) + result = w3.geth.admin.peers() assert len(result) == 1 - def test_admin_start_stop_rpc(self, web3: "Web3") -> None: - stop = web3.geth.admin.stop_rpc() + def test_admin_start_stop_rpc(self, w3: "Web3") -> None: + stop = w3.geth.admin.stop_rpc() assert stop is True - start = web3.geth.admin.start_rpc() + start = w3.geth.admin.start_rpc() assert start is True with pytest.warns(DeprecationWarning): - stop = web3.geth.admin.stopRPC() + stop = w3.geth.admin.stopRPC() assert stop is True with pytest.warns(DeprecationWarning): - start = web3.geth.admin.startRPC() + start = w3.geth.admin.startRPC() assert start is True - def test_admin_start_stop_ws(self, web3: "Web3") -> None: - stop = web3.geth.admin.stop_ws() + def test_admin_start_stop_ws(self, w3: "Web3") -> None: + stop = w3.geth.admin.stop_ws() assert stop is True - start = web3.geth.admin.start_ws() + start = w3.geth.admin.start_ws() assert start is True with pytest.warns(DeprecationWarning): - stop = web3.geth.admin.stopWS() + stop = w3.geth.admin.stopWS() assert stop is True with pytest.warns(DeprecationWarning): - start = web3.geth.admin.startWS() + start = w3.geth.admin.startWS() assert start is True # # Deprecated # - def test_admin_addPeer(self, web3: "Web3") -> None: + def test_admin_addPeer(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - result = web3.geth.admin.addPeer( + result = w3.geth.admin.addPeer( EnodeURI('enode://f1a6b0bdbf014355587c3018454d070ac57801f05d3b39fe85da574f002a32e929f683d72aa5a8318382e4d3c7a05c9b91687b0d997a39619fb8a6e7ad88e512@1.1.1.1:30303'), # noqa: E501 ) assert result is True - def test_admin_nodeInfo(self, web3: "Web3") -> None: + def test_admin_nodeInfo(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - result = web3.geth.admin.nodeInfo() + result = w3.geth.admin.nodeInfo() expected = AttributeDict({ 'id': '', 'name': '', @@ -119,24 +119,24 @@ async def test_async_nodes(self, async_w3: "Web3") -> None: assert isinstance(nodes, List) @pytest.mark.asyncio - async def test_admin_peers(self, web3: "Web3") -> None: - enode = await web3.geth.admin.node_info()['enode'] # type: ignore - web3.geth.admin.add_peer(enode) - result = await web3.geth.admin.peers() # type: ignore + async def test_admin_peers(self, w3: "Web3") -> None: + enode = await w3.geth.admin.node_info()['enode'] # type: ignore + w3.geth.admin.add_peer(enode) + result = await w3.geth.admin.peers() # type: ignore assert len(result) == 1 @pytest.mark.asyncio - async def test_admin_start_stop_rpc(self, web3: "Web3") -> None: - stop = await web3.geth.admin.stop_rpc() # type: ignore + async def test_admin_start_stop_rpc(self, w3: "Web3") -> None: + stop = await w3.geth.admin.stop_rpc() # type: ignore assert stop is True - start = await web3.geth.admin.start_rpc() # type: ignore + start = await w3.geth.admin.start_rpc() # type: ignore assert start is True @pytest.mark.asyncio - async def test_admin_start_stop_ws(self, web3: "Web3") -> None: - stop = await web3.geth.admin.stop_ws() # type: ignore + async def test_admin_start_stop_ws(self, w3: "Web3") -> None: + stop = await w3.geth.admin.stop_ws() # type: ignore assert stop is True - start = await web3.geth.admin.start_ws() # type: ignore + start = await w3.geth.admin.start_ws() # type: ignore assert start is True diff --git a/web3/_utils/module_testing/go_ethereum_personal_module.py b/web3/_utils/module_testing/go_ethereum_personal_module.py index 1e7fb35f06..34bff726b2 100644 --- a/web3/_utils/module_testing/go_ethereum_personal_module.py +++ b/web3/_utils/module_testing/go_ethereum_personal_module.py @@ -45,17 +45,17 @@ class GoEthereumPersonalModuleTest: - def test_personal_import_raw_key(self, web3: "Web3") -> None: - actual = web3.geth.personal.import_raw_key(PRIVATE_KEY_HEX, PASSWORD) + def test_personal_import_raw_key(self, w3: "Web3") -> None: + actual = w3.geth.personal.import_raw_key(PRIVATE_KEY_HEX, PASSWORD) assert actual == ADDRESS - def test_personal_importRawKey_deprecated(self, web3: "Web3") -> None: + def test_personal_importRawKey_deprecated(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - actual = web3.geth.personal.importRawKey(SECOND_PRIVATE_KEY_HEX, PASSWORD) + actual = w3.geth.personal.importRawKey(SECOND_PRIVATE_KEY_HEX, PASSWORD) assert actual == SECOND_ADDRESS - def test_personal_list_accounts(self, web3: "Web3") -> None: - accounts = web3.geth.personal.list_accounts() + def test_personal_list_accounts(self, w3: "Web3") -> None: + accounts = w3.geth.personal.list_accounts() assert is_list_like(accounts) assert len(accounts) > 0 assert all(( @@ -64,9 +64,9 @@ def test_personal_list_accounts(self, web3: "Web3") -> None: in accounts )) - def test_personal_listAccounts_deprecated(self, web3: "Web3") -> None: + def test_personal_listAccounts_deprecated(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - accounts = web3.geth.personal.listAccounts() + accounts = w3.geth.personal.listAccounts() assert is_list_like(accounts) assert len(accounts) > 0 assert all(( @@ -75,8 +75,8 @@ def test_personal_listAccounts_deprecated(self, web3: "Web3") -> None: in accounts )) - def test_personal_list_wallets(self, web3: "Web3") -> None: - wallets = web3.geth.personal.list_wallets() + def test_personal_list_wallets(self, w3: "Web3") -> None: + wallets = w3.geth.personal.list_wallets() assert is_list_like(wallets) assert len(wallets) > 0 assert is_checksum_address(wallets[0]['accounts'][0]['address']) @@ -85,25 +85,25 @@ def test_personal_list_wallets(self, web3: "Web3") -> None: assert is_string(wallets[0]['url']) def test_personal_lock_account( - self, web3: "Web3", unlockable_account_dual_type: ChecksumAddress + self, w3: "Web3", unlockable_account_dual_type: ChecksumAddress ) -> None: # TODO: how do we test this better? - web3.geth.personal.lock_account(unlockable_account_dual_type) + w3.geth.personal.lock_account(unlockable_account_dual_type) def test_personal_lockAccount_deprecated( - self, web3: "Web3", unlockable_account_dual_type: ChecksumAddress + self, w3: "Web3", unlockable_account_dual_type: ChecksumAddress ) -> None: with pytest.warns(DeprecationWarning): # TODO: how do we test this better? - web3.geth.personal.lockAccount(unlockable_account_dual_type) + w3.geth.personal.lockAccount(unlockable_account_dual_type) def test_personal_unlock_account_success( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: - result = web3.geth.personal.unlock_account( + result = w3.geth.personal.unlock_account( unlockable_account_dual_type, unlockable_account_pw ) @@ -111,56 +111,56 @@ def test_personal_unlock_account_success( def test_personal_unlockAccount_success_deprecated( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: with pytest.warns(DeprecationWarning): - result = web3.geth.personal.unlockAccount( + result = w3.geth.personal.unlockAccount( unlockable_account_dual_type, unlockable_account_pw ) assert result is True def test_personal_unlock_account_failure( - self, web3: "Web3", unlockable_account_dual_type: ChecksumAddress + self, w3: "Web3", unlockable_account_dual_type: ChecksumAddress ) -> None: with pytest.raises(ValueError): - web3.geth.personal.unlock_account(unlockable_account_dual_type, 'bad-password') + w3.geth.personal.unlock_account(unlockable_account_dual_type, 'bad-password') def test_personal_unlockAccount_failure_deprecated( - self, web3: "Web3", unlockable_account_dual_type: ChecksumAddress + self, w3: "Web3", unlockable_account_dual_type: ChecksumAddress ) -> None: with pytest.warns(DeprecationWarning): with pytest.raises(ValueError): - web3.geth.personal.unlockAccount(unlockable_account_dual_type, 'bad-password') + w3.geth.personal.unlockAccount(unlockable_account_dual_type, 'bad-password') - def test_personal_new_account(self, web3: "Web3") -> None: - new_account = web3.geth.personal.new_account(PASSWORD) + def test_personal_new_account(self, w3: "Web3") -> None: + new_account = w3.geth.personal.new_account(PASSWORD) assert is_checksum_address(new_account) - def test_personal_newAccount_deprecated(self, web3: "Web3") -> None: + def test_personal_newAccount_deprecated(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - new_account = web3.geth.personal.newAccount(PASSWORD) + new_account = w3.geth.personal.newAccount(PASSWORD) assert is_checksum_address(new_account) def test_personal_send_transaction( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: - assert web3.eth.get_balance(unlockable_account_dual_type) > constants.WEI_PER_ETHER + assert w3.eth.get_balance(unlockable_account_dual_type) > constants.WEI_PER_ETHER txn_params: TxParams = { 'from': unlockable_account_dual_type, 'to': unlockable_account_dual_type, 'gas': 21000, 'value': Wei(1), - 'gasPrice': web3.toWei(1, 'gwei'), + 'gasPrice': w3.toWei(1, 'gwei'), } - txn_hash = web3.geth.personal.send_transaction(txn_params, unlockable_account_pw) + txn_hash = w3.geth.personal.send_transaction(txn_params, unlockable_account_pw) assert txn_hash - transaction = web3.eth.get_transaction(txn_hash) + transaction = w3.eth.get_transaction(txn_hash) assert is_same_address(transaction['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(transaction['to'], cast(ChecksumAddress, txn_params['to'])) @@ -170,23 +170,23 @@ def test_personal_send_transaction( def test_personal_sendTransaction_deprecated( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: - assert web3.eth.get_balance(unlockable_account_dual_type) > constants.WEI_PER_ETHER + assert w3.eth.get_balance(unlockable_account_dual_type) > constants.WEI_PER_ETHER txn_params: TxParams = { 'from': unlockable_account_dual_type, 'to': unlockable_account_dual_type, 'gas': 21000, 'value': Wei(1), - 'gasPrice': web3.toWei(1, 'gwei'), + 'gasPrice': w3.toWei(1, 'gwei'), } with pytest.warns(DeprecationWarning): - txn_hash = web3.geth.personal.sendTransaction(txn_params, unlockable_account_pw) + txn_hash = w3.geth.personal.sendTransaction(txn_params, unlockable_account_pw) assert txn_hash - transaction = web3.eth.get_transaction(txn_hash) + transaction = w3.eth.get_transaction(txn_hash) assert is_same_address(transaction['from'], cast(ChecksumAddress, txn_params['from'])) assert is_same_address(transaction['to'], cast(ChecksumAddress, txn_params['to'])) @@ -196,33 +196,33 @@ def test_personal_sendTransaction_deprecated( def test_personal_sign_and_ecrecover( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: message = 'test-web3-geth-personal-sign' - signature = web3.geth.personal.sign( + signature = w3.geth.personal.sign( message, unlockable_account_dual_type, unlockable_account_pw ) - signer = web3.geth.personal.ec_recover(message, signature) + signer = w3.geth.personal.ec_recover(message, signature) assert is_same_address(signer, unlockable_account_dual_type) def test_personal_sign_and_ecrecover_deprecated( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: with pytest.warns(DeprecationWarning): message = 'test-web3-geth-personal-sign' - signature = web3.geth.personal.sign( + signature = w3.geth.personal.sign( message, unlockable_account_dual_type, unlockable_account_pw ) - signer = web3.geth.personal.ecRecover(message, signature) + signer = w3.geth.personal.ecRecover(message, signature) assert is_same_address(signer, unlockable_account_dual_type) @pytest.mark.xfail( @@ -230,7 +230,7 @@ def test_personal_sign_and_ecrecover_deprecated( ) def test_personal_sign_typed_data( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: @@ -273,7 +273,7 @@ def test_personal_sign_typed_data( } } ''' - signature = HexBytes(web3.geth.personal.sign_typed_data( + signature = HexBytes(w3.geth.personal.sign_typed_data( json.loads(typed_message), unlockable_account_dual_type, unlockable_account_pw @@ -290,7 +290,7 @@ def test_personal_sign_typed_data( @pytest.mark.xfail(reason="personal_signTypedData JSON RPC call has not been released in geth") def test_personal_sign_typed_data_deprecated( self, - web3: "Web3", + w3: "Web3", unlockable_account_dual_type: ChecksumAddress, unlockable_account_pw: str, ) -> None: @@ -334,7 +334,7 @@ def test_personal_sign_typed_data_deprecated( } } ''' - signature = HexBytes(web3.geth.personal.sign_typed_data( + signature = HexBytes(w3.geth.personal.sign_typed_data( json.loads(typed_message), unlockable_account_dual_type, unlockable_account_pw diff --git a/web3/_utils/module_testing/go_ethereum_txpool_module.py b/web3/_utils/module_testing/go_ethereum_txpool_module.py index 98117b7882..23a8a87498 100644 --- a/web3/_utils/module_testing/go_ethereum_txpool_module.py +++ b/web3/_utils/module_testing/go_ethereum_txpool_module.py @@ -23,14 +23,14 @@ async def test_async_geth_txpool_status(self, async_w3: "Web3") -> None: class GoEthereumTxPoolModuleTest: - def test_geth_txpool_inspect(self, web3: "Web3") -> None: - test_data = web3.geth.txpool.inspect() # type: ignore + def test_geth_txpool_inspect(self, w3: "Web3") -> None: + test_data = w3.geth.txpool.inspect() # type: ignore assert "pending" in test_data - def test_geth_txpool_content(self, web3: "Web3") -> None: - test_data = web3.geth.txpool.content() # type: ignore + def test_geth_txpool_content(self, w3: "Web3") -> None: + test_data = w3.geth.txpool.content() # type: ignore assert "pending" in test_data - def test_geth_txpool_status(self, web3: "Web3") -> None: - test_data = web3.geth.txpool.status() # type: ignore + def test_geth_txpool_status(self, w3: "Web3") -> None: + test_data = w3.geth.txpool.status() # type: ignore assert "pending" in test_data diff --git a/web3/_utils/module_testing/net_module.py b/web3/_utils/module_testing/net_module.py index 57deed74cc..dd894a735a 100644 --- a/web3/_utils/module_testing/net_module.py +++ b/web3/_utils/module_testing/net_module.py @@ -14,31 +14,31 @@ class NetModuleTest: - def test_net_version(self, web3: "Web3") -> None: - version = web3.net.version + def test_net_version(self, w3: "Web3") -> None: + version = w3.net.version assert is_string(version) assert version.isdigit() - def test_net_listening(self, web3: "Web3") -> None: - listening = web3.net.listening + def test_net_listening(self, w3: "Web3") -> None: + listening = w3.net.listening assert is_boolean(listening) - def test_net_peer_count(self, web3: "Web3") -> None: - peer_count = web3.net.peer_count + def test_net_peer_count(self, w3: "Web3") -> None: + peer_count = w3.net.peer_count assert is_integer(peer_count) - def test_net_peerCount(self, web3: "Web3") -> None: + def test_net_peerCount(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - peer_count = web3.net.peerCount + peer_count = w3.net.peerCount assert is_integer(peer_count) - def test_net_chainId_deprecation(self, web3: "Web3") -> None: + def test_net_chainId_deprecation(self, w3: "Web3") -> None: with pytest.raises(DeprecationWarning): - web3.net.chainId + w3.net.chainId class AsyncNetModuleTest: diff --git a/web3/_utils/module_testing/version_module.py b/web3/_utils/module_testing/version_module.py index 69b7c907ed..825e5afda7 100644 --- a/web3/_utils/module_testing/version_module.py +++ b/web3/_utils/module_testing/version_module.py @@ -12,16 +12,16 @@ class VersionModuleTest: - def test_eth_protocol_version(self, web3: "Web3") -> None: + def test_eth_protocol_version(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - protocol_version = web3.eth.protocol_version + protocol_version = w3.eth.protocol_version assert is_string(protocol_version) assert protocol_version.isdigit() - def test_eth_protocolVersion(self, web3: "Web3") -> None: + def test_eth_protocolVersion(self, w3: "Web3") -> None: with pytest.warns(DeprecationWarning): - protocol_version = web3.eth.protocolVersion + protocol_version = w3.eth.protocolVersion assert is_string(protocol_version) assert protocol_version.isdigit() diff --git a/web3/_utils/module_testing/web3_module.py b/web3/_utils/module_testing/web3_module.py index 17e25e1ff7..73abb9cbfb 100644 --- a/web3/_utils/module_testing/web3_module.py +++ b/web3/_utils/module_testing/web3_module.py @@ -25,8 +25,8 @@ class Web3ModuleTest: - def test_web3_clientVersion(self, web3: Web3) -> None: - client_version = web3.clientVersion + def test_web3_clientVersion(self, w3: Web3) -> None: + client_version = w3.clientVersion self._check_web3_clientVersion(client_version) def _check_web3_clientVersion(self, client_version: str) -> NoReturn: @@ -176,14 +176,14 @@ def _check_web3_clientVersion(self, client_version: str) -> NoReturn: ), ) def test_solidityKeccak( - self, web3: "Web3", types: Sequence[TypeStr], values: Sequence[Any], expected: HexBytes + self, w3: "Web3", types: Sequence[TypeStr], values: Sequence[Any], expected: HexBytes ) -> None: if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): # type: ignore - web3.solidityKeccak(types, values) + w3.solidityKeccak(types, values) return - actual = web3.solidityKeccak(types, values) + actual = w3.solidityKeccak(types, values) assert actual == expected @pytest.mark.parametrize( @@ -202,9 +202,9 @@ def test_solidityKeccak( ), ) def test_solidityKeccak_ens( - self, web3: "Web3", types: Sequence[TypeStr], values: Sequence[str], expected: HexBytes + self, w3: "Web3", types: Sequence[TypeStr], values: Sequence[str], expected: HexBytes ) -> None: - with ens_addresses(web3, { + with ens_addresses(w3, { 'one.eth': ChecksumAddress( HexAddress(HexStr("0x49EdDD3769c0712032808D86597B84ac5c2F5614")) ), @@ -217,7 +217,7 @@ def test_solidityKeccak_ens( Web3.solidityKeccak(types, values) # when called as instance method, ens lookups can succeed - actual = web3.solidityKeccak(types, values) + actual = w3.solidityKeccak(types, values) assert actual == expected @pytest.mark.parametrize( @@ -229,10 +229,10 @@ def test_solidityKeccak_ens( ) ) def test_solidityKeccak_same_number_of_types_and_values( - self, web3: "Web3", types: Sequence[TypeStr], values: Sequence[Any] + self, w3: "Web3", types: Sequence[TypeStr], values: Sequence[Any] ) -> None: with pytest.raises(ValueError): - web3.solidityKeccak(types, values) + w3.solidityKeccak(types, values) - def test_is_connected(self, web3: "Web3") -> None: - assert web3.isConnected() + def test_is_connected(self, w3: "Web3") -> None: + assert w3.isConnected() diff --git a/web3/_utils/transactions.py b/web3/_utils/transactions.py index 13d43ffea7..6a7d0f2bed 100644 --- a/web3/_utils/transactions.py +++ b/web3/_utils/transactions.py @@ -56,14 +56,14 @@ TRANSACTION_DEFAULTS = { 'value': 0, 'data': b'', - 'gas': lambda web3, tx: web3.eth.estimate_gas(tx), - 'gasPrice': lambda web3, tx: web3.eth.generate_gas_price(tx) or web3.eth.gas_price, + 'gas': lambda w3, tx: w3.eth.estimate_gas(tx), + 'gasPrice': lambda w3, tx: w3.eth.generate_gas_price(tx) or w3.eth.gas_price, 'maxFeePerGas': ( - lambda web3, tx: - web3.eth.max_priority_fee + (2 * web3.eth.get_block('latest')['baseFeePerGas']) + lambda w3, tx: + w3.eth.max_priority_fee + (2 * w3.eth.get_block('latest')['baseFeePerGas']) ), - 'maxPriorityFeePerGas': lambda web3, tx: web3.eth.max_priority_fee, - 'chainId': lambda web3, tx: web3.eth.chain_id, + 'maxPriorityFeePerGas': lambda w3, tx: w3.eth.max_priority_fee, + 'chainId': lambda w3, tx: w3.eth.chain_id, } if TYPE_CHECKING: @@ -71,12 +71,12 @@ @curry -def fill_nonce(web3: "Web3", transaction: TxParams) -> TxParams: +def fill_nonce(w3: "Web3", transaction: TxParams) -> TxParams: if 'from' in transaction and 'nonce' not in transaction: return assoc( transaction, 'nonce', - web3.eth.get_transaction_count( + w3.eth.get_transaction_count( cast(ChecksumAddress, transaction['from']), block_identifier='pending')) else: @@ -84,11 +84,11 @@ def fill_nonce(web3: "Web3", transaction: TxParams) -> TxParams: @curry -def fill_transaction_defaults(web3: "Web3", transaction: TxParams) -> TxParams: +def fill_transaction_defaults(w3: "Web3", transaction: TxParams) -> TxParams: """ if web3 is None, fill as much as possible while offline """ - strategy_based_gas_price = web3.eth.generate_gas_price(transaction) + strategy_based_gas_price = w3.eth.generate_gas_price(transaction) is_dynamic_fee_transaction = ( not strategy_based_gas_price and ( @@ -108,9 +108,9 @@ def fill_transaction_defaults(web3: "Web3", transaction: TxParams) -> TxParams: continue if callable(default_getter): - if web3 is None: + if w3 is None: raise ValueError("You must specify a '%s' value in the transaction" % key) - default_val = default_getter(web3, transaction) + default_val = default_getter(w3, transaction) else: default_val = default_getter @@ -118,21 +118,21 @@ def fill_transaction_defaults(web3: "Web3", transaction: TxParams) -> TxParams: return merge(defaults, transaction) -def get_block_gas_limit(web3: "Web3", block_identifier: Optional[BlockIdentifier] = None) -> int: +def get_block_gas_limit(w3: "Web3", block_identifier: Optional[BlockIdentifier] = None) -> int: if block_identifier is None: - block_identifier = web3.eth.block_number - block = web3.eth.get_block(block_identifier) + block_identifier = w3.eth.block_number + block = w3.eth.get_block(block_identifier) return block['gasLimit'] def get_buffered_gas_estimate( - web3: "Web3", transaction: TxParams, gas_buffer: int = 100000 + w3: "Web3", transaction: TxParams, gas_buffer: int = 100000 ) -> int: gas_estimate_transaction = cast(TxParams, dict(**transaction)) - gas_estimate = web3.eth.estimate_gas(gas_estimate_transaction) + gas_estimate = w3.eth.estimate_gas(gas_estimate_transaction) - gas_limit = get_block_gas_limit(web3) + gas_limit = get_block_gas_limit(w3) if gas_estimate > gas_limit: raise ValueError( @@ -144,8 +144,8 @@ def get_buffered_gas_estimate( return min(gas_limit, gas_estimate + gas_buffer) -def get_required_transaction(web3: "Web3", transaction_hash: _Hash32) -> TxData: - current_transaction = web3.eth.get_transaction(transaction_hash) +def get_required_transaction(w3: "Web3", transaction_hash: _Hash32) -> TxData: + current_transaction = w3.eth.get_transaction(transaction_hash) if not current_transaction: raise ValueError(f'Supplied transaction with hash {transaction_hash!r} does not exist') return current_transaction @@ -193,7 +193,7 @@ def assert_valid_transaction_params(transaction_params: TxParams) -> None: def prepare_replacement_transaction( - web3: "Web3", + w3: "Web3", original_transaction: TxData, replacement_transaction: TxParams, gas_multiplier: float = 1.125 @@ -220,7 +220,7 @@ def prepare_replacement_transaction( raise ValueError('Supplied gas price must exceed existing transaction gas price') else: - generated_gas_price = web3.eth.generate_gas_price(replacement_transaction) + generated_gas_price = w3.eth.generate_gas_price(replacement_transaction) minimum_gas_price = int(math.ceil(original_transaction['gasPrice'] * gas_multiplier)) if generated_gas_price and generated_gas_price > minimum_gas_price: replacement_transaction = assoc( @@ -233,9 +233,9 @@ def prepare_replacement_transaction( def replace_transaction( - web3: "Web3", current_transaction: TxData, new_transaction: TxParams + w3: "Web3", current_transaction: TxData, new_transaction: TxParams ) -> HexBytes: new_transaction = prepare_replacement_transaction( - web3, current_transaction, new_transaction + w3, current_transaction, new_transaction ) - return web3.eth.send_transaction(new_transaction) + return w3.eth.send_transaction(new_transaction) diff --git a/web3/contract.py b/web3/contract.py index d8b7227bbd..38e98b4152 100644 --- a/web3/contract.py +++ b/web3/contract.py @@ -155,9 +155,9 @@ class ContractFunctions: """Class containing contract function objects """ - def __init__(self, abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None) -> None: + def __init__(self, abi: ABI, w3: 'Web3', address: Optional[ChecksumAddress] = None) -> None: self.abi = abi - self.web3 = web3 + self.w3 = w3 self.address = address if self.abi: @@ -168,7 +168,7 @@ def __init__(self, abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = func['name'], ContractFunction.factory( func['name'], - web3=self.web3, + w3=self.w3, contract_abi=self.abi, address=self.address, function_identifier=func['name'])) @@ -229,7 +229,7 @@ class ContractEvents: """ - def __init__(self, abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None) -> None: + def __init__(self, abi: ABI, w3: 'Web3', address: Optional[ChecksumAddress] = None) -> None: if abi: self.abi = abi self._events = filter_by_type('event', self.abi) @@ -239,7 +239,7 @@ def __init__(self, abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = event['name'], ContractEvent.factory( event['name'], - web3=web3, + w3=w3, contract_abi=self.abi, address=address, event_name=event['name'])) @@ -294,7 +294,7 @@ class Contract: """ # set during class construction - web3: 'Web3' = None + w3: 'Web3' = None # instance level properties address: ChecksumAddress = None @@ -328,32 +328,32 @@ def __init__(self, address: Optional[ChecksumAddress] = None) -> None: :param address: Contract address as 0x hex string """ - if self.web3 is None: + if self.w3 is None: raise AttributeError( 'The `Contract` class has not been initialized. Please use the ' '`web3.contract` interface to create your contract class.' ) if address: - self.address = normalize_address(self.web3.ens, address) + self.address = normalize_address(self.w3.ens, address) if not self.address: raise TypeError("The address argument is required to instantiate a contract.") - self.functions = ContractFunctions(self.abi, self.web3, self.address) - self.caller = ContractCaller(self.abi, self.web3, self.address) - self.events = ContractEvents(self.abi, self.web3, self.address) - self.fallback = Contract.get_fallback_function(self.abi, self.web3, self.address) - self.receive = Contract.get_receive_function(self.abi, self.web3, self.address) + self.functions = ContractFunctions(self.abi, self.w3, self.address) + self.caller = ContractCaller(self.abi, self.w3, self.address) + self.events = ContractEvents(self.abi, self.w3, self.address) + self.fallback = Contract.get_fallback_function(self.abi, self.w3, self.address) + self.receive = Contract.get_receive_function(self.abi, self.w3, self.address) @classmethod - def factory(cls, web3: 'Web3', class_name: Optional[str] = None, **kwargs: Any) -> 'Contract': + def factory(cls, w3: 'Web3', class_name: Optional[str] = None, **kwargs: Any) -> 'Contract': - kwargs['web3'] = web3 + kwargs['w3'] = w3 normalizers = { 'abi': normalize_abi, - 'address': partial(normalize_address, kwargs['web3'].ens), + 'address': partial(normalize_address, kwargs['w3'].ens), 'bytecode': normalize_bytecode, 'bytecode_runtime': normalize_bytecode, } @@ -364,11 +364,11 @@ def factory(cls, web3: 'Web3', class_name: Optional[str] = None, **kwargs: Any) kwargs, normalizers=normalizers, )) - contract.functions = ContractFunctions(contract.abi, contract.web3) - contract.caller = ContractCaller(contract.abi, contract.web3, contract.address) - contract.events = ContractEvents(contract.abi, contract.web3) - contract.fallback = Contract.get_fallback_function(contract.abi, contract.web3) - contract.receive = Contract.get_receive_function(contract.abi, contract.web3) + contract.functions = ContractFunctions(contract.abi, contract.w3) + contract.caller = ContractCaller(contract.abi, contract.w3, contract.address) + contract.events = ContractEvents(contract.abi, contract.w3) + contract.fallback = Contract.get_fallback_function(contract.abi, contract.w3) + contract.receive = Contract.get_receive_function(contract.abi, contract.w3) return contract @@ -388,7 +388,7 @@ def constructor(cls, *args: Any, **kwargs: Any) -> 'ContractConstructor': "with it" ) - return ContractConstructor(cls.web3, + return ContractConstructor(cls.w3, cls.abi, cls.bytecode, *args, @@ -406,18 +406,18 @@ def encodeABI(cls, fn_name: str, args: Optional[Any] = None, :param data: defaults to function selector """ fn_abi, fn_selector, fn_arguments = get_function_info( - fn_name, cls.web3.codec, contract_abi=cls.abi, args=args, kwargs=kwargs, + fn_name, cls.w3.codec, contract_abi=cls.abi, args=args, kwargs=kwargs, ) if data is None: data = fn_selector - return encode_abi(cls.web3, fn_abi, fn_arguments, data) + return encode_abi(cls.w3, fn_abi, fn_arguments, data) @combomethod def all_functions(self) -> List['ContractFunction']: return find_functions_by_identifier( - self.abi, self.web3, self.address, lambda _: True + self.abi, self.w3, self.address, lambda _: True ) @combomethod @@ -431,7 +431,7 @@ def get_function_by_signature(self, signature: str) -> 'ContractFunction': def callable_check(fn_abi: ABIFunction) -> bool: return abi_to_signature(fn_abi) == signature - fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check) + fns = find_functions_by_identifier(self.abi, self.w3, self.address, callable_check) return get_function_by_identifier(fns, 'signature') @combomethod @@ -440,7 +440,7 @@ def callable_check(fn_abi: ABIFunction) -> bool: return fn_abi['name'] == fn_name return find_functions_by_identifier( - self.abi, self.web3, self.address, callable_check + self.abi, self.w3, self.address, callable_check ) @combomethod @@ -455,7 +455,7 @@ def callable_check(fn_abi: ABIFunction) -> bool: # https://github.com/python/mypy/issues/4976 return encode_hex(function_abi_to_4byte_selector(fn_abi)) == to_4byte_hex(selector) # type: ignore # noqa: E501 - fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check) + fns = find_functions_by_identifier(self.abi, self.w3, self.address, callable_check) return get_function_by_identifier(fns, 'selector') @combomethod @@ -468,7 +468,7 @@ def decode_function_input(self, data: HexStr) -> Tuple['ContractFunction', Dict[ names = get_abi_input_names(func.abi) types = get_abi_input_types(func.abi) - decoded = self.web3.codec.decode_abi(types, cast(HexBytes, params)) + decoded = self.w3.codec.decode_abi(types, cast(HexBytes, params)) normalized = map_abi_data(BASE_RETURN_NORMALIZERS, types, decoded) return func, dict(zip(names, normalized)) @@ -476,10 +476,10 @@ def decode_function_input(self, data: HexStr) -> Tuple['ContractFunction', Dict[ @combomethod def find_functions_by_args(self, *args: Any) -> List['ContractFunction']: def callable_check(fn_abi: ABIFunction) -> bool: - return check_if_arguments_can_be_encoded(fn_abi, self.web3.codec, args=args, kwargs={}) + return check_if_arguments_can_be_encoded(fn_abi, self.w3.codec, args=args, kwargs={}) return find_functions_by_identifier( - self.abi, self.web3, self.address, callable_check + self.abi, self.w3, self.address, callable_check ) @combomethod @@ -501,7 +501,7 @@ def _prepare_transaction(cls, return prepare_transaction( cls.address, - cls.web3, + cls.w3, fn_identifier=fn_name, contract_abi=cls.abi, transaction=transaction, @@ -515,7 +515,7 @@ def _find_matching_fn_abi( kwargs: Optional[Any] = None ) -> ABIFunction: return find_matching_fn_abi(cls.abi, - cls.web3.codec, + cls.w3.codec, fn_identifier=fn_identifier, args=args, kwargs=kwargs) @@ -531,12 +531,12 @@ def _find_matching_event_abi( @staticmethod def get_fallback_function( - abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None + abi: ABI, w3: 'Web3', address: Optional[ChecksumAddress] = None ) -> 'ContractFunction': if abi and fallback_func_abi_exists(abi): return ContractFunction.factory( 'fallback', - web3=web3, + w3=w3, contract_abi=abi, address=address, function_identifier=FallbackFn)() @@ -545,12 +545,12 @@ def get_fallback_function( @staticmethod def get_receive_function( - abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None + abi: ABI, w3: 'Web3', address: Optional[ChecksumAddress] = None ) -> 'ContractFunction': if abi and receive_func_abi_exists(abi): return ContractFunction.factory( 'receive', - web3=web3, + w3=w3, contract_abi=abi, address=address, function_identifier=ReceiveFn)() @@ -571,7 +571,7 @@ def _encode_constructor_data(cls, args: Optional[Any] = None, arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( - encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode) + encode_abi(cls.w3, constructor_abi, arguments, data=cls.bytecode) ) else: if args is not None or kwargs is not None: @@ -596,9 +596,9 @@ class ContractConstructor: Class for contract constructor API. """ def __init__( - self, web3: 'Web3', abi: ABI, bytecode: HexStr, *args: Any, **kwargs: Any + self, w3: 'Web3', abi: ABI, bytecode: HexStr, *args: Any, **kwargs: Any ) -> None: - self.web3 = web3 + self.w3 = w3 self.abi = abi self.bytecode = bytecode self.data_in_transaction = self._encode_data_in_transaction(*args, **kwargs) @@ -615,7 +615,7 @@ def _encode_data_in_transaction(self, *args: Any, **kwargs: Any) -> HexStr: arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) data = add_0x_prefix( - encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode) + encode_abi(self.w3, constructor_abi, arguments, data=self.bytecode) ) else: data = to_hex(self.bytecode) @@ -634,13 +634,13 @@ def estimateGas( self.check_forbidden_keys_in_transaction(estimate_gas_transaction, ["data", "to"]) - if self.web3.eth.default_account is not empty: + if self.w3.eth.default_account is not empty: # type ignored b/c check prevents an empty default_account - estimate_gas_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore # noqa: E501 + estimate_gas_transaction.setdefault('from', self.w3.eth.default_account) # type: ignore # noqa: E501 estimate_gas_transaction['data'] = self.data_in_transaction - return self.web3.eth.estimate_gas( + return self.w3.eth.estimate_gas( estimate_gas_transaction, block_identifier=block_identifier ) @@ -653,14 +653,14 @@ def transact(self, transaction: Optional[TxParams] = None) -> HexBytes: self.check_forbidden_keys_in_transaction(transact_transaction, ["data", "to"]) - if self.web3.eth.default_account is not empty: + if self.w3.eth.default_account is not empty: # type ignored b/c check prevents an empty default_account - transact_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore + transact_transaction.setdefault('from', self.w3.eth.default_account) # type: ignore transact_transaction['data'] = self.data_in_transaction # TODO: handle asynchronous contract creation - return self.web3.eth.send_transaction(transact_transaction) + return self.w3.eth.send_transaction(transact_transaction) @combomethod def buildTransaction(self, transaction: Optional[TxParams] = None) -> TxParams: @@ -675,13 +675,13 @@ def buildTransaction(self, transaction: Optional[TxParams] = None) -> TxParams: self.check_forbidden_keys_in_transaction(built_transaction, ["data", "to"]) - if self.web3.eth.default_account is not empty: + if self.w3.eth.default_account is not empty: # type ignored b/c check prevents an empty default_account - built_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore + built_transaction.setdefault('from', self.w3.eth.default_account) # type: ignore built_transaction['data'] = self.data_in_transaction built_transaction['to'] = Address(b'') - return fill_transaction_defaults(self.web3, built_transaction) + return fill_transaction_defaults(self.w3, built_transaction) @staticmethod def check_forbidden_keys_in_transaction( @@ -787,7 +787,7 @@ def _none_addr(datatype: str, data: ChecksumAddress) -> Tuple[str, Optional[Chec class ImplicitMethod(ConciseMethod): def __call_by_default(self, args: Any) -> bool: function_abi = find_matching_fn_abi(self._function.contract_abi, - self._function.web3.codec, + self._function.w3.codec, fn_identifier=self._function.function_identifier, args=args) @@ -852,7 +852,7 @@ class ContractFunction: """ address: ChecksumAddress = None function_identifier: FunctionIdentifier = None - web3: 'Web3' = None + w3: 'Web3' = None contract_abi: ABI = None abi: ABIFunction = None transaction: TxParams = None @@ -882,7 +882,7 @@ def _set_function_info(self) -> None: if not self.abi: self.abi = find_matching_fn_abi( self.contract_abi, - self.web3.codec, + self.w3.codec, self.function_identifier, self.args, self.kwargs @@ -936,9 +936,9 @@ def call( if self.address: call_transaction.setdefault('to', self.address) - if self.web3.eth.default_account is not empty: + if self.w3.eth.default_account is not empty: # type ignored b/c check prevents an empty default_account - call_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore + call_transaction.setdefault('from', self.w3.eth.default_account) # type: ignore if 'to' not in call_transaction: if isinstance(self, type): @@ -952,10 +952,10 @@ def call( "Please ensure that this contract instance has an address." ) - block_id = parse_block_identifier(self.web3, block_identifier) + block_id = parse_block_identifier(self.w3, block_identifier) return call_contract_function( - self.web3, + self.w3, self.address, self._return_data_normalizers, self.function_identifier, @@ -979,9 +979,9 @@ def transact(self, transaction: Optional[TxParams] = None) -> HexBytes: if self.address is not None: transact_transaction.setdefault('to', self.address) - if self.web3.eth.default_account is not empty: + if self.w3.eth.default_account is not empty: # type ignored b/c check prevents an empty default_account - transact_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore + transact_transaction.setdefault('from', self.w3.eth.default_account) # type: ignore if 'to' not in transact_transaction: if isinstance(self, type): @@ -996,7 +996,7 @@ def transact(self, transaction: Optional[TxParams] = None) -> HexBytes: return transact_with_contract_function( self.address, - self.web3, + self.w3, self.function_identifier, transact_transaction, self.contract_abi, @@ -1021,9 +1021,9 @@ def estimateGas( if self.address: estimate_gas_transaction.setdefault('to', self.address) - if self.web3.eth.default_account is not empty: + if self.w3.eth.default_account is not empty: # type ignored b/c check prevents an empty default_account - estimate_gas_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore # noqa: E501 + estimate_gas_transaction.setdefault('from', self.w3.eth.default_account) # type: ignore # noqa: E501 if 'to' not in estimate_gas_transaction: if isinstance(self, type): @@ -1038,7 +1038,7 @@ def estimateGas( return estimate_gas_for_function( self.address, - self.web3, + self.w3, self.function_identifier, estimate_gas_transaction, self.contract_abi, @@ -1078,7 +1078,7 @@ def buildTransaction(self, transaction: Optional[TxParams] = None) -> TxParams: return build_transaction_for_function( self.address, - self.web3, + self.w3, self.function_identifier, built_transaction, self.contract_abi, @@ -1089,7 +1089,7 @@ def buildTransaction(self, transaction: Optional[TxParams] = None) -> TxParams: @combomethod def _encode_transaction_data(cls) -> HexStr: - return add_0x_prefix(encode_abi(cls.web3, cls.abi, cls.arguments, cls.selector)) + return add_0x_prefix(encode_abi(cls.w3, cls.abi, cls.arguments, cls.selector)) _return_data_normalizers: Optional[Tuple[Callable[..., Any], ...]] = tuple() @@ -1114,7 +1114,7 @@ class ContractEvent: """ address: ChecksumAddress = None event_name: str = None - web3: 'Web3' = None + w3: 'Web3' = None contract_abi: ABI = None abi: ABIEvent = None @@ -1151,7 +1151,7 @@ def _parse_logs( for log in txn_receipt['logs']: try: - rich_log = get_event_data(self.web3.codec, self.abi, log) + rich_log = get_event_data(self.w3.codec, self.abi, log) except (MismatchedABI, LogTopicError, InvalidEventABI, TypeError) as e: if errors == DISCARD: continue @@ -1173,7 +1173,7 @@ def _parse_logs( @combomethod def processLog(self, log: HexStr) -> EventData: - return get_event_data(self.web3.codec, self.abi, log) + return get_event_data(self.w3.codec, self.abi, log) @combomethod def createFilter( @@ -1201,7 +1201,7 @@ def createFilter( _, event_filter_params = construct_event_filter_params( self._get_event_abi(), - self.web3.codec, + self.w3.codec, contract_address=self.address, argument_filters=_filters, fromBlock=fromBlock, @@ -1210,7 +1210,7 @@ def createFilter( topics=topics, ) - filter_builder = EventFilterBuilder(event_abi, self.web3.codec) + filter_builder = EventFilterBuilder(event_abi, self.w3.codec) filter_builder.address = cast(ChecksumAddress, event_filter_params.get('address')) filter_builder.fromBlock = event_filter_params.get('fromBlock') filter_builder.toBlock = event_filter_params.get('toBlock') @@ -1228,8 +1228,8 @@ def createFilter( for arg, value in match_single_vals.items(): filter_builder.args[arg].match_single(value) - log_filter = filter_builder.deploy(self.web3) - log_filter.log_entry_formatter = get_event_data(self.web3.codec, self._get_event_abi()) + log_filter = filter_builder.deploy(self.w3) + log_filter.log_entry_formatter = get_event_data(self.w3.codec, self._get_event_abi()) log_filter.builder = filter_builder return log_filter @@ -1238,8 +1238,8 @@ def createFilter( def build_filter(self) -> EventFilterBuilder: builder = EventFilterBuilder( self._get_event_abi(), - self.web3.codec, - formatter=get_event_data(self.web3.codec, self._get_event_abi())) + self.w3.codec, + formatter=get_event_data(self.w3.codec, self._get_event_abi())) builder.address = self.address return builder @@ -1326,7 +1326,7 @@ def getLogs(self, # Namely, convert event names to their keccak signatures data_filter_set, event_filter_params = construct_event_filter_params( abi, - self.web3.codec, + self.w3.codec, contract_address=self.address, argument_filters=_filters, fromBlock=fromBlock, @@ -1338,10 +1338,10 @@ def getLogs(self, event_filter_params['blockHash'] = blockHash # Call JSON-RPC API - logs = self.web3.eth.get_logs(event_filter_params) + logs = self.w3.eth.get_logs(event_filter_params) # Convert raw binary data to Python proxy objects as described by ABI - return tuple(get_event_data(self.web3.codec, abi, entry) for entry in logs) + return tuple(get_event_data(self.w3.codec, abi, entry) for entry in logs) @classmethod def factory(cls, class_name: str, **kwargs: Any) -> PropertyCheckingFactory: @@ -1372,11 +1372,11 @@ class ContractCaller: """ def __init__(self, abi: ABI, - web3: 'Web3', + w3: 'Web3', address: ChecksumAddress, transaction: Optional[TxParams] = None, block_identifier: BlockIdentifier = 'latest') -> None: - self.web3 = web3 + self.w3 = w3 self.address = address self.abi = abi self._functions = None @@ -1389,12 +1389,12 @@ def __init__(self, for func in self._functions: fn: ContractFunction = ContractFunction.factory( func['name'], - web3=self.web3, + w3=self.w3, contract_abi=self.abi, address=self.address, function_identifier=func['name']) - block_id = parse_block_identifier(self.web3, block_identifier) + block_id = parse_block_identifier(self.w3, block_identifier) caller_method = partial(self.call_function, fn, transaction=transaction, @@ -1435,7 +1435,7 @@ def __call__( if transaction is None: transaction = {} return type(self)(self.abi, - self.web3, + self.w3, self.address, transaction=transaction, block_identifier=block_identifier) @@ -1472,7 +1472,7 @@ def check_for_forbidden_api_filter_arguments( def call_contract_function( - web3: 'Web3', + w3: 'Web3', address: ChecksumAddress, normalizers: Tuple[Callable[..., Any], ...], function_identifier: FunctionIdentifier, @@ -1489,7 +1489,7 @@ def call_contract_function( """ call_transaction = prepare_transaction( address, - web3, + w3, fn_identifier=function_identifier, contract_abi=contract_abi, fn_abi=fn_abi, @@ -1498,25 +1498,25 @@ def call_contract_function( fn_kwargs=kwargs, ) - return_data = web3.eth.call( + return_data = w3.eth.call( call_transaction, block_identifier=block_id, state_override=state_override, ) if fn_abi is None: - fn_abi = find_matching_fn_abi(contract_abi, web3.codec, function_identifier, args, kwargs) + fn_abi = find_matching_fn_abi(contract_abi, w3.codec, function_identifier, args, kwargs) output_types = get_abi_output_types(fn_abi) try: - output_data = web3.codec.decode_abi(output_types, return_data) + output_data = w3.codec.decode_abi(output_types, return_data) except DecodingError as e: # Provide a more helpful error message than the one provided by # eth-abi-utils is_missing_code_error = ( return_data in ACCEPTABLE_EMPTY_STRINGS - and web3.eth.get_code(address) in ACCEPTABLE_EMPTY_STRINGS) + and w3.eth.get_code(address) in ACCEPTABLE_EMPTY_STRINGS) if is_missing_code_error: msg = ( "Could not transact with/call contract function, is contract " @@ -1541,22 +1541,22 @@ def call_contract_function( return normalized_data -def parse_block_identifier(web3: 'Web3', block_identifier: BlockIdentifier) -> BlockIdentifier: +def parse_block_identifier(w3: 'Web3', block_identifier: BlockIdentifier) -> BlockIdentifier: if isinstance(block_identifier, int): - return parse_block_identifier_int(web3, block_identifier) + return parse_block_identifier_int(w3, block_identifier) elif block_identifier in ['latest', 'earliest', 'pending']: return block_identifier elif isinstance(block_identifier, bytes) or is_hex_encoded_block_hash(block_identifier): - return web3.eth.get_block(block_identifier)['number'] + return w3.eth.get_block(block_identifier)['number'] else: raise BlockNumberOutofRange -def parse_block_identifier_int(web3: 'Web3', block_identifier_int: int) -> BlockNumber: +def parse_block_identifier_int(w3: 'Web3', block_identifier_int: int) -> BlockNumber: if block_identifier_int >= 0: block_num = block_identifier_int else: - last_block = web3.eth.get_block('latest')['number'] + last_block = w3.eth.get_block('latest')['number'] block_num = last_block + block_identifier_int + 1 if block_num < 0: raise BlockNumberOutofRange @@ -1565,7 +1565,7 @@ def parse_block_identifier_int(web3: 'Web3', block_identifier_int: int) -> Block def transact_with_contract_function( address: ChecksumAddress, - web3: 'Web3', + w3: 'Web3', function_name: Optional[FunctionIdentifier] = None, transaction: Optional[TxParams] = None, contract_abi: Optional[ABI] = None, @@ -1578,7 +1578,7 @@ def transact_with_contract_function( """ transact_transaction = prepare_transaction( address, - web3, + w3, fn_identifier=function_name, contract_abi=contract_abi, transaction=transaction, @@ -1587,13 +1587,13 @@ def transact_with_contract_function( fn_kwargs=kwargs, ) - txn_hash = web3.eth.send_transaction(transact_transaction) + txn_hash = w3.eth.send_transaction(transact_transaction) return txn_hash def estimate_gas_for_function( address: ChecksumAddress, - web3: 'Web3', + w3: 'Web3', fn_identifier: Optional[FunctionIdentifier] = None, transaction: Optional[TxParams] = None, contract_abi: Optional[ABI] = None, @@ -1608,7 +1608,7 @@ def estimate_gas_for_function( """ estimate_transaction = prepare_transaction( address, - web3, + w3, fn_identifier=fn_identifier, contract_abi=contract_abi, fn_abi=fn_abi, @@ -1617,12 +1617,12 @@ def estimate_gas_for_function( fn_kwargs=kwargs, ) - return web3.eth.estimate_gas(estimate_transaction, block_identifier) + return w3.eth.estimate_gas(estimate_transaction, block_identifier) def build_transaction_for_function( address: ChecksumAddress, - web3: 'Web3', + w3: 'Web3', function_name: Optional[FunctionIdentifier] = None, transaction: Optional[TxParams] = None, contract_abi: Optional[ABI] = None, @@ -1636,7 +1636,7 @@ def build_transaction_for_function( """ prepared_transaction = prepare_transaction( address, - web3, + w3, fn_identifier=function_name, contract_abi=contract_abi, fn_abi=fn_abi, @@ -1645,19 +1645,19 @@ def build_transaction_for_function( fn_kwargs=kwargs, ) - prepared_transaction = fill_transaction_defaults(web3, prepared_transaction) + prepared_transaction = fill_transaction_defaults(w3, prepared_transaction) return prepared_transaction def find_functions_by_identifier( - contract_abi: ABI, web3: 'Web3', address: ChecksumAddress, callable_check: Callable[..., Any] + contract_abi: ABI, w3: 'Web3', address: ChecksumAddress, callable_check: Callable[..., Any] ) -> List[ContractFunction]: fns_abi = filter_by_type('function', contract_abi) return [ ContractFunction.factory( fn_abi['name'], - web3=web3, + w3=w3, contract_abi=contract_abi, address=address, function_identifier=fn_abi['name'], diff --git a/web3/eth.py b/web3/eth.py index 95473c0bc2..079f6bd1f5 100644 --- a/web3/eth.py +++ b/web3/eth.py @@ -210,7 +210,7 @@ def send_transaction_munger(self, transaction: TxParams) -> Tuple[TxParams]: def _generate_gas_price(self, transaction_params: Optional[TxParams] = None) -> Optional[Wei]: if self.gasPriceStrategy: - return self.gasPriceStrategy(self.web3, transaction_params) + return self.gasPriceStrategy(self.w3, transaction_params) return None def set_gas_price_strategy(self, gas_price_strategy: GasPriceStrategy) -> None: @@ -804,8 +804,8 @@ def replaceTransaction(self, transaction_hash: _Hash32, new_transaction: TxParam return self.replace_transaction(transaction_hash, new_transaction) def replace_transaction(self, transaction_hash: _Hash32, new_transaction: TxParams) -> HexBytes: - current_transaction = get_required_transaction(self.web3, transaction_hash) - return replace_transaction(self.web3, current_transaction, new_transaction) + current_transaction = get_required_transaction(self.w3, transaction_hash) + return replace_transaction(self.w3, current_transaction, new_transaction) # todo: Update Any to stricter kwarg checking with TxParams # https://github.com/python/mypy/issues/4441 @@ -819,10 +819,10 @@ def modify_transaction( self, transaction_hash: _Hash32, **transaction_params: Any ) -> HexBytes: assert_valid_transaction_params(cast(TxParams, transaction_params)) - current_transaction = get_required_transaction(self.web3, transaction_hash) + current_transaction = get_required_transaction(self.w3, transaction_hash) current_transaction_params = extract_valid_transaction_params(current_transaction) new_transaction = merge(current_transaction_params, transaction_params) - return replace_transaction(self.web3, current_transaction, new_transaction) + return replace_transaction(self.w3, current_transaction, new_transaction) def send_transaction(self, transaction: TxParams) -> HexBytes: return self._send_transaction(transaction) @@ -952,7 +952,7 @@ def contract( # noqa: F811 ) -> Union[Type[Contract], Contract]: ContractFactoryClass = kwargs.pop('ContractFactoryClass', self.defaultContractFactory) - ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs) + ContractFactory = ContractFactoryClass.factory(self.w3, **kwargs) if address: return ContractFactory(address) diff --git a/web3/gas_strategies/rpc.py b/web3/gas_strategies/rpc.py index 272c90ebe8..aea969daae 100644 --- a/web3/gas_strategies/rpc.py +++ b/web3/gas_strategies/rpc.py @@ -12,9 +12,9 @@ ) -def rpc_gas_price_strategy(web3: Web3, +def rpc_gas_price_strategy(w3: Web3, transaction_params: Optional[TxParams] = None) -> Wei: """ A simple gas price strategy deriving it's value from the eth_gasPrice JSON-RPC call. """ - return web3.manager.request_blocking(RPC.eth_gasPrice, []) + return w3.manager.request_blocking(RPC.eth_gasPrice, []) diff --git a/web3/gas_strategies/time_based.py b/web3/gas_strategies/time_based.py index 34af8e6cde..042f58a88d 100644 --- a/web3/gas_strategies/time_based.py +++ b/web3/gas_strategies/time_based.py @@ -201,14 +201,14 @@ def construct_time_based_gas_price_strategy( and 100 means 100%. """ - def time_based_gas_price_strategy(web3: Web3, transaction_params: TxParams) -> Wei: + def time_based_gas_price_strategy(w3: Web3, transaction_params: TxParams) -> Wei: if weighted: - avg_block_time = _get_weighted_avg_block_time(web3, sample_size=sample_size) + avg_block_time = _get_weighted_avg_block_time(w3, sample_size=sample_size) else: - avg_block_time = _get_avg_block_time(web3, sample_size=sample_size) + avg_block_time = _get_avg_block_time(w3, sample_size=sample_size) wait_blocks = int(math.ceil(max_wait_seconds / avg_block_time)) - raw_miner_data = _get_raw_miner_data(web3, sample_size=sample_size) + raw_miner_data = _get_raw_miner_data(w3, sample_size=sample_size) miner_data = _aggregate_miner_data(raw_miner_data) probabilities = _compute_probabilities( diff --git a/web3/manager.py b/web3/manager.py index 1cd4e1c241..1594c4dd6f 100644 --- a/web3/manager.py +++ b/web3/manager.py @@ -90,15 +90,15 @@ class RequestManager: def __init__( self, - web3: 'Web3', + w3: 'Web3', provider: Optional[BaseProvider] = None, middlewares: Optional[Sequence[Tuple[Middleware, str]]] = None ) -> None: - self.web3 = web3 + self.w3 = w3 self.pending_requests: Dict[UUID, ThreadWithReturn[RPCResponse]] = {} if middlewares is None: - middlewares = self.default_middlewares(web3) + middlewares = self.default_middlewares(w3) self.middleware_onion: MiddlewareOnion = NamedElementOnion(middlewares) @@ -107,7 +107,7 @@ def __init__( else: self.provider = provider - web3: 'Web3' = None + w3: 'Web3' = None _provider = None @property @@ -120,7 +120,7 @@ def provider(self, provider: BaseProvider) -> None: @staticmethod def default_middlewares( - web3: 'Web3' + w3: 'Web3' ) -> List[Tuple[Middleware, str]]: """ List the default middlewares for the request manager. @@ -129,7 +129,7 @@ def default_middlewares( return [ (request_parameter_normalizer, 'request_param_normalizer'), # Delete (gas_price_strategy_middleware, 'gas_price_strategy'), - (name_to_address_middleware(web3), 'name_to_address'), # Add Async + (name_to_address_middleware(w3), 'name_to_address'), # Add Async (attrdict_middleware, 'attrdict'), # Delete (pythonic_middleware, 'pythonic'), # Delete (validation_middleware, 'validation'), @@ -144,7 +144,7 @@ def _make_request( self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any ) -> RPCResponse: request_func = self.provider.request_func( - self.web3, + self.w3, self.middleware_onion) self.logger.debug("Making request. Method: %s", method) return request_func(method, params) @@ -154,7 +154,7 @@ async def _coro_make_request( ) -> RPCResponse: # type ignored b/c request_func is an awaitable in async model request_func = await self.provider.request_func( # type: ignore - self.web3, + self.w3, self.middleware_onion) self.logger.debug("Making request. Method: %s", method) return await request_func(method, params) diff --git a/web3/method.py b/web3/method.py index 78f68a68e3..4f08807e40 100644 --- a/web3/method.py +++ b/web3/method.py @@ -123,7 +123,7 @@ def __init__( error_formatters: Optional[Callable[..., TReturn]] = None, null_result_formatters: Optional[Callable[..., TReturn]] = None, method_choice_depends_on_args: Optional[Callable[..., RPCEndpoint]] = None, - web3: Optional["Web3"] = None): + w3: Optional["Web3"] = None): self.json_rpc_method = json_rpc_method self.mungers = mungers or [default_munger] diff --git a/web3/middleware/__init__.py b/web3/middleware/__init__.py index ea2f00c6ed..7ca174697c 100644 --- a/web3/middleware/__init__.py +++ b/web3/middleware/__init__.py @@ -80,7 +80,7 @@ def combine_middlewares( middlewares: Sequence[Middleware], - web3: 'Web3', + w3: 'Web3', provider_request_fn: Callable[[RPCEndpoint, Any], Any] ) -> Callable[..., RPCResponse]: """ @@ -88,7 +88,7 @@ def combine_middlewares( function wrapped with all of the middlewares. """ return functools.reduce( - lambda request_fn, middleware: middleware(request_fn, web3), + lambda request_fn, middleware: middleware(request_fn, w3), reversed(middlewares), provider_request_fn, ) @@ -96,7 +96,7 @@ def combine_middlewares( async def async_combine_middlewares( middlewares: Sequence[Middleware], - web3: 'Web3', + w3: 'Web3', provider_request_fn: Callable[[RPCEndpoint, Any], Any] ) -> Callable[..., RPCResponse]: """ @@ -105,7 +105,7 @@ async def async_combine_middlewares( """ accumulator_fn = provider_request_fn for middleware in reversed(middlewares): - accumulator_fn = await construct_middleware(middleware, accumulator_fn, web3) + accumulator_fn = await construct_middleware(middleware, accumulator_fn, w3) return accumulator_fn diff --git a/web3/middleware/attrdict.py b/web3/middleware/attrdict.py index 14f33e1bf1..16643ae4ac 100644 --- a/web3/middleware/attrdict.py +++ b/web3/middleware/attrdict.py @@ -24,7 +24,7 @@ def attrdict_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: """ Converts any result which is a dictionary into an a diff --git a/web3/middleware/buffered_gas_estimate.py b/web3/middleware/buffered_gas_estimate.py index 194c4178e1..faa8baa0a7 100644 --- a/web3/middleware/buffered_gas_estimate.py +++ b/web3/middleware/buffered_gas_estimate.py @@ -25,7 +25,7 @@ def buffered_gas_estimate_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if method == 'eth_sendTransaction': @@ -34,7 +34,7 @@ def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: transaction = assoc( transaction, 'gas', - hex(get_buffered_gas_estimate(web3, transaction)), + hex(get_buffered_gas_estimate(w3, transaction)), ) return make_request(method, [transaction]) return make_request(method, params) @@ -42,13 +42,13 @@ def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: async def async_buffered_gas_estimate_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> AsyncMiddleware: async def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if method == 'eth_sendTransaction': transaction = params[0] if 'gas' not in transaction: - gas_estimate = await async_get_buffered_gas_estimate(web3, transaction) + gas_estimate = await async_get_buffered_gas_estimate(w3, transaction) transaction = assoc( transaction, 'gas', diff --git a/web3/middleware/cache.py b/web3/middleware/cache.py index e81761b0a3..c0635daf97 100644 --- a/web3/middleware/cache.py +++ b/web3/middleware/cache.py @@ -112,7 +112,7 @@ def construct_simple_cache_middleware( cached. """ def simple_cache_middleware( - make_request: Callable[[RPCEndpoint, Any], RPCResponse], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], RPCResponse], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: cache = cache_class() lock = threading.Lock() @@ -216,7 +216,7 @@ def construct_time_based_cache_middleware( cached. """ def time_based_cache_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: cache = cache_class() lock = threading.Lock() @@ -356,7 +356,7 @@ def construct_latest_block_based_cache_middleware( block time. """ def latest_block_based_cache_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: cache = cache_class() block_info: BlockInfoCache = {} @@ -379,12 +379,12 @@ def _update_block_info_cache() -> None: # measured by blocks is greater than or equal to the number of # blocks sampled then we need to recompute the average block # time. - latest_block = web3.eth.get_block('latest') + latest_block = w3.eth.get_block('latest') ancestor_block_number = BlockNumber(max( 0, latest_block['number'] - average_block_time_sample_size, )) - ancestor_block = web3.eth.get_block(ancestor_block_number) + ancestor_block = w3.eth.get_block(ancestor_block_number) sample_size = latest_block['number'] - ancestor_block_number block_info[AVG_BLOCK_SAMPLE_SIZE_KEY] = sample_size @@ -402,10 +402,10 @@ def _update_block_info_cache() -> None: # latest block is too old so update cache if time_since_latest_block > avg_block_time: - block_info['latest_block'] = web3.eth.get_block('latest') + block_info['latest_block'] = w3.eth.get_block('latest') else: # latest block has not been fetched so we fetch it. - block_info['latest_block'] = web3.eth.get_block('latest') + block_info['latest_block'] = w3.eth.get_block('latest') lock = threading.Lock() diff --git a/web3/middleware/exception_handling.py b/web3/middleware/exception_handling.py index a74cc19694..c2781456a9 100644 --- a/web3/middleware/exception_handling.py +++ b/web3/middleware/exception_handling.py @@ -30,7 +30,7 @@ def construct_exception_handler_middleware( method_handlers = {} def exception_handler_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if method in method_handlers: diff --git a/web3/middleware/exception_retry_request.py b/web3/middleware/exception_retry_request.py index 3289189d5a..48514ef44c 100644 --- a/web3/middleware/exception_retry_request.py +++ b/web3/middleware/exception_retry_request.py @@ -90,7 +90,7 @@ def check_if_retry_on_failure(method: RPCEndpoint) -> bool: def exception_retry_middleware( make_request: Callable[[RPCEndpoint, Any], RPCResponse], - web3: "Web3", + w3: "Web3", errors: Collection[Type[BaseException]], retries: int = 5, ) -> Callable[[RPCEndpoint, Any], RPCResponse]: @@ -116,10 +116,10 @@ def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: def http_retry_request_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], Any]: return exception_retry_middleware( make_request, - web3, + w3, (ConnectionError, HTTPError, Timeout, TooManyRedirects) ) diff --git a/web3/middleware/gas_price_strategy.py b/web3/middleware/gas_price_strategy.py index 9d3fcacc6d..c336956d64 100644 --- a/web3/middleware/gas_price_strategy.py +++ b/web3/middleware/gas_price_strategy.py @@ -70,7 +70,7 @@ def validate_transaction_params( def gas_price_strategy_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: """ - Uses a gas price strategy if one is set. This is only supported for legacy transactions. @@ -81,8 +81,8 @@ def gas_price_strategy_middleware( def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if method == 'eth_sendTransaction': transaction = params[0] - generated_gas_price = web3.eth.generate_gas_price(transaction) - latest_block = web3.eth.get_block('latest') + generated_gas_price = w3.eth.generate_gas_price(transaction) + latest_block = w3.eth.get_block('latest') transaction = validate_transaction_params( transaction, latest_block, generated_gas_price ) @@ -93,7 +93,7 @@ def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: async def async_gas_price_strategy_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> AsyncMiddleware: """ - Uses a gas price strategy if one is set. This is only supported for legacy transactions. @@ -104,8 +104,8 @@ async def async_gas_price_strategy_middleware( async def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if method == 'eth_sendTransaction': transaction = params[0] - generated_gas_price = await web3.eth.generate_gas_price(transaction) # type: ignore - latest_block = await web3.eth.get_block('latest') # type: ignore + generated_gas_price = await w3.eth.generate_gas_price(transaction) # type: ignore + latest_block = await w3.eth.get_block('latest') # type: ignore transaction = validate_transaction_params( transaction, latest_block, generated_gas_price ) diff --git a/web3/middleware/geth_poa.py b/web3/middleware/geth_poa.py index 6048cc70f0..5f2f74a135 100644 --- a/web3/middleware/geth_poa.py +++ b/web3/middleware/geth_poa.py @@ -55,7 +55,7 @@ async def async_geth_poa_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> AsyncMiddleware: middleware = await async_construct_formatting_middleware( result_formatters={ @@ -63,4 +63,4 @@ async def async_geth_poa_middleware( RPC.eth_getBlockByNumber: apply_formatter_if(is_not_null, geth_poa_cleanup), }, ) - return await middleware(make_request, web3) + return await middleware(make_request, w3) diff --git a/web3/middleware/simulate_unmined_transaction.py b/web3/middleware/simulate_unmined_transaction.py index e36300c9ff..9e74b20c06 100644 --- a/web3/middleware/simulate_unmined_transaction.py +++ b/web3/middleware/simulate_unmined_transaction.py @@ -22,7 +22,7 @@ def unmined_receipt_simulator_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: Web3 + make_request: Callable[[RPCEndpoint, Any], Any], w3: Web3 ) -> Callable[[RPCEndpoint, Any], RPCResponse]: receipt_counters: DefaultDict[Hash32, TxReceipt] = collections.defaultdict( # type: ignore # noqa: F821, E501 itertools.count diff --git a/web3/middleware/stalecheck.py b/web3/middleware/stalecheck.py index 7b244653f9..73e8158770 100644 --- a/web3/middleware/stalecheck.py +++ b/web3/middleware/stalecheck.py @@ -50,7 +50,7 @@ def make_stalecheck_middleware( raise ValueError("You must set a positive allowable_delay in seconds for this middleware") def stalecheck_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: cache: Dict[str, BlockData] = {'latest': None} @@ -59,7 +59,7 @@ def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if _isfresh(cache['latest'], allowable_delay): pass else: - latest = web3.eth.get_block('latest') + latest = w3.eth.get_block('latest') if _isfresh(latest, allowable_delay): cache['latest'] = latest else: diff --git a/web3/middleware/validation.py b/web3/middleware/validation.py index 44d79825de..5fafce175b 100644 --- a/web3/middleware/validation.py +++ b/web3/middleware/validation.py @@ -164,9 +164,9 @@ async def async_build_method_validators(async_w3: "Web3", method: RPCEndpoint) - async def async_validation_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> AsyncMiddleware: middleware = await async_construct_web3_formatting_middleware( async_build_method_validators ) - return await middleware(make_request, web3) + return await middleware(make_request, w3) diff --git a/web3/module.py b/web3/module.py index c0dc6edb24..49fdfb9209 100644 --- a/web3/module.py +++ b/web3/module.py @@ -84,10 +84,10 @@ async def caller(*args: Any, **kwargs: Any) -> RPCResponse: class Module: is_async = False - def __init__(self, web3: "Web3") -> None: + def __init__(self, w3: "Web3") -> None: if self.is_async: - self.retrieve_caller_fn = retrieve_async_method_call_fn(web3, self) + self.retrieve_caller_fn = retrieve_async_method_call_fn(w3, self) else: - self.retrieve_caller_fn = retrieve_blocking_method_call_fn(web3, self) - self.web3 = web3 - self.codec: ABICodec = web3.codec + self.retrieve_caller_fn = retrieve_blocking_method_call_fn(w3, self) + self.w3 = w3 + self.codec: ABICodec = w3.codec diff --git a/web3/parity.py b/web3/parity.py index 2c32c3b96f..84bcaa5c44 100644 --- a/web3/parity.py +++ b/web3/parity.py @@ -186,8 +186,8 @@ def trace_call_munger( block_identifier: Optional[BlockIdentifier] = None ) -> Tuple[TxParams, ParityTraceMode, BlockIdentifier]: # TODO: move to middleware - if 'from' not in transaction and is_checksum_address(self.web3.eth.default_account): - transaction = assoc(transaction, 'from', self.web3.eth.default_account) + if 'from' not in transaction and is_checksum_address(self.w3.eth.default_account): + transaction = assoc(transaction, 'from', self.w3.eth.default_account) # TODO: move to middleware if block_identifier is None: diff --git a/web3/pm.py b/web3/pm.py index 2646dc4b9b..be32db5eb1 100644 --- a/web3/pm.py +++ b/web3/pm.py @@ -327,7 +327,7 @@ def get_package_from_manifest(self, manifest: Manifest) -> Package: * Parameters: * ``manifest``: A dict representing a valid manifest """ - return Package(manifest, self.web3) + return Package(manifest, self.w3) def get_package_from_uri(self, manifest_uri: URI) -> Package: """ @@ -339,7 +339,7 @@ def get_package_from_uri(self, manifest_uri: URI) -> Package: * Parameters: * ``uri``: Must be a valid content-addressed URI """ - return Package.from_uri(manifest_uri, self.web3) + return Package.from_uri(manifest_uri, self.w3) def get_local_package(self, package_name: str, ethpm_dir: Path = None) -> Package: """ @@ -381,17 +381,17 @@ def set_registry(self, address: Union[Address, ChecksumAddress, ENS]) -> None: """ if is_canonical_address(address): addr_string = to_text(address) - self.registry = SimpleRegistry(to_checksum_address(addr_string), self.web3) + self.registry = SimpleRegistry(to_checksum_address(addr_string), self.w3) elif is_checksum_address(address): - self.registry = SimpleRegistry(cast(ChecksumAddress, address), self.web3) + self.registry = SimpleRegistry(cast(ChecksumAddress, address), self.w3) elif is_ens_name(address): self._validate_set_ens() - addr_lookup = self.web3.ens.address(str(address)) + addr_lookup = self.w3.ens.address(str(address)) if not addr_lookup: raise NameNotFound( f"No address found after ENS lookup for name: {address!r}." ) - self.registry = SimpleRegistry(addr_lookup, self.web3) + self.registry = SimpleRegistry(addr_lookup, self.w3) else: raise PMError( "Expected a canonical/checksummed address or ENS name for the address, " @@ -409,7 +409,7 @@ def deploy_and_set_registry(self) -> ChecksumAddress: w3.ens.setup_address(ens_name, w3.pm.registry.address) """ - self.registry = SimpleRegistry.deploy_new_instance(self.web3) + self.registry = SimpleRegistry.deploy_new_instance(self.w3) return to_checksum_address(self.registry.address) def release_package( @@ -554,11 +554,11 @@ def _validate_set_registry(self) -> None: ) def _validate_set_ens(self) -> None: - if not self.web3: + if not self.w3: raise InvalidAddress( "Could not look up ENS address because no web3 " "connection available" ) - elif not self.web3.ens: + elif not self.w3.ens: raise InvalidAddress( "Could not look up ENS address because web3.ens is " "set to None" ) diff --git a/web3/providers/async_base.py b/web3/providers/async_base.py index 1d446389b7..6f2fa551ab 100644 --- a/web3/providers/async_base.py +++ b/web3/providers/async_base.py @@ -53,7 +53,7 @@ def middlewares( self._middlewares = tuple(values) # type: ignore async def request_func( - self, web3: "Web3", outer_middlewares: MiddlewareOnion + self, w3: "Web3", outer_middlewares: MiddlewareOnion ) -> Callable[[RPCEndpoint], Any]: all_middlewares: Tuple[Middleware] = tuple(outer_middlewares) + tuple(self.middlewares) # type: ignore # noqa: E501 @@ -61,16 +61,16 @@ async def request_func( if cache_key is None or cache_key != all_middlewares: self._request_func_cache = ( all_middlewares, - await self._generate_request_func(web3, all_middlewares) + await self._generate_request_func(w3, all_middlewares) ) return self._request_func_cache[-1] async def _generate_request_func( - self, web3: "Web3", middlewares: Sequence[Middleware] + self, w3: "Web3", middlewares: Sequence[Middleware] ) -> Callable[..., RPCResponse]: return await async_combine_middlewares( middlewares=middlewares, - web3=web3, + w3=w3, provider_request_fn=self.make_request, ) diff --git a/web3/providers/base.py b/web3/providers/base.py index 4f426934d5..51f4ba123c 100644 --- a/web3/providers/base.py +++ b/web3/providers/base.py @@ -47,7 +47,7 @@ def middlewares( self._middlewares = tuple(values) # type: ignore def request_func( - self, web3: "Web3", outer_middlewares: MiddlewareOnion + self, w3: "Web3", outer_middlewares: MiddlewareOnion ) -> Callable[..., RPCResponse]: """ @param outer_middlewares is an iterable of middlewares, ordered by first to execute @@ -60,16 +60,16 @@ def request_func( if cache_key is None or cache_key != all_middlewares: self._request_func_cache = ( all_middlewares, - self._generate_request_func(web3, all_middlewares) + self._generate_request_func(w3, all_middlewares) ) return self._request_func_cache[-1] def _generate_request_func( - self, web3: "Web3", middlewares: Sequence[Middleware] + self, w3: "Web3", middlewares: Sequence[Middleware] ) -> Callable[..., RPCResponse]: return combine_middlewares( middlewares=middlewares, - web3=web3, + w3=w3, provider_request_fn=self.make_request, ) diff --git a/web3/providers/eth_tester/middleware.py b/web3/providers/eth_tester/middleware.py index fb865d8aab..18fbd42965 100644 --- a/web3/providers/eth_tester/middleware.py +++ b/web3/providers/eth_tester/middleware.py @@ -287,13 +287,13 @@ def is_hexstr(value: Any) -> bool: ) -def guess_from(web3: "Web3", _: TxParams) -> ChecksumAddress: - coinbase = web3.eth.coinbase +def guess_from(w3: "Web3", _: TxParams) -> ChecksumAddress: + coinbase = w3.eth.coinbase if coinbase is not None: return coinbase try: - return web3.eth.accounts[0] + return w3.eth.accounts[0] except KeyError: # no accounts available to pre-fill, carry on pass @@ -303,20 +303,20 @@ def guess_from(web3: "Web3", _: TxParams) -> ChecksumAddress: @curry def fill_default( - field: str, guess_func: Callable[..., Any], web3: "Web3", transaction: TxParams + field: str, guess_func: Callable[..., Any], w3: "Web3", transaction: TxParams ) -> TxParams: # type ignored b/c TxParams keys must be string literal types if field in transaction and transaction[field] is not None: # type: ignore return transaction else: - guess_val = guess_func(web3, transaction) + guess_val = guess_func(w3, transaction) return assoc(transaction, field, guess_val) def default_transaction_fields_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], web3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: - fill_default_from = fill_default('from', guess_from, web3) + fill_default_from = fill_default('from', guess_from, w3) def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if method in ( diff --git a/web3/testing.py b/web3/testing.py index 4537df8c80..f421c83a22 100644 --- a/web3/testing.py +++ b/web3/testing.py @@ -12,21 +12,21 @@ class Testing(Module): def timeTravel(self, timestamp: int) -> None: - return self.web3.manager.request_blocking(RPC.testing_timeTravel, [timestamp]) + return self.w3.manager.request_blocking(RPC.testing_timeTravel, [timestamp]) def mine(self, num_blocks: int = 1) -> None: - return self.web3.manager.request_blocking(RPC.evm_mine, [num_blocks]) + return self.w3.manager.request_blocking(RPC.evm_mine, [num_blocks]) def snapshot(self) -> int: - self.last_snapshot_idx = self.web3.manager.request_blocking(RPC.evm_snapshot, []) + self.last_snapshot_idx = self.w3.manager.request_blocking(RPC.evm_snapshot, []) return self.last_snapshot_idx def reset(self) -> None: - return self.web3.manager.request_blocking(RPC.evm_reset, []) + return self.w3.manager.request_blocking(RPC.evm_reset, []) def revert(self, snapshot_idx: Optional[int] = None) -> None: if snapshot_idx is None: revert_target = self.last_snapshot_idx else: revert_target = snapshot_idx - return self.web3.manager.request_blocking(RPC.evm_revert, [revert_target]) + return self.w3.manager.request_blocking(RPC.evm_revert, [revert_target]) diff --git a/web3/tools/benchmark/main.py b/web3/tools/benchmark/main.py index 7146974e0e..efef6d8189 100644 --- a/web3/tools/benchmark/main.py +++ b/web3/tools/benchmark/main.py @@ -63,21 +63,21 @@ def build_web3_http(endpoint_uri: str) -> Web3: wait_for_http(endpoint_uri) - _web3 = Web3( + _w3 = Web3( HTTPProvider(endpoint_uri), middlewares=[gas_price_strategy_middleware, buffered_gas_estimate_middleware] ) - return _web3 + return _w3 async def build_async_w3_http(endpoint_uri: str) -> Web3: await wait_for_aiohttp(endpoint_uri) - _web3 = Web3( + _w3 = Web3( AsyncHTTPProvider(endpoint_uri), # type: ignore middlewares=[async_gas_price_strategy_middleware, async_buffered_gas_estimate_middleware], modules={"eth": AsyncEth}, ) - return _web3 + return _w3 def sync_benchmark(func: Callable[..., Any], n: int) -> Union[float, str]: From b38b1e30ec3bd119904629934efd7d4af3e0d4ac Mon Sep 17 00:00:00 2001 From: Felipe Selmo Date: Wed, 23 Feb 2022 14:54:12 -0700 Subject: [PATCH 2/2] Remove unnecessary w3 arguments to tests while reviewing PR #2357 --- .../contracts/test_contract_call_interface.py | 8 +++---- .../contracts/test_extracting_event_data.py | 7 ------ .../core/contracts/test_implicit_contract.py | 2 +- ...est_contract_createFilter_topic_merging.py | 6 +---- .../test_contract_on_event_filtering.py | 2 +- tests/core/manager/conftest.py | 2 +- .../test_middleware_can_be_stateful.py | 2 +- .../core/mining-module/test_miner_hashrate.py | 6 ++--- tests/core/mining-module/test_miner_start.py | 24 +++++++++---------- tests/core/mining-module/test_miner_stop.py | 16 ++++++------- tests/core/utilities/test_attach_modules.py | 2 +- tests/integration/go_ethereum/conftest.py | 8 +++---- tests/integration/test_ethereum_tester.py | 2 +- web3/_utils/transactions.py | 2 +- 14 files changed, 39 insertions(+), 50 deletions(-) diff --git a/tests/core/contracts/test_contract_call_interface.py b/tests/core/contracts/test_contract_call_interface.py index 218e558894..6b1c1809b8 100644 --- a/tests/core/contracts/test_contract_call_interface.py +++ b/tests/core/contracts/test_contract_call_interface.py @@ -150,7 +150,7 @@ def bytes32_contract(w3, Bytes32Contract, request, address_conversion_func): @pytest.fixture() -def undeployed_math_contract(w3, MathContract, address_conversion_func): +def undeployed_math_contract(MathContract, address_conversion_func): empty_address = address_conversion_func("0x000000000000000000000000000000000000dEaD") _undeployed_math_contract = MathContract(address=empty_address) return _undeployed_math_contract @@ -191,7 +191,7 @@ def nested_tuple_contract(w3, NestedTupleContract, address_conversion_func): return deploy(w3, NestedTupleContract, address_conversion_func) -def test_invalid_address_in_deploy_arg(w3, WithConstructorAddressArgumentsContract): +def test_invalid_address_in_deploy_arg(WithConstructorAddressArgumentsContract): with pytest.raises(InvalidAddress): WithConstructorAddressArgumentsContract.constructor( "0xd3cda913deb6f67967b99d67acdfa1712c293601", @@ -704,7 +704,7 @@ def test_call_sending_ether_to_nonpayable_function(payable_tester_contract, call ('reflect_short_u', Decimal('25.5')), ), ) -def test_reflect_fixed_value(w3, fixed_reflection_contract, function, value): +def test_reflect_fixed_value(fixed_reflection_contract, function, value): contract_func = fixed_reflection_contract.functions[function] reflected = contract_func(value).call({'gas': 420000}) assert reflected == value @@ -741,7 +741,7 @@ def test_reflect_fixed_value(w3, fixed_reflection_contract, function, value): ('reflect', 0, "Ambiguous argument encoding"), ), ) -def test_invalid_fixed_value_reflections(w3, fixed_reflection_contract, function, value, error): +def test_invalid_fixed_value_reflections(fixed_reflection_contract, function, value, error): contract_func = fixed_reflection_contract.functions[function] with pytest.raises(ValidationError, match=error): contract_func(value).call({'gas': 420000}) diff --git a/tests/core/contracts/test_extracting_event_data.py b/tests/core/contracts/test_extracting_event_data.py index 42a5744972..1d03a82848 100644 --- a/tests/core/contracts/test_extracting_event_data.py +++ b/tests/core/contracts/test_extracting_event_data.py @@ -662,7 +662,6 @@ def test_event_rich_log_with_byte_args( def test_receipt_processing_with_discard_flag( - w3, event_contract, indexed_event_contract, dup_txn_receipt, @@ -675,7 +674,6 @@ def test_receipt_processing_with_discard_flag( def test_receipt_processing_with_ignore_flag( - w3, event_contract, indexed_event_contract, dup_txn_receipt, @@ -704,7 +702,6 @@ def test_receipt_processing_with_ignore_flag( def test_receipt_processing_with_warn_flag( - w3, indexed_event_contract, dup_txn_receipt): @@ -716,7 +713,6 @@ def test_receipt_processing_with_warn_flag( def test_receipt_processing_with_strict_flag( - w3, indexed_event_contract, dup_txn_receipt): @@ -727,7 +723,6 @@ def test_receipt_processing_with_strict_flag( def test_receipt_processing_with_invalid_flag( - w3, indexed_event_contract, dup_txn_receipt): @@ -738,7 +733,6 @@ def test_receipt_processing_with_invalid_flag( def test_receipt_processing_with_no_flag( - w3, indexed_event_contract, dup_txn_receipt): @@ -750,7 +744,6 @@ def test_receipt_processing_with_no_flag( def test_single_log_processing_with_errors( - w3, indexed_event_contract, dup_txn_receipt): event_instance = indexed_event_contract.events.LogSingleWithIndex() diff --git a/tests/core/contracts/test_implicit_contract.py b/tests/core/contracts/test_implicit_contract.py index 1cc864a38c..c1311fc191 100644 --- a/tests/core/contracts/test_implicit_contract.py +++ b/tests/core/contracts/test_implicit_contract.py @@ -62,7 +62,7 @@ def test_implicitcontract_call_default(math_contract, get_transaction_count): assert get_transaction_count("pending") == (blocknum, 0) -def test_implicitcontract_transact_default(w3, math_contract, get_transaction_count): +def test_implicitcontract_transact_default(math_contract, get_transaction_count): # Use to verify correct operation later on with pytest.warns(DeprecationWarning, match='deprecated in favor of classic contract syntax'): start_count = math_contract.counter() diff --git a/tests/core/filtering/test_contract_createFilter_topic_merging.py b/tests/core/filtering/test_contract_createFilter_topic_merging.py index 2b15532465..711b66c308 100644 --- a/tests/core/filtering/test_contract_createFilter_topic_merging.py +++ b/tests/core/filtering/test_contract_createFilter_topic_merging.py @@ -1,11 +1,7 @@ import pytest -def test_merged_topic_list_event( - w3, - emitter, - emitter_event_ids, - wait_for_transaction): +def test_merged_topic_list_event(emitter): manual_topics = [ '0xf16c999b533366ca5138d78e85da51611089cd05749f098d6c225d4cd42ee6ec', # event sig '0x0000000000000000000000000000000000000000000000000000000000000457', # 1111 diff --git a/tests/core/filtering/test_contract_on_event_filtering.py b/tests/core/filtering/test_contract_on_event_filtering.py index 044bb0eec2..5828ffe49a 100644 --- a/tests/core/filtering/test_contract_on_event_filtering.py +++ b/tests/core/filtering/test_contract_on_event_filtering.py @@ -6,7 +6,7 @@ @pytest.mark.parametrize('call_as_instance', (True, False)) -def test_create_filter_address_parameter(w3, emitter, Emitter, call_as_instance): +def test_create_filter_address_parameter(emitter, Emitter, call_as_instance): if call_as_instance: event_filter = emitter.events.LogNoArguments.createFilter(fromBlock="latest") else: diff --git a/tests/core/manager/conftest.py b/tests/core/manager/conftest.py index 7653961d55..e79989a4a5 100644 --- a/tests/core/manager/conftest.py +++ b/tests/core/manager/conftest.py @@ -15,7 +15,7 @@ class Wrapper: def __repr__(self): return 'middleware-' + key - def __call__(self, make_request, web3): + def __call__(self, make_request, w3): def middleware_fn(method, params): params.append(key) method = "|".join((method, key)) diff --git a/tests/core/manager/test_middleware_can_be_stateful.py b/tests/core/manager/test_middleware_can_be_stateful.py index db652c03a6..4927b56230 100644 --- a/tests/core/manager/test_middleware_can_be_stateful.py +++ b/tests/core/manager/test_middleware_can_be_stateful.py @@ -6,7 +6,7 @@ ) -def stateful_middleware(make_request, web3): +def stateful_middleware(make_request, w3): state = [] def middleware(method, params): diff --git a/tests/core/mining-module/test_miner_hashrate.py b/tests/core/mining-module/test_miner_hashrate.py index d28acfcc72..0c6b16df66 100644 --- a/tests/core/mining-module/test_miner_hashrate.py +++ b/tests/core/mining-module/test_miner_hashrate.py @@ -4,8 +4,8 @@ @flaky(max_runs=3) -def test_miner_hashrate(web3_empty, wait_for_miner_start): - web3 = web3_empty +def test_miner_hashrate(w3_empty, wait_for_miner_start): + w3 = w3_empty - hashrate = web3.eth.hashrate + hashrate = w3.eth.hashrate assert hashrate > 0 diff --git a/tests/core/mining-module/test_miner_start.py b/tests/core/mining-module/test_miner_start.py index 80de7839c4..daa04e6835 100644 --- a/tests/core/mining-module/test_miner_start.py +++ b/tests/core/mining-module/test_miner_start.py @@ -10,25 +10,25 @@ @flaky(max_runs=3) -def test_miner_start(web3_empty, wait_for_miner_start): - web3 = web3_empty +def test_miner_start(w3_empty, wait_for_miner_start): + w3 = w3_empty # sanity - assert web3.eth.mining - assert web3.eth.hashrate + assert w3.eth.mining + assert w3.eth.hashrate - web3.geth.miner.stop() + w3.geth.miner.stop() with Timeout(60) as timeout: - while web3.eth.mining or web3.eth.hashrate: + while w3.eth.mining or w3.eth.hashrate: timeout.sleep(random.random()) - assert not web3.eth.mining - assert not web3.eth.hashrate + assert not w3.eth.mining + assert not w3.eth.hashrate - web3.miner.start(1) + w3.miner.start(1) - wait_for_miner_start(web3) + wait_for_miner_start(w3) - assert web3.eth.mining - assert web3.eth.hashrate + assert w3.eth.mining + assert w3.eth.hashrate diff --git a/tests/core/mining-module/test_miner_stop.py b/tests/core/mining-module/test_miner_stop.py index 60b6633b3f..1e2af7698c 100644 --- a/tests/core/mining-module/test_miner_stop.py +++ b/tests/core/mining-module/test_miner_stop.py @@ -10,18 +10,18 @@ @flaky(max_runs=3) -def test_miner_stop(web3_empty): - web3 = web3_empty +def test_miner_stop(w3_empty): + w3 = w3_empty - assert web3.eth.mining - assert web3.eth.hashrate + assert w3.eth.mining + assert w3.eth.hashrate - web3.geth.miner.stop() + w3.geth.miner.stop() with Timeout(60) as timeout: - while web3.eth.mining or web3.eth.hashrate: + while w3.eth.mining or w3.eth.hashrate: timeout.sleep(random.random()) timeout.check() - assert not web3.eth.mining - assert not web3.eth.hashrate + assert not w3.eth.mining + assert not w3.eth.hashrate diff --git a/tests/core/utilities/test_attach_modules.py b/tests/core/utilities/test_attach_modules.py index bc65b64847..42a3cf820b 100644 --- a/tests/core/utilities/test_attach_modules.py +++ b/tests/core/utilities/test_attach_modules.py @@ -169,7 +169,7 @@ def test_attach_external_modules_that_do_not_inherit_from_module_class( assert is_integer(w3.eth.chain_id) -def test_attach_modules_for_module_with_more_than_one_init_argument(w3, module_many_init_args): +def test_attach_modules_for_module_with_more_than_one_init_argument(module_many_init_args): with pytest.raises( UnsupportedOperation, match=( diff --git a/tests/integration/go_ethereum/conftest.py b/tests/integration/go_ethereum/conftest.py index 06870f95e3..0862c47aa1 100644 --- a/tests/integration/go_ethereum/conftest.py +++ b/tests/integration/go_ethereum/conftest.py @@ -140,7 +140,7 @@ def math_contract_deploy_txn_hash(geth_fixture_data): @pytest.fixture(scope="module") -def math_contract(w3, math_contract_factory, geth_fixture_data): +def math_contract(math_contract_factory, geth_fixture_data): return math_contract_factory(address=geth_fixture_data['math_address']) @@ -150,7 +150,7 @@ def math_contract_address(math_contract, address_conversion_func): @pytest.fixture(scope="module") -def emitter_contract(w3, emitter_contract_factory, geth_fixture_data): +def emitter_contract(emitter_contract_factory, geth_fixture_data): return emitter_contract_factory(address=geth_fixture_data['emitter_address']) @@ -172,7 +172,7 @@ def unlockable_account_pw(geth_fixture_data): @pytest.fixture(scope="module") -def unlockable_account(w3, coinbase): +def unlockable_account(coinbase): yield coinbase @@ -237,5 +237,5 @@ def block_hash_revert_with_msg(geth_fixture_data): @pytest.fixture(scope="module") -def revert_contract(w3, revert_contract_factory, geth_fixture_data): +def revert_contract(revert_contract_factory, geth_fixture_data): return revert_contract_factory(address=geth_fixture_data['revert_address']) diff --git a/tests/integration/test_ethereum_tester.py b/tests/integration/test_ethereum_tester.py index 1e992121a7..c688fa1f14 100644 --- a/tests/integration/test_ethereum_tester.py +++ b/tests/integration/test_ethereum_tester.py @@ -163,7 +163,7 @@ def revert_contract(w3, revert_contract_factory, revert_contract_deploy_txn_hash @pytest.fixture(scope='module') -def unlockable_account_pw(w3): +def unlockable_account_pw(): return 'web3-testing' diff --git a/web3/_utils/transactions.py b/web3/_utils/transactions.py index 6a7d0f2bed..8d9ca470df 100644 --- a/web3/_utils/transactions.py +++ b/web3/_utils/transactions.py @@ -86,7 +86,7 @@ def fill_nonce(w3: "Web3", transaction: TxParams) -> TxParams: @curry def fill_transaction_defaults(w3: "Web3", transaction: TxParams) -> TxParams: """ - if web3 is None, fill as much as possible while offline + if w3 is None, fill as much as possible while offline """ strategy_based_gas_price = w3.eth.generate_gas_price(transaction) is_dynamic_fee_transaction = (