Skip to content

fix: no balance error in hooks #81

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

Closed
wants to merge 2 commits into from
Closed

Conversation

kemuru
Copy link
Contributor

@kemuru kemuru commented Sep 26, 2024

PR-Codex overview

This PR enhances the RaiseDisputeButton component by adding loading states for the arbitration fee configurations based on whether the user is a buyer or a seller, improving user experience during asynchronous operations.

Detailed summary

  • Added loading states isPreparingBuyerConfig and isPreparingSellerConfig for buyer and seller arbitration fee configurations.
  • Updated the useSimulateEscrowUniversalPayArbitrationFeeByBuyer and useSimulateEscrowUniversalPayArbitrationFeeBySeller hooks to include a query object for enabling/disabling based on user role.
  • Modified the Button component to reflect loading states for both buyer and seller configurations.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for raising disputes, providing specific feedback for buyers and sellers.
    • Introduced toast notifications for users regarding errors, particularly for insufficient funds.
    • Added loading states for both buyer and seller configurations during arbitration fee payment simulations.
  • Bug Fixes

    • Improved clarity and maintainability of the dispute raising process, ensuring smoother user experience during payment simulations.

Copy link

netlify bot commented Sep 26, 2024

Deploy Preview for kleros-escrow-v2 ready!

Name Link
🔨 Latest commit 284c401
🔍 Latest deploy log https://app.netlify.com/sites/kleros-escrow-v2/deploys/66f559f479d8f000076dc522
😎 Deploy Preview https://deploy-preview-81--kleros-escrow-v2.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The RaiseDisputeButton component has been updated to improve error handling and control flow when raising disputes. The implementation now includes checks for simulation errors related to arbitration fee payments for both buyers and sellers. If errors occur, appropriate messages are logged, and users receive toast notifications. The logic ensures that simulation errors are addressed before proceeding with payment attempts, enhancing clarity and maintainability in the handling of asynchronous functions.

Changes

Files Change Summary
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx Enhanced error handling for buyers and sellers when raising disputes; restructured control flow to check for simulation errors before payment attempts; improved management of asynchronous payment function and loading states.

Poem

In the garden where disputes arise,
A button now handles errors wise.
With toasts and logs, it guides the way,
For buyers and sellers, come what may.
Hopping through code, we cheer and play! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 45d61ce and 284c401.

📒 Files selected for processing (1)
  • web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx

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 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 or @coderabbitai title 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: 3

🧹 Outside diff range and nitpick comments (1)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (1)

73-73: Use optional chaining for cleaner conditional function calls

Instead of using the logical AND operator to conditionally call toggleModal, you can utilize optional chaining for a more concise and readable solution.

Update the code:

- toggleModal && toggleModal();
+ toggleModal?.();

Also applies to: 105-105

🧰 Tools
🪛 Biome

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9f353a8 and 45d61ce.

📒 Files selected for processing (1)
  • web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (2 hunks)
🧰 Additional context used
🪛 Biome
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (1)

73-73: Adhere to static analysis recommendations

The static analysis tool suggests changing to an optional chain at lines 73 and 105. This improves code clarity and aligns with best practices.

The recommended change was already addressed in a previous comment.

Also applies to: 105-105

🧰 Tools
🪛 Biome

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines 48 to 81
if (isBuyer) {
if (simulateBuyerError) {
console.log({simulateBuyerError});
let errorMessage = "An error occurred during simulation.";
if (simulateBuyerError.message.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}
// Use wrapWithToast to display the error
wrapWithToast(() => Promise.reject(new Error(errorMessage)), publicClient);
return;
}

if (isUndefined(payArbitrationFeeByBuyerConfig)) {
console.log({ payArbitrationFeeByBuyerConfig });
console.log({ simulateBuyerError });
wrapWithToast(() => Promise.reject(new Error("Unable to prepare transaction.")), publicClient);
return;
}

if (!isUndefined(payArbitrationFeeByBuyer)) {
setIsSending(true);
wrapWithToast(() => payArbitrationFeeByBuyer(payArbitrationFeeByBuyerConfig.request), publicClient)
.then((wrapResult) => {
setIsSending(false);
if (wrapResult.status) {
toggleModal && toggleModal();
refetchQuery([["refetchOnBlock", "useTransactionDetailsQuery"]]);
}
})
.catch((error) => {
console.error("Error raising dispute as buyer:", error);
setIsSending(false);
});
}
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

Refactor to eliminate duplicated code in buyer and seller dispute handling

The logic within the buyer and seller sections is nearly identical. Refactoring this code can improve maintainability and reduce the potential for errors due to code duplication.

Consider abstracting the common logic into a single function:

const handleRaiseDispute = () => {
  const isBuyerOrSeller = isBuyer ? 'Buyer' : 'Seller';
  const simulateError = isBuyer ? simulateBuyerError : simulateSellerError;
  const payArbitrationFeeConfig = isBuyer ? payArbitrationFeeByBuyerConfig : payArbitrationFeeBySellerConfig;
  const payArbitrationFee = isBuyer ? payArbitrationFeeByBuyer : payArbitrationFeeBySeller;

  if (simulateError) {
    console.log({ simulateError });
    let errorMessage = "An error occurred during simulation.";
    if (simulateError?.message?.includes("insufficient funds")) {
      errorMessage = "You don't have enough balance to raise a dispute.";
    }
    wrapWithToast(() => Promise.reject(new Error(errorMessage)), publicClient);
    return;
  }

  if (isUndefined(payArbitrationFeeConfig)) {
    console.log({ payArbitrationFeeConfig });
    console.log({ simulateError });
    wrapWithToast(() => Promise.reject(new Error("Unable to prepare transaction.")), publicClient);
    return;
  }

  if (!isUndefined(payArbitrationFee)) {
    setIsSending(true);
    wrapWithToast(() => payArbitrationFee(payArbitrationFeeConfig.request), publicClient)
      .then((wrapResult) => {
        setIsSending(false);
        if (wrapResult.status) {
          toggleModal?.();
          refetchQuery([["refetchOnBlock", "useTransactionDetailsQuery"]]);
        }
      })
      .catch((error) => {
        console.error(`Error raising dispute as ${isBuyerOrSeller.toLowerCase()}:`, error);
        setIsSending(false);
      });
  }
};

Also applies to: 83-113

🧰 Tools
🪛 Biome

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines 85 to 87
if (simulateSellerError.message.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}
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

Ensure safe access to 'message' property of 'simulateSellerError'

Similarly, in the error handling for simulateSellerError, it's important to verify that simulateSellerError and simulateSellerError.message exist before accessing them to prevent potential runtime errors.

Modify the code as follows:

- if (simulateSellerError.message.includes("insufficient funds")) {
+ if (simulateSellerError?.message?.includes("insufficient funds")) {
📝 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
if (simulateSellerError.message.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}
if (simulateSellerError?.message?.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}

Comment on lines 49 to 54
if (simulateBuyerError) {
console.log({simulateBuyerError});
let errorMessage = "An error occurred during simulation.";
if (simulateBuyerError.message.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}
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

Ensure safe access to 'message' property of 'simulateBuyerError'

In the error handling for simulateBuyerError, accessing simulateBuyerError.message without confirming its existence could lead to runtime errors if simulateBuyerError is undefined or if message is not present.

Apply the following change to safely access the message property:

- if (simulateBuyerError.message.includes("insufficient funds")) {
+ if (simulateBuyerError?.message?.includes("insufficient funds")) {
📝 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
if (simulateBuyerError) {
console.log({simulateBuyerError});
let errorMessage = "An error occurred during simulation.";
if (simulateBuyerError.message.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}
if (simulateBuyerError) {
console.log({simulateBuyerError});
let errorMessage = "An error occurred during simulation.";
if (simulateBuyerError?.message?.includes("insufficient funds")) {
errorMessage = "You don't have enough balance to raise a dispute.";
}

@kemuru
Copy link
Contributor Author

kemuru commented Sep 30, 2024

continued in #80

@kemuru kemuru closed this Sep 30, 2024
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.

1 participant