diff --git a/src/constants/dialogs.ts b/src/constants/dialogs.ts index 56a6c238e8..16c4020212 100644 --- a/src/constants/dialogs.ts +++ b/src/constants/dialogs.ts @@ -31,6 +31,7 @@ export type ConfirmPendingDepositDialogProps = { usdcBalance: number; }; export type DepositAddressDialogProps = {}; +export type InjectiveDepositDialogProps = {}; export type DisconnectWalletDialogProps = {}; export type DisplaySettingsDialogProps = {}; export type EmailSignInStatusDialogProps = {}; @@ -153,6 +154,7 @@ export const DialogTypes = unionize( FillDetails: ofType(), GlobalCommand: ofType(), Help: ofType(), + InjectiveDeposit: ofType(), ManageAccount: ofType(), MnemonicExport: ofType(), MobileDownload: ofType(), diff --git a/src/constants/notifications.ts b/src/constants/notifications.ts index f179a0065b..597a627ca1 100644 --- a/src/constants/notifications.ts +++ b/src/constants/notifications.ts @@ -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 { @@ -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 = [ @@ -65,6 +67,7 @@ export const SingleSessionNotificationTypes = [ NotificationType.OrderStatus, NotificationType.Custom, NotificationType.CosmosWalletLifecycle, + NotificationType.InjectiveDeposit, ]; export type NotificationId = string | number; diff --git a/src/constants/transfers.ts b/src/constants/transfers.ts index 9e183b13fd..0de54edb46 100644 --- a/src/constants/transfers.ts +++ b/src/constants/transfers.ts @@ -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; diff --git a/src/hooks/transfers/useInjectiveBalances.ts b/src/hooks/transfers/useInjectiveBalances.ts new file mode 100644 index 0000000000..958d360024 --- /dev/null +++ b/src/hooks/transfers/useInjectiveBalances.ts @@ -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, + }; +} diff --git a/src/hooks/useNotificationTypes.tsx b/src/hooks/useNotificationTypes.tsx index daad02fe67..582d0ed288 100644 --- a/src/hooks/useNotificationTypes.tsx +++ b/src/hooks/useNotificationTypes.tsx @@ -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'; @@ -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 }, @@ -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: , + 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: () => ( + { + e.preventDefault(); + dispatch(openDialog(DialogTypes.InjectiveDeposit())); + }} + > + Complete deposit → + + ), + }, + }); + } 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`; diff --git a/src/hooks/useUpdateTransfers.tsx b/src/hooks/useUpdateTransfers.tsx index 597dbabc39..ed6c91baf8 100644 --- a/src/hooks/useUpdateTransfers.tsx +++ b/src/hooks/useUpdateTransfers.tsx @@ -63,10 +63,7 @@ export function useUpdateTransfers() { dispatch( updateDeposit({ dydxAddress, - deposit: { - ...transfer, - explorerLink: txInfo.explorerLink, - }, + deposit: { txHash, chainId, explorerLink: txInfo.explorerLink }, }) ); }, @@ -83,11 +80,7 @@ export function useUpdateTransfers() { dispatch( updateDeposit({ dydxAddress, - deposit: { - ...transfer, - finalAmountUsd: finalAmount, - status, - }, + deposit: { txHash, chainId, finalAmountUsd: finalAmount, status }, }) ); @@ -158,10 +151,7 @@ export function useUpdateTransfers() { dispatch( updateWithdraw({ dydxAddress, - withdraw: { - ...transfer, - transactions: subTransactions, - }, + withdraw: { id: transfer.id, transactions: subTransactions }, }) ); }, diff --git a/src/layout/DialogManager.tsx b/src/layout/DialogManager.tsx index 88ea191d69..57cd71ecd0 100644 --- a/src/layout/DialogManager.tsx +++ b/src/layout/DialogManager.tsx @@ -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'; @@ -116,6 +117,7 @@ export const DialogManager = React.memo(() => { FillDetails: (args) => , GlobalCommand: (args) => , Help: (args) => , + InjectiveDeposit: (args) => , ExternalNavKeplr: (args) => , ManageAccount: (args) => , MnemonicExport: (args) => , diff --git a/src/lib/gasSponsorship.ts b/src/lib/gasSponsorship.ts new file mode 100644 index 0000000000..afe472c948 --- /dev/null +++ b/src/lib/gasSponsorship.ts @@ -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 { + try { + return await simpleFetch( + `${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 { + 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.'); +} diff --git a/src/lib/injectiveTx.ts b/src/lib/injectiveTx.ts new file mode 100644 index 0000000000..7846dd9278 --- /dev/null +++ b/src/lib/injectiveTx.ts @@ -0,0 +1,247 @@ +import { fromBase64 } from '@cosmjs/encoding'; +import type { OfflineSigner } from '@cosmjs/proto-signing'; +import type { Account } from '@cosmjs/stargate'; + +import { INJECTIVE_USDC_DENOM } from '@/constants/tokens'; + +/** + * Injective accounts use ethsecp256k1 keys, which cosmjs's signing client does not support: it + * cannot parse Injective's EthAccount type and encodes the wrong public key type. The few + * Injective-specific protobuf pieces are therefore encoded here by hand, and everything else is + * left to cosmjs. + */ + +const ETH_ACCOUNT_TYPE_URL = '/injective.types.v1beta1.EthAccount'; +const ETH_SECP256K1_PUBKEY_TYPE_URL = '/injective.crypto.v1beta1.ethsecp256k1.PubKey'; +const MSG_TRANSFER_TYPE_URL = '/ibc.applications.transfer.v1.MsgTransfer'; +const TX_BODY_TYPE_URL = '/cosmos.tx.v1beta1.TxBody'; + +export const INJECTIVE_FEE_DENOM = 'inj'; +// IBC channel on Injective (injective-1) that leads to the dYdX chain +export const INJECTIVE_TO_DYDX_IBC_CHANNEL = 'channel-258'; +export const INJECTIVE_IBC_TRANSFER_GAS_LIMIT = BigInt(450_000); +// Price per unit of gas, in inj. Comfortably above the minimum base fee (1.6e8). +export const INJECTIVE_GAS_PRICE = BigInt(1_000_000_000); +// The timeout is set when the transfer is signed, so it only needs to cover IBC relaying +const IBC_TRANSFER_TIMEOUT_MS = 10 * 60 * 1000; + +export const getInjectiveIbcTransferFee = ( + gasLimit = INJECTIVE_IBC_TRANSFER_GAS_LIMIT, + gasPrice = INJECTIVE_GAS_PRICE +) => gasLimit * gasPrice; + +// ------ Minimal protobuf encoding/decoding ------ // + +function encodeVarint(value: number): number[] { + const bytes: number[] = []; + let remaining = value; + while (remaining >= 0x80) { + bytes.push((remaining % 0x80) + 0x80); + remaining = Math.floor(remaining / 0x80); + } + bytes.push(remaining); + return bytes; +} + +function encodeBytesField(fieldNumber: number, bytes: Uint8Array): Uint8Array { + return new Uint8Array([ + ...encodeVarint(fieldNumber * 8 + 2), + ...encodeVarint(bytes.length), + ...bytes, + ]); +} + +function readVarint(bytes: Uint8Array, offset: number): [value: number, nextOffset: number] { + let value = 0; + let multiplier = 1; + let position = offset; + for (;;) { + const byte = bytes[position]; + if (byte === undefined) throw new Error('invalid protobuf: truncated varint'); + value += (byte % 0x80) * multiplier; + position += 1; + if (byte < 0x80) return [value, position]; + multiplier *= 0x80; + } +} + +/** + * Reads the top-level varint and length-delimited fields of a protobuf message. + */ +function readFields(bytes: Uint8Array) { + const varints: Record = {}; + const lengthDelimited: Record = {}; + let offset = 0; + while (offset < bytes.length) { + const [tag, afterTag] = readVarint(bytes, offset); + const fieldNumber = Math.floor(tag / 8); + const wireType = tag % 8; + if (wireType === 0) { + const [value, next] = readVarint(bytes, afterTag); + varints[fieldNumber] = value; + offset = next; + } else if (wireType === 2) { + const [length, start] = readVarint(bytes, afterTag); + lengthDelimited[fieldNumber] = bytes.slice(start, start + length); + offset = start + length; + } else { + throw new Error(`invalid protobuf: unsupported wire type ${wireType}`); + } + } + return { varints, lengthDelimited }; +} + +// ------ Accounts ------ // + +/** + * Parses an Injective EthAccount, which wraps a BaseAccount (address = 1, pub_key = 2, + * account_number = 3, sequence = 4). The public key is left out: cosmjs cannot decode the + * ethsecp256k1 type, and signing only needs the account number and sequence. + */ +function parseEthAccount(value: Uint8Array): Account { + const baseAccount = readFields(value).lengthDelimited[1]; + if (!baseAccount) throw new Error('invalid EthAccount: missing base account'); + + const { varints, lengthDelimited } = readFields(baseAccount); + return { + address: new TextDecoder().decode(lengthDelimited[1]), + pubkey: null, + accountNumber: varints[3] ?? 0, + sequence: varints[4] ?? 0, + }; +} + +async function connectInjectiveClient(rpcUrl: string) { + const [{ StargateClient, accountFromAny }, { Comet38Client }] = await Promise.all([ + import('@cosmjs/stargate'), + import('@cosmjs/tendermint-rpc'), + ]); + // Injective runs CometBFT 1.x. cosmjs only recognizes versions up to 0.38 and falls back to its + // 0.34 client for anything else, which then fails to decode transaction results. 1.x is + // compatible with the 0.38 client, so it is used directly. + const cometClient = await Comet38Client.connect(rpcUrl); + return StargateClient.create(cometClient, { + accountParser: (any) => + any.typeUrl === ETH_ACCOUNT_TYPE_URL ? parseEthAccount(any.value) : accountFromAny(any), + }); +} + +// ------ Transactions ------ // + +/** + * Sends USDC from an Injective account to the dYdX chain over IBC, signing with the account's + * ethsecp256k1 key. When `feeGranter` is set, the fee is paid from that account's fee allowance. + */ +export async function sendInjectiveUsdcToDydx({ + rpcUrl, + signer, + injectiveAddress, + dydxAddress, + amount, + feeGranter, + gasLimit = INJECTIVE_IBC_TRANSFER_GAS_LIMIT, + gasPrice = INJECTIVE_GAS_PRICE, +}: { + rpcUrl: string; + signer: OfflineSigner; + injectiveAddress: string; + dydxAddress: string; + amount: string; + feeGranter?: string; + gasLimit?: bigint; + gasPrice?: bigint; +}): Promise { + if (!('signDirect' in signer)) { + throw new Error('Injective wallet does not support direct signing'); + } + + const [{ defaultRegistryTypes }, { makeAuthInfoBytes, makeSignDoc, Registry }] = + await Promise.all([import('@cosmjs/stargate'), import('@cosmjs/proto-signing')]); + + const client = await connectInjectiveClient(rpcUrl); + try { + const [chainId, { accountNumber, sequence }, accounts] = await Promise.all([ + client.getChainId(), + client.getSequence(injectiveAddress), + signer.getAccounts(), + ]); + const account = accounts.find((a) => a.address === injectiveAddress); + if (!account) throw new Error(`Injective wallet has no account ${injectiveAddress}`); + + const bodyBytes = new Registry(defaultRegistryTypes).encode({ + typeUrl: TX_BODY_TYPE_URL, + value: { + messages: [ + { + typeUrl: MSG_TRANSFER_TYPE_URL, + value: { + sourcePort: 'transfer', + sourceChannel: INJECTIVE_TO_DYDX_IBC_CHANNEL, + token: { denom: INJECTIVE_USDC_DENOM, amount }, + sender: injectiveAddress, + receiver: dydxAddress, + timeoutHeight: { revisionNumber: BigInt(0), revisionHeight: BigInt(0) }, + timeoutTimestamp: BigInt(Date.now() + IBC_TRANSFER_TIMEOUT_MS) * BigInt(1_000_000), + memo: '', + }, + }, + ], + memo: '', + }, + }); + + const authInfoBytes = makeAuthInfoBytes( + [ + { + pubkey: { + typeUrl: ETH_SECP256K1_PUBKEY_TYPE_URL, + value: encodeBytesField(1, account.pubkey), + }, + sequence, + }, + ], + [ + { + denom: INJECTIVE_FEE_DENOM, + amount: getInjectiveIbcTransferFee(gasLimit, gasPrice).toString(), + }, + ], + Number(gasLimit), + feeGranter, + undefined + ); + + const { signed, signature } = await signer.signDirect( + injectiveAddress, + makeSignDoc(bodyBytes, authInfoBytes, chainId, accountNumber) + ); + + // TxRaw: body_bytes = 1, auth_info_bytes = 2, signatures = 3 + const txRaw = new Uint8Array([ + ...encodeBytesField(1, signed.bodyBytes), + ...encodeBytesField(2, signed.authInfoBytes), + ...encodeBytesField(3, fromBase64(signature.signature)), + ]); + + const result = await client.broadcastTx(txRaw); + if (result.code !== 0) { + throw new Error(`Injective transfer failed (code ${result.code}): ${result.rawLog ?? ''}`); + } + return result.transactionHash; + } finally { + client.disconnect(); + } +} + +export async function getInjectiveBalances(rpcUrl: string, injectiveAddress: string) { + const client = await connectInjectiveClient(rpcUrl); + try { + const [usdc, inj] = await Promise.all([ + client.getBalance(injectiveAddress, INJECTIVE_USDC_DENOM), + client.getBalance(injectiveAddress, INJECTIVE_FEE_DENOM), + ]); + return { usdc: BigInt(usdc.amount), inj: BigInt(inj.amount) }; + } finally { + client.disconnect(); + } +} diff --git a/src/state/transfers.ts b/src/state/transfers.ts index c701255cd7..3ffa2d5e32 100644 --- a/src/state/transfers.ts +++ b/src/state/transfers.ts @@ -16,6 +16,7 @@ export type Deposit = { finalAmountUsd?: string; isInstantDeposit: boolean; explorerLink?: string; + skipExplorerLink?: string; updatedAt?: number; }; @@ -38,6 +39,7 @@ export type Withdraw = { status: 'pending' | 'success' | 'error'; updatedAt?: number; txHash: string; + skipExplorerLink?: string; }; export type Transfer = Deposit | Withdraw; diff --git a/src/views/dialogs/TransferDialogs/DepositAddressDialog.tsx b/src/views/dialogs/TransferDialogs/DepositAddressDialog.tsx index efb1300001..2beb981a4c 100644 --- a/src/views/dialogs/TransferDialogs/DepositAddressDialog.tsx +++ b/src/views/dialogs/TransferDialogs/DepositAddressDialog.tsx @@ -11,7 +11,6 @@ import { ComplianceStates } from '@/constants/compliance'; import { DepositDialog2Props, DialogProps } from '@/constants/dialogs'; import { STRING_KEYS } from '@/constants/localization'; import { SOLANA_MAINNET_ID } from '@/constants/solana'; -import { IS_DEPOSIT_UNDER_MAINTENANCE } from '@/constants/transfers'; import { useAccounts } from '@/hooks/useAccounts'; import { useBreakpoints } from '@/hooks/useBreakpoints'; @@ -56,7 +55,6 @@ export const DepositAddressDialog = ({ setIsOpen }: DialogProps { - if (IS_DEPOSIT_UNDER_MAINTENANCE) return; // Optimistic Deposit Initiated for tracking purposes track(AnalyticsEvents.TurnkeyDepositInitiated({})); }, []); @@ -187,12 +185,7 @@ export const DepositAddressDialog = ({ setIsOpen }: DialogProps - Deposits are temporarily under maintenance. Please check back soon. - - ) : ( + const perpetualsContent = (
{ - if (IS_DEPOSIT_UNDER_MAINTENANCE) return 'Under Maintenance'; if (!hasSufficientBalance) return `Insufficient ${getTokenSymbol(token.denom)}`; if (hasInput && !isDepositingMoreThanMin) { return ( @@ -408,11 +405,6 @@ export const DepositForm = ({ onTokenClick={onTokenSelect} error={error} /> - {IS_DEPOSIT_UNDER_MAINTENANCE && ( - - Deposits are temporarily under maintenance. Please check back soon. - - )} {isMissingGas && ( {stringGetter({ @@ -435,9 +427,7 @@ export const DepositForm = ({ onClick={onDepositClick} state={{ isDisabled: depositDisabled, - isLoading: - !IS_DEPOSIT_UNDER_MAINTENANCE && - (isFetching || (!depositDisabled && !steps?.length) || awaitingWalletAction), + isLoading: isFetching || (!depositDisabled && !steps?.length) || awaitingWalletAction, }} action={ButtonAction.Primary} type={ButtonType.Submit} diff --git a/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositStatus.tsx b/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositStatus.tsx index e0bdc0cd48..7c1f4036e8 100644 --- a/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositStatus.tsx +++ b/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositStatus.tsx @@ -1,7 +1,4 @@ -import { useMemo } from 'react'; - import { ButtonAction } from '@/constants/buttons'; -import { NEAR_INSTANT_DEPOSIT_CHAINS } from '@/constants/chains'; import { STRING_KEYS } from '@/constants/localization'; import { useAppSelectorWithArgs } from '@/hooks/useParameterizedSelector'; @@ -32,22 +29,15 @@ export const DepositStatus = ({ txHash, chainId, onClose }: DepositStatusProps) const depositSuccess = deposit?.status === 'success'; - const statusDescription = useMemo(() => { - if (depositSuccess) { - return stringGetter({ key: STRING_KEYS.YOUR_FUNDS_AVAILABLE_FOR_TRADING }); - } - if ( - Boolean(deposit?.isInstantDeposit) || - NEAR_INSTANT_DEPOSIT_CHAINS.includes(deposit?.chainId ?? '') - ) { - return stringGetter({ key: STRING_KEYS.YOUR_FUNDS_AVAILABLE_SOON }); - } - - return stringGetter({ key: STRING_KEYS.YOU_MAY_CLOSE_WINDOW }); - }, [deposit, depositSuccess, stringGetter]); + // TODO: localize + const statusDescription = depositSuccess + ? 'Your funds have arrived on Injective. Complete your deposit from the notification or your account menu.' + : 'Your funds will arrive on Injective. Once they do, you will get a notification to complete your deposit, which you can also do from your account menu. You may close this window.'; if (!deposit) return null; + const explorerLink = deposit.skipExplorerLink ?? deposit.explorerLink; + return (
@@ -61,7 +51,8 @@ export const DepositStatus = ({ txHash, chainId, onClose }: DepositStatusProps)
{!depositSuccess ? stringGetter({ key: STRING_KEYS.DEPOSIT_IN_PROGRESS }) - : stringGetter({ key: STRING_KEYS.DEPOSIT_COMPLETED })} + : // TODO: localize + 'Funds arrived on Injective'}
{statusDescription}
@@ -86,12 +77,12 @@ export const DepositStatus = ({ txHash, chainId, onClose }: DepositStatusProps) : stringGetter({ key: STRING_KEYS.CLOSE })} - {deposit.explorerLink && ( + {explorerLink && (
{stringGetter({ key: STRING_KEYS.VIEW_TRANSACTIONS_SHORT })} - + {truncateAddress(deposit.txHash, '')}
diff --git a/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositSteps.tsx b/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositSteps.tsx index 4f406a0dd6..7c2d5da555 100644 --- a/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositSteps.tsx +++ b/src/views/dialogs/TransferDialogs/DepositDialog2/DepositForm/DepositSteps.tsx @@ -12,10 +12,8 @@ import ConnectingLine from '@/icons/connecting-line.svg'; import { Icon, IconName } from '@/components/Icon'; import { LoadingSpinner } from '@/components/Loading/LoadingSpinner'; -import { DepositStep } from '../depositHooks'; - type DepositStepsProps = { - steps: DepositStep[]; + steps: Array<{ type: string }>; currentStep: number; currentStepError?: string; onRetry: () => void; @@ -26,7 +24,7 @@ type StyleProps = { }; const STEP_TYPE_TO_INFO: { - [type: string]: { titleKey: string; icon: ReactNode }; + [type: string]: { titleKey?: string; title?: string; icon: ReactNode }; } = { network: { titleKey: STRING_KEYS.SWITCH_NETWORKS, @@ -40,6 +38,14 @@ const STEP_TYPE_TO_INFO: { titleKey: STRING_KEYS.CONFIRM_DEPOSIT, icon: , }, + 'ibc-transfer': { + title: 'Send USDC to dYdX', + icon: , + }, + subaccount: { + title: 'Deposit to trading account', + icon: , + }, }; const SHAKE_DURATION = 1000; @@ -95,7 +101,7 @@ export const DepositSteps = ({ tw="transition-all duration-300" css={[i === currentStep ? tw`opacity-100` : tw`opacity-50`]} > - {stringGetter({ key: stepInfo.titleKey })} + {stepInfo.titleKey ? stringGetter({ key: stepInfo.titleKey }) : stepInfo.title}
{error &&
{error}
}
diff --git a/src/views/dialogs/TransferDialogs/DepositDialog2/depositHooks.ts b/src/views/dialogs/TransferDialogs/DepositDialog2/depositHooks.ts index c9285d7f5d..244eabe54b 100644 --- a/src/views/dialogs/TransferDialogs/DepositDialog2/depositHooks.ts +++ b/src/views/dialogs/TransferDialogs/DepositDialog2/depositHooks.ts @@ -19,18 +19,25 @@ import { SkipClient, useSkipClient } from '@/hooks/transfers/skipClient'; import { useAccounts } from '@/hooks/useAccounts'; import { useStringGetter } from '@/hooks/useStringGetter'; -import { Deposit } from '@/state/transfers'; +import { useAppDispatch } from '@/state/appTypes'; +import { Deposit, updateDeposit } from '@/state/transfers'; import { SourceAccount } from '@/state/wallet'; import { track } from '@/lib/analytics/analytics'; import { sleep } from '@/lib/timeUtils'; import { CHAIN_ID_TO_INFO, EvmDepositChainId, VIEM_PUBLIC_CLIENTS } from '@/lib/viem'; -import { getUserAddressesForRoute, parseError, userAddressHelper } from '../utils'; +import { + getSkipExplorerLink, + getUserAddressesForRoute, + parseError, + userAddressHelper, +} from '../utils'; import { isInstantDeposit } from './queries'; -// Number of seconds for the IBC transfer timeout (Skip default is 5 minutes) -const DEPOSIT_TIMEOUT_SECONDS = (10 * 60).toString(); +// Number of seconds for the IBC transfer timeout (Skip default is 24 hours) +const DEPOSIT_TIMEOUT_SECONDS = (24 * 60 * 60).toString(); +const SLIPPAGE_TOLERANCE_PERCENT = '1'; type StepResult = | { success: true; errorMessage: undefined } @@ -63,6 +70,7 @@ export function useDepositSteps({ onDeposit: (deposit: Deposit) => void; }) { const stringGetter = useStringGetter(); + const dispatch = useAppDispatch(); const walletChainId = useChainId(); const { skipClient } = useSkipClient(); @@ -152,6 +160,7 @@ export function useDepositSteps({ amountOut: depositRoute.estimatedAmountOut ?? '0', addressList: userAddressHelper(depositRoute, userAddresses), timeoutSeconds: DEPOSIT_TIMEOUT_SECONDS, + slippageTolerancePercent: SLIPPAGE_TOLERANCE_PERCENT, }); let approvalMaybeNeeded: (Erc20Approval & { chainId: string }) | undefined; @@ -226,6 +235,9 @@ export function useDepositSteps({ depositRoute, }); + let firstBroadcast: { txHash: string; chainId: string } | undefined; + let skipExplorerLink: string | undefined; + try { await updatedSkipClient.executeRoute({ getCosmosSigner, @@ -233,10 +245,22 @@ export function useDepositSteps({ userAddresses, // Bypass because we manually handle allowance checks above bypassApprovalCheck: true, - // Extend the IBC transfer timeout from the default 5 minutes to 10 minutes timeoutSeconds: DEPOSIT_TIMEOUT_SECONDS, // TODO(deposit2.0): add custom slippage tolerance here + onRouteStatusUpdated: (routeDetails) => { + skipExplorerLink = getSkipExplorerLink(routeDetails); + if (!firstBroadcast || !dydxAddress) return; + + dispatch( + updateDeposit({ + dydxAddress, + deposit: { ...firstBroadcast, skipExplorerLink }, + }) + ); + }, onTransactionBroadcast: async ({ txHash, chainId }) => { + firstBroadcast ??= { txHash, chainId }; + logBonsaiInfo('depositHooks', 'deposit tx submitted', { depositId, txHash, @@ -262,7 +286,7 @@ export function useDepositSteps({ userAddresses, }) ); - onDeposit({ ...baseDeposit, token: depositToken }); + onDeposit({ ...baseDeposit, token: depositToken, skipExplorerLink }); }, }); return { success: true }; diff --git a/src/views/dialogs/TransferDialogs/InjectiveDepositDialog.tsx b/src/views/dialogs/TransferDialogs/InjectiveDepositDialog.tsx new file mode 100644 index 0000000000..007f2cd5c3 --- /dev/null +++ b/src/views/dialogs/TransferDialogs/InjectiveDepositDialog.tsx @@ -0,0 +1,275 @@ +import { useMemo, useRef, useState } from 'react'; + +import { logBonsaiError } from '@/bonsai/logs'; +import { formatUnits } from 'viem'; + +import { AMOUNT_RESERVED_FOR_GAS_USDC } from '@/constants/account'; +import { AlertType } from '@/constants/alerts'; +import { ButtonAction } from '@/constants/buttons'; +import { DialogProps, InjectiveDepositDialogProps } from '@/constants/dialogs'; +import { getInjectiveChainId } from '@/constants/graz'; +import { STRING_KEYS } from '@/constants/localization'; +import { timeUnits } from '@/constants/time'; +import { IS_GAS_SPONSORSHIP_ENABLED } from '@/constants/transfers'; + +import { useSkipClient } from '@/hooks/transfers/skipClient'; +import { useInjectiveBalances } from '@/hooks/transfers/useInjectiveBalances'; +import { useAccountBalance } from '@/hooks/useAccountBalance'; +import { useAccounts } from '@/hooks/useAccounts'; +import { useEndpointsConfig } from '@/hooks/useEndpointsConfig'; +import { useStringGetter } from '@/hooks/useStringGetter'; +import { useSubaccount } from '@/hooks/useSubaccount'; +import { useTokenConfigs } from '@/hooks/useTokenConfigs'; + +import { AlertMessage } from '@/components/AlertMessage'; +import { Button } from '@/components/Button'; +import { Dialog } from '@/components/Dialog'; +import { Output, OutputType } from '@/components/Output'; + +import { getSelectedDydxChainId } from '@/state/appSelectors'; +import { useAppSelector } from '@/state/appTypes'; +import { selectIsKeplrConnected } from '@/state/walletSelectors'; + +import { GasSponsorshipGrant, requestGasSponsorship } from '@/lib/gasSponsorship'; +import { getInjectiveIbcTransferFee, sendInjectiveUsdcToDydx } from '@/lib/injectiveTx'; +import { MustBigNumber } from '@/lib/numbers'; +import { log } from '@/lib/telemetry'; +import { sleep } from '@/lib/timeUtils'; + +import { DepositSteps } from './DepositDialog2/DepositForm/DepositSteps'; + +type StepResult = { success: true } | { success: false; errorMessage: string }; + +type InjectiveDepositStep = { + type: 'ibc-transfer' | 'subaccount'; + executeStep: () => Promise; +}; + +const INJ_DECIMALS = 18; +const AUTO_DEPOSIT_POLL_INTERVAL = 3 * timeUnits.second; +const AUTO_DEPOSIT_TIMEOUT = 2 * timeUnits.minute; + +/** + * Completes a deposit whose USDC has arrived on Injective: sends it to the dYdX chain over IBC, + * then into the trading account. + */ +export const InjectiveDepositDialog = ({ setIsOpen }: DialogProps) => { + const stringGetter = useStringGetter(); + const { skipClient } = useSkipClient(); + const { indexer, injectiveValidator } = useEndpointsConfig(); + const { dydxAddress, localInjectiveWallet } = useAccounts(); + const { deposit } = useSubaccount(); + const isKeplr = useAppSelector(selectIsKeplrConnected); + + const selectedDydxChainId = useAppSelector(getSelectedDydxChainId); + const { usdcDenom } = useTokenConfigs(); + const { refetchQuery: refetchDydxUsdcBalance } = useAccountBalance({ + chainId: selectedDydxChainId, + isCosmosChain: true, + addressOrDenom: usdcDenom, + }); + + const { + injectiveAddress, + usdc, + usdcAmount, + hasPendingInjectiveDeposit, + isLoading: isLoadingBalances, + refetch: refetchInjectiveBalances, + } = useInjectiveBalances(); + + const [depositAmount, setDepositAmount] = useState(); + const [currentStep, setCurrentStep] = useState(-1); + const [currentStepError, setCurrentStepError] = useState(); + const [isRunning, setIsRunning] = useState(false); + + const ibcTxHashRef = useRef(); + + const steps: InjectiveDepositStep[] = useMemo( + () => [ + { + type: 'ibc-transfer', + executeStep: async () => { + try { + if (!ibcTxHashRef.current) { + if (!injectiveAddress || !dydxAddress || !localInjectiveWallet?.offlineSigner) { + return { success: false, errorMessage: 'Wallet not connected' }; + } + + const { data: balances } = await refetchInjectiveBalances(); + if (!balances || balances.usdc === BigInt(0)) { + return { success: false, errorMessage: 'No USDC found on Injective' }; + } + + let sponsorship: GasSponsorshipGrant | undefined; + const fee = getInjectiveIbcTransferFee(); + if (balances.inj < fee) { + const notEnoughInjMessage = `Not enough INJ to pay for gas. Send at least ${formatUnits(fee, INJ_DECIMALS)} INJ to ${injectiveAddress}.`; + if (!IS_GAS_SPONSORSHIP_ENABLED) { + return { success: false, errorMessage: notEnoughInjMessage }; + } + + try { + sponsorship = await requestGasSponsorship({ + indexerUrl: indexer.api, + dydxAddress, + injectiveAddress, + }); + } catch (error) { + logBonsaiError('InjectiveDepositDialog/gasSponsorship', error); + return { success: false, errorMessage: notEnoughInjMessage }; + } + } + + ibcTxHashRef.current = await sendInjectiveUsdcToDydx({ + rpcUrl: injectiveValidator, + signer: localInjectiveWallet.offlineSigner, + injectiveAddress, + dydxAddress, + amount: balances.usdc.toString(), + // Fees are paid from the sponsor's allowance, priced to fit within it + feeGranter: sponsorship?.granter, + gasLimit: sponsorship && BigInt(sponsorship.gasLimit), + gasPrice: sponsorship && BigInt(sponsorship.gasPrice), + }); + } + + await skipClient.waitForTransaction({ + chainId: getInjectiveChainId(), + txHash: ibcTxHashRef.current, + }); + + refetchInjectiveBalances(); + return { success: true }; + } catch (error) { + log('InjectiveDepositDialog/ibcTransfer', error); + return { success: false, errorMessage: error.message }; + } + }, + }, + { + type: 'subaccount', + executeStep: async () => { + try { + const deadline = Date.now() + AUTO_DEPOSIT_TIMEOUT; + while (Date.now() < deadline) { + // eslint-disable-next-line no-await-in-loop + const { data } = await refetchDydxUsdcBalance(); + const amountToDeposit = MustBigNumber(data as string | undefined).minus( + AMOUNT_RESERVED_FOR_GAS_USDC + ); + if (amountToDeposit.lt(0.01)) return { success: true }; + + if (isKeplr) { + // eslint-disable-next-line no-await-in-loop + await deposit(amountToDeposit.toNumber()); + return { success: true }; + } + + // eslint-disable-next-line no-await-in-loop + await sleep(AUTO_DEPOSIT_POLL_INTERVAL); + } + + return { + success: false, + errorMessage: + 'Your funds are on dYdX and will be added to your trading account shortly.', + }; + } catch (error) { + log('InjectiveDepositDialog/depositToSubaccount', error); + return { success: false, errorMessage: error.message }; + } + }, + }, + ], + [ + deposit, + dydxAddress, + indexer.api, + injectiveAddress, + injectiveValidator, + isKeplr, + localInjectiveWallet, + refetchDydxUsdcBalance, + refetchInjectiveBalances, + skipClient, + ] + ); + + const runSteps = async (fromStep: number) => { + setIsRunning(true); + setCurrentStepError(undefined); + for (let i = fromStep; i < steps.length; i += 1) { + setCurrentStep(i); + // eslint-disable-next-line no-await-in-loop + const result = await steps[i]!.executeStep(); + if (!result.success) { + setCurrentStepError(result.errorMessage); + setIsRunning(false); + return; + } + } + setCurrentStep(steps.length); + setIsRunning(false); + }; + + const onStart = () => { + setDepositAmount(usdcAmount); + runSteps(0); + }; + + const hasStarted = currentStep >= 0; + const isComplete = currentStep === steps.length; + const displayAmount = depositAmount ?? usdcAmount; + + return ( + +
+ {!hasStarted && !isLoadingBalances && !hasPendingInjectiveDeposit ? ( + No USDC is waiting on Injective. + ) : ( + <> +
+ {isComplete + ? 'Your deposit is complete.' + : 'Your USDC has arrived on Injective. Send it to dYdX to finish your deposit.'} +
+ +
+
{stringGetter({ key: STRING_KEYS.AMOUNT })}
+ +
+ + runSteps(currentStep)} + /> + + )} + + {isComplete || (!hasStarted && !hasPendingInjectiveDeposit && !isLoadingBalances) ? ( + + ) : ( + !hasStarted && ( + + ) + )} +
+
+ ); +}; diff --git a/src/views/dialogs/TransferDialogs/WithdrawDialog2/WithdrawStatus.tsx b/src/views/dialogs/TransferDialogs/WithdrawDialog2/WithdrawStatus.tsx index c2e114e556..71c13d2de1 100644 --- a/src/views/dialogs/TransferDialogs/WithdrawDialog2/WithdrawStatus.tsx +++ b/src/views/dialogs/TransferDialogs/WithdrawDialog2/WithdrawStatus.tsx @@ -59,19 +59,25 @@ export const WithdrawStatus = ({ id = '', onClose }: WithdrawStatusProps) => { /> ); - const withdrawalExplorerLinks = withdraw - ? withdraw.transactions - .map((t) => { - if (!t.explorerLink) return null; + const withdrawalExplorerLinks = withdraw?.skipExplorerLink + ? [ + + {truncateAddress(withdraw.txHash, '')} + , + ] + : withdraw + ? withdraw.transactions + .map((t) => { + if (!t.explorerLink) return null; - return ( - - {truncateAddress(t.txHash, '')} - - ); - }) - .filter(isTruthy) - : []; + return ( + + {truncateAddress(t.txHash, '')} + + ); + }) + .filter(isTruthy) + : []; return (
diff --git a/src/views/dialogs/TransferDialogs/WithdrawDialog2/withdrawHooks.ts b/src/views/dialogs/TransferDialogs/WithdrawDialog2/withdrawHooks.ts index b333eb2eb0..c40577405d 100644 --- a/src/views/dialogs/TransferDialogs/WithdrawDialog2/withdrawHooks.ts +++ b/src/views/dialogs/TransferDialogs/WithdrawDialog2/withdrawHooks.ts @@ -20,15 +20,16 @@ import { useWithdrawalInfo } from '@/hooks/useWithdrawalInfo'; import { formatNumberOutput, OutputType } from '@/components/Output'; -import { useAppSelector } from '@/state/appTypes'; +import { useAppDispatch, useAppSelector } from '@/state/appTypes'; import { getSelectedLocale } from '@/state/localizationSelectors'; -import { Withdraw, WithdrawSubtransaction } from '@/state/transfers'; +import { updateWithdraw, Withdraw, WithdrawSubtransaction } from '@/state/transfers'; import { track } from '@/lib/analytics/analytics'; import { AttemptBigNumber } from '@/lib/numbers'; import { DYDX_DEPOSIT_CHAIN } from '../consts'; import { + getSkipExplorerLink, getUserAddressesForRoute, isInstantTransfer, isValidWithdrawalAddress, @@ -49,6 +50,7 @@ export function useWithdrawStep({ onWithdrawSigned: (withdrawId: string) => void; }) { const stringGetter = useStringGetter(); + const dispatch = useAppDispatch(); const { skipClient } = useSkipClient(); const { dydxAddress, @@ -123,6 +125,9 @@ export function useWithdrawStep({ } const withdrawId = `withdraw-${crypto.randomUUID()}`; + // The explorer link can update before the withdraw is created on the first broadcast + let isWithdrawCreated = false; + let skipExplorerLink: string | undefined; logBonsaiInfo('withdrawHooks', 'withdraw initiated', { withdrawId, @@ -152,6 +157,11 @@ export function useWithdrawStep({ onTransactionSigned: async () => { onWithdrawSigned(withdrawId); }, + onRouteStatusUpdated: (routeDetails) => { + skipExplorerLink = getSkipExplorerLink(routeDetails); + if (!isWithdrawCreated) return; + dispatch(updateWithdraw({ dydxAddress, withdraw: { id: withdrawId, skipExplorerLink } })); + }, onTransactionBroadcast: async ({ txHash, chainId }) => { // First Broadcast will always originate from v4 chain if (chainId === DYDX_DEPOSIT_CHAIN) { @@ -174,6 +184,7 @@ export function useWithdrawStep({ isInstantWithdraw: isInstantTransfer(withdrawRoute), transferAssetRelease: null, txHash, + skipExplorerLink, }; logBonsaiInfo('withdrawHooks', 'withdraw tx submitted', { withdrawId, @@ -183,6 +194,7 @@ export function useWithdrawStep({ }); track(AnalyticsEvents.WithdrawSubmitted(baseWithdraw)); onWithdraw(baseWithdraw); + isWithdrawCreated = true; } else { logBonsaiInfo('withdrawHooks', 'additional withdraw tx submitted', { withdrawId, diff --git a/src/views/dialogs/TransferDialogs/utils.ts b/src/views/dialogs/TransferDialogs/utils.ts index 4ad08ac195..251c259a47 100644 --- a/src/views/dialogs/TransferDialogs/utils.ts +++ b/src/views/dialogs/TransferDialogs/utils.ts @@ -1,4 +1,4 @@ -import { RouteResponse, UserAddress } from '@skip-go/client'; +import { RouteDetails, RouteResponse, UserAddress } from '@skip-go/client'; import { ChainMismatchError, isAddress, UserRejectedRequestError } from 'viem'; import { arbitrum, avalanche, base, mainnet, optimism, polygon } from 'viem/chains'; @@ -17,6 +17,25 @@ import { validateInjectiveAddress, } from '@/lib/addressUtils'; +const SKIP_EXPLORER_URL = 'https://explorer.skip.build/'; + +export function getSkipExplorerLink({ + route, + userAddresses, + transactionDetails, + status, +}: RouteDetails) { + const bytes = new TextEncoder().encode( + JSON.stringify({ route, userAddresses, transactionDetails, status }) + ); + let binary = ''; + bytes.forEach((byte) => { + binary += String.fromCharCode(byte); + }); + + return `${SKIP_EXPLORER_URL}?data=${encodeURIComponent(btoa(binary))}`; +} + // Because our deposit flow only supports ETH and USDC export function getTokenSymbol(denom: string) { diff --git a/src/views/menus/AccountMenu/AccountMenu.tsx b/src/views/menus/AccountMenu/AccountMenu.tsx index df00504a52..2ae9d07237 100644 --- a/src/views/menus/AccountMenu/AccountMenu.tsx +++ b/src/views/menus/AccountMenu/AccountMenu.tsx @@ -13,6 +13,7 @@ import { SMALL_USD_DECIMALS, USD_DECIMALS } from '@/constants/numbers'; import { StatsigFlags } from '@/constants/statsig'; import { ConnectorType, DydxChainAsset, wallets, WalletType } from '@/constants/wallets'; +import { useInjectiveBalances } from '@/hooks/transfers/useInjectiveBalances'; import { useAccountBalance } from '@/hooks/useAccountBalance'; import { useAccounts } from '@/hooks/useAccounts'; import { useBreakpoints } from '@/hooks/useBreakpoints'; @@ -65,6 +66,7 @@ export const AccountMenu = () => { const isTurnkey = useAppSelector(selectIsTurnkeyConnected); const { nativeTokenBalance, usdcBalance } = useAccountBalance(); + const { hasPendingInjectiveDeposit } = useInjectiveBalances(); const { usdcImage, usdcLabel, chainTokenImage, chainTokenLabel } = useTokenConfigs(); const theme = useAppSelector(getAppTheme); @@ -268,6 +270,19 @@ export const AccountMenu = () => { /> )} + {hasPendingInjectiveDeposit && ( + // TODO: localize + <$ConfirmPendingDeposit> + You have USDC on Injective +
waiting to be deposited + <$IconButton + action={ButtonAction.Base} + shape={ButtonShape.Square} + iconName={IconName.Send} + onClick={() => dispatch(openDialog(DialogTypes.InjectiveDeposit()))} + /> + + )}
) }