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(dojo-lang): add bytearray_hash macro #2946

Merged
merged 8 commits into from
Jan 24, 2025

Conversation

bengineer42
Copy link
Contributor

@bengineer42 bengineer42 commented Jan 23, 2025

Description

Replace #2686

Related issue

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

Release Notes

  • New Features

    • Added a new bytearray hash functionality for computing hash values from byte arrays
    • Introduced a new inline macro for computing bytearray hashes
    • Enhanced namespace and selector generation methods
  • Improvements

    • Added new methods for creating WorldStorage instances using namespace hashes
    • Optimized gas usage for namespace-related operations
  • Testing

    • Expanded test coverage for bytearray hash functionality
    • Added comprehensive unit tests for hash generation
  • Dependency Updates

    • Updated Scarb dependencies to a new commit

Copy link

coderabbitai bot commented Jan 23, 2025

Walkthrough

Ohayo, sensei! This pull request introduces a comprehensive enhancement to the Dojo framework's testing and hashing capabilities. The changes span multiple crates, adding a new bytearray_hash module, implementing a new inline macro for bytearray hashing, and extending the WorldStorage functionality with methods for creating storage instances from namespace hashes. The modifications provide more flexible ways to generate and work with hashes across different components of the Dojo ecosystem.

Changes

File Change Summary
crates/dojo/core-cairo-test/src/lib.cairo Added new bytearray_hash module in expanded tests section
crates/dojo/core/src/world/storage.cairo Added methods: new_from_hash, dns_from_hash, dns_from_selector in WorldStorageInternalImpl
crates/dojo/lang/src/attribute_macros/patches/contract.patch.cairo Added world_ns_hash method to contract internal implementation
crates/dojo/lang/src/cairo_plugin.rs Added BytearrayHashMacro to plugin suite
crates/dojo/lang/src/inline_macros/mod.rs Added bytearray_hash module and public export for BytearrayHashMacro
crates/dojo/core/src/lib.cairo Updated hash module exports to include selector_from_hashes
crates/dojo/core/src/utils/hash.cairo Added selector_from_hashes function
crates/dojo/lang/src/inline_macros/bytearray_hash.rs Implemented new BytearrayHashMacro
examples/spawn-and-move/src/actions.cairo Added world_default_ns_hash method and related test
crates/dojo/core-cairo-test/src/tests/expanded/bytearray_hash.cairo Added comprehensive unit tests for bytearray hashing

Possibly related PRs


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)
crates/dojo/lang/src/inline_macros/poseidon_hash_string.rs (1)

18-62: Robust macro code generation

Ohayo, sensei! The generate_code function effectively handles the macro logic:

  • Validates that exactly one string argument is provided.
  • Returns a diagnostic error if the argument count is incorrect.
  • Computes the byte array hash using naming::compute_bytearray_hash.
  • Builds the output code with proper hexadecimal formatting.

However, consider enhancing the string extraction for better robustness.

Suggestion: Improve string extraction to handle edge cases

In line 43, using replace('\"', "") may not handle cases where the string contains escaped quotes or special characters. It's safer to parse the string literal properly.

Apply this diff to enhance string extraction:

-let tag = &args[0].as_syntax_node().get_text(db).replace('\"', "");
+let ast::Expr::String(ref string_literal) = args[0] else {
+    return InlinePluginResult {
+        code: None,
+        diagnostics: vec![PluginDiagnostic {
+            stable_ptr: args[0].stable_ptr().untyped(),
+            message: "Expected a string literal.".to_string(),
+            severity: Severity::Error,
+        }],
+    };
+};
+let tag = string_literal.string_value(db);
crates/dojo/core/src/world/storage.cairo (1)

49-65: Consider adding documentation for the new methods.

The implementation looks good, but it would be helpful to add documentation explaining:

  • The purpose of each method
  • The relationship between namespace_hash, contract_name_hash, and the final selector
  • The expected format and constraints of the input hashes
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f54b66 and 1930819.

📒 Files selected for processing (7)
  • crates/dojo/core-cairo-test/src/lib.cairo (1 hunks)
  • crates/dojo/core-cairo-test/src/tests/expanded/poseidon_hash_string.cairo (1 hunks)
  • crates/dojo/core/src/world/storage.cairo (2 hunks)
  • crates/dojo/lang/src/attribute_macros/patches/contract.patch.cairo (1 hunks)
  • crates/dojo/lang/src/cairo_plugin.rs (2 hunks)
  • crates/dojo/lang/src/inline_macros/mod.rs (2 hunks)
  • crates/dojo/lang/src/inline_macros/poseidon_hash_string.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (13)
crates/dojo/lang/src/inline_macros/poseidon_hash_string.rs (2)

12-12: Well-defined macro struct

Ohayo, sensei! The PoseidonHashStringMacro struct is properly defined and sets the stage for the macro implementation.


14-16: Correct implementation of the NamedPlugin trait

Ohayo, sensei! Implementing the NamedPlugin trait with the correct NAME ensures the macro is correctly registered as "poseidon_hash_string".

crates/dojo/lang/src/attribute_macros/patches/contract.patch.cairo (1)

33-35: Addition of world_from_hash method looks good

Ohayo, sensei! The new method world_from_hash correctly allows retrieval of WorldStorage using a namespace hash. This enhances flexibility when working with hashed namespaces.

crates/dojo/core-cairo-test/src/tests/expanded/poseidon_hash_string.cairo (5)

4-12: Comprehensive test for poseidon_hash_string with "foo"

Ohayo, sensei! The test verifies that the computed hash matches the macro's output, ensuring correctness for a standard string input.


13-21: Effective test for empty string edge case

Ohayo, sensei! Including a test for an empty string ensures the macro handles this edge case properly. Great attention to detail!


23-31: Boundary condition test with 31-character string

Ohayo, sensei! Testing with a 31-character string effectively checks boundary conditions, confirming the macro's robustness.


33-41: Robustness test with a longer string

Ohayo, sensei! Testing with a longer string like "0123456789012345678901234567890foo" ensures the macro accurately handles strings beyond typical lengths.


43-51: Negative test case confirms hash inequality

Ohayo, sensei! Verifying that different input strings produce different hashes strengthens the validity of the hashing function.

crates/dojo/core-cairo-test/src/lib.cairo (1)

41-41: LGTM!

Ohayo, sensei! The new module follows the existing pattern and is correctly placed within the expanded tests section.

crates/dojo/lang/src/inline_macros/mod.rs (1)

15-15: LGTM!

Ohayo, sensei! The new module and its export follow the established patterns and are correctly organized within the inline macros module.

Also applies to: 25-25

crates/dojo/lang/src/cairo_plugin.rs (1)

15-15: LGTM!

Ohayo, sensei! The new macro is properly imported and registered in the plugin suite.

Also applies to: 29-29

crates/dojo/core/src/world/storage.cairo (2)

4-4: LGTM!

Ohayo, sensei! The import and new constructor method are well-implemented.

Also applies to: 36-38


44-47: LGTM!

Clean refactor of the dns method to use the new hash-based functionality.

@glihm glihm changed the title feat(namespace): add poseidon_hash_string macro and related tests feat(dojo-lang): add bytearray_hash macro and related tests Jan 24, 2025
@glihm glihm changed the title feat(dojo-lang): add bytearray_hash macro and related tests feat(dojo-lang): add bytearray_hash macro and related tests Jan 24, 2025
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 @bengineer42 for the contribution, renamed a bit for more consistency and fixed the scarb issue.

Comment on lines +29 to +31
.add_plugin::<BuiltinDojoPlugin>()
.add_inline_macro_plugin::<SelectorFromTagMacro>()
.add_inline_macro_plugin::<BytearrayHashMacro>();
Copy link
Collaborator

Choose a reason for hiding this comment

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

@bengineer42 fyi the issue was that you were trying to add 2 times the BuiltinDojoPlugin. This was causing the weird scarb issue on events, which is not related at all. But this was the reason.

@glihm glihm enabled auto-merge (squash) January 24, 2025 03:34
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)
crates/dojo/core-cairo-test/src/tests/expanded/bytearray_hash.cairo (1)

4-11: Consider a helper to reduce duplicated serialization in tests.

Most of these tests repeat the serializeposeidon_hash_spanassert_eq! sequence. A helper function could reduce code repetition and improve readability.

-    let mut array = array![];
-    bytes.serialize(ref array);
-    let computed = poseidon_hash_span(array.span());
-    assert_eq!(computed, hash);
+    call_assert_hash(bytes, hash); // Suppose you define a helper function
crates/dojo/core/src/world/storage.cairo (2)

47-53: Concise hash-based DNS lookup method.

Logging or error tracking on failure might help debugging, but the current approach is acceptable.


55-58: Selector-based resolution is efficient.

The internal match pattern is clean. If you anticipate new resource types, consider factoring out resource validation into a dedicated function.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 61a04a9 and 6f38ac2.

⛔ Files ignored due to path filters (2)
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
📒 Files selected for processing (4)
  • crates/dojo/core-cairo-test/src/lib.cairo (1 hunks)
  • crates/dojo/core-cairo-test/src/tests/expanded/bytearray_hash.cairo (1 hunks)
  • crates/dojo/core/src/world/storage.cairo (1 hunks)
  • examples/spawn-and-move/src/actions.cairo (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/dojo/core-cairo-test/src/lib.cairo
  • examples/spawn-and-move/src/actions.cairo
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: ensure-wasm
  • GitHub Check: build
  • GitHub Check: docs
🔇 Additional comments (7)
crates/dojo/core-cairo-test/src/tests/expanded/bytearray_hash.cairo (5)

1-2: Ohayo sensei! All set up for hashing.

These imports look correct. Poseidon-based hashing is consistent with the Dojo ecosystem.


14-21: Test coverage of empty case is commendable.

Verifying boundary conditions like empty strings ensures robust hashing.


24-31: Good job including length-boundary tests.

Ensuring the function handles exactly 31 characters addresses a common off-by-one pitfall.


34-41: Thorough test for longer strings.

This scenario guards against performance or memory issues when hashing bigger data.


44-51: Nicely done verifying inequality.

A negative test confirming that different inputs yield different hashes is crucial.

crates/dojo/core/src/world/storage.cairo (2)

35-37: Straightforward constructor.

This is consistent with the existing new constructor. Consider adding inline documentation if additional validation or usage constraints arise later.


44-45: Improved clarity by delegating to dns_from_hash.

This encapsulation keeps dns succinct, making it easier to maintain.

@glihm glihm changed the title feat(dojo-lang): add bytearray_hash macro and related tests feat(dojo-lang): add bytearray_hash macro Jan 24, 2025
@glihm glihm disabled auto-merge January 24, 2025 03:59
@glihm glihm enabled auto-merge (squash) January 24, 2025 03:59
Copy link

codecov bot commented Jan 24, 2025

Codecov Report

Attention: Patch coverage is 0% with 46 lines in your changes missing coverage. Please review.

Project coverage is 55.86%. Comparing base (01111f4) to head (6f38ac2).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...ates/dojo/lang/src/inline_macros/bytearray_hash.rs 0.00% 42 Missing ⚠️
crates/dojo/lang/src/cairo_plugin.rs 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2946      +/-   ##
==========================================
- Coverage   55.91%   55.86%   -0.06%     
==========================================
  Files         446      447       +1     
  Lines       57814    57859      +45     
==========================================
- Hits        32325    32321       -4     
- Misses      25489    25538      +49     

☔ 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
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants