Skip to content

Commit

Permalink
Merge pull request #888 from PolkaGate/fixUnstakeAllIssue
Browse files Browse the repository at this point in the history
fix unstakeAll issue
  • Loading branch information
Nick-1979 authored Nov 11, 2023
2 parents 2bf3a28 + 4375307 commit da73d0f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,50 +8,48 @@
* this component opens unstake review page
* */

import type { ApiPromise } from '@polkadot/api';
import type { SubmittableExtrinsicFunction } from '@polkadot/api/types';
import type { AnyTuple } from '@polkadot/types/types';

import { Container, Grid } from '@mui/material';
import React, { useCallback, useContext, useEffect, useState } from 'react';

import { Chain } from '@polkadot/extension-chains/types';
import { Balance } from '@polkadot/types/interfaces';
import keyring from '@polkadot/ui-keyring';
import { BN } from '@polkadot/util';

import { AccountHolderWithProxy, ActionContext, AmountFee, Motion, PasswordUseProxyConfirm, Popup, ShowBalance2, WrongPasswordAlert } from '../../../../components';
import { useAccountDisplay, useDecimal, useProxies, useToken, useTranslation } from '../../../../hooks';
import { useAccountDisplay, useApi, useChain, useDecimal, useFormatted, useProxies, useToken, useTranslation } from '../../../../hooks';
import { HeaderBrand, SubTitle, WaitScreen } from '../../../../partials';
import Confirmation from '../../../../partials/Confirmation';
import { signAndSend } from '../../../../util/api';
import { Proxy, ProxyItem, TxInfo } from '../../../../util/types';
import { amountToMachine, getSubstrateAddress, saveAsHistory } from '../../../../util/utils';
import { amountToHuman, amountToMachine, getSubstrateAddress, saveAsHistory } from '../../../../util/utils';
import TxDetail from './partials/TxDetail';

interface Props {
address: string;
amount: string;
api: ApiPromise;
chain: Chain;
chilled: SubmittableExtrinsicFunction<'promise', AnyTuple> | undefined
estimatedFee: Balance | undefined;
formatted: string;
hasNominator: boolean;
ç: boolean;
maxUnlockingChunks: number
redeem: SubmittableExtrinsicFunction<'promise', AnyTuple> | undefined;
redeemDate: string | undefined;
setShow: React.Dispatch<React.SetStateAction<boolean>>;
staked: BN;
show: boolean;
total: BN | undefined;
unlockingLen: number;
unbonded: SubmittableExtrinsicFunction<'promise', AnyTuple> | undefined;
staked: BN;
isUnstakeAll: boolean;
}

export default function Review({ address, amount, api, chain, chilled, estimatedFee, formatted, hasNominator, maxUnlockingChunks, redeem, redeemDate, setShow, show, staked, total, unbonded, unlockingLen }: Props): React.ReactElement {
export default function Review({ address, amount, chilled, estimatedFee, hasNominator, isUnstakeAll, maxUnlockingChunks, redeem, redeemDate, setShow, show, staked, total, unbonded, unlockingLen }: Props): React.ReactElement {
const { t } = useTranslation();
const formatted = useFormatted(address);
const chain = useChain(address);
const api = useApi(address);
const proxies = useProxies(api, formatted);
const name = useAccountDisplay(address);
const onAction = useContext(ActionContext);
Expand Down Expand Up @@ -89,7 +87,7 @@ export default function Review({ address, amount, api, chain, chilled, estimated

const unstake = useCallback(async () => {
try {
if (!formatted || !unbonded || !redeem || !chilled || hasNominator === undefined) {
if (!api || !chain || !formatted || !unbonded || !redeem || !chilled || hasNominator === undefined) {
return;
}

Expand All @@ -103,12 +101,12 @@ export default function Review({ address, amount, api, chain, chilled, estimated

if (unlockingLen >= maxUnlockingChunks) {
const optSpans = await api.query.staking.slashingSpans(formatted);
const spanCount = optSpans.isNone ? 0 : optSpans.unwrap().prior.length + 1;
const spanCount = optSpans.isNone ? 0 : optSpans.unwrap().prior.length + 1 as number;

txs.push(redeem(spanCount));
}

if (amountAsBN.eq(staked) && hasNominator) {
if ((isUnstakeAll || amount === amountToHuman(staked, decimal)) && hasNominator) {
txs.push(chilled());
}

Expand All @@ -124,7 +122,7 @@ export default function Review({ address, amount, api, chain, chilled, estimated
date: Date.now(),
failureText,
fee: fee || String(estimatedFee || 0),
from: { address: formatted, name },
from: { address: String(formatted), name },
subAction: 'Unstake',
success,
throughProxy: selectedProxyAddress ? { address: selectedProxyAddress, name: selectedProxyName } : undefined,
Expand All @@ -138,10 +136,10 @@ export default function Review({ address, amount, api, chain, chilled, estimated
setShowWaitScreen(false);
setShowConfirmation(true);
} catch (e) {
console.log('error:', e);
console.error('Unstaking error:', e);
setIsPasswordError(true);
}
}, [amount, api, chain, chilled, decimal, estimatedFee, formatted, hasNominator, maxUnlockingChunks, name, password, redeem, selectedProxy, selectedProxyAddress, selectedProxyName, staked, unbonded, unlockingLen]);
}, [amount, api, chain, chilled, decimal, estimatedFee, formatted, hasNominator, maxUnlockingChunks, name, password, redeem, selectedProxy, selectedProxyAddress, selectedProxyName, staked, unbonded, unlockingLen, isUnstakeAll]);

const _onBackClick = useCallback(() => {
setShow(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import { BN, BN_ONE, BN_ZERO } from '@polkadot/util';
import { AmountWithOptions, Motion, PButton, Warning } from '../../../../components';
import { useApi, useChain, useDecimal, useFormatted, useStakingAccount, useStakingConsts, useToken, useTranslation, useUnSupportedNetwork } from '../../../../hooks';
import { HeaderBrand, SubTitle } from '../../../../partials';
import Asset from '../../../../partials/Asset';
import { DATE_OPTIONS, MAX_AMOUNT_LENGTH, STAKING_CHAINS } from '../../../../util/constants';
import { amountToHuman, amountToMachine } from '../../../../util/utils';
import Asset from '../../../../partials/Asset';
import Review from './Review';

interface State {
Expand Down Expand Up @@ -48,10 +48,10 @@ export default function Index(): React.ReactElement {
const [amount, setAmount] = useState<string>();
const [alert, setAlert] = useState<string | undefined>();
const [showReview, setShowReview] = useState<boolean>(false);
const [unstakeAllAmount, setUnstakeAllAmount] = useState<boolean>(false);
const [isUnstakeAll, setIsUnstakeAll] = useState<boolean>(false);

const staked = useMemo(() => stakingAccount && stakingAccount.stakingLedger.active, [stakingAccount]);
const totalAfterUnstake = useMemo(() => staked && decimal && staked.sub(amountToMachine(amount, decimal)) as BN | undefined, [amount, decimal, staked]);
const staked = useMemo(() => stakingAccount && stakingAccount.stakingLedger.active as unknown as BN, [stakingAccount]);
const totalAfterUnstake = useMemo(() => staked && decimal ? staked.sub(amountToMachine(amount, decimal)) : undefined, [amount, decimal, staked]);
const unlockingLen = stakingAccount?.stakingLedger?.unlocking?.length;
const maxUnlockingChunks = api && api.consts.staking.maxUnlockingChunks?.toNumber() as unknown as number;
const amountAsBN = useMemo(() => amountToMachine(amount, decimal), [amount, decimal]);
Expand All @@ -78,15 +78,15 @@ export default function Index(): React.ReactElement {
return setAlert(t('It is more than already staked.'));
}

if (api && staked && stakingConsts && !staked.sub(amountAsBN).isZero() && !unstakeAllAmount && staked.sub(amountAsBN).lt(stakingConsts.minNominatorBond)) {
if (api && staked && stakingConsts && !staked.sub(amountAsBN).isZero() && !isUnstakeAll && staked.sub(amountAsBN).lt(stakingConsts.minNominatorBond)) {
const remained = api.createType('Balance', staked.sub(amountAsBN)).toHuman();
const min = api.createType('Balance', stakingConsts.minNominatorBond).toHuman();

return setAlert(t('Remaining stake amount ({{remained}}) should not be less than {{min}}.', { replace: { min, remained } }));
}

setAlert(undefined);
}, [amountAsBN, api, staked, stakingConsts, t, unstakeAllAmount]);
}, [amountAsBN, api, staked, stakingConsts, t, isUnstakeAll]);

const getFee = useCallback(async () => {
const txs = [];
Expand All @@ -104,7 +104,7 @@ export default function Index(): React.ReactElement {
txs.push(redeem(...dummyParams));
}

if (amountAsBN.eq(staked)) {
if (isUnstakeAll) {
txs.push(chilled());
}

Expand All @@ -114,7 +114,7 @@ export default function Index(): React.ReactElement {

setEstimatedFee(api?.createType('Balance', partialFee));
}
}, [amountAsBN, api, chilled, formatted, maxUnlockingChunks, redeem, staked, unbonded, unlockingLen]);
}, [amountAsBN, api, chilled, formatted, maxUnlockingChunks, redeem, staked, unbonded, unlockingLen, isUnstakeAll]);

useEffect(() => {
if (amountAsBN && redeem && chilled && maxUnlockingChunks && unlockingLen !== undefined && unbonded && formatted && staked) {
Expand All @@ -130,15 +130,17 @@ export default function Index(): React.ReactElement {
}, [address, history, state]);

const onChangeAmount = useCallback((value: string) => {
setUnstakeAllAmount(false);
setIsUnstakeAll(false);

if (decimal && value.length > decimal - 1) {
console.log(`The amount digits is more than decimal:${decimal}`);

return;
}

setAmount(value.slice(0, MAX_AMOUNT_LENGTH));
const roundedAmount = value.slice(0, MAX_AMOUNT_LENGTH);

setAmount(roundedAmount);
}, [decimal]);

const onAllAmount = useCallback(() => {
Expand All @@ -148,7 +150,7 @@ export default function Index(): React.ReactElement {

const allToShow = amountToHuman(staked.toString(), decimal);

setUnstakeAllAmount(true);
setIsUnstakeAll(true);
setAmount(allToShow);
}, [decimal, staked]);

Expand Down Expand Up @@ -219,18 +221,16 @@ export default function Index(): React.ReactElement {
<Review
address={address}
amount={amount}
api={api}
chain={chain}
staked={staked}
chilled={chilled}
estimatedFee={estimatedFee}
formatted={formatted}
hasNominator={!!stakingAccount?.nominators?.length}
isUnstakeAll={isUnstakeAll}
maxUnlockingChunks={maxUnlockingChunks}
redeem={redeem}
redeemDate={redeemDate}
setShow={setShowReview}
show={showReview}
staked={staked}
total={totalAfterUnstake}
unbonded={unbonded}
unlockingLen={unlockingLen ?? 0}
Expand Down

0 comments on commit da73d0f

Please sign in to comment.