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

[TASK-8160] fix: race condition when resetting token selector #631

Merged
merged 3 commits into from
Jan 17, 2025

Conversation

jjramirezn
Copy link
Contributor

@jjramirezn jjramirezn commented Jan 16, 2025

We actually don't need to reset token selector if we are in peanut wallet (we already set the correct token/chain pair)

In this PR I also refactored around the kernel client, it state should be persistent on the session and between pages, so having it in a hook that is used in different components was causing it to be recreated again and again. Now the client lives in a provider (it is non serializable so it can't live in the redux store) and the rest of the state lives in the redux store

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new Kernel Client Provider to manage wallet interactions.
    • Added support for WebAuthn key management in wallet context.
  • Improvements

    • Enhanced wallet type detection and conditional logic.
    • Simplified state management for kernel client interactions.
  • Changes

    • Removed wallet connection handling in some components.
    • Updated context provider hierarchy.
  • Technical Updates

    • Refactored kernel client initialization and management approach.

The client needs to be part of a client state, right now as a hook
local state, it was being recreated innecesarily and also could not be
shared between components. Now the simple state is in redux and this
client is part of a context provider.
Copy link

vercel bot commented Jan 16, 2025

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

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 16, 2025 1:17pm

Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Walkthrough

This pull request introduces significant changes to the wallet interaction and context management across multiple components. The key modifications include adding an isPeanutWallet property to the useWallet hook, restructuring context providers, and creating a new KernelClientProvider. The changes aim to enhance wallet type handling, particularly for Peanut wallets, and improve the overall context management strategy for kernel client interactions.

Changes

File Change Summary
src/components/Claim/Link/Onchain/Success.view.tsx Added isPeanutWallet to conditionally reset token context provider and updated useEffect dependencies.
src/components/Create/Create.tsx Updated useWallet hook to include isPeanutWallet, modified useEffect dependencies.
src/components/Create/Link/Input.view.tsx Removed handleConnectWallet function.
src/context/contextProvider.tsx Added KernelClientProvider to context provider hierarchy.
src/context/kernelClient.context.tsx Created new kernel client context with provider and hook.
src/hooks/useZeroDev.ts Refactored hook to use new kernel client context, removed Peanut-specific imports.

Possibly related PRs

Suggested reviewers

  • Hugo0

Poem

🐰 A Rabbit's Ode to Wallet Delight
Kernel clients dance, contexts align,
Peanut wallets now with a special sign
Providers wrap, hooks intertwine
Code evolves with each design
Hopping forward, tech so bright! 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

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

🧹 Nitpick comments (5)
src/hooks/useZeroDev.ts (5)

31-31: Check for Unused Imports

The variable user is imported from useAuth but not used anywhere else in the code.

Consider removing the unused variable to clean up the code.

 const { user } = useAuth()
-const { isKernelClientReady, isRegistering, isLoggingIn, isSendingUserOp, address } = useZerodevStore()
+const { isKernelClientReady, isRegistering, isLoggingIn, isSendingUserOp, address } = useZerodevStore()

Alternatively, if user is intended to be used later, ensure it is utilized appropriately.


33-33: Destructure Only Necessary Functions from useKernelClient

Ensure that you are only destructuring the necessary variables from useKernelClient. If kernelClient or setWebAuthnKey are unused, consider removing them.


Line range hint 52-68: Handle Errors More Specifically in Registration

In the handleRegister function, the error handling is generic. Catching all errors and re-throwing them may not provide enough context.

Consider handling specific error cases to provide better feedback to the user.


Line range hint 73-90: Consolidate Error Handling in Login Function

Similar to handleRegister, the handleLogin function could benefit from more specific error handling and user feedback.


Line range hint 137-153: Avoid Returning Redux Action Dispatchers in Hook Return Object

Returning functions like setIsKernelClientReady that dispatch Redux actions might not be the best practice.

Encapsulate state management within the hook or provide setter functions that abstract away the Redux implementation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 013b240 and ce4992b.

📒 Files selected for processing (6)
  • src/components/Claim/Link/Onchain/Success.view.tsx (2 hunks)
  • src/components/Create/Create.tsx (2 hunks)
  • src/components/Create/Link/Input.view.tsx (0 hunks)
  • src/context/contextProvider.tsx (1 hunks)
  • src/context/kernelClient.context.tsx (1 hunks)
  • src/hooks/useZeroDev.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/components/Create/Link/Input.view.tsx
🔇 Additional comments (7)
src/context/kernelClient.context.tsx (2)

79-83: Persist WebAuthn Key Retrieval Failure

The code assumes that the storedWebAuthnKey will always be retrieved successfully. If the key is missing or corrupted in local storage, it could lead to unexpected behavior.

Ensure that the storedWebAuthnKey is valid before setting it in the state. You might want to add validation or handle the case where the key is not found.


96-101: Verify Version Compatibility of Validator Contracts

The validatorContractVersion is hardcoded to PasskeyValidatorContractVersion.V0_0_2. Ensure that this version is compatible with the rest of your application and that it's the intended version.

Consider parameterizing the validator contract version or documenting the reasoning behind the chosen version.

src/hooks/useZeroDev.ts (1)

Line range hint 92-128: Check for Null or Undefined kernelClient Before Sending User Operations

The functions handleSendUserOpEncoded and handleSendUserOpNotEncoded check for !kernelClient or !kernelClient?.account. Ensure that this check is sufficient and that appropriate error messages are provided.

Consider providing more descriptive error messages or handling the null cases more gracefully.

src/context/contextProvider.tsx (1)

13-17: Review Context Provider Nesting Order

The introduction of KernelClientProvider changes the context hierarchy. Ensure that the KernelClientProvider is correctly positioned in relation to other providers like AuthProvider and PushProvider.

Confirm that all child components have access to the necessary contexts and that there are no unintended side effects due to the reordering.

src/components/Claim/Link/Onchain/Success.view.tsx (2)

14-14: LGTM: Added isPeanutWallet property

The addition of isPeanutWallet to the useWallet hook's destructured values aligns with the PR's objective to handle Peanut Wallet cases differently.


48-52: LGTM: Conditional token selector reset

Good improvement to prevent unnecessary token selector resets when using Peanut Wallet. The dependencies array correctly includes isPeanutWallet to ensure proper effect triggering.

src/components/Create/Create.tsx (1)

56-56: LGTM: Added isPeanutWallet property

The addition of isPeanutWallet to the useWallet hook's destructured values maintains consistency with other components.

src/context/kernelClient.context.tsx Outdated Show resolved Hide resolved
src/context/kernelClient.context.tsx Show resolved Hide resolved
src/context/kernelClient.context.tsx Show resolved Hide resolved
src/hooks/useZeroDev.ts Show resolved Hide resolved
src/components/Create/Create.tsx Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 0

♻️ Duplicate comments (2)
src/context/kernelClient.context.tsx (2)

34-69: ⚠️ Potential issue

Add error handling to createKernelClient function

The createKernelClient function lacks comprehensive error handling. If any of the asynchronous operations fail (e.g., network requests, account creation), the errors might not be caught, potentially causing unhandled promise rejections.

Apply this diff to add error handling:

 const createKernelClient = async (passkeyValidator: any) => {
+    try {
         console.log('Creating new kernel client...')
         const kernelAccount = await createKernelAccount(peanutPublicClient, {
             plugins: {
                 sudo: passkeyValidator,
             },
             entryPoint: consts.USER_OP_ENTRY_POINT,
             kernelVersion: KERNEL_V3_1,
         })

         const kernelClient = createKernelAccountClient({
             account: kernelAccount,
             chain: consts.PEANUT_WALLET_CHAIN,
             bundlerTransport: http(consts.BUNDLER_URL),
             paymaster: {
                 getPaymasterData: async (userOperation) => {
                     const zerodevPaymaster = createZeroDevPaymasterClient({
                         chain: consts.PEANUT_WALLET_CHAIN,
                         transport: http(consts.PAYMASTER_URL),
                     })

                     try {
                         return await zerodevPaymaster.sponsorUserOperation({
                             userOperation,
                             shouldOverrideFee: true,
                         })
                     } catch (error) {
                         console.error('Paymaster error:', error)
                         throw error
                     }
                 },
             },
         })

         return kernelClient
+    } catch (error) {
+        console.error('Error creating kernel client:', error)
+        throw error
+    }
 }

85-124: ⚠️ Potential issue

Ensure cleanup function is correctly set in useEffect

In the useEffect hook, the cleanup function is returned inside the if (!webAuthnKey) block at lines 88-92. This means that when webAuthnKey is undefined, the cleanup function will be set, but when webAuthnKey is defined, the cleanup function at the end of the effect is used. This can be confusing and may lead to unexpected behavior.

To ensure the cleanup function is always set correctly, move the return statement to the end of the effect, and adjust the logic accordingly.

Apply this diff to correct it:

 useEffect(() => {
     let isMounted = true

     if (!webAuthnKey) {
-        return () => {
-            isMounted = false
-        }
+        return
     }

     const initializeClient = async () => {
         try {
             // existing code
         } catch (error) {
             // error handling
         }
     }

     initializeClient()

     return () => {
         isMounted = false
     }
 }, [webAuthnKey])
🧹 Nitpick comments (1)
src/context/kernelClient.context.tsx (1)

34-34: Specify the correct type instead of using any

Using any for the passkeyValidator parameter defeats the purpose of TypeScript's type safety. Specify a more precise type for passkeyValidator to enhance type safety and maintainability.

Apply this diff to specify the correct type:

-const createKernelClient = async (passkeyValidator: any) => {
+const createKernelClient = async (passkeyValidator: PasskeyValidatorType) => {

Ensure that PasskeyValidatorType is imported or defined appropriately.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce4992b and b1a6e36.

📒 Files selected for processing (1)
  • src/context/kernelClient.context.tsx (1 hunks)

Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

don't see any issue

@@ -45,11 +45,11 @@ export const SuccessClaimLinkView = ({ transactionHash, claimLinkData, type }: _
}

useEffect(() => {
resetTokenContextProvider()
if (!isPeanutWallet) resetTokenContextProvider()
Copy link
Contributor

Choose a reason for hiding this comment

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

nice

Comment on lines 10 to 20
<ToastProvider>
<AuthProvider>
<PushProvider>
<TokenContextProvider>
<LoadingStateContextProvider>{children}</LoadingStateContextProvider>
</TokenContextProvider>
<KernelClientProvider>
<TokenContextProvider>
<LoadingStateContextProvider>{children}</LoadingStateContextProvider>
</TokenContextProvider>
</KernelClientProvider>
</PushProvider>
</AuthProvider>
</ToastProvider>
Copy link
Contributor

Choose a reason for hiding this comment

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

T: this is becoming a pyramid

@Hugo0 Hugo0 merged commit 32f676e into peanut-wallet Jan 17, 2025
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
None yet
Development

Successfully merging this pull request may close these issues.

2 participants