Skip to content
This repository has been archived by the owner on Dec 15, 2023. It is now read-only.

Improve logging #487

Merged
merged 18 commits into from
Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 8 additions & 5 deletions page/docs/guide/run.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,19 @@ Installing the package adds the `starknet-devnet` command.
<!-- Developer note: the following section should be a copy-paste of `starknet-devnet --help` -->

```text
usage: starknet-devnet [-h] [-v] [--host HOST] [--port PORT] [--load-path LOAD_PATH] [--dump-path DUMP_PATH] [--dump-on DUMP_ON]
usage: starknet-devnet [-h] [-v] [--verbose] [--host HOST] [--port PORT] [--load-path LOAD_PATH] [--dump-path DUMP_PATH] [--dump-on DUMP_ON]
[--lite-mode] [--blocks-on-demand] [--accounts ACCOUNTS] [--initial-balance INITIAL_BALANCE] [--seed SEED]
[--hide-predeployed-accounts] [--start-time START_TIME] [--gas-price GAS_PRICE] [--allow-max-fee-zero]
[--hide-predeployed-contracts] [--start-time START_TIME] [--gas-price GAS_PRICE] [--allow-max-fee-zero]
[--timeout TIMEOUT] [--account-class ACCOUNT_CLASS] [--fork-network FORK_NETWORK] [--fork-block FORK_BLOCK]
[--fork-retries FORK_RETRIES] [--chain-id CHAIN_ID] [--disable-rpc-request-validation]
[--disable-rpc-response-validation]
[--disable-rpc-response-validation] [--hide-server-logs]

Run a local instance of Starknet Devnet

optional arguments:
-h, --help show this help message and exit
-v, --version Print the version
--verbose Show more verbose output. Has higher priority than --hide-server-logs and --hide-predeployed-contracts
--host HOST Specify the address to listen at; defaults to 127.0.0.1 (use the address the program outputs on start)
--port PORT, -p PORT Specify the port to listen at; defaults to 5050
--load-path LOAD_PATH
Expand All @@ -34,8 +35,8 @@ optional arguments:
--initial-balance INITIAL_BALANCE, -e INITIAL_BALANCE
Specify the initial balance of accounts to be predeployed; defaults to 1e+21
--seed SEED Specify the seed for randomness of accounts to be predeployed
--hide-predeployed-accounts
Prevents from printing the predeployed accounts details
--hide-predeployed-contracts, --hide-predeployed-accounts
Prevents from printing the predeployed contracts details. Argument --hide-predeployed-accounts is deprecated
--start-time START_TIME
Specify the start time of the genesis block in Unix time seconds
--gas-price GAS_PRICE, -g GAS_PRICE
Expand All @@ -60,6 +61,8 @@ optional arguments:
Specify the path to the manifest (Cargo.toml) of the Cairo 1.0 compiler to be used for contract recompilation; if omitted, the default x86-compatible compiler (from cairo-lang package) is used
--sierra-compiler-path SIERRA_COMPILER_PATH
Specify the path to the binary executable of starknet-sierra-compile

--hide-server-logs Hide server access logging
```

<!-- Developer note: the previous section should be a copy-paste of `starknet-devnet --help` -->
Expand Down
10 changes: 10 additions & 0 deletions starknet_devnet/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Account class and its predefined constants.
"""

import sys

from starkware.starknet.core.os.contract_address.contract_address import (
calculate_contract_address_from_hash,
)
Expand Down Expand Up @@ -58,3 +60,11 @@ async def _mimic_constructor(self):
)

await set_balance(starknet.state, self.address, self.initial_balance)

def print(self):
print("Account:")
print(f"Address: {hex(self.address)}")
print(f"Public key: {hex(self.public_key)}")
print(f"Private key: {hex(self.private_key)}")
print(f"Initial balance: {self.initial_balance} WEI")
sys.stdout.flush()
17 changes: 5 additions & 12 deletions starknet_devnet/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ def __init__(self, starknet_wrapper):
self.list = []

self.__generate()
if (
starknet_wrapper.config.accounts
and not starknet_wrapper.config.hide_predeployed_accounts
):
self.__print()

def __getitem__(self, index) -> Account:
return self.list[index]
Expand All @@ -43,6 +38,11 @@ async def deploy(self):
"""deploy listed accounts"""
for account in self.list:
await account.deploy()
if self.starknet_wrapper.config.accounts and (
self.starknet_wrapper.config.verbose
or not self.starknet_wrapper.config.hide_predeployed_contracts
):
self.__print()

def add(self, account):
"""append account to list"""
Expand Down Expand Up @@ -70,13 +70,6 @@ def __generate(self):

def __print(self):
"""stdout accounts list"""
for idx, account in enumerate(self):
print(f"Account #{idx}")
print(f"Address: {hex(account.address)}")
print(f"Public key: {hex(account.public_key)}")
print(f"Private key: {hex(account.private_key)}\n")

print(f"Initial balance of each account: {self.__initial_balance} WEI")
print("Seed to replicate this account sequence:", self.__seed)
warn(
"WARNING: Use these accounts and their keys ONLY for local testing. "
Expand Down
4 changes: 4 additions & 0 deletions starknet_devnet/blueprints/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from starknet_devnet.util import (
StarknetDevnetException,
check_valid_dump_path,
log_request,
parse_hex_string,
)

Expand Down Expand Up @@ -126,6 +127,7 @@ def load():


@base.route("/increase_time", methods=["POST"])
@log_request()
async def increase_time():
"""Increases the block timestamp offset and generates a new block"""
request_dict = request.json or {}
Expand All @@ -147,6 +149,7 @@ async def increase_time():


@base.route("/set_time", methods=["POST"])
@log_request()
async def set_time():
"""Sets the block timestamp offset and generates a new block"""
request_dict = request.json or {}
Expand Down Expand Up @@ -190,6 +193,7 @@ async def get_fee_token():


@base.route("/mint", methods=["POST"])
@log_request()
async def mint():
"""Mint token and transfer to the provided address"""
request_json = request.json or {}
Expand Down
3 changes: 2 additions & 1 deletion starknet_devnet/blueprints/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@

from starknet_devnet.devnet_config import DumpOn
from starknet_devnet.state import state
from starknet_devnet.util import StarknetDevnetException, fixed_length_hex
from starknet_devnet.util import StarknetDevnetException, fixed_length_hex, log_request

from .shared import validate_transaction

gateway = Blueprint("gateway", __name__, url_prefix="/gateway")


@gateway.route("/add_transaction", methods=["POST"])
@log_request()
async def add_transaction():
"""Endpoint for accepting (state-changing) transactions."""

Expand Down
15 changes: 7 additions & 8 deletions starknet_devnet/blueprints/rpc/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
)
from starknet_devnet.constants import LEGACY_TX_VERSION
from starknet_devnet.state import state
from starknet_devnet.util import StarknetDevnetException
from starknet_devnet.util import StarknetDevnetException, log_request


@validate_schema("getTransactionByHash")
Expand Down Expand Up @@ -102,21 +102,21 @@ async def pending_transactions() -> List[RpcTransaction]:


@validate_schema("addInvokeTransaction")
@log_request(rpc=True)
async def add_invoke_transaction(invoke_transaction: RpcBroadcastedInvokeTxn) -> dict:
"""
Submit a new transaction to be added to the chain
"""
invoke_function = make_invoke_function(invoke_transaction)

_, transaction_hash = await state.starknet_wrapper.invoke(
external_tx=invoke_function
external_tx=make_invoke_function(invoke_transaction)
)
return RpcInvokeTransactionResult(
transaction_hash=rpc_felt(transaction_hash),
)


@validate_schema("addDeclareTransaction")
@log_request(rpc=True)
async def add_declare_transaction(
declare_transaction: RpcBroadcastedDeclareTxn,
) -> dict:
Expand Down Expand Up @@ -148,16 +148,15 @@ async def add_declare_transaction(


@validate_schema("addDeployAccountTransaction")
@log_request(rpc=True)
async def add_deploy_account_transaction(
deploy_account_transaction: RpcBroadcastedDeployAccountTxn,
) -> dict:
"""
Submit a new deploy account transaction
"""
deploy_account_tx = make_deploy_account(deploy_account_transaction)

contract_address, transaction_hash = await state.starknet_wrapper.deploy_account(
external_tx=deploy_account_tx
(contract_address, transaction_hash,) = await state.starknet_wrapper.deploy_account(
external_tx=make_deploy_account(deploy_account_transaction)
)

status_response = await state.starknet_wrapper.transactions.get_transaction_status(
Expand Down
3 changes: 3 additions & 0 deletions starknet_devnet/chargeable_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,6 @@ def __init__(self, starknet_wrapper):
initial_balance=2**251, # loads of cash
account_class_wrapper=starknet_wrapper.config.account_class,
)

def print(self):
pass
39 changes: 34 additions & 5 deletions starknet_devnet/devnet_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
FeederGatewayClient,
)

from starknet_devnet.util import suppress_feeder_gateway_client_logger
from starknet_devnet.util import suppress_feeder_gateway_client_logger, warn

from . import __version__
from .constants import (
Expand Down Expand Up @@ -210,6 +210,23 @@ def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, value)


class WarnIfDeprecatedArgumentAction(argparse.Action):
"""
Action to warn if user uses old flag;
"""

def __init__(self, nargs=0, **kw):
super().__init__(nargs=nargs, **kw)

def __call__(self, parser, namespace, values, option_string=None):
if option_string == "--hide-predeployed-accounts":
warn(
"WARNING: Argument --hide-predeployed-accounts is deprecated; applying --hide-predeployed-contracts instead",
file=sys.stderr,
)
setattr(namespace, self.dest, True)


def _assert_valid_compiler(command: List[str]):
"""Assert user machine can compile with cairo 1"""
check = subprocess.run(
Expand Down Expand Up @@ -264,6 +281,16 @@ def parse_args(raw_args: List[str]):
action="version",
version=__version__,
)
parser.add_argument(
"--verbose",
action="store_true",
help="Show more verbose output. Has higher priority than --hide-server-logs and --hide-predeployed-contracts",
)
parser.add_argument(
"--hide-server-logs",
action="store_true",
help="Hide server access logging",
)
parser.add_argument(
"--host",
help=f"Specify the address to listen at; defaults to {DEFAULT_HOST} "
Expand Down Expand Up @@ -317,9 +344,10 @@ def parse_args(raw_args: List[str]):
help="Specify the seed for randomness of accounts to be predeployed",
)
parser.add_argument(
"--hide-predeployed-accounts",
FabijanC marked this conversation as resolved.
Show resolved Hide resolved
action="store_true",
help="Prevents from printing the predeployed accounts details",
"--hide-predeployed-contracts",
"--hide-predeployed-accounts", # for backwards compatibility
action=WarnIfDeprecatedArgumentAction,
help="Prevents from printing the predeployed contracts details. Argument --hide-predeployed-accounts is deprecated",
)
parser.add_argument(
"--start-time",
Expand Down Expand Up @@ -437,11 +465,12 @@ def __init__(self, args: argparse.Namespace = None):
self.lite_mode = self.args.lite_mode
self.blocks_on_demand = self.args.blocks_on_demand
self.account_class = self.args.account_class
self.hide_predeployed_accounts = self.args.hide_predeployed_accounts
self.hide_predeployed_contracts = self.args.hide_predeployed_contracts
self.fork_network = self.args.fork_network
self.fork_block = self.args.fork_block
self.chain_id = self.args.chain_id
self.validate_rpc_requests = not self.args.disable_rpc_request_validation
self.validate_rpc_responses = not self.args.disable_rpc_response_validation
self.cairo_compiler_manifest = self.args.cairo_compiler_manifest
self.sierra_compiler_path = self.args.sierra_compiler_path
self.verbose = self.args.verbose
19 changes: 17 additions & 2 deletions starknet_devnet/fee_token.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
Fee token and its predefined constants.
"""
import pprint
import sys

from starkware.solidity.utils import load_nearby_contract
from starkware.starknet.business_logic.transaction.objects import InternalInvokeFunction
Expand All @@ -16,7 +18,7 @@
from starknet_devnet.chargeable_account import ChargeableAccount
from starknet_devnet.constants import SUPPORTED_TX_VERSION
from starknet_devnet.predeployed_contract_wrapper import PredeployedContractWrapper
from starknet_devnet.util import Uint256, str_to_felt
from starknet_devnet.util import Uint256, logger, str_to_felt


class FeeToken(PredeployedContractWrapper):
Expand Down Expand Up @@ -131,14 +133,27 @@ async def mint(self, to_address: int, amount: int, lite: bool):

tx_hash = None
transaction = await self.get_mint_transaction(to_address, amount_uint256)
logger.info(transaction)
starknet: Starknet = self.starknet_wrapper.starknet
if lite:
internal_tx = InternalInvokeFunction.from_external(
transaction, starknet.state.general_config
)
await starknet.state.execute_tx(internal_tx)
execution_info = await starknet.state.execute_tx(internal_tx)
logger.info(
"transaction execution info: %s", pprint.pformat(execution_info.dump())
FabijanC marked this conversation as resolved.
Show resolved Hide resolved
)
else:
# execution info logs inside starknet_wrapper.invoke call
_, tx_hash_int = await self.starknet_wrapper.invoke(transaction)
tx_hash = hex(tx_hash_int)

return tx_hash

def print(self):
print("")
print("Predeployed FeeToken")
print(f"Address: {hex(self.address)}")
print(f"Class Hash: {hex(self.class_hash)}")
print(f"Symbol: {self.SYMBOL}\n")
sys.stdout.flush()
10 changes: 10 additions & 0 deletions starknet_devnet/predeployed_contract_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,13 @@ async def deploy(self):
abi=self.contract_class.abi,
contract_address=self.address,
)

if (
self.starknet_wrapper.config.verbose
or not self.starknet_wrapper.config.hide_predeployed_contracts
):
self.print()

def print(self):
"Prints contract info"
raise NotImplementedError()
7 changes: 4 additions & 3 deletions starknet_devnet/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,15 @@ def load_config(self):
{
"loggers": {
"gunicorn.error": {
# Disable info messages like "Starting gunicorn"
"level": "WARNING",
"level": "INFO" if self.args.verbose else "WARNING",
"handlers": ["error_console"],
"propagate": False,
"qualname": "gunicorn.error",
},
"gunicorn.access": {
"level": "INFO",
"level": "INFO"
if self.args.verbose or not self.args.hide_server_logs
else "WARNING",
# Log access to stderr to maintain backward compatibility
"handlers": ["error_console"],
"propagate": False,
Expand Down
Loading