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(dojo-lang): verify constructor args to follow dojo rules #2944

Merged
merged 3 commits into from
Jan 23, 2025
Merged

Conversation

glihm
Copy link
Collaborator

@glihm glihm commented Jan 23, 2025

Dojo contracts are always deployed with an empty calldata for constructor. This is done as such for two reasons:

  1. Deterministic addresses, since calldata of the constructor impacts the computed address.
  2. All the contract can be first deployed, and then the initialization can be ordered with the guarantee that all resources are already deployed.

This PR aims at ensuring the user is warned in case that a custom constructor is used. This is something possible, and some logic may be done in the constructor in some specific cases.

However, the recommended way to initialize a contract is adding the dojo_init function, which ensures that all models and permissions are already done.

Summary by CodeRabbit

  • Dependency Updates

    • Updated scarb, scarb-metadata, and scarb-ui dependencies to a new commit hash.
  • Code Improvements

    • Added validation for constructor parameters in contract implementation.
    • Introduced stricter checks for constructor method definitions.
    • Added a test module to verify the correctness of the new validation function.

Copy link

coderabbitai bot commented Jan 23, 2025

Walkthrough

Ohayo, sensei! The pull request introduces updates to the Scarb dependencies in the Cargo.toml file, changing the commit references for scarb, scarb-metadata, and scarb-ui to a new commit hash. Additionally, a validation mechanism has been added to the contract.rs file to ensure constructor parameters meet specific criteria in Dojo contract implementations.

Changes

File Change Summary
Cargo.toml Updated Scarb dependencies to new commit hash b5ab351aa9b52dcf27a397021d84a423afd016dc
crates/dojo/lang/src/attribute_macros/contract.rs Added is_valid_constructor_params() function to validate constructor parameters and included a test module

Sequence Diagram

sequenceDiagram
    participant ContractImpl as Contract Implementation
    participant ValidationFunc as is_valid_constructor_params()
    participant Diagnostics as Diagnostics Vector

    ContractImpl->>ValidationFunc: Check constructor parameters
    ValidationFunc-->>ContractImpl: Validation result
    alt Invalid Parameters
        ValidationFunc->>Diagnostics: Push error diagnostic
    else Valid Parameters
        ContractImpl->>ContractImpl: Continue processing
    end
Loading

The sequence diagram illustrates the new validation flow for constructor parameters, showing how the is_valid_constructor_params() function checks the parameters and potentially adds diagnostics if the validation fails.


📜 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 6eb6127 and cafeffe.

📒 Files selected for processing (1)
  • crates/dojo/lang/src/attribute_macros/contract.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/lang/src/attribute_macros/contract.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: ensure-wasm
  • GitHub Check: docs
  • GitHub Check: clippy

🪧 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 (1)
crates/dojo/lang/src/attribute_macros/contract.rs (1)

387-398: Consider making the validation more robust.

While the validation logic works, it could be more resilient to whitespace variations.

Consider this improvement:

 fn is_valid_constructor_params(params: &str) -> bool {
-    let frags = params.split(",").collect::<Vec<_>>();
+    let frags: Vec<_> = params.split(',').map(str::trim).collect();
 
     if frags.len() != 1 {
         return false;
     }
 
-    frags.first().unwrap().starts_with("ref self: ContractState")
+    frags.first().unwrap().trim().starts_with("ref self: ContractState")
 }
📜 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 6eb6127.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • Cargo.toml (1 hunks)
  • crates/dojo/lang/src/attribute_macros/contract.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (2)
crates/dojo/lang/src/attribute_macros/contract.rs (1)

175-185: Ohayo, sensei! The constructor validation looks solid!

The error message clearly explains why custom constructor parameters are discouraged and guides users toward using dojo_init instead.

Cargo.toml (1)

215-217: Verify the Scarb dependency update.

All Scarb dependencies are consistently updated to the same commit hash, which is good. However, let's verify this version.

✅ Verification successful

Ohayo sensei! The Scarb dependency update looks good 🍜

The update is a minor chore change fixing a constructor in the dojo plugin, with no breaking changes or reported issues. All dependencies are correctly pinned to the same commit.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the Scarb commit for any breaking changes or issues

# Fetch commit info
gh api \
  -H "Accept: application/vnd.github+json" \
  repos/dojoengine/scarb/commits/b5ab351aa9b52dcf27a397021d84a423afd016dc \
  --jq '.commit.message'

# Check for any issues referencing this commit
gh api \
  -H "Accept: application/vnd.github+json" \
  search/issues?q=b5ab351aa9b52dcf27a397021d84a423afd016dc+repo:dojoengine/scarb \
  --jq '.items[].title'

Length of output: 337

Copy link

codecov bot commented Jan 23, 2025

Codecov Report

Attention: Patch coverage is 67.74194% with 10 lines in your changes missing coverage. Please review.

Project coverage is 55.75%. Comparing base (8f54b66) to head (cafeffe).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
crates/dojo/lang/src/attribute_macros/contract.rs 67.74% 10 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2944   +/-   ##
=======================================
  Coverage   55.75%   55.75%           
=======================================
  Files         445      445           
  Lines       57627    57657   +30     
=======================================
+ Hits        32129    32149   +20     
- Misses      25498    25508   +10     

☔ 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.

1 participant