@0xsquid/react-hooks 8.0.1-para-beta.5 → 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 (44) 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 +13 -19
  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-CjNxoWnC.js → index-DVmnHUzP.js} +1148 -1168
  24. package/dist/{index-CjNxoWnC.js.map → index-DVmnHUzP.js.map} +1 -1
  25. package/dist/{index-gPUCtJnZ.js → index-jI-SulDo.js} +1147 -1170
  26. package/dist/index-jI-SulDo.js.map +1 -0
  27. package/dist/index.esm.js +3 -5
  28. package/dist/index.esm.js.map +1 -1
  29. package/dist/index.js +7 -6
  30. package/dist/index.js.map +1 -1
  31. package/dist/provider/index.d.ts +0 -2
  32. package/dist/{secretService-Dp2zmZW_.js → secretService-DBxDcfuA.js} +4 -6
  33. package/dist/{secretService-Dp2zmZW_.js.map → secretService-DBxDcfuA.js.map} +1 -1
  34. package/dist/{secretService-7WbMaDcW.js → secretService-DN5IzV4w.js} +4 -6
  35. package/dist/{secretService-7WbMaDcW.js.map → secretService-DN5IzV4w.js.map} +1 -1
  36. package/dist/services/internal/configService.d.ts +1 -0
  37. package/dist/services/internal/eventService.d.ts +1 -0
  38. package/dist/{stellarService.client-CfGdqxtp.js → stellarService.client-7sSrAZi2.js} +4 -6
  39. package/dist/{stellarService.client-CfGdqxtp.js.map → stellarService.client-7sSrAZi2.js.map} +1 -1
  40. package/dist/{stellarService.client-CqP7EehD.js → stellarService.client-DTFEi5m2.js} +4 -6
  41. package/dist/{stellarService.client-CqP7EehD.js.map → stellarService.client-DTFEi5m2.js.map} +1 -1
  42. package/package.json +14 -19
  43. package/dist/index-gPUCtJnZ.js.map +0 -1
  44. package/scripts/setup-para.js +0 -62
@@ -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, QueryClient, QueryClientProvider, useQueries } 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';
@@ -22,7 +22,7 @@ import getSymbolFromCurrency from 'currency-symbol-map';
22
22
  import Fuse from 'fuse.js';
23
23
  import { create } from 'zustand';
24
24
  import { persist } from 'zustand/middleware';
25
- import { useAccount, useConnectors, useConnect, useDisconnect, useSwitchChain, useBalance, useReadContract, createConfig, http, WagmiProvider, useWalletClient, usePublicClient } from 'wagmi';
25
+ import { useAccount, useConnectors, useConnect, useDisconnect, useSwitchChain, useBalance, useReadContract, createConfig, http, useWalletClient, usePublicClient, WagmiProvider } from 'wagmi';
26
26
  import SafeAppsSDK, { TransactionStatus as TransactionStatus$1 } from '@safe-global/safe-apps-sdk';
27
27
  import { getWallets } from '@wallet-standard/core';
28
28
  import { SlushWallet } from '@mysten/slush-wallet';
@@ -30,13 +30,11 @@ import { StargateClient, SigningStargateClient } from '@cosmjs/stargate';
30
30
  import { SuiClient } from '@mysten/sui/client';
31
31
  import { coin as coin$1 } from '@cosmjs/proto-signing';
32
32
  import { Transaction as Transaction$2 } from '@mysten/sui/transactions';
33
- import { paraConnector } from '@getpara/wagmi-v2-integration';
34
- import Para from '@getpara/web-sdk';
35
33
  import { injected, safe, metaMask, coinbaseWallet, walletConnect } from 'wagmi/connectors';
36
- import { Squid } from '@0xsquid/sdk';
37
- import { mainnet } from 'viem/chains';
38
34
  import { SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate';
39
35
  import { InjectiveSigningStargateClient } from '@injectivelabs/sdk-ts/dist/cjs/core/stargate/index.js';
36
+ import { Squid } from '@0xsquid/sdk';
37
+ import { mainnet } from 'viem/chains';
40
38
 
41
39
  const squidApiBaseUrl = "https://api.uatsquidrouter.com";
42
40
 
@@ -3983,6 +3981,20 @@ class WidgetEvents extends EventTarget {
3983
3981
  constructor() {
3984
3982
  super();
3985
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
+ };
3986
3998
  // Singleton, because we need to access this service outside the widget
3987
3999
  static getInstance() {
3988
4000
  if (!WidgetEvents.instance) {
@@ -4033,7 +4045,7 @@ class WidgetEvents extends EventTarget {
4033
4045
  * @param route
4034
4046
  */
4035
4047
  dispatchSwapExecuteCall(route, txHash) {
4036
- this.dispatch("swap", { route, txHash });
4048
+ this.dispatch("swap", this.getRouteEventPayload(route, txHash));
4037
4049
  }
4038
4050
  /**
4039
4051
  * Dispatch event when user changes chain/token
@@ -4112,7 +4124,18 @@ class WidgetEvents extends EventTarget {
4112
4124
  * @param data Quote execution parameters
4113
4125
  */
4114
4126
  dispatchOnrampQuoteExecute(data) {
4115
- 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
+ });
4116
4139
  }
4117
4140
  /**
4118
4141
  * Dispatch event when the search query has no results
@@ -26767,6 +26790,9 @@ const getConfigWithDefaults = (config) => {
26767
26790
  postHook: get$3(config, "postHook", defaultConfigValues.postHook),
26768
26791
  };
26769
26792
  };
26793
+ const randomIntFromInterval = (min, max) => {
26794
+ return Math.floor(Math.random() * (max - min + 1) + min);
26795
+ };
26770
26796
  const getTokensForChain = (tokens, chainId) => {
26771
26797
  return chainId ? tokens.filter((t) => t.chainId === chainId) : tokens;
26772
26798
  };
@@ -26794,9 +26820,7 @@ const fetchHighestBalanceToken = (fetchCachedBalance, chainId) => {
26794
26820
  if (fetchCachedBalance) {
26795
26821
  const queryCache = fetchCachedBalance?.queryClient?.getQueryCache();
26796
26822
  // get cached balance from key
26797
- const cache = queryCache?.find({
26798
- queryKey: keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? ChainType.EVM : ChainType.COSMOS),
26799
- });
26823
+ const cache = queryCache?.find(keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? ChainType.EVM : ChainType.COSMOS));
26800
26824
  // Parse result to TokenWithBalance[]
26801
26825
  const cacheResult = cache?.state.data ?? [];
26802
26826
  if (cacheResult.length > 0) {
@@ -27452,7 +27476,7 @@ const filterViewableTokens = (tokens, config, direction) => {
27452
27476
  };
27453
27477
  const getSecretNetworkBalances = async (chainData, cosmosAddress, squidTokens, keplrTypeWallet) => {
27454
27478
  const squidSecretTokens = squidTokens.filter((t) => t.chainId === CHAIN_IDS.SECRET);
27455
- const { fetchAllSecretBalances } = await import('./secretService-7WbMaDcW.js');
27479
+ const { fetchAllSecretBalances } = await import('./secretService-DN5IzV4w.js');
27456
27480
  return fetchAllSecretBalances(chainData, cosmosAddress, squidSecretTokens, keplrTypeWallet);
27457
27481
  };
27458
27482
  function getTokenAssetsKey(token) {
@@ -29211,16 +29235,13 @@ const useSquid = () => {
29211
29235
  * Fetch squid info
29212
29236
  * Will refetch every minute
29213
29237
  */
29214
- const squidInfoQuery = useQuery({
29215
- queryKey: keys().squidInfo(),
29216
- queryFn: async () => {
29217
- if (squid) {
29218
- await squid?.init();
29219
- initializeSquidWithAssetsColors(squid, assetsColors);
29220
- return squid;
29221
- }
29222
- return null;
29238
+ const squidInfoQuery = useQuery(keys().squidInfo(), async () => {
29239
+ if (squid) {
29240
+ await squid?.init();
29241
+ initializeSquidWithAssetsColors(squid, assetsColors);
29242
+ return squid;
29223
29243
  }
29244
+ return null;
29224
29245
  });
29225
29246
  const tokens = useMemo(() => {
29226
29247
  if ((squidInfoQuery?.data?.tokens ?? []).length > 0) {
@@ -29336,11 +29357,47 @@ const FINAL_TRANSACTION_STATUSES = [
29336
29357
  "completed",
29337
29358
  "failed",
29338
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
+ };
29339
29396
  /**
29340
29397
  * Fetches quotes for fiat to crypto conversion with provider details.
29341
29398
  * Returns available rates, fees, and supported payment methods for the conversion.
29342
29399
  */
29343
- const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, }) => {
29400
+ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, onSuccess, }) => {
29344
29401
  const service = useMemo(() => new OnrampService(), []);
29345
29402
  const { data: config } = useGetOnRampConfig();
29346
29403
  return useQuery({
@@ -29376,6 +29433,7 @@ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, payme
29376
29433
  return quoteResponse;
29377
29434
  },
29378
29435
  enabled: enabled && !!fiatCurrency && !!cryptoCurrencyID && amount > 0,
29436
+ onSuccess,
29379
29437
  });
29380
29438
  };
29381
29439
  /**
@@ -29392,7 +29450,7 @@ const useGetOnRampConfig = () => {
29392
29450
  chains,
29393
29451
  tokens,
29394
29452
  }),
29395
- gcTime: 1000 * 60 * 60,
29453
+ cacheTime: 1000 * 60 * 60,
29396
29454
  staleTime: 1000 * 60 * 30, // 30 minutes
29397
29455
  });
29398
29456
  };
@@ -29450,11 +29508,49 @@ const useExecuteFiatQuote = () => {
29450
29508
  },
29451
29509
  });
29452
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
+ };
29453
29548
  /**
29454
29549
  * Gets currency details including symbol and limits.
29455
29550
  * Example: USD → { symbol: "$", name: "US Dollar", ... }
29456
29551
  */
29457
29552
  const useCurrencyDetails = (currencyCode) => {
29553
+ const { data: config } = useGetOnRampConfig();
29458
29554
  return useMemo(() => {
29459
29555
  if (!currencyCode)
29460
29556
  return undefined;
@@ -29467,7 +29563,7 @@ const useCurrencyDetails = (currencyCode) => {
29467
29563
  };
29468
29564
  }
29469
29565
  return undefined;
29470
- }, [currencyCode]);
29566
+ }, [currencyCode, config?.supportedFiats]);
29471
29567
  };
29472
29568
  /**
29473
29569
  * Gets country details with flag URL and localized name.
@@ -29494,6 +29590,23 @@ const useAvailableQuotes = (quotes) => {
29494
29590
  return uniqueQuotes;
29495
29591
  }, [quotes]);
29496
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
+ };
29497
29610
  /**
29498
29611
  * Fetches the available payment methods for a given fiat and crypto currency pair.
29499
29612
  * The first item in the returned array is the most recommended.
@@ -29596,7 +29709,7 @@ const middleStepChecker = (statusResponse) => {
29596
29709
  }
29597
29710
  return TransactionStatus.ERROR;
29598
29711
  }
29599
- if (statusResponse?.isLoading) {
29712
+ if (statusResponse?.isInitialLoading) {
29600
29713
  return TransactionStatus.INITIAL_LOADING;
29601
29714
  }
29602
29715
  return TransactionStatus.ONGOING;
@@ -30041,7 +30154,7 @@ const useClient = () => {
30041
30154
  queryFn: getUserCountry,
30042
30155
  enabled: isClient,
30043
30156
  retry: false,
30044
- gcTime: CACHE_TIME,
30157
+ cacheTime: CACHE_TIME,
30045
30158
  staleTime: STALE_TIME,
30046
30159
  });
30047
30160
  const userCountry = countryData?.countryCode || DEFAULT_COUNTRY_CODE;
@@ -30142,13 +30255,11 @@ function useDebouncedValue(value, delay) {
30142
30255
  * @returns the ENS data of the given address
30143
30256
  */
30144
30257
  function useEnsDataForAddress({ address, options, }) {
30145
- const ensQuery = useQuery({
30146
- queryKey: keys().ensData(address?.toLowerCase()),
30147
- queryFn: () => EnsService.getEnsDataFromAddress(address),
30258
+ const ensQuery = useQuery(keys().ensData(address?.toLowerCase()), () => EnsService.getEnsDataFromAddress(address), {
30148
30259
  ...options,
30149
30260
  enabled: Boolean(address?.trim()) &&
30150
30261
  (options?.enabled === undefined ? true : options.enabled),
30151
- gcTime: Infinity,
30262
+ cacheTime: Infinity,
30152
30263
  });
30153
30264
  return ensQuery;
30154
30265
  }
@@ -30164,16 +30275,14 @@ function useEnsDataForAddress({ address, options, }) {
30164
30275
  */
30165
30276
  function useEnsSearch({ name, enabled = true, delayMs = 500, }) {
30166
30277
  const debouncedName = useDebouncedValue(enabled ? name : undefined, delayMs);
30167
- const ensSearchQuery = useQuery({
30168
- queryKey: keys().ensSearch(debouncedName),
30169
- queryFn: () => {
30170
- const isExactEnsSearch = checkIsExactEns(debouncedName);
30171
- return isExactEnsSearch
30172
- ? EnsService.getExactEns(debouncedName)
30173
- : EnsService.searchEnsNames(debouncedName);
30174
- },
30278
+ const ensSearchQuery = useQuery(keys().ensSearch(debouncedName), () => {
30279
+ const isExactEnsSearch = checkIsExactEns(debouncedName);
30280
+ return isExactEnsSearch
30281
+ ? EnsService.getExactEns(debouncedName)
30282
+ : EnsService.searchEnsNames(debouncedName);
30283
+ }, {
30175
30284
  enabled: Boolean(debouncedName?.trim()) && enabled,
30176
- gcTime: Infinity,
30285
+ cacheTime: Infinity,
30177
30286
  });
30178
30287
  return ensSearchQuery;
30179
30288
  }
@@ -30194,25 +30303,23 @@ function checkIsExactEns(name = "") {
30194
30303
 
30195
30304
  const useCosmosForChain = (chain) => {
30196
30305
  const { keplrTypeWallet } = useCosmosSigner({ chain });
30197
- const cosmosAddressQuery = useQuery({
30198
- queryKey: keys().cosmosAddress(chain?.chainId),
30199
- queryFn: async () => {
30200
- if (!chain || !keplrTypeWallet)
30201
- return "";
30202
- try {
30203
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30204
- return address ?? "";
30205
- }
30206
- catch (error) {
30207
- await suggestChainOrThrow({
30208
- chain: chain,
30209
- error,
30210
- keplrTypeWallet,
30211
- });
30212
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30213
- return address ?? "";
30214
- }
30215
- },
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
+ }, {
30216
30323
  enabled: !!keplrTypeWallet && chain?.chainType === ChainType.COSMOS,
30217
30324
  });
30218
30325
  return cosmosAddressQuery;
@@ -30289,14 +30396,12 @@ const useIsSameAddressAndGnosisContext = () => {
30289
30396
 
30290
30397
  function useBitcoin() {
30291
30398
  const connectedBitcoinWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.BTC]);
30292
- const connectBitcoin = useMutation({
30293
- mutationFn: async ({ wallet, }) => {
30294
- const { address } = await wallet.connector.requestAccount();
30295
- return {
30296
- wallet,
30297
- address,
30298
- };
30299
- }
30399
+ const connectBitcoin = useMutation(async ({ wallet, }) => {
30400
+ const { address } = await wallet.connector.requestAccount();
30401
+ return {
30402
+ wallet,
30403
+ address,
30404
+ };
30300
30405
  });
30301
30406
  return {
30302
30407
  connectBitcoin,
@@ -30336,17 +30441,15 @@ function useEvm() {
30336
30441
  const { wallets } = useEvmWallets();
30337
30442
  const connectedEvmWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.EVM]);
30338
30443
  const recentEvmWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.EVM]);
30339
- const connectEvm = useMutation({
30340
- mutationFn: async ({ wallet, }) => {
30341
- const result = await connectAsync({
30342
- connector: wallet.connector,
30343
- });
30344
- const [firstAddress] = result.accounts;
30345
- return {
30346
- wallet,
30347
- address: firstAddress,
30348
- };
30349
- }
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
+ };
30350
30453
  });
30351
30454
  const disconnectEvm = useCallback(async () => {
30352
30455
  disconnect({ connector: connectedEvmWallet.wallet?.connector });
@@ -30440,23 +30543,21 @@ function useSolana() {
30440
30543
  const { wallets } = useSolanaWallets();
30441
30544
  const connectedSolanaWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.SOLANA]);
30442
30545
  const recentSolanaWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.SOLANA]);
30443
- const connectSolana = useMutation({
30444
- mutationFn: async ({ wallet, }) => {
30445
- try {
30446
- // try to connect silently first
30447
- await wallet.connector.autoConnect();
30448
- }
30449
- catch {
30450
- // if auto-connect fails (e.g. not authorized yet)
30451
- // fallback to connect via popup
30452
- await wallet.connector.connect();
30453
- }
30454
- const address = wallet.connector.wallet.accounts[0].address;
30455
- return {
30456
- wallet,
30457
- address,
30458
- };
30546
+ const connectSolana = useMutation(async ({ wallet, }) => {
30547
+ try {
30548
+ // try to connect silently first
30549
+ await wallet.connector.autoConnect();
30550
+ }
30551
+ catch {
30552
+ // if auto-connect fails (e.g. not authorized yet)
30553
+ // fallback to connect via popup
30554
+ await wallet.connector.connect();
30459
30555
  }
30556
+ const address = wallet.connector.wallet.accounts[0].address;
30557
+ return {
30558
+ wallet,
30559
+ address,
30560
+ };
30460
30561
  });
30461
30562
  const disconnectSolana = useCallback(async () => {
30462
30563
  await connectedSolanaWallet.wallet?.connector.disconnect();
@@ -30531,7 +30632,7 @@ function useStellarWallets() {
30531
30632
  return;
30532
30633
  try {
30533
30634
  const { allowAllModules: initializeAllModules } = await import('@creit.tech/stellar-wallets-kit');
30534
- const { formatStellarWallet } = await import('./stellarService.client-CfGdqxtp.js');
30635
+ const { formatStellarWallet } = await import('./stellarService.client-7sSrAZi2.js');
30535
30636
  const modules = initializeAllModules();
30536
30637
  const promises = modules.map(async (module) => {
30537
30638
  const isAvailable = await module.isAvailable();
@@ -30559,14 +30660,12 @@ function useStellarWallets() {
30559
30660
  function useStellar() {
30560
30661
  const { wallets } = useStellarWallets();
30561
30662
  const connectedStellarWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.STELLAR]);
30562
- const connectStellar = useMutation({
30563
- mutationFn: async ({ wallet, }) => {
30564
- const { address } = await wallet.connector.getAddress();
30565
- return {
30566
- wallet,
30567
- address,
30568
- };
30569
- }
30663
+ const connectStellar = useMutation(async ({ wallet, }) => {
30664
+ const { address } = await wallet.connector.getAddress();
30665
+ return {
30666
+ wallet,
30667
+ address,
30668
+ };
30570
30669
  });
30571
30670
  const disconnectStellar = useCallback(async () => {
30572
30671
  await connectedStellarWallet.wallet?.connector.disconnect?.();
@@ -30618,24 +30717,22 @@ function useSui() {
30618
30717
  const recentSuiWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.SUI]);
30619
30718
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
30620
30719
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
30621
- const connectSui = useMutation({
30622
- mutationFn: async ({ wallet, }) => {
30623
- let account;
30624
- try {
30625
- // try to connect silently first
30626
- account = await wallet.connector.connect({ silent: true });
30627
- }
30628
- catch {
30629
- // if auto-connect fails (e.g. not authorized yet)
30630
- // fallback to connect via popup
30631
- account = await wallet.connector.connect();
30632
- }
30633
- return {
30634
- wallet,
30635
- address: account.account.address,
30636
- account: account.account,
30637
- };
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 });
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();
30638
30730
  }
30731
+ return {
30732
+ wallet,
30733
+ address: account.account.address,
30734
+ account: account.account,
30735
+ };
30639
30736
  });
30640
30737
  const disconnectSui = useCallback(async () => {
30641
30738
  await connectedSuiWallet.wallet?.connector.disconnect();
@@ -30944,14 +31041,12 @@ function useXrpl() {
30944
31041
  const recentXrplWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.XRPL]);
30945
31042
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
30946
31043
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
30947
- const connectXrpl = useMutation({
30948
- mutationFn: async ({ wallet, }) => {
30949
- const xrplConnectedAddress = await wallet.connector.connect();
30950
- return {
30951
- wallet,
30952
- address: xrplConnectedAddress,
30953
- };
30954
- }
31044
+ const connectXrpl = useMutation(async ({ wallet, }) => {
31045
+ const xrplConnectedAddress = await wallet.connector.connect();
31046
+ return {
31047
+ wallet,
31048
+ address: xrplConnectedAddress,
31049
+ };
30955
31050
  });
30956
31051
  const disconnectXrpl = useCallback(async () => {
30957
31052
  await connectedXrplWallet?.wallet?.connector.disconnect?.();
@@ -31338,19 +31433,18 @@ const useMultiChainWallet = (chain) => {
31338
31433
  /**
31339
31434
  * Change current network for desired chain
31340
31435
  */
31341
- const changeNetworkIfNeeded = useMutation({
31342
- mutationFn: async () => {
31343
- const isNotOnDesiredChain = chain?.chainType === ChainType.EVM &&
31344
- currentEvmChain?.id !== Number(chain.chainId);
31345
- if (isNotOnDesiredChain) {
31346
- await switchChainAsync({
31347
- chainId: Number(chain.chainId),
31348
- });
31349
- }
31350
- // Implement keplr change network
31351
- // Looks like there are no method to do that at the moment
31352
- return false;
31353
- },
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
+ }, {
31354
31448
  onError: async (error) => {
31355
31449
  if (error instanceof UserRejectedRequestError) {
31356
31450
  return;
@@ -31362,7 +31456,7 @@ const useMultiChainWallet = (chain) => {
31362
31456
  provider,
31363
31457
  });
31364
31458
  }
31365
- }
31459
+ },
31366
31460
  });
31367
31461
  const isChainTypeConnected = useCallback((chainType) => {
31368
31462
  if (isGnosisConnected && chainType === ChainType.EVM) {
@@ -31710,53 +31804,51 @@ const useCosmos = () => {
31710
31804
  clientWindow?.removeEventListener("keplr_keystorechange", () => handleKeplrAccountChanged());
31711
31805
  };
31712
31806
  }, [handleKeplrAccountChanged, clientWindow]);
31713
- const connectCosmos = useMutation({
31714
- mutationFn: async ({ chain, wallet, approveAllChains = true, }) => {
31715
- const chainInfos = getCosmosChainInfosObject(chain);
31716
- const cosmosWalletObject = wallet.connector().provider;
31717
- if (cosmosWalletObject) {
31718
- setCosmosChainId(chainInfos.chainId.toString());
31719
- try {
31720
- if (approveAllChains &&
31721
- typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31722
- "function") {
31723
- try {
31724
- const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31725
- const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31726
- const chainsToEnable = cosmosChains
31727
- .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31728
- .map((c) => c.chainId.toString());
31729
- await cosmosWalletObject.enable(chainsToEnable);
31730
- }
31731
- catch (error) {
31732
- console.warn("Failed to get chain infos, falling back to single chain enable", error);
31733
- await cosmosWalletObject.enable(chainInfos.chainId);
31734
- }
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);
31735
31823
  }
31736
- else {
31824
+ catch (error) {
31825
+ console.warn("Failed to get chain infos, falling back to single chain enable", error);
31737
31826
  await cosmosWalletObject.enable(chainInfos.chainId);
31738
31827
  }
31739
- const address = await getAddress({
31740
- chainId: chain.chainId.toString(),
31741
- cosmosWalletObject,
31742
- wallet,
31743
- });
31744
- if (address) {
31745
- updateWalletStore(wallet, cosmosWalletObject, address);
31746
- return address;
31747
- }
31748
31828
  }
31749
- catch (error) {
31750
- await suggestChainOrThrow({
31751
- chain,
31752
- error,
31753
- keplrTypeWallet: cosmosWalletObject,
31754
- });
31755
- 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;
31756
31840
  }
31757
31841
  }
31758
- return undefined;
31759
- },
31842
+ catch (error) {
31843
+ await suggestChainOrThrow({
31844
+ chain,
31845
+ error,
31846
+ keplrTypeWallet: cosmosWalletObject,
31847
+ });
31848
+ return connectCosmos.mutateAsync({ chain, wallet });
31849
+ }
31850
+ }
31851
+ return undefined;
31760
31852
  });
31761
31853
  const clearData = () => {
31762
31854
  disconnectWallet(ChainType.COSMOS);
@@ -31805,7 +31897,7 @@ function useCosmosSigner({ chain }) {
31805
31897
  // use Amino signer for Ledger compatibility
31806
31898
  const newCosmosSigner = getCosmosSignerForChain(chain.chainId, connector);
31807
31899
  return newCosmosSigner;
31808
- }, [chain?.chainId, chain?.chainType, connector, getCosmosSignerForChain]);
31900
+ }, [chain?.chainId, chain?.chainType, connector]);
31809
31901
  return { signer, keplrTypeWallet: connector };
31810
31902
  }
31811
31903
 
@@ -31910,11 +32002,11 @@ const useSquidQueryClient = () => {
31910
32002
  const queryClient = useQueryClient();
31911
32003
  const invalidateQueries = (key) => {
31912
32004
  const prefixKey = getPrefixKey(key);
31913
- queryClient.invalidateQueries({ queryKey: prefixKey });
32005
+ queryClient.invalidateQueries(prefixKey);
31914
32006
  };
31915
32007
  const refetchQueries = (key) => {
31916
32008
  const prefixKey = getPrefixKey(key);
31917
- queryClient.refetchQueries({ queryKey: prefixKey });
32009
+ queryClient.refetchQueries(prefixKey);
31918
32010
  };
31919
32011
  const invalidateAndRefetchQueries = (key) => {
31920
32012
  invalidateQueries(key);
@@ -33421,19 +33513,17 @@ function useDepositAddress(squidRoute) {
33421
33513
  toggleDepositFlow(false);
33422
33514
  setDeposit(null);
33423
33515
  }, [toggleDepositFlow, setDeposit]);
33424
- const getRouteWithDeposit = useMutation({
33425
- mutationFn: async ({ route }) => {
33426
- if (!squid)
33427
- throw new Error("Squid SDK not initialized");
33428
- const depositAddressResponse = (await squid.executeRoute({
33429
- signer: {},
33430
- route,
33431
- }));
33432
- setDeposit(depositAddressResponse);
33433
- return {
33434
- depositAddress: depositAddressResponse,
33435
- };
33436
- }
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
+ };
33437
33527
  });
33438
33528
  return {
33439
33529
  isEnabled,
@@ -33517,55 +33607,53 @@ const useAllTokensWithBalanceForChainType = ({ chainType, address, direction, qu
33517
33607
  xrplTokens.length,
33518
33608
  stellarTokens.length,
33519
33609
  ]);
33520
- const query = useQuery({
33521
- queryKey: keys().allTokensBalance(address, chainType, direction),
33522
- queryFn: async () => {
33523
- // Return zero balances if no address
33524
- if (!address) {
33525
- const defaultTokens = placeholderData.tokens;
33526
- return {
33527
- tokens: defaultTokens,
33528
- totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33529
- };
33530
- }
33531
- let fetchedTokens = [];
33532
- // Fetch tokens based on chain type
33533
- switch (chainType) {
33534
- case ChainType.EVM:
33535
- fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33536
- break;
33537
- case ChainType.COSMOS:
33538
- const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33539
- fetchedTokens = await getAllCosmosBalances({
33540
- addresses,
33541
- cosmosChains,
33542
- cosmosTokens,
33543
- });
33544
- break;
33545
- case ChainType.SOLANA:
33546
- fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33547
- break;
33548
- case ChainType.BTC:
33549
- fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33550
- break;
33551
- case ChainType.SUI:
33552
- fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33553
- break;
33554
- case ChainType.XRPL:
33555
- fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33556
- break;
33557
- case ChainType.STELLAR:
33558
- fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33559
- break;
33560
- default:
33561
- fetchedTokens = placeholderData.tokens;
33562
- break;
33563
- }
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;
33564
33614
  return {
33565
- tokens: fetchedTokens,
33566
- totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33615
+ tokens: defaultTokens,
33616
+ totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33567
33617
  };
33568
- },
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
+ }, {
33569
33657
  ...queryOptions,
33570
33658
  enabled: isQueryEnabled,
33571
33659
  });
@@ -33580,7 +33668,7 @@ const BALANCE_STALE_TIME = 60000; // 1 minute
33580
33668
  const BALANCE_CACHE_TIME = 300000; // 5 minutes
33581
33669
  const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33582
33670
  staleTime: BALANCE_STALE_TIME,
33583
- gcTime: BALANCE_CACHE_TIME,
33671
+ cacheTime: BALANCE_CACHE_TIME,
33584
33672
  refetchOnWindowFocus: true,
33585
33673
  refetchOnMount: true,
33586
33674
  }, } = {}) => {
@@ -33661,9 +33749,9 @@ const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33661
33749
  }, [balanceQueries]);
33662
33750
  // Aggregate loading states
33663
33751
  const queryStates = useMemo(() => ({
33664
- isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33752
+ isInitialLoading: Object.values(balanceQueries).some((q) => q.isInitialLoading),
33665
33753
  isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33666
- isPending: Object.values(balanceQueries).some((q) => q.isPending),
33754
+ isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33667
33755
  isRefetching: Object.values(balanceQueries).some((q) => q.isRefetching),
33668
33756
  isError: Object.values(balanceQueries).some((q) => q.isError),
33669
33757
  isSuccess: Object.values(balanceQueries).every((q) => q.isSuccess),
@@ -33705,7 +33793,7 @@ function useNativeTokenForChain(chain) {
33705
33793
 
33706
33794
  const useEvmNativeBalance = ({ address, chain, }) => {
33707
33795
  const { isChainTypeConnected } = useWallet();
33708
- const { data: nativeEvmBalance, isPending } = useBalance({
33796
+ const { data: nativeEvmBalance, isLoading } = useBalance({
33709
33797
  address: address,
33710
33798
  chainId: Number(chain?.chainId),
33711
33799
  query: {
@@ -33727,13 +33815,13 @@ const useEvmNativeBalance = ({ address, chain, }) => {
33727
33815
  }, [nativeEvmBalance?.decimals, nativeEvmBalance?.value]);
33728
33816
  return {
33729
33817
  balance,
33730
- isPending,
33818
+ isLoading,
33731
33819
  };
33732
33820
  };
33733
33821
  const useCosmosNativeBalance = ({ address, chain, }) => {
33734
33822
  const { isConnected: isCosmosConnected } = useCosmosContext();
33735
33823
  const { nativeToken: nativeCosmosToken } = useNativeTokenForChain(chain);
33736
- const { balance: rawBalance, isPending } = useCosmosBalance({
33824
+ const { balance: rawBalance, isLoading } = useCosmosBalance({
33737
33825
  chain,
33738
33826
  token: nativeCosmosToken,
33739
33827
  userAddress: address,
@@ -33748,18 +33836,16 @@ const useCosmosNativeBalance = ({ address, chain, }) => {
33748
33836
  };
33749
33837
  }
33750
33838
  }, [nativeCosmosToken?.decimals, rawBalance]);
33751
- return { balance, isPending };
33839
+ return { balance, isLoading };
33752
33840
  };
33753
33841
  const useBitcoinNativeBalance = ({ chain, address, }) => {
33754
33842
  const { nativeToken } = useNativeTokenForChain(chain);
33755
- const { data: rawBalance = "0", isPending } = useQuery({
33756
- queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33757
- queryFn: async () => {
33758
- if (!address || !nativeToken)
33759
- return "0";
33760
- const balance = await getBitcoinNativeBalance(address);
33761
- return formatBNToReadable(balance, nativeToken.decimals);
33762
- },
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
+ }, {
33763
33849
  enabled: chain?.chainType === ChainType.BTC &&
33764
33850
  nativeToken?.decimals != null &&
33765
33851
  isWalletAddressValid(chain, address),
@@ -33778,17 +33864,15 @@ const useBitcoinNativeBalance = ({ chain, address, }) => {
33778
33864
  }, [nativeToken?.decimals, rawBalance]);
33779
33865
  return {
33780
33866
  balance,
33781
- isPending,
33867
+ isLoading,
33782
33868
  };
33783
33869
  };
33784
33870
  const useSolanaNativeBalance = ({ chain, address, }) => {
33785
33871
  const { nativeToken } = useNativeTokenForChain(chain);
33786
- const { data: rawBalance, isPending } = useQuery({
33787
- queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33788
- queryFn: async () => {
33789
- const balance = await getSolanaNativeBalance(address);
33790
- return formatBNToReadable(balance, nativeToken.decimals);
33791
- },
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
+ }, {
33792
33876
  enabled: !!address &&
33793
33877
  nativeToken?.decimals != null &&
33794
33878
  chain?.chainType === ChainType.SOLANA,
@@ -33807,12 +33891,12 @@ const useSolanaNativeBalance = ({ chain, address, }) => {
33807
33891
  }, [nativeToken?.decimals, rawBalance]);
33808
33892
  return {
33809
33893
  balance,
33810
- isPending,
33894
+ isLoading,
33811
33895
  };
33812
33896
  };
33813
33897
  const useSuiNativeBalance = ({ address, chain, }) => {
33814
33898
  const { nativeToken } = useNativeTokenForChain(chain);
33815
- const { balance: rawBalance, isPending } = useSuiBalance({
33899
+ const { balance: rawBalance, isLoading } = useSuiBalance({
33816
33900
  chain,
33817
33901
  token: nativeToken,
33818
33902
  userAddress: address,
@@ -33827,12 +33911,12 @@ const useSuiNativeBalance = ({ address, chain, }) => {
33827
33911
  }, [nativeToken?.decimals, rawBalance]);
33828
33912
  return {
33829
33913
  balance,
33830
- isPending,
33914
+ isLoading,
33831
33915
  };
33832
33916
  };
33833
33917
  const useXrplNativeBalance = ({ address, chain, }) => {
33834
33918
  const { nativeToken } = useNativeTokenForChain(chain);
33835
- const { balance: rawBalance, isPending } = useXrplBalance({
33919
+ const { balance: rawBalance, isLoading } = useXrplBalance({
33836
33920
  chain,
33837
33921
  token: nativeToken,
33838
33922
  userAddress: address,
@@ -33848,12 +33932,12 @@ const useXrplNativeBalance = ({ address, chain, }) => {
33848
33932
  }, [nativeToken?.decimals, rawBalance]);
33849
33933
  return {
33850
33934
  balance,
33851
- isPending,
33935
+ isLoading,
33852
33936
  };
33853
33937
  };
33854
33938
  const useStellarNativeBalance = ({ address, chain, }) => {
33855
33939
  const { nativeToken } = useNativeTokenForChain(chain);
33856
- const { balance: rawBalance, isPending } = useStellarBalance({
33940
+ const { balance: rawBalance, isLoading } = useStellarBalance({
33857
33941
  chain,
33858
33942
  token: nativeToken,
33859
33943
  userAddress: address,
@@ -33869,7 +33953,7 @@ const useStellarNativeBalance = ({ address, chain, }) => {
33869
33953
  }, [nativeToken?.decimals, rawBalance]);
33870
33954
  return {
33871
33955
  balance,
33872
- isPending,
33956
+ isLoading,
33873
33957
  };
33874
33958
  };
33875
33959
  const useNativeBalance = (chain) => {
@@ -33877,28 +33961,28 @@ const useNativeBalance = (chain) => {
33877
33961
  const { data: cosmosAddressForChain } = useCosmosForChain(chain);
33878
33962
  // Cosmos is a special case because the address changes on every chain
33879
33963
  // so we can't use the default cosmos connected address
33880
- const { balance: nativeCosmosBalance, isPending: isCosmosPending } = useCosmosNativeBalance({
33964
+ const { balance: nativeCosmosBalance, isLoading: isCosmosLoading } = useCosmosNativeBalance({
33881
33965
  address: cosmosAddressForChain,
33882
33966
  chain,
33883
33967
  });
33884
- const { balance: nativeEvmBalance, isPending: isEvmPending } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33885
- 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({
33886
33970
  address: connectedAddresses[ChainType.BTC],
33887
33971
  chain,
33888
33972
  });
33889
- const { balance: nativeSolanaBalance, isPending: isSolanaPending } = useSolanaNativeBalance({
33973
+ const { balance: nativeSolanaBalance, isLoading: isSolanaLoading } = useSolanaNativeBalance({
33890
33974
  address: connectedAddresses[ChainType.SOLANA],
33891
33975
  chain,
33892
33976
  });
33893
- const { balance: nativeSuiBalance, isPending: isSuiPending } = useSuiNativeBalance({
33977
+ const { balance: nativeSuiBalance, isLoading: isSuiLoading } = useSuiNativeBalance({
33894
33978
  address: connectedAddresses[ChainType.SUI],
33895
33979
  chain,
33896
33980
  });
33897
- const { balance: nativeXrplBalance, isPending: isXrplPending } = useXrplNativeBalance({
33981
+ const { balance: nativeXrplBalance, isLoading: isXrpLoading } = useXrplNativeBalance({
33898
33982
  address: connectedAddresses[ChainType.XRPL],
33899
33983
  chain,
33900
33984
  });
33901
- const { balance: nativeStellarBalance, isPending: isStellarPending } = useStellarNativeBalance({
33985
+ const { balance: nativeStellarBalance, isLoading: isStellarLoading } = useStellarNativeBalance({
33902
33986
  address: connectedAddresses[ChainType.STELLAR],
33903
33987
  chain,
33904
33988
  });
@@ -33943,36 +34027,36 @@ const useNativeBalance = (chain) => {
33943
34027
  nativeXrplBalance,
33944
34028
  nativeStellarBalance,
33945
34029
  ]);
33946
- const isPending = useMemo(() => {
34030
+ const isLoading = useMemo(() => {
33947
34031
  if (!chain?.chainType)
33948
34032
  return false;
33949
34033
  switch (chain.chainType) {
33950
34034
  case ChainType.EVM:
33951
- return isEvmPending;
34035
+ return isEvmLoading;
33952
34036
  case ChainType.COSMOS:
33953
- return isCosmosPending;
34037
+ return isCosmosLoading;
33954
34038
  case ChainType.BTC:
33955
- return isBitcoinPending;
34039
+ return isBitcoinLoading;
33956
34040
  case ChainType.SOLANA:
33957
- return isSolanaPending;
34041
+ return isSolanaLoading;
33958
34042
  case ChainType.SUI:
33959
- return isSuiPending;
34043
+ return isSuiLoading;
33960
34044
  case ChainType.XRPL:
33961
- return isXrplPending;
34045
+ return isXrpLoading;
33962
34046
  case ChainType.STELLAR:
33963
- return isStellarPending;
34047
+ return isStellarLoading;
33964
34048
  }
33965
34049
  }, [
33966
34050
  chain?.chainType,
33967
- isEvmPending,
33968
- isCosmosPending,
33969
- isBitcoinPending,
33970
- isSolanaPending,
33971
- isSuiPending,
33972
- isXrplPending,
33973
- isStellarPending,
34051
+ isEvmLoading,
34052
+ isCosmosLoading,
34053
+ isBitcoinLoading,
34054
+ isSolanaLoading,
34055
+ isSuiLoading,
34056
+ isXrpLoading,
34057
+ isStellarLoading,
33974
34058
  ]);
33975
- return { nativeBalance, nativeBalanceFormatted, isPending };
34059
+ return { nativeBalance, nativeBalanceFormatted, isLoading };
33976
34060
  };
33977
34061
 
33978
34062
  const DEFAULT_REFRESH_INTERVAL_MS = 15000;
@@ -33981,7 +34065,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
33981
34065
  const isNativeToken = token?.address.toLowerCase() === nativeEvmTokenAddress.toLowerCase();
33982
34066
  const userAddressParsed = userAddress;
33983
34067
  // Only fetch using useBalance if it's a native token
33984
- const { data: nativeBalance, isPending: isNativeTokenPending } = useBalance({
34068
+ const { data: nativeBalance, isLoading: isNativeTokenLoading } = useBalance({
33985
34069
  address: userAddressParsed,
33986
34070
  chainId: Number(chain?.chainId),
33987
34071
  query: {
@@ -33997,7 +34081,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
33997
34081
  });
33998
34082
  // Only fetch using useReadContract if it's not a native token
33999
34083
  // This is temporary, because of wagmi error: https://github.com/wevm/wagmi/issues/4353
34000
- const { data: erc20Balance, isPending: isErc20Pending } = useReadContract({
34084
+ const { data: erc20Balance, isLoading: isErc20Loading } = useReadContract({
34001
34085
  address: token?.address,
34002
34086
  abi: erc20Abi,
34003
34087
  functionName: "balanceOf",
@@ -34013,15 +34097,15 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34013
34097
  },
34014
34098
  });
34015
34099
  const balance = isNativeToken ? nativeBalance?.value : erc20Balance;
34016
- const isPending = isNativeToken ? isNativeTokenPending : isErc20Pending;
34100
+ const isLoading = isNativeToken ? isNativeTokenLoading : isErc20Loading;
34017
34101
  const formattedBalance = balance != null && token?.decimals != null
34018
34102
  ? formatBNToReadable(balance, token.decimals)
34019
34103
  : "0";
34020
- return { balance: formattedBalance, isPending };
34104
+ return { balance: formattedBalance, isLoading };
34021
34105
  };
34022
34106
  const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34023
34107
  const { isConnected } = useCosmosContext();
34024
- const { data: balance = "0", isPending } = useQuery({
34108
+ const { data: balance = "0", isLoading } = useQuery({
34025
34109
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34026
34110
  queryFn: async () => {
34027
34111
  if (!userAddress || !token || chain?.chainType !== ChainType.COSMOS) {
@@ -34041,10 +34125,10 @@ const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34041
34125
  refetchInterval: refreshIntervalMs,
34042
34126
  retry: 2,
34043
34127
  });
34044
- return { balance, isPending };
34128
+ return { balance, isLoading };
34045
34129
  };
34046
34130
  const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34047
- const { data: balance = "0", isPending } = useQuery({
34131
+ const { data: balance = "0", isLoading } = useQuery({
34048
34132
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34049
34133
  queryFn: async () => {
34050
34134
  if (!userAddress || !token)
@@ -34059,11 +34143,11 @@ const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34059
34143
  refetchInterval: refreshIntervalMs,
34060
34144
  retry: 2,
34061
34145
  });
34062
- return { balance, isPending };
34146
+ return { balance, isLoading };
34063
34147
  };
34064
34148
  // TODO: implement fetching balances for all bitcoin tokens
34065
34149
  const useBitcoinBalance = ({ userAddress, chain, }) => {
34066
- const { balance: balanceBn, isPending } = useBitcoinNativeBalance({
34150
+ const { balance: balanceBn, isLoading } = useBitcoinNativeBalance({
34067
34151
  address: userAddress,
34068
34152
  chain,
34069
34153
  });
@@ -34072,10 +34156,10 @@ const useBitcoinBalance = ({ userAddress, chain, }) => {
34072
34156
  return "0";
34073
34157
  return formatBNToReadable(balanceBn?.value, balanceBn?.decimals);
34074
34158
  }, [balanceBn]);
34075
- return { balance, isPending };
34159
+ return { balance, isLoading };
34076
34160
  };
34077
34161
  const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34078
- const { data: balance = "0", isPending } = useQuery({
34162
+ const { data: balance = "0", isLoading } = useQuery({
34079
34163
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34080
34164
  queryFn: async () => {
34081
34165
  if (!userAddress ||
@@ -34095,10 +34179,10 @@ const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34095
34179
  refetchInterval: refreshIntervalMs,
34096
34180
  retry: 2,
34097
34181
  });
34098
- return { balance, isPending };
34182
+ return { balance, isLoading };
34099
34183
  };
34100
34184
  const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34101
- const { data: balance = "0", isPending } = useQuery({
34185
+ const { data: balance = "0", isLoading } = useQuery({
34102
34186
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34103
34187
  queryFn: async () => {
34104
34188
  if (!userAddress || !token || !chain)
@@ -34115,10 +34199,10 @@ const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs
34115
34199
  refetchInterval: refreshIntervalMs,
34116
34200
  retry: 2,
34117
34201
  });
34118
- return { balance, isPending };
34202
+ return { balance, isLoading };
34119
34203
  };
34120
34204
  const useStellarBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34121
- const { data: balance = "0", isPending } = useQuery({
34205
+ const { data: balance = "0", isLoading } = useQuery({
34122
34206
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34123
34207
  queryFn: async () => {
34124
34208
  if (!userAddress || !token || !chain)
@@ -34135,7 +34219,7 @@ const useStellarBalance = ({ userAddress, chain, enabled, token, refreshInterval
34135
34219
  refetchInterval: refreshIntervalMs,
34136
34220
  retry: 2,
34137
34221
  });
34138
- return { balance, isPending };
34222
+ return { balance, isLoading };
34139
34223
  };
34140
34224
 
34141
34225
  /**
@@ -34256,7 +34340,7 @@ const useMultipleTokenPrices = (tokens) => {
34256
34340
  return {
34257
34341
  tokenPrices,
34258
34342
  getTokenPrice,
34259
- isPending: coinGeckoQuery.isPending,
34343
+ isLoading: coinGeckoQuery.isLoading,
34260
34344
  isError: coinGeckoQuery.isError,
34261
34345
  error: coinGeckoQuery.error,
34262
34346
  refetch: coinGeckoQuery.refetch,
@@ -34405,17 +34489,13 @@ const fetchTokensData = async (tokens) => {
34405
34489
 
34406
34490
  // Coingecko has a limit for some queries for multiple tokens, not sure what it is, but let's use 100 for now
34407
34491
  const useHistoricalData = (coingeckoId, timeFrame) => {
34408
- return useQuery({
34409
- queryKey: keys().historicalData(coingeckoId, timeFrame),
34410
- queryFn: () => fetchHistoricalData(coingeckoId, timeFrame),
34492
+ return useQuery(keys().historicalData(coingeckoId, timeFrame), () => fetchHistoricalData(coingeckoId, timeFrame), {
34411
34493
  staleTime: 5 * 60 * 1000,
34412
34494
  enabled: !!coingeckoId,
34413
34495
  });
34414
34496
  };
34415
34497
  const useTokensData = (tokens) => {
34416
- return useQuery({
34417
- queryKey: keys().tokensData(tokens),
34418
- queryFn: () => fetchTokensData(tokens),
34498
+ return useQuery(keys().tokensData(tokens), () => fetchTokensData(tokens), {
34419
34499
  staleTime: 60 * 1000,
34420
34500
  enabled: !!tokens && tokens.length > 0,
34421
34501
  });
@@ -34720,7 +34800,7 @@ function useSendTransactionGas({ chain, token, from, }) {
34720
34800
  }
34721
34801
 
34722
34802
  function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34723
- const { data: estimatedGas = BigInt(0), isPending } = useSendTransactionGas({
34803
+ const { data: estimatedGas = BigInt(0), isLoading } = useSendTransactionGas({
34724
34804
  chain,
34725
34805
  token,
34726
34806
  from,
@@ -34765,7 +34845,7 @@ function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34765
34845
  return {
34766
34846
  estimatedGas,
34767
34847
  isBalanceEnough,
34768
- isPending,
34848
+ isLoading,
34769
34849
  isNativeBalanceEnoughToPayGasFees,
34770
34850
  minAmountValueWarnMsg,
34771
34851
  };
@@ -35011,126 +35091,6 @@ async function sendTransactionStellar({ amount, signer, to, token, chain, }) {
35011
35091
  };
35012
35092
  }
35013
35093
 
35014
- // Prevent fetching too soon after the first successful request.
35015
- const DEFAULT_STALE_TIME = 8000;
35016
- const defaultOptions = {
35017
- queries: {
35018
- staleTime: DEFAULT_STALE_TIME,
35019
- refetchOnWindowFocus: false,
35020
- retry: false,
35021
- retryOnMount: false,
35022
- },
35023
- };
35024
-
35025
- const queryClient = new QueryClient({ defaultOptions });
35026
- const verifyIntegratorIdValidity = (integratorId) => {
35027
- if (!integratorId) {
35028
- throw new Error("Integrator ID is required");
35029
- }
35030
- };
35031
- const SquidProvider = ({ children, config, placeholder, }) => {
35032
- verifyIntegratorIdValidity(config.integratorId);
35033
- const [wagmiConfig, setWagmiConfig] = useState();
35034
- const sdkInitializedRef = useRef(false);
35035
- const initializeSdk = useCallback(async () => {
35036
- if (sdkInitializedRef.current) {
35037
- return;
35038
- }
35039
- sdkInitializedRef.current = true;
35040
- try {
35041
- const squid = new Squid({
35042
- integratorId: config.integratorId,
35043
- baseUrl: config.apiUrl ?? squidApiBaseUrl,
35044
- });
35045
- const [sdkInfoResponse, assetsColorsResponse] = await Promise.allSettled([
35046
- squid.init(),
35047
- fetchAssetsColors(),
35048
- ]);
35049
- if (sdkInfoResponse.status === "rejected") {
35050
- throw sdkInfoResponse.reason;
35051
- }
35052
- if (assetsColorsResponse.status === "fulfilled") {
35053
- useAssetsColorsStore.setState(assetsColorsResponse.value);
35054
- initializeSquidWithAssetsColors(squid, assetsColorsResponse.value);
35055
- }
35056
- const shouldResetSwapRouteStore =
35057
- // reset swap route if specified in config
35058
- !config?.loadPreviousStateFromLocalStorage ||
35059
- // or if initial assets are provided
35060
- !isEmptyObject(config.initialAssets?.from) ||
35061
- !isEmptyObject(config.initialAssets?.to);
35062
- if (shouldResetSwapRouteStore) {
35063
- useSwapRoutePersistStore.setState({
35064
- swapRoute: undefined,
35065
- });
35066
- }
35067
- useSquidStore.setState((_) => ({
35068
- squid,
35069
- maintenanceMode: { active: false, message: undefined },
35070
- }));
35071
- const newWagmiConfig = createWagmiConfig(squid.chains);
35072
- setWagmiConfig(newWagmiConfig);
35073
- useConfigStore.setState({
35074
- isInitialized: true,
35075
- config: getConfigWithDefaults(config),
35076
- });
35077
- }
35078
- catch (error) {
35079
- const isAxios503Error = error.isAxiosError &&
35080
- error.response?.status === 503;
35081
- if (isAxios503Error) {
35082
- const maintenanceMessage = error.response?.data
35083
- ?.message ?? undefined;
35084
- // Even with an error, we want wagmi to be defined so that we can display the maintenance mode layout
35085
- // Create wagmi config with mainnet as fallback in maintenance mode
35086
- const newWagmiConfig = createConfig({
35087
- chains: [mainnet],
35088
- connectors: [injected()],
35089
- transports: {
35090
- [mainnet.id]: http(),
35091
- },
35092
- });
35093
- setWagmiConfig(newWagmiConfig);
35094
- useConfigStore.setState({
35095
- isInitialized: false,
35096
- config: getConfigWithDefaults(config),
35097
- });
35098
- useSquidStore.setState({
35099
- squid: undefined,
35100
- maintenanceMode: {
35101
- active: true,
35102
- message: maintenanceMessage,
35103
- },
35104
- });
35105
- }
35106
- else {
35107
- console.error("Error initializing SDK:", error);
35108
- }
35109
- }
35110
- }, [config]);
35111
- useEffect(() => {
35112
- initializeSdk();
35113
- }, [initializeSdk]);
35114
- return wagmiConfig ? (React.createElement(WagmiProvider, { reconnectOnMount: false, config: wagmiConfig },
35115
- React.createElement(QueryClientProvider, { client: queryClient },
35116
- React.createElement(StellarProvider, null,
35117
- React.createElement(EvmProvider, null,
35118
- React.createElement(XrplProvider, null,
35119
- React.createElement(SuiProvider, null,
35120
- React.createElement(SolanaProvider, null,
35121
- React.createElement(BitcoinProvider, null,
35122
- React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
35123
- };
35124
-
35125
- const para = new Para("beta_c529f95c6a31bfb50487b0929a19b682");
35126
- const connector = paraConnector({
35127
- para,
35128
- appName: SQUID_METADATA.name,
35129
- isGuestModeEnabled: false,
35130
- hideWallets: true,
35131
- options: {},
35132
- queryClient: queryClient,
35133
- });
35134
35094
  const createWagmiConfig = (squidChains) => {
35135
35095
  const filteredEvmChains = squidChains.filter((chain) => chain.chainType === ChainType.EVM);
35136
35096
  if (filteredEvmChains.length === 0) {
@@ -35186,8 +35146,6 @@ const createWagmiConfig = (squidChains) => {
35186
35146
  description: SQUID_METADATA.description,
35187
35147
  },
35188
35148
  }),
35189
- // @ts-expect-error - TODO: fix types
35190
- connector,
35191
35149
  ],
35192
35150
  });
35193
35151
  };
@@ -35294,12 +35252,10 @@ function useSendTransaction({ to, amount, token, chain, }) {
35294
35252
  // amount is already formatted with the token decimals
35295
35253
  amount,
35296
35254
  toAddress: to,
35297
- token: {
35298
- address: token.address,
35299
- chainId: token.chainId,
35300
- symbol: token.symbol,
35301
- type: token.type,
35302
- },
35255
+ tokenAddress: token.address,
35256
+ tokenChainId: token.chainId,
35257
+ tokenSymbol: token.symbol,
35258
+ tokenType: token.type,
35303
35259
  });
35304
35260
  }, [
35305
35261
  allEventParamsDefined,
@@ -35319,12 +35275,10 @@ function useSendTransaction({ to, amount, token, chain, }) {
35319
35275
  // amount is already formatted with the token decimals
35320
35276
  amount,
35321
35277
  toAddress: to,
35322
- token: {
35323
- address: token.address,
35324
- chainId: token.chainId,
35325
- symbol: token.symbol,
35326
- type: token.type,
35327
- },
35278
+ tokenAddress: token.address,
35279
+ tokenChainId: token.chainId,
35280
+ tokenSymbol: token.symbol,
35281
+ tokenType: token.type,
35328
35282
  txHash,
35329
35283
  });
35330
35284
  }, [
@@ -35470,9 +35424,7 @@ function useSendTransaction({ to, amount, token, chain, }) {
35470
35424
  });
35471
35425
  },
35472
35426
  onSuccess: (tx, variables) => {
35473
- queryClient.invalidateQueries({
35474
- queryKey: getPrefixKey(QueryKeys.Balance),
35475
- });
35427
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balance));
35476
35428
  setTransactionState(variables.id, tx);
35477
35429
  persistTransaction({
35478
35430
  txType: HistoryTxType.SEND,
@@ -35777,6 +35729,20 @@ const useAllTransactionsStatus = ({ enabled }) => {
35777
35729
  retry: 4,
35778
35730
  retryDelay: getSwapTxStatusRefetchInterval(data),
35779
35731
  refetchInterval: 5000,
35732
+ onSuccess: (statusResponse) => {
35733
+ if (!statusResponse)
35734
+ return;
35735
+ const endStatus = getTransactionEndStatus({
35736
+ statusResponse,
35737
+ });
35738
+ if (!endStatus)
35739
+ return;
35740
+ replaceSwapTransactionStatus({
35741
+ transactionId: data.transactionId,
35742
+ statusResponse,
35743
+ status: endStatus,
35744
+ });
35745
+ },
35780
35746
  };
35781
35747
  }
35782
35748
  case HistoryTxType.BUY:
@@ -35785,14 +35751,29 @@ const useAllTransactionsStatus = ({ enabled }) => {
35785
35751
  queryKey: keys().fiatToCryptoStatus(data.orderId),
35786
35752
  retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
35787
35753
  retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
35788
- refetchInterval: (query) => {
35789
- const { state } = query;
35790
- if (state.data?.status &&
35791
- FINAL_TRANSACTION_STATUSES.includes(state.data.status)) {
35754
+ refetchInterval: (data) => {
35755
+ if (data?.status &&
35756
+ FINAL_TRANSACTION_STATUSES.includes(data.status)) {
35792
35757
  return false;
35793
35758
  }
35794
35759
  return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
35795
35760
  },
35761
+ onSuccess: (statusData) => {
35762
+ replaceTransactionStatus({
35763
+ orderId: data.orderId,
35764
+ status: statusData.status,
35765
+ transactionHash: statusData.transactionHash,
35766
+ txType: HistoryTxType.BUY,
35767
+ });
35768
+ },
35769
+ onError: () => {
35770
+ replaceTransactionStatus({
35771
+ txType: HistoryTxType.BUY,
35772
+ orderId: data.orderId,
35773
+ status: "failed",
35774
+ transactionHash: undefined,
35775
+ });
35776
+ },
35796
35777
  enabled: true,
35797
35778
  };
35798
35779
  case HistoryTxType.SEND:
@@ -35809,97 +35790,30 @@ const useAllTransactionsStatus = ({ enabled }) => {
35809
35790
  });
35810
35791
  },
35811
35792
  refetchInterval: getSendTxStatusRefetchInterval(data.token.type),
35812
- };
35813
- }
35814
- });
35815
- const queries = useQueries({
35816
- queries: enabled && config.apiUrl ? statusQueries : [],
35817
- });
35818
- useEffect(() => {
35819
- queries.forEach((query, index) => {
35820
- const transaction = pendingTransactions[index];
35821
- switch (transaction.txType) {
35822
- case HistoryTxType.SWAP:
35823
- if (query.isSuccess && query.data) {
35824
- const statusResponse = query.data;
35825
- const endStatus = getTransactionEndStatus({
35826
- statusResponse,
35827
- });
35828
- if (!endStatus)
35829
- return;
35830
- replaceSwapTransactionStatus({
35831
- transactionId: transaction.data.transactionId,
35832
- statusResponse,
35833
- status: endStatus,
35834
- });
35835
- }
35836
- if (query.isError) {
35837
- const error = query.error;
35838
- const is404 = is404Error(error.cause);
35839
- if (is404) {
35840
- replaceSwapTransactionStatus({
35841
- transactionId: transaction.data.transactionId,
35842
- statusResponse: undefined,
35843
- status: TransactionStatus.NOT_FOUND,
35844
- });
35845
- }
35846
- else {
35847
- replaceSwapTransactionStatus({
35848
- transactionId: transaction.data.transactionId,
35849
- statusResponse: undefined,
35850
- status: TransactionStatus.ERROR,
35851
- });
35852
- }
35853
- }
35854
- break;
35855
- case HistoryTxType.BUY:
35856
- if (query.isSuccess && query.data) {
35857
- const statusData = query.data;
35858
- replaceTransactionStatus({
35859
- orderId: transaction.data.orderId,
35860
- status: statusData.status,
35861
- transactionHash: statusData.transactionHash,
35862
- txType: HistoryTxType.BUY,
35863
- });
35864
- }
35865
- if (query.isError) {
35866
- replaceTransactionStatus({
35867
- txType: HistoryTxType.BUY,
35868
- orderId: transaction.data.orderId,
35869
- status: "failed",
35870
- transactionHash: undefined,
35871
- });
35872
- }
35873
- break;
35874
- case HistoryTxType.SEND:
35875
- if (query.isSuccess && query.data) {
35876
- const status = query.data;
35793
+ onSuccess: (status) => {
35877
35794
  if (status !== SendTransactionStatus.ONGOING) {
35878
35795
  replaceTransactionStatus({
35879
35796
  txType: HistoryTxType.SEND,
35880
35797
  status,
35881
- hash: transaction.data.hash,
35798
+ hash: data.hash,
35882
35799
  });
35883
35800
  }
35884
- }
35885
- if (query.isError) {
35801
+ },
35802
+ onError: () => {
35886
35803
  replaceTransactionStatus({
35887
35804
  txType: HistoryTxType.SEND,
35888
35805
  status: SendTransactionStatus.ERROR,
35889
- hash: transaction.data.hash,
35806
+ hash: data.hash,
35890
35807
  });
35891
- }
35892
- break;
35893
- }
35894
- });
35895
- }, [
35896
- pendingTransactions,
35897
- queries,
35898
- replaceSwapTransactionStatus,
35899
- replaceTransactionStatus,
35900
- ]);
35808
+ },
35809
+ };
35810
+ }
35811
+ });
35812
+ const queries = useQueries({
35813
+ queries: enabled && config.apiUrl ? statusQueries : [],
35814
+ });
35901
35815
  return {
35902
- isPending: queries.some((q) => q.isPending),
35816
+ isLoading: queries.some((q) => q.isLoading),
35903
35817
  isError: queries.some((q) => q.isError),
35904
35818
  data: queries.map((q) => q.data).filter(Boolean),
35905
35819
  };
@@ -36158,18 +36072,16 @@ const useApproval = ({ squidRoute, }) => {
36158
36072
  * On Error: Showing the error message if any
36159
36073
  * @returns {boolean} approved
36160
36074
  */
36161
- const routeApproved = useQuery({
36162
- queryKey: keys().routeApproved(squidRoute, allowanceInWei),
36163
- queryFn: async () => {
36164
- // Approval is only needed for EVM chains
36165
- if (getChainType(squidRoute?.params.fromChain) === ChainType.EVM) {
36166
- return hasAllowance;
36167
- }
36168
- return true;
36169
- },
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
+ }, {
36170
36082
  enabled: !!squidRoute &&
36171
36083
  !!sourceUserAddress &&
36172
- !allowanceQuery?.isPending &&
36084
+ !allowanceQuery?.isLoading &&
36173
36085
  allowanceQuery?.isFetched,
36174
36086
  });
36175
36087
  // USDT has a very specific way of handling approvals
@@ -36258,84 +36170,81 @@ const useApproval = ({ squidRoute, }) => {
36258
36170
  /**
36259
36171
  * Manually approve route if necessary
36260
36172
  */
36261
- const approveRoute = useMutation({
36262
- mutationFn: async () => {
36263
- try {
36264
- if (fromToken?.address === nativeEvmTokenAddress) {
36265
- 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) });
36266
36184
  }
36267
- if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36268
- await approveSpecificTokenToZero(fromToken);
36269
- try {
36270
- // If needed, we can switch the chain here
36271
- // If already on the correct chain, this will do nothing
36272
- await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36273
- }
36274
- catch (error) {
36275
- console.error("Error switching network:", error);
36276
- }
36277
- let approveTx;
36278
- if (useIcs20) {
36279
- const channel = squidRoute.estimate.actions[0].data
36280
- .ibcChannel;
36281
- const ics20Interface = new ethers.Interface(ics20Abi);
36282
- const approveData = ics20Interface.encodeFunctionData("approve", [
36283
- squidRoute.params.fromAddress,
36284
- [
36285
- {
36286
- sourcePort: "transfer",
36287
- sourceChannel: channel,
36288
- spendLimit: [
36289
- {
36290
- denom: squidRoute.estimate.actions[0].fromToken
36291
- .originalAddress,
36292
- amount: squidRoute.params.fromAmount,
36293
- },
36294
- ],
36295
- allowList: [],
36296
- allowedPacketData: ["*"],
36297
- },
36298
- ],
36299
- ]);
36300
- approveTx = await evmSigner.sendTransaction({
36301
- to: squidRoute.transactionRequest.target,
36302
- data: approveData,
36303
- value: "0",
36304
- gasLimit: squidRoute.transactionRequest
36305
- .gasLimit,
36306
- gasPrice: squidRoute.transactionRequest
36307
- .gasPrice,
36308
- });
36309
- }
36310
- else {
36311
- approveTx = await squid.approveRoute({
36312
- route: squidRoute,
36313
- signer: evmSigner,
36314
- // For security reasons, we don't want to allow infinite approvals in our frontends
36315
- executionSettings: {
36316
- 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: ["*"],
36317
36208
  },
36318
- });
36319
- }
36320
- if (isProblematicConnector(activeConnector)) {
36321
- await sleep(3_000);
36322
- }
36323
- await approveTx?.wait();
36324
- 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
+ });
36325
36220
  }
36326
- return false;
36327
- }
36328
- catch (error) {
36329
- // Keep the error in the console to debug future issues
36330
- console.error(error);
36331
- 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;
36332
36236
  }
36333
- },
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
+ }, {
36334
36245
  onSuccess: async () => {
36335
36246
  await allowanceQuery?.refetch();
36336
- queryClient.invalidateQueries({
36337
- queryKey: getPrefixKey(QueryKeys.RouteApproved),
36338
- });
36247
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.RouteApproved));
36339
36248
  // After an approval, we refetch the transaction query with all required parameters
36340
36249
  // This is to ensure we're using the latest expiry timestamp
36341
36250
  if (squidRoute) {
@@ -39455,10 +39364,8 @@ const useExecuteTransaction = (squidRoute) => {
39455
39364
  }
39456
39365
  }, [cosmosSigner, fromChain]);
39457
39366
  const resetQueriesAfterTxSigned = () => {
39458
- queryClient.refetchQueries({ queryKey: getPrefixKey(QueryKeys.Balance) });
39459
- queryClient.invalidateQueries({
39460
- queryKey: getPrefixKey(QueryKeys.Transaction),
39461
- });
39367
+ queryClient.refetchQueries(getPrefixKey(QueryKeys.Balance));
39368
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Transaction));
39462
39369
  };
39463
39370
  const dispatchSignatureRequestEvent = useCallback((route) => {
39464
39371
  WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
@@ -39476,64 +39383,62 @@ const useExecuteTransaction = (squidRoute) => {
39476
39383
  txHash,
39477
39384
  }, findToken);
39478
39385
  }, [findToken]);
39479
- const swapMutationCosmos = useMutation({
39480
- mutationFn: async ({ id, route }) => {
39481
- const fromChainId = route?.params.fromChain;
39482
- if (cosmosSigner && fromChainId) {
39483
- try {
39484
- const signingClient = await getCosmosSignerClient();
39485
- const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39486
- if (signerAddress && signingClient && route) {
39487
- dispatchSignatureRequestEvent(route);
39488
- const tx$1 = (await squid?.executeRoute({
39489
- signer: signingClient,
39490
- signerAddress,
39491
- route,
39492
- }));
39493
- // set the tx state to loading, as soon as user signed the tx
39494
- setTransactionState({
39495
- txHash: "",
39496
- route,
39497
- status: TransactionStatus.ONGOING,
39498
- sourceStatus: TransactionStatus.ONGOING,
39499
- id,
39500
- });
39501
- // broadcast the signed tx to get hash and listen to events
39502
- const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39503
- const hash = response.transactionHash;
39504
- if (hash) {
39505
- resetQueriesAfterTxSigned();
39506
- }
39507
- // Dispatch event so it can be listened from outside the widget
39508
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39509
- const txParams = setTransactionState({
39510
- route,
39511
- txHash: hash,
39512
- userAddress: sourceUserAddress,
39513
- status: TransactionStatus.ONGOING,
39514
- sourceStatus: TransactionStatus.ONGOING,
39515
- axelarUrl: undefined,
39516
- 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,
39517
39429
  });
39518
- if (txParams) {
39519
- addSwapTransaction({
39520
- ...txParams,
39521
- params: route.params,
39522
- estimate: route.estimate,
39523
- });
39524
- }
39525
- return response.code === 0;
39526
39430
  }
39431
+ return response.code === 0;
39527
39432
  }
39528
- catch (error) {
39529
- console.error("Error executing Cosmos transaction", error);
39530
- if (isUserRejectionError(normalizeError(error))) {
39531
- throw new Error("Request rejected");
39532
- }
39433
+ }
39434
+ catch (error) {
39435
+ console.error("Error executing Cosmos transaction", error);
39436
+ if (isUserRejectionError(normalizeError(error))) {
39437
+ throw new Error("Request rejected");
39533
39438
  }
39534
39439
  }
39535
- throw new Error("Need all parameters");
39536
- },
39440
+ }
39441
+ throw new Error("Need all parameters");
39537
39442
  });
39538
39443
  // If the transaction is replaced, we need to update the transaction hash
39539
39444
  // Transaction replaced can mean that the user has speed up the transaction for example
@@ -39586,126 +39491,97 @@ const useExecuteTransaction = (squidRoute) => {
39586
39491
  throw error;
39587
39492
  }
39588
39493
  }, [replaceSwapTransactionNonce, setTransactionState, sourceUserAddress]);
39589
- const swapMutationEvm = useMutation({
39590
- mutationFn: async ({ id, route }) => {
39591
- await changeNetworkIfNeeded.mutateAsync();
39592
- if (!route || !squid || !evmSigner) {
39593
- throw new Error("Need all parameters");
39594
- }
39595
- dispatchSignatureRequestEvent(route);
39596
- const txResponse = (await squid.executeRoute({
39597
- bypassBalanceChecks: true,
39598
- 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({
39599
39516
  route,
39600
- }));
39601
- let hash = txResponse.hash;
39602
- if (activeConnector?.id === "safe") {
39603
- 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
+ });
39604
39531
  }
39605
- if (hash) {
39606
- resetQueriesAfterTxSigned();
39532
+ }
39533
+ try {
39534
+ if (isProblematicConnector(activeConnector)) {
39535
+ await sleep(3_000);
39607
39536
  }
39608
- // Dispatch event so it can be listened from outside the widget
39609
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39610
- if (route.transactionRequest) {
39611
- const txParams = setTransactionState({
39612
- route,
39613
- txHash: hash,
39614
- nonce: txResponse.nonce,
39615
- userAddress: sourceUserAddress,
39616
- status: TransactionStatus.INITIAL_LOADING,
39617
- sourceStatus: TransactionStatus.ONGOING,
39618
- axelarUrl: undefined,
39619
- id,
39620
- });
39621
- if (txParams) {
39622
- addSwapTransaction({
39623
- ...txParams,
39624
- params: route.params,
39625
- estimate: route.estimate,
39626
- });
39627
- }
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");
39628
39556
  }
39629
- try {
39630
- if (isProblematicConnector(activeConnector)) {
39631
- await sleep(3_000);
39632
- }
39633
- const response = await txResponse.wait();
39634
- return response;
39557
+ if (!solanaSigner) {
39558
+ throw new Error("Solana signer is required");
39635
39559
  }
39636
- catch (error) {
39637
- return handleTransactionReplacementError({
39638
- error,
39639
- route,
39640
- status: TransactionStatus.INITIAL_LOADING,
39641
- sourceStatus: TransactionStatus.ONGOING,
39642
- userAddress: sourceUserAddress,
39643
- axelarUrl: undefined,
39644
- id,
39645
- });
39560
+ if (!route.params.fromAddress || !route.params.toAddress) {
39561
+ throw new Error("From or to address is required");
39646
39562
  }
39647
- },
39648
- });
39649
- const swapMutationSolana = useMutation({
39650
- mutationFn: async ({ id, route }) => {
39651
- try {
39652
- if (!route) {
39653
- throw new Error("Route is required");
39654
- }
39655
- if (!solanaSigner) {
39656
- throw new Error("Solana signer is required");
39657
- }
39658
- if (!route.params.fromAddress || !route.params.toAddress) {
39659
- throw new Error("From or to address is required");
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");
39660
39572
  }
39661
- const isDirectTransfer = isDepositRoute(route);
39662
- // Means it's a transfer to a deposit address
39663
- // Instead of a Swap/Contract call using a DEX like Jupiter
39664
- if (isDirectTransfer) {
39665
- // Get the deposit address from the squidRoute
39666
- const depositData = useDepositAddressStore.getState().deposit;
39667
- // Validate params
39668
- if (!depositData?.depositAddress) {
39669
- throw new Error("Deposit address is required");
39670
- }
39671
- const signature = await executeSolanaTransfer({
39672
- amount: BigInt(route.params.fromAmount),
39673
- target: depositData.depositAddress,
39674
- signer: solanaSigner,
39675
- connection: solanaConnection,
39676
- sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39677
- onSigned: (txHash) => {
39678
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39679
- const txParams = setTransactionState({
39680
- route,
39681
- txHash,
39682
- transactionIdForStatus: depositData.chainflipStatusTrackingId,
39683
- userAddress: sourceUserAddress,
39684
- status: TransactionStatus.INITIAL_LOADING,
39685
- sourceStatus: TransactionStatus.ONGOING,
39686
- id,
39687
- });
39688
- if (txParams) {
39689
- addSwapTransaction({
39690
- ...txParams,
39691
- params: route.params,
39692
- estimate: route.estimate,
39693
- });
39694
- }
39695
- },
39696
- });
39697
- return signature;
39698
- }
39699
- const signature = await executeSolanaSwap({
39700
- route,
39573
+ const signature = await executeSolanaTransfer({
39574
+ amount: BigInt(route.params.fromAmount),
39575
+ target: depositData.depositAddress,
39701
39576
  signer: solanaSigner,
39702
39577
  connection: solanaConnection,
39578
+ sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39703
39579
  onSigned: (txHash) => {
39704
39580
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39705
39581
  const txParams = setTransactionState({
39706
39582
  route,
39707
39583
  txHash,
39708
- transactionIdForStatus: undefined,
39584
+ transactionIdForStatus: depositData.chainflipStatusTrackingId,
39709
39585
  userAddress: sourceUserAddress,
39710
39586
  status: TransactionStatus.INITIAL_LOADING,
39711
39587
  sourceStatus: TransactionStatus.ONGOING,
@@ -39722,13 +39598,39 @@ const useExecuteTransaction = (squidRoute) => {
39722
39598
  });
39723
39599
  return signature;
39724
39600
  }
39725
- catch (error) {
39726
- console.error("Solana transaction failed:", error);
39727
- throw error instanceof Error
39728
- ? error
39729
- : new Error("Failed to execute Solana transaction");
39730
- }
39731
- },
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
+ }, {
39732
39634
  onError: (error, variables) => {
39733
39635
  const currentTx = getTransaction(variables.id);
39734
39636
  const errorObject = getTransactionError(error);
@@ -39749,9 +39651,7 @@ const useExecuteTransaction = (squidRoute) => {
39749
39651
  },
39750
39652
  onSuccess: (_data, variables) => {
39751
39653
  const currentTx = getTransaction(variables.id);
39752
- queryClient.invalidateQueries({
39753
- queryKey: getPrefixKey(QueryKeys.Balances),
39754
- });
39654
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39755
39655
  if (isSameChain && currentTx?.transactionId) {
39756
39656
  replaceSwapTransactionStatus({
39757
39657
  transactionId: currentTx.transactionId,
@@ -39768,207 +39668,197 @@ const useExecuteTransaction = (squidRoute) => {
39768
39668
  });
39769
39669
  },
39770
39670
  });
39771
- const swapMutationBitcoin = useMutation({
39772
- mutationFn: async ({ id, route }) => {
39773
- const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39774
- if (!depositAddress) {
39775
- throw new Error(`Invalid deposit address: ${depositAddress}`);
39776
- }
39777
- if (!sendAmount) {
39778
- throw new Error(`Invalid send amount: ${sendAmount}`);
39779
- }
39780
- const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39781
- await changeNetworkIfNeeded.mutateAsync();
39782
- if (allParamsValid) {
39783
- dispatchSignatureRequestEvent(route);
39784
- const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39785
- if (txHash) {
39786
- resetQueriesAfterTxSigned();
39787
- }
39788
- // Dispatch event so it can be listened from outside the widget
39789
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39790
- if (route.transactionRequest) {
39791
- const txParams = setTransactionState({
39792
- route,
39793
- txHash,
39794
- // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39795
- // instead of the Bitcoin transaction hash
39796
- transactionIdForStatus: chainflipStatusTrackingId,
39797
- userAddress: sourceUserAddress,
39798
- status: TransactionStatus.INITIAL_LOADING,
39799
- sourceStatus: TransactionStatus.ONGOING,
39800
- axelarUrl: undefined,
39801
- id,
39802
- });
39803
- if (txParams) {
39804
- addSwapTransaction({
39805
- ...txParams,
39806
- params: route.params,
39807
- estimate: route.estimate,
39808
- });
39809
- }
39810
- }
39811
- }
39812
- else {
39813
- throw new Error("Need all parameters");
39814
- }
39815
- },
39816
- });
39817
- const swapMutationXrpl = useMutation({
39818
- mutationFn: async ({ id, route }) => {
39819
- if (!route?.transactionRequest || !xrplSigner) {
39820
- throw new Error("Need all parameters");
39821
- }
39822
- if (route.transactionRequest.type !== SquidDataType.OnChainExecution) {
39823
- throw new Error("Invalid route type");
39824
- }
39825
- const { data } = route.transactionRequest;
39826
- const paymentTx = parseXrplPaymentTx(data);
39827
- if (!paymentTx)
39828
- throw new Error("Could not parse transaction");
39829
- const fromChainId = route.params.fromChain;
39830
- const xrplNetwork = getXrplNetwork(fromChainId);
39831
- if (xrplNetwork == null) {
39832
- throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39833
- }
39834
- const txRes = await xrplSigner.signAndSubmit({
39835
- tx: paymentTx,
39836
- network: xrplNetwork,
39837
- });
39838
- const txParams = setTransactionState({
39839
- txHash: txRes.hash,
39840
- id,
39841
- sourceStatus: TransactionStatus.ONGOING,
39842
- status: TransactionStatus.ONGOING,
39843
- route: route,
39844
- userAddress: sourceUserAddress,
39845
- });
39846
- if (txParams && route) {
39847
- addSwapTransaction({
39848
- ...txParams,
39849
- params: route.params,
39850
- estimate: route.estimate,
39851
- });
39852
- }
39853
- if (txRes.status !== XrplTxStatus.SUCCESS) {
39854
- throw new Error(`Transaction failed with status: ${txRes.status}`);
39855
- }
39856
- },
39857
- });
39858
- const swapMutationSui = useMutation({
39859
- mutationFn: async ({ id, route }) => {
39860
- if (!route || !suiSigner || !fromChain) {
39861
- throw new Error("Need all parameters");
39862
- }
39863
- if (route.transactionRequest?.type !== SquidDataType.OnChainExecution) {
39864
- throw new Error("Invalid route type");
39865
- }
39866
- const suiWalletState = connectedWalletsByChainType[ChainType.SUI];
39867
- if (!suiWalletState.account) {
39868
- throw new Error("Sui wallet is missing account data");
39869
- }
39870
- const fromChainId = route.params.fromChain;
39871
- const suiChain = getSuiChain(fromChainId);
39872
- if (!suiChain) {
39873
- throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39874
- }
39875
- const suiClient = await getClient(fromChain);
39876
- const txJson = route.transactionRequest.data;
39877
- const tx = Transaction$2.from(txJson);
39878
- const signedTx = await suiSigner.signTransaction({
39879
- transaction: tx,
39880
- account: suiWalletState.account,
39881
- chain: suiChain,
39882
- });
39883
- // execute transaction without waiting for confirmation
39884
- const txResponse = await suiClient.executeTransactionBlock({
39885
- signature: signedTx.signature,
39886
- transactionBlock: signedTx.bytes,
39887
- });
39888
- 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));
39889
39684
  if (txHash) {
39890
39685
  resetQueriesAfterTxSigned();
39891
39686
  }
39687
+ // Dispatch event so it can be listened from outside the widget
39892
39688
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39893
- const txParams = setTransactionState({
39894
- route,
39895
- txHash,
39896
- userAddress: sourceUserAddress,
39897
- status: TransactionStatus.INITIAL_LOADING,
39898
- sourceStatus: TransactionStatus.ONGOING,
39899
- id,
39900
- });
39901
- if (txParams) {
39902
- addSwapTransaction({
39903
- ...txParams,
39904
- params: route.params,
39905
- 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,
39906
39701
  });
39702
+ if (txParams) {
39703
+ addSwapTransaction({
39704
+ ...txParams,
39705
+ params: route.params,
39706
+ estimate: route.estimate,
39707
+ });
39708
+ }
39907
39709
  }
39908
- // wait for transaction confirmation
39909
- await suiClient.waitForTransaction({
39910
- digest: txHash,
39911
- });
39912
- },
39710
+ }
39711
+ else {
39712
+ throw new Error("Need all parameters");
39713
+ }
39913
39714
  });
39914
- const swapMutationStellar = useMutation({
39915
- mutationFn: async ({ id, route }) => {
39916
- if (!stellarSigner || !route || !squid || !fromChain) {
39917
- throw new Error("Need all parameters");
39918
- }
39919
- const fromChainId = route.params.fromChain;
39920
- const stellarNetwork = getStellarNetwork(fromChainId);
39921
- if (stellarNetwork == null) {
39922
- throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39923
- }
39924
- const { data: xdrHex, gasPrice } = route.transactionRequest;
39925
- const { address } = await stellarSigner.getAddress();
39926
- const client = await getClient(fromChain);
39927
- const account = await client.getAccount(address);
39928
- const operation = xdr.Operation.fromXDR(xdrHex, "hex");
39929
- const builtTransaction = new TransactionBuilder(account, {
39930
- fee: gasPrice || (BigInt(BASE_FEE) * BigInt(2)).toString(),
39931
- networkPassphrase: stellarNetwork,
39932
- })
39933
- .addOperation(operation)
39934
- .setTimeout(300)
39935
- .build();
39936
- const preparedTransaction = await client.prepareTransaction(builtTransaction);
39937
- const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39938
- 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,
39939
39748
  });
39940
- const signedTransaction = new Transaction$1(signedTxXdr, stellarNetwork);
39941
- // get hash before submitting
39942
- const hash = signedTransaction.hash().toString("hex");
39943
- if (hash) {
39944
- resetQueriesAfterTxSigned();
39945
- }
39946
- // Dispatch event so it can be listened from outside the widget
39947
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39948
- const txParams = setTransactionState({
39949
- route,
39950
- txHash: hash,
39951
- userAddress: sourceUserAddress,
39952
- status: TransactionStatus.INITIAL_LOADING,
39953
- sourceStatus: TransactionStatus.ONGOING,
39954
- 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,
39955
39801
  });
39956
- if (txParams) {
39957
- addSwapTransaction({
39958
- ...txParams,
39959
- params: route.params,
39960
- estimate: route.estimate,
39961
- });
39962
- }
39963
- const sentTransaction = await client.sendTransaction(signedTransaction);
39964
- await client.waitForTransaction(sentTransaction.hash);
39965
- },
39966
- });
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
+ }, {});
39967
39859
  const handleTransactionSuccess = useCallback((id) => {
39968
39860
  const currentTx = getTransaction(id);
39969
- queryClient.invalidateQueries({
39970
- queryKey: getPrefixKey(QueryKeys.Balances),
39971
- });
39861
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39972
39862
  if (isSameChain && currentTx?.transactionId) {
39973
39863
  replaceSwapTransactionStatus({
39974
39864
  transactionId: currentTx.transactionId,
@@ -40020,39 +39910,38 @@ const useExecuteTransaction = (squidRoute) => {
40020
39910
  setTransactionStoreState,
40021
39911
  squidRoute,
40022
39912
  ]);
40023
- const swapMutation = useMutation({
40024
- mutationFn: async (mutationParams) => {
40025
- if (!mutationParams.route)
40026
- throw new Error("route is required");
40027
- const sourceChain = findChain(mutationParams.route.params?.fromChain);
40028
- if (!sourceChain)
40029
- throw new Error("Could not find source chain");
40030
- switch (sourceChain.chainType) {
40031
- case ChainType.COSMOS: {
40032
- return swapMutationCosmos.mutateAsync(mutationParams);
40033
- }
40034
- case ChainType.EVM: {
40035
- return swapMutationEvm.mutateAsync(mutationParams);
40036
- }
40037
- case ChainType.BTC: {
40038
- return swapMutationBitcoin.mutateAsync(mutationParams);
40039
- }
40040
- case ChainType.SOLANA: {
40041
- return swapMutationSolana.mutateAsync(mutationParams);
40042
- }
40043
- case ChainType.SUI: {
40044
- return swapMutationSui.mutateAsync(mutationParams);
40045
- }
40046
- case ChainType.XRPL: {
40047
- return swapMutationXrpl.mutateAsync(mutationParams);
40048
- }
40049
- case ChainType.STELLAR: {
40050
- return swapMutationStellar.mutateAsync(mutationParams);
40051
- }
40052
- default:
40053
- 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);
40054
39922
  }
40055
- },
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
+ }, {
40056
39945
  onMutate: (variables) => {
40057
39946
  useTransactionStore.setState({
40058
39947
  txLocalId: variables.id,
@@ -40101,7 +39990,7 @@ const useExecuteTransaction = (squidRoute) => {
40101
39990
  toToken,
40102
39991
  toChain,
40103
39992
  fromChain,
40104
- isPending: swapMutation.isPending,
39993
+ isLoading: swapMutation.isLoading,
40105
39994
  error: swapMutation.error,
40106
39995
  };
40107
39996
  };
@@ -40162,59 +40051,57 @@ const useGetRoute = () => {
40162
40051
  * These data will be used to trigger the transaction
40163
40052
  * @returns {Route} Route data
40164
40053
  */
40165
- return useMutation({
40166
- mutationFn: async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40167
- if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40168
- return undefined;
40169
- }
40170
- // Dispatch requestQuote event
40171
- dispatchRequestQuoteEvent({
40172
- fromChain,
40173
- toChain,
40174
- fromToken: fromToken.address,
40175
- toToken: toToken.address,
40176
- fromAmount: fromPrice,
40177
- fromAddress: sourceUserAddress,
40178
- toAddress: destinationAddress,
40179
- });
40180
- const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40181
- const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40182
- const fromTokenAddress = fromToken.address;
40183
- const toTokenAddress = toToken.address;
40184
- const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40185
- const fromAddress = sourceUserAddress ??
40186
- chainTypeToZeroAddressMap[fromChainType ?? ChainType.EVM];
40187
- const params = {
40188
- fromChain,
40189
- fromToken: fromTokenAddress,
40190
- fromAddress,
40191
- fromAmount,
40192
- toChain,
40193
- toToken: toTokenAddress,
40194
- toAddress: destinationAddress ?? "",
40195
- quoteOnly,
40196
- slippage: config.slippage === 0 ? undefined : config.slippage,
40197
- bypassGuardrails,
40198
- preHook,
40199
- postHook,
40200
- };
40201
- // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40202
- if (cosmosFallbackAddresses &&
40203
- cosmosFallbackAddresses.length > 0 &&
40204
- cosmosFallbackAddresses[0].address) {
40205
- params.fallbackAddresses = cosmosFallbackAddresses;
40206
- }
40207
- const { route } = await squid.getRoute({
40208
- ...params,
40209
- });
40210
- // Cache the route data
40211
- // Useful when the getRoute mutation is called from another hook
40212
- 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);
40213
- return route;
40214
- },
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;
40215
40102
  });
40216
40103
  };
40217
- const useGetRouteWrapper = ({ enabled, gcTime = 5 * 60 * 1000, // 5 minutes
40104
+ const useGetRouteWrapper = ({ enabled, cacheTime = 5 * 60 * 1000, // 5 minutes
40218
40105
  staleTime = 60 * 1000, // 1 minute
40219
40106
  refetchOnWindowFocus = (query) => Date.now() - query.state.dataUpdatedAt > 30000, // Update if older than 30 seconds, when window is focused
40220
40107
  refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true, }) => {
@@ -40264,27 +40151,25 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40264
40151
  * These data will be used to trigger the transaction
40265
40152
  * @returns {Route} Route data
40266
40153
  */
40267
- const squidRoute = useQuery({
40268
- queryKey: squidRouteQueryKeys,
40269
- queryFn: async () => {
40270
- const route = await getRouteMutation.mutateAsync({
40271
- fromChain: fromChain?.chainId,
40272
- toChain: toChain?.chainId,
40273
- fromToken,
40274
- toToken,
40275
- sourceUserAddress,
40276
- destinationAddress,
40277
- fromPrice,
40278
- bypassGuardrails: config.degenMode,
40279
- quoteOnly,
40280
- fromChainType: fromChain?.chainType,
40281
- postHook: config.postHook,
40282
- preHook: config.preHook,
40283
- });
40284
- return route;
40285
- },
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
+ }, {
40286
40171
  enabled: queryEnabled,
40287
- gcTime,
40172
+ cacheTime,
40288
40173
  staleTime,
40289
40174
  refetchOnWindowFocus,
40290
40175
  refetchIntervalInBackground,
@@ -40293,7 +40178,7 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40293
40178
  /**
40294
40179
  * If last updated data is older than X seconds and the query is currently loading, show loading indicator
40295
40180
  */
40296
- const showLoading = squidRoute.isFetching || squidRoute.isRefetching;
40181
+ const showLoading = useMemo(() => squidRoute.isFetching || squidRoute.isRefetching, [squidRoute.isFetching, squidRoute.isRefetching]);
40297
40182
  return {
40298
40183
  squidRoute,
40299
40184
  showLoading,
@@ -40325,7 +40210,7 @@ function useSendTransactionStatus({ chain, txHash, }) {
40325
40210
  transactionId: txHash,
40326
40211
  txType: HistoryTxType.SEND,
40327
40212
  });
40328
- const { data: status, isSuccess, isError, } = useQuery({
40213
+ const { data: status } = useQuery({
40329
40214
  queryKey: keys().sendTransactionStatus(txHash, chain?.chainId),
40330
40215
  queryFn: async () => {
40331
40216
  if (!chain || !txHash)
@@ -40335,30 +40220,17 @@ function useSendTransactionStatus({ chain, txHash, }) {
40335
40220
  txHash,
40336
40221
  });
40337
40222
  },
40338
- refetchInterval: chain
40339
- ? getSendTxStatusRefetchInterval(chain.chainType)
40340
- : false,
40341
- enabled: !!chain &&
40342
- !!txHash &&
40343
- !isTransactionComplete &&
40344
- !!currentHistoryItem &&
40345
- !isHistoryTransactionEnded({
40346
- data: currentHistoryItem?.data,
40347
- txType: HistoryTxType.SEND,
40348
- }),
40349
- });
40350
- useEffect(() => {
40351
- if (isSuccess) {
40352
- setIsTransactionComplete(status !== SendTransactionStatus.ONGOING);
40353
- if (status != null && !!txHash) {
40223
+ onSuccess: (txStatus) => {
40224
+ setIsTransactionComplete(txStatus !== SendTransactionStatus.ONGOING);
40225
+ if (txStatus != null && !!txHash) {
40354
40226
  replaceTransactionStatus({
40355
40227
  txType: HistoryTxType.SEND,
40356
- status: status,
40228
+ status: txStatus,
40357
40229
  hash: txHash,
40358
40230
  });
40359
40231
  }
40360
- }
40361
- if (isError) {
40232
+ },
40233
+ onError() {
40362
40234
  setIsTransactionComplete(true);
40363
40235
  if (txHash) {
40364
40236
  replaceTransactionStatus({
@@ -40367,8 +40239,19 @@ function useSendTransactionStatus({ chain, txHash, }) {
40367
40239
  hash: txHash,
40368
40240
  });
40369
40241
  }
40370
- }
40371
- }, [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
+ });
40372
40255
  return {
40373
40256
  status: status ?? currentHistoryItem?.data?.status,
40374
40257
  };
@@ -40402,9 +40285,7 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40402
40285
  apiUrl: latestConfig.apiUrl,
40403
40286
  });
40404
40287
  }, [transaction]);
40405
- const transactionStatusQuery = useQuery({
40406
- queryKey: keys().swapTransactionStatus(transaction?.transactionId),
40407
- queryFn: fetchTransactionStatusWithLatestConfig,
40288
+ const transactionStatusQuery = useQuery(keys().swapTransactionStatus(transaction?.transactionId), fetchTransactionStatusWithLatestConfig, {
40408
40289
  enabled: enabled &&
40409
40290
  transaction?.transactionId !== "0" &&
40410
40291
  !!transaction?.transactionId &&
@@ -40418,12 +40299,12 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40418
40299
  data: currentHistoryItem?.data,
40419
40300
  txType: HistoryTxType.SWAP,
40420
40301
  }),
40421
- refetchInterval({ state }) {
40302
+ refetchInterval(statusResponse) {
40422
40303
  // If the status response is something telling that the transaction
40423
40304
  // is finished, then store transaction history state if success
40424
40305
  // And return false to indicate refetcher to stop
40425
- if (state.data &&
40426
- transactionEndStatuses.includes(getTransactionStatus(state.data) ?? "")) {
40306
+ if (statusResponse &&
40307
+ transactionEndStatuses.includes(getTransactionStatus(statusResponse) ?? "")) {
40427
40308
  return false;
40428
40309
  }
40429
40310
  return refetchInterval; // Had to handle a variable here because after onError, we want the interval to stop
@@ -40432,10 +40313,7 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40432
40313
  retryDelay: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 5000 : 3000,
40433
40314
  retry: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 6 : retry,
40434
40315
  refetchOnWindowFocus,
40435
- });
40436
- useEffect(() => {
40437
- if (transactionStatusQuery.isSuccess && transactionStatusQuery.data) {
40438
- const statusResponse = transactionStatusQuery.data;
40316
+ onSuccess: (statusResponse) => {
40439
40317
  // Dispatch event
40440
40318
  WidgetEvents.getInstance().dispatchSwapStatus(statusResponse.squidTransactionStatus ?? "");
40441
40319
  const endStatus = getTransactionEndStatus({ statusResponse });
@@ -40447,9 +40325,8 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40447
40325
  status: endStatus,
40448
40326
  });
40449
40327
  }
40450
- }
40451
- if (transactionStatusQuery.isError) {
40452
- const error = transactionStatusQuery.error;
40328
+ },
40329
+ onError: (error) => {
40453
40330
  // `fetchTransactionStatus` throws an error with a cause being an AxiosError
40454
40331
  const is404 = is404Error(error.cause);
40455
40332
  if (!transaction?.transactionId)
@@ -40470,15 +40347,8 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40470
40347
  status: TransactionStatus.ERROR,
40471
40348
  });
40472
40349
  }
40473
- }
40474
- }, [
40475
- transactionStatusQuery.isSuccess,
40476
- transactionStatusQuery.isError,
40477
- transaction?.transactionId,
40478
- transactionStatusQuery.error,
40479
- replaceSwapTransactionStatus,
40480
- transactionStatusQuery.data,
40481
- ]);
40350
+ },
40351
+ });
40482
40352
  return {
40483
40353
  transactionStatusQuery,
40484
40354
  latestStatus: transactionStatusQuery.data
@@ -40521,7 +40391,7 @@ const useAvatar = (seed = zeroAddress) => {
40521
40391
  },
40522
40392
  // data is static, so no need to refetch
40523
40393
  refetchOnWindowFocus: false,
40524
- gcTime: Infinity,
40394
+ cacheTime: Infinity,
40525
40395
  staleTime: Infinity,
40526
40396
  });
40527
40397
  return avatar || "";
@@ -40563,40 +40433,38 @@ const useAddToken = (chainToCompare, tokenToCompare) => {
40563
40433
  /**
40564
40434
  * Add token to wallet
40565
40435
  */
40566
- const addToken = useMutation({
40567
- mutationFn: async ({ chain: _chain, token: _token, }) => {
40568
- const token = _token ?? tokenToCompare;
40569
- const chain = _chain ?? chainToCompare;
40570
- if (token && chain?.chainType === ChainType.EVM) {
40571
- const provider = await connector?.getProvider();
40572
- // Switch network if needed
40573
- if (currentEvmChain?.id.toString() !== token?.chainId) {
40574
- 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
+ });
40575
40455
  await switchChainAsync({
40576
40456
  chainId: +token.chainId,
40577
40457
  });
40578
40458
  }
40579
- catch (error) {
40580
- console.debug("Error switching network:", error);
40581
- if (isEvmChainNotSupportedError(error)) {
40582
- await addEthereumChain({
40583
- chain,
40584
- provider,
40585
- });
40586
- await switchChainAsync({
40587
- chainId: +token.chainId,
40588
- });
40589
- }
40590
- }
40591
- // Metamask is not popping the second modal if we don't wait a bit
40592
- // eslint-disable-next-line no-promise-executor-return
40593
- await new Promise((resolve) => setTimeout(resolve, 100));
40594
40459
  }
40595
- 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));
40596
40463
  }
40597
- // TODO: Implement keplr add token
40598
- return false;
40464
+ await addTokenToWallet({ token, provider });
40599
40465
  }
40466
+ // TODO: Implement keplr add token
40467
+ return false;
40600
40468
  });
40601
40469
  return {
40602
40470
  addToken,
@@ -40801,9 +40669,7 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40801
40669
  }
40802
40670
  },
40803
40671
  async onSuccess() {
40804
- queryClient.invalidateQueries({
40805
- queryKey: getPrefixKey(QueryKeys.XrplTrustLine),
40806
- });
40672
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.XrplTrustLine));
40807
40673
  },
40808
40674
  });
40809
40675
  /**
@@ -40870,5 +40736,116 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40870
40736
  };
40871
40737
  }
40872
40738
 
40873
- 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, normalizeIbcAddress 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, queryClient as aI, SquidProvider as aJ, EnsService as aK, getXummClient as aL, isXamanXAppContext as aM, getQueryHeaders as aN, getStatusCode as aO, is404Error as aP, assetsBaseUrl as aQ, shareSubgraphId as aR, sortTokensBySharedSubgraphIds as aS, getSupportedChainIdsForDirection as aT, filterChains as aU, filterTokens as aV, getTokenImage as aW, getNewSwapParamsFromInput as aX, sortAllTokens as aY, findToken as aZ, findNativeToken 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$, groupTokensBySymbol as b0, groupTokensByChainId as b1, filterViewableTokens as b2, getSecretNetworkBalances as b3, getTokenAssetsKey as b4, fetchAssetsColors as b5, initializeSquidWithAssetsColors as b6, isEmptyObject as b7, normalizeTokenSymbol as b8, areTokenSymbolsCompatible 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_, isEvmosChain as ba, getConfigWithDefaults 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 };
40874
- //# sourceMappingURL=index-gPUCtJnZ.js.map
40739
+ // Prevent fetching too soon after the first successful request.
40740
+ const DEFAULT_STALE_TIME = 8000;
40741
+ const defaultOptions = {
40742
+ queries: {
40743
+ staleTime: DEFAULT_STALE_TIME,
40744
+ refetchOnWindowFocus: false,
40745
+ retry: false,
40746
+ retryOnMount: false,
40747
+ },
40748
+ };
40749
+
40750
+ const queryClient = new QueryClient({ defaultOptions });
40751
+ const verifyIntegratorIdValidity = (integratorId) => {
40752
+ if (!integratorId) {
40753
+ throw new Error("Integrator ID is required");
40754
+ }
40755
+ };
40756
+ const SquidProvider = ({ children, config, placeholder, }) => {
40757
+ verifyIntegratorIdValidity(config.integratorId);
40758
+ const [wagmiConfig, setWagmiConfig] = useState();
40759
+ const sdkInitializedRef = useRef(false);
40760
+ const initializeSdk = useCallback(async () => {
40761
+ if (sdkInitializedRef.current) {
40762
+ return;
40763
+ }
40764
+ sdkInitializedRef.current = true;
40765
+ try {
40766
+ const squid = new Squid({
40767
+ integratorId: config.integratorId,
40768
+ baseUrl: config.apiUrl ?? squidApiBaseUrl,
40769
+ });
40770
+ const [sdkInfoResponse, assetsColorsResponse] = await Promise.allSettled([
40771
+ squid.init(),
40772
+ fetchAssetsColors(),
40773
+ ]);
40774
+ if (sdkInfoResponse.status === "rejected") {
40775
+ throw sdkInfoResponse.reason;
40776
+ }
40777
+ if (assetsColorsResponse.status === "fulfilled") {
40778
+ useAssetsColorsStore.setState(assetsColorsResponse.value);
40779
+ initializeSquidWithAssetsColors(squid, assetsColorsResponse.value);
40780
+ }
40781
+ const shouldResetSwapRouteStore =
40782
+ // reset swap route if specified in config
40783
+ !config?.loadPreviousStateFromLocalStorage ||
40784
+ // or if initial assets are provided
40785
+ !isEmptyObject(config.initialAssets?.from) ||
40786
+ !isEmptyObject(config.initialAssets?.to);
40787
+ if (shouldResetSwapRouteStore) {
40788
+ useSwapRoutePersistStore.setState({
40789
+ swapRoute: undefined,
40790
+ });
40791
+ }
40792
+ useSquidStore.setState((_) => ({
40793
+ squid,
40794
+ maintenanceMode: { active: false, message: undefined },
40795
+ }));
40796
+ const newWagmiConfig = createWagmiConfig(squid.chains);
40797
+ setWagmiConfig(newWagmiConfig);
40798
+ useConfigStore.setState({
40799
+ isInitialized: true,
40800
+ config: getConfigWithDefaults(config),
40801
+ });
40802
+ }
40803
+ catch (error) {
40804
+ const isAxios503Error = error.isAxiosError &&
40805
+ error.response?.status === 503;
40806
+ if (isAxios503Error) {
40807
+ const maintenanceMessage = error.response?.data
40808
+ ?.message ?? undefined;
40809
+ // Even with an error, we want wagmi to be defined so that we can display the maintenance mode layout
40810
+ // Create wagmi config with mainnet as fallback in maintenance mode
40811
+ const newWagmiConfig = createConfig({
40812
+ chains: [mainnet],
40813
+ connectors: [injected()],
40814
+ transports: {
40815
+ [mainnet.id]: http(),
40816
+ },
40817
+ });
40818
+ setWagmiConfig(newWagmiConfig);
40819
+ useConfigStore.setState({
40820
+ isInitialized: false,
40821
+ config: getConfigWithDefaults(config),
40822
+ });
40823
+ useSquidStore.setState({
40824
+ squid: undefined,
40825
+ maintenanceMode: {
40826
+ active: true,
40827
+ message: maintenanceMessage,
40828
+ },
40829
+ });
40830
+ }
40831
+ else {
40832
+ console.error("Error initializing SDK:", error);
40833
+ }
40834
+ }
40835
+ }, [config]);
40836
+ useEffect(() => {
40837
+ initializeSdk();
40838
+ }, [initializeSdk]);
40839
+ return wagmiConfig ? (React.createElement(WagmiProvider, { reconnectOnMount: false, config: wagmiConfig },
40840
+ React.createElement(QueryClientProvider, { client: queryClient },
40841
+ React.createElement(StellarProvider, null,
40842
+ React.createElement(EvmProvider, null,
40843
+ React.createElement(XrplProvider, null,
40844
+ React.createElement(SuiProvider, null,
40845
+ React.createElement(SolanaProvider, null,
40846
+ React.createElement(BitcoinProvider, null,
40847
+ React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
40848
+ };
40849
+
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