@0xsquid/react-hooks 5.0.4-beta.0 → 5.0.4-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/core/constants.d.ts +9 -0
  2. package/dist/core/constants.js +10 -2
  3. package/dist/core/constants.js.map +1 -1
  4. package/dist/core/types/wallet.d.ts +4 -2
  5. package/dist/core/types/wallet.js +2 -0
  6. package/dist/core/types/wallet.js.map +1 -1
  7. package/dist/core/wallets.js +33 -0
  8. package/dist/core/wallets.js.map +1 -1
  9. package/dist/hooks/store/useDepositAddressStore.d.ts +9 -0
  10. package/dist/hooks/store/useDepositAddressStore.js +12 -0
  11. package/dist/hooks/store/useDepositAddressStore.js.map +1 -0
  12. package/dist/hooks/swap/useDepositAddress.d.ts +7 -10
  13. package/dist/hooks/swap/useDepositAddress.js +36 -59
  14. package/dist/hooks/swap/useDepositAddress.js.map +1 -1
  15. package/dist/hooks/transaction/useAllTransactionsStatus.js +17 -5
  16. package/dist/hooks/transaction/useAllTransactionsStatus.js.map +1 -1
  17. package/dist/hooks/transaction/useEstimate.d.ts +18 -9
  18. package/dist/hooks/transaction/useEstimate.js +69 -0
  19. package/dist/hooks/transaction/useEstimate.js.map +1 -1
  20. package/dist/hooks/transaction/useExecuteTransaction.d.ts +1 -8
  21. package/dist/hooks/transaction/useExecuteTransaction.js +186 -214
  22. package/dist/hooks/transaction/useExecuteTransaction.js.map +1 -1
  23. package/dist/hooks/transaction/useSingleTransaction.js +1 -0
  24. package/dist/hooks/transaction/useSingleTransaction.js.map +1 -1
  25. package/dist/services/internal/estimateService.js +2 -2
  26. package/dist/services/internal/estimateService.js.map +1 -1
  27. package/dist/services/internal/solanaService.d.ts +0 -8
  28. package/dist/services/internal/solanaService.js +17 -12
  29. package/dist/services/internal/solanaService.js.map +1 -1
  30. package/dist/services/internal/transactionService.d.ts +3 -1
  31. package/dist/services/internal/transactionService.js +8 -1
  32. package/dist/services/internal/transactionService.js.map +1 -1
  33. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
+ import { FeeType } from "@0xsquid/squid-types";
1
2
  import { useMemo } from "react";
2
3
  import { limitTradeSizeUsd } from "../../core/constants";
3
4
  import { useSquidTokens } from "../../hooks/tokens/useSquidTokens";
5
+ import { formatUsdAmount } from "../../services";
4
6
  import { calculateEstimateResults, calculateTotalWithRefundEstimate, getProposedGasDestinationAmount, } from "../../services/internal/estimateService";
5
7
  import { useConfigStore } from "../store/useSquidStore";
6
8
  import { useSwap } from "../swap/useSwap";
@@ -8,6 +10,8 @@ import { useMultiChainBalance } from "../tokens/useMultiChainBalance";
8
10
  import { useNativeBalance } from "../tokens/useNativeBalance";
9
11
  import { useSingleTokenPrice } from "../tokens/useSingleTokenPrice";
10
12
  import { useEstimateExpress } from "./useExpress";
13
+ const DEFAULT_PROVIDER_IMAGE_URL = "https://raw.githubusercontent.com/0xsquid/assets/main/images/webp128/providers/squid.webp";
14
+ const AXELAR_PROVIDER_IMAGE_URL = "https://raw.githubusercontent.com/0xsquid/assets/main/images/webp128/providers/axelar.webp";
11
15
  export const useEstimate = (squidRoute) => {
12
16
  const collectFees = useConfigStore((state) => state.config.collectFees);
13
17
  const { tokens } = useSquidTokens();
@@ -44,16 +48,81 @@ export const useEstimate = (squidRoute) => {
44
48
  getUSDValue,
45
49
  ]);
46
50
  const proposedGasDestinationAmount = useMemo(() => getProposedGasDestinationAmount(estimateResults.destChainNativeToken?.symbol), [estimateResults.destChainNativeToken]);
51
+ const { feeCostsFormatted, totalFeeCostsUsd } = useMemo(() => {
52
+ const feeCosts = squidRoute?.estimate.feeCosts ?? [];
53
+ const feeCostsRenamed = [];
54
+ const feesToRename = [
55
+ {
56
+ newName: "CORAL fee",
57
+ match: [FeeType.EXECUTION_FEE, FeeType.SETTLEMENT_FEE],
58
+ imageUrl: DEFAULT_PROVIDER_IMAGE_URL,
59
+ },
60
+ {
61
+ newName: "Axelar fee",
62
+ match: [FeeType.GAS_RECEIVER_FEE, FeeType.BOOST_FEE],
63
+ imageUrl: AXELAR_PROVIDER_IMAGE_URL,
64
+ },
65
+ ];
66
+ for (const fee of feeCosts) {
67
+ if (Number(fee.amountUsd) === 0)
68
+ continue;
69
+ const feeToRename = feesToRename.find(({ match }) => match.includes(fee.name));
70
+ if (feeToRename) {
71
+ const previousRenamedFeeIndex = feeCostsRenamed.findIndex((f) => f.name === feeToRename.newName);
72
+ if (feeCostsRenamed[previousRenamedFeeIndex] == null) {
73
+ feeCostsRenamed.push({
74
+ name: feeToRename.newName,
75
+ amountUsd: Number(fee.amountUsd),
76
+ imageUrl: feeToRename.imageUrl,
77
+ });
78
+ }
79
+ else {
80
+ feeCostsRenamed[previousRenamedFeeIndex].amountUsd += Number(fee.amountUsd);
81
+ }
82
+ }
83
+ else {
84
+ feeCostsRenamed.push({
85
+ name: fee.name,
86
+ amountUsd: Number(fee.amountUsd),
87
+ imageUrl: DEFAULT_PROVIDER_IMAGE_URL,
88
+ });
89
+ }
90
+ }
91
+ const feeCostsFormatted = feeCostsRenamed.map((fee) => ({
92
+ name: fee.name,
93
+ imageUrl: fee.imageUrl,
94
+ amountUsdFormatted: formatUsdAmount(fee.amountUsd, {
95
+ decimalPrecision: true,
96
+ }),
97
+ }));
98
+ const totalFeeCostsUsd = feeCosts.reduce((totalFees, currentFee) => {
99
+ return Number(totalFees) + Number(currentFee.amountUsd);
100
+ }, 0);
101
+ const totalFeeCostsUsdFormatted = formatUsdAmount(totalFeeCostsUsd, {
102
+ decimalPrecision: true,
103
+ });
104
+ return {
105
+ feeCostsFormatted,
106
+ totalFeeCostsUsd: totalFeeCostsUsdFormatted,
107
+ };
108
+ }, [squidRoute?.estimate.feeCosts]);
109
+ const slippageFormatted =
110
+ // TODO: update types
111
+ Number(squidRoute?.estimate?.aggregateSlippage ?? 0).toFixed(2) +
112
+ "%";
47
113
  const swapAmountExceedsLimit = estimateResults.toAmountUSDFloat > limitTradeSizeUsd;
48
114
  const enoughBalanceToSwap = +balanceFormatted >= 0 &&
49
115
  +balanceFormatted > +estimateResults.fromAmountFormatted;
50
116
  return {
51
117
  ...estimateResults,
52
118
  balanceFormatted,
119
+ slippageFormatted,
53
120
  totalWithRefundEstimate,
54
121
  proposedGasDestinationAmount,
55
122
  swapAmountExceedsLimit,
56
123
  enoughBalanceToSwap,
124
+ feeCostsFormatted,
125
+ totalFeeCostsUsd,
57
126
  };
58
127
  };
59
128
  //# sourceMappingURL=useEstimate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useEstimate.js","sourceRoot":"","sources":["../../../src/hooks/transaction/useEstimate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACnE,OAAO,EACL,wBAAwB,EACxB,gCAAgC,EAChC,+BAA+B,GAChC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAElD,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,UAAmC,EAAE,EAAE;IACjE,MAAM,WAAW,GAAG,cAAc,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAExE,MAAM,EAAE,MAAM,EAAE,GAAG,cAAc,EAAE,CAAC;IACpC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;IACzC,MAAM,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AC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;QACxE,GAAG,CAAC;IAEN,MAAM,sBAAsB,GAC1B,eAAe,CAAC,gBAAgB,GAAG,iBAAiB,CAAC;IAEvD,MAAM,mBAAmB,GACvB,CAAC,gBAAgB,IAAI,CAAC;QACtB,CAAC,gBAAgB,GAAG,CAAC,eAAe,CAAC,mBAAmB,CAAC;IAE3D,OAAO;QACL,GAAG,eAAe;QAClB,gBAAgB;QAChB,iBAAiB;QACjB,uBAAuB;QACvB,4BAA4B;QAC5B,sBAAsB;QACtB,mBAAmB;QACnB,iBAAiB;QACjB,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC"}
@@ -1,20 +1,13 @@
1
1
  import type { RouteResponse } from "@0xsquid/squid-types";
2
2
  import { TransactionReceipt } from "ethers";
3
3
  import type { TransactionParams } from "../../core/types/transaction";
4
- declare enum ExecutionState {
5
- NOT_ENOUGH_BALANCE = "NOT_ENOUGH_BALANCE",
6
- NOT_CONNECTED = "NOT_CONNECTED",
7
- READY = "READY"
8
- }
9
4
  export declare const useExecuteTransaction: (squidRoute?: RouteResponse["route"]) => {
10
- swapQuery: import("@tanstack/react-query").UseMutationResult<boolean | TransactionReceipt | null, any, void, unknown>;
5
+ swapQuery: import("@tanstack/react-query").UseMutationResult<string | boolean | void | TransactionReceipt | null, any, void, unknown>;
11
6
  currentTransaction: TransactionParams | undefined;
12
7
  fromToken: import("@0xsquid/squid-types").Token | undefined;
13
8
  toToken: import("@0xsquid/squid-types").Token | undefined;
14
9
  fromPrice: string | undefined;
15
10
  toChain: import("@0xsquid/squid-types").ChainData | undefined;
16
11
  fromChain: import("@0xsquid/squid-types").ChainData | undefined;
17
- executionState: ExecutionState;
18
12
  signerReady: boolean;
19
13
  };
20
- export {};
@@ -10,35 +10,28 @@ import { TransactionErrorType } from "../../core/types/error";
10
10
  import { TransactionStatus } from "../../core/types/transaction";
11
11
  import { getWorkingCosmosRpcUrl } from "../../services/external/rpcService";
12
12
  import { getTransactionError } from "../../services/internal/errorService";
13
- import { getSourceExplorerTxUrl } from "../../services/internal/transactionService";
13
+ import { getSourceExplorerTxUrl, isDepositRoute, sleep, } from "../../services/internal/transactionService";
14
14
  import { InjectiveSigningStargateClient } from "@injectivelabs/sdk-ts/dist/cjs/core/stargate";
15
15
  import { CHAIN_IDS } from "../../core/constants";
16
16
  import { useSquidChains } from "../../hooks//chains/useSquidChains";
17
17
  import { useSquidStore, useTransactionStore, } from "../../hooks/store/useSquidStore";
18
18
  import { useSwap } from "../../hooks/swap/useSwap";
19
- import { useEstimate } from "../../hooks/transaction/useEstimate";
20
19
  import { useGnosisContext } from "../../hooks/wallet/useGnosisContext";
21
20
  import { useMultiChainWallet } from "../../hooks/wallet/useMultiChainWallet";
22
- import { getCosmosSigningClient } from "../../services";
21
+ import { executeSolanaSwap, executeSolanaTransfer, getCosmosSigningClient, } from "../../services";
23
22
  import { WidgetEvents } from "../../services/internal/eventService";
23
+ import { useSolana } from "../solana/useSolana";
24
+ import { useDepositAddressStore } from "../store/useDepositAddressStore";
24
25
  import { useHistory } from "../user/useHistory";
25
26
  import { useSigner } from "../wallet/useSigner";
26
- var ExecutionState;
27
- (function (ExecutionState) {
28
- ExecutionState["NOT_ENOUGH_BALANCE"] = "NOT_ENOUGH_BALANCE";
29
- ExecutionState["NOT_CONNECTED"] = "NOT_CONNECTED";
30
- ExecutionState["READY"] = "READY";
31
- })(ExecutionState || (ExecutionState = {}));
32
27
  export const useExecuteTransaction = (squidRoute) => {
33
- const { evmSigner, isEvmSignerReady, cosmosSigner,
34
- // solanaSigner,
35
- bitcoinSigner, isSolanaSignerReady, } = useSigner();
36
- const { chains } = useSquidChains();
28
+ const { evmSigner, isEvmSignerReady, cosmosSigner, solanaSigner, bitcoinSigner, isSolanaSignerReady, } = useSigner();
29
+ const { connection } = useSolana();
30
+ const { findChain } = useSquidChains();
37
31
  const queryClient = useQueryClient();
38
32
  const squid = useSquidStore((state) => state.squid);
39
33
  const currentTransaction = useTransactionStore((state) => state.currentTransaction);
40
34
  const fromPrice = useTransactionStore((state) => state.fromPrice);
41
- const { enoughBalanceToSwap } = useEstimate(squidRoute);
42
35
  const { connector: activeConnector } = useAccount();
43
36
  const { fromChain, toChain, fromToken, toToken, isSameChain } = useSwap();
44
37
  const { getGnosisTransactionHash } = useGnosisContext();
@@ -64,18 +57,6 @@ export const useExecuteTransaction = (squidRoute) => {
64
57
  bitcoinSigner,
65
58
  isSolanaSignerReady,
66
59
  ]);
67
- /**
68
- * States to see if the swap execution is possible or not based on swap & user params
69
- * And if not possible, gives the reason
70
- * TODO: The NOT_ENOUGH_BALANCE state could be fetch independently from the route response, only based on user fromAmount
71
- */
72
- const executionState = useMemo(() => {
73
- if (!enoughBalanceToSwap) {
74
- return ExecutionState.NOT_ENOUGH_BALANCE;
75
- }
76
- // TODO:; Add more states here
77
- return ExecutionState.READY;
78
- }, [enoughBalanceToSwap]);
79
60
  /**
80
61
  * Set the transaction state in the store
81
62
  * This is useful to access the latest transaction from any hook
@@ -276,6 +257,19 @@ export const useExecuteTransaction = (squidRoute) => {
276
257
  }
277
258
  }
278
259
  try {
260
+ // TODO: inconsistent connector ID behavior, investigate and debug Wagmi
261
+ const isProblematicConnector = activeConnector?.id != null &&
262
+ ["rabby", "io.rabby"].includes(activeConnector.id);
263
+ const isProblematicSourceChain = [
264
+ CHAIN_IDS.BSC.mainnet,
265
+ CHAIN_IDS.BASE.mainnet,
266
+ ].includes(route.params.fromChain);
267
+ // Issues with Rabby wallet on some chains
268
+ // we need to wait some time before getting the transaction receipt
269
+ // https://github.com/ethers-io/ethers.js/issues/4760
270
+ if (isProblematicConnector && isProblematicSourceChain) {
271
+ await sleep(3_000);
272
+ }
279
273
  const response = await txResponse.wait();
280
274
  return response;
281
275
  }
@@ -293,189 +287,168 @@ export const useExecuteTransaction = (squidRoute) => {
293
287
  throw new Error("Need all parameters");
294
288
  });
295
289
  // TODO: Find a better way to parse (route.transactionRequest as OnChainExecutionData)
296
- // const swapQuerySolana = useMutation(
297
- // async (route?: RouteResponse["route"]) => {
298
- // try {
299
- // if (!route) {
300
- // throw new Error("Route is required");
301
- // }
302
- // if (!solanaSigner) {
303
- // throw new Error("Solana signer is required");
304
- // }
305
- // if (!route.params.fromAddress || !route.params.toAddress) {
306
- // throw new Error("From or to address is required");
307
- // }
308
- // const isDirectTransfer = isSolanaDirectTransfer({
309
- // fromChain,
310
- // route,
311
- // });
312
- // if (isDirectTransfer) {
313
- // const signature = await executeSolanaTransfer({
314
- // amount: BigInt(route.params.fromAmount),
315
- // target: (route.transactionRequest as OnChainExecutionData)?.target,
316
- // solanaSigner,
317
- // connection,
318
- // onSigned: (signature) => {
319
- // const txParams = setTransactionState({
320
- // route,
321
- // txHash: signature,
322
- // transactionIdForStatus:
323
- // (route.transactionRequest as OnChainExecutionData)
324
- // ?.requestId ?? "",
325
- // userAddress: sourceUserAddress,
326
- // status: TransactionStatus.INITIAL_LOADING,
327
- // sourceStatus: TransactionStatus.ONGOING,
328
- // });
329
- // if (txParams) {
330
- // addTransaction({
331
- // ...txParams,
332
- // params: route.params,
333
- // estimate: route.estimate,
334
- // });
335
- // }
336
- // WidgetEvents.getInstance().dispatchSwapExecuteCall(
337
- // route,
338
- // signature
339
- // );
340
- // },
341
- // });
342
- // return signature;
343
- // }
344
- // const signature = await executeSolanaSwap({
345
- // route: route!,
346
- // squid,
347
- // solanaSigner,
348
- // connection,
349
- // sourceUserAddress: route.params.fromAddress,
350
- // });
351
- // const txParams = setTransactionState({
352
- // route,
353
- // txHash: signature,
354
- // transactionIdForStatus:
355
- // (route.transactionRequest as OnChainExecutionData)?.requestId ?? "",
356
- // userAddress: sourceUserAddress,
357
- // status: TransactionStatus.INITIAL_LOADING,
358
- // sourceStatus: TransactionStatus.ONGOING,
359
- // });
360
- // if (txParams) {
361
- // addTransaction({
362
- // ...txParams,
363
- // params: route.params,
364
- // estimate: route.estimate,
365
- // });
366
- // }
367
- // WidgetEvents.getInstance().dispatchSwapExecuteCall(route, signature);
368
- // return signature;
369
- // } catch (error) {
370
- // console.error("Solana transaction failed:", error);
371
- // throw error instanceof Error
372
- // ? error
373
- // : new Error("Failed to execute Solana transaction");
374
- // }
375
- // },
376
- // {
377
- // onError: (error) => {
378
- // const { currentTransaction: currentTx } =
379
- // useTransactionStore.getState();
380
- // const errorObject = getTransactionError(error);
381
- // useTransactionStore.setState({
382
- // currentTransaction: {
383
- // ...currentTx!,
384
- // status: TransactionStatus.ERROR,
385
- // sourceStatus: TransactionStatus.ERROR,
386
- // error: errorObject,
387
- // },
388
- // });
389
- // WidgetEvents.getInstance().dispatchSwapRouteExecutionError({
390
- // error: errorObject,
391
- // });
392
- // // TODO: Handle that for solana
393
- // if (
394
- // currentTx?.transactionId &&
395
- // errorObject?.type === TransactionErrorType.CALL_EXCEPTION
396
- // ) {
397
- // replaceTransactionStatus(
398
- // currentTx.transactionId,
399
- // currentTx.statusResponse,
400
- // TransactionStatus.ERROR
401
- // );
402
- // }
403
- // },
404
- // onSuccess: () => {
405
- // const { currentTransaction: currentTx } =
406
- // useTransactionStore.getState();
407
- // queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
408
- // if (isSameChain && currentTx?.transactionId) {
409
- // replaceTransactionStatus(
410
- // currentTx.transactionId,
411
- // currentTx.statusResponse,
412
- // TransactionStatus.SUCCESS
413
- // );
414
- // }
415
- // useTransactionStore.setState({
416
- // currentTransaction: {
417
- // ...currentTx!,
418
- // sourceStatus: TransactionStatus.SUCCESS,
419
- // status: isSameChain
420
- // ? TransactionStatus.SUCCESS
421
- // : TransactionStatus.ONGOING,
422
- // },
423
- // });
424
- // },
425
- // }
426
- // );
290
+ const swapQuerySolana = useMutation(async (route) => {
291
+ try {
292
+ if (!route) {
293
+ throw new Error("Route is required");
294
+ }
295
+ if (!solanaSigner) {
296
+ throw new Error("Solana signer is required");
297
+ }
298
+ if (!route.params.fromAddress || !route.params.toAddress) {
299
+ throw new Error("From or to address is required");
300
+ }
301
+ const isDirectTransfer = isDepositRoute(route);
302
+ // Get the deposit address from the squidRoute
303
+ const depositData = useDepositAddressStore.getState().deposit;
304
+ // Validate params
305
+ if (!depositData?.depositAddress) {
306
+ throw new Error("Deposit address is required");
307
+ }
308
+ // Means it's a transfer to a deposit address
309
+ // Instead of a Swap/Contract call using a DEX like Jupiter
310
+ if (isDirectTransfer) {
311
+ const signature = await executeSolanaTransfer({
312
+ amount: BigInt(route.params.fromAmount),
313
+ target: depositData.depositAddress,
314
+ solanaSigner,
315
+ connection,
316
+ onSigned: (txHash) => {
317
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
318
+ const txParams = setTransactionState({
319
+ route,
320
+ txHash,
321
+ transactionIdForStatus: depositData.chainflipStatusTrackingId,
322
+ userAddress: sourceUserAddress,
323
+ status: TransactionStatus.INITIAL_LOADING,
324
+ sourceStatus: TransactionStatus.ONGOING,
325
+ });
326
+ if (txParams) {
327
+ addTransaction({
328
+ ...txParams,
329
+ params: route.params,
330
+ estimate: route.estimate,
331
+ });
332
+ }
333
+ },
334
+ });
335
+ return signature;
336
+ }
337
+ const signature = await executeSolanaSwap({
338
+ route: route,
339
+ squid,
340
+ solanaSigner,
341
+ connection,
342
+ sourceUserAddress: route.params.fromAddress,
343
+ });
344
+ const txParams = setTransactionState({
345
+ route,
346
+ txHash: signature,
347
+ transactionIdForStatus: undefined,
348
+ userAddress: sourceUserAddress,
349
+ status: TransactionStatus.INITIAL_LOADING,
350
+ sourceStatus: TransactionStatus.ONGOING,
351
+ });
352
+ if (txParams) {
353
+ addTransaction({
354
+ ...txParams,
355
+ params: route.params,
356
+ estimate: route.estimate,
357
+ });
358
+ }
359
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, signature);
360
+ return signature;
361
+ }
362
+ catch (error) {
363
+ console.error("Solana transaction failed:", error);
364
+ throw error instanceof Error
365
+ ? error
366
+ : new Error("Failed to execute Solana transaction");
367
+ }
368
+ }, {
369
+ onError: (error) => {
370
+ const { currentTransaction: currentTx } = useTransactionStore.getState();
371
+ const errorObject = getTransactionError(error);
372
+ useTransactionStore.setState({
373
+ currentTransaction: {
374
+ ...currentTx,
375
+ status: TransactionStatus.ERROR,
376
+ sourceStatus: TransactionStatus.ERROR,
377
+ error: errorObject,
378
+ },
379
+ });
380
+ WidgetEvents.getInstance().dispatchSwapRouteExecutionError({
381
+ error: errorObject,
382
+ });
383
+ // TODO: Handle that for solana
384
+ if (currentTx?.transactionId &&
385
+ errorObject?.type === TransactionErrorType.CALL_EXCEPTION) {
386
+ replaceTransactionStatus(currentTx.transactionId, currentTx.statusResponse, TransactionStatus.ERROR);
387
+ }
388
+ },
389
+ onSuccess: () => {
390
+ const { currentTransaction: currentTx } = useTransactionStore.getState();
391
+ queryClient.invalidateQueries(getPrefixKey(QueryKeys.Balances));
392
+ if (isSameChain && currentTx?.transactionId) {
393
+ replaceTransactionStatus(currentTx.transactionId, currentTx.statusResponse, TransactionStatus.SUCCESS);
394
+ }
395
+ useTransactionStore.setState({
396
+ currentTransaction: {
397
+ ...currentTx,
398
+ sourceStatus: TransactionStatus.SUCCESS,
399
+ status: isSameChain
400
+ ? TransactionStatus.SUCCESS
401
+ : TransactionStatus.ONGOING,
402
+ },
403
+ });
404
+ },
405
+ });
427
406
  // // TODO: Find a better way to parse (route.transactionRequest as OnChainExecutionData)
428
- // const swapQueryBitcoin = useMutation(
429
- // async (route?: RouteResponse["route"]) => {
430
- // const depositAddress = (route?.transactionRequest as OnChainExecutionData)
431
- // ?.target;
432
- // const sendAmount = (route?.transactionRequest as OnChainExecutionData)
433
- // ?.value;
434
- // const allParamsValid =
435
- // route && bitcoinSigner && depositAddress && sendAmount;
436
- // await changeNetworkIfNeeded.mutateAsync();
437
- // if (allParamsValid) {
438
- // WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
439
- // route,
440
- // });
441
- // const { txHash } = await bitcoinSigner.sendBTC(
442
- // depositAddress,
443
- // Number(sendAmount)
444
- // );
445
- // if (txHash) {
446
- // resetQueriesAfterTxSigned();
447
- // }
448
- // // Dispatch event so it can be listened from outside the widget
449
- // WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
450
- // if (route.transactionRequest) {
451
- // const txParams: TransactionParams | undefined = setTransactionState({
452
- // route,
453
- // txHash,
454
- // // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
455
- // // instead of the Bitcoin transaction hash
456
- // transactionIdForStatus:
457
- // (route.transactionRequest as OnChainExecutionData)?.requestId ??
458
- // "",
459
- // userAddress: sourceUserAddress,
460
- // status: TransactionStatus.INITIAL_LOADING,
461
- // sourceStatus: TransactionStatus.ONGOING,
462
- // axelarUrl: undefined,
463
- // });
464
- // if (txParams) {
465
- // addTransaction({
466
- // ...txParams,
467
- // params: route.params,
468
- // estimate: route.estimate,
469
- // });
470
- // }
471
- // }
472
- // } else {
473
- // throw new Error("Need all parameters");
474
- // }
475
- // }
476
- // );
407
+ const swapQueryBitcoin = useMutation(async (route) => {
408
+ const depositAddress = route?.transactionRequest
409
+ ?.target;
410
+ const sendAmount = route?.transactionRequest
411
+ ?.value;
412
+ const allParamsValid = route && bitcoinSigner && depositAddress && sendAmount;
413
+ await changeNetworkIfNeeded.mutateAsync();
414
+ if (allParamsValid) {
415
+ WidgetEvents.getInstance().dispatchSwapTxSignatureRequested({
416
+ route,
417
+ });
418
+ const { txHash } = await bitcoinSigner.sendBTC(depositAddress, Number(sendAmount));
419
+ if (txHash) {
420
+ resetQueriesAfterTxSigned();
421
+ }
422
+ // Dispatch event so it can be listened from outside the widget
423
+ WidgetEvents.getInstance().dispatchSwapExecuteCall(route, txHash);
424
+ if (route.transactionRequest) {
425
+ const txParams = setTransactionState({
426
+ route,
427
+ txHash,
428
+ // When bridging from Bitcoin we need to send the chainflipId to the status endpoint
429
+ // instead of the Bitcoin transaction hash
430
+ transactionIdForStatus: route.transactionRequest?.requestId ??
431
+ "",
432
+ userAddress: sourceUserAddress,
433
+ status: TransactionStatus.INITIAL_LOADING,
434
+ sourceStatus: TransactionStatus.ONGOING,
435
+ axelarUrl: undefined,
436
+ });
437
+ if (txParams) {
438
+ addTransaction({
439
+ ...txParams,
440
+ params: route.params,
441
+ estimate: route.estimate,
442
+ });
443
+ }
444
+ }
445
+ }
446
+ else {
447
+ throw new Error("Need all parameters");
448
+ }
449
+ });
477
450
  const swapQuery = useMutation(async () => {
478
- const sourceChain = chains?.find((chain) => chain.chainId == squidRoute?.params?.fromChain);
451
+ const sourceChain = findChain(squidRoute?.params?.fromChain);
479
452
  switch (sourceChain?.chainType) {
480
453
  case ChainType.COSMOS: {
481
454
  return swapQueryCosmos.mutateAsync(squidRoute);
@@ -483,12 +456,12 @@ export const useExecuteTransaction = (squidRoute) => {
483
456
  case ChainType.EVM: {
484
457
  return swapQueryEvm.mutateAsync(squidRoute);
485
458
  }
486
- // case ChainType.BTC: {
487
- // return swapQueryBitcoin.mutateAsync(squidRoute);
488
- // }
489
- // case ChainType.SOLANA: {
490
- // return swapQuerySolana.mutateAsync(squidRoute);
491
- // }
459
+ case ChainType.BTC: {
460
+ return swapQueryBitcoin.mutateAsync(squidRoute);
461
+ }
462
+ case ChainType.SOLANA: {
463
+ return swapQuerySolana.mutateAsync(squidRoute);
464
+ }
492
465
  default:
493
466
  throw new Error("Invalid parameters or chain not found");
494
467
  }
@@ -538,7 +511,6 @@ export const useExecuteTransaction = (squidRoute) => {
538
511
  fromPrice,
539
512
  toChain,
540
513
  fromChain,
541
- executionState,
542
514
  signerReady,
543
515
  };
544
516
  };