@sodax/dapp-kit 2.2.0-rc.8 → 2.3.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/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,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hook folds the swaps-API approval into the intent broadcast: one EIP-5792 batch when the
|
|
3
|
+
* wallet can, the approval plan then the intent tx when it cannot. The SDK's batch policy runs for
|
|
4
|
+
* real here; only the wallet and the API are faked.
|
|
5
|
+
*
|
|
6
|
+
* Follows the package convention of testing hooks without a renderer: the React Query wrapper is
|
|
7
|
+
* mocked so `mutationFn` can be captured and driven directly.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
ACCOUNT_UPGRADE_DECLINED,
|
|
12
|
+
ATOMIC_BATCH_REFUSED,
|
|
13
|
+
ATOMIC_BATCH_UNCONFIRMED,
|
|
14
|
+
ChainKeys,
|
|
15
|
+
type EvmAtomicBatchSupport,
|
|
16
|
+
type EvmBatchResult,
|
|
17
|
+
type EvmRawTransaction,
|
|
18
|
+
} from '@sodax/sdk';
|
|
19
|
+
import { AtomicityNotSupportedError, AtomicReadyWalletRejectedUpgradeError, UserRejectedRequestError } from 'viem';
|
|
20
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
21
|
+
|
|
22
|
+
const approve = vi.fn();
|
|
23
|
+
const invalidateQueries = vi.fn();
|
|
24
|
+
|
|
25
|
+
let captured: any;
|
|
26
|
+
|
|
27
|
+
vi.mock('../shared/useSodaxContext.js', () => ({
|
|
28
|
+
useSodaxContext: () => ({ sodax: { api: { swaps: { approve } } } }),
|
|
29
|
+
}));
|
|
30
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
|
|
31
|
+
vi.mock('../shared/useSafeMutation.js', () => ({
|
|
32
|
+
useSafeMutation: (options: any) => {
|
|
33
|
+
captured = options;
|
|
34
|
+
return {};
|
|
35
|
+
},
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
const { useSwapsApiBroadcastWithApproval } = await import('./useSwapsApiBroadcastWithApproval.js');
|
|
39
|
+
|
|
40
|
+
const SRC = '0x00000000000000000000000000000000000000a1';
|
|
41
|
+
const RESET_TX: EvmRawTransaction = {
|
|
42
|
+
from: SRC,
|
|
43
|
+
to: '0x00000000000000000000000000000000000000b1',
|
|
44
|
+
value: 0n,
|
|
45
|
+
data: '0x01',
|
|
46
|
+
};
|
|
47
|
+
const APPROVE_TX: EvmRawTransaction = {
|
|
48
|
+
from: SRC,
|
|
49
|
+
to: '0x00000000000000000000000000000000000000b1',
|
|
50
|
+
value: 0n,
|
|
51
|
+
data: '0x02',
|
|
52
|
+
};
|
|
53
|
+
const INTENT_TX: EvmRawTransaction = {
|
|
54
|
+
from: SRC,
|
|
55
|
+
to: '0x00000000000000000000000000000000000000c1',
|
|
56
|
+
value: 0n,
|
|
57
|
+
data: '0x03',
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const BASE_CHAIN_ID = 8453;
|
|
61
|
+
const SONIC_CHAIN_ID = 146;
|
|
62
|
+
|
|
63
|
+
const body = (srcChainKey: string = ChainKeys.BASE_MAINNET) => ({
|
|
64
|
+
srcChainKey,
|
|
65
|
+
dstChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
66
|
+
inputToken: '0x00000000000000000000000000000000000000d1',
|
|
67
|
+
outputToken: '0x00000000000000000000000000000000000000d2',
|
|
68
|
+
inputAmount: '1000000',
|
|
69
|
+
minOutputAmount: '1',
|
|
70
|
+
deadline: '0',
|
|
71
|
+
allowPartialFill: false,
|
|
72
|
+
srcAddress: SRC,
|
|
73
|
+
dstAddress: SRC,
|
|
74
|
+
solver: '0x0000000000000000000000000000000000000000',
|
|
75
|
+
data: '0x',
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const confirmed: EvmBatchResult = {
|
|
79
|
+
status: 'success',
|
|
80
|
+
statusCode: 200,
|
|
81
|
+
atomic: true,
|
|
82
|
+
receipts: [{ transactionHash: '0xdeposit', status: 'success' }],
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/** Records sends and waits in order, so the sequential path's ordering is asserted, not assumed. */
|
|
86
|
+
function plainWallet(calls: string[]) {
|
|
87
|
+
return {
|
|
88
|
+
chainType: 'EVM' as const,
|
|
89
|
+
getWalletAddress: vi.fn(async () => SRC.toUpperCase().replace('0X', '0x')),
|
|
90
|
+
sendTransaction: vi.fn(async (tx: EvmRawTransaction, _options?: { expectedChainId?: number }) => {
|
|
91
|
+
calls.push(`send:${tx.data}`);
|
|
92
|
+
return `0xhash${tx.data.slice(2)}` as const;
|
|
93
|
+
}),
|
|
94
|
+
waitForTransactionReceipt: vi.fn(async (hash: string) => {
|
|
95
|
+
calls.push(`wait:${hash}`);
|
|
96
|
+
return { status: 'success' };
|
|
97
|
+
}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function batchWallet(calls: string[], support: EvmAtomicBatchSupport) {
|
|
102
|
+
return {
|
|
103
|
+
...plainWallet(calls),
|
|
104
|
+
getAtomicBatchSupport: vi.fn(async (_chainId: number) => support),
|
|
105
|
+
sendAtomicBatch: vi.fn(async (txs: readonly EvmRawTransaction[], _options: { expectedChainId: number }) => {
|
|
106
|
+
calls.push(`batch:${txs.map(tx => tx.data).join(',')}`);
|
|
107
|
+
return 'batch-1';
|
|
108
|
+
}),
|
|
109
|
+
waitForBatch: vi.fn(async (_batchId: string, _options?: { timeout?: number }) => confirmed),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const run = (vars: any) => {
|
|
114
|
+
useSwapsApiBroadcastWithApproval();
|
|
115
|
+
return captured.mutationFn({ body: body(), intentTx: INTENT_TX, ...vars });
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
beforeEach(() => {
|
|
119
|
+
vi.clearAllMocks();
|
|
120
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe('useSwapsApiBroadcastWithApproval', () => {
|
|
124
|
+
it('sends approve + intent as one batch on a batch-capable wallet', async () => {
|
|
125
|
+
const calls: string[] = [];
|
|
126
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
127
|
+
|
|
128
|
+
const result = await run({ walletProvider });
|
|
129
|
+
|
|
130
|
+
expect(result).toEqual({ txHash: '0xdeposit', approvalStrategy: 'atomic-batch' });
|
|
131
|
+
expect(calls).toEqual(['batch:0x02,0x03']);
|
|
132
|
+
expect(walletProvider.sendAtomicBatch).toHaveBeenCalledWith([APPROVE_TX, INTENT_TX], {
|
|
133
|
+
expectedChainId: BASE_CHAIN_ID,
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('puts the allowance reset first in the batch', async () => {
|
|
138
|
+
approve.mockResolvedValueOnce({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
139
|
+
const calls: string[] = [];
|
|
140
|
+
|
|
141
|
+
await run({ walletProvider: batchWallet(calls, 'ready') });
|
|
142
|
+
|
|
143
|
+
expect(calls).toEqual(['batch:0x01,0x02,0x03']);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('rejects a wallet that cannot batch by default, sending nothing', async () => {
|
|
147
|
+
const calls: string[] = [];
|
|
148
|
+
const walletProvider = plainWallet(calls);
|
|
149
|
+
|
|
150
|
+
await expect(run({ walletProvider })).rejects.toMatchObject({
|
|
151
|
+
code: 'INTENT_CREATION_FAILED',
|
|
152
|
+
context: { reason: ATOMIC_BATCH_REFUSED, approvalStrategy: 'sequential' },
|
|
153
|
+
});
|
|
154
|
+
expect(calls).toEqual([]);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('approves separately, then sends the intent, when the wallet cannot batch and fallbackOnRefusal is true', async () => {
|
|
158
|
+
const calls: string[] = [];
|
|
159
|
+
const walletProvider = plainWallet(calls);
|
|
160
|
+
|
|
161
|
+
const result = await run({ walletProvider, fallbackOnRefusal: true });
|
|
162
|
+
|
|
163
|
+
expect(result).toEqual({
|
|
164
|
+
txHash: '0xhash03',
|
|
165
|
+
approvalStrategy: 'sequential',
|
|
166
|
+
approval: { approveTxHash: '0xhash02' },
|
|
167
|
+
});
|
|
168
|
+
expect(calls).toEqual(['send:0x02', 'wait:0xhash02', 'send:0x03']);
|
|
169
|
+
expect(walletProvider.sendTransaction).toHaveBeenLastCalledWith(INTENT_TX, { expectedChainId: BASE_CHAIN_ID });
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('reports the batch id and call count once the wallet accepts the batch', async () => {
|
|
173
|
+
const onBatchSent = vi.fn();
|
|
174
|
+
await run({ walletProvider: batchWallet([], 'supported'), onBatchSent });
|
|
175
|
+
expect(onBatchSent).toHaveBeenCalledWith('batch-1', 2);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('rejects a refused batch instead of approving by default', async () => {
|
|
179
|
+
const calls: string[] = [];
|
|
180
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
181
|
+
walletProvider.sendAtomicBatch.mockRejectedValueOnce(new AtomicityNotSupportedError(new Error('no atomicity')));
|
|
182
|
+
|
|
183
|
+
await expect(run({ walletProvider })).rejects.toMatchObject({
|
|
184
|
+
code: 'INTENT_CREATION_FAILED',
|
|
185
|
+
context: { reason: ATOMIC_BATCH_REFUSED },
|
|
186
|
+
});
|
|
187
|
+
expect(walletProvider.sendTransaction).not.toHaveBeenCalled();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// The caller chose the batch on an earlier capability read; a later read that fails must not approve
|
|
191
|
+
// and send its pre-approval intent behind the caller's back.
|
|
192
|
+
it('hands back a wallet that can no longer batch by default', async () => {
|
|
193
|
+
const calls: string[] = [];
|
|
194
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
195
|
+
walletProvider.getAtomicBatchSupport.mockRejectedValueOnce(new Error('capabilities unavailable'));
|
|
196
|
+
|
|
197
|
+
await expect(run({ walletProvider })).rejects.toMatchObject({
|
|
198
|
+
code: 'INTENT_CREATION_FAILED',
|
|
199
|
+
context: { reason: ATOMIC_BATCH_REFUSED, approvalStrategy: 'sequential' },
|
|
200
|
+
});
|
|
201
|
+
expect(calls).toEqual([]);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('refreshes the allowance once the approval lands, even when the intent is then rejected', async () => {
|
|
205
|
+
const calls: string[] = [];
|
|
206
|
+
const walletProvider = plainWallet(calls);
|
|
207
|
+
walletProvider.sendTransaction.mockImplementation(async (tx: EvmRawTransaction) => {
|
|
208
|
+
calls.push(`send:${tx.data}`);
|
|
209
|
+
if (tx.data === INTENT_TX.data) throw new Error('User rejected the request.');
|
|
210
|
+
return `0xhash${tx.data.slice(2)}` as const;
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
await expect(run({ walletProvider, fallbackOnRefusal: true })).rejects.toThrow('User rejected');
|
|
214
|
+
expect(calls).toEqual(['send:0x02', 'wait:0xhash02', 'send:0x03']);
|
|
215
|
+
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swapsApi', 'allowance'] });
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
it('falls back to approving separately when the wallet refuses the batch and fallbackOnRefusal is true', async () => {
|
|
219
|
+
const calls: string[] = [];
|
|
220
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
221
|
+
walletProvider.sendAtomicBatch.mockRejectedValueOnce(new AtomicityNotSupportedError(new Error('no atomicity')));
|
|
222
|
+
|
|
223
|
+
const result = await run({ walletProvider, fallbackOnRefusal: true });
|
|
224
|
+
|
|
225
|
+
expect(result.approvalStrategy).toBe('sequential');
|
|
226
|
+
expect(calls).toEqual(['send:0x02', 'wait:0xhash02', 'send:0x03']);
|
|
227
|
+
expect(approve).toHaveBeenCalledTimes(1);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it('keeps a ready wallet sequential when the account upgrade is not allowed', async () => {
|
|
231
|
+
const calls: string[] = [];
|
|
232
|
+
const walletProvider = batchWallet(calls, 'ready');
|
|
233
|
+
|
|
234
|
+
const result = await run({ walletProvider, allowAccountUpgrade: false, fallbackOnRefusal: true });
|
|
235
|
+
|
|
236
|
+
expect(result.approvalStrategy).toBe('sequential');
|
|
237
|
+
expect(walletProvider.sendAtomicBatch).not.toHaveBeenCalled();
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it.each([
|
|
241
|
+
['a rejected batch', new UserRejectedRequestError(new Error('User rejected')), undefined],
|
|
242
|
+
['a declined upgrade', new AtomicReadyWalletRejectedUpgradeError(new Error('declined')), ACCOUNT_UPGRADE_DECLINED],
|
|
243
|
+
])('reports %s as USER_REJECTED and sends nothing else', async (_label, cause, reason) => {
|
|
244
|
+
const calls: string[] = [];
|
|
245
|
+
const walletProvider = batchWallet(calls, 'ready');
|
|
246
|
+
walletProvider.sendAtomicBatch.mockRejectedValueOnce(cause);
|
|
247
|
+
|
|
248
|
+
const error = await run({ walletProvider }).catch((e: unknown) => e);
|
|
249
|
+
expect(error).toMatchObject({ code: 'USER_REJECTED' });
|
|
250
|
+
expect((error as { context?: { reason?: string } }).context?.reason).toBe(reason);
|
|
251
|
+
expect(walletProvider.sendTransaction).not.toHaveBeenCalled();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it('never resends a batch that was sent but not confirmed', async () => {
|
|
255
|
+
const calls: string[] = [];
|
|
256
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
257
|
+
walletProvider.waitForBatch.mockRejectedValueOnce(new Error('timed out'));
|
|
258
|
+
|
|
259
|
+
await expect(run({ walletProvider })).rejects.toMatchObject({
|
|
260
|
+
code: 'TX_VERIFICATION_FAILED',
|
|
261
|
+
context: { reason: ATOMIC_BATCH_UNCONFIRMED, batchId: 'batch-1' },
|
|
262
|
+
});
|
|
263
|
+
expect(walletProvider.sendTransaction).not.toHaveBeenCalled();
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it('hands back a Sonic hub source by default, without asking the wallet', async () => {
|
|
267
|
+
const calls: string[] = [];
|
|
268
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
269
|
+
|
|
270
|
+
await expect(run({ body: body(ChainKeys.SONIC_MAINNET), walletProvider })).rejects.toMatchObject({
|
|
271
|
+
context: { reason: ATOMIC_BATCH_REFUSED },
|
|
272
|
+
});
|
|
273
|
+
expect(walletProvider.getAtomicBatchSupport).not.toHaveBeenCalled();
|
|
274
|
+
expect(calls).toEqual([]);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it('keeps the Sonic hub sequential without asking the wallet', async () => {
|
|
278
|
+
const calls: string[] = [];
|
|
279
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
280
|
+
|
|
281
|
+
const result = await run({ body: body(ChainKeys.SONIC_MAINNET), walletProvider, fallbackOnRefusal: true });
|
|
282
|
+
|
|
283
|
+
expect(result.approvalStrategy).toBe('sequential');
|
|
284
|
+
expect(walletProvider.getAtomicBatchSupport).not.toHaveBeenCalled();
|
|
285
|
+
expect(walletProvider.sendTransaction).toHaveBeenLastCalledWith(INTENT_TX, { expectedChainId: SONIC_CHAIN_ID });
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it('refuses before sending when the connected account is not the source address', async () => {
|
|
289
|
+
const calls: string[] = [];
|
|
290
|
+
const walletProvider = batchWallet(calls, 'supported');
|
|
291
|
+
walletProvider.getWalletAddress.mockResolvedValueOnce('0x00000000000000000000000000000000000000ff');
|
|
292
|
+
|
|
293
|
+
await expect(run({ walletProvider })).rejects.toThrow(/not the swap's source address/);
|
|
294
|
+
expect(calls).toEqual([]);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it('refuses an intent tx built for another account', async () => {
|
|
298
|
+
const calls: string[] = [];
|
|
299
|
+
|
|
300
|
+
await expect(
|
|
301
|
+
run({
|
|
302
|
+
walletProvider: batchWallet(calls, 'supported'),
|
|
303
|
+
intentTx: { ...INTENT_TX, from: '0x00000000000000000000000000000000000000ff' },
|
|
304
|
+
}),
|
|
305
|
+
).rejects.toThrow(/not the swap's source address/);
|
|
306
|
+
expect(calls).toEqual([]);
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it('refuses a non-EVM source before calling the API', async () => {
|
|
310
|
+
await expect(run({ body: body(ChainKeys.SOLANA_MAINNET), walletProvider: plainWallet([]) })).rejects.toThrow(
|
|
311
|
+
/not an EVM chain/,
|
|
312
|
+
);
|
|
313
|
+
expect(approve).not.toHaveBeenCalled();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it('awaits the allowance invalidation, then the consumer onSuccess', async () => {
|
|
317
|
+
const order: string[] = [];
|
|
318
|
+
invalidateQueries.mockImplementationOnce(async () => {
|
|
319
|
+
order.push('invalidate');
|
|
320
|
+
});
|
|
321
|
+
const onSuccess = vi.fn(() => {
|
|
322
|
+
order.push('consumer');
|
|
323
|
+
});
|
|
324
|
+
useSwapsApiBroadcastWithApproval({ mutationOptions: { onSuccess } });
|
|
325
|
+
|
|
326
|
+
await captured.onSuccess({ txHash: '0xdeposit', approvalStrategy: 'atomic-batch' }, {}, undefined);
|
|
327
|
+
|
|
328
|
+
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swapsApi', 'allowance'] });
|
|
329
|
+
expect(order).toEqual(['invalidate', 'consumer']);
|
|
330
|
+
});
|
|
331
|
+
});
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ATOMIC_BATCH_REFUSED,
|
|
3
|
+
DEFAULT_RELAY_TX_TIMEOUT,
|
|
4
|
+
SodaxError,
|
|
5
|
+
getEvmViemChain,
|
|
6
|
+
isEvmChainKeyType,
|
|
7
|
+
isAtomicBatchRefusal,
|
|
8
|
+
isEvmSpokeOnlyChainKeyType,
|
|
9
|
+
resolveApprovalStrategy,
|
|
10
|
+
sendApprovalBatch,
|
|
11
|
+
type ApprovalOptions,
|
|
12
|
+
type ApprovalStrategy,
|
|
13
|
+
type CreateIntentParamsV2,
|
|
14
|
+
type EvmRawTransaction,
|
|
15
|
+
type Hash,
|
|
16
|
+
type IEvmWalletProvider,
|
|
17
|
+
type RequestOverrideConfig,
|
|
18
|
+
type SpokeChainKey,
|
|
19
|
+
} from '@sodax/sdk';
|
|
20
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
21
|
+
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
22
|
+
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
23
|
+
import type { MutationHookParams } from '../shared/types.js';
|
|
24
|
+
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
25
|
+
import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
|
|
26
|
+
|
|
27
|
+
const HOOK_NAME = 'useSwapsApiBroadcastWithApproval';
|
|
28
|
+
|
|
29
|
+
export type UseSwapsApiBroadcastWithApprovalVars = ApprovalOptions & {
|
|
30
|
+
/** The swap's create-intent params — the same body `/swaps/intents` built `intentTx` from. */
|
|
31
|
+
body: CreateIntentParamsV2;
|
|
32
|
+
/** The unsigned source transaction `/swaps/intents` returned for `body`. */
|
|
33
|
+
intentTx: EvmRawTransaction;
|
|
34
|
+
walletProvider: IEvmWalletProvider;
|
|
35
|
+
apiConfig?: RequestOverrideConfig;
|
|
36
|
+
/** Progress of a separate approval, hashes included. A batch is one prompt and reports nothing. */
|
|
37
|
+
onProgress?: ApprovalProgressListener;
|
|
38
|
+
/**
|
|
39
|
+
* Called with the batch id and its call count once the wallet accepts the batch, before the wait.
|
|
40
|
+
* Persist both: if the batch comes back unconfirmed, `confirmApprovalBatch` with them is how to find
|
|
41
|
+
* the deposit again instead of sending a second one.
|
|
42
|
+
*/
|
|
43
|
+
onBatchSent?: (batchId: string, callCount: number) => void;
|
|
44
|
+
/**
|
|
45
|
+
* What happens when there is no batch to send: the wallet refuses it before signing, or cannot batch
|
|
46
|
+
* (the Sonic hub never does). By default the hook rejects with a refusal (`isAtomicBatchRefusal`) and
|
|
47
|
+
* sends nothing: approve with `useSwapsApiApproveAndBroadcast`, then create the intent again and sign
|
|
48
|
+
* that one. `true` approves and then sends this `intentTx` instead — built before the approval, so its
|
|
49
|
+
* deadline and quote must outlast the approval's wait.
|
|
50
|
+
*/
|
|
51
|
+
fallbackOnRefusal?: boolean;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export type SwapsApiBroadcastWithApprovalResult = {
|
|
55
|
+
/** The source transaction carrying the deposit — what `/swaps/submit-tx` takes as `txHash`. */
|
|
56
|
+
txHash: Hash;
|
|
57
|
+
approvalStrategy: Exclude<ApprovalStrategy, 'not-required'>;
|
|
58
|
+
/** The separate approval's hashes, when it ran on its own (`'sequential'`). */
|
|
59
|
+
approval?: ApprovalHashes;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const sameAddress = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase();
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* React hook that broadcasts a swaps-API intent transaction whose source-token allowance is short,
|
|
66
|
+
* with the approval folded in: on an EIP-5792 wallet, the approval and `intentTx` go out as **one
|
|
67
|
+
* atomic batch — one signature**.
|
|
68
|
+
*
|
|
69
|
+
* Call it when `/swaps/allowance/check` says the allowance is short and the source is an EVM chain —
|
|
70
|
+
* it always approves, so with enough allowance sign `intentTx` directly instead. It stops at the
|
|
71
|
+
* broadcast: persist `txHash` and then call `/swaps/submit-tx` as before.
|
|
72
|
+
*
|
|
73
|
+
* The batch rules match the SDK's `swapWithApproval`; the Sonic hub never batches. With no batch to
|
|
74
|
+
* send — the wallet cannot batch, or refuses the batch before signing — it rejects with a refusal
|
|
75
|
+
* (`isAtomicBatchRefusal`) and sends nothing: approve with `useSwapsApiApproveAndBroadcast`, create
|
|
76
|
+
* the intent again and sign that. `fallbackOnRefusal: true` approves (via {@link runApprovalPlan}) and
|
|
77
|
+
* sends this `intentTx` instead. A batch the user saw is never resent:
|
|
78
|
+
* - rejected → `SodaxError` `USER_REJECTED`, with `context.reason: ACCOUNT_UPGRADE_DECLINED` when the
|
|
79
|
+
* user declined the account upgrade — retry with `allowAccountUpgrade: false`;
|
|
80
|
+
* - never included or fully reverted → `INTENT_CREATION_FAILED`, `context.reason: 'atomic-batch-failed'`;
|
|
81
|
+
* - sent but not confirmed → `TX_VERIFICATION_FAILED`, `context.reason: ATOMIC_BATCH_UNCONFIRMED`. It
|
|
82
|
+
* may still land: do not let the user swap again. Resume it with `confirmApprovalBatch` and the
|
|
83
|
+
* batch id `onBatchSent` reported.
|
|
84
|
+
*
|
|
85
|
+
* With `fallbackOnRefusal: true`, errors from the separate approval or intent send are the wallet's
|
|
86
|
+
* own, as with `useSwapsApiApproveAndBroadcast`.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* const { mutateAsyncSafe: broadcast } = useSwapsApiBroadcastWithApproval();
|
|
90
|
+
* const created = await sodax.api.swaps.createIntent(body);
|
|
91
|
+
* const result = await broadcast({ body, intentTx: created.value.tx as EvmRawTransaction, walletProvider });
|
|
92
|
+
* if (result.ok) await submitTx({ txHash: result.value.txHash, ... });
|
|
93
|
+
* else if (isAtomicBatchRefusal(result.error)) {
|
|
94
|
+
* // Nothing was sent: approve, create the intent again (fresh deadline), sign it, then submit-tx.
|
|
95
|
+
* }
|
|
96
|
+
*/
|
|
97
|
+
export const useSwapsApiBroadcastWithApproval = ({
|
|
98
|
+
mutationOptions,
|
|
99
|
+
}: MutationHookParams<
|
|
100
|
+
SwapsApiBroadcastWithApprovalResult,
|
|
101
|
+
UseSwapsApiBroadcastWithApprovalVars
|
|
102
|
+
> = {}): SafeUseMutationResult<SwapsApiBroadcastWithApprovalResult, Error, UseSwapsApiBroadcastWithApprovalVars> => {
|
|
103
|
+
const { sodax } = useSodaxContext();
|
|
104
|
+
const queryClient = useQueryClient();
|
|
105
|
+
|
|
106
|
+
return useSafeMutation<SwapsApiBroadcastWithApprovalResult, Error, UseSwapsApiBroadcastWithApprovalVars>({
|
|
107
|
+
mutationKey: ['swapsApi', 'broadcastWithApproval'],
|
|
108
|
+
...mutationOptions,
|
|
109
|
+
mutationFn: async ({
|
|
110
|
+
body,
|
|
111
|
+
intentTx,
|
|
112
|
+
walletProvider,
|
|
113
|
+
apiConfig,
|
|
114
|
+
allowAccountUpgrade,
|
|
115
|
+
onProgress,
|
|
116
|
+
onBatchSent,
|
|
117
|
+
fallbackOnRefusal = false,
|
|
118
|
+
}): Promise<SwapsApiBroadcastWithApprovalResult> => {
|
|
119
|
+
const srcChainKey = body.srcChainKey as SpokeChainKey;
|
|
120
|
+
if (!isEvmChainKeyType(srcChainKey)) {
|
|
121
|
+
throw new Error(`[${HOOK_NAME}] ${body.srcChainKey} is not an EVM chain; approve and sign it separately.`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// The backend call stays ahead of any wallet call: `_apiKeyWire.test.ts` pins it as the first step.
|
|
125
|
+
const plan = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
|
|
126
|
+
|
|
127
|
+
const account = await walletProvider.getWalletAddress();
|
|
128
|
+
if (!sameAddress(account, body.srcAddress) || !sameAddress(account, intentTx.from)) {
|
|
129
|
+
throw new Error(`[${HOOK_NAME}] the connected account is not the swap's source address.`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const strategy = await resolveApprovalStrategy({ srcChainKey, walletProvider, allowAccountUpgrade });
|
|
133
|
+
if (strategy === 'atomic-batch' && isEvmSpokeOnlyChainKeyType(srcChainKey)) {
|
|
134
|
+
// The swaps-api client parses each tx with the source chain's schema: an EVM source yields EVM txs.
|
|
135
|
+
const approvalTxs = (plan.resetTx ? [plan.resetTx, plan.tx] : [plan.tx]) as EvmRawTransaction[];
|
|
136
|
+
const txs = [...approvalTxs, intentTx];
|
|
137
|
+
const sent = await sendApprovalBatch({
|
|
138
|
+
walletProvider,
|
|
139
|
+
srcChainKey,
|
|
140
|
+
txs,
|
|
141
|
+
timeoutMs: DEFAULT_RELAY_TX_TIMEOUT,
|
|
142
|
+
feature: 'swap',
|
|
143
|
+
context: { srcChainKey, dstChainKey: body.dstChainKey, action: HOOK_NAME, approvalStrategy: strategy },
|
|
144
|
+
onBatchSent: onBatchSent && (batchId => onBatchSent(batchId, txs.length)),
|
|
145
|
+
});
|
|
146
|
+
// Only a refusal before signing may approve separately: nothing was sent, so nothing can duplicate.
|
|
147
|
+
if (sent.ok || !isAtomicBatchRefusal(sent.error) || !fallbackOnRefusal) {
|
|
148
|
+
return { txHash: unwrapResult(sent).txHash, approvalStrategy: 'atomic-batch' };
|
|
149
|
+
}
|
|
150
|
+
} else if (!fallbackOnRefusal) {
|
|
151
|
+
// The two-step path is the caller's, so a wallet that cannot batch is handed back like a refusal.
|
|
152
|
+
throw new SodaxError(
|
|
153
|
+
'INTENT_CREATION_FAILED',
|
|
154
|
+
`[${HOOK_NAME}] the wallet cannot send this approval as a batch.`,
|
|
155
|
+
{
|
|
156
|
+
feature: 'swap',
|
|
157
|
+
context: {
|
|
158
|
+
srcChainKey,
|
|
159
|
+
dstChainKey: body.dstChainKey,
|
|
160
|
+
action: HOOK_NAME,
|
|
161
|
+
approvalStrategy: strategy,
|
|
162
|
+
phase: 'intentCreation',
|
|
163
|
+
reason: ATOMIC_BATCH_REFUSED,
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const approval = await runApprovalPlan({ plan, srcChainKey, walletProvider, hookName: HOOK_NAME, onProgress });
|
|
170
|
+
// The allowance is on-chain whatever happens to the intent next; a stale cached `valid: false` would re-offer it.
|
|
171
|
+
await queryClient.invalidateQueries({ queryKey: ['swapsApi', 'allowance'] });
|
|
172
|
+
const txHash = await walletProvider.sendTransaction(intentTx, {
|
|
173
|
+
expectedChainId: getEvmViemChain(srcChainKey).id,
|
|
174
|
+
});
|
|
175
|
+
return { txHash, approvalStrategy: 'sequential', approval };
|
|
176
|
+
},
|
|
177
|
+
onSuccess: async (data, vars, ctx) => {
|
|
178
|
+
// Awaited, as in useSwapsApiApproveAndBroadcast: a stale cached `valid: false` must not re-enable approval.
|
|
179
|
+
await queryClient.invalidateQueries({ queryKey: ['swapsApi', 'allowance'] });
|
|
180
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
};
|
|
@@ -27,7 +27,10 @@ export interface NearStorageGateState {
|
|
|
27
27
|
* triggered before registration status is known; `needsRegistration` only flips once the check has
|
|
28
28
|
* resolved (so the "register" button isn't shown speculatively while still checking).
|
|
29
29
|
*/
|
|
30
|
-
export function resolveNearStorageGate(
|
|
30
|
+
export function resolveNearStorageGate(
|
|
31
|
+
chainKey: SpokeChainKey | undefined,
|
|
32
|
+
check: NearStorageCheckResult,
|
|
33
|
+
): NearStorageGateState {
|
|
31
34
|
const isNear = chainKey === ChainKeys.NEAR_MAINNET;
|
|
32
35
|
const isChecking = check.isLoading;
|
|
33
36
|
const isRegistered = check.data;
|