@sodax/dapp-kit 2.1.0 → 2.2.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.
Files changed (70) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +120 -8
  3. package/dist/index.mjs +126 -61
  4. package/package.json +3 -3
  5. package/src/hooks/_apiKeyWire.test.ts +487 -0
  6. package/src/hooks/_mutationContract.test.ts +6 -0
  7. package/src/hooks/backend/index.ts +4 -0
  8. package/src/hooks/backend/useBackendOracleCandles.ts +47 -0
  9. package/src/hooks/backend/useBackendOracleMarkets.ts +30 -0
  10. package/src/hooks/bitcoin/useFundTradingWallet.ts +2 -1
  11. package/src/hooks/bitcoin/useRadfiWithdraw.ts +2 -1
  12. package/src/hooks/bridge/useBridge.test.ts +104 -0
  13. package/src/hooks/bridge/useBridge.ts +2 -2
  14. package/src/hooks/dex/useDexDeposit.ts +2 -1
  15. package/src/hooks/dex/useDexWithdraw.ts +2 -1
  16. package/src/hooks/dex/useSupplyLiquidity.ts +2 -1
  17. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +2 -2
  18. package/src/hooks/migrate/useMigrateBaln.ts +2 -2
  19. package/src/hooks/migrate/useMigrateIcxToSoda.ts +2 -2
  20. package/src/hooks/migrate/useMigratebnUSD.ts +2 -2
  21. package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +2 -2
  22. package/src/hooks/mm/useBorrow.ts +2 -4
  23. package/src/hooks/mm/useRepay.ts +2 -1
  24. package/src/hooks/mm/useSupply.ts +2 -1
  25. package/src/hooks/mm/useWithdraw.ts +2 -4
  26. package/src/hooks/partner/useFeeClaimWithdraw.ts +2 -1
  27. package/src/hooks/recovery/useWithdrawHubAsset.ts +2 -1
  28. package/src/hooks/shared/index.ts +3 -0
  29. package/src/hooks/shared/invalidateBalances.test.ts +71 -0
  30. package/src/hooks/shared/invalidateBalances.ts +25 -0
  31. package/src/hooks/shared/retryUnlessAuthFailure.test.ts +38 -0
  32. package/src/hooks/shared/retryUnlessAuthFailure.ts +18 -0
  33. package/src/hooks/shared/useBalances.test.ts +118 -0
  34. package/src/hooks/shared/useBalances.ts +81 -0
  35. package/src/hooks/shared/useEstablishTrustline.test.ts +2 -0
  36. package/src/hooks/shared/useEstablishTrustline.ts +2 -1
  37. package/src/hooks/shared/useStellarGate.test.ts +1 -1
  38. package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +6 -4
  39. package/src/hooks/sponsoring/useActivateStellarAccount.ts +2 -1
  40. package/src/hooks/sponsoring/useActivateStellarAccount.wire.test.ts +109 -0
  41. package/src/hooks/sponsoring/useSponsorConfig.test.ts +8 -2
  42. package/src/hooks/sponsoring/useStellarAccountActive.test.ts +2 -2
  43. package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +8 -2
  44. package/src/hooks/staking/useClaim.ts +2 -1
  45. package/src/hooks/staking/useInstantUnstake.ts +2 -1
  46. package/src/hooks/staking/useStake.ts +2 -1
  47. package/src/hooks/swap/useDetailedStatus.test.ts +2 -2
  48. package/src/hooks/swap/useSwap.test.ts +128 -0
  49. package/src/hooks/swap/useSwap.ts +2 -2
  50. package/src/hooks/swapsApi/useSwapsApiAllowance.ts +2 -1
  51. package/src/hooks/swapsApi/useSwapsApiApprove.ts +2 -1
  52. package/src/hooks/swapsApi/useSwapsApiCancelIntent.ts +2 -1
  53. package/src/hooks/swapsApi/useSwapsApiCreateIntent.ts +2 -1
  54. package/src/hooks/swapsApi/useSwapsApiCreateLimitOrder.ts +2 -1
  55. package/src/hooks/swapsApi/useSwapsApiDeadline.ts +2 -1
  56. package/src/hooks/swapsApi/useSwapsApiEstimateGas.ts +2 -1
  57. package/src/hooks/swapsApi/useSwapsApiFilledIntent.ts +2 -1
  58. package/src/hooks/swapsApi/useSwapsApiIntent.ts +2 -1
  59. package/src/hooks/swapsApi/useSwapsApiIntentExtraData.ts +2 -1
  60. package/src/hooks/swapsApi/useSwapsApiIntentHash.ts +2 -1
  61. package/src/hooks/swapsApi/useSwapsApiIntentPacket.ts +2 -1
  62. package/src/hooks/swapsApi/useSwapsApiPartnerFee.ts +2 -1
  63. package/src/hooks/swapsApi/useSwapsApiQuote.ts +5 -1
  64. package/src/hooks/swapsApi/useSwapsApiSolverFee.ts +2 -1
  65. package/src/hooks/swapsApi/useSwapsApiStatus.ts +10 -4
  66. package/src/hooks/swapsApi/useSwapsApiSubmitTx.ts +5 -3
  67. package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +8 -4
  68. package/src/hooks/swapsApi/useSwapsApiTokens.ts +2 -1
  69. package/src/hooks/swapsApi/useSwapsApiTokensByChain.ts +2 -1
  70. package/src/providers/SodaxProvider.test.ts +41 -0
@@ -0,0 +1,487 @@
1
+ /**
2
+ * Executable API-key wire manifest for the swapsApi + bridgeApi hook families.
3
+ *
4
+ * Every hook that accepts a per-request `apiConfig` must land it on the outgoing HTTP request as
5
+ * `x-api-key`. Each row renders its hook without a renderer (the package convention: the React
6
+ * Query wrapper is mocked so `queryFn`/`mutationFn` can be captured and driven directly) against a
7
+ * REAL `Sodax` instance whose config carries a DIFFERENT key — so a hook that silently drops its
8
+ * `apiConfig` still makes a request, still sends a key, and fails its row. The stubbed fetch serves
9
+ * a minimal 200 body; post-request validation rejections are expected and tolerated, because the
10
+ * request that already went out is the whole subject. For the approveAndBroadcast hooks that
11
+ * rejection also means the wallet machinery is never touched.
12
+ *
13
+ * To add a new swapsApi/bridgeApi hook, add its row here. The friction is intentional — it forces
14
+ * key-on-wire coverage from day one.
15
+ */
16
+
17
+ import { ChainKeys, Sodax, type RequestOverrideConfig } from '@sodax/sdk';
18
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
19
+
20
+ // biome-ignore lint/suspicious/noExplicitAny: the captured query/mutation options are driven directly.
21
+ let captured: any;
22
+
23
+ const sodax = new Sodax({ apiKey: 'instance-key', logger: 'silent' });
24
+
25
+ vi.mock('./shared/useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax }) }));
26
+ vi.mock('@tanstack/react-query', () => ({
27
+ // biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
28
+ useQuery: (options: any) => {
29
+ captured = options;
30
+ return {};
31
+ },
32
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
33
+ }));
34
+ vi.mock('./shared/useSafeMutation.js', () => ({
35
+ // biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
36
+ useSafeMutation: (options: any) => {
37
+ captured = options;
38
+ return {};
39
+ },
40
+ }));
41
+
42
+ const swapsApi = await import('./swapsApi/index.js');
43
+ const bridgeApi = await import('./bridgeApi/index.js');
44
+
45
+ const fetchMock = vi.fn<typeof globalThis.fetch>(
46
+ async () => new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }),
47
+ );
48
+ vi.stubGlobal('fetch', fetchMock);
49
+
50
+ // --- wire-DTO fixtures (string amounts; the six intent bigint fields are serialized client-side) ---
51
+
52
+ const INTENT = {
53
+ intentId: 1n,
54
+ creator: '0x3333333333333333333333333333333333333333',
55
+ inputToken: '0x4444444444444444444444444444444444444444',
56
+ outputToken: '0x5555555555555555555555555555555555555555',
57
+ inputAmount: 1_000_000n,
58
+ minOutputAmount: 900_000n,
59
+ deadline: 0n,
60
+ allowPartialFill: false,
61
+ srcChain: 4n,
62
+ dstChain: 44n,
63
+ srcAddress: '0x1111111111111111111111111111111111111111',
64
+ dstAddress: '0x2222222222222222222222222222222222222222',
65
+ solver: '0x0000000000000000000000000000000000000000',
66
+ data: '0x',
67
+ } as const;
68
+
69
+ const CREATE_INTENT_BODY = {
70
+ srcChainKey: ChainKeys.SONIC_MAINNET,
71
+ dstChainKey: ChainKeys.ARBITRUM_MAINNET,
72
+ inputToken: '0x4444444444444444444444444444444444444444',
73
+ outputToken: '0x5555555555555555555555555555555555555555',
74
+ inputAmount: '1000000',
75
+ minOutputAmount: '1',
76
+ deadline: '0',
77
+ allowPartialFill: false,
78
+ srcAddress: '0x1111111111111111111111111111111111111111',
79
+ dstAddress: '0x2222222222222222222222222222222222222222',
80
+ };
81
+
82
+ const QUOTE_BODY = {
83
+ tokenSrc: '0x4444444444444444444444444444444444444444',
84
+ tokenSrcChainKey: ChainKeys.SONIC_MAINNET,
85
+ tokenDst: '0x5555555555555555555555555555555555555555',
86
+ tokenDstChainKey: ChainKeys.ARBITRUM_MAINNET,
87
+ amount: '1000000',
88
+ quoteType: 'exact_input' as const,
89
+ };
90
+
91
+ const SUBMIT_TX_REQUEST = {
92
+ txHash: '0xabc',
93
+ srcChainKey: ChainKeys.SONIC_MAINNET,
94
+ walletAddress: '0x1111111111111111111111111111111111111111',
95
+ intent: INTENT,
96
+ relayData: '0x',
97
+ };
98
+
99
+ const BRIDGE_INTENT_BODY = {
100
+ srcChainKey: ChainKeys.BSC_MAINNET,
101
+ dstChainKey: ChainKeys.ARBITRUM_MAINNET,
102
+ inputToken: '0x4444444444444444444444444444444444444444',
103
+ outputToken: '0x5555555555555555555555555555555555555555',
104
+ inputAmount: '1000000',
105
+ srcAddress: '0x1111111111111111111111111111111111111111',
106
+ dstAddress: '0x2222222222222222222222222222222222222222',
107
+ };
108
+
109
+ const BRIDGE_QUOTE_BODY = {
110
+ srcChainKey: ChainKeys.BSC_MAINNET,
111
+ dstChainKey: ChainKeys.ARBITRUM_MAINNET,
112
+ inputToken: '0x4444444444444444444444444444444444444444',
113
+ outputToken: '0x5555555555555555555555555555555555555555',
114
+ };
115
+
116
+ const BRIDGE_SUBMIT_REQUEST = {
117
+ txHash: '0xabc',
118
+ srcChainKey: ChainKeys.BSC_MAINNET,
119
+ walletAddress: '0x1111111111111111111111111111111111111111',
120
+ relayData: { address: '0x1111111111111111111111111111111111111111', payload: '0x' },
121
+ };
122
+
123
+ // --- manifest ---------------------------------------------------------------
124
+
125
+ type Row = {
126
+ hook: string;
127
+ /** Exact pathname (below the `/v1` gateway root) the row's single request must hit. */
128
+ path: string;
129
+ /** Exact HTTP method of that request — with `path`, pins the row to one endpoint. */
130
+ method: 'GET' | 'POST';
131
+ /** Renders the hook with `apiConfig` threaded in, then drives the captured queryFn/mutationFn. */
132
+ run: (apiConfig: RequestOverrideConfig) => Promise<unknown>;
133
+ };
134
+
135
+ const ROWS: Row[] = [
136
+ // swapsApi read hooks
137
+ {
138
+ hook: 'useSwapsApiTokens',
139
+ path: '/swaps/tokens',
140
+ method: 'GET',
141
+ run: apiConfig => {
142
+ swapsApi.useSwapsApiTokens({ params: { apiConfig } });
143
+ return captured.queryFn();
144
+ },
145
+ },
146
+ {
147
+ hook: 'useSwapsApiTokensByChain',
148
+ path: '/swaps/tokens/sonic',
149
+ method: 'GET',
150
+ run: apiConfig => {
151
+ swapsApi.useSwapsApiTokensByChain({ params: { chainKey: ChainKeys.SONIC_MAINNET, apiConfig } });
152
+ return captured.queryFn();
153
+ },
154
+ },
155
+ {
156
+ hook: 'useSwapsApiQuote',
157
+ path: '/swaps/quote',
158
+ method: 'POST',
159
+ run: apiConfig => {
160
+ swapsApi.useSwapsApiQuote({ params: { body: QUOTE_BODY, apiConfig } });
161
+ return captured.queryFn();
162
+ },
163
+ },
164
+ {
165
+ hook: 'useSwapsApiDeadline',
166
+ path: '/swaps/deadline',
167
+ method: 'GET',
168
+ run: apiConfig => {
169
+ swapsApi.useSwapsApiDeadline({ params: { apiConfig } });
170
+ return captured.queryFn();
171
+ },
172
+ },
173
+ {
174
+ hook: 'useSwapsApiAllowance',
175
+ path: '/swaps/allowance/check',
176
+ method: 'POST',
177
+ run: apiConfig => {
178
+ swapsApi.useSwapsApiAllowance({ params: { body: CREATE_INTENT_BODY, apiConfig } });
179
+ return captured.queryFn();
180
+ },
181
+ },
182
+ {
183
+ hook: 'useSwapsApiStatus',
184
+ path: '/swaps/intents/status',
185
+ method: 'POST',
186
+ run: apiConfig => {
187
+ swapsApi.useSwapsApiStatus({ params: { intentTxHash: '0xabc', apiConfig } });
188
+ return captured.queryFn();
189
+ },
190
+ },
191
+ {
192
+ hook: 'useSwapsApiSubmitTxStatus',
193
+ path: '/swaps/submit-tx/status',
194
+ method: 'GET',
195
+ run: apiConfig => {
196
+ swapsApi.useSwapsApiSubmitTxStatus({
197
+ params: { txHash: '0xabc', srcChainKey: ChainKeys.SONIC_MAINNET, apiConfig },
198
+ });
199
+ return captured.queryFn();
200
+ },
201
+ },
202
+ {
203
+ hook: 'useSwapsApiFilledIntent',
204
+ path: '/swaps/intents/0xabc/fill',
205
+ method: 'GET',
206
+ run: apiConfig => {
207
+ swapsApi.useSwapsApiFilledIntent({ params: { txHash: '0xabc', apiConfig } });
208
+ return captured.queryFn();
209
+ },
210
+ },
211
+ {
212
+ hook: 'useSwapsApiIntent',
213
+ path: '/swaps/intents/0xabc',
214
+ method: 'GET',
215
+ run: apiConfig => {
216
+ swapsApi.useSwapsApiIntent({ params: { txHash: '0xabc', apiConfig } });
217
+ return captured.queryFn();
218
+ },
219
+ },
220
+ {
221
+ hook: 'useSwapsApiPartnerFee',
222
+ path: '/swaps/fees/partner',
223
+ method: 'GET',
224
+ run: apiConfig => {
225
+ swapsApi.useSwapsApiPartnerFee({ params: { amount: '1000', apiConfig } });
226
+ return captured.queryFn();
227
+ },
228
+ },
229
+ {
230
+ hook: 'useSwapsApiSolverFee',
231
+ path: '/swaps/fees/solver',
232
+ method: 'GET',
233
+ run: apiConfig => {
234
+ swapsApi.useSwapsApiSolverFee({ params: { amount: '1000', apiConfig } });
235
+ return captured.queryFn();
236
+ },
237
+ },
238
+ {
239
+ hook: 'useSwapsApiEstimateGas',
240
+ path: '/swaps/gas/estimate',
241
+ method: 'POST',
242
+ run: apiConfig => {
243
+ swapsApi.useSwapsApiEstimateGas({
244
+ params: { body: { chainKey: ChainKeys.SONIC_MAINNET, tx: { from: '0xf', to: '0xt', data: '0x' } }, apiConfig },
245
+ });
246
+ return captured.queryFn();
247
+ },
248
+ },
249
+ {
250
+ hook: 'useSwapsApiIntentExtraData',
251
+ path: '/swaps/intents/extra-data',
252
+ method: 'POST',
253
+ run: apiConfig => {
254
+ swapsApi.useSwapsApiIntentExtraData({ params: { body: { txHash: '0xabc' }, apiConfig } });
255
+ return captured.queryFn();
256
+ },
257
+ },
258
+ {
259
+ hook: 'useSwapsApiIntentHash',
260
+ path: '/swaps/intents/hash',
261
+ method: 'POST',
262
+ run: apiConfig => {
263
+ swapsApi.useSwapsApiIntentHash({ params: { intent: INTENT, apiConfig } });
264
+ return captured.queryFn();
265
+ },
266
+ },
267
+ {
268
+ hook: 'useSwapsApiIntentPacket',
269
+ path: '/swaps/intents/packet',
270
+ method: 'POST',
271
+ run: apiConfig => {
272
+ swapsApi.useSwapsApiIntentPacket({ params: { body: { chainId: '146', fillTxHash: '0xf' }, apiConfig } });
273
+ return captured.queryFn();
274
+ },
275
+ },
276
+ // swapsApi mutation hooks
277
+ {
278
+ hook: 'useSwapsApiApprove',
279
+ path: '/swaps/approve',
280
+ method: 'POST',
281
+ run: apiConfig => {
282
+ swapsApi.useSwapsApiApprove();
283
+ return captured.mutationFn({ body: CREATE_INTENT_BODY, apiConfig });
284
+ },
285
+ },
286
+ {
287
+ hook: 'useSwapsApiCancelIntent',
288
+ path: '/swaps/intents/cancel',
289
+ method: 'POST',
290
+ run: apiConfig => {
291
+ swapsApi.useSwapsApiCancelIntent();
292
+ return captured.mutationFn({ body: { srcChainKey: ChainKeys.SONIC_MAINNET, intent: INTENT }, apiConfig });
293
+ },
294
+ },
295
+ {
296
+ hook: 'useSwapsApiCreateIntent',
297
+ path: '/swaps/intents',
298
+ method: 'POST',
299
+ run: apiConfig => {
300
+ swapsApi.useSwapsApiCreateIntent();
301
+ return captured.mutationFn({ body: CREATE_INTENT_BODY, apiConfig });
302
+ },
303
+ },
304
+ {
305
+ hook: 'useSwapsApiCreateLimitOrder',
306
+ path: '/swaps/limit-orders',
307
+ method: 'POST',
308
+ run: apiConfig => {
309
+ swapsApi.useSwapsApiCreateLimitOrder();
310
+ return captured.mutationFn({ body: CREATE_INTENT_BODY, apiConfig });
311
+ },
312
+ },
313
+ {
314
+ hook: 'useSwapsApiSubmitIntent',
315
+ path: '/swaps/intents/submit',
316
+ method: 'POST',
317
+ run: apiConfig => {
318
+ swapsApi.useSwapsApiSubmitIntent();
319
+ return captured.mutationFn({ body: { chainId: '146', txHash: '0xabc' }, apiConfig });
320
+ },
321
+ },
322
+ {
323
+ hook: 'useSwapsApiSubmitTx',
324
+ path: '/swaps/submit-tx',
325
+ method: 'POST',
326
+ run: apiConfig => {
327
+ swapsApi.useSwapsApiSubmitTx();
328
+ return captured.mutationFn({ request: SUBMIT_TX_REQUEST, apiConfig });
329
+ },
330
+ },
331
+ {
332
+ // The `{}` 200 fails the approve schema, so the mutation rejects BEFORE any wallet work — the
333
+ // backend request this row asserts is the hook's first step.
334
+ hook: 'useSwapsApiApproveAndBroadcast',
335
+ path: '/swaps/approve',
336
+ method: 'POST',
337
+ run: apiConfig => {
338
+ swapsApi.useSwapsApiApproveAndBroadcast();
339
+ return captured.mutationFn({ body: CREATE_INTENT_BODY, walletProvider: {}, apiConfig });
340
+ },
341
+ },
342
+ // bridgeApi read hooks
343
+ {
344
+ hook: 'useBridgeApiTokens',
345
+ path: '/bridge/tokens',
346
+ method: 'GET',
347
+ run: apiConfig => {
348
+ bridgeApi.useBridgeApiTokens({ params: { apiConfig } });
349
+ return captured.queryFn();
350
+ },
351
+ },
352
+ {
353
+ hook: 'useBridgeApiTokensByChain',
354
+ path: '/bridge/tokens/0x38.bsc',
355
+ method: 'GET',
356
+ run: apiConfig => {
357
+ bridgeApi.useBridgeApiTokensByChain({ params: { chainKey: ChainKeys.BSC_MAINNET, apiConfig } });
358
+ return captured.queryFn();
359
+ },
360
+ },
361
+ {
362
+ hook: 'useBridgeApiAllowance',
363
+ path: '/bridge/allowance/check',
364
+ method: 'POST',
365
+ run: apiConfig => {
366
+ bridgeApi.useBridgeApiAllowance({ params: { body: BRIDGE_INTENT_BODY, apiConfig } });
367
+ return captured.queryFn();
368
+ },
369
+ },
370
+ {
371
+ hook: 'useBridgeApiBridgeableAmount',
372
+ path: '/bridge/bridgeable-amount',
373
+ method: 'POST',
374
+ run: apiConfig => {
375
+ bridgeApi.useBridgeApiBridgeableAmount({ params: { body: BRIDGE_QUOTE_BODY, apiConfig } });
376
+ return captured.queryFn();
377
+ },
378
+ },
379
+ {
380
+ hook: 'useBridgeApiFee',
381
+ path: '/bridge/fee',
382
+ method: 'POST',
383
+ run: apiConfig => {
384
+ bridgeApi.useBridgeApiFee({ params: { body: { inputAmount: '1000000' }, apiConfig } });
385
+ return captured.queryFn();
386
+ },
387
+ },
388
+ {
389
+ hook: 'useBridgeApiIsBridgeable',
390
+ path: '/bridge/bridgeable/check',
391
+ method: 'POST',
392
+ run: apiConfig => {
393
+ bridgeApi.useBridgeApiIsBridgeable({ params: { body: BRIDGE_QUOTE_BODY, apiConfig } });
394
+ return captured.queryFn();
395
+ },
396
+ },
397
+ {
398
+ hook: 'useBridgeApiSubmitTxStatus',
399
+ path: '/bridge/submit-tx/status',
400
+ method: 'GET',
401
+ run: apiConfig => {
402
+ bridgeApi.useBridgeApiSubmitTxStatus({
403
+ params: { txHash: '0xabc', srcChainKey: ChainKeys.BSC_MAINNET, apiConfig },
404
+ });
405
+ return captured.queryFn();
406
+ },
407
+ },
408
+ // bridgeApi mutation hooks
409
+ {
410
+ hook: 'useBridgeApiApprove',
411
+ path: '/bridge/approve',
412
+ method: 'POST',
413
+ run: apiConfig => {
414
+ bridgeApi.useBridgeApiApprove();
415
+ return captured.mutationFn({ body: BRIDGE_INTENT_BODY, apiConfig });
416
+ },
417
+ },
418
+ {
419
+ hook: 'useBridgeApiCreateBridgeIntent',
420
+ path: '/bridge/intents',
421
+ method: 'POST',
422
+ run: apiConfig => {
423
+ bridgeApi.useBridgeApiCreateBridgeIntent();
424
+ return captured.mutationFn({ body: BRIDGE_INTENT_BODY, apiConfig });
425
+ },
426
+ },
427
+ {
428
+ hook: 'useBridgeApiSubmitTx',
429
+ path: '/bridge/submit-tx',
430
+ method: 'POST',
431
+ run: apiConfig => {
432
+ bridgeApi.useBridgeApiSubmitTx();
433
+ return captured.mutationFn({ request: BRIDGE_SUBMIT_REQUEST, apiConfig });
434
+ },
435
+ },
436
+ {
437
+ // Same shape as the swaps row: the failed approve unwrap rejects before any wallet work.
438
+ hook: 'useBridgeApiApproveAndBroadcast',
439
+ path: '/bridge/approve',
440
+ method: 'POST',
441
+ run: apiConfig => {
442
+ bridgeApi.useBridgeApiApproveAndBroadcast();
443
+ return captured.mutationFn({ body: BRIDGE_INTENT_BODY, walletProvider: {}, apiConfig });
444
+ },
445
+ },
446
+ ];
447
+
448
+ /** Fails loudly when a named row is missing, so a hook rename cannot silently drop coverage. */
449
+ const rowFor = (hook: string): Row => {
450
+ const row = ROWS.find(r => r.hook === hook);
451
+ if (!row) throw new Error(`_apiKeyWire manifest has no row named ${hook}`);
452
+ return row;
453
+ };
454
+
455
+ beforeEach(() => {
456
+ fetchMock.mockClear();
457
+ captured = undefined;
458
+ });
459
+
460
+ describe('apiConfig.apiKey reaches the wire (hook-level key beats the instance key)', () => {
461
+ it.each(ROWS)('$hook → $method $path carries x-api-key: hook-key', async ({ path, method, run }) => {
462
+ await run({ apiKey: 'hook-key' }).catch(() => {}); // response may fail validation; the request is the subject
463
+ expect(fetchMock).toHaveBeenCalledTimes(1);
464
+ const [url, init] = fetchMock.mock.calls[0] ?? [];
465
+ expect(new URL(String(url)).pathname).toBe(`/v1${path}`);
466
+ expect(init?.method).toBe(method);
467
+ expect(new Headers(init?.headers).get('x-api-key')).toBe('hook-key');
468
+ });
469
+ });
470
+
471
+ describe('a raw x-api-key header override wins in any casing, without duplicating the header', () => {
472
+ const REPRESENTATIVES = [rowFor('useSwapsApiTokens'), rowFor('useBridgeApiTokens')];
473
+
474
+ it.each(REPRESENTATIVES)(
475
+ '$hook → $method $path carries exactly one x-api-key: raw-key',
476
+ async ({ path, method, run }) => {
477
+ await run({ headers: { 'X-Api-Key': 'raw-key' } }).catch(() => {});
478
+ expect(fetchMock).toHaveBeenCalledTimes(1);
479
+ const [url, init] = fetchMock.mock.calls[0] ?? [];
480
+ expect(new URL(String(url)).pathname).toBe(`/v1${path}`);
481
+ expect(init?.method).toBe(method);
482
+ const headers = init?.headers as Record<string, string>;
483
+ expect(Object.keys(headers).filter(name => name.toLowerCase() === 'x-api-key')).toHaveLength(1);
484
+ expect(new Headers(headers).get('x-api-key')).toBe('raw-key');
485
+ },
486
+ );
487
+ });
@@ -111,6 +111,12 @@ describe.each(HOOKS)('mutation hook contract: $path', ({ path, nativeThrow }) =>
111
111
  expect(fnIdx).toBeGreaterThan(spreadIdx);
112
112
  });
113
113
 
114
+ it('routes balance invalidation through invalidateBalances', () => {
115
+ // Hand-rolling one balance key invalidates only one of the two balance hooks (useBalances vs
116
+ // useXBalances) and leaves the other stale — the exact drift the shared helper exists to stop.
117
+ expect(src).not.toMatch(/invalidateQueries\(\{\s*queryKey:\s*\[\s*'shared',\s*'x?[bB]alances'/);
118
+ });
119
+
114
120
  if (!nativeThrow) {
115
121
  it('translates SDK Result via unwrapResult', () => {
116
122
  expect(src).toMatch(/unwrapResult\(/);
@@ -22,4 +22,8 @@ export { useBackendMoneyMarketAsset } from './useBackendMoneyMarketAsset.js';
22
22
  export { useBackendMoneyMarketAssetBorrowers } from './useBackendMoneyMarketAssetBorrowers.js';
23
23
  export { useBackendMoneyMarketAssetSuppliers } from './useBackendMoneyMarketAssetSuppliers.js';
24
24
  export { useBackendAllMoneyMarketBorrowers } from './useBackendAllMoneyMarketBorrowers.js';
25
+
26
+ // Oracle hooks
27
+ export { useBackendOracleMarkets } from './useBackendOracleMarkets.js';
28
+ export { useBackendOracleCandles } from './useBackendOracleCandles.js';
25
29
  export * from './types.js';
@@ -0,0 +1,47 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { OracleCandleInterval, OracleCandlesResponse } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { unwrapResult } from './unwrapResult.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseBackendOracleCandlesParams = ReadHookParams<
8
+ OracleCandlesResponse,
9
+ {
10
+ symbol: string;
11
+ interval: OracleCandleInterval;
12
+ /** Range start, UNIX seconds, inclusive. */
13
+ from: number;
14
+ /** Range end, UNIX seconds, exclusive; the range may cover at most 5000 buckets. */
15
+ to: number;
16
+ }
17
+ >;
18
+
19
+ /**
20
+ * Hook for fetching USD OHLC candles for a symbol over the half-open range `[from, to)`
21
+ * from the backend API. Responses are cached server-side for roughly 10 seconds.
22
+ *
23
+ * @example
24
+ * const { data } = useBackendOracleCandles({
25
+ * params: { symbol: 'ETH', interval: '1h', from: 1756000000, to: 1756360000 },
26
+ * });
27
+ */
28
+ export const useBackendOracleCandles = ({
29
+ params,
30
+ queryOptions,
31
+ }: UseBackendOracleCandlesParams = {}): UseQueryResult<OracleCandlesResponse, Error> => {
32
+ const { sodax } = useSodaxContext();
33
+
34
+ return useQuery<OracleCandlesResponse, Error>({
35
+ queryKey: ['backend', 'oracle', 'candles', params?.symbol, params?.interval, params?.from, params?.to],
36
+ queryFn: async (): Promise<OracleCandlesResponse> => {
37
+ if (!params) {
38
+ throw new Error('symbol, interval, from and to are required');
39
+ }
40
+ return unwrapResult(await sodax.backendApi.getOracleCandles(params));
41
+ },
42
+ enabled: !!params?.symbol && !!params?.interval && params?.from != null && params?.to != null,
43
+ staleTime: 10 * 1000,
44
+ retry: 3,
45
+ ...queryOptions,
46
+ });
47
+ };
@@ -0,0 +1,30 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { OracleMarketsResponse } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { unwrapResult } from './unwrapResult.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseBackendOracleMarketsParams = ReadHookParams<OracleMarketsResponse>;
8
+
9
+ /**
10
+ * Hook for fetching the oracle candle store's discovery payload (quote currency,
11
+ * selectable intervals, and covered symbols) from the backend API.
12
+ *
13
+ * @example
14
+ * const { data: markets } = useBackendOracleMarkets();
15
+ */
16
+ export const useBackendOracleMarkets = ({
17
+ queryOptions,
18
+ }: UseBackendOracleMarketsParams = {}): UseQueryResult<OracleMarketsResponse, Error> => {
19
+ const { sodax } = useSodaxContext();
20
+
21
+ return useQuery<OracleMarketsResponse, Error>({
22
+ queryKey: ['backend', 'oracle', 'markets'],
23
+ queryFn: async (): Promise<OracleMarketsResponse> => {
24
+ return unwrapResult(await sodax.backendApi.getOracleMarkets());
25
+ },
26
+ staleTime: 60 * 1000,
27
+ retry: 3,
28
+ ...queryOptions,
29
+ });
30
+ };
@@ -2,6 +2,7 @@
2
2
  import { useQueryClient } from '@tanstack/react-query';
3
3
  import { ChainKeys, type IBitcoinWalletProvider } from '@sodax/sdk';
4
4
  import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
5
6
  import type { MutationHookParams } from '../shared/types.js';
6
7
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
7
8
 
@@ -35,7 +36,7 @@ export function useFundTradingWallet({
35
36
  onSuccess: async (data, vars, ctx) => {
36
37
  queryClient.invalidateQueries({ queryKey: ['bitcoin', 'balance'] });
37
38
  queryClient.invalidateQueries({ queryKey: ['bitcoin', 'tradingWalletBalance'] });
38
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.BITCOIN_MAINNET] });
39
+ invalidateBalances(queryClient, ChainKeys.BITCOIN_MAINNET);
39
40
  await mutationOptions?.onSuccess?.(data, vars, ctx);
40
41
  },
41
42
  });
@@ -3,6 +3,7 @@ import { normalizePsbtToBase64, ChainKeys, type IBitcoinWalletProvider } from '@
3
3
  import { useQueryClient } from '@tanstack/react-query';
4
4
  import { loadRadfiSession } from './useRadfiAuth.js';
5
5
  import { useSodaxContext } from '../shared/useSodaxContext.js';
6
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
6
7
  import type { MutationHookParams } from '../shared/types.js';
7
8
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
8
9
 
@@ -60,7 +61,7 @@ export function useRadfiWithdraw({
60
61
  onSuccess: async (data, vars, ctx) => {
61
62
  queryClient.invalidateQueries({ queryKey: ['bitcoin', 'tradingWalletBalance'] });
62
63
  queryClient.invalidateQueries({ queryKey: ['bitcoin', 'balance'] });
63
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.BITCOIN_MAINNET] });
64
+ invalidateBalances(queryClient, ChainKeys.BITCOIN_MAINNET);
64
65
  await mutationOptions?.onSuccess?.(data, vars, ctx);
65
66
  },
66
67
  });