Skip to content

Conversation

@aimensahnoun
Copy link
Member

@aimensahnoun aimensahnoun commented Aug 21, 2025

Problem

Due to the way USDT works in mainnet and a bug in our API, first USDT invoice payments goes through, second payment would prompt for an approval again, which is blocked by metamask because it will automatically fail because USDT on mainnet blocks non zero approvals if a user already has allowance.

This PR builds on top of changes made to Request API , and fully depends on that PR.

Summary

Enable multi-approval processing for Ethereum USDT direct payments to fix approval transaction
failures.

Changes

  • Enhanced approval transaction handling: Modified the direct payment flow to process
    multiple approval transactions instead of assuming a single approval transaction
  • Dynamic payment transaction identification: Updated logic to use paymentTransactionIndex
    metadata to correctly identify which transaction is the actual payment
  • Improved error handling: Added null safety check for network name display during network
    switching

Technical Details

The previous implementation assumed only one approval transaction was needed, but some payment
scenarios require multiple approvals. This PR:

  1. Loops through all transactions except the payment transaction to execute approvals
  2. Uses metadata indices to properly identify approval vs payment transactions
  3. Maintains existing flow while supporting multi-approval scenarios

Files Modified

  • src/components/payment-section.tsx - Updated handleDirectPayments function to support
    multiple approval transactions

Screenshot:

CleanShot 2025-08-21 at 13 52 57

All of these invoices were paid in a row

Summary by CodeRabbit

  • Bug Fixes
    • Ensures the correct transaction is used for finalizing direct payments, improving reliability.
    • Automatically handles multiple approval steps when required, reducing failed or stuck payments.
    • Prevents a potential error when switching networks by safely handling missing network details.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 21, 2025

Walkthrough

Refactors direct payment logic to use paymentTransactionIndex from metadata, iterating approvals across all non-payment transactions before submitting the designated payment transaction. Removes fixed index logic, adds optional chaining for network-switch toast, and leaves cross-chain flow unchanged.

Changes

Cohort / File(s) Summary
Direct payment flow updates
src/components/payment-section.tsx
Use metadata.paymentTransactionIndex to select payment txn; iterate and send all other txns as approvals when needsApproval; submit payment txn last; remove approvalIndex logic; guard network-switch toast with optional chaining; cross-chain path unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as PaymentSection
  participant Wallet as Wallet/Provider
  participant Chain as Blockchain

  User->>UI: Initiate direct payment
  UI->>UI: Read paymentTransactionIndex from metadata
  alt needsApproval
    loop For each txn ≠ paymentTransactionIndex
      UI->>Wallet: Send approval transaction
      Wallet->>Chain: Broadcast approval
      Chain-->>Wallet: Approval receipt
      Wallet-->>UI: Approval result
    end
  end
  UI->>Wallet: Send payment transaction (at paymentTransactionIndex)
  Wallet->>Chain: Broadcast payment
  Chain-->>Wallet: Payment receipt
  Wallet-->>UI: Payment result
  note over UI: Network-switch toast uses optional chaining for name
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • rodrigopavezi
  • bassgeta
  • MantisClone

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 131-easyinvoice---ethereum-usdt-direct-payments-failure

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 1

🧹 Nitpick comments (3)
src/components/payment-section.tsx (3)

297-305: Drive approvals via an explicit index list; preserves order and clarifies intent

Current loop is fine, but iterating all indices and skipping the payment index is a bit opaque and couples logic to equality checks. Building an approvals index list improves readability and makes room for progress UX if you want to show “Approval 1/2…”. It also leverages the sanitized transactions array from the previous comment.

Apply this diff:

-      // Execute all approval transactions (all transactions except the payment transaction)
-      for (let i = 0; i < paymentData.transactions.length; i++) {
-        if (i !== paymentTransactionIndex) {
-          const approvalTransaction = await signer.sendTransaction(
-            paymentData.transactions[i],
-          );
-          await approvalTransaction.wait();
-        }
-      }
+      // Execute all approval transactions (every tx except the payment one), preserving order from the API
+      const approvalTxIndices = transactions
+        .map((_, i) => i)
+        .filter((i) => i !== paymentTransactionIndex);
+      for (const i of approvalTxIndices) {
+        const approvalTx = await signer.sendTransaction(transactions[i]);
+        await approvalTx.wait();
+      }

Optional UX tweak (outside this range): update the approval toast to reflect multiple approvals, e.g., “Please approve 2 transactions in your wallet.”


315-316: Use the sanitized transactions array for the payment submission

Minor reliability/readability improvement: use the validated transactions array introduced above.

-    const paymentTransaction = await signer.sendTransaction(
-      paymentData.transactions[paymentTransactionIndex],
-    );
+    const paymentTransaction = await signer.sendTransaction(
+      transactions[paymentTransactionIndex],
+    );

335-349: Fail fast if targetAppkitNetwork cannot be resolved; improve user feedback

Today you always attempt switchNetwork even if the mapping is undefined; this is caught and a generic error toast is shown. Provide an earlier, clearer message and avoid making a doomed switch call.

     if (targetChain !== chainId) {
       const targetAppkitNetwork =
         ID_TO_APPKIT_NETWORK[targetChain as keyof typeof ID_TO_APPKIT_NETWORK];

-      toast("Switching to network", {
-        description: `Switching to ${targetAppkitNetwork?.name} network`,
-      });
+      if (!targetAppkitNetwork) {
+        toast("Unsupported network", {
+          description: `Cannot resolve network for ${selectedRoute?.chain}.`,
+        });
+        return;
+      }
+
+      toast("Switching to network", {
+        description: `Switching to ${targetAppkitNetwork.name} network`,
+      });
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 41acd52 and 97d979a.

📒 Files selected for processing (1)
  • src/components/payment-section.tsx (3 hunks)
🔇 Additional comments (1)
src/components/payment-section.tsx (1)

340-340: Nice null-safety on network name in toast

The optional chaining prevents a runtime error when the network mapping is temporarily unavailable. Good defensive tweak.

@aimensahnoun aimensahnoun linked an issue Aug 21, 2025 that may be closed by this pull request
@aimensahnoun aimensahnoun merged commit efd1bdc into main Aug 22, 2025
9 checks passed
@aimensahnoun aimensahnoun deleted the 131-easyinvoice---ethereum-usdt-direct-payments-failure branch August 22, 2025 09:44
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.

EasyInvoice - Ethereum USDT direct payments failure

3 participants