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 8 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
311 changes: 311 additions & 0 deletions log

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion page/docs/guide/accounts.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ sidebar_position: 13

## Predeployed accounts

Devnet predeploys `--accounts` with some `--initial-balance`. To hide the details of these accounts use `--hide-predeployed-accounts`. The accounts get charged for transactions according to the `--gas-price`. A `--seed` can be used to regenerate the same set of accounts. Read more about it in the [Run section](run.md).
Devnet predeploys `--accounts` with some `--initial-balance`. To hide the details of these accounts use `--hide-predeployed-contracts`. The accounts get charged for transactions according to the `--gas-price`. A `--seed` can be used to regenerate the same set of accounts. Read more about it in the [Run section](run.md).
FabijanC marked this conversation as resolved.
Show resolved Hide resolved

To get the code of the account (currently OpenZeppelin [v0.5.1](https://github.com/OpenZeppelin/cairo-contracts/releases/tag/v0.5.1)), use one of the following:

Expand Down
13 changes: 8 additions & 5 deletions page/docs/guide/run.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ sidebar_position: 1
Installing the package adds the `starknet-devnet` command.

```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-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 logs
--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 @@ -32,8 +33,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
Prevents from printing the predeployed contracts details
--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 @@ -58,6 +59,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-logs Hide access info logging
```

You can run `starknet-devnet` in a separate shell, or you can run it in background with `starknet-devnet &`.
Expand Down
2 changes: 1 addition & 1 deletion scripts/test_fork.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ PORT2=5050
DEVNET2_URL="http://$HOST:$PORT2"


poetry run starknet-devnet --host "$HOST" --port "$PORT1" --seed 42 --accounts 1 --hide-predeployed-accounts &
poetry run starknet-devnet --host "$HOST" --port "$PORT1" --seed 42 --accounts 1 --hide-predeployed-contracts &
DEVNET1_PID=$!
curl --retry 20 --retry-delay 1 --retry-connrefused -s -o /dev/null "$DEVNET1_URL/is_alive"
echo "Started up devnet1; pid: $DEVNET1_PID"
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
8 changes: 6 additions & 2 deletions starknet_devnet/blueprints/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Base routes
"""

from flask import Blueprint, Response, jsonify, request
from starkware.starkware_utils.error_handling import StarkErrorCode

Expand All @@ -9,6 +10,7 @@
from starknet_devnet.util import (
StarknetDevnetException,
check_valid_dump_path,
log_request,
parse_hex_string,
)

Expand Down Expand Up @@ -126,6 +128,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 +150,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,19 +194,19 @@ 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 {}

address = hex_converter(request_json, "address")
amount = extract_positive(request_json, "amount")
is_lite = request_json.get("lite", False)

tx_hash = await state.starknet_wrapper.fee_token.mint(
to_address=address, amount=amount, lite=is_lite
)

new_balance = await state.starknet_wrapper.fee_token.get_balance(address)

return jsonify({"new_balance": new_balance, "unit": "wei", "tx_hash": tx_hash})


Expand Down
13 changes: 7 additions & 6 deletions starknet_devnet/blueprints/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@
Gateway routes
"""


from flask import Blueprint, jsonify, request
from starkware.starknet.definitions.error_codes import StarknetErrorCode
from starkware.starknet.definitions.transaction_type import TransactionType
from starkware.starkware_utils.error_handling import StarkErrorCode

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."""

transaction = validate_transaction(request.get_data())
tx_type = transaction.tx_type

Expand All @@ -28,9 +29,10 @@ async def add_transaction():
}

if tx_type == TransactionType.DECLARE:
contract_class_hash, transaction_hash = await state.starknet_wrapper.declare(
transaction
)
(
FabijanC marked this conversation as resolved.
Show resolved Hide resolved
contract_class_hash,
transaction_hash,
) = await state.starknet_wrapper.declare(transaction)
response_dict["class_hash"] = hex(contract_class_hash)

elif tx_type == TransactionType.DEPLOY_ACCOUNT:
Expand Down Expand Up @@ -64,5 +66,4 @@ async def add_transaction():
# after tx
if state.dumper.dump_on == DumpOn.TRANSACTION:
state.dumper.dump()

return jsonify(response_dict)
18 changes: 7 additions & 11 deletions starknet_devnet/blueprints/rpc/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,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 @@ -100,21 +100,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 All @@ -123,7 +123,6 @@ async def add_declare_transaction(
"""
if int(declare_transaction["version"], 0) == LEGACY_TX_VERSION:
raise RpcError.from_spec_name("INVALID_CONTRACT_CLASS")

FabijanC marked this conversation as resolved.
Show resolved Hide resolved
class_hash, transaction_hash = await state.starknet_wrapper.declare(
external_tx=make_declare(declare_transaction)
)
Expand All @@ -138,24 +137,22 @@ async def add_declare_transaction(
and "is already declared" in error_message
):
raise RpcError.from_spec_name("CLASS_ALREADY_DECLARED")

return RpcDeclareTransactionResult(
transaction_hash=rpc_felt(transaction_hash),
class_hash=rpc_felt(class_hash),
)


@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 Expand Up @@ -211,5 +208,4 @@ async def estimate_fee(request: List[RpcBroadcastedTxn], block_id: BlockId) -> l
if "is not deployed" in ex.message:
raise RpcError.from_spec_name("CONTRACT_NOT_FOUND") from ex
raise RpcError(code=-1, message=ex.message) from ex

return rpc_fee_estimate(fee_response)
17 changes: 17 additions & 0 deletions starknet_devnet/chargeable_account.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""
Account that is charged with a fee when nobody else can be charged.
"""
import sys

from starknet_devnet.account import Account

from .util import warn


class ChargeableAccount(Account):
"""
Expand All @@ -23,3 +26,17 @@ def __init__(self, starknet_wrapper):
initial_balance=2**251, # loads of cash
account_class_wrapper=starknet_wrapper.config.account_class,
)

def print(self):
print("")
print("Predeployed chargeable 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 of chargeable account: {self.initial_balance} WEI")
warn(
"WARNING: Use these accounts and their keys ONLY for local testing. "
"DO NOT use them on mainnet or other live networks because you will LOSE FUNDS.\n",
file=sys.stderr,
)
sys.stdout.flush()
17 changes: 14 additions & 3 deletions starknet_devnet/devnet_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,16 @@ def parse_args(raw_args: List[str]):
action="version",
version=__version__,
)
parser.add_argument(
"--verbose",
action="store_true",
help="Show more verbose logs",
)
parser.add_argument(
"--hide-logs",
action="store_true",
help="Hide info logging",
FabijanC marked this conversation as resolved.
Show resolved Hide resolved
)
parser.add_argument(
"--host",
help=f"Specify the address to listen at; defaults to {DEFAULT_HOST} "
Expand Down Expand Up @@ -317,9 +327,9 @@ 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
"--hide-predeployed-contracts",
action="store_true",
help="Prevents from printing the predeployed accounts details",
help="Prevents from printing the predeployed contracts details",
)
parser.add_argument(
"--start-time",
Expand Down Expand Up @@ -437,11 +447,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
Loading