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

refactor(web): min-stake-check #1806

Merged
merged 2 commits into from
Dec 19, 2024
Merged

refactor(web): min-stake-check #1806

merged 2 commits into from
Dec 19, 2024

Conversation

Harman-singh-waraich
Copy link
Contributor

@Harman-singh-waraich Harman-singh-waraich commented Dec 19, 2024

PR-Codex overview

This PR enhances the InputDisplay and StakeWithdrawButton components by integrating courtDetails for improved validation and error messaging related to staking and withdrawing actions.

Detailed summary

  • Added useCourtDetails hook to fetch court details in both InputDisplay and StakeWithdrawButton.
  • Updated error handling for insufficient stake based on courtDetails.court?.minStake.
  • Modified dependency arrays in useEffect hooks to include courtDetails.
  • Improved conditional checks for enabling/disabling actions based on courtDetails.

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

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for staking by incorporating minimum stake requirements.
    • Improved clarity in error messages for users during staking operations.
  • Bug Fixes

    • Streamlined error handling logic in the StakeWithdrawButton component.
  • Documentation

    • Updated import paths for useCourtDetails to reflect new structure.

Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request enhances the staking functionality within the Court Details section of the web application. Key modifications are made to the InputDisplay and StakeWithdrawButton components, focusing on improved error handling related to minimum stake requirements. Updates include new import paths, refined validation logic, and adjustments to the dependencies of the useEffect hooks, ensuring a better user experience during staking operations.

Changes

File Change Summary
web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx - Added useCourtDetails import
- Enhanced useEffect hook to validate minimum stake requirement
web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx - Updated useCourtDetails import path
- Streamlined error handling logic
- Modified isDisabled computation to include minimum stake check
contracts/lib/forge-std - Updated subproject commit reference

Sequence Diagram

sequenceDiagram
    participant User
    participant InputDisplay
    participant StakeWithdrawButton
    participant CourtDetails

    User->>InputDisplay: Enter stake amount
    InputDisplay->>CourtDetails: Fetch court details
    CourtDetails-->>InputDisplay: Return minimum stake
    InputDisplay->>InputDisplay: Validate stake amount
    alt Stake amount < Minimum stake
        InputDisplay->>User: Display minimum stake error
    else Stake amount >= Minimum stake
        InputDisplay->>StakeWithdrawButton: Enable stake button
    end
Loading

Possibly related PRs

  • fix(web): display-stake-button-error #1742: This PR enhances error feedback in the StakeWithdrawButton component, which is directly related to the changes made in the main PR's InputDisplay component regarding error handling for staking operations.
  • fix(web): stake-button-disabling #1787: This PR modifies the StakeWithdrawButton to improve the conditions for enabling stake operations, which aligns with the changes in the main PR that also focus on validating stake requirements.
  • fix(web): stake-input-error-display #1797: This PR updates the InputDisplay and StakeWithdrawButton components to manage popup visibility and error messages, directly connecting to the changes made in the main PR regarding error handling and state management.

Suggested labels

Type: Enhancement :sparkles:, Package: Web

Suggested reviewers

  • kemuru
  • alcercu

Poem

🐰 In the court where stakes are high,
A rabbit hops, with a watchful eye.
Minimums set, errors now clear,
With each token, we conquer fear.
Staking made smooth, let’s give a cheer! 🌟


🪧 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 Dec 19, 2024

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

Name Link
🔨 Latest commit efedc56
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/6763b9fb2299d60008ec1855
😎 Deploy Preview https://deploy-preview-1806--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

netlify bot commented Dec 19, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit efedc56
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/6763b9fb31aacc00088a12b6
😎 Deploy Preview https://deploy-preview-1806--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 Dec 19, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit efedc56
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/6763b9fb701dd50008dd8747
😎 Deploy Preview https://deploy-preview-1806--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 Dec 19, 2024

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit efedc56
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/6763b9fbe8581e00086771cf
😎 Deploy Preview https://deploy-preview-1806--kleros-v2-university.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: 2

🧹 Nitpick comments (3)
web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx (1)

266-273: Consider adding user feedback for minimum stake requirement.

While the minimum stake validation is correctly implemented, users might not understand why the stake button is disabled when their stake amount is below the minimum requirement.

Consider setting an error message in the useEffect hook when the stake amount is below the minimum:

  useEffect(() => {
    if (isPopupOpen) return;
    if (setStakeError || allowanceError) {
      setErrorMsg(parseWagmiError(setStakeError || allowanceError));
+   } else if (
+     action === ActionType.stake &&
+     targetStake !== 0n &&
+     courtDetails?.court?.minStake &&
+     targetStake < BigInt(courtDetails.court.minStake)
+   ) {
+     setErrorMsg(`Minimum stake required: ${courtDetails.court.minStake} PNK`);
    }
-  }, [setStakeError, setErrorMsg, targetStake, allowanceError, isPopupOpen]);
+  }, [setStakeError, setErrorMsg, targetStake, allowanceError, isPopupOpen, action, courtDetails]);
web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx (2)

10-10: Consider organizing imports by type

The imports could be better organized by grouping them into:

  1. External dependencies (React, styled-components)
  2. Internal utilities
  3. Components
  4. Hooks
  5. Styles
import React, { useState, useMemo, useEffect } from "react";
import styled from "styled-components";
import { useParams } from "react-router-dom";
import { useDebounce } from "react-use";

+ // Internal hooks
import { useCourtDetails } from "queries/useCourtDetails";
import { useParsedAmount } from "hooks/useParsedAmount";
import { usePnkData } from "hooks/usePNKData";

+ // Utilities
import { commify, uncommify } from "utils/commify";
import { formatETH, formatPNK, roundNumberDown } from "utils/format";
import { isUndefined } from "utils/index";

+ // Styles
import { hoverShortTransitionTiming } from "styles/commonStyles";

Also applies to: 13-16


94-101: Consider refactoring complex validation logic

The validation logic could be simplified and made more maintainable by:

  1. Extracting validation logic into separate functions
  2. Adding null checks for courtDetails.court
  3. Using early returns instead of nested conditions
+ const isMinStakeValid = (
+   action: ActionType,
+   courtDetails?: { court?: { minStake: string } },
+   jurorBalance?: bigint[],
+   parsedAmount: bigint
+ ) => {
+   if (
+     action !== ActionType.stake ||
+     !courtDetails?.court?.minStake ||
+     !jurorBalance ||
+     parsedAmount === 0n
+   ) return true;
+   
+   return jurorBalance[2] + parsedAmount >= BigInt(courtDetails.court.minStake);
+ };

  useEffect(() => {
    if (parsedAmount > 0n && balance === 0n && isStaking) {
      setErrorMsg("You need a non-zero PNK balance to stake");
      return;
    }
    
    if (isStaking && balance && parsedAmount > balance) {
      setErrorMsg("Insufficient balance to stake this amount");
      return;
    }
    
    if (!isStaking && jurorBalance && parsedAmount > jurorBalance[2]) {
      setErrorMsg("Insufficient staked amount to withdraw this amount");
      return;
    }
    
-   if (
-     action === ActionType.stake &&
-     courtDetails &&
-     jurorBalance &&
-     parsedAmount !== 0n &&
-     jurorBalance[2] + parsedAmount < BigInt(courtDetails?.court?.minStake)
-   ) {
+   if (!isMinStakeValid(action, courtDetails, jurorBalance, parsedAmount)) {
      setErrorMsg(`Min Stake in court is: ${formatETH(courtDetails?.court?.minStake)}`);
      return;
    }
    
    setErrorMsg(undefined);
  }, [parsedAmount, isStaking, balance, jurorBalance, action, courtDetails]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f9cb5a6 and c4916c2.

📒 Files selected for processing (2)
  • web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx (3 hunks)
  • web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx (5 hunks)
🧰 Additional context used
📓 Learnings (1)
web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx (1)
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1775
File: web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx:0-0
Timestamp: 2024-12-09T12:36:59.441Z
Learning: In the `StakeWithdrawButton` component, the transaction flow logic is tightly linked to component updates, so extracting it into a custom hook does not provide significant benefits.
🔇 Additional comments (5)
web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx (4)

71-71: LGTM: Court details integration for minimum stake validation.

The useCourtDetails hook is properly integrated using the court ID from URL parameters.


183-192: LGTM: Clear error handling for simulation failure.

The error handling for simulation failure is well-implemented with a clear, actionable message and proper abort signal handling.


260-263: LGTM: Streamlined error handling logic.

The error handling has been simplified to focus on stake and allowance errors, with minimum stake validation moved to the disabled state check.


287-289: LGTM: Proper dependency management.

The dependencies array has been correctly updated to include all variables used in the isDisabled calculation.

web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx (1)

80-80: LGTM: Proper hook usage

The useCourtDetails hook is correctly implemented with the court id from URL parameters, following React's data fetching best practices.

Copy link

codeclimate bot commented Dec 19, 2024

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

Here's the issue category breakdown:

Category Count
Style 3

View more on Code Climate.

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 (1)
web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx (1)

94-105: Consider extracting validation logic for better readability

The useEffect hook has grown complex with multiple conditions. Consider extracting the validation logic into separate functions:

+ const isInsufficientMinStake = (
+   action: ActionType,
+   courtDetails?: any,
+   jurorBalance?: any,
+   parsedAmount?: bigint
+ ) => {
+   return (
+     action === ActionType.stake &&
+     courtDetails &&
+     jurorBalance &&
+     parsedAmount !== 0n &&
+     jurorBalance[2] + parsedAmount < BigInt(courtDetails?.court?.minStake)
+   );
+ };

  useEffect(() => {
    if (parsedAmount > 0n && balance === 0n && isStaking) {
      setErrorMsg("You need a non-zero PNK balance to stake");
    } else if (isStaking && balance && parsedAmount > balance) {
      setErrorMsg("Insufficient balance to stake this amount");
    } else if (!isStaking && jurorBalance && parsedAmount > jurorBalance[2]) {
      setErrorMsg("Insufficient staked amount to withdraw this amount");
-    } else if (
-      action === ActionType.stake &&
-      courtDetails &&
-      jurorBalance &&
-      parsedAmount !== 0n &&
-      jurorBalance[2] + parsedAmount < BigInt(courtDetails?.court?.minStake)
-    ) {
+    } else if (isInsufficientMinStake(action, courtDetails, jurorBalance, parsedAmount)) {
      setErrorMsg(`Min Stake in court is: ${formatPNK(courtDetails?.court?.minStake)} PNK`);
    } else {
      setErrorMsg(undefined);
    }
  }, [parsedAmount, isStaking, balance, jurorBalance, action, courtDetails]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c4916c2 and efedc56.

📒 Files selected for processing (2)
  • contracts/lib/forge-std (1 hunks)
  • web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • contracts/lib/forge-std
🧰 Additional context used
📓 Learnings (1)
📓 Common learnings
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1775
File: web/src/pages/Courts/CourtDetails/StakePanel/StakeWithdrawButton.tsx:0-0
Timestamp: 2024-12-09T12:36:59.441Z
Learning: In the `StakeWithdrawButton` component, the transaction flow logic is tightly linked to component updates, so extracting it into a custom hook does not provide significant benefits.
🔇 Additional comments (3)
web/src/pages/Courts/CourtDetails/StakePanel/InputDisplay.tsx (3)

13-16: LGTM: Import statements are clean and well-organized

The new imports are properly structured and used within the component.


101-101: LGTM: Consistent token formatting

The error message now correctly uses formatPNK for formatting the minimum stake amount, which is consistent with the rest of the component.


80-80: Verify court details fetching behavior

The hook usage looks correct, but let's verify the error handling for cases where court details might be undefined.

✅ Verification successful

Proper error handling is in place for undefined court details

The verification shows that the useCourtDetails hook is properly implemented and its usage in InputDisplay.tsx has appropriate error handling:

  • The hook itself is enabled conditionally based on the ID's existence
  • Error cases are handled in the component through conditional checks before accessing courtDetails properties
  • The component uses proper null-safe access with optional chaining (courtDetails?.court?.minStake)
  • The courtDetails dependency is correctly included in the dependency arrays of hooks and callbacks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there's proper error handling for undefined court details
ast-grep --pattern 'useCourtDetails($id)' -A 10

Length of output: 49


Script:

#!/bin/bash
# Let's try a different pattern to find the hook usage and its context
ast-grep --pattern 'const { $_ } = useCourtDetails($_)'

# Also search for the hook definition
ast-grep --pattern 'function useCourtDetails($_) {
  $$$
}'

# Search for error handling patterns around court details
rg "courtDetails" -A 5 -B 5

Length of output: 13343

@kemuru kemuru self-requested a review December 19, 2024 07:44
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 Dec 19, 2024
Merged via the queue into dev with commit a744c1f Dec 19, 2024
28 of 29 checks passed
This was referenced Jan 7, 2025
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.

3 participants