Add redeem rewards

This commit is contained in:
Yana
2025-01-17 16:19:01 +02:00
parent 5edb1dd3b0
commit fd8d226d68
4 changed files with 216 additions and 26 deletions
@@ -0,0 +1,45 @@
import SimpleModal from "@/components/modal/SimpleModal";
import { formatBigNum } from "@/utils/formatBigNumbers";
import { Button, Stack, Typography } from "@mui/material";
const RedeemRewardsModal = ({
totalRewardsAmount,
onRedeem,
onClose,
}: {
totalRewardsAmount: number;
onRedeem: () => Promise<void>;
onClose: () => void;
}) => {
const handleOnClose = () => {
onClose();
};
return (
<SimpleModal
title="Redeem all rewards"
open={true}
onClose={handleOnClose}
Actions={
<Button
variant="contained"
color="secondary"
onClick={() => onRedeem()}
fullWidth
>
Next
</Button>
}
>
<Stack spacing={3}>
<Stack spacing={0.5}>
<Typography variant="h3" textAlign={"center"}>
{`${formatBigNum(totalRewardsAmount / 1_000_000)} NYM`}
</Typography>
</Stack>
</Stack>
</SimpleModal>
);
};
export default RedeemRewardsModal;
@@ -4,7 +4,7 @@ import { Button, Stack, Typography } from "@mui/material";
import { CurrencyFormField } from "@nymproject/react/currency/CurrencyFormField.js";
import { IdentityKeyFormField } from "@nymproject/react/mixnodes/IdentityKeyFormField.js";
import type { DecCoin } from "@nymproject/types";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import ExplorerListItem from "../list/ListItem";
import stakingSchema, { MIN_AMOUNT_TO_DELEGATE } from "./schemas";
@@ -33,25 +33,35 @@ const StakeModal = ({
const [isValidated, setValidated] = useState<boolean>(false);
const [errorAmount, setErrorAmount] = useState<string | undefined>();
useEffect(() => {
const asyncValidate = async () => {
await stakingSchema
.parseAsync({ amount: amount.amount, balance, nodeId })
.then(() => {
setValidated(true);
setErrorAmount(undefined);
return true;
})
.catch((e) => {
console.error(e.errors);
setValidated(false);
setErrorAmount(e.errors[0]?.message);
return false;
});
};
asyncValidate();
const validateAmount = useCallback(async () => {
try {
await stakingSchema.parseAsync({
amount: amount.amount,
balance,
nodeId,
});
setValidated(true);
setErrorAmount(undefined);
} catch (e) {
if (e instanceof Error && "errors" in e) {
const validationError = (e as any).errors; // Explicitly cast if necessary
console.error(validationError);
setValidated(false);
setErrorAmount(validationError[0]?.message);
} else {
console.error("Unknown error during validation:", e);
setValidated(false);
setErrorAmount("An unexpected error occurred.");
}
}
}, [amount, balance, nodeId]);
useEffect(() => {
if (nodeId) {
validateAmount();
}
}, [validateAmount, nodeId]);
if (!nodeId) {
return null;
}
@@ -138,8 +138,6 @@ const StakeTable = ({ nodes }: { nodes: MappedNymNodes }) => {
[handleUnstake],
);
console.log("delegations :>> ", delegations);
const columns: MRT_ColumnDef<DelegationWithNodeDetails>[] = useMemo(
() => [
{
@@ -1,22 +1,159 @@
"use client";
import { useChain } from "@cosmos-kit/react";
import type { ObservatoryBalance } from "@/app/api/types";
import { DATA_OBSERVATORY_BALANCES_URL } from "@/app/api/urls";
import { COSMOS_KIT_USE_CHAIN, NYM_MIXNET_CONTRACT } from "@/config";
import { useNymClient } from "@/hooks/useNymClient";
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { GasPrice } from "@cosmjs/stargate";
import { Button, Stack } from "@mui/material";
import type { Delegation } from "@nymproject/contract-clients/Mixnet.types";
import { useCallback, useEffect, useState } from "react";
import Loading from "../loading";
import InfoModal, { type InfoModalProps } from "../modal/InfoModal";
import { Link } from "../muiLink";
import RedeemRewardsModal from "../redeemRewards/RedeemRewardsModal";
import ConnectWallet from "../wallet/ConnectWallet";
const fee = { gas: "1000000", amount: [{ amount: "1000000", denom: "unym" }] };
const SubHeaderRowActions = () => {
const { address } = useNymClient();
const [delegations, setDelegations] = useState<Delegation[]>([]);
const [totalStakerRewards, setTotalStakerRewards] = useState<number>(0);
const [openRedeemRewardsModal, setOpenRedeemRewardsModal] =
useState<boolean>(false);
if (!address) {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [infoModalProps, setInfoModalProps] = useState<InfoModalProps>({
open: false,
});
const { address, nymClient } = useNymClient();
const { getSigningCosmWasmClient } = useChain(COSMOS_KIT_USE_CHAIN);
useEffect(() => {
if (!nymClient || !address) return;
const fetchDelegations = async () => {
try {
const data = await nymClient.getDelegatorDelegations({
delegator: address,
});
setDelegations(data.delegations);
} catch (error) {
console.error("Failed to fetch delegations:", error);
}
};
fetchDelegations();
const fetchBalances = async () => {
const data = await fetch(`${DATA_OBSERVATORY_BALANCES_URL}/${address}`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
},
next: { revalidate: 60 },
// refresh event list cache at given interval
});
const balances: ObservatoryBalance = await data.json();
return setTotalStakerRewards(balances.rewards.staking_rewards.amount);
};
fetchBalances();
}, [address, nymClient]);
const handleRedeemRewards = useCallback(async () => {
setIsLoading(true);
setOpenRedeemRewardsModal(false);
try {
if (!nymClient || !address || !delegations.length) {
throw new Error("Wallet, client, or delegations not available.");
}
console.log("Preparing to redeem rewards...");
const messages = delegations.map((delegation) => {
const nodeId = delegation.node_id;
// Generate the withdraw message
const tx = {
contractAddress: NYM_MIXNET_CONTRACT,
funds: [],
msg: {
withdraw_delegator_reward: {
node_id: nodeId,
},
},
};
return tx; // Use the first message generated
});
console.log("Messages prepared for multi-signing:", messages);
const cosmWasmSigningClient = await getSigningCosmWasmClient();
console.log("Signing client obtained.");
// Execute all messages in one transaction
const result = await cosmWasmSigningClient.executeMultiple(
address,
messages,
fee,
"Redeeming all rewards",
);
console.log("Rewards redeemed successfully:", result);
// Success state
setIsLoading(false);
setInfoModalProps({
open: true,
title: "Success",
message: "All rewards have been redeemed successfully!",
onClose: () => setInfoModalProps({ open: false }),
});
setOpenRedeemRewardsModal(false);
} catch (e) {
console.error("Error redeeming rewards:", e);
setInfoModalProps({
open: true,
title: "Error",
message:
e instanceof Error
? e.message
: "An error occurred while redeeming rewards.",
onClose: () => setInfoModalProps({ open: false }),
});
setIsLoading(false);
}
}, [address, nymClient, delegations, getSigningCosmWasmClient]);
const handleRedeemRewardsButtonClick = () => {
setOpenRedeemRewardsModal(true);
};
if (!address || !nymClient) {
return null;
}
return (
<Stack direction="row" spacing={3} justifyContent={"end"}>
<Button variant="outlined">Redeem all rewards</Button>
<Link href="/explorer">
<Button variant="contained">Stake NYM</Button>
</Link>
<Button variant="contained" onClick={handleRedeemRewardsButtonClick}>
Redeem NYM
</Button>
{isLoading && <Loading />}
{openRedeemRewardsModal && (
<RedeemRewardsModal
onRedeem={() => handleRedeemRewards()}
onClose={() => setOpenRedeemRewardsModal(false)}
totalRewardsAmount={totalStakerRewards}
/>
)}
<InfoModal {...infoModalProps} />
</Stack>
);
};