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

feat(katana): non-interactive init #2988

Merged
merged 1 commit into from
Feb 3, 2025
Merged

feat(katana): non-interactive init #2988

merged 1 commit into from
Feb 3, 2025

Conversation

kariy
Copy link
Member

@kariy kariy commented Feb 3, 2025

If no arguments are provided, katana init retains its interactive prompt (current behavior). This PR adds a non-interactive flow where all required values can be passed directly via CLI options to skip the prompts.

$ katana init
Initialize chain

Usage: katana init [OPTIONS]

Options:
      --id <ID>
      --settlement-chain <SETTLEMENT_CHAIN>
      --settlement-account-address <SETTLEMENT_ACCOUNT>
      --settlement-account-private-key <SETTLEMENT_ACCOUNT_PRIVATE_KEY>
      --settlement-contract <SETTLEMENT_CONTRACT>
  -h, --help                                                             Print help

Copy link

coderabbitai bot commented Feb 3, 2025

Ohayo sensei!

Walkthrough

This pull request introduces several asynchronous enhancements and refactors across CLI components. A new dependency (url.workspace = true) is added, and the initialization process is significantly updated. The InitArgs struct now includes additional optional fields with corresponding logic changes, and its execution method has been converted to asynchronous. A new prompt function facilitates interactive Starknet rollup chain configuration. Furthermore, asynchronous execution has been integrated into the CLI core via new functions (execute_async and build_tokio_runtime) and an updated NodeArgs execution.

Changes

File(s) Change Summary
bin/katana/Cargo.toml Added dependency declaration for the url crate with the workspace flag.
bin/katana/src/cli/init/{mod.rs, prompt.rs} Expanded InitArgs with new optional fields; converted the execute method to async returning anyhow::Result<()>; introduced the SettlementChain enum and corresponding error handling; replaced the old prompt with a unified process_args method; added async prompt functionality and unit tests.
bin/katana/src/cli/mod.rs, crates/katana/cli/src/args.rs Introduced asynchronous command execution by adding execute_async and build_tokio_runtime functions; updated CLI command handling in run and converted NodeArgs::execute to async by awaiting internal asynchronous calls.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant P as Prompt Module
    participant RPC as JSON RPC Client
    participant O as Outcome Constructor

    U->>P: Enter chain ID & select settlement option
    P->>RPC: Validate settlement RPC URL & contract
    RPC-->>P: Return validation result
    P->>U: Request account address and private key
    U->>P: Submit account info
    P->>O: Construct Outcome with config details
    O-->>P: Outcome ready
    P-->>U: Return Outcome
Loading
sequenceDiagram
    participant CLI as CLI Runner
    participant RT as Tokio Runtime
    participant CMD as Command

    CLI->>RT: execute_async(command.execute())
    RT->>CMD: Process command asynchronously
    CMD-->>RT: Return command result
    RT-->>CLI: Deliver result
Loading

Possibly related PRs


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
bin/katana/src/cli/mod.rs (2)

68-70: Ohayo sensei, consider customizing error messages.
execute_async is clear, but if build_tokio_runtime fails, it might help to provide a more detailed error log or fallback strategy.


72-74: Ohayo sensei, reviewing multi-thread runtime.
new_multi_thread() is a solid default, but some users may require explicit thread-count control.

bin/katana/src/cli/init/prompt.rs (1)

80-88: Ohayo sensei, well-done with the private key input.
Consider using a masked input or specialized widget to safeguard sensitive info from shoulder surfers.

bin/katana/src/cli/init/mod.rs (3)

51-56: Ohayo sensei, moving execute to async is a good step for concurrency.
Just ensure that potential blocking calls (e.g., file I/O) are carefully handled with async I/O if needed.


92-122: Ohayo sensei, defensive checks on existing vs. newly deployed contracts.
Verifying the contract program info is a good security measure. Recommended to wrap any unavoidable unwrap() in more descriptive errors if there's an edge case.


163-168: Ohayo sensei, enumerating settlement chain variants.
Well-structured for expansions. Possibly consider an Off chain or a more advanced scenario in future.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e823d42 and d9d920e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • bin/katana/Cargo.toml (1 hunks)
  • bin/katana/src/cli/init/mod.rs (4 hunks)
  • bin/katana/src/cli/init/prompt.rs (1 hunks)
  • bin/katana/src/cli/mod.rs (3 hunks)
  • crates/katana/cli/src/args.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (18)
bin/katana/src/cli/mod.rs (4)

1-2: Ohayo sensei, nice addition for async support!
Bringing in Future from the standard library paves the way for concurrency-savvy CLI commands.


8-8: Ohayo sensei, good job using tokio::runtime::Runtime for concurrency.
This is essential for asynchronous tasks.


30-31: Ohayo sensei, verify error handling on async command.
Wrapping the Init command in execute_async is a sound approach. Ensure any panics inside args.execute() are gracefully handled.


35-35: Ohayo sensei, consistent async strategy.
The same execute_async usage keeps the code uniform. Looks good!

bin/katana/src/cli/init/prompt.rs (4)

19-31: Ohayo sensei, user input for chain_id is well-defined.
Validating ASCII ensures a clean chain identifier. Consider clarifying if uppercase vs. lowercase matters.


33-53: Ohayo sensei, settlement chain selection logic looks good.
The dynamic #[cfg(feature = "init-custom-settlement-chain")] approach is neat. It's easy to extend in the future for more settlement chains.


98-119: Ohayo sensei, mindful deployment logic.
Deploying vs re-using a settlement contract is straightforward. Confirm that the deployment instructions have thorough retry or crash recovery steps in production scenarios.


121-128: Ohayo sensei, final Outcome structure is clear and well-organized.
Great job consolidating user inputs here for easy consumption downstream.

bin/katana/src/cli/init/mod.rs (8)

26-46: Ohayo sensei, nice usage of requires_all in InitArgs.
This elegantly ensures that the user either provides all settlement-related arguments or none.


59-63: Ohayo sensei, settlement layer struct usage is intuitive.
Neatly compartmentalizes chain ID, account, and contract.


76-90: Ohayo sensei, process_args gating logic is robust!
Clap's requires_all helps, but double-check all side effects if partial arguments are supplied.


130-145: Ohayo sensei, Outcome struct is well-labeled.
Makes it easy to see which fields are used for settlement configuration and storing user-provided data.


157-161: Ohayo sensei, informative error type.
Mentioning the invalid chain ID in SettlementChainTryFromStrError is good for debugging.


170-185: Ohayo sensei, FromStr implementation is user-friendly.
This pattern elegantly captures recognized chain aliases or custom URLs, if the feature is enabled.


187-192: Ohayo sensei, bridging try_from is consistent.
No duplication of logic — nicely calls from_str.


194-230: Ohayo sensei, solid test coverage for SettlementChain.
Nice to see corner cases, including uppercase variants and invalid inputs. Continue adding more tests for dynamic use cases if required.

crates/katana/cli/src/args.rs (1)

116-119: Ohayo! The async implementation looks great, sensei!

The conversion of execute to an async function is well-implemented, properly awaiting the start_node call.

bin/katana/Cargo.toml (1)

35-35: Ohayo! Good choice with the url crate, sensei!

Using the workspace-managed url crate is a solid choice for URL handling and maintains version consistency across the project.

Comment on lines +67 to +79
let contract_exist_parser = &|input: &str| {
let block_id = BlockId::Tag(BlockTag::Pending);
let address = Felt::from_str(input).map_err(|_| ())?;
let result = tokio::task::block_in_place(|| {
Handle::current().block_on(l1_provider.clone().get_class_hash_at(block_id, address))
});

match result {
Ok(..) => Ok(ContractAddress::from(address)),
Err(..) => Err(()),
}
};

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Ohayo sensei, blocking within block_in_place can stall other tasks.
To avoid blocking the entire thread pool, consider a non-blocking approach, such as fully async calls without block_in_place.

- let result = tokio::task::block_in_place(|| {
-     Handle::current().block_on(l1_provider.clone().get_class_hash_at(block_id, address))
- });
+ let result = l1_provider
+     .clone()
+     .get_class_hash_at(block_id, address)
+     .await;

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Feb 3, 2025

Codecov Report

Attention: Patch coverage is 19.87578% with 129 lines in your changes missing coverage. Please review.

Project coverage is 56.97%. Comparing base (e823d42) to head (d9d920e).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
bin/katana/src/cli/init/prompt.rs 0.00% 72 Missing ⚠️
bin/katana/src/cli/init/mod.rs 41.02% 46 Missing ⚠️
bin/katana/src/cli/mod.rs 0.00% 9 Missing ⚠️
crates/katana/cli/src/args.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2988      +/-   ##
==========================================
- Coverage   56.99%   56.97%   -0.02%     
==========================================
  Files         425      426       +1     
  Lines       56303    56376      +73     
==========================================
+ Hits        32088    32120      +32     
- Misses      24215    24256      +41     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@kariy kariy merged commit bf0c5ee into main Feb 3, 2025
13 of 15 checks passed
@kariy kariy deleted the katana/init-args branch February 3, 2025 20:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant