@sodax/dapp-kit 2.1.0-rc.1 → 2.1.0-rc.3

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.
@@ -0,0 +1,132 @@
1
+ import type {
2
+ ApproveResponseV2,
3
+ CreateIntentParamsV2,
4
+ EvmRawTransaction,
5
+ GetWalletProviderType,
6
+ Hex,
7
+ IEvmWalletProvider,
8
+ IStellarWalletProvider,
9
+ RawTxReturnType,
10
+ RequestOverrideConfig,
11
+ SpokeChainKey,
12
+ StellarRawTransaction,
13
+ } from '@sodax/sdk';
14
+ import { isEvmSpokeOnlyChainKeyType, isHubChainKeyType, isStellarChainKeyType } from '@sodax/sdk';
15
+ import { useQueryClient } from '@tanstack/react-query';
16
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
17
+ import { unwrapResult } from '../shared/unwrapResult.js';
18
+ import type { MutationHookParams } from '../shared/types.js';
19
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
20
+
21
+ /** Hashes of the transactions this hook broadcast, in the order they were sent. */
22
+ export type SwapsApiApprovalHashes = {
23
+ /** Present only when the source token needed its stale allowance cleared first. */
24
+ readonly resetTxHash?: string;
25
+ readonly approveTxHash: string;
26
+ };
27
+
28
+ /** Names the transaction in an error, so a revert says which of the two steps failed. */
29
+ type ApprovalStep = 'allowance reset' | 'approve';
30
+
31
+ /**
32
+ * `EvmRawTransactionReceipt.status` is documented as the JSON-RPC hex flag, but `EvmWalletProvider`
33
+ * passes viem's `'reverted'` through unchanged, so both spellings reach this hook. A receipt without
34
+ * a status is pre-Byzantium and inconclusive — not a revert.
35
+ */
36
+ const isRevertedEvmReceiptStatus = (status: string | undefined): boolean => status === 'reverted' || status === '0x0';
37
+
38
+ export type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
39
+ body: CreateIntentParamsV2;
40
+ walletProvider: GetWalletProviderType<K>;
41
+ apiConfig?: RequestOverrideConfig;
42
+ };
43
+
44
+ /**
45
+ * React hook that runs the whole swaps-API approval: asks the API for the transactions, then signs,
46
+ * broadcasts, and waits for each one.
47
+ *
48
+ * Prefer this over {@link useSwapsApiApprove}, which returns the unsigned `{ tx, resetTx? }` and
49
+ * leaves the rest to you. A source token of the 2017 TetherToken lineage rejects an allowance change
50
+ * from one non-zero value to another, so the API can hand back a **reset** transaction that must be
51
+ * mined **before** the approve is even a valid state transition. Broadcasting them out of order, or
52
+ * without waiting, spends the user's gas on a transaction that is certain to revert — and that is
53
+ * ordering the package should own rather than every integration re-deriving it.
54
+ *
55
+ * Because confirmation now happens inside the hook, it can invalidate `['swapsApi','allowance']`
56
+ * itself; callers of `useSwapsApiApprove` have to refetch by hand.
57
+ *
58
+ * Supports the chains the swaps API can approve on — the hub (Sonic), EVM spokes, and Stellar.
59
+ * Every other chain reports its allowance as always sufficient, so approval never runs for it.
60
+ *
61
+ * @example
62
+ * const { mutateAsyncSafe: approve } = useSwapsApiApproveAndBroadcast();
63
+ * const result = await approve({ body: createIntentParams, walletProvider });
64
+ * if (!result.ok) return;
65
+ * const { resetTxHash, approveTxHash } = result.value; // resetTxHash only on a guarded token
66
+ */
67
+ export const useSwapsApiApproveAndBroadcast = <K extends SpokeChainKey = SpokeChainKey>({
68
+ mutationOptions,
69
+ }: MutationHookParams<SwapsApiApprovalHashes, UseSwapsApiApproveAndBroadcastVars<K>> = {}): SafeUseMutationResult<
70
+ SwapsApiApprovalHashes,
71
+ Error,
72
+ UseSwapsApiApproveAndBroadcastVars<K>
73
+ > => {
74
+ const { sodax } = useSodaxContext();
75
+ const queryClient = useQueryClient();
76
+
77
+ return useSafeMutation<SwapsApiApprovalHashes, Error, UseSwapsApiApproveAndBroadcastVars<K>>({
78
+ mutationKey: ['swapsApi', 'approveAndBroadcast'],
79
+ ...mutationOptions,
80
+ mutationFn: async ({ body, walletProvider, apiConfig }): Promise<SwapsApiApprovalHashes> => {
81
+ const { tx, resetTx }: ApproveResponseV2 = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
82
+ const srcChainKey = body.srcChainKey as SpokeChainKey;
83
+
84
+ // Broadcast and wait as one step: the next transaction is only valid once this one has landed,
85
+ // so returning before confirmation would hand the caller back the same ordering hazard.
86
+ const sendAndWait = async (raw: RawTxReturnType, step: ApprovalStep): Promise<string> => {
87
+ if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
88
+ const evm = walletProvider as IEvmWalletProvider;
89
+ const hash = await evm.sendTransaction(raw as EvmRawTransaction);
90
+ const receipt = await evm.waitForTransactionReceipt(hash as Hex);
91
+ // Mined is not the same as succeeded: a paused or blacklisted token reverts on-chain, and
92
+ // waiting alone would let the next transaction go out over an allowance that never moved.
93
+ if (isRevertedEvmReceiptStatus(receipt.status)) {
94
+ throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} reverted on chain.`);
95
+ }
96
+ return hash;
97
+ }
98
+
99
+ if (isStellarChainKeyType(srcChainKey)) {
100
+ const stellar = walletProvider as IStellarWalletProvider;
101
+ // Optional on the interface — not every Stellar wallet implements it.
102
+ if (!stellar.signAndSendTransaction) {
103
+ throw new Error(
104
+ '[useSwapsApiApproveAndBroadcast] this Stellar wallet provider does not implement signAndSendTransaction.',
105
+ );
106
+ }
107
+ const hash = await stellar.signAndSendTransaction(raw as StellarRawTransaction);
108
+ const receipt = await stellar.waitForTransactionReceipt(hash);
109
+ if (receipt.successful === false) {
110
+ throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} failed on chain.`);
111
+ }
112
+ return hash;
113
+ }
114
+
115
+ throw new Error(
116
+ `[useSwapsApiApproveAndBroadcast] ${srcChainKey} cannot be approved — the swaps API supports the hub (Sonic), EVM spokes, and Stellar.`,
117
+ );
118
+ };
119
+
120
+ // A throw here aborts before the approve is sent, which is the point: an unconfirmed reset
121
+ // leaves the allowance untouched, so a retry re-plans and costs a single transaction.
122
+ const resetTxHash = resetTx === undefined ? undefined : await sendAndWait(resetTx, 'allowance reset');
123
+ const approveTxHash = await sendAndWait(tx, 'approve');
124
+
125
+ return resetTxHash === undefined ? { approveTxHash } : { resetTxHash, approveTxHash };
126
+ },
127
+ onSuccess: async (data, vars, ctx) => {
128
+ queryClient.invalidateQueries({ queryKey: ['swapsApi', 'allowance'] });
129
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
130
+ },
131
+ });
132
+ };
@@ -24,7 +24,8 @@ export type UseSwapsApiSubmitTxStatusParams = ReadHookParams<
24
24
  * });
25
25
  *
26
26
  * @remarks
27
- * - Default refetch interval is 1 second; stops on 'solved' or 'failed' status.
27
+ * - Default refetch interval is 1 second; stops on 'solved' or 'failed' status, or when the
28
+ * backend marks the submission abandoned (`abandonedAt`) while `status` stays non-terminal.
28
29
  */
29
30
  export const useSwapsApiSubmitTxStatus = ({
30
31
  params,
@@ -46,8 +47,10 @@ export const useSwapsApiSubmitTxStatus = ({
46
47
  enabled: !!txHash && txHash.length > 0 && !!srcChainKey,
47
48
  retry: 3,
48
49
  refetchInterval: query => {
49
- const status = query.state.data?.data?.status;
50
- if (status === 'solved' || status === 'failed') return false;
50
+ const data = query.state.data?.data;
51
+ // `abandonedAt` is terminal even when `status` is still non-terminal — same rule as the
52
+ // SDK's pollBackendSubmitTx and the bridge-api status hook.
53
+ if (data?.status === 'solved' || data?.status === 'failed' || data?.abandonedAt) return false;
51
54
  return 1000;
52
55
  },
53
56
  ...queryOptions,