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: rainbow connect + translations + remove unused code #1128

Merged
merged 1 commit into from
Oct 29, 2024

Conversation

thierryskoda
Copy link
Collaborator

@thierryskoda thierryskoda commented Oct 29, 2024

…nslations

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced wallet connection process with improved state management and error handling.
    • Dynamic subtitle localization for private key connection based on the user's platform (iOS/Android).
  • Bug Fixes

    • Improved user feedback during wallet connection attempts, including specific error messages for connection failures.
  • Documentation

    • Updated comments for better clarity in the connection handling logic.
  • Chores

    • Cleaned up unused code and improved overall readability of the components.

@thierryskoda thierryskoda requested a review from a team as a code owner October 29, 2024 12:46
Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The pull request introduces multiple modifications across several components related to wallet connectivity. Key changes include refining the context value handling in ConnectViaWalletContextProvider, enhancing wallet connection logic and error handling in InstalledWalletsTableView, and improving navigation behavior in various screens using useFocusEffect. Additionally, localization for subtitles is enhanced based on the platform in relevant screens. Overall, these changes streamline wallet connection processes and improve user feedback and navigation.

Changes

File Change Summary
components/Onboarding/ConnectViaWallet/ConnectViaWallet.context.tsx Updated ConnectViaWalletContextProvider to accept explicit parameters for context values instead of a spread object, enhancing clarity.
components/Onboarding/ConnectViaWallet/ConnectViaWalletTableViewItems.tsx Enhanced wallet connection functionality with state management and improved error handling. Removed functions related to obtaining signers and addresses, consolidating logic within the component.
components/Onboarding/ConnectViaWallet/useInitConnectViaWalletState.ts Removed unused disconnect functionality and streamlined control flow by adjusting dependencies in useEffect hooks.
navigation/useNavigation.tsx Modified useRouter function to change the memoization strategy and added console logs for listener cleanup.
screens/NewAccount/NewAccountConnectWalletScreen.tsx Implemented useFocusEffect to manage navigation based on wallet connection state and updated connection handling logic.
screens/NewAccount/NewAccountPrivateKeyScreen.tsx Enhanced subtitle localization by incorporating platform-specific translation logic.
screens/NewAccount/NewAccountUserProfileScreen.tsx Changed import order for TextInput and useColorScheme, with no functional changes.
screens/Onboarding/OnboardingConnectWalletScreen.tsx Added useFocusEffect to manage navigation based on wallet connection state, improving user experience.
screens/Onboarding/OnboardingPrivateKeyScreen.tsx Updated subtitle translation logic to dynamically select based on the platform, enhancing localization.

Possibly related PRs

  • [feat: remove split screen stuff #1105] The main PR modifies the ConnectViaWalletContextProvider component, while the retrieved PR focuses on removing split-screen logic from various components. Although both involve component modifications, they target different functionalities and do not share direct code changes or related components.

Suggested reviewers

  • alexrisch

Poem

🐰 In the world of wallets, we hop and play,
With clearer paths, we find our way.
Connections made, with joy we cheer,
A seamless journey, no need to fear.
So let's connect, and dance in delight,
For every wallet brings us closer, just right! 🎉


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
Contributor

Performance Comparison Report

  • Current: 982da23 - 2024-10-29 12:49:49Z
  • Baseline: release/2.0.8 (4745a3a) - 2024-10-29 12:49:10Z

Significant Changes To Duration

There are no entries

Meaningless Changes To Duration

Show entries
Name Type Duration Count
Avatar Image 10 runs render 1.2 ms → 1.3 ms (+0.1 ms, +8.3%) 1 → 1
Avatar Image 50 runs render 1.2 ms → 1.1 ms (-0.1 ms, -8.6%) 1 → 1
Empty Avatar 10 runs render 1.0 ms → 1.2 ms (+0.2 ms, +20.0%) 🔴 1 → 1
Empty Avatar 50 runs render 0.8 ms → 0.6 ms (-0.2 ms, -26.3%) 🟢 1 → 1
Show details
Name Type Duration Count
Avatar Image 10 runs render Baseline
Mean: 1.2 ms
Stdev: 0.4 ms (35.1%)
Runs: 2 2 1 1 1 1 1 1 1 1
Warmup runs: 2

Current
Mean: 1.3 ms
Stdev: 0.5 ms (37.2%)
Runs: 2 1 2 2 1 1 1 1 1 1
Warmup runs: 2
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Avatar Image 50 runs render Baseline
Mean: 1.2 ms
Stdev: 0.4 ms (31.9%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 2 1 2 1 1 1 1 1 1 2 1 1 2 2 1 1 1 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1
Warmup runs: 2

Current
Mean: 1.1 ms
Stdev: 0.2 ms (22.6%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1
Warmup runs: 1
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:
Empty Avatar 10 runs render Baseline
Mean: 1.0 ms
Stdev: 0.7 ms (66.7%)
Runs: 2 2 1 0 1 0 1 1 1 1
Warmup runs: 75

Current
Mean: 1.2 ms
Stdev: 0.4 ms (35.1%)
Runs: 1 2 1 1 1 1 1 1 2 1
Warmup runs: 8
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Empty Avatar 50 runs render Baseline
Mean: 0.8 ms
Stdev: 0.4 ms (56.8%)
Runs: 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 0 0 0
Warmup runs: 1

Current
Mean: 0.6 ms
Stdev: 0.5 ms (89.5%)
Runs: 1 0 0 1 1 1 1 0 0 0 1 1 1 1 1 0 0 1 1 0 1 1 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 0 0 0 0
Warmup runs: 1
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Render Count Changes

There are no entries

Render Issues

There are no entries

Added Scenarios

There are no entries

Removed Scenarios

There are no entries

Generated by 🚫 dangerJS against b7d2327

Copy link
Contributor

@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: 8

🧹 Outside diff range and nitpick comments (6)
screens/Onboarding/OnboardingConnectWalletScreen.tsx (1)

Line range hint 1-53: Consider implementing a more robust wallet connection state management.

The current implementation uses a local ref to track the connection state. Consider moving this logic to a global wallet connection context or state management solution for better consistency across the app.

This would:

  • Prevent potential race conditions in the connection flow
  • Make the connection state accessible to other components
  • Enable better error recovery mechanisms
screens/NewAccount/NewAccountConnectWalletScreen.tsx (1)

Line range hint 50-61: Consider extracting shared wallet connection logic

The comment indicates that the same logic is used for both onboarding and new account flows. Consider extracting this into a custom hook (e.g., useWalletConnection) to promote code reuse and maintainability.

Example structure:

function useWalletConnection(address: string) {
  const router = useRouter();
  const finishedConnecting = useRef(false);
  
  useFocusEffect(
    useCallback(() => {
      if (finishedConnecting.current) {
        router.goBack();
      }
    }, [router])
  );

  const handleDoneConnecting = useCallback(() => {
    router.navigate("NewAccountUserProfile");
    finishedConnecting.current = true;
  }, [router]);

  const handleErrorConnecting = useCallback((arg: { error: Error }) => {
    console.error('Wallet connection failed:', arg.error);
    router.goBack();
  }, [router]);

  return { handleDoneConnecting, handleErrorConnecting };
}
navigation/useNavigation.tsx (1)

Line range hint 52-57: Simplify event listener cleanup.

The current cleanup implementation has redundant code. Each useEffect's cleanup function both unsubscribes and removes the listener, while also adding console.log statements. The unsubscribe() function returned by addListener is sufficient for cleanup.

Simplify the cleanup functions:

  useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      if (onFocus) {
        onFocus();
      }
    });

    return () => {
-     navigation.removeListener("focus", () => {
-       console.log("focus listener removed");
-     });
+     unsubscribe();
    };
  }, [onFocus, navigation]);

Apply similar changes to the "blur" and "beforeRemove" listeners.

Also applies to: 67-72, 82-87

screens/Onboarding/OnboardingPrivateKeyScreen.tsx (1)

Private key input requires security enhancements

The verification confirms that the private key input is using a basic TextInput without security measures. Specific issues found:

  • No secureTextEntry property is used in the PrivateKeyInput component
  • Private key remains in state after successful connection
  • No automatic clearing when app moves to background

Required changes in screens/Onboarding/OnboardingPrivateKeyScreen.tsx:

  1. Add secureTextEntry={true} to the TextInput in PrivateKeyInput
  2. Clear private key state after successful connection in handlePressConnect
  3. Implement AppState listener to clear private key when app moves to background
  4. Consider using the design system's TextField component which supports additional security features
🔗 Analysis chain

Line range hint 41-68: Enhance private key input security

The private key input handling could benefit from additional security measures:

  1. Consider using a secure text entry component
  2. Clear the private key from state after successful connection
  3. Add auto-clear on app background

Let's check if secure text handling is implemented elsewhere:

Consider implementing these security enhancements:

const [privateKey, setPrivateKey] = useState("");

useEffect(() => {
  const subscription = AppState.addEventListener('change', nextAppState => {
    if (nextAppState === 'background') {
      setPrivateKey(''); // Clear sensitive data
    }
  });
  return () => subscription.remove();
}, []);

Let me analyze the results of these broader searches to verify the security concerns and provide appropriate recommendations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for secure text entry implementations
rg -i "secureTextEntry|secure.*input|private.*key.*input" --type typescript

Length of output: 112


Script:

#!/bin/bash
# Search for secure text entry implementations with broader file extensions
rg -i "secureTextEntry|secure.*input|private.*key.*input" --type ts --type tsx

# Search for TextInput components to analyze their security properties
rg -i "TextInput.*secureTextEntry|TextInput.*password" --type ts --type tsx

# Look for private key handling patterns
rg -i "privateKey.*input|privateKey.*state" --type ts --type tsx

Length of output: 309


Script:

#!/bin/bash
# Search for secure text entry implementations without specifying file types
rg -l "secureTextEntry"

# Search for TextInput components and their properties
rg -l "TextInput"

# Look specifically in the Onboarding directory
fd . screens/Onboarding -t f -x cat {} \; | grep -i "textinput"

Length of output: 1436


Script:

#!/bin/bash
# Check TextField component implementation since it's used in the design system
cat design-system/TextField/TextField.tsx

# Check the specific implementation in OnboardingPrivateKeyScreen
cat screens/Onboarding/OnboardingPrivateKeyScreen.tsx

# Look for any existing password/sensitive input handling
rg -l "password|sensitive|secure" design-system/TextField/

Length of output: 11123

components/Onboarding/ConnectViaWallet/ConnectViaWalletTableViewItems.tsx (2)

Line range hint 124-187: Enhance error handling and user feedback.

While the wallet connection logic is solid, there are several areas for improvement in error handling:

  1. Error messages should be user-friendly and localized
  2. Different failure scenarios should have specific error handling
  3. Users should receive visual feedback on errors

Consider applying these improvements:

 } catch (e: any) {
   logger.error("Error connecting to wallet:", e);
+  const errorMessage = getWalletErrorMessage(e);
+  showErrorToast(translate(errorMessage));
 } finally {
   setIsProcessingWalletId(null);
 }

Add a helper function:

function getWalletErrorMessage(error: Error): string {
  if (error.message === "No coinbase wallet") {
    return "walletSelector.errors.noCoinbaseWallet";
  }
  if (error.message === "No EthOS signer found") {
    return "walletSelector.errors.noEthOSSigner";
  }
  return "walletSelector.errors.generic";
}

Line range hint 93-187: Consider refactoring wallet connection logic for better maintainability.

The component currently handles multiple wallet types with different connection flows. Consider:

  1. Moving wallet-specific connection logic to custom hooks (e.g., useCoinbaseWallet, useEthOSWallet)
  2. Creating a dedicated context for managing connection states
  3. Implementing a wallet connection strategy pattern

This would improve maintainability and make it easier to add new wallet types.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4745a3a and b7d2327.

📒 Files selected for processing (9)
  • components/Onboarding/ConnectViaWallet/ConnectViaWallet.context.tsx (1 hunks)
  • components/Onboarding/ConnectViaWallet/ConnectViaWalletTableViewItems.tsx (4 hunks)
  • components/Onboarding/ConnectViaWallet/useInitConnectViaWalletState.ts (2 hunks)
  • navigation/useNavigation.tsx (1 hunks)
  • screens/NewAccount/NewAccountConnectWalletScreen.tsx (2 hunks)
  • screens/NewAccount/NewAccountPrivateKeyScreen.tsx (2 hunks)
  • screens/NewAccount/NewAccountUserProfileScreen.tsx (1 hunks)
  • screens/Onboarding/OnboardingConnectWalletScreen.tsx (2 hunks)
  • screens/Onboarding/OnboardingPrivateKeyScreen.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • screens/NewAccount/NewAccountUserProfileScreen.tsx
🔇 Additional comments (12)
components/Onboarding/ConnectViaWallet/ConnectViaWallet.context.tsx (2)

18-19: LGTM! Props interface changes improve type safety.

The explicit prop destructuring makes the component's API more clear and self-documenting compared to using spread operator.


21-27: LGTM! Proper memoization of context value.

The useMemo implementation with correct dependency array will prevent unnecessary re-renders of child components that consume this context.

screens/Onboarding/OnboardingConnectWalletScreen.tsx (1)

1-1: LGTM: Clean import organization and ref setup.

The imports are well-organized and the boolean ref is properly initialized.

Also applies to: 3-3, 20-20

navigation/useNavigation.tsx (1)

Line range hint 1-96: Verify the impact on navigation behavior.

Given that this is a core navigation utility used across the app, we should verify its usage to ensure the changes don't break navigation in connected components.

✅ Verification successful

No breaking changes detected in navigation implementation

The verification shows that the useRouter hook is safely implemented and used consistently across the application:

  • The hook is used in 20 components, primarily in screen components and navigation-related files
  • All navigation event handlers (onTransitionEnd, onBeforeRemove, onBlur, onFocus) are properly cleaned up in their respective useEffect hooks
  • The implementation follows React Navigation's recommended patterns for event listeners and state management
  • No error handling issues or navigation state inconsistencies were found

The changes in the core navigation utility maintain backward compatibility and proper cleanup of navigation listeners.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using useRouter
echo "Components using useRouter:"
rg "useRouter\(" -l

# Search for potential navigation-related issues in error boundaries or error logs
echo "\nPotential navigation error handling:"
rg -i "navigation.*error|failed.*navigate"

Length of output: 1064


Script:

#!/bin/bash
# Let's analyze the usage patterns of useRouter to understand the impact
echo "Analyzing useRouter usage patterns:"
rg "useRouter\(" -A 5

# Check for any existing navigation transition handlers
echo "\nChecking navigation transition handlers:"
rg "onTransitionEnd|onBeforeRemove|onBlur|onFocus" -A 2

# Look for any navigation state management
echo "\nChecking navigation state management:"
rg "navigation\.state|navigation\.isFocused|navigation\.addListener" -A 2

Length of output: 14840

screens/NewAccount/NewAccountPrivateKeyScreen.tsx (2)

2-2: LGTM: Platform import is correctly added

The Platform import is properly placed and necessary for the platform-specific translation implementation.


46-52: 🛠️ Refactor suggestion

Verify translation keys and consider refactoring

While the platform-specific translation implementation is functional, there are a few points to consider:

  1. Verify that the required translation keys exist
  2. Consider extracting the platform-specific logic for reusability

Consider extracting the platform-specific storage translation to a utility function for better maintainability:

const getStorageTranslation = () => 
  translate(`privateKeyConnect.storage.${Platform.OS === "ios" ? "ios" : "android"}`);

// Usage in component:
translate("privateKeyConnect.subtitle", {
  storage: getStorageTranslation()
})

This would:

  1. Make the code more maintainable
  2. Allow for easier reuse across components
  3. Centralize platform-specific logic
components/Onboarding/ConnectViaWallet/useInitConnectViaWalletState.ts (2)

Line range hint 44-54: Improved error handling through context.

The error handling has been enhanced by utilizing the onErrorConnecting callback from context, which centralizes error handling logic. The added debug logging also improves observability.

Let's verify the error handling implementation in the context provider:

✅ Verification successful

Let me gather more information about the error handling implementation by checking the actual handler function:


Error handling implementation is properly centralized and includes disconnect safety

The error handling implementation is well-structured:

  • The onErrorConnecting callback is properly passed through context
  • The handler includes a safety disconnect operation before propagating the error
  • Error handling is consistently used across the wallet connection flow
  • The implementation in the review file correctly uses this centralized error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the error handling implementation in ConnectViaWallet.context.tsx
# Expected: Find the implementation of onErrorConnecting and its usage

# Search for the error handling implementation
rg -A 5 "onErrorConnecting.*=" components/Onboarding/ConnectViaWallet/

Length of output: 3701


Script:

#!/bin/bash
# Search for handleErrorConnecting implementation
ast-grep --pattern 'const handleErrorConnecting = $$$'

Length of output: 1827


Line range hint 1-99: Verify impact of removed disconnect functionality.

The AI summary indicates that disconnect functionality was removed. Let's ensure this doesn't impact the wallet connection lifecycle.

✅ Verification successful

Based on the search results, I can see that the disconnect functionality is properly maintained in useConnectViaWalletDisconnect.tsx and is being used in ConnectViaWalletTableViewItems.tsx. Let me verify the cleanup handlers in the wallet connection lifecycle to ensure there are no issues.


Based on the analysis of the codebase, I can now provide a final response:

No issues found with wallet connection lifecycle after disconnect removal

The wallet connection lifecycle is properly maintained:

  • Disconnect functionality is still present in useConnectViaWalletDisconnect.tsx and used in ConnectViaWalletTableViewItems.tsx
  • Proper cleanup handlers exist in useConnectViaWalletInitXmtpClient.tsx for timeouts and abort controllers
  • The wallet initialization in useInitConnectViaWalletState.ts has appropriate state management and error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining disconnect references that might be broken
# Expected: No orphaned disconnect calls

# Search for any remaining disconnect references
rg -i "disconnect.*wallet|wallet.*disconnect" components/Onboarding/

# Search for potential cleanup in useEffect hooks
ast-grep --pattern 'useEffect(() => {
  $$$
  return () => {
    $$$
  }
}, $$$)'

Length of output: 42555


Script:

#!/bin/bash
# Check wallet connection lifecycle and cleanup
# Looking for useEffect cleanup in wallet connection related files

# Search for cleanup handlers in wallet connection files
rg -A 5 "useEffect" components/Onboarding/ConnectViaWallet/useInitConnectViaWalletState.ts
rg -A 5 "useEffect" components/Onboarding/ConnectViaWallet/useConnectViaWalletInitXmtpClient.tsx

Length of output: 1280

screens/Onboarding/OnboardingPrivateKeyScreen.tsx (1)

13-19: LGTM: Clean import organization

The Platform import is properly grouped with other React Native components and is necessary for the platform-specific translation logic.

components/Onboarding/ConnectViaWallet/ConnectViaWalletTableViewItems.tsx (3)

2-8: LGTM: Clean import organization for wallet management.

The added imports properly support the new wallet connection state management and loading indicator functionality.


110-115: LGTM: Improved UX with loading indicators.

The addition of per-wallet loading indicators provides clear visual feedback during connection attempts.


97-102: Verify wallet connection cleanup on app state changes.

While resetting the processing state on app foreground is good, we should ensure that any ongoing wallet connections are properly cleaned up to prevent orphaned connections.

✅ Verification successful

Let me try a different search strategy to verify the wallet connection cleanup handling.


Let me search for the wallet connection handling to understand the complete flow.


Based on the gathered information, I can now provide the final response:

Wallet connection cleanup is properly implemented

The current implementation already handles wallet connection cleanup appropriately:

  • Disconnects existing wallet connection before initiating a new one using disconnectThirdweb
  • Resets processing state on app foreground via useAppStateHandlers
  • Manages wallet connection state through proper state management hooks
  • Includes error handling in the connection flow
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other wallet connection cleanup handlers
rg -A 5 "useAppStateHandlers.*wallet"

Length of output: 39


Script:

#!/bin/bash
# Search for wallet connection cleanup patterns
rg -A 5 "setIsProcessingWalletId"

# Search for app state handlers in the same component
ast-grep --pattern 'useAppStateHandlers({
  $$$
})'

# Look for wallet connection cleanup patterns
rg -A 5 "(cleanup|clear|reset).*[Ww]allet"

Length of output: 3556


Script:

#!/bin/bash
# Search for wallet connection handling
rg -A 10 "disconnectThirdweb"

# Look for wallet connection state management
ast-grep --pattern 'const [$_] = useState<$_>($$$)'

Length of output: 2588

Comment on lines +22 to +30
useFocusEffect(
useCallback(() => {
// User already connected wallet but decided to come back here, so we need to go back to get started screen
if (finishedConnecting.current) {
router.goBack();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving the focus effect implementation.

Several improvements could enhance this implementation:

  1. The router dependency should be included in the dependency array instead of using eslint-disable
  2. The navigation pattern might cause UX issues if users need to go back

Consider this improved implementation:

 useFocusEffect(
   useCallback(() => {
-    // User already connected wallet but decided to come back here, so we need to go back to get started screen
+    // If wallet is already connected, redirect to prevent duplicate connections
+    // and maintain proper navigation state
     if (finishedConnecting.current) {
-      router.goBack();
+      router.replace("OnboardingUserProfile");
     }
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, [])
+  }, [router])
 );

This change:

  • Properly includes router in dependencies
  • Uses replace instead of goBack for cleaner navigation
  • Improves the explanatory comment
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useFocusEffect(
useCallback(() => {
// User already connected wallet but decided to come back here, so we need to go back to get started screen
if (finishedConnecting.current) {
router.goBack();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
);
useFocusEffect(
useCallback(() => {
// If wallet is already connected, redirect to prevent duplicate connections
// and maintain proper navigation state
if (finishedConnecting.current) {
router.replace("OnboardingUserProfile");
}
}, [router])
);

Comment on lines 32 to +41
const handleDoneConnecting = useCallback(() => {
router.navigate("OnboardingUserProfile");
}, [router]);
finishedConnecting.current = true;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const handleErrorConnecting = useCallback(
(arg: { error: Error }) => {
router.goBack();
},
[router]
);
const handleErrorConnecting = useCallback((arg: { error: Error }) => {
router.goBack();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance error handling and fix dependency issues.

The handlers need improvement in several areas:

  1. Missing router dependency in useCallback
  2. Basic error handling
  3. Non-specific error type

Consider this improved implementation:

-  const handleDoneConnecting = useCallback(() => {
+  const handleDoneConnecting = useCallback(() => {
     router.navigate("OnboardingUserProfile");
     finishedConnecting.current = true;
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, []);
+  }, [router]);

-  const handleErrorConnecting = useCallback((arg: { error: Error }) => {
-    router.goBack();
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, []);
+  type WalletError = {
+    error: Error & { code?: string; message: string };
+  };
+
+  const handleErrorConnecting = useCallback(
+    ({ error }: WalletError) => {
+      // Handle specific error cases
+      if (error.code === "USER_REJECTED") {
+        router.goBack();
+      } else {
+        // Handle other errors appropriately
+        console.error("Wallet connection error:", error.message);
+        router.replace("OnboardingGetStarted", { error: error.message });
+      }
+    },
+    [router]
+  );

This improves:

  • Proper dependency inclusion
  • More specific error typing
  • Better error handling based on error type
  • More appropriate navigation patterns
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleDoneConnecting = useCallback(() => {
router.navigate("OnboardingUserProfile");
}, [router]);
finishedConnecting.current = true;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleErrorConnecting = useCallback(
(arg: { error: Error }) => {
router.goBack();
},
[router]
);
const handleErrorConnecting = useCallback((arg: { error: Error }) => {
router.goBack();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleDoneConnecting = useCallback(() => {
router.navigate("OnboardingUserProfile");
finishedConnecting.current = true;
}, [router]);
type WalletError = {
error: Error & { code?: string; message: string };
};
const handleErrorConnecting = useCallback(
({ error }: WalletError) => {
// Handle specific error cases
if (error.code === "USER_REJECTED") {
router.goBack();
} else {
// Handle other errors appropriately
console.error("Wallet connection error:", error.message);
router.replace("OnboardingGetStarted", { error: error.message });
}
},
[router]
);

Comment on lines 42 to 48
const handleErrorConnecting = useCallback(
(arg: { error: Error }) => {
router.goBack();
},
[router]
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling implementation

The error handler receives an error object but doesn't use it. Consider logging the error or showing it to the user for better debugging and user experience.

  const handleErrorConnecting = useCallback(
    (arg: { error: Error }) => {
+     console.error('Wallet connection failed:', arg.error);
      router.goBack();
    },
-   // eslint-disable-next-line react-hooks/exhaustive-deps
-   []
+   [router]
  );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleErrorConnecting = useCallback(
(arg: { error: Error }) => {
router.goBack();
},
[router]
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
const handleErrorConnecting = useCallback(
(arg: { error: Error }) => {
console.error('Wallet connection failed:', arg.error);
router.goBack();
},
[router]
);

Comment on lines +20 to +31
useFocusEffect(
useCallback(
() => {
// User already connected wallet but decided to come back here, so we need to go back to new account screen
if (finishedConnecting.current) {
router.goBack();
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add missing dependency to useFocusEffect

The effect uses router but it's not included in the dependency array. This could lead to stale closures.

  useFocusEffect(
    useCallback(
      () => {
        if (finishedConnecting.current) {
          router.goBack();
        }
      },
-     // eslint-disable-next-line react-hooks/exhaustive-deps
-     []
+     [router]
    )
  );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useFocusEffect(
useCallback(
() => {
// User already connected wallet but decided to come back here, so we need to go back to new account screen
if (finishedConnecting.current) {
router.goBack();
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
);
useFocusEffect(
useCallback(
() => {
// User already connected wallet but decided to come back here, so we need to go back to new account screen
if (finishedConnecting.current) {
router.goBack();
}
},
[router]
)
);

Comment on lines +33 to +40
const handleDoneConnecthing = useCallback(
() => {
router.navigate("NewAccountUserProfile");
finishedConnecting.current = true;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in function name: handleDoneConnecthinghandleDoneConnecting

The function name contains a typo that should be corrected for consistency and maintainability.

-const handleDoneConnecthing = useCallback(
+const handleDoneConnecting = useCallback(
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleDoneConnecthing = useCallback(
() => {
router.navigate("NewAccountUserProfile");
finishedConnecting.current = true;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
const handleDoneConnecting = useCallback(
() => {
router.navigate("NewAccountUserProfile");
finishedConnecting.current = true;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);

Comment on lines +87 to +96
return useMemo(
() => {
return {
popToTop: () => navigation.dispatch(StackActions.popToTop()),
...navigation,
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Fix stale navigation reference in useMemo.

The empty dependency array [] in useMemo will cause the returned navigation object to become stale. This is dangerous because:

  1. The memoized value is created once and never updates
  2. The returned object includes the navigation prop which is dynamic
  3. This can lead to using outdated navigation references

Fix the dependency array:

  return useMemo(
    () => ({
      popToTop: () => navigation.dispatch(StackActions.popToTop()),
      ...navigation,
    }),
-    []
+    [navigation]
  );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return useMemo(
() => {
return {
popToTop: () => navigation.dispatch(StackActions.popToTop()),
...navigation,
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
return useMemo(
() => {
return {
popToTop: () => navigation.dispatch(StackActions.popToTop()),
...navigation,
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[navigation]
);

@@ -32,6 +38,8 @@ export function OnboardingPrivateKeyScreen(

const router = useRouter();

useAvoidInputEffect();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove duplicate hook call

The useAvoidInputEffect hook is already called at the start of the component. Calling it twice is unnecessary and could lead to unintended side effects with keyboard behavior management.

- useAvoidInputEffect();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useAvoidInputEffect();

Comment on lines +62 to +68
{translate("privateKeyConnect.subtitle", {
storage: translate(
`privateKeyConnect.storage.${
Platform.OS === "ios" ? "ios" : "android"
}`
),
})}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider handling all possible platform values

While the platform-specific translation is a good approach, the current implementation assumes only iOS and Android platforms. React Native supports additional platforms like web, windows, and macos.

Consider using a more explicit platform check:

- Platform.OS === "ios" ? "ios" : "android"
+ Platform.select({
+   ios: "ios",
+   android: "android",
+   default: "android" // or handle other platforms differently
+ })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{translate("privateKeyConnect.subtitle", {
storage: translate(
`privateKeyConnect.storage.${
Platform.OS === "ios" ? "ios" : "android"
}`
),
})}
{translate("privateKeyConnect.subtitle", {
storage: translate(
`privateKeyConnect.storage.${
Platform.select({
ios: "ios",
android: "android",
default: "android" // or handle other platforms differently
})
}`
),
})}

@thierryskoda thierryskoda merged commit 04d44d7 into release/2.0.8 Oct 29, 2024
6 checks passed
@thierryskoda thierryskoda deleted the ts/navigation-refactor-fix branch October 29, 2024 15:41
This was referenced Dec 11, 2024
This was referenced Jan 13, 2025
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