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(sozo): selector from tag command on sozo #2282

Merged
merged 3 commits into from
Aug 10, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Aug 9, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new command for model selection via the command line, enabling users to compute selectors based on tags.
    • Added a new hashing command, allowing users to hash various inputs relevant to the StarkNet ecosystem.
    • Enhanced command handling to display and execute the new selector and hashing functionalities seamlessly.
  • Bug Fixes

    • Improved error handling for the new command-line interfaces to ensure a smooth user experience.

Copy link

coderabbitai bot commented Aug 9, 2024

Walkthrough

Ohayo, sensei! The recent updates significantly enhance the command handling of the application by introducing both Selector and Hash command variants. Users can now compute selectors and hash inputs directly through the command-line interface, streamlining interactions with the underlying smart contract system. The updates include new argument parsing using the clap library and modifications to existing command functionalities, ensuring a seamless integration of these features.

Changes

Files Change Summary
bin/sozo/src/commands/* Added Selector(selector::SelectorArgs) and Hash(hash::HashArgs) variants to Commands enum, updated fmt::Display, and modified run function to accommodate both commands.
bin/sozo/src/commands/selector.rs Introduced SelectorArgs struct for tag-based input, implementing a run method to compute selectors.
bin/sozo/src/commands/hash.rs Created HashArgs struct for hashing operations, with a run method to process various input types and compute hashes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Commands
    participant Selector
    participant Hash

    User->>CLI: Executes Selector command with tag
    CLI->>Commands: Match Commands::Selector
    Commands->>Selector: Invoke run method with SelectorArgs
    Selector->>Config: Process tag and compute selector
    Selector->>User: Display computed selector

    User->>CLI: Executes Hash command with input
    CLI->>Commands: Match Commands::Hash
    Commands->>Hash: Invoke run method with HashArgs
    Hash->>Config: Process input and compute hashes
    Hash->>User: Display computed hashes
Loading

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 807ad5d and a6b02a3.

Files selected for processing (2)
  • bin/sozo/src/commands/hash.rs (1 hunks)
  • bin/sozo/src/commands/mod.rs (5 hunks)
Additional comments not posted (6)
bin/sozo/src/commands/mod.rs (2)

99-99: LGTM! The fmt::Display implementation for Hash is correct.

The addition of the Hash variant in the fmt::Display implementation looks good and follows the existing pattern.


130-130: Ohayo, sensei! Consider error handling improvements.

The run method for Commands::Hash uses .map(|_| ()) to handle the result. Ensure that any potential errors are logged or handled appropriately.

bin/sozo/src/commands/hash.rs (4)

24-28: LGTM! Selector computation from tag is well-handled.

The logic for computing the selector from a tag looks correct and efficiently implemented.


52-61: LGTM! The handling of multiple inputs for Poseidon hashing is efficient.

The logic for handling multiple inputs and computing the Poseidon hash is implemented correctly and efficiently.


73-143: Ohayo, sensei! Excellent test coverage.

The test cases cover a wide range of scenarios and edge cases, ensuring robust functionality.


30-39: Ohayo, sensei! Ensure input length validation is consistent.

The check for input length assumes it must be less than or equal to 32. Ensure this constraint is documented or verified against specifications.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

Comment on lines 23 to 29
impl SelectorArgs {
pub fn run(self, config: &Config) -> Result<()> {
trace!(args = ?self);

println!("{:#x}", compute_selector_from_tag(&self.tag));
Ok(())
}
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Consider adding error handling for robustness.

The run method currently assumes that compute_selector_from_tag will always succeed. It would be wise to handle potential errors to prevent unexpected crashes.

pub fn run(self, config: &Config) -> Result<()> {
    trace!(args = ?self);

    match compute_selector_from_tag(&self.tag) {
        Ok(selector) => println!("{:#x}", selector),
        Err(e) => eprintln!("Error computing selector: {}", e),
    }
    Ok(())
}

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

Outside diff range, codebase verification and nitpick comments (4)
bin/sozo/src/commands/mod.rs (2)

17-17: Ohayo, sensei! Add missing module documentation.

The new hash module is introduced without any documentation. Consider adding a brief comment to explain its purpose.

// Module for handling hash-related commands
pub(crate) mod hash;

72-73: Ohayo, sensei! The Hash command description needs revision.

The current description "Select a model" does not accurately reflect the functionality of the Hash command. The Hash command is designed to hash input values, as indicated by the HashArgs struct and its run method. Consider updating the description to better align with its purpose.

  • File: bin/sozo/src/commands/mod.rs
  • Line: 72

Please update the description to accurately reflect the command's functionality.

Analysis chain

Ensure consistency in command descriptions.

The description for the Hash command is "Select a model," which might not accurately reflect its functionality. Ensure it aligns with the actual purpose of the command.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the purpose of the `Hash` command.

# Test: Search for the command usage in documentation or comments. Expect: Consistent descriptions.
rg --type markdown --type rust -A 2 "Hash"

Length of output: 361719


Script:

#!/bin/bash
# Search for the definition and usage of `HashArgs` to understand the `Hash` command's purpose.
ast-grep --lang rust --pattern 'struct HashArgs { $$$ }'

Length of output: 58


Script:

#!/bin/bash
# Search for comments or documentation related to `HashArgs` for additional context on the `Hash` command.
rg --type rust -A 3 "HashArgs"

Length of output: 2766

bin/sozo/src/commands/hash.rs (2)

1-7: Ohayo, sensei! Consider organizing imports.

The imports are comprehensive, but consider grouping them by functionality or origin for better readability.

// External crates
use anyhow::Result;
use clap::Args;
use tracing::trace;

// Starknet related
use starknet::core::types::Felt;
use starknet::core::utils::{get_selector_from_name, starknet_keccak};
use starknet_crypto::{poseidon_hash_many, poseidon_hash_single};

// Dojo specific
use dojo_world::contracts::naming::compute_selector_from_tag;

65-70: Ohayo, sensei! Improve error messages for felt_from_str.

The error messages could be more descriptive to help users understand the input format requirements.

if s.starts_with("0x") {
    return Ok(Felt::from_hex(s).map_err(|_| anyhow::anyhow!("Invalid hex format for Felt"))?);
}

Ok(Felt::from_dec_str(s).map_err(|_| anyhow::anyhow!("Invalid decimal format for Felt"))?)

Comment on lines +16 to +22
impl HashArgs {
pub fn run(self) -> Result<Vec<String>> {
trace!(args = ?self);

if self.input.is_empty() {
return Err(anyhow::anyhow!("Input is empty"));
}
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Validate input handling.

The input validation checks for an empty string but consider trimming whitespace before this check to avoid false negatives.

if self.input.trim().is_empty() {
    return Err(anyhow::anyhow!("Input is empty"));
}

Comment on lines +41 to +50
if !self.input.contains(',') {
let felt = felt_from_str(&self.input)?;
let poseidon = format!("{:#066x}", poseidon_hash_single(felt));
let snkeccak = format!("{:#066x}", starknet_keccak(&felt.to_bytes_le()));

println!("Poseidon: {}", poseidon);
println!("SnKeccak: {}", snkeccak);

return Ok(vec![poseidon.to_string(), snkeccak.to_string()]);
}
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Handle potential errors gracefully.

The felt_from_str function is used within a map and could panic if the input is invalid. Consider handling this gracefully.

.map(|s| felt_from_str(s.trim()).unwrap_or_else(|_| panic!("Invalid felt value")))

Copy link

codecov bot commented Aug 10, 2024

Codecov Report

Attention: Patch coverage is 97.24771% with 3 lines in your changes missing coverage. Please review.

Project coverage is 66.96%. Comparing base (7461b53) to head (a6b02a3).

Files Patch % Lines
bin/sozo/src/commands/mod.rs 60.00% 2 Missing ⚠️
bin/sozo/src/commands/hash.rs 99.03% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2282      +/-   ##
==========================================
+ Coverage   66.88%   66.96%   +0.07%     
==========================================
  Files         342      343       +1     
  Lines       45149    45258     +109     
==========================================
+ Hits        30198    30305     +107     
- Misses      14951    14953       +2     

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

@glihm glihm merged commit 998c680 into dojoengine:main Aug 10, 2024
15 checks passed
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