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): Error handling logic #1583

Closed
wants to merge 4 commits into from

Conversation

ShubhamParkhi
Copy link
Contributor

@ShubhamParkhi ShubhamParkhi commented May 18, 2024

The changes in hook checks if the isAllowance flag is true. If it is, it sets an error message based on whether parsedAmount is zero or if there’s an allowanceError. If isAllowance is false, it does a similar check but for setStakeError instead.

Breakdown of the conditions:

  • If parsedAmount is zero, it sets the error message to “Please enter a valid amount to stake or withdraw.”
  • If there’s an allowanceError or setStakeError, it sets the error message to “There was an error processing your request. Please try again later.”

PR-Codex overview

The focus of this PR is to add a min prop to the NumberInputField component and handle error messages in stake operations.

Detailed summary

  • Added min prop to NumberInputField
  • Implemented error message handling in stake operations
  • Removed unused setErrorMsg prop

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

Copy link

netlify bot commented May 18, 2024

Deploy Preview for kleros-v2 ready!

Name Link
🔨 Latest commit 955a35d
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2/deploys/664fbfedc520bf00083471b3
😎 Deploy Preview https://deploy-preview-1583--kleros-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

netlify bot commented May 18, 2024

👷 Deploy request for kleros-v2-neo pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 955a35d

Copy link

netlify bot commented May 18, 2024

👷 Deploy request for kleros-v2-university pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 955a35d

Copy link
Contributor

coderabbitai bot commented May 18, 2024

Important

Review Skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@ShubhamParkhi ShubhamParkhi changed the title fix(web): Error message refactored(web): Error handling logic May 18, 2024
@ShubhamParkhi ShubhamParkhi changed the title refactored(web): Error handling logic refactor(web): Error handling logic May 18, 2024
@kemuru kemuru linked an issue May 20, 2024 that may be closed by this pull request
@jaybuidl jaybuidl requested review from alcercu and kemuru May 20, 2024 14:37
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.

Errors do not go away when you interact with the InputDisplay Field, I think we should rethink this in another way. I think contract errors should not be displayed for users, as they are too strange and technical. I've tried modifying this a bit, maybe something like this? probably without the "hasInteracted" variable since we are already not showing errors if the parsedAmount === 0n

InputDisplay.tsx

import React, { useState, useMemo, useEffect } from "react";
import styled from "styled-components";

import { useParams } from "react-router-dom";
import { useDebounce } from "react-use";
import { useAccount } from "wagmi";

import { useSortitionModuleGetJurorBalance, usePnkBalanceOf } from "hooks/contracts/generated";
import { useParsedAmount } from "hooks/useParsedAmount";
import { commify, uncommify } from "utils/commify";
import { formatPNK, roundNumberDown } from "utils/format";
import { isUndefined } from "utils/index";

import { NumberInputField } from "components/NumberInputField";

import StakeWithdrawButton, { ActionType } from "./StakeWithdrawButton";

const StyledField = styled(NumberInputField)`
  height: fit-content;
`;

const LabelArea = styled.div`
  display: flex;
  justify-content: space-between;
`;

const StyledLabel = styled.label`
  color: ${({ theme }) => theme.primaryBlue};
  cursor: pointer;
`;

const InputArea = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  width: 100%;
`;

const InputFieldAndButton = styled.div`
  display: flex;
  flex-direction: row;
  width: 100%;
`;

const EnsureChainContainer = styled.div`
  button {
    height: 45px;
    border: 1px solid ${({ theme }) => theme.stroke};
  }
`;

interface IInputDisplay {
  action: ActionType;
  isSending: boolean;
  setIsSending: (arg0: boolean) => void;
  setIsPopupOpen: (arg0: boolean) => void;
  amount: string;
  setAmount: (arg0: string) => void;
}

const InputDisplay: React.FC<IInputDisplay> = ({
  action,
  isSending,
  setIsSending,
  setIsPopupOpen,
  amount,
  setAmount,
}) => {
  const [debouncedAmount, setDebouncedAmount] = useState("");
  const [hasInteracted, setHasInteracted] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | undefined>();
  useDebounce(() => setDebouncedAmount(amount), 500, [amount]);
  const parsedAmount = useParsedAmount(uncommify(debouncedAmount) as `${number}`);

  const { id } = useParams();
  const { address } = useAccount();
  const { data: balance } = usePnkBalanceOf({
    enabled: !isUndefined(address),
    args: [address ?? "0x"],
    watch: true,
  });
  const parsedBalance = formatPNK(balance ?? 0n, 0, true);
  const { data: jurorBalance } = useSortitionModuleGetJurorBalance({
    enabled: !isUndefined(address),
    args: [address!, BigInt(id!)],
    watch: true,
  });
  const parsedStake = formatPNK(jurorBalance?.[2] || 0n, 0, true);
  const isStaking = useMemo(() => action === ActionType.stake, [action]);

  useEffect(() => {
    if (!hasInteracted || parsedAmount === 0n) {
      setErrorMsg(undefined);
    } 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 {
      setErrorMsg(undefined);
    }
  }, [hasInteracted, parsedAmount, isStaking, balance, jurorBalance]);

  return (
    <>
      <LabelArea>
        <label>{`Available ${isStaking ? parsedBalance : parsedStake} PNK`}</label>
        <StyledLabel
          onClick={() => {
            const amount = isStaking ? parsedBalance : parsedStake;
            setAmount(amount);
            setHasInteracted(true);
          }}
        >
          {isStaking ? "Stake" : "Withdraw"} all
        </StyledLabel>
      </LabelArea>
      <InputArea>
        <InputFieldAndButton>
          <StyledField
            value={uncommify(amount)}
            onChange={(e) => {
              setAmount(e);
              setHasInteracted(true);
            }}
            placeholder={isStaking ? "Amount to stake" : "Amount to withdraw"}
            message={errorMsg ?? undefined}
            variant={!isUndefined(errorMsg) ? "error" : "info"}
            formatter={(number: string) => commify(roundNumberDown(Number(number)))}
          />
          <EnsureChainContainer>
            <StakeWithdrawButton
              {...{
                parsedAmount,
                action,
                setAmount,
                isSending,
                setIsSending,
                setIsPopupOpen,
                setErrorMsg,
                hasInteracted,
                setHasInteracted,
              }}
            />
          </EnsureChainContainer>
        </InputFieldAndButton>
      </InputArea>
    </>
  );
};

export default InputDisplay;

StakeWithdrawButton.tsx

import React, { useMemo } from "react";

import { useParams } from "react-router-dom";
import { useAccount, usePublicClient } from "wagmi";

import { Button } from "@kleros/ui-components-library";

import {
  usePnkBalanceOf,
  usePnkIncreaseAllowance,
  usePreparePnkIncreaseAllowance,
  usePnkAllowance,
  getKlerosCore,
  useKlerosCoreSetStake,
  usePrepareKlerosCoreSetStake,
  useSortitionModuleGetJurorBalance,
} from "hooks/contracts/generated";
import { useCourtDetails } from "hooks/queries/useCourtDetails";
import { isUndefined } from "utils/index";
import { wrapWithToast } from "utils/wrapWithToast";

import { EnsureChain } from "components/EnsureChain";

export enum ActionType {
  allowance = "allowance",
  stake = "stake",
  withdraw = "withdraw",
}

interface IActionButton {
  isSending: boolean;
  parsedAmount: bigint;
  action: ActionType;
  setIsSending: (arg0: boolean) => void;
  setAmount: (arg0: string) => void;
  setIsPopupOpen: (arg0: boolean) => void;
  setErrorMsg: (arg0: string | undefined) => void;
  hasInteracted: boolean;
  setHasInteracted: (arg0: boolean) => void;
}

const StakeWithdrawButton: React.FC<IActionButton> = ({
  parsedAmount,
  action,
  isSending,
  setIsSending,
  setIsPopupOpen,
  setHasInteracted,
}) => {
  const { id } = useParams();
  const { address } = useAccount();
  const klerosCore = getKlerosCore({});
  const { data: courtDetails } = useCourtDetails(id);
  const { data: balance } = usePnkBalanceOf({
    enabled: !isUndefined(address),
    args: [address!],
    watch: true,
  });
  const { data: jurorBalance } = useSortitionModuleGetJurorBalance({
    enabled: !isUndefined(address),
    args: [address ?? "0x", BigInt(id ?? 0)],
    watch: true,
  });
  const { data: allowance } = usePnkAllowance({
    enabled: !isUndefined(address),
    args: [address ?? "0x", klerosCore.address],
    watch: true,
  });
  const publicClient = usePublicClient();

  const isStaking = action === ActionType.stake;
  const isAllowance = isStaking && !isUndefined(allowance) && allowance < parsedAmount;

  const targetStake = useMemo(() => {
    if (jurorBalance) {
      if (isAllowance) {
        return parsedAmount;
      } else if (isStaking) {
        return jurorBalance[2] + parsedAmount;
      } else {
        return jurorBalance[2] - parsedAmount;
      }
    }
    return 0n;
  }, [jurorBalance, parsedAmount, isAllowance, isStaking]);

  const { config: increaseAllowanceConfig } = usePreparePnkIncreaseAllowance({
    enabled: isAllowance && !isUndefined(klerosCore) && !isUndefined(targetStake) && !isUndefined(allowance),
    args: [klerosCore?.address, BigInt(targetStake ?? 0) - BigInt(allowance ?? 0)],
  });
  const { writeAsync: increaseAllowance } = usePnkIncreaseAllowance(increaseAllowanceConfig);
  const handleAllowance = () => {
    if (!isUndefined(increaseAllowance)) {
      setIsSending(true);
      wrapWithToast(async () => await increaseAllowance().then((response) => response.hash), publicClient).finally(
        () => {
          setIsSending(false);
        }
      );
    }
  };

  const { config: setStakeConfig, error: setStakeError } = usePrepareKlerosCoreSetStake({
    enabled: !isUndefined(targetStake) && !isUndefined(id) && !isAllowance && parsedAmount !== 0n,
    args: [BigInt(id ?? 0), targetStake],
  });
  const { writeAsync: setStake } = useKlerosCoreSetStake(setStakeConfig);
  const handleStake = () => {
    if (typeof setStake !== "undefined") {
      setIsSending(true);
      wrapWithToast(async () => await setStake().then((response) => response.hash), publicClient)
        .then((res) => res.status && setIsPopupOpen(true))
        .finally(() => {
          setIsSending(false);
        });
    }
  };

  const buttonProps = {
    [ActionType.allowance]: {
      text: "Allow PNK",
      checkDisabled: () => !balance || targetStake! > balance,
      onClick: handleAllowance,
    },
    [ActionType.stake]: {
      text: "Stake",
      checkDisabled: () => !isUndefined(setStakeError),
      onClick: handleStake,
    },
    [ActionType.withdraw]: {
      text: "Withdraw",
      checkDisabled: () => !jurorBalance || parsedAmount > jurorBalance[2],
      onClick: handleStake,
    },
  };

  const { text, checkDisabled, onClick } = buttonProps[isAllowance ? ActionType.allowance : action];
  return (
    <EnsureChain>
      <Button
        text={text}
        isLoading={isSending}
        disabled={
          isSending ||
          parsedAmount == 0n ||
          isUndefined(targetStake) ||
          isUndefined(courtDetails) ||
          checkDisabled() ||
          (targetStake !== 0n && targetStake < BigInt(courtDetails.court?.minStake)) ||
          (isStaking && !isAllowance && isUndefined(setStakeConfig.request))
        }
        onClick={() => {
          setHasInteracted(true);
          onClick();
        }}
      />
    </EnsureChain>
  );
};

export default StakeWithdrawButton;

@Harman-singh-waraich
Copy link
Contributor

Negative numbers not handled in withdraw. Fine for staking.

Screenshot 2024-05-21 at 2 04 22 PM

@Harman-singh-waraich
Copy link
Contributor

Harman-singh-waraich commented May 21, 2024

Errors do not go away when you interact with the InputDisplay Field, I think we should rethink this in another way. I think contract errors should not be displayed for users, as they are too strange and technical. I've tried modifying this a bit, maybe something like this? probably without the "hasInteracted" variable since we are already not showing errors if the parsedAmount === 0n

Agreed , technical errors should not be displayed, logging them to console should be fine.

  • wondering if we should display insufficient balance warning (not error), while staking. Otherwise, it's not necessary as the balance displayed above should be enough

Copy link

codeclimate bot commented May 23, 2024

Code Climate has analyzed commit 955a35d and detected 1 issue on this pull request.

Here's the issue category breakdown:

Category Count
Style 1

View more on Code Climate.

@kemuru
Copy link
Contributor

kemuru commented May 24, 2024

continued on #1585

@kemuru kemuru closed this May 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

UI Bug: incorrect error "setStake function reverted"
4 participants