Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ProtostarFixture #566

Merged
merged 46 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from 38 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
9aeeae1
Initial draft
Radinyn Aug 9, 2022
3616fb0
Removed artifacts
Radinyn Aug 9, 2022
6ac63e4
Cleanup
Radinyn Aug 9, 2022
1237a75
Added protocols
Radinyn Aug 9, 2022
8de3f4f
add compiled_project fixture
kasperski95 Aug 10, 2022
1861fd0
fix project testing environemnet
kasperski95 Aug 10, 2022
8b7a574
rename fixtures
kasperski95 Aug 10, 2022
fd999c2
use constants for fixture names
kasperski95 Aug 10, 2022
205204f
fix importing fixtures
kasperski95 Aug 10, 2022
9cef01d
use module scope
kasperski95 Aug 10, 2022
2ab9625
add declare test
kasperski95 Aug 10, 2022
226cb5d
add tests
kasperski95 Aug 10, 2022
c4df9c0
add more learning tests
kasperski95 Aug 11, 2022
5752227
remove invoke and _add call test
kasperski95 Aug 11, 2022
684ab21
_add test
kasperski95 Aug 11, 2022
3174a72
refine test
kasperski95 Aug 11, 2022
3f859cb
change fixture desired interface
kasperski95 Aug 11, 2022
288fc62
_add protostar fixture
kasperski95 Aug 11, 2022
3732554
add protostar fixture
kasperski95 Aug 11, 2022
3d64e05
use protostar fixture for declare cheatcode
kasperski95 Aug 11, 2022
2a44242
use protostar fixture in gateway facade
kasperski95 Aug 11, 2022
678db3c
remove asyncs
kasperski95 Aug 11, 2022
2521c0a
remove dead code
kasperski95 Aug 11, 2022
42ddd28
use protostar fixture
kasperski95 Aug 11, 2022
cf6d536
make call pass
kasperski95 Aug 11, 2022
4dcebf2
move contract to tests.data
kasperski95 Aug 12, 2022
eb86294
fix creating migration output file
kasperski95 Aug 12, 2022
90dd036
add more tests
kasperski95 Aug 12, 2022
956250c
format
kasperski95 Aug 12, 2022
33b40ea
handle errors
kasperski95 Aug 12, 2022
8a13d88
fix gateway facade tests
kasperski95 Aug 12, 2022
6e9e88b
fix types and format
kasperski95 Aug 12, 2022
a4d3fa0
refine
kasperski95 Aug 12, 2022
1ae2947
fix protostar toml
kasperski95 Aug 12, 2022
436c5f4
fix lint
kasperski95 Aug 12, 2022
b237c83
remove invoke
kasperski95 Aug 16, 2022
e2871d2
remove call cheatcode
kasperski95 Aug 16, 2022
34a1b6c
refine no protostar toml exception
kasperski95 Aug 16, 2022
5a557fe
remove "call" literal type
kasperski95 Aug 17, 2022
f8bd58c
rename type
kasperski95 Aug 17, 2022
f2b6c5c
remove unnecessary log color provider
kasperski95 Aug 17, 2022
265ac19
remove cwd
kasperski95 Aug 17, 2022
e5cf92a
remove cwd
kasperski95 Aug 17, 2022
a548c00
remove type
kasperski95 Aug 17, 2022
556b624
renamed cwd to project root path
kasperski95 Aug 17, 2022
3434ca1
fix e2e tests
kasperski95 Aug 17, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion protostar/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys

from starkware.crypto.signature.fast_pedersen_hash import pedersen_hash
from crypto_cpp_py.cpp_bindings import cpp_hash
from starkware.crypto.signature.fast_pedersen_hash import pedersen_hash


def patched_pedersen_hash(left: int, right: int) -> int:
Expand Down
19 changes: 16 additions & 3 deletions protostar/commands/build/build_command.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from logging import Logger
from pathlib import Path
from typing import List, Optional

from protostar.cli import ActivityIndicator, Command
Expand Down Expand Up @@ -48,15 +49,27 @@ def arguments(self) -> List[Command.Argument]:
]

async def run(self, args):
await self.build(
output_dir=args.output,
disable_hint_validation=args.disable_hint_validation,
relative_cairo_path=args.cairo_path,
)

async def build(
self,
output_dir: Path,
disable_hint_validation=False,
relative_cairo_path: Optional[List[Path]] = None,
):
with ActivityIndicator(
log_color_provider.colorize("GRAY", "Building projects' contracts")
):
try:
self._project_compiler.compile_project(
output_dir=args.output,
output_dir=output_dir,
config=ProjectCompilerConfig(
hint_validation_disabled=args.disable_hint_validation,
relative_cairo_path=args.cairo_path,
hint_validation_disabled=disable_hint_validation,
relative_cairo_path=relative_cairo_path or [],
),
)
except BaseException as exc:
Expand Down
17 changes: 12 additions & 5 deletions protostar/commands/init/init_command.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import glob
from glob import glob
from pathlib import Path
from typing import List, Optional

from protostar.cli import Command
Expand All @@ -17,11 +18,13 @@ def __init__(
requester: InputRequester,
new_project_creator: NewProjectCreator,
adapted_project_creator: AdaptedProjectCreator,
cwd: Path,
) -> None:
super().__init__()
self._adapted_project_creator = adapted_project_creator
self._new_project_creator = new_project_creator
self._requester = requester
self._cwd = cwd
kasperski95 marked this conversation as resolved.
Show resolved Hide resolved

@property
def name(self) -> str:
Expand Down Expand Up @@ -65,9 +68,13 @@ def init(self, force_adapting_existing_project: bool):
else:
self._new_project_creator.run()

@staticmethod
def _can_be_protostar_project() -> bool:
files_depth_3 = glob.glob("*") + glob.glob("*/*") + glob.glob("*/*/*")
def _can_be_protostar_project(self) -> bool:

files_depth_3 = (
glob(str(self._cwd / "*"))
+ glob(str(self._cwd / "*" / "*"))
+ glob(str(self._cwd / "*" / "*" / "*"))
)
return any(
map(lambda f: f.endswith(".cairo") or f == ".git", files_depth_3)
) and "protostar.toml" not in glob.glob("*")
) and "protostar.toml" not in glob(str(self._cwd / "*"))
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

from git import InvalidGitRepositoryError
from git.repo import Repo
Expand All @@ -16,17 +17,20 @@ class UserInput:
project_dirname: str
lib_dirname: str

# pylint: disable=too-many-arguments
def __init__(
self,
script_root: Path,
requester: InputRequester,
protostar_toml_writer: ProtostarTOMLWriter,
version_manager: VersionManager,
output_dir_path: Optional[Path] = None,
):
super().__init__(script_root, protostar_toml_writer, version_manager)
self._protostar_toml_writer = protostar_toml_writer
self._version_manager = version_manager
self._requester = requester
self._output_dir_path = output_dir_path or Path()

def run(self):
self._create_project(self._gather_input())
Expand All @@ -46,7 +50,8 @@ def _gather_input(self) -> "NewProjectCreator.UserInput":
return NewProjectCreator.UserInput(project_dirname, lib_dirname)

def _create_project(self, user_input: "NewProjectCreator.UserInput") -> None:
project_root_path = Path() / user_input.project_dirname
output_dir_path = self._output_dir_path
project_root_path = output_dir_path / user_input.project_dirname
self.copy_template("default", project_root_path)

libs_path = Path(project_root_path, user_input.lib_dirname)
Expand Down
10 changes: 6 additions & 4 deletions protostar/commands/migrate/migrate_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
from typing import List, Optional

from protostar.cli import Command
from protostar.commands.deploy import DeployCommand
from protostar.commands.test.test_environment_exceptions import CheatcodeException
from protostar.migrator import Migrator
from protostar.protostar_exception import ProtostarException
from protostar.utils.input_requester import InputRequester
from protostar.utils.log_color_provider import LogColorProvider
from protostar.commands.deploy import DeployCommand


class MigrateCommand(Command):
Expand Down Expand Up @@ -69,8 +69,8 @@ def arguments(self) -> List[Command.Argument]:
DeployCommand.network_arg,
]

async def run(self, args):
await self.migrate(
async def run(self, args) -> Optional[Migrator.History]:
return await self.migrate(
migration_file_path=args.path,
rollback=args.rollback,
network=args.network or args.gateway_url,
Expand Down Expand Up @@ -114,8 +114,10 @@ async def migrate(
migrator.save_history(
migrator_history,
migration_file_basename=Path(migration_file_path).stem,
output_dir_path=output_dir_path,
output_dir_relative_path=output_dir_path,
)
self._logger.info("Migration completed")

return migrator_history
except CheatcodeException as ex:
raise ProtostarException(str(ex)) from ex
13 changes: 7 additions & 6 deletions protostar/composition_root.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import List
from typing import List, Optional

from protostar.cli import Command
from protostar.commands import (
Expand Down Expand Up @@ -55,13 +55,12 @@ class DIContainer:


# pylint: disable=too-many-locals
def build_di_container(script_root: Path):
def build_di_container(script_root: Path, cwd: Optional[Path] = None):
cwd = cwd or Path()
logger = getLogger()
protostar_toml_path = search_upwards_protostar_toml_path(
start_path=Path().resolve()
)
protostar_toml_path = search_upwards_protostar_toml_path(start_path=cwd.resolve())
project_root_path = (
protostar_toml_path.parent if protostar_toml_path is not None else Path()
protostar_toml_path.parent if protostar_toml_path is not None else cwd
)
protostar_toml_path = protostar_toml_path or project_root_path / "protostar.toml"
protostar_directory = ProtostarDirectory(script_root)
Expand Down Expand Up @@ -112,6 +111,7 @@ def build_di_container(script_root: Path):
protostar_toml_writer,
version_manager,
),
cwd=cwd,
),
BuildCommand(project_compiler, logger),
InstallCommand(
Expand Down Expand Up @@ -152,6 +152,7 @@ def build_di_container(script_root: Path):
migrator_builder=Migrator.Builder(
migrator_execution_environment_builder=MigratorExecutionEnvironment.Builder(),
gateway_facade_builder=GatewayFacade.Builder(project_root_path),
cwd=project_root_path,
kasperski95 marked this conversation as resolved.
Show resolved Hide resolved
),
requester=requester,
logger=logger,
Expand Down
18 changes: 13 additions & 5 deletions protostar/migrator/migrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from protostar.migrator.migrator_execution_environment import (
MigratorExecutionEnvironment,
)

from protostar.starknet_gateway.gateway_facade import GatewayFacade
from protostar.starknet_gateway.starknet_request import StarknetRequest
from protostar.utils.log_color_provider import LogColorProvider
Expand All @@ -29,6 +28,7 @@ def __init__(
self,
migrator_execution_environment_builder: MigratorExecutionEnvironment.Builder,
gateway_facade_builder: GatewayFacade.Builder,
cwd: Optional[Path] = None,
) -> None:
self._migrator_execution_environment_builder = (
migrator_execution_environment_builder
Expand All @@ -39,6 +39,7 @@ def __init__(
self._migrator_execution_environment_config = (
MigratorExecutionEnvironment.Config()
)
self._cwd = cwd

def set_logger(
self, logger: Logger, log_color_provider: LogColorProvider
Expand Down Expand Up @@ -72,12 +73,16 @@ async def build(self, migration_file_path: Path):
)
)

return Migrator(migrator_execution_environment=migrator_execution_env)
return Migrator(
migrator_execution_environment=migrator_execution_env, cwd=self._cwd
)

def __init__(
self,
migrator_execution_environment: MigratorExecutionEnvironment,
cwd: Optional[Path] = None,
) -> None:
self._cwd = cwd or Path()
self._migrator_execution_environment = migrator_execution_environment

async def run(self, rollback=False) -> History:
Expand All @@ -90,16 +95,19 @@ async def run(self, rollback=False) -> History:
starknet_requests=self._migrator_execution_environment.cheatcode_factory.gateway_facade.get_starknet_requests()
)

@staticmethod
def save_history(
self,
history: History,
migration_file_basename: str,
output_dir_path: Path,
output_dir_relative_path: Path,
):
output_dir_path = self._cwd / output_dir_relative_path
prefix = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S")
output_file_path = output_dir_path / f"{prefix}_{migration_file_basename}.json"

if not output_dir_path.exists():
output_dir_path.mkdir(parents=True)
output_dir_path.mkdir(
parents=True,
)

history.save_as_json(output_file_path)
11 changes: 8 additions & 3 deletions protostar/migrator/migrator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@
from pathlib import Path

from freezegun import freeze_time
from pytest_mock import MockerFixture

from protostar.migrator.migrator import Migrator
from protostar.starknet_gateway.starknet_request import StarknetRequest


@freeze_time("2022-04-02 21:37:42")
def test_migrator_saves_result_successfully_with_proper_name(tmp_path: Path):
Migrator.save_history(
def test_migrator_saves_result_successfully_with_proper_name(
mocker: MockerFixture, tmp_path: Path
):
migrator = Migrator(migrator_execution_environment=mocker.MagicMock())

migrator.save_history(
history=Migrator.History(
starknet_requests=[
StarknetRequest(
Expand All @@ -18,7 +23,7 @@ def test_migrator_saves_result_successfully_with_proper_name(tmp_path: Path):
]
),
migration_file_basename="01_init",
output_dir_path=tmp_path,
output_dir_relative_path=tmp_path,
)

assert "20220402213742_01_init.json" in listdir(tmp_path)
4 changes: 1 addition & 3 deletions protostar/protostar_toml/io/protostar_toml_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ def _read_if_cache_miss(self) -> Dict[str, Any]:
return self._cache

if not self.path.is_file():
raise NoProtostarProjectFoundException(
"No protostar.toml found in the working directory"
)
raise NoProtostarProjectFoundException("`protostar.toml` not found")

with open(self.path, "rb") as protostar_toml_file:
protostar_toml_dict = tomli.load(protostar_toml_file)
Expand Down
15 changes: 8 additions & 7 deletions protostar/starknet_gateway/gateway_facade.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import dataclasses
from logging import Logger
from pathlib import Path
from typing import Callable, List, Optional
import dataclasses

from starkware.starknet.services.api.gateway.transaction import DECLARE_SENDER_ADDRESS
from starkware.starknet.definitions import constants
from typing import Any, Callable, Dict, List, Optional, Union

from starknet_py.net.gateway_client import GatewayClient
from starknet_py.transactions.deploy import make_deploy_tx
from starknet_py.transactions.declare import make_declare_tx
from starknet_py.net.models import StarknetChainId
from starknet_py.transactions.declare import make_declare_tx
from starknet_py.transactions.deploy import make_deploy_tx
from starkware.starknet.definitions import constants
from starkware.starknet.services.api.gateway.transaction import DECLARE_SENDER_ADDRESS

from protostar.protostar_exception import ProtostarException
from protostar.starknet_gateway.gateway_response import (
Expand All @@ -19,6 +18,8 @@
from protostar.starknet_gateway.starknet_request import StarknetRequest
from protostar.utils.log_color_provider import LogColorProvider

GatewayFacadeSupportedInputType = Union[List[int], Dict[str, Any]]
kasperski95 marked this conversation as resolved.
Show resolved Hide resolved


class TransactionException(ProtostarException):
pass
Expand Down
2 changes: 1 addition & 1 deletion protostar/starknet_gateway/starknet_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

@dataclass
class StarknetRequest:
Action = Literal["DEPLOY", "DECLARE"]
Action = Literal["DEPLOY", "DECLARE", "CALL"]
kasperski95 marked this conversation as resolved.
Show resolved Hide resolved
Payload = Dict[str, Union[None, str, int, List[int], List[str]]]

action: Action
Expand Down
2 changes: 1 addition & 1 deletion protostar/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@


def main(script_root: Path):
container = build_di_container(script_root)
container = build_di_container(script_root, cwd=Path())
arg_parser = build_parser(container.protostar_cli, container.protostar_toml_reader)
args = parse_args(arg_parser)
run_protostar(container.protostar_cli, args, arg_parser)
Expand Down
2 changes: 1 addition & 1 deletion scripts/generate_reference_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from protostar.composition_root import build_di_container

CLI_REFERENCE_MARKDOWN_CONTENT = ReferenceDocsGenerator(
build_di_container(Path()).protostar_cli
build_di_container(script_root=Path()).protostar_cli
).generate_cli_reference_markdown()

ReferenceDocsGenerator.save_to_markdown_file(
Expand Down
2 changes: 1 addition & 1 deletion scripts/generate_reference_docs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


def test_instance_matches_cli_reference_docs():
di_container = build_di_container(Path())
di_container = build_di_container(script_root=Path(), cwd=Path())
new_snapshot = ReferenceDocsGenerator(
di_container.protostar_cli
).generate_cli_reference_markdown()
Expand Down
8 changes: 8 additions & 0 deletions tests/data/contracts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
IDENTITY_CONTRACT = """
%lang starknet

@view
func identity(arg) -> (res : felt):
return (arg)
end
"""
Loading