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: add i128 + use BigNumberish type #2705

Merged
merged 2 commits into from
Nov 21, 2024

Conversation

MartianGreed
Copy link
Contributor

@MartianGreed MartianGreed commented Nov 20, 2024

Description

  • Replace number type to BigNumberish to allow types returned from torii to work.
  • Add type support for i128

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

Summary by CodeRabbit

  • New Features

    • Enhanced type support for function parameters, now utilizing BigNumberish for improved type safety.
    • Updated TypeScript interface generation to reflect new type definitions, ensuring compatibility with the starknet library.
    • Introduced new constant mappings for various numeric types to improve maintainability and consistency in JavaScript representations.
  • Bug Fixes

    • Adjusted test cases to align with the new type definitions and mappings, ensuring expected outputs are accurate.

Copy link

coderabbitai bot commented Nov 20, 2024

Walkthrough

Ohayo, sensei! This pull request introduces updates to the TypeScript generator within the Dojo bindgen crate. Key changes enhance type handling for function parameters, transitioning from number to BigNumberish. The TsFunctionGenerator and TsInterfaceGenerator structs have been modified to accommodate these new types, with adjustments to import statements and method signatures. Additionally, mappings for various JavaScript types have been updated for consistency. Test cases have also been revised to align with these changes.

Changes

File Path Change Summary
crates/dojo/bindgen/src/plugins/typescript/generator/function.rs - Updated check_imports to import both Account and JS_BIGNUMBERISH.
- Changed value parameter type from number to BigNumberish in generate_system_function.
- Adjusted format_function_inputs to generate input signatures with BigNumberish.
crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs - Added constant BIGNUMNERISH_IMPORT for BigNumberish.
- Modified generate method to accept mutable Buffer.
- Updated field types in test_interface_with_inners from number to BigNumberish.
crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs - Introduced a new constants module.
- Updated mappings for types ("felt252", "u8", "u16", "u32", "u64", "u128", "u256", "U256", "i128", "bool") to reference constants.
- Adjusted default values for these types to use constants.
crates/dojo/bindgen/src/plugins/typescript/generator/constants.rs - Added constants for various data types and identifiers used in Cairo and JavaScript, including felt252, ContractAddress, and JS_BIGNUMBERISH.

Possibly related PRs

  • fix: function mappings + object naming #2651: The changes in this PR directly modify the generate_system_function method in the TsFunctionGenerator, which is also a focus of the main PR. Both PRs enhance type handling and address naming conventions in function parameters, ensuring consistency in the generated TypeScript code.

Suggested reviewers

  • glihm

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

🧹 Outside diff range and nitpick comments (3)
crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs (1)

17-20: Nice buffer check implementation!

The conditional check prevents duplicate imports, which is a good practice. However, consider extracting common import handling logic into a shared utility if similar patterns exist in other generators.

crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (1)

Line range hint 197-225: Test coverage looks solid, but could be enhanced!

The test updates properly verify the BigNumberish changes, but we could make them even better.

Consider adding specific test cases for the new i128 type to ensure it behaves correctly in all scenarios:

#[test]
fn test_i128_type() {
    assert_eq!(
        "BigNumberish",
        JsType::from(&Token::CoreBasic(CoreBasic {
            type_path: "core::integer::i128".to_owned()
        }))
    );
}
crates/dojo/bindgen/src/plugins/typescript/generator/function.rs (1)

272-272: Consider consolidating duplicate test cases

Ohayo sensei! I noticed that test_format_function_inputs and test_format_function_inputs_complex have identical expectations and test logic. Consider consolidating these tests or differentiating their test cases to improve test coverage.

- #[test]
- fn test_format_function_inputs_complex() {
-     let generator = TsFunctionGenerator {};
-     let function = create_change_theme_function();
-     let expected = "snAccount: Account, value: BigNumberish";
-     assert_eq!(expected, generator.format_function_inputs(&function))
- }

Also applies to: 280-280

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d005475 and 6a9e5ca.

📒 Files selected for processing (3)
  • crates/dojo/bindgen/src/plugins/typescript/generator/function.rs (3 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs (2 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (4 hunks)
🔇 Additional comments (7)
crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs (3)

7-8: Ohayo! LGTM on the import constant!

The constant BIGNUMNERISH_IMPORT is well-defined and follows the pattern of importing types from starknet.


12-12: Method signature change looks good, sensei!

The change from &Buffer to &mut Buffer is necessary to support the new import functionality.


91-92: Test assertions updated correctly!

The test assertions have been properly updated to reflect the type change from number to BigNumberish, maintaining consistency with the PR objectives.

Please ensure that all other test files that might be asserting against this interface's output are also updated accordingly.

crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (2)

57-67: Ohayo sensei! Comprehensive type mapping update looks good!

The transition from number to BigNumberish for all numeric types is consistent with the PR objectives. The addition of i128 type maintains the pattern.

Consider if smaller integer types (u8, u16) really need BigNumberish, or if they could remain as regular numbers for better performance in cases where the values are guaranteed to be small.


116-116: Clean and consistent default value addition!

The default value for i128 follows the established pattern for numeric types.

crates/dojo/bindgen/src/plugins/typescript/generator/function.rs (2)

15-15: LGTM! Import statement updated correctly

Ohayo sensei! The addition of BigNumberish import alongside Account aligns perfectly with the PR's objective to enhance type support.


238-239: LGTM! Test expectations properly updated

The test expectations now correctly use BigNumberish instead of number for the value parameter, maintaining consistency with the new type system.

Copy link

codecov bot commented Nov 20, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Please upload report for BASE (main@d005475). Learn more about missing BASE report.
Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2705   +/-   ##
=======================================
  Coverage        ?   56.22%           
=======================================
  Files           ?      410           
  Lines           ?    52898           
  Branches        ?        0           
=======================================
  Hits            ?    29742           
  Misses          ?    23156           
  Partials        ?        0           

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


🚨 Try these New Features:

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

🧹 Outside diff range and nitpick comments (2)
crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs (1)

7-7: Ohayo! Fix typo in constant name, sensei!

The constant name contains a typo: BIGNUMNERISH should be BIGNUMBERISH to match the actual type name BigNumberish.

-const BIGNUMNERISH_IMPORT: &str = "import type { BigNumberish } from 'starknet';";
+const BIGNUMBERISH_IMPORT: &str = "import type { BigNumberish } from 'starknet';";
crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (1)

Line range hint 1-324: Consider adding explicit tests for i128, sensei! 🎍

While the implementation for i128 is correct, it would be beneficial to add specific test cases for this new type to ensure it behaves correctly in all scenarios (basic types, tuples, and arrays).

Would you like me to help draft these additional test cases?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6a9e5ca and be29262.

📒 Files selected for processing (3)
  • crates/dojo/bindgen/src/plugins/typescript/generator/function.rs (3 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs (2 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/bindgen/src/plugins/typescript/generator/function.rs
🔇 Additional comments (5)
crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs (2)

12-19: Ohayo! Clean implementation of import management, sensei!

The changes to handle BigNumberish imports are well-implemented:

  • Proper buffer mutability for import management
  • Clean duplicate prevention using has check
  • Follows Rust best practices

91-92: Test expectations properly updated for BigNumberish type!

The test case correctly verifies the generation of TypeScript interfaces with BigNumberish types, providing good coverage of the new type system changes.

crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (3)

57-67: Ohayo! Consistent type mapping for numeric types looks good, sensei! 🎋

The transition from number to BigNumberish for all numeric types (felt252, u8, u16, u32, u64, u128, u256, U256, i128) aligns well with the PR objectives and ensures proper handling of large numbers from torii.


116-116: Default value for i128 is properly aligned with other numeric types

The addition of i128 with a default value of "0" maintains consistency with other numeric type defaults.


197-203: Test cases properly validate BigNumberish type generation, sensei! 🍜

The test cases have been appropriately updated to verify:

  1. Basic type conversion for u8 and felt252 to BigNumberish
  2. Tuple type handling with BigNumberish components
  3. Array type handling with nested BigNumberish types

This comprehensive test coverage ensures the type generation remains reliable.

Also applies to: 211-225

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.

May be easier to change using some constants @MartianGreed. 👍

But not a blocker for me, happy to merge if more urgent stuff is on-going.

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

🧹 Outside diff range and nitpick comments (2)
crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (2)

2-9: Ohayo sensei! Nice architectural improvement with constants extraction!

The introduction of a dedicated constants module and organized imports improves maintainability and follows Rust's module system best practices.


Line range hint 186-232: Consider adding more test cases for comprehensive coverage

The test updates look good, sensei! However, consider adding these test cases:

  • Edge cases for BigNumberish (max/min values)
  • Nested array structures with mixed types
  • Complex tuple combinations

Example test case structure:

#[test]
fn test_complex_nested_types() {
    // Test array of tuples containing BigNumberish and string
    assert_eq!(
        format!("Array<[{}, string]>", JS_BIGNUMBERISH).as_str(),
        JsType::from(&Token::Array(/* ... */))
    );
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between be29262 and dd55a6f.

📒 Files selected for processing (2)
  • crates/dojo/bindgen/src/plugins/typescript/generator/constants.rs (1 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/dojo/bindgen/src/plugins/typescript/generator/constants.rs
🔇 Additional comments (2)
crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (2)

112-123: Default values look solid, sensei!

The default values are type-safe, consistent, and follow TypeScript/JavaScript conventions. The numeric types defaulting to "0" aligns well with the BigNumberish type system.


63-74: Verify type compatibility with torii component

The type mappings look good, sensei! The transition to BigNumberish for numeric types aligns perfectly with the PR objectives. However, let's verify the compatibility:

✅ Verification successful

Type mappings are correctly implemented and compatible with torii

Ohayo sensei! After reviewing the codebase, I can confirm that the type mappings are perfectly aligned and compatible:

  • The example TypeScript file shows that numeric types are already using BigNumberish in the generated code
  • The torii client integration in the codebase correctly handles these types through the valueToToriiValueAndOperator function
  • The interface generator properly imports and uses BigNumberish type from 'starknet'
  • The type mappings in the constants file are consistent with the PR changes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify type usage consistency across the codebase

# Check for any remaining direct 'number' type usage that should be BigNumberish
rg -g '*.ts' 'type.*:.*\bnumber\b'

# Check torii component type definitions for compatibility
rg -g '*.ts' 'type.*BigNumberish'

Length of output: 72


Script:

#!/bin/bash
# Let's check the repository structure first to locate TypeScript files
fd -e ts

# Then let's search for BigNumberish type imports and usage
rg -l "BigNumberish"

# Check for number type declarations in TypeScript interfaces and types
rg --type typescript "interface.*\{[\s\S]*?number.*?\}" -A 5

# Look for type definitions specifically in torii related files
fd -e ts torii

Length of output: 400


Script:

#!/bin/bash
# Let's examine the content of the example TypeScript file
cat crates/dojo/bindgen/src/test_data/mocks/dojo_examples.ts

# Check the constants file where BigNumberish is used
cat crates/dojo/bindgen/src/plugins/typescript/generator/constants.rs

# Look for any type definitions in the function generator
cat crates/dojo/bindgen/src/plugins/typescript/generator/function.rs

# Check interface generator implementation
cat crates/dojo/bindgen/src/plugins/typescript/generator/interface.rs

Length of output: 27959

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.

Some constants usage missing and let's merge. :)

@@ -12,7 +12,7 @@ impl TsFunctionGenerator {
fn check_imports(&self, buffer: &mut Buffer) {
if !buffer.has("import { DojoProvider } from ") {
buffer.insert(0, "import { DojoProvider } from \"@dojoengine/core\";".to_owned());
buffer.insert(1, "import { Account } from \"starknet\";".to_owned());
buffer.insert(1, "import { Account, BigNumberish } from \"starknet\";".to_owned());
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
buffer.insert(1, "import { Account, BigNumberish } from \"starknet\";".to_owned());
buffer.insert(1, "import { Account, JS_BIGNUMBERISH } from \"starknet\";".to_owned());

Use the newly defined constant.

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

🧹 Outside diff range and nitpick comments (2)
crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (2)

112-123: Consider documenting BigNumberish default values

While the default values remain as "0" for all numeric types including the new i128, it would be helpful to document that these are now interpreted as BigNumberish values.

+ // Default values are represented as strings but should be interpreted as BigNumberish
  match value {
      CAIRO_FELT252 => JsDefaultValue("0".to_string()),

204-210: Consider adding BigNumberish edge case tests

The tests have been updated to use JS_BIGNUMBERISH, but we could strengthen them by adding edge cases specific to BigNumberish values.

Consider adding tests for:

  1. Maximum safe integer values
  2. Values requiring BigNumberish representation
  3. Negative values for i128

Also applies to: 218-218, 232-232

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dd55a6f and 33d0043.

📒 Files selected for processing (3)
  • crates/dojo/bindgen/src/plugins/typescript/generator/constants.rs (1 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/function.rs (4 hunks)
  • crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/dojo/bindgen/src/plugins/typescript/generator/constants.rs
  • crates/dojo/bindgen/src/plugins/typescript/generator/function.rs
🔇 Additional comments (2)
crates/dojo/bindgen/src/plugins/typescript/generator/mod.rs (2)

2-6: Ohayo sensei! Clean organization of constants!

The separation of constants into a dedicated module and the well-structured imports improve code maintainability.

Also applies to: 9-9


63-74: Verify callers are ready for BigNumberish transition

The transition from number to BigNumberish for all numeric types is consistent with the PR objectives. However, we should verify that all consumers are prepared for this change.

✅ Verification successful

Ohayo sensei! The BigNumberish transition is properly implemented

The code generator correctly handles the BigNumberish type transition:

  • Automatically imports BigNumberish from 'starknet' in generated files
  • Consistently maps all numeric Cairo types to BigNumberish
  • Test files confirm the correct type mappings
  • The generator's test suite validates the numeric type conversions

The mock files still using number are test fixtures and not actual generated code, so they don't affect the implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct number type usage in TypeScript files
rg -t ts ":\s*number" 

# Search for potential BigNumberish imports
rg -t ts "BigNumberish"

Length of output: 515


Script:

#!/bin/bash
# Let's check the test files and generated code for BigNumberish usage
fd -e ts -x cat {} | grep -i "bignumberish"

# Let's check the actual TypeScript output directory for generated files
fd "\.ts$" crates/dojo/bindgen/src/test_data/output -x cat {} | grep -E ":\s*(number|BigNumberish)"

# Let's also check for any type definitions or interfaces that might show the type mappings
ast-grep --pattern 'interface $_ {
  $$$
}'

Length of output: 3166


Script:

#!/bin/bash
# Let's check the TypeScript generator implementation for where these types are used
ast-grep --pattern 'function $name($$$) {
  $$$
  JS_BIGNUMBERISH
  $$$
}'

# Let's also check for any test files that might show the generated output
fd -e rs "test" -x cat {} | grep -A 5 -B 5 "JS_BIGNUMBERISH"

# And check where the JS type constants are defined
rg "JS_BIGNUMBERISH|JS_NUMBER" -A 2 -B 2

Length of output: 6477

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