@sodax/dapp-kit 2.3.0 → 2.4.0-rc.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.
- package/README.md +10 -2
- package/dist/index.d.ts +182 -31
- package/dist/index.mjs +297 -25
- package/package.json +10 -5
- package/src/hooks/_mutationContract.test.ts +1 -0
- 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/index.ts +4 -0
- 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/useEstablishXrpTrustline.test.ts +113 -0
- package/src/hooks/shared/useEstablishXrpTrustline.ts +65 -0
- package/src/hooks/shared/useSafeMutation.retry.test.ts +47 -0
- package/src/hooks/shared/useSafeMutation.ts +8 -1
- package/src/hooks/shared/useXrpDestinationCheck.ts +75 -0
- package/src/hooks/shared/useXrpGate.test.ts +118 -0
- package/src/hooks/shared/useXrpGate.ts +81 -0
- package/src/hooks/shared/useXrpTrustlineReserveCheck.ts +45 -0
- package/src/hooks/swap/useCreateLimitOrder.ts +8 -0
- package/src/hooks/swap/useSwap.ts +6 -0
- package/src/hooks/swap/useSwapLifecycle.test.ts +73 -1
- package/src/hooks/swap/useSwapLifecycle.ts +29 -5
- package/src/hooks/swap/useSwapWithApproval.test.ts +24 -1
- package/src/hooks/swap/useSwapWithApproval.ts +6 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/swapLifecycle.test.ts +35 -0
- package/src/utils/swapLifecycle.ts +29 -5
- package/src/utils/xrpGate.test.ts +112 -0
- package/src/utils/xrpGate.ts +72 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Sodax } from '@sodax/sdk';
|
|
2
|
+
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
3
|
+
import type { ReadHookParams } from './types.js';
|
|
4
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
5
|
+
|
|
6
|
+
export type UseXrpTrustlineReserveCheckParams = ReadHookParams<
|
|
7
|
+
boolean,
|
|
8
|
+
{
|
|
9
|
+
token: string | undefined;
|
|
10
|
+
address: string | undefined;
|
|
11
|
+
}
|
|
12
|
+
>;
|
|
13
|
+
|
|
14
|
+
type XrpReserveReader = { spoke: { xrp: Pick<Sodax['spoke']['xrp'], 'canAffordTrustline'> } };
|
|
15
|
+
|
|
16
|
+
export function getXrpTrustlineReserveCheckQueryOptions({
|
|
17
|
+
sodax,
|
|
18
|
+
token,
|
|
19
|
+
address,
|
|
20
|
+
}: {
|
|
21
|
+
sodax: XrpReserveReader;
|
|
22
|
+
token: string | undefined;
|
|
23
|
+
address: string | undefined;
|
|
24
|
+
}) {
|
|
25
|
+
return {
|
|
26
|
+
queryKey: ['shared', 'xrpTrustlineReserveCheck', token, address] as const,
|
|
27
|
+
queryFn: async (): Promise<boolean> => {
|
|
28
|
+
if (!address || !token) throw new Error('address and token are required');
|
|
29
|
+
return sodax.spoke.xrp.canAffordTrustline({ address, token });
|
|
30
|
+
},
|
|
31
|
+
enabled: !!address && !!token,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether an XRPL account holds the spendable XRP to set the trustline for an issued `token`. */
|
|
36
|
+
export function useXrpTrustlineReserveCheck({
|
|
37
|
+
params,
|
|
38
|
+
queryOptions,
|
|
39
|
+
}: UseXrpTrustlineReserveCheckParams = {}): UseQueryResult<boolean, Error> {
|
|
40
|
+
const { sodax } = useSodaxContext();
|
|
41
|
+
return useQuery<boolean, Error>({
|
|
42
|
+
...getXrpTrustlineReserveCheckQueryOptions({ sodax, token: params?.token, address: params?.address }),
|
|
43
|
+
...queryOptions,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -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);
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
ATOMIC_BATCH_UNCONFIRMED,
|
|
3
|
+
ChainKeys,
|
|
4
|
+
IndeterminateOutcomeError,
|
|
5
|
+
intentCreationFailed,
|
|
6
|
+
SodaxError,
|
|
7
|
+
type CreateIntentParams,
|
|
8
|
+
} from '@sodax/sdk';
|
|
2
9
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
10
|
|
|
4
11
|
const strategyHook = vi.fn();
|
|
@@ -6,6 +13,7 @@ const swapHook = vi.fn();
|
|
|
6
13
|
const statusHook = vi.fn();
|
|
7
14
|
const stellarHook = vi.fn();
|
|
8
15
|
const nearHook = vi.fn();
|
|
16
|
+
const xrpHook = vi.fn();
|
|
9
17
|
const fetchingChecks = vi.fn(() => 0);
|
|
10
18
|
|
|
11
19
|
// The lifecycle is composition plus a pure resolver (covered in utils/swapLifecycle.test.ts), so the
|
|
@@ -15,6 +23,7 @@ vi.mock('./useSwapWithApproval.js', () => ({ useSwapWithApproval: (args: unknown
|
|
|
15
23
|
vi.mock('./useDetailedStatus.js', () => ({ useDetailedStatus: (args: unknown) => statusHook(args) }));
|
|
16
24
|
vi.mock('../shared/useStellarGate.js', () => ({ useStellarGate: (args: unknown) => stellarHook(args) }));
|
|
17
25
|
vi.mock('../shared/useNearStorageGate.js', () => ({ useNearStorageGate: (args: unknown) => nearHook(args) }));
|
|
26
|
+
vi.mock('../shared/useXrpGate.js', () => ({ useXrpGate: (args: unknown) => xrpHook(args) }));
|
|
18
27
|
// Its own state is one ref; a fresh one per run() is a fresh mount.
|
|
19
28
|
vi.mock('react', () => ({ useRef: (initial: unknown) => ({ current: initial }) }));
|
|
20
29
|
vi.mock('@tanstack/react-query', () => ({ useIsFetching: () => fetchingChecks() }));
|
|
@@ -49,6 +58,8 @@ const openGate = {
|
|
|
49
58
|
blocksAction: false,
|
|
50
59
|
isNear: false,
|
|
51
60
|
needsRegistration: false,
|
|
61
|
+
isXrpIssuedToken: false,
|
|
62
|
+
blockedReason: undefined,
|
|
52
63
|
activate: vi.fn(),
|
|
53
64
|
requestTrustline: vi.fn(),
|
|
54
65
|
retry: vi.fn(),
|
|
@@ -61,12 +72,14 @@ const stub = ({
|
|
|
61
72
|
status,
|
|
62
73
|
stellar = {},
|
|
63
74
|
near = {},
|
|
75
|
+
xrp = {},
|
|
64
76
|
}: {
|
|
65
77
|
swap?: Record<string, unknown>;
|
|
66
78
|
strategy?: string;
|
|
67
79
|
status?: unknown;
|
|
68
80
|
stellar?: Record<string, unknown>;
|
|
69
81
|
near?: Record<string, unknown>;
|
|
82
|
+
xrp?: Record<string, unknown>;
|
|
70
83
|
} = {}) => {
|
|
71
84
|
strategyHook.mockReturnValue({ data: strategy, error: null, refetch: refetchStrategy });
|
|
72
85
|
swapHook.mockReturnValue({
|
|
@@ -81,6 +94,7 @@ const stub = ({
|
|
|
81
94
|
statusHook.mockReturnValue({ data: status });
|
|
82
95
|
stellarHook.mockReturnValue({ ...openGate, ...stellar });
|
|
83
96
|
nearHook.mockReturnValue({ ...openGate, ...near });
|
|
97
|
+
xrpHook.mockReturnValue({ ...openGate, ...xrp });
|
|
84
98
|
};
|
|
85
99
|
|
|
86
100
|
const run = (overrides: Partial<Parameters<typeof useSwapLifecycle>[0]> = {}) =>
|
|
@@ -185,6 +199,8 @@ describe('useSwapLifecycle', () => {
|
|
|
185
199
|
[{ stellar: { isStellar: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
|
|
186
200
|
[{ stellar: { isStellar: true, checkFailed: true, blocksAction: true } }, 'retry'],
|
|
187
201
|
[{ near: { isNear: true, needsRegistration: true, blocksAction: true } }, 'registerStorage'],
|
|
202
|
+
[{ xrp: { isXrpIssuedToken: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
|
|
203
|
+
[{ xrp: { isXrpIssuedToken: true, checkFailed: true, blocksAction: true } }, 'retry'],
|
|
188
204
|
] as const)('runs the matching setup action', async (gates, action) => {
|
|
189
205
|
stub(gates);
|
|
190
206
|
const lifecycle = run();
|
|
@@ -204,6 +220,43 @@ describe('useSwapLifecycle', () => {
|
|
|
204
220
|
expect(nearHook).toHaveBeenCalledWith(expect.objectContaining({ accountId: PARAMS.dstAddress }));
|
|
205
221
|
});
|
|
206
222
|
|
|
223
|
+
it('sizes the XRPL trustline check as the SDK sizes its check before signing', () => {
|
|
224
|
+
stub();
|
|
225
|
+
run({ intentParams: { ...PARAMS, dstChainKey: ChainKeys.XRP_MAINNET } });
|
|
226
|
+
|
|
227
|
+
expect(xrpHook).toHaveBeenCalledWith(
|
|
228
|
+
expect.objectContaining({
|
|
229
|
+
dstChainKey: ChainKeys.XRP_MAINNET,
|
|
230
|
+
address: PARAMS.dstAddress,
|
|
231
|
+
token: PARAMS.outputToken,
|
|
232
|
+
amount: PARAMS.minOutputAmount,
|
|
233
|
+
maxAmount: PARAMS.minOutputAmount * 2n,
|
|
234
|
+
}),
|
|
235
|
+
);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it.each([
|
|
239
|
+
['xrpBlocked', { blockedReason: 'issuer_frozen' }],
|
|
240
|
+
['xrpFunding', { needsFunding: true }],
|
|
241
|
+
] as const)('leaves %s to the app and sends nothing', async (reason, gate) => {
|
|
242
|
+
stub({ xrp: { isXrpIssuedToken: true, blocksAction: true, ...gate } });
|
|
243
|
+
const lifecycle = run();
|
|
244
|
+
|
|
245
|
+
expect(lifecycle.state).toEqual({ kind: 'needsSetup', reason });
|
|
246
|
+
expect(await lifecycle.next()).toBeUndefined();
|
|
247
|
+
expect(openGate.requestTrustline).not.toHaveBeenCalled();
|
|
248
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('holds the XRPL trustline step while its TrustSet is in flight', async () => {
|
|
252
|
+
stub({ xrp: { isXrpIssuedToken: true, needsTrustline: true, blocksAction: true, isRequestingTrustline: true } });
|
|
253
|
+
const lifecycle = run();
|
|
254
|
+
|
|
255
|
+
expect(lifecycle.state).toEqual({ kind: 'checking' });
|
|
256
|
+
await lifecycle.next();
|
|
257
|
+
expect(openGate.requestTrustline).not.toHaveBeenCalled();
|
|
258
|
+
});
|
|
259
|
+
|
|
207
260
|
it('retries a failed NEAR storage check instead of swapping', async () => {
|
|
208
261
|
const nearRetry = vi.fn();
|
|
209
262
|
stub({ near: { isNear: true, checkFailed: true, retry: nearRetry } });
|
|
@@ -306,6 +359,25 @@ describe('useSwapLifecycle', () => {
|
|
|
306
359
|
expect(lifecycle.error).toBe(error);
|
|
307
360
|
});
|
|
308
361
|
|
|
362
|
+
it('keeps a recovery-only attempt pending across an input edit without sending again', async () => {
|
|
363
|
+
const recovery = { validUntil: 42 };
|
|
364
|
+
const failure = intentCreationFailed(
|
|
365
|
+
'swap',
|
|
366
|
+
new IndeterminateOutcomeError('submit reply lost', {
|
|
367
|
+
cause: new Error('timeout'),
|
|
368
|
+
recovery,
|
|
369
|
+
}),
|
|
370
|
+
);
|
|
371
|
+
stub({ swap: { status: 'error', error: failure, variables: { params: PARAMS } } });
|
|
372
|
+
const lifecycle = run({ intentParams: { ...PARAMS, minOutputAmount: 899_000n } });
|
|
373
|
+
|
|
374
|
+
expect(lifecycle.state).toEqual({ kind: 'pending', srcChainKey: PARAMS.srcChainKey, recovery, error: failure });
|
|
375
|
+
expect(statusHook).toHaveBeenCalledWith({ params: { srcChainKey: undefined, srcTxHash: undefined } });
|
|
376
|
+
await expect(lifecycle.next()).resolves.toBeUndefined();
|
|
377
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
378
|
+
expect(resetSwap).not.toHaveBeenCalled();
|
|
379
|
+
});
|
|
380
|
+
|
|
309
381
|
it('ignores reset() while the swap call is in flight', () => {
|
|
310
382
|
stub({ swap: { status: 'pending', isPending: true, variables: { params: PARAMS } } });
|
|
311
383
|
const lifecycle = run();
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
+
SOLVED_PAYOUT_HEADROOM_FACTOR,
|
|
2
3
|
isAuthFailure,
|
|
3
4
|
summarizeSwapStatus,
|
|
4
5
|
type CreateIntentParams,
|
|
@@ -14,6 +15,7 @@ import { useRef } from 'react';
|
|
|
14
15
|
import { resolveSwapLifecycle, toSwapAttempt, type SwapLifecycleState } from '../../utils/swapLifecycle.js';
|
|
15
16
|
import { useNearStorageGate, type NearStorageGate } from '../shared/useNearStorageGate.js';
|
|
16
17
|
import { useStellarGate, type StellarGate } from '../shared/useStellarGate.js';
|
|
18
|
+
import { useXrpGate, type XrpGate } from '../shared/useXrpGate.js';
|
|
17
19
|
import type { MutationHookOptions } from '../shared/types.js';
|
|
18
20
|
import type { SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
19
21
|
import { useDetailedStatus, type UseDetailedStatusResult } from './useDetailedStatus.js';
|
|
@@ -31,7 +33,7 @@ export type UseSwapLifecycleParams<K extends SpokeChainKey = SpokeChainKey> = {
|
|
|
31
33
|
intentParams: CreateIntentParams<K> | undefined;
|
|
32
34
|
srcWalletProvider: GetWalletProviderType<K> | undefined;
|
|
33
35
|
/**
|
|
34
|
-
* Destination wallet, for the Stellar and
|
|
36
|
+
* Destination wallet, for the Stellar, NEAR and XRPL setup actions. The gates check `intentParams.dstAddress`,
|
|
35
37
|
* the account the swap pays, so this wallet must control it for those actions to clear them.
|
|
36
38
|
*/
|
|
37
39
|
dstWalletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
|
|
@@ -70,11 +72,13 @@ export type SwapLifecycle<K extends SpokeChainKey = SpokeChainKey> = {
|
|
|
70
72
|
status: UseQueryResult<UseDetailedStatusResult>;
|
|
71
73
|
stellar: StellarGate;
|
|
72
74
|
nearStorage: NearStorageGate;
|
|
75
|
+
/** `blockedReason` names why an XRPL destination cannot receive when the state is `xrpBlocked`. */
|
|
76
|
+
xrp: XrpGate;
|
|
73
77
|
};
|
|
74
78
|
|
|
75
79
|
/**
|
|
76
80
|
* One hook for a swap form: approval strategy, destination prerequisites (Stellar account and
|
|
77
|
-
* trustline, NEAR storage), source-chain switching, the swap itself (`useSwapWithApproval` — one
|
|
81
|
+
* trustline, NEAR storage, XRPL trustline), source-chain switching, the swap itself (`useSwapWithApproval` — one
|
|
78
82
|
* signature on an EIP-5792 wallet) and its status (`useDetailedStatus`), as a single discriminated
|
|
79
83
|
* `state` with one `next()` action. Render from `state.kind`; wire the button to `next()`.
|
|
80
84
|
*
|
|
@@ -112,12 +116,24 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
112
116
|
walletProvider: dstWalletProvider,
|
|
113
117
|
});
|
|
114
118
|
|
|
119
|
+
const xrp = useXrpGate({
|
|
120
|
+
dstChainKey: intentParams?.dstChainKey,
|
|
121
|
+
token: intentParams?.outputToken,
|
|
122
|
+
address: intentParams?.dstAddress,
|
|
123
|
+
// Sized as the SDK's check before signing sizes it, so the gate never passes a swap the SDK then refuses.
|
|
124
|
+
amount: intentParams?.minOutputAmount,
|
|
125
|
+
maxAmount: intentParams && intentParams.minOutputAmount * SOLVED_PAYOUT_HEADROOM_FACTOR,
|
|
126
|
+
walletProvider: dstWalletProvider,
|
|
127
|
+
});
|
|
128
|
+
|
|
115
129
|
// The setup mutations invalidate these checks without awaiting the refetch, so a stale "needs setup"
|
|
116
130
|
// outlives the tx by one read.
|
|
117
131
|
const fetchingSetupChecks =
|
|
118
132
|
useIsFetching({ queryKey: ['sponsoring', 'stellarAccountStatus'] }) +
|
|
119
133
|
useIsFetching({ queryKey: ['shared', 'stellarTrustlineCheck'] }) +
|
|
120
|
-
useIsFetching({ queryKey: ['shared', 'nearStorageCheck'] })
|
|
134
|
+
useIsFetching({ queryKey: ['shared', 'nearStorageCheck'] }) +
|
|
135
|
+
useIsFetching({ queryKey: ['shared', 'xrpDestinationCheck'] }) +
|
|
136
|
+
useIsFetching({ queryKey: ['shared', 'xrpTrustlineReserveCheck'] });
|
|
121
137
|
|
|
122
138
|
const attempt = toSwapAttempt(swap, intentParams);
|
|
123
139
|
const broadcast = attempt.phase === 'broadcast' ? attempt : undefined;
|
|
@@ -132,9 +148,14 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
132
148
|
hasInputs: !!intentParams && !!srcWalletProvider,
|
|
133
149
|
stellar,
|
|
134
150
|
nearStorage,
|
|
151
|
+
xrp,
|
|
135
152
|
externalBlocked,
|
|
136
153
|
setupBusy:
|
|
137
|
-
stellar.isActivating ||
|
|
154
|
+
stellar.isActivating ||
|
|
155
|
+
stellar.isRequestingTrustline ||
|
|
156
|
+
nearStorage.isRegistering ||
|
|
157
|
+
xrp.isRequestingTrustline ||
|
|
158
|
+
fetchingSetupChecks > 0,
|
|
138
159
|
isWrongChain: chainSwitch?.isWrongChain ?? false,
|
|
139
160
|
strategy: { data: approvalStrategy.data, error: approvalStrategy.error },
|
|
140
161
|
});
|
|
@@ -157,7 +178,9 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
157
178
|
if (state.reason === 'nearStorage') return nearStorage.registerStorage();
|
|
158
179
|
if (state.reason === 'stellarCheckFailed') stellar.retry();
|
|
159
180
|
if (state.reason === 'nearStorageCheckFailed') nearStorage.retry();
|
|
160
|
-
|
|
181
|
+
if (state.reason === 'xrpTrustline') return xrp.requestTrustline();
|
|
182
|
+
if (state.reason === 'xrpCheckFailed') xrp.retry();
|
|
183
|
+
// `stellarFunding`, `xrpFunding`, `xrpBlocked` and `external` are for the app to resolve.
|
|
161
184
|
return undefined;
|
|
162
185
|
case 'ready':
|
|
163
186
|
if (!intentParams || !srcWalletProvider) return undefined;
|
|
@@ -208,5 +231,6 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
208
231
|
status,
|
|
209
232
|
stellar,
|
|
210
233
|
nearStorage,
|
|
234
|
+
xrp,
|
|
211
235
|
};
|
|
212
236
|
}
|
|
@@ -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('useSwapWithApproval', () => {
|
|
37
|
+
it.each([
|
|
38
|
+
{ batchId: 'batch-1' },
|
|
39
|
+
{ reason: ATOMIC_BATCH_UNCONFIRMED },
|
|
40
|
+
])('suppresses configured retries after an unconfirmed batch ($context)', context => {
|
|
41
|
+
useSwapWithApproval({ mutationOptions: { retry: 3 } });
|
|
42
|
+
const error = new SodaxError('TX_VERIFICATION_FAILED', 'Batch was sent but not confirmed', {
|
|
43
|
+
feature: 'swap',
|
|
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
|
+
useSwapWithApproval({ mutationOptions: { retry: 3 } });
|
|
51
|
+
const error = new SodaxError('RELAY_TIMEOUT', 'Settlement pending', {
|
|
52
|
+
feature: 'swap',
|
|
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 swap and calls swapWithApproval in signed mode', async () => {
|
|
37
60
|
swapWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
|
|
38
61
|
useSwapWithApproval();
|
|
@@ -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
|
/**
|
|
@@ -34,6 +35,11 @@ export function useSwapWithApproval<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
34
35
|
return useSafeMutation<SwapWithApprovalResponse, Error, UseSwapWithApprovalVars<K>>({
|
|
35
36
|
mutationKey: ['swap', 'swapWithApproval'],
|
|
36
37
|
...mutationOptions,
|
|
38
|
+
retry: retryBeforeSubmission(
|
|
39
|
+
mutationOptions?.retry ??
|
|
40
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['swap', 'swapWithApproval'])?.retry ??
|
|
41
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
42
|
+
),
|
|
37
43
|
mutationFn: async vars => unwrapResult(await sodax.swaps.swapWithApproval({ ...vars, raw: false })),
|
|
38
44
|
onSuccess: async (data, vars, ctx) => {
|
|
39
45
|
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
package/src/utils/index.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
import { describe, expect, it } from 'vitest';
|
|
10
10
|
import type { NearStorageGateState } from './nearStorageGate.js';
|
|
11
11
|
import type { StellarGateState } from './stellarGate.js';
|
|
12
|
+
import type { XrpGateState } from './xrpGate.js';
|
|
12
13
|
import {
|
|
13
14
|
isSameIntent,
|
|
14
15
|
resolveSwapLifecycle,
|
|
@@ -54,6 +55,14 @@ const OPEN_STELLAR: StellarGateState = {
|
|
|
54
55
|
blocksAction: false,
|
|
55
56
|
};
|
|
56
57
|
const OPEN_NEAR: NearStorageGateState = { isNear: false, needsRegistration: false, blocksAction: false };
|
|
58
|
+
const OPEN_XRP: XrpGateState = {
|
|
59
|
+
isXrpIssuedToken: false,
|
|
60
|
+
needsTrustline: false,
|
|
61
|
+
needsFunding: false,
|
|
62
|
+
blockedReason: undefined,
|
|
63
|
+
checkFailed: false,
|
|
64
|
+
blocksAction: false,
|
|
65
|
+
};
|
|
57
66
|
|
|
58
67
|
const inputs = (overrides: Partial<SwapLifecycleInputs> = {}): SwapLifecycleInputs => ({
|
|
59
68
|
attempt: { phase: 'none' },
|
|
@@ -62,6 +71,7 @@ const inputs = (overrides: Partial<SwapLifecycleInputs> = {}): SwapLifecycleInpu
|
|
|
62
71
|
hasInputs: true,
|
|
63
72
|
stellar: OPEN_STELLAR,
|
|
64
73
|
nearStorage: OPEN_NEAR,
|
|
74
|
+
xrp: OPEN_XRP,
|
|
65
75
|
externalBlocked: false,
|
|
66
76
|
setupBusy: false,
|
|
67
77
|
isWrongChain: false,
|
|
@@ -230,6 +240,31 @@ describe('resolveSwapLifecycle', () => {
|
|
|
230
240
|
});
|
|
231
241
|
});
|
|
232
242
|
|
|
243
|
+
it.each([
|
|
244
|
+
[{ needsTrustline: true, blocksAction: true }, 'xrpTrustline'],
|
|
245
|
+
[{ needsFunding: true, blocksAction: true }, 'xrpFunding'],
|
|
246
|
+
[{ blockedReason: 'issuer_frozen', blocksAction: true }, 'xrpBlocked'],
|
|
247
|
+
[{ checkFailed: true, blocksAction: true }, 'xrpCheckFailed'],
|
|
248
|
+
] as const)('blocks on the XRPL gate (%o → %s)', (gate, reason) => {
|
|
249
|
+
expect(resolveSwapLifecycle(inputs({ xrp: { ...OPEN_XRP, isXrpIssuedToken: true, ...gate } }))).toEqual({
|
|
250
|
+
kind: 'needsSetup',
|
|
251
|
+
reason,
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it('is checking while the XRPL gate resolves, or while a TrustSet and its refreshed check run', () => {
|
|
256
|
+
const xrp = { ...OPEN_XRP, isXrpIssuedToken: true, blocksAction: true };
|
|
257
|
+
expect(resolveSwapLifecycle(inputs({ xrp }))).toEqual({ kind: 'checking' });
|
|
258
|
+
expect(resolveSwapLifecycle(inputs({ xrp: { ...xrp, needsTrustline: true }, setupBusy: true }))).toEqual({
|
|
259
|
+
kind: 'checking',
|
|
260
|
+
});
|
|
261
|
+
// Once the trustline is in place the swap goes ahead.
|
|
262
|
+
expect(resolveSwapLifecycle(inputs({ xrp: { ...OPEN_XRP, isXrpIssuedToken: true } }))).toEqual({
|
|
263
|
+
kind: 'ready',
|
|
264
|
+
approvalStrategy: 'atomic-batch',
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
|
|
233
268
|
it('blocks on NEAR storage, then on the app-owned prerequisite', () => {
|
|
234
269
|
expect(
|
|
235
270
|
resolveSwapLifecycle(inputs({ nearStorage: { isNear: true, needsRegistration: true, blocksAction: true } })),
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from '@sodax/sdk';
|
|
11
11
|
import type { NearStorageGateState } from './nearStorageGate.js';
|
|
12
12
|
import type { StellarGateState } from './stellarGate.js';
|
|
13
|
+
import type { XrpGateState } from './xrpGate.js';
|
|
13
14
|
|
|
14
15
|
/** A prerequisite the user must resolve before the swap can go out. */
|
|
15
16
|
export type SwapSetupReason =
|
|
@@ -19,6 +20,10 @@ export type SwapSetupReason =
|
|
|
19
20
|
| 'stellarCheckFailed'
|
|
20
21
|
| 'nearStorage'
|
|
21
22
|
| 'nearStorageCheckFailed'
|
|
23
|
+
| 'xrpTrustline'
|
|
24
|
+
| 'xrpFunding'
|
|
25
|
+
| 'xrpBlocked'
|
|
26
|
+
| 'xrpCheckFailed'
|
|
22
27
|
| 'external';
|
|
23
28
|
|
|
24
29
|
/**
|
|
@@ -27,7 +32,8 @@ export type SwapSetupReason =
|
|
|
27
32
|
* - `checking` — waiting before anything can be done: a gate or the approval strategy is still reading, or a
|
|
28
33
|
* setup tx (activation, trustline, NEAR storage) is in flight or its check is refreshing.
|
|
29
34
|
* - `submitting` — the swap call is in flight: signing, and on the default backend path settlement too.
|
|
30
|
-
* - `pending` — the source tx
|
|
35
|
+
* - `pending` — the source tx status is being read, or a recovery handle is waiting for identification.
|
|
36
|
+
* `error` is set when the swap call
|
|
31
37
|
* failed after broadcast, or when the status read cannot recover (a rejected API key); the swap may
|
|
32
38
|
* still complete either way. The read can also stop polling without an error (after its budget of
|
|
33
39
|
* ambiguous reads), so keep `reset()` reachable here.
|
|
@@ -43,6 +49,7 @@ export type SwapLifecycleState =
|
|
|
43
49
|
| { kind: 'ready'; approvalStrategy: SwapApprovalStrategy }
|
|
44
50
|
| { kind: 'submitting' }
|
|
45
51
|
| { kind: 'pending'; srcChainKey: SpokeChainKey; srcTxHash: string; error?: Error }
|
|
52
|
+
| { kind: 'pending'; srcChainKey: SpokeChainKey; srcTxHash?: never; recovery: unknown; error: Error }
|
|
46
53
|
| { kind: 'unconfirmed'; batchId: string; callCount?: number; error: Error }
|
|
47
54
|
| { kind: 'settled'; srcChainKey: SpokeChainKey; srcTxHash: string; fillTxHash?: Hex }
|
|
48
55
|
| { kind: 'failed'; error: Error; srcChainKey?: SpokeChainKey; srcTxHash?: string };
|
|
@@ -60,6 +67,7 @@ export type SwapAttempt =
|
|
|
60
67
|
| { phase: 'none' }
|
|
61
68
|
| { phase: 'submitting' }
|
|
62
69
|
| { phase: 'broadcast'; srcChainKey: SpokeChainKey; srcTxHash: string; error?: Error }
|
|
70
|
+
| { phase: 'recovering'; srcChainKey: SpokeChainKey; recovery: unknown; error: Error }
|
|
63
71
|
| { phase: 'unconfirmed'; batchId: string; callCount?: number; error: Error }
|
|
64
72
|
| { phase: 'failed'; error: Error };
|
|
65
73
|
|
|
@@ -74,6 +82,7 @@ export type SwapLifecycleInputs = {
|
|
|
74
82
|
stellar: StellarGateState;
|
|
75
83
|
/** `checkFailed`: the registration check errored, so the swap waits for a retry rather than going out blind. */
|
|
76
84
|
nearStorage: NearStorageGateState & { checkFailed?: boolean };
|
|
85
|
+
xrp: XrpGateState;
|
|
77
86
|
externalBlocked: boolean;
|
|
78
87
|
/** A setup tx is in flight, or the check it invalidated is still refreshing: acting now would resend it. */
|
|
79
88
|
setupBusy: boolean;
|
|
@@ -112,7 +121,9 @@ export function toSwapAttempt(mutation: SwapAttemptSource, intentParams: CreateI
|
|
|
112
121
|
if (mutation.status === 'idle' || !attempted) return { phase: 'none' };
|
|
113
122
|
const attempt = toFinishedAttempt(mutation, attempted);
|
|
114
123
|
const mayStillLand =
|
|
115
|
-
attempt.phase === 'unconfirmed' ||
|
|
124
|
+
attempt.phase === 'unconfirmed' ||
|
|
125
|
+
attempt.phase === 'recovering' ||
|
|
126
|
+
(attempt.phase === 'broadcast' && attempt.error !== undefined);
|
|
116
127
|
if (mayStillLand || (intentParams && isSameIntent(attempted, intentParams))) return attempt;
|
|
117
128
|
return { phase: 'none' };
|
|
118
129
|
}
|
|
@@ -127,6 +138,9 @@ function toFinishedAttempt(mutation: SwapAttemptSource, attempted: CreateIntentP
|
|
|
127
138
|
if (typeof context?.srcTxHash === 'string') {
|
|
128
139
|
return { phase: 'broadcast', srcChainKey: attempted.srcChainKey, srcTxHash: context.srcTxHash, error };
|
|
129
140
|
}
|
|
141
|
+
if (context?.recovery !== undefined) {
|
|
142
|
+
return { phase: 'recovering', srcChainKey: attempted.srcChainKey, recovery: context.recovery, error };
|
|
143
|
+
}
|
|
130
144
|
if (context?.reason === ATOMIC_BATCH_UNCONFIRMED && typeof context.batchId === 'string') {
|
|
131
145
|
return typeof context.callCount === 'number'
|
|
132
146
|
? { phase: 'unconfirmed', batchId: context.batchId, callCount: context.callCount, error }
|
|
@@ -137,7 +151,7 @@ function toFinishedAttempt(mutation: SwapAttemptSource, attempted: CreateIntentP
|
|
|
137
151
|
|
|
138
152
|
/**
|
|
139
153
|
* Derives the lifecycle state. Order: an attempt in flight or broadcast wins; then missing inputs;
|
|
140
|
-
* then destination prerequisites (Stellar, NEAR, app-owned); then the source chain; then the
|
|
154
|
+
* then destination prerequisites (Stellar, NEAR, XRPL, app-owned); then the source chain; then the
|
|
141
155
|
* approval strategy. Pure — `useSwapLifecycle` feeds it from its sub-hooks.
|
|
142
156
|
*/
|
|
143
157
|
export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycleState {
|
|
@@ -152,6 +166,10 @@ export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycle
|
|
|
152
166
|
const error = attempt.error ?? inputs.statusError;
|
|
153
167
|
return error ? { kind: 'pending', srcChainKey, srcTxHash, error } : { kind: 'pending', srcChainKey, srcTxHash };
|
|
154
168
|
}
|
|
169
|
+
if (attempt.phase === 'recovering') {
|
|
170
|
+
const { srcChainKey, recovery, error } = attempt;
|
|
171
|
+
return { kind: 'pending', srcChainKey, recovery, error };
|
|
172
|
+
}
|
|
155
173
|
if (attempt.phase === 'unconfirmed') {
|
|
156
174
|
const { batchId, callCount, error } = attempt;
|
|
157
175
|
return callCount === undefined
|
|
@@ -163,7 +181,9 @@ export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycle
|
|
|
163
181
|
|
|
164
182
|
const reason = setupReason(inputs);
|
|
165
183
|
if (reason) return inputs.setupBusy ? { kind: 'checking' } : { kind: 'needsSetup', reason };
|
|
166
|
-
if (inputs.stellar.blocksAction || inputs.nearStorage.blocksAction)
|
|
184
|
+
if (inputs.stellar.blocksAction || inputs.nearStorage.blocksAction || inputs.xrp.blocksAction) {
|
|
185
|
+
return { kind: 'checking' };
|
|
186
|
+
}
|
|
167
187
|
if (inputs.isWrongChain) return { kind: 'needsChainSwitch' };
|
|
168
188
|
// A failed refetch keeps the last strategy; `swapWithApproval` resolves its own before sending anyway.
|
|
169
189
|
if (inputs.strategy.error && !inputs.strategy.data) return { kind: 'failed', error: inputs.strategy.error };
|
|
@@ -171,13 +191,17 @@ export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycle
|
|
|
171
191
|
return { kind: 'ready', approvalStrategy: inputs.strategy.data };
|
|
172
192
|
}
|
|
173
193
|
|
|
174
|
-
function setupReason({ stellar, nearStorage, externalBlocked }: SwapLifecycleInputs): SwapSetupReason | undefined {
|
|
194
|
+
function setupReason({ stellar, nearStorage, xrp, externalBlocked }: SwapLifecycleInputs): SwapSetupReason | undefined {
|
|
175
195
|
if (stellar.needsActivation) return 'stellarActivation';
|
|
176
196
|
if (stellar.needsFunding) return 'stellarFunding';
|
|
177
197
|
if (stellar.needsTrustline) return 'stellarTrustline';
|
|
178
198
|
if (stellar.checkFailed) return 'stellarCheckFailed';
|
|
179
199
|
if (nearStorage.needsRegistration) return 'nearStorage';
|
|
180
200
|
if (nearStorage.checkFailed) return 'nearStorageCheckFailed';
|
|
201
|
+
if (xrp.blockedReason) return 'xrpBlocked';
|
|
202
|
+
if (xrp.needsFunding) return 'xrpFunding';
|
|
203
|
+
if (xrp.needsTrustline) return 'xrpTrustline';
|
|
204
|
+
if (xrp.checkFailed) return 'xrpCheckFailed';
|
|
181
205
|
if (externalBlocked) return 'external';
|
|
182
206
|
return undefined;
|
|
183
207
|
}
|