Skip to content

fix wallet connect through privy#301

Merged
RanaBug merged 3 commits intostagingfrom
fix/PRO-3209/change-chainId-wallet-connect-privy
May 12, 2025
Merged

fix wallet connect through privy#301
RanaBug merged 3 commits intostagingfrom
fix/PRO-3209/change-chainId-wallet-connect-privy

Conversation

@RanaBug
Copy link
Collaborator

@RanaBug RanaBug commented May 9, 2025

Description

  • Fix wallet connect flow when connected via Privy
  • Fix default chain of Privy to Mainnet

How Has This Been Tested?

  • Existing Unit Tests and Manual Testing

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

  • New Features
    • WalletConnect session list now hides sessions associated with the user's own Privy wallet address.
    • Users are automatically logged out if their Privy-linked WalletConnect session is disconnected.
    • Loading screen now triggers automatic logout after 15 seconds of inactivity.
  • Bug Fixes
    • Improved session management to prevent disconnection of Privy-linked sessions when disconnecting all sessions.
  • Chores
    • Updated "@reown/walletkit" dependency to version ^1.2.4.
    • Streamlined blockchain chain imports and configuration for improved maintainability.

@RanaBug RanaBug requested a review from IAmKio May 9, 2025 13:02
@RanaBug RanaBug self-assigned this May 9, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 9, 2025

Walkthrough

This update integrates Privy authentication state with WalletConnect session management, introducing logic to filter out sessions linked to the user's Privy wallet and enforce logout if such sessions are disconnected. It adds new utility functions for session address handling, modifies chain configuration in the provider, and implements an automatic logout timeout in the loading screen.

Changes

File(s) Change Summary
package.json Updated @reown/walletkit dependency version from ^1.1.2 to ^1.2.4.
src/utils/walletConnect.ts Added two utility functions: getWalletAddressesFromSession (extracts wallet addresses from a WalletConnect session) and isAddressInSessionViaPrivy (checks if a given address is present in a session).
src/services/walletConnect.ts Integrated Privy authentication with WalletConnect session management. Added logic to detect and filter sessions associated with the Privy wallet, enforce logout if such sessions are disconnected, and prevent disconnecting Privy-linked sessions. Refactored event handling and session tracking.
src/apps/pillarx-app/components/WalletConnectDropdown/WalletConnectDropdown.tsx Modified to use the Privy user's wallet address to filter out sessions associated with the user's own wallet from the active session list and dropdown display, using the new isAddressInSessionViaPrivy utility.
src/containers/Main.tsx Reduced blockchain chain imports to only mainnet and sepolia. Removed the supportedChains array from the PrivyProvider configuration.
src/pages/Loading.tsx Added automatic logout: uses usePrivy to access the logout function and triggers a logout 15 seconds after the component mounts, independent of the existing loading animation logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LoadingComponent
    participant PrivyAuth

    User->>LoadingComponent: Mounts Loading page
    LoadingComponent->>PrivyAuth: usePrivy() to get logout()
    Note right of LoadingComponent: Starts 15s timer
    alt Timer expires
        LoadingComponent->>PrivyAuth: logout()
    end
Loading
sequenceDiagram
    participant User
    participant WalletConnectDropdown
    participant WalletConnectService
    participant PrivyAuth

    WalletConnectDropdown->>PrivyAuth: usePrivy() to get user address
    WalletConnectDropdown->>WalletConnectService: get active sessions
    WalletConnectService->>WalletConnectDropdown: returns sessions
    WalletConnectDropdown->>WalletConnectDropdown: Filter sessions using isAddressInSessionViaPrivy
    WalletConnectDropdown->>User: Display filtered sessions
Loading
sequenceDiagram
    participant User
    participant WalletConnectService
    participant PrivyAuth

    User->>WalletConnectService: Disconnect session
    WalletConnectService->>WalletConnectService: Check if session is linked to Privy user
    alt Session is linked to Privy
        WalletConnectService->>PrivyAuth: logout()
        WalletConnectService->>User: Reload page
    else Session is not linked to Privy
        WalletConnectService->>User: Continue as usual
    end
Loading

Possibly related PRs

  • pillarwallet/x#300: Both PRs modify the imported chains and the supportedChains array in the PrivyProvider configuration, but in opposite directions (one expands, the other restricts), making their changes directly related.

Suggested reviewers

  • IAmKio

Poem

🐇
Hopping through sessions, I sniff and I sort,
Privy and WalletConnect, now play a new sport.
If my wallet’s in danger, I’ll log myself out,
With fifteen seconds waiting, I’m quick—there’s no doubt!
Chains trimmed and tidy, addresses in view,
This bunny ensures your wallet’s like new!

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 9628d64 and 7fbb98e.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit-tests
  • GitHub Check: build
  • GitHub Check: Cloudflare Pages

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

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 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 May 9, 2025

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7fbb98e
Status: ✅  Deploy successful!
Preview URL: https://025c23da.x-e62.pages.dev
Branch Preview URL: https://fix-pro-3209-change-chainid.x-e62.pages.dev

View logs

@github-actions github-actions bot temporarily deployed to Preview (fix/PRO-3209/change-chainId-wallet-connect-privy) May 9, 2025 13:03 Inactive
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.

LGTM!

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

🧹 Nitpick comments (3)
src/utils/walletConnect.ts (2)

22-27: Consider supporting any WalletConnect namespace & add defensive parsing

The current implementation extracts accounts only from the eip155 namespace and blindly splits by ':', assuming the third chunk is always the address.

  1. Projects that support multiple namespaces (e.g. cosmos, polkadot) will silently ignore those accounts.
  2. If an entry is malformed (less than three chunks), acc.split(':')[2] will produce undefined, propagating into the returned array.
-  const accounts: string[] = session.namespaces?.eip155?.accounts || [];
-  return accounts.map((acc) => acc.split(':')[2]);
+  // Collect accounts from **all** namespaces
+  const namespaceAccounts = Object.values(session.namespaces ?? {})
+    .flatMap((ns: any) => ns.accounts ?? []) as string[];
+
+  return namespaceAccounts
+    .map((acc) => {
+      const parts = acc.split(':');
+      return parts.length === 3 ? parts[2] : undefined;
+    })
+    .filter(Boolean) as string[];

This keeps the helper generic and avoids leaking undefined values into the callers.


29-36: Minor naming improvement

EOAAddress is capital-cased like a type, but it’s a value. Prefer camelCase (eoaAddress) to stay consistent with the rest of the codebase.

src/services/walletConnect.ts (1)

69-75: Non-blocking: handle logout failures gracefully

In handleLogout, a failure in logout() will currently swallow the error and still reload the page.
Logging or surfacing the error (and skipping reload() upon failure) would help diagnose issues during sign-out flows.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7adb48b and 9628d64.

⛔ Files ignored due to path filters (4)
  • package-lock.json is excluded by !**/package-lock.json
  • src/apps/pillarx-app/components/MediaGridCollection/tests/__snapshots__/DisplayCollectionImage.test.tsx.snap is excluded by !**/*.snap
  • src/apps/pillarx-app/components/TokenMarketDataRow/tests/__snapshots__/LeftColumnTokenMarketDataRow.test.tsx.snap is excluded by !**/*.snap
  • src/apps/pillarx-app/components/TokensWithMarketDataTile/test/__snapshots__/TokensWithMarketDataTile.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (6)
  • package.json (1 hunks)
  • src/apps/pillarx-app/components/WalletConnectDropdown/WalletConnectDropdown.tsx (4 hunks)
  • src/containers/Main.tsx (1 hunks)
  • src/pages/Loading.tsx (3 hunks)
  • src/services/walletConnect.ts (12 hunks)
  • src/utils/walletConnect.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/apps/pillarx-app/components/WalletConnectDropdown/WalletConnectDropdown.tsx (1)
src/utils/walletConnect.ts (1)
  • isAddressInSessionViaPrivy (29-37)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (9)
package.json (1)

36-36: Updated @reown/walletkit dependency.

The dependency has been updated from version ^1.1.2 to ^1.2.4 to support enhanced WalletConnect integration with Privy authentication.

src/containers/Main.tsx (2)

18-18: Simplified chain imports.

Imports have been reduced to only include mainnet and sepolia chains, which aligns with the PR objective of fixing the wallet connect flow.


332-336: Streamlined Privy provider configuration.

The Privy provider configuration was simplified by removing the supportedChains array, leaving only defaultChain (set to mainnet or sepolia based on environment) and embeddedWallets settings. This change supports the PR objective of setting the default blockchain network of Privy to Mainnet.

src/pages/Loading.tsx (2)

2-2: Added Privy authentication integration.

The usePrivy hook has been imported to access the logout function, integrating Privy's authentication capabilities into the Loading component.

Also applies to: 17-17


39-49:

Details

❓ Verification inconclusive

Implemented auto-logout safety mechanism.

An automatic logout feature has been added that triggers after 15 seconds in the loading state. This prevents users from getting stuck in loading screens during failed wallet connections.

Consider if 15 seconds is sufficient time for users on slower connections or devices. You might want to verify this timing through user testing or add a visual countdown to inform users before the logout occurs.


🏁 Script executed:

#!/bin/bash
# Check for any other timeout values used for similar automatic logout mechanisms
rg -A 1 -B 1 "setTimeout.*logout" --glob "*.{ts,tsx,js,jsx}" | grep -v "15000"

Length of output: 62994


No additional auto-logout timeouts found
– Verified across the codebase: the only setTimeout invoking logout is the new 15 000 ms instance in src/pages/Loading.tsx (lines 39–49).

The 15-second delay stands alone—please confirm it suits users on slower connections or devices. You may also consider adding a visible countdown or making the timeout configurable to improve UX.

src/apps/pillarx-app/components/WalletConnectDropdown/WalletConnectDropdown.tsx (3)

5-5: Added Privy integration for wallet identification.

Imported usePrivy hook and utility function isAddressInSessionViaPrivy to access the current user's wallet address and check for its presence in WalletConnect sessions.

Also applies to: 11-13, 42-42


130-137: Implemented session filtering for connected wallet.

Added logic to filter out WalletConnect sessions that are linked to the user's own Privy wallet. This prevents confusion by not showing the user's own wallet as a separate WalletConnect session.

The filtering assumes user?.wallet?.address is always available when needed. Consider adding a null check to handle cases where the user object or wallet address might not be available:

-        !isAddressInSessionViaPrivy(session, user?.wallet?.address || '')
+        !user?.wallet?.address || !isAddressInSessionViaPrivy(session, user.wallet.address)

139-139: Updated session count and rendering to use filtered sessions.

Modified the active sessions count and session list rendering to use the filtered sessions list, ensuring consistency in the UI with the implemented session filtering logic.

Also applies to: 252-252

src/services/walletConnect.ts (1)

490-508: prevSessionsRef might miss the very first deletion event

prevSessionsRef.current is updated only when activeSessions changes or when listeners are attached (line 691).
If the provider emits a session_delete before either effect executes, the ref will still be {} and the deleted session lookup will fail.

Consider populating the ref immediately after setActiveSessions in places where the initial fetch happens (e.g. after walletKit.getActiveSessions() in initWalletKit) or inside the event callback by falling back to activeSessions[deletedTopic] when the ref misses.

@RanaBug RanaBug merged commit 5dcde63 into staging May 12, 2025
7 of 8 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 20, 2026
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