@0xsquid/react-hooks 8.0.0 → 8.0.1-para-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) 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 +19 -13
  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-BxbblIad.js} +1075 -1068
  23. package/dist/{index-_Qp4Ou3J.js.map → index-BxbblIad.js.map} +1 -1
  24. package/dist/{index-BtOPNnH5.js → index-CvsT0xf8.js} +1073 -1069
  25. package/dist/{index-BtOPNnH5.js.map → index-CvsT0xf8.js.map} +1 -1
  26. package/dist/index.esm.js +5 -3
  27. package/dist/index.esm.js.map +1 -1
  28. package/dist/index.js +6 -7
  29. package/dist/index.js.map +1 -1
  30. package/dist/provider/index.d.ts +2 -0
  31. package/dist/{secretService-DdVLwd-q.js → secretService-BjLmYyy4.js} +6 -4
  32. package/dist/{secretService-DdVLwd-q.js.map → secretService-BjLmYyy4.js.map} +1 -1
  33. package/dist/{secretService-CR2RaJtB.js → secretService-nvn8-zjs.js} +6 -4
  34. package/dist/{secretService-CR2RaJtB.js.map → secretService-nvn8-zjs.js.map} +1 -1
  35. package/dist/services/internal/configService.d.ts +0 -1
  36. package/dist/{stellarService.client-BvSwmxzo.js → stellarService.client-BuIqVMl2.js} +6 -4
  37. package/dist/{stellarService.client-BvSwmxzo.js.map → stellarService.client-BuIqVMl2.js.map} +1 -1
  38. package/dist/{stellarService.client-7rBIc_IW.js → stellarService.client-ep6_7QVE.js} +6 -4
  39. package/dist/{stellarService.client-7rBIc_IW.js.map → stellarService.client-ep6_7QVE.js.map} +1 -1
  40. package/package.json +14 -12
@@ -31,11 +31,13 @@ var stargate = require('@cosmjs/stargate');
31
31
  var client = require('@mysten/sui/client');
32
32
  var protoSigning = require('@cosmjs/proto-signing');
33
33
  var transactions = require('@mysten/sui/transactions');
34
+ var wagmiV2Integration = require('@getpara/wagmi-v2-integration');
35
+ var Para = require('@getpara/web-sdk');
34
36
  var connectors = require('wagmi/connectors');
35
- var cosmwasmStargate = require('@cosmjs/cosmwasm-stargate');
36
- var index_js = require('@injectivelabs/sdk-ts/dist/cjs/core/stargate/index.js');
37
37
  var sdk = require('@0xsquid/sdk');
38
38
  var chains$1 = require('viem/chains');
39
+ var cosmwasmStargate = require('@cosmjs/cosmwasm-stargate');
40
+ var index_js = require('@injectivelabs/sdk-ts/dist/cjs/core/stargate/index.js');
39
41
 
40
42
  function _interopNamespaceDefault(e) {
41
43
  var n = Object.create(null);
@@ -26786,9 +26788,6 @@ const getConfigWithDefaults = (config) => {
26786
26788
  postHook: get$3(config, "postHook", defaultConfigValues.postHook),
26787
26789
  };
26788
26790
  };
26789
- const randomIntFromInterval = (min, max) => {
26790
- return Math.floor(Math.random() * (max - min + 1) + min);
26791
- };
26792
26791
  const getTokensForChain = (tokens, chainId) => {
26793
26792
  return chainId ? tokens.filter((t) => t.chainId === chainId) : tokens;
26794
26793
  };
@@ -26816,7 +26815,9 @@ const fetchHighestBalanceToken = (fetchCachedBalance, chainId) => {
26816
26815
  if (fetchCachedBalance) {
26817
26816
  const queryCache = fetchCachedBalance?.queryClient?.getQueryCache();
26818
26817
  // get cached balance from key
26819
- const cache = queryCache?.find(keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? squidTypes.ChainType.EVM : squidTypes.ChainType.COSMOS));
26818
+ const cache = queryCache?.find({
26819
+ queryKey: keys().allTokensBalance(fetchCachedBalance?.address, !isNaN(Number(chainId)) ? squidTypes.ChainType.EVM : squidTypes.ChainType.COSMOS),
26820
+ });
26820
26821
  // Parse result to TokenWithBalance[]
26821
26822
  const cacheResult = cache?.state.data ?? [];
26822
26823
  if (cacheResult.length > 0) {
@@ -27472,7 +27473,7 @@ const filterViewableTokens = (tokens, config, direction) => {
27472
27473
  };
27473
27474
  const getSecretNetworkBalances = async (chainData, cosmosAddress, squidTokens, keplrTypeWallet) => {
27474
27475
  const squidSecretTokens = squidTokens.filter((t) => t.chainId === CHAIN_IDS.SECRET);
27475
- const { fetchAllSecretBalances } = await Promise.resolve().then(function () { return require('./secretService-DdVLwd-q.js'); });
27476
+ const { fetchAllSecretBalances } = await Promise.resolve().then(function () { return require('./secretService-BjLmYyy4.js'); });
27476
27477
  return fetchAllSecretBalances(chainData, cosmosAddress, squidSecretTokens, keplrTypeWallet);
27477
27478
  };
27478
27479
  function getTokenAssetsKey(token) {
@@ -29231,13 +29232,16 @@ const useSquid = () => {
29231
29232
  * Fetch squid info
29232
29233
  * Will refetch every minute
29233
29234
  */
29234
- const squidInfoQuery = reactQuery.useQuery(keys().squidInfo(), async () => {
29235
- if (squid) {
29236
- await squid?.init();
29237
- initializeSquidWithAssetsColors(squid, assetsColors);
29238
- return squid;
29235
+ const squidInfoQuery = reactQuery.useQuery({
29236
+ queryKey: keys().squidInfo(),
29237
+ queryFn: async () => {
29238
+ if (squid) {
29239
+ await squid?.init();
29240
+ initializeSquidWithAssetsColors(squid, assetsColors);
29241
+ return squid;
29242
+ }
29243
+ return null;
29239
29244
  }
29240
- return null;
29241
29245
  });
29242
29246
  const tokens = React.useMemo(() => {
29243
29247
  if ((squidInfoQuery?.data?.tokens ?? []).length > 0) {
@@ -29353,47 +29357,11 @@ const FINAL_TRANSACTION_STATUSES = [
29353
29357
  "completed",
29354
29358
  "failed",
29355
29359
  ];
29356
- /**
29357
- * Configuration for transaction status tracking
29358
- */
29359
- const createTransactionStatusConfig = ({ transactionId, walletAddress, providerId, replaceTransactionStatus, }) => {
29360
- return {
29361
- queryKey: keys().fiatToCryptoStatus(transactionId),
29362
- queryFn: () => new OnrampService().getTransactionStatus(transactionId, walletAddress, providerId),
29363
- enabled: !!transactionId && !!walletAddress && !!providerId,
29364
- retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
29365
- retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
29366
- refetchInterval: (data) => {
29367
- if (data?.status && FINAL_TRANSACTION_STATUSES.includes(data.status)) {
29368
- return false;
29369
- }
29370
- return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
29371
- },
29372
- onSuccess: (data) => {
29373
- if (data) {
29374
- replaceTransactionStatus({
29375
- txType: exports.HistoryTxType.BUY,
29376
- orderId: transactionId,
29377
- status: data.status,
29378
- transactionHash: data.transactionHash,
29379
- });
29380
- }
29381
- },
29382
- onError: () => {
29383
- replaceTransactionStatus({
29384
- txType: exports.HistoryTxType.BUY,
29385
- orderId: transactionId,
29386
- status: "failed",
29387
- transactionHash: undefined,
29388
- });
29389
- },
29390
- };
29391
- };
29392
29360
  /**
29393
29361
  * Fetches quotes for fiat to crypto conversion with provider details.
29394
29362
  * Returns available rates, fees, and supported payment methods for the conversion.
29395
29363
  */
29396
- const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, onSuccess, }) => {
29364
+ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, paymentMethod, enabled = true, }) => {
29397
29365
  const service = React.useMemo(() => new OnrampService(), []);
29398
29366
  const { data: config } = useGetOnRampConfig();
29399
29367
  return reactQuery.useQuery({
@@ -29429,7 +29397,6 @@ const useGetFiatQuote = ({ fiatCurrency, cryptoCurrencyID, amount, region, payme
29429
29397
  return quoteResponse;
29430
29398
  },
29431
29399
  enabled: enabled && !!fiatCurrency && !!cryptoCurrencyID && amount > 0,
29432
- onSuccess,
29433
29400
  });
29434
29401
  };
29435
29402
  /**
@@ -29446,7 +29413,7 @@ const useGetOnRampConfig = () => {
29446
29413
  chains,
29447
29414
  tokens,
29448
29415
  }),
29449
- cacheTime: 1000 * 60 * 60,
29416
+ gcTime: 1000 * 60 * 60,
29450
29417
  staleTime: 1000 * 60 * 30, // 30 minutes
29451
29418
  });
29452
29419
  };
@@ -29504,49 +29471,11 @@ const useExecuteFiatQuote = () => {
29504
29471
  },
29505
29472
  });
29506
29473
  };
29507
- /**
29508
- * Tracks the status of a single fiat to crypto transaction.
29509
- */
29510
- const useFiatOnRampTxStatus = (transactionId, walletAddress, providerId) => {
29511
- const replaceTransactionStatus = useHistoryStore((state) => state.replaceTransactionStatus);
29512
- return reactQuery.useQuery({
29513
- ...createTransactionStatusConfig({
29514
- transactionId,
29515
- walletAddress,
29516
- providerId,
29517
- replaceTransactionStatus,
29518
- }),
29519
- });
29520
- };
29521
- /**
29522
- * Tracks all pending fiat transactions.
29523
- */
29524
- const useFiatTransactions = () => {
29525
- const transactions = useHistoryStore((state) => state.transactions.filter((tx) => tx.txType === exports.HistoryTxType.BUY));
29526
- const replaceTransactionStatus = useHistoryStore((state) => state.replaceTransactionStatus);
29527
- const pendingTransactions = React.useMemo(() => transactions?.filter((tx) => !FINAL_TRANSACTION_STATUSES.includes(tx.data.status)) ?? [], [transactions]);
29528
- const queries = reactQuery.useQueries({
29529
- queries: pendingTransactions.map((tx) => ({
29530
- ...createTransactionStatusConfig({
29531
- transactionId: tx.data.orderId,
29532
- walletAddress: tx.data.toAddress,
29533
- providerId: tx.data.providerId,
29534
- replaceTransactionStatus,
29535
- }),
29536
- })),
29537
- });
29538
- return {
29539
- transactions: transactions.map((tx) => tx.data),
29540
- isLoading: queries.some((q) => q.isLoading),
29541
- isError: queries.some((q) => q.isError),
29542
- };
29543
- };
29544
29474
  /**
29545
29475
  * Gets currency details including symbol and limits.
29546
29476
  * Example: USD → { symbol: "$", name: "US Dollar", ... }
29547
29477
  */
29548
29478
  const useCurrencyDetails = (currencyCode) => {
29549
- const { data: config } = useGetOnRampConfig();
29550
29479
  return React.useMemo(() => {
29551
29480
  if (!currencyCode)
29552
29481
  return undefined;
@@ -29559,7 +29488,7 @@ const useCurrencyDetails = (currencyCode) => {
29559
29488
  };
29560
29489
  }
29561
29490
  return undefined;
29562
- }, [currencyCode, config?.supportedFiats]);
29491
+ }, [currencyCode]);
29563
29492
  };
29564
29493
  /**
29565
29494
  * Gets country details with flag URL and localized name.
@@ -29586,23 +29515,6 @@ const useAvailableQuotes = (quotes) => {
29586
29515
  return uniqueQuotes;
29587
29516
  }, [quotes]);
29588
29517
  };
29589
- /**
29590
- * Gets the recommended quote based on best rates or provider preferences.
29591
- * Falls back to first available quote if no specific recommendation.
29592
- */
29593
- const useRecommendedQuote = (quotes, recommendedQuote) => {
29594
- const availableQuotes = useAvailableQuotes(quotes);
29595
- return React.useMemo(() => {
29596
- if (!availableQuotes.length)
29597
- return undefined;
29598
- if (!recommendedQuote)
29599
- return availableQuotes[0];
29600
- // Try to find the recommended quote among available quotes
29601
- const recommendedAvailableQuote = availableQuotes.find((quote) => quote.onrampProviderId === recommendedQuote.onrampProviderId);
29602
- // If recommended quote is not available, return first available quote
29603
- return recommendedAvailableQuote ?? availableQuotes[0];
29604
- }, [availableQuotes, recommendedQuote]);
29605
- };
29606
29518
  /**
29607
29519
  * Fetches the available payment methods for a given fiat and crypto currency pair.
29608
29520
  * The first item in the returned array is the most recommended.
@@ -29705,7 +29617,7 @@ const middleStepChecker = (statusResponse) => {
29705
29617
  }
29706
29618
  return exports.TransactionStatus.ERROR;
29707
29619
  }
29708
- if (statusResponse?.isInitialLoading) {
29620
+ if (statusResponse?.isLoading) {
29709
29621
  return exports.TransactionStatus.INITIAL_LOADING;
29710
29622
  }
29711
29623
  return exports.TransactionStatus.ONGOING;
@@ -30150,7 +30062,7 @@ const useClient = () => {
30150
30062
  queryFn: getUserCountry,
30151
30063
  enabled: isClient,
30152
30064
  retry: false,
30153
- cacheTime: CACHE_TIME,
30065
+ gcTime: CACHE_TIME,
30154
30066
  staleTime: STALE_TIME,
30155
30067
  });
30156
30068
  const userCountry = countryData?.countryCode || DEFAULT_COUNTRY_CODE;
@@ -30251,11 +30163,13 @@ function useDebouncedValue(value, delay) {
30251
30163
  * @returns the ENS data of the given address
30252
30164
  */
30253
30165
  function useEnsDataForAddress({ address, options, }) {
30254
- const ensQuery = reactQuery.useQuery(keys().ensData(address?.toLowerCase()), () => EnsService.getEnsDataFromAddress(address), {
30166
+ const ensQuery = reactQuery.useQuery({
30167
+ queryKey: keys().ensData(address?.toLowerCase()),
30168
+ queryFn: () => EnsService.getEnsDataFromAddress(address),
30255
30169
  ...options,
30256
30170
  enabled: Boolean(address?.trim()) &&
30257
30171
  (options?.enabled === undefined ? true : options.enabled),
30258
- cacheTime: Infinity,
30172
+ gcTime: Infinity,
30259
30173
  });
30260
30174
  return ensQuery;
30261
30175
  }
@@ -30271,14 +30185,16 @@ function useEnsDataForAddress({ address, options, }) {
30271
30185
  */
30272
30186
  function useEnsSearch({ name, enabled = true, delayMs = 500, }) {
30273
30187
  const debouncedName = useDebouncedValue(enabled ? name : undefined, delayMs);
30274
- const ensSearchQuery = reactQuery.useQuery(keys().ensSearch(debouncedName), () => {
30275
- const isExactEnsSearch = checkIsExactEns(debouncedName);
30276
- return isExactEnsSearch
30277
- ? EnsService.getExactEns(debouncedName)
30278
- : EnsService.searchEnsNames(debouncedName);
30279
- }, {
30188
+ const ensSearchQuery = reactQuery.useQuery({
30189
+ queryKey: keys().ensSearch(debouncedName),
30190
+ queryFn: () => {
30191
+ const isExactEnsSearch = checkIsExactEns(debouncedName);
30192
+ return isExactEnsSearch
30193
+ ? EnsService.getExactEns(debouncedName)
30194
+ : EnsService.searchEnsNames(debouncedName);
30195
+ },
30280
30196
  enabled: Boolean(debouncedName?.trim()) && enabled,
30281
- cacheTime: Infinity,
30197
+ gcTime: Infinity,
30282
30198
  });
30283
30199
  return ensSearchQuery;
30284
30200
  }
@@ -30299,23 +30215,25 @@ function checkIsExactEns(name = "") {
30299
30215
 
30300
30216
  const useCosmosForChain = (chain) => {
30301
30217
  const { keplrTypeWallet } = useCosmosSigner({ chain });
30302
- const cosmosAddressQuery = reactQuery.useQuery(keys().cosmosAddress(chain?.chainId), async () => {
30303
- if (!chain || !keplrTypeWallet)
30304
- return "";
30305
- try {
30306
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30307
- return address ?? "";
30308
- }
30309
- catch (error) {
30310
- await suggestChainOrThrow({
30311
- chain: chain,
30312
- error,
30313
- keplrTypeWallet,
30314
- });
30315
- const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30316
- return address ?? "";
30317
- }
30318
- }, {
30218
+ const cosmosAddressQuery = reactQuery.useQuery({
30219
+ queryKey: keys().cosmosAddress(chain?.chainId),
30220
+ queryFn: async () => {
30221
+ if (!chain || !keplrTypeWallet)
30222
+ return "";
30223
+ try {
30224
+ const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30225
+ return address ?? "";
30226
+ }
30227
+ catch (error) {
30228
+ await suggestChainOrThrow({
30229
+ chain: chain,
30230
+ error,
30231
+ keplrTypeWallet,
30232
+ });
30233
+ const address = await getCosmosKey(chain.chainId, keplrTypeWallet);
30234
+ return address ?? "";
30235
+ }
30236
+ },
30319
30237
  enabled: !!keplrTypeWallet && chain?.chainType === squidTypes.ChainType.COSMOS,
30320
30238
  });
30321
30239
  return cosmosAddressQuery;
@@ -30392,12 +30310,14 @@ const useIsSameAddressAndGnosisContext = () => {
30392
30310
 
30393
30311
  function useBitcoin() {
30394
30312
  const connectedBitcoinWallet = useWalletStore((store) => store.connectedWalletsByChainType[squidTypes.ChainType.BTC]);
30395
- const connectBitcoin = reactQuery.useMutation(async ({ wallet, }) => {
30396
- const { address } = await wallet.connector.requestAccount();
30397
- return {
30398
- wallet,
30399
- address,
30400
- };
30313
+ const connectBitcoin = reactQuery.useMutation({
30314
+ mutationFn: async ({ wallet, }) => {
30315
+ const { address } = await wallet.connector.requestAccount();
30316
+ return {
30317
+ wallet,
30318
+ address,
30319
+ };
30320
+ }
30401
30321
  });
30402
30322
  return {
30403
30323
  connectBitcoin,
@@ -30437,15 +30357,17 @@ function useEvm() {
30437
30357
  const { wallets } = useEvmWallets();
30438
30358
  const connectedEvmWallet = useWalletStore((store) => store.connectedWalletsByChainType[squidTypes.ChainType.EVM]);
30439
30359
  const recentEvmWalletId = useWalletStore((store) => store.recentConnectorIds[squidTypes.ChainType.EVM]);
30440
- const connectEvm = reactQuery.useMutation(async ({ wallet, }) => {
30441
- const result = await connectAsync({
30442
- connector: wallet.connector,
30443
- });
30444
- const [firstAddress] = result.accounts;
30445
- return {
30446
- wallet,
30447
- address: firstAddress,
30448
- };
30360
+ const connectEvm = reactQuery.useMutation({
30361
+ mutationFn: async ({ wallet, }) => {
30362
+ const result = await connectAsync({
30363
+ connector: wallet.connector,
30364
+ });
30365
+ const [firstAddress] = result.accounts;
30366
+ return {
30367
+ wallet,
30368
+ address: firstAddress,
30369
+ };
30370
+ }
30449
30371
  });
30450
30372
  const disconnectEvm = React.useCallback(async () => {
30451
30373
  disconnect({ connector: connectedEvmWallet.wallet?.connector });
@@ -30539,21 +30461,23 @@ function useSolana() {
30539
30461
  const { wallets } = useSolanaWallets();
30540
30462
  const connectedSolanaWallet = useWalletStore((store) => store.connectedWalletsByChainType[squidTypes.ChainType.SOLANA]);
30541
30463
  const recentSolanaWalletId = useWalletStore((store) => store.recentConnectorIds[squidTypes.ChainType.SOLANA]);
30542
- const connectSolana = reactQuery.useMutation(async ({ wallet, }) => {
30543
- try {
30544
- // try to connect silently first
30545
- await wallet.connector.autoConnect();
30546
- }
30547
- catch {
30548
- // if auto-connect fails (e.g. not authorized yet)
30549
- // fallback to connect via popup
30550
- await wallet.connector.connect();
30464
+ const connectSolana = reactQuery.useMutation({
30465
+ mutationFn: async ({ wallet, }) => {
30466
+ try {
30467
+ // try to connect silently first
30468
+ await wallet.connector.autoConnect();
30469
+ }
30470
+ catch {
30471
+ // if auto-connect fails (e.g. not authorized yet)
30472
+ // fallback to connect via popup
30473
+ await wallet.connector.connect();
30474
+ }
30475
+ const address = wallet.connector.wallet.accounts[0].address;
30476
+ return {
30477
+ wallet,
30478
+ address,
30479
+ };
30551
30480
  }
30552
- const address = wallet.connector.wallet.accounts[0].address;
30553
- return {
30554
- wallet,
30555
- address,
30556
- };
30557
30481
  });
30558
30482
  const disconnectSolana = React.useCallback(async () => {
30559
30483
  await connectedSolanaWallet.wallet?.connector.disconnect();
@@ -30628,7 +30552,7 @@ function useStellarWallets() {
30628
30552
  return;
30629
30553
  try {
30630
30554
  const { allowAllModules: initializeAllModules } = await import('@creit.tech/stellar-wallets-kit');
30631
- const { formatStellarWallet } = await Promise.resolve().then(function () { return require('./stellarService.client-7rBIc_IW.js'); });
30555
+ const { formatStellarWallet } = await Promise.resolve().then(function () { return require('./stellarService.client-ep6_7QVE.js'); });
30632
30556
  const modules = initializeAllModules();
30633
30557
  const promises = modules.map(async (module) => {
30634
30558
  const isAvailable = await module.isAvailable();
@@ -30656,12 +30580,14 @@ function useStellarWallets() {
30656
30580
  function useStellar() {
30657
30581
  const { wallets } = useStellarWallets();
30658
30582
  const connectedStellarWallet = useWalletStore((store) => store.connectedWalletsByChainType[squidTypes.ChainType.STELLAR]);
30659
- const connectStellar = reactQuery.useMutation(async ({ wallet, }) => {
30660
- const { address } = await wallet.connector.getAddress();
30661
- return {
30662
- wallet,
30663
- address,
30664
- };
30583
+ const connectStellar = reactQuery.useMutation({
30584
+ mutationFn: async ({ wallet, }) => {
30585
+ const { address } = await wallet.connector.getAddress();
30586
+ return {
30587
+ wallet,
30588
+ address,
30589
+ };
30590
+ }
30665
30591
  });
30666
30592
  const disconnectStellar = React.useCallback(async () => {
30667
30593
  await connectedStellarWallet.wallet?.connector.disconnect?.();
@@ -30713,22 +30639,24 @@ function useSui() {
30713
30639
  const recentSuiWalletId = useWalletStore((store) => store.recentConnectorIds[squidTypes.ChainType.SUI]);
30714
30640
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
30715
30641
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
30716
- const connectSui = reactQuery.useMutation(async ({ wallet, }) => {
30717
- let account;
30718
- try {
30719
- // try to connect silently first
30720
- account = await wallet.connector.connect({ silent: true });
30721
- }
30722
- catch {
30723
- // if auto-connect fails (e.g. not authorized yet)
30724
- // fallback to connect via popup
30725
- account = await wallet.connector.connect();
30642
+ const connectSui = reactQuery.useMutation({
30643
+ mutationFn: async ({ wallet, }) => {
30644
+ let account;
30645
+ try {
30646
+ // try to connect silently first
30647
+ account = await wallet.connector.connect({ silent: true });
30648
+ }
30649
+ catch {
30650
+ // if auto-connect fails (e.g. not authorized yet)
30651
+ // fallback to connect via popup
30652
+ account = await wallet.connector.connect();
30653
+ }
30654
+ return {
30655
+ wallet,
30656
+ address: account.account.address,
30657
+ account: account.account,
30658
+ };
30726
30659
  }
30727
- return {
30728
- wallet,
30729
- address: account.account.address,
30730
- account: account.account,
30731
- };
30732
30660
  });
30733
30661
  const disconnectSui = React.useCallback(async () => {
30734
30662
  await connectedSuiWallet.wallet?.connector.disconnect();
@@ -31037,12 +30965,14 @@ function useXrpl() {
31037
30965
  const recentXrplWalletId = useWalletStore((store) => store.recentConnectorIds[squidTypes.ChainType.XRPL]);
31038
30966
  const setConnectedWallet = useWalletStore((store) => store.setConnectedWallet);
31039
30967
  const disconnectWallet = useWalletStore((store) => store.disconnectWallet);
31040
- const connectXrpl = reactQuery.useMutation(async ({ wallet, }) => {
31041
- const xrplConnectedAddress = await wallet.connector.connect();
31042
- return {
31043
- wallet,
31044
- address: xrplConnectedAddress,
31045
- };
30968
+ const connectXrpl = reactQuery.useMutation({
30969
+ mutationFn: async ({ wallet, }) => {
30970
+ const xrplConnectedAddress = await wallet.connector.connect();
30971
+ return {
30972
+ wallet,
30973
+ address: xrplConnectedAddress,
30974
+ };
30975
+ }
31046
30976
  });
31047
30977
  const disconnectXrpl = React.useCallback(async () => {
31048
30978
  await connectedXrplWallet?.wallet?.connector.disconnect?.();
@@ -31429,18 +31359,19 @@ const useMultiChainWallet = (chain) => {
31429
31359
  /**
31430
31360
  * Change current network for desired chain
31431
31361
  */
31432
- const changeNetworkIfNeeded = reactQuery.useMutation(async () => {
31433
- const isNotOnDesiredChain = chain?.chainType === squidTypes.ChainType.EVM &&
31434
- currentEvmChain?.id !== Number(chain.chainId);
31435
- if (isNotOnDesiredChain) {
31436
- await switchChainAsync({
31437
- chainId: Number(chain.chainId),
31438
- });
31439
- }
31440
- // Implement keplr change network
31441
- // Looks like there are no method to do that at the moment
31442
- return false;
31443
- }, {
31362
+ const changeNetworkIfNeeded = reactQuery.useMutation({
31363
+ mutationFn: async () => {
31364
+ const isNotOnDesiredChain = chain?.chainType === squidTypes.ChainType.EVM &&
31365
+ currentEvmChain?.id !== Number(chain.chainId);
31366
+ if (isNotOnDesiredChain) {
31367
+ await switchChainAsync({
31368
+ chainId: Number(chain.chainId),
31369
+ });
31370
+ }
31371
+ // Implement keplr change network
31372
+ // Looks like there are no method to do that at the moment
31373
+ return false;
31374
+ },
31444
31375
  onError: async (error) => {
31445
31376
  if (error instanceof viem.UserRejectedRequestError) {
31446
31377
  return;
@@ -31452,7 +31383,7 @@ const useMultiChainWallet = (chain) => {
31452
31383
  provider,
31453
31384
  });
31454
31385
  }
31455
- },
31386
+ }
31456
31387
  });
31457
31388
  const isChainTypeConnected = React.useCallback((chainType) => {
31458
31389
  if (isGnosisConnected && chainType === squidTypes.ChainType.EVM) {
@@ -31800,51 +31731,53 @@ const useCosmos = () => {
31800
31731
  clientWindow?.removeEventListener("keplr_keystorechange", () => handleKeplrAccountChanged());
31801
31732
  };
31802
31733
  }, [handleKeplrAccountChanged, clientWindow]);
31803
- const connectCosmos = reactQuery.useMutation(async ({ chain, wallet, approveAllChains = true, }) => {
31804
- const chainInfos = getCosmosChainInfosObject(chain);
31805
- const cosmosWalletObject = wallet.connector().provider;
31806
- if (cosmosWalletObject) {
31807
- setCosmosChainId(chainInfos.chainId.toString());
31808
- try {
31809
- if (approveAllChains &&
31810
- typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31811
- "function") {
31812
- try {
31813
- const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31814
- const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31815
- const chainsToEnable = cosmosChains
31816
- .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31817
- .map((c) => c.chainId.toString());
31818
- await cosmosWalletObject.enable(chainsToEnable);
31734
+ const connectCosmos = reactQuery.useMutation({
31735
+ mutationFn: async ({ chain, wallet, approveAllChains = true, }) => {
31736
+ const chainInfos = getCosmosChainInfosObject(chain);
31737
+ const cosmosWalletObject = wallet.connector().provider;
31738
+ if (cosmosWalletObject) {
31739
+ setCosmosChainId(chainInfos.chainId.toString());
31740
+ try {
31741
+ if (approveAllChains &&
31742
+ typeof cosmosWalletObject.getChainInfosWithoutEndpoints ===
31743
+ "function") {
31744
+ try {
31745
+ const addedChains = await cosmosWalletObject.getChainInfosWithoutEndpoints();
31746
+ const addedChainIds = addedChains?.map((addedChain) => addedChain.chainId);
31747
+ const chainsToEnable = cosmosChains
31748
+ .filter((c) => addedChainIds?.includes(c.chainId.toString()))
31749
+ .map((c) => c.chainId.toString());
31750
+ await cosmosWalletObject.enable(chainsToEnable);
31751
+ }
31752
+ catch (error) {
31753
+ console.warn("Failed to get chain infos, falling back to single chain enable", error);
31754
+ await cosmosWalletObject.enable(chainInfos.chainId);
31755
+ }
31819
31756
  }
31820
- catch (error) {
31821
- console.warn("Failed to get chain infos, falling back to single chain enable", error);
31757
+ else {
31822
31758
  await cosmosWalletObject.enable(chainInfos.chainId);
31823
31759
  }
31760
+ const address = await getAddress({
31761
+ chainId: chain.chainId.toString(),
31762
+ cosmosWalletObject,
31763
+ wallet,
31764
+ });
31765
+ if (address) {
31766
+ updateWalletStore(wallet, cosmosWalletObject, address);
31767
+ return address;
31768
+ }
31824
31769
  }
31825
- else {
31826
- await cosmosWalletObject.enable(chainInfos.chainId);
31827
- }
31828
- const address = await getAddress({
31829
- chainId: chain.chainId.toString(),
31830
- cosmosWalletObject,
31831
- wallet,
31832
- });
31833
- if (address) {
31834
- updateWalletStore(wallet, cosmosWalletObject, address);
31835
- return address;
31770
+ catch (error) {
31771
+ await suggestChainOrThrow({
31772
+ chain,
31773
+ error,
31774
+ keplrTypeWallet: cosmosWalletObject,
31775
+ });
31776
+ return connectCosmos.mutateAsync({ chain, wallet });
31836
31777
  }
31837
31778
  }
31838
- catch (error) {
31839
- await suggestChainOrThrow({
31840
- chain,
31841
- error,
31842
- keplrTypeWallet: cosmosWalletObject,
31843
- });
31844
- return connectCosmos.mutateAsync({ chain, wallet });
31845
- }
31779
+ return undefined;
31846
31780
  }
31847
- return undefined;
31848
31781
  });
31849
31782
  const clearData = () => {
31850
31783
  disconnectWallet(squidTypes.ChainType.COSMOS);
@@ -31998,11 +31931,11 @@ const useSquidQueryClient = () => {
31998
31931
  const queryClient = reactQuery.useQueryClient();
31999
31932
  const invalidateQueries = (key) => {
32000
31933
  const prefixKey = getPrefixKey(key);
32001
- queryClient.invalidateQueries(prefixKey);
31934
+ queryClient.invalidateQueries({ queryKey: prefixKey });
32002
31935
  };
32003
31936
  const refetchQueries = (key) => {
32004
31937
  const prefixKey = getPrefixKey(key);
32005
- queryClient.refetchQueries(prefixKey);
31938
+ queryClient.refetchQueries({ queryKey: prefixKey });
32006
31939
  };
32007
31940
  const invalidateAndRefetchQueries = (key) => {
32008
31941
  invalidateQueries(key);
@@ -33509,17 +33442,19 @@ function useDepositAddress(squidRoute) {
33509
33442
  toggleDepositFlow(false);
33510
33443
  setDeposit(null);
33511
33444
  }, [toggleDepositFlow, setDeposit]);
33512
- const getRouteWithDeposit = reactQuery.useMutation(async ({ route }) => {
33513
- if (!squid)
33514
- throw new Error("Squid SDK not initialized");
33515
- const depositAddressResponse = (await squid.executeRoute({
33516
- signer: {},
33517
- route,
33518
- }));
33519
- setDeposit(depositAddressResponse);
33520
- return {
33521
- depositAddress: depositAddressResponse,
33522
- };
33445
+ const getRouteWithDeposit = reactQuery.useMutation({
33446
+ mutationFn: async ({ route }) => {
33447
+ if (!squid)
33448
+ throw new Error("Squid SDK not initialized");
33449
+ const depositAddressResponse = (await squid.executeRoute({
33450
+ signer: {},
33451
+ route,
33452
+ }));
33453
+ setDeposit(depositAddressResponse);
33454
+ return {
33455
+ depositAddress: depositAddressResponse,
33456
+ };
33457
+ }
33523
33458
  });
33524
33459
  return {
33525
33460
  isEnabled,
@@ -33603,53 +33538,55 @@ const useAllTokensWithBalanceForChainType = ({ chainType, address, direction, qu
33603
33538
  xrplTokens.length,
33604
33539
  stellarTokens.length,
33605
33540
  ]);
33606
- const query = reactQuery.useQuery(keys().allTokensBalance(address, chainType, direction), async () => {
33607
- // Return zero balances if no address
33608
- if (!address) {
33609
- const defaultTokens = placeholderData.tokens;
33541
+ const query = reactQuery.useQuery({
33542
+ queryKey: keys().allTokensBalance(address, chainType, direction),
33543
+ queryFn: async () => {
33544
+ // Return zero balances if no address
33545
+ if (!address) {
33546
+ const defaultTokens = placeholderData.tokens;
33547
+ return {
33548
+ tokens: defaultTokens,
33549
+ totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33550
+ };
33551
+ }
33552
+ let fetchedTokens = [];
33553
+ // Fetch tokens based on chain type
33554
+ switch (chainType) {
33555
+ case squidTypes.ChainType.EVM:
33556
+ fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33557
+ break;
33558
+ case squidTypes.ChainType.COSMOS:
33559
+ const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33560
+ fetchedTokens = await getAllCosmosBalances({
33561
+ addresses,
33562
+ cosmosChains,
33563
+ cosmosTokens,
33564
+ });
33565
+ break;
33566
+ case squidTypes.ChainType.SOLANA:
33567
+ fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33568
+ break;
33569
+ case squidTypes.ChainType.BTC:
33570
+ fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33571
+ break;
33572
+ case squidTypes.ChainType.SUI:
33573
+ fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33574
+ break;
33575
+ case squidTypes.ChainType.XRPL:
33576
+ fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33577
+ break;
33578
+ case squidTypes.ChainType.STELLAR:
33579
+ fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33580
+ break;
33581
+ default:
33582
+ fetchedTokens = placeholderData.tokens;
33583
+ break;
33584
+ }
33610
33585
  return {
33611
- tokens: defaultTokens,
33612
- totalUsdBalance: calculateTotalUsdBalanceUSD(defaultTokens),
33586
+ tokens: fetchedTokens,
33587
+ totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33613
33588
  };
33614
- }
33615
- let fetchedTokens = [];
33616
- // Fetch tokens based on chain type
33617
- switch (chainType) {
33618
- case squidTypes.ChainType.EVM:
33619
- fetchedTokens = await getAllEvmTokensBalance(evmTokens, address, evmChains);
33620
- break;
33621
- case squidTypes.ChainType.COSMOS:
33622
- const addresses = await getAllKeysForSupportedCosmosChains(cosmosChains.map((c) => c.chainId), keplrTypeWallet);
33623
- fetchedTokens = await getAllCosmosBalances({
33624
- addresses,
33625
- cosmosChains,
33626
- cosmosTokens,
33627
- });
33628
- break;
33629
- case squidTypes.ChainType.SOLANA:
33630
- fetchedTokens = await getAllSolanaTokensBalance(solanaTokens, address);
33631
- break;
33632
- case squidTypes.ChainType.BTC:
33633
- fetchedTokens = await getAllBitcoinTokensBalance(address, bitcoinTokens);
33634
- break;
33635
- case squidTypes.ChainType.SUI:
33636
- fetchedTokens = await getAllSuiTokensBalance(address, suiTokens, suiChains);
33637
- break;
33638
- case squidTypes.ChainType.XRPL:
33639
- fetchedTokens = await getAllXrplTokensBalance(address, xrplTokens, xrplChains);
33640
- break;
33641
- case squidTypes.ChainType.STELLAR:
33642
- fetchedTokens = await getAllStellarTokensBalance(address, stellarTokens, stellarChains);
33643
- break;
33644
- default:
33645
- fetchedTokens = placeholderData.tokens;
33646
- break;
33647
- }
33648
- return {
33649
- tokens: fetchedTokens,
33650
- totalUsdBalance: calculateTotalUsdBalanceUSD(fetchedTokens),
33651
- };
33652
- }, {
33589
+ },
33653
33590
  ...queryOptions,
33654
33591
  enabled: isQueryEnabled,
33655
33592
  });
@@ -33664,7 +33601,7 @@ const BALANCE_STALE_TIME = 60000; // 1 minute
33664
33601
  const BALANCE_CACHE_TIME = 300000; // 5 minutes
33665
33602
  const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33666
33603
  staleTime: BALANCE_STALE_TIME,
33667
- cacheTime: BALANCE_CACHE_TIME,
33604
+ gcTime: BALANCE_CACHE_TIME,
33668
33605
  refetchOnWindowFocus: true,
33669
33606
  refetchOnMount: true,
33670
33607
  }, } = {}) => {
@@ -33745,9 +33682,9 @@ const useAllConnectedWalletBalances = ({ direction, queryOptions = {
33745
33682
  }, [balanceQueries]);
33746
33683
  // Aggregate loading states
33747
33684
  const queryStates = React.useMemo(() => ({
33748
- isInitialLoading: Object.values(balanceQueries).some((q) => q.isInitialLoading),
33749
- isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33750
33685
  isLoading: Object.values(balanceQueries).some((q) => q.isLoading),
33686
+ isFetching: Object.values(balanceQueries).some((q) => q.isFetching),
33687
+ isPending: Object.values(balanceQueries).some((q) => q.isPending),
33751
33688
  isRefetching: Object.values(balanceQueries).some((q) => q.isRefetching),
33752
33689
  isError: Object.values(balanceQueries).some((q) => q.isError),
33753
33690
  isSuccess: Object.values(balanceQueries).every((q) => q.isSuccess),
@@ -33789,7 +33726,7 @@ function useNativeTokenForChain(chain) {
33789
33726
 
33790
33727
  const useEvmNativeBalance = ({ address, chain, }) => {
33791
33728
  const { isChainTypeConnected } = useWallet();
33792
- const { data: nativeEvmBalance, isLoading } = wagmi.useBalance({
33729
+ const { data: nativeEvmBalance, isPending } = wagmi.useBalance({
33793
33730
  address: address,
33794
33731
  chainId: Number(chain?.chainId),
33795
33732
  query: {
@@ -33811,13 +33748,13 @@ const useEvmNativeBalance = ({ address, chain, }) => {
33811
33748
  }, [nativeEvmBalance?.decimals, nativeEvmBalance?.value]);
33812
33749
  return {
33813
33750
  balance,
33814
- isLoading,
33751
+ isPending,
33815
33752
  };
33816
33753
  };
33817
33754
  const useCosmosNativeBalance = ({ address, chain, }) => {
33818
33755
  const { isConnected: isCosmosConnected } = useCosmosContext();
33819
33756
  const { nativeToken: nativeCosmosToken } = useNativeTokenForChain(chain);
33820
- const { balance: rawBalance, isLoading } = useCosmosBalance({
33757
+ const { balance: rawBalance, isPending } = useCosmosBalance({
33821
33758
  chain,
33822
33759
  token: nativeCosmosToken,
33823
33760
  userAddress: address,
@@ -33832,16 +33769,18 @@ const useCosmosNativeBalance = ({ address, chain, }) => {
33832
33769
  };
33833
33770
  }
33834
33771
  }, [nativeCosmosToken?.decimals, rawBalance]);
33835
- return { balance, isLoading };
33772
+ return { balance, isPending };
33836
33773
  };
33837
33774
  const useBitcoinNativeBalance = ({ chain, address, }) => {
33838
33775
  const { nativeToken } = useNativeTokenForChain(chain);
33839
- const { data: rawBalance = "0", isLoading } = reactQuery.useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33840
- if (!address || !nativeToken)
33841
- return "0";
33842
- const balance = await getBitcoinNativeBalance(address);
33843
- return formatBNToReadable(balance, nativeToken.decimals);
33844
- }, {
33776
+ const { data: rawBalance = "0", isPending } = reactQuery.useQuery({
33777
+ queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33778
+ queryFn: async () => {
33779
+ if (!address || !nativeToken)
33780
+ return "0";
33781
+ const balance = await getBitcoinNativeBalance(address);
33782
+ return formatBNToReadable(balance, nativeToken.decimals);
33783
+ },
33845
33784
  enabled: chain?.chainType === squidTypes.ChainType.BTC &&
33846
33785
  nativeToken?.decimals != null &&
33847
33786
  isWalletAddressValid(chain, address),
@@ -33860,15 +33799,17 @@ const useBitcoinNativeBalance = ({ chain, address, }) => {
33860
33799
  }, [nativeToken?.decimals, rawBalance]);
33861
33800
  return {
33862
33801
  balance,
33863
- isLoading,
33802
+ isPending,
33864
33803
  };
33865
33804
  };
33866
33805
  const useSolanaNativeBalance = ({ chain, address, }) => {
33867
33806
  const { nativeToken } = useNativeTokenForChain(chain);
33868
- const { data: rawBalance, isLoading } = reactQuery.useQuery(keys().balance(chain?.chainId, nativeToken?.address, address), async () => {
33869
- const balance = await getSolanaNativeBalance(address);
33870
- return formatBNToReadable(balance, nativeToken.decimals);
33871
- }, {
33807
+ const { data: rawBalance, isPending } = reactQuery.useQuery({
33808
+ queryKey: keys().balance(chain?.chainId, nativeToken?.address, address),
33809
+ queryFn: async () => {
33810
+ const balance = await getSolanaNativeBalance(address);
33811
+ return formatBNToReadable(balance, nativeToken.decimals);
33812
+ },
33872
33813
  enabled: !!address &&
33873
33814
  nativeToken?.decimals != null &&
33874
33815
  chain?.chainType === squidTypes.ChainType.SOLANA,
@@ -33887,12 +33828,12 @@ const useSolanaNativeBalance = ({ chain, address, }) => {
33887
33828
  }, [nativeToken?.decimals, rawBalance]);
33888
33829
  return {
33889
33830
  balance,
33890
- isLoading,
33831
+ isPending,
33891
33832
  };
33892
33833
  };
33893
33834
  const useSuiNativeBalance = ({ address, chain, }) => {
33894
33835
  const { nativeToken } = useNativeTokenForChain(chain);
33895
- const { balance: rawBalance, isLoading } = useSuiBalance({
33836
+ const { balance: rawBalance, isPending } = useSuiBalance({
33896
33837
  chain,
33897
33838
  token: nativeToken,
33898
33839
  userAddress: address,
@@ -33907,12 +33848,12 @@ const useSuiNativeBalance = ({ address, chain, }) => {
33907
33848
  }, [nativeToken?.decimals, rawBalance]);
33908
33849
  return {
33909
33850
  balance,
33910
- isLoading,
33851
+ isPending,
33911
33852
  };
33912
33853
  };
33913
33854
  const useXrplNativeBalance = ({ address, chain, }) => {
33914
33855
  const { nativeToken } = useNativeTokenForChain(chain);
33915
- const { balance: rawBalance, isLoading } = useXrplBalance({
33856
+ const { balance: rawBalance, isPending } = useXrplBalance({
33916
33857
  chain,
33917
33858
  token: nativeToken,
33918
33859
  userAddress: address,
@@ -33928,12 +33869,12 @@ const useXrplNativeBalance = ({ address, chain, }) => {
33928
33869
  }, [nativeToken?.decimals, rawBalance]);
33929
33870
  return {
33930
33871
  balance,
33931
- isLoading,
33872
+ isPending,
33932
33873
  };
33933
33874
  };
33934
33875
  const useStellarNativeBalance = ({ address, chain, }) => {
33935
33876
  const { nativeToken } = useNativeTokenForChain(chain);
33936
- const { balance: rawBalance, isLoading } = useStellarBalance({
33877
+ const { balance: rawBalance, isPending } = useStellarBalance({
33937
33878
  chain,
33938
33879
  token: nativeToken,
33939
33880
  userAddress: address,
@@ -33949,7 +33890,7 @@ const useStellarNativeBalance = ({ address, chain, }) => {
33949
33890
  }, [nativeToken?.decimals, rawBalance]);
33950
33891
  return {
33951
33892
  balance,
33952
- isLoading,
33893
+ isPending,
33953
33894
  };
33954
33895
  };
33955
33896
  const useNativeBalance = (chain) => {
@@ -33957,28 +33898,28 @@ const useNativeBalance = (chain) => {
33957
33898
  const { data: cosmosAddressForChain } = useCosmosForChain(chain);
33958
33899
  // Cosmos is a special case because the address changes on every chain
33959
33900
  // so we can't use the default cosmos connected address
33960
- const { balance: nativeCosmosBalance, isLoading: isCosmosLoading } = useCosmosNativeBalance({
33901
+ const { balance: nativeCosmosBalance, isPending: isCosmosPending } = useCosmosNativeBalance({
33961
33902
  address: cosmosAddressForChain,
33962
33903
  chain,
33963
33904
  });
33964
- const { balance: nativeEvmBalance, isLoading: isEvmLoading } = useEvmNativeBalance({ address: connectedAddresses[squidTypes.ChainType.EVM], chain });
33965
- const { balance: nativeBitcoinBalance, isLoading: isBitcoinLoading } = useBitcoinNativeBalance({
33905
+ const { balance: nativeEvmBalance, isPending: isEvmPending } = useEvmNativeBalance({ address: connectedAddresses[squidTypes.ChainType.EVM], chain });
33906
+ const { balance: nativeBitcoinBalance, isPending: isBitcoinPending } = useBitcoinNativeBalance({
33966
33907
  address: connectedAddresses[squidTypes.ChainType.BTC],
33967
33908
  chain,
33968
33909
  });
33969
- const { balance: nativeSolanaBalance, isLoading: isSolanaLoading } = useSolanaNativeBalance({
33910
+ const { balance: nativeSolanaBalance, isPending: isSolanaPending } = useSolanaNativeBalance({
33970
33911
  address: connectedAddresses[squidTypes.ChainType.SOLANA],
33971
33912
  chain,
33972
33913
  });
33973
- const { balance: nativeSuiBalance, isLoading: isSuiLoading } = useSuiNativeBalance({
33914
+ const { balance: nativeSuiBalance, isPending: isSuiPending } = useSuiNativeBalance({
33974
33915
  address: connectedAddresses[squidTypes.ChainType.SUI],
33975
33916
  chain,
33976
33917
  });
33977
- const { balance: nativeXrplBalance, isLoading: isXrpLoading } = useXrplNativeBalance({
33918
+ const { balance: nativeXrplBalance, isPending: isXrplPending } = useXrplNativeBalance({
33978
33919
  address: connectedAddresses[squidTypes.ChainType.XRPL],
33979
33920
  chain,
33980
33921
  });
33981
- const { balance: nativeStellarBalance, isLoading: isStellarLoading } = useStellarNativeBalance({
33922
+ const { balance: nativeStellarBalance, isPending: isStellarPending } = useStellarNativeBalance({
33982
33923
  address: connectedAddresses[squidTypes.ChainType.STELLAR],
33983
33924
  chain,
33984
33925
  });
@@ -34023,36 +33964,36 @@ const useNativeBalance = (chain) => {
34023
33964
  nativeXrplBalance,
34024
33965
  nativeStellarBalance,
34025
33966
  ]);
34026
- const isLoading = React.useMemo(() => {
33967
+ const isPending = React.useMemo(() => {
34027
33968
  if (!chain?.chainType)
34028
33969
  return false;
34029
33970
  switch (chain.chainType) {
34030
33971
  case squidTypes.ChainType.EVM:
34031
- return isEvmLoading;
33972
+ return isEvmPending;
34032
33973
  case squidTypes.ChainType.COSMOS:
34033
- return isCosmosLoading;
33974
+ return isCosmosPending;
34034
33975
  case squidTypes.ChainType.BTC:
34035
- return isBitcoinLoading;
33976
+ return isBitcoinPending;
34036
33977
  case squidTypes.ChainType.SOLANA:
34037
- return isSolanaLoading;
33978
+ return isSolanaPending;
34038
33979
  case squidTypes.ChainType.SUI:
34039
- return isSuiLoading;
33980
+ return isSuiPending;
34040
33981
  case squidTypes.ChainType.XRPL:
34041
- return isXrpLoading;
33982
+ return isXrplPending;
34042
33983
  case squidTypes.ChainType.STELLAR:
34043
- return isStellarLoading;
33984
+ return isStellarPending;
34044
33985
  }
34045
33986
  }, [
34046
33987
  chain?.chainType,
34047
- isEvmLoading,
34048
- isCosmosLoading,
34049
- isBitcoinLoading,
34050
- isSolanaLoading,
34051
- isSuiLoading,
34052
- isXrpLoading,
34053
- isStellarLoading,
33988
+ isEvmPending,
33989
+ isCosmosPending,
33990
+ isBitcoinPending,
33991
+ isSolanaPending,
33992
+ isSuiPending,
33993
+ isXrplPending,
33994
+ isStellarPending,
34054
33995
  ]);
34055
- return { nativeBalance, nativeBalanceFormatted, isLoading };
33996
+ return { nativeBalance, nativeBalanceFormatted, isPending };
34056
33997
  };
34057
33998
 
34058
33999
  const DEFAULT_REFRESH_INTERVAL_MS = 15000;
@@ -34061,7 +34002,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34061
34002
  const isNativeToken = token?.address.toLowerCase() === nativeEvmTokenAddress.toLowerCase();
34062
34003
  const userAddressParsed = userAddress;
34063
34004
  // Only fetch using useBalance if it's a native token
34064
- const { data: nativeBalance, isLoading: isNativeTokenLoading } = wagmi.useBalance({
34005
+ const { data: nativeBalance, isPending: isNativeTokenPending } = wagmi.useBalance({
34065
34006
  address: userAddressParsed,
34066
34007
  chainId: Number(chain?.chainId),
34067
34008
  query: {
@@ -34077,7 +34018,7 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34077
34018
  });
34078
34019
  // Only fetch using useReadContract if it's not a native token
34079
34020
  // This is temporary, because of wagmi error: https://github.com/wevm/wagmi/issues/4353
34080
- const { data: erc20Balance, isLoading: isErc20Loading } = wagmi.useReadContract({
34021
+ const { data: erc20Balance, isPending: isErc20Pending } = wagmi.useReadContract({
34081
34022
  address: token?.address,
34082
34023
  abi: viem.erc20Abi,
34083
34024
  functionName: "balanceOf",
@@ -34093,15 +34034,15 @@ const useEvmBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34093
34034
  },
34094
34035
  });
34095
34036
  const balance = isNativeToken ? nativeBalance?.value : erc20Balance;
34096
- const isLoading = isNativeToken ? isNativeTokenLoading : isErc20Loading;
34037
+ const isPending = isNativeToken ? isNativeTokenPending : isErc20Pending;
34097
34038
  const formattedBalance = balance != null && token?.decimals != null
34098
34039
  ? formatBNToReadable(balance, token.decimals)
34099
34040
  : "0";
34100
- return { balance: formattedBalance, isLoading };
34041
+ return { balance: formattedBalance, isPending };
34101
34042
  };
34102
34043
  const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34103
34044
  const { isConnected } = useCosmosContext();
34104
- const { data: balance = "0", isLoading } = reactQuery.useQuery({
34045
+ const { data: balance = "0", isPending } = reactQuery.useQuery({
34105
34046
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34106
34047
  queryFn: async () => {
34107
34048
  if (!userAddress || !token || chain?.chainType !== squidTypes.ChainType.COSMOS) {
@@ -34121,10 +34062,10 @@ const useCosmosBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34121
34062
  refetchInterval: refreshIntervalMs,
34122
34063
  retry: 2,
34123
34064
  });
34124
- return { balance, isLoading };
34065
+ return { balance, isPending };
34125
34066
  };
34126
34067
  const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34127
- const { data: balance = "0", isLoading } = reactQuery.useQuery({
34068
+ const { data: balance = "0", isPending } = reactQuery.useQuery({
34128
34069
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34129
34070
  queryFn: async () => {
34130
34071
  if (!userAddress || !token)
@@ -34139,11 +34080,11 @@ const useSolanaBalance = ({ chain, token, userAddress, enabled = true, refreshIn
34139
34080
  refetchInterval: refreshIntervalMs,
34140
34081
  retry: 2,
34141
34082
  });
34142
- return { balance, isLoading };
34083
+ return { balance, isPending };
34143
34084
  };
34144
34085
  // TODO: implement fetching balances for all bitcoin tokens
34145
34086
  const useBitcoinBalance = ({ userAddress, chain, }) => {
34146
- const { balance: balanceBn, isLoading } = useBitcoinNativeBalance({
34087
+ const { balance: balanceBn, isPending } = useBitcoinNativeBalance({
34147
34088
  address: userAddress,
34148
34089
  chain,
34149
34090
  });
@@ -34152,10 +34093,10 @@ const useBitcoinBalance = ({ userAddress, chain, }) => {
34152
34093
  return "0";
34153
34094
  return formatBNToReadable(balanceBn?.value, balanceBn?.decimals);
34154
34095
  }, [balanceBn]);
34155
- return { balance, isLoading };
34096
+ return { balance, isPending };
34156
34097
  };
34157
34098
  const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34158
- const { data: balance = "0", isLoading } = reactQuery.useQuery({
34099
+ const { data: balance = "0", isPending } = reactQuery.useQuery({
34159
34100
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34160
34101
  queryFn: async () => {
34161
34102
  if (!userAddress ||
@@ -34175,10 +34116,10 @@ const useSuiBalance = ({ chain, token, userAddress, enabled = true, refreshInter
34175
34116
  refetchInterval: refreshIntervalMs,
34176
34117
  retry: 2,
34177
34118
  });
34178
- return { balance, isLoading };
34119
+ return { balance, isPending };
34179
34120
  };
34180
34121
  const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34181
- const { data: balance = "0", isLoading } = reactQuery.useQuery({
34122
+ const { data: balance = "0", isPending } = reactQuery.useQuery({
34182
34123
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34183
34124
  queryFn: async () => {
34184
34125
  if (!userAddress || !token || !chain)
@@ -34195,10 +34136,10 @@ const useXrplBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs
34195
34136
  refetchInterval: refreshIntervalMs,
34196
34137
  retry: 2,
34197
34138
  });
34198
- return { balance, isLoading };
34139
+ return { balance, isPending };
34199
34140
  };
34200
34141
  const useStellarBalance = ({ userAddress, chain, enabled, token, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS, }) => {
34201
- const { data: balance = "0", isLoading } = reactQuery.useQuery({
34142
+ const { data: balance = "0", isPending } = reactQuery.useQuery({
34202
34143
  queryKey: keys().balance(chain?.chainId, token?.address, userAddress),
34203
34144
  queryFn: async () => {
34204
34145
  if (!userAddress || !token || !chain)
@@ -34215,7 +34156,7 @@ const useStellarBalance = ({ userAddress, chain, enabled, token, refreshInterval
34215
34156
  refetchInterval: refreshIntervalMs,
34216
34157
  retry: 2,
34217
34158
  });
34218
- return { balance, isLoading };
34159
+ return { balance, isPending };
34219
34160
  };
34220
34161
 
34221
34162
  /**
@@ -34336,7 +34277,7 @@ const useMultipleTokenPrices = (tokens) => {
34336
34277
  return {
34337
34278
  tokenPrices,
34338
34279
  getTokenPrice,
34339
- isLoading: coinGeckoQuery.isLoading,
34280
+ isPending: coinGeckoQuery.isPending,
34340
34281
  isError: coinGeckoQuery.isError,
34341
34282
  error: coinGeckoQuery.error,
34342
34283
  refetch: coinGeckoQuery.refetch,
@@ -34485,13 +34426,17 @@ const fetchTokensData = async (tokens) => {
34485
34426
 
34486
34427
  // Coingecko has a limit for some queries for multiple tokens, not sure what it is, but let's use 100 for now
34487
34428
  const useHistoricalData = (coingeckoId, timeFrame) => {
34488
- return reactQuery.useQuery(keys().historicalData(coingeckoId, timeFrame), () => fetchHistoricalData(coingeckoId, timeFrame), {
34429
+ return reactQuery.useQuery({
34430
+ queryKey: keys().historicalData(coingeckoId, timeFrame),
34431
+ queryFn: () => fetchHistoricalData(coingeckoId, timeFrame),
34489
34432
  staleTime: 5 * 60 * 1000,
34490
34433
  enabled: !!coingeckoId,
34491
34434
  });
34492
34435
  };
34493
34436
  const useTokensData = (tokens) => {
34494
- return reactQuery.useQuery(keys().tokensData(tokens), () => fetchTokensData(tokens), {
34437
+ return reactQuery.useQuery({
34438
+ queryKey: keys().tokensData(tokens),
34439
+ queryFn: () => fetchTokensData(tokens),
34495
34440
  staleTime: 60 * 1000,
34496
34441
  enabled: !!tokens && tokens.length > 0,
34497
34442
  });
@@ -34796,7 +34741,7 @@ function useSendTransactionGas({ chain, token, from, }) {
34796
34741
  }
34797
34742
 
34798
34743
  function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34799
- const { data: estimatedGas = BigInt(0), isLoading } = useSendTransactionGas({
34744
+ const { data: estimatedGas = BigInt(0), isPending } = useSendTransactionGas({
34800
34745
  chain,
34801
34746
  token,
34802
34747
  from,
@@ -34841,7 +34786,7 @@ function useEstimateSendTransaction({ chain, token, amount, balance, from, }) {
34841
34786
  return {
34842
34787
  estimatedGas,
34843
34788
  isBalanceEnough,
34844
- isLoading,
34789
+ isPending,
34845
34790
  isNativeBalanceEnoughToPayGasFees,
34846
34791
  minAmountValueWarnMsg,
34847
34792
  };
@@ -35087,6 +35032,126 @@ async function sendTransactionStellar({ amount, signer, to, token, chain, }) {
35087
35032
  };
35088
35033
  }
35089
35034
 
35035
+ // Prevent fetching too soon after the first successful request.
35036
+ const DEFAULT_STALE_TIME = 8000;
35037
+ const defaultOptions = {
35038
+ queries: {
35039
+ staleTime: DEFAULT_STALE_TIME,
35040
+ refetchOnWindowFocus: false,
35041
+ retry: false,
35042
+ retryOnMount: false,
35043
+ },
35044
+ };
35045
+
35046
+ const queryClient = new reactQuery.QueryClient({ defaultOptions });
35047
+ const verifyIntegratorIdValidity = (integratorId) => {
35048
+ if (!integratorId) {
35049
+ throw new Error("Integrator ID is required");
35050
+ }
35051
+ };
35052
+ const SquidProvider = ({ children, config, placeholder, }) => {
35053
+ verifyIntegratorIdValidity(config.integratorId);
35054
+ const [wagmiConfig, setWagmiConfig] = React.useState();
35055
+ const sdkInitializedRef = React.useRef(false);
35056
+ const initializeSdk = React.useCallback(async () => {
35057
+ if (sdkInitializedRef.current) {
35058
+ return;
35059
+ }
35060
+ sdkInitializedRef.current = true;
35061
+ try {
35062
+ const squid = new sdk.Squid({
35063
+ integratorId: config.integratorId,
35064
+ baseUrl: config.apiUrl ?? squidApiBaseUrl,
35065
+ });
35066
+ const [sdkInfoResponse, assetsColorsResponse] = await Promise.allSettled([
35067
+ squid.init(),
35068
+ fetchAssetsColors(),
35069
+ ]);
35070
+ if (sdkInfoResponse.status === "rejected") {
35071
+ throw sdkInfoResponse.reason;
35072
+ }
35073
+ if (assetsColorsResponse.status === "fulfilled") {
35074
+ useAssetsColorsStore.setState(assetsColorsResponse.value);
35075
+ initializeSquidWithAssetsColors(squid, assetsColorsResponse.value);
35076
+ }
35077
+ const shouldResetSwapRouteStore =
35078
+ // reset swap route if specified in config
35079
+ !config?.loadPreviousStateFromLocalStorage ||
35080
+ // or if initial assets are provided
35081
+ !isEmptyObject(config.initialAssets?.from) ||
35082
+ !isEmptyObject(config.initialAssets?.to);
35083
+ if (shouldResetSwapRouteStore) {
35084
+ useSwapRoutePersistStore.setState({
35085
+ swapRoute: undefined,
35086
+ });
35087
+ }
35088
+ useSquidStore.setState((_) => ({
35089
+ squid,
35090
+ maintenanceMode: { active: false, message: undefined },
35091
+ }));
35092
+ const newWagmiConfig = createWagmiConfig(squid.chains);
35093
+ setWagmiConfig(newWagmiConfig);
35094
+ useConfigStore.setState({
35095
+ isInitialized: true,
35096
+ config: getConfigWithDefaults(config),
35097
+ });
35098
+ }
35099
+ catch (error) {
35100
+ const isAxios503Error = error.isAxiosError &&
35101
+ error.response?.status === 503;
35102
+ if (isAxios503Error) {
35103
+ const maintenanceMessage = error.response?.data
35104
+ ?.message ?? undefined;
35105
+ // Even with an error, we want wagmi to be defined so that we can display the maintenance mode layout
35106
+ // Create wagmi config with mainnet as fallback in maintenance mode
35107
+ const newWagmiConfig = wagmi.createConfig({
35108
+ chains: [chains$1.mainnet],
35109
+ connectors: [connectors.injected()],
35110
+ transports: {
35111
+ [chains$1.mainnet.id]: wagmi.http(),
35112
+ },
35113
+ });
35114
+ setWagmiConfig(newWagmiConfig);
35115
+ useConfigStore.setState({
35116
+ isInitialized: false,
35117
+ config: getConfigWithDefaults(config),
35118
+ });
35119
+ useSquidStore.setState({
35120
+ squid: undefined,
35121
+ maintenanceMode: {
35122
+ active: true,
35123
+ message: maintenanceMessage,
35124
+ },
35125
+ });
35126
+ }
35127
+ else {
35128
+ console.error("Error initializing SDK:", error);
35129
+ }
35130
+ }
35131
+ }, [config]);
35132
+ React.useEffect(() => {
35133
+ initializeSdk();
35134
+ }, [initializeSdk]);
35135
+ return wagmiConfig ? (React.createElement(wagmi.WagmiProvider, { reconnectOnMount: false, config: wagmiConfig },
35136
+ React.createElement(reactQuery.QueryClientProvider, { client: queryClient },
35137
+ React.createElement(StellarProvider, null,
35138
+ React.createElement(EvmProvider, null,
35139
+ React.createElement(XrplProvider, null,
35140
+ React.createElement(SuiProvider, null,
35141
+ React.createElement(SolanaProvider, null,
35142
+ React.createElement(BitcoinProvider, null,
35143
+ React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
35144
+ };
35145
+
35146
+ const para = new Para("beta_c529f95c6a31bfb50487b0929a19b682");
35147
+ const connector = wagmiV2Integration.paraConnector({
35148
+ para,
35149
+ appName: SQUID_METADATA.name,
35150
+ isGuestModeEnabled: false,
35151
+ hideWallets: true,
35152
+ options: {},
35153
+ queryClient: queryClient,
35154
+ });
35090
35155
  const createWagmiConfig = (squidChains) => {
35091
35156
  const filteredEvmChains = squidChains.filter((chain) => chain.chainType === squidTypes.ChainType.EVM);
35092
35157
  if (filteredEvmChains.length === 0) {
@@ -35142,6 +35207,8 @@ const createWagmiConfig = (squidChains) => {
35142
35207
  description: SQUID_METADATA.description,
35143
35208
  },
35144
35209
  }),
35210
+ // @ts-expect-error - TODO: fix types
35211
+ connector,
35145
35212
  ],
35146
35213
  });
35147
35214
  };
@@ -35424,7 +35491,9 @@ function useSendTransaction({ to, amount, token, chain, }) {
35424
35491
  });
35425
35492
  },
35426
35493
  onSuccess: (tx, variables) => {
35427
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balance));
35494
+ queryClient.invalidateQueries({
35495
+ queryKey: getPrefixKey(QueryKeys.Balance),
35496
+ });
35428
35497
  setTransactionState(variables.id, tx);
35429
35498
  persistTransaction({
35430
35499
  txType: exports.HistoryTxType.SEND,
@@ -35751,9 +35820,10 @@ const useAllTransactionsStatus = ({ enabled }) => {
35751
35820
  queryKey: keys().fiatToCryptoStatus(data.orderId),
35752
35821
  retry: TX_STATUS_CONSTANTS.RETRY_COUNT,
35753
35822
  retryDelay: TX_STATUS_CONSTANTS.RETRY_DELAY,
35754
- refetchInterval: (data) => {
35755
- if (data?.status &&
35756
- FINAL_TRANSACTION_STATUSES.includes(data.status)) {
35823
+ refetchInterval: (query) => {
35824
+ const { state } = query;
35825
+ if (state.data?.status &&
35826
+ FINAL_TRANSACTION_STATUSES.includes(state.data.status)) {
35757
35827
  return false;
35758
35828
  }
35759
35829
  return TX_STATUS_CONSTANTS.REFETCH_INTERVAL;
@@ -35813,7 +35883,7 @@ const useAllTransactionsStatus = ({ enabled }) => {
35813
35883
  queries: enabled && config.apiUrl ? statusQueries : [],
35814
35884
  });
35815
35885
  return {
35816
- isLoading: queries.some((q) => q.isLoading),
35886
+ isPending: queries.some((q) => q.isPending),
35817
35887
  isError: queries.some((q) => q.isError),
35818
35888
  data: queries.map((q) => q.data).filter(Boolean),
35819
35889
  };
@@ -36072,16 +36142,18 @@ const useApproval = ({ squidRoute, }) => {
36072
36142
  * On Error: Showing the error message if any
36073
36143
  * @returns {boolean} approved
36074
36144
  */
36075
- const routeApproved = reactQuery.useQuery(keys().routeApproved(squidRoute, allowanceInWei), async () => {
36076
- // Approval is only needed for EVM chains
36077
- if (getChainType(squidRoute?.params.fromChain) === squidTypes.ChainType.EVM) {
36078
- return hasAllowance;
36079
- }
36080
- return true;
36081
- }, {
36145
+ const routeApproved = reactQuery.useQuery({
36146
+ queryKey: keys().routeApproved(squidRoute, allowanceInWei),
36147
+ queryFn: async () => {
36148
+ // Approval is only needed for EVM chains
36149
+ if (getChainType(squidRoute?.params.fromChain) === squidTypes.ChainType.EVM) {
36150
+ return hasAllowance;
36151
+ }
36152
+ return true;
36153
+ },
36082
36154
  enabled: !!squidRoute &&
36083
36155
  !!sourceUserAddress &&
36084
- !allowanceQuery?.isLoading &&
36156
+ !allowanceQuery?.isPending &&
36085
36157
  allowanceQuery?.isFetched,
36086
36158
  });
36087
36159
  // USDT has a very specific way of handling approvals
@@ -36170,81 +36242,84 @@ const useApproval = ({ squidRoute, }) => {
36170
36242
  /**
36171
36243
  * Manually approve route if necessary
36172
36244
  */
36173
- const approveRoute = reactQuery.useMutation(async () => {
36174
- try {
36175
- if (fromToken?.address === nativeEvmTokenAddress) {
36176
- return true;
36177
- }
36178
- if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36179
- await approveSpecificTokenToZero(fromToken);
36180
- try {
36181
- // If needed, we can switch the chain here
36182
- // If already on the correct chain, this will do nothing
36183
- await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36184
- }
36185
- catch (error) {
36186
- console.error("Error switching network:", error);
36245
+ const approveRoute = reactQuery.useMutation({
36246
+ mutationFn: async () => {
36247
+ try {
36248
+ if (fromToken?.address === nativeEvmTokenAddress) {
36249
+ return true;
36187
36250
  }
36188
- let approveTx;
36189
- if (useIcs20) {
36190
- const channel = squidRoute.estimate.actions[0].data
36191
- .ibcChannel;
36192
- const ics20Interface = new ethers.ethers.Interface(ics20Abi);
36193
- const approveData = ics20Interface.encodeFunctionData("approve", [
36194
- squidRoute.params.fromAddress,
36195
- [
36196
- {
36197
- sourcePort: "transfer",
36198
- sourceChannel: channel,
36199
- spendLimit: [
36200
- {
36201
- denom: squidRoute.estimate.actions[0].fromToken
36202
- .originalAddress,
36203
- amount: squidRoute.params.fromAmount,
36204
- },
36205
- ],
36206
- allowList: [],
36207
- allowedPacketData: ["*"],
36251
+ if (!!squidRoute && walletClient && fromToken && evmSigner && squid) {
36252
+ await approveSpecificTokenToZero(fromToken);
36253
+ try {
36254
+ // If needed, we can switch the chain here
36255
+ // If already on the correct chain, this will do nothing
36256
+ await switchChainAsync({ chainId: Number(fromChain?.chainId) });
36257
+ }
36258
+ catch (error) {
36259
+ console.error("Error switching network:", error);
36260
+ }
36261
+ let approveTx;
36262
+ if (useIcs20) {
36263
+ const channel = squidRoute.estimate.actions[0].data
36264
+ .ibcChannel;
36265
+ const ics20Interface = new ethers.ethers.Interface(ics20Abi);
36266
+ const approveData = ics20Interface.encodeFunctionData("approve", [
36267
+ squidRoute.params.fromAddress,
36268
+ [
36269
+ {
36270
+ sourcePort: "transfer",
36271
+ sourceChannel: channel,
36272
+ spendLimit: [
36273
+ {
36274
+ denom: squidRoute.estimate.actions[0].fromToken
36275
+ .originalAddress,
36276
+ amount: squidRoute.params.fromAmount,
36277
+ },
36278
+ ],
36279
+ allowList: [],
36280
+ allowedPacketData: ["*"],
36281
+ },
36282
+ ],
36283
+ ]);
36284
+ approveTx = await evmSigner.sendTransaction({
36285
+ to: squidRoute.transactionRequest.target,
36286
+ data: approveData,
36287
+ value: "0",
36288
+ gasLimit: squidRoute.transactionRequest
36289
+ .gasLimit,
36290
+ gasPrice: squidRoute.transactionRequest
36291
+ .gasPrice,
36292
+ });
36293
+ }
36294
+ else {
36295
+ approveTx = await squid.approveRoute({
36296
+ route: squidRoute,
36297
+ signer: evmSigner,
36298
+ // For security reasons, we don't want to allow infinite approvals in our frontends
36299
+ executionSettings: {
36300
+ infiniteApproval: false,
36208
36301
  },
36209
- ],
36210
- ]);
36211
- approveTx = await evmSigner.sendTransaction({
36212
- to: squidRoute.transactionRequest.target,
36213
- data: approveData,
36214
- value: "0",
36215
- gasLimit: squidRoute.transactionRequest
36216
- .gasLimit,
36217
- gasPrice: squidRoute.transactionRequest
36218
- .gasPrice,
36219
- });
36220
- }
36221
- else {
36222
- approveTx = await squid.approveRoute({
36223
- route: squidRoute,
36224
- signer: evmSigner,
36225
- // For security reasons, we don't want to allow infinite approvals in our frontends
36226
- executionSettings: {
36227
- infiniteApproval: false,
36228
- },
36229
- });
36230
- }
36231
- if (isProblematicConnector(activeConnector)) {
36232
- await sleep(3_000);
36302
+ });
36303
+ }
36304
+ if (isProblematicConnector(activeConnector)) {
36305
+ await sleep(3_000);
36306
+ }
36307
+ await approveTx?.wait();
36308
+ return true;
36233
36309
  }
36234
- await approveTx?.wait();
36235
- return true;
36310
+ return false;
36236
36311
  }
36237
- return false;
36238
- }
36239
- catch (error) {
36240
- // Keep the error in the console to debug future issues
36241
- console.error(error);
36242
- return false;
36243
- }
36244
- }, {
36312
+ catch (error) {
36313
+ // Keep the error in the console to debug future issues
36314
+ console.error(error);
36315
+ return false;
36316
+ }
36317
+ },
36245
36318
  onSuccess: async () => {
36246
36319
  await allowanceQuery?.refetch();
36247
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.RouteApproved));
36320
+ queryClient.invalidateQueries({
36321
+ queryKey: getPrefixKey(QueryKeys.RouteApproved),
36322
+ });
36248
36323
  // After an approval, we refetch the transaction query with all required parameters
36249
36324
  // This is to ensure we're using the latest expiry timestamp
36250
36325
  if (squidRoute) {
@@ -39364,8 +39439,10 @@ const useExecuteTransaction = (squidRoute) => {
39364
39439
  }
39365
39440
  }, [cosmosSigner, fromChain]);
39366
39441
  const resetQueriesAfterTxSigned = () => {
39367
- queryClient.refetchQueries(getPrefixKey(QueryKeys.Balance));
39368
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Transaction));
39442
+ queryClient.refetchQueries({ queryKey: getPrefixKey(QueryKeys.Balance) });
39443
+ queryClient.invalidateQueries({
39444
+ queryKey: getPrefixKey(QueryKeys.Transaction),
39445
+ });
39369
39446
  };
39370
39447
  const dispatchSignatureRequestEvent = React.useCallback((route) => {
39371
39448
  WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
@@ -39383,62 +39460,64 @@ const useExecuteTransaction = (squidRoute) => {
39383
39460
  txHash,
39384
39461
  }, findToken);
39385
39462
  }, [findToken]);
39386
- const swapMutationCosmos = reactQuery.useMutation(async ({ id, route }) => {
39387
- const fromChainId = route?.params.fromChain;
39388
- if (cosmosSigner && fromChainId) {
39389
- try {
39390
- const signingClient = await getCosmosSignerClient();
39391
- const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39392
- if (signerAddress && signingClient && route) {
39393
- dispatchSignatureRequestEvent(route);
39394
- const tx$1 = (await squid?.executeRoute({
39395
- signer: signingClient,
39396
- signerAddress,
39397
- route,
39398
- }));
39399
- // set the tx state to loading, as soon as user signed the tx
39400
- setTransactionState({
39401
- txHash: "",
39402
- route,
39403
- status: exports.TransactionStatus.ONGOING,
39404
- sourceStatus: exports.TransactionStatus.ONGOING,
39405
- id,
39406
- });
39407
- // broadcast the signed tx to get hash and listen to events
39408
- const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39409
- const hash = response.transactionHash;
39410
- if (hash) {
39411
- resetQueriesAfterTxSigned();
39412
- }
39413
- // Dispatch event so it can be listened from outside the widget
39414
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39415
- const txParams = setTransactionState({
39416
- route,
39417
- txHash: hash,
39418
- userAddress: sourceUserAddress,
39419
- status: exports.TransactionStatus.ONGOING,
39420
- sourceStatus: exports.TransactionStatus.ONGOING,
39421
- axelarUrl: undefined,
39422
- id,
39423
- });
39424
- if (txParams) {
39425
- addSwapTransaction({
39426
- ...txParams,
39427
- params: route.params,
39428
- estimate: route.estimate,
39463
+ const swapMutationCosmos = reactQuery.useMutation({
39464
+ mutationFn: async ({ id, route }) => {
39465
+ const fromChainId = route?.params.fromChain;
39466
+ if (cosmosSigner && fromChainId) {
39467
+ try {
39468
+ const signingClient = await getCosmosSignerClient();
39469
+ const signerAddress = (await cosmosSigner.getAccounts())[0].address;
39470
+ if (signerAddress && signingClient && route) {
39471
+ dispatchSignatureRequestEvent(route);
39472
+ const tx$1 = (await squid?.executeRoute({
39473
+ signer: signingClient,
39474
+ signerAddress,
39475
+ route,
39476
+ }));
39477
+ // set the tx state to loading, as soon as user signed the tx
39478
+ setTransactionState({
39479
+ txHash: "",
39480
+ route,
39481
+ status: exports.TransactionStatus.ONGOING,
39482
+ sourceStatus: exports.TransactionStatus.ONGOING,
39483
+ id,
39484
+ });
39485
+ // broadcast the signed tx to get hash and listen to events
39486
+ const response = await signingClient.broadcastTx(tx.TxRaw.encode(tx$1).finish());
39487
+ const hash = response.transactionHash;
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
+ const txParams = setTransactionState({
39494
+ route,
39495
+ txHash: hash,
39496
+ userAddress: sourceUserAddress,
39497
+ status: exports.TransactionStatus.ONGOING,
39498
+ sourceStatus: exports.TransactionStatus.ONGOING,
39499
+ axelarUrl: undefined,
39500
+ id,
39429
39501
  });
39502
+ if (txParams) {
39503
+ addSwapTransaction({
39504
+ ...txParams,
39505
+ params: route.params,
39506
+ estimate: route.estimate,
39507
+ });
39508
+ }
39509
+ return response.code === 0;
39430
39510
  }
39431
- return response.code === 0;
39432
39511
  }
39433
- }
39434
- catch (error) {
39435
- console.error("Error executing Cosmos transaction", error);
39436
- if (isUserRejectionError(normalizeError(error))) {
39437
- throw new Error("Request rejected");
39512
+ catch (error) {
39513
+ console.error("Error executing Cosmos transaction", error);
39514
+ if (isUserRejectionError(normalizeError(error))) {
39515
+ throw new Error("Request rejected");
39516
+ }
39438
39517
  }
39439
39518
  }
39440
- }
39441
- throw new Error("Need all parameters");
39519
+ throw new Error("Need all parameters");
39520
+ },
39442
39521
  });
39443
39522
  // If the transaction is replaced, we need to update the transaction hash
39444
39523
  // Transaction replaced can mean that the user has speed up the transaction for example
@@ -39491,97 +39570,126 @@ const useExecuteTransaction = (squidRoute) => {
39491
39570
  throw error;
39492
39571
  }
39493
39572
  }, [replaceSwapTransactionNonce, setTransactionState, sourceUserAddress]);
39494
- const swapMutationEvm = reactQuery.useMutation(async ({ id, route }) => {
39495
- await changeNetworkIfNeeded.mutateAsync();
39496
- if (!route || !squid || !evmSigner) {
39497
- throw new Error("Need all parameters");
39498
- }
39499
- dispatchSignatureRequestEvent(route);
39500
- const txResponse = (await squid.executeRoute({
39501
- bypassBalanceChecks: true,
39502
- signer: evmSigner,
39503
- route,
39504
- }));
39505
- let hash = txResponse.hash;
39506
- if (activeConnector?.id === "safe") {
39507
- hash = await getGnosisTransactionHash(txResponse.hash);
39508
- }
39509
- if (hash) {
39510
- resetQueriesAfterTxSigned();
39511
- }
39512
- // Dispatch event so it can be listened from outside the widget
39513
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39514
- if (route.transactionRequest) {
39515
- const txParams = setTransactionState({
39573
+ const swapMutationEvm = reactQuery.useMutation({
39574
+ mutationFn: async ({ id, route }) => {
39575
+ await changeNetworkIfNeeded.mutateAsync();
39576
+ if (!route || !squid || !evmSigner) {
39577
+ throw new Error("Need all parameters");
39578
+ }
39579
+ dispatchSignatureRequestEvent(route);
39580
+ const txResponse = (await squid.executeRoute({
39581
+ bypassBalanceChecks: true,
39582
+ signer: evmSigner,
39516
39583
  route,
39517
- txHash: hash,
39518
- nonce: txResponse.nonce,
39519
- userAddress: sourceUserAddress,
39520
- status: exports.TransactionStatus.INITIAL_LOADING,
39521
- sourceStatus: exports.TransactionStatus.ONGOING,
39522
- axelarUrl: undefined,
39523
- id,
39524
- });
39525
- if (txParams) {
39526
- addSwapTransaction({
39527
- ...txParams,
39528
- params: route.params,
39529
- estimate: route.estimate,
39530
- });
39584
+ }));
39585
+ let hash = txResponse.hash;
39586
+ if (activeConnector?.id === "safe") {
39587
+ hash = await getGnosisTransactionHash(txResponse.hash);
39531
39588
  }
39532
- }
39533
- try {
39534
- if (isProblematicConnector(activeConnector)) {
39535
- await sleep(3_000);
39589
+ if (hash) {
39590
+ resetQueriesAfterTxSigned();
39536
39591
  }
39537
- const response = await txResponse.wait();
39538
- return response;
39539
- }
39540
- catch (error) {
39541
- return handleTransactionReplacementError({
39542
- error,
39543
- route,
39544
- status: exports.TransactionStatus.INITIAL_LOADING,
39545
- sourceStatus: exports.TransactionStatus.ONGOING,
39546
- userAddress: sourceUserAddress,
39547
- axelarUrl: undefined,
39548
- id,
39549
- });
39550
- }
39551
- });
39552
- const swapMutationSolana = reactQuery.useMutation(async ({ id, route }) => {
39553
- try {
39554
- if (!route) {
39555
- throw new Error("Route is required");
39592
+ // Dispatch event so it can be listened from outside the widget
39593
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39594
+ if (route.transactionRequest) {
39595
+ const txParams = setTransactionState({
39596
+ route,
39597
+ txHash: hash,
39598
+ nonce: txResponse.nonce,
39599
+ userAddress: sourceUserAddress,
39600
+ status: exports.TransactionStatus.INITIAL_LOADING,
39601
+ sourceStatus: exports.TransactionStatus.ONGOING,
39602
+ axelarUrl: undefined,
39603
+ id,
39604
+ });
39605
+ if (txParams) {
39606
+ addSwapTransaction({
39607
+ ...txParams,
39608
+ params: route.params,
39609
+ estimate: route.estimate,
39610
+ });
39611
+ }
39556
39612
  }
39557
- if (!solanaSigner) {
39558
- throw new Error("Solana signer is required");
39613
+ try {
39614
+ if (isProblematicConnector(activeConnector)) {
39615
+ await sleep(3_000);
39616
+ }
39617
+ const response = await txResponse.wait();
39618
+ return response;
39559
39619
  }
39560
- if (!route.params.fromAddress || !route.params.toAddress) {
39561
- throw new Error("From or to address is required");
39620
+ catch (error) {
39621
+ return handleTransactionReplacementError({
39622
+ error,
39623
+ route,
39624
+ status: exports.TransactionStatus.INITIAL_LOADING,
39625
+ sourceStatus: exports.TransactionStatus.ONGOING,
39626
+ userAddress: sourceUserAddress,
39627
+ axelarUrl: undefined,
39628
+ id,
39629
+ });
39562
39630
  }
39563
- const isDirectTransfer = isDepositRoute(route);
39564
- // Means it's a transfer to a deposit address
39565
- // Instead of a Swap/Contract call using a DEX like Jupiter
39566
- if (isDirectTransfer) {
39567
- // Get the deposit address from the squidRoute
39568
- const depositData = useDepositAddressStore.getState().deposit;
39569
- // Validate params
39570
- if (!depositData?.depositAddress) {
39571
- throw new Error("Deposit address is required");
39631
+ },
39632
+ });
39633
+ const swapMutationSolana = reactQuery.useMutation({
39634
+ mutationFn: async ({ id, route }) => {
39635
+ try {
39636
+ if (!route) {
39637
+ throw new Error("Route is required");
39638
+ }
39639
+ if (!solanaSigner) {
39640
+ throw new Error("Solana signer is required");
39641
+ }
39642
+ if (!route.params.fromAddress || !route.params.toAddress) {
39643
+ throw new Error("From or to address is required");
39644
+ }
39645
+ const isDirectTransfer = isDepositRoute(route);
39646
+ // Means it's a transfer to a deposit address
39647
+ // Instead of a Swap/Contract call using a DEX like Jupiter
39648
+ if (isDirectTransfer) {
39649
+ // Get the deposit address from the squidRoute
39650
+ const depositData = useDepositAddressStore.getState().deposit;
39651
+ // Validate params
39652
+ if (!depositData?.depositAddress) {
39653
+ throw new Error("Deposit address is required");
39654
+ }
39655
+ const signature = await executeSolanaTransfer({
39656
+ amount: BigInt(route.params.fromAmount),
39657
+ target: depositData.depositAddress,
39658
+ signer: solanaSigner,
39659
+ connection: solanaConnection,
39660
+ sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39661
+ onSigned: (txHash) => {
39662
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39663
+ const txParams = setTransactionState({
39664
+ route,
39665
+ txHash,
39666
+ transactionIdForStatus: depositData.chainflipStatusTrackingId,
39667
+ userAddress: sourceUserAddress,
39668
+ status: exports.TransactionStatus.INITIAL_LOADING,
39669
+ sourceStatus: exports.TransactionStatus.ONGOING,
39670
+ id,
39671
+ });
39672
+ if (txParams) {
39673
+ addSwapTransaction({
39674
+ ...txParams,
39675
+ params: route.params,
39676
+ estimate: route.estimate,
39677
+ });
39678
+ }
39679
+ },
39680
+ });
39681
+ return signature;
39572
39682
  }
39573
- const signature = await executeSolanaTransfer({
39574
- amount: BigInt(route.params.fromAmount),
39575
- target: depositData.depositAddress,
39683
+ const signature = await executeSolanaSwap({
39684
+ route,
39576
39685
  signer: solanaSigner,
39577
39686
  connection: solanaConnection,
39578
- sourceToken: findToken(route.params.fromToken, route?.params?.fromChain),
39579
39687
  onSigned: (txHash) => {
39580
39688
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39581
39689
  const txParams = setTransactionState({
39582
39690
  route,
39583
39691
  txHash,
39584
- transactionIdForStatus: depositData.chainflipStatusTrackingId,
39692
+ transactionIdForStatus: undefined,
39585
39693
  userAddress: sourceUserAddress,
39586
39694
  status: exports.TransactionStatus.INITIAL_LOADING,
39587
39695
  sourceStatus: exports.TransactionStatus.ONGOING,
@@ -39598,39 +39706,13 @@ const useExecuteTransaction = (squidRoute) => {
39598
39706
  });
39599
39707
  return signature;
39600
39708
  }
39601
- const signature = await executeSolanaSwap({
39602
- route,
39603
- signer: solanaSigner,
39604
- connection: solanaConnection,
39605
- onSigned: (txHash) => {
39606
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39607
- const txParams = setTransactionState({
39608
- route,
39609
- txHash,
39610
- transactionIdForStatus: undefined,
39611
- userAddress: sourceUserAddress,
39612
- status: exports.TransactionStatus.INITIAL_LOADING,
39613
- sourceStatus: exports.TransactionStatus.ONGOING,
39614
- id,
39615
- });
39616
- if (txParams) {
39617
- addSwapTransaction({
39618
- ...txParams,
39619
- params: route.params,
39620
- estimate: route.estimate,
39621
- });
39622
- }
39623
- },
39624
- });
39625
- return signature;
39626
- }
39627
- catch (error) {
39628
- console.error("Solana transaction failed:", error);
39629
- throw error instanceof Error
39630
- ? error
39631
- : new Error("Failed to execute Solana transaction");
39632
- }
39633
- }, {
39709
+ catch (error) {
39710
+ console.error("Solana transaction failed:", error);
39711
+ throw error instanceof Error
39712
+ ? error
39713
+ : new Error("Failed to execute Solana transaction");
39714
+ }
39715
+ },
39634
39716
  onError: (error, variables) => {
39635
39717
  const currentTx = getTransaction(variables.id);
39636
39718
  const errorObject = getTransactionError(error);
@@ -39651,7 +39733,9 @@ const useExecuteTransaction = (squidRoute) => {
39651
39733
  },
39652
39734
  onSuccess: (_data, variables) => {
39653
39735
  const currentTx = getTransaction(variables.id);
39654
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39736
+ queryClient.invalidateQueries({
39737
+ queryKey: getPrefixKey(QueryKeys.Balances),
39738
+ });
39655
39739
  if (isSameChain && currentTx?.transactionId) {
39656
39740
  replaceSwapTransactionStatus({
39657
39741
  transactionId: currentTx.transactionId,
@@ -39668,197 +39752,207 @@ const useExecuteTransaction = (squidRoute) => {
39668
39752
  });
39669
39753
  },
39670
39754
  });
39671
- const swapMutationBitcoin = reactQuery.useMutation(async ({ id, route }) => {
39672
- const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39673
- if (!depositAddress) {
39674
- throw new Error(`Invalid deposit address: ${depositAddress}`);
39675
- }
39676
- if (!sendAmount) {
39677
- throw new Error(`Invalid send amount: ${sendAmount}`);
39678
- }
39679
- const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39680
- await changeNetworkIfNeeded.mutateAsync();
39681
- if (allParamsValid) {
39682
- dispatchSignatureRequestEvent(route);
39683
- const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39755
+ const swapMutationBitcoin = reactQuery.useMutation({
39756
+ mutationFn: async ({ id, route }) => {
39757
+ const { depositAddress, amount: sendAmount, chainflipStatusTrackingId, } = useDepositAddressStore.getState().deposit ?? {};
39758
+ if (!depositAddress) {
39759
+ throw new Error(`Invalid deposit address: ${depositAddress}`);
39760
+ }
39761
+ if (!sendAmount) {
39762
+ throw new Error(`Invalid send amount: ${sendAmount}`);
39763
+ }
39764
+ const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
39765
+ await changeNetworkIfNeeded.mutateAsync();
39766
+ if (allParamsValid) {
39767
+ dispatchSignatureRequestEvent(route);
39768
+ const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
39769
+ if (txHash) {
39770
+ resetQueriesAfterTxSigned();
39771
+ }
39772
+ // Dispatch event so it can be listened from outside the widget
39773
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39774
+ if (route.transactionRequest) {
39775
+ const txParams = setTransactionState({
39776
+ route,
39777
+ txHash,
39778
+ // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39779
+ // instead of the Bitcoin transaction hash
39780
+ transactionIdForStatus: chainflipStatusTrackingId,
39781
+ userAddress: sourceUserAddress,
39782
+ status: exports.TransactionStatus.INITIAL_LOADING,
39783
+ sourceStatus: exports.TransactionStatus.ONGOING,
39784
+ axelarUrl: undefined,
39785
+ id,
39786
+ });
39787
+ if (txParams) {
39788
+ addSwapTransaction({
39789
+ ...txParams,
39790
+ params: route.params,
39791
+ estimate: route.estimate,
39792
+ });
39793
+ }
39794
+ }
39795
+ }
39796
+ else {
39797
+ throw new Error("Need all parameters");
39798
+ }
39799
+ },
39800
+ });
39801
+ const swapMutationXrpl = reactQuery.useMutation({
39802
+ mutationFn: async ({ id, route }) => {
39803
+ if (!route?.transactionRequest || !xrplSigner) {
39804
+ throw new Error("Need all parameters");
39805
+ }
39806
+ if (route.transactionRequest.type !== squidTypes.SquidDataType.OnChainExecution) {
39807
+ throw new Error("Invalid route type");
39808
+ }
39809
+ const { data } = route.transactionRequest;
39810
+ const paymentTx = parseXrplPaymentTx(data);
39811
+ if (!paymentTx)
39812
+ throw new Error("Could not parse transaction");
39813
+ const fromChainId = route.params.fromChain;
39814
+ const xrplNetwork = getXrplNetwork(fromChainId);
39815
+ if (xrplNetwork == null) {
39816
+ throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39817
+ }
39818
+ const txRes = await xrplSigner.signAndSubmit({
39819
+ tx: paymentTx,
39820
+ network: xrplNetwork,
39821
+ });
39822
+ const txParams = setTransactionState({
39823
+ txHash: txRes.hash,
39824
+ id,
39825
+ sourceStatus: exports.TransactionStatus.ONGOING,
39826
+ status: exports.TransactionStatus.ONGOING,
39827
+ route: route,
39828
+ userAddress: sourceUserAddress,
39829
+ });
39830
+ if (txParams && route) {
39831
+ addSwapTransaction({
39832
+ ...txParams,
39833
+ params: route.params,
39834
+ estimate: route.estimate,
39835
+ });
39836
+ }
39837
+ if (txRes.status !== XrplTxStatus.SUCCESS) {
39838
+ throw new Error(`Transaction failed with status: ${txRes.status}`);
39839
+ }
39840
+ },
39841
+ });
39842
+ const swapMutationSui = reactQuery.useMutation({
39843
+ mutationFn: async ({ id, route }) => {
39844
+ if (!route || !suiSigner || !fromChain) {
39845
+ throw new Error("Need all parameters");
39846
+ }
39847
+ if (route.transactionRequest?.type !== squidTypes.SquidDataType.OnChainExecution) {
39848
+ throw new Error("Invalid route type");
39849
+ }
39850
+ const suiWalletState = connectedWalletsByChainType[squidTypes.ChainType.SUI];
39851
+ if (!suiWalletState.account) {
39852
+ throw new Error("Sui wallet is missing account data");
39853
+ }
39854
+ const fromChainId = route.params.fromChain;
39855
+ const suiChain = getSuiChain(fromChainId);
39856
+ if (!suiChain) {
39857
+ throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39858
+ }
39859
+ const suiClient = await getClient(fromChain);
39860
+ const txJson = route.transactionRequest.data;
39861
+ const tx = transactions.Transaction.from(txJson);
39862
+ const signedTx = await suiSigner.signTransaction({
39863
+ transaction: tx,
39864
+ account: suiWalletState.account,
39865
+ chain: suiChain,
39866
+ });
39867
+ // execute transaction without waiting for confirmation
39868
+ const txResponse = await suiClient.executeTransactionBlock({
39869
+ signature: signedTx.signature,
39870
+ transactionBlock: signedTx.bytes,
39871
+ });
39872
+ const txHash = txResponse.digest;
39684
39873
  if (txHash) {
39685
39874
  resetQueriesAfterTxSigned();
39686
39875
  }
39687
- // Dispatch event so it can be listened from outside the widget
39688
39876
  WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39689
- if (route.transactionRequest) {
39690
- const txParams = setTransactionState({
39691
- route,
39692
- txHash,
39693
- // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
39694
- // instead of the Bitcoin transaction hash
39695
- transactionIdForStatus: chainflipStatusTrackingId,
39696
- userAddress: sourceUserAddress,
39697
- status: exports.TransactionStatus.INITIAL_LOADING,
39698
- sourceStatus: exports.TransactionStatus.ONGOING,
39699
- axelarUrl: undefined,
39700
- id,
39877
+ const txParams = setTransactionState({
39878
+ route,
39879
+ txHash,
39880
+ userAddress: sourceUserAddress,
39881
+ status: exports.TransactionStatus.INITIAL_LOADING,
39882
+ sourceStatus: exports.TransactionStatus.ONGOING,
39883
+ id,
39884
+ });
39885
+ if (txParams) {
39886
+ addSwapTransaction({
39887
+ ...txParams,
39888
+ params: route.params,
39889
+ estimate: route.estimate,
39701
39890
  });
39702
- if (txParams) {
39703
- addSwapTransaction({
39704
- ...txParams,
39705
- params: route.params,
39706
- estimate: route.estimate,
39707
- });
39708
- }
39709
39891
  }
39710
- }
39711
- else {
39712
- throw new Error("Need all parameters");
39713
- }
39714
- });
39715
- const swapMutationXrpl = reactQuery.useMutation(async ({ id, route }) => {
39716
- if (!route?.transactionRequest || !xrplSigner) {
39717
- throw new Error("Need all parameters");
39718
- }
39719
- if (route.transactionRequest.type !== squidTypes.SquidDataType.OnChainExecution) {
39720
- throw new Error("Invalid route type");
39721
- }
39722
- const { data } = route.transactionRequest;
39723
- const paymentTx = parseXrplPaymentTx(data);
39724
- if (!paymentTx)
39725
- throw new Error("Could not parse transaction");
39726
- const fromChainId = route.params.fromChain;
39727
- const xrplNetwork = getXrplNetwork(fromChainId);
39728
- if (xrplNetwork == null) {
39729
- throw new Error(`No XRPL network found for chainId '${fromChainId}'`);
39730
- }
39731
- const txRes = await xrplSigner.signAndSubmit({
39732
- tx: paymentTx,
39733
- network: xrplNetwork,
39734
- });
39735
- const txParams = setTransactionState({
39736
- txHash: txRes.hash,
39737
- id,
39738
- sourceStatus: exports.TransactionStatus.ONGOING,
39739
- status: exports.TransactionStatus.ONGOING,
39740
- route: route,
39741
- userAddress: sourceUserAddress,
39742
- });
39743
- if (txParams && route) {
39744
- addSwapTransaction({
39745
- ...txParams,
39746
- params: route.params,
39747
- estimate: route.estimate,
39892
+ // wait for transaction confirmation
39893
+ await suiClient.waitForTransaction({
39894
+ digest: txHash,
39748
39895
  });
39749
- }
39750
- if (txRes.status !== XrplTxStatus.SUCCESS) {
39751
- throw new Error(`Transaction failed with status: ${txRes.status}`);
39752
- }
39753
- }, {});
39754
- const swapMutationSui = reactQuery.useMutation(async ({ id, route }) => {
39755
- if (!route || !suiSigner || !fromChain) {
39756
- throw new Error("Need all parameters");
39757
- }
39758
- if (route.transactionRequest?.type !== squidTypes.SquidDataType.OnChainExecution) {
39759
- throw new Error("Invalid route type");
39760
- }
39761
- const suiWalletState = connectedWalletsByChainType[squidTypes.ChainType.SUI];
39762
- if (!suiWalletState.account) {
39763
- throw new Error("Sui wallet is missing account data");
39764
- }
39765
- const fromChainId = route.params.fromChain;
39766
- const suiChain = getSuiChain(fromChainId);
39767
- if (!suiChain) {
39768
- throw new Error(`Source chain (${fromChainId}) does not match any Sui chain`);
39769
- }
39770
- const suiClient = await getClient(fromChain);
39771
- const txJson = route.transactionRequest.data;
39772
- const tx = transactions.Transaction.from(txJson);
39773
- const signedTx = await suiSigner.signTransaction({
39774
- transaction: tx,
39775
- account: suiWalletState.account,
39776
- chain: suiChain,
39777
- });
39778
- // execute transaction without waiting for confirmation
39779
- const txResponse = await suiClient.executeTransactionBlock({
39780
- signature: signedTx.signature,
39781
- transactionBlock: signedTx.bytes,
39782
- });
39783
- const txHash = txResponse.digest;
39784
- if (txHash) {
39785
- resetQueriesAfterTxSigned();
39786
- }
39787
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
39788
- const txParams = setTransactionState({
39789
- route,
39790
- txHash,
39791
- userAddress: sourceUserAddress,
39792
- status: exports.TransactionStatus.INITIAL_LOADING,
39793
- sourceStatus: exports.TransactionStatus.ONGOING,
39794
- id,
39795
- });
39796
- if (txParams) {
39797
- addSwapTransaction({
39798
- ...txParams,
39799
- params: route.params,
39800
- estimate: route.estimate,
39896
+ },
39897
+ });
39898
+ const swapMutationStellar = reactQuery.useMutation({
39899
+ mutationFn: async ({ id, route }) => {
39900
+ if (!stellarSigner || !route || !squid || !fromChain) {
39901
+ throw new Error("Need all parameters");
39902
+ }
39903
+ const fromChainId = route.params.fromChain;
39904
+ const stellarNetwork = getStellarNetwork(fromChainId);
39905
+ if (stellarNetwork == null) {
39906
+ throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39907
+ }
39908
+ const { data: xdrHex, gasPrice } = route.transactionRequest;
39909
+ const { address } = await stellarSigner.getAddress();
39910
+ const client = await getClient(fromChain);
39911
+ const account = await client.getAccount(address);
39912
+ const operation = stellarSdk.xdr.Operation.fromXDR(xdrHex, "hex");
39913
+ const builtTransaction = new stellarSdk.TransactionBuilder(account, {
39914
+ fee: gasPrice || (BigInt(stellarSdk.BASE_FEE) * BigInt(2)).toString(),
39915
+ networkPassphrase: stellarNetwork,
39916
+ })
39917
+ .addOperation(operation)
39918
+ .setTimeout(300)
39919
+ .build();
39920
+ const preparedTransaction = await client.prepareTransaction(builtTransaction);
39921
+ const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39922
+ networkPassphrase: stellarNetwork,
39801
39923
  });
39802
- }
39803
- // wait for transaction confirmation
39804
- await suiClient.waitForTransaction({
39805
- digest: txHash,
39806
- });
39807
- }, {});
39808
- const swapMutationStellar = reactQuery.useMutation(async ({ id, route }) => {
39809
- if (!stellarSigner || !route || !squid || !fromChain) {
39810
- throw new Error("Need all parameters");
39811
- }
39812
- const fromChainId = route.params.fromChain;
39813
- const stellarNetwork = getStellarNetwork(fromChainId);
39814
- if (stellarNetwork == null) {
39815
- throw new Error(`No Stellar network found for chainId ${fromChainId}`);
39816
- }
39817
- const { data: xdrHex, gasPrice } = route.transactionRequest;
39818
- const { address } = await stellarSigner.getAddress();
39819
- const client = await getClient(fromChain);
39820
- const account = await client.getAccount(address);
39821
- const operation = stellarSdk.xdr.Operation.fromXDR(xdrHex, "hex");
39822
- const builtTransaction = new stellarSdk.TransactionBuilder(account, {
39823
- fee: gasPrice || (BigInt(stellarSdk.BASE_FEE) * BigInt(2)).toString(),
39824
- networkPassphrase: stellarNetwork,
39825
- })
39826
- .addOperation(operation)
39827
- .setTimeout(300)
39828
- .build();
39829
- const preparedTransaction = await client.prepareTransaction(builtTransaction);
39830
- const { signedTxXdr } = await stellarSigner.signTransaction(preparedTransaction.toXDR(), {
39831
- networkPassphrase: stellarNetwork,
39832
- });
39833
- const signedTransaction = new stellarSdk.Transaction(signedTxXdr, stellarNetwork);
39834
- // get hash before submitting
39835
- const hash = signedTransaction.hash().toString("hex");
39836
- if (hash) {
39837
- resetQueriesAfterTxSigned();
39838
- }
39839
- // Dispatch event so it can be listened from outside the widget
39840
- WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39841
- const txParams = setTransactionState({
39842
- route,
39843
- txHash: hash,
39844
- userAddress: sourceUserAddress,
39845
- status: exports.TransactionStatus.INITIAL_LOADING,
39846
- sourceStatus: exports.TransactionStatus.ONGOING,
39847
- id,
39848
- });
39849
- if (txParams) {
39850
- addSwapTransaction({
39851
- ...txParams,
39852
- params: route.params,
39853
- estimate: route.estimate,
39924
+ const signedTransaction = new stellarSdk.Transaction(signedTxXdr, stellarNetwork);
39925
+ // get hash before submitting
39926
+ const hash = signedTransaction.hash().toString("hex");
39927
+ if (hash) {
39928
+ resetQueriesAfterTxSigned();
39929
+ }
39930
+ // Dispatch event so it can be listened from outside the widget
39931
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, hash);
39932
+ const txParams = setTransactionState({
39933
+ route,
39934
+ txHash: hash,
39935
+ userAddress: sourceUserAddress,
39936
+ status: exports.TransactionStatus.INITIAL_LOADING,
39937
+ sourceStatus: exports.TransactionStatus.ONGOING,
39938
+ id,
39854
39939
  });
39855
- }
39856
- const sentTransaction = await client.sendTransaction(signedTransaction);
39857
- await client.waitForTransaction(sentTransaction.hash);
39858
- }, {});
39940
+ if (txParams) {
39941
+ addSwapTransaction({
39942
+ ...txParams,
39943
+ params: route.params,
39944
+ estimate: route.estimate,
39945
+ });
39946
+ }
39947
+ const sentTransaction = await client.sendTransaction(signedTransaction);
39948
+ await client.waitForTransaction(sentTransaction.hash);
39949
+ },
39950
+ });
39859
39951
  const handleTransactionSuccess = React.useCallback((id) => {
39860
39952
  const currentTx = getTransaction(id);
39861
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
39953
+ queryClient.invalidateQueries({
39954
+ queryKey: getPrefixKey(QueryKeys.Balances),
39955
+ });
39862
39956
  if (isSameChain && currentTx?.transactionId) {
39863
39957
  replaceSwapTransactionStatus({
39864
39958
  transactionId: currentTx.transactionId,
@@ -39910,38 +40004,39 @@ const useExecuteTransaction = (squidRoute) => {
39910
40004
  setTransactionStoreState,
39911
40005
  squidRoute,
39912
40006
  ]);
39913
- const swapMutation = reactQuery.useMutation(async (mutationParams) => {
39914
- if (!mutationParams.route)
39915
- throw new Error("route is required");
39916
- const sourceChain = findChain(mutationParams.route.params?.fromChain);
39917
- if (!sourceChain)
39918
- throw new Error("Could not find source chain");
39919
- switch (sourceChain.chainType) {
39920
- case squidTypes.ChainType.COSMOS: {
39921
- return swapMutationCosmos.mutateAsync(mutationParams);
39922
- }
39923
- case squidTypes.ChainType.EVM: {
39924
- return swapMutationEvm.mutateAsync(mutationParams);
39925
- }
39926
- case squidTypes.ChainType.BTC: {
39927
- return swapMutationBitcoin.mutateAsync(mutationParams);
39928
- }
39929
- case squidTypes.ChainType.SOLANA: {
39930
- return swapMutationSolana.mutateAsync(mutationParams);
39931
- }
39932
- case squidTypes.ChainType.SUI: {
39933
- return swapMutationSui.mutateAsync(mutationParams);
39934
- }
39935
- case squidTypes.ChainType.XRPL: {
39936
- return swapMutationXrpl.mutateAsync(mutationParams);
39937
- }
39938
- case squidTypes.ChainType.STELLAR: {
39939
- return swapMutationStellar.mutateAsync(mutationParams);
40007
+ const swapMutation = reactQuery.useMutation({
40008
+ mutationFn: async (mutationParams) => {
40009
+ if (!mutationParams.route)
40010
+ throw new Error("route is required");
40011
+ const sourceChain = findChain(mutationParams.route.params?.fromChain);
40012
+ if (!sourceChain)
40013
+ throw new Error("Could not find source chain");
40014
+ switch (sourceChain.chainType) {
40015
+ case squidTypes.ChainType.COSMOS: {
40016
+ return swapMutationCosmos.mutateAsync(mutationParams);
40017
+ }
40018
+ case squidTypes.ChainType.EVM: {
40019
+ return swapMutationEvm.mutateAsync(mutationParams);
40020
+ }
40021
+ case squidTypes.ChainType.BTC: {
40022
+ return swapMutationBitcoin.mutateAsync(mutationParams);
40023
+ }
40024
+ case squidTypes.ChainType.SOLANA: {
40025
+ return swapMutationSolana.mutateAsync(mutationParams);
40026
+ }
40027
+ case squidTypes.ChainType.SUI: {
40028
+ return swapMutationSui.mutateAsync(mutationParams);
40029
+ }
40030
+ case squidTypes.ChainType.XRPL: {
40031
+ return swapMutationXrpl.mutateAsync(mutationParams);
40032
+ }
40033
+ case squidTypes.ChainType.STELLAR: {
40034
+ return swapMutationStellar.mutateAsync(mutationParams);
40035
+ }
40036
+ default:
40037
+ throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39940
40038
  }
39941
- default:
39942
- throw new Error(`Swap mutation not implemented for chain type: ${sourceChain.chainType}`);
39943
- }
39944
- }, {
40039
+ },
39945
40040
  onMutate: (variables) => {
39946
40041
  useTransactionStore.setState({
39947
40042
  txLocalId: variables.id,
@@ -39990,7 +40085,7 @@ const useExecuteTransaction = (squidRoute) => {
39990
40085
  toToken,
39991
40086
  toChain,
39992
40087
  fromChain,
39993
- isLoading: swapMutation.isLoading,
40088
+ isPending: swapMutation.isPending,
39994
40089
  error: swapMutation.error,
39995
40090
  };
39996
40091
  };
@@ -40051,57 +40146,59 @@ const useGetRoute = () => {
40051
40146
  * These data will be used to trigger the transaction
40052
40147
  * @returns {Route} Route data
40053
40148
  */
40054
- return reactQuery.useMutation(async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40055
- if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40056
- return undefined;
40057
- }
40058
- // Dispatch requestQuote event
40059
- dispatchRequestQuoteEvent({
40060
- fromChain,
40061
- toChain,
40062
- fromToken: fromToken.address,
40063
- toToken: toToken.address,
40064
- fromAmount: fromPrice,
40065
- fromAddress: sourceUserAddress,
40066
- toAddress: destinationAddress,
40067
- });
40068
- const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40069
- const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40070
- const fromTokenAddress = fromToken.address;
40071
- const toTokenAddress = toToken.address;
40072
- const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40073
- const fromAddress = sourceUserAddress ??
40074
- chainTypeToZeroAddressMap[fromChainType ?? squidTypes.ChainType.EVM];
40075
- const params = {
40076
- fromChain,
40077
- fromToken: fromTokenAddress,
40078
- fromAddress,
40079
- fromAmount,
40080
- toChain,
40081
- toToken: toTokenAddress,
40082
- toAddress: destinationAddress ?? "",
40083
- quoteOnly,
40084
- slippage: config.slippage === 0 ? undefined : config.slippage,
40085
- bypassGuardrails,
40086
- preHook,
40087
- postHook,
40088
- };
40089
- // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40090
- if (cosmosFallbackAddresses &&
40091
- cosmosFallbackAddresses.length > 0 &&
40092
- cosmosFallbackAddresses[0].address) {
40093
- params.fallbackAddresses = cosmosFallbackAddresses;
40094
- }
40095
- const { route } = await squid.getRoute({
40096
- ...params,
40097
- });
40098
- // Cache the route data
40099
- // Useful when the getRoute mutation is called from another hook
40100
- queryClient.setQueryData(keys().transaction(fromChain, toChain, toToken.address, fromToken.address, fromPrice, config.slippage, config.enableGetGasOnDestination, sourceUserAddress, config.degenMode, destinationAddress, swapRoute?.fallbackAddress, quoteOnly, fromChainType, config.preHook, config.postHook), route);
40101
- return route;
40149
+ return reactQuery.useMutation({
40150
+ mutationFn: async ({ fromChain, toChain, fromToken, toToken, sourceUserAddress, destinationAddress, fromPrice, bypassGuardrails, quoteOnly, fromChainType, postHook, preHook, }) => {
40151
+ if (!fromChain || !toChain || !fromToken || !toToken || !fromPrice) {
40152
+ return undefined;
40153
+ }
40154
+ // Dispatch requestQuote event
40155
+ dispatchRequestQuoteEvent({
40156
+ fromChain,
40157
+ toChain,
40158
+ fromToken: fromToken.address,
40159
+ toToken: toToken.address,
40160
+ fromAmount: fromPrice,
40161
+ fromAddress: sourceUserAddress,
40162
+ toAddress: destinationAddress,
40163
+ });
40164
+ const isEvmSwap = Number(fromChain) > 0 && Number(toChain) > 0;
40165
+ const cosmosFallbackAddresses = quoteOnly || isEvmSwap ? undefined : await getCosmosFallbackAddresses();
40166
+ const fromTokenAddress = fromToken.address;
40167
+ const toTokenAddress = toToken.address;
40168
+ const fromAmount = parseToBigInt(fromPrice?.toString() ?? "0", fromToken?.decimals).toString();
40169
+ const fromAddress = sourceUserAddress ??
40170
+ chainTypeToZeroAddressMap[fromChainType ?? squidTypes.ChainType.EVM];
40171
+ const params = {
40172
+ fromChain,
40173
+ fromToken: fromTokenAddress,
40174
+ fromAddress,
40175
+ fromAmount,
40176
+ toChain,
40177
+ toToken: toTokenAddress,
40178
+ toAddress: destinationAddress ?? "",
40179
+ quoteOnly,
40180
+ slippage: config.slippage === 0 ? undefined : config.slippage,
40181
+ bypassGuardrails,
40182
+ preHook,
40183
+ postHook,
40184
+ };
40185
+ // If the swap is involving cosmos chains, we need to add the fallback addresses (if any)
40186
+ if (cosmosFallbackAddresses &&
40187
+ cosmosFallbackAddresses.length > 0 &&
40188
+ cosmosFallbackAddresses[0].address) {
40189
+ params.fallbackAddresses = cosmosFallbackAddresses;
40190
+ }
40191
+ const { route } = await squid.getRoute({
40192
+ ...params,
40193
+ });
40194
+ // Cache the route data
40195
+ // Useful when the getRoute mutation is called from another hook
40196
+ 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);
40197
+ return route;
40198
+ },
40102
40199
  });
40103
40200
  };
40104
- const useGetRouteWrapper = ({ enabled, cacheTime = 5 * 60 * 1000, // 5 minutes
40201
+ const useGetRouteWrapper = ({ enabled, gcTime = 5 * 60 * 1000, // 5 minutes
40105
40202
  staleTime = 60 * 1000, // 1 minute
40106
40203
  refetchOnWindowFocus = (query) => Date.now() - query.state.dataUpdatedAt > 30000, // Update if older than 30 seconds, when window is focused
40107
40204
  refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true, }) => {
@@ -40151,25 +40248,27 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40151
40248
  * These data will be used to trigger the transaction
40152
40249
  * @returns {Route} Route data
40153
40250
  */
40154
- const squidRoute = reactQuery.useQuery(squidRouteQueryKeys, async () => {
40155
- const route = await getRouteMutation.mutateAsync({
40156
- fromChain: fromChain?.chainId,
40157
- toChain: toChain?.chainId,
40158
- fromToken,
40159
- toToken,
40160
- sourceUserAddress,
40161
- destinationAddress,
40162
- fromPrice,
40163
- bypassGuardrails: config.degenMode,
40164
- quoteOnly,
40165
- fromChainType: fromChain?.chainType,
40166
- postHook: config.postHook,
40167
- preHook: config.preHook,
40168
- });
40169
- return route;
40170
- }, {
40251
+ const squidRoute = reactQuery.useQuery({
40252
+ queryKey: squidRouteQueryKeys,
40253
+ queryFn: async () => {
40254
+ const route = await getRouteMutation.mutateAsync({
40255
+ fromChain: fromChain?.chainId,
40256
+ toChain: toChain?.chainId,
40257
+ fromToken,
40258
+ toToken,
40259
+ sourceUserAddress,
40260
+ destinationAddress,
40261
+ fromPrice,
40262
+ bypassGuardrails: config.degenMode,
40263
+ quoteOnly,
40264
+ fromChainType: fromChain?.chainType,
40265
+ postHook: config.postHook,
40266
+ preHook: config.preHook,
40267
+ });
40268
+ return route;
40269
+ },
40171
40270
  enabled: queryEnabled,
40172
- cacheTime,
40271
+ gcTime,
40173
40272
  staleTime,
40174
40273
  refetchOnWindowFocus,
40175
40274
  refetchIntervalInBackground,
@@ -40178,7 +40277,7 @@ refetchIntervalInBackground = false, refetchInterval = 30000, quoteOnly = true,
40178
40277
  /**
40179
40278
  * If last updated data is older than X seconds and the query is currently loading, show loading indicator
40180
40279
  */
40181
- const showLoading = React.useMemo(() => squidRoute.isFetching || squidRoute.isRefetching, [squidRoute.isFetching, squidRoute.isRefetching]);
40280
+ const showLoading = squidRoute.isFetching || squidRoute.isRefetching;
40182
40281
  return {
40183
40282
  squidRoute,
40184
40283
  showLoading,
@@ -40210,7 +40309,7 @@ function useSendTransactionStatus({ chain, txHash, }) {
40210
40309
  transactionId: txHash,
40211
40310
  txType: exports.HistoryTxType.SEND,
40212
40311
  });
40213
- const { data: status } = reactQuery.useQuery({
40312
+ const { data: status, isSuccess, isError, } = reactQuery.useQuery({
40214
40313
  queryKey: keys().sendTransactionStatus(txHash, chain?.chainId),
40215
40314
  queryFn: async () => {
40216
40315
  if (!chain || !txHash)
@@ -40220,17 +40319,30 @@ function useSendTransactionStatus({ chain, txHash, }) {
40220
40319
  txHash,
40221
40320
  });
40222
40321
  },
40223
- onSuccess: (txStatus) => {
40224
- setIsTransactionComplete(txStatus !== exports.SendTransactionStatus.ONGOING);
40225
- if (txStatus != null && !!txHash) {
40322
+ refetchInterval: chain
40323
+ ? getSendTxStatusRefetchInterval(chain.chainType)
40324
+ : false,
40325
+ enabled: !!chain &&
40326
+ !!txHash &&
40327
+ !isTransactionComplete &&
40328
+ !!currentHistoryItem &&
40329
+ !isHistoryTransactionEnded({
40330
+ data: currentHistoryItem?.data,
40331
+ txType: exports.HistoryTxType.SEND,
40332
+ }),
40333
+ });
40334
+ React.useEffect(() => {
40335
+ if (isSuccess) {
40336
+ setIsTransactionComplete(status !== exports.SendTransactionStatus.ONGOING);
40337
+ if (status != null && !!txHash) {
40226
40338
  replaceTransactionStatus({
40227
40339
  txType: exports.HistoryTxType.SEND,
40228
- status: txStatus,
40340
+ status: status,
40229
40341
  hash: txHash,
40230
40342
  });
40231
40343
  }
40232
- },
40233
- onError() {
40344
+ }
40345
+ if (isError) {
40234
40346
  setIsTransactionComplete(true);
40235
40347
  if (txHash) {
40236
40348
  replaceTransactionStatus({
@@ -40239,19 +40351,8 @@ function useSendTransactionStatus({ chain, txHash, }) {
40239
40351
  hash: txHash,
40240
40352
  });
40241
40353
  }
40242
- },
40243
- refetchInterval: chain
40244
- ? getSendTxStatusRefetchInterval(chain.chainType)
40245
- : false,
40246
- enabled: !!chain &&
40247
- !!txHash &&
40248
- !isTransactionComplete &&
40249
- !!currentHistoryItem &&
40250
- !isHistoryTransactionEnded({
40251
- data: currentHistoryItem?.data,
40252
- txType: exports.HistoryTxType.SEND,
40253
- }),
40254
- });
40354
+ }
40355
+ }, [isError, isSuccess, replaceTransactionStatus, status, txHash]);
40255
40356
  return {
40256
40357
  status: status ?? currentHistoryItem?.data?.status,
40257
40358
  };
@@ -40285,7 +40386,9 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40285
40386
  apiUrl: latestConfig.apiUrl,
40286
40387
  });
40287
40388
  }, [transaction]);
40288
- const transactionStatusQuery = reactQuery.useQuery(keys().swapTransactionStatus(transaction?.transactionId), fetchTransactionStatusWithLatestConfig, {
40389
+ const transactionStatusQuery = reactQuery.useQuery({
40390
+ queryKey: keys().swapTransactionStatus(transaction?.transactionId),
40391
+ queryFn: fetchTransactionStatusWithLatestConfig,
40289
40392
  enabled: enabled &&
40290
40393
  transaction?.transactionId !== "0" &&
40291
40394
  !!transaction?.transactionId &&
@@ -40299,12 +40402,12 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40299
40402
  data: currentHistoryItem?.data,
40300
40403
  txType: exports.HistoryTxType.SWAP,
40301
40404
  }),
40302
- refetchInterval(statusResponse) {
40405
+ refetchInterval({ state }) {
40303
40406
  // If the status response is something telling that the transaction
40304
40407
  // is finished, then store transaction history state if success
40305
40408
  // And return false to indicate refetcher to stop
40306
- if (statusResponse &&
40307
- transactionEndStatuses.includes(getTransactionStatus(statusResponse) ?? "")) {
40409
+ if (state.data &&
40410
+ transactionEndStatuses.includes(getTransactionStatus(state.data) ?? "")) {
40308
40411
  return false;
40309
40412
  }
40310
40413
  return refetchInterval; // Had to handle a variable here because after onError, we want the interval to stop
@@ -40313,7 +40416,10 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40313
40416
  retryDelay: getChainType(transaction?.fromChain) === squidTypes.ChainType.COSMOS ? 5000 : 3000,
40314
40417
  retry: getChainType(transaction?.fromChain) === squidTypes.ChainType.COSMOS ? 6 : retry,
40315
40418
  refetchOnWindowFocus,
40316
- onSuccess: (statusResponse) => {
40419
+ });
40420
+ React.useEffect(() => {
40421
+ if (transactionStatusQuery.isSuccess && transactionStatusQuery.data) {
40422
+ const statusResponse = transactionStatusQuery.data;
40317
40423
  // Dispatch event
40318
40424
  WidgetEvents.getInstance().dispatchSwapStatus(statusResponse.squidTransactionStatus ?? "");
40319
40425
  const endStatus = getTransactionEndStatus({ statusResponse });
@@ -40325,8 +40431,9 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40325
40431
  status: endStatus,
40326
40432
  });
40327
40433
  }
40328
- },
40329
- onError: (error) => {
40434
+ }
40435
+ if (transactionStatusQuery.isError) {
40436
+ const error = transactionStatusQuery.error;
40330
40437
  // `fetchTransactionStatus` throws an error with a cause being an AxiosError
40331
40438
  const is404 = is404Error(error.cause);
40332
40439
  if (!transaction?.transactionId)
@@ -40347,8 +40454,15 @@ const useSwapTransactionStatus = ({ transaction, retry = 25, refetchOnWindowFocu
40347
40454
  status: exports.TransactionStatus.ERROR,
40348
40455
  });
40349
40456
  }
40350
- },
40351
- });
40457
+ }
40458
+ }, [
40459
+ transactionStatusQuery.isSuccess,
40460
+ transactionStatusQuery.isError,
40461
+ transaction?.transactionId,
40462
+ transactionStatusQuery.error,
40463
+ replaceSwapTransactionStatus,
40464
+ transactionStatusQuery.data,
40465
+ ]);
40352
40466
  return {
40353
40467
  transactionStatusQuery,
40354
40468
  latestStatus: transactionStatusQuery.data
@@ -40391,7 +40505,7 @@ const useAvatar = (seed = zeroAddress) => {
40391
40505
  },
40392
40506
  // data is static, so no need to refetch
40393
40507
  refetchOnWindowFocus: false,
40394
- cacheTime: Infinity,
40508
+ gcTime: Infinity,
40395
40509
  staleTime: Infinity,
40396
40510
  });
40397
40511
  return avatar || "";
@@ -40433,38 +40547,40 @@ const useAddToken = (chainToCompare, tokenToCompare) => {
40433
40547
  /**
40434
40548
  * Add token to wallet
40435
40549
  */
40436
- const addToken = reactQuery.useMutation(async ({ chain: _chain, token: _token, }) => {
40437
- const token = _token ?? tokenToCompare;
40438
- const chain = _chain ?? chainToCompare;
40439
- if (token && chain?.chainType === squidTypes.ChainType.EVM) {
40440
- const provider = await connector?.getProvider();
40441
- // Switch network if needed
40442
- if (currentEvmChain?.id.toString() !== token?.chainId) {
40443
- try {
40444
- await switchChainAsync({
40445
- chainId: +token.chainId,
40446
- });
40447
- }
40448
- catch (error) {
40449
- console.debug("Error switching network:", error);
40450
- if (isEvmChainNotSupportedError(error)) {
40451
- await addEthereumChain({
40452
- chain,
40453
- provider,
40454
- });
40550
+ const addToken = reactQuery.useMutation({
40551
+ mutationFn: async ({ chain: _chain, token: _token, }) => {
40552
+ const token = _token ?? tokenToCompare;
40553
+ const chain = _chain ?? chainToCompare;
40554
+ if (token && chain?.chainType === squidTypes.ChainType.EVM) {
40555
+ const provider = await connector?.getProvider();
40556
+ // Switch network if needed
40557
+ if (currentEvmChain?.id.toString() !== token?.chainId) {
40558
+ try {
40455
40559
  await switchChainAsync({
40456
40560
  chainId: +token.chainId,
40457
40561
  });
40458
40562
  }
40563
+ catch (error) {
40564
+ console.debug("Error switching network:", error);
40565
+ if (isEvmChainNotSupportedError(error)) {
40566
+ await addEthereumChain({
40567
+ chain,
40568
+ provider,
40569
+ });
40570
+ await switchChainAsync({
40571
+ chainId: +token.chainId,
40572
+ });
40573
+ }
40574
+ }
40575
+ // Metamask is not popping the second modal if we don't wait a bit
40576
+ // eslint-disable-next-line no-promise-executor-return
40577
+ await new Promise((resolve) => setTimeout(resolve, 100));
40459
40578
  }
40460
- // Metamask is not popping the second modal if we don't wait a bit
40461
- // eslint-disable-next-line no-promise-executor-return
40462
- await new Promise((resolve) => setTimeout(resolve, 100));
40579
+ await addTokenToWallet({ token, provider });
40463
40580
  }
40464
- await addTokenToWallet({ token, provider });
40581
+ // TODO: Implement keplr add token
40582
+ return false;
40465
40583
  }
40466
- // TODO: Implement keplr add token
40467
- return false;
40468
40584
  });
40469
40585
  return {
40470
40586
  addToken,
@@ -40669,7 +40785,9 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40669
40785
  }
40670
40786
  },
40671
40787
  async onSuccess() {
40672
- queryClient.invalidateQueries(getPrefixKey(QueryKeys.XrplTrustLine));
40788
+ queryClient.invalidateQueries({
40789
+ queryKey: getPrefixKey(QueryKeys.XrplTrustLine),
40790
+ });
40673
40791
  },
40674
40792
  });
40675
40793
  /**
@@ -40736,117 +40854,6 @@ function useXrplTrustLine({ address, chain, token, amount }) {
40736
40854
  };
40737
40855
  }
40738
40856
 
40739
- // Prevent fetching too soon after the first successful request.
40740
- const DEFAULT_STALE_TIME = 8000;
40741
- const defaultOptions = {
40742
- queries: {
40743
- staleTime: DEFAULT_STALE_TIME,
40744
- refetchOnWindowFocus: false,
40745
- retry: false,
40746
- retryOnMount: false,
40747
- },
40748
- };
40749
-
40750
- const queryClient = new reactQuery.QueryClient({ defaultOptions });
40751
- const verifyIntegratorIdValidity = (integratorId) => {
40752
- if (!integratorId) {
40753
- throw new Error("Integrator ID is required");
40754
- }
40755
- };
40756
- const SquidProvider = ({ children, config, placeholder, }) => {
40757
- verifyIntegratorIdValidity(config.integratorId);
40758
- const [wagmiConfig, setWagmiConfig] = React.useState();
40759
- const sdkInitializedRef = React.useRef(false);
40760
- const initializeSdk = React.useCallback(async () => {
40761
- if (sdkInitializedRef.current) {
40762
- return;
40763
- }
40764
- sdkInitializedRef.current = true;
40765
- try {
40766
- const squid = new sdk.Squid({
40767
- integratorId: config.integratorId,
40768
- baseUrl: config.apiUrl ?? squidApiBaseUrl,
40769
- });
40770
- const [sdkInfoResponse, assetsColorsResponse] = await Promise.allSettled([
40771
- squid.init(),
40772
- fetchAssetsColors(),
40773
- ]);
40774
- if (sdkInfoResponse.status === "rejected") {
40775
- throw sdkInfoResponse.reason;
40776
- }
40777
- if (assetsColorsResponse.status === "fulfilled") {
40778
- useAssetsColorsStore.setState(assetsColorsResponse.value);
40779
- initializeSquidWithAssetsColors(squid, assetsColorsResponse.value);
40780
- }
40781
- const shouldResetSwapRouteStore =
40782
- // reset swap route if specified in config
40783
- !config?.loadPreviousStateFromLocalStorage ||
40784
- // or if initial assets are provided
40785
- !isEmptyObject(config.initialAssets?.from) ||
40786
- !isEmptyObject(config.initialAssets?.to);
40787
- if (shouldResetSwapRouteStore) {
40788
- useSwapRoutePersistStore.setState({
40789
- swapRoute: undefined,
40790
- });
40791
- }
40792
- useSquidStore.setState((_) => ({
40793
- squid,
40794
- maintenanceMode: { active: false, message: undefined },
40795
- }));
40796
- const newWagmiConfig = createWagmiConfig(squid.chains);
40797
- setWagmiConfig(newWagmiConfig);
40798
- useConfigStore.setState({
40799
- isInitialized: true,
40800
- config: getConfigWithDefaults(config),
40801
- });
40802
- }
40803
- catch (error) {
40804
- const isAxios503Error = error.isAxiosError &&
40805
- error.response?.status === 503;
40806
- if (isAxios503Error) {
40807
- const maintenanceMessage = error.response?.data
40808
- ?.message ?? undefined;
40809
- // Even with an error, we want wagmi to be defined so that we can display the maintenance mode layout
40810
- // Create wagmi config with mainnet as fallback in maintenance mode
40811
- const newWagmiConfig = wagmi.createConfig({
40812
- chains: [chains$1.mainnet],
40813
- connectors: [connectors.injected()],
40814
- transports: {
40815
- [chains$1.mainnet.id]: wagmi.http(),
40816
- },
40817
- });
40818
- setWagmiConfig(newWagmiConfig);
40819
- useConfigStore.setState({
40820
- isInitialized: false,
40821
- config: getConfigWithDefaults(config),
40822
- });
40823
- useSquidStore.setState({
40824
- squid: undefined,
40825
- maintenanceMode: {
40826
- active: true,
40827
- message: maintenanceMessage,
40828
- },
40829
- });
40830
- }
40831
- else {
40832
- console.error("Error initializing SDK:", error);
40833
- }
40834
- }
40835
- }, [config]);
40836
- React.useEffect(() => {
40837
- initializeSdk();
40838
- }, [initializeSdk]);
40839
- return wagmiConfig ? (React.createElement(wagmi.WagmiProvider, { reconnectOnMount: false, config: wagmiConfig },
40840
- React.createElement(reactQuery.QueryClientProvider, { client: queryClient },
40841
- React.createElement(StellarProvider, null,
40842
- React.createElement(EvmProvider, null,
40843
- React.createElement(XrplProvider, null,
40844
- React.createElement(SuiProvider, null,
40845
- React.createElement(SolanaProvider, null,
40846
- React.createElement(BitcoinProvider, null,
40847
- React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
40848
- };
40849
-
40850
40857
  exports.CHAIN_IDS = CHAIN_IDS;
40851
40858
  exports.CosmosProvider = CosmosProvider;
40852
40859
  exports.DEFAULT_LOCALE = DEFAULT_LOCALE;
@@ -40985,7 +40992,7 @@ exports.parseEvmAddress = parseEvmAddress;
40985
40992
  exports.parseToBigInt = parseToBigInt;
40986
40993
  exports.parseXrplPaymentTx = parseXrplPaymentTx;
40987
40994
  exports.populateWallets = populateWallets;
40988
- exports.randomIntFromInterval = randomIntFromInterval;
40995
+ exports.queryClient = queryClient;
40989
40996
  exports.redirectToExtensionsStore = redirectToExtensionsStore;
40990
40997
  exports.roundNumericValue = roundNumericValue;
40991
40998
  exports.searchTokens = searchTokens;
@@ -41027,8 +41034,6 @@ exports.useEvmBalance = useEvmBalance;
41027
41034
  exports.useExecuteFiatQuote = useExecuteFiatQuote;
41028
41035
  exports.useExecuteTransaction = useExecuteTransaction;
41029
41036
  exports.useFavoriteTokensStore = useFavoriteTokensStore;
41030
- exports.useFiatOnRampTxStatus = useFiatOnRampTxStatus;
41031
- exports.useFiatTransactions = useFiatTransactions;
41032
41037
  exports.useGetFiatQuote = useGetFiatQuote;
41033
41038
  exports.useGetOnRampConfig = useGetOnRampConfig;
41034
41039
  exports.useGetOnrampPaymentTypes = useGetOnrampPaymentTypes;
@@ -41046,7 +41051,6 @@ exports.useMultiChainWallet = useMultiChainWallet;
41046
41051
  exports.useMultipleTokenPrices = useMultipleTokenPrices;
41047
41052
  exports.useNativeBalance = useNativeBalance;
41048
41053
  exports.useNativeTokenForChain = useNativeTokenForChain;
41049
- exports.useRecommendedQuote = useRecommendedQuote;
41050
41054
  exports.useRouteWarnings = useRouteWarnings;
41051
41055
  exports.useSendTransaction = useSendTransaction;
41052
41056
  exports.useSendTransactionGas = useSendTransactionGas;
@@ -41074,4 +41078,4 @@ exports.useWallets = useWallets;
41074
41078
  exports.useXrplTrustLine = useXrplTrustLine;
41075
41079
  exports.walletIconBaseUrl = walletIconBaseUrl;
41076
41080
  exports.walletSupportsChainType = walletSupportsChainType;
41077
- //# sourceMappingURL=index-BtOPNnH5.js.map
41081
+ //# sourceMappingURL=index-CvsT0xf8.js.map