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: Reconnect to Wallet Connect session on signing #251

Merged
merged 4 commits into from
Oct 26, 2024

Conversation

rossbulat
Copy link
Collaborator

@rossbulat rossbulat commented Oct 26, 2024

Reconnects to a WC session when signing a transaction if needed, and checks if the signer address is a part of the WC session.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a fetchAccounts method for retrieving account addresses based on the active chain.
    • Enhanced WalletConnect session management during transaction signing.
  • Bug Fixes

    • Improved error handling during the signing process to ensure consistent state management.
  • Style

    • Adjusted z-index values for modal components to improve visibility and layering.

These updates enhance user experience by streamlining account retrieval and improving session management.

Copy link

coderabbitai bot commented Oct 26, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces a new method fetchAccounts to the WalletConnect context and related components, enhancing account retrieval functionality based on a specified chain ID. This method is added to the defaultWalletConnect object and the WalletConnectContextInterface. The ManageWalletConnect component is updated to utilize this new method, simplifying account management by removing session initialization logic. Additionally, several z-index values in the modal components are adjusted for better layering. Overall, the changes focus on improving the WalletConnect integration and account handling.

Changes

File Path Change Summary
packages/app/src/contexts/WalletConnect/defaults.ts Added method fetchAccounts(directoryId) to defaultWalletConnect, returning a resolved promise with an empty array.
packages/app/src/contexts/WalletConnect/index.tsx Introduced fetchAccounts(chainid: ChainId): Promise<string[]>, updated context provider to include this method.
packages/app/src/contexts/WalletConnect/types.ts Added method signature fetchAccounts(directoryId: ChainId) => Promise<string[]> to WalletConnectContextInterface.
packages/app/src/library/ConnectOverlay/ManageWalletConnect.tsx Added fetchAccounts to the useWalletConnect hook, simplified handleImportAddresses to directly call fetchAccounts.
packages/app/src/library/Overlay/index.scss Adjusted z-index values for modal components, reducing values for several classes.
packages/app/src/library/SubmitTx/ManualSign/WalletConnect/index.tsx Updated useWalletConnect to destructure fetchAccounts, enhanced transaction signing logic with account validation.

Possibly related PRs

🐇 In the meadow, hopping around,
A new method's here, accounts to be found!
With fetchAccounts, we simplify the way,
No more sessions to manage, hip-hip-hooray!
So let’s connect and sign with glee,
A smoother journey, just wait and see! 🌼


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 (2)
packages/app/src/contexts/WalletConnect/defaults.ts (1)

14-14: Consider adding JSDoc documentation for the new method.

For consistency and better developer experience, consider adding JSDoc documentation to describe the purpose of fetchAccounts and its directoryId parameter.

+  /** Fetches accounts associated with the given directory ID.
+   * @param directoryId - The ID of the directory to fetch accounts from
+   * @returns A promise that resolves to an array of accounts
+   */
   fetchAccounts: (directoryId) => Promise.resolve([]),
packages/app/src/library/SubmitTx/ManualSign/WalletConnect/index.tsx (1)

63-78: Consider improving error handling and user feedback

While the session reconnection logic is solid, consider these improvements:

  1. Add specific error handling for different failure scenarios
  2. Provide user feedback during the reconnection process

Consider this enhancement:

 buttonOnClick = async () => {
   setIsSigning(true);
   
   // If Wallet Connect session is not active, re-connect.
   if (!wcSessionActive) {
+    // Inform user about reconnection
+    toast.info('Reconnecting to WalletConnect...');
     await connectProvider();
   }

   const caip = getChainIdCaip(chainId);
   const wcAccounts = await fetchAccounts(chainId as ChainId);

   // Re-fetch accounts here to ensure that the signer address still exists.
   const accountExists = from && wcAccounts.includes(from);

   const payload = getTxPayloadValue(instanceId);
   if (!from || !payload || !accountExists) {
+    // Provide specific error messages
+    if (!from) toast.error('Sender address not found');
+    if (!accountExists) toast.error('Account no longer exists in WalletConnect session');
+    if (!payload) toast.error('Transaction payload is missing');
     setIsSigning(false);
     return;
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9181f6c and 84cf4e4.

📒 Files selected for processing (6)
  • packages/app/src/contexts/WalletConnect/defaults.ts (1 hunks)
  • packages/app/src/contexts/WalletConnect/index.tsx (3 hunks)
  • packages/app/src/contexts/WalletConnect/types.ts (2 hunks)
  • packages/app/src/library/ConnectOverlay/ManageWalletConnect.tsx (2 hunks)
  • packages/app/src/library/Overlay/index.scss (6 hunks)
  • packages/app/src/library/SubmitTx/ManualSign/WalletConnect/index.tsx (3 hunks)
🔇 Additional comments (13)
packages/app/src/contexts/WalletConnect/defaults.ts (1)

14-14: LGTM! Default implementation follows established patterns.

The placeholder implementation of fetchAccounts aligns well with other default methods in the context, maintaining consistency in the default behavior pattern.

packages/app/src/contexts/WalletConnect/types.ts (1)

5-5: LGTM! Let's verify the implementation.

The new fetchAccounts method is well-defined and aligns with the PR objectives for enhancing WalletConnect session management.

Let's verify the implementation and usage:

Also applies to: 14-14

✅ Verification successful

Let me gather more information about the implementation details since we found usage but not the actual implementation.

This will help us verify:

  1. The actual implementation of fetchAccounts
  2. The complete interface definition
  3. The default implementation if any
  4. How it fits with the rest of the context

Implementation verified and properly integrated

The fetchAccounts method is correctly implemented and used:

  • Implementation in context properly handles WalletConnect session management
  • Used appropriately in ManualSign/WalletConnect and ConnectOverlay/ManageWalletConnect components
  • Default implementation provides safe fallback
  • Follows the interface contract returning Promise<string[]>
  • Correctly filters accounts by chain ID using CAIP format
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation and usage of fetchAccounts method

# Test 1: Check implementation in defaults
echo "Checking implementation in defaults..."
rg -A 5 "fetchAccounts.*:.*Promise<string\[\]>" "packages/app/src/contexts/WalletConnect/defaults.ts"

# Test 2: Check implementation in context
echo "Checking implementation in context..."
rg -A 10 "fetchAccounts.*=.*async.*directoryId" "packages/app/src/contexts/WalletConnect/index.tsx"

# Test 3: Check usage in components
echo "Checking usage in components..."
rg "fetchAccounts" "packages/app/src/library"

Length of output: 976


Script:

#!/bin/bash
# Check the WalletConnect context implementation
echo "Checking WalletConnect context implementation..."
cat "packages/app/src/contexts/WalletConnect/index.tsx"

# Check the interface definition
echo "Checking interface definition..."
cat "packages/app/src/contexts/WalletConnect/types.ts"

# Check defaults implementation
echo "Checking defaults implementation..."
cat "packages/app/src/contexts/WalletConnect/defaults.ts"

Length of output: 12881

packages/app/src/library/SubmitTx/ManualSign/WalletConnect/index.tsx (4)

16-16: LGTM: Hook usage properly expanded for session management

The additional properties from useWalletConnect (wcSessionActive, fetchAccounts, connectProvider) align well with the PR's objective of handling session reconnection.

Also applies to: 36-37


39-39: LGTM: Good practice in sender address handling

Early capture of the sender address improves code readability and prevents potential inconsistencies.


95-96: LGTM: Clear documentation and state representation

The comments clearly explain the purpose of the text updates, and the state handling properly reflects the signing process to the user.


36-37: Verify WalletConnect usage across the application

Let's ensure consistent WalletConnect session handling across other components.

✅ Verification successful

Based on the search results, I can now provide a final response as we have sufficient information about WalletConnect usage across the application:

WalletConnect integration is consistently implemented

The WalletConnect implementation is properly centralized and consistently used across the application:

  • Main context provider in contexts/WalletConnect/index.tsx
  • Used in only two components:
    • library/ConnectOverlay/ManageWalletConnect.tsx for connection management
    • library/SubmitTx/ManualSign/WalletConnect/index.tsx for transaction signing

Both components follow the same session handling pattern using wcSessionActive and connectProvider, ensuring consistent behavior across the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other components using WalletConnect hooks
echo "Searching for other WalletConnect hook usages:"
rg "useWalletConnect" --type tsx -l

# Search for potential session handling patterns
echo -e "\nSearching for WalletConnect session handling patterns:"
rg "wcSessionActive|connectProvider" --type tsx -A 3

Length of output: 374


Script:

#!/bin/bash
# Search for WalletConnect hook usages without file type restriction
echo "Searching for WalletConnect hook usages:"
rg "useWalletConnect"

# Search for WalletConnect session handling patterns
echo -e "\nSearching for WalletConnect session handling patterns:"
rg "wcSessionActive|connectProvider"

# Find all TypeScript/React files that might use WalletConnect
echo -e "\nFinding relevant TypeScript/React files:"
fd "\.(tsx?|jsx?)$"

Length of output: 25451

packages/app/src/library/ConnectOverlay/ManageWalletConnect.tsx (3)

36-36: LGTM: New account fetching capability added.

The addition of fetchAccounts to the hook dependencies aligns with the PR's objective of improving WalletConnect session management.


Line range hint 165-175: Potential race condition in connect flow.

The sequential calls to connectProvider, initializeWcSession, and handleImportAddresses could lead to a race condition if the session isn't fully established before fetching accounts.

Let's verify the session initialization flow:

#!/bin/bash
# Search for session initialization patterns
ast-grep --pattern 'initializeWcSession = async () => {
  $$$
}'

Consider:

  1. Adding state checks between operations
  2. Implementing a retry mechanism for failed connections
  3. Adding timeouts to prevent hanging operations

Example approach:

const ensureConnection = async () => {
  if (!wcSessionActive) {
    await connectProvider();
    // Add timeout and retry logic
    const sessionInitialized = await initializeWcSession();
    if (!sessionInitialized) {
      throw new Error('Failed to initialize session');
    }
  }
  return true;
};

92-93: 🛠️ Refactor suggestion

Consider enhancing error handling for account fetching.

While the simplified account fetching logic is cleaner, consider adding:

  1. Error handling for failed account fetches
  2. Validation of directoryId before making the call
  3. User feedback during the fetch operation

Let's verify the error handling in the fetchAccounts implementation:

Consider adding error handling:

 // Fetch accounts from Wallet Connect.
-const filteredAccounts = await fetchAccounts(directoryId);
+try {
+  const filteredAccounts = await fetchAccounts(directoryId);
+  // Save accounts to local storage.
+  filteredAccounts.forEach((address) => {
+    addWcAccount(directoryId, address, wcAccounts.length);
+  });
+} catch (error) {
+  console.error('Failed to fetch accounts:', error);
+  // Consider showing user feedback here
+} finally {
+  setImportActive(false);
+}
-// Save accounts to local storage.
-filteredAccounts.forEach((address) => {
-  addWcAccount(directoryId, address, wcAccounts.length);
-});
-
-setImportActive(false);
packages/app/src/library/Overlay/index.scss (1)

72-72: Verify z-index adjustments across the application.

The z-index values have been consistently decreased by 10 across all modal components. While the relative stacking order is maintained, we should ensure these changes don't affect the visibility of modals in relation to other UI elements.

Let's check for potential z-index conflicts:

Consider adding a comment to document the z-index ranges:

/* Z-index hierarchy:
 * modal-canvas: 90
 * modal components (container, overlay, scroll): 89
 * close buttons: 88
 */

Also applies to: 78-78, 96-96, 185-185, 199-199, 418-418, 445-445

✅ Verification successful

Z-index adjustments are safe to proceed

The search results confirm that the z-index values in the range 88-90 are only used within the Overlay component itself, with no conflicts found in other SCSS/CSS files. The relative stacking order is maintained consistently across all modal-related elements:

  • modal-canvas: 90
  • modal components (container, overlay, scroll): 89
  • close buttons: 88
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for z-index declarations in other SCSS/CSS files
# that might conflict with the new modal z-index range (88-90)

echo "Searching for z-index declarations in the range 88-99..."
rg -g '*.{scss,css}' 'z-index:\s*(8[8-9]|9[0-9])\b'

Length of output: 597

packages/app/src/contexts/WalletConnect/index.tsx (3)

16-16: LGTM: Type import enhances type safety

The addition of the ChainId type import improves type safety for chain identifier handling.


363-363: LGTM: Context properly exposes the new method

The fetchAccounts method is correctly added to the context provider value.


284-315: Verify integration with transaction signing flow

The implementation supports automatic session reconnection, but let's verify its integration with the transaction signing flow.

✅ Verification successful

Integration with transaction signing flow is properly implemented

The implementation is correctly integrated with the transaction signing flow:

  • fetchAccounts is called before signing in ManualSign/WalletConnect/index.tsx to verify the signer address still exists in the active session
  • The signing flow includes proper session initialization through initializeWcSession called within fetchAccounts
  • Error cases are handled through account existence checks before proceeding with signing
  • The implementation follows the WalletConnect context interface defined in types.ts

Key integration points:

  • packages/app/src/library/SubmitTx/ManualSign/WalletConnect/index.tsx: Verifies signer existence before signing
  • packages/app/src/contexts/WalletConnect/index.tsx: Implements the signing logic with proper session handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of fetchAccounts with transaction signing

# Check for transaction signing components that should use fetchAccounts
echo "Searching for transaction signing components..."
rg -l "signWcTx.*fetchAccounts" --type ts --type tsx

# Check for proper error handling in signing flow
echo "Checking error handling in signing flow..."
rg "signWcTx.*catch" --type ts --type tsx -A 5

Length of output: 359


Script:

#!/bin/bash
# Let's try a different approach to find the integration points

# Search for WalletConnect signing related functions
echo "Searching for WalletConnect signing functions..."
rg "signWc.*" -t typescript -t typescriptreact

# Search for fetchAccounts usage
echo "Searching for fetchAccounts usage..."
rg "fetchAccounts" -t typescript -t typescriptreact

# Look for WalletConnect session handling in signing
echo "Searching for WalletConnect session handling..."
rg "wcSession.*sign" -t typescript -t typescriptreact

Length of output: 556


Script:

#!/bin/bash
# Let's try without file type specifications since they're not recognized

# Search for WalletConnect signing related functions
echo "Searching for WalletConnect signing functions..."
rg "signWc"

# Search for fetchAccounts usage
echo "Searching for fetchAccounts usage..."
rg "fetchAccounts" -A 3 -B 3

# Look for WalletConnect session handling in signing
echo "Searching for WalletConnect session handling..."
rg "wcSession.*sign"

# Also search for any signing-related functions in the context
echo "Searching for general signing functions..."
rg "sign.*transaction|sign.*tx" -A 3

Length of output: 9802

@rossbulat rossbulat merged commit 52f2219 into main Oct 26, 2024
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

1 participant