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

fix(sozo): model get not using prefixes #2867

Merged
merged 27 commits into from
Feb 5, 2025

Conversation

emarc99
Copy link
Contributor

@emarc99 emarc99 commented Jan 6, 2025

Description

Related issue

Closes #2835

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

  • New Features

    • Enhanced key input handling for model retrieval, now accepting serialized keys with various prefixes.
    • Added support for short string key parsing with sstr: prefix.
    • Introduced new fields such as tag and selector in the manifest for improved entity categorization.
  • Bug Fixes

    • Improved input parsing for model keys.
    • Added quote trimming for string inputs to enhance flexibility.
  • Improvements

    • More flexible and robust key specification process for model commands.
    • Updated identifiers and addresses in the manifest for better entity management.
    • Restructured method calls and target addresses in policy configurations for streamlined functionality.

Copy link

coderabbitai bot commented Jan 6, 2025

Walkthrough

Ohayo, sensei! The pull request enhances the sozo model get command by modifying the keys argument to accept a Vec<String> instead of Vec<Felt>, enabling more flexible input formats. A new function, parse_keys, is introduced to convert these strings into Vec<Felt>, ensuring proper handling of various prefixes. Additionally, the calldata_decoder is updated to trim quotes from string inputs, improving the robustness of the input processing. New tests are also added to validate the parsing functionality.

Changes

File Change Summary
bin/sozo/src/commands/model.rs - Updated ModelCommand::Get to accept keys as Vec<String> instead of Vec<Felt>
- Added parse_keys function to convert Vec<String> to Vec<Felt>
- Modified run method to call parse_keys before processing
crates/dojo/world/src/config/calldata_decoder.rs - Updated StrCalldataDecoder and ShortStrCalldataDecoder to trim surrounding quotes from input strings
examples/spawn-and-move/manifest_dev.json - Updated class_hash and address fields in world and contracts sections, including new fields like tag and selector
bin/sozo/tests/test_data/policies.json - Updated target addresses and method names for various entries

Assessment against linked issues

Objective Addressed Explanation
Support prefix parsing for sozo model get
Allow string input with sstr: prefix

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.


📜 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 10d9419 and acaea86.

⛔ Files ignored due to path filters (3)
  • examples/game-lib/Scarb.lock is excluded by !**/*.lock
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
📒 Files selected for processing (1)
  • bin/sozo/tests/test_data/policies.json (1 hunks)
🔇 Additional comments (33)
bin/sozo/tests/test_data/policies.json (33)

3-4: Ohayo, sensei! The updated target address and method "upgrade" here ensure that we are now correctly using the intended prefix. Please verify that target
"0x780e3207b4f11b56f32cc0f19975af5b3a4df3cad6a4b0ab59a1702ba0304d8"
aligns with the new model retrieval requirements.


7-8: Ohayo, sensei! The change to method "spawn" under target
"0x7447baef53fdcc376b73963aa2bd3b0894be7d5bd40f596cc44d1d54d80ea52"
reflects the shift for prefix support. Looks solid; just double-check its integration downstream.


11-12: Ohayo, sensei! The update to the "move" method in this object reinforces consistent prefix usage. Please confirm that the behavior remains as expected in related tests.


15-16: Ohayo, sensei! The method "set_player_config" now clearly aligns with our updated prefix strategy. Ensure that any configuration mappings or client references are also updated accordingly.


19-20: Ohayo, sensei! Changing to "update_player_config_name" adds clarity to configuration updates under the new system. Just verify that the update logic correctly interprets prefix-based inputs.


23-24: Ohayo, sensei! The update to "reset_player_config" is straightforward and consistent with our naming conventions. This looks well-integrated with the overall changes.


27-28: Ohayo, sensei! The revised method "set_player_server_profile" now targets the intended address correctly. Please ensure that any client-side calls are adjusted to this change.


31-32: Ohayo, sensei! The addition of "set_models" indicates an expanded support for multiple models within our new prefix regime. Everything appears in order here.


35-36: Ohayo, sensei! The "enter_dungeon" method update is applied to the correct target with the new prefix. Kindly double-check that any related model transitions are thoroughly tested.


39-40: Ohayo, sensei! The repeated "upgrade" under the target "0x7447baef53fdcc376b73963aa2bd3b0894be7d5bd40f596cc44d1d54d80ea52" looks consistent. Just verify that these upgrade calls do not introduce conflicts.


43-44: Ohayo, sensehi! The "upgrade" method applied to target
"0xca72f1cd782b614fa12c8b54afa895a169a4de1792738d4e3f09d0929f7834"
should be checked to ensure it now supports the required prefix.


47-48: Ohayo, sensei! The updated "upgrade" at target
"0x608ffd2e6b74a7bede256770ebe3d07bc65c79622e6a9396ea764011152102"
is consistent with our new definitions. Please verify its proper integration with the overall change set.


51-52: Ohayo, sensei! The introduction of method "uuid" on target
"0x5baea2d83fc19bae80dc5d4626a27b2b2d5012822cd862c56ed7007eb92eaa2"
is a neat addition for unique identification within the new prefix framework.


55-56: Ohayo, sensei! The change to "set_metadata" on the same target further reinforces our strategy. Please ensure any consumers of metadata are updated to recognize this change.


59-60: Ohayo, sensei! The update to "register_namespace" indicates that namespace registration now aligns with the new prefix requirements. Confirm that tests cover different prefix scenarios.


63-64: Ohayo, sensei! The modified "register_event" here follows the same updated approach. This change is clear; just verify it against expected event registration flows.


67-68: Ohayo, sensei! The update to "register_model" is consistent with our new registration pattern. Ensure that any dependencies on the model's key format are also updated.


71-72: Ohayo, sensei! The "register_contract" method is now updated to work with the new key prefixes. Please verify its implementation with integration tests to avoid any mismatches.


75-76: Ohayo, sensei! Updating to "init_contract" under the new target reflects the intended initialization process with prefixes. Looks good to me.


79-80: Ohayo, sensei! The "upgrade_event" method is updated with the new prefix support. Kindly ensure that event upgrade mechanisms in the system accommodate this change.


83-84: Ohayo, sensei! Changing to "upgrade_model" fits well within the new naming convention. Please confirm that all consumers of this method are aware of the update.


87-88: Ohayo, sensei! The update to "upgrade_contract" is implemented correctly according to the new prefix framework. Verify that any legacy references are updated accordingly.


91-92: Ohayo, sensei! The "emit_event" update appears sound. Just ensure that the event emission mechanism and its message formatting are fully compatible with the new scheme.


95-96: Ohayo, sensei! The pairing of "emit_events" with the singular form provides clarity for bulk versus individual operations. Please double-check that both implementations handle prefixes consistently.


99-100: Ohayo, sensei! The "set_entity" method update aligns perfectly with the objective of refining entity management under our new system.


103-104: Ohayo, sensei! The method "set_entities" will handle batch operations under the updated key system. Kindly verify that plural processing is consistent with the singular case.


107-108: Ohayo, sensei! The update to "delete_entity" is straightforward. Just ensure that deletion operations remain precise within the new prefix framework.


111-112: Ohayo, sensei! The change to "delete_entities" for batch deletion looks good and aligns with our new structural changes.


115-116: Ohayo, sensei! The "grant_owner" update now more clearly supports permissions under the new prefix rules. Please verify its consistency with the rest of the permission management system.


119-120: Ohayo, sensei! The adjustment to "revoke_owner" fits the new permission scheme. Confirm that all access-control checks properly refer to this updated identifier.


123-124: Ohayo, sensei! Updating the method to "grant_writer" is a clean change. Ensure that the writer's permissions are correctly interpreted in the overall policy.


127-128: Ohayo, sensei! The "revoke_writer" update is consistent with our permission model. Please verify that downstream systems accommodate this change without issue.


131-132: Ohayo, sensei! The final update to "upgrade" on target
"0x5baea2d83fc19bae80dc5d4626a27b2b2d5012822cd862c56ed7007eb92eaa2"
rounds out the changes. Ensure that there is no conflict with earlier upgrade calls and that the new prefix support is uniformly applied.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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: 0

🧹 Nitpick comments (2)
bin/sozo/src/commands/model.rs (2)

113-116: Ohayo sensei! Nice usage of multi-line help docs.
This enhanced help text clearly explains how to supply comma-separated values with various prefixes. The additional detail helps users form correct input on the command line.


214-215: Sensei, consider robust error handling.
You raise an error if decode_calldata fails. That's good. If you anticipate user mistakes frequently, you might provide a more descriptive error or usage example upon failure.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ddee9e and 69d83d0.

📒 Files selected for processing (3)
  • bin/sozo/src/commands/auth.rs (3 hunks)
  • bin/sozo/src/commands/mod.rs (1 hunks)
  • bin/sozo/src/commands/model.rs (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • bin/sozo/src/commands/mod.rs
🔇 Additional comments (8)
bin/sozo/src/commands/model.rs (4)

3-3: Ohayo sensei! Great addition for the decoder import.
The import of calldata_decoder sets the foundation for decoding user input with flexible prefixes. This is useful for supporting short-string notation and conventional felts.


117-117: Sensei, verify the impact of switching from Vec to String.
Swapping from Vec<Felt> to String is beneficial for user-friendly input, but ensure that usage sites (including tests and other commands) are updated accordingly.


126-128: Ohayo sensei! Thorough documentation for the block argument.
No issues spotted; the docstring clarifies the usage of a block number or a pending block. Looks good to merge.


233-264: Ohayo sensei! Impressive test coverage for short strings and hex validation.
Testing both short-string prefixes and hex-to-decimal conversions is crucial. The tests confirm that your new input format is working as intended.

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

245-249: Sensei, good clarity in the resource filtering condition.
The explicit if checks improve readability compared to a one-liner.


258-262: Ohayo sensei! Consistent approach for filtering owners.
Following the same pattern for owners and writers helps maintain a uniform code style.


314-320: Sensei, verifying name resolution for external writers.
You map resource selectors to hex strings or “World” if they match WORLD. This is clear. Make sure there’s no confusion about which resources are truly global.


321-327: Ohayo sensei! Good consistency in naming for external owners.
Repeating the same logic for owners ensures symmetrical permission logic for resource tagging.

@emarc99 emarc99 marked this pull request as draft January 6, 2025 09:07
@emarc99 emarc99 marked this pull request as ready for review January 6, 2025 09:35
@emarc99 emarc99 marked this pull request as draft January 6, 2025 13:39
Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thank you for taking the time on this @emarc99!

Some comments, please don't hesitate if you have any questions.

Comment on lines 113 to 116
#[arg(help = "Comma separated values e.g., \
0x12345,0x69420,sstr:\"hello\",sstr:\"misty\". Supported prefixes:\n \
- sstr: A cairo short string\n \
- no prefix: A cairo felt")]
Copy link
Collaborator

Choose a reason for hiding this comment

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

In the case of the keys, only one felt long serialized type are supported (everything that can fit in one felt).

That's great you've only put the sstr which is the only one supported actually.

Suggested change
#[arg(help = "Comma separated values e.g., \
0x12345,0x69420,sstr:\"hello\",sstr:\"misty\". Supported prefixes:\n \
- sstr: A cairo short string\n \
- no prefix: A cairo felt")]
#[arg(help = "Comma separated values e.g., \
0x12345,0x69420,sstr:\"hello\". Supported prefixes:\n \
- sstr: A cairo short string\n \
- no prefix: A cairo felt")]

Copy link
Collaborator

Choose a reason for hiding this comment

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

We may add a check that only this prefix is actually used, wdyt?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, the check will be quite useful. I'll add it.

bin/sozo/src/commands/model.rs Show resolved Hide resolved
@glihm
Copy link
Collaborator

glihm commented Jan 8, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

@emarc99
Copy link
Contributor Author

emarc99 commented Jan 8, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

Noted, sir.

@glihm
Copy link
Collaborator

glihm commented Jan 15, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

Noted, sir.

Hey @emarc99, let me know if you have any blocker on that.

@emarc99
Copy link
Contributor Author

emarc99 commented Jan 16, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

Noted, sir.

Hey @emarc99, let me know if you have any blocker on that.

The script rust_fmt.sh keep failing to run. So I applied cargo fmt on file directly.

@emarc99 emarc99 marked this pull request as ready for review January 16, 2025 16:27
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 (3)
bin/sozo/src/commands/model.rs (2)

113-117: Ohayo, sensei! Clarify the help message formatting

The help message for the keys argument could be formatted for better readability in the command-line interface. Adjusting the indentation and line breaks will make the supported prefixes clearer to the user.

Apply this diff to improve the formatting:

     #[arg(value_name = "KEYS")]
     #[arg(value_delimiter = ',')]
-    #[arg(help = "Comma separated values e.g., \
-                         0x12345,0x69420,sstr:\"hello\". Supported prefixes:\n  \
-                         - sstr: A cairo short string\n  \
-                         - no prefix: A cairo felt")]
+    #[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\".\nSupported prefixes:\n  - sstr: A Cairo short string\n  - no prefix: A Cairo felt")]

136-137: Ohayo, sensei! Enhance error message for unsupported prefixes

If a user provides an unsupported prefix, the error message could be more informative. Including the invalid prefix in the message and listing supported prefixes will guide the user towards correct usage.

Apply this diff to improve the error message:

     if s.contains(':') && !s.starts_with("sstr:") {
-        anyhow::bail!("Only 'sstr:' prefix is supported for model keys");
+        anyhow::bail!("Unsupported prefix in key '{}'. Only 'sstr:' prefix is supported for model keys.", s);
     }
crates/dojo/world/src/config/calldata_decoder.rs (1)

164-171: Ohayo, sensei! Handle mismatched quotes in sstr decoding

When decoding sstr prefixed values, the current implementation trims quotes if they are present but doesn't validate if they are correctly paired. This could lead to unexpected behavior with mismatched or unpaired quotes. Consider adding validation to check for properly matched quotes and provide an informative error message if they are not.

Apply this diff to add quote validation:

     "sstr" => {
         let value = if value.starts_with('"') && value.ends_with('"') {
             value.trim_matches('"')
+        } else if value.starts_with('"') || value.ends_with('"') {
+            return Err(CalldataDecoderError::ParseError("Mismatched quotes in 'sstr' value.".to_string()));
         } else {
             value
         };
         ShortStrCalldataDecoder.decode(value)?
     },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69d83d0 and fee9cfb.

📒 Files selected for processing (3)
  • bin/sozo/src/commands/mod.rs (1 hunks)
  • bin/sozo/src/commands/model.rs (4 hunks)
  • crates/dojo/world/src/config/calldata_decoder.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • bin/sozo/src/commands/mod.rs
🔇 Additional comments (1)
bin/sozo/src/commands/model.rs (1)

243-303: Ohayo, sensei! Excellent addition of argument parsing tests

Great job adding tests for the Get command's argument parsing. The tests cover both hexadecimal and sstr prefixed inputs, ensuring robust handling of various input formats.

Comment on lines 139 to 141
let felts = calldata_decoder::decode_calldata(s)?;
Ok(felts[0])
}
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! Prevent potential index out-of-bounds panic

The code assumes that felts contains at least one element. If decode_calldata(s) returns an empty vector, accessing felts[0] will cause a panic. Consider adding a check to ensure felts is not empty before accessing the first element.

Apply this diff to handle the potential empty felts:

     let felts = calldata_decoder::decode_calldata(s)?;
+    if felts.is_empty() {
+        anyhow::bail!("Failed to parse key '{}': no values returned.", s);
+    }
     Ok(felts[0])
📝 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
let felts = calldata_decoder::decode_calldata(s)?;
Ok(felts[0])
}
let felts = calldata_decoder::decode_calldata(s)?;
if felts.is_empty() {
anyhow::bail!("Failed to parse key '{}': no values returned.", s);
}
Ok(felts[0])
}

@emarc99 emarc99 requested a review from glihm January 16, 2025 16:58
Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

For the linting, you can use:

bash scripts/rust_fmt.sh --fix

Comment on lines 165 to 170
let value = if value.starts_with('"') && value.ends_with('"') {
value.trim_matches('"')
} else {
value
};
ShortStrCalldataDecoder.decode(value)?
Copy link
Collaborator

Choose a reason for hiding this comment

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

Wasn't the quotes already taken in account? Would you mind explaining the choice here.
Maybe this should land in decode function in case we have some?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Second part of test kept failing with below error;

running 1 test
test commands::model::tests::test_model_get_argument_parsing ... FAILED

failures:

---- commands::model::tests::test_model_get_argument_parsing stdout ----
thread 'commands::model::tests::test_model_get_argument_parsing' panicked at bin/sozo/src/commands/model.rs:296:13:assertion `left == right` failed
  left: [0x54cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5, 0x226d6973747922]
 right: [0x54cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5, 0x6d69737479]
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    commands::model::tests::test_model_get_argument_parsing

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 51 filtered out; finished in 1.30s

error: test failed, to rerun pass `--bin sozo`

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The issue wanted below to work.

sozo --profile sepolia model get Account 0x054cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5,sstr:"misty"

Maybe what was intended was below, without quotes around the short string; if so I'll remove the check for trimming quotes.

sozo --profile sepolia model get Account 0x054cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5,sstr:misty

Copy link
Collaborator

Choose a reason for hiding this comment

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

We need the " to make sure strings with spaces are actually included. So sstr:bla bla is not supported without ". So it is important to have them.

bin/sozo/src/commands/model.rs Show resolved Hide resolved
@emarc99
Copy link
Contributor Author

emarc99 commented Jan 16, 2025

For the linting, you can use:

bash scripts/rust_fmt.sh --fix

There's progress with this command. Will apply it soon and pr.

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/sozo/src/commands/model.rs (3)

113-115: Ohayo! Consider improving help text readability

The help text could be more readable with consistent indentation and alignment:

-        #[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\". Supported \
-                      prefixes:\n  - sstr: A cairo short string\n  - no prefix: A cairo felt")]
+        #[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\".\n\
+                      Supported prefixes:\n\
+                      - sstr: A cairo short string\n\
+                      - no prefix: A cairo felt")]

130-140: Ohayo! Consider additional input validation

The parser handles prefix validation and empty results well. Consider adding validation for malformed inputs:

 fn model_key_parser(s: &str) -> Result<Felt> {
+    if s.trim().is_empty() {
+        anyhow::bail!("Empty key is not allowed");
+    }
     if s.contains(':') && !s.starts_with("sstr:") {
         anyhow::bail!("Only 'sstr:' prefix is supported for model keys");
     }
     let felts = calldata_decoder::decode_calldata(s)?;
     if felts.is_empty() {
         anyhow::bail!("Failed to parse key '{}': no values returned.", s);
     }
     Ok(felts[0])
 }

241-303: Ohayo! Consider adding more edge case tests

The test coverage is good, but could be enhanced with additional edge cases:

#[test]
fn test_model_get_edge_cases() {
    // Test empty input
    let result = TestCommand::try_parse_from(["model", "get", "Account", ""]);
    assert!(result.is_err());

    // Test malformed sstr (missing quotes)
    let result = TestCommand::try_parse_from(["model", "get", "Account", "sstr:hello"]);
    assert!(result.is_err());

    // Test malformed hex
    let result = TestCommand::try_parse_from(["model", "get", "Account", "0xZZZ"]);
    assert!(result.is_err());
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0dac4 and 7d3d719.

📒 Files selected for processing (2)
  • bin/sozo/src/commands/model.rs (4 hunks)
  • crates/dojo/world/src/config/calldata_decoder.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/world/src/config/calldata_decoder.rs
🔇 Additional comments (1)
bin/sozo/src/commands/model.rs (1)

3-3: Ohayo, sensei! Import looks good!

The calldata_decoder import is correctly added and aligns with the new key parsing functionality.

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 (1)
bin/sozo/src/commands/mod.rs (1)

132-149: Clean error handling improvement, sensei!

The version check error handling is now more precise about manifest locations and handles both regular and virtual workspaces consistently. Nice work!

Consider making the error messages even more user-friendly by adding a hint about how to fix the version mismatch:

-                    "Found dojo-core version mismatch: expected {}. Please verify your dojo \
-                     dependency in {}",
+                    "Found dojo-core version mismatch: expected {}. Please update your dojo \
+                     dependency to the expected version in {} (hint: update the tag in your dependency)",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d3d719 and 018847f.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/mod.rs (3 hunks)
🔇 Additional comments (2)
bin/sozo/src/commands/mod.rs (2)

108-108: Verify Hash command's config independence, sensei!

The Hash command no longer uses the config parameter. This change looks intentional and aligns with the testing comment, but let's verify that the Hash command implementation doesn't require any config parameters.


50-51: Ohayo! Verify if Execute command functionality has changed.

The documentation change from "Execute one or several systems" to "Execute a system" suggests a breaking change in functionality. Let's verify if this reflects an actual implementation change.

@glihm
Copy link
Collaborator

glihm commented Jan 27, 2025

All good @emarc99 or do you still need some feedback? Let me know if you're blocked.

@emarc99
Copy link
Contributor Author

emarc99 commented Jan 27, 2025

All good @emarc99 or do you still need some feedback? Let me know if you're blocked.

Yea, I am running tests. I'll update in less than 24 hours for some feedback if tests keep failing, sir.

@emarc99
Copy link
Contributor Author

emarc99 commented Jan 30, 2025

Quick question sir @glihm.
str: and u256: return 2 or more felts, will the dojo engine know what to do with these keys?

I know the magic is happening in crates\sozo\ops\src\model.rs

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

🧹 Nitpick comments (1)
bin/sozo/src/commands/model.rs (1)

238-377: Ohayo, sensei! Enhance test coverage

While the current tests are thorough for happy paths, consider adding these test cases:

  1. Error cases for invalid prefixes
  2. Empty input handling
  3. Flattening edge cases (e.g., nested arrays)
#[test]
fn test_model_get_error_cases() {
    // Test invalid prefix
    let result = TestCommand::try_parse_from([
        "model", "get", "Account", "invalid:value"
    ]);
    assert!(result.is_err());

    // Test empty input
    let result = TestCommand::try_parse_from([
        "model", "get", "Account", ""
    ]);
    assert!(result.is_err());
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 70a8da2 and 42a8b53.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/model.rs (5 hunks)
🔇 Additional comments (1)
bin/sozo/src/commands/model.rs (1)

217-221: Ohayo, sensei! Clean and efficient implementation

The key flattening implementation is elegant and uses the appropriate iterator methods.

Comment on lines 130 to 134
// Custom parser for model keys
fn model_key_parser(s: &str) -> Result<Vec<Felt>> {
let felts = calldata_decoder::decode_calldata(&vec![s.to_string()])?;
Ok(felts)
}
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! Add validation and error handling

The parser implementation could be enhanced with:

  1. Empty result handling to prevent index out-of-bounds panic
  2. Prefix validation to ensure only supported prefixes are used
 fn model_key_parser(s: &str) -> Result<Vec<Felt>> {
     let felts = calldata_decoder::decode_calldata(&vec![s.to_string()])?;
+    if felts.is_empty() {
+        anyhow::bail!("Failed to parse key '{}': no values returned", s);
+    }
+    
+    // Validate prefix
+    if s.contains(':') {
+        let prefix = s.split(':').next().unwrap();
+        if !["sstr"].contains(&prefix) {
+            anyhow::bail!("Unsupported prefix '{}' in key '{}'", prefix, s);
+        }
+    }
     Ok(felts)
 }
📝 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
// Custom parser for model keys
fn model_key_parser(s: &str) -> Result<Vec<Felt>> {
let felts = calldata_decoder::decode_calldata(&vec![s.to_string()])?;
Ok(felts)
}
fn model_key_parser(s: &str) -> Result<Vec<Felt>> {
let felts = calldata_decoder::decode_calldata(&vec![s.to_string()])?;
if felts.is_empty() {
anyhow::bail!("Failed to parse key '{}': no values returned", s);
}
// Validate prefix
if s.contains(':') {
let prefix = s.split(':').next().unwrap();
if !["sstr"].contains(&prefix) {
anyhow::bail!("Unsupported prefix '{}' in key '{}'", prefix, s);
}
}
Ok(felts)
}

Comment on lines 113 to 116
#[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\". Supported \
prefixes:\n - sstr: A cairo short string\n - no prefix: A cairo felt")]
#[arg(value_parser = model_key_parser)]
keys: Vec<Vec<Felt>>,
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Ohayo, sensei! Help text needs updating

The help text for the keys argument only shows a subset of supported prefixes. The codebase fully supports:

  • u256: 256-bit unsigned integer
  • sstr: Cairo short string
  • str: Cairo string (ByteArray)
  • no prefix: Cairo felt or any type that fits into one felt
🔗 Analysis chain

Ohayo, sensei! Verify prefix support scope

Based on past discussions, only felt-long serialized types were supported. The help text now suggests support for multiple prefixes. Please confirm if this aligns with the current design decisions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any size constraints or prefix validations in the codebase

# Search for prefix validation logic
rg -A 5 'prefix|serialize' src/

Length of output: 78


Script:

#!/bin/bash
# Search for model key parser and related code
rg -A 10 "model_key_parser|fn parse" bin/sozo/src/

# Search for prefix validation and serialization logic
rg -A 5 "prefix|serialize" bin/sozo/src/

# Look for any type constraints or validation
rg -A 5 "Felt|felt|short string" bin/sozo/src/commands/

Length of output: 61730

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

♻️ Duplicate comments (1)
bin/sozo/src/commands/model.rs (1)

133-137: 🛠️ Refactor suggestion

Ohayo, sensei! Add validation for empty results and prefix support.

The parser implementation should be enhanced with validation to prevent potential issues.

 fn model_key_parser(s: &str) -> Result<Vec<Felt>> {
     let felts = calldata_decoder::decode_calldata(&vec![s.to_string()])?;
+    if felts.is_empty() {
+        anyhow::bail!("Failed to parse key '{}': no values returned", s);
+    }
     Ok(felts)
 }
🧹 Nitpick comments (2)
bin/sozo/src/commands/model.rs (2)

220-224: Ohayo, sensei! Consider adding debug logging for key flattening.

Adding debug logging would help with troubleshooting key parsing issues.

+                    trace!(?keys, "Original keys before flattening");
                     let flattened_keys: Vec<Felt> = keys.into_iter().flatten().collect();
+                    trace!(?flattened_keys, "Flattened keys");

241-381: Ohayo, sensei! Comprehensive test coverage looks good!

The test suite thoroughly covers various input scenarios including hex values, short strings, u256, int, and str prefixes. Great job on including edge cases and multiple prefix combinations!

However, consider adding negative test cases:

  1. Empty input
  2. Invalid prefixes
  3. Malformed input
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 42a8b53 and 0cfa683.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/model.rs (5 hunks)
🔇 Additional comments (1)
bin/sozo/src/commands/model.rs (1)

113-119: Ohayo, sensei! Help text needs updating based on recent changes.

Based on the PR comments, glihm mentioned that any serializable item can now be a key. The help text should be updated to reflect this change.

-        #[arg(help = "Comma separated values, e.g., 0x12345,0x69420,sstr:\"hello\", u256:0x123.
-                      Supporting all prefixes:\n  - u256: A 256-bit unsigned integer\n  - str: A \
-                      cairo string (ByteArray)\n  - sstr: A cairo short string\n  - int: A \
-                      signed integer\n  - no prefix: A cairo felt or any type that fits into \
-                      one felt")]
+        #[arg(help = "Comma separated values, e.g., 0x12345,0x69420,sstr:\"hello\", u256:0x123.
+                      Supporting any serializable type with prefixes:\n  - u256: A 256-bit unsigned integer\n  - str: A \
+                      cairo string (ByteArray)\n  - sstr: A cairo short string\n  - int: A \
+                      signed integer\n  - no prefix: A cairo felt\n  - <type>: Any serializable type")]

@emarc99 emarc99 requested a review from glihm January 30, 2025 18:06
@glihm
Copy link
Collaborator

glihm commented Jan 30, 2025

Quick question sir @glihm.

str: and u256: return 2 or more felts, will the dojo engine know what to do with these keys?

I know the magic is happening in crates\sozo\ops\src\model.rs

Yes with latest changes keys are not limited. So all prefixes are supported. The important point is having the he correct serialization, which is handled by the prefixes. 👍

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thank you @emarc99, you may also have look with new changes on the sozo calldata which is now without ,. To be consistent with the other part of the stack.

Comment on lines 165 to 170
let value = if value.starts_with('"') && value.ends_with('"') {
value.trim_matches('"')
} else {
value
};
ShortStrCalldataDecoder.decode(value)?
Copy link
Collaborator

Choose a reason for hiding this comment

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

We need the " to make sure strings with spaces are actually included. So sstr:bla bla is not supported without ". So it is important to have them.

@emarc99
Copy link
Contributor Author

emarc99 commented Jan 30, 2025

Thank you @emarc99, you may also have look with new changes on the sozo calldata which is now without ,. To be consistent with the other part of the stack.

Will look into that asap!
Introduced by this PR.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thank you @emarc99 for the work 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

🧹 Nitpick comments (1)
bin/sozo/src/commands/model.rs (1)

246-249: Ohayo, sensei! Address the TODO comment about key flattening tests.

The test suite is comprehensive, but we should implement the missing tests for key flattening.

Would you like me to help implement the additional test cases for key flattening?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0cfa683 and 039ad49.

📒 Files selected for processing (3)
  • bin/sozo/src/commands/model.rs (5 hunks)
  • crates/dojo/world/src/config/calldata_decoder.rs (2 hunks)
  • examples/spawn-and-move/manifest_dev.json (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/world/src/config/calldata_decoder.rs
🔇 Additional comments (3)
bin/sozo/src/commands/model.rs (2)

1-14: Ohayo, sensei! The imports look good!

The added imports for calldata_decoder and CALLDATA_DOC align well with the new key parsing functionality.


113-118: Ohayo, sensei! The Get command argument changes look good!

The change from Vec<Felt> to Vec<String> improves usability by allowing more flexible input formats, and the help text now properly references the calldata documentation.

examples/spawn-and-move/manifest_dev.json (1)

3-4: Ohayo, sensei! The manifest updates look good!

The changes to class hashes and addresses are consistent throughout the manifest, and the new models (Flatbow and RiverSkale) have been properly integrated.

Also applies to: 1255-1255, 1609-1609, 1803-1803, 1979-1979, 2165-2168, 2177-2177, 2183-2183, 2189-2189, 2195-2195, 2201-2208, 2215-2215, 2221-2221

Comment on lines +231 to +243
/// Parses the keys from the command line into a vector of Felt representing the serialized keys of
/// the model.
fn parse_keys(keys: &[String]) -> Result<Vec<Felt>> {
let mut keys_serde = vec![];

for key in keys {
let key_felt = calldata_decoder::decode_single_calldata(key)
.with_context(|| format!("Failed to decode key: {}", key))?;
keys_serde.extend(key_felt);
}

Ok(keys_serde)
}
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! Add validation to the parse_keys function.

The function should validate empty results and supported prefixes to prevent runtime errors.

Apply this diff to add validation:

 fn parse_keys(keys: &[String]) -> Result<Vec<Felt>> {
     let mut keys_serde = vec![];
 
     for key in keys {
         let key_felt = calldata_decoder::decode_single_calldata(key)
             .with_context(|| format!("Failed to decode key: {}", key))?;
+        if key_felt.is_empty() {
+            anyhow::bail!("Failed to parse key '{}': no values returned", key);
+        }
+        
+        // Validate prefix if present
+        if key.contains(':') {
+            let prefix = key.split(':').next().unwrap();
+            if !["u256", "sstr", "str", "int"].contains(&prefix) {
+                anyhow::bail!("Unsupported prefix '{}' in key '{}'", prefix, key);
+            }
+        }
         keys_serde.extend(key_felt);
     }
 
     Ok(keys_serde)
 }
📝 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
/// Parses the keys from the command line into a vector of Felt representing the serialized keys of
/// the model.
fn parse_keys(keys: &[String]) -> Result<Vec<Felt>> {
let mut keys_serde = vec![];
for key in keys {
let key_felt = calldata_decoder::decode_single_calldata(key)
.with_context(|| format!("Failed to decode key: {}", key))?;
keys_serde.extend(key_felt);
}
Ok(keys_serde)
}
fn parse_keys(keys: &[String]) -> Result<Vec<Felt>> {
let mut keys_serde = vec![];
for key in keys {
let key_felt = calldata_decoder::decode_single_calldata(key)
.with_context(|| format!("Failed to decode key: {}", key))?;
if key_felt.is_empty() {
anyhow::bail!("Failed to parse key '{}': no values returned", key);
}
// Validate prefix if present
if key.contains(':') {
let prefix = key.split(':').next().unwrap();
if !["u256", "sstr", "str", "int"].contains(&prefix) {
anyhow::bail!("Unsupported prefix '{}' in key '{}'", prefix, key);
}
}
keys_serde.extend(key_felt);
}
Ok(keys_serde)
}

@emarc99
Copy link
Contributor Author

emarc99 commented Feb 5, 2025

Thank you @emarc99 for the work here.

Thanks for the chance, sir. Would've taken me longer to implement the new changes.
Also studying your final code for learning.

@glihm glihm enabled auto-merge (squash) February 5, 2025 22:16
@glihm glihm merged commit 9c5d099 into dojoengine:main Feb 5, 2025
13 checks passed
Copy link

codecov bot commented Feb 5, 2025

Codecov Report

Attention: Patch coverage is 94.61538% with 7 lines in your changes missing coverage. Please review.

Project coverage is 57.13%. Comparing base (b751c50) to head (acaea86).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
bin/sozo/src/commands/model.rs 92.78% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2867      +/-   ##
==========================================
+ Coverage   57.04%   57.13%   +0.08%     
==========================================
  Files         427      427              
  Lines       56561    56686     +125     
==========================================
+ Hits        32266    32385     +119     
- Misses      24295    24301       +6     

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] Sozo model get is not using prefixes
2 participants