Skip to content

Commit

Permalink
chore: simplify logic for pending deposit notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryz0nd committed Aug 2, 2024
1 parent a9158f2 commit aa6d78a
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 82 deletions.
1 change: 1 addition & 0 deletions src/constants/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ export type TransferNotifcation = {
requestId?: string;
tracked?: boolean;
isDummy?: boolean;
isSubaccountDepositCompleted?: boolean;
};

export enum ReleaseUpdateNotificationIds {
Expand Down
52 changes: 13 additions & 39 deletions src/hooks/useNotificationTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import { openDialog } from '@/state/dialogs';
import { getAbacusNotifications } from '@/state/notificationsSelectors';
import { getMarketIds } from '@/state/perpetualsSelectors';

import { getNobleChainId } from '@/lib/squid';
import { SUPPORTED_COSMOS_CHAINS } from '@/lib/graz';
import { formatSeconds } from '@/lib/timeUtils';

import { useAccounts } from './useAccounts';
Expand Down Expand Up @@ -221,43 +221,17 @@ export const notificationTypes: NotificationTypeConfig[] = [
? TransferNotificationTypes.Withdrawal
: TransferNotificationTypes.Deposit);

const nobleChainId = getNobleChainId();
const isCosmosTransfer = [nobleChainId].includes(fromChainId ?? '');
if (isCosmosTransfer) {
const icon = <$AssetIcon symbol="USDC" />;
const isFinished = depositSubaccount?.txHash && !depositSubaccount?.needToDeposit;
const title = isFinished
? stringGetter({
key: STRING_KEYS.DEPOSIT,
})
: // TODO: Need to add Localization
'Confirm Pending Deposit';

trigger(
txHash,
{
icon,
title,
toastSensitivity: 'foreground',
renderCustomBody: ({ isToast, notification }) => (
<TransferStatusNotification
isToast={isToast}
slotIcon={icon}
slotTitle={title}
transfer={transfer}
type={transferType}
triggeredAt={transfer.triggeredAt}
notification={notification}
/>
),
groupKey: NotificationType.SquidTransfer,
},
[]
);
} else {
const isFinished =
(Boolean(status) && status?.squidTransactionStatus !== 'ongoing') || isExchange;
const icon = <Icon iconName={isFinished ? IconName.Transfer : IconName.Clock} />;
const isCosmosDeposit =
SUPPORTED_COSMOS_CHAINS.includes(fromChainId ?? '') &&
fromChainId !== selectedDydxChainId;

const isFinished =
(Boolean(status) && status?.squidTransactionStatus !== 'ongoing') || isExchange;
const icon = isCosmosDeposit ? (
<$AssetIcon symbol="USDC" />
) : (
<Icon iconName={isFinished ? IconName.Transfer : IconName.Clock} />
);

trigger(
id ?? txHash,
Expand All @@ -282,7 +256,7 @@ export const notificationTypes: NotificationTypeConfig[] = [
[isFinished]
);
}
}, [transferNotifications, stringGetter]);
}, [transferNotifications, stringGetter, selectedDydxChainId]);
},
useNotificationAction: () => {
return () => {};
Expand Down
5 changes: 3 additions & 2 deletions src/hooks/useSubaccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -305,12 +305,13 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall
if (isKeplr && usdcCoinBalance) {
if (showDepositDialog) {
const balanceAmount = parseFloat(usdcCoinBalance.amount);
const shouldDeposit = balanceAmount - AMOUNT_RESERVED_FOR_GAS_USDC > 0;
const usdcBalance = balanceAmount - AMOUNT_RESERVED_FOR_GAS_USDC;
const shouldDeposit = usdcBalance > 0 && usdcBalance.toFixed(2) !== '0.00';
if (shouldDeposit) {
dispatch(
openDialog(
DialogTypes.ConfirmPendingDeposit({
usdcBalance: balanceAmount - AMOUNT_RESERVED_FOR_GAS_USDC,
usdcBalance,
})
)
);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/squid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export const trackSkipTx = async ({
return response.json();
};

const MAX_TRACK_TX_ATTEMPTS = 5;
export const MAX_TRACK_TX_ATTEMPTS = 5;
const TRACK_TX_INTERVAL = 1000;

export const trackSkipTxWithTenacity = async ({
Expand Down
26 changes: 25 additions & 1 deletion src/views/dialogs/ConfirmPendingDepositDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { ConfirmPendingDepositDialogProps, DialogProps } from '@/constants/dialo
import { STRING_KEYS } from '@/constants/localization';

import { useAccountBalance } from '@/hooks/useAccountBalance';
import { useAccounts } from '@/hooks/useAccounts';
import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { useStringGetter } from '@/hooks/useStringGetter';
import { useSubaccount } from '@/hooks/useSubaccount';
import { useTokenConfigs } from '@/hooks/useTokenConfigs';
Expand All @@ -22,6 +24,7 @@ import { Output, OutputType } from '@/components/Output';
import { getSelectedDydxChainId } from '@/state/appSelectors';
import { useAppSelector } from '@/state/appTypes';

import { SUPPORTED_COSMOS_CHAINS } from '@/lib/graz';
import { log } from '@/lib/telemetry';

export const ConfirmPendingDepositDialog = ({
Expand All @@ -30,6 +33,9 @@ export const ConfirmPendingDepositDialog = ({
}: DialogProps<ConfirmPendingDepositDialogProps>) => {
const [isLoading, setIsLoading] = useState(false);
const selectedDydxChainId = useAppSelector(getSelectedDydxChainId);
const { dydxAddress } = useAccounts();

const { setAllTransferNotifications } = useLocalNotifications();
const stringGetter = useStringGetter();

const { deposit } = useSubaccount();
Expand All @@ -45,8 +51,26 @@ export const ConfirmPendingDepositDialog = ({
setIsLoading(true);
try {
const tx = await deposit(usdcBalance);
if (tx !== undefined) {
if (tx && dydxAddress) {
await refetchQuery();

setAllTransferNotifications((transferNotification) => {
return {
...transferNotification,
[dydxAddress]: transferNotification[dydxAddress].map((notification) => {
const isCosmosDeposit =
SUPPORTED_COSMOS_CHAINS.includes(notification.fromChainId ?? '') &&
notification.fromChainId !== selectedDydxChainId;
if (isCosmosDeposit) {
return {
...notification,
isSubaccountDepositCompleted: true,
};
}
return notification;
}),
};
});
setIsOpen(false);
}
} catch (err) {
Expand Down
55 changes: 33 additions & 22 deletions src/views/dialogs/CosmosDepositDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import { Description } from '@radix-ui/react-dialog';
import styled from 'styled-components';

import { AMOUNT_RESERVED_FOR_GAS_NOBLE } from '@/constants/account';
import { AnalyticsEvents } from '@/constants/analytics';
import { ButtonAction, ButtonType } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { TransferNotificationTypes } from '@/constants/notifications';

import { useAccounts } from '@/hooks/useAccounts';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import { useEndpointsConfig } from '@/hooks/useEndpointsConfig';
import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { useStringGetter } from '@/hooks/useStringGetter';
import { useSubaccount } from '@/hooks/useSubaccount';
Expand All @@ -23,8 +22,13 @@ import { GreenCheckCircle } from '@/components/GreenCheckCircle';
import { Icon, IconName } from '@/components/Icon';
import { LoadingSpinner } from '@/components/Loading/LoadingSpinner';

import { track } from '@/lib/analytics';
import { getNeutronChainId, getNobleChainId, getOsmosisChainId } from '@/lib/squid';
import {
getNeutronChainId,
getNobleChainId,
getOsmosisChainId,
MAX_TRACK_TX_ATTEMPTS,
trackSkipTxWithTenacity,
} from '@/lib/squid';

type ElementProps = {
setIsOpen: (open: boolean) => void;
Expand All @@ -37,11 +41,13 @@ export const CosmosDepositDialog = ({ setIsOpen, toAmount, txHash, fromChainId }
const stringGetter = useStringGetter();
const { isMobile } = useBreakpoints();
const { deposit } = useSubaccount();
const { setAllTransferNotifications } = useLocalNotifications();
const { dydxAddress } = useAccounts();
const { skip } = useEndpointsConfig();

const [txStatus, setTxStatus] = useState<'success' | 'error' | 'pending'>('pending');

const { setAllTransferNotifications } = useLocalNotifications();

const depositToSubaccount = useCallback(async () => {
try {
if (toAmount && dydxAddress && txHash) {
Expand All @@ -54,33 +60,33 @@ export const CosmosDepositDialog = ({ setIsOpen, toAmount, txHash, fromChainId }
if (tx !== undefined) {
const depositTxHash = Buffer.from(tx.hash).toString('hex');

// eslint-disable-next-line prefer-const
let attemptNumber = 1;
await trackSkipTxWithTenacity({
attemptNumber,
transactionHash: depositTxHash,
chainId: fromChainId,
baseUrl: skip,
});

if (attemptNumber === MAX_TRACK_TX_ATTEMPTS) {
throw new Error('Transaction failed');
}

setAllTransferNotifications((transferNotification) => {
return {
...transferNotification,
[dydxAddress]: transferNotification[dydxAddress].map((notification) => {
if (notification.txHash === txHash) {
return {
...notification,
depositSubaccount: {
txHash: depositTxHash,
needToDeposit: false,
},
isSubaccountDepositCompleted: true,
};
}
return notification;
}),
};
});
track(
AnalyticsEvents.TransferNotification({
triggeredAt: undefined,
timeSpent: undefined,
txHash,
toAmount,
type: TransferNotificationTypes.Deposit,
status: 'success',
})
);

setTxStatus('success');
} else {
Expand All @@ -90,16 +96,21 @@ export const CosmosDepositDialog = ({ setIsOpen, toAmount, txHash, fromChainId }
} catch (e) {
setTxStatus('error');
}
}, [dydxAddress, setAllTransferNotifications, toAmount, txHash]);
}, [dydxAddress, fromChainId, skip, toAmount, txHash]);

const [isExecuted, setIsExecuted] = useState(false);

useEffect(() => {
if (txStatus === 'pending') {
if (!isExecuted) {
depositToSubaccount();
}
}, [depositToSubaccount, txStatus]);
setIsExecuted(true);
}, [depositToSubaccount, isExecuted]);

const onRetry = () => {
setTxStatus('pending');

depositToSubaccount();
};

const onClose = () => {
Expand Down
3 changes: 0 additions & 3 deletions src/views/forms/AccountManagementForms/DepositForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -400,9 +400,6 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
triggeredAt: Date.now(),
isCctp,
type: TransferNotificationTypes.Deposit,
depositSubaccount: {
needToDeposit: true,
},
});
abacusStateManager.clearTransferInputValues();
setFromAmount('');
Expand Down
3 changes: 2 additions & 1 deletion src/views/menus/AccountMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ export const AccountMenu = () => {

const showConfirmPendingDeposit =
walletType === WalletType.Keplr &&
MustBigNumber(usdcBalance).toNumber() > AMOUNT_RESERVED_FOR_GAS_USDC;
MustBigNumber(usdcBalance).toNumber() > AMOUNT_RESERVED_FOR_GAS_USDC &&
MustBigNumber(usdcBalance).toFixed(2) !== '0.00';

let walletIcon;
if (onboardingState === OnboardingState.WalletConnected) {
Expand Down
31 changes: 18 additions & 13 deletions src/views/notifications/TransferStatusNotification/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ import { Notification, NotificationProps } from '@/components/Notification';
import { Output, OutputType } from '@/components/Output';
import { WithReceipt } from '@/components/WithReceipt';

import { useAppDispatch } from '@/state/appTypes';
import { getSelectedDydxChainId } from '@/state/appSelectors';
import { useAppDispatch, useAppSelector } from '@/state/appTypes';
import { openDialog } from '@/state/dialogs';

import { getNobleChainId } from '@/lib/squid';
import { SUPPORTED_COSMOS_CHAINS } from '@/lib/graz';
import { formatSeconds } from '@/lib/timeUtils';

import { TransferStatusSteps } from './TransferStatusSteps';
Expand All @@ -51,7 +52,10 @@ export const TransferStatusNotification = ({
const [open, setOpen] = useState<boolean>(false);
const [secondsLeft, setSecondsLeft] = useState<number>(0);
const dispatch = useAppDispatch();
const { status, toAmount, isExchange, fromChainId, txHash, depositSubaccount } = transfer;
const selectedDydxChainId = useAppSelector(getSelectedDydxChainId);

const { status, toAmount, isExchange, fromChainId, txHash, isSubaccountDepositCompleted } =
transfer;

// @ts-ignore status.errors is not in the type definition but can be returned
const error = status?.errors?.length ? status?.errors[0] : status?.error;
Expand All @@ -75,11 +79,12 @@ export const TransferStatusNotification = ({

useInterval({ callback: updateSecondsLeft });

const nobleChainId = getNobleChainId();
const isCosmosTransfer = [nobleChainId].includes(fromChainId ?? '');
const isComplete = isCosmosTransfer
? depositSubaccount?.txHash && depositSubaccount?.needToDeposit === false
const isCosmosDeposit =
SUPPORTED_COSMOS_CHAINS.includes(fromChainId ?? '') && fromChainId !== selectedDydxChainId;
const isComplete = isCosmosDeposit
? isSubaccountDepositCompleted
: status?.squidTransactionStatus === 'success' || isExchange;

const inProgressStatusString =
type === TransferNotificationTypes.Deposit
? secondsLeft > 0
Expand Down Expand Up @@ -108,16 +113,16 @@ export const TransferStatusNotification = ({
key: 'status',
label: 'Status',
// TODO: Need to add localization
value: isComplete ? 'Complete' : 'Awaiting Confirmation',
value: isComplete ? 'Confirmed' : 'Awaiting Confirmation',
},
];

const customContent =
!status && !isExchange && !isCosmosTransfer ? (
!status && !isExchange && !isCosmosDeposit ? (
<LoadingDots size={3} />
) : (
<$BridgingStatus>
{isCosmosTransfer ? (
{isCosmosDeposit ? (
<>
<$Details items={detailItems} />
{!isToast && !isComplete && (
Expand Down Expand Up @@ -171,13 +176,13 @@ export const TransferStatusNotification = ({
)}
</>
)}
{!isToast && !isComplete && !hasError && !isCosmosTransfer && (
{!isToast && !isComplete && !hasError && !isCosmosDeposit && (
<$TransferStatusSteps status={status} type={type} />
)}
</$BridgingStatus>
);

const transferIcon = isCosmosTransfer ? slotIcon : isToast && slotIcon;
const transferIcon = isCosmosDeposit ? slotIcon : isToast && slotIcon;

const transferNotif = (
<Notification
Expand Down Expand Up @@ -207,7 +212,7 @@ export const TransferStatusNotification = ({
}
slotAction={
isToast &&
!isCosmosTransfer &&
!isCosmosDeposit &&
status && (
<$Trigger
isOpen={open}
Expand Down

0 comments on commit aa6d78a

Please sign in to comment.