to/from wei method updates for web3 v6+ support

pull/2960/head
Kieran Prasch 2022-10-03 15:29:22 +02:00
parent a0bbfa0f59
commit 9ae4d5c966
25 changed files with 65 additions and 63 deletions

View File

@ -32,7 +32,7 @@ class Economics:
_default_min_authorization = TToken(40_000, 'T').to_units()
_default_min_operator_seconds = 60 * 60 * 24 # one day in seconds
_default_fee_rate = Wei(Web3.toWei(1, 'gwei'))
_default_fee_rate = Wei(Web3.to_wei(1, 'gwei'))
# TODO: Reintroduce Adjudicator
# Slashing parameters

View File

@ -110,7 +110,7 @@ class BaseActor:
"""Return this actor's current ETH balance"""
blockchain = BlockchainInterfaceFactory.get_interface() # TODO: EthAgent? #1509
balance = blockchain.client.get_balance(self.wallet_address)
return Web3.fromWei(balance, 'ether')
return Web3.from_wei(balance, 'ether')
@property
def wallet_address(self):
@ -362,7 +362,7 @@ class Operator(BaseActor):
ether_balance = client.get_balance(self.operator_address)
if ether_balance:
# funds found
funded, balance = True, Web3.fromWei(ether_balance, 'ether')
funded, balance = True, Web3.from_wei(ether_balance, 'ether')
emitter.message(f"✓ Operator {self.operator_address} is funded with {balance} ETH", color='green')
else:
emitter.message(f"! Operator {self.operator_address} is not funded with ETH", color="yellow")

View File

@ -227,7 +227,7 @@ class EthereumClient:
@property
def is_connected(self):
return self.w3.isConnected()
return self.w3.is_connected()
@property
def etherbase(self) -> str:

View File

@ -308,7 +308,7 @@ class BlockchainInterface:
configuration_message = f"Using gas strategy '{reported_gas_strategy}'"
if self.max_gas_price:
__price = Web3.toWei(self.max_gas_price, 'gwei') # from gwei to wei
__price = Web3.to_wei(self.max_gas_price, 'gwei') # from gwei to wei
gas_strategy = max_price_gas_strategy_wrapper(gas_strategy=gas_strategy, max_gas_price_wei=__price)
configuration_message += f", with a max price of {self.max_gas_price} gwei."
@ -316,7 +316,7 @@ class BlockchainInterface:
# TODO: This line must not be called prior to establishing a connection
# Move it down to a lower layer, near the client.
# gwei_gas_price = Web3.fromWei(self.client.gas_price_for_transaction(), 'gwei')
# gwei_gas_price = Web3.from_wei(self.client.gas_price_for_transaction(), 'gwei')
self.log.info(configuration_message)
# self.log.debug(f"Gas strategy currently reports a gas price of {gwei_gas_price} gwei.")
@ -570,9 +570,9 @@ class BlockchainInterface:
max_unit_price = transaction_dict['gasPrice']
tx_type = 'Legacy'
max_price_gwei = Web3.fromWei(max_unit_price, 'gwei')
max_price_gwei = Web3.from_wei(max_unit_price, 'gwei')
max_cost_wei = max_unit_price * transaction_dict['gas']
max_cost = Web3.fromWei(max_cost_wei, 'ether')
max_cost = Web3.from_wei(max_cost_wei, 'ether')
if transacting_power.is_device:
emitter.message(f'Confirm transaction {transaction_name} on hardware wallet... '

View File

@ -128,11 +128,11 @@ def prettify_eth_amount(amount, original_denomination: str = 'wei') -> str:
"""
try:
# First obtain canonical representation in wei. Works for int, float, Decimal and str amounts
amount_in_wei = Web3.toWei(Decimal(amount), original_denomination)
amount_in_wei = Web3.to_wei(Decimal(amount), original_denomination)
common_denominations = ('wei', 'gwei', 'ether')
options = [str(Web3.fromWei(amount_in_wei, d)) for d in common_denominations]
options = [str(Web3.from_wei(amount_in_wei, d)) for d in common_denominations]
best_option = min(zip(map(len, options), options, common_denominations))
_length, pretty_amount, denomination = best_option

View File

@ -117,7 +117,7 @@ def collect_policy_rate_and_value(alice: Alice, rate: int, value: int, shares: i
rate = alice.payment_method.rate # wei
if not force:
default_gwei = Web3.fromWei(rate, 'gwei') # wei -> gwei
default_gwei = Web3.from_wei(rate, 'gwei') # wei -> gwei
prompt = "Confirm rate of {node_rate} gwei * {shares} nodes ({period_rate} gwei per period)?"
if not click.confirm(prompt.format(node_rate=default_gwei, period_rate=default_gwei * shares, shares=shares), default=True):
@ -125,7 +125,7 @@ def collect_policy_rate_and_value(alice: Alice, rate: int, value: int, shares: i
# TODO: Interactive rate sampling & validation (#1709)
interactive_prompt = prompt.format(node_rate=interactive_rate, period_rate=interactive_rate * shares, shares=shares)
click.confirm(interactive_prompt, default=True, abort=True)
rate = Web3.toWei(interactive_rate, 'gwei') # gwei -> wei
rate = Web3.to_wei(interactive_rate, 'gwei') # gwei -> wei
return rate, value

View File

@ -103,7 +103,7 @@ def confirm_staged_grant(emitter, grant_request: Dict, federated: bool, seconds_
emitter.echo(tabulate(table, tablefmt="simple"))
return
period_rate = Web3.fromWei(pretty_request['shares'] * pretty_request['rate'], 'gwei')
period_rate = Web3.from_wei(pretty_request['shares'] * pretty_request['rate'], 'gwei')
pretty_request['rate'] = f"{pretty_request['rate']} wei/period * {pretty_request['shares']} nodes"
expiration = pretty_request['expiration']

View File

@ -117,7 +117,7 @@ def select_client_account(emitter,
is_staking = 'Yes' if bool(staker.stakes) else 'No'
row.append(is_staking)
if show_eth_balance:
ether_balance = Web3.fromWei(blockchain.client.get_balance(account), 'ether')
ether_balance = Web3.from_wei(blockchain.client.get_balance(account), 'ether')
row.append(f'{ether_balance} ETH')
if show_nu_balance:
token_agent = ContractAgency.get_agent(NucypherTokenAgent, registry=registry)

View File

@ -114,7 +114,7 @@ Registry ................ {registry.filepath}
token_contract_info = f"""
{token_agent.contract_name} ........... {token_agent.contract_address}
~ Ethers ............ {Web3.fromWei(blockchain.client.get_balance(token_agent.contract_address), 'ether')} ETH
~ Ethers ............ {Web3.from_wei(blockchain.client.get_balance(token_agent.contract_address), 'ether')} ETH
~ Tokens ............ {NU.from_units(token_agent.get_balance(token_agent.contract_address))}"""
except BaseContractRegistry.UnknownContract:
message = f"\n{NucypherTokenAgent.contract_name} is not enrolled in {registry.filepath}"
@ -146,12 +146,12 @@ Registry ................ {registry.filepath}
{agent.contract_name} .... {bare_contract.address}
~ Version ............ {bare_contract.version}
~ Owner .............. {bare_contract.functions.owner().call()}
~ Ethers ............. {Web3.fromWei(blockchain.client.get_balance(bare_contract.address), 'ether')} ETH
~ Ethers ............. {Web3.from_wei(blockchain.client.get_balance(bare_contract.address), 'ether')} ETH
~ Tokens ............. {NU.from_units(token_agent.get_balance(bare_contract.address))}
~ Dispatcher ......... {dispatcher_deployer.contract_address}
~ Owner .......... {dispatcher_deployer.contract.functions.owner().call()}
~ Target ......... {dispatcher_deployer.contract.functions.target().call()}
~ Ethers ......... {Web3.fromWei(blockchain.client.get_balance(dispatcher_deployer.contract_address), 'ether')} ETH
~ Ethers ......... {Web3.from_wei(blockchain.client.get_balance(dispatcher_deployer.contract_address), 'ether')} ETH
~ Tokens ......... {NU.from_units(token_agent.get_balance(dispatcher_deployer.contract_address))}"""
emitter.echo(proxy_payload)
emitter.echo(sep, nl=False)

View File

@ -35,7 +35,7 @@ def paint_contract_status(registry, emitter):
blockchain = f"""
| '{blockchain.client.chain_name}' Blockchain Network |
Gas Price ................ {Web3.fromWei(blockchain.client.gas_price, 'gwei')} Gwei
Gas Price ................ {Web3.from_wei(blockchain.client.gas_price, 'gwei')} Gwei
ETH Provider URI ......... {blockchain.eth_provider_uri}
Registry ................. {registry.filepath}
"""

View File

@ -112,7 +112,7 @@ class EtherchainGasPriceDatafeed(EthereumGasPriceDatafeed):
def _parse_gas_prices(self):
self._probe_feed()
self.gas_prices = {self.get_canonical_speed(k): int(Web3.toWei(v, 'gwei')) for k, v in self._raw_data.items()}
self.gas_prices = {self.get_canonical_speed(k): int(Web3.to_wei(v, 'gwei')) for k, v in self._raw_data.items()}
class UpvestGasPriceDatafeed(EthereumGasPriceDatafeed):
@ -130,7 +130,7 @@ class UpvestGasPriceDatafeed(EthereumGasPriceDatafeed):
def _parse_gas_prices(self):
self._probe_feed()
self.gas_prices = {self.get_canonical_speed(k): int(Web3.toWei(v, 'gwei'))
self.gas_prices = {self.get_canonical_speed(k): int(Web3.to_wei(v, 'gwei'))
for k, v in self._raw_data['estimates'].items()}
@ -152,5 +152,5 @@ class ZoltuGasPriceDatafeed(EthereumGasPriceDatafeed):
self.gas_prices = dict()
for canonical_speed_name, zoltu_speed in self._speed_names.items():
gwei_price = self._raw_data[zoltu_speed].split(" ")[0]
wei_price = int(Web3.toWei(gwei_price, 'gwei'))
wei_price = int(Web3.to_wei(gwei_price, 'gwei'))
self.gas_prices[canonical_speed_name] = wei_price

View File

@ -129,11 +129,11 @@ EXPECTED_CONFIRMATION_TIME_IN_SECONDS = { # TODO: See #2447
def construct_fixed_price_gas_strategy(gas_price, denomination: str = "wei") -> Callable:
gas_price_in_wei = Web3.toWei(gas_price, denomination)
gas_price_in_wei = Web3.to_wei(gas_price, denomination)
def _fixed_price_strategy(web3: Web3, transaction_params: TxParams = None) -> Wei:
return gas_price_in_wei
_fixed_price_strategy.name = f"{round(Web3.fromWei(gas_price_in_wei, 'gwei'))}gwei"
_fixed_price_strategy.name = f"{round(Web3.from_wei(gas_price_in_wei, 'gwei'))}gwei"
return _fixed_price_strategy

View File

@ -73,7 +73,7 @@ def rpc_condition():
condition = RPCCondition(
method="eth_getBalance",
chain="testerchain",
return_value_test=ReturnValueTest("==", Web3.toWei(1_000_000, "ether")),
return_value_test=ReturnValueTest("==", Web3.to_wei(1_000_000, "ether")),
parameters=[USER_ADDRESS_CONTEXT],
)
return condition

View File

@ -148,7 +148,7 @@ def test_rpc_condition_evaluation(get_context_value_mock, testerchain, rpc_condi
provider=testerchain.provider, **context
)
assert condition_result is True
assert call_result == Web3.toWei(
assert call_result == Web3.to_wei(
1_000_000, "ether"
) # same value used in rpc_condition fixture

View File

@ -333,7 +333,7 @@ def run_entire_cli_lifecycle(click_runner,
grant_args += ('--federated-only',)
else:
grant_args += ('--eth-provider', TEST_ETH_PROVIDER_URI,
'--value', Web3.toWei(9, 'gwei'))
'--value', Web3.to_wei(9, 'gwei'))
grant_result = click_runner.invoke(nucypher_cli, grant_args, catch_exceptions=False, env=envvars)
assert grant_result.exit_code == 0, (grant_result.output, grant_result.exception)

View File

@ -58,7 +58,7 @@ def mock_funded_account_password_keystore(tmp_path_factory, testerchain, thresho
testerchain.client.w3.eth.send_transaction({
'to': account.address,
'from': testerchain.etherbase_account,
'value': Web3.toWei('1', 'ether')}))
'value': Web3.to_wei('1', 'ether')}))
# initialize threshold stake
provider_address = testerchain.unassigned_accounts[0]

View File

@ -65,7 +65,7 @@ MIN_STAKE_FOR_TESTS = NU(750_000, 'NU').to_units()
BONUS_TOKENS_FOR_TESTS = NU(150_000, 'NU').to_units()
DEVELOPMENT_ETH_AIRDROP_AMOUNT = int(Web3().toWei(100, 'ether'))
DEVELOPMENT_ETH_AIRDROP_AMOUNT = int(Web3().to_wei(100, 'ether'))
NUMBER_OF_ALLOCATIONS_IN_TESTS = 50 # TODO: Move to constants

View File

@ -558,7 +558,7 @@ def testerchain(_testerchain) -> TesterBlockchain:
txhash = testerchain.w3.eth.send_transaction(tx)
_receipt = testerchain.wait_for_receipt(txhash)
eth_amount = Web3().fromWei(spent, 'ether')
eth_amount = Web3().from_wei(spent, 'ether')
testerchain.log.info("Airdropped {} ETH {} -> {}".format(eth_amount, tx['from'], tx['to']))
BlockchainInterfaceFactory.register_interface(interface=testerchain, force=True)
@ -707,7 +707,7 @@ def blockchain_ursulas(testerchain, staking_providers, ursula_decentralized_test
@pytest.fixture(scope='module')
def policy_rate():
rate = Web3.toWei(21, 'gwei')
rate = Web3.to_wei(21, 'gwei')
return rate
@ -766,7 +766,7 @@ def software_stakeholder(testerchain, agency, stakeholder_config_file_location,
tx = {'to': address,
'from': testerchain.etherbase_account,
'value': Web3.toWei('1', 'ether')}
'value': Web3.to_wei('1', 'ether')}
txhash = testerchain.client.w3.eth.send_transaction(tx)
_receipt = testerchain.wait_for_receipt(txhash)
@ -809,7 +809,7 @@ def manual_operator(testerchain):
tx = {'to': address,
'from': testerchain.etherbase_account,
'value': Web3.toWei('1', 'ether')}
'value': Web3.to_wei('1', 'ether')}
txhash = testerchain.client.w3.eth.send_transaction(tx)
_receipt = testerchain.wait_for_receipt(txhash)

View File

@ -207,7 +207,7 @@ def test_select_client_account_with_balance_display(mock_stdin,
if show_eth:
balance = mock_testerchain.client.get_balance(account=account)
assert str(Web3.fromWei(balance, 'ether')) in captured.out
assert str(Web3.from_wei(balance, 'ether')) in captured.out
if show_staking:
if len(stake_info) == 0:

View File

@ -16,11 +16,6 @@
You should have received a copy of the GNU Affero General Public License
along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
from pathlib import Path
from nucypher.blockchain.eth.signers import Signer
from nucypher.network.nodes import TEACHER_NODES
from nucypher.policy.payment import SubscriptionManagerPayment
"""
WARNING: This script makes automatic transactions.
@ -29,22 +24,28 @@ are doing and intend to spend ETH measuring live
policy availability.
"""
import datetime
import maya
import os
import shutil
import time
from eth_typing.evm import ChecksumAddress
from pathlib import Path
from typing import Set, Optional, List, Tuple
import maya
from eth_typing.evm import ChecksumAddress
from nucypher_core.umbral import SecretKey
from web3 import Web3
from web3.types import Wei
from nucypher.blockchain.eth.signers import Signer
from nucypher.characters.lawful import Bob, Ursula, Alice
from nucypher.config.characters import AliceConfiguration
from nucypher.network.nodes import TEACHER_NODES
from nucypher.policy.payment import SubscriptionManagerPayment
from nucypher.policy.policies import Policy
from nucypher.utilities.logging import GlobalLoggerSettings
# Signer Configuration
# In order to use this script, you must configure a wallet for alice
ADDRESS_ENVVAR: str = 'NUCYPHER_GRANT_METRICS_ADDRESS'
@ -76,8 +77,9 @@ INSECURE_PASSWORD: str = "METRICS_INSECURE_DEVELOPMENT_PASSWORD"
TEMP_ALICE_DIR: Path = Path('/', 'tmp', 'grant-metrics')
# Policy Parameters
THRESHOLD: int = 2
SHARES: int = 3
THRESHOLD: int = 1
SHARES: int = 1
RATE: Wei = Web3.to_wei(50, 'gwei')
DURATION: datetime.timedelta = datetime.timedelta(days=1)
# Tuning

View File

@ -68,7 +68,7 @@ def rpc_condition():
condition = RPCCondition(
method="eth_getBalance",
chain="testerchain",
return_value_test=ReturnValueTest("==", Web3.toWei(1_000_000, "ether")),
return_value_test=ReturnValueTest("==", Web3.to_wei(1_000_000, "ether")),
parameters=[USER_ADDRESS_CONTEXT],
)
return condition

View File

@ -159,10 +159,10 @@ def test_etherchain():
with patch.object(feed, '_probe_feed'):
feed._raw_data = etherchain_json
assert feed.get_gas_price('safeLow') == Web3.toWei(99.0, 'gwei')
assert feed.get_gas_price('standard') == Web3.toWei(105.0, 'gwei')
assert feed.get_gas_price('fast') == Web3.toWei(108.0, 'gwei')
assert feed.get_gas_price('fastest') == Web3.toWei(119.9, 'gwei')
assert feed.get_gas_price('safeLow') == Web3.to_wei(99.0, 'gwei')
assert feed.get_gas_price('standard') == Web3.to_wei(105.0, 'gwei')
assert feed.get_gas_price('fast') == Web3.to_wei(108.0, 'gwei')
assert feed.get_gas_price('fastest') == Web3.to_wei(119.9, 'gwei')
assert feed.get_gas_price() == feed.get_gas_price('fast') # Default
parsed_gas_prices = feed.gas_prices
@ -170,7 +170,7 @@ def test_etherchain():
EtherchainGasPriceDatafeed.gas_prices = dict()
with patch.dict(EtherchainGasPriceDatafeed.gas_prices, values=parsed_gas_prices):
gas_strategy = feed.construct_gas_strategy()
assert gas_strategy("web3", "tx") == Web3.toWei(108.0, 'gwei')
assert gas_strategy("web3", "tx") == Web3.to_wei(108.0, 'gwei')
def test_upvest():
@ -181,10 +181,10 @@ def test_upvest():
with patch.object(feed, '_probe_feed'):
feed._raw_data = upvest_json
assert feed.get_gas_price('slow') == Web3.toWei(87.19, 'gwei')
assert feed.get_gas_price('medium') == Web3.toWei(91.424, 'gwei')
assert feed.get_gas_price('fast') == Web3.toWei(97.158, 'gwei')
assert feed.get_gas_price('fastest') == Web3.toWei(105.2745, 'gwei')
assert feed.get_gas_price('slow') == Web3.to_wei(87.19, 'gwei')
assert feed.get_gas_price('medium') == Web3.to_wei(91.424, 'gwei')
assert feed.get_gas_price('fast') == Web3.to_wei(97.158, 'gwei')
assert feed.get_gas_price('fastest') == Web3.to_wei(105.2745, 'gwei')
assert feed.get_gas_price() == feed.get_gas_price('fastest') # Default
parsed_gas_prices = feed.gas_prices
@ -192,7 +192,7 @@ def test_upvest():
UpvestGasPriceDatafeed.gas_prices = dict()
with patch.dict(UpvestGasPriceDatafeed.gas_prices, values=parsed_gas_prices):
gas_strategy = feed.construct_gas_strategy()
assert gas_strategy("web3", "tx") == Web3.toWei(105.2745, 'gwei')
assert gas_strategy("web3", "tx") == Web3.to_wei(105.2745, 'gwei')
def test_zoltu():
@ -203,10 +203,10 @@ def test_zoltu():
with patch.object(feed, '_probe_feed'):
feed._raw_data = zoltu_json
assert feed.get_gas_price('slow') == Web3.toWei(41, 'gwei')
assert feed.get_gas_price('medium') == Web3.toWei(58, 'gwei')
assert feed.get_gas_price('fast') == Web3.toWei(67, 'gwei')
assert feed.get_gas_price('fastest') == Web3.toWei(70, 'gwei')
assert feed.get_gas_price('slow') == Web3.to_wei(41, 'gwei')
assert feed.get_gas_price('medium') == Web3.to_wei(58, 'gwei')
assert feed.get_gas_price('fast') == Web3.to_wei(67, 'gwei')
assert feed.get_gas_price('fastest') == Web3.to_wei(70, 'gwei')
assert feed.get_gas_price() == feed.get_gas_price('fast') # Default
parsed_gas_prices = feed.gas_prices
@ -214,7 +214,7 @@ def test_zoltu():
ZoltuGasPriceDatafeed.gas_prices = dict()
with patch.dict(ZoltuGasPriceDatafeed.gas_prices, values=parsed_gas_prices):
gas_strategy = feed.construct_gas_strategy()
assert gas_strategy("web3", "tx") == Web3.toWei(67, 'gwei')
assert gas_strategy("web3", "tx") == Web3.to_wei(67, 'gwei')
def test_datafeed_median_gas_price_strategy():

View File

@ -46,9 +46,9 @@ def test_fixed_price_gas_strategy():
def test_max_price_gas_strategy(mocker, monkeypatch):
gas_prices_gwei = [10, 100, 999, 1000, 1001, 1_000_000, 1_000_000_000]
gas_prices_wei = [Web3.toWei(gwei_price, 'gwei') for gwei_price in gas_prices_gwei]
gas_prices_wei = [Web3.to_wei(gwei_price, 'gwei') for gwei_price in gas_prices_gwei]
max_gas_price_gwei = 1000
max_gas_price_wei = Web3.toWei(max_gas_price_gwei, 'gwei')
max_gas_price_wei = Web3.to_wei(max_gas_price_gwei, 'gwei')
mock_gas_strategy = mocker.Mock(side_effect=itertools.cycle(gas_prices_wei))
wrapped_strategy = max_price_gas_strategy_wrapper(gas_strategy=mock_gas_strategy,

View File

@ -122,7 +122,7 @@ class SyncedMockWeb3:
return self.provider.clientVersion
@property
def isConnected(self):
def is_connected(self):
return lambda: True

View File

@ -177,7 +177,7 @@ class TesterBlockchain(BlockchainDeployerInterface):
_receipt = self.wait_for_receipt(txhash)
tx_hashes.append(txhash)
eth_amount = Web3().fromWei(amount, 'ether')
eth_amount = Web3().from_wei(amount, 'ether')
self.log.info("Airdropped {} ETH {} -> {}".format(eth_amount, tx['from'], tx['to']))
return tx_hashes