Skip to content

fix/metamask-walletConnect-fix#373

Merged
RanaBug merged 10 commits intostagingfrom
fix/metamask-walletConnect-fix
Jul 24, 2025
Merged

fix/metamask-walletConnect-fix#373
RanaBug merged 10 commits intostagingfrom
fix/metamask-walletConnect-fix

Conversation

@RanaBug
Copy link
Collaborator

@RanaBug RanaBug commented Jul 24, 2025

Description

  • Fix MetaMask and WalletConnect signing issues on production

How Has This Been Tested?

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Summary by CodeRabbit

  • Bug Fixes

    • Improved authentication logic for more consistent login and wallet connection handling.
  • Style

    • Cleaned up import order and removed unnecessary blank lines for better code readability.

@RanaBug RanaBug requested review from IAmKio and vignesha22 July 24, 2025 16:04
@RanaBug RanaBug self-assigned this Jul 24, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 24, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes remove the useAccount hook and related isConnected and address references from src/containers/Main.tsx, relying solely on the private key login hook's account state for authentication logic. Import statements were reordered in src/pages/Login.tsx without functional changes. A blank line was removed in AccountModal.tsx, and the useWallets mock in tests was updated to return { wallets: [] } instead of {}.

Changes

File(s) Change Summary
src/containers/Main.tsx Removed useAccount hook usage; updated authentication logic to depend only on private key login account; simplified conditions; adjusted effect dependencies; removed isConnected and address references.
src/pages/Login.tsx Reordered import statements without changing functionality or component signature.
src/components/BottomMenuModal/AccountModal.tsx Removed an extraneous blank line inside the onLogoutClick async callback; no logic changes.
src/test-utils/setupTests.ts Changed mocked useWallets hook return value from {} to { wallets: [] } to reflect expected shape.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

  • fix/metamask-walletConnect-fix #373: Modifies internal logic in AuthLayout related to wallet/account handling and authentication conditions, closely related to the removal of useAccount and isConnected here.
  • Removed loginOrLink for Wagmi WC #354: Adds or modifies usage of useAccount and isConnected, making it directly connected to the changes removing these hooks in this PR.
  • feat/PRO-3018/Private-Key-Mode #243: Focuses on private key login integration and authentication state management, overlapping with this PR’s modifications to private key login usage.

Suggested reviewers

  • IAmKio

Poem

🐇 Hopping past the wallet maze,
No more useAccount haze.
Private keys now lead the way,
Imports sorted, clear as day.
Tests aligned, blank lines gone,
Our code hops swiftly on and on!
🌿✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-24T20_05_48_914Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 325639c and 94009df.

📒 Files selected for processing (3)
  • src/components/BottomMenuModal/AccountModal.tsx (0 hunks)
  • src/containers/Main.tsx (4 hunks)
  • src/test-utils/setupTests.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/metamask-walletConnect-fix

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jul 24, 2025

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: 94009df
Status: ✅  Deploy successful!
Preview URL: https://1cdb03f1.x-e62.pages.dev
Branch Preview URL: https://fix-metamask-walletconnect-f.x-e62.pages.dev

View logs

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6de6da5 and ee893dc.

📒 Files selected for processing (1)
  • src/containers/Main.tsx (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/containers/Main.tsx (1)

Learnt from: IAmKio
PR: #243
File: src/containers/Main.tsx:85-86
Timestamp: 2025-02-20T19:50:40.447Z
Learning: Passing private key via URL parameters in the login flow is an intentional design choice for handling edge cases in the private key login mode.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: unit-tests
  • GitHub Check: lint
  • GitHub Check: build
🔇 Additional comments (4)
src/containers/Main.tsx (4)

97-98: Good refactoring for improved readability.

The introduction of the isPK boolean consolidates the private key login detection logic, making the subsequent conditional statements clearer and more maintainable.


100-134: Simplified condition improves code clarity.

The refactoring to use the isPK boolean and explicitly use the account state in the provider creation makes the private key login flow more explicit and easier to follow.


152-189: Explicit condition improves authentication flow clarity.

Converting the catch-all else to an explicit else if (authenticated && wallets.length) condition makes the Privy login branch more self-documenting and easier to debug.


208-208: Correct dependency updates for authentication state reactivity.

Adding authenticated and isConnected to the useEffect dependencies ensures the authentication flow properly responds to state changes from both Privy and wagmi authentication systems.

@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 16:15 Inactive
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee893dc and 0bae583.

📒 Files selected for processing (1)
  • src/containers/Main.tsx (6 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/containers/Main.tsx (1)

Learnt from: IAmKio
PR: #243
File: src/containers/Main.tsx:85-86
Timestamp: 2025-02-20T19:50:40.447Z
Learning: Passing private key via URL parameters in the login flow is an intentional design choice for handling edge cases in the private key login mode.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: lint
  • GitHub Check: unit-tests
  • GitHub Check: build
🔇 Additional comments (5)
src/containers/Main.tsx (5)

20-20: LGTM: Import additions are correct.

The useConnect import and its usage are properly added to support the new WalletConnect functionality.

Also applies to: 71-71


98-99: Good refactoring: Improved readability with isPK variable.

Extracting the private key login condition into a single variable improves code maintainability and readability.

Also applies to: 101-101


102-102: LGTM: Private key login branch clarified.

The comment and direct use of account state make the private key login flow clearer and more explicit about using HTTP transport.

Also applies to: 135-135


153-154: LGTM: Privy login branch made more explicit.

The explicit condition check and descriptive comment clarify that this branch handles Privy-managed authentication including MetaMask, WalletConnect, and social logins.


236-236: LGTM: useEffect dependencies correctly updated.

The added dependencies (authenticated, isConnected, connectors) are all used within the effect and ensure proper re-execution when these authentication states change.

Comment on lines 191 to 234
} else if (isConnected && address) {
// Direct WalletConnect (wagmi): use wagmi provider ONLY if not PK and not Privy
const updateProvider = async () => {
const walletChainId = 1; // default chain id is 1
// Find the active connector (WalletConnect)
const walletConnectConnector = connectors.find(
(c) => c.id === 'walletConnect'
);
console.log('DEBUG: walletConnectConnector', walletConnectConnector);
if (walletConnectConnector) {
const providerWagmi = await walletConnectConnector.getProvider();
console.log('DEBUG: providerWagmi', providerWagmi);
if (
providerWagmi &&
typeof (providerWagmi as any).request === 'function'
) {
console.log('DEBUG: Using WalletConnect provider for viem');
const newProvider = createWalletClient({
account: address as `0x${string}`,
chain: getNetworkViem(walletChainId),
transport: custom(providerWagmi as any),
});
setProvider(newProvider);
const isWithinVisibleChains = visibleChains.some(
(chain) => chain.id === walletChainId
);
setChainId(
isWithinVisibleChains ? walletChainId : visibleChains[0].id
);
} else {
console.warn(
'WalletConnect: connector.getProvider() returned invalid provider',
providerWagmi
);
}
} else {
console.warn(
'WalletConnect: walletConnectConnector not found',
connectors
);
}
};
updateProvider();
}
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

WalletConnect implementation fixes the transport issue but needs cleanup.

This implementation correctly addresses the signing issue mentioned in the PR objectives by using custom(providerWagmi) transport instead of HTTP transport, ensuring signing requests are routed through the connected wallet.

However, several improvements are needed:

  1. Remove debug logging - Console.log statements should be removed for production
  2. Improve type safety - Replace as any type assertions with proper typing
  3. Enhance provider validation - The EIP-1193 provider check could be more comprehensive
-        console.log('DEBUG: walletConnectConnector', walletConnectConnector);
         if (walletConnectConnector) {
           const providerWagmi = await walletConnectConnector.getProvider();
-          console.log('DEBUG: providerWagmi', providerWagmi);
           if (
             providerWagmi &&
-            typeof (providerWagmi as any).request === 'function'
+            typeof providerWagmi.request === 'function'
           ) {
-            console.log('DEBUG: Using WalletConnect provider for viem');
             const newProvider = createWalletClient({
               account: address as `0x${string}`,
               chain: getNetworkViem(walletChainId),
-              transport: custom(providerWagmi as any),
+              transport: custom(providerWagmi),
             });

Note: This implementation correctly resolves the transport issue flagged in the previous review.

📝 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
} else if (isConnected && address) {
// Direct WalletConnect (wagmi): use wagmi provider ONLY if not PK and not Privy
const updateProvider = async () => {
const walletChainId = 1; // default chain id is 1
// Find the active connector (WalletConnect)
const walletConnectConnector = connectors.find(
(c) => c.id === 'walletConnect'
);
console.log('DEBUG: walletConnectConnector', walletConnectConnector);
if (walletConnectConnector) {
const providerWagmi = await walletConnectConnector.getProvider();
console.log('DEBUG: providerWagmi', providerWagmi);
if (
providerWagmi &&
typeof (providerWagmi as any).request === 'function'
) {
console.log('DEBUG: Using WalletConnect provider for viem');
const newProvider = createWalletClient({
account: address as `0x${string}`,
chain: getNetworkViem(walletChainId),
transport: custom(providerWagmi as any),
});
setProvider(newProvider);
const isWithinVisibleChains = visibleChains.some(
(chain) => chain.id === walletChainId
);
setChainId(
isWithinVisibleChains ? walletChainId : visibleChains[0].id
);
} else {
console.warn(
'WalletConnect: connector.getProvider() returned invalid provider',
providerWagmi
);
}
} else {
console.warn(
'WalletConnect: walletConnectConnector not found',
connectors
);
}
};
updateProvider();
}
} else if (isConnected && address) {
// Direct WalletConnect (wagmi): use wagmi provider ONLY if not PK and not Privy
const updateProvider = async () => {
const walletChainId = 1; // default chain id is 1
// Find the active connector (WalletConnect)
const walletConnectConnector = connectors.find(
(c) => c.id === 'walletConnect'
);
if (walletConnectConnector) {
const providerWagmi = await walletConnectConnector.getProvider();
if (
providerWagmi &&
typeof providerWagmi.request === 'function'
) {
const newProvider = createWalletClient({
account: address as `0x${string}`,
chain: getNetworkViem(walletChainId),
transport: custom(providerWagmi),
});
setProvider(newProvider);
const isWithinVisibleChains = visibleChains.some(
(chain) => chain.id === walletChainId
);
setChainId(
isWithinVisibleChains ? walletChainId : visibleChains[0].id
);
} else {
console.warn(
'WalletConnect: connector.getProvider() returned invalid provider',
providerWagmi
);
}
} else {
console.warn(
'WalletConnect: walletConnectConnector not found',
connectors
);
}
};
updateProvider();
}
🤖 Prompt for AI Agents
In src/containers/Main.tsx between lines 191 and 234, remove all console.log
debug statements to clean up the code for production. Replace the `as any` type
assertions on providerWagmi with proper EIP-1193 provider typings to improve
type safety. Enhance the provider validation by implementing a more
comprehensive check for EIP-1193 compliance, such as verifying the presence of
required methods like request, on, and removeListener, instead of only checking
if request is a function.

Copy link
Collaborator

@IAmKio IAmKio left a comment

Choose a reason for hiding this comment

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

🤞🏾🤞🏾🤞🏾

@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 16:44 Inactive
@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 17:19 Inactive
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: 2

🔭 Outside diff range comments (1)
src/pages/Login.tsx (1)

34-47: Add error handling for logout operation.

If the logout() call fails, the WalletConnect setup will still proceed, which could lead to inconsistent authentication state. Consider adding error handling.

 const handleWalletConnect = async () => {
-  await logout(); // Logout Privy session if any
+  try {
+    await logout(); // Logout Privy session if any
+  } catch (error) {
+    console.warn('Failed to logout from Privy:', error);
+  }
   if (!walletConnectConnector) {
     throw new Error('WalletConnect connector not found');
   }
   connect({ connector: walletConnectConnector });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65b0183 and d168bde.

📒 Files selected for processing (3)
  • src/components/BottomMenuModal/AccountModal.tsx (1 hunks)
  • src/pages/Loading.tsx (3 hunks)
  • src/pages/Login.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/pages/Login.tsx (1)
src/components/LandingPage/Button/index.jsx (1)
  • Button (38-61)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: unit-tests
  • GitHub Check: lint
  • GitHub Check: build
🔇 Additional comments (6)
src/pages/Loading.tsx (3)

7-7: LGTM: Import addition aligns with authentication flow improvements.

The addition of useDisconnect import is consistent with the broader changes to improve session management across authentication methods.


18-18: LGTM: Hook usage is correct.

The useDisconnect hook is properly destructured and will be used in the auto-logout flow.


52-52: LGTM: Dependency array correctly updated.

The addition of disconnect to the dependency array ensures the effect will update if the disconnect function changes.

src/components/BottomMenuModal/AccountModal.tsx (1)

153-160: LGTM: Unified logout logic improves consistency.

The refactored logic ensures both disconnect() and logout() are called together when either a wagmi connection or Privy account exists. This eliminates the previous separate handling and aligns with the consistent session cleanup pattern implemented across other components.

The change is safe because both functions handle cases where there's nothing to disconnect/logout from gracefully.

src/pages/Login.tsx (2)

2-2: LGTM: Import additions support the authentication flow improvements.

The added imports (useLogout, useDisconnect) are necessary for the enhanced session management functionality.

Also applies to: 4-4, 7-7, 14-14, 21-22


78-78: LGTM: Button handlers correctly use new authentication functions.

The button click handlers properly reference the new handlePrivyLogin and handleWalletConnect functions, ensuring proper session management when switching between authentication methods.

Also applies to: 81-81

Comment on lines 44 to 47
const handleLogout = async () => {
await disconnect();
await logout();
};
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 adding error handling for the disconnect operation.

While the implementation correctly calls disconnect() before logout(), there's no error handling if the disconnect operation fails. This could prevent the logout from occurring.

 const handleLogout = async () => {
+  try {
     await disconnect();
+  } catch (error) {
+    console.warn('Failed to disconnect:', error);
+  }
   await logout();
 };
📝 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 handleLogout = async () => {
await disconnect();
await logout();
};
const handleLogout = async () => {
try {
await disconnect();
} catch (error) {
console.warn('Failed to disconnect:', error);
}
await logout();
};
🤖 Prompt for AI Agents
In src/pages/Loading.tsx around lines 44 to 47, the handleLogout function calls
disconnect() without error handling, which could block logout if disconnect
fails. Wrap the disconnect() call in a try-catch block to catch any errors, log
or handle them appropriately, and ensure that logout() is called regardless of
disconnect's success or failure.

Comment on lines 29 to 32
const handlePrivyLogin = async () => {
disconnect(); // Disconnect wagmi session if any
await login(); // Then login with Privy
};
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 async handling in handlePrivyLogin.

The disconnect() call should be awaited to ensure the wagmi session is properly disconnected before starting the Privy login flow. This prevents potential race conditions.

 const handlePrivyLogin = async () => {
-  disconnect(); // Disconnect wagmi session if any
+  await disconnect(); // Disconnect wagmi session if any
   await login(); // Then login with Privy
 };
📝 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 handlePrivyLogin = async () => {
disconnect(); // Disconnect wagmi session if any
await login(); // Then login with Privy
};
const handlePrivyLogin = async () => {
await disconnect(); // Disconnect wagmi session if any
await login(); // Then login with Privy
};
🤖 Prompt for AI Agents
In src/pages/Login.tsx around lines 29 to 32, the disconnect() function call
inside handlePrivyLogin is not awaited, which can cause race conditions by
starting login before disconnect completes. Fix this by adding the await keyword
before disconnect() to ensure the wagmi session is fully disconnected before
proceeding with the login call.

@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 17:40 Inactive
@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 18:10 Inactive
@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 18:21 Inactive
@github-actions github-actions bot temporarily deployed to Preview (fix/metamask-walletConnect-fix) July 24, 2025 19:19 Inactive
@RanaBug RanaBug merged commit ae9917e into staging Jul 24, 2025
5 of 6 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 29, 2025
3 tasks
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