@sodax/dapp-kit 2.2.0 → 2.3.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 +176 -166
- package/dist/index.d.ts +313 -30
- package/dist/index.mjs +392 -3
- package/package.json +5 -5
- package/src/hooks/_apiKeyWire.test.ts +10 -0
- package/src/hooks/_mutationContract.test.ts +4 -0
- package/src/hooks/bridge/index.ts +2 -0
- package/src/hooks/bridge/useBridgeApprovalStrategy.test.ts +75 -0
- package/src/hooks/bridge/useBridgeApprovalStrategy.ts +53 -0
- package/src/hooks/bridge/useBridgeWithApproval.test.ts +73 -0
- package/src/hooks/bridge/useBridgeWithApproval.ts +48 -0
- package/src/hooks/leverageYield/index.ts +2 -0
- package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.test.ts +82 -0
- package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.ts +55 -0
- package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.test.ts +73 -0
- package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.ts +48 -0
- package/src/hooks/shared/useNearStorageGate.ts +10 -4
- package/src/hooks/swap/index.ts +3 -0
- package/src/hooks/swap/useSwapApprovalStrategy.test.ts +92 -0
- package/src/hooks/swap/useSwapApprovalStrategy.ts +54 -0
- package/src/hooks/swap/useSwapLifecycle.test.ts +329 -0
- package/src/hooks/swap/useSwapLifecycle.ts +212 -0
- package/src/hooks/swap/useSwapWithApproval.test.ts +63 -0
- package/src/hooks/swap/useSwapWithApproval.ts +45 -0
- package/src/hooks/swapsApi/index.ts +1 -0
- package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.test.ts +331 -0
- package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.ts +183 -0
- package/src/utils/nearStorageGate.ts +4 -1
- package/src/utils/swapLifecycle.test.ts +292 -0
- package/src/utils/swapLifecycle.ts +183 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
import { ATOMIC_BATCH_UNCONFIRMED, ChainKeys, SodaxError, type CreateIntentParams } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
const strategyHook = vi.fn();
|
|
5
|
+
const swapHook = vi.fn();
|
|
6
|
+
const statusHook = vi.fn();
|
|
7
|
+
const stellarHook = vi.fn();
|
|
8
|
+
const nearHook = vi.fn();
|
|
9
|
+
const fetchingChecks = vi.fn(() => 0);
|
|
10
|
+
|
|
11
|
+
// The lifecycle is composition plus a pure resolver (covered in utils/swapLifecycle.test.ts), so the
|
|
12
|
+
// sub-hooks are stubbed and the hook runs as a plain function.
|
|
13
|
+
vi.mock('./useSwapApprovalStrategy.js', () => ({ useSwapApprovalStrategy: (args: unknown) => strategyHook(args) }));
|
|
14
|
+
vi.mock('./useSwapWithApproval.js', () => ({ useSwapWithApproval: (args: unknown) => swapHook(args) }));
|
|
15
|
+
vi.mock('./useDetailedStatus.js', () => ({ useDetailedStatus: (args: unknown) => statusHook(args) }));
|
|
16
|
+
vi.mock('../shared/useStellarGate.js', () => ({ useStellarGate: (args: unknown) => stellarHook(args) }));
|
|
17
|
+
vi.mock('../shared/useNearStorageGate.js', () => ({ useNearStorageGate: (args: unknown) => nearHook(args) }));
|
|
18
|
+
// Its own state is one ref; a fresh one per run() is a fresh mount.
|
|
19
|
+
vi.mock('react', () => ({ useRef: (initial: unknown) => ({ current: initial }) }));
|
|
20
|
+
vi.mock('@tanstack/react-query', () => ({ useIsFetching: () => fetchingChecks() }));
|
|
21
|
+
|
|
22
|
+
const { useSwapLifecycle } = await import('./useSwapLifecycle.js');
|
|
23
|
+
|
|
24
|
+
const PARAMS: CreateIntentParams = {
|
|
25
|
+
inputToken: '0x2170Ed0880ac9A755fd29B2688956BD959F933F8',
|
|
26
|
+
outputToken: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f',
|
|
27
|
+
inputAmount: 1_000_000n,
|
|
28
|
+
minOutputAmount: 900_000n,
|
|
29
|
+
deadline: 0n,
|
|
30
|
+
allowPartialFill: false,
|
|
31
|
+
srcChainKey: ChainKeys.BSC_MAINNET,
|
|
32
|
+
dstChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
33
|
+
srcAddress: '0x1111111111111111111111111111111111111111',
|
|
34
|
+
dstAddress: '0x2222222222222222222222222222222222222222',
|
|
35
|
+
solver: '0x0000000000000000000000000000000000000000',
|
|
36
|
+
data: '0x',
|
|
37
|
+
};
|
|
38
|
+
const WALLET = { chainType: 'EVM' } as never;
|
|
39
|
+
|
|
40
|
+
const mutateAsyncSafe = vi.fn();
|
|
41
|
+
const resetSwap = vi.fn();
|
|
42
|
+
const refetchStrategy = vi.fn();
|
|
43
|
+
const openGate = {
|
|
44
|
+
isStellar: false,
|
|
45
|
+
needsActivation: false,
|
|
46
|
+
needsFunding: false,
|
|
47
|
+
needsTrustline: false,
|
|
48
|
+
checkFailed: false,
|
|
49
|
+
blocksAction: false,
|
|
50
|
+
isNear: false,
|
|
51
|
+
needsRegistration: false,
|
|
52
|
+
activate: vi.fn(),
|
|
53
|
+
requestTrustline: vi.fn(),
|
|
54
|
+
retry: vi.fn(),
|
|
55
|
+
registerStorage: vi.fn(),
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const stub = ({
|
|
59
|
+
swap = {},
|
|
60
|
+
strategy = 'atomic-batch',
|
|
61
|
+
status,
|
|
62
|
+
stellar = {},
|
|
63
|
+
near = {},
|
|
64
|
+
}: {
|
|
65
|
+
swap?: Record<string, unknown>;
|
|
66
|
+
strategy?: string;
|
|
67
|
+
status?: unknown;
|
|
68
|
+
stellar?: Record<string, unknown>;
|
|
69
|
+
near?: Record<string, unknown>;
|
|
70
|
+
} = {}) => {
|
|
71
|
+
strategyHook.mockReturnValue({ data: strategy, error: null, refetch: refetchStrategy });
|
|
72
|
+
swapHook.mockReturnValue({
|
|
73
|
+
status: 'idle',
|
|
74
|
+
data: undefined,
|
|
75
|
+
error: null,
|
|
76
|
+
variables: undefined,
|
|
77
|
+
mutateAsyncSafe,
|
|
78
|
+
reset: resetSwap,
|
|
79
|
+
...swap,
|
|
80
|
+
});
|
|
81
|
+
statusHook.mockReturnValue({ data: status });
|
|
82
|
+
stellarHook.mockReturnValue({ ...openGate, ...stellar });
|
|
83
|
+
nearHook.mockReturnValue({ ...openGate, ...near });
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const run = (overrides: Partial<Parameters<typeof useSwapLifecycle>[0]> = {}) =>
|
|
87
|
+
useSwapLifecycle({
|
|
88
|
+
intentParams: PARAMS,
|
|
89
|
+
srcWalletProvider: WALLET,
|
|
90
|
+
dstWalletProvider: undefined,
|
|
91
|
+
...overrides,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
beforeEach(() => {
|
|
95
|
+
vi.clearAllMocks();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe('useSwapLifecycle', () => {
|
|
99
|
+
it('feeds the sub-hooks from the intent params', () => {
|
|
100
|
+
stub();
|
|
101
|
+
run();
|
|
102
|
+
|
|
103
|
+
expect(strategyHook).toHaveBeenCalledWith({ params: { payload: PARAMS, walletProvider: WALLET } });
|
|
104
|
+
expect(stellarHook).toHaveBeenCalledWith(
|
|
105
|
+
expect.objectContaining({ dstChainKey: ChainKeys.ARBITRUM_MAINNET, amount: PARAMS.minOutputAmount }),
|
|
106
|
+
);
|
|
107
|
+
expect(nearHook).toHaveBeenCalledWith(expect.objectContaining({ dstChainKey: ChainKeys.ARBITRUM_MAINNET }));
|
|
108
|
+
// No attempt yet, so the status read stays disabled.
|
|
109
|
+
expect(statusHook).toHaveBeenCalledWith({ params: { srcChainKey: undefined, srcTxHash: undefined } });
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('checks the Stellar trustline for one unit when the minimum is 0n, so the check still runs', () => {
|
|
113
|
+
stub();
|
|
114
|
+
run({ intentParams: { ...PARAMS, minOutputAmount: 0n } });
|
|
115
|
+
expect(stellarHook).toHaveBeenLastCalledWith(expect.objectContaining({ amount: 1n }));
|
|
116
|
+
|
|
117
|
+
run({ intentParams: undefined });
|
|
118
|
+
expect(stellarHook).toHaveBeenLastCalledWith(expect.objectContaining({ amount: undefined }));
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('swaps from the ready state with the configured extras and timeout', async () => {
|
|
122
|
+
stub();
|
|
123
|
+
mutateAsyncSafe.mockResolvedValueOnce({ ok: true, value: {} });
|
|
124
|
+
const lifecycle = run({ extras: { apiKey: 'k' }, timeout: 30_000 });
|
|
125
|
+
|
|
126
|
+
expect(lifecycle.state).toEqual({ kind: 'ready', approvalStrategy: 'atomic-batch' });
|
|
127
|
+
await lifecycle.next();
|
|
128
|
+
|
|
129
|
+
expect(mutateAsyncSafe).toHaveBeenCalledWith({
|
|
130
|
+
params: PARAMS,
|
|
131
|
+
walletProvider: WALLET,
|
|
132
|
+
extras: { apiKey: 'k' },
|
|
133
|
+
timeout: 30_000,
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('passes allowAccountUpgrade to the strategy read and the swap', async () => {
|
|
138
|
+
stub({ strategy: 'sequential' });
|
|
139
|
+
mutateAsyncSafe.mockResolvedValueOnce({ ok: true, value: {} });
|
|
140
|
+
const lifecycle = run({ allowAccountUpgrade: false });
|
|
141
|
+
|
|
142
|
+
expect(strategyHook).toHaveBeenCalledWith({
|
|
143
|
+
params: { payload: PARAMS, walletProvider: WALLET, allowAccountUpgrade: false },
|
|
144
|
+
});
|
|
145
|
+
await lifecycle.next();
|
|
146
|
+
expect(mutateAsyncSafe).toHaveBeenCalledWith(expect.objectContaining({ allowAccountUpgrade: false }));
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('reads status from the source tx of the current swap and settles on solved', () => {
|
|
150
|
+
stub({
|
|
151
|
+
swap: {
|
|
152
|
+
status: 'success',
|
|
153
|
+
data: { intentDeliveryInfo: { srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc' } },
|
|
154
|
+
variables: { params: PARAMS },
|
|
155
|
+
},
|
|
156
|
+
status: {
|
|
157
|
+
ok: true,
|
|
158
|
+
value: { source: 'solver', dstTxHash: '0xhub', data: { status: 3, fill_tx_hash: '0xf111' } },
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
const lifecycle = run();
|
|
162
|
+
|
|
163
|
+
expect(statusHook).toHaveBeenCalledWith({ params: { srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc' } });
|
|
164
|
+
expect(lifecycle.state).toEqual({
|
|
165
|
+
kind: 'settled',
|
|
166
|
+
srcChainKey: ChainKeys.BSC_MAINNET,
|
|
167
|
+
srcTxHash: '0xsrc',
|
|
168
|
+
fillTxHash: '0xf111',
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('switches chain when the source wallet is on the wrong network', async () => {
|
|
173
|
+
stub();
|
|
174
|
+
const switchChain = vi.fn();
|
|
175
|
+
const lifecycle = run({ chainSwitch: { isWrongChain: true, switchChain } });
|
|
176
|
+
|
|
177
|
+
expect(lifecycle.state).toEqual({ kind: 'needsChainSwitch' });
|
|
178
|
+
await lifecycle.next();
|
|
179
|
+
expect(switchChain).toHaveBeenCalledOnce();
|
|
180
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it.each([
|
|
184
|
+
[{ stellar: { isStellar: true, needsActivation: true, blocksAction: true } }, 'activate'],
|
|
185
|
+
[{ stellar: { isStellar: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
|
|
186
|
+
[{ stellar: { isStellar: true, checkFailed: true, blocksAction: true } }, 'retry'],
|
|
187
|
+
[{ near: { isNear: true, needsRegistration: true, blocksAction: true } }, 'registerStorage'],
|
|
188
|
+
] as const)('runs the matching setup action', async (gates, action) => {
|
|
189
|
+
stub(gates);
|
|
190
|
+
const lifecycle = run();
|
|
191
|
+
|
|
192
|
+
expect(lifecycle.state.kind).toBe('needsSetup');
|
|
193
|
+
await lifecycle.next();
|
|
194
|
+
expect(openGate[action]).toHaveBeenCalledOnce();
|
|
195
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// The gates must check the account the swap pays, not whichever destination account the app tracks.
|
|
199
|
+
it('checks the Stellar and NEAR gates on the intent recipient', () => {
|
|
200
|
+
stub();
|
|
201
|
+
run();
|
|
202
|
+
|
|
203
|
+
expect(stellarHook).toHaveBeenCalledWith(expect.objectContaining({ address: PARAMS.dstAddress }));
|
|
204
|
+
expect(nearHook).toHaveBeenCalledWith(expect.objectContaining({ accountId: PARAMS.dstAddress }));
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('retries a failed NEAR storage check instead of swapping', async () => {
|
|
208
|
+
const nearRetry = vi.fn();
|
|
209
|
+
stub({ near: { isNear: true, checkFailed: true, retry: nearRetry } });
|
|
210
|
+
const lifecycle = run();
|
|
211
|
+
|
|
212
|
+
expect(lifecycle.state).toEqual({ kind: 'needsSetup', reason: 'nearStorageCheckFailed' });
|
|
213
|
+
await lifecycle.next();
|
|
214
|
+
expect(nearRetry).toHaveBeenCalledOnce();
|
|
215
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
it.each([
|
|
219
|
+
['a trustline tx in flight', { stellar: { needsTrustline: true, isRequestingTrustline: true } }, 0],
|
|
220
|
+
['a storage tx in flight', { near: { needsRegistration: true, isRegistering: true } }, 0],
|
|
221
|
+
['the storage check refreshing after the tx', { near: { needsRegistration: true } }, 1],
|
|
222
|
+
] as const)('holds the setup step while %s, so a second click sends nothing', async (_label, gates, fetching) => {
|
|
223
|
+
stub({
|
|
224
|
+
stellar: { isStellar: true, blocksAction: true, ...('stellar' in gates ? gates.stellar : {}) },
|
|
225
|
+
near: { isNear: true, blocksAction: true, ...('near' in gates ? gates.near : {}) },
|
|
226
|
+
});
|
|
227
|
+
fetchingChecks.mockReturnValueOnce(fetching);
|
|
228
|
+
const lifecycle = run();
|
|
229
|
+
|
|
230
|
+
expect(lifecycle.state).toEqual({ kind: 'checking' });
|
|
231
|
+
await lifecycle.next();
|
|
232
|
+
expect(openGate.requestTrustline).not.toHaveBeenCalled();
|
|
233
|
+
expect(openGate.registerStorage).not.toHaveBeenCalled();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it('leaves app-owned prerequisites to the app', async () => {
|
|
237
|
+
stub();
|
|
238
|
+
const lifecycle = run({ externalBlocked: true });
|
|
239
|
+
|
|
240
|
+
expect(lifecycle.state).toEqual({ kind: 'needsSetup', reason: 'external' });
|
|
241
|
+
await expect(lifecycle.next()).resolves.toBeUndefined();
|
|
242
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it('resumes an unconfirmed batch from next() instead of sending it again, and exposes its error', async () => {
|
|
246
|
+
const error = new SodaxError('TX_VERIFICATION_FAILED', 'batch not confirmed', {
|
|
247
|
+
feature: 'swap',
|
|
248
|
+
context: { reason: ATOMIC_BATCH_UNCONFIRMED, batchId: 'batch-1', callCount: 2 },
|
|
249
|
+
});
|
|
250
|
+
const sent = { params: PARAMS, walletProvider: WALLET, extras: { apiKey: 'k' }, timeout: 30_000 };
|
|
251
|
+
stub({ swap: { status: 'error', error, variables: sent } });
|
|
252
|
+
mutateAsyncSafe.mockResolvedValueOnce({ ok: true, value: {} });
|
|
253
|
+
const lifecycle = run();
|
|
254
|
+
|
|
255
|
+
expect(lifecycle.state).toEqual({ kind: 'unconfirmed', batchId: 'batch-1', callCount: 2, error });
|
|
256
|
+
expect(lifecycle.error).toBe(error);
|
|
257
|
+
await lifecycle.next();
|
|
258
|
+
expect(resetSwap).not.toHaveBeenCalled();
|
|
259
|
+
expect(mutateAsyncSafe).toHaveBeenCalledWith({ ...sent, resumeBatchId: 'batch-1', resumeBatchCallCount: 2 });
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it('keeps an unconfirmed batch after the params change, and resumes it with the params that sent it', async () => {
|
|
263
|
+
const error = new SodaxError('TX_VERIFICATION_FAILED', 'batch not confirmed', {
|
|
264
|
+
feature: 'swap',
|
|
265
|
+
context: { reason: ATOMIC_BATCH_UNCONFIRMED, batchId: 'batch-1' },
|
|
266
|
+
});
|
|
267
|
+
stub({ swap: { status: 'error', error, variables: { params: PARAMS, walletProvider: WALLET } } });
|
|
268
|
+
mutateAsyncSafe.mockResolvedValueOnce({ ok: true, value: {} });
|
|
269
|
+
const lifecycle = run({ intentParams: { ...PARAMS, minOutputAmount: 899_000n } });
|
|
270
|
+
|
|
271
|
+
expect(lifecycle.state).toEqual({ kind: 'unconfirmed', batchId: 'batch-1', error });
|
|
272
|
+
await lifecycle.next();
|
|
273
|
+
expect(mutateAsyncSafe).toHaveBeenCalledWith({ params: PARAMS, walletProvider: WALLET, resumeBatchId: 'batch-1' });
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it('runs one next() at a time, so a double click swaps once', async () => {
|
|
277
|
+
stub();
|
|
278
|
+
let finish: (value: unknown) => void = () => {};
|
|
279
|
+
mutateAsyncSafe.mockReturnValueOnce(
|
|
280
|
+
new Promise(resolve => {
|
|
281
|
+
finish = resolve;
|
|
282
|
+
}),
|
|
283
|
+
);
|
|
284
|
+
const lifecycle = run();
|
|
285
|
+
|
|
286
|
+
const first = lifecycle.next();
|
|
287
|
+
await expect(lifecycle.next()).resolves.toBeUndefined();
|
|
288
|
+
expect(mutateAsyncSafe).toHaveBeenCalledOnce();
|
|
289
|
+
|
|
290
|
+
finish({ ok: true, value: {} });
|
|
291
|
+
await first;
|
|
292
|
+
mutateAsyncSafe.mockResolvedValueOnce({ ok: true, value: {} });
|
|
293
|
+
await lifecycle.next();
|
|
294
|
+
expect(mutateAsyncSafe).toHaveBeenCalledTimes(2);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it('exposes the error of a swap that failed after broadcast while it stays pending', () => {
|
|
298
|
+
const error = new SodaxError('RELAY_TIMEOUT', 'relay timed out', {
|
|
299
|
+
feature: 'swap',
|
|
300
|
+
context: { srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc' },
|
|
301
|
+
});
|
|
302
|
+
stub({ swap: { status: 'error', error, variables: { params: PARAMS } } });
|
|
303
|
+
const lifecycle = run();
|
|
304
|
+
|
|
305
|
+
expect(lifecycle.state).toMatchObject({ kind: 'pending', srcTxHash: '0xsrc' });
|
|
306
|
+
expect(lifecycle.error).toBe(error);
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it('ignores reset() while the swap call is in flight', () => {
|
|
310
|
+
stub({ swap: { status: 'pending', isPending: true, variables: { params: PARAMS } } });
|
|
311
|
+
const lifecycle = run();
|
|
312
|
+
|
|
313
|
+
expect(lifecycle.state).toEqual({ kind: 'submitting' });
|
|
314
|
+
lifecycle.reset();
|
|
315
|
+
expect(resetSwap).not.toHaveBeenCalled();
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it('surfaces a failed swap on error and resets it from next()', async () => {
|
|
319
|
+
const error = new Error('User rejected the request');
|
|
320
|
+
stub({ swap: { status: 'error', error, variables: { params: PARAMS } } });
|
|
321
|
+
const lifecycle = run();
|
|
322
|
+
|
|
323
|
+
expect(lifecycle.state).toEqual({ kind: 'failed', error });
|
|
324
|
+
expect(lifecycle.error).toBe(error);
|
|
325
|
+
await lifecycle.next();
|
|
326
|
+
expect(resetSwap).toHaveBeenCalledOnce();
|
|
327
|
+
expect(refetchStrategy).toHaveBeenCalledOnce();
|
|
328
|
+
});
|
|
329
|
+
});
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isAuthFailure,
|
|
3
|
+
summarizeSwapStatus,
|
|
4
|
+
type CreateIntentParams,
|
|
5
|
+
type GetWalletProviderType,
|
|
6
|
+
type Result,
|
|
7
|
+
type SpokeChainKey,
|
|
8
|
+
type SwapApprovalStrategy,
|
|
9
|
+
type SwapExtras,
|
|
10
|
+
type SwapWithApprovalResponse,
|
|
11
|
+
} from '@sodax/sdk';
|
|
12
|
+
import { useIsFetching, type UseQueryResult } from '@tanstack/react-query';
|
|
13
|
+
import { useRef } from 'react';
|
|
14
|
+
import { resolveSwapLifecycle, toSwapAttempt, type SwapLifecycleState } from '../../utils/swapLifecycle.js';
|
|
15
|
+
import { useNearStorageGate, type NearStorageGate } from '../shared/useNearStorageGate.js';
|
|
16
|
+
import { useStellarGate, type StellarGate } from '../shared/useStellarGate.js';
|
|
17
|
+
import type { MutationHookOptions } from '../shared/types.js';
|
|
18
|
+
import type { SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
19
|
+
import { useDetailedStatus, type UseDetailedStatusResult } from './useDetailedStatus.js';
|
|
20
|
+
import { useSwapApprovalStrategy } from './useSwapApprovalStrategy.js';
|
|
21
|
+
import { useSwapWithApproval, type UseSwapWithApprovalVars } from './useSwapWithApproval.js';
|
|
22
|
+
|
|
23
|
+
export type { SwapLifecycleState, SwapSetupReason } from '../../utils/swapLifecycle.js';
|
|
24
|
+
|
|
25
|
+
export type UseSwapLifecycleParams<K extends SpokeChainKey = SpokeChainKey> = {
|
|
26
|
+
/**
|
|
27
|
+
* The swap to run. Changing it starts a new lifecycle once the current swap is done; one that may still
|
|
28
|
+
* land (failed after broadcast, or an unconfirmed batch) holds until `reset()`. A `0n` `minOutputAmount`
|
|
29
|
+
* accepts any fill, so an app should not send one.
|
|
30
|
+
*/
|
|
31
|
+
intentParams: CreateIntentParams<K> | undefined;
|
|
32
|
+
srcWalletProvider: GetWalletProviderType<K> | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Destination wallet, for the Stellar and NEAR setup actions. The gates check `intentParams.dstAddress`,
|
|
35
|
+
* the account the swap pays, so this wallet must control it for those actions to clear them.
|
|
36
|
+
*/
|
|
37
|
+
dstWalletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
|
|
38
|
+
/** Source-chain switching, e.g. `useEvmSwitchChain` from `@sodax/wallet-sdk-react`. */
|
|
39
|
+
chainSwitch?: { isWrongChain: boolean; switchChain: () => void | Promise<void> };
|
|
40
|
+
/** An app-owned prerequisite that must hold before swapping (e.g. a Bitcoin trading-wallet setup). */
|
|
41
|
+
externalBlocked?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* `false` approves separately instead of asking a `'ready'` wallet to upgrade the account (e.g. after
|
|
44
|
+
* the user declined: `USER_REJECTED` with `context.reason === ACCOUNT_UPGRADE_DECLINED`). Defaults to `true`.
|
|
45
|
+
*/
|
|
46
|
+
allowAccountUpgrade?: boolean;
|
|
47
|
+
extras?: SwapExtras<K>;
|
|
48
|
+
timeout?: number;
|
|
49
|
+
mutationOptions?: MutationHookOptions<SwapWithApprovalResponse, UseSwapWithApprovalVars<K>>;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export type SwapLifecycle<K extends SpokeChainKey = SpokeChainKey> = {
|
|
53
|
+
state: SwapLifecycleState;
|
|
54
|
+
/** The error behind `failed`, `unconfirmed` or a `pending` with one. Setup-action failures come back from `next()`. */
|
|
55
|
+
error: Error | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Does what the current state needs: switch chain, resolve a setup step, swap, re-check an `unconfirmed`
|
|
58
|
+
* batch (finishing the swap once it lands, never sending it again), or start over after a settled or
|
|
59
|
+
* failed swap. Does nothing while waiting or while a previous call is still running.
|
|
60
|
+
*/
|
|
61
|
+
next: () => Promise<Result<unknown> | undefined>;
|
|
62
|
+
/**
|
|
63
|
+
* Stops tracking the current swap and re-reads the approval strategy. Cancels nothing on-chain; a no-op
|
|
64
|
+
* while the swap call is still in flight.
|
|
65
|
+
*/
|
|
66
|
+
reset: () => void;
|
|
67
|
+
// Escape hatches: the composed hooks, for UIs that need more than `state`.
|
|
68
|
+
approvalStrategy: UseQueryResult<SwapApprovalStrategy, Error>;
|
|
69
|
+
swap: SafeUseMutationResult<SwapWithApprovalResponse, Error, UseSwapWithApprovalVars<K>>;
|
|
70
|
+
status: UseQueryResult<UseDetailedStatusResult>;
|
|
71
|
+
stellar: StellarGate;
|
|
72
|
+
nearStorage: NearStorageGate;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 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
|
|
78
|
+
* signature on an EIP-5792 wallet) and its status (`useDetailedStatus`), as a single discriminated
|
|
79
|
+
* `state` with one `next()` action. Render from `state.kind`; wire the button to `next()`.
|
|
80
|
+
*
|
|
81
|
+
* Headless and additive: the granular hooks are unchanged, and each one this composes is returned.
|
|
82
|
+
* Wallet-layer concerns (chain switching, app-owned setup) are passed in, because dapp-kit does not
|
|
83
|
+
* depend on the wallet packages.
|
|
84
|
+
*/
|
|
85
|
+
export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
|
|
86
|
+
intentParams,
|
|
87
|
+
srcWalletProvider,
|
|
88
|
+
dstWalletProvider,
|
|
89
|
+
chainSwitch,
|
|
90
|
+
externalBlocked = false,
|
|
91
|
+
allowAccountUpgrade,
|
|
92
|
+
extras,
|
|
93
|
+
timeout,
|
|
94
|
+
mutationOptions,
|
|
95
|
+
}: UseSwapLifecycleParams<K>): SwapLifecycle<K> {
|
|
96
|
+
const approvalStrategy = useSwapApprovalStrategy<K>({
|
|
97
|
+
params: { payload: intentParams, walletProvider: srcWalletProvider, allowAccountUpgrade },
|
|
98
|
+
});
|
|
99
|
+
const swap = useSwapWithApproval<K>({ mutationOptions });
|
|
100
|
+
const stellar = useStellarGate({
|
|
101
|
+
dstChainKey: intentParams?.dstChainKey,
|
|
102
|
+
token: intentParams?.outputToken,
|
|
103
|
+
// A 0n amount disables the trustline check, which would hold the lifecycle in `checking`.
|
|
104
|
+
amount: intentParams && (intentParams.minOutputAmount > 0n ? intentParams.minOutputAmount : 1n),
|
|
105
|
+
address: intentParams?.dstAddress,
|
|
106
|
+
walletProvider: dstWalletProvider,
|
|
107
|
+
});
|
|
108
|
+
const nearStorage = useNearStorageGate({
|
|
109
|
+
dstChainKey: intentParams?.dstChainKey,
|
|
110
|
+
token: intentParams?.outputToken,
|
|
111
|
+
accountId: intentParams?.dstAddress,
|
|
112
|
+
walletProvider: dstWalletProvider,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// The setup mutations invalidate these checks without awaiting the refetch, so a stale "needs setup"
|
|
116
|
+
// outlives the tx by one read.
|
|
117
|
+
const fetchingSetupChecks =
|
|
118
|
+
useIsFetching({ queryKey: ['sponsoring', 'stellarAccountStatus'] }) +
|
|
119
|
+
useIsFetching({ queryKey: ['shared', 'stellarTrustlineCheck'] }) +
|
|
120
|
+
useIsFetching({ queryKey: ['shared', 'nearStorageCheck'] });
|
|
121
|
+
|
|
122
|
+
const attempt = toSwapAttempt(swap, intentParams);
|
|
123
|
+
const broadcast = attempt.phase === 'broadcast' ? attempt : undefined;
|
|
124
|
+
const status = useDetailedStatus({
|
|
125
|
+
params: { srcChainKey: broadcast?.srcChainKey, srcTxHash: broadcast?.srcTxHash },
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const state = resolveSwapLifecycle({
|
|
129
|
+
attempt,
|
|
130
|
+
status: status.data?.ok ? summarizeSwapStatus(status.data.value) : undefined,
|
|
131
|
+
statusError: status.data && !status.data.ok && isAuthFailure(status.data.error) ? status.data.error : undefined,
|
|
132
|
+
hasInputs: !!intentParams && !!srcWalletProvider,
|
|
133
|
+
stellar,
|
|
134
|
+
nearStorage,
|
|
135
|
+
externalBlocked,
|
|
136
|
+
setupBusy:
|
|
137
|
+
stellar.isActivating || stellar.isRequestingTrustline || nearStorage.isRegistering || fetchingSetupChecks > 0,
|
|
138
|
+
isWrongChain: chainSwitch?.isWrongChain ?? false,
|
|
139
|
+
strategy: { data: approvalStrategy.data, error: approvalStrategy.error },
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const reset = (): void => {
|
|
143
|
+
// Resetting mid-call would detach the observer and re-enable the button while the swap still runs.
|
|
144
|
+
if (swap.isPending) return;
|
|
145
|
+
swap.reset();
|
|
146
|
+
void approvalStrategy.refetch();
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const act = async (): Promise<Result<unknown> | undefined> => {
|
|
150
|
+
switch (state.kind) {
|
|
151
|
+
case 'needsChainSwitch':
|
|
152
|
+
await chainSwitch?.switchChain();
|
|
153
|
+
return undefined;
|
|
154
|
+
case 'needsSetup':
|
|
155
|
+
if (state.reason === 'stellarActivation') return stellar.activate();
|
|
156
|
+
if (state.reason === 'stellarTrustline') return stellar.requestTrustline();
|
|
157
|
+
if (state.reason === 'nearStorage') return nearStorage.registerStorage();
|
|
158
|
+
if (state.reason === 'stellarCheckFailed') stellar.retry();
|
|
159
|
+
if (state.reason === 'nearStorageCheckFailed') nearStorage.retry();
|
|
160
|
+
// `stellarFunding` and `external` are for the app to resolve.
|
|
161
|
+
return undefined;
|
|
162
|
+
case 'ready':
|
|
163
|
+
if (!intentParams || !srcWalletProvider) return undefined;
|
|
164
|
+
return swap.mutateAsyncSafe({
|
|
165
|
+
params: intentParams,
|
|
166
|
+
walletProvider: srcWalletProvider,
|
|
167
|
+
allowAccountUpgrade,
|
|
168
|
+
extras,
|
|
169
|
+
timeout,
|
|
170
|
+
});
|
|
171
|
+
// Sending it again could swap twice, so this only waits for the batch the wallet already holds.
|
|
172
|
+
case 'unconfirmed':
|
|
173
|
+
if (!swap.variables) return undefined;
|
|
174
|
+
return swap.mutateAsyncSafe({
|
|
175
|
+
...swap.variables,
|
|
176
|
+
resumeBatchId: state.batchId,
|
|
177
|
+
resumeBatchCallCount: state.callCount,
|
|
178
|
+
});
|
|
179
|
+
case 'settled':
|
|
180
|
+
case 'failed':
|
|
181
|
+
reset();
|
|
182
|
+
return undefined;
|
|
183
|
+
default:
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// Two calls before React re-renders would both see `ready` and swap twice.
|
|
189
|
+
const acting = useRef(false);
|
|
190
|
+
const next = async (): Promise<Result<unknown> | undefined> => {
|
|
191
|
+
if (acting.current) return undefined;
|
|
192
|
+
acting.current = true;
|
|
193
|
+
try {
|
|
194
|
+
return await act();
|
|
195
|
+
} finally {
|
|
196
|
+
acting.current = false;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
state,
|
|
202
|
+
error:
|
|
203
|
+
state.kind === 'failed' || state.kind === 'unconfirmed' || state.kind === 'pending' ? state.error : undefined,
|
|
204
|
+
next,
|
|
205
|
+
reset,
|
|
206
|
+
approvalStrategy,
|
|
207
|
+
swap,
|
|
208
|
+
status,
|
|
209
|
+
stellar,
|
|
210
|
+
nearStorage,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
const VARS = {
|
|
5
|
+
params: { srcChainKey: ChainKeys.BSC_MAINNET, dstChainKey: ChainKeys.ARBITRUM_MAINNET },
|
|
6
|
+
walletProvider: {},
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
type CapturedMutation = {
|
|
10
|
+
mutationKey: unknown;
|
|
11
|
+
mutationFn: (vars: unknown) => Promise<unknown>;
|
|
12
|
+
onSuccess: (data: unknown, vars: typeof VARS, ctx: unknown) => Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
let captured: CapturedMutation;
|
|
15
|
+
const invalidateQueries = vi.fn();
|
|
16
|
+
const swapWithApproval = vi.fn();
|
|
17
|
+
|
|
18
|
+
vi.mock('../shared/useSodaxContext.js', () => ({
|
|
19
|
+
useSodaxContext: () => ({ sodax: { swaps: { swapWithApproval } } }),
|
|
20
|
+
}));
|
|
21
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
|
|
22
|
+
vi.mock('../shared/useSafeMutation.js', () => ({
|
|
23
|
+
useSafeMutation: (options: CapturedMutation) => {
|
|
24
|
+
captured = options;
|
|
25
|
+
return {};
|
|
26
|
+
},
|
|
27
|
+
}));
|
|
28
|
+
|
|
29
|
+
const { useSwapWithApproval } = await import('./useSwapWithApproval.js');
|
|
30
|
+
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
vi.clearAllMocks();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe('useSwapWithApproval', () => {
|
|
36
|
+
it('keys the mutation under swap and calls swapWithApproval in signed mode', async () => {
|
|
37
|
+
swapWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
|
|
38
|
+
useSwapWithApproval();
|
|
39
|
+
|
|
40
|
+
expect(captured.mutationKey).toEqual(['swap', 'swapWithApproval']);
|
|
41
|
+
await expect(captured.mutationFn(VARS)).resolves.toEqual({ approvalStrategy: 'atomic-batch' });
|
|
42
|
+
expect(swapWithApproval).toHaveBeenCalledWith({ ...VARS, raw: false });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('throws the SDK error so React Query sees a failure', async () => {
|
|
46
|
+
const error = new Error('USER_REJECTED');
|
|
47
|
+
swapWithApproval.mockResolvedValueOnce({ ok: false, error });
|
|
48
|
+
useSwapWithApproval();
|
|
49
|
+
|
|
50
|
+
await expect(captured.mutationFn(VARS)).rejects.toBe(error);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('invalidates allowance and approval strategy on success, then runs the consumer callback', async () => {
|
|
54
|
+
const onSuccess = vi.fn();
|
|
55
|
+
useSwapWithApproval({ mutationOptions: { onSuccess } });
|
|
56
|
+
|
|
57
|
+
await captured.onSuccess({}, VARS, undefined);
|
|
58
|
+
|
|
59
|
+
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swap', 'allowance'] });
|
|
60
|
+
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swap', 'approvalStrategy'] });
|
|
61
|
+
expect(onSuccess).toHaveBeenCalledOnce();
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
2
|
+
import type { SpokeChainKey, SwapWithApprovalParams, SwapWithApprovalResponse } from '@sodax/sdk';
|
|
3
|
+
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
4
|
+
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
5
|
+
import type { MutationHookParams } from '../shared/types.js';
|
|
6
|
+
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
7
|
+
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Mutation variables for {@link useSwapWithApproval}: `useSwap`'s, plus `allowAccountUpgrade`, `resumeBatchId` and
|
|
11
|
+
* `resumeBatchCallCount`.
|
|
12
|
+
*/
|
|
13
|
+
export type UseSwapWithApprovalVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SwapWithApprovalParams<K>, 'raw'>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `useSwap` with the source-token approval folded in (`sodax.swaps.swapWithApproval`): no approval
|
|
17
|
+
* when the allowance suffices, approve + swap as one EIP-5792 batch (one signature) on a
|
|
18
|
+
* batch-capable EVM wallet, otherwise approve, wait for it, then swap. `data.approvalStrategy`
|
|
19
|
+
* says which ran; {@link useSwapApprovalStrategy} predicts it.
|
|
20
|
+
*
|
|
21
|
+
* Throws on SDK failure so React Query's error model engages. On success invalidates balances and
|
|
22
|
+
* the swap allowance and approval-strategy queries.
|
|
23
|
+
*/
|
|
24
|
+
export function useSwapWithApproval<K extends SpokeChainKey = SpokeChainKey>({
|
|
25
|
+
mutationOptions,
|
|
26
|
+
}: MutationHookParams<SwapWithApprovalResponse, UseSwapWithApprovalVars<K>> = {}): SafeUseMutationResult<
|
|
27
|
+
SwapWithApprovalResponse,
|
|
28
|
+
Error,
|
|
29
|
+
UseSwapWithApprovalVars<K>
|
|
30
|
+
> {
|
|
31
|
+
const { sodax } = useSodaxContext();
|
|
32
|
+
const queryClient = useQueryClient();
|
|
33
|
+
|
|
34
|
+
return useSafeMutation<SwapWithApprovalResponse, Error, UseSwapWithApprovalVars<K>>({
|
|
35
|
+
mutationKey: ['swap', 'swapWithApproval'],
|
|
36
|
+
...mutationOptions,
|
|
37
|
+
mutationFn: async vars => unwrapResult(await sodax.swaps.swapWithApproval({ ...vars, raw: false })),
|
|
38
|
+
onSuccess: async (data, vars, ctx) => {
|
|
39
|
+
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
|
40
|
+
queryClient.invalidateQueries({ queryKey: ['swap', 'allowance'] });
|
|
41
|
+
queryClient.invalidateQueries({ queryKey: ['swap', 'approvalStrategy'] });
|
|
42
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -18,6 +18,7 @@ export * from './useSwapsApiDeadline.js';
|
|
|
18
18
|
export * from './useSwapsApiAllowance.js';
|
|
19
19
|
export * from './useSwapsApiApprove.js';
|
|
20
20
|
export * from './useSwapsApiApproveAndBroadcast.js';
|
|
21
|
+
export * from './useSwapsApiBroadcastWithApproval.js';
|
|
21
22
|
export * from './useSwapsApiCreateIntent.js';
|
|
22
23
|
|
|
23
24
|
// Intent lifecycle: submit · status · cancel · hash · packet · extra-data · lookup
|