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

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 (37) hide show
  1. package/dist/hooks/onramp/useFiatToCrypto.d.ts +6 -28
  2. package/dist/hooks/squid/useSquid.d.ts +2 -2
  3. package/dist/hooks/swap/useDepositAddress.d.ts +2 -2
  4. package/dist/hooks/tokens/useAllConnectedWalletBalances.d.ts +5 -11
  5. package/dist/hooks/tokens/useAllTokensWithBalanceForChainType.d.ts +1 -1
  6. package/dist/hooks/tokens/useBalance.d.ts +1 -1
  7. package/dist/hooks/tokens/useMultipleTokenPrices.d.ts +2 -2
  8. package/dist/hooks/tokens/useNativeBalance.d.ts +2 -2
  9. package/dist/hooks/tokens/useTokenHistoricalData.d.ts +4 -4
  10. package/dist/hooks/transaction/send/useEstimateSendTransactionGas.d.ts +1 -1
  11. package/dist/hooks/transaction/send/useSendTransactionGas.d.ts +1 -1
  12. package/dist/hooks/transaction/useAllTransactionsStatus.d.ts +3 -29
  13. package/dist/hooks/transaction/useApproval.d.ts +2 -2
  14. package/dist/hooks/transaction/useExecuteTransaction.d.ts +2 -2
  15. package/dist/hooks/transaction/useGetRoute.d.ts +7 -7
  16. package/dist/hooks/transaction/useSwapTransactionStatus.d.ts +1 -1
  17. package/dist/hooks/wallet/useAddToken.d.ts +1 -1
  18. package/dist/hooks/wallet/useEns.d.ts +2 -2
  19. package/dist/hooks/wallet/useMultiChainWallet.d.ts +1 -1
  20. package/dist/hooks/wallet/useWallet.d.ts +1 -1
  21. package/dist/hooks/xrpl/useXrplTrustLine.d.ts +5 -5
  22. package/dist/{index-_Qp4Ou3J.js → index-BA79s7uI.js} +948 -951
  23. package/dist/{index-_Qp4Ou3J.js.map → index-BA79s7uI.js.map} +1 -1
  24. package/dist/{index-BtOPNnH5.js → index-CS74WzWX.js} +946 -952
  25. package/dist/{index-BtOPNnH5.js.map → index-CS74WzWX.js.map} +1 -1
  26. package/dist/index.esm.js +1 -1
  27. package/dist/index.js +1 -4
  28. package/dist/index.js.map +1 -1
  29. package/dist/{secretService-CR2RaJtB.js → secretService-D3MB_TMv.js} +2 -2
  30. package/dist/{secretService-CR2RaJtB.js.map → secretService-D3MB_TMv.js.map} +1 -1
  31. package/dist/{secretService-DdVLwd-q.js → secretService-U8WiVPay.js} +2 -2
  32. package/dist/{secretService-DdVLwd-q.js.map → secretService-U8WiVPay.js.map} +1 -1
  33. package/dist/{stellarService.client-7rBIc_IW.js → stellarService.client-BUdrOP04.js} +2 -2
  34. package/dist/{stellarService.client-7rBIc_IW.js.map → stellarService.client-BUdrOP04.js.map} +1 -1
  35. package/dist/{stellarService.client-BvSwmxzo.js → stellarService.client-Dp4tvmUo.js} +2 -2
  36. package/dist/{stellarService.client-BvSwmxzo.js.map → stellarService.client-Dp4tvmUo.js.map} +1 -1
  37. package/package.json +12 -12
@@ -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, useQueries, useQueryClient, QueryClient, QueryClientProvider } from '@tanstack/react-query';
4
+ import { useQuery, useMutation, useQueryClient, useQueries, 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';
@@ -26795,7 +26795,9 @@ const fetchHighestBalanceToken = (fetchCachedBalance, chainId) => {
26795
26795
  if (fetchCachedBalance) {
26796
26796
  const queryCache = fetchCachedBalance?.queryClient?.getQueryCache();
26797
26797
  // get cached balance from key
26798
- const cache = queryCache?.find(keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? ChainType.EVM : ChainType.COSMOS));
26798
+ const cache = queryCache?.find({
26799
+ queryKey: keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? ChainType.EVM : ChainType.COSMOS),
26800
+ });
26799
26801
  // Parse result to TokenWithBalance[]
26800
26802
  const cacheResult = cache?.state.data ?? [];
26801
26803
  if (cacheResult.length > 0) {
@@ -27451,7 +27453,7 @@ const filterViewableTokens = (tokens, config, direction) => {
27451
27453
  };
27452
27454
  const getSecretNetworkBalances = async (chainData, cosmosAddress, squidTokens, keplrTypeWallet) => {
27453
27455
  const squidSecretTokens = squidTokens.filter((t) => t.chainId === CHAIN_IDS.SECRET);
27454
- const { fetchAllSecretBalances } = await import('./secretService-CR2RaJtB.js');
27456
+ const { fetchAllSecretBalances } = await import('./secretService-D3MB_TMv.js');
27455
27457
  return fetchAllSecretBalances(chainData, cosmosAddress, squidSecretTokens, keplrTypeWallet);
27456
27458
  };
27457
27459
  function getTokenAssetsKey(token) {
@@ -29210,13 +29212,16 @@ const useSquid = () => {
29210
29212
  * Fetch squid info
29211
29213
  * Will refetch every minute
29212
29214
  */
29213
- const squidInfoQuery = useQuery(keys().squidInfo(), async () => {
29214
- if (squid) {
29215
- await squid?.init();
29216
- initializeSquidWithAssetsColors(squid, assetsColors);
29217
- return squid;
29215
+ const squidInfoQuery = useQuery({
29216
+ queryKey: keys().squidInfo(),
29217
+ queryFn: async () => {
29218
+ if (squid) {
29219
+ await squid?.init();
29220
+ initializeSquidWithAssetsColors(squid, assetsColors);
29221
+ return squid;
29222
+ }
29223
+ return null;
29218
29224
  }
29219
- return null;
29220
29225
  });
29221
29226
  const tokens = useMemo(() => {
29222
29227
  if ((squidInfoQuery?.data?.tokens ?? []).length > 0) {
@@ -29332,47 +29337,11 @@ const FINAL_TRANSACTION_STATUSES = [
29332
29337
  "completed",
29333
29338
  "failed",
29334
29339
  ];
29335
- /**
29336
- * Configuration for transaction status tracking
29337
- */
29338
- const createTransactionStatusConfig = ({ transactionId, walletAddress, providerId, replaceTransactionStatus, }) => {
29339
- return {
29340
- queryKey: keys().fiatToCryptoStatus(transactionId),
29341
- queryFn: () => new OnrampService().getTransactionStatus(transactionId, walletAddress, providerId),
29342
- enabled: !!transactionId && !!walletAddress && !!providerId,
29343
- retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
29344
- retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
29345
- refetchInterval: (data) => {
29346
- if (data?.status && FINAL_TRANSACTION_STATUSES.includes(data.status)) {
29347
- return false;
29348
- }
29349
- return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
29350
- },
29351
- onSuccess: (data) => {
29352
- if (data) {
29353
- replaceTransactionStatus({
29354
- txType: HistoryTxType.BUY,
29355
- orderId: transactionId,
29356
- status: data.status,
29357
- transactionHash: data.transactionHash,
29358
- });
29359
- }
29360
- },
29361
- onError: () => {
29362
- replaceTransactionStatus({
29363
- txType: HistoryTxType.BUY,
29364
- orderId: transactionId,
29365
- status: "failed",
29366
- transactionHash: undefined,
29367
- });
29368
- },
29369
- };
29370
- };
29371
29340
  /**
29372
29341
  * Fetches quotes for fiat to crypto conversion with provider details.
29373
29342
  * Returns available rates, fees, and supported payment methods for the conversion.
29374
29343
  */
29375
- const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, onSuccess, }) => {
29344
+ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, }) => {
29376
29345
  const service = useMemo(() => new OnrampService(), []);
29377
29346
  const { data: config } = useGetOnRampConfig();
29378
29347
  return useQuery({
@@ -29408,7 +29377,6 @@ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, payme
29408
29377
  return quoteResponse;
29409
29378
  },
29410
29379
  enabled: enabled && !!fiatCurrency && !!cryptoCurrencyID && amount > 0,
29411
- onSuccess,
29412
29380
  });
29413
29381
  };
29414
29382
  /**
@@ -29425,7 +29393,7 @@ const useGetOnRampConfig = () => {
29425
29393
  chains,
29426
29394
  tokens,
29427
29395
  }),
29428
- cacheTime: 1000 * 60 * 60,
29396
+ gcTime: 1000 * 60 * 60,
29429
29397
  staleTime: 1000 * 60 * 30, // 30 minutes
29430
29398
  });
29431
29399
  };
@@ -29483,49 +29451,11 @@ const useExecuteFiatQuote = () => {
29483
29451
  },
29484
29452
  });
29485
29453
  };
29486
- /**
29487
- * Tracks the status of a single fiat to crypto transaction.
29488
- */
29489
- const useFiatOnRampTxStatus = (transactionId, walletAddress, providerId) => {
29490
- const replaceTransactionStatus = useHistoryStore((state) => state.replaceTransactionStatus);
29491
- return useQuery({
29492
- ...createTransactionStatusConfig({
29493
- transactionId,
29494
- walletAddress,
29495
- providerId,
29496
- replaceTransactionStatus,
29497
- }),
29498
- });
29499
- };
29500
- /**
29501
- * Tracks all pending fiat transactions.
29502
- */
29503
- const useFiatTransactions = () => {
29504
- const transactions = useHistoryStore((state) => state.transactions.filter((tx) => tx.txType === HistoryTxType.BUY));
29505
- const replaceTransactionStatus = useHistoryStore((state) => state.replaceTransactionStatus);
29506
- const pendingTransactions = useMemo(() => transactions?.filter((tx) => !FINAL_TRANSACTION_STATUSES.includes(tx.data.status)) ?? [], [transactions]);
29507
- const queries = useQueries({
29508
- queries: pendingTransactions.map((tx) => ({
29509
- ...createTransactionStatusConfig({
29510
- transactionId: tx.data.orderId,
29511
- walletAddress: tx.data.toAddress,
29512
- providerId: tx.data.providerId,
29513
- replaceTransactionStatus,
29514
- }),
29515
- })),
29516
- });
29517
- return {
29518
- transactions: transactions.map((tx) => tx.data),
29519
- isLoading: queries.some((q) => q.isLoading),
29520
- isError: queries.some((q) => q.isError),
29521
- };
29522
- };
29523
29454
  /**
29524
29455
  * Gets currency details including symbol and limits.
29525
29456
  * Example: USD → { symbol: "$", name: "US Dollar", ... }
29526
29457
  */
29527
29458
  const useCurrencyDetails = (currencyCode) => {
29528
- const { data: config } = useGetOnRampConfig();
29529
29459
  return useMemo(() => {
29530
29460
  if (!currencyCode)
29531
29461
  return undefined;
@@ -29538,7 +29468,7 @@ const useCurrencyDetails = (currencyCode) => {
29538
29468
  };
29539
29469
  }
29540
29470
  return undefined;
29541
- }, [currencyCode, config?.supportedFiats]);
29471
+ }, [currencyCode]);
29542
29472
  };
29543
29473
  /**
29544
29474
  * Gets country details with flag URL and localized name.
@@ -29565,23 +29495,6 @@ const useAvailableQuotes = (quotes) => {
29565
29495
  return uniqueQuotes;
29566
29496
  }, [quotes]);
29567
29497
  };
29568
- /**
29569
- * Gets the recommended quote based on best rates or provider preferences.
29570
- * Falls back to first available quote if no specific recommendation.
29571
- */
29572
- const useRecommendedQuote = (quotes, recommendedQuote) => {
29573
- const availableQuotes = useAvailableQuotes(quotes);
29574
- return useMemo(() => {
29575
- if (!availableQuotes.length)
29576
- return undefined;
29577
- if (!recommendedQuote)
29578
- return availableQuotes[0];
29579
- // Try to find the recommended quote among available quotes
29580
- const recommendedAvailableQuote = availableQuotes.find((quote) => quote.onrampProviderId === recommendedQuote.onrampProviderId);
29581
- // If recommended quote is not available, return first available quote
29582
- return recommendedAvailableQuote ?? availableQuotes[0];
29583
- }, [availableQuotes, recommendedQuote]);
29584
- };
29585
29498
  /**
29586
29499
  * Fetches the available payment methods for a given fiat and crypto currency pair.
29587
29500
  * The first item in the returned array is the most recommended.
@@ -29684,7 +29597,7 @@ const middleStepChecker = (statusResponse) => {
29684
29597
  }
29685
29598
  return TransactionStatus.ERROR;
29686
29599
  }
29687
- if (statusResponse?.isInitialLoading) {
29600
+ if (statusResponse?.isLoading) {
29688
29601
  return TransactionStatus.INITIAL_LOADING;
29689
29602
  }
29690
29603
  return TransactionStatus.ONGOING;
@@ -30129,7 +30042,7 @@ const useClient = () => {
30129
30042
  queryFn: getUserCountry,
30130
30043
  enabled: isClient,
30131
30044
  retry: false,
30132
- cacheTime: CACHE_TIME,
30045
+ gcTime: CACHE_TIME,
30133
30046
  staleTime: STALE_TIME,
30134
30047
  });
30135
30048
  const userCountry = countryData?.countryCode || DEFAULT_COUNTRY_CODE;
@@ -30230,11 +30143,13 @@ function useDebouncedValue(value, delay) {
30230
30143
  * @returns the ENS data of the given address
30231
30144
  */
30232
30145
  function useEnsDataForAddress({ address, options, }) {
30233
- const ensQuery = useQuery(keys().ensData(address?.toLowerCase()), () => EnsService.getEnsDataFromAddress(address), {
30146
+ const ensQuery = useQuery({
30147
+ queryKey: keys().ensData(address?.toLowerCase()),
30148
+ queryFn: () => EnsService.getEnsDataFromAddress(address),
30234
30149
  ...options,
30235
30150
  enabled: Boolean(address?.trim()) &&
30236
30151
  (options?.enabled === undefined ? true : options.enabled),
30237
- cacheTime: Infinity,
30152
+ gcTime: Infinity,
30238
30153
  });
30239
30154
  return ensQuery;
30240
30155
  }
@@ -30250,14 +30165,16 @@ function useEnsDataForAddress({ address, options, }) {
30250
30165
  */
30251
30166
  function useEnsSearch({ name, enabled = true, delayMs = 500, }) {
30252
30167
  const debouncedName = useDebouncedValue(enabled ? name : undefined, delayMs);
30253
- const ensSearchQuery = useQuery(keys().ensSearch(debouncedName), () => {
30254
- const isExactEnsSearch = checkIsExactEns(debouncedName);
30255
- return isExactEnsSearch
30256
- ? EnsService.getExactEns(debouncedName)
30257
- : EnsService.searchEnsNames(debouncedName);
30258
- }, {
30168
+ const ensSearchQuery = useQuery({
30169
+ queryKey: keys().ensSearch(debouncedName),
30170
+ queryFn: () => {
30171
+ const isExactEnsSearch = checkIsExactEns(debouncedName);
30172
+ return isExactEnsSearch
30173
+ ? EnsService.getExactEns(debouncedName)
30174
+ : EnsService.searchEnsNames(debouncedName);
30175
+ },
30259
30176
  enabled: Boolean(debouncedName?.trim()) && enabled,
30260
- cacheTime: Infinity,
30177
+ gcTime: Infinity,
30261
30178
  });
30262
30179
  return ensSearchQuery;
30263
30180
  }
@@ -30278,23 +30195,25 @@ function checkIsExactEns(name = "") {
30278
30195
 
30279
30196
  const useCosmosForChain = (chain) => {
30280
30197
  const { keplrTypeWallet } = useCosmosSigner({ chain });
30281
- const cosmosAddressQuery = useQuery(keys().cosmosAddress(chain?.chainId), async () => {
30282
- if (!chain || !keplrTypeWallet)
30283
- return "";
30284
- try {
30285
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30286
- return address ?? "";
30287
- }
30288
- catch (error) {
30289
- await suggestChainOrThrow({
30290
- chain: chain,
30291
- error,
30292
- keplrTypeWallet,
30293
- });
30294
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30295
- return address ?? "";
30296
- }
30297
- }, {
30198
+ const cosmosAddressQuery = useQuery({
30199
+ queryKey: keys().cosmosAddress(chain?.chainId),
30200
+ queryFn: async () => {
30201
+ if (!chain || !keplrTypeWallet)
30202
+ return "";
30203
+ try {
30204
+ const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30205
+ return address ?? "";
30206
+ }
30207
+ catch (error) {
30208
+ await suggestChainOrThrow({
30209
+ chain: chain,
30210
+ error,
30211
+ keplrTypeWallet,
30212
+ });
30213
+ const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30214
+ return address ?? "";
30215
+ }
30216
+ },
30298
30217
  enabled: !!keplrTypeWallet && chain?.chainType === ChainType.COSMOS,
30299
30218
  });
30300
30219
  return cosmosAddressQuery;
@@ -30371,12 +30290,14 @@ const useIsSameAddressAndGnosisContext = () => {
30371
30290
 
30372
30291
  function useBitcoin() {
30373
30292
  const connectedBitcoinWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.BTC]);
30374
- const connectBitcoin = useMutation(async ({ wallet, }) => {
30375
- const { address } = await wallet.connector.requestAccount();
30376
- return {
30377
- wallet,
30378
- address,
30379
- };
30293
+ const connectBitcoin = useMutation({
30294
+ mutationFn: async ({ wallet, }) => {
30295
+ const { address } = await wallet.connector.requestAccount();
30296
+ return {
30297
+ wallet,
30298
+ address,
30299
+ };
30300
+ }
30380
30301
  });
30381
30302
  return {
30382
30303
  connectBitcoin,
@@ -30416,15 +30337,17 @@ function useEvm() {
30416
30337
  const { wallets } = useEvmWallets();
30417
30338
  const connectedEvmWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.EVM]);
30418
30339
  const recentEvmWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.EVM]);
30419
- const connectEvm = useMutation(async ({ wallet, }) => {
30420
- const result = await connectAsync({
30421
- connector: wallet.connector,
30422
- });
30423
- const [firstAddress] = result.accounts;
30424
- return {
30425
- wallet,
30426
- address: firstAddress,
30427
- };
30340
+ const connectEvm = useMutation({
30341
+ mutationFn: async ({ wallet, }) => {
30342
+ const result = await connectAsync({
30343
+ connector: wallet.connector,
30344
+ });
30345
+ const [firstAddress] = result.accounts;
30346
+ return {
30347
+ wallet,
30348
+ address: firstAddress,
30349
+ };
30350
+ }
30428
30351
  });
30429
30352
  const disconnectEvm = useCallback(async () => {
30430
30353
  disconnect({ connector: connectedEvmWallet.wallet?.connector });
@@ -30518,21 +30441,23 @@ function useSolana() {
30518
30441
  const { wallets } = useSolanaWallets();
30519
30442
  const connectedSolanaWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.SOLANA]);
30520
30443
  const recentSolanaWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.SOLANA]);
30521
- const connectSolana = useMutation(async ({ wallet, }) => {
30522
- try {
30523
- // try to connect silently first
30524
- await wallet.connector.autoConnect();
30525
- }
30526
- catch {
30527
- // if auto-connect fails (e.g. not authorized yet)
30528
- // fallback to connect via popup
30529
- await wallet.connector.connect();
30444
+ const connectSolana = useMutation({
30445
+ mutationFn: async ({ wallet, }) => {
30446
+ try {
30447
+ // try to connect silently first
30448
+ await wallet.connector.autoConnect();
30449
+ }
30450
+ catch {
30451
+ // if auto-connect fails (e.g. not authorized yet)
30452
+ // fallback to connect via popup
30453
+ await wallet.connector.connect();
30454
+ }
30455
+ const address = wallet.connector.wallet.accounts[0].address;
30456
+ return {
30457
+ wallet,
30458
+ address,
30459
+ };
30530
30460
  }
30531
- const address = wallet.connector.wallet.accounts[0].address;
30532
- return {
30533
- wallet,
30534
- address,
30535
- };
30536
30461
  });
30537
30462
  const disconnectSolana = useCallback(async () => {
30538
30463
  await connectedSolanaWallet.wallet?.connector.disconnect();
@@ -30607,7 +30532,7 @@ function useStellarWallets() {
30607
30532
  return;
30608
30533
  try {
30609
30534
  const { allowAllModules: initializeAllModules } = await import('@creit.tech/stellar-wallets-kit');
30610
- const { formatStellarWallet } = await import('./stellarService.client-BvSwmxzo.js');
30535
+ const { formatStellarWallet } = await import('./stellarService.client-Dp4tvmUo.js');
30611
30536
  const modules = initializeAllModules();
30612
30537
  const promises = modules.map(async (module) => {
30613
30538
  const isAvailable = await module.isAvailable();
@@ -30635,12 +30560,14 @@ function useStellarWallets() {
30635
30560
  function useStellar() {
30636
30561
  const { wallets } = useStellarWallets();
30637
30562
  const connectedStellarWallet = useWalletStore((store) => store.connectedWalletsByChainType[ChainType.STELLAR]);
30638
- const connectStellar = useMutation(async ({ wallet, }) => {
30639
- const { address } = await wallet.connector.getAddress();
30640
- return {
30641
- wallet,
30642
- address,
30643
- };
30563
+ const connectStellar = useMutation({
30564
+ mutationFn: async ({ wallet, }) => {
30565
+ const { address } = await wallet.connector.getAddress();
30566
+ return {
30567
+ wallet,
30568
+ address,
30569
+ };
30570
+ }
30644
30571
  });
30645
30572
  const disconnectStellar = useCallback(async () => {
30646
30573
  await connectedStellarWallet.wallet?.connector.disconnect?.();
@@ -30692,22 +30619,24 @@ function useSui() {
30692
30619
  const recentSuiWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.SUI]);
30693
30620
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
30694
30621
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
30695
- const connectSui = useMutation(async ({ wallet, }) => {
30696
- let account;
30697
- try {
30698
- // try to connect silently first
30699
- account = await wallet.connector.connect({ silent: true });
30700
- }
30701
- catch {
30702
- // if auto-connect fails (e.g. not authorized yet)
30703
- // fallback to connect via popup
30704
- account = await wallet.connector.connect();
30622
+ const connectSui = useMutation({
30623
+ mutationFn: async ({ wallet, }) => {
30624
+ let account;
30625
+ try {
30626
+ // try to connect silently first
30627
+ account = await wallet.connector.connect({ silent: true });
30628
+ }
30629
+ catch {
30630
+ // if auto-connect fails (e.g. not authorized yet)
30631
+ // fallback to connect via popup
30632
+ account = await wallet.connector.connect();
30633
+ }
30634
+ return {
30635
+ wallet,
30636
+ address: account.account.address,
30637
+ account: account.account,
30638
+ };
30705
30639
  }
30706
- return {
30707
- wallet,
30708
- address: account.account.address,
30709
- account: account.account,
30710
- };
30711
30640
  });
30712
30641
  const disconnectSui = useCallback(async () => {
30713
30642
  await connectedSuiWallet.wallet?.connector.disconnect();
@@ -31016,12 +30945,14 @@ function useXrpl() {
31016
30945
  const recentXrplWalletId = useWalletStore((store) => store.recentConnectorIds[ChainType.XRPL]);
31017
30946
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
31018
30947
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
31019
- const connectXrpl = useMutation(async ({ wallet, }) => {
31020
- const xrplConnectedAddress = await wallet.connector.connect();
31021
- return {
31022
- wallet,
31023
- address: xrplConnectedAddress,
31024
- };
30948
+ const connectXrpl = useMutation({
30949
+ mutationFn: async ({ wallet, }) => {
30950
+ const xrplConnectedAddress = await wallet.connector.connect();
30951
+ return {
30952
+ wallet,
30953
+ address: xrplConnectedAddress,
30954
+ };
30955
+ }
31025
30956
  });
31026
30957
  const disconnectXrpl = useCallback(async () => {
31027
30958
  await connectedXrplWallet?.wallet?.connector.disconnect?.();
@@ -31408,18 +31339,19 @@ const useMultiChainWallet = (chain) => {
31408
31339
  /**
31409
31340
  * Change current network for desired chain
31410
31341
  */
31411
- const changeNetworkIfNeeded = useMutation(async () => {
31412
- const isNotOnDesiredChain = chain?.chainType === ChainType.EVM &&
31413
- currentEvmChain?.id !== Number(chain.chainId);
31414
- if (isNotOnDesiredChain) {
31415
- await switchChainAsync({
31416
- chainId: Number(chain.chainId),
31417
- });
31418
- }
31419
- // Implement keplr change network
31420
- // Looks like there are no method to do that at the moment
31421
- return false;
31422
- }, {
31342
+ const changeNetworkIfNeeded = useMutation({
31343
+ mutationFn: async () => {
31344
+ const isNotOnDesiredChain = chain?.chainType === ChainType.EVM &&
31345
+ currentEvmChain?.id !== Number(chain.chainId);
31346
+ if (isNotOnDesiredChain) {
31347
+ await switchChainAsync({
31348
+ chainId: Number(chain.chainId),
31349
+ });
31350
+ }
31351
+ // Implement keplr change network
31352
+ // Looks like there are no method to do that at the moment
31353
+ return false;
31354
+ },
31423
31355
  onError: async (error) => {
31424
31356
  if (error instanceof UserRejectedRequestError) {
31425
31357
  return;
@@ -31431,7 +31363,7 @@ const useMultiChainWallet = (chain) => {
31431
31363
  provider,
31432
31364
  });
31433
31365
  }
31434
- },
31366
+ }
31435
31367
  });
31436
31368
  const isChainTypeConnected = useCallback((chainType) => {
31437
31369
  if (isGnosisConnected && chainType === ChainType.EVM) {
@@ -31779,51 +31711,53 @@ const useCosmos = () => {
31779
31711
  clientWindow?.removeEventListener("keplr_keystorechange", () => handleKeplrAccountChanged());
31780
31712
  };
31781
31713
  }, [handleKeplrAccountChanged, clientWindow]);
31782
- const connectCosmos = useMutation(async ({ chain, wallet, approveAllChains = true, }) => {
31783
- const chainInfos = getCosmosChainInfosObject(chain);
31784
- const cosmosWalletObject = wallet.connector().provider;
31785
- if (cosmosWalletObject) {
31786
- setCosmosChainId(chainInfos.chainId.toString());
31787
- try {
31788
- if (approveAllChains &&
31789
- typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31790
- "function") {
31791
- try {
31792
- const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31793
- const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31794
- const chainsToEnable = cosmosChains
31795
- .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31796
- .map((c) => c.chainId.toString());
31797
- await cosmosWalletObject.enable(chainsToEnable);
31714
+ const connectCosmos = useMutation({
31715
+ mutationFn: async ({ chain, wallet, approveAllChains = true, }) => {
31716
+ const chainInfos = getCosmosChainInfosObject(chain);
31717
+ const cosmosWalletObject = wallet.connector().provider;
31718
+ if (cosmosWalletObject) {
31719
+ setCosmosChainId(chainInfos.chainId.toString());
31720
+ try {
31721
+ if (approveAllChains &&
31722
+ typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31723
+ "function") {
31724
+ try {
31725
+ const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31726
+ const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31727
+ const chainsToEnable = cosmosChains
31728
+ .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31729
+ .map((c) => c.chainId.toString());
31730
+ await cosmosWalletObject.enable(chainsToEnable);
31731
+ }
31732
+ catch (error) {
31733
+ console.warn("Failed to get chain infos, falling back to single chain enable", error);
31734
+ await cosmosWalletObject.enable(chainInfos.chainId);
31735
+ }
31798
31736
  }
31799
- catch (error) {
31800
- console.warn("Failed to get chain infos, falling back to single chain enable", error);
31737
+ else {
31801
31738
  await cosmosWalletObject.enable(chainInfos.chainId);
31802
31739
  }
31740
+ const address = await getAddress({
31741
+ chainId: chain.chainId.toString(),
31742
+ cosmosWalletObject,
31743
+ wallet,
31744
+ });
31745
+ if (address) {
31746
+ updateWalletStore(wallet, cosmosWalletObject, address);
31747
+ return address;
31748
+ }
31803
31749
  }
31804
- else {
31805
- await cosmosWalletObject.enable(chainInfos.chainId);
31806
- }
31807
- const address = await getAddress({
31808
- chainId: chain.chainId.toString(),
31809
- cosmosWalletObject,
31810
- wallet,
31811
- });
31812
- if (address) {
31813
- updateWalletStore(wallet, cosmosWalletObject, address);
31814
- return address;
31750
+ catch (error) {
31751
+ await suggestChainOrThrow({
31752
+ chain,
31753
+ error,
31754
+ keplrTypeWallet: cosmosWalletObject,
31755
+ });
31756
+ return connectCosmos.mutateAsync({ chain, wallet });
31815
31757
  }
31816
31758
  }
31817
- catch (error) {
31818
- await suggestChainOrThrow({
31819
- chain,
31820
- error,
31821
- keplrTypeWallet: cosmosWalletObject,
31822
- });
31823
- return connectCosmos.mutateAsync({ chain, wallet });
31824
- }
31759
+ return undefined;
31825
31760
  }
31826
- return undefined;
31827
31761
  });
31828
31762
  const clearData = () => {
31829
31763
  disconnectWallet(ChainType.COSMOS);
@@ -31977,11 +31911,11 @@ const useSquidQueryClient = () => {
31977
31911
  const queryClient = useQueryClient();
31978
31912
  const invalidateQueries = (key) => {
31979
31913
  const prefixKey = getPrefixKey(key);
31980
- queryClient.invalidateQueries(prefixKey);
31914
+ queryClient.invalidateQueries({ queryKey: prefixKey });
31981
31915
  };
31982
31916
  const refetchQueries = (key) => {
31983
31917
  const prefixKey = getPrefixKey(key);
31984
- queryClient.refetchQueries(prefixKey);
31918
+ queryClient.refetchQueries({ queryKey: prefixKey });
31985
31919
  };
31986
31920
  const invalidateAndRefetchQueries = (key) => {
31987
31921
  invalidateQueries(key);
@@ -33488,17 +33422,19 @@ function useDepositAddress(squidRoute) {
33488
33422
  toggleDepositFlow(false);
33489
33423
  setDeposit(null);
33490
33424
  }, [toggleDepositFlow, setDeposit]);
33491
- const getRouteWithDeposit = useMutation(async ({ route }) => {
33492
- if (!squid)
33493
- throw new Error("Squid SDK not initialized");
33494
- const depositAddressResponse = (await squid.executeRoute({
33495
- signer: {},
33496
- route,
33497
- }));
33498
- setDeposit(depositAddressResponse);
33499
- return {
33500
- depositAddress: depositAddressResponse,
33501
- };
33425
+ const getRouteWithDeposit = useMutation({
33426
+ mutationFn: async ({ route }) => {
33427
+ if (!squid)
33428
+ throw new Error("Squid SDK not initialized");
33429
+ const depositAddressResponse = (await squid.executeRoute({
33430
+ signer: {},
33431
+ route,
33432
+ }));
33433
+ setDeposit(depositAddressResponse);
33434
+ return {
33435
+ depositAddress: depositAddressResponse,
33436
+ };
33437
+ }
33502
33438
  });
33503
33439
  return {
33504
33440
  isEnabled,
@@ -33582,53 +33518,55 @@ const useAllTokensWithBalanceForChainType = ({ chainType, address, direction, qu
33582
33518
  xrplTokens.length,
33583
33519
  stellarTokens.length,
33584
33520
  ]);
33585
- const query = useQuery(keys().allTokensBalance(address, chainType, direction), async () => {
33586
- // Return zero balances if no address
33587
- if (!address) {
33588
- const defaultTokens = placeholderData.tokens;
33521
+ const query = useQuery({
33522
+ queryKey: keys().allTokensBalance(address, chainType, direction),
33523
+ queryFn: async () => {
33524
+ // Return zero balances if no address
33525
+ if (!address) {
33526
+ const defaultTokens = placeholderData.tokens;
33527
+ return {
33528
+ tokens: defaultTokens,
33529
+ totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33530
+ };
33531
+ }
33532
+ let fetchedTokens = [];
33533
+ // Fetch tokens based on chain type
33534
+ switch (chainType) {
33535
+ case ChainType.EVM:
33536
+ fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33537
+ break;
33538
+ case ChainType.COSMOS:
33539
+ const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33540
+ fetchedTokens = await getAllCosmosBalances({
33541
+ addresses,
33542
+ cosmosChains,
33543
+ cosmosTokens,
33544
+ });
33545
+ break;
33546
+ case ChainType.SOLANA:
33547
+ fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33548
+ break;
33549
+ case ChainType.BTC:
33550
+ fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33551
+ break;
33552
+ case ChainType.SUI:
33553
+ fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33554
+ break;
33555
+ case ChainType.XRPL:
33556
+ fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33557
+ break;
33558
+ case ChainType.STELLAR:
33559
+ fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33560
+ break;
33561
+ default:
33562
+ fetchedTokens = placeholderData.tokens;
33563
+ break;
33564
+ }
33589
33565
  return {
33590
- tokens: defaultTokens,
33591
- totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33566
+ tokens: fetchedTokens,
33567
+ totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33592
33568
  };
33593
- }
33594
- let fetchedTokens = [];
33595
- // Fetch tokens based on chain type
33596
- switch (chainType) {
33597
- case ChainType.EVM:
33598
- fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33599
- break;
33600
- case ChainType.COSMOS:
33601
- const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33602
- fetchedTokens = await getAllCosmosBalances({
33603
- addresses,
33604
- cosmosChains,
33605
- cosmosTokens,
33606
- });
33607
- break;
33608
- case ChainType.SOLANA:
33609
- fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33610
- break;
33611
- case ChainType.BTC:
33612
- fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33613
- break;
33614
- case ChainType.SUI:
33615
- fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33616
- break;
33617
- case ChainType.XRPL:
33618
- fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33619
- break;
33620
- case ChainType.STELLAR:
33621
- fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33622
- break;
33623
- default:
33624
- fetchedTokens = placeholderData.tokens;
33625
- break;
33626
- }
33627
- return {
33628
- tokens: fetchedTokens,
33629
- totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33630
- };
33631
- }, {
33569
+ },
33632
33570
  ...queryOptions,
33633
33571
  enabled: isQueryEnabled,
33634
33572
  });
@@ -33643,7 +33581,7 @@ const BALANCE_STALE_TIME = 60000; // 1 minute
33643
33581
  const BALANCE_CACHE_TIME = 300000; // 5 minutes
33644
33582
  const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33645
33583
  staleTime: BALANCE_STALE_TIME,
33646
- cacheTime: BALANCE_CACHE_TIME,
33584
+ gcTime: BALANCE_CACHE_TIME,
33647
33585
  refetchOnWindowFocus: true,
33648
33586
  refetchOnMount: true,
33649
33587
  }, } = {}) => {
@@ -33724,9 +33662,9 @@ const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33724
33662
  }, [balanceQueries]);
33725
33663
  // Aggregate loading states
33726
33664
  const queryStates = useMemo(() => ({
33727
- isInitialLoading: Object.values(balanceQueries).some((q) => q.isInitialLoading),
33728
- isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33729
33665
  isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33666
+ isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33667
+ isPending: Object.values(balanceQueries).some((q) => q.isPending),
33730
33668
  isRefetching: Object.values(balanceQueries).some((q) => q.isRefetching),
33731
33669
  isError: Object.values(balanceQueries).some((q) => q.isError),
33732
33670
  isSuccess: Object.values(balanceQueries).every((q) => q.isSuccess),
@@ -33768,7 +33706,7 @@ function useNativeTokenForChain(chain) {
33768
33706
 
33769
33707
  const useEvmNativeBalance = ({ address, chain, }) => {
33770
33708
  const { isChainTypeConnected } = useWallet();
33771
- const { data: nativeEvmBalance, isLoading } = useBalance({
33709
+ const { data: nativeEvmBalance, isPending } = useBalance({
33772
33710
  address: address,
33773
33711
  chainId: Number(chain?.chainId),
33774
33712
  query: {
@@ -33790,13 +33728,13 @@ const useEvmNativeBalance = ({ address, chain, }) => {
33790
33728
  }, [nativeEvmBalance?.decimals, nativeEvmBalance?.value]);
33791
33729
  return {
33792
33730
  balance,
33793
- isLoading,
33731
+ isPending,
33794
33732
  };
33795
33733
  };
33796
33734
  const useCosmosNativeBalance = ({ address, chain, }) => {
33797
33735
  const { isConnected: isCosmosConnected } = useCosmosContext();
33798
33736
  const { nativeToken: nativeCosmosToken } = useNativeTokenForChain(chain);
33799
- const { balance: rawBalance, isLoading } = useCosmosBalance({
33737
+ const { balance: rawBalance, isPending } = useCosmosBalance({
33800
33738
  chain,
33801
33739
  token: nativeCosmosToken,
33802
33740
  userAddress: address,
@@ -33811,16 +33749,18 @@ const useCosmosNativeBalance = ({ address, chain, }) => {
33811
33749
  };
33812
33750
  }
33813
33751
  }, [nativeCosmosToken?.decimals, rawBalance]);
33814
- return { balance, isLoading };
33752
+ return { balance, isPending };
33815
33753
  };
33816
33754
  const useBitcoinNativeBalance = ({ chain, address, }) => {
33817
33755
  const { nativeToken } = useNativeTokenForChain(chain);
33818
- const { data: rawBalance = "0", isLoading } = useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33819
- if (!address || !nativeToken)
33820
- return "0";
33821
- const balance = await getBitcoinNativeBalance(address);
33822
- return formatBNToReadable(balance, nativeToken.decimals);
33823
- }, {
33756
+ const { data: rawBalance = "0", isPending } = useQuery({
33757
+ queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33758
+ queryFn: async () => {
33759
+ if (!address || !nativeToken)
33760
+ return "0";
33761
+ const balance = await getBitcoinNativeBalance(address);
33762
+ return formatBNToReadable(balance, nativeToken.decimals);
33763
+ },
33824
33764
  enabled: chain?.chainType === ChainType.BTC &&
33825
33765
  nativeToken?.decimals != null &&
33826
33766
  isWalletAddressValid(chain, address),
@@ -33839,15 +33779,17 @@ const useBitcoinNativeBalance = ({ chain, address, }) => {
33839
33779
  }, [nativeToken?.decimals, rawBalance]);
33840
33780
  return {
33841
33781
  balance,
33842
- isLoading,
33782
+ isPending,
33843
33783
  };
33844
33784
  };
33845
33785
  const useSolanaNativeBalance = ({ chain, address, }) => {
33846
33786
  const { nativeToken } = useNativeTokenForChain(chain);
33847
- const { data: rawBalance, isLoading } = useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33848
- const balance = await getSolanaNativeBalance(address);
33849
- return formatBNToReadable(balance, nativeToken.decimals);
33850
- }, {
33787
+ const { data: rawBalance, isPending } = useQuery({
33788
+ queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33789
+ queryFn: async () => {
33790
+ const balance = await getSolanaNativeBalance(address);
33791
+ return formatBNToReadable(balance, nativeToken.decimals);
33792
+ },
33851
33793
  enabled: !!address &&
33852
33794
  nativeToken?.decimals != null &&
33853
33795
  chain?.chainType === ChainType.SOLANA,
@@ -33866,12 +33808,12 @@ const useSolanaNativeBalance = ({ chain, address, }) => {
33866
33808
  }, [nativeToken?.decimals, rawBalance]);
33867
33809
  return {
33868
33810
  balance,
33869
- isLoading,
33811
+ isPending,
33870
33812
  };
33871
33813
  };
33872
33814
  const useSuiNativeBalance = ({ address, chain, }) => {
33873
33815
  const { nativeToken } = useNativeTokenForChain(chain);
33874
- const { balance: rawBalance, isLoading } = useSuiBalance({
33816
+ const { balance: rawBalance, isPending } = useSuiBalance({
33875
33817
  chain,
33876
33818
  token: nativeToken,
33877
33819
  userAddress: address,
@@ -33886,12 +33828,12 @@ const useSuiNativeBalance = ({ address, chain, }) => {
33886
33828
  }, [nativeToken?.decimals, rawBalance]);
33887
33829
  return {
33888
33830
  balance,
33889
- isLoading,
33831
+ isPending,
33890
33832
  };
33891
33833
  };
33892
33834
  const useXrplNativeBalance = ({ address, chain, }) => {
33893
33835
  const { nativeToken } = useNativeTokenForChain(chain);
33894
- const { balance: rawBalance, isLoading } = useXrplBalance({
33836
+ const { balance: rawBalance, isPending } = useXrplBalance({
33895
33837
  chain,
33896
33838
  token: nativeToken,
33897
33839
  userAddress: address,
@@ -33907,12 +33849,12 @@ const useXrplNativeBalance = ({ address, chain, }) => {
33907
33849
  }, [nativeToken?.decimals, rawBalance]);
33908
33850
  return {
33909
33851
  balance,
33910
- isLoading,
33852
+ isPending,
33911
33853
  };
33912
33854
  };
33913
33855
  const useStellarNativeBalance = ({ address, chain, }) => {
33914
33856
  const { nativeToken } = useNativeTokenForChain(chain);
33915
- const { balance: rawBalance, isLoading } = useStellarBalance({
33857
+ const { balance: rawBalance, isPending } = useStellarBalance({
33916
33858
  chain,
33917
33859
  token: nativeToken,
33918
33860
  userAddress: address,
@@ -33928,7 +33870,7 @@ const useStellarNativeBalance = ({ address, chain, }) => {
33928
33870
  }, [nativeToken?.decimals, rawBalance]);
33929
33871
  return {
33930
33872
  balance,
33931
- isLoading,
33873
+ isPending,
33932
33874
  };
33933
33875
  };
33934
33876
  const useNativeBalance = (chain) => {
@@ -33936,28 +33878,28 @@ const useNativeBalance = (chain) => {
33936
33878
  const { data: cosmosAddressForChain } = useCosmosForChain(chain);
33937
33879
  // Cosmos is a special case because the address changes on every chain
33938
33880
  // so we can't use the default cosmos connected address
33939
- const { balance: nativeCosmosBalance, isLoading: isCosmosLoading } = useCosmosNativeBalance({
33881
+ const { balance: nativeCosmosBalance, isPending: isCosmosPending } = useCosmosNativeBalance({
33940
33882
  address: cosmosAddressForChain,
33941
33883
  chain,
33942
33884
  });
33943
- const { balance: nativeEvmBalance, isLoading: isEvmLoading } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33944
- const { balance: nativeBitcoinBalance, isLoading: isBitcoinLoading } = useBitcoinNativeBalance({
33885
+ const { balance: nativeEvmBalance, isPending: isEvmPending } = useEvmNativeBalance({ address: connectedAddresses[ChainType.EVM], chain });
33886
+ const { balance: nativeBitcoinBalance, isPending: isBitcoinPending } = useBitcoinNativeBalance({
33945
33887
  address: connectedAddresses[ChainType.BTC],
33946
33888
  chain,
33947
33889
  });
33948
- const { balance: nativeSolanaBalance, isLoading: isSolanaLoading } = useSolanaNativeBalance({
33890
+ const { balance: nativeSolanaBalance, isPending: isSolanaPending } = useSolanaNativeBalance({
33949
33891
  address: connectedAddresses[ChainType.SOLANA],
33950
33892
  chain,
33951
33893
  });
33952
- const { balance: nativeSuiBalance, isLoading: isSuiLoading } = useSuiNativeBalance({
33894
+ const { balance: nativeSuiBalance, isPending: isSuiPending } = useSuiNativeBalance({
33953
33895
  address: connectedAddresses[ChainType.SUI],
33954
33896
  chain,
33955
33897
  });
33956
- const { balance: nativeXrplBalance, isLoading: isXrpLoading } = useXrplNativeBalance({
33898
+ const { balance: nativeXrplBalance, isPending: isXrplPending } = useXrplNativeBalance({
33957
33899
  address: connectedAddresses[ChainType.XRPL],
33958
33900
  chain,
33959
33901
  });
33960
- const { balance: nativeStellarBalance, isLoading: isStellarLoading } = useStellarNativeBalance({
33902
+ const { balance: nativeStellarBalance, isPending: isStellarPending } = useStellarNativeBalance({
33961
33903
  address: connectedAddresses[ChainType.STELLAR],
33962
33904
  chain,
33963
33905
  });
@@ -34002,36 +33944,36 @@ const useNativeBalance = (chain) => {
34002
33944
  nativeXrplBalance,
34003
33945
  nativeStellarBalance,
34004
33946
  ]);
34005
- const isLoading = useMemo(() => {
33947
+ const isPending = useMemo(() => {
34006
33948
  if (!chain?.chainType)
34007
33949
  return false;
34008
33950
  switch (chain.chainType) {
34009
33951
  case ChainType.EVM:
34010
- return isEvmLoading;
33952
+ return isEvmPending;
34011
33953
  case ChainType.COSMOS:
34012
- return isCosmosLoading;
33954
+ return isCosmosPending;
34013
33955
  case ChainType.BTC:
34014
- return isBitcoinLoading;
33956
+ return isBitcoinPending;
34015
33957
  case ChainType.SOLANA:
34016
- return isSolanaLoading;
33958
+ return isSolanaPending;
34017
33959
  case ChainType.SUI:
34018
- return isSuiLoading;
33960
+ return isSuiPending;
34019
33961
  case ChainType.XRPL:
34020
- return isXrpLoading;
33962
+ return isXrplPending;
34021
33963
  case ChainType.STELLAR:
34022
- return isStellarLoading;
33964
+ return isStellarPending;
34023
33965
  }
34024
33966
  }, [
34025
33967
  chain?.chainType,
34026
- isEvmLoading,
34027
- isCosmosLoading,
34028
- isBitcoinLoading,
34029
- isSolanaLoading,
34030
- isSuiLoading,
34031
- isXrpLoading,
34032
- isStellarLoading,
33968
+ isEvmPending,
33969
+ isCosmosPending,
33970
+ isBitcoinPending,
33971
+ isSolanaPending,
33972
+ isSuiPending,
33973
+ isXrplPending,
33974
+ isStellarPending,
34033
33975
  ]);
34034
- return { nativeBalance, nativeBalanceFormatted, isLoading };
33976
+ return { nativeBalance, nativeBalanceFormatted, isPending };
34035
33977
  };
34036
33978
 
34037
33979
  const DEFAULT_REFRESH_INTERVAL_MS = 15000;
@@ -34040,7 +33982,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34040
33982
  const isNativeToken = token?.address.toLowerCase() === nativeEvmTokenAddress.toLowerCase();
34041
33983
  const userAddressParsed = userAddress;
34042
33984
  // Only fetch using useBalance if it's a native token
34043
- const { data: nativeBalance, isLoading: isNativeTokenLoading } = useBalance({
33985
+ const { data: nativeBalance, isPending: isNativeTokenPending } = useBalance({
34044
33986
  address: userAddressParsed,
34045
33987
  chainId: Number(chain?.chainId),
34046
33988
  query: {
@@ -34056,7 +33998,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34056
33998
  });
34057
33999
  // Only fetch using useReadContract if it's not a native token
34058
34000
  // This is temporary, because of wagmi error: https://github.com/wevm/wagmi/issues/4353
34059
- const { data: erc20Balance, isLoading: isErc20Loading } = useReadContract({
34001
+ const { data: erc20Balance, isPending: isErc20Pending } = useReadContract({
34060
34002
  address: token?.address,
34061
34003
  abi: erc20Abi,
34062
34004
  functionName: "balanceOf",
@@ -34072,15 +34014,15 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34072
34014
  },
34073
34015
  });
34074
34016
  const balance = isNativeToken ? nativeBalance?.value : erc20Balance;
34075
- const isLoading = isNativeToken ? isNativeTokenLoading : isErc20Loading;
34017
+ const isPending = isNativeToken ? isNativeTokenPending : isErc20Pending;
34076
34018
  const formattedBalance = balance != null && token?.decimals != null
34077
34019
  ? formatBNToReadable(balance, token.decimals)
34078
34020
  : "0";
34079
- return { balance: formattedBalance, isLoading };
34021
+ return { balance: formattedBalance, isPending };
34080
34022
  };
34081
34023
  const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34082
34024
  const { isConnected } = useCosmosContext();
34083
- const { data: balance = "0", isLoading } = useQuery({
34025
+ const { data: balance = "0", isPending } = useQuery({
34084
34026
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34085
34027
  queryFn: async () => {
34086
34028
  if (!userAddress || !token || chain?.chainType !== ChainType.COSMOS) {
@@ -34100,10 +34042,10 @@ const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34100
34042
  refetchInterval: refreshIntervalMs,
34101
34043
  retry: 2,
34102
34044
  });
34103
- return { balance, isLoading };
34045
+ return { balance, isPending };
34104
34046
  };
34105
34047
  const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34106
- const { data: balance = "0", isLoading } = useQuery({
34048
+ const { data: balance = "0", isPending } = useQuery({
34107
34049
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34108
34050
  queryFn: async () => {
34109
34051
  if (!userAddress || !token)
@@ -34118,11 +34060,11 @@ const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34118
34060
  refetchInterval: refreshIntervalMs,
34119
34061
  retry: 2,
34120
34062
  });
34121
- return { balance, isLoading };
34063
+ return { balance, isPending };
34122
34064
  };
34123
34065
  // TODO: implement fetching balances for all bitcoin tokens
34124
34066
  const useBitcoinBalance = ({ userAddress, chain, }) => {
34125
- const { balance: balanceBn, isLoading } = useBitcoinNativeBalance({
34067
+ const { balance: balanceBn, isPending } = useBitcoinNativeBalance({
34126
34068
  address: userAddress,
34127
34069
  chain,
34128
34070
  });
@@ -34131,10 +34073,10 @@ const useBitcoinBalance = ({ userAddress, chain, }) => {
34131
34073
  return "0";
34132
34074
  return formatBNToReadable(balanceBn?.value, balanceBn?.decimals);
34133
34075
  }, [balanceBn]);
34134
- return { balance, isLoading };
34076
+ return { balance, isPending };
34135
34077
  };
34136
34078
  const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34137
- const { data: balance = "0", isLoading } = useQuery({
34079
+ const { data: balance = "0", isPending } = useQuery({
34138
34080
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34139
34081
  queryFn: async () => {
34140
34082
  if (!userAddress ||
@@ -34154,10 +34096,10 @@ const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34154
34096
  refetchInterval: refreshIntervalMs,
34155
34097
  retry: 2,
34156
34098
  });
34157
- return { balance, isLoading };
34099
+ return { balance, isPending };
34158
34100
  };
34159
34101
  const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34160
- const { data: balance = "0", isLoading } = useQuery({
34102
+ const { data: balance = "0", isPending } = useQuery({
34161
34103
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34162
34104
  queryFn: async () => {
34163
34105
  if (!userAddress || !token || !chain)
@@ -34174,10 +34116,10 @@ const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs
34174
34116
  refetchInterval: refreshIntervalMs,
34175
34117
  retry: 2,
34176
34118
  });
34177
- return { balance, isLoading };
34119
+ return { balance, isPending };
34178
34120
  };
34179
34121
  const useStellarBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34180
- const { data: balance = "0", isLoading } = useQuery({
34122
+ const { data: balance = "0", isPending } = useQuery({
34181
34123
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34182
34124
  queryFn: async () => {
34183
34125
  if (!userAddress || !token || !chain)
@@ -34194,7 +34136,7 @@ const useStellarBalance = ({ userAddress, chain, enabled, token, refreshInterval
34194
34136
  refetchInterval: refreshIntervalMs,
34195
34137
  retry: 2,
34196
34138
  });
34197
- return { balance, isLoading };
34139
+ return { balance, isPending };
34198
34140
  };
34199
34141
 
34200
34142
  /**
@@ -34315,7 +34257,7 @@ const useMultipleTokenPrices = (tokens) => {
34315
34257
  return {
34316
34258
  tokenPrices,
34317
34259
  getTokenPrice,
34318
- isLoading: coinGeckoQuery.isLoading,
34260
+ isPending: coinGeckoQuery.isPending,
34319
34261
  isError: coinGeckoQuery.isError,
34320
34262
  error: coinGeckoQuery.error,
34321
34263
  refetch: coinGeckoQuery.refetch,
@@ -34464,13 +34406,17 @@ const fetchTokensData = async (tokens) => {
34464
34406
 
34465
34407
  // Coingecko has a limit for some queries for multiple tokens, not sure what it is, but let's use 100 for now
34466
34408
  const useHistoricalData = (coingeckoId, timeFrame) => {
34467
- return useQuery(keys().historicalData(coingeckoId, timeFrame), () => fetchHistoricalData(coingeckoId, timeFrame), {
34409
+ return useQuery({
34410
+ queryKey: keys().historicalData(coingeckoId, timeFrame),
34411
+ queryFn: () => fetchHistoricalData(coingeckoId, timeFrame),
34468
34412
  staleTime: 5 * 60 * 1000,
34469
34413
  enabled: !!coingeckoId,
34470
34414
  });
34471
34415
  };
34472
34416
  const useTokensData = (tokens) => {
34473
- return useQuery(keys().tokensData(tokens), () => fetchTokensData(tokens), {
34417
+ return useQuery({
34418
+ queryKey: keys().tokensData(tokens),
34419
+ queryFn: () => fetchTokensData(tokens),
34474
34420
  staleTime: 60 * 1000,
34475
34421
  enabled: !!tokens && tokens.length > 0,
34476
34422
  });
@@ -34775,7 +34721,7 @@ function useSendTransactionGas({ chain, token, from, }) {
34775
34721
  }
34776
34722
 
34777
34723
  function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34778
- const { data: estimatedGas = BigInt(0), isLoading } = useSendTransactionGas({
34724
+ const { data: estimatedGas = BigInt(0), isPending } = useSendTransactionGas({
34779
34725
  chain,
34780
34726
  token,
34781
34727
  from,
@@ -34820,7 +34766,7 @@ function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34820
34766
  return {
34821
34767
  estimatedGas,
34822
34768
  isBalanceEnough,
34823
- isLoading,
34769
+ isPending,
34824
34770
  isNativeBalanceEnoughToPayGasFees,
34825
34771
  minAmountValueWarnMsg,
34826
34772
  };
@@ -35403,7 +35349,9 @@ function useSendTransaction({ to, amount, token, chain, }) {
35403
35349
  });
35404
35350
  },
35405
35351
  onSuccess: (tx, variables) => {
35406
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balance));
35352
+ queryClient.invalidateQueries({
35353
+ queryKey: getPrefixKey(QueryKeys.Balance),
35354
+ });
35407
35355
  setTransactionState(variables.id, tx);
35408
35356
  persistTransaction({
35409
35357
  txType: HistoryTxType.SEND,
@@ -35730,9 +35678,10 @@ const useAllTransactionsStatus = ({ enabled }) => {
35730
35678
  queryKey: keys().fiatToCryptoStatus(data.orderId),
35731
35679
  retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
35732
35680
  retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
35733
- refetchInterval: (data) => {
35734
- if (data?.status &&
35735
- FINAL_TRANSACTION_STATUSES.includes(data.status)) {
35681
+ refetchInterval: (query) => {
35682
+ const { state } = query;
35683
+ if (state.data?.status &&
35684
+ FINAL_TRANSACTION_STATUSES.includes(state.data.status)) {
35736
35685
  return false;
35737
35686
  }
35738
35687
  return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
@@ -35792,7 +35741,7 @@ const useAllTransactionsStatus = ({ enabled }) => {
35792
35741
  queries: enabled && config.apiUrl ? statusQueries : [],
35793
35742
  });
35794
35743
  return {
35795
- isLoading: queries.some((q) => q.isLoading),
35744
+ isPending: queries.some((q) => q.isPending),
35796
35745
  isError: queries.some((q) => q.isError),
35797
35746
  data: queries.map((q) => q.data).filter(Boolean),
35798
35747
  };
@@ -36051,16 +36000,18 @@ const useApproval = ({ squidRoute, }) => {
36051
36000
  * On Error: Showing the error message if any
36052
36001
  * @returns {boolean} approved
36053
36002
  */
36054
- const routeApproved = useQuery(keys().routeApproved(squidRoute, allowanceInWei), async () => {
36055
- // Approval is only needed for EVM chains
36056
- if (getChainType(squidRoute?.params.fromChain) === ChainType.EVM) {
36057
- return hasAllowance;
36058
- }
36059
- return true;
36060
- }, {
36003
+ const routeApproved = useQuery({
36004
+ queryKey: keys().routeApproved(squidRoute, allowanceInWei),
36005
+ queryFn: async () => {
36006
+ // Approval is only needed for EVM chains
36007
+ if (getChainType(squidRoute?.params.fromChain) === ChainType.EVM) {
36008
+ return hasAllowance;
36009
+ }
36010
+ return true;
36011
+ },
36061
36012
  enabled: !!squidRoute &&
36062
36013
  !!sourceUserAddress &&
36063
- !allowanceQuery?.isLoading &&
36014
+ !allowanceQuery?.isPending &&
36064
36015
  allowanceQuery?.isFetched,
36065
36016
  });
36066
36017
  // USDT has a very specific way of handling approvals
@@ -36149,81 +36100,84 @@ const useApproval = ({ squidRoute, }) => {
36149
36100
  /**
36150
36101
  * Manually approve route if necessary
36151
36102
  */
36152
- const approveRoute = useMutation(async () => {
36153
- try {
36154
- if (fromToken?.address === nativeEvmTokenAddress) {
36155
- return true;
36156
- }
36157
- if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36158
- await approveSpecificTokenToZero(fromToken);
36159
- try {
36160
- // If needed, we can switch the chain here
36161
- // If already on the correct chain, this will do nothing
36162
- await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36163
- }
36164
- catch (error) {
36165
- console.error("Error switching network:", error);
36103
+ const approveRoute = useMutation({
36104
+ mutationFn: async () => {
36105
+ try {
36106
+ if (fromToken?.address === nativeEvmTokenAddress) {
36107
+ return true;
36166
36108
  }
36167
- let approveTx;
36168
- if (useIcs20) {
36169
- const channel = squidRoute.estimate.actions[0].data
36170
- .ibcChannel;
36171
- const ics20Interface = new ethers.Interface(ics20Abi);
36172
- const approveData = ics20Interface.encodeFunctionData("approve", [
36173
- squidRoute.params.fromAddress,
36174
- [
36175
- {
36176
- sourcePort: "transfer",
36177
- sourceChannel: channel,
36178
- spendLimit: [
36179
- {
36180
- denom: squidRoute.estimate.actions[0].fromToken
36181
- .originalAddress,
36182
- amount: squidRoute.params.fromAmount,
36183
- },
36184
- ],
36185
- allowList: [],
36186
- allowedPacketData: ["*"],
36109
+ if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36110
+ await approveSpecificTokenToZero(fromToken);
36111
+ try {
36112
+ // If needed, we can switch the chain here
36113
+ // If already on the correct chain, this will do nothing
36114
+ await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36115
+ }
36116
+ catch (error) {
36117
+ console.error("Error switching network:", error);
36118
+ }
36119
+ let approveTx;
36120
+ if (useIcs20) {
36121
+ const channel = squidRoute.estimate.actions[0].data
36122
+ .ibcChannel;
36123
+ const ics20Interface = new ethers.Interface(ics20Abi);
36124
+ const approveData = ics20Interface.encodeFunctionData("approve", [
36125
+ squidRoute.params.fromAddress,
36126
+ [
36127
+ {
36128
+ sourcePort: "transfer",
36129
+ sourceChannel: channel,
36130
+ spendLimit: [
36131
+ {
36132
+ denom: squidRoute.estimate.actions[0].fromToken
36133
+ .originalAddress,
36134
+ amount: squidRoute.params.fromAmount,
36135
+ },
36136
+ ],
36137
+ allowList: [],
36138
+ allowedPacketData: ["*"],
36139
+ },
36140
+ ],
36141
+ ]);
36142
+ approveTx = await evmSigner.sendTransaction({
36143
+ to: squidRoute.transactionRequest.target,
36144
+ data: approveData,
36145
+ value: "0",
36146
+ gasLimit: squidRoute.transactionRequest
36147
+ .gasLimit,
36148
+ gasPrice: squidRoute.transactionRequest
36149
+ .gasPrice,
36150
+ });
36151
+ }
36152
+ else {
36153
+ approveTx = await squid.approveRoute({
36154
+ route: squidRoute,
36155
+ signer: evmSigner,
36156
+ // For security reasons, we don't want to allow infinite approvals in our frontends
36157
+ executionSettings: {
36158
+ infiniteApproval: false,
36187
36159
  },
36188
- ],
36189
- ]);
36190
- approveTx = await evmSigner.sendTransaction({
36191
- to: squidRoute.transactionRequest.target,
36192
- data: approveData,
36193
- value: "0",
36194
- gasLimit: squidRoute.transactionRequest
36195
- .gasLimit,
36196
- gasPrice: squidRoute.transactionRequest
36197
- .gasPrice,
36198
- });
36199
- }
36200
- else {
36201
- approveTx = await squid.approveRoute({
36202
- route: squidRoute,
36203
- signer: evmSigner,
36204
- // For security reasons, we don't want to allow infinite approvals in our frontends
36205
- executionSettings: {
36206
- infiniteApproval: false,
36207
- },
36208
- });
36209
- }
36210
- if (isProblematicConnector(activeConnector)) {
36211
- await sleep(3_000);
36160
+ });
36161
+ }
36162
+ if (isProblematicConnector(activeConnector)) {
36163
+ await sleep(3_000);
36164
+ }
36165
+ await approveTx?.wait();
36166
+ return true;
36212
36167
  }
36213
- await approveTx?.wait();
36214
- return true;
36168
+ return false;
36215
36169
  }
36216
- return false;
36217
- }
36218
- catch (error) {
36219
- // Keep the error in the console to debug future issues
36220
- console.error(error);
36221
- return false;
36222
- }
36223
- }, {
36170
+ catch (error) {
36171
+ // Keep the error in the console to debug future issues
36172
+ console.error(error);
36173
+ return false;
36174
+ }
36175
+ },
36224
36176
  onSuccess: async () => {
36225
36177
  await allowanceQuery?.refetch();
36226
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.RouteApproved));
36178
+ queryClient.invalidateQueries({
36179
+ queryKey: getPrefixKey(QueryKeys.RouteApproved),
36180
+ });
36227
36181
  // After an approval, we refetch the transaction query with all required parameters
36228
36182
  // This is to ensure we're using the latest expiry timestamp
36229
36183
  if (squidRoute) {
@@ -39343,8 +39297,10 @@ const useExecuteTransaction = (squidRoute) => {
39343
39297
  }
39344
39298
  }, [cosmosSigner, fromChain]);
39345
39299
  const resetQueriesAfterTxSigned = () => {
39346
- queryClient.refetchQueries(getPrefixKey(QueryKeys.Balance));
39347
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Transaction));
39300
+ queryClient.refetchQueries({ queryKey: getPrefixKey(QueryKeys.Balance) });
39301
+ queryClient.invalidateQueries({
39302
+ queryKey: getPrefixKey(QueryKeys.Transaction),
39303
+ });
39348
39304
  };
39349
39305
  const dispatchSignatureRequestEvent = useCallback((route) => {
39350
39306
  WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
@@ -39362,62 +39318,64 @@ const useExecuteTransaction = (squidRoute) => {
39362
39318
  txHash,
39363
39319
  }, findToken);
39364
39320
  }, [findToken]);
39365
- const swapMutationCosmos = useMutation(async ({ id, route }) => {
39366
- const fromChainId = route?.params.fromChain;
39367
- if (cosmosSigner && fromChainId) {
39368
- try {
39369
- const signingClient = await getCosmosSignerClient();
39370
- const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39371
- if (signerAddress && signingClient && route) {
39372
- dispatchSignatureRequestEvent(route);
39373
- const tx$1 = (await squid?.executeRoute({
39374
- signer: signingClient,
39375
- signerAddress,
39376
- route,
39377
- }));
39378
- // set the tx state to loading, as soon as user signed the tx
39379
- setTransactionState({
39380
- txHash: "",
39381
- route,
39382
- status: TransactionStatus.ONGOING,
39383
- sourceStatus: TransactionStatus.ONGOING,
39384
- id,
39385
- });
39386
- // broadcast the signed tx to get hash and listen to events
39387
- const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39388
- const hash = response.transactionHash;
39389
- if (hash) {
39390
- resetQueriesAfterTxSigned();
39391
- }
39392
- // Dispatch event so it can be listened from outside the widget
39393
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39394
- const txParams = setTransactionState({
39395
- route,
39396
- txHash: hash,
39397
- userAddress: sourceUserAddress,
39398
- status: TransactionStatus.ONGOING,
39399
- sourceStatus: TransactionStatus.ONGOING,
39400
- axelarUrl: undefined,
39401
- id,
39402
- });
39403
- if (txParams) {
39404
- addSwapTransaction({
39405
- ...txParams,
39406
- params: route.params,
39407
- estimate: route.estimate,
39321
+ const swapMutationCosmos = useMutation({
39322
+ mutationFn: async ({ id, route }) => {
39323
+ const fromChainId = route?.params.fromChain;
39324
+ if (cosmosSigner && fromChainId) {
39325
+ try {
39326
+ const signingClient = await getCosmosSignerClient();
39327
+ const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39328
+ if (signerAddress && signingClient && route) {
39329
+ dispatchSignatureRequestEvent(route);
39330
+ const tx$1 = (await squid?.executeRoute({
39331
+ signer: signingClient,
39332
+ signerAddress,
39333
+ route,
39334
+ }));
39335
+ // set the tx state to loading, as soon as user signed the tx
39336
+ setTransactionState({
39337
+ txHash: "",
39338
+ route,
39339
+ status: TransactionStatus.ONGOING,
39340
+ sourceStatus: TransactionStatus.ONGOING,
39341
+ id,
39408
39342
  });
39343
+ // broadcast the signed tx to get hash and listen to events
39344
+ const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39345
+ const hash = response.transactionHash;
39346
+ if (hash) {
39347
+ resetQueriesAfterTxSigned();
39348
+ }
39349
+ // Dispatch event so it can be listened from outside the widget
39350
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39351
+ const txParams = setTransactionState({
39352
+ route,
39353
+ txHash: hash,
39354
+ userAddress: sourceUserAddress,
39355
+ status: TransactionStatus.ONGOING,
39356
+ sourceStatus: TransactionStatus.ONGOING,
39357
+ axelarUrl: undefined,
39358
+ id,
39359
+ });
39360
+ if (txParams) {
39361
+ addSwapTransaction({
39362
+ ...txParams,
39363
+ params: route.params,
39364
+ estimate: route.estimate,
39365
+ });
39366
+ }
39367
+ return response.code === 0;
39409
39368
  }
39410
- return response.code === 0;
39411
39369
  }
39412
- }
39413
- catch (error) {
39414
- console.error("Error executing Cosmos transaction", error);
39415
- if (isUserRejectionError(normalizeError(error))) {
39416
- throw new Error("Request rejected");
39370
+ catch (error) {
39371
+ console.error("Error executing Cosmos transaction", error);
39372
+ if (isUserRejectionError(normalizeError(error))) {
39373
+ throw new Error("Request rejected");
39374
+ }
39417
39375
  }
39418
39376
  }
39419
- }
39420
- throw new Error("Need all parameters");
39377
+ throw new Error("Need all parameters");
39378
+ },
39421
39379
  });
39422
39380
  // If the transaction is replaced, we need to update the transaction hash
39423
39381
  // Transaction replaced can mean that the user has speed up the transaction for example
@@ -39470,97 +39428,126 @@ const useExecuteTransaction = (squidRoute) => {
39470
39428
  throw error;
39471
39429
  }
39472
39430
  }, [replaceSwapTransactionNonce, setTransactionState, sourceUserAddress]);
39473
- const swapMutationEvm = useMutation(async ({ id, route }) => {
39474
- await changeNetworkIfNeeded.mutateAsync();
39475
- if (!route || !squid || !evmSigner) {
39476
- throw new Error("Need all parameters");
39477
- }
39478
- dispatchSignatureRequestEvent(route);
39479
- const txResponse = (await squid.executeRoute({
39480
- bypassBalanceChecks: true,
39481
- signer: evmSigner,
39482
- route,
39483
- }));
39484
- let hash = txResponse.hash;
39485
- if (activeConnector?.id === "safe") {
39486
- hash = await getGnosisTransactionHash(txResponse.hash);
39487
- }
39488
- if (hash) {
39489
- resetQueriesAfterTxSigned();
39490
- }
39491
- // Dispatch event so it can be listened from outside the widget
39492
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39493
- if (route.transactionRequest) {
39494
- const txParams = setTransactionState({
39431
+ const swapMutationEvm = useMutation({
39432
+ mutationFn: async ({ id, route }) => {
39433
+ await changeNetworkIfNeeded.mutateAsync();
39434
+ if (!route || !squid || !evmSigner) {
39435
+ throw new Error("Need all parameters");
39436
+ }
39437
+ dispatchSignatureRequestEvent(route);
39438
+ const txResponse = (await squid.executeRoute({
39439
+ bypassBalanceChecks: true,
39440
+ signer: evmSigner,
39495
39441
  route,
39496
- txHash: hash,
39497
- nonce: txResponse.nonce,
39498
- userAddress: sourceUserAddress,
39499
- status: TransactionStatus.INITIAL_LOADING,
39500
- sourceStatus: TransactionStatus.ONGOING,
39501
- axelarUrl: undefined,
39502
- id,
39503
- });
39504
- if (txParams) {
39505
- addSwapTransaction({
39506
- ...txParams,
39507
- params: route.params,
39508
- estimate: route.estimate,
39509
- });
39442
+ }));
39443
+ let hash = txResponse.hash;
39444
+ if (activeConnector?.id === "safe") {
39445
+ hash = await getGnosisTransactionHash(txResponse.hash);
39510
39446
  }
39511
- }
39512
- try {
39513
- if (isProblematicConnector(activeConnector)) {
39514
- await sleep(3_000);
39447
+ if (hash) {
39448
+ resetQueriesAfterTxSigned();
39515
39449
  }
39516
- const response = await txResponse.wait();
39517
- return response;
39518
- }
39519
- catch (error) {
39520
- return handleTransactionReplacementError({
39521
- error,
39522
- route,
39523
- status: TransactionStatus.INITIAL_LOADING,
39524
- sourceStatus: TransactionStatus.ONGOING,
39525
- userAddress: sourceUserAddress,
39526
- axelarUrl: undefined,
39527
- id,
39528
- });
39529
- }
39530
- });
39531
- const swapMutationSolana = useMutation(async ({ id, route }) => {
39532
- try {
39533
- if (!route) {
39534
- throw new Error("Route is required");
39450
+ // Dispatch event so it can be listened from outside the widget
39451
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39452
+ if (route.transactionRequest) {
39453
+ const txParams = setTransactionState({
39454
+ route,
39455
+ txHash: hash,
39456
+ nonce: txResponse.nonce,
39457
+ userAddress: sourceUserAddress,
39458
+ status: TransactionStatus.INITIAL_LOADING,
39459
+ sourceStatus: TransactionStatus.ONGOING,
39460
+ axelarUrl: undefined,
39461
+ id,
39462
+ });
39463
+ if (txParams) {
39464
+ addSwapTransaction({
39465
+ ...txParams,
39466
+ params: route.params,
39467
+ estimate: route.estimate,
39468
+ });
39469
+ }
39535
39470
  }
39536
- if (!solanaSigner) {
39537
- throw new Error("Solana signer is required");
39471
+ try {
39472
+ if (isProblematicConnector(activeConnector)) {
39473
+ await sleep(3_000);
39474
+ }
39475
+ const response = await txResponse.wait();
39476
+ return response;
39538
39477
  }
39539
- if (!route.params.fromAddress || !route.params.toAddress) {
39540
- throw new Error("From or to address is required");
39478
+ catch (error) {
39479
+ return handleTransactionReplacementError({
39480
+ error,
39481
+ route,
39482
+ status: TransactionStatus.INITIAL_LOADING,
39483
+ sourceStatus: TransactionStatus.ONGOING,
39484
+ userAddress: sourceUserAddress,
39485
+ axelarUrl: undefined,
39486
+ id,
39487
+ });
39541
39488
  }
39542
- const isDirectTransfer = isDepositRoute(route);
39543
- // Means it's a transfer to a deposit address
39544
- // Instead of a Swap/Contract call using a DEX like Jupiter
39545
- if (isDirectTransfer) {
39546
- // Get the deposit address from the squidRoute
39547
- const depositData = useDepositAddressStore.getState().deposit;
39548
- // Validate params
39549
- if (!depositData?.depositAddress) {
39550
- throw new Error("Deposit address is required");
39489
+ },
39490
+ });
39491
+ const swapMutationSolana = useMutation({
39492
+ mutationFn: async ({ id, route }) => {
39493
+ try {
39494
+ if (!route) {
39495
+ throw new Error("Route is required");
39496
+ }
39497
+ if (!solanaSigner) {
39498
+ throw new Error("Solana signer is required");
39499
+ }
39500
+ if (!route.params.fromAddress || !route.params.toAddress) {
39501
+ throw new Error("From or to address is required");
39502
+ }
39503
+ const isDirectTransfer = isDepositRoute(route);
39504
+ // Means it's a transfer to a deposit address
39505
+ // Instead of a Swap/Contract call using a DEX like Jupiter
39506
+ if (isDirectTransfer) {
39507
+ // Get the deposit address from the squidRoute
39508
+ const depositData = useDepositAddressStore.getState().deposit;
39509
+ // Validate params
39510
+ if (!depositData?.depositAddress) {
39511
+ throw new Error("Deposit address is required");
39512
+ }
39513
+ const signature = await executeSolanaTransfer({
39514
+ amount: BigInt(route.params.fromAmount),
39515
+ target: depositData.depositAddress,
39516
+ signer: solanaSigner,
39517
+ connection: solanaConnection,
39518
+ sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39519
+ onSigned: (txHash) => {
39520
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39521
+ const txParams = setTransactionState({
39522
+ route,
39523
+ txHash,
39524
+ transactionIdForStatus: depositData.chainflipStatusTrackingId,
39525
+ userAddress: sourceUserAddress,
39526
+ status: TransactionStatus.INITIAL_LOADING,
39527
+ sourceStatus: TransactionStatus.ONGOING,
39528
+ id,
39529
+ });
39530
+ if (txParams) {
39531
+ addSwapTransaction({
39532
+ ...txParams,
39533
+ params: route.params,
39534
+ estimate: route.estimate,
39535
+ });
39536
+ }
39537
+ },
39538
+ });
39539
+ return signature;
39551
39540
  }
39552
- const signature = await executeSolanaTransfer({
39553
- amount: BigInt(route.params.fromAmount),
39554
- target: depositData.depositAddress,
39541
+ const signature = await executeSolanaSwap({
39542
+ route,
39555
39543
  signer: solanaSigner,
39556
39544
  connection: solanaConnection,
39557
- sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39558
39545
  onSigned: (txHash) => {
39559
39546
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39560
39547
  const txParams = setTransactionState({
39561
39548
  route,
39562
39549
  txHash,
39563
- transactionIdForStatus: depositData.chainflipStatusTrackingId,
39550
+ transactionIdForStatus: undefined,
39564
39551
  userAddress: sourceUserAddress,
39565
39552
  status: TransactionStatus.INITIAL_LOADING,
39566
39553
  sourceStatus: TransactionStatus.ONGOING,
@@ -39577,39 +39564,13 @@ const useExecuteTransaction = (squidRoute) => {
39577
39564
  });
39578
39565
  return signature;
39579
39566
  }
39580
- const signature = await executeSolanaSwap({
39581
- route,
39582
- signer: solanaSigner,
39583
- connection: solanaConnection,
39584
- onSigned: (txHash) => {
39585
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39586
- const txParams = setTransactionState({
39587
- route,
39588
- txHash,
39589
- transactionIdForStatus: undefined,
39590
- userAddress: sourceUserAddress,
39591
- status: TransactionStatus.INITIAL_LOADING,
39592
- sourceStatus: TransactionStatus.ONGOING,
39593
- id,
39594
- });
39595
- if (txParams) {
39596
- addSwapTransaction({
39597
- ...txParams,
39598
- params: route.params,
39599
- estimate: route.estimate,
39600
- });
39601
- }
39602
- },
39603
- });
39604
- return signature;
39605
- }
39606
- catch (error) {
39607
- console.error("Solana transaction failed:", error);
39608
- throw error instanceof Error
39609
- ? error
39610
- : new Error("Failed to execute Solana transaction");
39611
- }
39612
- }, {
39567
+ catch (error) {
39568
+ console.error("Solana transaction failed:", error);
39569
+ throw error instanceof Error
39570
+ ? error
39571
+ : new Error("Failed to execute Solana transaction");
39572
+ }
39573
+ },
39613
39574
  onError: (error, variables) => {
39614
39575
  const currentTx = getTransaction(variables.id);
39615
39576
  const errorObject = getTransactionError(error);
@@ -39630,7 +39591,9 @@ const useExecuteTransaction = (squidRoute) => {
39630
39591
  },
39631
39592
  onSuccess: (_data, variables) => {
39632
39593
  const currentTx = getTransaction(variables.id);
39633
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39594
+ queryClient.invalidateQueries({
39595
+ queryKey: getPrefixKey(QueryKeys.Balances),
39596
+ });
39634
39597
  if (isSameChain && currentTx?.transactionId) {
39635
39598
  replaceSwapTransactionStatus({
39636
39599
  transactionId: currentTx.transactionId,
@@ -39647,197 +39610,207 @@ const useExecuteTransaction = (squidRoute) => {
39647
39610
  });
39648
39611
  },
39649
39612
  });
39650
- const swapMutationBitcoin = useMutation(async ({ id, route }) => {
39651
- const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39652
- if (!depositAddress) {
39653
- throw new Error(`Invalid deposit address: ${depositAddress}`);
39654
- }
39655
- if (!sendAmount) {
39656
- throw new Error(`Invalid send amount: ${sendAmount}`);
39657
- }
39658
- const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39659
- await changeNetworkIfNeeded.mutateAsync();
39660
- if (allParamsValid) {
39661
- dispatchSignatureRequestEvent(route);
39662
- const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39613
+ const swapMutationBitcoin = useMutation({
39614
+ mutationFn: async ({ id, route }) => {
39615
+ const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39616
+ if (!depositAddress) {
39617
+ throw new Error(`Invalid deposit address: ${depositAddress}`);
39618
+ }
39619
+ if (!sendAmount) {
39620
+ throw new Error(`Invalid send amount: ${sendAmount}`);
39621
+ }
39622
+ const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39623
+ await changeNetworkIfNeeded.mutateAsync();
39624
+ if (allParamsValid) {
39625
+ dispatchSignatureRequestEvent(route);
39626
+ const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39627
+ if (txHash) {
39628
+ resetQueriesAfterTxSigned();
39629
+ }
39630
+ // Dispatch event so it can be listened from outside the widget
39631
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39632
+ if (route.transactionRequest) {
39633
+ const txParams = setTransactionState({
39634
+ route,
39635
+ txHash,
39636
+ // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39637
+ // instead of the Bitcoin transaction hash
39638
+ transactionIdForStatus: chainflipStatusTrackingId,
39639
+ userAddress: sourceUserAddress,
39640
+ status: TransactionStatus.INITIAL_LOADING,
39641
+ sourceStatus: TransactionStatus.ONGOING,
39642
+ axelarUrl: undefined,
39643
+ id,
39644
+ });
39645
+ if (txParams) {
39646
+ addSwapTransaction({
39647
+ ...txParams,
39648
+ params: route.params,
39649
+ estimate: route.estimate,
39650
+ });
39651
+ }
39652
+ }
39653
+ }
39654
+ else {
39655
+ throw new Error("Need all parameters");
39656
+ }
39657
+ },
39658
+ });
39659
+ const swapMutationXrpl = useMutation({
39660
+ mutationFn: async ({ id, route }) => {
39661
+ if (!route?.transactionRequest || !xrplSigner) {
39662
+ throw new Error("Need all parameters");
39663
+ }
39664
+ if (route.transactionRequest.type !== SquidDataType.OnChainExecution) {
39665
+ throw new Error("Invalid route type");
39666
+ }
39667
+ const { data } = route.transactionRequest;
39668
+ const paymentTx = parseXrplPaymentTx(data);
39669
+ if (!paymentTx)
39670
+ throw new Error("Could not parse transaction");
39671
+ const fromChainId = route.params.fromChain;
39672
+ const xrplNetwork = getXrplNetwork(fromChainId);
39673
+ if (xrplNetwork == null) {
39674
+ throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39675
+ }
39676
+ const txRes = await xrplSigner.signAndSubmit({
39677
+ tx: paymentTx,
39678
+ network: xrplNetwork,
39679
+ });
39680
+ const txParams = setTransactionState({
39681
+ txHash: txRes.hash,
39682
+ id,
39683
+ sourceStatus: TransactionStatus.ONGOING,
39684
+ status: TransactionStatus.ONGOING,
39685
+ route: route,
39686
+ userAddress: sourceUserAddress,
39687
+ });
39688
+ if (txParams && route) {
39689
+ addSwapTransaction({
39690
+ ...txParams,
39691
+ params: route.params,
39692
+ estimate: route.estimate,
39693
+ });
39694
+ }
39695
+ if (txRes.status !== XrplTxStatus.SUCCESS) {
39696
+ throw new Error(`Transaction failed with status: ${txRes.status}`);
39697
+ }
39698
+ },
39699
+ });
39700
+ const swapMutationSui = useMutation({
39701
+ mutationFn: async ({ id, route }) => {
39702
+ if (!route || !suiSigner || !fromChain) {
39703
+ throw new Error("Need all parameters");
39704
+ }
39705
+ if (route.transactionRequest?.type !== SquidDataType.OnChainExecution) {
39706
+ throw new Error("Invalid route type");
39707
+ }
39708
+ const suiWalletState = connectedWalletsByChainType[ChainType.SUI];
39709
+ if (!suiWalletState.account) {
39710
+ throw new Error("Sui wallet is missing account data");
39711
+ }
39712
+ const fromChainId = route.params.fromChain;
39713
+ const suiChain = getSuiChain(fromChainId);
39714
+ if (!suiChain) {
39715
+ throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39716
+ }
39717
+ const suiClient = await getClient(fromChain);
39718
+ const txJson = route.transactionRequest.data;
39719
+ const tx = Transaction$2.from(txJson);
39720
+ const signedTx = await suiSigner.signTransaction({
39721
+ transaction: tx,
39722
+ account: suiWalletState.account,
39723
+ chain: suiChain,
39724
+ });
39725
+ // execute transaction without waiting for confirmation
39726
+ const txResponse = await suiClient.executeTransactionBlock({
39727
+ signature: signedTx.signature,
39728
+ transactionBlock: signedTx.bytes,
39729
+ });
39730
+ const txHash = txResponse.digest;
39663
39731
  if (txHash) {
39664
39732
  resetQueriesAfterTxSigned();
39665
39733
  }
39666
- // Dispatch event so it can be listened from outside the widget
39667
39734
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39668
- if (route.transactionRequest) {
39669
- const txParams = setTransactionState({
39670
- route,
39671
- txHash,
39672
- // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39673
- // instead of the Bitcoin transaction hash
39674
- transactionIdForStatus: chainflipStatusTrackingId,
39675
- userAddress: sourceUserAddress,
39676
- status: TransactionStatus.INITIAL_LOADING,
39677
- sourceStatus: TransactionStatus.ONGOING,
39678
- axelarUrl: undefined,
39679
- id,
39735
+ const txParams = setTransactionState({
39736
+ route,
39737
+ txHash,
39738
+ userAddress: sourceUserAddress,
39739
+ status: TransactionStatus.INITIAL_LOADING,
39740
+ sourceStatus: TransactionStatus.ONGOING,
39741
+ id,
39742
+ });
39743
+ if (txParams) {
39744
+ addSwapTransaction({
39745
+ ...txParams,
39746
+ params: route.params,
39747
+ estimate: route.estimate,
39680
39748
  });
39681
- if (txParams) {
39682
- addSwapTransaction({
39683
- ...txParams,
39684
- params: route.params,
39685
- estimate: route.estimate,
39686
- });
39687
- }
39688
39749
  }
39689
- }
39690
- else {
39691
- throw new Error("Need all parameters");
39692
- }
39693
- });
39694
- const swapMutationXrpl = useMutation(async ({ id, route }) => {
39695
- if (!route?.transactionRequest || !xrplSigner) {
39696
- throw new Error("Need all parameters");
39697
- }
39698
- if (route.transactionRequest.type !== SquidDataType.OnChainExecution) {
39699
- throw new Error("Invalid route type");
39700
- }
39701
- const { data } = route.transactionRequest;
39702
- const paymentTx = parseXrplPaymentTx(data);
39703
- if (!paymentTx)
39704
- throw new Error("Could not parse transaction");
39705
- const fromChainId = route.params.fromChain;
39706
- const xrplNetwork = getXrplNetwork(fromChainId);
39707
- if (xrplNetwork == null) {
39708
- throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39709
- }
39710
- const txRes = await xrplSigner.signAndSubmit({
39711
- tx: paymentTx,
39712
- network: xrplNetwork,
39713
- });
39714
- const txParams = setTransactionState({
39715
- txHash: txRes.hash,
39716
- id,
39717
- sourceStatus: TransactionStatus.ONGOING,
39718
- status: TransactionStatus.ONGOING,
39719
- route: route,
39720
- userAddress: sourceUserAddress,
39721
- });
39722
- if (txParams && route) {
39723
- addSwapTransaction({
39724
- ...txParams,
39725
- params: route.params,
39726
- estimate: route.estimate,
39750
+ // wait for transaction confirmation
39751
+ await suiClient.waitForTransaction({
39752
+ digest: txHash,
39727
39753
  });
39728
- }
39729
- if (txRes.status !== XrplTxStatus.SUCCESS) {
39730
- throw new Error(`Transaction failed with status: ${txRes.status}`);
39731
- }
39732
- }, {});
39733
- const swapMutationSui = useMutation(async ({ id, route }) => {
39734
- if (!route || !suiSigner || !fromChain) {
39735
- throw new Error("Need all parameters");
39736
- }
39737
- if (route.transactionRequest?.type !== SquidDataType.OnChainExecution) {
39738
- throw new Error("Invalid route type");
39739
- }
39740
- const suiWalletState = connectedWalletsByChainType[ChainType.SUI];
39741
- if (!suiWalletState.account) {
39742
- throw new Error("Sui wallet is missing account data");
39743
- }
39744
- const fromChainId = route.params.fromChain;
39745
- const suiChain = getSuiChain(fromChainId);
39746
- if (!suiChain) {
39747
- throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39748
- }
39749
- const suiClient = await getClient(fromChain);
39750
- const txJson = route.transactionRequest.data;
39751
- const tx = Transaction$2.from(txJson);
39752
- const signedTx = await suiSigner.signTransaction({
39753
- transaction: tx,
39754
- account: suiWalletState.account,
39755
- chain: suiChain,
39756
- });
39757
- // execute transaction without waiting for confirmation
39758
- const txResponse = await suiClient.executeTransactionBlock({
39759
- signature: signedTx.signature,
39760
- transactionBlock: signedTx.bytes,
39761
- });
39762
- const txHash = txResponse.digest;
39763
- if (txHash) {
39764
- resetQueriesAfterTxSigned();
39765
- }
39766
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39767
- const txParams = setTransactionState({
39768
- route,
39769
- txHash,
39770
- userAddress: sourceUserAddress,
39771
- status: TransactionStatus.INITIAL_LOADING,
39772
- sourceStatus: TransactionStatus.ONGOING,
39773
- id,
39774
- });
39775
- if (txParams) {
39776
- addSwapTransaction({
39777
- ...txParams,
39778
- params: route.params,
39779
- estimate: route.estimate,
39754
+ },
39755
+ });
39756
+ const swapMutationStellar = useMutation({
39757
+ mutationFn: async ({ id, route }) => {
39758
+ if (!stellarSigner || !route || !squid || !fromChain) {
39759
+ throw new Error("Need all parameters");
39760
+ }
39761
+ const fromChainId = route.params.fromChain;
39762
+ const stellarNetwork = getStellarNetwork(fromChainId);
39763
+ if (stellarNetwork == null) {
39764
+ throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39765
+ }
39766
+ const { data: xdrHex, gasPrice } = route.transactionRequest;
39767
+ const { address } = await stellarSigner.getAddress();
39768
+ const client = await getClient(fromChain);
39769
+ const account = await client.getAccount(address);
39770
+ const operation = xdr.Operation.fromXDR(xdrHex, "hex");
39771
+ const builtTransaction = new TransactionBuilder(account, {
39772
+ fee: gasPrice || (BigInt(BASE_FEE) * BigInt(2)).toString(),
39773
+ networkPassphrase: stellarNetwork,
39774
+ })
39775
+ .addOperation(operation)
39776
+ .setTimeout(300)
39777
+ .build();
39778
+ const preparedTransaction = await client.prepareTransaction(builtTransaction);
39779
+ const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39780
+ networkPassphrase: stellarNetwork,
39780
39781
  });
39781
- }
39782
- // wait for transaction confirmation
39783
- await suiClient.waitForTransaction({
39784
- digest: txHash,
39785
- });
39786
- }, {});
39787
- const swapMutationStellar = useMutation(async ({ id, route }) => {
39788
- if (!stellarSigner || !route || !squid || !fromChain) {
39789
- throw new Error("Need all parameters");
39790
- }
39791
- const fromChainId = route.params.fromChain;
39792
- const stellarNetwork = getStellarNetwork(fromChainId);
39793
- if (stellarNetwork == null) {
39794
- throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39795
- }
39796
- const { data: xdrHex, gasPrice } = route.transactionRequest;
39797
- const { address } = await stellarSigner.getAddress();
39798
- const client = await getClient(fromChain);
39799
- const account = await client.getAccount(address);
39800
- const operation = xdr.Operation.fromXDR(xdrHex, "hex");
39801
- const builtTransaction = new TransactionBuilder(account, {
39802
- fee: gasPrice || (BigInt(BASE_FEE) * BigInt(2)).toString(),
39803
- networkPassphrase: stellarNetwork,
39804
- })
39805
- .addOperation(operation)
39806
- .setTimeout(300)
39807
- .build();
39808
- const preparedTransaction = await client.prepareTransaction(builtTransaction);
39809
- const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39810
- networkPassphrase: stellarNetwork,
39811
- });
39812
- const signedTransaction = new Transaction$1(signedTxXdr, stellarNetwork);
39813
- // get hash before submitting
39814
- const hash = signedTransaction.hash().toString("hex");
39815
- if (hash) {
39816
- resetQueriesAfterTxSigned();
39817
- }
39818
- // Dispatch event so it can be listened from outside the widget
39819
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39820
- const txParams = setTransactionState({
39821
- route,
39822
- txHash: hash,
39823
- userAddress: sourceUserAddress,
39824
- status: TransactionStatus.INITIAL_LOADING,
39825
- sourceStatus: TransactionStatus.ONGOING,
39826
- id,
39827
- });
39828
- if (txParams) {
39829
- addSwapTransaction({
39830
- ...txParams,
39831
- params: route.params,
39832
- estimate: route.estimate,
39782
+ const signedTransaction = new Transaction$1(signedTxXdr, stellarNetwork);
39783
+ // get hash before submitting
39784
+ const hash = signedTransaction.hash().toString("hex");
39785
+ if (hash) {
39786
+ resetQueriesAfterTxSigned();
39787
+ }
39788
+ // Dispatch event so it can be listened from outside the widget
39789
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39790
+ const txParams = setTransactionState({
39791
+ route,
39792
+ txHash: hash,
39793
+ userAddress: sourceUserAddress,
39794
+ status: TransactionStatus.INITIAL_LOADING,
39795
+ sourceStatus: TransactionStatus.ONGOING,
39796
+ id,
39833
39797
  });
39834
- }
39835
- const sentTransaction = await client.sendTransaction(signedTransaction);
39836
- await client.waitForTransaction(sentTransaction.hash);
39837
- }, {});
39798
+ if (txParams) {
39799
+ addSwapTransaction({
39800
+ ...txParams,
39801
+ params: route.params,
39802
+ estimate: route.estimate,
39803
+ });
39804
+ }
39805
+ const sentTransaction = await client.sendTransaction(signedTransaction);
39806
+ await client.waitForTransaction(sentTransaction.hash);
39807
+ },
39808
+ });
39838
39809
  const handleTransactionSuccess = useCallback((id) => {
39839
39810
  const currentTx = getTransaction(id);
39840
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39811
+ queryClient.invalidateQueries({
39812
+ queryKey: getPrefixKey(QueryKeys.Balances),
39813
+ });
39841
39814
  if (isSameChain && currentTx?.transactionId) {
39842
39815
  replaceSwapTransactionStatus({
39843
39816
  transactionId: currentTx.transactionId,
@@ -39889,38 +39862,39 @@ const useExecuteTransaction = (squidRoute) => {
39889
39862
  setTransactionStoreState,
39890
39863
  squidRoute,
39891
39864
  ]);
39892
- const swapMutation = useMutation(async (mutationParams) => {
39893
- if (!mutationParams.route)
39894
- throw new Error("route is required");
39895
- const sourceChain = findChain(mutationParams.route.params?.fromChain);
39896
- if (!sourceChain)
39897
- throw new Error("Could not find source chain");
39898
- switch (sourceChain.chainType) {
39899
- case ChainType.COSMOS: {
39900
- return swapMutationCosmos.mutateAsync(mutationParams);
39901
- }
39902
- case ChainType.EVM: {
39903
- return swapMutationEvm.mutateAsync(mutationParams);
39904
- }
39905
- case ChainType.BTC: {
39906
- return swapMutationBitcoin.mutateAsync(mutationParams);
39907
- }
39908
- case ChainType.SOLANA: {
39909
- return swapMutationSolana.mutateAsync(mutationParams);
39910
- }
39911
- case ChainType.SUI: {
39912
- return swapMutationSui.mutateAsync(mutationParams);
39913
- }
39914
- case ChainType.XRPL: {
39915
- return swapMutationXrpl.mutateAsync(mutationParams);
39916
- }
39917
- case ChainType.STELLAR: {
39918
- return swapMutationStellar.mutateAsync(mutationParams);
39865
+ const swapMutation = useMutation({
39866
+ mutationFn: async (mutationParams) => {
39867
+ if (!mutationParams.route)
39868
+ throw new Error("route is required");
39869
+ const sourceChain = findChain(mutationParams.route.params?.fromChain);
39870
+ if (!sourceChain)
39871
+ throw new Error("Could not find source chain");
39872
+ switch (sourceChain.chainType) {
39873
+ case ChainType.COSMOS: {
39874
+ return swapMutationCosmos.mutateAsync(mutationParams);
39875
+ }
39876
+ case ChainType.EVM: {
39877
+ return swapMutationEvm.mutateAsync(mutationParams);
39878
+ }
39879
+ case ChainType.BTC: {
39880
+ return swapMutationBitcoin.mutateAsync(mutationParams);
39881
+ }
39882
+ case ChainType.SOLANA: {
39883
+ return swapMutationSolana.mutateAsync(mutationParams);
39884
+ }
39885
+ case ChainType.SUI: {
39886
+ return swapMutationSui.mutateAsync(mutationParams);
39887
+ }
39888
+ case ChainType.XRPL: {
39889
+ return swapMutationXrpl.mutateAsync(mutationParams);
39890
+ }
39891
+ case ChainType.STELLAR: {
39892
+ return swapMutationStellar.mutateAsync(mutationParams);
39893
+ }
39894
+ default:
39895
+ throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39919
39896
  }
39920
- default:
39921
- throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39922
- }
39923
- }, {
39897
+ },
39924
39898
  onMutate: (variables) => {
39925
39899
  useTransactionStore.setState({
39926
39900
  txLocalId: variables.id,
@@ -39969,7 +39943,7 @@ const useExecuteTransaction = (squidRoute) => {
39969
39943
  toToken,
39970
39944
  toChain,
39971
39945
  fromChain,
39972
- isLoading: swapMutation.isLoading,
39946
+ isPending: swapMutation.isPending,
39973
39947
  error: swapMutation.error,
39974
39948
  };
39975
39949
  };
@@ -40030,57 +40004,59 @@ const useGetRoute = () => {
40030
40004
  * These data will be used to trigger the transaction
40031
40005
  * @returns {Route} Route data
40032
40006
  */
40033
- return useMutation(async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40034
- if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40035
- return undefined;
40036
- }
40037
- // Dispatch requestQuote event
40038
- dispatchRequestQuoteEvent({
40039
- fromChain,
40040
- toChain,
40041
- fromToken: fromToken.address,
40042
- toToken: toToken.address,
40043
- fromAmount: fromPrice,
40044
- fromAddress: sourceUserAddress,
40045
- toAddress: destinationAddress,
40046
- });
40047
- const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40048
- const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40049
- const fromTokenAddress = fromToken.address;
40050
- const toTokenAddress = toToken.address;
40051
- const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40052
- const fromAddress = sourceUserAddress ??
40053
- chainTypeToZeroAddressMap[fromChainType ?? ChainType.EVM];
40054
- const params = {
40055
- fromChain,
40056
- fromToken: fromTokenAddress,
40057
- fromAddress,
40058
- fromAmount,
40059
- toChain,
40060
- toToken: toTokenAddress,
40061
- toAddress: destinationAddress ?? "",
40062
- quoteOnly,
40063
- slippage: config.slippage === 0 ? undefined : config.slippage,
40064
- bypassGuardrails,
40065
- preHook,
40066
- postHook,
40067
- };
40068
- // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40069
- if (cosmosFallbackAddresses &&
40070
- cosmosFallbackAddresses.length > 0 &&
40071
- cosmosFallbackAddresses[0].address) {
40072
- params.fallbackAddresses = cosmosFallbackAddresses;
40073
- }
40074
- const { route } = await squid.getRoute({
40075
- ...params,
40076
- });
40077
- // Cache the route data
40078
- // Useful when the getRoute mutation is called from another hook
40079
- 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);
40080
- return route;
40007
+ return useMutation({
40008
+ mutationFn: async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40009
+ if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40010
+ return undefined;
40011
+ }
40012
+ // Dispatch requestQuote event
40013
+ dispatchRequestQuoteEvent({
40014
+ fromChain,
40015
+ toChain,
40016
+ fromToken: fromToken.address,
40017
+ toToken: toToken.address,
40018
+ fromAmount: fromPrice,
40019
+ fromAddress: sourceUserAddress,
40020
+ toAddress: destinationAddress,
40021
+ });
40022
+ const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40023
+ const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40024
+ const fromTokenAddress = fromToken.address;
40025
+ const toTokenAddress = toToken.address;
40026
+ const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40027
+ const fromAddress = sourceUserAddress ??
40028
+ chainTypeToZeroAddressMap[fromChainType ?? ChainType.EVM];
40029
+ const params = {
40030
+ fromChain,
40031
+ fromToken: fromTokenAddress,
40032
+ fromAddress,
40033
+ fromAmount,
40034
+ toChain,
40035
+ toToken: toTokenAddress,
40036
+ toAddress: destinationAddress ?? "",
40037
+ quoteOnly,
40038
+ slippage: config.slippage === 0 ? undefined : config.slippage,
40039
+ bypassGuardrails,
40040
+ preHook,
40041
+ postHook,
40042
+ };
40043
+ // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40044
+ if (cosmosFallbackAddresses &&
40045
+ cosmosFallbackAddresses.length > 0 &&
40046
+ cosmosFallbackAddresses[0].address) {
40047
+ params.fallbackAddresses = cosmosFallbackAddresses;
40048
+ }
40049
+ const { route } = await squid.getRoute({
40050
+ ...params,
40051
+ });
40052
+ // Cache the route data
40053
+ // Useful when the getRoute mutation is called from another hook
40054
+ queryClient.setQueryData(keys().transaction(fromChain, toChain, toToken.address, fromToken.address, fromPrice, config.slippage, config.enableGetGasOnDestination, sourceUserAddress, config.degenMode, destinationAddress, swapRoute?.fallbackAddress, quoteOnly, fromChainType, config.preHook, config.postHook), route);
40055
+ return route;
40056
+ },
40081
40057
  });
40082
40058
  };
40083
- const useGetRouteWrapper = ({ enabled, cacheTime = 5 * 60 * 1000, // 5 minutes
40059
+ const useGetRouteWrapper = ({ enabled, gcTime = 5 * 60 * 1000, // 5 minutes
40084
40060
  staleTime = 60 * 1000, // 1 minute
40085
40061
  refetchOnWindowFocus = (query) => Date.now() - query.state.dataUpdatedAt > 30000, // Update if older than 30 seconds, when window is focused
40086
40062
  refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true, }) => {
@@ -40130,25 +40106,27 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40130
40106
  * These data will be used to trigger the transaction
40131
40107
  * @returns {Route} Route data
40132
40108
  */
40133
- const squidRoute = useQuery(squidRouteQueryKeys, async () => {
40134
- const route = await getRouteMutation.mutateAsync({
40135
- fromChain: fromChain?.chainId,
40136
- toChain: toChain?.chainId,
40137
- fromToken,
40138
- toToken,
40139
- sourceUserAddress,
40140
- destinationAddress,
40141
- fromPrice,
40142
- bypassGuardrails: config.degenMode,
40143
- quoteOnly,
40144
- fromChainType: fromChain?.chainType,
40145
- postHook: config.postHook,
40146
- preHook: config.preHook,
40147
- });
40148
- return route;
40149
- }, {
40109
+ const squidRoute = useQuery({
40110
+ queryKey: squidRouteQueryKeys,
40111
+ queryFn: async () => {
40112
+ const route = await getRouteMutation.mutateAsync({
40113
+ fromChain: fromChain?.chainId,
40114
+ toChain: toChain?.chainId,
40115
+ fromToken,
40116
+ toToken,
40117
+ sourceUserAddress,
40118
+ destinationAddress,
40119
+ fromPrice,
40120
+ bypassGuardrails: config.degenMode,
40121
+ quoteOnly,
40122
+ fromChainType: fromChain?.chainType,
40123
+ postHook: config.postHook,
40124
+ preHook: config.preHook,
40125
+ });
40126
+ return route;
40127
+ },
40150
40128
  enabled: queryEnabled,
40151
- cacheTime,
40129
+ gcTime,
40152
40130
  staleTime,
40153
40131
  refetchOnWindowFocus,
40154
40132
  refetchIntervalInBackground,
@@ -40157,7 +40135,7 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40157
40135
  /**
40158
40136
  * If last updated data is older than X seconds and the query is currently loading, show loading indicator
40159
40137
  */
40160
- const showLoading = useMemo(() => squidRoute.isFetching || squidRoute.isRefetching, [squidRoute.isFetching, squidRoute.isRefetching]);
40138
+ const showLoading = squidRoute.isFetching || squidRoute.isRefetching;
40161
40139
  return {
40162
40140
  squidRoute,
40163
40141
  showLoading,
@@ -40189,7 +40167,7 @@ function useSendTransactionStatus({ chain, txHash, }) {
40189
40167
  transactionId: txHash,
40190
40168
  txType: HistoryTxType.SEND,
40191
40169
  });
40192
- const { data: status } = useQuery({
40170
+ const { data: status, isSuccess, isError, } = useQuery({
40193
40171
  queryKey: keys().sendTransactionStatus(txHash, chain?.chainId),
40194
40172
  queryFn: async () => {
40195
40173
  if (!chain || !txHash)
@@ -40199,17 +40177,30 @@ function useSendTransactionStatus({ chain, txHash, }) {
40199
40177
  txHash,
40200
40178
  });
40201
40179
  },
40202
- onSuccess: (txStatus) => {
40203
- setIsTransactionComplete(txStatus !== SendTransactionStatus.ONGOING);
40204
- if (txStatus != null && !!txHash) {
40180
+ refetchInterval: chain
40181
+ ? getSendTxStatusRefetchInterval(chain.chainType)
40182
+ : false,
40183
+ enabled: !!chain &&
40184
+ !!txHash &&
40185
+ !isTransactionComplete &&
40186
+ !!currentHistoryItem &&
40187
+ !isHistoryTransactionEnded({
40188
+ data: currentHistoryItem?.data,
40189
+ txType: HistoryTxType.SEND,
40190
+ }),
40191
+ });
40192
+ useEffect(() => {
40193
+ if (isSuccess) {
40194
+ setIsTransactionComplete(status !== SendTransactionStatus.ONGOING);
40195
+ if (status != null && !!txHash) {
40205
40196
  replaceTransactionStatus({
40206
40197
  txType: HistoryTxType.SEND,
40207
- status: txStatus,
40198
+ status: status,
40208
40199
  hash: txHash,
40209
40200
  });
40210
40201
  }
40211
- },
40212
- onError() {
40202
+ }
40203
+ if (isError) {
40213
40204
  setIsTransactionComplete(true);
40214
40205
  if (txHash) {
40215
40206
  replaceTransactionStatus({
@@ -40218,19 +40209,8 @@ function useSendTransactionStatus({ chain, txHash, }) {
40218
40209
  hash: txHash,
40219
40210
  });
40220
40211
  }
40221
- },
40222
- refetchInterval: chain
40223
- ? getSendTxStatusRefetchInterval(chain.chainType)
40224
- : false,
40225
- enabled: !!chain &&
40226
- !!txHash &&
40227
- !isTransactionComplete &&
40228
- !!currentHistoryItem &&
40229
- !isHistoryTransactionEnded({
40230
- data: currentHistoryItem?.data,
40231
- txType: HistoryTxType.SEND,
40232
- }),
40233
- });
40212
+ }
40213
+ }, [isError, isSuccess, replaceTransactionStatus, status, txHash]);
40234
40214
  return {
40235
40215
  status: status ?? currentHistoryItem?.data?.status,
40236
40216
  };
@@ -40264,7 +40244,9 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40264
40244
  apiUrl: latestConfig.apiUrl,
40265
40245
  });
40266
40246
  }, [transaction]);
40267
- const transactionStatusQuery = useQuery(keys().swapTransactionStatus(transaction?.transactionId), fetchTransactionStatusWithLatestConfig, {
40247
+ const transactionStatusQuery = useQuery({
40248
+ queryKey: keys().swapTransactionStatus(transaction?.transactionId),
40249
+ queryFn: fetchTransactionStatusWithLatestConfig,
40268
40250
  enabled: enabled &&
40269
40251
  transaction?.transactionId !== "0" &&
40270
40252
  !!transaction?.transactionId &&
@@ -40278,12 +40260,12 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40278
40260
  data: currentHistoryItem?.data,
40279
40261
  txType: HistoryTxType.SWAP,
40280
40262
  }),
40281
- refetchInterval(statusResponse) {
40263
+ refetchInterval({ state }) {
40282
40264
  // If the status response is something telling that the transaction
40283
40265
  // is finished, then store transaction history state if success
40284
40266
  // And return false to indicate refetcher to stop
40285
- if (statusResponse &&
40286
- transactionEndStatuses.includes(getTransactionStatus(statusResponse) ?? "")) {
40267
+ if (state.data &&
40268
+ transactionEndStatuses.includes(getTransactionStatus(state.data) ?? "")) {
40287
40269
  return false;
40288
40270
  }
40289
40271
  return refetchInterval; // Had to handle a variable here because after onError, we want the interval to stop
@@ -40292,7 +40274,10 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40292
40274
  retryDelay: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 5000 : 3000,
40293
40275
  retry: getChainType(transaction?.fromChain) === ChainType.COSMOS ? 6 : retry,
40294
40276
  refetchOnWindowFocus,
40295
- onSuccess: (statusResponse) => {
40277
+ });
40278
+ useEffect(() => {
40279
+ if (transactionStatusQuery.isSuccess && transactionStatusQuery.data) {
40280
+ const statusResponse = transactionStatusQuery.data;
40296
40281
  // Dispatch event
40297
40282
  WidgetEvents.getInstance().dispatchSwapStatus(statusResponse.squidTransactionStatus ?? "");
40298
40283
  const endStatus = getTransactionEndStatus({ statusResponse });
@@ -40304,8 +40289,9 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40304
40289
  status: endStatus,
40305
40290
  });
40306
40291
  }
40307
- },
40308
- onError: (error) => {
40292
+ }
40293
+ if (transactionStatusQuery.isError) {
40294
+ const error = transactionStatusQuery.error;
40309
40295
  // `fetchTransactionStatus` throws an error with a cause being an AxiosError
40310
40296
  const is404 = is404Error(error.cause);
40311
40297
  if (!transaction?.transactionId)
@@ -40326,8 +40312,15 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40326
40312
  status: TransactionStatus.ERROR,
40327
40313
  });
40328
40314
  }
40329
- },
40330
- });
40315
+ }
40316
+ }, [
40317
+ transactionStatusQuery.isSuccess,
40318
+ transactionStatusQuery.isError,
40319
+ transaction?.transactionId,
40320
+ transactionStatusQuery.error,
40321
+ replaceSwapTransactionStatus,
40322
+ transactionStatusQuery.data,
40323
+ ]);
40331
40324
  return {
40332
40325
  transactionStatusQuery,
40333
40326
  latestStatus: transactionStatusQuery.data
@@ -40370,7 +40363,7 @@ const useAvatar = (seed = zeroAddress) => {
40370
40363
  },
40371
40364
  // data is static, so no need to refetch
40372
40365
  refetchOnWindowFocus: false,
40373
- cacheTime: Infinity,
40366
+ gcTime: Infinity,
40374
40367
  staleTime: Infinity,
40375
40368
  });
40376
40369
  return avatar || "";
@@ -40412,38 +40405,40 @@ const useAddToken = (chainToCompare, tokenToCompare) => {
40412
40405
  /**
40413
40406
  * Add token to wallet
40414
40407
  */
40415
- const addToken = useMutation(async ({ chain: _chain, token: _token, }) => {
40416
- const token = _token ?? tokenToCompare;
40417
- const chain = _chain ?? chainToCompare;
40418
- if (token && chain?.chainType === ChainType.EVM) {
40419
- const provider = await connector?.getProvider();
40420
- // Switch network if needed
40421
- if (currentEvmChain?.id.toString() !== token?.chainId) {
40422
- try {
40423
- await switchChainAsync({
40424
- chainId: +token.chainId,
40425
- });
40426
- }
40427
- catch (error) {
40428
- console.debug("Error switching network:", error);
40429
- if (isEvmChainNotSupportedError(error)) {
40430
- await addEthereumChain({
40431
- chain,
40432
- provider,
40433
- });
40408
+ const addToken = useMutation({
40409
+ mutationFn: async ({ chain: _chain, token: _token, }) => {
40410
+ const token = _token ?? tokenToCompare;
40411
+ const chain = _chain ?? chainToCompare;
40412
+ if (token && chain?.chainType === ChainType.EVM) {
40413
+ const provider = await connector?.getProvider();
40414
+ // Switch network if needed
40415
+ if (currentEvmChain?.id.toString() !== token?.chainId) {
40416
+ try {
40434
40417
  await switchChainAsync({
40435
40418
  chainId: +token.chainId,
40436
40419
  });
40437
40420
  }
40421
+ catch (error) {
40422
+ console.debug("Error switching network:", error);
40423
+ if (isEvmChainNotSupportedError(error)) {
40424
+ await addEthereumChain({
40425
+ chain,
40426
+ provider,
40427
+ });
40428
+ await switchChainAsync({
40429
+ chainId: +token.chainId,
40430
+ });
40431
+ }
40432
+ }
40433
+ // Metamask is not popping the second modal if we don't wait a bit
40434
+ // eslint-disable-next-line no-promise-executor-return
40435
+ await new Promise((resolve) => setTimeout(resolve, 100));
40438
40436
  }
40439
- // Metamask is not popping the second modal if we don't wait a bit
40440
- // eslint-disable-next-line no-promise-executor-return
40441
- await new Promise((resolve) => setTimeout(resolve, 100));
40437
+ await addTokenToWallet({ token, provider });
40442
40438
  }
40443
- await addTokenToWallet({ token, provider });
40439
+ // TODO: Implement keplr add token
40440
+ return false;
40444
40441
  }
40445
- // TODO: Implement keplr add token
40446
- return false;
40447
40442
  });
40448
40443
  return {
40449
40444
  addToken,
@@ -40648,7 +40643,9 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40648
40643
  }
40649
40644
  },
40650
40645
  async onSuccess() {
40651
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.XrplTrustLine));
40646
+ queryClient.invalidateQueries({
40647
+ queryKey: getPrefixKey(QueryKeys.XrplTrustLine),
40648
+ });
40652
40649
  },
40653
40650
  });
40654
40651
  /**
@@ -40826,5 +40823,5 @@ const SquidProvider = ({ children, config, placeholder, }) => {
40826
40823
  React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
40827
40824
  };
40828
40825
 
40829
- 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 };
40830
- //# sourceMappingURL=index-_Qp4Ou3J.js.map
40826
+ export { useNativeBalance as $, AxelarStatusResponseType as A, useAddressBookStore as B, CHAIN_IDS as C, DEFAULT_LOCALE as D, useAssetsColorsStore as E, useFavoriteTokensStore as F, useHistoryStore as G, HistoryTxType as H, useSendTransactionStore as I, useConfigStore as J, useSquidStore as K, useSwapRoutePersistStore as L, useTransactionStore as M, ConnectingWalletStatus as N, useWalletStore as O, useDepositAddress as P, useSwap as Q, useAllConnectedWalletBalances as R, SquidStatusErrorType as S, TransactionErrorType as T, useAllTokensWithBalanceForChainType as U, useCosmosBalance as V, WindowWalletFlag as W, XamanXrplNetwork as X, useEvmBalance as Y, useMultiChainBalance as Z, useMultipleTokenPrices as _, chainTypeToZeroAddressMap as a, groupTokensBySymbol as a$, useNativeTokenForChain as a0, useSingleTokenPrice as a1, useSquidTokens as a2, useHistoricalData as a3, useTokensData as a4, useEstimateSendTransaction as a5, useSendTransaction as a6, useSendTransactionGas as a7, useAllTransactionsStatus as a8, useApproval as a9, useGetFiatQuote as aA, useGetOnRampConfig as aB, useExecuteFiatQuote as aC, useCurrencyDetails as aD, useCountryDetails as aE, useAvailableQuotes as aF, useGetOnrampPaymentTypes as aG, useSuggestedFiatAmounts as aH, SquidProvider as aI, EnsService as aJ, getXummClient as aK, isXamanXAppContext as aL, getQueryHeaders as aM, getStatusCode as aN, is404Error as aO, assetsBaseUrl as aP, shareSubgraphId as aQ, sortTokensBySharedSubgraphIds as aR, getSupportedChainIdsForDirection as aS, filterChains as aT, filterTokens as aU, getTokenImage as aV, getNewSwapParamsFromInput as aW, sortAllTokens as aX, findToken as aY, findNativeToken as aZ, normalizeIbcAddress as a_, useEstimate as aa, useEstimatePriceImpact as ab, useExecuteTransaction as ac, useGetRoute as ad, useGetRouteWrapper as ae, useRouteWarnings as af, useSendTransactionStatus as ag, useSwapTransactionStatus as ah, useAvatar as ai, useHistory as aj, useUserParams as ak, useDebouncedValue as al, useAddToken as am, useAutoConnect as an, useEnsDataForAddress as ao, useEnsSearch as ap, useGnosisContext as aq, useIsSameAddressAndGnosisContext as ar, useIntegratorContext as as, useMultiChainWallet as at, useSigner as au, useWallet as av, useWallets as aw, useXrplTrustLine as ax, TX_STATUS_CONSTANTS as ay, FINAL_TRANSACTION_STATUSES as az, destinationAddressResetValue as b, formatTransactionHistoryDate as b$, groupTokensByChainId as b0, filterViewableTokens as b1, getSecretNetworkBalances as b2, getTokenAssetsKey as b3, fetchAssetsColors as b4, initializeSquidWithAssetsColors as b5, isEmptyObject as b6, normalizeTokenSymbol as b7, areTokenSymbolsCompatible as b8, isEvmosChain as b9, WidgetEvents as bA, EvmNetworkNotSupportedErrorCode as bB, addEthereumChain as bC, parseEvmAddress as bD, formatEvmWallet as bE, filterWagmiConnector as bF, getUserCountry as bG, getCountryData as bH, getCurrencyData as bI, adaptiveRound as bJ, getSuggestedAmountsForCurrency as bK, parseToBigInt as bL, roundNumericValue as bM, formatUnitsRounded as bN, formatTokenAmount as bO, formatUsdAmount as bP, trimExtraDecimals as bQ, getNumericValue as bR, cleanAmount as bS, convertTokenAmountToUSD as bT, convertUSDToTokenAmount as bU, calculateTotal24hChange as bV, searchTokens as bW, filterSolanaWallets as bX, isSolanaAddressValid as bY, executeSolanaSwap as bZ, executeSolanaTransfer as b_, getConfigWithDefaults as ba, randomIntFromInterval as bb, getTokensForChain as bc, getFirstAvailableChainId as bd, fetchHighestBalanceToken as be, getInitialOrDefaultTokenAddressForChain as bf, getInitialTokenAddressForChain as bg, filterTokensForDestination as bh, getInitialChainIdFromConfig as bi, getCosmosKey as bj, getKeysSettled as bk, getAllKeysForSupportedCosmosChains as bl, isCosmosAddressValid as bm, getCosmosSigningClient as bn, getCosmosChainInfosObject as bo, connectCosmosWallet as bp, isFallbackAddressNeeded as bq, suggestChainOrThrow as br, normalizeError as bs, transactionErrorCode as bt, isUserRejectionError as bu, getTransactionError as bv, handleTransactionErrorEvents as bw, isSwapRouteError as bx, isStatusError as by, createQuoteRequestParamsHash as bz, chainTypeToNativeTokenAddressMap as c, getAxelarExplorerTxUrl as c0, getSourceExplorerTxUrl as c1, getMainExplorerUrl as c2, formatDistance as c3, formatSeconds as c4, formatSwapTxStatusResponseForStorage as c5, simplifyRouteAction as c6, fetchSwapTransactionStatus as c7, compareTransactionIds as c8, isCoralBridgeAction as c9, calculateTotalUsdBalanceUSD as cA, addTokenToWallet as cB, isEvmChainNotSupportedError as cC, getWalletSupportedChainTypes as cD, getConnectorForChainType as cE, walletSupportsChainType as cF, connectWallet as cG, cancelConnectWallet as cH, isProblematicConnector as cI, mergeWallets as cJ, isXionSmartContractAddress as cK, isXrplAddressValid as cL, buildXrplTrustSetTx as cM, getXrplNetwork as cN, parseXrplPaymentTx as cO, sleep as ca, isDepositRoute as cb, isChainflipBridgeTransaction as cc, getHistoryTransactionId as cd, getStepStatuses as ce, getHalfSuccessState as cf, getStepsInfos as cg, getSwapTxStatusRefetchInterval as ch, getSendTxStatusRefetchInterval as ci, chainflipMultihopBridgeType as cj, getBridgeType as ck, getTransactionStatus as cl, getTransactionEndStatus as cm, isHistoryTransactionPending as cn, isHistoryTransactionFailed as co, isHistoryTransactionWarning as cp, isHistoryTransactionEnded as cq, formatHash as cr, isWalletAddressValid as cs, redirectToExtensionsStore as ct, accessProperty as cu, populateWallets as cv, getDefaultChain as cw, sortWallets as cx, areSameAddress as cy, sortAddressBook as cz, definedInWindow as d, fallbackAddressResetValue as e, formatBNToReadable as f, nativeCosmosTokenAddress as g, nativeEvmTokenAddress as h, nativeSolanaTokenAddress as i, nativeStellarTokenAddress as j, nativeSuiTokenAddress as k, nativeXrplTokenAddress as l, CosmosProvider as m, nativeBitcoinTokenAddress as n, SendTransactionStatus as o, TransactionStatus as p, useTrackSearchEmpty as q, useSquidChains as r, useClient as s, useCosmosForChain as t, useCosmosContext as u, useKeyboardNavigation as v, walletIconBaseUrl as w, useSquidQueryClient as x, useSquid as y, useStellarAccountActivation as z };
40827
+ //# sourceMappingURL=index-BA79s7uI.js.map