Skip to content

Commit

Permalink
-code refactor
Browse files Browse the repository at this point in the history
-added unbonding functionality
  • Loading branch information
isunaslabs committed Jan 4, 2023
1 parent ffe1cd1 commit 12b3488
Show file tree
Hide file tree
Showing 7 changed files with 155 additions and 86 deletions.
21 changes: 14 additions & 7 deletions packages/app-providers/src/hooks/useLedger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Deposit,
DepositEncoded,
StakingAsset,
UnbondingDeposit,
} from "@darwinia/app-types";
import { Option, Vec } from "@polkadot/types";
import BigNumber from "bignumber.js";
Expand Down Expand Up @@ -67,13 +68,18 @@ const useLedger = ({ apiPromise, selectedAccount }: Params) => {
const depositsList: Deposit[] = [];

if (depositsOption.isSome) {
const unstakingDeposits: { depositId: number; expireBlock: number }[] = [];
/*These are the deposits that the user has decided to unbond from staking, they are in the
* 14 days unbonding period */
const unstakingDeposits: UnbondingDeposit[] = [];
if (ledgerOption.isSome) {
const ledgerData = ledgerOption.unwrap().toHuman() as unknown as DarwiniaStakingLedger;
ledgerData.unstakingDeposits?.forEach((item) => {
const expireBlock = Number(item[1].toString().replaceAll(",", ""));
const depositId = Number(item[0].toString().replaceAll(",", ""));
unstakingDeposits.push({
depositId: Number(item[0]),
expireBlock: Number(item[1]),
depositId: depositId,
expireBlock: expireBlock,
isUnbondingComplete: currentBlock.number >= expireBlock,
});
});
}
Expand All @@ -86,12 +92,13 @@ const useLedger = ({ apiPromise, selectedAccount }: Params) => {
depositsData.forEach((item) => {
const startTime = Number(item.startTime.toString().replaceAll(",", ""));
const expiredTime = Number(item.expiredTime.toString().replaceAll(",", ""));
// TODO isEarlyWithdrawn,isRegularWithdrawn, etc need to be updated
const isEarlyWithdrawn = false;
const isRegularWithdrawn = false;
// canWithdraw (canClaim) = item.expiredTime <= now
const hasExpireTimeReached = currentBlock.timestamp >= expiredTime;
const canEarlyWithdraw = !isEarlyWithdrawn && !hasExpireTimeReached;
const canRegularWithdraw = !isRegularWithdrawn && hasExpireTimeReached;
const canRegularWithdraw = hasExpireTimeReached;

const ringAmount = BigNumber(item.value.toString().replaceAll(",", ""));

Expand Down Expand Up @@ -150,21 +157,21 @@ const useLedger = ({ apiPromise, selectedAccount }: Params) => {

// find deposits that have been used in staking by their IDs
const stakedDepositsList = depositsList.filter((deposit) => stakedDepositsIdsList.includes(deposit.id));
const totalStakingDeposit = stakedDepositsList.reduce(
const totalOfDepositsInStaking = stakedDepositsList.reduce(
(acc, deposit) => acc.plus(deposit.value),
BigNumber(0)
);
setStakedAssetDistribution({
ring: {
bonded: BigNumber(ledgerData.stakedRing.toString()),
totalStakingDeposit: BigNumber(totalStakingDeposit.toString()),
totalOfDepositsInStaking: BigNumber(totalOfDepositsInStaking.toString()),
},
kton: {
bonded: BigNumber(ledgerData.stakedKton.toString()),
},
});

const totalRingInStaking = ledgerData.stakedRing.plus(totalStakingDeposit);
const totalRingInStaking = ledgerData.stakedRing.plus(totalOfDepositsInStaking);
const totalKtonInStaking = ledgerData.stakedKton;
totalStakedKton = ledgerData.stakedKton;
setStakingAsset({
Expand Down
1 change: 0 additions & 1 deletion packages/app-providers/src/storageProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ export const StorageProvider = ({ children }: PropsWithChildren) => {
item.nominators.map((nominator) => nominator.toLowerCase()).includes(selectedAccount.toLowerCase())
);
setCurrentlyNominatedCollator(collator);
console.log("collator=====", collator);
}, [collators, selectedAccount]);

useEffect(() => {
Expand Down
6 changes: 6 additions & 0 deletions packages/app-types/src/staking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,10 @@ export interface Delegate {
canChangeCollator?: boolean;
}

export interface UnbondingDeposit {
depositId: number;
isUnbondingComplete: boolean;
expireBlock: number;
}

/*Staking types end here*/
2 changes: 1 addition & 1 deletion packages/app-types/src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Collator, Deposit, StakingAsset } from "./staking";

export interface AssetDetail {
bonded: BigNumber;
totalStakingDeposit?: BigNumber;
totalOfDepositsInStaking?: BigNumber;
}

export interface AssetDistribution {
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/components/AccountOverview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ const AccountOverview = () => {
<div>{t(localeKeys.inDeposit)}</div>
<div>
{prettifyNumber({
number: stakedAssetDistribution?.ring.totalStakingDeposit ?? BigNumber(0),
number: stakedAssetDistribution?.ring.totalOfDepositsInStaking ?? BigNumber(0),
precision: 4,
})}
</div>
Expand Down
55 changes: 47 additions & 8 deletions packages/app/src/components/DepositRecordsTable/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Button, Column, Table, Tooltip, ModalEnhanced } from "@darwinia/ui";
import { Button, Column, Table, Tooltip, ModalEnhanced, notification } from "@darwinia/ui";
import { localeKeys, useAppTranslation } from "@darwinia/app-locale";
import { useStorage, useWallet } from "@darwinia/app-providers";
import helpIcon from "../../assets/images/help.svg";
Expand Down Expand Up @@ -210,7 +210,7 @@ interface WithdrawProps {
const WithdrawModal = ({ isVisible, onClose, onConfirm, onCancel, deposit, type }: WithdrawProps) => {
const { t } = useAppTranslation();
const [isLoading, setLoading] = useState<boolean>(false);
const { selectedNetwork, depositContract } = useWallet();
const { selectedNetwork, depositContract, stakingContract } = useWallet();

/*You'll be charged a penalty of 3 times the rewarded Kton if you want to
* withdraw before the expiredTime */
Expand All @@ -220,7 +220,7 @@ const WithdrawModal = ({ isVisible, onClose, onConfirm, onCancel, deposit, type
? `${t(localeKeys.payAmount, {
amount: `${prettifyNumber({
number: fineAmount,
precision: 3,
precision: 9,
})} ${selectedNetwork?.kton.symbol.toUpperCase()}`,
})} ${selectedNetwork?.kton.symbol.toUpperCase()}`
: `${t(localeKeys.withdraw)}`;
Expand All @@ -229,12 +229,51 @@ const WithdrawModal = ({ isVisible, onClose, onConfirm, onCancel, deposit, type
setLoading(false);
}, [isVisible]);

const onConfirmWithdraw = async () => {
setLoading(true);
/*simulate a request*/
setTimeout(() => {
const regularWithdraw = async () => {
try {
setLoading(true);
const response = (await stakingContract?.claim()) as TransactionResponse;
await response.wait(1);
setLoading(false);
onConfirm();
notification.success({
message: <div>{t(localeKeys.operationSuccessful)}</div>,
});
} catch (e) {
setLoading(false);
notification.error({
message: <div>{t(localeKeys.somethingWrongHappened)}</div>,
});
console.log(e);
}
};

const withdrawEarly = async () => {
try {
setLoading(true);
//TODO needs to be changed
const response = (await stakingContract?.claim()) as TransactionResponse;
await response.wait(1);
setLoading(false);
onConfirm();
}, 6000);
notification.success({
message: <div>{t(localeKeys.operationSuccessful)}</div>,
});
} catch (e) {
setLoading(false);
notification.error({
message: <div>{t(localeKeys.somethingWrongHappened)}</div>,
});
console.log(e);
}
};

const onConfirmWithdraw = async () => {
if (type === "early") {
withdrawEarly();
} else {
regularWithdraw();
}
};

const onCloseModal = () => {
Expand Down
Loading

0 comments on commit 12b3488

Please sign in to comment.