Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions src/constants/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type ConfirmPendingDepositDialogProps = {
usdcBalance: number;
};
export type DepositAddressDialogProps = {};
export type InjectiveDepositDialogProps = {};
export type DisconnectWalletDialogProps = {};
export type DisplaySettingsDialogProps = {};
export type EmailSignInStatusDialogProps = {};
Expand Down Expand Up @@ -153,6 +154,7 @@ export const DialogTypes = unionize(
FillDetails: ofType<FillDetailsDialogProps>(),
GlobalCommand: ofType<GlobalCommandDialogProps>(),
Help: ofType<HelpDialogProps>(),
InjectiveDeposit: ofType<InjectiveDepositDialogProps>(),
ManageAccount: ofType<ManageAccountDialogProps>(),
MnemonicExport: ofType<MnemonicExportDialogProps>(),
MobileDownload: ofType<MobileDownloadDialogProps>(),
Expand Down
3 changes: 3 additions & 0 deletions src/constants/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export enum NotificationType {
Order = 'Order',
CosmosWalletLifecycle = 'CosmosWalletLifecycle', // lifecycle events for cosmos wallets
DepositAddressEvents = 'DepositAddressEvents', // lifecycle events for deposit notifications
InjectiveDeposit = 'InjectiveDeposit', // USDC waiting on Injective to be sent to dYdX
}

export enum NotificationCategoryPreferences {
Expand Down Expand Up @@ -57,6 +58,7 @@ export const NotificationTypeCategory: {
[NotificationType.Custom]: NotificationCategoryPreferences.MustSee,
[NotificationType.CosmosWalletLifecycle]: NotificationCategoryPreferences.MustSee,
[NotificationType.DepositAddressEvents]: NotificationCategoryPreferences.MustSee,
[NotificationType.InjectiveDeposit]: NotificationCategoryPreferences.MustSee,
};

export const SingleSessionNotificationTypes = [
Expand All @@ -65,6 +67,7 @@ export const SingleSessionNotificationTypes = [
NotificationType.OrderStatus,
NotificationType.Custom,
NotificationType.CosmosWalletLifecycle,
NotificationType.InjectiveDeposit,
];

export type NotificationId = string | number;
Expand Down
4 changes: 2 additions & 2 deletions src/constants/transfers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { timeUnits } from './time';

export const TIME_UNTIL_IDLE_WITHDRAW_IS_CONSIDERED_EXPIRED = 10 * timeUnits.minute;

// TEMP: Deposits are paused while multi-tx Injective routes are fixed. Flip to false to re-enable.
export const IS_DEPOSIT_UNDER_MAINTENANCE: boolean = true;
// TODO(inj-gas-sponsorship): enable once the endpoint is deployed.
export const IS_GAS_SPONSORSHIP_ENABLED: boolean = true;
38 changes: 38 additions & 0 deletions src/hooks/transfers/useInjectiveBalances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useQuery } from '@tanstack/react-query';
import { formatUnits } from 'viem';

import { timeUnits } from '@/constants/time';
import { USDC_DECIMALS } from '@/constants/tokens';

import { useAccounts } from '@/hooks/useAccounts';
import { useEndpointsConfig } from '@/hooks/useEndpointsConfig';

import { getInjectiveBalances } from '@/lib/injectiveTx';

export const MIN_INJECTIVE_USDC_TO_DEPOSIT = BigInt(1_000_000);

const REFETCH_INTERVAL = 30 * timeUnits.second;

export function useInjectiveBalances() {
const { injectiveAddress } = useAccounts();
const { injectiveValidator } = useEndpointsConfig();

const query = useQuery({
queryKey: ['injectiveBalances', injectiveAddress, injectiveValidator],
enabled: Boolean(injectiveAddress && injectiveValidator),
queryFn: () => getInjectiveBalances(injectiveValidator, injectiveAddress!),
refetchInterval: REFETCH_INTERVAL,
refetchOnWindowFocus: false,
});

const usdc = query.data?.usdc;

return {
...query,
injectiveAddress,
usdc,
usdcAmount: usdc != null ? formatUnits(usdc, USDC_DECIMALS) : undefined,
inj: query.data?.inj,
hasPendingInjectiveDeposit: usdc != null && usdc >= MIN_INJECTIVE_USDC_TO_DEPOSIT,
};
}
56 changes: 51 additions & 5 deletions src/hooks/useNotificationTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,12 @@ import {
getIndexerOrderSideStringKey,
getIndexerOrderTypeStringKey,
} from '@/lib/enumToStringKeyHelpers';
import { BIG_NUMBERS, MaybeBigNumber, MustNumber } from '@/lib/numbers';
import { BIG_NUMBERS, MaybeBigNumber, MustBigNumber, MustNumber } from '@/lib/numbers';
import { getAverageFillPrice } from '@/lib/orders';
import { isPresent, orEmptyObj, orEmptyRecord } from '@/lib/typeUtils';

import { DEC_2025_COMPETITION_DETAILS } from './rewards/util';
import { useInjectiveBalances } from './transfers/useInjectiveBalances';
import { useAccounts } from './useAccounts';
import { useAffiliateMetadata } from './useAffiliatesInfo';
import { useApiState } from './useApiState';
Expand Down Expand Up @@ -352,11 +353,9 @@ export const notificationTypes: NotificationTypeConfig[] = [
key: isSuccess ? STRING_KEYS.DEPOSIT : STRING_KEYS.DEPOSIT_IN_PROGRESS,
});

// TODO: localize
body = isSuccess
? stringGetter({
key: STRING_KEYS.DEPOSIT_AVAILABLE,
params: { AMOUNT_USD: finalAmount },
})
? `Your deposit of ${finalAmount} has arrived on Injective. Complete your deposit to start trading.`
: stringGetter({
key: STRING_KEYS.DEPOSIT_PENDING,
params: { AMOUNT_USD: finalAmount },
Expand Down Expand Up @@ -1362,6 +1361,53 @@ export const notificationTypes: NotificationTypeConfig[] = [
};
},
},
{
type: NotificationType.InjectiveDeposit,
useTrigger: ({ trigger, hideNotification }) => {
const dispatch = useAppDispatch();
const { usdcAmount, hasPendingInjectiveDeposit } = useInjectiveBalances();

useEffect(() => {
if (hasPendingInjectiveDeposit && usdcAmount != null) {
// TODO: localize
trigger({
id: NotificationType.InjectiveDeposit,
updateKey: [usdcAmount],
displayData: {
icon: <Icon iconName={IconName.Deposit} />,
title: 'Complete your deposit',
body: `${MustBigNumber(usdcAmount).toFixed(USD_DECIMALS)} USDC is waiting on Injective. Send it to dYdX to start trading.`,
toastSensitivity: 'background',
groupKey: NotificationType.InjectiveDeposit,
toastDuration: Infinity,
renderActionSlot: () => (
<Link
isAccent
onClick={(e) => {
e.preventDefault();
dispatch(openDialog(DialogTypes.InjectiveDeposit()));
}}
>
Complete deposit →
</Link>
),
},
});
} else {
hideNotification({
type: NotificationType.InjectiveDeposit,
id: NotificationType.InjectiveDeposit,
});
}
}, [dispatch, hasPendingInjectiveDeposit, hideNotification, trigger, usdcAmount]);
},
useNotificationAction: () => {
const dispatch = useAppDispatch();
return () => {
dispatch(openDialog(DialogTypes.InjectiveDeposit()));
};
},
},
];

const $Icon = tw.img`h-1.5 w-1.5`;
Expand Down
16 changes: 3 additions & 13 deletions src/hooks/useUpdateTransfers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,7 @@ export function useUpdateTransfers() {
dispatch(
updateDeposit({
dydxAddress,
deposit: {
...transfer,
explorerLink: txInfo.explorerLink,
},
deposit: { txHash, chainId, explorerLink: txInfo.explorerLink },
})
);
},
Expand All @@ -83,11 +80,7 @@ export function useUpdateTransfers() {
dispatch(
updateDeposit({
dydxAddress,
deposit: {
...transfer,
finalAmountUsd: finalAmount,
status,
},
deposit: { txHash, chainId, finalAmountUsd: finalAmount, status },
})
);

Expand Down Expand Up @@ -158,10 +151,7 @@ export function useUpdateTransfers() {
dispatch(
updateWithdraw({
dydxAddress,
withdraw: {
...transfer,
transactions: subTransactions,
},
withdraw: { id: transfer.id, transactions: subTransactions },
})
);
},
Expand Down
2 changes: 2 additions & 0 deletions src/layout/DialogManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import { TradingKeysDialog } from '@/views/dialogs/TradingKeysDialog';
import { TransferDialog } from '@/views/dialogs/TransferDialog';
import { DepositAddressDialog } from '@/views/dialogs/TransferDialogs/DepositAddressDialog';
import { DepositDialog2 } from '@/views/dialogs/TransferDialogs/DepositDialog2/DepositDialog2';
import { InjectiveDepositDialog } from '@/views/dialogs/TransferDialogs/InjectiveDepositDialog';
import { TransferStatusDialog } from '@/views/dialogs/TransferDialogs/TransferStatusDialog';
import { WithdrawDialog2 } from '@/views/dialogs/TransferDialogs/WithdrawDialog2/WithdrawDialog2';
import { TriggersDialog } from '@/views/dialogs/TriggersDialog';
Expand Down Expand Up @@ -116,6 +117,7 @@ export const DialogManager = React.memo(() => {
FillDetails: (args) => <FillDetailsDialog {...args} {...modalProps} />,
GlobalCommand: (args) => <GlobalCommandDialog {...args} {...modalProps} />,
Help: (args) => <HelpDialog {...args} {...modalProps} />,
InjectiveDeposit: (args) => <InjectiveDepositDialog {...args} {...modalProps} />,
ExternalNavKeplr: (args) => <ExternalNavKeplrDialog {...args} {...modalProps} />,
ManageAccount: (args) => <ManageAccountDialog {...args} {...modalProps} />,
MnemonicExport: (args) => <MnemonicExportDialog {...args} {...modalProps} />,
Expand Down
108 changes: 108 additions & 0 deletions src/lib/gasSponsorship.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { timeUnits } from '@/constants/time';

import { isSimpleFetchError, simpleFetch } from './simpleFetch';
import { removeTrailingSlash } from './stringifyHelpers';
import { sleep } from './timeUtils';

export enum GasSponsorshipStatus {
PENDING = 'PENDING',
CONFIRMED = 'CONFIRMED',
}

export enum GasSponsorshipErrorCode {
DISABLED = 'GAS_SPONSORSHIP_DISABLED',
INVALID_ADDRESS = 'GAS_SPONSORSHIP_INVALID_ADDRESS',
INSUFFICIENT_USDC_BALANCE = 'GAS_SPONSORSHIP_INSUFFICIENT_USDC_BALANCE',
ALREADY_HAS_GAS = 'GAS_SPONSORSHIP_ALREADY_HAS_GAS',
COOLDOWN = 'GAS_SPONSORSHIP_COOLDOWN',
BUDGET_EXHAUSTED = 'GAS_SPONSORSHIP_BUDGET_EXHAUSTED',
BASE_FEE_TOO_HIGH = 'GAS_SPONSORSHIP_BASE_FEE_TOO_HIGH',
DEPOSITS_CLOSED = 'GAS_SPONSORSHIP_DEPOSITS_CLOSED',
SPONSOR_UNDERFUNDED = 'GAS_SPONSORSHIP_SPONSOR_UNDERFUNDED',
BUSY = 'GAS_SPONSORSHIP_BUSY',
CHAIN_UNAVAILABLE = 'GAS_SPONSORSHIP_CHAIN_UNAVAILABLE',
GRANT_FAILED = 'GAS_SPONSORSHIP_GRANT_FAILED',
}

export type GasSponsorshipGrant = {
chainId: string;
// The address to set as the fee granter of the sponsored transaction
granter: string;
grantee: string;
feeDenom: string;
// What the grantee may still spend on fees, in the smallest unit of feeDenom
spendLimit: string;
expiresAt: string;
allowedMessages: string[];
status: GasSponsorshipStatus;
transactionHash?: string;
// A transaction whose fee is at most gasLimit * gasPrice fits within the allowance
gasLimit: string;
gasPrice: string;
};

export class GasSponsorshipError extends Error {
constructor(
message: string,
public code?: GasSponsorshipErrorCode
) {
super(message);
this.name = 'GasSponsorshipError';
}
}

// The endpoint already waits for the grant to confirm before answering PENDING, and is rate
// limited to 5 requests a minute, so a few spaced-out attempts are enough
const MAX_REQUEST_ATTEMPTS = 4;
const PENDING_RETRY_DELAY = 5 * timeUnits.second;

async function postGasSponsorship(
indexerUrl: string,
body: { address: string; injectiveAddress: string }
): Promise<GasSponsorshipGrant> {
try {
return await simpleFetch<GasSponsorshipGrant>(
`${removeTrailingSlash(indexerUrl)}/v4/gasSponsorship`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
);
} catch (error) {
if (!isSimpleFetchError(error)) throw error;
const errorBody = await error.response.json().catch(() => undefined);
const firstError = errorBody?.errors?.[0];
throw new GasSponsorshipError(firstError?.msg ?? error.message, firstError?.code);
}
}

/**
* Requests a fee allowance for `injectiveAddress` and resolves once it can be used.
*
* @throws GasSponsorshipError if the address is refused or the allowance is still not confirmed
* after a few attempts.
*/
export async function requestGasSponsorship({
indexerUrl,
dydxAddress,
injectiveAddress,
}: {
indexerUrl: string;
dydxAddress: string;
injectiveAddress: string;
}): Promise<GasSponsorshipGrant> {
for (let attempt = 1; attempt <= MAX_REQUEST_ATTEMPTS; attempt += 1) {
// eslint-disable-next-line no-await-in-loop
const grant = await postGasSponsorship(indexerUrl, {
address: dydxAddress,
injectiveAddress,
});
if (grant.status === GasSponsorshipStatus.CONFIRMED) return grant;

// eslint-disable-next-line no-await-in-loop
if (attempt < MAX_REQUEST_ATTEMPTS) await sleep(PENDING_RETRY_DELAY);
}

throw new GasSponsorshipError('Gas sponsorship is taking longer than expected. Please retry.');
}
Loading
Loading