Skip to content

Commit

Permalink
Merge pull request #1064 from skellet0r/feat/upgrade-web3
Browse files Browse the repository at this point in the history
Upgrade web3 dependency
  • Loading branch information
iamdefinitelyahuman authored Apr 19, 2021
2 parents da078f9 + 4b134d4 commit 6f25248
Show file tree
Hide file tree
Showing 41 changed files with 399 additions and 445 deletions.
14 changes: 7 additions & 7 deletions brownie/network/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ def __eq__(self, other: Union[object, str]) -> bool:

def balance(self) -> Wei:
"""Returns the current balance at the address, in wei."""
balance = web3.eth.getBalance(self.address)
balance = web3.eth.get_balance(self.address)
return Wei(balance)

@property
Expand All @@ -303,7 +303,7 @@ def gas_used(self) -> int:

@property
def nonce(self) -> int:
return web3.eth.getTransactionCount(self.address)
return web3.eth.get_transaction_count(self.address)

def get_deployment_address(self, nonce: Optional[int] = None) -> EthAddress:
"""
Expand Down Expand Up @@ -391,7 +391,7 @@ def _gas_price(self, gas_price: Any = None) -> Tuple[Wei, Optional[GasABC], Opti
return gas_price, None, None

if isinstance(gas_price, bool) or gas_price in (None, "auto"):
return web3.eth.generateGasPrice(), None, None
return web3.eth.generate_gas_price(), None, None

return Wei(gas_price), None, None

Expand Down Expand Up @@ -547,11 +547,11 @@ def estimate_gas(
if gas_price is not None:
tx["gasPrice"] = gas_price
try:
return web3.eth.estimateGas(tx)
return web3.eth.estimate_gas(tx)
except ValueError as exc:
revert_gas_limit = CONFIG.active_network["settings"]["reverting_tx_gas_limit"]
if revert_gas_limit == "max":
revert_gas_limit = web3.eth.getBlock("latest")["gasLimit"]
revert_gas_limit = web3.eth.get_block("latest")["gasLimit"]
CONFIG.active_network["settings"]["reverting_tx_gas_limit"] = revert_gas_limit
if revert_gas_limit:
return revert_gas_limit
Expand Down Expand Up @@ -708,7 +708,7 @@ def _transact(self, tx: Dict, allow_revert: bool) -> Any:
allow_revert = bool(CONFIG.network_type == "development")
if not allow_revert:
self._check_for_revert(tx)
return web3.eth.sendTransaction(tx)
return web3.eth.send_transaction(tx)


class LocalAccount(_PrivateKeyAccount):
Expand Down Expand Up @@ -764,4 +764,4 @@ def _transact(self, tx: Dict, allow_revert: bool) -> None:
self._check_for_revert(tx)
tx["chainId"] = web3.chain_id
signed_tx = self._acct.sign_transaction(tx).rawTransaction # type: ignore
return web3.eth.sendRawTransaction(signed_tx)
return web3.eth.send_raw_transaction(signed_tx)
16 changes: 8 additions & 8 deletions brownie/network/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def _revert(self, height: int) -> None:
i
for i in self._contracts
if (i.tx and i.tx.block_number is not None and i.tx.block_number > height)
or len(web3.eth.getCode(i.address).hex()) <= 4
or len(web3.eth.get_code(i.address).hex()) <= 4
]
for contract in reverted:
self.remove(contract)
Expand Down Expand Up @@ -745,7 +745,7 @@ def __init__(
self, address: str, owner: Optional[AccountsType] = None, tx: TransactionReceiptType = None
) -> None:
address = _resolve_address(address)
self.bytecode = web3.eth.getCode(address).hex()[2:]
self.bytecode = web3.eth.get_code(address).hex()[2:]
if not self.bytecode:
raise ContractNotFound(f"No contract deployed at {address}")
self._owner = owner
Expand Down Expand Up @@ -845,7 +845,7 @@ def get_method_object(self, calldata: str) -> Optional["_ContractMethod"]:

def balance(self) -> Wei:
"""Returns the current ether balance of the contract, in wei."""
balance = web3.eth.getBalance(self.address)
balance = web3.eth.get_balance(self.address)
return Wei(balance)

def _deployment_path(self) -> Optional[Path]:
Expand All @@ -867,7 +867,7 @@ def _save_deployment(self) -> None:
deployment_build["deployment"] = {
"address": self.address,
"chainid": chainid,
"blockHeight": web3.eth.blockNumber,
"blockHeight": web3.eth.block_number,
}
if path:
self._project._add_to_deployment_map(self)
Expand Down Expand Up @@ -1110,11 +1110,11 @@ def from_explorer(

if as_proxy_for is None:
# always check for an EIP1967 proxy - https://eips.ethereum.org/EIPS/eip-1967
implementation_eip1967 = web3.eth.getStorageAt(
implementation_eip1967 = web3.eth.get_storage_at(
address, int(web3.keccak(text="eip1967.proxy.implementation").hex(), 16) - 1
)
# always check for an EIP1822 proxy - https://eips.ethereum.org/EIPS/eip-1822
implementation_eip1822 = web3.eth.getStorageAt(address, web3.keccak(text="PROXIABLE"))
implementation_eip1822 = web3.eth.get_storage_at(address, web3.keccak(text="PROXIABLE"))
if len(implementation_eip1967) > 0 and int(implementation_eip1967.hex(), 16):
as_proxy_for = _resolve_address(implementation_eip1967[-20:])
elif len(implementation_eip1822) > 0 and int(implementation_eip1822.hex(), 16):
Expand Down Expand Up @@ -1791,7 +1791,7 @@ def _inputs(abi: Dict) -> str:


def _verify_deployed_code(address: str, expected_bytecode: str, language: str) -> bool:
actual_bytecode = web3.eth.getCode(address).hex()[2:]
actual_bytecode = web3.eth.get_code(address).hex()[2:]
expected_bytecode = remove_0x_prefix(expected_bytecode) # type: ignore

if expected_bytecode.startswith("730000000000000000000000000000000000000000"):
Expand Down Expand Up @@ -1846,7 +1846,7 @@ def _fetch_from_explorer(address: str, action: str, silent: bool) -> Dict:
if address in _unverified_addresses:
raise ValueError(f"Source for {address} has not been verified")

code = web3.eth.getCode(address).hex()[2:]
code = web3.eth.get_code(address).hex()[2:]
# EIP-1167: Minimal Proxy Contract
if code[:20] == "363d3d373d3d3d363d73" and code[60:] == "5af43d82803e903d91602b57fd5bf3":
address = _resolve_address(code[20:60])
Expand Down
6 changes: 3 additions & 3 deletions brownie/network/gas/bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ def _loop(self, receipt: Any, gas_iter: Iterator) -> None:
# silenced by the 2nd replacement
silent = receipt._silent

while web3.eth.getTransactionCount(str(receipt.sender)) < receipt.nonce:
while web3.eth.get_transaction_count(str(receipt.sender)) < receipt.nonce:
# do not run scaling strategy while prior tx's are still pending
time.sleep(5)

latest_interval = self.interval()
while True:
if web3.eth.getTransactionCount(str(receipt.sender)) > receipt.nonce:
if web3.eth.get_transaction_count(str(receipt.sender)) > receipt.nonce:
break

if self.interval() - latest_interval >= self.duration:
Expand Down Expand Up @@ -122,7 +122,7 @@ def __init__(self, block_duration: int = 2) -> None:
self.duration = block_duration

def interval(self) -> int:
return web3.eth.blockNumber
return web3.eth.block_number

@abstractmethod
def get_gas_price(self) -> Generator[int, None, None]:
Expand Down
4 changes: 2 additions & 2 deletions brownie/network/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ def connect(network: str = None, launch_rpc: bool = True) -> None:
web3.connect(host, active.get("timeout", 30))
if CONFIG.network_type == "development" and launch_rpc and not rpc.is_active():
if is_connected():
if web3.eth.blockNumber != 0:
if web3.eth.block_number != 0:
warnings.warn(
f"Development network has a block height of {web3.eth.blockNumber}",
f"Development network has a block height of {web3.eth.block_number}",
BrownieEnvironmentWarning,
)
rpc.attach(host)
Expand Down
4 changes: 2 additions & 2 deletions brownie/network/middlewares/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def is_cacheable_bytecode(web3: Web3, bytecode: HexBytes) -> bool:
if not int(address.hex(), 16):
# if the delegatecall targets 0x00 this is a factory pattern, we can ignore
continue
target_bytecode = web3.eth.getCode(address)
target_bytecode = web3.eth.get_code(address)
if not is_cacheable_bytecode(web3, target_bytecode):
return False

Expand All @@ -96,7 +96,7 @@ def __init__(self, w3: Web3) -> None:
self.cur = Cursor(_get_data_folder().joinpath("cache.db"))
self.cur.execute(f"CREATE TABLE IF NOT EXISTS {self.table_key} (method, params, result)")

latest = w3.eth.getBlock("latest")
latest = w3.eth.get_block("latest")
self.last_block = latest.hash
self.last_block_seen = latest.timestamp
self.last_request = 0.0
Expand Down
28 changes: 28 additions & 0 deletions brownie/network/middlewares/catch_tx_revert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from typing import Callable, Dict, List, Optional

from web3 import Web3

from brownie.network.middlewares import BrownieMiddlewareABC


class TxRevertCatcherMiddleware(BrownieMiddlewareABC):

"""
Middleware to handle reverting transactions, bypasses web3 error formatting.
As of web3.py version 5.13.0, a new error formatting middleware was added by default
`raise_solidity_error_on_revert` which when a `eth_call` or `eth_estimateGas` tx
raises a `ContractLogicError` instead of providing us with an RPCError dictionary.
"""

@classmethod
def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
return -1

def process_request(self, make_request: Callable, method: str, params: List) -> Dict:
"""Raise a ValueError when RPC.eth_call or RPC.eth_estimateGas errors."""
result = make_request(method, params)
if method in ("eth_call", "eth_estimateGas"):
if "error" in result:
raise ValueError(result["error"])
return result
2 changes: 1 addition & 1 deletion brownie/network/middlewares/geth_poa.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class GethPOAMiddleware(BrownieMiddlewareABC):
@classmethod
def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
try:
w3.eth.getBlock("latest")
w3.eth.get_block("latest")
return None
except ExtraDataLengthError:
return -1
Expand Down
4 changes: 2 additions & 2 deletions brownie/network/rpc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def sleep(self, seconds: int) -> int:
@internal
def mine(self, timestamp: int = None) -> int:
self.backend.mine(timestamp)
return web3.eth.blockNumber
return web3.eth.block_number

@internal
def snapshot(self) -> int:
Expand All @@ -180,7 +180,7 @@ def snapshot(self) -> int:
@internal
def revert(self, snapshot_id: int) -> int:
self.backend.revert(snapshot_id)
return web3.eth.blockNumber
return web3.eth.block_number

def unlock_account(self, address: str) -> None:
self.backend.unlock_account(address)
Expand Down
34 changes: 17 additions & 17 deletions brownie/network/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def __len__(self) -> int:
"""
Return the current number of blocks.
"""
return web3.eth.blockNumber + 1
return web3.eth.block_number + 1

def __getitem__(self, block_number: int) -> BlockData:
"""
Expand All @@ -224,15 +224,15 @@ def __getitem__(self, block_number: int) -> BlockData:
if not isinstance(block_number, int):
raise TypeError("Block height must be given as an integer")
if block_number < 0:
block_number = web3.eth.blockNumber + 1 + block_number
block = web3.eth.getBlock(block_number)
block_number = web3.eth.block_number + 1 + block_number
block = web3.eth.get_block(block_number)
if block["timestamp"] > self._block_gas_time:
self._block_gas_limit = block["gasLimit"]
self._block_gas_time = block["timestamp"]
return block

def __iter__(self) -> Iterator:
return iter(web3.eth.getBlock(i) for i in range(web3.eth.blockNumber + 1))
return iter(web3.eth.get_block(i) for i in range(web3.eth.block_number + 1))

def new_blocks(self, height_buffer: int = 0, poll_interval: int = 5) -> Iterator:
"""
Expand All @@ -255,9 +255,9 @@ def new_blocks(self, height_buffer: int = 0, poll_interval: int = 5) -> Iterator
last_poll = 0.0

while True:
if last_poll + poll_interval < time.time() or last_height != web3.eth.blockNumber:
last_height = web3.eth.blockNumber
block = web3.eth.getBlock(last_height - height_buffer)
if last_poll + poll_interval < time.time() or last_height != web3.eth.block_number:
last_height = web3.eth.block_number
block = web3.eth.get_block(last_height - height_buffer)
last_poll = time.time()

if block != last_block:
Expand All @@ -268,25 +268,25 @@ def new_blocks(self, height_buffer: int = 0, poll_interval: int = 5) -> Iterator

@property
def height(self) -> int:
return web3.eth.blockNumber
return web3.eth.block_number

@property
def id(self) -> int:
if self._chainid is None:
self._chainid = web3.eth.chainId
self._chainid = web3.eth.chain_id
return self._chainid

@property
def block_gas_limit(self) -> Wei:
if time.time() > self._block_gas_time + 3600:
block = web3.eth.getBlock("latest")
block = web3.eth.get_block("latest")
self._block_gas_limit = block["gasLimit"]
self._block_gas_time = block["timestamp"]
return Wei(self._block_gas_limit)

def _revert(self, id_: int) -> int:
rpc_client = rpc.Rpc()
if web3.isConnected() and not web3.eth.blockNumber and not self._time_offset:
if web3.isConnected() and not web3.eth.block_number and not self._time_offset:
_notify_registry(0)
return rpc_client.snapshot()
rpc_client.revert(id_)
Expand Down Expand Up @@ -402,7 +402,7 @@ def mine(self, blocks: int = 1, timestamp: int = None, timedelta: int = None) ->

self._redo_buffer.clear()
self._current_id = rpc.Rpc().snapshot()
return web3.eth.blockNumber
return web3.eth.block_number

def snapshot(self) -> None:
"""
Expand Down Expand Up @@ -430,7 +430,7 @@ def revert(self) -> int:
self._undo_buffer.clear()
self._redo_buffer.clear()
self._snapshot_id = self._current_id = self._revert(self._snapshot_id)
return web3.eth.blockNumber
return web3.eth.block_number

def reset(self) -> int:
"""
Expand All @@ -451,7 +451,7 @@ def reset(self) -> int:
_notify_registry(0)
else:
self._reset_id = self._current_id = self._revert(self._reset_id)
return web3.eth.blockNumber
return web3.eth.block_number

def undo(self, num: int = 1) -> int:
"""
Expand Down Expand Up @@ -480,7 +480,7 @@ def undo(self, num: int = 1) -> int:
self._redo_buffer.append((fn, args, kwargs))

self._current_id = self._revert(id_)
return web3.eth.blockNumber
return web3.eth.block_number

def redo(self, num: int = 1) -> int:
"""
Expand Down Expand Up @@ -508,7 +508,7 @@ def redo(self, num: int = 1) -> int:
fn, args, kwargs = self._redo_buffer.pop()
fn(*args, **kwargs)

return web3.eth.blockNumber
return web3.eth.block_number


# objects that will update whenever the RPC is reset or reverted must register
Expand All @@ -521,7 +521,7 @@ def _revert_register(obj: object) -> None:
def _notify_registry(height: int = None) -> None:
gc.collect()
if height is None:
height = web3.eth.blockNumber
height = web3.eth.block_number
for ref in _revert_refs.copy():
obj = ref()
if obj is None:
Expand Down
Loading

0 comments on commit 6f25248

Please sign in to comment.