-
Notifications
You must be signed in to change notification settings - Fork 46
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
Conversation
✅ Deploy Preview for kleros-v2 ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
👷 Deploy request for kleros-v2-neo pending review.Visit the deploys page to approve it
|
👷 Deploy request for kleros-v2-university pending review.Visit the deploys page to approve it
|
Important Review SkippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Additionally, you can add CodeRabbit Configration File (
|
There was a problem hiding this 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;
Agreed , technical errors should not be displayed, logging them to console should be fine.
|
Code Climate has analyzed commit 955a35d and detected 1 issue on this pull request. Here's the issue category breakdown:
View more on Code Climate. |
continued on #1585 |
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:
PR-Codex overview
The focus of this PR is to add a
min
prop to theNumberInputField
component and handle error messages in stake operations.Detailed summary
min
prop toNumberInputField
setErrorMsg
prop