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

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 (41) hide show
  1. package/dist/core/types/event.d.ts +17 -8
  2. package/dist/hooks/onramp/useFiatToCrypto.d.ts +28 -6
  3. package/dist/hooks/squid/useSquid.d.ts +2 -2
  4. package/dist/hooks/swap/useDepositAddress.d.ts +2 -2
  5. package/dist/hooks/tokens/useAllConnectedWalletBalances.d.ts +11 -5
  6. package/dist/hooks/tokens/useAllTokensWithBalanceForChainType.d.ts +1 -1
  7. package/dist/hooks/tokens/useBalance.d.ts +1 -1
  8. package/dist/hooks/tokens/useMultipleTokenPrices.d.ts +2 -2
  9. package/dist/hooks/tokens/useNativeBalance.d.ts +2 -2
  10. package/dist/hooks/tokens/useTokenHistoricalData.d.ts +4 -4
  11. package/dist/hooks/transaction/send/useEstimateSendTransactionGas.d.ts +1 -1
  12. package/dist/hooks/transaction/send/useSendTransactionGas.d.ts +1 -1
  13. package/dist/hooks/transaction/useAllTransactionsStatus.d.ts +29 -3
  14. package/dist/hooks/transaction/useApproval.d.ts +2 -2
  15. package/dist/hooks/transaction/useExecuteTransaction.d.ts +2 -2
  16. package/dist/hooks/transaction/useGetRoute.d.ts +7 -7
  17. package/dist/hooks/transaction/useSwapTransactionStatus.d.ts +1 -1
  18. package/dist/hooks/wallet/useAddToken.d.ts +1 -1
  19. package/dist/hooks/wallet/useEns.d.ts +2 -2
  20. package/dist/hooks/wallet/useMultiChainWallet.d.ts +1 -1
  21. package/dist/hooks/wallet/useWallet.d.ts +1 -1
  22. package/dist/hooks/xrpl/useXrplTrustLine.d.ts +5 -5
  23. package/dist/{index-CS74WzWX.js → index-DVmnHUzP.js} +987 -960
  24. package/dist/index-DVmnHUzP.js.map +1 -0
  25. package/dist/{index-BA79s7uI.js → index-jI-SulDo.js} +986 -962
  26. package/dist/index-jI-SulDo.js.map +1 -0
  27. package/dist/index.esm.js +1 -1
  28. package/dist/index.js +4 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/{secretService-U8WiVPay.js → secretService-DBxDcfuA.js} +2 -2
  31. package/dist/{secretService-U8WiVPay.js.map → secretService-DBxDcfuA.js.map} +1 -1
  32. package/dist/{secretService-D3MB_TMv.js → secretService-DN5IzV4w.js} +2 -2
  33. package/dist/{secretService-D3MB_TMv.js.map → secretService-DN5IzV4w.js.map} +1 -1
  34. package/dist/services/internal/eventService.d.ts +1 -0
  35. package/dist/{stellarService.client-Dp4tvmUo.js → stellarService.client-7sSrAZi2.js} +2 -2
  36. package/dist/{stellarService.client-Dp4tvmUo.js.map → stellarService.client-7sSrAZi2.js.map} +1 -1
  37. package/dist/{stellarService.client-BUdrOP04.js → stellarService.client-DTFEi5m2.js} +2 -2
  38. package/dist/{stellarService.client-BUdrOP04.js.map → stellarService.client-DTFEi5m2.js.map} +1 -1
  39. package/package.json +12 -12
  40. package/dist/index-BA79s7uI.js.map +0 -1
  41. 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-DN5IzV4w.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();
30460
30550
  }
30551
+ catch {
30552
+ // if auto-connect fails (e.g. not authorized yet)
30553
+ // fallback to connect via popup
30554
+ await wallet.connector.connect();
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-7sSrAZi2.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);
@@ -31911,11 +32002,11 @@ const useSquidQueryClient = () => {
31911
32002
  const queryClient = useQueryClient();
31912
32003
  const invalidateQueries = (key) => {
31913
32004
  const prefixKey = getPrefixKey(key);
31914
- queryClient.invalidateQueries({ queryKey: prefixKey });
32005
+ queryClient.invalidateQueries(prefixKey);
31915
32006
  };
31916
32007
  const refetchQueries = (key) => {
31917
32008
  const prefixKey = getPrefixKey(key);
31918
- queryClient.refetchQueries({ queryKey: prefixKey });
32009
+ queryClient.refetchQueries(prefixKey);
31919
32010
  };
31920
32011
  const invalidateAndRefetchQueries = (key) => {
31921
32012
  invalidateQueries(key);
@@ -33422,19 +33513,17 @@ function useDepositAddress(squidRoute) {
33422
33513
  toggleDepositFlow(false);
33423
33514
  setDeposit(null);
33424
33515
  }, [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
- }
33516
+ const getRouteWithDeposit = useMutation(async ({ route }) => {
33517
+ if (!squid)
33518
+ throw new Error("Squid SDK not initialized");
33519
+ const depositAddressResponse = (await squid.executeRoute({
33520
+ signer: {},
33521
+ route,
33522
+ }));
33523
+ setDeposit(depositAddressResponse);
33524
+ return {
33525
+ depositAddress: depositAddressResponse,
33526
+ };
33438
33527
  });
33439
33528
  return {
33440
33529
  isEnabled,
@@ -33518,55 +33607,53 @@ const useAllTokensWithBalanceForChainType = ({ chainType, address, direction, qu
33518
33607
  xrplTokens.length,
33519
33608
  stellarTokens.length,
33520
33609
  ]);
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
- }
33610
+ const query = useQuery(keys().allTokensBalance(address, chainType, direction), async () => {
33611
+ // Return zero balances if no address
33612
+ if (!address) {
33613
+ const defaultTokens = placeholderData.tokens;
33565
33614
  return {
33566
- tokens: fetchedTokens,
33567
- totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33615
+ tokens: defaultTokens,
33616
+ totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33568
33617
  };
33569
- },
33618
+ }
33619
+ let fetchedTokens = [];
33620
+ // Fetch tokens based on chain type
33621
+ switch (chainType) {
33622
+ case ChainType.EVM:
33623
+ fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33624
+ break;
33625
+ case ChainType.COSMOS:
33626
+ const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33627
+ fetchedTokens = await getAllCosmosBalances({
33628
+ addresses,
33629
+ cosmosChains,
33630
+ cosmosTokens,
33631
+ });
33632
+ break;
33633
+ case ChainType.SOLANA:
33634
+ fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33635
+ break;
33636
+ case ChainType.BTC:
33637
+ fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33638
+ break;
33639
+ case ChainType.SUI:
33640
+ fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33641
+ break;
33642
+ case ChainType.XRPL:
33643
+ fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33644
+ break;
33645
+ case ChainType.STELLAR:
33646
+ fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33647
+ break;
33648
+ default:
33649
+ fetchedTokens = placeholderData.tokens;
33650
+ break;
33651
+ }
33652
+ return {
33653
+ tokens: fetchedTokens,
33654
+ totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33655
+ };
33656
+ }, {
33570
33657
  ...queryOptions,
33571
33658
  enabled: isQueryEnabled,
33572
33659
  });
@@ -33581,7 +33668,7 @@ const BALANCE_STALE_TIME = 60000; // 1 minute
33581
33668
  const BALANCE_CACHE_TIME = 300000; // 5 minutes
33582
33669
  const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33583
33670
  staleTime: BALANCE_STALE_TIME,
33584
- gcTime: BALANCE_CACHE_TIME,
33671
+ cacheTime: BALANCE_CACHE_TIME,
33585
33672
  refetchOnWindowFocus: true,
33586
33673
  refetchOnMount: true,
33587
33674
  }, } = {}) => {
@@ -33662,9 +33749,9 @@ const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33662
33749
  }, [balanceQueries]);
33663
33750
  // Aggregate loading states
33664
33751
  const queryStates = useMemo(() => ({
33665
- isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33752
+ isInitialLoading: Object.values(balanceQueries).some((q) => q.isInitialLoading),
33666
33753
  isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33667
- isPending: Object.values(balanceQueries).some((q) => q.isPending),
33754
+ isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33668
33755
  isRefetching: Object.values(balanceQueries).some((q) => q.isRefetching),
33669
33756
  isError: Object.values(balanceQueries).some((q) => q.isError),
33670
33757
  isSuccess: Object.values(balanceQueries).every((q) => q.isSuccess),
@@ -33706,7 +33793,7 @@ function useNativeTokenForChain(chain) {
33706
33793
 
33707
33794
  const useEvmNativeBalance = ({ address, chain, }) => {
33708
33795
  const { isChainTypeConnected } = useWallet();
33709
- const { data: nativeEvmBalance, isPending } = useBalance({
33796
+ const { data: nativeEvmBalance, isLoading } = useBalance({
33710
33797
  address: address,
33711
33798
  chainId: Number(chain?.chainId),
33712
33799
  query: {
@@ -33728,13 +33815,13 @@ const useEvmNativeBalance = ({ address, chain, }) => {
33728
33815
  }, [nativeEvmBalance?.decimals, nativeEvmBalance?.value]);
33729
33816
  return {
33730
33817
  balance,
33731
- isPending,
33818
+ isLoading,
33732
33819
  };
33733
33820
  };
33734
33821
  const useCosmosNativeBalance = ({ address, chain, }) => {
33735
33822
  const { isConnected: isCosmosConnected } = useCosmosContext();
33736
33823
  const { nativeToken: nativeCosmosToken } = useNativeTokenForChain(chain);
33737
- const { balance: rawBalance, isPending } = useCosmosBalance({
33824
+ const { balance: rawBalance, isLoading } = useCosmosBalance({
33738
33825
  chain,
33739
33826
  token: nativeCosmosToken,
33740
33827
  userAddress: address,
@@ -33749,18 +33836,16 @@ const useCosmosNativeBalance = ({ address, chain, }) => {
33749
33836
  };
33750
33837
  }
33751
33838
  }, [nativeCosmosToken?.decimals, rawBalance]);
33752
- return { balance, isPending };
33839
+ return { balance, isLoading };
33753
33840
  };
33754
33841
  const useBitcoinNativeBalance = ({ chain, address, }) => {
33755
33842
  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
- },
33843
+ const { data: rawBalance = "0", isLoading } = useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33844
+ if (!address || !nativeToken)
33845
+ return "0";
33846
+ const balance = await getBitcoinNativeBalance(address);
33847
+ return formatBNToReadable(balance, nativeToken.decimals);
33848
+ }, {
33764
33849
  enabled: chain?.chainType === ChainType.BTC &&
33765
33850
  nativeToken?.decimals != null &&
33766
33851
  isWalletAddressValid(chain, address),
@@ -33779,17 +33864,15 @@ const useBitcoinNativeBalance = ({ chain, address, }) => {
33779
33864
  }, [nativeToken?.decimals, rawBalance]);
33780
33865
  return {
33781
33866
  balance,
33782
- isPending,
33867
+ isLoading,
33783
33868
  };
33784
33869
  };
33785
33870
  const useSolanaNativeBalance = ({ chain, address, }) => {
33786
33871
  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
- },
33872
+ const { data: rawBalance, isLoading } = useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33873
+ const balance = await getSolanaNativeBalance(address);
33874
+ return formatBNToReadable(balance, nativeToken.decimals);
33875
+ }, {
33793
33876
  enabled: !!address &&
33794
33877
  nativeToken?.decimals != null &&
33795
33878
  chain?.chainType === ChainType.SOLANA,
@@ -33808,12 +33891,12 @@ const useSolanaNativeBalance = ({ chain, address, }) => {
33808
33891
  }, [nativeToken?.decimals, rawBalance]);
33809
33892
  return {
33810
33893
  balance,
33811
- isPending,
33894
+ isLoading,
33812
33895
  };
33813
33896
  };
33814
33897
  const useSuiNativeBalance = ({ address, chain, }) => {
33815
33898
  const { nativeToken } = useNativeTokenForChain(chain);
33816
- const { balance: rawBalance, isPending } = useSuiBalance({
33899
+ const { balance: rawBalance, isLoading } = useSuiBalance({
33817
33900
  chain,
33818
33901
  token: nativeToken,
33819
33902
  userAddress: address,
@@ -33828,12 +33911,12 @@ const useSuiNativeBalance = ({ address, chain, }) => {
33828
33911
  }, [nativeToken?.decimals, rawBalance]);
33829
33912
  return {
33830
33913
  balance,
33831
- isPending,
33914
+ isLoading,
33832
33915
  };
33833
33916
  };
33834
33917
  const useXrplNativeBalance = ({ address, chain, }) => {
33835
33918
  const { nativeToken } = useNativeTokenForChain(chain);
33836
- const { balance: rawBalance, isPending } = useXrplBalance({
33919
+ const { balance: rawBalance, isLoading } = useXrplBalance({
33837
33920
  chain,
33838
33921
  token: nativeToken,
33839
33922
  userAddress: address,
@@ -33849,12 +33932,12 @@ const useXrplNativeBalance = ({ address, chain, }) => {
33849
33932
  }, [nativeToken?.decimals, rawBalance]);
33850
33933
  return {
33851
33934
  balance,
33852
- isPending,
33935
+ isLoading,
33853
33936
  };
33854
33937
  };
33855
33938
  const useStellarNativeBalance = ({ address, chain, }) => {
33856
33939
  const { nativeToken } = useNativeTokenForChain(chain);
33857
- const { balance: rawBalance, isPending } = useStellarBalance({
33940
+ const { balance: rawBalance, isLoading } = useStellarBalance({
33858
33941
  chain,
33859
33942
  token: nativeToken,
33860
33943
  userAddress: address,
@@ -33870,7 +33953,7 @@ const useStellarNativeBalance = ({ address, chain, }) => {
33870
33953
  }, [nativeToken?.decimals, rawBalance]);
33871
33954
  return {
33872
33955
  balance,
33873
- isPending,
33956
+ isLoading,
33874
33957
  };
33875
33958
  };
33876
33959
  const useNativeBalance = (chain) => {
@@ -33878,28 +33961,28 @@ const useNativeBalance = (chain) => {
33878
33961
  const { data: cosmosAddressForChain } = useCosmosForChain(chain);
33879
33962
  // Cosmos is a special case because the address changes on every chain
33880
33963
  // so we can't use the default cosmos connected address
33881
- const { balance: nativeCosmosBalance, isPending: isCosmosPending } = useCosmosNativeBalance({
33964
+ const { balance: nativeCosmosBalance, isLoading: isCosmosLoading } = useCosmosNativeBalance({
33882
33965
  address: cosmosAddressForChain,
33883
33966
  chain,
33884
33967
  });
33885
- const { balance: nativeEvmBalance, isPending: isEvmPending } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33886
- const { balance: nativeBitcoinBalance, isPending: isBitcoinPending } = useBitcoinNativeBalance({
33968
+ const { balance: nativeEvmBalance, isLoading: isEvmLoading } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33969
+ const { balance: nativeBitcoinBalance, isLoading: isBitcoinLoading } = useBitcoinNativeBalance({
33887
33970
  address: connectedAddresses[ChainType.BTC],
33888
33971
  chain,
33889
33972
  });
33890
- const { balance: nativeSolanaBalance, isPending: isSolanaPending } = useSolanaNativeBalance({
33973
+ const { balance: nativeSolanaBalance, isLoading: isSolanaLoading } = useSolanaNativeBalance({
33891
33974
  address: connectedAddresses[ChainType.SOLANA],
33892
33975
  chain,
33893
33976
  });
33894
- const { balance: nativeSuiBalance, isPending: isSuiPending } = useSuiNativeBalance({
33977
+ const { balance: nativeSuiBalance, isLoading: isSuiLoading } = useSuiNativeBalance({
33895
33978
  address: connectedAddresses[ChainType.SUI],
33896
33979
  chain,
33897
33980
  });
33898
- const { balance: nativeXrplBalance, isPending: isXrplPending } = useXrplNativeBalance({
33981
+ const { balance: nativeXrplBalance, isLoading: isXrpLoading } = useXrplNativeBalance({
33899
33982
  address: connectedAddresses[ChainType.XRPL],
33900
33983
  chain,
33901
33984
  });
33902
- const { balance: nativeStellarBalance, isPending: isStellarPending } = useStellarNativeBalance({
33985
+ const { balance: nativeStellarBalance, isLoading: isStellarLoading } = useStellarNativeBalance({
33903
33986
  address: connectedAddresses[ChainType.STELLAR],
33904
33987
  chain,
33905
33988
  });
@@ -33944,36 +34027,36 @@ const useNativeBalance = (chain) => {
33944
34027
  nativeXrplBalance,
33945
34028
  nativeStellarBalance,
33946
34029
  ]);
33947
- const isPending = useMemo(() => {
34030
+ const isLoading = useMemo(() => {
33948
34031
  if (!chain?.chainType)
33949
34032
  return false;
33950
34033
  switch (chain.chainType) {
33951
34034
  case ChainType.EVM:
33952
- return isEvmPending;
34035
+ return isEvmLoading;
33953
34036
  case ChainType.COSMOS:
33954
- return isCosmosPending;
34037
+ return isCosmosLoading;
33955
34038
  case ChainType.BTC:
33956
- return isBitcoinPending;
34039
+ return isBitcoinLoading;
33957
34040
  case ChainType.SOLANA:
33958
- return isSolanaPending;
34041
+ return isSolanaLoading;
33959
34042
  case ChainType.SUI:
33960
- return isSuiPending;
34043
+ return isSuiLoading;
33961
34044
  case ChainType.XRPL:
33962
- return isXrplPending;
34045
+ return isXrpLoading;
33963
34046
  case ChainType.STELLAR:
33964
- return isStellarPending;
34047
+ return isStellarLoading;
33965
34048
  }
33966
34049
  }, [
33967
34050
  chain?.chainType,
33968
- isEvmPending,
33969
- isCosmosPending,
33970
- isBitcoinPending,
33971
- isSolanaPending,
33972
- isSuiPending,
33973
- isXrplPending,
33974
- isStellarPending,
34051
+ isEvmLoading,
34052
+ isCosmosLoading,
34053
+ isBitcoinLoading,
34054
+ isSolanaLoading,
34055
+ isSuiLoading,
34056
+ isXrpLoading,
34057
+ isStellarLoading,
33975
34058
  ]);
33976
- return { nativeBalance, nativeBalanceFormatted, isPending };
34059
+ return { nativeBalance, nativeBalanceFormatted, isLoading };
33977
34060
  };
33978
34061
 
33979
34062
  const DEFAULT_REFRESH_INTERVAL_MS = 15000;
@@ -33982,7 +34065,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
33982
34065
  const isNativeToken = token?.address.toLowerCase() === nativeEvmTokenAddress.toLowerCase();
33983
34066
  const userAddressParsed = userAddress;
33984
34067
  // Only fetch using useBalance if it's a native token
33985
- const { data: nativeBalance, isPending: isNativeTokenPending } = useBalance({
34068
+ const { data: nativeBalance, isLoading: isNativeTokenLoading } = useBalance({
33986
34069
  address: userAddressParsed,
33987
34070
  chainId: Number(chain?.chainId),
33988
34071
  query: {
@@ -33998,7 +34081,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
33998
34081
  });
33999
34082
  // Only fetch using useReadContract if it's not a native token
34000
34083
  // This is temporary, because of wagmi error: https://github.com/wevm/wagmi/issues/4353
34001
- const { data: erc20Balance, isPending: isErc20Pending } = useReadContract({
34084
+ const { data: erc20Balance, isLoading: isErc20Loading } = useReadContract({
34002
34085
  address: token?.address,
34003
34086
  abi: erc20Abi,
34004
34087
  functionName: "balanceOf",
@@ -34014,15 +34097,15 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34014
34097
  },
34015
34098
  });
34016
34099
  const balance = isNativeToken ? nativeBalance?.value : erc20Balance;
34017
- const isPending = isNativeToken ? isNativeTokenPending : isErc20Pending;
34100
+ const isLoading = isNativeToken ? isNativeTokenLoading : isErc20Loading;
34018
34101
  const formattedBalance = balance != null && token?.decimals != null
34019
34102
  ? formatBNToReadable(balance, token.decimals)
34020
34103
  : "0";
34021
- return { balance: formattedBalance, isPending };
34104
+ return { balance: formattedBalance, isLoading };
34022
34105
  };
34023
34106
  const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34024
34107
  const { isConnected } = useCosmosContext();
34025
- const { data: balance = "0", isPending } = useQuery({
34108
+ const { data: balance = "0", isLoading } = useQuery({
34026
34109
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34027
34110
  queryFn: async () => {
34028
34111
  if (!userAddress || !token || chain?.chainType !== ChainType.COSMOS) {
@@ -34042,10 +34125,10 @@ const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34042
34125
  refetchInterval: refreshIntervalMs,
34043
34126
  retry: 2,
34044
34127
  });
34045
- return { balance, isPending };
34128
+ return { balance, isLoading };
34046
34129
  };
34047
34130
  const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34048
- const { data: balance = "0", isPending } = useQuery({
34131
+ const { data: balance = "0", isLoading } = useQuery({
34049
34132
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34050
34133
  queryFn: async () => {
34051
34134
  if (!userAddress || !token)
@@ -34060,11 +34143,11 @@ const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34060
34143
  refetchInterval: refreshIntervalMs,
34061
34144
  retry: 2,
34062
34145
  });
34063
- return { balance, isPending };
34146
+ return { balance, isLoading };
34064
34147
  };
34065
34148
  // TODO: implement fetching balances for all bitcoin tokens
34066
34149
  const useBitcoinBalance = ({ userAddress, chain, }) => {
34067
- const { balance: balanceBn, isPending } = useBitcoinNativeBalance({
34150
+ const { balance: balanceBn, isLoading } = useBitcoinNativeBalance({
34068
34151
  address: userAddress,
34069
34152
  chain,
34070
34153
  });
@@ -34073,10 +34156,10 @@ const useBitcoinBalance = ({ userAddress, chain, }) => {
34073
34156
  return "0";
34074
34157
  return formatBNToReadable(balanceBn?.value, balanceBn?.decimals);
34075
34158
  }, [balanceBn]);
34076
- return { balance, isPending };
34159
+ return { balance, isLoading };
34077
34160
  };
34078
34161
  const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34079
- const { data: balance = "0", isPending } = useQuery({
34162
+ const { data: balance = "0", isLoading } = useQuery({
34080
34163
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34081
34164
  queryFn: async () => {
34082
34165
  if (!userAddress ||
@@ -34096,10 +34179,10 @@ const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34096
34179
  refetchInterval: refreshIntervalMs,
34097
34180
  retry: 2,
34098
34181
  });
34099
- return { balance, isPending };
34182
+ return { balance, isLoading };
34100
34183
  };
34101
34184
  const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34102
- const { data: balance = "0", isPending } = useQuery({
34185
+ const { data: balance = "0", isLoading } = useQuery({
34103
34186
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34104
34187
  queryFn: async () => {
34105
34188
  if (!userAddress || !token || !chain)
@@ -34116,10 +34199,10 @@ const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs
34116
34199
  refetchInterval: refreshIntervalMs,
34117
34200
  retry: 2,
34118
34201
  });
34119
- return { balance, isPending };
34202
+ return { balance, isLoading };
34120
34203
  };
34121
34204
  const useStellarBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34122
- const { data: balance = "0", isPending } = useQuery({
34205
+ const { data: balance = "0", isLoading } = useQuery({
34123
34206
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34124
34207
  queryFn: async () => {
34125
34208
  if (!userAddress || !token || !chain)
@@ -34136,7 +34219,7 @@ const useStellarBalance = ({ userAddress, chain, enabled, token, refreshInterval
34136
34219
  refetchInterval: refreshIntervalMs,
34137
34220
  retry: 2,
34138
34221
  });
34139
- return { balance, isPending };
34222
+ return { balance, isLoading };
34140
34223
  };
34141
34224
 
34142
34225
  /**
@@ -34257,7 +34340,7 @@ const useMultipleTokenPrices = (tokens) => {
34257
34340
  return {
34258
34341
  tokenPrices,
34259
34342
  getTokenPrice,
34260
- isPending: coinGeckoQuery.isPending,
34343
+ isLoading: coinGeckoQuery.isLoading,
34261
34344
  isError: coinGeckoQuery.isError,
34262
34345
  error: coinGeckoQuery.error,
34263
34346
  refetch: coinGeckoQuery.refetch,
@@ -34406,17 +34489,13 @@ const fetchTokensData = async (tokens) => {
34406
34489
 
34407
34490
  // Coingecko has a limit for some queries for multiple tokens, not sure what it is, but let's use 100 for now
34408
34491
  const useHistoricalData = (coingeckoId, timeFrame) => {
34409
- return useQuery({
34410
- queryKey: keys().historicalData(coingeckoId, timeFrame),
34411
- queryFn: () => fetchHistoricalData(coingeckoId, timeFrame),
34492
+ return useQuery(keys().historicalData(coingeckoId, timeFrame), () => fetchHistoricalData(coingeckoId, timeFrame), {
34412
34493
  staleTime: 5 * 60 * 1000,
34413
34494
  enabled: !!coingeckoId,
34414
34495
  });
34415
34496
  };
34416
34497
  const useTokensData = (tokens) => {
34417
- return useQuery({
34418
- queryKey: keys().tokensData(tokens),
34419
- queryFn: () => fetchTokensData(tokens),
34498
+ return useQuery(keys().tokensData(tokens), () => fetchTokensData(tokens), {
34420
34499
  staleTime: 60 * 1000,
34421
34500
  enabled: !!tokens && tokens.length > 0,
34422
34501
  });
@@ -34721,7 +34800,7 @@ function useSendTransactionGas({ chain, token, from, }) {
34721
34800
  }
34722
34801
 
34723
34802
  function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34724
- const { data: estimatedGas = BigInt(0), isPending } = useSendTransactionGas({
34803
+ const { data: estimatedGas = BigInt(0), isLoading } = useSendTransactionGas({
34725
34804
  chain,
34726
34805
  token,
34727
34806
  from,
@@ -34766,7 +34845,7 @@ function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34766
34845
  return {
34767
34846
  estimatedGas,
34768
34847
  isBalanceEnough,
34769
- isPending,
34848
+ isLoading,
34770
34849
  isNativeBalanceEnoughToPayGasFees,
34771
34850
  minAmountValueWarnMsg,
34772
34851
  };
@@ -35173,12 +35252,10 @@ function useSendTransaction({ to, amount, token, chain, }) {
35173
35252
  // amount is already formatted with the token decimals
35174
35253
  amount,
35175
35254
  toAddress: to,
35176
- token: {
35177
- address: token.address,
35178
- chainId: token.chainId,
35179
- symbol: token.symbol,
35180
- type: token.type,
35181
- },
35255
+ tokenAddress: token.address,
35256
+ tokenChainId: token.chainId,
35257
+ tokenSymbol: token.symbol,
35258
+ tokenType: token.type,
35182
35259
  });
35183
35260
  }, [
35184
35261
  allEventParamsDefined,
@@ -35198,12 +35275,10 @@ function useSendTransaction({ to, amount, token, chain, }) {
35198
35275
  // amount is already formatted with the token decimals
35199
35276
  amount,
35200
35277
  toAddress: to,
35201
- token: {
35202
- address: token.address,
35203
- chainId: token.chainId,
35204
- symbol: token.symbol,
35205
- type: token.type,
35206
- },
35278
+ tokenAddress: token.address,
35279
+ tokenChainId: token.chainId,
35280
+ tokenSymbol: token.symbol,
35281
+ tokenType: token.type,
35207
35282
  txHash,
35208
35283
  });
35209
35284
  }, [
@@ -35349,9 +35424,7 @@ function useSendTransaction({ to, amount, token, chain, }) {
35349
35424
  });
35350
35425
  },
35351
35426
  onSuccess: (tx, variables) => {
35352
- queryClient.invalidateQueries({
35353
- queryKey: getPrefixKey(QueryKeys.Balance),
35354
- });
35427
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balance));
35355
35428
  setTransactionState(variables.id, tx);
35356
35429
  persistTransaction({
35357
35430
  txType: HistoryTxType.SEND,
@@ -35678,10 +35751,9 @@ const useAllTransactionsStatus = ({ enabled }) => {
35678
35751
  queryKey: keys().fiatToCryptoStatus(data.orderId),
35679
35752
  retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
35680
35753
  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)) {
35754
+ refetchInterval: (data) => {
35755
+ if (data?.status &&
35756
+ FINAL_TRANSACTION_STATUSES.includes(data.status)) {
35685
35757
  return false;
35686
35758
  }
35687
35759
  return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
@@ -35741,7 +35813,7 @@ const useAllTransactionsStatus = ({ enabled }) => {
35741
35813
  queries: enabled && config.apiUrl ? statusQueries : [],
35742
35814
  });
35743
35815
  return {
35744
- isPending: queries.some((q) => q.isPending),
35816
+ isLoading: queries.some((q) => q.isLoading),
35745
35817
  isError: queries.some((q) => q.isError),
35746
35818
  data: queries.map((q) => q.data).filter(Boolean),
35747
35819
  };
@@ -36000,18 +36072,16 @@ const useApproval = ({ squidRoute, }) => {
36000
36072
  * On Error: Showing the error message if any
36001
36073
  * @returns {boolean} approved
36002
36074
  */
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
- },
36075
+ const routeApproved = useQuery(keys().routeApproved(squidRoute, allowanceInWei), async () => {
36076
+ // Approval is only needed for EVM chains
36077
+ if (getChainType(squidRoute?.params.fromChain) === ChainType.EVM) {
36078
+ return hasAllowance;
36079
+ }
36080
+ return true;
36081
+ }, {
36012
36082
  enabled: !!squidRoute &&
36013
36083
  !!sourceUserAddress &&
36014
- !allowanceQuery?.isPending &&
36084
+ !allowanceQuery?.isLoading &&
36015
36085
  allowanceQuery?.isFetched,
36016
36086
  });
36017
36087
  // USDT has a very specific way of handling approvals
@@ -36100,84 +36170,81 @@ const useApproval = ({ squidRoute, }) => {
36100
36170
  /**
36101
36171
  * Manually approve route if necessary
36102
36172
  */
36103
- const approveRoute = useMutation({
36104
- mutationFn: async () => {
36105
- try {
36106
- if (fromToken?.address === nativeEvmTokenAddress) {
36107
- return true;
36173
+ const approveRoute = useMutation(async () => {
36174
+ try {
36175
+ if (fromToken?.address === nativeEvmTokenAddress) {
36176
+ return true;
36177
+ }
36178
+ if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36179
+ await approveSpecificTokenToZero(fromToken);
36180
+ try {
36181
+ // If needed, we can switch the chain here
36182
+ // If already on the correct chain, this will do nothing
36183
+ await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36108
36184
  }
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,
36185
+ catch (error) {
36186
+ console.error("Error switching network:", error);
36187
+ }
36188
+ let approveTx;
36189
+ if (useIcs20) {
36190
+ const channel = squidRoute.estimate.actions[0].data
36191
+ .ibcChannel;
36192
+ const ics20Interface = new ethers.Interface(ics20Abi);
36193
+ const approveData = ics20Interface.encodeFunctionData("approve", [
36194
+ squidRoute.params.fromAddress,
36195
+ [
36196
+ {
36197
+ sourcePort: "transfer",
36198
+ sourceChannel: channel,
36199
+ spendLimit: [
36200
+ {
36201
+ denom: squidRoute.estimate.actions[0].fromToken
36202
+ .originalAddress,
36203
+ amount: squidRoute.params.fromAmount,
36204
+ },
36205
+ ],
36206
+ allowList: [],
36207
+ allowedPacketData: ["*"],
36159
36208
  },
36160
- });
36161
- }
36162
- if (isProblematicConnector(activeConnector)) {
36163
- await sleep(3_000);
36164
- }
36165
- await approveTx?.wait();
36166
- return true;
36209
+ ],
36210
+ ]);
36211
+ approveTx = await evmSigner.sendTransaction({
36212
+ to: squidRoute.transactionRequest.target,
36213
+ data: approveData,
36214
+ value: "0",
36215
+ gasLimit: squidRoute.transactionRequest
36216
+ .gasLimit,
36217
+ gasPrice: squidRoute.transactionRequest
36218
+ .gasPrice,
36219
+ });
36167
36220
  }
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;
36221
+ else {
36222
+ approveTx = await squid.approveRoute({
36223
+ route: squidRoute,
36224
+ signer: evmSigner,
36225
+ // For security reasons, we don't want to allow infinite approvals in our frontends
36226
+ executionSettings: {
36227
+ infiniteApproval: false,
36228
+ },
36229
+ });
36230
+ }
36231
+ if (isProblematicConnector(activeConnector)) {
36232
+ await sleep(3_000);
36233
+ }
36234
+ await approveTx?.wait();
36235
+ return true;
36174
36236
  }
36175
- },
36237
+ return false;
36238
+ }
36239
+ catch (error) {
36240
+ // Keep the error in the console to debug future issues
36241
+ console.error(error);
36242
+ return false;
36243
+ }
36244
+ }, {
36176
36245
  onSuccess: async () => {
36177
36246
  await allowanceQuery?.refetch();
36178
- queryClient.invalidateQueries({
36179
- queryKey: getPrefixKey(QueryKeys.RouteApproved),
36180
- });
36247
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.RouteApproved));
36181
36248
  // After an approval, we refetch the transaction query with all required parameters
36182
36249
  // This is to ensure we're using the latest expiry timestamp
36183
36250
  if (squidRoute) {
@@ -39297,10 +39364,8 @@ const useExecuteTransaction = (squidRoute) => {
39297
39364
  }
39298
39365
  }, [cosmosSigner, fromChain]);
39299
39366
  const resetQueriesAfterTxSigned = () => {
39300
- queryClient.refetchQueries({ queryKey: getPrefixKey(QueryKeys.Balance) });
39301
- queryClient.invalidateQueries({
39302
- queryKey: getPrefixKey(QueryKeys.Transaction),
39303
- });
39367
+ queryClient.refetchQueries(getPrefixKey(QueryKeys.Balance));
39368
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Transaction));
39304
39369
  };
39305
39370
  const dispatchSignatureRequestEvent = useCallback((route) => {
39306
39371
  WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
@@ -39318,64 +39383,62 @@ const useExecuteTransaction = (squidRoute) => {
39318
39383
  txHash,
39319
39384
  }, findToken);
39320
39385
  }, [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,
39386
+ const swapMutationCosmos = useMutation(async ({ id, route }) => {
39387
+ const fromChainId = route?.params.fromChain;
39388
+ if (cosmosSigner && fromChainId) {
39389
+ try {
39390
+ const signingClient = await getCosmosSignerClient();
39391
+ const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39392
+ if (signerAddress && signingClient && route) {
39393
+ dispatchSignatureRequestEvent(route);
39394
+ const tx$1 = (await squid?.executeRoute({
39395
+ signer: signingClient,
39396
+ signerAddress,
39397
+ route,
39398
+ }));
39399
+ // set the tx state to loading, as soon as user signed the tx
39400
+ setTransactionState({
39401
+ txHash: "",
39402
+ route,
39403
+ status: TransactionStatus.ONGOING,
39404
+ sourceStatus: TransactionStatus.ONGOING,
39405
+ id,
39406
+ });
39407
+ // broadcast the signed tx to get hash and listen to events
39408
+ const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39409
+ const hash = response.transactionHash;
39410
+ if (hash) {
39411
+ resetQueriesAfterTxSigned();
39412
+ }
39413
+ // Dispatch event so it can be listened from outside the widget
39414
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39415
+ const txParams = setTransactionState({
39416
+ route,
39417
+ txHash: hash,
39418
+ userAddress: sourceUserAddress,
39419
+ status: TransactionStatus.ONGOING,
39420
+ sourceStatus: TransactionStatus.ONGOING,
39421
+ axelarUrl: undefined,
39422
+ id,
39423
+ });
39424
+ if (txParams) {
39425
+ addSwapTransaction({
39426
+ ...txParams,
39427
+ params: route.params,
39428
+ estimate: route.estimate,
39359
39429
  });
39360
- if (txParams) {
39361
- addSwapTransaction({
39362
- ...txParams,
39363
- params: route.params,
39364
- estimate: route.estimate,
39365
- });
39366
- }
39367
- return response.code === 0;
39368
39430
  }
39431
+ return response.code === 0;
39369
39432
  }
39370
- catch (error) {
39371
- console.error("Error executing Cosmos transaction", error);
39372
- if (isUserRejectionError(normalizeError(error))) {
39373
- throw new Error("Request rejected");
39374
- }
39433
+ }
39434
+ catch (error) {
39435
+ console.error("Error executing Cosmos transaction", error);
39436
+ if (isUserRejectionError(normalizeError(error))) {
39437
+ throw new Error("Request rejected");
39375
39438
  }
39376
39439
  }
39377
- throw new Error("Need all parameters");
39378
- },
39440
+ }
39441
+ throw new Error("Need all parameters");
39379
39442
  });
39380
39443
  // If the transaction is replaced, we need to update the transaction hash
39381
39444
  // Transaction replaced can mean that the user has speed up the transaction for example
@@ -39428,126 +39491,97 @@ const useExecuteTransaction = (squidRoute) => {
39428
39491
  throw error;
39429
39492
  }
39430
39493
  }, [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,
39494
+ const swapMutationEvm = useMutation(async ({ id, route }) => {
39495
+ await changeNetworkIfNeeded.mutateAsync();
39496
+ if (!route || !squid || !evmSigner) {
39497
+ throw new Error("Need all parameters");
39498
+ }
39499
+ dispatchSignatureRequestEvent(route);
39500
+ const txResponse = (await squid.executeRoute({
39501
+ bypassBalanceChecks: true,
39502
+ signer: evmSigner,
39503
+ route,
39504
+ }));
39505
+ let hash = txResponse.hash;
39506
+ if (activeConnector?.id === "safe") {
39507
+ hash = await getGnosisTransactionHash(txResponse.hash);
39508
+ }
39509
+ if (hash) {
39510
+ resetQueriesAfterTxSigned();
39511
+ }
39512
+ // Dispatch event so it can be listened from outside the widget
39513
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39514
+ if (route.transactionRequest) {
39515
+ const txParams = setTransactionState({
39441
39516
  route,
39442
- }));
39443
- let hash = txResponse.hash;
39444
- if (activeConnector?.id === "safe") {
39445
- hash = await getGnosisTransactionHash(txResponse.hash);
39517
+ txHash: hash,
39518
+ nonce: txResponse.nonce,
39519
+ userAddress: sourceUserAddress,
39520
+ status: TransactionStatus.INITIAL_LOADING,
39521
+ sourceStatus: TransactionStatus.ONGOING,
39522
+ axelarUrl: undefined,
39523
+ id,
39524
+ });
39525
+ if (txParams) {
39526
+ addSwapTransaction({
39527
+ ...txParams,
39528
+ params: route.params,
39529
+ estimate: route.estimate,
39530
+ });
39446
39531
  }
39447
- if (hash) {
39448
- resetQueriesAfterTxSigned();
39532
+ }
39533
+ try {
39534
+ if (isProblematicConnector(activeConnector)) {
39535
+ await sleep(3_000);
39449
39536
  }
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
- }
39537
+ const response = await txResponse.wait();
39538
+ return response;
39539
+ }
39540
+ catch (error) {
39541
+ return handleTransactionReplacementError({
39542
+ error,
39543
+ route,
39544
+ status: TransactionStatus.INITIAL_LOADING,
39545
+ sourceStatus: TransactionStatus.ONGOING,
39546
+ userAddress: sourceUserAddress,
39547
+ axelarUrl: undefined,
39548
+ id,
39549
+ });
39550
+ }
39551
+ });
39552
+ const swapMutationSolana = useMutation(async ({ id, route }) => {
39553
+ try {
39554
+ if (!route) {
39555
+ throw new Error("Route is required");
39470
39556
  }
39471
- try {
39472
- if (isProblematicConnector(activeConnector)) {
39473
- await sleep(3_000);
39474
- }
39475
- const response = await txResponse.wait();
39476
- return response;
39557
+ if (!solanaSigner) {
39558
+ throw new Error("Solana signer is required");
39477
39559
  }
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
- });
39560
+ if (!route.params.fromAddress || !route.params.toAddress) {
39561
+ throw new Error("From or to address is required");
39488
39562
  }
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");
39499
- }
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;
39563
+ const isDirectTransfer = isDepositRoute(route);
39564
+ // Means it's a transfer to a deposit address
39565
+ // Instead of a Swap/Contract call using a DEX like Jupiter
39566
+ if (isDirectTransfer) {
39567
+ // Get the deposit address from the squidRoute
39568
+ const depositData = useDepositAddressStore.getState().deposit;
39569
+ // Validate params
39570
+ if (!depositData?.depositAddress) {
39571
+ throw new Error("Deposit address is required");
39540
39572
  }
39541
- const signature = await executeSolanaSwap({
39542
- route,
39573
+ const signature = await executeSolanaTransfer({
39574
+ amount: BigInt(route.params.fromAmount),
39575
+ target: depositData.depositAddress,
39543
39576
  signer: solanaSigner,
39544
39577
  connection: solanaConnection,
39578
+ sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39545
39579
  onSigned: (txHash) => {
39546
39580
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39547
39581
  const txParams = setTransactionState({
39548
39582
  route,
39549
39583
  txHash,
39550
- transactionIdForStatus: undefined,
39584
+ transactionIdForStatus: depositData.chainflipStatusTrackingId,
39551
39585
  userAddress: sourceUserAddress,
39552
39586
  status: TransactionStatus.INITIAL_LOADING,
39553
39587
  sourceStatus: TransactionStatus.ONGOING,
@@ -39564,13 +39598,39 @@ const useExecuteTransaction = (squidRoute) => {
39564
39598
  });
39565
39599
  return signature;
39566
39600
  }
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
- },
39601
+ const signature = await executeSolanaSwap({
39602
+ route,
39603
+ signer: solanaSigner,
39604
+ connection: solanaConnection,
39605
+ onSigned: (txHash) => {
39606
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39607
+ const txParams = setTransactionState({
39608
+ route,
39609
+ txHash,
39610
+ transactionIdForStatus: undefined,
39611
+ userAddress: sourceUserAddress,
39612
+ status: TransactionStatus.INITIAL_LOADING,
39613
+ sourceStatus: TransactionStatus.ONGOING,
39614
+ id,
39615
+ });
39616
+ if (txParams) {
39617
+ addSwapTransaction({
39618
+ ...txParams,
39619
+ params: route.params,
39620
+ estimate: route.estimate,
39621
+ });
39622
+ }
39623
+ },
39624
+ });
39625
+ return signature;
39626
+ }
39627
+ catch (error) {
39628
+ console.error("Solana transaction failed:", error);
39629
+ throw error instanceof Error
39630
+ ? error
39631
+ : new Error("Failed to execute Solana transaction");
39632
+ }
39633
+ }, {
39574
39634
  onError: (error, variables) => {
39575
39635
  const currentTx = getTransaction(variables.id);
39576
39636
  const errorObject = getTransactionError(error);
@@ -39591,9 +39651,7 @@ const useExecuteTransaction = (squidRoute) => {
39591
39651
  },
39592
39652
  onSuccess: (_data, variables) => {
39593
39653
  const currentTx = getTransaction(variables.id);
39594
- queryClient.invalidateQueries({
39595
- queryKey: getPrefixKey(QueryKeys.Balances),
39596
- });
39654
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39597
39655
  if (isSameChain && currentTx?.transactionId) {
39598
39656
  replaceSwapTransactionStatus({
39599
39657
  transactionId: currentTx.transactionId,
@@ -39610,207 +39668,197 @@ const useExecuteTransaction = (squidRoute) => {
39610
39668
  });
39611
39669
  },
39612
39670
  });
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;
39671
+ const swapMutationBitcoin = useMutation(async ({ id, route }) => {
39672
+ const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39673
+ if (!depositAddress) {
39674
+ throw new Error(`Invalid deposit address: ${depositAddress}`);
39675
+ }
39676
+ if (!sendAmount) {
39677
+ throw new Error(`Invalid send amount: ${sendAmount}`);
39678
+ }
39679
+ const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39680
+ await changeNetworkIfNeeded.mutateAsync();
39681
+ if (allParamsValid) {
39682
+ dispatchSignatureRequestEvent(route);
39683
+ const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39731
39684
  if (txHash) {
39732
39685
  resetQueriesAfterTxSigned();
39733
39686
  }
39687
+ // Dispatch event so it can be listened from outside the widget
39734
39688
  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,
39689
+ if (route.transactionRequest) {
39690
+ const txParams = setTransactionState({
39691
+ route,
39692
+ txHash,
39693
+ // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39694
+ // instead of the Bitcoin transaction hash
39695
+ transactionIdForStatus: chainflipStatusTrackingId,
39696
+ userAddress: sourceUserAddress,
39697
+ status: TransactionStatus.INITIAL_LOADING,
39698
+ sourceStatus: TransactionStatus.ONGOING,
39699
+ axelarUrl: undefined,
39700
+ id,
39748
39701
  });
39702
+ if (txParams) {
39703
+ addSwapTransaction({
39704
+ ...txParams,
39705
+ params: route.params,
39706
+ estimate: route.estimate,
39707
+ });
39708
+ }
39749
39709
  }
39750
- // wait for transaction confirmation
39751
- await suiClient.waitForTransaction({
39752
- digest: txHash,
39753
- });
39754
- },
39710
+ }
39711
+ else {
39712
+ throw new Error("Need all parameters");
39713
+ }
39755
39714
  });
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,
39715
+ const swapMutationXrpl = useMutation(async ({ id, route }) => {
39716
+ if (!route?.transactionRequest || !xrplSigner) {
39717
+ throw new Error("Need all parameters");
39718
+ }
39719
+ if (route.transactionRequest.type !== SquidDataType.OnChainExecution) {
39720
+ throw new Error("Invalid route type");
39721
+ }
39722
+ const { data } = route.transactionRequest;
39723
+ const paymentTx = parseXrplPaymentTx(data);
39724
+ if (!paymentTx)
39725
+ throw new Error("Could not parse transaction");
39726
+ const fromChainId = route.params.fromChain;
39727
+ const xrplNetwork = getXrplNetwork(fromChainId);
39728
+ if (xrplNetwork == null) {
39729
+ throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39730
+ }
39731
+ const txRes = await xrplSigner.signAndSubmit({
39732
+ tx: paymentTx,
39733
+ network: xrplNetwork,
39734
+ });
39735
+ const txParams = setTransactionState({
39736
+ txHash: txRes.hash,
39737
+ id,
39738
+ sourceStatus: TransactionStatus.ONGOING,
39739
+ status: TransactionStatus.ONGOING,
39740
+ route: route,
39741
+ userAddress: sourceUserAddress,
39742
+ });
39743
+ if (txParams && route) {
39744
+ addSwapTransaction({
39745
+ ...txParams,
39746
+ params: route.params,
39747
+ estimate: route.estimate,
39781
39748
  });
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,
39749
+ }
39750
+ if (txRes.status !== XrplTxStatus.SUCCESS) {
39751
+ throw new Error(`Transaction failed with status: ${txRes.status}`);
39752
+ }
39753
+ }, {});
39754
+ const swapMutationSui = useMutation(async ({ id, route }) => {
39755
+ if (!route || !suiSigner || !fromChain) {
39756
+ throw new Error("Need all parameters");
39757
+ }
39758
+ if (route.transactionRequest?.type !== SquidDataType.OnChainExecution) {
39759
+ throw new Error("Invalid route type");
39760
+ }
39761
+ const suiWalletState = connectedWalletsByChainType[ChainType.SUI];
39762
+ if (!suiWalletState.account) {
39763
+ throw new Error("Sui wallet is missing account data");
39764
+ }
39765
+ const fromChainId = route.params.fromChain;
39766
+ const suiChain = getSuiChain(fromChainId);
39767
+ if (!suiChain) {
39768
+ throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39769
+ }
39770
+ const suiClient = await getClient(fromChain);
39771
+ const txJson = route.transactionRequest.data;
39772
+ const tx = Transaction$2.from(txJson);
39773
+ const signedTx = await suiSigner.signTransaction({
39774
+ transaction: tx,
39775
+ account: suiWalletState.account,
39776
+ chain: suiChain,
39777
+ });
39778
+ // execute transaction without waiting for confirmation
39779
+ const txResponse = await suiClient.executeTransactionBlock({
39780
+ signature: signedTx.signature,
39781
+ transactionBlock: signedTx.bytes,
39782
+ });
39783
+ const txHash = txResponse.digest;
39784
+ if (txHash) {
39785
+ resetQueriesAfterTxSigned();
39786
+ }
39787
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39788
+ const txParams = setTransactionState({
39789
+ route,
39790
+ txHash,
39791
+ userAddress: sourceUserAddress,
39792
+ status: TransactionStatus.INITIAL_LOADING,
39793
+ sourceStatus: TransactionStatus.ONGOING,
39794
+ id,
39795
+ });
39796
+ if (txParams) {
39797
+ addSwapTransaction({
39798
+ ...txParams,
39799
+ params: route.params,
39800
+ estimate: route.estimate,
39797
39801
  });
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
- });
39802
+ }
39803
+ // wait for transaction confirmation
39804
+ await suiClient.waitForTransaction({
39805
+ digest: txHash,
39806
+ });
39807
+ }, {});
39808
+ const swapMutationStellar = useMutation(async ({ id, route }) => {
39809
+ if (!stellarSigner || !route || !squid || !fromChain) {
39810
+ throw new Error("Need all parameters");
39811
+ }
39812
+ const fromChainId = route.params.fromChain;
39813
+ const stellarNetwork = getStellarNetwork(fromChainId);
39814
+ if (stellarNetwork == null) {
39815
+ throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39816
+ }
39817
+ const { data: xdrHex, gasPrice } = route.transactionRequest;
39818
+ const { address } = await stellarSigner.getAddress();
39819
+ const client = await getClient(fromChain);
39820
+ const account = await client.getAccount(address);
39821
+ const operation = xdr.Operation.fromXDR(xdrHex, "hex");
39822
+ const builtTransaction = new TransactionBuilder(account, {
39823
+ fee: gasPrice || (BigInt(BASE_FEE) * BigInt(2)).toString(),
39824
+ networkPassphrase: stellarNetwork,
39825
+ })
39826
+ .addOperation(operation)
39827
+ .setTimeout(300)
39828
+ .build();
39829
+ const preparedTransaction = await client.prepareTransaction(builtTransaction);
39830
+ const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39831
+ networkPassphrase: stellarNetwork,
39832
+ });
39833
+ const signedTransaction = new Transaction$1(signedTxXdr, stellarNetwork);
39834
+ // get hash before submitting
39835
+ const hash = signedTransaction.hash().toString("hex");
39836
+ if (hash) {
39837
+ resetQueriesAfterTxSigned();
39838
+ }
39839
+ // Dispatch event so it can be listened from outside the widget
39840
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39841
+ const txParams = setTransactionState({
39842
+ route,
39843
+ txHash: hash,
39844
+ userAddress: sourceUserAddress,
39845
+ status: TransactionStatus.INITIAL_LOADING,
39846
+ sourceStatus: TransactionStatus.ONGOING,
39847
+ id,
39848
+ });
39849
+ if (txParams) {
39850
+ addSwapTransaction({
39851
+ ...txParams,
39852
+ params: route.params,
39853
+ estimate: route.estimate,
39854
+ });
39855
+ }
39856
+ const sentTransaction = await client.sendTransaction(signedTransaction);
39857
+ await client.waitForTransaction(sentTransaction.hash);
39858
+ }, {});
39809
39859
  const handleTransactionSuccess = useCallback((id) => {
39810
39860
  const currentTx = getTransaction(id);
39811
- queryClient.invalidateQueries({
39812
- queryKey: getPrefixKey(QueryKeys.Balances),
39813
- });
39861
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39814
39862
  if (isSameChain && currentTx?.transactionId) {
39815
39863
  replaceSwapTransactionStatus({
39816
39864
  transactionId: currentTx.transactionId,
@@ -39862,39 +39910,38 @@ const useExecuteTransaction = (squidRoute) => {
39862
39910
  setTransactionStoreState,
39863
39911
  squidRoute,
39864
39912
  ]);
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}`);
39913
+ const swapMutation = useMutation(async (mutationParams) => {
39914
+ if (!mutationParams.route)
39915
+ throw new Error("route is required");
39916
+ const sourceChain = findChain(mutationParams.route.params?.fromChain);
39917
+ if (!sourceChain)
39918
+ throw new Error("Could not find source chain");
39919
+ switch (sourceChain.chainType) {
39920
+ case ChainType.COSMOS: {
39921
+ return swapMutationCosmos.mutateAsync(mutationParams);
39896
39922
  }
39897
- },
39923
+ case ChainType.EVM: {
39924
+ return swapMutationEvm.mutateAsync(mutationParams);
39925
+ }
39926
+ case ChainType.BTC: {
39927
+ return swapMutationBitcoin.mutateAsync(mutationParams);
39928
+ }
39929
+ case ChainType.SOLANA: {
39930
+ return swapMutationSolana.mutateAsync(mutationParams);
39931
+ }
39932
+ case ChainType.SUI: {
39933
+ return swapMutationSui.mutateAsync(mutationParams);
39934
+ }
39935
+ case ChainType.XRPL: {
39936
+ return swapMutationXrpl.mutateAsync(mutationParams);
39937
+ }
39938
+ case ChainType.STELLAR: {
39939
+ return swapMutationStellar.mutateAsync(mutationParams);
39940
+ }
39941
+ default:
39942
+ throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39943
+ }
39944
+ }, {
39898
39945
  onMutate: (variables) => {
39899
39946
  useTransactionStore.setState({
39900
39947
  txLocalId: variables.id,
@@ -39943,7 +39990,7 @@ const useExecuteTransaction = (squidRoute) => {
39943
39990
  toToken,
39944
39991
  toChain,
39945
39992
  fromChain,
39946
- isPending: swapMutation.isPending,
39993
+ isLoading: swapMutation.isLoading,
39947
39994
  error: swapMutation.error,
39948
39995
  };
39949
39996
  };
@@ -40004,59 +40051,57 @@ const useGetRoute = () => {
40004
40051
  * These data will be used to trigger the transaction
40005
40052
  * @returns {Route} Route data
40006
40053
  */
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
- },
40054
+ return useMutation(async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40055
+ if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40056
+ return undefined;
40057
+ }
40058
+ // Dispatch requestQuote event
40059
+ dispatchRequestQuoteEvent({
40060
+ fromChain,
40061
+ toChain,
40062
+ fromToken: fromToken.address,
40063
+ toToken: toToken.address,
40064
+ fromAmount: fromPrice,
40065
+ fromAddress: sourceUserAddress,
40066
+ toAddress: destinationAddress,
40067
+ });
40068
+ const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40069
+ const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40070
+ const fromTokenAddress = fromToken.address;
40071
+ const toTokenAddress = toToken.address;
40072
+ const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40073
+ const fromAddress = sourceUserAddress ??
40074
+ chainTypeToZeroAddressMap[fromChainType ?? ChainType.EVM];
40075
+ const params = {
40076
+ fromChain,
40077
+ fromToken: fromTokenAddress,
40078
+ fromAddress,
40079
+ fromAmount,
40080
+ toChain,
40081
+ toToken: toTokenAddress,
40082
+ toAddress: destinationAddress ?? "",
40083
+ quoteOnly,
40084
+ slippage: config.slippage === 0 ? undefined : config.slippage,
40085
+ bypassGuardrails,
40086
+ preHook,
40087
+ postHook,
40088
+ };
40089
+ // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40090
+ if (cosmosFallbackAddresses &&
40091
+ cosmosFallbackAddresses.length > 0 &&
40092
+ cosmosFallbackAddresses[0].address) {
40093
+ params.fallbackAddresses = cosmosFallbackAddresses;
40094
+ }
40095
+ const { route } = await squid.getRoute({
40096
+ ...params,
40097
+ });
40098
+ // Cache the route data
40099
+ // Useful when the getRoute mutation is called from another hook
40100
+ 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);
40101
+ return route;
40057
40102
  });
40058
40103
  };
40059
- const useGetRouteWrapper = ({ enabled, gcTime = 5 * 60 * 1000, // 5 minutes
40104
+ const useGetRouteWrapper = ({ enabled, cacheTime = 5 * 60 * 1000, // 5 minutes
40060
40105
  staleTime = 60 * 1000, // 1 minute
40061
40106
  refetchOnWindowFocus = (query) => Date.now() - query.state.dataUpdatedAt > 30000, // Update if older than 30 seconds, when window is focused
40062
40107
  refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true, }) => {
@@ -40106,27 +40151,25 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40106
40151
  * These data will be used to trigger the transaction
40107
40152
  * @returns {Route} Route data
40108
40153
  */
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
- },
40154
+ const squidRoute = useQuery(squidRouteQueryKeys, async () => {
40155
+ const route = await getRouteMutation.mutateAsync({
40156
+ fromChain: fromChain?.chainId,
40157
+ toChain: toChain?.chainId,
40158
+ fromToken,
40159
+ toToken,
40160
+ sourceUserAddress,
40161
+ destinationAddress,
40162
+ fromPrice,
40163
+ bypassGuardrails: config.degenMode,
40164
+ quoteOnly,
40165
+ fromChainType: fromChain?.chainType,
40166
+ postHook: config.postHook,
40167
+ preHook: config.preHook,
40168
+ });
40169
+ return route;
40170
+ }, {
40128
40171
  enabled: queryEnabled,
40129
- gcTime,
40172
+ cacheTime,
40130
40173
  staleTime,
40131
40174
  refetchOnWindowFocus,
40132
40175
  refetchIntervalInBackground,
@@ -40135,7 +40178,7 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40135
40178
  /**
40136
40179
  * If last updated data is older than X seconds and the query is currently loading, show loading indicator
40137
40180
  */
40138
- const showLoading = squidRoute.isFetching || squidRoute.isRefetching;
40181
+ const showLoading = useMemo(() => squidRoute.isFetching || squidRoute.isRefetching, [squidRoute.isFetching, squidRoute.isRefetching]);
40139
40182
  return {
40140
40183
  squidRoute,
40141
40184
  showLoading,
@@ -40167,7 +40210,7 @@ function useSendTransactionStatus({ chain, txHash, }) {
40167
40210
  transactionId: txHash,
40168
40211
  txType: HistoryTxType.SEND,
40169
40212
  });
40170
- const { data: status, isSuccess, isError, } = useQuery({
40213
+ const { data: status } = useQuery({
40171
40214
  queryKey: keys().sendTransactionStatus(txHash, chain?.chainId),
40172
40215
  queryFn: async () => {
40173
40216
  if (!chain || !txHash)
@@ -40177,30 +40220,17 @@ function useSendTransactionStatus({ chain, txHash, }) {
40177
40220
  txHash,
40178
40221
  });
40179
40222
  },
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) {
40223
+ onSuccess: (txStatus) => {
40224
+ setIsTransactionComplete(txStatus !== SendTransactionStatus.ONGOING);
40225
+ if (txStatus != null && !!txHash) {
40196
40226
  replaceTransactionStatus({
40197
40227
  txType: HistoryTxType.SEND,
40198
- status: status,
40228
+ status: txStatus,
40199
40229
  hash: txHash,
40200
40230
  });
40201
40231
  }
40202
- }
40203
- if (isError) {
40232
+ },
40233
+ onError() {
40204
40234
  setIsTransactionComplete(true);
40205
40235
  if (txHash) {
40206
40236
  replaceTransactionStatus({
@@ -40209,8 +40239,19 @@ function useSendTransactionStatus({ chain, txHash, }) {
40209
40239
  hash: txHash,
40210
40240
  });
40211
40241
  }
40212
- }
40213
- }, [isError, isSuccess, replaceTransactionStatus, status, txHash]);
40242
+ },
40243
+ refetchInterval: chain
40244
+ ? getSendTxStatusRefetchInterval(chain.chainType)
40245
+ : false,
40246
+ enabled: !!chain &&
40247
+ !!txHash &&
40248
+ !isTransactionComplete &&
40249
+ !!currentHistoryItem &&
40250
+ !isHistoryTransactionEnded({
40251
+ data: currentHistoryItem?.data,
40252
+ txType: HistoryTxType.SEND,
40253
+ }),
40254
+ });
40214
40255
  return {
40215
40256
  status: status ?? currentHistoryItem?.data?.status,
40216
40257
  };
@@ -40244,9 +40285,7 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40244
40285
  apiUrl: latestConfig.apiUrl,
40245
40286
  });
40246
40287
  }, [transaction]);
40247
- const transactionStatusQuery = useQuery({
40248
- queryKey: keys().swapTransactionStatus(transaction?.transactionId),
40249
- queryFn: fetchTransactionStatusWithLatestConfig,
40288
+ const transactionStatusQuery = useQuery(keys().swapTransactionStatus(transaction?.transactionId), fetchTransactionStatusWithLatestConfig, {
40250
40289
  enabled: enabled &&
40251
40290
  transaction?.transactionId !== "0" &&
40252
40291
  !!transaction?.transactionId &&
@@ -40260,12 +40299,12 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40260
40299
  data: currentHistoryItem?.data,
40261
40300
  txType: HistoryTxType.SWAP,
40262
40301
  }),
40263
- refetchInterval({ state }) {
40302
+ refetchInterval(statusResponse) {
40264
40303
  // If the status response is something telling that the transaction
40265
40304
  // is finished, then store transaction history state if success
40266
40305
  // And return false to indicate refetcher to stop
40267
- if (state.data &&
40268
- transactionEndStatuses.includes(getTransactionStatus(state.data) ?? "")) {
40306
+ if (statusResponse &&
40307
+ transactionEndStatuses.includes(getTransactionStatus(statusResponse) ?? "")) {
40269
40308
  return false;
40270
40309
  }
40271
40310
  return refetchInterval; // Had to handle a variable here because after onError, we want the interval to stop
@@ -40274,10 +40313,7 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40274
40313
  retryDelay: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 5000 : 3000,
40275
40314
  retry: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 6 : retry,
40276
40315
  refetchOnWindowFocus,
40277
- });
40278
- useEffect(() => {
40279
- if (transactionStatusQuery.isSuccess && transactionStatusQuery.data) {
40280
- const statusResponse = transactionStatusQuery.data;
40316
+ onSuccess: (statusResponse) => {
40281
40317
  // Dispatch event
40282
40318
  WidgetEvents.getInstance().dispatchSwapStatus(statusResponse.squidTransactionStatus ?? "");
40283
40319
  const endStatus = getTransactionEndStatus({ statusResponse });
@@ -40289,9 +40325,8 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40289
40325
  status: endStatus,
40290
40326
  });
40291
40327
  }
40292
- }
40293
- if (transactionStatusQuery.isError) {
40294
- const error = transactionStatusQuery.error;
40328
+ },
40329
+ onError: (error) => {
40295
40330
  // `fetchTransactionStatus` throws an error with a cause being an AxiosError
40296
40331
  const is404 = is404Error(error.cause);
40297
40332
  if (!transaction?.transactionId)
@@ -40312,15 +40347,8 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40312
40347
  status: TransactionStatus.ERROR,
40313
40348
  });
40314
40349
  }
40315
- }
40316
- }, [
40317
- transactionStatusQuery.isSuccess,
40318
- transactionStatusQuery.isError,
40319
- transaction?.transactionId,
40320
- transactionStatusQuery.error,
40321
- replaceSwapTransactionStatus,
40322
- transactionStatusQuery.data,
40323
- ]);
40350
+ },
40351
+ });
40324
40352
  return {
40325
40353
  transactionStatusQuery,
40326
40354
  latestStatus: transactionStatusQuery.data
@@ -40363,7 +40391,7 @@ const useAvatar = (seed = zeroAddress) => {
40363
40391
  },
40364
40392
  // data is static, so no need to refetch
40365
40393
  refetchOnWindowFocus: false,
40366
- gcTime: Infinity,
40394
+ cacheTime: Infinity,
40367
40395
  staleTime: Infinity,
40368
40396
  });
40369
40397
  return avatar || "";
@@ -40405,40 +40433,38 @@ const useAddToken = (chainToCompare, tokenToCompare) => {
40405
40433
  /**
40406
40434
  * Add token to wallet
40407
40435
  */
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 {
40436
+ const addToken = useMutation(async ({ chain: _chain, token: _token, }) => {
40437
+ const token = _token ?? tokenToCompare;
40438
+ const chain = _chain ?? chainToCompare;
40439
+ if (token && chain?.chainType === ChainType.EVM) {
40440
+ const provider = await connector?.getProvider();
40441
+ // Switch network if needed
40442
+ if (currentEvmChain?.id.toString() !== token?.chainId) {
40443
+ try {
40444
+ await switchChainAsync({
40445
+ chainId: +token.chainId,
40446
+ });
40447
+ }
40448
+ catch (error) {
40449
+ console.debug("Error switching network:", error);
40450
+ if (isEvmChainNotSupportedError(error)) {
40451
+ await addEthereumChain({
40452
+ chain,
40453
+ provider,
40454
+ });
40417
40455
  await switchChainAsync({
40418
40456
  chainId: +token.chainId,
40419
40457
  });
40420
40458
  }
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
40459
  }
40437
- await addTokenToWallet({ token, provider });
40460
+ // Metamask is not popping the second modal if we don't wait a bit
40461
+ // eslint-disable-next-line no-promise-executor-return
40462
+ await new Promise((resolve) => setTimeout(resolve, 100));
40438
40463
  }
40439
- // TODO: Implement keplr add token
40440
- return false;
40464
+ await addTokenToWallet({ token, provider });
40441
40465
  }
40466
+ // TODO: Implement keplr add token
40467
+ return false;
40442
40468
  });
40443
40469
  return {
40444
40470
  addToken,
@@ -40643,9 +40669,7 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40643
40669
  }
40644
40670
  },
40645
40671
  async onSuccess() {
40646
- queryClient.invalidateQueries({
40647
- queryKey: getPrefixKey(QueryKeys.XrplTrustLine),
40648
- });
40672
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.XrplTrustLine));
40649
40673
  },
40650
40674
  });
40651
40675
  /**
@@ -40823,5 +40847,5 @@ const SquidProvider = ({ children, config, placeholder, }) => {
40823
40847
  React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
40824
40848
  };
40825
40849
 
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
40850
+ 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 };
40851
+ //# sourceMappingURL=index-jI-SulDo.js.map