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

fix(web): disable buttons if insufficient balance #1720

Merged
merged 3 commits into from
Oct 17, 2024

Conversation

ShubhamParkhi
Copy link
Contributor

@ShubhamParkhi ShubhamParkhi commented Oct 17, 2024

PR-Codex overview

This PR introduces new styled components for error messages and modifies various buttons to display warnings for insufficient balance. It enhances user feedback in different components by integrating the ErrorButtonMessage and ClosedCircleIcon.

Detailed summary

  • Added ErrorButtonMessage styled component in ErrorButtonMessage.tsx.
  • Created ClosedCircleIcon component in ClosedCircleIcon.tsx.
  • Integrated insufficient balance checks in SubmitDisputeButton.
  • Updated DrawButton to show a message if conditions are not met.
  • Enhanced Fund component with balance checks and error messages.

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

Summary by CodeRabbit

  • New Features

    • Introduced ErrorButtonMessage component for displaying error messages.
    • Added ClosedCircleIcon for enhanced visual feedback on error states.
    • Updated Fund component to conditionally render error messages based on user balance.
    • Enhanced SubmitDisputeButton to display a message when the user's balance is insufficient for dispute submission.
    • Added StyledLabel in DrawButton for improved user guidance during the drawing phase.
    • Updated StakeMaintenanceButtons to open maintenance buttons based on the URL hash.
  • Bug Fixes

    • Improved logic for enabling fund appeals and dispute submissions based on user balance.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes introduce new components and modify existing ones to enhance error handling and user feedback in the application. A styled component ErrorButtonMessage and a new icon component ClosedCircleIcon are added. The Fund and SubmitDisputeButton components are updated to incorporate these new components and to check for insufficient user balance, affecting their rendering and functionality. The useFundAppeal hook is also modified to accept an additional parameter related to balance checks.

Changes

File Path Change Summary
web/src/components/ErrorButtonMessage.tsx Introduced a new styled component ErrorButtonMessage with specific styles and dynamic text color.
web/src/components/StyledIcons/ClosedCircleIcon.tsx Added a new functional component ClosedCircleIcon styled with styled-components for error indication.
web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx Modified Fund component to import new components and update useFundAppeal to include insufficientBalance.
web/src/pages/Resolver/NavigationButtons/SubmitDisputeButton.tsx Updated SubmitDisputeButton to import new components and check for insufficientBalance before submission.
web/src/pages/Cases/CaseDetails/MaintenanceButtons/DrawButton.tsx Enhanced DrawButton with a new styled label and logic for conditional rendering based on needToPassPhase.
web/src/pages/Courts/StakeMaintenanceButton/index.tsx Added useEffect to check the URL hash and set isOpen state for maintenance buttons on mount.

Possibly related PRs

Suggested labels

Priority: Low, Type: Enhancement :sparkles:, Package: Web

Suggested reviewers

  • alcercu

Poem

In the garden where errors bloom,
A button now chases away the gloom.
With circles closed and colors bright,
We fund our dreams, make wrongs turn right.
So hop along, don’t hesitate,
For balance checks can’t seal our fate! 🐇✨


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

netlify bot commented Oct 17, 2024

Deploy Preview for kleros-v2-university failed. Why did it fail? →

Name Link
🔨 Latest commit 0dc7b17
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/6711033fc7e7b800087e7c27

Copy link

netlify bot commented Oct 17, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit 0dc7b17
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/6711033f5dfa7f0008728a7f
😎 Deploy Preview https://deploy-preview-1720--kleros-v2-testnet.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

netlify bot commented Oct 17, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit 0dc7b17
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/6711033fc884660008a0b527
😎 Deploy Preview https://deploy-preview-1720--kleros-v2-neo.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

netlify bot commented Oct 17, 2024

Deploy Preview for kleros-v2-testnet-devtools ready!

Name Link
🔨 Latest commit 0dc7b17
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/6711033f199ac400087bd49a
😎 Deploy Preview https://deploy-preview-1720--kleros-v2-testnet-devtools.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 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 (4)
web/src/components/ErrorButtonMessage.tsx (1)

1-11: LGTM! Well-structured styled component.

The ErrorButtonMessage component is well-implemented using styled-components. It provides a reusable, themed error message style that can be easily integrated into other components. The use of flexbox for layout and theme-based color is a good practice.

Consider adding a role="alert" attribute to improve accessibility for screen readers. This can be done by modifying the component definition:

-export const ErrorButtonMessage = styled.div`
+export const ErrorButtonMessage = styled.div.attrs({ role: 'alert' })`

This change will ensure that assistive technologies properly announce the error message when it appears.

web/src/components/StyledIcons/ClosedCircleIcon.tsx (2)

1-3: LGTM! Consider using absolute imports for better maintainability.

The imports are appropriate for the component's needs. However, consider using absolute imports for the SVG file to improve maintainability and reduce the risk of broken imports if the file structure changes.

You could update the SVG import to use an absolute path:

-import ClosedCircle from "svgs/icons/close-circle.svg";
+import ClosedCircle from "@/svgs/icons/close-circle.svg";

This assumes you have configured absolute imports in your project. If not, you may need to set up path aliases in your TypeScript configuration.


11-14: LGTM! Consider adding prop support for enhanced flexibility.

The ClosedCircleIcon component is correctly defined and exported. It serves as a simple wrapper for the styled SVG, which is a common and clean pattern.

To enhance the component's flexibility, consider allowing it to accept and pass through additional props:

-const ClosedCircleIcon: React.FC = () => {
-  return <StyledClosedCircle />;
+const ClosedCircleIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => {
+  return <StyledClosedCircle {...props} />;
};

This change would allow users of the component to pass additional SVG properties if needed, making the component more versatile.

web/src/pages/Resolver/NavigationButtons/SubmitDisputeButton.tsx (1)

70-99: Consider providing additional guidance for insufficient balance.

To enhance user experience, consider displaying the required arbitration cost and the user's current balance. This additional information can help users understand how much more they need to proceed.

You could update the error message as follows:

              {insufficientBalance && (
                <ErrorButtonMessage>
                  <ClosedCircleIcon /> Insufficient balance
+                 <div>
+                   Required: {disputeData.arbitrationCost} ETH
+                   <br />
+                   Your Balance: {userBalance?.formatted} ETH
+                 </div>
                </ErrorButtonMessage>
              )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e72bd47 and 4330dbf.

📒 Files selected for processing (4)
  • web/src/components/ErrorButtonMessage.tsx (1 hunks)
  • web/src/components/StyledIcons/ClosedCircleIcon.tsx (1 hunks)
  • web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx (5 hunks)
  • web/src/pages/Resolver/NavigationButtons/SubmitDisputeButton.tsx (4 hunks)
🧰 Additional context used
🔇 Additional comments (14)
web/src/components/StyledIcons/ClosedCircleIcon.tsx (2)

5-9: LGTM! Well-structured styled component.

The StyledClosedCircle component is well-defined:

  • It correctly uses the theme for dynamic styling, promoting consistency.
  • The component name follows the "Styled" prefix convention.
  • Targeting the SVG's path element for styling is appropriate.

1-14: Summary: Well-implemented icon component aligning with PR objectives

The new ClosedCircleIcon component is a well-structured addition that aligns perfectly with the PR's objective of enhancing error handling and user feedback. It provides a consistent way to display error-related icons, which can be used in conjunction with the disabled buttons for insufficient balance mentioned in the PR title.

Key points:

  1. The component uses styled-components effectively for theming.
  2. It follows React best practices for functional components.
  3. The implementation is clean and maintainable.

The suggested improvements (absolute imports and prop forwarding) are minor and optional, aimed at enhancing flexibility and maintainability.

Great job on this addition to the UI components!

web/src/pages/Resolver/NavigationButtons/SubmitDisputeButton.tsx (8)

5-5: Imports are correctly added for new hooks and components.

The addition of useAccount, useBalance, and usePublicClient from "wagmi" is appropriate for retrieving account and balance information. Similarly, importing ErrorButtonMessage and ClosedCircleIcon ensures the error message components are available for use.


37-39: Balance retrieval handles user account correctly.

Using useAccount to get the address and then useBalance to retrieve the user's balance is appropriate. This allows the component to access the user's balance information securely.


40-44: Logic for determining insufficient balance is sound.

The useMemo hook correctly calculates insufficientBalance by comparing the user's balance to the arbitration cost. This optimization ensures the computation is efficient and only recalculates when dependencies change.


48-48: Simulation is disabled when user has insufficient balance.

Including !insufficientBalance in the enabled condition prevents unnecessary simulations when the user cannot afford the arbitration cost, optimizing performance.


62-63: Button disabled state appropriately includes balance checks.

Updating isButtonDisabled to consider isBalanceLoading and insufficientBalance ensures the button is only enabled when the user's balance is known and sufficient.


70-75: Button loading state reflects submission and balance loading status.

The isLoading prop correctly uses (isSubmittingCase || isBalanceLoading) && !insufficientBalance, preventing the loading state when the user has insufficient balance.


94-99: Appropriate error message displayed for insufficient balance.

Displaying the ErrorButtonMessage with ClosedCircleIcon when insufficientBalance is true provides clear feedback to the user about their balance status.


70-99: Verify that the balance updates correctly upon changes.

Ensure that the balance information reflects real-time data, especially after transactions that might change the user's balance. This is crucial for accurate validation.

You can run the following script to check if the balance updates as expected:

web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx (4)

18-19: Imports are correctly added

The imports for ErrorButtonMessage and ClosedCircleIcon are appropriately added and necessary for the new functionality.


108-110: Ensure consistent types when comparing values

Verify that balance.value and parsedAmount are of the same type (both BigInt) to ensure the comparison balance.value < parsedAmount works correctly without unexpected errors.


134-134: Confirm the loading state logic when balance is insufficient

In the isLoading property of the StyledButton, the loading state is set to false when insufficientBalance is true:

isLoading={(isSending || isLoading) && !insufficientBalance}

Please verify if this behavior aligns with the desired user experience. If the loading state should not depend on insufficientBalance, consider adjusting the condition.


140-141: Ensure correct handling of the transaction response

Verify that accessing res.status accurately determines the success of the transaction. Depending on the structure of the response from wrapWithToast, res may not have a status property. Ensure that you are checking the correct property before calling setIsOpen(true).

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 17, 2024
@ShubhamParkhi ShubhamParkhi requested a review from kemuru October 17, 2024 12:14
kemuru
kemuru previously approved these changes Oct 17, 2024
Copy link
Contributor

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

codeclimate bot commented Oct 17, 2024

Code Climate has analyzed commit 0dc7b17 and detected 3 issues on this pull request.

Here's the issue category breakdown:

Category Count
Complexity 1
Duplication 2

View more on Code Climate.

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

🧹 Outside diff range and nitpick comments (3)
web/src/pages/Courts/StakeMaintenanceButton/index.tsx (1)

50-53: Approved with a minor optimization suggestion.

The new useEffect hook successfully implements the ability to open the maintenance buttons by default when the URL contains the "#maintenance" hash. This enhances the component's functionality and improves user experience.

Consider optimizing this implementation by using the useState initializer function instead of useEffect. This approach is more efficient for setting initial state based on props or global values. Here's how you can refactor it:

-const [isOpen, setIsOpen] = useState(false);
+const [isOpen, setIsOpen] = useState(() => location.hash.includes("#maintenance"));

-useEffect(() => {
-  const openDefault = location.hash.includes("#maintenance");
-  if (openDefault) setIsOpen(true);
-}, []);

This change eliminates the need for an additional effect and ensures the initial state is set correctly from the start.

web/src/pages/Cases/CaseDetails/MaintenanceButtons/DrawButton.tsx (2)

26-26: Consider adding styles to StyledLabel or remove if unused.

The StyledLabel component is created but doesn't have any styles defined. If specific styles are intended, please add them. If no custom styling is needed, consider using a regular label element instead.


78-88: LGTM with a suggestion: Consider parameterizing the link destination.

The conditional rendering of the StyledLabel with informative text and a link is a good addition. It provides clear guidance to users when the phase needs to be changed.

However, the link destination "/courts/1/purpose/#maintenance" is hardcoded. Consider parameterizing this to make it flexible for different court IDs:

<Link to={`/courts/${courtId}/purpose/#maintenance`}>here</Link>

This assumes courtId is available in the component's props or context. If not, you may need to add it.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4330dbf and 0dc7b17.

📒 Files selected for processing (2)
  • web/src/pages/Cases/CaseDetails/MaintenanceButtons/DrawButton.tsx (3 hunks)
  • web/src/pages/Courts/StakeMaintenanceButton/index.tsx (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
web/src/pages/Cases/CaseDetails/MaintenanceButtons/DrawButton.tsx (3)

20-20: LGTM: New import for navigation.

The addition of the Link import from 'react-router-dom' is appropriate for the new navigation functionality introduced in the component.


45-48: LGTM: Well-implemented memoized variable.

The needToPassPhase variable is correctly implemented using useMemo. It efficiently determines if the current state requires a phase transition for juror drawing. The dependencies are properly specified, ensuring the value is recalculated when necessary.


Line range hint 1-88: Overall assessment: Well-implemented changes with minor suggestions.

The modifications to the DrawButton component effectively enhance its functionality and user experience. The addition of conditional rendering to guide users when a phase change is needed is particularly valuable. The code is well-structured and follows React best practices.

Consider the following minor improvements:

  1. Add styles to the StyledLabel component or use a regular label if no custom styling is needed.
  2. Parameterize the hardcoded link in the conditional rendering to make it more flexible for different court IDs.

These changes significantly improve the component's usability and provide clear guidance to users.

Copy link
Contributor

@alcercu alcercu left a comment

Choose a reason for hiding this comment

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

lgtm

@alcercu alcercu added this pull request to the merge queue Oct 17, 2024
Merged via the queue into dev with commit f2c8401 Oct 17, 2024
22 of 28 checks passed
@kemuru kemuru deleted the feat/disable-buttons-if-insufficient-balance branch October 17, 2024 16:31
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.

4 participants