Support for web3.py v6

pull/2960/head
Kieran Prasch 2022-09-07 18:58:03 +02:00
parent 0608608460
commit 0acfc7e381
18 changed files with 89 additions and 87 deletions

View File

@ -238,7 +238,7 @@ class EthereumClient:
return self.w3.eth.accounts
def get_balance(self, account):
return self.w3.eth.getBalance(account)
return self.w3.eth.get_balance(account)
def inject_middleware(self, middleware, **kwargs):
self.w3.middleware_onion.inject(middleware, **kwargs)
@ -247,16 +247,16 @@ class EthereumClient:
self.w3.middleware_onion.add(middleware)
def set_gas_strategy(self, gas_strategy):
self.w3.eth.setGasPriceStrategy(gas_strategy)
self.w3.eth.set_gas_price_strategy(gas_strategy)
@property
def chain_id(self) -> int:
try:
# from hex-str
return int(self.w3.eth.chainId, 16)
return int(self.w3.eth.chain_id, 16)
except TypeError:
# from str
return int(self.w3.eth.chainId)
return int(self.w3.eth.chain_id)
@property
def net_version(self) -> int:
@ -270,18 +270,18 @@ class EthereumClient:
"""
Returns client's gas price. Underneath, it uses the eth_gasPrice JSON-RPC method
"""
return self.w3.eth.gasPrice
return self.w3.eth.gas_price
def gas_price_for_transaction(self, transaction=None) -> Wei:
"""
Obtains a gas price via the current gas strategy, if any; otherwise, it resorts to the client's gas price.
This method mirrors the behavior of web3._utils.transactions when building transactions.
"""
return self.w3.eth.generateGasPrice(transaction) or self.gas_price
return self.w3.eth.generate_gas_price(transaction) or self.gas_price
@property
def block_number(self) -> BlockNumber:
return self.w3.eth.blockNumber
return self.w3.eth.block_number
@property
def coinbase(self) -> ChecksumAddress:
@ -310,7 +310,7 @@ class EthereumClient:
else:
# If not asking for confirmations, just use web3 and assume the returned receipt is final
try:
receipt = self.w3.eth.waitForTransactionReceipt(transaction_hash=transaction_hash,
receipt = self.w3.eth.wait_for_transaction_receipt(transaction_hash=transaction_hash,
timeout=timeout,
poll_latency=self.TRANSACTION_POLLING_TIME)
except TimeExhausted:
@ -320,9 +320,11 @@ class EthereumClient:
def block_until_enough_confirmations(self, transaction_hash: str, timeout: float, confirmations: int) -> dict:
receipt: TxReceipt = self.w3.eth.waitForTransactionReceipt(transaction_hash=transaction_hash,
timeout=timeout,
poll_latency=self.TRANSACTION_POLLING_TIME)
receipt: TxReceipt = self.w3.eth.wait_for_transaction_receipt(
transaction_hash=transaction_hash,
timeout=timeout,
poll_latency=self.TRANSACTION_POLLING_TIME
)
preliminary_block_hash = Web3.toHex(receipt['blockHash'])
tx_block_number = Web3.toInt(receipt['blockNumber'])
@ -348,7 +350,7 @@ class EthereumClient:
def check_transaction_is_on_chain(self, receipt: TxReceipt) -> bool:
transaction_hash = Web3.toHex(receipt['transactionHash'])
try:
new_receipt = self.w3.eth.getTransactionReceipt(transaction_hash)
new_receipt = self.w3.eth.get_transaction_receipt(transaction_hash)
except TransactionNotFound:
reorg_detected = True
else:
@ -365,20 +367,20 @@ class EthereumClient:
raise NotImplementedError
def get_transaction(self, transaction_hash) -> dict:
return self.w3.eth.getTransaction(transaction_hash)
return self.w3.eth.get_transaction(transaction_hash)
def get_transaction_receipt(self, transaction_hash) -> Union[dict, None]:
return self.w3.eth.getTransactionReceipt(transaction_hash)
return self.w3.eth.get_transaction_receipt(transaction_hash)
def get_transaction_count(self, account: str, pending: bool) -> int:
block_identifier = 'pending' if pending else 'latest'
return self.w3.eth.getTransactionCount(account, block_identifier)
return self.w3.eth.get_transaction_count(account, block_identifier)
def send_transaction(self, transaction_dict: dict) -> str:
return self.w3.eth.sendTransaction(transaction_dict)
return self.w3.eth.send_transaction(transaction_dict)
def send_raw_transaction(self, transaction_bytes: bytes) -> str:
return self.w3.eth.sendRawTransaction(transaction_bytes)
return self.w3.eth.send_raw_transaction(transaction_bytes)
def sign_message(self, account: str, message: bytes) -> str:
"""
@ -389,12 +391,12 @@ class EthereumClient:
return self.w3.eth.sign(account, data=message)
def get_blocktime(self):
highest_block = self.w3.eth.getBlock('latest')
highest_block = self.w3.eth.get_block('latest')
now = highest_block['timestamp']
return now
def get_block(self, block_identifier):
return self.w3.eth.getBlock(block_identifier)
return self.w3.eth.get_block(block_identifier)
def _has_latest_block(self) -> bool:
# TODO: Investigate using `web3.middleware.make_stalecheck_middleware` #2060
@ -457,7 +459,7 @@ class GethClient(EthereumClient):
transaction_dict = dissoc(transaction_dict, 'to')
# Sign
result = self.w3.eth.signTransaction(transaction_dict)
result = self.w3.eth.sign_transaction(transaction_dict)
# Return RLP bytes
rlp_encoded_transaction = result.raw

View File

@ -34,7 +34,7 @@ class EventRecord:
except BlockchainInterfaceFactory.NoRegisteredInterfaces:
self.timestamp = None
else:
self.timestamp = blockchain.client.w3.eth.getBlock(self.block_number)['timestamp']
self.timestamp = blockchain.client.w3.eth.get_block(self.block_number)['timestamp']
def __repr__(self):
pairs_to_show = dict(self.args.items())

View File

@ -505,11 +505,11 @@ class BlockchainInterface:
self.__log_transaction(transaction_dict=payload, contract_function=contract_function)
try:
if 'gas' not in payload: # i.e., transaction_gas_limit is not None
# As web3 buildTransaction() will estimate gas with block identifier "pending" by default,
# As web3 build_transaction() will estimate gas with block identifier "pending" by default,
# explicitly estimate gas here with block identifier 'latest' if not otherwise specified
# as a pending transaction can cause gas estimation to fail, notably in case of worklock refunds.
payload['gas'] = contract_function.estimateGas(payload, block_identifier='latest')
transaction_dict = contract_function.buildTransaction(payload)
payload['gas'] = contract_function.estimate_gas(payload, block_identifier='latest')
transaction_dict = contract_function.build_transaction(payload)
except (TestTransactionFailed, ValidationError, ValueError) as error:
# Note: Geth (1.9.15) raises ValueError in the same condition that pyevm raises ValidationError here.
# Treat this condition as "Transaction Failed" during gas estimation.

View File

@ -26,7 +26,7 @@ _DIRECTIVES = {
# TODO: Move this method to a util function
__CHAINS = {
60: 'ethereum', # TODO: make a few edits for now
61: 'testerchain', # TODO: this one can be moved to a pytest fixture / setup logic
131277322940537: 'testerchain', # TODO: this one can be moved to a pytest fixture / setup logic
**PUBLIC_CHAINS,
}
@ -145,6 +145,7 @@ class RPCCondition(ReencryptionCondition):
raise Exception(f'{method} is not a permitted RPC endpoint for conditions.')
if not method.startswith('eth_'):
raise Exception(f'Only eth RPC methods are accepted for conditions.')
method = camel_case_to_snake(method)
return method
def _configure_provider(self, provider: BaseProvider):
@ -160,8 +161,9 @@ class RPCCondition(ReencryptionCondition):
"""Performs onchain read and return value test"""
self._configure_provider(provider=provider)
parameters = _process_parameters(self.parameters, **contract_kwargs) # resolve context variables
eth_, method = self.method.split('_') # TODO: Ugly
rpc_function = getattr(self.w3.eth, method) # bind contract function (only exposes the eth API)
rpc_endpoint_, rpc_method = self.method.split('_', 1)
web3_py_method = camel_case_to_snake(rpc_method)
rpc_function = getattr(self.w3.eth, web3_py_method) # bind contract function (only exposes the eth API)
rpc_result = rpc_function(*parameters) # RPC read
eval_result = self.return_value_test.eval(rpc_result) # test
return eval_result, rpc_result
@ -212,7 +214,7 @@ class ContractCondition(RPCCondition):
def _configure_provider(self, *args, **kwargs):
super()._configure_provider(*args, **kwargs)
self.contract_function.web3 = self.w3
self.contract_function.w3 = self.w3
def _get_unbound_contract_function(self) -> ContractFunction:
"""Gets an unbound contract function to evaluate for this condition"""

View File

@ -55,7 +55,6 @@ def test_onchain_conditions_lingo_evaluation(testerchain, timelock_condition, rp
def test_single_retrieve_with_onchain_conditions(enacted_blockchain_policy, blockchain_bob, blockchain_ursulas):
blockchain_bob.start_learning_loop()
messages, message_kits = _make_message_kits(enacted_blockchain_policy.public_key)
conditions = [
{'returnValueTest': {'value': '0', 'comparator': '>'}, 'method': 'timelock'},
{'operator': 'and'},
@ -72,9 +71,7 @@ def test_single_retrieve_with_onchain_conditions(enacted_blockchain_policy, bloc
}
]
for mk in message_kits:
mk.conditions = ConditionLingo.from_json(json.dumps(conditions))
messages, message_kits = _make_message_kits(enacted_blockchain_policy.public_key, conditions)
policy_info_kwargs = dict(
encrypted_treasure_map=enacted_blockchain_policy.treasure_map,
alice_verifying_key=enacted_blockchain_policy.publisher_verifying_key,

View File

@ -63,8 +63,8 @@ def test_transacting_power_sign_transaction(testerchain):
signer=Web3Signer(testerchain.client),
account=eth_address)
transaction_dict = {'nonce': testerchain.client.w3.eth.getTransactionCount(eth_address),
'gasPrice': testerchain.client.w3.eth.gasPrice,
transaction_dict = {'nonce': testerchain.client.w3.eth.get_transaction_count(eth_address),
'gasPrice': testerchain.client.w3.eth.gas_price,
'gas': 100000,
'from': eth_address,
'to': testerchain.unassigned_accounts[1],
@ -94,12 +94,12 @@ def test_transacting_power_sign_agent_transaction(testerchain, agency, test_regi
contract_function = agent.contract.functions.confirmOperatorAddress()
payload = {'chainId': int(testerchain.client.chain_id),
'nonce': testerchain.client.w3.eth.getTransactionCount(testerchain.etherbase_account),
'nonce': testerchain.client.w3.eth.get_transaction_count(testerchain.etherbase_account),
'from': testerchain.etherbase_account,
'gasPrice': testerchain.client.gas_price,
'gas': 500_000}
unsigned_transaction = contract_function.buildTransaction(payload)
unsigned_transaction = contract_function.build_transaction(payload)
# Sign with Transacting Power
transacting_power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD,

View File

@ -54,8 +54,8 @@ def test_character_transacting_power_signing(testerchain, agency, test_registry)
assert is_verified is True
# Sign Transaction
transaction_dict = {'nonce': testerchain.client.w3.eth.getTransactionCount(eth_address),
'gasPrice': testerchain.client.w3.eth.gasPrice,
transaction_dict = {'nonce': testerchain.client.w3.eth.get_transaction_count(eth_address),
'gasPrice': testerchain.client.w3.eth.gas_price,
'gas': 100000,
'from': eth_address,
'to': testerchain.unassigned_accounts[1],

View File

@ -55,7 +55,7 @@ def mock_funded_account_password_keystore(tmp_path_factory, testerchain, thresho
json.dump(account.encrypt(password), open(path, 'x+t'))
testerchain.wait_for_receipt(
testerchain.client.w3.eth.sendTransaction({
testerchain.client.w3.eth.send_transaction({
'to': account.address,
'from': testerchain.etherbase_account,
'value': Web3.toWei('1', 'ether')}))
@ -151,7 +151,7 @@ def test_ursula_and_local_keystore_signer_integration(click_runner,
# ...and that transactions are signed by the keystore signer
txhash = ursula.confirm_address()
receipt = testerchain.wait_for_receipt(txhash)
transaction_data = testerchain.client.w3.eth.getTransaction(receipt['transactionHash'])
transaction_data = testerchain.client.w3.eth.get_transaction(receipt['transactionHash'])
assert transaction_data['from'] == worker_account.address
finally:
ursula.stop()

View File

@ -89,7 +89,7 @@ def test_bond_operator(testerchain, threshold_staking, pre_application, applicat
# Staking provider bonds operator and now operator can make a confirmation
tx = pre_application.functions.bondOperator(staking_provider_3, operator1).transact({'from': owner3})
testerchain.wait_for_receipt(tx)
timestamp = testerchain.w3.eth.getBlock('latest').timestamp
timestamp = testerchain.w3.eth.get_block('latest').timestamp
assert pre_application.functions.getOperatorFromStakingProvider(staking_provider_3).call() == operator1
assert pre_application.functions.stakingProviderFromOperator(operator1).call() == staking_provider_3
assert not pre_application.functions.stakingProviderInfo(staking_provider_3).call()[CONFIRMATION_SLOT]
@ -151,7 +151,7 @@ def test_bond_operator(testerchain, threshold_staking, pre_application, applicat
testerchain.time_travel(seconds=min_operator_seconds)
tx = pre_application.functions.bondOperator(staking_provider_3, NULL_ADDRESS).transact({'from': staking_provider_3})
testerchain.wait_for_receipt(tx)
timestamp = testerchain.w3.eth.getBlock('latest').timestamp
timestamp = testerchain.w3.eth.get_block('latest').timestamp
assert pre_application.functions.getOperatorFromStakingProvider(staking_provider_3).call() == NULL_ADDRESS
assert pre_application.functions.stakingProviderFromOperator(staking_provider_3).call() == NULL_ADDRESS
assert pre_application.functions.stakingProviderFromOperator(operator1).call() == NULL_ADDRESS
@ -178,7 +178,7 @@ def test_bond_operator(testerchain, threshold_staking, pre_application, applicat
# The staking provider can bond now a new operator, without waiting additional time.
tx = pre_application.functions.bondOperator(staking_provider_3, operator2).transact({'from': staking_provider_3})
testerchain.wait_for_receipt(tx)
timestamp = testerchain.w3.eth.getBlock('latest').timestamp
timestamp = testerchain.w3.eth.get_block('latest').timestamp
assert pre_application.functions.getOperatorFromStakingProvider(staking_provider_3).call() == operator2
assert pre_application.functions.stakingProviderFromOperator(operator2).call() == staking_provider_3
assert not pre_application.functions.stakingProviderInfo(staking_provider_3).call()[CONFIRMATION_SLOT]
@ -208,7 +208,7 @@ def test_bond_operator(testerchain, threshold_staking, pre_application, applicat
# Another staker can bond a free operator
tx = pre_application.functions.bondOperator(staking_provider_4, operator1).transact({'from': staking_provider_4})
testerchain.wait_for_receipt(tx)
timestamp = testerchain.w3.eth.getBlock('latest').timestamp
timestamp = testerchain.w3.eth.get_block('latest').timestamp
assert pre_application.functions.getOperatorFromStakingProvider(staking_provider_4).call() == operator1
assert pre_application.functions.stakingProviderFromOperator(operator1).call() == staking_provider_4
assert not pre_application.functions.isOperatorConfirmed(operator1).call()
@ -242,7 +242,7 @@ def test_bond_operator(testerchain, threshold_staking, pre_application, applicat
testerchain.time_travel(seconds=min_operator_seconds)
tx = pre_application.functions.bondOperator(staking_provider_4, operator3).transact({'from': staking_provider_4})
testerchain.wait_for_receipt(tx)
timestamp = testerchain.w3.eth.getBlock('latest').timestamp
timestamp = testerchain.w3.eth.get_block('latest').timestamp
assert pre_application.functions.getOperatorFromStakingProvider(staking_provider_4).call() == operator3
assert pre_application.functions.stakingProviderFromOperator(operator3).call() == staking_provider_4
assert pre_application.functions.stakingProviderFromOperator(operator1).call() == NULL_ADDRESS
@ -289,7 +289,7 @@ def test_bond_operator(testerchain, threshold_staking, pre_application, applicat
tx = pre_application.functions.bondOperator(
staking_provider_1, staking_provider_1).transact({'from': staking_provider_1})
testerchain.wait_for_receipt(tx)
timestamp = testerchain.w3.eth.getBlock('latest').timestamp
timestamp = testerchain.w3.eth.get_block('latest').timestamp
assert pre_application.functions.getOperatorFromStakingProvider(staking_provider_1).call() == staking_provider_1
assert pre_application.functions.stakingProviderFromOperator(staking_provider_1).call() == staking_provider_1
assert pre_application.functions.getStakingProvidersLength().call() == 3

View File

@ -308,7 +308,7 @@ def test_withdraw(testerchain, token, worklock, threshold_staking, escrow):
# Set vesting for the staker
tx = threshold_staking.functions.setStakedNu(staking_provider, value // 2).transact()
testerchain.wait_for_receipt(tx)
now = testerchain.w3.eth.getBlock('latest').timestamp
now = testerchain.w3.eth.get_block('latest').timestamp
release_timestamp = now + ONE_HOUR
rate = 2 * value // ONE_HOUR
tx = escrow.functions.setupVesting([staker], [release_timestamp], [rate]).transact({'from': creator})
@ -397,7 +397,7 @@ def test_vesting(testerchain, token, worklock, escrow):
tx = worklock.functions.depositFromWorkLock(staker1, value, 0).transact()
testerchain.wait_for_receipt(tx)
now = testerchain.w3.eth.getBlock('latest').timestamp
now = testerchain.w3.eth.get_block('latest').timestamp
release_timestamp = now + ONE_HOUR
rate = 2 * value // ONE_HOUR
@ -455,7 +455,7 @@ def test_vesting(testerchain, token, worklock, escrow):
assert event_args['releaseRate'] == rate
testerchain.time_travel(seconds=40 * 60)
now = testerchain.w3.eth.getBlock('latest').timestamp
now = testerchain.w3.eth.get_block('latest').timestamp
vested = (release_timestamp - now) * rate
assert escrow.functions.getUnvestedTokens(staker1).call() == vested
@ -476,7 +476,7 @@ def test_vesting(testerchain, token, worklock, escrow):
tx = worklock.functions.depositFromWorkLock(staker4, value, 0).transact()
testerchain.wait_for_receipt(tx)
now = testerchain.w3.eth.getBlock('latest').timestamp + 1 # +1 sec because tx will be executed in new block
now = testerchain.w3.eth.get_block('latest').timestamp + 1 # +1 sec because tx will be executed in new block
release_timestamp_2 = now + ONE_HOUR
release_timestamp_3 = now + 2 * ONE_HOUR
release_timestamp_4 = now + 2 * ONE_HOUR

View File

@ -294,7 +294,7 @@ def blockchain_treasure_map(enacted_blockchain_policy, blockchain_bob):
def random_blockchain_policy(testerchain, blockchain_alice, blockchain_bob, application_economics):
random_label = generate_random_label()
seconds = 60 * 60 * 24 # TODO This needs to be better thought out...?
now = testerchain.w3.eth.getBlock('latest').timestamp
now = testerchain.w3.eth.get_block('latest').timestamp
expiration = maya.MayaDT(now).add(seconds=seconds)
shares = 3
threshold = 2
@ -544,7 +544,7 @@ def testerchain(_testerchain) -> TesterBlockchain:
if spent > 0:
tx = {'to': address, 'from': coinbase, 'value': spent}
txhash = testerchain.w3.eth.sendTransaction(tx)
txhash = testerchain.w3.eth.send_transaction(tx)
_receipt = testerchain.wait_for_receipt(txhash)
eth_amount = Web3().fromWei(spent, 'ether')
@ -757,7 +757,7 @@ def software_stakeholder(testerchain, agency, stakeholder_config_file_location,
'from': testerchain.etherbase_account,
'value': Web3.toWei('1', 'ether')}
txhash = testerchain.client.w3.eth.sendTransaction(tx)
txhash = testerchain.client.w3.eth.send_transaction(tx)
_receipt = testerchain.wait_for_receipt(txhash)
# Mock TransactingPower consumption (Etherbase)
@ -800,7 +800,7 @@ def manual_operator(testerchain):
'from': testerchain.etherbase_account,
'value': Web3.toWei('1', 'ether')}
txhash = testerchain.client.w3.eth.sendTransaction(tx)
txhash = testerchain.client.w3.eth.send_transaction(tx)
_receipt = testerchain.wait_for_receipt(txhash)
yield address

View File

@ -29,14 +29,14 @@ def _policy_info_kwargs(enacted_policy):
)
def _make_message_kits(policy_pubkey):
def _make_message_kits(policy_pubkey, conditions=None):
messages = [b"plaintext1", b"plaintext2", b"plaintext3"]
message_kits = []
for message in messages:
# Using different Enricos, because why not.
enrico = Enrico(policy_encrypting_key=policy_pubkey)
message_kit = enrico.encrypt_message(message)
message_kit = enrico.encrypt_message(message, conditions=conditions)
message_kits.append(message_kit)
return messages, message_kits

View File

@ -202,7 +202,7 @@ def estimate_gas(analyzer: AnalyzeGas = None) -> None:
print("********* Estimating Gas *********")
def transact_and_log(label, function, transaction):
estimates = function.estimateGas(transaction)
estimates = function.estimate_gas(transaction)
transaction.update(gas=estimates)
tx = function.transact(transaction)
receipt = testerchain.wait_for_receipt(tx)
@ -288,7 +288,7 @@ def estimate_gas(analyzer: AnalyzeGas = None) -> None:
rate = 100
one_period = economics.hours_per_period * 60 * 60
value = number_of_periods * rate
current_timestamp = testerchain.w3.eth.getBlock('latest').timestamp
current_timestamp = testerchain.w3.eth.get_block('latest').timestamp
end_timestamp = current_timestamp + (number_of_periods - 1) * one_period
transact_and_log("Creating policy (1 node, 10 periods, pre-committed), first",
policy_functions.createPolicy(policy_id_1, alice1, end_timestamp, [staker1]),
@ -363,7 +363,7 @@ def estimate_gas(analyzer: AnalyzeGas = None) -> None:
policy_id_3 = os.urandom(int(POLICY_ID_LENGTH))
number_of_periods = 100
value = 3 * number_of_periods * rate
current_timestamp = testerchain.w3.eth.getBlock('latest').timestamp
current_timestamp = testerchain.w3.eth.get_block('latest').timestamp
end_timestamp = current_timestamp + (number_of_periods - 1) * one_period
transact_and_log("Creating policy (3 nodes, 100 periods, pre-committed), first",
policy_functions.createPolicy(policy_id_1, alice1, end_timestamp, [staker1, staker2, staker3]),
@ -392,13 +392,13 @@ def estimate_gas(analyzer: AnalyzeGas = None) -> None:
policy_id_3 = os.urandom(int(POLICY_ID_LENGTH))
number_of_periods = 100
value = number_of_periods * rate
current_timestamp = testerchain.w3.eth.getBlock('latest').timestamp
current_timestamp = testerchain.w3.eth.get_block('latest').timestamp
end_timestamp = current_timestamp + (number_of_periods - 1) * one_period
transact_and_log("Creating policy (1 node, 100 periods)",
policy_functions.createPolicy(policy_id_1, alice2, end_timestamp, [staker2]),
{'from': alice1, 'value': value})
testerchain.time_travel(periods=1)
current_timestamp = testerchain.w3.eth.getBlock('latest').timestamp
current_timestamp = testerchain.w3.eth.get_block('latest').timestamp
end_timestamp = current_timestamp + (number_of_periods - 1) * one_period
transact_and_log("Creating policy (1 node, 100 periods), next period",
policy_functions.createPolicy(policy_id_2, alice2, end_timestamp, [staker2]),
@ -440,7 +440,7 @@ def estimate_gas(analyzer: AnalyzeGas = None) -> None:
#
policy_id_1 = os.urandom(int(POLICY_ID_LENGTH))
policy_id_2 = os.urandom(int(POLICY_ID_LENGTH))
current_timestamp = testerchain.w3.eth.getBlock('latest').timestamp
current_timestamp = testerchain.w3.eth.get_block('latest').timestamp
end_timestamp = current_timestamp + (number_of_periods - 1) * one_period
value = 3 * number_of_periods * rate
transact_and_log("Creating 2 policies (3 nodes, 100 periods, pre-committed)",

View File

@ -33,7 +33,7 @@ MOCK_TESTERCHAIN = MockBlockchain()
CACHED_MOCK_TESTERCHAIN = BlockchainInterfaceFactory.CachedInterface(interface=MOCK_TESTERCHAIN, emitter=None)
BlockchainInterfaceFactory._interfaces[MOCK_ETH_PROVIDER_URI] = CACHED_MOCK_TESTERCHAIN
CURRENT_BLOCK = MOCK_TESTERCHAIN.w3.eth.getBlock('latest')
CURRENT_BLOCK = MOCK_TESTERCHAIN.w3.eth.get_block('latest')
class MockContractAgent:

View File

@ -39,7 +39,7 @@ def receipt():
def test_check_transaction_is_on_chain(mocker, mock_ethereum_client, receipt):
# Mocking Web3 and EthereumClient
web3_mock = mock_ethereum_client.w3
web3_mock.eth.getTransactionReceipt = mocker.Mock(return_value=receipt)
web3_mock.eth.get_transaction_receipt = mocker.Mock(return_value=receipt)
# Test with no chain reorganizations:
@ -52,7 +52,7 @@ def test_check_transaction_is_on_chain(mocker, mock_ethereum_client, receipt):
new_receipt = dict(receipt)
new_receipt.update({'blockHash': HexBytes('0xBebeCebada')})
web3_mock.eth.getTransactionReceipt = mocker.Mock(return_value=new_receipt)
web3_mock.eth.get_transaction_receipt = mocker.Mock(return_value=new_receipt)
exception = mock_ethereum_client.ChainReorganizationDetected
message = exception(receipt=receipt).message
@ -60,18 +60,19 @@ def test_check_transaction_is_on_chain(mocker, mock_ethereum_client, receipt):
_ = mock_ethereum_client.check_transaction_is_on_chain(receipt=receipt)
# Another example: there has been a chain reorganization and our beloved TX is gone for good:
web3_mock.eth.getTransactionReceipt = mocker.Mock(side_effect=TransactionNotFound)
web3_mock.eth.get_transaction_receipt = mocker.Mock(side_effect=TransactionNotFound)
with pytest.raises(exception, match=message):
_ = mock_ethereum_client.check_transaction_is_on_chain(receipt=receipt)
@pytest.mark.skip("Needs fix for web3.py v6+")
def test_block_until_enough_confirmations(mocker, mock_ethereum_client, receipt):
my_tx_hash = receipt['transactionHash']
block_number_of_my_tx = receipt['blockNumber']
# Test that web3's TimeExhausted is propagated:
web3_mock = mock_ethereum_client.w3
web3_mock.eth.waitForTransactionReceipt = mocker.Mock(side_effect=TimeExhausted)
web3_mock.eth.wait_for_transaction_receipt = mocker.Mock(side_effect=TimeExhausted)
with pytest.raises(TimeExhausted):
mock_ethereum_client.block_until_enough_confirmations(transaction_hash=my_tx_hash,
@ -80,10 +81,10 @@ def test_block_until_enough_confirmations(mocker, mock_ethereum_client, receipt)
# Test that NotEnoughConfirmations is raised when there are not enough confirmations.
# In this case, we're going to mock eth.blockNumber to be stuck
web3_mock.eth.waitForTransactionReceipt = mocker.Mock(return_value=receipt)
web3_mock.eth.getTransactionReceipt = mocker.Mock(return_value=receipt)
web3_mock.eth.wait_for_transaction_receipt = mocker.Mock(return_value=receipt)
web3_mock.eth.get_transaction_receipt = mocker.Mock(return_value=receipt)
type(web3_mock.eth).blockNumber = PropertyMock(return_value=block_number_of_my_tx) # See docs of PropertyMock
type(web3_mock.eth).block_number = PropertyMock(return_value=block_number_of_my_tx) # See docs of PropertyMock
# Additional adjustments to make the test faster
mocker.patch.object(mock_ethereum_client, '_calculate_confirmations_timeout', return_value=0.1)
@ -112,20 +113,20 @@ def test_wait_for_receipt_no_confirmations(mocker, mock_ethereum_client, receipt
# Test that web3's TimeExhausted is propagated:
web3_mock = mock_ethereum_client.w3
web3_mock.eth.waitForTransactionReceipt = mocker.Mock(side_effect=TimeExhausted)
web3_mock.eth.wait_for_transaction_receipt = mocker.Mock(side_effect=TimeExhausted)
with pytest.raises(TimeExhausted):
_ = mock_ethereum_client.wait_for_receipt(transaction_hash=my_tx_hash, timeout=1, confirmations=0)
web3_mock.eth.waitForTransactionReceipt.assert_called_once_with(transaction_hash=my_tx_hash,
timeout=1,
poll_latency=MockEthereumClient.TRANSACTION_POLLING_TIME)
web3_mock.eth.wait_for_transaction_receipt.assert_called_once_with(transaction_hash=my_tx_hash,
timeout=1,
poll_latency=MockEthereumClient.TRANSACTION_POLLING_TIME)
# Test that when web3's layer returns the receipt, we get that receipt
web3_mock.eth.waitForTransactionReceipt = mocker.Mock(return_value=receipt)
web3_mock.eth.wait_for_transaction_receipt = mocker.Mock(return_value=receipt)
returned_receipt = mock_ethereum_client.wait_for_receipt(transaction_hash=my_tx_hash, timeout=1, confirmations=0)
assert receipt == returned_receipt
web3_mock.eth.waitForTransactionReceipt.assert_called_once_with(transaction_hash=my_tx_hash,
timeout=1,
poll_latency=MockEthereumClient.TRANSACTION_POLLING_TIME)
web3_mock.eth.wait_for_transaction_receipt.assert_called_once_with(transaction_hash=my_tx_hash,
timeout=1,
poll_latency=MockEthereumClient.TRANSACTION_POLLING_TIME)
def test_wait_for_receipt_with_confirmations(mocker, mock_ethereum_client, receipt):

View File

@ -59,7 +59,7 @@ def test_use_pending_nonce_when_building_payload(mock_testerchain, mocker):
def mock_get_transaction_count(sender, block_identifier) -> int:
return transaction_count[block_identifier]
mock_testerchain.client.w3.eth.getTransactionCount = mocker.Mock(side_effect=mock_get_transaction_count)
mock_testerchain.client.w3.eth.get_transaction_count = mocker.Mock(side_effect=mock_get_transaction_count)
def simulate_successful_transaction():
transaction_count['pending'] += 1

View File

@ -68,8 +68,8 @@ class SyncedMockW3Eth:
# Support older and newer versions of web3 py in-test
version = 5
chainId = hex(5)
blockNumber = 5
chain_id = hex(5)
block_number = 5
def getBlock(self, blockNumber):
return {
@ -322,8 +322,8 @@ def test_ganache_web3_client():
def test_gas_prices(mocker, mock_ethereum_client):
web3_mock = mock_ethereum_client.w3
web3_mock.eth.generateGasPrice = mocker.Mock(side_effect=[None, GAS_PRICE_FROM_STRATEGY])
type(web3_mock.eth).gasPrice = PropertyMock(return_value=DEFAULT_GAS_PRICE) # See docs of PropertyMock
web3_mock.eth.generate_gas_price = mocker.Mock(side_effect=[None, GAS_PRICE_FROM_STRATEGY])
type(web3_mock.eth).gas_price = PropertyMock(return_value=DEFAULT_GAS_PRICE) # See docs of PropertyMock
assert mock_ethereum_client.gas_price == DEFAULT_GAS_PRICE
assert mock_ethereum_client.gas_price_for_transaction("there's no gas strategy") == DEFAULT_GAS_PRICE

View File

@ -173,7 +173,7 @@ class TesterBlockchain(BlockchainDeployerInterface):
tx_hashes = list()
for address in addresses:
tx = {'to': address, 'from': coinbase, 'value': amount, 'gasPrice': self.w3.eth.generate_gas_price()}
txhash = self.w3.eth.sendTransaction(tx)
txhash = self.w3.eth.send_transaction(tx)
_receipt = self.wait_for_receipt(txhash)
tx_hashes.append(txhash)
@ -203,11 +203,11 @@ class TesterBlockchain(BlockchainDeployerInterface):
else:
raise ValueError("Specify either hours, or seconds.")
now = self.w3.eth.getBlock('latest').timestamp
now = self.w3.eth.get_block('latest').timestamp
end_timestamp = ((now+duration)//base) * base
self.w3.eth.web3.testing.timeTravel(timestamp=end_timestamp)
self.w3.eth.web3.testing.mine(1)
self.w3.eth.w3.testing.timeTravel(timestamp=end_timestamp)
self.w3.eth.w3.testing.mine(1)
delta = maya.timedelta(seconds=end_timestamp-now)
self.log.info(f"Time traveled {delta} "