Skip to content

Commit

Permalink
Careful with set_balance in networks
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielSchiavini committed Apr 29, 2024
1 parent cf33614 commit f1d0d7b
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 22 deletions.
1 change: 0 additions & 1 deletion boa_zksync/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ class ZksyncBrowserEnv(ZksyncEnv):
"""
A zkSync environment for deploying contracts using a browser wallet RPC.
"""

def __init__(self, address=None, *args, **kwargs):
if colab_eval_js and not which("zkvyper"):
logging.warning(
Expand Down
6 changes: 5 additions & 1 deletion boa_zksync/contract.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import textwrap
from contextlib import contextmanager
from unittest.mock import MagicMock

from boa.contracts.abi.abi_contract import ABIContract, ABIFunction
from boa.contracts.vyper.compiler_utils import (
Expand All @@ -8,6 +9,7 @@
detect_statement_type,
)
from boa.rpc import to_bytes
from boa.vyper.contract import VyperContract
from cached_property import cached_property
from vyper.semantics.analysis.base import VarInfo
from vyper.semantics.types.function import ContractFunctionT
Expand All @@ -25,7 +27,9 @@ def eval(self, code):

@contextmanager
def override_vyper_namespace(self):
yield
c = VyperContract(self.compiler_data.vyper, env=self.env, override_address=self.address, skip_initcode=True, filename=self.filename)
with c.override_vyper_namespace():
yield

@cached_property
def _storage(self):
Expand Down
8 changes: 5 additions & 3 deletions boa_zksync/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from hashlib import sha256
from pathlib import Path
from typing import Any, Iterable, Optional
from unittest.mock import MagicMock

from boa.contracts.abi.abi_contract import ABIContract, ABIContractFactory
from boa.environment import _AddressType
Expand Down Expand Up @@ -32,13 +33,15 @@ class ZksyncEnv(NetworkEnv):
This is a mix-in so the logic may be reused in both network and browser modes.
"""

_DEFAULT_BALANCE = 10**20

def __init__(self, rpc: str | RPC, *args, **kwargs):
super().__init__(rpc, *args, **kwargs)
self.evm = None # not used in zkSync
self.eoa = self.generate_address("eoa")

@property
def vm(self):
return MagicMock() # todo: vyper base contract is calling vm directly

@cached_property
def create(self):
return next(
Expand Down Expand Up @@ -233,7 +236,6 @@ def generate_address(self, alias: Optional[str] = None) -> _AddressType:
self.add_account(account)

address = Address(account.address)
self.set_balance(address, self._DEFAULT_BALANCE)
if alias:
self._aliases[alias] = address
return address
Expand Down
2 changes: 1 addition & 1 deletion boa_zksync/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def __init__(self, rpc: Optional[EthereumRPC] = None, block_identifier="safe"):
fork_at = (
["--fork-at", block_identifier] if isinstance(block_identifier, int) else []
)
fork_args = ["--fork", rpc._rpc_url] + fork_at if rpc else ["run"]
fork_args = ["fork", rpc._rpc_url] + fork_at if rpc else ["run"]
self._test_node = Popen(
["era_test_node", "--port", f"{port}"] + fork_args,
stdout=sys.stdout,
Expand Down
6 changes: 4 additions & 2 deletions dev-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
IPython
Sphinx
black
flake8
flake8-bugbear
Expand All @@ -11,4 +10,7 @@ pre-commit
pytest
pytest-xdist
pytest-cov
sphinx-rtd-theme

# jupyter
jupyter_server
nest_asyncio
5 changes: 3 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
def zksync_env(account):
old_env = boa.env
boa_zksync.set_zksync_test_env()
boa.env.add_account(account)
boa.env.add_account(account, force_eoa=True)
yield boa.env
boa.set_env(old_env)

Expand All @@ -21,13 +21,14 @@ def zksync_fork_env(account):
old_env = boa.env
fork_url = os.getenv("FORK_URL", "https://sepolia.era.zksync.dev")
boa_zksync.set_zksync_fork(fork_url)
boa.env.add_account(account)
boa.env.add_account(account, force_eoa=True)
yield boa.env
boa.set_env(old_env)


@pytest.fixture(scope="module")
def account():
# default rich account from era_test_node
return Account.from_key(
"0x3d3cbc973389cb26f657686445bcc75662b415b656078503592ac8c1abb8810e"
)
50 changes: 50 additions & 0 deletions tests/test_browser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from typing import Any
from unittest.mock import MagicMock

import boa
import pytest
from _pytest.monkeypatch import MonkeyPatch

from boa_zksync import set_zksync_browser_env
from boa_zksync.environment import ZERO_ADDRESS


def _javascript_call(js_func: str, *args, timeout_message: str) -> Any:
if js_func == "rpc":
method = args[0]
if method == "evm_snapshot":
return 1

if method == "evm_revert":
assert args[1:] == ([1],), f"Bad args passed to mock: {args}"
return None

if method == "wallet_switchEthereumChain":
assert args[1:] == ([{"chainId": "0x1"}],), f"Bad args passed to mock: {args}"
return None

raise KeyError(args)

if js_func == "loadSigner":
return ZERO_ADDRESS

raise KeyError(js_func)


@pytest.fixture(scope="session", autouse=True)
def patch_js():
# we call MonkeyPatch directly because the default `monkeypatch` fixture has a function scope
# this clashes with the boa plugin that tries to clean up the env after each test.
mpatch = MonkeyPatch()
mpatch.setattr("boa.integrations.jupyter.browser._javascript_call", _javascript_call)
yield
mpatch.undo()


@pytest.fixture
def browser_env():
set_zksync_browser_env()


def test_browser(browser_env):
boa.env.set_chain_id(1)
22 changes: 10 additions & 12 deletions tests/test_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,18 +151,16 @@ def get_name_of(addr: HasName) -> String[32]:

(trace,) = ctx.value.args
assert trace == StackTrace(
[
f" (<CalledContract interface at {called_contract.address}>."
f"name() -> ['string'])",
f" (<CallerContract interface at {caller_contract.address}>."
f"get_name_of(address) -> ['string'])",
# MsgValueSimulator
" <Unknown contract 0x0000000000000000000000000000000000008009>",
# AccountCodeStorage
" <Unknown contract 0x0000000000000000000000000000000000008002>",
f" (<CallerContract interface at {caller_contract.address}>."
f"get_name_of(address) -> ['string'])",
]
[" Test an error(<CalledContract interface at "
f"{called_contract.address}>.name() -> ['string'])",
" Test an error(<CallerContract interface at "
f"{caller_contract.address}>.get_name_of(address) -> "
"['string'])",
" <Unknown contract 0x0000000000000000000000000000000000008009>",
" <Unknown contract 0x0000000000000000000000000000000000008002>",
" Test an error(<CallerContract interface at "
f"{caller_contract.address}>.get_name_of(address) -> "
"['string'])"]
)


Expand Down

0 comments on commit f1d0d7b

Please sign in to comment.