Skip to content
This repository has been archived by the owner on Jun 6, 2024. It is now read-only.

Commit

Permalink
Merge pull request #12 from unparalleled-js/chore/upgrade-starknet.py
Browse files Browse the repository at this point in the history
chore: upgrade starknet.py
  • Loading branch information
antazoey authored May 20, 2022
2 parents e635394 + b69c68e commit cd45fd9
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 35 deletions.
46 changes: 30 additions & 16 deletions ape_starknet/_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import re
from typing import Any, Union
from typing import Any, Optional, Union

from ape.api.networks import LOCAL_NETWORK_NAME
from ape.exceptions import AddressError, ApeException, ContractLogicError, ProviderError
from ape.exceptions import (
AddressError,
ApeException,
ContractLogicError,
ProviderError,
VirtualMachineError,
)
from ape.types import AddressType, RawAddress
from eth_typing import HexAddress, HexStr
from eth_utils import (
Expand Down Expand Up @@ -32,10 +38,10 @@ def get_chain_id(network_id: Union[str, int]) -> StarknetChainId:
if isinstance(network_id, int):
return StarknetChainId(network_id)

if network_id == LOCAL_NETWORK_NAME:
elif network_id == LOCAL_NETWORK_NAME:
return StarknetChainId.TESTNET # Use TESTNET chain ID for local network

if network_id not in NETWORKS:
elif network_id not in NETWORKS:
raise ValueError(f"Unknown network '{network_id}'.")

return StarknetChainId(NETWORKS[network_id][0])
Expand Down Expand Up @@ -87,19 +93,27 @@ def func(*args, **kwargs):
# Don't catch ApeExceptions, let them raise as they would.
raise
except Exception as err:
err_msg = str(err)
if "rejected" in err_msg:
if "Error message: " in err_msg:
err_msg = err_msg.split("Error message: ")[-1]
if "Error at pc=" in err_msg:
err_msg = err_msg.split("Error at pc=")[0]
elif "error_message=" in err_msg:
err_msg = err_msg.split("error_message=")[-1].strip("'")

# Fix escaping newline issue with error message.
err_msg = err_msg.replace("\\n", "")
raise ContractLogicError(revert_message=err_msg) from err
vm_error = get_virtual_machine_error(err)
if vm_error:
raise vm_error from err

raise # Original exception

return func


def get_virtual_machine_error(err: Exception) -> Optional[VirtualMachineError]:
err_msg = str(err)
if "rejected" not in err_msg:
return None

if "Error message: " in err_msg:
err_msg = err_msg.split("Error message: ")[-1]
if "Error at pc=" in err_msg:
err_msg = err_msg.split("Error at pc=")[0]
elif "error_message=" in err_msg:
err_msg = err_msg.split("error_message=")[-1].strip("'")

# Fix escaping newline issue with error message.
err_msg = err_msg.replace("\\n", "").strip()
return ContractLogicError(revert_message=err_msg)
6 changes: 5 additions & 1 deletion ape_starknet/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from ape.api import BlockAPI, ProviderAPI, ReceiptAPI, SubprocessProvider, TransactionAPI
from ape.api.networks import LOCAL_NETWORK_NAME
from ape.contracts import ContractInstance
from ape.exceptions import ProviderError, ProviderNotConnectedError
from ape.exceptions import ProviderError, ProviderNotConnectedError, VirtualMachineError
from ape.types import AddressType, BlockID, ContractLog
from ape.utils import cached_property
from ethpm_types import ContractType
Expand All @@ -26,6 +26,7 @@
ALPHA_MAINNET_WL_DEPLOY_TOKEN_KEY,
PLUGIN_NAME,
get_chain_id,
get_virtual_machine_error,
handle_client_errors,
)
from ape_starknet.config import StarknetConfig
Expand Down Expand Up @@ -241,6 +242,9 @@ def prepare_transaction(self, txn: TransactionAPI) -> TransactionAPI:

return txn

def get_virtual_machine_error(self, exception: Exception) -> VirtualMachineError:
return get_virtual_machine_error(exception) or VirtualMachineError(base_err=exception)

def _get_code(self, address: Union[str, AddressType]):
address_int = parse_address(address)
return self.starknet_client.get_code_sync(address_int)
Expand Down
6 changes: 4 additions & 2 deletions ape_starknet/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def get_balance(self, account: AddressType, token: str = "eth") -> int:
return 0

contract = self.provider.contract_at(contract_address)
if "balanceOf" in [m.name for m in contract._contract_type.view_methods]:

if "balanceOf" in [m.name for m in contract.contract_type.view_methods]:
return contract.balanceOf(account)[0]

# Handle proxy-implementation (not yet supported in ape-core)
Expand All @@ -69,7 +70,8 @@ def transfer(self, sender: int, receiver: int, amount: int, token: str = "eth"):

contract = self.provider.contract_at(contract_address)
sender_address = self.provider.network.ecosystem.decode_address(sender)
if "transfer" in [m.name for m in contract._contract_type.mutable_methods]:

if "transfer" in [m.name for m in contract.contract_type.mutable_methods]:
return contract.transfer(receiver, amount, sender=sender_address)

# Handle proxy-implementation (not yet supported in ape-core)
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@
"eth-ape>=0.2.4,<0.3.0",
"ethpm-types", # Use same as `eth-ape`.
"pydantic>=1.9.0,<2.0",
"starknet.py==0.2.2a0",
"starknet-devnet>=0.1.23",
"starknet.py>=0.2.3a0,<0.2.4",
"starknet-devnet>=0.2.1",
"importlib-metadata ; python_version<'3.8'",
], # NOTE: Add 3rd party libraries here
entry_points={"ape_cli_subcommands": ["ape_starknet=ape_starknet._cli:cli"]},
Expand Down
9 changes: 6 additions & 3 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List
from typing import List, Optional, Union

import pytest
from ape._cli import cli
Expand All @@ -17,11 +17,14 @@ def __init__(self, cli, base_cmd: List[str]):
self._cli = cli
self.base_cmd = base_cmd

def invoke(self, *cmd, input=None, ensure_successful: bool = True):
def invoke(
self, *cmd, input: Optional[Union[str, List[str]]] = None, ensure_successful: bool = True
):
input_str = "\n".join(input) if isinstance(input, list) else (input or "")
ape_cmd = self._get_cmd(*cmd)
catch_exceptions = not ensure_successful
result = self.runner.invoke(
self._cli, ape_cmd, catch_exceptions=catch_exceptions, input=input
self._cli, ape_cmd, catch_exceptions=catch_exceptions, input=input_str
)

if ensure_successful:
Expand Down
17 changes: 7 additions & 10 deletions tests/integration/test_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def test_delete(accounts_runner, existing_key_file_account):
EXISTING_KEY_FILE_ALIAS,
"--network",
"starknet:testnet",
input=f"{PASSWORD}\n",
input=PASSWORD,
)
assert EXISTING_KEY_FILE_ALIAS in output
output = accounts_runner.invoke("list")
Expand Down Expand Up @@ -93,7 +93,7 @@ def test_delete(accounts_runner, existing_key_file_account):
"starknet:testnet",
"--address",
CONTRACT_ADDRESS,
input=f"{PASSWORD}\n",
input=PASSWORD,
)


Expand All @@ -106,15 +106,14 @@ def test_import(accounts_runner, existing_key_file_account, account_container):
account_path.unlink()

private_key = str(CONTRACT_ADDRESS)
valid_input = f"{private_key}\n{PASSWORD}\n{PASSWORD}"
accounts_runner.invoke(
"import",
NEW_ALIAS,
"--network",
network,
"--address",
CONTRACT_ADDRESS,
input=valid_input,
input=[private_key, PASSWORD, PASSWORD],
)

# Clean-up
Expand All @@ -123,7 +122,7 @@ def test_import(accounts_runner, existing_key_file_account, account_container):
NEW_ALIAS,
"--network",
network,
input=f"{PASSWORD}\ny\n",
input=[PASSWORD, "y"],
)


Expand All @@ -140,7 +139,7 @@ def test_import_argent_x_key_file(accounts_runner, argent_x_backup, account_cont
alias,
"--keyfile",
str(argent_x_backup),
input=f"{PASSWORD}\n",
input=PASSWORD,
)
assert "SUCCESS" in output
account_path.unlink()
Expand All @@ -158,10 +157,8 @@ def test_core_accounts_list_all(root_accounts_runner, existing_key_file_account)
def test_change_password(accounts_runner, existing_key_file_account):
new_password = "321"
assert "SUCCESS" in accounts_runner.invoke(
"change-password",
EXISTING_KEY_FILE_ALIAS,
input=f"{PASSWORD}\n{new_password}\n{new_password}",
"change-password", EXISTING_KEY_FILE_ALIAS, input=[PASSWORD, new_password, new_password]
)
assert "SUCCESS" in accounts_runner.invoke(
"change-password", EXISTING_KEY_FILE_ALIAS, input=f"{new_password}\n{PASSWORD}\n{PASSWORD}"
"change-password", EXISTING_KEY_FILE_ALIAS, input=[new_password, PASSWORD, PASSWORD]
)
2 changes: 1 addition & 1 deletion tests/integration/test_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def test_console_accounts_object(ape_cli, console_runner, existing_key_file_acco
# NOTE: This console connects to Eth-Tester and makes sure we can still _read_
# starknet accounts.
output = console_runner.invoke(
input=f"accounts\naccounts['{existing_key_file_account.alias}']\nexit\n"
input=["accounts", "accounts['{existing_key_file_account.alias}']", "exit"]
)
assert existing_key_file_account.contract_address in output, [
e.name for e in networks.ecosystems
Expand Down

0 comments on commit cd45fd9

Please sign in to comment.