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): initialize slot paymaster account #3014

Merged
merged 4 commits into from
Feb 12, 2025

Conversation

kariy
Copy link
Member

@kariy kariy commented Feb 12, 2025

This is VERY slot-specific addition. This PR adds new arguments in the katana init command, essentially allowing to initialize # paymaster accounts in a slot-hosted katana. As such, it is gated under the init-slot feature (but currently is enabled by default) to avoid having separate binary builds.

To configure the paymasters, the --slot flag must be specified.

Usage:

katana init --slot --slot.paymasters 0x1,0x2,0x3

, where 0x1,0x2,0x3 are the public keys of the paymaster accounts. The number of public keys listed implicitly determine the total # of paymaster accounts to be pre-deployed.

The accounts use the same class hash, and salt as the default predeployed accounts in katana (as well as the master account in the default genesis created by katana init), where:-

Class hash: 0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2
Salt: 0x666

The contract addresses of the paymasters can be computed deterministically like so:

h(	
	CONTRACT_ADDRESS_PREFIX,
	deployer_address,
	salt,
	class_hash,
	h(public_key),
)

where h is the pedersen hash.

Summary by CodeRabbit

  • New Features

    • Introduced the init-slot feature for enhanced initialization options, allowing configuration of slot paymaster accounts during genesis setup.
    • Added a new module for managing paymaster accounts and included an interactive prompt for entering paymaster public keys, integrating these inputs into the genesis state.
    • Updated the default configuration to include the new init-slot functionality.
  • Chores

    • Removed an obsolete dependency to streamline project configuration.

Copy link

coderabbitai bot commented Feb 12, 2025

Ohayo sensei!

Walkthrough

This pull request introduces a new feature flag, init-slot, to the Katana CLI by modifying the Cargo.toml file and conditionally adding functionalities for managing slot paymaster accounts. Key updates include changes to argument parsing, genesis state generation, and user prompts for slot paymaster accounts. A new module named slot.rs is created to define structures and functions related to paymaster accounts. The CLI initialization flow has been adjusted to incorporate these changes based on the init-slot feature flag.

Changes

File(s) Change Summary
bin/katana/Cargo.toml Added init-slot feature to the default feature list; removed the lazy_static dependency.
bin/katana/src/cli/init/mod.rs Updated InitArgs to conditionally include a new slot field (of type SlotArgs); replaced process_args with configure_from_args; updated the Outcome struct to include a new slot_paymasters field; added generate_genesis function.
bin/katana/src/cli/init/prompt.rs Extended the prompt function to collect slot paymaster accounts and updated the Outcome struct to include slot-specific data, conditionally compiled under init-slot.
bin/katana/src/cli/init/slot.rs Introduced a new module for slot handling; added SlotArgs and PaymasterAccountArgs structs; implemented functions for parsing paymaster accounts and adding them to the genesis allocation; included corresponding tests.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as Init CLI
    participant Prompt as Prompt Function
    participant Slot as Slot Module
    participant Genesis as Genesis Generator
    participant User as User

    User->>CLI: Execute init command
    CLI->>Prompt: Invoke prompt for account inputs
    Prompt->>User: Request paymaster public key input (if init-slot enabled)
    User->>Prompt: Provide paymaster public keys
    Prompt->>CLI: Return slot paymaster data
    CLI->>Slot: Parse and add slot paymasters
    Slot->>Genesis: Update genesis state with paymaster accounts
    CLI->>User: Display updated genesis outcome
Loading

Possibly related PRs

  • refactor(cli): katana cli module  #2236: The changes in the main PR, which involve adding the init-slot feature and modifying the InitArgs struct, are related to the new module and structures introduced in this PR that also focus on command-line argument handling and struct modifications.
  • feat(katana): non-interactive init #2988: The changes in the main PR are related to the modifications in the InitArgs struct and its methods, which are also altered in this PR to enhance argument parsing capabilities, indicating a direct connection in their functionality.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d58776 and f2596cd.

📒 Files selected for processing (1)
  • bin/katana/src/cli/init/mod.rs (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • bin/katana/src/cli/init/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: ensure-wasm
  • GitHub Check: docs
  • GitHub Check: build

🪧 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 (2)
bin/katana/src/cli/init/slot.rs (1)

40-60: The implementation is solid, sensei! Consider adding documentation.

The function efficiently handles paymaster account creation. Adding rustdoc comments would improve maintainability.

+/// Adds paymaster accounts to the genesis state.
+///
+/// # Arguments
+/// * `genesis` - Mutable reference to the genesis state
+/// * `slot_paymasters` - Slice of paymaster account arguments
+///
+/// # Returns
+/// Vector of contract addresses for the added paymaster accounts
 pub fn add_paymasters_to_genesis(
     genesis: &mut Genesis,
     slot_paymasters: &[PaymasterAccountArgs],
 ) -> Vec<ContractAddress> {
bin/katana/src/cli/init/prompt.rs (1)

128-137: Add validation for duplicate public keys, sensei!

Consider checking for duplicate public keys to prevent unintended behavior.

     let mut slot_paymasters = Vec::new();
+    let mut seen_keys = std::collections::HashSet::new();
 
     while Confirm::new("Add slot paymaster account?").with_default(true).prompt()? {
         let public_key = CustomType::<Felt>::new("Paymaster public key")
             .with_formatter(&|input: Felt| format!("{input:#x}"))
             .prompt()?;
 
+        if !seen_keys.insert(public_key) {
+            println!("Warning: Duplicate public key detected");
+            continue;
+        }
         slot_paymasters.push(super::slot::PaymasterAccountArgs { public_key });
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a1b21bf and 278e710.

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

14-24: Ohayo! The SlotArgs struct looks good, sensei!

The struct is well-designed with appropriate constraints and documentation.

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

187-194: Clean implementation of genesis generation, sensei!

The function nicely encapsulates the genesis generation logic with appropriate defaults.

bin/katana/Cargo.toml (1)

43-43: Feature configuration looks good, sensei!

The init-slot feature is properly defined and included in the default features.

Also applies to: 46-46

Comment on lines 32 to 38
fn parse_paymaster_accounts_args(value: &str) -> Result<Vec<PaymasterAccountArgs>> {
let mut accounts = Vec::new();
for s in value.split(',') {
accounts.push(PaymasterAccountArgs { public_key: Felt::from_str(s)? });
}
Ok(accounts)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding input validation, sensei!

The parser should validate:

  • Empty input strings
  • Malformed public keys
  • Maximum number of paymaster accounts
 fn parse_paymaster_accounts_args(value: &str) -> Result<Vec<PaymasterAccountArgs>> {
+    if value.trim().is_empty() {
+        return Err(anyhow::anyhow!("Empty input string"));
+    }
     let mut accounts = Vec::new();
     for s in value.split(',') {
+        let s = s.trim();
+        if s.is_empty() {
+            return Err(anyhow::anyhow!("Empty public key in list"));
+        }
         accounts.push(PaymasterAccountArgs { public_key: Felt::from_str(s)? });
     }
+    if accounts.len() > 10 {  // Example limit
+        return Err(anyhow::anyhow!("Too many paymaster accounts"));
+    }
     Ok(accounts)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn parse_paymaster_accounts_args(value: &str) -> Result<Vec<PaymasterAccountArgs>> {
let mut accounts = Vec::new();
for s in value.split(',') {
accounts.push(PaymasterAccountArgs { public_key: Felt::from_str(s)? });
}
Ok(accounts)
}
fn parse_paymaster_accounts_args(value: &str) -> Result<Vec<PaymasterAccountArgs>> {
if value.trim().is_empty() {
return Err(anyhow::anyhow!("Empty input string"));
}
let mut accounts = Vec::new();
for s in value.split(',') {
let s = s.trim();
if s.is_empty() {
return Err(anyhow::anyhow!("Empty public key in list"));
}
accounts.push(PaymasterAccountArgs { public_key: Felt::from_str(s)? });
}
if accounts.len() > 10 { // Example limit
return Err(anyhow::anyhow!("Too many paymaster accounts"));
}
Ok(accounts)
}

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: 0

🧹 Nitpick comments (3)
bin/katana/src/cli/init/slot.rs (3)

26-30: Consider enhancing documentation, sensei!

The struct could benefit from additional documentation:

  • Valid format for public keys
  • Any constraints or limitations
  • Example usage
 #[derive(Debug, Clone)]
+/// Represents a paymaster account configuration.
+///
+/// # Example
+/// ```
+/// let paymaster = PaymasterAccountArgs {
+///     public_key: Felt::from_str("0x1234...")?,
+/// };
+/// ```
 pub struct PaymasterAccountArgs {
     /// The public key of the paymaster account.
+    /// Must be a valid Starknet public key in hexadecimal format.
     pub public_key: Felt,
 }

40-60: Consider adding capacity validation and error handling, sensei!

The function could benefit from:

  1. Validating the input slice capacity to prevent excessive memory allocation
  2. Adding error handling for potential overflow scenarios
 pub fn add_paymasters_to_genesis(
     genesis: &mut Genesis,
     slot_paymasters: &[PaymasterAccountArgs],
 ) -> Vec<ContractAddress> {
+    const MAX_PAYMASTERS: usize = 1000; // Example limit
+    if slot_paymasters.len() > MAX_PAYMASTERS {
+        panic!("Too many paymaster accounts. Maximum allowed: {}", MAX_PAYMASTERS);
+    }
+
     let mut accounts = Vec::with_capacity(slot_paymasters.len());

62-93: Enhance test coverage with edge cases, sensei!

Consider adding tests for:

  1. Empty paymaster list
  2. Maximum capacity scenarios
  3. Error cases from parsing
#[test]
fn test_empty_paymasters() {
    let mut genesis = Genesis::default();
    let paymasters = Vec::new();
    let addresses = add_paymasters_to_genesis(&mut genesis, &paymasters);
    assert!(addresses.is_empty());
}

#[test]
#[should_panic(expected = "Too many paymaster accounts")]
fn test_max_capacity() {
    let mut genesis = Genesis::default();
    let paymasters = vec![
        PaymasterAccountArgs { public_key: Felt::from(1) };
        1001 // Exceeds MAX_PAYMASTERS
    ];
    add_paymasters_to_genesis(&mut genesis, &paymasters);
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 278e710 and 1c0c667.

📒 Files selected for processing (1)
  • bin/katana/src/cli/init/slot.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: clippy
  • GitHub Check: ensure-wasm
  • GitHub Check: build
  • GitHub Check: docs
🔇 Additional comments (2)
bin/katana/src/cli/init/slot.rs (2)

14-24: Ohayo! The SlotArgs struct looks solid, sensei!

The struct is well-structured with proper clap attributes and conditional requirements. The requires_all = ["id", "slot"] constraint ensures proper configuration.


32-38: Add input validation and improve error context, sensei!

The input validation concerns from the previous review are still valid.

Additionally, consider improving error messages with more context:

 fn parse_paymaster_accounts_args(value: &str) -> Result<Vec<PaymasterAccountArgs>> {
     let mut accounts = Vec::new();
-    for s in value.split(',') {
-        accounts.push(PaymasterAccountArgs { public_key: Felt::from_str(s)? });
+    for (index, s) in value.split(',').enumerate() {
+        accounts.push(PaymasterAccountArgs {
+            public_key: Felt::from_str(s).map_err(|e| {
+                anyhow::anyhow!("Invalid public key at position {}: {}", index + 1, e)
+            })?,
+        });
     }
     Ok(accounts)
 }

Copy link

codecov bot commented Feb 12, 2025

Codecov Report

Attention: Patch coverage is 54.41176% with 31 lines in your changes missing coverage. Please review.

Project coverage is 56.42%. Comparing base (a1b21bf) to head (f2596cd).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
bin/katana/src/cli/init/mod.rs 0.00% 17 Missing ⚠️
bin/katana/src/cli/init/prompt.rs 0.00% 8 Missing ⚠️
bin/katana/src/cli/init/slot.rs 86.04% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3014      +/-   ##
==========================================
+ Coverage   56.40%   56.42%   +0.01%     
==========================================
  Files         434      435       +1     
  Lines       58077    58140      +63     
==========================================
+ Hits        32761    32808      +47     
- Misses      25316    25332      +16     

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

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

♻️ Duplicate comments (1)
bin/katana/src/cli/init/slot.rs (1)

31-37: ⚠️ Potential issue

Input validation is still missing, sensei!

The previous review comment about adding input validation for the FromStr implementation is still relevant.

 impl FromStr for PaymasterAccountArgs {
     type Err = anyhow::Error;
 
     fn from_str(s: &str) -> Result<Self> {
+        let s = s.trim();
+        if s.is_empty() {
+            return Err(anyhow::anyhow!("Empty public key"));
+        }
+        if !s.starts_with("0x") {
+            return Err(anyhow::anyhow!("Public key must start with 0x"));
+        }
         Ok(PaymasterAccountArgs { public_key: Felt::from_str(s)? })
     }
 }
🧹 Nitpick comments (1)
bin/katana/src/cli/init/slot.rs (1)

61-92: Let's enhance the test coverage, sensei!

While the current test verifies the happy path, we should add more test cases:

  • Empty paymaster list
  • Maximum number of paymasters
  • Error cases for invalid public keys
 #[cfg(test)]
 mod tests {
     use super::*;
 
+    #[test]
+    fn test_empty_paymasters() {
+        let mut genesis = Genesis::default();
+        let paymasters = Vec::new();
+        let addresses = add_paymasters_to_genesis(&mut genesis, &paymasters);
+        assert!(addresses.is_empty());
+    }
+
+    #[test]
+    fn test_invalid_public_key() {
+        assert!(PaymasterAccountArgs::from_str("invalid").is_err());
+        assert!(PaymasterAccountArgs::from_str("").is_err());
+        assert!(PaymasterAccountArgs::from_str("123").is_err());
+    }
+
     #[test]
     fn test_add_paymasters_to_genesis() {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c0c667 and 6d58776.

📒 Files selected for processing (1)
  • bin/katana/src/cli/init/slot.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: ensure-wasm
  • GitHub Check: build
  • GitHub Check: docs
  • GitHub Check: clippy
🔇 Additional comments (1)
bin/katana/src/cli/init/slot.rs (1)

39-59: Ohayo! The genesis account creation looks good, sensei!

The implementation correctly follows the PR objectives by using the specified default class hash and creating deterministic addresses for the paymaster accounts.

Comment on lines +20 to +22
#[arg(requires_all = ["id", "slot"])]
#[arg(long = "slot.paymasters", value_delimiter = ',')]
pub paymaster_accounts: Option<Vec<PaymasterAccountArgs>>,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ohayo sensei! The argument constraints need adjustment.

The requires_all = ["id", "slot"] constraint contradicts the PR objectives. According to the example usage katana init --slot --slot.paymasters 0x1,0x2,0x3, only the --slot flag is needed, not an id argument.

-    #[arg(requires_all = ["id", "slot"])]
+    #[arg(requires = "slot")]
     #[arg(long = "slot.paymasters", value_delimiter = ',')]
     pub paymaster_accounts: Option<Vec<PaymasterAccountArgs>>,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[arg(requires_all = ["id", "slot"])]
#[arg(long = "slot.paymasters", value_delimiter = ',')]
pub paymaster_accounts: Option<Vec<PaymasterAccountArgs>>,
#[arg(requires = "slot")]
#[arg(long = "slot.paymasters", value_delimiter = ',')]
pub paymaster_accounts: Option<Vec<PaymasterAccountArgs>>,

@glihm glihm enabled auto-merge (squash) February 12, 2025 23:07
@glihm glihm merged commit 906106a into main Feb 12, 2025
13 checks passed
@glihm glihm deleted the katana/init-slot-paymasters branch February 12, 2025 23:22
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.

2 participants