@sodax/dapp-kit 2.3.0-rc.4 → 2.4.0-rc.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.
- package/dist/index.d.ts +48 -28
- package/dist/index.mjs +108 -20
- package/package.json +10 -5
- package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.test.ts +28 -3
- package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.ts +17 -8
- package/src/hooks/bridge/useBridge.ts +6 -0
- package/src/hooks/bridge/useBridgeDetailedStatus.test.ts +56 -1
- package/src/hooks/bridge/useBridgeDetailedStatus.ts +26 -9
- package/src/hooks/bridge/useBridgeWithApproval.test.ts +24 -1
- package/src/hooks/bridge/useBridgeWithApproval.ts +6 -0
- package/src/hooks/dex/useDexDeposit.ts +6 -0
- package/src/hooks/dex/useDexWithdraw.ts +12 -5
- package/src/hooks/mm/useBorrow.ts +15 -4
- package/src/hooks/mm/useRepay.ts +6 -0
- package/src/hooks/mm/useSupply.ts +6 -0
- package/src/hooks/mm/useWithdraw.ts +12 -5
- package/src/hooks/recovery/useWithdrawHubAsset.ts +12 -5
- package/src/hooks/shared/notFoundStreak.ts +5 -0
- package/src/hooks/shared/retryBeforeSubmission.ts +26 -0
- package/src/hooks/shared/useBalances.test.ts +10 -0
- package/src/hooks/shared/useBalances.ts +17 -4
- package/src/hooks/shared/useSafeMutation.retry.test.ts +47 -0
- package/src/hooks/shared/useSafeMutation.ts +8 -1
- package/src/hooks/swap/useCreateLimitOrder.ts +8 -0
- package/src/hooks/swap/useSwap.ts +6 -0
- package/src/hooks/swap/useSwapLifecycle.test.ts +27 -1
- package/src/hooks/swap/useSwapWithApproval.test.ts +24 -1
- package/src/hooks/swap/useSwapWithApproval.ts +6 -0
- package/src/utils/swapLifecycle.ts +14 -2
|
@@ -12,6 +12,7 @@ import type { ReadHookParams } from '../shared/types.js';
|
|
|
12
12
|
import { advanceNotFoundStreak, INITIAL_NOT_FOUND_STREAK } from '../shared/notFoundStreak.js';
|
|
13
13
|
import {
|
|
14
14
|
getBridgeDetailedStatusRefetchInterval,
|
|
15
|
+
isBridgeMpcRelayRead,
|
|
15
16
|
isBridgeNotDelivered,
|
|
16
17
|
} from './getBridgeDetailedStatusRefetchInterval.js';
|
|
17
18
|
|
|
@@ -22,30 +23,41 @@ export type UseBridgeDetailedStatusParams = ReadHookParams<
|
|
|
22
23
|
{
|
|
23
24
|
srcChainKey: SpokeChainKey | undefined;
|
|
24
25
|
srcTxHash: string | undefined;
|
|
26
|
+
/** The bridge's destination; from Tron to another spoke the read waits for that leg. */
|
|
27
|
+
dstChainKey?: SpokeChainKey;
|
|
25
28
|
apiConfig?: RequestOverrideConfig;
|
|
26
29
|
}
|
|
27
30
|
>;
|
|
28
31
|
|
|
32
|
+
/** The hub tx a miss is waiting on past, once its first leg has reached the hub. */
|
|
33
|
+
function onwardHubTxHash(data: UseBridgeDetailedStatusResult): string | undefined {
|
|
34
|
+
const hubTxHash = data && !data.ok ? data.error.context?.hubTxHash : undefined;
|
|
35
|
+
return typeof hubTxHash === 'string' ? hubTxHash : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
29
38
|
/**
|
|
30
39
|
* Hook for monitoring a bridge from its source-chain transaction.
|
|
31
40
|
*
|
|
32
41
|
* `useBridgeApiSubmitTxStatus` needs the backend to still hold a usable record; this takes
|
|
33
|
-
* `(srcChainKey, srcTxHash)` — the pair you hold after `bridge()`
|
|
42
|
+
* `(srcChainKey, srcTxHash)` — the pair you hold after `bridge()`, plus `dstChainKey` for a bridge from Tron —
|
|
43
|
+
* and routes to whichever source
|
|
34
44
|
* can answer, so it also covers a bridge the client-side fallback completed. `data.value` is
|
|
35
45
|
* discriminated on `source`, and each variant carries that source's payload unmodified.
|
|
36
46
|
*
|
|
37
47
|
* Polls every 3s. Stops once the answering source is terminal (a relay packet always is), once the
|
|
38
48
|
* backend rejects the API key, and — like `useDetailedStatus` — after 40 consecutive *ambiguous*
|
|
39
|
-
* reads, meaning a `LOOKUP_FAILED` whose relay has no packet for the tx
|
|
49
|
+
* reads, meaning a `LOOKUP_FAILED` whose relay has no packet for the tx — 100, about 5 minutes, for a bridge
|
|
50
|
+
* with an MPC-relay end (`context.mpcRelay`), which settles more slowly. A dependency outage keeps
|
|
40
51
|
* polling instead, so the read recovers by itself; any real answer resets the budget. Override with
|
|
41
52
|
* `queryOptions.refetchInterval`.
|
|
42
53
|
*
|
|
43
54
|
* @example
|
|
44
55
|
* ```typescript
|
|
45
|
-
* const { data } = useBridgeDetailedStatus({ params: { srcChainKey, srcTxHash } });
|
|
56
|
+
* const { data } = useBridgeDetailedStatus({ params: { srcChainKey, srcTxHash, dstChainKey } });
|
|
46
57
|
* if (data?.ok && data.value.source === 'relay') console.log(data.value.data.dst_tx_hash);
|
|
47
58
|
* ```
|
|
48
59
|
*/
|
|
60
|
+
|
|
49
61
|
export const useBridgeDetailedStatus = ({
|
|
50
62
|
params,
|
|
51
63
|
queryOptions,
|
|
@@ -53,26 +65,31 @@ export const useBridgeDetailedStatus = ({
|
|
|
53
65
|
const { sodax } = useSodaxContext();
|
|
54
66
|
const srcChainKey = params?.srcChainKey;
|
|
55
67
|
const srcTxHash = params?.srcTxHash;
|
|
68
|
+
const dstChainKey = params?.dstChainKey;
|
|
56
69
|
const apiConfig = params?.apiConfig;
|
|
57
70
|
// Composite identity: a new bridge must start its own not-delivered budget.
|
|
58
|
-
const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : undefined;
|
|
71
|
+
const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}:${dstChainKey ?? ''}` : undefined;
|
|
59
72
|
const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
|
|
60
73
|
|
|
61
74
|
return useQuery({
|
|
62
|
-
queryKey: ['bridge', 'detailedStatus', srcChainKey, srcTxHash],
|
|
75
|
+
queryKey: ['bridge', 'detailedStatus', srcChainKey, srcTxHash, ...(dstChainKey ? [dstChainKey] : [])],
|
|
63
76
|
queryFn: async () => {
|
|
64
77
|
if (!srcChainKey || !srcTxHash) return undefined;
|
|
65
|
-
return sodax.bridge.getDetailedStatus({ srcChainKey, srcTxHash }, apiConfig);
|
|
78
|
+
return sodax.bridge.getDetailedStatus({ srcChainKey, srcTxHash, dstChainKey }, apiConfig);
|
|
66
79
|
},
|
|
67
80
|
enabled: !!srcChainKey && !!srcTxHash,
|
|
68
81
|
refetchInterval: query => {
|
|
82
|
+
// Reaching the hub is progress, so the leg after it gets a budget of its own. An MPC-relay miss counts
|
|
83
|
+
// on its own streak too, so one untagged miss in between cannot cut its longer budget short.
|
|
84
|
+
const { data } = query.state;
|
|
85
|
+
const leg = [onwardHubTxHash(data), isBridgeMpcRelayRead(data) ? 'mpcRelay' : undefined].filter(Boolean);
|
|
69
86
|
notFoundStreakRef.current = advanceNotFoundStreak(
|
|
70
87
|
notFoundStreakRef.current,
|
|
71
|
-
pollKey,
|
|
72
|
-
isBridgeNotDelivered(
|
|
88
|
+
pollKey && [pollKey, ...leg].join(':'),
|
|
89
|
+
isBridgeNotDelivered(data),
|
|
73
90
|
query.state.dataUpdateCount,
|
|
74
91
|
);
|
|
75
|
-
return getBridgeDetailedStatusRefetchInterval(
|
|
92
|
+
return getBridgeDetailedStatusRefetchInterval(data, notFoundStreakRef.current.consecutiveNotFound);
|
|
76
93
|
},
|
|
77
94
|
...queryOptions,
|
|
78
95
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChainKeys } from '@sodax/sdk';
|
|
1
|
+
import { ATOMIC_BATCH_UNCONFIRMED, ChainKeys, SodaxError } from '@sodax/sdk';
|
|
2
2
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
3
|
|
|
4
4
|
const VARS = {
|
|
@@ -8,6 +8,7 @@ const VARS = {
|
|
|
8
8
|
|
|
9
9
|
type CapturedMutation = {
|
|
10
10
|
mutationKey: unknown;
|
|
11
|
+
retry: (failureCount: number, error: Error) => boolean;
|
|
11
12
|
mutationFn: (vars: unknown) => Promise<unknown>;
|
|
12
13
|
onSuccess: (data: unknown, vars: typeof VARS, ctx: unknown) => Promise<void>;
|
|
13
14
|
};
|
|
@@ -33,6 +34,28 @@ beforeEach(() => {
|
|
|
33
34
|
});
|
|
34
35
|
|
|
35
36
|
describe('useBridgeWithApproval', () => {
|
|
37
|
+
it.each([
|
|
38
|
+
{ batchId: 'batch-1' },
|
|
39
|
+
{ reason: ATOMIC_BATCH_UNCONFIRMED },
|
|
40
|
+
])('suppresses configured retries after an unconfirmed batch ($context)', context => {
|
|
41
|
+
useBridgeWithApproval({ mutationOptions: { retry: 3 } });
|
|
42
|
+
const error = new SodaxError('TX_VERIFICATION_FAILED', 'Batch was sent but not confirmed', {
|
|
43
|
+
feature: 'bridge',
|
|
44
|
+
context,
|
|
45
|
+
});
|
|
46
|
+
expect(captured.retry(0, error)).toBe(false);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('suppresses configured retries when the original source hash is known', () => {
|
|
50
|
+
useBridgeWithApproval({ mutationOptions: { retry: 3 } });
|
|
51
|
+
const error = new SodaxError('RELAY_TIMEOUT', 'Settlement pending', {
|
|
52
|
+
feature: 'bridge',
|
|
53
|
+
context: { srcTxHash: '0x1234' },
|
|
54
|
+
});
|
|
55
|
+
expect(captured.retry(0, error)).toBe(false);
|
|
56
|
+
expect(captured.retry(0, new Error('Before submission'))).toBe(true);
|
|
57
|
+
});
|
|
58
|
+
|
|
36
59
|
it('keys the mutation under bridge and calls bridgeWithApproval in signed mode', async () => {
|
|
37
60
|
bridgeWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
|
|
38
61
|
useBridgeWithApproval();
|
|
@@ -4,6 +4,7 @@ import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
|
4
4
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
5
5
|
import type { MutationHookParams } from '../shared/types.js';
|
|
6
6
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
7
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
7
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -37,6 +38,11 @@ export function useBridgeWithApproval<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
37
38
|
return useSafeMutation<BridgeWithApprovalResponse, Error, UseBridgeWithApprovalVars<K>>({
|
|
38
39
|
mutationKey: ['bridge', 'bridgeWithApproval'],
|
|
39
40
|
...mutationOptions,
|
|
41
|
+
retry: retryBeforeSubmission(
|
|
42
|
+
mutationOptions?.retry ??
|
|
43
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['bridge', 'bridgeWithApproval'])?.retry ??
|
|
44
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
45
|
+
),
|
|
40
46
|
mutationFn: async vars => unwrapResult(await sodax.bridge.bridgeWithApproval({ ...vars, raw: false })),
|
|
41
47
|
onSuccess: async (data, vars, ctx) => {
|
|
42
48
|
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
|
@@ -5,6 +5,7 @@ import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
8
9
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -44,6 +45,11 @@ export function useDexDeposit<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
44
45
|
return useSafeMutation<TxHashPair, Error, UseDexDepositVars<K>>({
|
|
45
46
|
mutationKey: ['dex', 'deposit'],
|
|
46
47
|
...mutationOptions,
|
|
48
|
+
retry: retryBeforeSubmission(
|
|
49
|
+
mutationOptions?.retry ??
|
|
50
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['dex', 'deposit'])?.retry ??
|
|
51
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
52
|
+
),
|
|
47
53
|
mutationFn: async vars => unwrapResult(await sodax.dex.assetService.deposit({ ...vars, raw: false })),
|
|
48
54
|
onSuccess: async (data, vars, ctx) => {
|
|
49
55
|
const { params } = vars;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// packages/dapp-kit/src/hooks/dex/useDexWithdraw.ts
|
|
2
|
-
import type { AssetWithdrawAction, SpokeChainKey,
|
|
2
|
+
import type { AssetWithdrawAction, SpokeChainKey, OutboundSettlement } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
8
9
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -18,21 +19,27 @@ export type UseDexWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<A
|
|
|
18
19
|
* React hook for withdrawing an asset from a DEX pool.
|
|
19
20
|
*
|
|
20
21
|
* Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
|
|
21
|
-
* `onError`, `retry`). Returns the unwrapped
|
|
22
|
+
* `onError`, `retry`). Returns the unwrapped {@link OutboundSettlement} on success: a tx pair, or
|
|
23
|
+
* from Tron the relay's `trackingId` beside the destination tx.
|
|
22
24
|
*/
|
|
23
25
|
export function useDexWithdraw<K extends SpokeChainKey = SpokeChainKey>({
|
|
24
26
|
mutationOptions,
|
|
25
|
-
}: MutationHookParams<
|
|
26
|
-
|
|
27
|
+
}: MutationHookParams<OutboundSettlement<K>, UseDexWithdrawVars<K>> = {}): SafeUseMutationResult<
|
|
28
|
+
OutboundSettlement<K>,
|
|
27
29
|
Error,
|
|
28
30
|
UseDexWithdrawVars<K>
|
|
29
31
|
> {
|
|
30
32
|
const { sodax } = useSodaxContext();
|
|
31
33
|
const queryClient = useQueryClient();
|
|
32
34
|
|
|
33
|
-
return useSafeMutation<
|
|
35
|
+
return useSafeMutation<OutboundSettlement<K>, Error, UseDexWithdrawVars<K>>({
|
|
34
36
|
mutationKey: ['dex', 'withdraw'],
|
|
35
37
|
...mutationOptions,
|
|
38
|
+
retry: retryBeforeSubmission(
|
|
39
|
+
mutationOptions?.retry ??
|
|
40
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['dex', 'withdraw'])?.retry ??
|
|
41
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
42
|
+
),
|
|
36
43
|
mutationFn: async vars => unwrapResult(await sodax.dex.assetService.withdraw({ ...vars, raw: false })),
|
|
37
44
|
onSuccess: async (data, vars, ctx) => {
|
|
38
45
|
const { params } = vars;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// packages/dapp-kit/src/hooks/mm/useBorrow.ts
|
|
2
|
-
import type { MoneyMarketBorrowActionParams, SpokeChainKey,
|
|
2
|
+
import type { MoneyMarketBorrowActionParams, SpokeChainKey, OutboundSettlement } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Mutation variables for {@link useBorrow}. Generic over `K extends SpokeChainKey` (defaults to
|
|
@@ -21,17 +22,27 @@ export type UseBorrowVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
|
|
|
21
22
|
* React hook for borrowing tokens from the Sodax money market protocol.
|
|
22
23
|
*
|
|
23
24
|
* Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
|
|
24
|
-
* `onError`, `retry`). Returns the unwrapped
|
|
25
|
+
* `onError`, `retry`). Returns the unwrapped {@link OutboundSettlement} on success: a tx pair, or
|
|
26
|
+
* from Tron the relay's `trackingId` beside the destination tx.
|
|
25
27
|
*/
|
|
26
28
|
export function useBorrow<K extends SpokeChainKey = SpokeChainKey>({
|
|
27
29
|
mutationOptions,
|
|
28
|
-
}: MutationHookParams<
|
|
30
|
+
}: MutationHookParams<OutboundSettlement<K>, UseBorrowVars<K>> = {}): SafeUseMutationResult<
|
|
31
|
+
OutboundSettlement<K>,
|
|
32
|
+
Error,
|
|
33
|
+
UseBorrowVars<K>
|
|
34
|
+
> {
|
|
29
35
|
const { sodax } = useSodaxContext();
|
|
30
36
|
const queryClient = useQueryClient();
|
|
31
37
|
|
|
32
|
-
return useSafeMutation<
|
|
38
|
+
return useSafeMutation<OutboundSettlement<K>, Error, UseBorrowVars<K>>({
|
|
33
39
|
mutationKey: ['mm', 'borrow'],
|
|
34
40
|
...mutationOptions,
|
|
41
|
+
retry: retryBeforeSubmission(
|
|
42
|
+
mutationOptions?.retry ??
|
|
43
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['mm', 'borrow'])?.retry ??
|
|
44
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
45
|
+
),
|
|
35
46
|
mutationFn: async vars => unwrapResult(await sodax.moneyMarket.borrow({ ...vars, raw: false })),
|
|
36
47
|
onSuccess: async (data, vars, ctx) => {
|
|
37
48
|
const { params } = vars;
|
package/src/hooks/mm/useRepay.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
8
9
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -29,6 +30,11 @@ export function useRepay<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
29
30
|
return useSafeMutation<TxHashPair, Error, UseRepayVars<K>>({
|
|
30
31
|
mutationKey: ['mm', 'repay'],
|
|
31
32
|
...mutationOptions,
|
|
33
|
+
retry: retryBeforeSubmission(
|
|
34
|
+
mutationOptions?.retry ??
|
|
35
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['mm', 'repay'])?.retry ??
|
|
36
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
37
|
+
),
|
|
32
38
|
mutationFn: async vars => unwrapResult(await sodax.moneyMarket.repay({ ...vars, raw: false })),
|
|
33
39
|
onSuccess: async (data, vars, ctx) => {
|
|
34
40
|
const { params } = vars;
|
|
@@ -5,6 +5,7 @@ import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
8
9
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -44,6 +45,11 @@ export function useSupply<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
44
45
|
return useSafeMutation<TxHashPair, Error, UseSupplyVars<K>>({
|
|
45
46
|
mutationKey: ['mm', 'supply'],
|
|
46
47
|
...mutationOptions,
|
|
48
|
+
retry: retryBeforeSubmission(
|
|
49
|
+
mutationOptions?.retry ??
|
|
50
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['mm', 'supply'])?.retry ??
|
|
51
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
52
|
+
),
|
|
47
53
|
mutationFn: async vars => unwrapResult(await sodax.moneyMarket.supply({ ...vars, raw: false })),
|
|
48
54
|
onSuccess: async (data, vars, ctx) => {
|
|
49
55
|
const { params } = vars;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// packages/dapp-kit/src/hooks/mm/useWithdraw.ts
|
|
2
|
-
import type { MoneyMarketWithdrawActionParams, SpokeChainKey,
|
|
2
|
+
import type { MoneyMarketWithdrawActionParams, SpokeChainKey, OutboundSettlement } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Mutation variables for {@link useWithdraw}. Generic over `K extends SpokeChainKey` (defaults to
|
|
@@ -21,21 +22,27 @@ export type UseWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
|
|
|
21
22
|
* React hook for withdrawing supplied tokens from the Sodax money market protocol.
|
|
22
23
|
*
|
|
23
24
|
* Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
|
|
24
|
-
* `onError`, `retry`). Returns the unwrapped
|
|
25
|
+
* `onError`, `retry`). Returns the unwrapped {@link OutboundSettlement} on success: a tx pair, or
|
|
26
|
+
* from Tron the relay's `trackingId` beside the destination tx.
|
|
25
27
|
*/
|
|
26
28
|
export function useWithdraw<K extends SpokeChainKey = SpokeChainKey>({
|
|
27
29
|
mutationOptions,
|
|
28
|
-
}: MutationHookParams<
|
|
29
|
-
|
|
30
|
+
}: MutationHookParams<OutboundSettlement<K>, UseWithdrawVars<K>> = {}): SafeUseMutationResult<
|
|
31
|
+
OutboundSettlement<K>,
|
|
30
32
|
Error,
|
|
31
33
|
UseWithdrawVars<K>
|
|
32
34
|
> {
|
|
33
35
|
const { sodax } = useSodaxContext();
|
|
34
36
|
const queryClient = useQueryClient();
|
|
35
37
|
|
|
36
|
-
return useSafeMutation<
|
|
38
|
+
return useSafeMutation<OutboundSettlement<K>, Error, UseWithdrawVars<K>>({
|
|
37
39
|
mutationKey: ['mm', 'withdraw'],
|
|
38
40
|
...mutationOptions,
|
|
41
|
+
retry: retryBeforeSubmission(
|
|
42
|
+
mutationOptions?.retry ??
|
|
43
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['mm', 'withdraw'])?.retry ??
|
|
44
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
45
|
+
),
|
|
39
46
|
mutationFn: async vars => unwrapResult(await sodax.moneyMarket.withdraw({ ...vars, raw: false })),
|
|
40
47
|
onSuccess: async (data, vars, ctx) => {
|
|
41
48
|
const { params } = vars;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// packages/dapp-kit/src/hooks/recovery/useWithdrawHubAsset.ts
|
|
2
|
-
import type { SpokeChainKey,
|
|
2
|
+
import type { SpokeChainKey, SendMessageReturnType, WithdrawHubAssetAction } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
5
|
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
8
9
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -21,21 +22,27 @@ export type UseWithdrawHubAssetVars<K extends SpokeChainKey = SpokeChainKey> = O
|
|
|
21
22
|
* React hook for withdrawing a hub-side asset back to the user's spoke chain wallet.
|
|
22
23
|
*
|
|
23
24
|
* Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
|
|
24
|
-
* `onError`, `retry`). Returns the
|
|
25
|
+
* `onError`, `retry`). Returns the spoke tx hash on success, or from an MPC-relay chain (Tron) the
|
|
26
|
+
* relay's `trackingId`, which is not a tx hash: never link it to an explorer.
|
|
25
27
|
*/
|
|
26
28
|
export function useWithdrawHubAsset<K extends SpokeChainKey = SpokeChainKey>({
|
|
27
29
|
mutationOptions,
|
|
28
|
-
}: MutationHookParams<
|
|
29
|
-
|
|
30
|
+
}: MutationHookParams<SendMessageReturnType<K, false>, UseWithdrawHubAssetVars<K>> = {}): SafeUseMutationResult<
|
|
31
|
+
SendMessageReturnType<K, false>,
|
|
30
32
|
Error,
|
|
31
33
|
UseWithdrawHubAssetVars<K>
|
|
32
34
|
> {
|
|
33
35
|
const { sodax } = useSodaxContext();
|
|
34
36
|
const queryClient = useQueryClient();
|
|
35
37
|
|
|
36
|
-
return useSafeMutation<
|
|
38
|
+
return useSafeMutation<SendMessageReturnType<K, false>, Error, UseWithdrawHubAssetVars<K>>({
|
|
37
39
|
mutationKey: ['recovery', 'withdrawHubAsset'],
|
|
38
40
|
...mutationOptions,
|
|
41
|
+
retry: retryBeforeSubmission(
|
|
42
|
+
mutationOptions?.retry ??
|
|
43
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['recovery', 'withdrawHubAsset'])?.retry ??
|
|
44
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
45
|
+
),
|
|
39
46
|
mutationFn: async vars => unwrapResult(await sodax.recovery.withdrawHubAsset<K, false>({ ...vars, raw: false })),
|
|
40
47
|
onSuccess: async (data, vars, ctx) => {
|
|
41
48
|
const { params } = vars;
|
|
@@ -16,6 +16,11 @@
|
|
|
16
16
|
export const STATUS_POLL_MS = 3000;
|
|
17
17
|
/** Cap consecutive ambiguous polls (~2 min at 3s). The first one is a race, not a stop. */
|
|
18
18
|
export const MAX_NOT_FOUND_POLLS = 40;
|
|
19
|
+
/**
|
|
20
|
+
* The cap for a read the SDK tags `context.mpcRelay` (~5 min at 3s). An MPC-relay leg waits on confirmations,
|
|
21
|
+
* the NEAR signature and the hub tx, and the SDK itself allows it at least 5 minutes.
|
|
22
|
+
*/
|
|
23
|
+
export const MAX_MPC_RELAY_NOT_FOUND_POLLS = 100;
|
|
19
24
|
|
|
20
25
|
export type NotFoundStreakState = {
|
|
21
26
|
/** Identity of what is being polled — an intent tx hash, or a composite source-chain/tx key. */
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ATOMIC_BATCH_UNCONFIRMED, isIndeterminateOutcomeError, isSodaxError } from '@sodax/sdk';
|
|
2
|
+
import type { UseMutationOptions } from '@tanstack/react-query';
|
|
3
|
+
|
|
4
|
+
/** A mutation may have moved funds. Only retry errors without an existing operation to resume. */
|
|
5
|
+
export function retryBeforeSubmission<TError>(retry: UseMutationOptions<unknown, TError>['retry']) {
|
|
6
|
+
return (failureCount: number, error: TError): boolean => {
|
|
7
|
+
if (isIndeterminateOutcomeError(error)) return false;
|
|
8
|
+
if (isSodaxError(error)) {
|
|
9
|
+
const { srcTxHash, hubTxHash, dstTxHash, trackingId, recovery, batchId, reason } = error.context ?? {};
|
|
10
|
+
if (
|
|
11
|
+
srcTxHash ||
|
|
12
|
+
hubTxHash ||
|
|
13
|
+
dstTxHash ||
|
|
14
|
+
trackingId ||
|
|
15
|
+
recovery ||
|
|
16
|
+
batchId ||
|
|
17
|
+
reason === ATOMIC_BATCH_UNCONFIRMED
|
|
18
|
+
) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (typeof retry === 'function') return retry(failureCount, error);
|
|
23
|
+
if (typeof retry === 'number') return failureCount < retry;
|
|
24
|
+
return retry === true;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -43,6 +43,16 @@ describe('getBalancesQueryOptions', () => {
|
|
|
43
43
|
]);
|
|
44
44
|
});
|
|
45
45
|
|
|
46
|
+
it('keys TON wallet balances by the account address and forwards it to the SDK', async () => {
|
|
47
|
+
const sodax = makeSodax({ ok: true, value: {} });
|
|
48
|
+
const inputs = { chainKey: 'ton' as const, tokens: [tokenA], address: '0xpubkey' };
|
|
49
|
+
const accountAddress = 'EQ-wallet';
|
|
50
|
+
const opts = getBalancesQueryOptions(sodax, { ...inputs, accountAddress });
|
|
51
|
+
expect(opts.queryKey).not.toEqual(getBalancesQueryOptions(sodax, inputs).queryKey);
|
|
52
|
+
await opts.queryFn();
|
|
53
|
+
expect(sodax.spoke.getWalletBalances).toHaveBeenCalledWith(expect.objectContaining({ accountAddress }));
|
|
54
|
+
});
|
|
55
|
+
|
|
46
56
|
it('is disabled when chainKey is missing', () => {
|
|
47
57
|
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
48
58
|
chainKey: undefined,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type UseQueryResult, useQuery } from '@tanstack/react-query';
|
|
2
|
-
import type
|
|
2
|
+
import { ChainKeys, type Sodax, type SpokeChainKey, type XToken } from '@sodax/sdk';
|
|
3
3
|
import { useSodaxContext } from './useSodaxContext.js';
|
|
4
4
|
import { unwrapResult } from './unwrapResult.js';
|
|
5
5
|
import type { ReadHookParams } from './types.js';
|
|
@@ -15,6 +15,8 @@ export interface BalancesInputs {
|
|
|
15
15
|
chainKey: SpokeChainKey | undefined;
|
|
16
16
|
tokens: readonly XToken[];
|
|
17
17
|
address: string | undefined;
|
|
18
|
+
/** TON only: wallet account to read. Defaults to the public key’s wallet-v4R2 address. */
|
|
19
|
+
accountAddress?: string;
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
export type UseBalancesParams = ReadHookParams<Record<string, bigint>, BalancesInputs>;
|
|
@@ -26,14 +28,24 @@ const REFETCH_INTERVAL_MS = 5_000;
|
|
|
26
28
|
* callers that compose their own `useQuery` wrapper. Takes the SDK instance explicitly (the hook
|
|
27
29
|
* supplies it from context).
|
|
28
30
|
*/
|
|
29
|
-
export function getBalancesQueryOptions(sodax: Sodax, { chainKey, tokens, address }: BalancesInputs) {
|
|
31
|
+
export function getBalancesQueryOptions(sodax: Sodax, { chainKey, tokens, address, accountAddress }: BalancesInputs) {
|
|
32
|
+
const tonAccount = chainKey === ChainKeys.TON_MAINNET && accountAddress ? { accountAddress } : undefined;
|
|
30
33
|
return {
|
|
31
34
|
// Pair symbol + address: readable in devtools, unique on-chain (symbol alone can collide —
|
|
32
35
|
// e.g. scam tokens copying a legitimate ticker).
|
|
33
|
-
queryKey: [
|
|
36
|
+
queryKey: [
|
|
37
|
+
'shared',
|
|
38
|
+
'balances',
|
|
39
|
+
chainKey,
|
|
40
|
+
tokens.map(t => [t.symbol, t.address] as const),
|
|
41
|
+
address,
|
|
42
|
+
...(tonAccount ? [tonAccount.accountAddress] : []),
|
|
43
|
+
] as const,
|
|
34
44
|
queryFn: async (): Promise<Record<string, bigint>> => {
|
|
35
45
|
if (!chainKey || !address) return {};
|
|
36
|
-
return unwrapResult(
|
|
46
|
+
return unwrapResult(
|
|
47
|
+
await sodax.spoke.getWalletBalances({ srcChainKey: chainKey, srcAddress: address, tokens, ...tonAccount }),
|
|
48
|
+
);
|
|
37
49
|
},
|
|
38
50
|
enabled: !!chainKey && !!address && tokens.length > 0,
|
|
39
51
|
refetchInterval: REFETCH_INTERVAL_MS,
|
|
@@ -75,6 +87,7 @@ export function useBalances({ params, queryOptions }: UseBalancesParams = {}): U
|
|
|
75
87
|
chainKey: params?.chainKey,
|
|
76
88
|
tokens: params?.tokens ?? [],
|
|
77
89
|
address: params?.address,
|
|
90
|
+
accountAddress: params?.accountAddress,
|
|
78
91
|
}),
|
|
79
92
|
...queryOptions,
|
|
80
93
|
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { SodaxError } from '@sodax/sdk';
|
|
2
|
+
import { QueryClient, type UseMutationOptions } from '@tanstack/react-query';
|
|
3
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
4
|
+
import { useLeverageYieldVaultSwap } from '../leverageYield/useLeverageYieldVaultSwap.js';
|
|
5
|
+
import { useLeverageYieldVaultSwapWithApproval } from '../leverageYield/useLeverageYieldVaultSwapWithApproval.js';
|
|
6
|
+
import { useFeeClaimWithdraw } from '../partner/useFeeClaimWithdraw.js';
|
|
7
|
+
import { useSwapsApiBroadcastWithApproval } from '../swapsApi/useSwapsApiBroadcastWithApproval.js';
|
|
8
|
+
|
|
9
|
+
let queryClient: QueryClient;
|
|
10
|
+
let options: UseMutationOptions<unknown, Error, unknown>;
|
|
11
|
+
|
|
12
|
+
vi.mock('./useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax: {} }) }));
|
|
13
|
+
vi.mock('react', async importOriginal => ({
|
|
14
|
+
...(await importOriginal<typeof import('react')>()),
|
|
15
|
+
useCallback: (fn: unknown) => fn,
|
|
16
|
+
}));
|
|
17
|
+
vi.mock('@tanstack/react-query', async importOriginal => ({
|
|
18
|
+
...(await importOriginal<typeof import('@tanstack/react-query')>()),
|
|
19
|
+
useQueryClient: () => queryClient,
|
|
20
|
+
useMutation: (value: typeof options) => {
|
|
21
|
+
options = value;
|
|
22
|
+
return {};
|
|
23
|
+
},
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false, retryDelay: 0 } } });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it.each([
|
|
31
|
+
{ hook: useLeverageYieldVaultSwap, name: 'useLeverageYieldVaultSwap' },
|
|
32
|
+
{ hook: useLeverageYieldVaultSwapWithApproval, name: 'useLeverageYieldVaultSwapWithApproval' },
|
|
33
|
+
{ hook: useSwapsApiBroadcastWithApproval, name: 'useSwapsApiBroadcastWithApproval' },
|
|
34
|
+
{ hook: useFeeClaimWithdraw, name: 'useFeeClaimWithdraw' },
|
|
35
|
+
])('$name preserves keyed retries before submission and stops after submission', async ({ hook }) => {
|
|
36
|
+
queryClient.setMutationDefaults(['retry-test'], { retry: 2 });
|
|
37
|
+
hook({ mutationOptions: { mutationKey: ['retry-test'] } });
|
|
38
|
+
const pending = new SodaxError('RELAY_TIMEOUT', 'Settlement pending', {
|
|
39
|
+
feature: 'bridge',
|
|
40
|
+
context: { srcTxHash: '0x1234' },
|
|
41
|
+
});
|
|
42
|
+
const submit = vi.fn().mockRejectedValueOnce(new Error('Before submission')).mockRejectedValue(pending);
|
|
43
|
+
const mutation = queryClient.getMutationCache().build(queryClient, { ...options, mutationFn: submit });
|
|
44
|
+
|
|
45
|
+
await expect(mutation.execute(undefined)).rejects.toBe(pending);
|
|
46
|
+
expect(submit).toHaveBeenCalledTimes(2);
|
|
47
|
+
});
|
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
import type { Result } from '@sodax/sdk';
|
|
3
3
|
import {
|
|
4
4
|
useMutation,
|
|
5
|
+
useQueryClient,
|
|
5
6
|
type MutateOptions,
|
|
6
7
|
type UseMutationOptions,
|
|
7
8
|
type UseMutationResult,
|
|
8
9
|
} from '@tanstack/react-query';
|
|
9
10
|
import { useCallback } from 'react';
|
|
11
|
+
import { retryBeforeSubmission } from './retryBeforeSubmission.js';
|
|
10
12
|
|
|
11
13
|
/**
|
|
12
14
|
* Return shape of every dapp-kit mutation hook. Extends `UseMutationResult` with one extra
|
|
@@ -54,7 +56,12 @@ export async function toResult<T>(promise: Promise<T>): Promise<Result<T>> {
|
|
|
54
56
|
export function useSafeMutation<TData, TError, TVars, TContext = unknown>(
|
|
55
57
|
options: UseMutationOptions<TData, TError, TVars, TContext>,
|
|
56
58
|
): SafeUseMutationResult<TData, TError, TVars, TContext> {
|
|
57
|
-
const
|
|
59
|
+
const queryClient = useQueryClient();
|
|
60
|
+
const { retry } = queryClient.defaultMutationOptions(options);
|
|
61
|
+
const mutation = useMutation<TData, TError, TVars, TContext>({
|
|
62
|
+
...options,
|
|
63
|
+
retry: retryBeforeSubmission(retry),
|
|
64
|
+
});
|
|
58
65
|
const { mutateAsync } = mutation;
|
|
59
66
|
const mutateAsyncSafe = useCallback(
|
|
60
67
|
(vars: TVars, opts?: MutateOptions<TData, TError, TVars, TContext>): Promise<Result<TData>> =>
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
1
2
|
// packages/dapp-kit/src/hooks/swap/useCreateLimitOrder.ts
|
|
2
3
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
3
4
|
import type { LimitOrderActionParams, SpokeChainKey, SwapResponse } from '@sodax/sdk';
|
|
4
5
|
import type { MutationHookParams } from '../shared/types.js';
|
|
5
6
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
7
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
6
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
7
9
|
|
|
8
10
|
/**
|
|
@@ -29,10 +31,16 @@ export function useCreateLimitOrder<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
29
31
|
UseCreateLimitOrderVars<K>
|
|
30
32
|
> {
|
|
31
33
|
const { sodax } = useSodaxContext();
|
|
34
|
+
const queryClient = useQueryClient();
|
|
32
35
|
|
|
33
36
|
return useSafeMutation<SwapResponse, Error, UseCreateLimitOrderVars<K>>({
|
|
34
37
|
mutationKey: ['swap', 'limitOrder', 'create'],
|
|
35
38
|
...mutationOptions,
|
|
39
|
+
retry: retryBeforeSubmission(
|
|
40
|
+
mutationOptions?.retry ??
|
|
41
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['swap', 'limitOrder', 'create'])?.retry ??
|
|
42
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
43
|
+
),
|
|
36
44
|
mutationFn: async vars => unwrapResult(await sodax.swaps.createLimitOrder({ ...vars, raw: false })),
|
|
37
45
|
});
|
|
38
46
|
}
|
|
@@ -6,6 +6,7 @@ import { useQueryClient } from '@tanstack/react-query';
|
|
|
6
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
7
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
8
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
9
|
+
import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Mutation variables for {@link useSwap}. Generic over `K extends SpokeChainKey` (defaults to the
|
|
@@ -29,6 +30,11 @@ export function useSwap<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
29
30
|
return useSafeMutation<SwapResponse, Error, UseSwapVars<K>>({
|
|
30
31
|
mutationKey: ['swap'],
|
|
31
32
|
...mutationOptions,
|
|
33
|
+
retry: retryBeforeSubmission(
|
|
34
|
+
mutationOptions?.retry ??
|
|
35
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['swap'])?.retry ??
|
|
36
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
37
|
+
),
|
|
32
38
|
mutationFn: async vars => unwrapResult(await sodax.swaps.swap({ ...vars, raw: false })),
|
|
33
39
|
onSuccess: async (data, vars, ctx) => {
|
|
34
40
|
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|