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

Update for controller 0.5.0 (without starknet-react v3) #282

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

starknetdev
Copy link
Member

@starknetdev starknetdev commented Oct 24, 2024

  • update controller version
  • update controller interface

Summary by CodeRabbit

  • New Features

    • Updated the connector used in various components to improve functionality and user interactions.
  • Bug Fixes

    • Ensured the Withdraw button is conditionally enabled based on the connector's state.
  • Documentation

    • Clarified import statements and updated terminology for better consistency across components.

- update controller interface
Copy link

vercel bot commented Oct 24, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
loot-survivor ❌ Failed (Inspect) Oct 24, 2024 9:26pm

Copy link

coderabbitai bot commented Oct 24, 2024

Walkthrough

The pull request introduces significant updates across multiple files in the LootSurvivor project. The primary change is the update of the @cartridge/connector dependency version in package.json. Additionally, several components, including WalletSection, ProfileDialog, and connectors.ts, have undergone modifications to replace references to CartridgeConnector with ControllerConnector, reflecting a change in terminology and functionality. These updates affect the import statements, variable names, and how connectors are utilized within the components, while the overall structure and logic remain largely intact.

Changes

File Change Summary
ui/package.json Updated @cartridge/connector from ^0.3.44 to 0.5.0-alpha.1.
ui/src/app/components/onboarding/Sections/WalletSection.tsx Renamed cartridgeConnector to controllerConnector; reordered import statements.
ui/src/app/components/profile/ProfileDialog.tsx Replaced CartridgeConnector with ControllerConnector; updated method calls for settings and withdrawals.
ui/src/app/lib/connectors.ts Removed CartridgeConnector import; renamed cartridgeConnector to controllerConnector; removed paymaster property.
ui/src/app/page.tsx Replaced CartridgeConnector with ControllerConnector; adjusted type casting in useEffect.
ui/src/app/provider.tsx Updated imports to use controllerConnector; modified StarknetConfig to include the new connector.

Possibly related PRs

  • Implement changing adventurer name #276: The main PR updates the @cartridge/connector dependency, which is relevant to the changes in the ProfileDialog, WalletSection, and other components that utilize the connector. The changes in the main PR may affect how these components interact with the updated connector, particularly in the context of managing adventurer names and related functionalities.

🐰 In the meadow, hops a rabbit bright,
With changes afoot, oh what a delight!
Connectors renamed, and versions anew,
With every small tweak, the project will bloom.
So let’s celebrate, with a joyful cheer,
For the code is now better, let’s give a big cheer! 🎉


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4dc7220 and 65ef546.

📒 Files selected for processing (1)
  • ui/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ui/package.json

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.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
ui/src/app/provider.tsx (1)

Line range hint 40-46: Consider adding error handling for missing network config parameters.

The network configuration parameters are accessed with the non-null assertion operator (!), which could lead to runtime errors if the network configuration is incomplete.

Consider adding validation:

-        controllerConnector(
-          networkConfig[network!].gameAddress,
-          networkConfig[network!].lordsAddress,
-          networkConfig[network!].ethAddress,
-          networkConfig[network!].rpcUrl
-        ),
+        (() => {
+          const config = networkConfig[network!];
+          if (!config?.gameAddress || !config?.lordsAddress || 
+              !config?.ethAddress || !config?.rpcUrl) {
+            throw new Error(`Incomplete network configuration for ${network}`);
+          }
+          return controllerConnector(
+            config.gameAddress,
+            config.lordsAddress,
+            config.ethAddress,
+            config.rpcUrl
+          );
+        })(),
ui/src/app/lib/connectors.ts (1)

Line range hint 58-98: Review and document the security implications of approved methods.

The policies array defines a whitelist of contract methods that can be called. This is security-critical configuration that should be well-documented and carefully reviewed.

Consider:

  1. Adding comments explaining the security implications of each approved method
  2. Documenting the process for updating this whitelist
  3. Adding validation for the contract addresses passed to the function
ui/src/app/components/onboarding/Sections/WalletSection.tsx (1)

21-23: Inconsistent naming between code and UI text

The connector ID uses "controller" while the button text still displays "Cartridge Controller". This inconsistency might be confusing for maintenance. Consider updating the button text to match the new terminology.

-            Login with Cartridge Controller
+            Login with Controller

Also applies to: 61-64, 83-86

ui/src/app/page.tsx (1)

Line range hint 279-289: Consider improving the controller initialization logic

While the implementation works, there are a few potential improvements:

  1. The connector ID check using includes("controller") might be too permissive. Consider using a more specific check.
  2. The username() call lacks error handling.

Consider this more robust implementation:

-    if (connector?.id.includes("controller")) {
+    if (connector?.id === "controller") {  // Use exact match
       setIsController(true);
-      init();
+      try {
+        await init();
+      } catch (error) {
+        console.error("Failed to initialize controller:", error);
+        setIsController(false);
+        setControllerDelegate("");
+        setUsername("");
+      }
     } else {
       setIsController(false);
       setControllerDelegate("");
       setUsername("");
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0370e3b and 4dc7220.

⛔ Files ignored due to path filters (1)
  • ui/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • ui/package.json (1 hunks)
  • ui/src/app/components/onboarding/Sections/WalletSection.tsx (4 hunks)
  • ui/src/app/components/profile/ProfileDialog.tsx (2 hunks)
  • ui/src/app/lib/connectors.ts (2 hunks)
  • ui/src/app/page.tsx (2 hunks)
  • ui/src/app/provider.tsx (2 hunks)
🔇 Additional comments (11)
ui/src/app/provider.tsx (2)

Line range hint 40-46: LGTM: Connector configuration is properly updated.

The controllerConnector is correctly initialized with all required network parameters.


2-9: Verify @cartridge/connector version compatibility.

The import changes align with the controller update. Let's verify the dependency version compatibility.

✅ Verification successful

Import changes are correctly aligned with dependencies

The verification confirms that:

  • @cartridge/connector version 0.5.0-alpha.0 is present in ui/package.json
  • The controllerConnector import is correctly sourced from the local path @/app/lib/connectors
  • The implementation in ui/src/app/lib/connectors.ts shows proper integration with @cartridge/connector/controller

The import changes are consistent with the codebase and the dependency versions align with the controller 0.5.0 update mentioned in the PR objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check package.json for @cartridge/connector version
echo "Checking package.json for @cartridge/connector version:"
cat package.json | grep -A 5 "@cartridge/connector"

Length of output: 217


Script:

#!/bin/bash
# Let's first find the package.json file
echo "Looking for package.json files:"
fd "package.json" --type f

# Let's also check if the import path exists
echo -e "\nChecking for controllerConnector import:"
rg "controllerConnector" --type ts --type tsx -C 2

Length of output: 291


Script:

#!/bin/bash
# Check ui/package.json for dependencies
echo "Checking ui/package.json for dependencies:"
cat ui/package.json | jq '.dependencies'

# Check for controllerConnector without file type restriction
echo -e "\nChecking for controllerConnector usage:"
rg "controllerConnector" -C 2

# Check for any connector-related imports
echo -e "\nChecking for connector-related imports:"
rg "import.*connector" -i -C 2

Length of output: 9599

ui/package.json (2)

13-13: Verify alpha version usage in production.

The update to 0.5.0-alpha.0 introduces an alpha (pre-release) version. Alpha releases are typically unstable and not recommended for production use. Additionally, the exact version pinning (removing ^) prevents receiving bug fixes.

Consider:

  1. Waiting for a stable release
  2. Or if alpha is required, document the known limitations and test thoroughly
  3. Using ^0.5.0-alpha.0 to receive critical fixes within the alpha series

13-13: Verify compatibility with Starknet dependencies.

The controller update might have compatibility requirements with Starknet-related packages. Let's verify the dependencies.

Also applies to: 15-16

ui/src/app/lib/connectors.ts (3)

51-57: Verify impact of removed paymaster configuration.

The paymaster configuration has been removed in this update. This could affect how transaction fees are handled.

#!/bin/bash
# Description: Look for paymaster-related code and documentation
# Expected: Find evidence of how transaction fees are now handled

# Search for paymaster references in the codebase
echo "Checking for paymaster usage:"
rg -l "paymaster|transaction.*fee" --type ts

# Look for migration guides or documentation
echo "Checking for migration documentation:"
fd -e md . | xargs rg -l "0\.5\.0|migration|upgrade"

57-57: ⚠️ Potential issue

Consider removing unsafe type assertion.

The as never as Connector type assertion is a code smell that bypasses TypeScript's type checking. Consider using proper typing from the ControllerConnector package.

-  }) as never as Connector;
+  }) as Connector;

Likely invalid or redundant comment.


1-1: Verify the new controller import path.

The import path has changed from @cartridge/connector to @cartridge/connector/controller. Let's verify this is the correct import path for version 0.5.0.

✅ Verification successful

Import path change is consistent across the codebase

The import path @cartridge/connector/controller is consistently used across multiple files in the UI codebase:

  • ui/src/app/page.tsx
  • ui/src/app/lib/connectors.ts
  • ui/src/app/components/profile/ProfileDialog.tsx

This consistent usage pattern across different components suggests this is the correct import path for the updated controller version.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the package structure and import path
# Expected: Find evidence of the correct import path in package documentation or type definitions

# Check if the package.json specifies the correct version
echo "Checking package version:"
jq -r '.dependencies["@cartridge/connector"]' package.json

# Look for type definitions or documentation that confirms the import path
echo "Checking for type definitions:"
fd -e d.ts -e ts "controller.d.ts|index.d.ts" node_modules/@cartridge/connector

Length of output: 360


Script:

#!/bin/bash
# Let's try a different approach to verify the import path

# Check for any references to the controller import path in the codebase
echo "Checking for controller import usage patterns:"
rg -l "@cartridge/connector/controller" --type ts

# Look for any migration guides or documentation
echo "Checking documentation for migration info:"
rg -A 5 "0.5.0|migration|upgrade" README.md

# Check the actual structure of imports in the codebase
echo "Analyzing import patterns:"
ast-grep --pattern 'import $_ from "@cartridge/connector/$_"'

# Look for package.json in the repository
echo "Looking for package.json files:"
fd package.json

Length of output: 1481

ui/src/app/components/onboarding/Sections/WalletSection.tsx (1)

60-62: Consider UX impact of forced disconnection

The current implementation forces a disconnect before connecting with a new connector. This might lead to a jarring user experience, especially if the user is already connected with the desired wallet.

Also applies to: 82-84

ui/src/app/components/profile/ProfileDialog.tsx (2)

Line range hint 121-141: Review security implications of withdrawal functionality.

The withdrawal functionality has several security considerations that should be verified:

  1. The controller delegate validation only checks for "0x0" or empty string. Consider adding more robust validation.
  2. The withdrawal amount validation isn't visible in this component.
  3. The controller settings can be changed during an active withdrawal process.

10-10: Verify the continued usage of CartridgeIcon and checkCartridgeConnector.

While the connector has been updated to use ControllerConnector, the component still uses CartridgeIcon and checkCartridgeConnector. This might need to be updated for consistency with the new controller terminology.

ui/src/app/page.tsx (1)

69-69: LGTM: Import updated to use ControllerConnector

The import statement has been correctly updated to use the new ControllerConnector from the specific controller module path.

Comment on lines 60 to 64
disconnect();
connect({ connector: cartridgeConnector });
connect({ connector: controllerConnector });
}}
>
Login with Cartridge Controller
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicated connection logic

The connection handling logic is duplicated between mobile and desktop versions. Consider extracting this into a reusable function to improve maintainability.

+  const handleConnect = (connector: any) => {
+    disconnect();
+    connect({ connector });
+  };
+
   // In desktop version
   <Button
     onClick={() => {
-      disconnect();
-      connect({ connector: controllerConnector });
+      handleConnect(controllerConnector);
     }}
   >

   // In mobile version
   <Button
     onClick={() => {
-      disconnect();
-      connect({ connector: controllerConnector });
+      handleConnect(controllerConnector);
     }}
   >

Also applies to: 82-86

Comment on lines +121 to +123
(
connector as unknown as ControllerConnector
).controller.openSettings()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety by avoiding unsafe type casting.

The current implementation uses an unsafe type cast with unknown. Consider using a type-safe approach:

-                    (
-                      connector as unknown as ControllerConnector
-                    ).controller.openSettings()
+                    (connector as ControllerConnector).controller.openSettings()

Better yet, consider updating the connector's type definition:

interface ConnectHookState {
  connector: ControllerConnector | undefined;
  // ... other properties
}

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