Skip to content

Commit

Permalink
Coverage fix
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielSchiavini committed Apr 22, 2024
1 parent 75d2e85 commit 52582c2
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 107 deletions.
6 changes: 6 additions & 0 deletions boa_zksync/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ def set_zksync_env(url):
boa.set_env(ZksyncEnv.from_url(url))


def set_zksync_fork(url):
boa.set_env(ZksyncEnv.from_url(url))
boa.env.fork()


def set_zksync_browser_env(address=None):
# import locally because jupyter is generally not installed
from boa_zksync.browser import ZksyncBrowserEnv
Expand All @@ -15,4 +20,5 @@ def set_zksync_browser_env(address=None):


boa.set_zksync_env = set_zksync_env
boa.set_zksync_fork = set_zksync_fork
boa.set_zksync_browser_env = set_zksync_browser_env
4 changes: 3 additions & 1 deletion boa_zksync/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ def compile_zksync(filename: str, compiler_args=None) -> ZksyncCompilerData:
return ZksyncCompilerData(**output[filename])


def compile_zksync_source(source_code: str, name: str, compiler_args=None) -> ZksyncCompilerData:
def compile_zksync_source(
source_code: str, name: str, compiler_args=None
) -> ZksyncCompilerData:
with TemporaryDirectory() as tempdir:
filename = f"{tempdir}/{name}.vy"
with open(filename, "w") as file:
Expand Down
1 change: 1 addition & 0 deletions boa_zksync/deployer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class ZksyncDeployer(ABIContractFactory):
def deploy(self, *args, value=0, **kwargs):
env = Env.get_singleton()
from boa_zksync.environment import ZksyncEnv

assert isinstance(
env, ZksyncEnv
), "ZksyncDeployer can only be used in zkSync environments"
Expand Down
13 changes: 10 additions & 3 deletions boa_zksync/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ def _reset_fork(self, block_identifier="latest"):
del self._rpc
self._rpc = rpc

def fork(self, url: str = None, reset_traces=True, block_identifier="safe", **kwargs):
if url:
return super().fork(url, reset_traces, block_identifier, **kwargs)
return self.fork_rpc(self._rpc, reset_traces, block_identifier, **kwargs)

def fork_rpc(
self, rpc: EthereumRPC, reset_traces=True, block_identifier="safe", **kwargs
):
Expand Down Expand Up @@ -108,7 +113,9 @@ def execute_code(
if is_modifying:
try:
receipt, trace = self._send_txn(**args.as_tx_params())
assert traced_computation.is_error == trace.is_error, f"VMError mismatch: {traced_computation.error} != {trace.error}"
assert (
traced_computation.is_error == trace.is_error
), f"VMError mismatch: {traced_computation.error} != {trace.error}"
except _EstimateGasFailed:
return ZksyncComputation(args, error=VMError("Estimate gas failed"))

Expand Down Expand Up @@ -188,14 +195,14 @@ def create_deployer(
dedent: bool = True,
compiler_args: dict = None,
) -> "ZksyncDeployer":
if not name:
name = Path(filename).stem if filename else "<anonymous contract>"

if filename:
compiler_data = compile_zksync(filename, compiler_args)
else:
compiler_data = compile_zksync_source(source_code, name, compiler_args)

if not compiler_data.abi:
logging.warning("No ABI found in compiled contract")
return ZksyncDeployer.from_abi_dict(compiler_data.abi, name, filename, compiler_data)


Expand Down
24 changes: 13 additions & 11 deletions boa_zksync/types.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from dataclasses import dataclass, field

import rlp
from boa.rpc import to_bytes, fixup_dict, to_hex
from boa.rpc import fixup_dict, to_bytes, to_hex
from boa.util.abi import Address
from eth.exceptions import VMError, Revert
from eth.exceptions import Revert, VMError
from eth_account import Account
from eth_account.datastructures import SignedMessage
from eth_account.messages import encode_typed_data
Expand Down Expand Up @@ -176,13 +176,15 @@ def code_address(self) -> bytes:
return to_bytes(self.to)

def as_json_dict(self, sender_field="from"):
return fixup_dict({
sender_field: self.sender,
"to": self.to,
"gas": self.gas,
"value": self.value,
"data": to_hex(self.data),
})
return fixup_dict(
{
sender_field: self.sender,
"to": self.to,
"gas": self.gas,
"value": self.value,
"data": to_hex(self.data),
}
)

def as_tx_params(self):
return self.as_json_dict(sender_field="from_")
Expand All @@ -197,7 +199,7 @@ class ZksyncComputation:

@classmethod
def from_trace(cls, output: dict) -> "ZksyncComputation":
""" Recursively constructs a ZksyncComputation from a debug_traceCall output. """
"""Recursively constructs a ZksyncComputation from a debug_traceCall output."""
error = None
if output.get("error") is not None:
error = VMError(output["error"])
Expand Down Expand Up @@ -237,5 +239,5 @@ def raise_if_error(self) -> None:
:raise VMError:
"""
if self.is_error:
if self.error:
raise self.error
2 changes: 1 addition & 1 deletion boa_zksync/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ def stop_subprocess(proc: Popen[bytes]):
proc.terminate()
try:
proc.wait(timeout=10)
except TimeoutExpired:
except TimeoutExpired: # pragma: no cover
proc.kill()
proc.wait(timeout=1)
Empty file added tests/__init__.py
Empty file.
47 changes: 31 additions & 16 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,47 @@
import os
import sys
from subprocess import Popen

import boa
import pytest
from boa.rpc import EthereumRPC
from eth_account import Account

from boa_zksync.environment import ZksyncEnv
from boa_zksync.util import find_free_port, wait_url, stop_subprocess


@pytest.fixture(scope="module")
def rpc(era_test_node):
return EthereumRPC(era_test_node)

def zksync_env(era_test_node, account):
old_env = boa.env
boa.set_zksync_env(era_test_node)
boa.env.add_account(account)
yield boa.env
boa.set_env(old_env)

@pytest.fixture(scope="module", autouse=True)
def zksync_env(rpc, account):
env = ZksyncEnv(rpc)
env.add_account(account)
with boa.swap_env(env):
yield env


@pytest.fixture(autouse=True)
def cleanup_env(zksync_env):
with zksync_env.anchor():
yield
@pytest.fixture(scope="module")
def zksync_fork_env(account):
old_env = boa.env
fork_url = os.getenv("FORK_URL", "https://sepolia.era.zksync.dev")
boa.set_zksync_fork(fork_url)
boa.env.add_account(account)
yield boa.env
boa.set_env(old_env)


@pytest.fixture(scope="module")
def account():
return Account.from_key(
"0x3d3cbc973389cb26f657686445bcc75662b415b656078503592ac8c1abb8810e"
)


@pytest.fixture(scope="session")
def era_test_node():
era_port = find_free_port()
era_node = Popen(
["era_test_node", "--show-calls", "user", "--port", f"{era_port}", "run"],
stdout=sys.stdout,
stderr=sys.stderr,
)
yield wait_url(f"http://localhost:{era_port}")
stop_subprocess(era_node)
70 changes: 34 additions & 36 deletions tests/test_deploy.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,18 @@
import sys
from subprocess import Popen

import pytest

import boa
import pytest
from boa import BoaError
from boa.contracts.base_evm_contract import StackTrace

from boa_zksync.util import find_free_port, wait_url, stop_subprocess
from boa_zksync.util import find_free_port, stop_subprocess, wait_url

STARTING_SUPPLY = 100


@pytest.fixture(scope="session")
def era_test_node():
era_port = find_free_port()
era_node = Popen([
"era_test_node",
"--show-calls", 'user',
"--port",
f"{era_port}",
"run"
], stdout=sys.stdout, stderr=sys.stderr)
yield wait_url(f"http://localhost:{era_port}")
stop_subprocess(era_node)


@pytest.fixture(scope="module")
def simple_contract():
def simple_contract(zksync_env):
code = """
totalSupply: public(uint256)
balances: HashMap[address, uint256]
Expand Down Expand Up @@ -55,8 +40,8 @@ def test_total_supply(simple_contract):
assert simple_contract.totalSupply() == STARTING_SUPPLY * 3


def test_blueprint():
blueprint_code = f"""
def test_blueprint(zksync_env):
blueprint_code = """
val: public(uint256)
@external
Expand All @@ -74,7 +59,9 @@ def some_function() -> uint256:
def create_child(blueprint: address, salt: bytes32, val: uint256) -> address:
return create_from_blueprint(blueprint, val, salt=salt)
"""
blueprint = boa.loads_partial(blueprint_code, name="Blueprint").deploy_as_blueprint()
blueprint = boa.loads_partial(
blueprint_code, name="Blueprint"
).deploy_as_blueprint()
factory = boa.loads(factory_code, name="Factory")

salt = b"\x00" * 32
Expand All @@ -88,8 +75,8 @@ def create_child(blueprint: address, salt: bytes32, val: uint256) -> address:
assert child.some_function() == 5


def test_blueprint_immutable():
blueprint_code = f"""
def test_blueprint_immutable(zksync_env):
blueprint_code = """
VAL: immutable(uint256)
@external
Expand All @@ -107,7 +94,9 @@ def some_function() -> uint256:
def create_child(blueprint: address, val: uint256) -> address:
return create_from_blueprint(blueprint, val)
"""
blueprint = boa.loads_partial(blueprint_code, name="blueprint").deploy_as_blueprint()
blueprint = boa.loads_partial(
blueprint_code, name="blueprint"
).deploy_as_blueprint()
factory = boa.loads(factory_code, name="factory")

child_contract_address = factory.create_child(blueprint.address, 5)
Expand All @@ -116,7 +105,7 @@ def create_child(blueprint: address, val: uint256) -> address:
assert child.some_function() == 5


def test_internal_call():
def test_internal_call(zksync_env):
code = """
@internal
@view
Expand All @@ -132,7 +121,7 @@ def bar() -> uint256:
assert contract.bar() == 123


def test_stack_trace():
def test_stack_trace(zksync_env):
called_contract = boa.loads(
"""
@internal
Expand All @@ -145,7 +134,8 @@ def _get_name() -> String[32]:
@view
def name() -> String[32]:
return self._get_name()
""", name="CalledContract"
""",
name="CalledContract",
)
caller_contract = boa.loads(
"""
Expand All @@ -156,18 +146,26 @@ def name() -> String[32]: view
@view
def get_name_of(addr: HasName) -> String[32]:
return addr.name()
""", name="CallerContract"
""",
name="CallerContract",
)

# boa.reverts does not give us the stack trace, use pytest.raises instead
with pytest.raises(BoaError) as ctx:
caller_contract.get_name_of(called_contract)

trace, = ctx.value.args
assert trace == StackTrace([
f" (<CalledContract interface at {called_contract.address}>.name() -> ['string'])",
f" (<CallerContract interface at {caller_contract.address}>.get_name_of(address) -> ['string'])",
" <Unknown contract 0x0000000000000000000000000000000000008009>", # MsgValueSimulator
" <Unknown contract 0x0000000000000000000000000000000000008002>", # AccountCodeStorage
f" (<CallerContract interface at {caller_contract.address}>.get_name_of(address) -> ['string'])",
])
(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'])",
]
)
21 changes: 21 additions & 0 deletions tests/test_fork.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import os
import sys
from subprocess import Popen

import boa
import pytest

from boa_zksync.util import find_free_port, stop_subprocess, wait_url


def test_dummy_contract(zksync_fork_env):
code = """
@external
@view
def foo() -> bool:
return True
"""
c = boa.loads_partial(code).at("0xB27cCfd5909f46F5260Ca01BA27f591868D08704")
assert c.foo() is True
c = boa.loads(code)
assert c.foo() is True
Loading

0 comments on commit 52582c2

Please sign in to comment.