@0xsquid/react-hooks 8.0.1-tanstack-v5-beta.0 → 8.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/core/types/event.d.ts +17 -8
  2. package/dist/hooks/navigation/useKeyboardNavigation.d.ts +1 -4
  3. package/dist/hooks/onramp/useFiatToCrypto.d.ts +28 -6
  4. package/dist/hooks/squid/useSquid.d.ts +2 -2
  5. package/dist/hooks/swap/useDepositAddress.d.ts +2 -2
  6. package/dist/hooks/tokens/useAllConnectedWalletBalances.d.ts +11 -5
  7. package/dist/hooks/tokens/useAllTokensWithBalanceForChainType.d.ts +1 -1
  8. package/dist/hooks/tokens/useBalance.d.ts +1 -1
  9. package/dist/hooks/tokens/useMultipleTokenPrices.d.ts +2 -2
  10. package/dist/hooks/tokens/useNativeBalance.d.ts +2 -2
  11. package/dist/hooks/tokens/useTokenHistoricalData.d.ts +4 -4
  12. package/dist/hooks/transaction/send/useEstimateSendTransactionGas.d.ts +1 -1
  13. package/dist/hooks/transaction/send/useSendTransactionGas.d.ts +1 -1
  14. package/dist/hooks/transaction/useAllTransactionsStatus.d.ts +29 -3
  15. package/dist/hooks/transaction/useApproval.d.ts +2 -2
  16. package/dist/hooks/transaction/useExecuteTransaction.d.ts +2 -2
  17. package/dist/hooks/transaction/useGetRoute.d.ts +7 -7
  18. package/dist/hooks/transaction/useSwapTransactionStatus.d.ts +1 -1
  19. package/dist/hooks/wallet/useAddToken.d.ts +1 -1
  20. package/dist/hooks/wallet/useEns.d.ts +2 -2
  21. package/dist/hooks/wallet/useMultiChainWallet.d.ts +1 -1
  22. package/dist/hooks/wallet/useWallet.d.ts +1 -1
  23. package/dist/hooks/xrpl/useXrplTrustLine.d.ts +5 -5
  24. package/dist/{index-BA79s7uI.js → index-BKmIOD3t.js} +988 -1015
  25. package/dist/index-BKmIOD3t.js.map +1 -0
  26. package/dist/{index-CS74WzWX.js → index-BjIFR_GS.js} +989 -1013
  27. package/dist/index-BjIFR_GS.js.map +1 -0
  28. package/dist/index.esm.js +1 -1
  29. package/dist/index.js +4 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/{secretService-D3MB_TMv.js → secretService-C2TxPa-m.js} +2 -2
  32. package/dist/{secretService-D3MB_TMv.js.map → secretService-C2TxPa-m.js.map} +1 -1
  33. package/dist/{secretService-U8WiVPay.js → secretService-DT8cWLsm.js} +2 -2
  34. package/dist/{secretService-U8WiVPay.js.map → secretService-DT8cWLsm.js.map} +1 -1
  35. package/dist/services/internal/eventService.d.ts +1 -0
  36. package/dist/{stellarService.client-BUdrOP04.js → stellarService.client-DH1Yp2nE.js} +2 -2
  37. package/dist/{stellarService.client-BUdrOP04.js.map → stellarService.client-DH1Yp2nE.js.map} +1 -1
  38. package/dist/{stellarService.client-Dp4tvmUo.js → stellarService.client-deOQBP3h.js} +2 -2
  39. package/dist/{stellarService.client-Dp4tvmUo.js.map → stellarService.client-deOQBP3h.js.map} +1 -1
  40. package/package.json +12 -12
  41. package/dist/index-BA79s7uI.js.map +0 -1
  42. package/dist/index-CS74WzWX.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { ChainType, ActionType, SquidDataType, BridgeType, BridgeProvider, FeeType } from '@0xsquid/squid-types';
2
2
  import { zeroAddress as zeroAddress$1, parseUnits, formatUnits, isAddress, SwitchChainError, UserRejectedRequestError, erc20Abi, defineChain } from 'viem';
3
3
  import React, { useMemo, useCallback, useState, useEffect, createContext, useContext, useRef } from 'react';
4
- import { useQuery, useMutation, useQueryClient, useQueries, QueryClient, QueryClientProvider } from '@tanstack/react-query';
4
+ import { useQuery, useMutation, useQueries, useQueryClient, QueryClient, QueryClientProvider } from '@tanstack/react-query';
5
5
  import { fromBech32 } from '@cosmjs/encoding';
6
6
  import * as bitcoin from 'bitcoinjs-lib';
7
7
  import { address } from 'bitcoinjs-lib';
@@ -3981,6 +3981,20 @@ class WidgetEvents extends EventTarget {
3981
3981
  constructor() {
3982
3982
  super();
3983
3983
  }
3984
+ getRouteEventPayload = (route, txHash) => {
3985
+ const { fromAddress, toAddress, fromChain, toChain, fromToken, toToken, fromAmount, } = route.params;
3986
+ return {
3987
+ fromAddress,
3988
+ toAddress,
3989
+ fromChain,
3990
+ toChain,
3991
+ fromToken,
3992
+ toToken,
3993
+ fromAmount,
3994
+ quoteId: route.quoteId,
3995
+ txHash,
3996
+ };
3997
+ };
3984
3998
  // Singleton, because we need to access this service outside the widget
3985
3999
  static getInstance() {
3986
4000
  if (!WidgetEvents.instance) {
@@ -4031,7 +4045,7 @@ class WidgetEvents extends EventTarget {
4031
4045
  * @param route
4032
4046
  */
4033
4047
  dispatchSwapExecuteCall(route, txHash) {
4034
- this.dispatch("swap", { route, txHash });
4048
+ this.dispatch("swap", this.getRouteEventPayload(route, txHash));
4035
4049
  }
4036
4050
  /**
4037
4051
  * Dispatch event when user changes chain/token
@@ -4110,7 +4124,18 @@ class WidgetEvents extends EventTarget {
4110
4124
  * @param data Quote execution parameters
4111
4125
  */
4112
4126
  dispatchOnrampQuoteExecute(data) {
4113
- this.dispatch("onrampQuoteExecute", data);
4127
+ this.dispatch("onrampQuoteExecute", {
4128
+ tokenAddress: data.squidToken?.address,
4129
+ tokenChainId: data.squidToken?.chainId,
4130
+ amount: data.cryptoAmount,
4131
+ paymentMethod: data.paymentMethod,
4132
+ walletAddress: data.walletAddress,
4133
+ orderId: data.orderId,
4134
+ fiatCurrency: data.fiatCurrency,
4135
+ cryptoCurrencyID: data.cryptoCurrencyID,
4136
+ region: data.region,
4137
+ onrampProviderId: data.onrampProviderId,
4138
+ });
4114
4139
  }
4115
4140
  /**
4116
4141
  * Dispatch event when the search query has no results
@@ -26795,9 +26820,7 @@ const fetchHighestBalanceToken = (fetchCachedBalance, chainId) => {
26795
26820
  if (fetchCachedBalance) {
26796
26821
  const queryCache = fetchCachedBalance?.queryClient?.getQueryCache();
26797
26822
  // get cached balance from key
26798
- const cache = queryCache?.find({
26799
- queryKey: keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? ChainType.EVM : ChainType.COSMOS),
26800
- });
26823
+ const cache = queryCache?.find(keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? ChainType.EVM : ChainType.COSMOS));
26801
26824
  // Parse result to TokenWithBalance[]
26802
26825
  const cacheResult = cache?.state.data ?? [];
26803
26826
  if (cacheResult.length > 0) {
@@ -27453,7 +27476,7 @@ const filterViewableTokens = (tokens, config, direction) => {
27453
27476
  };
27454
27477
  const getSecretNetworkBalances = async (chainData, cosmosAddress, squidTokens, keplrTypeWallet) => {
27455
27478
  const squidSecretTokens = squidTokens.filter((t) => t.chainId === CHAIN_IDS.SECRET);
27456
- const { fetchAllSecretBalances } = await import('./secretService-D3MB_TMv.js');
27479
+ const { fetchAllSecretBalances } = await import('./secretService-C2TxPa-m.js');
27457
27480
  return fetchAllSecretBalances(chainData, cosmosAddress, squidSecretTokens, keplrTypeWallet);
27458
27481
  };
27459
27482
  function getTokenAssetsKey(token) {
@@ -29212,16 +29235,13 @@ const useSquid = () => {
29212
29235
  * Fetch squid info
29213
29236
  * Will refetch every minute
29214
29237
  */
29215
- const squidInfoQuery = useQuery({
29216
- queryKey: keys().squidInfo(),
29217
- queryFn: async () => {
29218
- if (squid) {
29219
- await squid?.init();
29220
- initializeSquidWithAssetsColors(squid, assetsColors);
29221
- return squid;
29222
- }
29223
- return null;
29238
+ const squidInfoQuery = useQuery(keys().squidInfo(), async () => {
29239
+ if (squid) {
29240
+ await squid?.init();
29241
+ initializeSquidWithAssetsColors(squid, assetsColors);
29242
+ return squid;
29224
29243
  }
29244
+ return null;
29225
29245
  });
29226
29246
  const tokens = useMemo(() => {
29227
29247
  if ((squidInfoQuery?.data?.tokens ?? []).length > 0) {
@@ -29337,11 +29357,47 @@ const FINAL_TRANSACTION_STATUSES = [
29337
29357
  "completed",
29338
29358
  "failed",
29339
29359
  ];
29360
+ /**
29361
+ * Configuration for transaction status tracking
29362
+ */
29363
+ const createTransactionStatusConfig = ({ transactionId, walletAddress, providerId, replaceTransactionStatus, }) => {
29364
+ return {
29365
+ queryKey: keys().fiatToCryptoStatus(transactionId),
29366
+ queryFn: () => new OnrampService().getTransactionStatus(transactionId, walletAddress, providerId),
29367
+ enabled: !!transactionId && !!walletAddress && !!providerId,
29368
+ retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
29369
+ retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
29370
+ refetchInterval: (data) => {
29371
+ if (data?.status && FINAL_TRANSACTION_STATUSES.includes(data.status)) {
29372
+ return false;
29373
+ }
29374
+ return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
29375
+ },
29376
+ onSuccess: (data) => {
29377
+ if (data) {
29378
+ replaceTransactionStatus({
29379
+ txType: HistoryTxType.BUY,
29380
+ orderId: transactionId,
29381
+ status: data.status,
29382
+ transactionHash: data.transactionHash,
29383
+ });
29384
+ }
29385
+ },
29386
+ onError: () => {
29387
+ replaceTransactionStatus({
29388
+ txType: HistoryTxType.BUY,
29389
+ orderId: transactionId,
29390
+ status: "failed",
29391
+ transactionHash: undefined,
29392
+ });
29393
+ },
29394
+ };
29395
+ };
29340
29396
  /**
29341
29397
  * Fetches quotes for fiat to crypto conversion with provider details.
29342
29398
  * Returns available rates, fees, and supported payment methods for the conversion.
29343
29399
  */
29344
- const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, }) => {
29400
+ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, onSuccess, }) => {
29345
29401
  const service = useMemo(() => new OnrampService(), []);
29346
29402
  const { data: config } = useGetOnRampConfig();
29347
29403
  return useQuery({
@@ -29377,6 +29433,7 @@ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, payme
29377
29433
  return quoteResponse;
29378
29434
  },
29379
29435
  enabled: enabled && !!fiatCurrency && !!cryptoCurrencyID && amount > 0,
29436
+ onSuccess,
29380
29437
  });
29381
29438
  };
29382
29439
  /**
@@ -29393,7 +29450,7 @@ const useGetOnRampConfig = () => {
29393
29450
  chains,
29394
29451
  tokens,
29395
29452
  }),
29396
- gcTime: 1000 * 60 * 60,
29453
+ cacheTime: 1000 * 60 * 60,
29397
29454
  staleTime: 1000 * 60 * 30, // 30 minutes
29398
29455
  });
29399
29456
  };
@@ -29451,11 +29508,49 @@ const useExecuteFiatQuote = () => {
29451
29508
  },
29452
29509
  });
29453
29510
  };
29511
+ /**
29512
+ * Tracks the status of a single fiat to crypto transaction.
29513
+ */
29514
+ const useFiatOnRampTxStatus = (transactionId, walletAddress, providerId) => {
29515
+ const replaceTransactionStatus = useHistoryStore((state) => state.replaceTransactionStatus);
29516
+ return useQuery({
29517
+ ...createTransactionStatusConfig({
29518
+ transactionId,
29519
+ walletAddress,
29520
+ providerId,
29521
+ replaceTransactionStatus,
29522
+ }),
29523
+ });
29524
+ };
29525
+ /**
29526
+ * Tracks all pending fiat transactions.
29527
+ */
29528
+ const useFiatTransactions = () => {
29529
+ const transactions = useHistoryStore((state) => state.transactions.filter((tx) => tx.txType === HistoryTxType.BUY));
29530
+ const replaceTransactionStatus = useHistoryStore((state) => state.replaceTransactionStatus);
29531
+ const pendingTransactions = useMemo(() => transactions?.filter((tx) => !FINAL_TRANSACTION_STATUSES.includes(tx.data.status)) ?? [], [transactions]);
29532
+ const queries = useQueries({
29533
+ queries: pendingTransactions.map((tx) => ({
29534
+ ...createTransactionStatusConfig({
29535
+ transactionId: tx.data.orderId,
29536
+ walletAddress: tx.data.toAddress,
29537
+ providerId: tx.data.providerId,
29538
+ replaceTransactionStatus,
29539
+ }),
29540
+ })),
29541
+ });
29542
+ return {
29543
+ transactions: transactions.map((tx) => tx.data),
29544
+ isLoading: queries.some((q) => q.isLoading),
29545
+ isError: queries.some((q) => q.isError),
29546
+ };
29547
+ };
29454
29548
  /**
29455
29549
  * Gets currency details including symbol and limits.
29456
29550
  * Example: USD → { symbol: "$", name: "US Dollar", ... }
29457
29551
  */
29458
29552
  const useCurrencyDetails = (currencyCode) => {
29553
+ const { data: config } = useGetOnRampConfig();
29459
29554
  return useMemo(() => {
29460
29555
  if (!currencyCode)
29461
29556
  return undefined;
@@ -29468,7 +29563,7 @@ const useCurrencyDetails = (currencyCode) => {
29468
29563
  };
29469
29564
  }
29470
29565
  return undefined;
29471
- }, [currencyCode]);
29566
+ }, [currencyCode, config?.supportedFiats]);
29472
29567
  };
29473
29568
  /**
29474
29569
  * Gets country details with flag URL and localized name.
@@ -29495,6 +29590,23 @@ const useAvailableQuotes = (quotes) => {
29495
29590
  return uniqueQuotes;
29496
29591
  }, [quotes]);
29497
29592
  };
29593
+ /**
29594
+ * Gets the recommended quote based on best rates or provider preferences.
29595
+ * Falls back to first available quote if no specific recommendation.
29596
+ */
29597
+ const useRecommendedQuote = (quotes, recommendedQuote) => {
29598
+ const availableQuotes = useAvailableQuotes(quotes);
29599
+ return useMemo(() => {
29600
+ if (!availableQuotes.length)
29601
+ return undefined;
29602
+ if (!recommendedQuote)
29603
+ return availableQuotes[0];
29604
+ // Try to find the recommended quote among available quotes
29605
+ const recommendedAvailableQuote = availableQuotes.find((quote) => quote.onrampProviderId === recommendedQuote.onrampProviderId);
29606
+ // If recommended quote is not available, return first available quote
29607
+ return recommendedAvailableQuote ?? availableQuotes[0];
29608
+ }, [availableQuotes, recommendedQuote]);
29609
+ };
29498
29610
  /**
29499
29611
  * Fetches the available payment methods for a given fiat and crypto currency pair.
29500
29612
  * The first item in the returned array is the most recommended.
@@ -29597,7 +29709,7 @@ const middleStepChecker = (statusResponse) => {
29597
29709
  }
29598
29710
  return TransactionStatus.ERROR;
29599
29711
  }
29600
- if (statusResponse?.isLoading) {
29712
+ if (statusResponse?.isInitialLoading) {
29601
29713
  return TransactionStatus.INITIAL_LOADING;
29602
29714
  }
29603
29715
  return TransactionStatus.ONGOING;
@@ -30042,7 +30154,7 @@ const useClient = () => {
30042
30154
  queryFn: getUserCountry,
30043
30155
  enabled: isClient,
30044
30156
  retry: false,
30045
- gcTime: CACHE_TIME,
30157
+ cacheTime: CACHE_TIME,
30046
30158
  staleTime: STALE_TIME,
30047
30159
  });
30048
30160
  const userCountry = countryData?.countryCode || DEFAULT_COUNTRY_CODE;
@@ -30143,13 +30255,11 @@ function useDebouncedValue(value, delay) {
30143
30255
  * @returns the ENS data of the given address
30144
30256
  */
30145
30257
  function useEnsDataForAddress({ address, options, }) {
30146
- const ensQuery = useQuery({
30147
- queryKey: keys().ensData(address?.toLowerCase()),
30148
- queryFn: () => EnsService.getEnsDataFromAddress(address),
30258
+ const ensQuery = useQuery(keys().ensData(address?.toLowerCase()), () => EnsService.getEnsDataFromAddress(address), {
30149
30259
  ...options,
30150
30260
  enabled: Boolean(address?.trim()) &&
30151
30261
  (options?.enabled === undefined ? true : options.enabled),
30152
- gcTime: Infinity,
30262
+ cacheTime: Infinity,
30153
30263
  });
30154
30264
  return ensQuery;
30155
30265
  }
@@ -30165,16 +30275,14 @@ function useEnsDataForAddress({ address, options, }) {
30165
30275
  */
30166
30276
  function useEnsSearch({ name, enabled = true, delayMs = 500, }) {
30167
30277
  const debouncedName = useDebouncedValue(enabled ? name : undefined, delayMs);
30168
- const ensSearchQuery = useQuery({
30169
- queryKey: keys().ensSearch(debouncedName),
30170
- queryFn: () => {
30171
- const isExactEnsSearch = checkIsExactEns(debouncedName);
30172
- return isExactEnsSearch
30173
- ? EnsService.getExactEns(debouncedName)
30174
- : EnsService.searchEnsNames(debouncedName);
30175
- },
30278
+ const ensSearchQuery = useQuery(keys().ensSearch(debouncedName), () => {
30279
+ const isExactEnsSearch = checkIsExactEns(debouncedName);
30280
+ return isExactEnsSearch
30281
+ ? EnsService.getExactEns(debouncedName)
30282
+ : EnsService.searchEnsNames(debouncedName);
30283
+ }, {
30176
30284
  enabled: Boolean(debouncedName?.trim()) && enabled,
30177
- gcTime: Infinity,
30285
+ cacheTime: Infinity,
30178
30286
  });
30179
30287
  return ensSearchQuery;
30180
30288
  }
@@ -30195,25 +30303,23 @@ function checkIsExactEns(name = "") {
30195
30303
 
30196
30304
  const useCosmosForChain = (chain) => {
30197
30305
  const { keplrTypeWallet } = useCosmosSigner({ chain });
30198
- const cosmosAddressQuery = useQuery({
30199
- queryKey: keys().cosmosAddress(chain?.chainId),
30200
- queryFn: async () => {
30201
- if (!chain || !keplrTypeWallet)
30202
- return "";
30203
- try {
30204
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30205
- return address ?? "";
30206
- }
30207
- catch (error) {
30208
- await suggestChainOrThrow({
30209
- chain: chain,
30210
- error,
30211
- keplrTypeWallet,
30212
- });
30213
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30214
- return address ?? "";
30215
- }
30216
- },
30306
+ const cosmosAddressQuery = useQuery(keys().cosmosAddress(chain?.chainId), async () => {
30307
+ if (!chain || !keplrTypeWallet)
30308
+ return "";
30309
+ try {
30310
+ const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30311
+ return address ?? "";
30312
+ }
30313
+ catch (error) {
30314
+ await suggestChainOrThrow({
30315
+ chain: chain,
30316
+ error,
30317
+ keplrTypeWallet,
30318
+ });
30319
+ const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30320
+ return address ?? "";
30321
+ }
30322
+ }, {
30217
30323
  enabled: !!keplrTypeWallet && chain?.chainType === ChainType.COSMOS,
30218
30324
  });
30219
30325
  return cosmosAddressQuery;
@@ -30290,14 +30396,12 @@ const useIsSameAddressAndGnosisContext = () => {
30290
30396
 
30291
30397
  function useBitcoin() {
30292
30398
  const connectedBitcoinWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.BTC]);
30293
- const connectBitcoin = useMutation({
30294
- mutationFn: async ({ wallet, }) => {
30295
- const { address } = await wallet.connector.requestAccount();
30296
- return {
30297
- wallet,
30298
- address,
30299
- };
30300
- }
30399
+ const connectBitcoin = useMutation(async ({ wallet, }) => {
30400
+ const { address } = await wallet.connector.requestAccount();
30401
+ return {
30402
+ wallet,
30403
+ address,
30404
+ };
30301
30405
  });
30302
30406
  return {
30303
30407
  connectBitcoin,
@@ -30337,17 +30441,15 @@ function useEvm() {
30337
30441
  const { wallets } = useEvmWallets();
30338
30442
  const connectedEvmWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.EVM]);
30339
30443
  const recentEvmWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.EVM]);
30340
- const connectEvm = useMutation({
30341
- mutationFn: async ({ wallet, }) => {
30342
- const result = await connectAsync({
30343
- connector: wallet.connector,
30344
- });
30345
- const [firstAddress] = result.accounts;
30346
- return {
30347
- wallet,
30348
- address: firstAddress,
30349
- };
30350
- }
30444
+ const connectEvm = useMutation(async ({ wallet, }) => {
30445
+ const result = await connectAsync({
30446
+ connector: wallet.connector,
30447
+ });
30448
+ const [firstAddress] = result.accounts;
30449
+ return {
30450
+ wallet,
30451
+ address: firstAddress,
30452
+ };
30351
30453
  });
30352
30454
  const disconnectEvm = useCallback(async () => {
30353
30455
  disconnect({ connector: connectedEvmWallet.wallet?.connector });
@@ -30441,23 +30543,21 @@ function useSolana() {
30441
30543
  const { wallets } = useSolanaWallets();
30442
30544
  const connectedSolanaWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.SOLANA]);
30443
30545
  const recentSolanaWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.SOLANA]);
30444
- const connectSolana = useMutation({
30445
- mutationFn: async ({ wallet, }) => {
30446
- try {
30447
- // try to connect silently first
30448
- await wallet.connector.autoConnect();
30449
- }
30450
- catch {
30451
- // if auto-connect fails (e.g. not authorized yet)
30452
- // fallback to connect via popup
30453
- await wallet.connector.connect();
30454
- }
30455
- const address = wallet.connector.wallet.accounts[0].address;
30456
- return {
30457
- wallet,
30458
- address,
30459
- };
30546
+ const connectSolana = useMutation(async ({ wallet, }) => {
30547
+ try {
30548
+ // try to connect silently first
30549
+ await wallet.connector.autoConnect();
30550
+ }
30551
+ catch {
30552
+ // if auto-connect fails (e.g. not authorized yet)
30553
+ // fallback to connect via popup
30554
+ await wallet.connector.connect();
30460
30555
  }
30556
+ const address = wallet.connector.wallet.accounts[0].address;
30557
+ return {
30558
+ wallet,
30559
+ address,
30560
+ };
30461
30561
  });
30462
30562
  const disconnectSolana = useCallback(async () => {
30463
30563
  await connectedSolanaWallet.wallet?.connector.disconnect();
@@ -30532,7 +30632,7 @@ function useStellarWallets() {
30532
30632
  return;
30533
30633
  try {
30534
30634
  const { allowAllModules: initializeAllModules } = await import('@creit.tech/stellar-wallets-kit');
30535
- const { formatStellarWallet } = await import('./stellarService.client-Dp4tvmUo.js');
30635
+ const { formatStellarWallet } = await import('./stellarService.client-deOQBP3h.js');
30536
30636
  const modules = initializeAllModules();
30537
30637
  const promises = modules.map(async (module) => {
30538
30638
  const isAvailable = await module.isAvailable();
@@ -30560,14 +30660,12 @@ function useStellarWallets() {
30560
30660
  function useStellar() {
30561
30661
  const { wallets } = useStellarWallets();
30562
30662
  const connectedStellarWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.STELLAR]);
30563
- const connectStellar = useMutation({
30564
- mutationFn: async ({ wallet, }) => {
30565
- const { address } = await wallet.connector.getAddress();
30566
- return {
30567
- wallet,
30568
- address,
30569
- };
30570
- }
30663
+ const connectStellar = useMutation(async ({ wallet, }) => {
30664
+ const { address } = await wallet.connector.getAddress();
30665
+ return {
30666
+ wallet,
30667
+ address,
30668
+ };
30571
30669
  });
30572
30670
  const disconnectStellar = useCallback(async () => {
30573
30671
  await connectedStellarWallet.wallet?.connector.disconnect?.();
@@ -30619,24 +30717,22 @@ function useSui() {
30619
30717
  const recentSuiWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.SUI]);
30620
30718
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
30621
30719
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
30622
- const connectSui = useMutation({
30623
- mutationFn: async ({ wallet, }) => {
30624
- let account;
30625
- try {
30626
- // try to connect silently first
30627
- account = await wallet.connector.connect({ silent: true });
30628
- }
30629
- catch {
30630
- // if auto-connect fails (e.g. not authorized yet)
30631
- // fallback to connect via popup
30632
- account = await wallet.connector.connect();
30633
- }
30634
- return {
30635
- wallet,
30636
- address: account.account.address,
30637
- account: account.account,
30638
- };
30720
+ const connectSui = useMutation(async ({ wallet, }) => {
30721
+ let account;
30722
+ try {
30723
+ // try to connect silently first
30724
+ account = await wallet.connector.connect({ silent: true });
30639
30725
  }
30726
+ catch {
30727
+ // if auto-connect fails (e.g. not authorized yet)
30728
+ // fallback to connect via popup
30729
+ account = await wallet.connector.connect();
30730
+ }
30731
+ return {
30732
+ wallet,
30733
+ address: account.account.address,
30734
+ account: account.account,
30735
+ };
30640
30736
  });
30641
30737
  const disconnectSui = useCallback(async () => {
30642
30738
  await connectedSuiWallet.wallet?.connector.disconnect();
@@ -30945,14 +31041,12 @@ function useXrpl() {
30945
31041
  const recentXrplWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.XRPL]);
30946
31042
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
30947
31043
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
30948
- const connectXrpl = useMutation({
30949
- mutationFn: async ({ wallet, }) => {
30950
- const xrplConnectedAddress = await wallet.connector.connect();
30951
- return {
30952
- wallet,
30953
- address: xrplConnectedAddress,
30954
- };
30955
- }
31044
+ const connectXrpl = useMutation(async ({ wallet, }) => {
31045
+ const xrplConnectedAddress = await wallet.connector.connect();
31046
+ return {
31047
+ wallet,
31048
+ address: xrplConnectedAddress,
31049
+ };
30956
31050
  });
30957
31051
  const disconnectXrpl = useCallback(async () => {
30958
31052
  await connectedXrplWallet?.wallet?.connector.disconnect?.();
@@ -31339,19 +31433,18 @@ const useMultiChainWallet = (chain) => {
31339
31433
  /**
31340
31434
  * Change current network for desired chain
31341
31435
  */
31342
- const changeNetworkIfNeeded = useMutation({
31343
- mutationFn: async () => {
31344
- const isNotOnDesiredChain = chain?.chainType === ChainType.EVM &&
31345
- currentEvmChain?.id !== Number(chain.chainId);
31346
- if (isNotOnDesiredChain) {
31347
- await switchChainAsync({
31348
- chainId: Number(chain.chainId),
31349
- });
31350
- }
31351
- // Implement keplr change network
31352
- // Looks like there are no method to do that at the moment
31353
- return false;
31354
- },
31436
+ const changeNetworkIfNeeded = useMutation(async () => {
31437
+ const isNotOnDesiredChain = chain?.chainType === ChainType.EVM &&
31438
+ currentEvmChain?.id !== Number(chain.chainId);
31439
+ if (isNotOnDesiredChain) {
31440
+ await switchChainAsync({
31441
+ chainId: Number(chain.chainId),
31442
+ });
31443
+ }
31444
+ // Implement keplr change network
31445
+ // Looks like there are no method to do that at the moment
31446
+ return false;
31447
+ }, {
31355
31448
  onError: async (error) => {
31356
31449
  if (error instanceof UserRejectedRequestError) {
31357
31450
  return;
@@ -31363,7 +31456,7 @@ const useMultiChainWallet = (chain) => {
31363
31456
  provider,
31364
31457
  });
31365
31458
  }
31366
- }
31459
+ },
31367
31460
  });
31368
31461
  const isChainTypeConnected = useCallback((chainType) => {
31369
31462
  if (isGnosisConnected && chainType === ChainType.EVM) {
@@ -31711,53 +31804,51 @@ const useCosmos = () => {
31711
31804
  clientWindow?.removeEventListener("keplr_keystorechange", () => handleKeplrAccountChanged());
31712
31805
  };
31713
31806
  }, [handleKeplrAccountChanged, clientWindow]);
31714
- const connectCosmos = useMutation({
31715
- mutationFn: async ({ chain, wallet, approveAllChains = true, }) => {
31716
- const chainInfos = getCosmosChainInfosObject(chain);
31717
- const cosmosWalletObject = wallet.connector().provider;
31718
- if (cosmosWalletObject) {
31719
- setCosmosChainId(chainInfos.chainId.toString());
31720
- try {
31721
- if (approveAllChains &&
31722
- typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31723
- "function") {
31724
- try {
31725
- const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31726
- const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31727
- const chainsToEnable = cosmosChains
31728
- .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31729
- .map((c) => c.chainId.toString());
31730
- await cosmosWalletObject.enable(chainsToEnable);
31731
- }
31732
- catch (error) {
31733
- console.warn("Failed to get chain infos, falling back to single chain enable", error);
31734
- await cosmosWalletObject.enable(chainInfos.chainId);
31735
- }
31807
+ const connectCosmos = useMutation(async ({ chain, wallet, approveAllChains = true, }) => {
31808
+ const chainInfos = getCosmosChainInfosObject(chain);
31809
+ const cosmosWalletObject = wallet.connector().provider;
31810
+ if (cosmosWalletObject) {
31811
+ setCosmosChainId(chainInfos.chainId.toString());
31812
+ try {
31813
+ if (approveAllChains &&
31814
+ typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31815
+ "function") {
31816
+ try {
31817
+ const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31818
+ const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31819
+ const chainsToEnable = cosmosChains
31820
+ .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31821
+ .map((c) => c.chainId.toString());
31822
+ await cosmosWalletObject.enable(chainsToEnable);
31736
31823
  }
31737
- else {
31824
+ catch (error) {
31825
+ console.warn("Failed to get chain infos, falling back to single chain enable", error);
31738
31826
  await cosmosWalletObject.enable(chainInfos.chainId);
31739
31827
  }
31740
- const address = await getAddress({
31741
- chainId: chain.chainId.toString(),
31742
- cosmosWalletObject,
31743
- wallet,
31744
- });
31745
- if (address) {
31746
- updateWalletStore(wallet, cosmosWalletObject, address);
31747
- return address;
31748
- }
31749
31828
  }
31750
- catch (error) {
31751
- await suggestChainOrThrow({
31752
- chain,
31753
- error,
31754
- keplrTypeWallet: cosmosWalletObject,
31755
- });
31756
- return connectCosmos.mutateAsync({ chain, wallet });
31829
+ else {
31830
+ await cosmosWalletObject.enable(chainInfos.chainId);
31831
+ }
31832
+ const address = await getAddress({
31833
+ chainId: chain.chainId.toString(),
31834
+ cosmosWalletObject,
31835
+ wallet,
31836
+ });
31837
+ if (address) {
31838
+ updateWalletStore(wallet, cosmosWalletObject, address);
31839
+ return address;
31757
31840
  }
31758
31841
  }
31759
- return undefined;
31842
+ catch (error) {
31843
+ await suggestChainOrThrow({
31844
+ chain,
31845
+ error,
31846
+ keplrTypeWallet: cosmosWalletObject,
31847
+ });
31848
+ return connectCosmos.mutateAsync({ chain, wallet });
31849
+ }
31760
31850
  }
31851
+ return undefined;
31761
31852
  });
31762
31853
  const clearData = () => {
31763
31854
  disconnectWallet(ChainType.COSMOS);
@@ -31841,64 +31932,13 @@ function useTrackSearchEmpty({ searchQuery, resultsLength, context, debounceMs =
31841
31932
  }, [context, debounceMs, resultsLength, searchQuery]);
31842
31933
  }
31843
31934
 
31844
- const useKeyboardNavigation = (props) => {
31845
- const { itemsListRef, activeListItemClassName = "", onEscape } = props ?? {};
31935
+ const useKeyboardNavigation = ({ onEscape }) => {
31846
31936
  const onKeyDown = useCallback((event) => {
31847
31937
  if (event.key === "Escape") {
31848
31938
  onEscape?.();
31849
31939
  return;
31850
31940
  }
31851
- if (activeListItemClassName.trim() === "")
31852
- return;
31853
- const itemsList = itemsListRef?.current;
31854
- const separatedActiveItemClassNames = activeListItemClassName.split(" ");
31855
- const defaultActiveItem = itemsList?.querySelector(`.${separatedActiveItemClassNames.join(".")}`);
31856
- if (event.key === "ArrowUp") {
31857
- if (!itemsList)
31858
- return;
31859
- event.preventDefault();
31860
- const activeItem = defaultActiveItem ?? itemsList.lastElementChild;
31861
- if (!activeItem)
31862
- return;
31863
- const previousItem = activeItem.previousElementSibling;
31864
- if (previousItem) {
31865
- activeItem.classList.remove(...separatedActiveItemClassNames);
31866
- previousItem.classList.add(...separatedActiveItemClassNames);
31867
- // scroll to previous item
31868
- itemsList.scrollTo({
31869
- top: (previousItem.offsetTop ?? 0) -
31870
- itemsList.clientHeight,
31871
- behavior: "smooth",
31872
- });
31873
- }
31874
- }
31875
- else if (event.key === "ArrowDown") {
31876
- if (!itemsList)
31877
- return;
31878
- event.preventDefault();
31879
- const activeItem = defaultActiveItem ?? itemsList.firstElementChild;
31880
- if (!activeItem)
31881
- return;
31882
- const nextItem = activeItem.nextElementSibling;
31883
- if (nextItem) {
31884
- activeItem.classList.remove(...separatedActiveItemClassNames);
31885
- nextItem.classList.add(...separatedActiveItemClassNames);
31886
- // scroll to next item
31887
- itemsList.scrollTo({
31888
- top: (nextItem.offsetTop ?? 0) -
31889
- itemsList.clientHeight,
31890
- behavior: "smooth",
31891
- });
31892
- }
31893
- }
31894
- else if (event.key === "Enter") {
31895
- event.preventDefault();
31896
- if (defaultActiveItem) {
31897
- // select active item
31898
- defaultActiveItem.querySelector("button")?.click();
31899
- }
31900
- }
31901
- }, [itemsListRef, activeListItemClassName]);
31941
+ }, [onEscape]);
31902
31942
  useEffect(() => {
31903
31943
  document.addEventListener("keydown", onKeyDown, false);
31904
31944
  return () => {
@@ -31911,11 +31951,11 @@ const useSquidQueryClient = () => {
31911
31951
  const queryClient = useQueryClient();
31912
31952
  const invalidateQueries = (key) => {
31913
31953
  const prefixKey = getPrefixKey(key);
31914
- queryClient.invalidateQueries({ queryKey: prefixKey });
31954
+ queryClient.invalidateQueries(prefixKey);
31915
31955
  };
31916
31956
  const refetchQueries = (key) => {
31917
31957
  const prefixKey = getPrefixKey(key);
31918
- queryClient.refetchQueries({ queryKey: prefixKey });
31958
+ queryClient.refetchQueries(prefixKey);
31919
31959
  };
31920
31960
  const invalidateAndRefetchQueries = (key) => {
31921
31961
  invalidateQueries(key);
@@ -33422,19 +33462,17 @@ function useDepositAddress(squidRoute) {
33422
33462
  toggleDepositFlow(false);
33423
33463
  setDeposit(null);
33424
33464
  }, [toggleDepositFlow, setDeposit]);
33425
- const getRouteWithDeposit = useMutation({
33426
- mutationFn: async ({ route }) => {
33427
- if (!squid)
33428
- throw new Error("Squid SDK not initialized");
33429
- const depositAddressResponse = (await squid.executeRoute({
33430
- signer: {},
33431
- route,
33432
- }));
33433
- setDeposit(depositAddressResponse);
33434
- return {
33435
- depositAddress: depositAddressResponse,
33436
- };
33437
- }
33465
+ const getRouteWithDeposit = useMutation(async ({ route }) => {
33466
+ if (!squid)
33467
+ throw new Error("Squid SDK not initialized");
33468
+ const depositAddressResponse = (await squid.executeRoute({
33469
+ signer: {},
33470
+ route,
33471
+ }));
33472
+ setDeposit(depositAddressResponse);
33473
+ return {
33474
+ depositAddress: depositAddressResponse,
33475
+ };
33438
33476
  });
33439
33477
  return {
33440
33478
  isEnabled,
@@ -33518,55 +33556,53 @@ const useAllTokensWithBalanceForChainType = ({ chainType, address, direction, qu
33518
33556
  xrplTokens.length,
33519
33557
  stellarTokens.length,
33520
33558
  ]);
33521
- const query = useQuery({
33522
- queryKey: keys().allTokensBalance(address, chainType, direction),
33523
- queryFn: async () => {
33524
- // Return zero balances if no address
33525
- if (!address) {
33526
- const defaultTokens = placeholderData.tokens;
33527
- return {
33528
- tokens: defaultTokens,
33529
- totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33530
- };
33531
- }
33532
- let fetchedTokens = [];
33533
- // Fetch tokens based on chain type
33534
- switch (chainType) {
33535
- case ChainType.EVM:
33536
- fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33537
- break;
33538
- case ChainType.COSMOS:
33539
- const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33540
- fetchedTokens = await getAllCosmosBalances({
33541
- addresses,
33542
- cosmosChains,
33543
- cosmosTokens,
33544
- });
33545
- break;
33546
- case ChainType.SOLANA:
33547
- fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33548
- break;
33549
- case ChainType.BTC:
33550
- fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33551
- break;
33552
- case ChainType.SUI:
33553
- fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33554
- break;
33555
- case ChainType.XRPL:
33556
- fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33557
- break;
33558
- case ChainType.STELLAR:
33559
- fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33560
- break;
33561
- default:
33562
- fetchedTokens = placeholderData.tokens;
33563
- break;
33564
- }
33559
+ const query = useQuery(keys().allTokensBalance(address, chainType, direction), async () => {
33560
+ // Return zero balances if no address
33561
+ if (!address) {
33562
+ const defaultTokens = placeholderData.tokens;
33565
33563
  return {
33566
- tokens: fetchedTokens,
33567
- totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33564
+ tokens: defaultTokens,
33565
+ totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33568
33566
  };
33569
- },
33567
+ }
33568
+ let fetchedTokens = [];
33569
+ // Fetch tokens based on chain type
33570
+ switch (chainType) {
33571
+ case ChainType.EVM:
33572
+ fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33573
+ break;
33574
+ case ChainType.COSMOS:
33575
+ const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33576
+ fetchedTokens = await getAllCosmosBalances({
33577
+ addresses,
33578
+ cosmosChains,
33579
+ cosmosTokens,
33580
+ });
33581
+ break;
33582
+ case ChainType.SOLANA:
33583
+ fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33584
+ break;
33585
+ case ChainType.BTC:
33586
+ fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33587
+ break;
33588
+ case ChainType.SUI:
33589
+ fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33590
+ break;
33591
+ case ChainType.XRPL:
33592
+ fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33593
+ break;
33594
+ case ChainType.STELLAR:
33595
+ fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33596
+ break;
33597
+ default:
33598
+ fetchedTokens = placeholderData.tokens;
33599
+ break;
33600
+ }
33601
+ return {
33602
+ tokens: fetchedTokens,
33603
+ totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33604
+ };
33605
+ }, {
33570
33606
  ...queryOptions,
33571
33607
  enabled: isQueryEnabled,
33572
33608
  });
@@ -33581,7 +33617,7 @@ const BALANCE_STALE_TIME = 60000; // 1 minute
33581
33617
  const BALANCE_CACHE_TIME = 300000; // 5 minutes
33582
33618
  const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33583
33619
  staleTime: BALANCE_STALE_TIME,
33584
- gcTime: BALANCE_CACHE_TIME,
33620
+ cacheTime: BALANCE_CACHE_TIME,
33585
33621
  refetchOnWindowFocus: true,
33586
33622
  refetchOnMount: true,
33587
33623
  }, } = {}) => {
@@ -33662,9 +33698,9 @@ const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33662
33698
  }, [balanceQueries]);
33663
33699
  // Aggregate loading states
33664
33700
  const queryStates = useMemo(() => ({
33665
- isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33701
+ isInitialLoading: Object.values(balanceQueries).some((q) => q.isInitialLoading),
33666
33702
  isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33667
- isPending: Object.values(balanceQueries).some((q) => q.isPending),
33703
+ isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33668
33704
  isRefetching: Object.values(balanceQueries).some((q) => q.isRefetching),
33669
33705
  isError: Object.values(balanceQueries).some((q) => q.isError),
33670
33706
  isSuccess: Object.values(balanceQueries).every((q) => q.isSuccess),
@@ -33706,7 +33742,7 @@ function useNativeTokenForChain(chain) {
33706
33742
 
33707
33743
  const useEvmNativeBalance = ({ address, chain, }) => {
33708
33744
  const { isChainTypeConnected } = useWallet();
33709
- const { data: nativeEvmBalance, isPending } = useBalance({
33745
+ const { data: nativeEvmBalance, isLoading } = useBalance({
33710
33746
  address: address,
33711
33747
  chainId: Number(chain?.chainId),
33712
33748
  query: {
@@ -33728,13 +33764,13 @@ const useEvmNativeBalance = ({ address, chain, }) => {
33728
33764
  }, [nativeEvmBalance?.decimals, nativeEvmBalance?.value]);
33729
33765
  return {
33730
33766
  balance,
33731
- isPending,
33767
+ isLoading,
33732
33768
  };
33733
33769
  };
33734
33770
  const useCosmosNativeBalance = ({ address, chain, }) => {
33735
33771
  const { isConnected: isCosmosConnected } = useCosmosContext();
33736
33772
  const { nativeToken: nativeCosmosToken } = useNativeTokenForChain(chain);
33737
- const { balance: rawBalance, isPending } = useCosmosBalance({
33773
+ const { balance: rawBalance, isLoading } = useCosmosBalance({
33738
33774
  chain,
33739
33775
  token: nativeCosmosToken,
33740
33776
  userAddress: address,
@@ -33749,18 +33785,16 @@ const useCosmosNativeBalance = ({ address, chain, }) => {
33749
33785
  };
33750
33786
  }
33751
33787
  }, [nativeCosmosToken?.decimals, rawBalance]);
33752
- return { balance, isPending };
33788
+ return { balance, isLoading };
33753
33789
  };
33754
33790
  const useBitcoinNativeBalance = ({ chain, address, }) => {
33755
33791
  const { nativeToken } = useNativeTokenForChain(chain);
33756
- const { data: rawBalance = "0", isPending } = useQuery({
33757
- queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33758
- queryFn: async () => {
33759
- if (!address || !nativeToken)
33760
- return "0";
33761
- const balance = await getBitcoinNativeBalance(address);
33762
- return formatBNToReadable(balance, nativeToken.decimals);
33763
- },
33792
+ const { data: rawBalance = "0", isLoading } = useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33793
+ if (!address || !nativeToken)
33794
+ return "0";
33795
+ const balance = await getBitcoinNativeBalance(address);
33796
+ return formatBNToReadable(balance, nativeToken.decimals);
33797
+ }, {
33764
33798
  enabled: chain?.chainType === ChainType.BTC &&
33765
33799
  nativeToken?.decimals != null &&
33766
33800
  isWalletAddressValid(chain, address),
@@ -33779,17 +33813,15 @@ const useBitcoinNativeBalance = ({ chain, address, }) => {
33779
33813
  }, [nativeToken?.decimals, rawBalance]);
33780
33814
  return {
33781
33815
  balance,
33782
- isPending,
33816
+ isLoading,
33783
33817
  };
33784
33818
  };
33785
33819
  const useSolanaNativeBalance = ({ chain, address, }) => {
33786
33820
  const { nativeToken } = useNativeTokenForChain(chain);
33787
- const { data: rawBalance, isPending } = useQuery({
33788
- queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33789
- queryFn: async () => {
33790
- const balance = await getSolanaNativeBalance(address);
33791
- return formatBNToReadable(balance, nativeToken.decimals);
33792
- },
33821
+ const { data: rawBalance, isLoading } = useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33822
+ const balance = await getSolanaNativeBalance(address);
33823
+ return formatBNToReadable(balance, nativeToken.decimals);
33824
+ }, {
33793
33825
  enabled: !!address &&
33794
33826
  nativeToken?.decimals != null &&
33795
33827
  chain?.chainType === ChainType.SOLANA,
@@ -33808,12 +33840,12 @@ const useSolanaNativeBalance = ({ chain, address, }) => {
33808
33840
  }, [nativeToken?.decimals, rawBalance]);
33809
33841
  return {
33810
33842
  balance,
33811
- isPending,
33843
+ isLoading,
33812
33844
  };
33813
33845
  };
33814
33846
  const useSuiNativeBalance = ({ address, chain, }) => {
33815
33847
  const { nativeToken } = useNativeTokenForChain(chain);
33816
- const { balance: rawBalance, isPending } = useSuiBalance({
33848
+ const { balance: rawBalance, isLoading } = useSuiBalance({
33817
33849
  chain,
33818
33850
  token: nativeToken,
33819
33851
  userAddress: address,
@@ -33828,12 +33860,12 @@ const useSuiNativeBalance = ({ address, chain, }) => {
33828
33860
  }, [nativeToken?.decimals, rawBalance]);
33829
33861
  return {
33830
33862
  balance,
33831
- isPending,
33863
+ isLoading,
33832
33864
  };
33833
33865
  };
33834
33866
  const useXrplNativeBalance = ({ address, chain, }) => {
33835
33867
  const { nativeToken } = useNativeTokenForChain(chain);
33836
- const { balance: rawBalance, isPending } = useXrplBalance({
33868
+ const { balance: rawBalance, isLoading } = useXrplBalance({
33837
33869
  chain,
33838
33870
  token: nativeToken,
33839
33871
  userAddress: address,
@@ -33849,12 +33881,12 @@ const useXrplNativeBalance = ({ address, chain, }) => {
33849
33881
  }, [nativeToken?.decimals, rawBalance]);
33850
33882
  return {
33851
33883
  balance,
33852
- isPending,
33884
+ isLoading,
33853
33885
  };
33854
33886
  };
33855
33887
  const useStellarNativeBalance = ({ address, chain, }) => {
33856
33888
  const { nativeToken } = useNativeTokenForChain(chain);
33857
- const { balance: rawBalance, isPending } = useStellarBalance({
33889
+ const { balance: rawBalance, isLoading } = useStellarBalance({
33858
33890
  chain,
33859
33891
  token: nativeToken,
33860
33892
  userAddress: address,
@@ -33870,7 +33902,7 @@ const useStellarNativeBalance = ({ address, chain, }) => {
33870
33902
  }, [nativeToken?.decimals, rawBalance]);
33871
33903
  return {
33872
33904
  balance,
33873
- isPending,
33905
+ isLoading,
33874
33906
  };
33875
33907
  };
33876
33908
  const useNativeBalance = (chain) => {
@@ -33878,28 +33910,28 @@ const useNativeBalance = (chain) => {
33878
33910
  const { data: cosmosAddressForChain } = useCosmosForChain(chain);
33879
33911
  // Cosmos is a special case because the address changes on every chain
33880
33912
  // so we can't use the default cosmos connected address
33881
- const { balance: nativeCosmosBalance, isPending: isCosmosPending } = useCosmosNativeBalance({
33913
+ const { balance: nativeCosmosBalance, isLoading: isCosmosLoading } = useCosmosNativeBalance({
33882
33914
  address: cosmosAddressForChain,
33883
33915
  chain,
33884
33916
  });
33885
- const { balance: nativeEvmBalance, isPending: isEvmPending } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33886
- const { balance: nativeBitcoinBalance, isPending: isBitcoinPending } = useBitcoinNativeBalance({
33917
+ const { balance: nativeEvmBalance, isLoading: isEvmLoading } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33918
+ const { balance: nativeBitcoinBalance, isLoading: isBitcoinLoading } = useBitcoinNativeBalance({
33887
33919
  address: connectedAddresses[ChainType.BTC],
33888
33920
  chain,
33889
33921
  });
33890
- const { balance: nativeSolanaBalance, isPending: isSolanaPending } = useSolanaNativeBalance({
33922
+ const { balance: nativeSolanaBalance, isLoading: isSolanaLoading } = useSolanaNativeBalance({
33891
33923
  address: connectedAddresses[ChainType.SOLANA],
33892
33924
  chain,
33893
33925
  });
33894
- const { balance: nativeSuiBalance, isPending: isSuiPending } = useSuiNativeBalance({
33926
+ const { balance: nativeSuiBalance, isLoading: isSuiLoading } = useSuiNativeBalance({
33895
33927
  address: connectedAddresses[ChainType.SUI],
33896
33928
  chain,
33897
33929
  });
33898
- const { balance: nativeXrplBalance, isPending: isXrplPending } = useXrplNativeBalance({
33930
+ const { balance: nativeXrplBalance, isLoading: isXrpLoading } = useXrplNativeBalance({
33899
33931
  address: connectedAddresses[ChainType.XRPL],
33900
33932
  chain,
33901
33933
  });
33902
- const { balance: nativeStellarBalance, isPending: isStellarPending } = useStellarNativeBalance({
33934
+ const { balance: nativeStellarBalance, isLoading: isStellarLoading } = useStellarNativeBalance({
33903
33935
  address: connectedAddresses[ChainType.STELLAR],
33904
33936
  chain,
33905
33937
  });
@@ -33944,36 +33976,36 @@ const useNativeBalance = (chain) => {
33944
33976
  nativeXrplBalance,
33945
33977
  nativeStellarBalance,
33946
33978
  ]);
33947
- const isPending = useMemo(() => {
33979
+ const isLoading = useMemo(() => {
33948
33980
  if (!chain?.chainType)
33949
33981
  return false;
33950
33982
  switch (chain.chainType) {
33951
33983
  case ChainType.EVM:
33952
- return isEvmPending;
33984
+ return isEvmLoading;
33953
33985
  case ChainType.COSMOS:
33954
- return isCosmosPending;
33986
+ return isCosmosLoading;
33955
33987
  case ChainType.BTC:
33956
- return isBitcoinPending;
33988
+ return isBitcoinLoading;
33957
33989
  case ChainType.SOLANA:
33958
- return isSolanaPending;
33990
+ return isSolanaLoading;
33959
33991
  case ChainType.SUI:
33960
- return isSuiPending;
33992
+ return isSuiLoading;
33961
33993
  case ChainType.XRPL:
33962
- return isXrplPending;
33994
+ return isXrpLoading;
33963
33995
  case ChainType.STELLAR:
33964
- return isStellarPending;
33996
+ return isStellarLoading;
33965
33997
  }
33966
33998
  }, [
33967
33999
  chain?.chainType,
33968
- isEvmPending,
33969
- isCosmosPending,
33970
- isBitcoinPending,
33971
- isSolanaPending,
33972
- isSuiPending,
33973
- isXrplPending,
33974
- isStellarPending,
34000
+ isEvmLoading,
34001
+ isCosmosLoading,
34002
+ isBitcoinLoading,
34003
+ isSolanaLoading,
34004
+ isSuiLoading,
34005
+ isXrpLoading,
34006
+ isStellarLoading,
33975
34007
  ]);
33976
- return { nativeBalance, nativeBalanceFormatted, isPending };
34008
+ return { nativeBalance, nativeBalanceFormatted, isLoading };
33977
34009
  };
33978
34010
 
33979
34011
  const DEFAULT_REFRESH_INTERVAL_MS = 15000;
@@ -33982,7 +34014,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
33982
34014
  const isNativeToken = token?.address.toLowerCase() === nativeEvmTokenAddress.toLowerCase();
33983
34015
  const userAddressParsed = userAddress;
33984
34016
  // Only fetch using useBalance if it's a native token
33985
- const { data: nativeBalance, isPending: isNativeTokenPending } = useBalance({
34017
+ const { data: nativeBalance, isLoading: isNativeTokenLoading } = useBalance({
33986
34018
  address: userAddressParsed,
33987
34019
  chainId: Number(chain?.chainId),
33988
34020
  query: {
@@ -33998,7 +34030,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
33998
34030
  });
33999
34031
  // Only fetch using useReadContract if it's not a native token
34000
34032
  // This is temporary, because of wagmi error: https://github.com/wevm/wagmi/issues/4353
34001
- const { data: erc20Balance, isPending: isErc20Pending } = useReadContract({
34033
+ const { data: erc20Balance, isLoading: isErc20Loading } = useReadContract({
34002
34034
  address: token?.address,
34003
34035
  abi: erc20Abi,
34004
34036
  functionName: "balanceOf",
@@ -34014,15 +34046,15 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34014
34046
  },
34015
34047
  });
34016
34048
  const balance = isNativeToken ? nativeBalance?.value : erc20Balance;
34017
- const isPending = isNativeToken ? isNativeTokenPending : isErc20Pending;
34049
+ const isLoading = isNativeToken ? isNativeTokenLoading : isErc20Loading;
34018
34050
  const formattedBalance = balance != null && token?.decimals != null
34019
34051
  ? formatBNToReadable(balance, token.decimals)
34020
34052
  : "0";
34021
- return { balance: formattedBalance, isPending };
34053
+ return { balance: formattedBalance, isLoading };
34022
34054
  };
34023
34055
  const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34024
34056
  const { isConnected } = useCosmosContext();
34025
- const { data: balance = "0", isPending } = useQuery({
34057
+ const { data: balance = "0", isLoading } = useQuery({
34026
34058
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34027
34059
  queryFn: async () => {
34028
34060
  if (!userAddress || !token || chain?.chainType !== ChainType.COSMOS) {
@@ -34042,10 +34074,10 @@ const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34042
34074
  refetchInterval: refreshIntervalMs,
34043
34075
  retry: 2,
34044
34076
  });
34045
- return { balance, isPending };
34077
+ return { balance, isLoading };
34046
34078
  };
34047
34079
  const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34048
- const { data: balance = "0", isPending } = useQuery({
34080
+ const { data: balance = "0", isLoading } = useQuery({
34049
34081
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34050
34082
  queryFn: async () => {
34051
34083
  if (!userAddress || !token)
@@ -34060,11 +34092,11 @@ const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34060
34092
  refetchInterval: refreshIntervalMs,
34061
34093
  retry: 2,
34062
34094
  });
34063
- return { balance, isPending };
34095
+ return { balance, isLoading };
34064
34096
  };
34065
34097
  // TODO: implement fetching balances for all bitcoin tokens
34066
34098
  const useBitcoinBalance = ({ userAddress, chain, }) => {
34067
- const { balance: balanceBn, isPending } = useBitcoinNativeBalance({
34099
+ const { balance: balanceBn, isLoading } = useBitcoinNativeBalance({
34068
34100
  address: userAddress,
34069
34101
  chain,
34070
34102
  });
@@ -34073,10 +34105,10 @@ const useBitcoinBalance = ({ userAddress, chain, }) => {
34073
34105
  return "0";
34074
34106
  return formatBNToReadable(balanceBn?.value, balanceBn?.decimals);
34075
34107
  }, [balanceBn]);
34076
- return { balance, isPending };
34108
+ return { balance, isLoading };
34077
34109
  };
34078
34110
  const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34079
- const { data: balance = "0", isPending } = useQuery({
34111
+ const { data: balance = "0", isLoading } = useQuery({
34080
34112
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34081
34113
  queryFn: async () => {
34082
34114
  if (!userAddress ||
@@ -34096,10 +34128,10 @@ const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34096
34128
  refetchInterval: refreshIntervalMs,
34097
34129
  retry: 2,
34098
34130
  });
34099
- return { balance, isPending };
34131
+ return { balance, isLoading };
34100
34132
  };
34101
34133
  const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34102
- const { data: balance = "0", isPending } = useQuery({
34134
+ const { data: balance = "0", isLoading } = useQuery({
34103
34135
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34104
34136
  queryFn: async () => {
34105
34137
  if (!userAddress || !token || !chain)
@@ -34116,10 +34148,10 @@ const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs
34116
34148
  refetchInterval: refreshIntervalMs,
34117
34149
  retry: 2,
34118
34150
  });
34119
- return { balance, isPending };
34151
+ return { balance, isLoading };
34120
34152
  };
34121
34153
  const useStellarBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34122
- const { data: balance = "0", isPending } = useQuery({
34154
+ const { data: balance = "0", isLoading } = useQuery({
34123
34155
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34124
34156
  queryFn: async () => {
34125
34157
  if (!userAddress || !token || !chain)
@@ -34136,7 +34168,7 @@ const useStellarBalance = ({ userAddress, chain, enabled, token, refreshInterval
34136
34168
  refetchInterval: refreshIntervalMs,
34137
34169
  retry: 2,
34138
34170
  });
34139
- return { balance, isPending };
34171
+ return { balance, isLoading };
34140
34172
  };
34141
34173
 
34142
34174
  /**
@@ -34257,7 +34289,7 @@ const useMultipleTokenPrices = (tokens) => {
34257
34289
  return {
34258
34290
  tokenPrices,
34259
34291
  getTokenPrice,
34260
- isPending: coinGeckoQuery.isPending,
34292
+ isLoading: coinGeckoQuery.isLoading,
34261
34293
  isError: coinGeckoQuery.isError,
34262
34294
  error: coinGeckoQuery.error,
34263
34295
  refetch: coinGeckoQuery.refetch,
@@ -34406,17 +34438,13 @@ const fetchTokensData = async (tokens) => {
34406
34438
 
34407
34439
  // Coingecko has a limit for some queries for multiple tokens, not sure what it is, but let's use 100 for now
34408
34440
  const useHistoricalData = (coingeckoId, timeFrame) => {
34409
- return useQuery({
34410
- queryKey: keys().historicalData(coingeckoId, timeFrame),
34411
- queryFn: () => fetchHistoricalData(coingeckoId, timeFrame),
34441
+ return useQuery(keys().historicalData(coingeckoId, timeFrame), () => fetchHistoricalData(coingeckoId, timeFrame), {
34412
34442
  staleTime: 5 * 60 * 1000,
34413
34443
  enabled: !!coingeckoId,
34414
34444
  });
34415
34445
  };
34416
34446
  const useTokensData = (tokens) => {
34417
- return useQuery({
34418
- queryKey: keys().tokensData(tokens),
34419
- queryFn: () => fetchTokensData(tokens),
34447
+ return useQuery(keys().tokensData(tokens), () => fetchTokensData(tokens), {
34420
34448
  staleTime: 60 * 1000,
34421
34449
  enabled: !!tokens && tokens.length > 0,
34422
34450
  });
@@ -34721,7 +34749,7 @@ function useSendTransactionGas({ chain, token, from, }) {
34721
34749
  }
34722
34750
 
34723
34751
  function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34724
- const { data: estimatedGas = BigInt(0), isPending } = useSendTransactionGas({
34752
+ const { data: estimatedGas = BigInt(0), isLoading } = useSendTransactionGas({
34725
34753
  chain,
34726
34754
  token,
34727
34755
  from,
@@ -34766,7 +34794,7 @@ function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34766
34794
  return {
34767
34795
  estimatedGas,
34768
34796
  isBalanceEnough,
34769
- isPending,
34797
+ isLoading,
34770
34798
  isNativeBalanceEnoughToPayGasFees,
34771
34799
  minAmountValueWarnMsg,
34772
34800
  };
@@ -35173,12 +35201,10 @@ function useSendTransaction({ to, amount, token, chain, }) {
35173
35201
  // amount is already formatted with the token decimals
35174
35202
  amount,
35175
35203
  toAddress: to,
35176
- token: {
35177
- address: token.address,
35178
- chainId: token.chainId,
35179
- symbol: token.symbol,
35180
- type: token.type,
35181
- },
35204
+ tokenAddress: token.address,
35205
+ tokenChainId: token.chainId,
35206
+ tokenSymbol: token.symbol,
35207
+ tokenType: token.type,
35182
35208
  });
35183
35209
  }, [
35184
35210
  allEventParamsDefined,
@@ -35198,12 +35224,10 @@ function useSendTransaction({ to, amount, token, chain, }) {
35198
35224
  // amount is already formatted with the token decimals
35199
35225
  amount,
35200
35226
  toAddress: to,
35201
- token: {
35202
- address: token.address,
35203
- chainId: token.chainId,
35204
- symbol: token.symbol,
35205
- type: token.type,
35206
- },
35227
+ tokenAddress: token.address,
35228
+ tokenChainId: token.chainId,
35229
+ tokenSymbol: token.symbol,
35230
+ tokenType: token.type,
35207
35231
  txHash,
35208
35232
  });
35209
35233
  }, [
@@ -35349,9 +35373,7 @@ function useSendTransaction({ to, amount, token, chain, }) {
35349
35373
  });
35350
35374
  },
35351
35375
  onSuccess: (tx, variables) => {
35352
- queryClient.invalidateQueries({
35353
- queryKey: getPrefixKey(QueryKeys.Balance),
35354
- });
35376
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balance));
35355
35377
  setTransactionState(variables.id, tx);
35356
35378
  persistTransaction({
35357
35379
  txType: HistoryTxType.SEND,
@@ -35678,10 +35700,9 @@ const useAllTransactionsStatus = ({ enabled }) => {
35678
35700
  queryKey: keys().fiatToCryptoStatus(data.orderId),
35679
35701
  retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
35680
35702
  retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
35681
- refetchInterval: (query) => {
35682
- const { state } = query;
35683
- if (state.data?.status &&
35684
- FINAL_TRANSACTION_STATUSES.includes(state.data.status)) {
35703
+ refetchInterval: (data) => {
35704
+ if (data?.status &&
35705
+ FINAL_TRANSACTION_STATUSES.includes(data.status)) {
35685
35706
  return false;
35686
35707
  }
35687
35708
  return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
@@ -35741,7 +35762,7 @@ const useAllTransactionsStatus = ({ enabled }) => {
35741
35762
  queries: enabled && config.apiUrl ? statusQueries : [],
35742
35763
  });
35743
35764
  return {
35744
- isPending: queries.some((q) => q.isPending),
35765
+ isLoading: queries.some((q) => q.isLoading),
35745
35766
  isError: queries.some((q) => q.isError),
35746
35767
  data: queries.map((q) => q.data).filter(Boolean),
35747
35768
  };
@@ -36000,18 +36021,16 @@ const useApproval = ({ squidRoute, }) => {
36000
36021
  * On Error: Showing the error message if any
36001
36022
  * @returns {boolean} approved
36002
36023
  */
36003
- const routeApproved = useQuery({
36004
- queryKey: keys().routeApproved(squidRoute, allowanceInWei),
36005
- queryFn: async () => {
36006
- // Approval is only needed for EVM chains
36007
- if (getChainType(squidRoute?.params.fromChain) === ChainType.EVM) {
36008
- return hasAllowance;
36009
- }
36010
- return true;
36011
- },
36024
+ const routeApproved = useQuery(keys().routeApproved(squidRoute, allowanceInWei), async () => {
36025
+ // Approval is only needed for EVM chains
36026
+ if (getChainType(squidRoute?.params.fromChain) === ChainType.EVM) {
36027
+ return hasAllowance;
36028
+ }
36029
+ return true;
36030
+ }, {
36012
36031
  enabled: !!squidRoute &&
36013
36032
  !!sourceUserAddress &&
36014
- !allowanceQuery?.isPending &&
36033
+ !allowanceQuery?.isLoading &&
36015
36034
  allowanceQuery?.isFetched,
36016
36035
  });
36017
36036
  // USDT has a very specific way of handling approvals
@@ -36100,84 +36119,81 @@ const useApproval = ({ squidRoute, }) => {
36100
36119
  /**
36101
36120
  * Manually approve route if necessary
36102
36121
  */
36103
- const approveRoute = useMutation({
36104
- mutationFn: async () => {
36105
- try {
36106
- if (fromToken?.address === nativeEvmTokenAddress) {
36107
- return true;
36122
+ const approveRoute = useMutation(async () => {
36123
+ try {
36124
+ if (fromToken?.address === nativeEvmTokenAddress) {
36125
+ return true;
36126
+ }
36127
+ if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36128
+ await approveSpecificTokenToZero(fromToken);
36129
+ try {
36130
+ // If needed, we can switch the chain here
36131
+ // If already on the correct chain, this will do nothing
36132
+ await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36108
36133
  }
36109
- if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36110
- await approveSpecificTokenToZero(fromToken);
36111
- try {
36112
- // If needed, we can switch the chain here
36113
- // If already on the correct chain, this will do nothing
36114
- await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36115
- }
36116
- catch (error) {
36117
- console.error("Error switching network:", error);
36118
- }
36119
- let approveTx;
36120
- if (useIcs20) {
36121
- const channel = squidRoute.estimate.actions[0].data
36122
- .ibcChannel;
36123
- const ics20Interface = new ethers.Interface(ics20Abi);
36124
- const approveData = ics20Interface.encodeFunctionData("approve", [
36125
- squidRoute.params.fromAddress,
36126
- [
36127
- {
36128
- sourcePort: "transfer",
36129
- sourceChannel: channel,
36130
- spendLimit: [
36131
- {
36132
- denom: squidRoute.estimate.actions[0].fromToken
36133
- .originalAddress,
36134
- amount: squidRoute.params.fromAmount,
36135
- },
36136
- ],
36137
- allowList: [],
36138
- allowedPacketData: ["*"],
36139
- },
36140
- ],
36141
- ]);
36142
- approveTx = await evmSigner.sendTransaction({
36143
- to: squidRoute.transactionRequest.target,
36144
- data: approveData,
36145
- value: "0",
36146
- gasLimit: squidRoute.transactionRequest
36147
- .gasLimit,
36148
- gasPrice: squidRoute.transactionRequest
36149
- .gasPrice,
36150
- });
36151
- }
36152
- else {
36153
- approveTx = await squid.approveRoute({
36154
- route: squidRoute,
36155
- signer: evmSigner,
36156
- // For security reasons, we don't want to allow infinite approvals in our frontends
36157
- executionSettings: {
36158
- infiniteApproval: false,
36134
+ catch (error) {
36135
+ console.error("Error switching network:", error);
36136
+ }
36137
+ let approveTx;
36138
+ if (useIcs20) {
36139
+ const channel = squidRoute.estimate.actions[0].data
36140
+ .ibcChannel;
36141
+ const ics20Interface = new ethers.Interface(ics20Abi);
36142
+ const approveData = ics20Interface.encodeFunctionData("approve", [
36143
+ squidRoute.params.fromAddress,
36144
+ [
36145
+ {
36146
+ sourcePort: "transfer",
36147
+ sourceChannel: channel,
36148
+ spendLimit: [
36149
+ {
36150
+ denom: squidRoute.estimate.actions[0].fromToken
36151
+ .originalAddress,
36152
+ amount: squidRoute.params.fromAmount,
36153
+ },
36154
+ ],
36155
+ allowList: [],
36156
+ allowedPacketData: ["*"],
36159
36157
  },
36160
- });
36161
- }
36162
- if (isProblematicConnector(activeConnector)) {
36163
- await sleep(3_000);
36164
- }
36165
- await approveTx?.wait();
36166
- return true;
36158
+ ],
36159
+ ]);
36160
+ approveTx = await evmSigner.sendTransaction({
36161
+ to: squidRoute.transactionRequest.target,
36162
+ data: approveData,
36163
+ value: "0",
36164
+ gasLimit: squidRoute.transactionRequest
36165
+ .gasLimit,
36166
+ gasPrice: squidRoute.transactionRequest
36167
+ .gasPrice,
36168
+ });
36167
36169
  }
36168
- return false;
36169
- }
36170
- catch (error) {
36171
- // Keep the error in the console to debug future issues
36172
- console.error(error);
36173
- return false;
36170
+ else {
36171
+ approveTx = await squid.approveRoute({
36172
+ route: squidRoute,
36173
+ signer: evmSigner,
36174
+ // For security reasons, we don't want to allow infinite approvals in our frontends
36175
+ executionSettings: {
36176
+ infiniteApproval: false,
36177
+ },
36178
+ });
36179
+ }
36180
+ if (isProblematicConnector(activeConnector)) {
36181
+ await sleep(3_000);
36182
+ }
36183
+ await approveTx?.wait();
36184
+ return true;
36174
36185
  }
36175
- },
36186
+ return false;
36187
+ }
36188
+ catch (error) {
36189
+ // Keep the error in the console to debug future issues
36190
+ console.error(error);
36191
+ return false;
36192
+ }
36193
+ }, {
36176
36194
  onSuccess: async () => {
36177
36195
  await allowanceQuery?.refetch();
36178
- queryClient.invalidateQueries({
36179
- queryKey: getPrefixKey(QueryKeys.RouteApproved),
36180
- });
36196
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.RouteApproved));
36181
36197
  // After an approval, we refetch the transaction query with all required parameters
36182
36198
  // This is to ensure we're using the latest expiry timestamp
36183
36199
  if (squidRoute) {
@@ -39297,10 +39313,8 @@ const useExecuteTransaction = (squidRoute) => {
39297
39313
  }
39298
39314
  }, [cosmosSigner, fromChain]);
39299
39315
  const resetQueriesAfterTxSigned = () => {
39300
- queryClient.refetchQueries({ queryKey: getPrefixKey(QueryKeys.Balance) });
39301
- queryClient.invalidateQueries({
39302
- queryKey: getPrefixKey(QueryKeys.Transaction),
39303
- });
39316
+ queryClient.refetchQueries(getPrefixKey(QueryKeys.Balance));
39317
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Transaction));
39304
39318
  };
39305
39319
  const dispatchSignatureRequestEvent = useCallback((route) => {
39306
39320
  WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
@@ -39318,64 +39332,62 @@ const useExecuteTransaction = (squidRoute) => {
39318
39332
  txHash,
39319
39333
  }, findToken);
39320
39334
  }, [findToken]);
39321
- const swapMutationCosmos = useMutation({
39322
- mutationFn: async ({ id, route }) => {
39323
- const fromChainId = route?.params.fromChain;
39324
- if (cosmosSigner && fromChainId) {
39325
- try {
39326
- const signingClient = await getCosmosSignerClient();
39327
- const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39328
- if (signerAddress && signingClient && route) {
39329
- dispatchSignatureRequestEvent(route);
39330
- const tx$1 = (await squid?.executeRoute({
39331
- signer: signingClient,
39332
- signerAddress,
39333
- route,
39334
- }));
39335
- // set the tx state to loading, as soon as user signed the tx
39336
- setTransactionState({
39337
- txHash: "",
39338
- route,
39339
- status: TransactionStatus.ONGOING,
39340
- sourceStatus: TransactionStatus.ONGOING,
39341
- id,
39342
- });
39343
- // broadcast the signed tx to get hash and listen to events
39344
- const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39345
- const hash = response.transactionHash;
39346
- if (hash) {
39347
- resetQueriesAfterTxSigned();
39348
- }
39349
- // Dispatch event so it can be listened from outside the widget
39350
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39351
- const txParams = setTransactionState({
39352
- route,
39353
- txHash: hash,
39354
- userAddress: sourceUserAddress,
39355
- status: TransactionStatus.ONGOING,
39356
- sourceStatus: TransactionStatus.ONGOING,
39357
- axelarUrl: undefined,
39358
- id,
39335
+ const swapMutationCosmos = useMutation(async ({ id, route }) => {
39336
+ const fromChainId = route?.params.fromChain;
39337
+ if (cosmosSigner && fromChainId) {
39338
+ try {
39339
+ const signingClient = await getCosmosSignerClient();
39340
+ const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39341
+ if (signerAddress && signingClient && route) {
39342
+ dispatchSignatureRequestEvent(route);
39343
+ const tx$1 = (await squid?.executeRoute({
39344
+ signer: signingClient,
39345
+ signerAddress,
39346
+ route,
39347
+ }));
39348
+ // set the tx state to loading, as soon as user signed the tx
39349
+ setTransactionState({
39350
+ txHash: "",
39351
+ route,
39352
+ status: TransactionStatus.ONGOING,
39353
+ sourceStatus: TransactionStatus.ONGOING,
39354
+ id,
39355
+ });
39356
+ // broadcast the signed tx to get hash and listen to events
39357
+ const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39358
+ const hash = response.transactionHash;
39359
+ if (hash) {
39360
+ resetQueriesAfterTxSigned();
39361
+ }
39362
+ // Dispatch event so it can be listened from outside the widget
39363
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39364
+ const txParams = setTransactionState({
39365
+ route,
39366
+ txHash: hash,
39367
+ userAddress: sourceUserAddress,
39368
+ status: TransactionStatus.ONGOING,
39369
+ sourceStatus: TransactionStatus.ONGOING,
39370
+ axelarUrl: undefined,
39371
+ id,
39372
+ });
39373
+ if (txParams) {
39374
+ addSwapTransaction({
39375
+ ...txParams,
39376
+ params: route.params,
39377
+ estimate: route.estimate,
39359
39378
  });
39360
- if (txParams) {
39361
- addSwapTransaction({
39362
- ...txParams,
39363
- params: route.params,
39364
- estimate: route.estimate,
39365
- });
39366
- }
39367
- return response.code === 0;
39368
39379
  }
39380
+ return response.code === 0;
39369
39381
  }
39370
- catch (error) {
39371
- console.error("Error executing Cosmos transaction", error);
39372
- if (isUserRejectionError(normalizeError(error))) {
39373
- throw new Error("Request rejected");
39374
- }
39382
+ }
39383
+ catch (error) {
39384
+ console.error("Error executing Cosmos transaction", error);
39385
+ if (isUserRejectionError(normalizeError(error))) {
39386
+ throw new Error("Request rejected");
39375
39387
  }
39376
39388
  }
39377
- throw new Error("Need all parameters");
39378
- },
39389
+ }
39390
+ throw new Error("Need all parameters");
39379
39391
  });
39380
39392
  // If the transaction is replaced, we need to update the transaction hash
39381
39393
  // Transaction replaced can mean that the user has speed up the transaction for example
@@ -39428,126 +39440,97 @@ const useExecuteTransaction = (squidRoute) => {
39428
39440
  throw error;
39429
39441
  }
39430
39442
  }, [replaceSwapTransactionNonce, setTransactionState, sourceUserAddress]);
39431
- const swapMutationEvm = useMutation({
39432
- mutationFn: async ({ id, route }) => {
39433
- await changeNetworkIfNeeded.mutateAsync();
39434
- if (!route || !squid || !evmSigner) {
39435
- throw new Error("Need all parameters");
39436
- }
39437
- dispatchSignatureRequestEvent(route);
39438
- const txResponse = (await squid.executeRoute({
39439
- bypassBalanceChecks: true,
39440
- signer: evmSigner,
39443
+ const swapMutationEvm = useMutation(async ({ id, route }) => {
39444
+ await changeNetworkIfNeeded.mutateAsync();
39445
+ if (!route || !squid || !evmSigner) {
39446
+ throw new Error("Need all parameters");
39447
+ }
39448
+ dispatchSignatureRequestEvent(route);
39449
+ const txResponse = (await squid.executeRoute({
39450
+ bypassBalanceChecks: true,
39451
+ signer: evmSigner,
39452
+ route,
39453
+ }));
39454
+ let hash = txResponse.hash;
39455
+ if (activeConnector?.id === "safe") {
39456
+ hash = await getGnosisTransactionHash(txResponse.hash);
39457
+ }
39458
+ if (hash) {
39459
+ resetQueriesAfterTxSigned();
39460
+ }
39461
+ // Dispatch event so it can be listened from outside the widget
39462
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39463
+ if (route.transactionRequest) {
39464
+ const txParams = setTransactionState({
39441
39465
  route,
39442
- }));
39443
- let hash = txResponse.hash;
39444
- if (activeConnector?.id === "safe") {
39445
- hash = await getGnosisTransactionHash(txResponse.hash);
39466
+ txHash: hash,
39467
+ nonce: txResponse.nonce,
39468
+ userAddress: sourceUserAddress,
39469
+ status: TransactionStatus.INITIAL_LOADING,
39470
+ sourceStatus: TransactionStatus.ONGOING,
39471
+ axelarUrl: undefined,
39472
+ id,
39473
+ });
39474
+ if (txParams) {
39475
+ addSwapTransaction({
39476
+ ...txParams,
39477
+ params: route.params,
39478
+ estimate: route.estimate,
39479
+ });
39446
39480
  }
39447
- if (hash) {
39448
- resetQueriesAfterTxSigned();
39481
+ }
39482
+ try {
39483
+ if (isProblematicConnector(activeConnector)) {
39484
+ await sleep(3_000);
39449
39485
  }
39450
- // Dispatch event so it can be listened from outside the widget
39451
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39452
- if (route.transactionRequest) {
39453
- const txParams = setTransactionState({
39454
- route,
39455
- txHash: hash,
39456
- nonce: txResponse.nonce,
39457
- userAddress: sourceUserAddress,
39458
- status: TransactionStatus.INITIAL_LOADING,
39459
- sourceStatus: TransactionStatus.ONGOING,
39460
- axelarUrl: undefined,
39461
- id,
39462
- });
39463
- if (txParams) {
39464
- addSwapTransaction({
39465
- ...txParams,
39466
- params: route.params,
39467
- estimate: route.estimate,
39468
- });
39469
- }
39486
+ const response = await txResponse.wait();
39487
+ return response;
39488
+ }
39489
+ catch (error) {
39490
+ return handleTransactionReplacementError({
39491
+ error,
39492
+ route,
39493
+ status: TransactionStatus.INITIAL_LOADING,
39494
+ sourceStatus: TransactionStatus.ONGOING,
39495
+ userAddress: sourceUserAddress,
39496
+ axelarUrl: undefined,
39497
+ id,
39498
+ });
39499
+ }
39500
+ });
39501
+ const swapMutationSolana = useMutation(async ({ id, route }) => {
39502
+ try {
39503
+ if (!route) {
39504
+ throw new Error("Route is required");
39470
39505
  }
39471
- try {
39472
- if (isProblematicConnector(activeConnector)) {
39473
- await sleep(3_000);
39474
- }
39475
- const response = await txResponse.wait();
39476
- return response;
39506
+ if (!solanaSigner) {
39507
+ throw new Error("Solana signer is required");
39477
39508
  }
39478
- catch (error) {
39479
- return handleTransactionReplacementError({
39480
- error,
39481
- route,
39482
- status: TransactionStatus.INITIAL_LOADING,
39483
- sourceStatus: TransactionStatus.ONGOING,
39484
- userAddress: sourceUserAddress,
39485
- axelarUrl: undefined,
39486
- id,
39487
- });
39509
+ if (!route.params.fromAddress || !route.params.toAddress) {
39510
+ throw new Error("From or to address is required");
39488
39511
  }
39489
- },
39490
- });
39491
- const swapMutationSolana = useMutation({
39492
- mutationFn: async ({ id, route }) => {
39493
- try {
39494
- if (!route) {
39495
- throw new Error("Route is required");
39496
- }
39497
- if (!solanaSigner) {
39498
- throw new Error("Solana signer is required");
39512
+ const isDirectTransfer = isDepositRoute(route);
39513
+ // Means it's a transfer to a deposit address
39514
+ // Instead of a Swap/Contract call using a DEX like Jupiter
39515
+ if (isDirectTransfer) {
39516
+ // Get the deposit address from the squidRoute
39517
+ const depositData = useDepositAddressStore.getState().deposit;
39518
+ // Validate params
39519
+ if (!depositData?.depositAddress) {
39520
+ throw new Error("Deposit address is required");
39499
39521
  }
39500
- if (!route.params.fromAddress || !route.params.toAddress) {
39501
- throw new Error("From or to address is required");
39502
- }
39503
- const isDirectTransfer = isDepositRoute(route);
39504
- // Means it's a transfer to a deposit address
39505
- // Instead of a Swap/Contract call using a DEX like Jupiter
39506
- if (isDirectTransfer) {
39507
- // Get the deposit address from the squidRoute
39508
- const depositData = useDepositAddressStore.getState().deposit;
39509
- // Validate params
39510
- if (!depositData?.depositAddress) {
39511
- throw new Error("Deposit address is required");
39512
- }
39513
- const signature = await executeSolanaTransfer({
39514
- amount: BigInt(route.params.fromAmount),
39515
- target: depositData.depositAddress,
39516
- signer: solanaSigner,
39517
- connection: solanaConnection,
39518
- sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39519
- onSigned: (txHash) => {
39520
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39521
- const txParams = setTransactionState({
39522
- route,
39523
- txHash,
39524
- transactionIdForStatus: depositData.chainflipStatusTrackingId,
39525
- userAddress: sourceUserAddress,
39526
- status: TransactionStatus.INITIAL_LOADING,
39527
- sourceStatus: TransactionStatus.ONGOING,
39528
- id,
39529
- });
39530
- if (txParams) {
39531
- addSwapTransaction({
39532
- ...txParams,
39533
- params: route.params,
39534
- estimate: route.estimate,
39535
- });
39536
- }
39537
- },
39538
- });
39539
- return signature;
39540
- }
39541
- const signature = await executeSolanaSwap({
39542
- route,
39522
+ const signature = await executeSolanaTransfer({
39523
+ amount: BigInt(route.params.fromAmount),
39524
+ target: depositData.depositAddress,
39543
39525
  signer: solanaSigner,
39544
39526
  connection: solanaConnection,
39527
+ sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39545
39528
  onSigned: (txHash) => {
39546
39529
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39547
39530
  const txParams = setTransactionState({
39548
39531
  route,
39549
39532
  txHash,
39550
- transactionIdForStatus: undefined,
39533
+ transactionIdForStatus: depositData.chainflipStatusTrackingId,
39551
39534
  userAddress: sourceUserAddress,
39552
39535
  status: TransactionStatus.INITIAL_LOADING,
39553
39536
  sourceStatus: TransactionStatus.ONGOING,
@@ -39564,13 +39547,39 @@ const useExecuteTransaction = (squidRoute) => {
39564
39547
  });
39565
39548
  return signature;
39566
39549
  }
39567
- catch (error) {
39568
- console.error("Solana transaction failed:", error);
39569
- throw error instanceof Error
39570
- ? error
39571
- : new Error("Failed to execute Solana transaction");
39572
- }
39573
- },
39550
+ const signature = await executeSolanaSwap({
39551
+ route,
39552
+ signer: solanaSigner,
39553
+ connection: solanaConnection,
39554
+ onSigned: (txHash) => {
39555
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39556
+ const txParams = setTransactionState({
39557
+ route,
39558
+ txHash,
39559
+ transactionIdForStatus: undefined,
39560
+ userAddress: sourceUserAddress,
39561
+ status: TransactionStatus.INITIAL_LOADING,
39562
+ sourceStatus: TransactionStatus.ONGOING,
39563
+ id,
39564
+ });
39565
+ if (txParams) {
39566
+ addSwapTransaction({
39567
+ ...txParams,
39568
+ params: route.params,
39569
+ estimate: route.estimate,
39570
+ });
39571
+ }
39572
+ },
39573
+ });
39574
+ return signature;
39575
+ }
39576
+ catch (error) {
39577
+ console.error("Solana transaction failed:", error);
39578
+ throw error instanceof Error
39579
+ ? error
39580
+ : new Error("Failed to execute Solana transaction");
39581
+ }
39582
+ }, {
39574
39583
  onError: (error, variables) => {
39575
39584
  const currentTx = getTransaction(variables.id);
39576
39585
  const errorObject = getTransactionError(error);
@@ -39591,9 +39600,7 @@ const useExecuteTransaction = (squidRoute) => {
39591
39600
  },
39592
39601
  onSuccess: (_data, variables) => {
39593
39602
  const currentTx = getTransaction(variables.id);
39594
- queryClient.invalidateQueries({
39595
- queryKey: getPrefixKey(QueryKeys.Balances),
39596
- });
39603
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39597
39604
  if (isSameChain && currentTx?.transactionId) {
39598
39605
  replaceSwapTransactionStatus({
39599
39606
  transactionId: currentTx.transactionId,
@@ -39610,207 +39617,197 @@ const useExecuteTransaction = (squidRoute) => {
39610
39617
  });
39611
39618
  },
39612
39619
  });
39613
- const swapMutationBitcoin = useMutation({
39614
- mutationFn: async ({ id, route }) => {
39615
- const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39616
- if (!depositAddress) {
39617
- throw new Error(`Invalid deposit address: ${depositAddress}`);
39618
- }
39619
- if (!sendAmount) {
39620
- throw new Error(`Invalid send amount: ${sendAmount}`);
39621
- }
39622
- const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39623
- await changeNetworkIfNeeded.mutateAsync();
39624
- if (allParamsValid) {
39625
- dispatchSignatureRequestEvent(route);
39626
- const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39627
- if (txHash) {
39628
- resetQueriesAfterTxSigned();
39629
- }
39630
- // Dispatch event so it can be listened from outside the widget
39631
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39632
- if (route.transactionRequest) {
39633
- const txParams = setTransactionState({
39634
- route,
39635
- txHash,
39636
- // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39637
- // instead of the Bitcoin transaction hash
39638
- transactionIdForStatus: chainflipStatusTrackingId,
39639
- userAddress: sourceUserAddress,
39640
- status: TransactionStatus.INITIAL_LOADING,
39641
- sourceStatus: TransactionStatus.ONGOING,
39642
- axelarUrl: undefined,
39643
- id,
39644
- });
39645
- if (txParams) {
39646
- addSwapTransaction({
39647
- ...txParams,
39648
- params: route.params,
39649
- estimate: route.estimate,
39650
- });
39651
- }
39652
- }
39653
- }
39654
- else {
39655
- throw new Error("Need all parameters");
39656
- }
39657
- },
39658
- });
39659
- const swapMutationXrpl = useMutation({
39660
- mutationFn: async ({ id, route }) => {
39661
- if (!route?.transactionRequest || !xrplSigner) {
39662
- throw new Error("Need all parameters");
39663
- }
39664
- if (route.transactionRequest.type !== SquidDataType.OnChainExecution) {
39665
- throw new Error("Invalid route type");
39666
- }
39667
- const { data } = route.transactionRequest;
39668
- const paymentTx = parseXrplPaymentTx(data);
39669
- if (!paymentTx)
39670
- throw new Error("Could not parse transaction");
39671
- const fromChainId = route.params.fromChain;
39672
- const xrplNetwork = getXrplNetwork(fromChainId);
39673
- if (xrplNetwork == null) {
39674
- throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39675
- }
39676
- const txRes = await xrplSigner.signAndSubmit({
39677
- tx: paymentTx,
39678
- network: xrplNetwork,
39679
- });
39680
- const txParams = setTransactionState({
39681
- txHash: txRes.hash,
39682
- id,
39683
- sourceStatus: TransactionStatus.ONGOING,
39684
- status: TransactionStatus.ONGOING,
39685
- route: route,
39686
- userAddress: sourceUserAddress,
39687
- });
39688
- if (txParams && route) {
39689
- addSwapTransaction({
39690
- ...txParams,
39691
- params: route.params,
39692
- estimate: route.estimate,
39693
- });
39694
- }
39695
- if (txRes.status !== XrplTxStatus.SUCCESS) {
39696
- throw new Error(`Transaction failed with status: ${txRes.status}`);
39697
- }
39698
- },
39699
- });
39700
- const swapMutationSui = useMutation({
39701
- mutationFn: async ({ id, route }) => {
39702
- if (!route || !suiSigner || !fromChain) {
39703
- throw new Error("Need all parameters");
39704
- }
39705
- if (route.transactionRequest?.type !== SquidDataType.OnChainExecution) {
39706
- throw new Error("Invalid route type");
39707
- }
39708
- const suiWalletState = connectedWalletsByChainType[ChainType.SUI];
39709
- if (!suiWalletState.account) {
39710
- throw new Error("Sui wallet is missing account data");
39711
- }
39712
- const fromChainId = route.params.fromChain;
39713
- const suiChain = getSuiChain(fromChainId);
39714
- if (!suiChain) {
39715
- throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39716
- }
39717
- const suiClient = await getClient(fromChain);
39718
- const txJson = route.transactionRequest.data;
39719
- const tx = Transaction$2.from(txJson);
39720
- const signedTx = await suiSigner.signTransaction({
39721
- transaction: tx,
39722
- account: suiWalletState.account,
39723
- chain: suiChain,
39724
- });
39725
- // execute transaction without waiting for confirmation
39726
- const txResponse = await suiClient.executeTransactionBlock({
39727
- signature: signedTx.signature,
39728
- transactionBlock: signedTx.bytes,
39729
- });
39730
- const txHash = txResponse.digest;
39620
+ const swapMutationBitcoin = useMutation(async ({ id, route }) => {
39621
+ const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39622
+ if (!depositAddress) {
39623
+ throw new Error(`Invalid deposit address: ${depositAddress}`);
39624
+ }
39625
+ if (!sendAmount) {
39626
+ throw new Error(`Invalid send amount: ${sendAmount}`);
39627
+ }
39628
+ const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39629
+ await changeNetworkIfNeeded.mutateAsync();
39630
+ if (allParamsValid) {
39631
+ dispatchSignatureRequestEvent(route);
39632
+ const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39731
39633
  if (txHash) {
39732
39634
  resetQueriesAfterTxSigned();
39733
39635
  }
39636
+ // Dispatch event so it can be listened from outside the widget
39734
39637
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39735
- const txParams = setTransactionState({
39736
- route,
39737
- txHash,
39738
- userAddress: sourceUserAddress,
39739
- status: TransactionStatus.INITIAL_LOADING,
39740
- sourceStatus: TransactionStatus.ONGOING,
39741
- id,
39742
- });
39743
- if (txParams) {
39744
- addSwapTransaction({
39745
- ...txParams,
39746
- params: route.params,
39747
- estimate: route.estimate,
39638
+ if (route.transactionRequest) {
39639
+ const txParams = setTransactionState({
39640
+ route,
39641
+ txHash,
39642
+ // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39643
+ // instead of the Bitcoin transaction hash
39644
+ transactionIdForStatus: chainflipStatusTrackingId,
39645
+ userAddress: sourceUserAddress,
39646
+ status: TransactionStatus.INITIAL_LOADING,
39647
+ sourceStatus: TransactionStatus.ONGOING,
39648
+ axelarUrl: undefined,
39649
+ id,
39748
39650
  });
39651
+ if (txParams) {
39652
+ addSwapTransaction({
39653
+ ...txParams,
39654
+ params: route.params,
39655
+ estimate: route.estimate,
39656
+ });
39657
+ }
39749
39658
  }
39750
- // wait for transaction confirmation
39751
- await suiClient.waitForTransaction({
39752
- digest: txHash,
39753
- });
39754
- },
39659
+ }
39660
+ else {
39661
+ throw new Error("Need all parameters");
39662
+ }
39755
39663
  });
39756
- const swapMutationStellar = useMutation({
39757
- mutationFn: async ({ id, route }) => {
39758
- if (!stellarSigner || !route || !squid || !fromChain) {
39759
- throw new Error("Need all parameters");
39760
- }
39761
- const fromChainId = route.params.fromChain;
39762
- const stellarNetwork = getStellarNetwork(fromChainId);
39763
- if (stellarNetwork == null) {
39764
- throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39765
- }
39766
- const { data: xdrHex, gasPrice } = route.transactionRequest;
39767
- const { address } = await stellarSigner.getAddress();
39768
- const client = await getClient(fromChain);
39769
- const account = await client.getAccount(address);
39770
- const operation = xdr.Operation.fromXDR(xdrHex, "hex");
39771
- const builtTransaction = new TransactionBuilder(account, {
39772
- fee: gasPrice || (BigInt(BASE_FEE) * BigInt(2)).toString(),
39773
- networkPassphrase: stellarNetwork,
39774
- })
39775
- .addOperation(operation)
39776
- .setTimeout(300)
39777
- .build();
39778
- const preparedTransaction = await client.prepareTransaction(builtTransaction);
39779
- const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39780
- networkPassphrase: stellarNetwork,
39664
+ const swapMutationXrpl = useMutation(async ({ id, route }) => {
39665
+ if (!route?.transactionRequest || !xrplSigner) {
39666
+ throw new Error("Need all parameters");
39667
+ }
39668
+ if (route.transactionRequest.type !== SquidDataType.OnChainExecution) {
39669
+ throw new Error("Invalid route type");
39670
+ }
39671
+ const { data } = route.transactionRequest;
39672
+ const paymentTx = parseXrplPaymentTx(data);
39673
+ if (!paymentTx)
39674
+ throw new Error("Could not parse transaction");
39675
+ const fromChainId = route.params.fromChain;
39676
+ const xrplNetwork = getXrplNetwork(fromChainId);
39677
+ if (xrplNetwork == null) {
39678
+ throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39679
+ }
39680
+ const txRes = await xrplSigner.signAndSubmit({
39681
+ tx: paymentTx,
39682
+ network: xrplNetwork,
39683
+ });
39684
+ const txParams = setTransactionState({
39685
+ txHash: txRes.hash,
39686
+ id,
39687
+ sourceStatus: TransactionStatus.ONGOING,
39688
+ status: TransactionStatus.ONGOING,
39689
+ route: route,
39690
+ userAddress: sourceUserAddress,
39691
+ });
39692
+ if (txParams && route) {
39693
+ addSwapTransaction({
39694
+ ...txParams,
39695
+ params: route.params,
39696
+ estimate: route.estimate,
39781
39697
  });
39782
- const signedTransaction = new Transaction$1(signedTxXdr, stellarNetwork);
39783
- // get hash before submitting
39784
- const hash = signedTransaction.hash().toString("hex");
39785
- if (hash) {
39786
- resetQueriesAfterTxSigned();
39787
- }
39788
- // Dispatch event so it can be listened from outside the widget
39789
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39790
- const txParams = setTransactionState({
39791
- route,
39792
- txHash: hash,
39793
- userAddress: sourceUserAddress,
39794
- status: TransactionStatus.INITIAL_LOADING,
39795
- sourceStatus: TransactionStatus.ONGOING,
39796
- id,
39698
+ }
39699
+ if (txRes.status !== XrplTxStatus.SUCCESS) {
39700
+ throw new Error(`Transaction failed with status: ${txRes.status}`);
39701
+ }
39702
+ }, {});
39703
+ const swapMutationSui = useMutation(async ({ id, route }) => {
39704
+ if (!route || !suiSigner || !fromChain) {
39705
+ throw new Error("Need all parameters");
39706
+ }
39707
+ if (route.transactionRequest?.type !== SquidDataType.OnChainExecution) {
39708
+ throw new Error("Invalid route type");
39709
+ }
39710
+ const suiWalletState = connectedWalletsByChainType[ChainType.SUI];
39711
+ if (!suiWalletState.account) {
39712
+ throw new Error("Sui wallet is missing account data");
39713
+ }
39714
+ const fromChainId = route.params.fromChain;
39715
+ const suiChain = getSuiChain(fromChainId);
39716
+ if (!suiChain) {
39717
+ throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39718
+ }
39719
+ const suiClient = await getClient(fromChain);
39720
+ const txJson = route.transactionRequest.data;
39721
+ const tx = Transaction$2.from(txJson);
39722
+ const signedTx = await suiSigner.signTransaction({
39723
+ transaction: tx,
39724
+ account: suiWalletState.account,
39725
+ chain: suiChain,
39726
+ });
39727
+ // execute transaction without waiting for confirmation
39728
+ const txResponse = await suiClient.executeTransactionBlock({
39729
+ signature: signedTx.signature,
39730
+ transactionBlock: signedTx.bytes,
39731
+ });
39732
+ const txHash = txResponse.digest;
39733
+ if (txHash) {
39734
+ resetQueriesAfterTxSigned();
39735
+ }
39736
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39737
+ const txParams = setTransactionState({
39738
+ route,
39739
+ txHash,
39740
+ userAddress: sourceUserAddress,
39741
+ status: TransactionStatus.INITIAL_LOADING,
39742
+ sourceStatus: TransactionStatus.ONGOING,
39743
+ id,
39744
+ });
39745
+ if (txParams) {
39746
+ addSwapTransaction({
39747
+ ...txParams,
39748
+ params: route.params,
39749
+ estimate: route.estimate,
39797
39750
  });
39798
- if (txParams) {
39799
- addSwapTransaction({
39800
- ...txParams,
39801
- params: route.params,
39802
- estimate: route.estimate,
39803
- });
39804
- }
39805
- const sentTransaction = await client.sendTransaction(signedTransaction);
39806
- await client.waitForTransaction(sentTransaction.hash);
39807
- },
39808
- });
39751
+ }
39752
+ // wait for transaction confirmation
39753
+ await suiClient.waitForTransaction({
39754
+ digest: txHash,
39755
+ });
39756
+ }, {});
39757
+ const swapMutationStellar = useMutation(async ({ id, route }) => {
39758
+ if (!stellarSigner || !route || !squid || !fromChain) {
39759
+ throw new Error("Need all parameters");
39760
+ }
39761
+ const fromChainId = route.params.fromChain;
39762
+ const stellarNetwork = getStellarNetwork(fromChainId);
39763
+ if (stellarNetwork == null) {
39764
+ throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39765
+ }
39766
+ const { data: xdrHex, gasPrice } = route.transactionRequest;
39767
+ const { address } = await stellarSigner.getAddress();
39768
+ const client = await getClient(fromChain);
39769
+ const account = await client.getAccount(address);
39770
+ const operation = xdr.Operation.fromXDR(xdrHex, "hex");
39771
+ const builtTransaction = new TransactionBuilder(account, {
39772
+ fee: gasPrice || (BigInt(BASE_FEE) * BigInt(2)).toString(),
39773
+ networkPassphrase: stellarNetwork,
39774
+ })
39775
+ .addOperation(operation)
39776
+ .setTimeout(300)
39777
+ .build();
39778
+ const preparedTransaction = await client.prepareTransaction(builtTransaction);
39779
+ const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39780
+ networkPassphrase: stellarNetwork,
39781
+ });
39782
+ const signedTransaction = new Transaction$1(signedTxXdr, stellarNetwork);
39783
+ // get hash before submitting
39784
+ const hash = signedTransaction.hash().toString("hex");
39785
+ if (hash) {
39786
+ resetQueriesAfterTxSigned();
39787
+ }
39788
+ // Dispatch event so it can be listened from outside the widget
39789
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39790
+ const txParams = setTransactionState({
39791
+ route,
39792
+ txHash: hash,
39793
+ userAddress: sourceUserAddress,
39794
+ status: TransactionStatus.INITIAL_LOADING,
39795
+ sourceStatus: TransactionStatus.ONGOING,
39796
+ id,
39797
+ });
39798
+ if (txParams) {
39799
+ addSwapTransaction({
39800
+ ...txParams,
39801
+ params: route.params,
39802
+ estimate: route.estimate,
39803
+ });
39804
+ }
39805
+ const sentTransaction = await client.sendTransaction(signedTransaction);
39806
+ await client.waitForTransaction(sentTransaction.hash);
39807
+ }, {});
39809
39808
  const handleTransactionSuccess = useCallback((id) => {
39810
39809
  const currentTx = getTransaction(id);
39811
- queryClient.invalidateQueries({
39812
- queryKey: getPrefixKey(QueryKeys.Balances),
39813
- });
39810
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39814
39811
  if (isSameChain && currentTx?.transactionId) {
39815
39812
  replaceSwapTransactionStatus({
39816
39813
  transactionId: currentTx.transactionId,
@@ -39862,39 +39859,38 @@ const useExecuteTransaction = (squidRoute) => {
39862
39859
  setTransactionStoreState,
39863
39860
  squidRoute,
39864
39861
  ]);
39865
- const swapMutation = useMutation({
39866
- mutationFn: async (mutationParams) => {
39867
- if (!mutationParams.route)
39868
- throw new Error("route is required");
39869
- const sourceChain = findChain(mutationParams.route.params?.fromChain);
39870
- if (!sourceChain)
39871
- throw new Error("Could not find source chain");
39872
- switch (sourceChain.chainType) {
39873
- case ChainType.COSMOS: {
39874
- return swapMutationCosmos.mutateAsync(mutationParams);
39875
- }
39876
- case ChainType.EVM: {
39877
- return swapMutationEvm.mutateAsync(mutationParams);
39878
- }
39879
- case ChainType.BTC: {
39880
- return swapMutationBitcoin.mutateAsync(mutationParams);
39881
- }
39882
- case ChainType.SOLANA: {
39883
- return swapMutationSolana.mutateAsync(mutationParams);
39884
- }
39885
- case ChainType.SUI: {
39886
- return swapMutationSui.mutateAsync(mutationParams);
39887
- }
39888
- case ChainType.XRPL: {
39889
- return swapMutationXrpl.mutateAsync(mutationParams);
39890
- }
39891
- case ChainType.STELLAR: {
39892
- return swapMutationStellar.mutateAsync(mutationParams);
39893
- }
39894
- default:
39895
- throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39862
+ const swapMutation = useMutation(async (mutationParams) => {
39863
+ if (!mutationParams.route)
39864
+ throw new Error("route is required");
39865
+ const sourceChain = findChain(mutationParams.route.params?.fromChain);
39866
+ if (!sourceChain)
39867
+ throw new Error("Could not find source chain");
39868
+ switch (sourceChain.chainType) {
39869
+ case ChainType.COSMOS: {
39870
+ return swapMutationCosmos.mutateAsync(mutationParams);
39896
39871
  }
39897
- },
39872
+ case ChainType.EVM: {
39873
+ return swapMutationEvm.mutateAsync(mutationParams);
39874
+ }
39875
+ case ChainType.BTC: {
39876
+ return swapMutationBitcoin.mutateAsync(mutationParams);
39877
+ }
39878
+ case ChainType.SOLANA: {
39879
+ return swapMutationSolana.mutateAsync(mutationParams);
39880
+ }
39881
+ case ChainType.SUI: {
39882
+ return swapMutationSui.mutateAsync(mutationParams);
39883
+ }
39884
+ case ChainType.XRPL: {
39885
+ return swapMutationXrpl.mutateAsync(mutationParams);
39886
+ }
39887
+ case ChainType.STELLAR: {
39888
+ return swapMutationStellar.mutateAsync(mutationParams);
39889
+ }
39890
+ default:
39891
+ throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39892
+ }
39893
+ }, {
39898
39894
  onMutate: (variables) => {
39899
39895
  useTransactionStore.setState({
39900
39896
  txLocalId: variables.id,
@@ -39943,7 +39939,7 @@ const useExecuteTransaction = (squidRoute) => {
39943
39939
  toToken,
39944
39940
  toChain,
39945
39941
  fromChain,
39946
- isPending: swapMutation.isPending,
39942
+ isLoading: swapMutation.isLoading,
39947
39943
  error: swapMutation.error,
39948
39944
  };
39949
39945
  };
@@ -40004,59 +40000,57 @@ const useGetRoute = () => {
40004
40000
  * These data will be used to trigger the transaction
40005
40001
  * @returns {Route} Route data
40006
40002
  */
40007
- return useMutation({
40008
- mutationFn: async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40009
- if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40010
- return undefined;
40011
- }
40012
- // Dispatch requestQuote event
40013
- dispatchRequestQuoteEvent({
40014
- fromChain,
40015
- toChain,
40016
- fromToken: fromToken.address,
40017
- toToken: toToken.address,
40018
- fromAmount: fromPrice,
40019
- fromAddress: sourceUserAddress,
40020
- toAddress: destinationAddress,
40021
- });
40022
- const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40023
- const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40024
- const fromTokenAddress = fromToken.address;
40025
- const toTokenAddress = toToken.address;
40026
- const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40027
- const fromAddress = sourceUserAddress ??
40028
- chainTypeToZeroAddressMap[fromChainType ?? ChainType.EVM];
40029
- const params = {
40030
- fromChain,
40031
- fromToken: fromTokenAddress,
40032
- fromAddress,
40033
- fromAmount,
40034
- toChain,
40035
- toToken: toTokenAddress,
40036
- toAddress: destinationAddress ?? "",
40037
- quoteOnly,
40038
- slippage: config.slippage === 0 ? undefined : config.slippage,
40039
- bypassGuardrails,
40040
- preHook,
40041
- postHook,
40042
- };
40043
- // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40044
- if (cosmosFallbackAddresses &&
40045
- cosmosFallbackAddresses.length > 0 &&
40046
- cosmosFallbackAddresses[0].address) {
40047
- params.fallbackAddresses = cosmosFallbackAddresses;
40048
- }
40049
- const { route } = await squid.getRoute({
40050
- ...params,
40051
- });
40052
- // Cache the route data
40053
- // Useful when the getRoute mutation is called from another hook
40054
- queryClient.setQueryData(keys().transaction(fromChain, toChain, toToken.address, fromToken.address, fromPrice, config.slippage, config.enableGetGasOnDestination, sourceUserAddress, config.degenMode, destinationAddress, swapRoute?.fallbackAddress, quoteOnly, fromChainType, config.preHook, config.postHook), route);
40055
- return route;
40056
- },
40003
+ return useMutation(async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40004
+ if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40005
+ return undefined;
40006
+ }
40007
+ // Dispatch requestQuote event
40008
+ dispatchRequestQuoteEvent({
40009
+ fromChain,
40010
+ toChain,
40011
+ fromToken: fromToken.address,
40012
+ toToken: toToken.address,
40013
+ fromAmount: fromPrice,
40014
+ fromAddress: sourceUserAddress,
40015
+ toAddress: destinationAddress,
40016
+ });
40017
+ const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40018
+ const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40019
+ const fromTokenAddress = fromToken.address;
40020
+ const toTokenAddress = toToken.address;
40021
+ const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40022
+ const fromAddress = sourceUserAddress ??
40023
+ chainTypeToZeroAddressMap[fromChainType ?? ChainType.EVM];
40024
+ const params = {
40025
+ fromChain,
40026
+ fromToken: fromTokenAddress,
40027
+ fromAddress,
40028
+ fromAmount,
40029
+ toChain,
40030
+ toToken: toTokenAddress,
40031
+ toAddress: destinationAddress ?? "",
40032
+ quoteOnly,
40033
+ slippage: config.slippage === 0 ? undefined : config.slippage,
40034
+ bypassGuardrails,
40035
+ preHook,
40036
+ postHook,
40037
+ };
40038
+ // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40039
+ if (cosmosFallbackAddresses &&
40040
+ cosmosFallbackAddresses.length > 0 &&
40041
+ cosmosFallbackAddresses[0].address) {
40042
+ params.fallbackAddresses = cosmosFallbackAddresses;
40043
+ }
40044
+ const { route } = await squid.getRoute({
40045
+ ...params,
40046
+ });
40047
+ // Cache the route data
40048
+ // Useful when the getRoute mutation is called from another hook
40049
+ queryClient.setQueryData(keys().transaction(fromChain, toChain, toToken.address, fromToken.address, fromPrice, config.slippage, config.enableGetGasOnDestination, sourceUserAddress, config.degenMode, destinationAddress, swapRoute?.fallbackAddress, quoteOnly, fromChainType, config.preHook, config.postHook), route);
40050
+ return route;
40057
40051
  });
40058
40052
  };
40059
- const useGetRouteWrapper = ({ enabled, gcTime = 5 * 60 * 1000, // 5 minutes
40053
+ const useGetRouteWrapper = ({ enabled, cacheTime = 5 * 60 * 1000, // 5 minutes
40060
40054
  staleTime = 60 * 1000, // 1 minute
40061
40055
  refetchOnWindowFocus = (query) => Date.now() - query.state.dataUpdatedAt > 30000, // Update if older than 30 seconds, when window is focused
40062
40056
  refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true, }) => {
@@ -40106,27 +40100,25 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40106
40100
  * These data will be used to trigger the transaction
40107
40101
  * @returns {Route} Route data
40108
40102
  */
40109
- const squidRoute = useQuery({
40110
- queryKey: squidRouteQueryKeys,
40111
- queryFn: async () => {
40112
- const route = await getRouteMutation.mutateAsync({
40113
- fromChain: fromChain?.chainId,
40114
- toChain: toChain?.chainId,
40115
- fromToken,
40116
- toToken,
40117
- sourceUserAddress,
40118
- destinationAddress,
40119
- fromPrice,
40120
- bypassGuardrails: config.degenMode,
40121
- quoteOnly,
40122
- fromChainType: fromChain?.chainType,
40123
- postHook: config.postHook,
40124
- preHook: config.preHook,
40125
- });
40126
- return route;
40127
- },
40103
+ const squidRoute = useQuery(squidRouteQueryKeys, async () => {
40104
+ const route = await getRouteMutation.mutateAsync({
40105
+ fromChain: fromChain?.chainId,
40106
+ toChain: toChain?.chainId,
40107
+ fromToken,
40108
+ toToken,
40109
+ sourceUserAddress,
40110
+ destinationAddress,
40111
+ fromPrice,
40112
+ bypassGuardrails: config.degenMode,
40113
+ quoteOnly,
40114
+ fromChainType: fromChain?.chainType,
40115
+ postHook: config.postHook,
40116
+ preHook: config.preHook,
40117
+ });
40118
+ return route;
40119
+ }, {
40128
40120
  enabled: queryEnabled,
40129
- gcTime,
40121
+ cacheTime,
40130
40122
  staleTime,
40131
40123
  refetchOnWindowFocus,
40132
40124
  refetchIntervalInBackground,
@@ -40135,7 +40127,7 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40135
40127
  /**
40136
40128
  * If last updated data is older than X seconds and the query is currently loading, show loading indicator
40137
40129
  */
40138
- const showLoading = squidRoute.isFetching || squidRoute.isRefetching;
40130
+ const showLoading = useMemo(() => squidRoute.isFetching || squidRoute.isRefetching, [squidRoute.isFetching, squidRoute.isRefetching]);
40139
40131
  return {
40140
40132
  squidRoute,
40141
40133
  showLoading,
@@ -40167,7 +40159,7 @@ function useSendTransactionStatus({ chain, txHash, }) {
40167
40159
  transactionId: txHash,
40168
40160
  txType: HistoryTxType.SEND,
40169
40161
  });
40170
- const { data: status, isSuccess, isError, } = useQuery({
40162
+ const { data: status } = useQuery({
40171
40163
  queryKey: keys().sendTransactionStatus(txHash, chain?.chainId),
40172
40164
  queryFn: async () => {
40173
40165
  if (!chain || !txHash)
@@ -40177,30 +40169,17 @@ function useSendTransactionStatus({ chain, txHash, }) {
40177
40169
  txHash,
40178
40170
  });
40179
40171
  },
40180
- refetchInterval: chain
40181
- ? getSendTxStatusRefetchInterval(chain.chainType)
40182
- : false,
40183
- enabled: !!chain &&
40184
- !!txHash &&
40185
- !isTransactionComplete &&
40186
- !!currentHistoryItem &&
40187
- !isHistoryTransactionEnded({
40188
- data: currentHistoryItem?.data,
40189
- txType: HistoryTxType.SEND,
40190
- }),
40191
- });
40192
- useEffect(() => {
40193
- if (isSuccess) {
40194
- setIsTransactionComplete(status !== SendTransactionStatus.ONGOING);
40195
- if (status != null && !!txHash) {
40172
+ onSuccess: (txStatus) => {
40173
+ setIsTransactionComplete(txStatus !== SendTransactionStatus.ONGOING);
40174
+ if (txStatus != null && !!txHash) {
40196
40175
  replaceTransactionStatus({
40197
40176
  txType: HistoryTxType.SEND,
40198
- status: status,
40177
+ status: txStatus,
40199
40178
  hash: txHash,
40200
40179
  });
40201
40180
  }
40202
- }
40203
- if (isError) {
40181
+ },
40182
+ onError() {
40204
40183
  setIsTransactionComplete(true);
40205
40184
  if (txHash) {
40206
40185
  replaceTransactionStatus({
@@ -40209,8 +40188,19 @@ function useSendTransactionStatus({ chain, txHash, }) {
40209
40188
  hash: txHash,
40210
40189
  });
40211
40190
  }
40212
- }
40213
- }, [isError, isSuccess, replaceTransactionStatus, status, txHash]);
40191
+ },
40192
+ refetchInterval: chain
40193
+ ? getSendTxStatusRefetchInterval(chain.chainType)
40194
+ : false,
40195
+ enabled: !!chain &&
40196
+ !!txHash &&
40197
+ !isTransactionComplete &&
40198
+ !!currentHistoryItem &&
40199
+ !isHistoryTransactionEnded({
40200
+ data: currentHistoryItem?.data,
40201
+ txType: HistoryTxType.SEND,
40202
+ }),
40203
+ });
40214
40204
  return {
40215
40205
  status: status ?? currentHistoryItem?.data?.status,
40216
40206
  };
@@ -40244,9 +40234,7 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40244
40234
  apiUrl: latestConfig.apiUrl,
40245
40235
  });
40246
40236
  }, [transaction]);
40247
- const transactionStatusQuery = useQuery({
40248
- queryKey: keys().swapTransactionStatus(transaction?.transactionId),
40249
- queryFn: fetchTransactionStatusWithLatestConfig,
40237
+ const transactionStatusQuery = useQuery(keys().swapTransactionStatus(transaction?.transactionId), fetchTransactionStatusWithLatestConfig, {
40250
40238
  enabled: enabled &&
40251
40239
  transaction?.transactionId !== "0" &&
40252
40240
  !!transaction?.transactionId &&
@@ -40260,12 +40248,12 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40260
40248
  data: currentHistoryItem?.data,
40261
40249
  txType: HistoryTxType.SWAP,
40262
40250
  }),
40263
- refetchInterval({ state }) {
40251
+ refetchInterval(statusResponse) {
40264
40252
  // If the status response is something telling that the transaction
40265
40253
  // is finished, then store transaction history state if success
40266
40254
  // And return false to indicate refetcher to stop
40267
- if (state.data &&
40268
- transactionEndStatuses.includes(getTransactionStatus(state.data) ?? "")) {
40255
+ if (statusResponse &&
40256
+ transactionEndStatuses.includes(getTransactionStatus(statusResponse) ?? "")) {
40269
40257
  return false;
40270
40258
  }
40271
40259
  return refetchInterval; // Had to handle a variable here because after onError, we want the interval to stop
@@ -40274,10 +40262,7 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40274
40262
  retryDelay: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 5000 : 3000,
40275
40263
  retry: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 6 : retry,
40276
40264
  refetchOnWindowFocus,
40277
- });
40278
- useEffect(() => {
40279
- if (transactionStatusQuery.isSuccess && transactionStatusQuery.data) {
40280
- const statusResponse = transactionStatusQuery.data;
40265
+ onSuccess: (statusResponse) => {
40281
40266
  // Dispatch event
40282
40267
  WidgetEvents.getInstance().dispatchSwapStatus(statusResponse.squidTransactionStatus ?? "");
40283
40268
  const endStatus = getTransactionEndStatus({ statusResponse });
@@ -40289,9 +40274,8 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40289
40274
  status: endStatus,
40290
40275
  });
40291
40276
  }
40292
- }
40293
- if (transactionStatusQuery.isError) {
40294
- const error = transactionStatusQuery.error;
40277
+ },
40278
+ onError: (error) => {
40295
40279
  // `fetchTransactionStatus` throws an error with a cause being an AxiosError
40296
40280
  const is404 = is404Error(error.cause);
40297
40281
  if (!transaction?.transactionId)
@@ -40312,15 +40296,8 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40312
40296
  status: TransactionStatus.ERROR,
40313
40297
  });
40314
40298
  }
40315
- }
40316
- }, [
40317
- transactionStatusQuery.isSuccess,
40318
- transactionStatusQuery.isError,
40319
- transaction?.transactionId,
40320
- transactionStatusQuery.error,
40321
- replaceSwapTransactionStatus,
40322
- transactionStatusQuery.data,
40323
- ]);
40299
+ },
40300
+ });
40324
40301
  return {
40325
40302
  transactionStatusQuery,
40326
40303
  latestStatus: transactionStatusQuery.data
@@ -40363,7 +40340,7 @@ const useAvatar = (seed = zeroAddress) => {
40363
40340
  },
40364
40341
  // data is static, so no need to refetch
40365
40342
  refetchOnWindowFocus: false,
40366
- gcTime: Infinity,
40343
+ cacheTime: Infinity,
40367
40344
  staleTime: Infinity,
40368
40345
  });
40369
40346
  return avatar || "";
@@ -40405,40 +40382,38 @@ const useAddToken = (chainToCompare, tokenToCompare) => {
40405
40382
  /**
40406
40383
  * Add token to wallet
40407
40384
  */
40408
- const addToken = useMutation({
40409
- mutationFn: async ({ chain: _chain, token: _token, }) => {
40410
- const token = _token ?? tokenToCompare;
40411
- const chain = _chain ?? chainToCompare;
40412
- if (token && chain?.chainType === ChainType.EVM) {
40413
- const provider = await connector?.getProvider();
40414
- // Switch network if needed
40415
- if (currentEvmChain?.id.toString() !== token?.chainId) {
40416
- try {
40385
+ const addToken = useMutation(async ({ chain: _chain, token: _token, }) => {
40386
+ const token = _token ?? tokenToCompare;
40387
+ const chain = _chain ?? chainToCompare;
40388
+ if (token && chain?.chainType === ChainType.EVM) {
40389
+ const provider = await connector?.getProvider();
40390
+ // Switch network if needed
40391
+ if (currentEvmChain?.id.toString() !== token?.chainId) {
40392
+ try {
40393
+ await switchChainAsync({
40394
+ chainId: +token.chainId,
40395
+ });
40396
+ }
40397
+ catch (error) {
40398
+ console.debug("Error switching network:", error);
40399
+ if (isEvmChainNotSupportedError(error)) {
40400
+ await addEthereumChain({
40401
+ chain,
40402
+ provider,
40403
+ });
40417
40404
  await switchChainAsync({
40418
40405
  chainId: +token.chainId,
40419
40406
  });
40420
40407
  }
40421
- catch (error) {
40422
- console.debug("Error switching network:", error);
40423
- if (isEvmChainNotSupportedError(error)) {
40424
- await addEthereumChain({
40425
- chain,
40426
- provider,
40427
- });
40428
- await switchChainAsync({
40429
- chainId: +token.chainId,
40430
- });
40431
- }
40432
- }
40433
- // Metamask is not popping the second modal if we don't wait a bit
40434
- // eslint-disable-next-line no-promise-executor-return
40435
- await new Promise((resolve) => setTimeout(resolve, 100));
40436
40408
  }
40437
- await addTokenToWallet({ token, provider });
40409
+ // Metamask is not popping the second modal if we don't wait a bit
40410
+ // eslint-disable-next-line no-promise-executor-return
40411
+ await new Promise((resolve) => setTimeout(resolve, 100));
40438
40412
  }
40439
- // TODO: Implement keplr add token
40440
- return false;
40413
+ await addTokenToWallet({ token, provider });
40441
40414
  }
40415
+ // TODO: Implement keplr add token
40416
+ return false;
40442
40417
  });
40443
40418
  return {
40444
40419
  addToken,
@@ -40643,9 +40618,7 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40643
40618
  }
40644
40619
  },
40645
40620
  async onSuccess() {
40646
- queryClient.invalidateQueries({
40647
- queryKey: getPrefixKey(QueryKeys.XrplTrustLine),
40648
- });
40621
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.XrplTrustLine));
40649
40622
  },
40650
40623
  });
40651
40624
  /**
@@ -40823,5 +40796,5 @@ const SquidProvider = ({ children, config, placeholder, }) => {
40823
40796
  React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
40824
40797
  };
40825
40798
 
40826
- export { useNativeBalance as $, AxelarStatusResponseType as A, useAddressBookStore as B, CHAIN_IDS as C, DEFAULT_LOCALE as D, useAssetsColorsStore as E, useFavoriteTokensStore as F, useHistoryStore as G, HistoryTxType as H, useSendTransactionStore as I, useConfigStore as J, useSquidStore as K, useSwapRoutePersistStore as L, useTransactionStore as M, ConnectingWalletStatus as N, useWalletStore as O, useDepositAddress as P, useSwap as Q, useAllConnectedWalletBalances as R, SquidStatusErrorType as S, TransactionErrorType as T, useAllTokensWithBalanceForChainType as U, useCosmosBalance as V, WindowWalletFlag as W, XamanXrplNetwork as X, useEvmBalance as Y, useMultiChainBalance as Z, useMultipleTokenPrices as _, chainTypeToZeroAddressMap as a, groupTokensBySymbol as a$, useNativeTokenForChain as a0, useSingleTokenPrice as a1, useSquidTokens as a2, useHistoricalData as a3, useTokensData as a4, useEstimateSendTransaction as a5, useSendTransaction as a6, useSendTransactionGas as a7, useAllTransactionsStatus as a8, useApproval as a9, useGetFiatQuote as aA, useGetOnRampConfig as aB, useExecuteFiatQuote as aC, useCurrencyDetails as aD, useCountryDetails as aE, useAvailableQuotes as aF, useGetOnrampPaymentTypes as aG, useSuggestedFiatAmounts as aH, SquidProvider as aI, EnsService as aJ, getXummClient as aK, isXamanXAppContext as aL, getQueryHeaders as aM, getStatusCode as aN, is404Error as aO, assetsBaseUrl as aP, shareSubgraphId as aQ, sortTokensBySharedSubgraphIds as aR, getSupportedChainIdsForDirection as aS, filterChains as aT, filterTokens as aU, getTokenImage as aV, getNewSwapParamsFromInput as aW, sortAllTokens as aX, findToken as aY, findNativeToken as aZ, normalizeIbcAddress as a_, useEstimate as aa, useEstimatePriceImpact as ab, useExecuteTransaction as ac, useGetRoute as ad, useGetRouteWrapper as ae, useRouteWarnings as af, useSendTransactionStatus as ag, useSwapTransactionStatus as ah, useAvatar as ai, useHistory as aj, useUserParams as ak, useDebouncedValue as al, useAddToken as am, useAutoConnect as an, useEnsDataForAddress as ao, useEnsSearch as ap, useGnosisContext as aq, useIsSameAddressAndGnosisContext as ar, useIntegratorContext as as, useMultiChainWallet as at, useSigner as au, useWallet as av, useWallets as aw, useXrplTrustLine as ax, TX_STATUS_CONSTANTS as ay, FINAL_TRANSACTION_STATUSES as az, destinationAddressResetValue as b, formatTransactionHistoryDate as b$, groupTokensByChainId as b0, filterViewableTokens as b1, getSecretNetworkBalances as b2, getTokenAssetsKey as b3, fetchAssetsColors as b4, initializeSquidWithAssetsColors as b5, isEmptyObject as b6, normalizeTokenSymbol as b7, areTokenSymbolsCompatible as b8, isEvmosChain as b9, WidgetEvents as bA, EvmNetworkNotSupportedErrorCode as bB, addEthereumChain as bC, parseEvmAddress as bD, formatEvmWallet as bE, filterWagmiConnector as bF, getUserCountry as bG, getCountryData as bH, getCurrencyData as bI, adaptiveRound as bJ, getSuggestedAmountsForCurrency as bK, parseToBigInt as bL, roundNumericValue as bM, formatUnitsRounded as bN, formatTokenAmount as bO, formatUsdAmount as bP, trimExtraDecimals as bQ, getNumericValue as bR, cleanAmount as bS, convertTokenAmountToUSD as bT, convertUSDToTokenAmount as bU, calculateTotal24hChange as bV, searchTokens as bW, filterSolanaWallets as bX, isSolanaAddressValid as bY, executeSolanaSwap as bZ, executeSolanaTransfer as b_, getConfigWithDefaults as ba, randomIntFromInterval as bb, getTokensForChain as bc, getFirstAvailableChainId as bd, fetchHighestBalanceToken as be, getInitialOrDefaultTokenAddressForChain as bf, getInitialTokenAddressForChain as bg, filterTokensForDestination as bh, getInitialChainIdFromConfig as bi, getCosmosKey as bj, getKeysSettled as bk, getAllKeysForSupportedCosmosChains as bl, isCosmosAddressValid as bm, getCosmosSigningClient as bn, getCosmosChainInfosObject as bo, connectCosmosWallet as bp, isFallbackAddressNeeded as bq, suggestChainOrThrow as br, normalizeError as bs, transactionErrorCode as bt, isUserRejectionError as bu, getTransactionError as bv, handleTransactionErrorEvents as bw, isSwapRouteError as bx, isStatusError as by, createQuoteRequestParamsHash as bz, chainTypeToNativeTokenAddressMap as c, getAxelarExplorerTxUrl as c0, getSourceExplorerTxUrl as c1, getMainExplorerUrl as c2, formatDistance as c3, formatSeconds as c4, formatSwapTxStatusResponseForStorage as c5, simplifyRouteAction as c6, fetchSwapTransactionStatus as c7, compareTransactionIds as c8, isCoralBridgeAction as c9, calculateTotalUsdBalanceUSD as cA, addTokenToWallet as cB, isEvmChainNotSupportedError as cC, getWalletSupportedChainTypes as cD, getConnectorForChainType as cE, walletSupportsChainType as cF, connectWallet as cG, cancelConnectWallet as cH, isProblematicConnector as cI, mergeWallets as cJ, isXionSmartContractAddress as cK, isXrplAddressValid as cL, buildXrplTrustSetTx as cM, getXrplNetwork as cN, parseXrplPaymentTx as cO, sleep as ca, isDepositRoute as cb, isChainflipBridgeTransaction as cc, getHistoryTransactionId as cd, getStepStatuses as ce, getHalfSuccessState as cf, getStepsInfos as cg, getSwapTxStatusRefetchInterval as ch, getSendTxStatusRefetchInterval as ci, chainflipMultihopBridgeType as cj, getBridgeType as ck, getTransactionStatus as cl, getTransactionEndStatus as cm, isHistoryTransactionPending as cn, isHistoryTransactionFailed as co, isHistoryTransactionWarning as cp, isHistoryTransactionEnded as cq, formatHash as cr, isWalletAddressValid as cs, redirectToExtensionsStore as ct, accessProperty as cu, populateWallets as cv, getDefaultChain as cw, sortWallets as cx, areSameAddress as cy, sortAddressBook as cz, definedInWindow as d, fallbackAddressResetValue as e, formatBNToReadable as f, nativeCosmosTokenAddress as g, nativeEvmTokenAddress as h, nativeSolanaTokenAddress as i, nativeStellarTokenAddress as j, nativeSuiTokenAddress as k, nativeXrplTokenAddress as l, CosmosProvider as m, nativeBitcoinTokenAddress as n, SendTransactionStatus as o, TransactionStatus as p, useTrackSearchEmpty as q, useSquidChains as r, useClient as s, useCosmosForChain as t, useCosmosContext as u, useKeyboardNavigation as v, walletIconBaseUrl as w, useSquidQueryClient as x, useSquid as y, useStellarAccountActivation as z };
40827
- //# sourceMappingURL=index-BA79s7uI.js.map
40799
+ export { useNativeBalance as $, AxelarStatusResponseType as A, useAddressBookStore as B, CHAIN_IDS as C, DEFAULT_LOCALE as D, useAssetsColorsStore as E, useFavoriteTokensStore as F, useHistoryStore as G, HistoryTxType as H, useSendTransactionStore as I, useConfigStore as J, useSquidStore as K, useSwapRoutePersistStore as L, useTransactionStore as M, ConnectingWalletStatus as N, useWalletStore as O, useDepositAddress as P, useSwap as Q, useAllConnectedWalletBalances as R, SquidStatusErrorType as S, TransactionErrorType as T, useAllTokensWithBalanceForChainType as U, useCosmosBalance as V, WindowWalletFlag as W, XamanXrplNetwork as X, useEvmBalance as Y, useMultiChainBalance as Z, useMultipleTokenPrices as _, chainTypeToZeroAddressMap as a, findToken as a$, useNativeTokenForChain as a0, useSingleTokenPrice as a1, useSquidTokens as a2, useHistoricalData as a3, useTokensData as a4, useEstimateSendTransaction as a5, useSendTransaction as a6, useSendTransactionGas as a7, useAllTransactionsStatus as a8, useApproval as a9, useGetFiatQuote as aA, useGetOnRampConfig as aB, useExecuteFiatQuote as aC, useFiatOnRampTxStatus as aD, useFiatTransactions as aE, useCurrencyDetails as aF, useCountryDetails as aG, useAvailableQuotes as aH, useRecommendedQuote as aI, useGetOnrampPaymentTypes as aJ, useSuggestedFiatAmounts as aK, SquidProvider as aL, EnsService as aM, getXummClient as aN, isXamanXAppContext as aO, getQueryHeaders as aP, getStatusCode as aQ, is404Error as aR, assetsBaseUrl as aS, shareSubgraphId as aT, sortTokensBySharedSubgraphIds as aU, getSupportedChainIdsForDirection as aV, filterChains as aW, filterTokens as aX, getTokenImage as aY, getNewSwapParamsFromInput as aZ, sortAllTokens as a_, useEstimate as aa, useEstimatePriceImpact as ab, useExecuteTransaction as ac, useGetRoute as ad, useGetRouteWrapper as ae, useRouteWarnings as af, useSendTransactionStatus as ag, useSwapTransactionStatus as ah, useAvatar as ai, useHistory as aj, useUserParams as ak, useDebouncedValue as al, useAddToken as am, useAutoConnect as an, useEnsDataForAddress as ao, useEnsSearch as ap, useGnosisContext as aq, useIsSameAddressAndGnosisContext as ar, useIntegratorContext as as, useMultiChainWallet as at, useSigner as au, useWallet as av, useWallets as aw, useXrplTrustLine as ax, TX_STATUS_CONSTANTS as ay, FINAL_TRANSACTION_STATUSES as az, destinationAddressResetValue as b, isSolanaAddressValid as b$, findNativeToken as b0, normalizeIbcAddress as b1, groupTokensBySymbol as b2, groupTokensByChainId as b3, filterViewableTokens as b4, getSecretNetworkBalances as b5, getTokenAssetsKey as b6, fetchAssetsColors as b7, initializeSquidWithAssetsColors as b8, isEmptyObject as b9, isSwapRouteError as bA, isStatusError as bB, createQuoteRequestParamsHash as bC, WidgetEvents as bD, EvmNetworkNotSupportedErrorCode as bE, addEthereumChain as bF, parseEvmAddress as bG, formatEvmWallet as bH, filterWagmiConnector as bI, getUserCountry as bJ, getCountryData as bK, getCurrencyData as bL, adaptiveRound as bM, getSuggestedAmountsForCurrency as bN, parseToBigInt as bO, roundNumericValue as bP, formatUnitsRounded as bQ, formatTokenAmount as bR, formatUsdAmount as bS, trimExtraDecimals as bT, getNumericValue as bU, cleanAmount as bV, convertTokenAmountToUSD as bW, convertUSDToTokenAmount as bX, calculateTotal24hChange as bY, searchTokens as bZ, filterSolanaWallets as b_, normalizeTokenSymbol as ba, areTokenSymbolsCompatible as bb, isEvmosChain as bc, getConfigWithDefaults as bd, randomIntFromInterval as be, getTokensForChain as bf, getFirstAvailableChainId as bg, fetchHighestBalanceToken as bh, getInitialOrDefaultTokenAddressForChain as bi, getInitialTokenAddressForChain as bj, filterTokensForDestination as bk, getInitialChainIdFromConfig as bl, getCosmosKey as bm, getKeysSettled as bn, getAllKeysForSupportedCosmosChains as bo, isCosmosAddressValid as bp, getCosmosSigningClient as bq, getCosmosChainInfosObject as br, connectCosmosWallet as bs, isFallbackAddressNeeded as bt, suggestChainOrThrow as bu, normalizeError as bv, transactionErrorCode as bw, isUserRejectionError as bx, getTransactionError as by, handleTransactionErrorEvents as bz, chainTypeToNativeTokenAddressMap as c, executeSolanaSwap as c0, executeSolanaTransfer as c1, formatTransactionHistoryDate as c2, getAxelarExplorerTxUrl as c3, getSourceExplorerTxUrl as c4, getMainExplorerUrl as c5, formatDistance as c6, formatSeconds as c7, formatSwapTxStatusResponseForStorage as c8, simplifyRouteAction as c9, sortWallets as cA, areSameAddress as cB, sortAddressBook as cC, calculateTotalUsdBalanceUSD as cD, addTokenToWallet as cE, isEvmChainNotSupportedError as cF, getWalletSupportedChainTypes as cG, getConnectorForChainType as cH, walletSupportsChainType as cI, connectWallet as cJ, cancelConnectWallet as cK, isProblematicConnector as cL, mergeWallets as cM, isXionSmartContractAddress as cN, isXrplAddressValid as cO, buildXrplTrustSetTx as cP, getXrplNetwork as cQ, parseXrplPaymentTx as cR, fetchSwapTransactionStatus as ca, compareTransactionIds as cb, isCoralBridgeAction as cc, sleep as cd, isDepositRoute as ce, isChainflipBridgeTransaction as cf, getHistoryTransactionId as cg, getStepStatuses as ch, getHalfSuccessState as ci, getStepsInfos as cj, getSwapTxStatusRefetchInterval as ck, getSendTxStatusRefetchInterval as cl, chainflipMultihopBridgeType as cm, getBridgeType as cn, getTransactionStatus as co, getTransactionEndStatus as cp, isHistoryTransactionPending as cq, isHistoryTransactionFailed as cr, isHistoryTransactionWarning as cs, isHistoryTransactionEnded as ct, formatHash as cu, isWalletAddressValid as cv, redirectToExtensionsStore as cw, accessProperty as cx, populateWallets as cy, getDefaultChain as cz, definedInWindow as d, fallbackAddressResetValue as e, formatBNToReadable as f, nativeCosmosTokenAddress as g, nativeEvmTokenAddress as h, nativeSolanaTokenAddress as i, nativeStellarTokenAddress as j, nativeSuiTokenAddress as k, nativeXrplTokenAddress as l, CosmosProvider as m, nativeBitcoinTokenAddress as n, SendTransactionStatus as o, TransactionStatus as p, useTrackSearchEmpty as q, useSquidChains as r, useClient as s, useCosmosForChain as t, useCosmosContext as u, useKeyboardNavigation as v, walletIconBaseUrl as w, useSquidQueryClient as x, useSquid as y, useStellarAccountActivation as z };
40800
+ //# sourceMappingURL=index-BKmIOD3t.js.map