Skip to content

fix for transaction with approval, feature to cancel transaction and …#255

Merged
RanaBug merged 1 commit intostagingfrom
fix/wallet-connect-qa-fixes
Mar 13, 2025
Merged

fix for transaction with approval, feature to cancel transaction and …#255
RanaBug merged 1 commit intostagingfrom
fix/wallet-connect-qa-fixes

Conversation

@RanaBug
Copy link
Collaborator

@RanaBug RanaBug commented Mar 13, 2025

…persistence of transaction in send modal

Description

  • Fix WalletConnect sendTransaction with approval step are now working
  • Feature to cancel WalletConnect pending transaction
  • Persistence of pending transaction state when opening the Send Modal

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
    • Introduced a Cancel action in the Send Modal, giving users a direct way to abort an operation.
    • Enhanced WalletConnect transaction handling to support a broader range of request types with clearer cancellation behavior.
    • Improved management of wallet connection data for smoother transaction flows.
    • Updated language support to include a "Cancel" label in the interface.

@RanaBug RanaBug requested a review from IAmKio March 13, 2025 17:21
@RanaBug RanaBug self-assigned this Mar 13, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 13, 2025

Walkthrough

This pull request introduces a cancel action into the send modal components and integrates WalletConnect transaction handling. A new optional callback (onCancel) is added in the bottom buttons component to render a "Cancel" button conditionally. The tokens tab view now uses this callback to reset relevant state when cancellation occurs. Additionally, the context provider and WalletConnect service are updated with new state properties (walletConnectPayload and its setter) to handle specific transaction types. A new translation entry for "cancel" is also added.

Changes

File(s) Change Summary
src/components/BottomMenuModal/SendModal/SendModalBottomButtons.tsx
src/components/BottomMenuModal/SendModal/SendModalTokensTabView.tsx
Added an optional onCancel callback and updated conditional logic to display either an "Add to Batch" or "Cancel" button. The tokens tab view now resets state variables and handles cancellation based on WalletConnect conditions.
src/providers/BottomMenuModalProvider.tsx
src/services/walletConnect.ts
Introduced walletConnectPayload and setWalletConnectPayload for managing WalletConnect data. Modified the provider’s showSend method and WalletConnect hook to update state and handle transaction approval and requests appropriately.
src/translations/en.json Added a new translation entry "cancel": "Cancel" under the "action" section.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant SB as SendModalBottomButtons
    participant ST as SendModalTokensTabView
    participant BP as BottomMenuModalProvider

    U->>SB: Clicks Cancel button
    SB->>ST: Invoke onCancel callback
    ST->>ST: Reset state variables (recipient, asset, amount, warnings)
    ST->>BP: Invoke hide() to close modal
Loading
sequenceDiagram
    participant TX as Transaction Handler
    participant WC as useWalletConnect hook
    participant BP as BottomMenuModalProvider
    participant ST as SendModalTokensTabView

    TX->>WC: Detect request type (approval vs transaction)
    WC->>BP: Set walletConnectPayload via setWalletConnectPayload
    BP->>ST: Update modal based on payload (adjust allowBatching & onCancel)
    Note over WC,BP: Reset walletConnectPayload after handling
Loading

Possibly related PRs

  • fix/wallet-connect-qa-fixes #254: Enhances cancellation handling and WalletConnect transaction management, closely aligning with the modifications introduced in this PR.

Suggested reviewers

  • IAmKio

Poem

I hop by moonlit code tonight,
A rabbit's joy in changes bright.
Cancel buttons and payload flows,
In every line, clarity shows.
Through modals and hooks, our code dances,
Celebrating logic with joyful prances 🐇!
Code and carrots, delight enhances!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

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

@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

🧹 Nitpick comments (4)
src/services/walletConnect.ts (2)

487-523: Enhanced transaction handling with approval support.

The code now properly differentiates between approval and regular transactions, creating appropriate requests for each case. This fixes the issue with WalletConnect sendTransaction approval.

Consider extracting the common steps (showTransactionConfirmation, setWalletConnectPayload, getTransactionHash) into a helper function to reduce code duplication.

 if (request.method === ETH_SEND_TX) {
   const transaction = request.params[0];
   
   const isApprovalTransaction =
     !!transaction.data.startsWith('0x095ea7b3');
     
+  const handleTransaction = async (requestData) => {
+    showTransactionConfirmation(requestData);
+    setWalletConnectPayload(requestData);
+    return await getTransactionHash();
+  };

   if (isApprovalTransaction) {
     const approvalRequest = {
       title: 'WalletConnect Approval Request',
       description: `${dAppName} is requesting approval for a contract.`,
       transaction: {
         to: checksumAddress(transaction.to),
         data: transaction.data,
         chainId: chainIdNumber,
       },
     };

-    showTransactionConfirmation(approvalRequest);
-    setWalletConnectPayload(approvalRequest);
-    requestResponse = await getTransactionHash();
+    requestResponse = await handleTransaction(approvalRequest);
   } else {
     const transactionRequest = {
       title: 'WalletConnect Transaction Request',
       description: `${dAppName} wants to send a transaction`,
       transaction: {
         to: checksumAddress(transaction.to),
         value: formatEther(hexToBigInt(transaction.value)),
         data: transaction.data,
         chainId: chainIdNumber,
       },
     };

-    showTransactionConfirmation(transactionRequest);
-    setWalletConnectPayload(transactionRequest);
-    requestResponse = await getTransactionHash();
+    requestResponse = await handleTransaction(transactionRequest);
   }
 }

532-532: Proper cleanup of WalletConnect payload.

The code correctly resets the WalletConnect payload after processing the transaction, regardless of success or failure. Consider using a finally block to reduce code duplication.

 try {
   await walletKit?.respondSessionRequest({
     topic,
     response: formatJsonRpcResult(id, requestResponse),
   });
   setWalletConnectTxHash(undefined);
-  setWalletConnectPayload(undefined);
 } catch (e: any) {
   console.error('WalletConnect session request error:', e.message);
   await walletKit?.respondSessionRequest({
     topic,
     response: formatJsonRpcError(id, e),
   });
   setWalletConnectTxHash(undefined);
-  setWalletConnectPayload(undefined);
   showToast({
     title: 'WalletConnect',
     subtitle:
       'The request has failed - there was a session request error. Please try again.',
   });
+ } finally {
+  setWalletConnectPayload(undefined);
 }

Also applies to: 540-540

src/components/BottomMenuModal/SendModal/SendModalTokensTabView.tsx (2)

462-465: Consider extracting the WalletConnect check into a variable

The condition payload.title.includes('WalletConnect') is repeated twice, which could lead to inconsistency if one instance is updated but not the other.

+ const isWalletConnectPayload = payload.title.includes('WalletConnect');
  <SendModalBottomButtons
    onSend={onSend}
    safetyWarningMessage={safetyWarningMessage}
    isSendDisabled={isSendDisabled}
    isSending={isSending}
    errorMessage={errorMessage}
    estimatedCostFormatted={estimatedCostFormatted}
    onAddToBatch={onAddToBatch}
-   allowBatching={!payload.title.includes('WalletConnect')}
-   onCancel={
-     !payload.title.includes('WalletConnect') ? undefined : onCancel
-   }
+   allowBatching={!isWalletConnectPayload}
+   onCancel={!isWalletConnectPayload ? undefined : onCancel}

277-280: Consider aligning the WalletConnect detection logic

The condition on lines 277-280 uses specific title checks ("WalletConnect Approval Request" and "WalletConnect Transaction Request"), while the condition on lines 462-465 uses a more general includes('WalletConnect'). For better maintainability, consider using a consistent approach.

+ const isWalletConnectApprovalOrTransaction = 
+   payload?.title === 'WalletConnect Approval Request' || 
+   payload?.title === 'WalletConnect Transaction Request';

  if (newUserOpHash) {
-   if (
-     payload?.title === 'WalletConnect Approval Request' ||
-     payload?.title === 'WalletConnect Transaction Request'
-   ) {
+   if (isWalletConnectApprovalOrTransaction) {
      const txHash = await getTransactionHash(newUserOpHash);
      if (!txHash) {
        setWalletConnectTxHash(undefined);
      } else {
        setWalletConnectTxHash(txHash);
      }
    }
  }

  // Later in the code...
+ const isWalletConnectPayload = payload.title.includes('WalletConnect');
  <SendModalBottomButtons
    // other props...
-   allowBatching={!payload.title.includes('WalletConnect')}
-   onCancel={
-     !payload.title.includes('WalletConnect') ? undefined : onCancel
-   }
+   allowBatching={!isWalletConnectPayload}
+   onCancel={isWalletConnectPayload ? onCancel : undefined}

Also applies to: 462-465

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 713898b and 7c79f14.

⛔ Files ignored due to path filters (2)
  • src/apps/pillarx-app/components/MediaGridCollection/tests/__snapshots__/DisplayCollectionImage.test.tsx.snap is excluded by !**/*.snap
  • src/apps/pillarx-app/components/PointsTile/test/__snapshots__/PointsTile.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (5)
  • src/components/BottomMenuModal/SendModal/SendModalBottomButtons.tsx (4 hunks)
  • src/components/BottomMenuModal/SendModal/SendModalTokensTabView.tsx (4 hunks)
  • src/providers/BottomMenuModalProvider.tsx (4 hunks)
  • src/services/walletConnect.ts (8 hunks)
  • src/translations/en.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit-tests
  • GitHub Check: lint
  • GitHub Check: build
🔇 Additional comments (18)
src/translations/en.json (1)

32-32: Good addition of the "cancel" translation.

The new cancel action has been properly added to the existing action section, following the established structure and convention of the translations file.

src/components/BottomMenuModal/SendModal/SendModalBottomButtons.tsx (3)

19-19: Well-defined optional callback for cancel action.

The new onCancel optional callback is properly typed in the interface, enhancing the component's flexibility.


31-31: Proper prop destructuring.

The onCancel callback is correctly added to the component's destructured props.


42-64: Clean implementation of the cancel button.

The code now properly handles conditionally rendering either the "Add to Batch" button or the new "Cancel" button based on the allowBatching prop. The Cancel button maintains UI consistency with proper styling and follows the existing component patterns.

src/providers/BottomMenuModalProvider.tsx (5)

17-20: Good addition of WalletConnect payload state to context.

The context interface is properly extended with the new state properties for managing WalletConnect payload data.


46-48: Well-implemented state management.

The new state is correctly initialized with React's useState hook and properly typed.


66-69: Enhanced showSend method with WalletConnect support.

The showSend method now intelligently checks for the presence of WalletConnect payload data and includes it when available, improving the user experience for WalletConnect transactions.


78-79: Context data properly updated.

The new state variables are correctly exposed through the context data object.


81-81: Correct dependency array update.

The useMemo dependency array is properly updated to include walletConnectPayload, ensuring the context is recalculated when this value changes.

src/services/walletConnect.ts (6)

24-24: Proper import of required type.

The SendModalData type is correctly imported for use with the new state management.


39-44: Complete hook destructuring.

The additional properties from useBottomMenuModal are properly destructured to access the new WalletConnect payload functionality.


56-58: Good use of ref for tracking WalletConnect payload.

Creating a ref to track the current WalletConnect payload ensures that the async operation has access to the most current value.


109-111: Proper ref synchronization.

The useEffect hook correctly updates the ref whenever the WalletConnect payload changes.


125-127: Improved error handling.

Added an early return when the payload is undefined, which prevents unnecessary waiting and improves user experience during cancellation.


142-142: More descriptive error message.

The transaction timeout error message has been improved to provide clearer guidance to users.

src/components/BottomMenuModal/SendModal/SendModalTokensTabView.tsx (3)

92-98: Properly integrates new WalletConnect state management

The addition of setWalletConnectPayload from useBottomMenuModal hook enables the reset of WalletConnect transaction state when canceling operations, which aligns with the PR objective of supporting transaction cancellation.


277-280: Good enhancement to WalletConnect transaction detection

The condition has been expanded to handle both "WalletConnect Approval Request" and "WalletConnect Transaction Request" types, making the transaction hash retrieval more robust and fixing the approval flow as mentioned in the PR objectives.


355-367: Well-implemented cancellation functionality

The onCancel function properly resets all relevant state variables and appropriately handles WalletConnect payloads, supporting the PR's goal of adding transaction cancellation capability.

@cloudflare-workers-and-pages
Copy link

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7c79f14
Status: ✅  Deploy successful!
Preview URL: https://390ff802.x-e62.pages.dev
Branch Preview URL: https://fix-wallet-connect-qa-fixes.x-e62.pages.dev

View logs

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.

Just a small defensive coding request (after what's been happening) but otherwise looking good!

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

@RanaBug RanaBug merged commit dd3b993 into staging Mar 13, 2025
7 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