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

[Issue-3554] [Issue-3555] WebApp - Add a warning or notice in case of chainStakingBoth #3691

Merged
merged 5 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// Copyright 2019-2022 @subwallet/extension-web-ui authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { APIItemState } from '@subwallet/extension-base/background/KoniTypes';
import { APIItemState, NotificationType } from '@subwallet/extension-base/background/KoniTypes';
import { ALL_ACCOUNT_KEY } from '@subwallet/extension-base/constants';
import { _STAKING_CHAIN_GROUP } from '@subwallet/extension-base/services/earning-service/constants';
import { EarningRewardItem, YieldPoolType, YieldPositionInfo } from '@subwallet/extension-base/types';
import { AlertModal, BaseModal, EarningInstructionModal, EarningPositionDesktopItem, EarningPositionItem, EmptyList, FilterModal, Layout } from '@subwallet/extension-web-ui/components';
import { FilterTabsNode } from '@subwallet/extension-web-ui/components/FilterTabsNode';
import BannerGenerator from '@subwallet/extension-web-ui/components/StaticContent/BannerGenerator';
import { ASTAR_PORTAL_URL, BN_TEN, CANCEL_UN_STAKE_TRANSACTION, CLAIM_REWARD_TRANSACTION, DEFAULT_CANCEL_UN_STAKE_PARAMS, DEFAULT_CLAIM_REWARD_PARAMS, DEFAULT_EARN_PARAMS, DEFAULT_UN_STAKE_PARAMS, DEFAULT_WITHDRAW_PARAMS, EARN_TRANSACTION, EARNING_INSTRUCTION_MODAL, TRANSACTION_YIELD_CANCEL_UNSTAKE_MODAL, TRANSACTION_YIELD_CLAIM_MODAL, TRANSACTION_YIELD_UNSTAKE_MODAL, TRANSACTION_YIELD_WITHDRAW_MODAL, UN_STAKE_TRANSACTION, WITHDRAW_TRANSACTION } from '@subwallet/extension-web-ui/constants';
import { ASTAR_PORTAL_URL, BN_TEN, CANCEL_UN_STAKE_TRANSACTION, CLAIM_REWARD_TRANSACTION, DEFAULT_CANCEL_UN_STAKE_PARAMS, DEFAULT_CLAIM_REWARD_PARAMS, DEFAULT_EARN_PARAMS, DEFAULT_UN_STAKE_PARAMS, DEFAULT_WITHDRAW_PARAMS, EARN_TRANSACTION, EARNING_INSTRUCTION_MODAL, EARNING_WARNING_ANNOUNCEMENT, TRANSACTION_YIELD_CANCEL_UNSTAKE_MODAL, TRANSACTION_YIELD_CLAIM_MODAL, TRANSACTION_YIELD_UNSTAKE_MODAL, TRANSACTION_YIELD_WITHDRAW_MODAL, UN_STAKE_TRANSACTION, WITHDRAW_TRANSACTION } from '@subwallet/extension-web-ui/constants';
import { ScreenContext } from '@subwallet/extension-web-ui/contexts/ScreenContext';
import { useAlert, useFilterModal, useGetBannerByScreen, useSelector, useTranslation } from '@subwallet/extension-web-ui/hooks';
import { useAlert, useFilterModal, useGetBannerByScreen, useGetYieldPositionForSpecificAccount, useSelector, useTranslation } from '@subwallet/extension-web-ui/hooks';
import { reloadCron } from '@subwallet/extension-web-ui/messaging';
import EarningPositionBalance from '@subwallet/extension-web-ui/Popup/Home/Earning/EarningEntry/EarningPositions/EarningPositionsBalance';
import { Toolbar } from '@subwallet/extension-web-ui/Popup/Home/Earning/shared/desktop/Toolbar';
Expand Down Expand Up @@ -69,7 +69,7 @@ function Component ({ className, earningPositions, setEntryView, setLoading }: P
const { currencyData, priceMap } = useSelector((state) => state.price);
const { assetRegistry: assetInfoMap } = useSelector((state) => state.assetRegistry);
const chainInfoMap = useSelector((state) => state.chainStore.chainInfoMap);
const { currentAccount } = useSelector((state) => state.accountState);
const { accounts, currentAccount } = useSelector((state) => state.accountState);
const { filterSelectionMap, onApplyFilter, onChangeFilterOption, onCloseFilterModal, selectedFilters } = useFilterModal(FILTER_MODAL_ID);
const { alertProps, closeAlert, openAlert } = useAlert(alertModalId);
const poolInfoMap = useSelector((state) => state.earning.poolInfoMap);
Expand All @@ -82,6 +82,8 @@ function Component ({ className, earningPositions, setEntryView, setLoading }: P
const [, setClaimRewardStorage] = useLocalStorage(CLAIM_REWARD_TRANSACTION, DEFAULT_CLAIM_REWARD_PARAMS);
const [, setWithdrawStorage] = useLocalStorage(WITHDRAW_TRANSACTION, DEFAULT_WITHDRAW_PARAMS);
const [, setCancelUnStakeStorage] = useLocalStorage(CANCEL_UN_STAKE_TRANSACTION, DEFAULT_CANCEL_UN_STAKE_PARAMS);
const [announcement, setAnnouncement] = useLocalStorage(EARNING_WARNING_ANNOUNCEMENT, 'nonConfirmed');
const specificList = useGetYieldPositionForSpecificAccount(currentAccount?.address);

const { inactiveModal } = useContext(ModalContext);

Expand Down Expand Up @@ -163,6 +165,96 @@ function Component ({ className, earningPositions, setEntryView, setLoading }: P
});
}, [assetInfoMap, currencyData, earningPositions, priceMap]);

const chainStakingBoth = useMemo(() => {
const chains = ['polkadot', 'kusama'];

const findChainWithStaking = (list: YieldPositionInfo[]) => {
const hasNativeStaking = (chain: string) => list.some((item) => item.chain === chain && item.type === YieldPoolType.NATIVE_STAKING);
const hasNominationPool = (chain: string) => list.some((item) => item.chain === chain && item.type === YieldPoolType.NOMINATION_POOL);

for (const chain of chains) {
if (hasNativeStaking(chain) && hasNominationPool(chain)) {
return chain;
}
}

return null;
};

if (currentAccount?.address !== ALL_ACCOUNT_KEY) {
return findChainWithStaking(specificList);
}

for (const acc of accounts) {
if (acc.address !== ALL_ACCOUNT_KEY) {
const listStaking = specificList.filter((item) => item.address === acc.address);
const chain = findChainWithStaking(listStaking);

if (chain) {
return chain;
}
}
}

return null;
}, [accounts, currentAccount?.address, specificList]);

const learnMore = useCallback(() => {
window.open('https://support.polkadot.network/support/solutions/articles/65000188140-changes-for-nomination-pool-members-and-opengov-participation');
}, []);

const onCancel = useCallback(() => {
closeAlert();
setAnnouncement('confirmed');
}, [closeAlert, setAnnouncement]);

useEffect(() => {
if (chainStakingBoth && announcement.includes('nonConfirmed')) {
const chainInfo = chainStakingBoth && chainInfoMap[chainStakingBoth];

const symbol = (!!chainInfo && chainInfo?.substrateInfo?.symbol) || '';
const originChain = (!!chainInfo && chainInfo?.name) || '';

openAlert({
type: NotificationType.WARNING,
onCancel: onCancel,
content:
(<>
<div className={CN(className, 'earning-alert-content')}>
<span>{t('You’re dual staking via both direct nomination and nomination pool, which')}&nbsp;</span>
<span className={'__info-highlight'}>{t('will not be supported')}&nbsp;</span>
<span>{t(`in the upcoming ${originChain} runtime upgrade. Read more to learn about the upgrade, and`)}&nbsp;</span>
<a
href={'https://docs.subwallet.app/main/mobile-app-user-guide/manage-staking/unstake'}
rel='noreferrer'
style={{ textDecoration: 'underline' }}
target={'_blank'}
>{(`unstake your ${symbol}`)}
</a>
<span>&nbsp;{t('from one of the methods to avoid issues')}</span>
</div>

</>),
title: t(`Unstake your ${symbol} now!`),
okButton: {
text: t('Read update'),
onClick: () => {
learnMore();
setAnnouncement('confirmed');
closeAlert();
}
},
cancelButton: {
text: t('Dismiss'),
onClick: () => {
closeAlert();
setAnnouncement('confirmed');
}
}
});
}
}, [announcement, chainInfoMap, chainStakingBoth, className, closeAlert, learnMore, onCancel, openAlert, setAnnouncement, t]);

const filterOptions = [
{ label: t('Nomination pool'), value: YieldPoolType.NOMINATION_POOL },
{ label: t('Direct nomination'), value: YieldPoolType.NATIVE_STAKING },
Expand Down Expand Up @@ -791,6 +883,13 @@ const EarningPositions = styled(Component)<Props>(({ theme: { token } }: Props)

// desktop

'&.earning-alert-content': {
display: 'contents',
'.__info-highlight': {
fontWeight: token.fontWeightStrong
}
},

'.__desktop-toolbar': {
marginBottom: 20
},
Expand Down
145 changes: 108 additions & 37 deletions packages/extension-web-ui/src/Popup/Transaction/variants/Earn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { EarningInstructionModal } from '@subwallet/extension-web-ui/components/
import { CREATE_RETURN, DEFAULT_ROUTER_PATH, EARNING_INSTRUCTION_MODAL, EVM_ACCOUNT_TYPE, STAKE_ALERT_DATA, SUBSTRATE_ACCOUNT_TYPE } from '@subwallet/extension-web-ui/constants';
import { ScreenContext } from '@subwallet/extension-web-ui/contexts/ScreenContext';
import { WebUIContext } from '@subwallet/extension-web-ui/contexts/WebUIContext';
import { useChainConnection, useFetchChainState, useGetBalance, useGetNativeTokenSlug, useInitValidateTransaction, usePreCheckAction, useRestoreTransaction, useSelector, useSetSelectedAccountTypes, useTransactionContext, useWatchTransaction, useYieldPositionDetail } from '@subwallet/extension-web-ui/hooks';
import { useChainConnection, useFetchChainState, useGetBalance, useGetNativeTokenSlug, useGetYieldPositionForSpecificAccount, useInitValidateTransaction, usePreCheckAction, useRestoreTransaction, useSelector, useSetSelectedAccountTypes, useTransactionContext, useWatchTransaction, useYieldPositionDetail } from '@subwallet/extension-web-ui/hooks';
import { fetchPoolTarget, getOptimalYieldPath, submitJoinYieldPool, validateYieldProcess } from '@subwallet/extension-web-ui/messaging';
// import { unlockDotCheckCanMint } from '@subwallet/extension-web-ui/messaging/campaigns';
import { DEFAULT_YIELD_PROCESS, EarningActionType, earningReducer } from '@subwallet/extension-web-ui/reducer';
Expand Down Expand Up @@ -115,6 +115,7 @@ const Component = ({ className }: ComponentProps) => {
const submitStepType = processState.steps?.[!currentStep ? currentStep + 1 : currentStep]?.type;

const { compound } = useYieldPositionDetail(slug);
const specificList = useGetYieldPositionForSpecificAccount(fromValue);
const { nativeTokenBalance } = useGetBalance(chainValue, fromValue);
const { checkChainConnected, turnOnChain } = useChainConnection();
const [isConnectingChainSuccess, setIsConnectingChainSuccess] = useState<boolean>(false);
Expand All @@ -123,7 +124,7 @@ const Component = ({ className }: ComponentProps) => {
const setSelectedAccountTypes = useSetSelectedAccountTypes(false);

const poolInfo = poolInfoMap[slug] as YieldPoolInfo | undefined;
const poolType = poolInfo?.type || '';
const poolType = poolInfo?.type || '' as YieldPoolType;
const poolChain = poolInfo?.chain || '';

const [isBalanceReady, setIsBalanceReady] = useState<boolean>(true);
Expand All @@ -143,10 +144,30 @@ const Component = ({ className }: ComponentProps) => {
const chainState = useFetchChainState(poolInfo?.chain || '');

const mustChooseTarget = useMemo(
() => !!poolType && [YieldPoolType.NATIVE_STAKING, YieldPoolType.NOMINATION_POOL].includes(poolType as YieldPoolType),
() => !!poolType && [YieldPoolType.NATIVE_STAKING, YieldPoolType.NOMINATION_POOL].includes(poolType),
[poolType]
);

const chainStakingBoth = useMemo(() => {
const hasNativeStaking = (chain: string) => specificList.some((item) => item.chain === chain && item.type === YieldPoolType.NATIVE_STAKING);
const hasNominationPool = (chain: string) => specificList.some((item) => item.chain === chain && item.type === YieldPoolType.NOMINATION_POOL);

const chains = ['polkadot', 'kusama'];
let chainStakingInBoth;

for (const chain of chains) {
if (hasNativeStaking(chain) && hasNominationPool(chain) && [YieldPoolType.NOMINATION_POOL, YieldPoolType.NATIVE_STAKING].includes(poolType) && chain === chainValue) {
chainStakingInBoth = chain;
break;
} else if (((hasNativeStaking(chain) && poolType === YieldPoolType.NOMINATION_POOL) || (hasNominationPool(chain) && poolType === YieldPoolType.NATIVE_STAKING)) && chain === chainValue) {
chainStakingInBoth = chain;
break;
}
}

return chainStakingInBoth;
}, [specificList, poolType, chainValue]);

const balanceTokens = useMemo(() => {
const result: Array<{ chain: string; token: string }> = [];

Expand Down Expand Up @@ -525,46 +546,96 @@ const Component = ({ className }: ComponentProps) => {
}
};

const maxCount = poolInfo?.statistic?.maxCandidatePerFarmer ?? 1;
const userSelectedPoolCount = poolTargetValue?.split(',').length ?? 1;
const label = getValidatorLabel(chainValue);
const checkValidatorConfirmationModal = (): Promise<void> => {
return new Promise((resolve, reject) => {
const maxCount = poolInfo?.statistic?.maxCandidatePerFarmer ?? 1;
const userSelectedPoolCount = poolTargetValue?.split(',').length ?? 1;
const label = getValidatorLabel(chainValue);

if (userSelectedPoolCount < maxCount && label === 'Validator') {
openAlert({
title: t('Pay attention!'),
content: t('You are recommended to choose {{maxCount}} validators to optimize your earnings. Do you wish to continue with {{userSelectedPoolCount}} validator{{x}}?', { replace: { maxCount, userSelectedPoolCount, x: userSelectedPoolCount === 1 ? '' : 's' } }),
okButton: {
text: t('Continue'),
onClick: () => {
closeAlert();
submitData(currentStep)
.catch(onError)
.finally(() => {
setSubmitLoading(false);
});
}
},
cancelButton: {
text: t('Go back'),
onClick: () => {
setSubmitLoading(false);
closeAlert();
}
},
closable: false
if (userSelectedPoolCount < maxCount && label === 'Validator') {
openAlert({
title: t('Pay attention!'),
content: t('You are recommended to choose {{maxCount}} validators to optimize your earnings. Do you wish to continue with {{userSelectedPoolCount}} validator{{x}}?', { replace: { maxCount, userSelectedPoolCount, x: userSelectedPoolCount === 1 ? '' : 's' } }),
okButton: {
text: t('Continue'),
onClick: () => {
closeAlert();
resolve();
}
},
cancelButton: {
text: t('Go back'),
onClick: () => {
// eslint-disable-next-line prefer-promise-reject-errors
reject();
closeAlert();
}
},
closable: false
});
} else {
resolve();
}
});
};

return;
}
const checkStakingWarningModal = (): Promise<void> => {
return new Promise((resolve, reject) => {
if (chainStakingBoth) {
const chainInfo = chainStakingBoth && chainInfoMap[chainStakingBoth];

const symbol = (!!chainInfo && chainInfo?.substrateInfo?.symbol) || '';
const originChain = (!!chainInfo && chainInfo?.name) || '';

openAlert({
type: NotificationType.WARNING,
content:
(<>
<div className={'earning-alert-content'}>
{t(`You're currently staking ${symbol} via direct nomination. Due to ${originChain}'s upcoming changes, continuing to stake via nomination pool will lead to pool-staked funds being frozen (e.g., can't unstake, claim rewards)`)}
</div>
</>),
title: t('Continue staking?'),
okButton: {
text: t('Continue'),
onClick: () => {
closeAlert();
resolve();
}
},
cancelButton: {
text: t('Cancel'),
onClick: () => {
closeAlert();
// eslint-disable-next-line prefer-promise-reject-errors
reject();
}
}
});
} else {
resolve();
}
});
};

const runSequentialChecks = async () => {
try {
await checkStakingWarningModal();
dungnguyen-art marked this conversation as resolved.
Show resolved Hide resolved
await checkValidatorConfirmationModal();
await submitData(currentStep);
} catch (error) {
setSubmitLoading(false);
} finally {
setSubmitLoading(false);
}
};

setTimeout(() => {
submitData(currentStep)
.catch(onError)
.finally(() => {
setSubmitLoading(false);
});
runSequentialChecks().catch((error) => {
console.error('Error occurred during sequential checks:', error);
});
}, 300);
}, [chainValue, closeAlert, currentStep, onError, onSuccess, openAlert, poolInfo, poolTargetValue, poolTargets, processState.feeStructure, processState.steps, t]);
}, [chainInfoMap, chainStakingBoth, chainValue, closeAlert, currentStep, onError, onSuccess, openAlert, poolInfo, poolTargetValue, poolTargets, processState.feeStructure, processState.steps, t]);

const renderMetaInfo = useCallback(() => {
if (!poolInfo || !inputAsset) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,13 @@ const Component: React.FC<Props> = (props: Props) => {
modalId,
okButton,
title,
onCancel,
closable,
type = NotificationType.INFO } = props;

const { inactiveModal } = useContext(ModalContext);

const onCancel = useCallback(() => {
const onDefaultCancel = useCallback(() => {
inactiveModal(modalId);
}, [inactiveModal, modalId]);

Expand Down Expand Up @@ -92,7 +93,7 @@ const Component: React.FC<Props> = (props: Props) => {
</>
}
id={modalId}
onCancel={onCancel}
onCancel={closable === false ? undefined : (onCancel || onDefaultCancel)}
title={title}
>
<div className='__modal-content'>
Expand Down
2 changes: 1 addition & 1 deletion packages/extension-web-ui/src/constants/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const CONFIRM_TERM_SEED_PHRASE = 'seed-phrase.term-and-condition';

export const DAPPS_FAVORITE = 'dapps.favorite';
export const APP_INSTRUCTION_DATA = 'static.instruction-data';

export const EARNING_WARNING_ANNOUNCEMENT = 'announcement.earning-position';
export const CREATE_RETURN = 'account.create-return';

export const CROWDLOAN_UNLOCK_TIME = 'event.crowdloan-unlock-time';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2019-2022 @polkadot/extension-ui authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { APP_POPUP_MODAL } from '@subwallet/extension-web-ui/constants';
import { APP_POPUP_MODAL, EARNING_WARNING_ANNOUNCEMENT } from '@subwallet/extension-web-ui/constants';
import { toggleCampaignPopup } from '@subwallet/extension-web-ui/messaging/campaigns';
import { RootState } from '@subwallet/extension-web-ui/stores';
import { ModalContext } from '@subwallet/react-ui';
Expand Down Expand Up @@ -36,13 +36,14 @@ export const AppPopupModalContextProvider = ({ children }: AppPopupModalContextP
const [appPopupModal, setAppPopupModal] = useState<AppPopupModalInfo>({});
const { activeModal, inactiveModal } = useContext(ModalContext);
const { isPopupVisible } = useSelector((state: RootState) => state.campaign);

const storageEarningPosition = window.localStorage.getItem(EARNING_WARNING_ANNOUNCEMENT);
// TODO: This is a hotfix solution; a better solution must be found.
const openAppPopupModal = useCallback((data: AppPopupModalInfo) => {
if (isPopupVisible) {
if (isPopupVisible && ((!storageEarningPosition || storageEarningPosition.includes('confirmed')))) {
setAppPopupModal(data);
activeModal(APP_POPUP_MODAL);
}
}, [activeModal, isPopupVisible]);
}, [activeModal, isPopupVisible, storageEarningPosition]);

const hideAppPopupModal = useCallback(() => {
toggleCampaignPopup({ value: false }).then(() => {
Expand Down
Loading
Loading