@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,104 @@
1
+ /**
2
+ * `useBridge` wire test for the per-action API key: `extras.apiKey` in the mutation vars must reach
3
+ * the backend submit-tx leg as `x-api-key` — on the POST and on the status poll — beating the
4
+ * instance-level key.
5
+ *
6
+ * Follows the package convention of testing hooks without a renderer (captured `mutationFn`), with
7
+ * the SDK stubbed at the same seams its own backend submit-tx tests use: `createBridgeIntent` is
8
+ * spied on a real keyed `Sodax` so no wallet or chain is touched, while `POST /bridge/submit-tx`
9
+ * and `GET /bridge/submit-tx/status` run call-through to a stubbed global fetch serving the
10
+ * schema-valid fixtures from packages/sdk/src/bridge/BridgeService.test.ts.
11
+ */
12
+
13
+ import { ChainKeys, Sodax } from '@sodax/sdk';
14
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
15
+
16
+ // biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
17
+ let captured: any;
18
+
19
+ const sodax = new Sodax({ apiKey: 'instance-key', logger: 'silent' });
20
+
21
+ vi.mock('../shared/useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax }) }));
22
+ vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries: vi.fn() }) }));
23
+ vi.mock('../shared/useSafeMutation.js', () => ({
24
+ // biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
25
+ useSafeMutation: (options: any) => {
26
+ captured = options;
27
+ return {};
28
+ },
29
+ }));
30
+
31
+ const { useBridge } = await import('./useBridge.js');
32
+
33
+ const fetchMock = vi.fn();
34
+ vi.stubGlobal('fetch', fetchMock);
35
+
36
+ const jsonOk = (data: unknown): Response =>
37
+ new Response(JSON.stringify(data), { status: 200, headers: { 'content-type': 'application/json' } });
38
+
39
+ const BRIDGE_PARAMS = {
40
+ srcChainKey: ChainKeys.BSC_MAINNET,
41
+ dstChainKey: ChainKeys.ARBITRUM_MAINNET,
42
+ srcToken: '0x4444444444444444444444444444444444444444',
43
+ dstToken: '0x5555555555555555555555555555555555555555',
44
+ amount: 1_000_000n,
45
+ srcAddress: '0x1111111111111111111111111111111111111111',
46
+ recipient: '0x2222222222222222222222222222222222222222',
47
+ };
48
+
49
+ const SUBMIT_ACCEPTED = { success: true, data: { status: 'inserted', message: 'accepted' } };
50
+ const STATUS_EXECUTED = {
51
+ success: true,
52
+ data: {
53
+ txHash: '0xspokeTx',
54
+ srcChainKey: ChainKeys.BSC_MAINNET,
55
+ status: 'executed',
56
+ processingAttempts: 1,
57
+ result: { dstIntentTxHash: '0xDST' },
58
+ },
59
+ };
60
+
61
+ beforeEach(() => {
62
+ vi.restoreAllMocks();
63
+ fetchMock.mockReset();
64
+ });
65
+
66
+ describe('useBridge — extras.apiKey on the backend submit-tx wire', () => {
67
+ it('lands the per-action key on the submit-tx POST and the status poll, beating the instance key', async () => {
68
+ vi.spyOn(sodax.bridge, 'createBridgeIntent').mockResolvedValueOnce({
69
+ ok: true,
70
+ value: {
71
+ tx: '0xspokeTx',
72
+ relayData: { address: '0x1111111111111111111111111111111111111111', payload: '0xpay' },
73
+ },
74
+ } as never);
75
+ fetchMock.mockImplementation(async (url: string | URL, init?: RequestInit) => {
76
+ const { pathname } = new URL(String(url));
77
+ if (pathname === '/v1/bridge/submit-tx/status' && init?.method === 'GET') return jsonOk(STATUS_EXECUTED);
78
+ if (pathname === '/v1/bridge/submit-tx' && init?.method === 'POST') return jsonOk(SUBMIT_ACCEPTED);
79
+ throw new Error(`unexpected fetch: ${String(url)}`);
80
+ });
81
+
82
+ useBridge();
83
+ const result = await captured.mutationFn({
84
+ params: BRIDGE_PARAMS,
85
+ extras: { apiKey: 'action-key' },
86
+ walletProvider: {},
87
+ });
88
+
89
+ // Completed on the backend path: TxHashPair from the executed status, no relay fallback fetches.
90
+ expect(result).toEqual({ srcChainTxHash: '0xspokeTx', dstChainTxHash: '0xDST' });
91
+ expect(fetchMock).toHaveBeenCalledTimes(2);
92
+
93
+ const submit = fetchMock.mock.calls.find(
94
+ ([url, init]) => new URL(String(url)).pathname === '/v1/bridge/submit-tx' && init?.method === 'POST',
95
+ );
96
+ const poll = fetchMock.mock.calls.find(
97
+ ([url, init]) => new URL(String(url)).pathname === '/v1/bridge/submit-tx/status' && init?.method === 'GET',
98
+ );
99
+ expect(submit).toBeDefined();
100
+ expect(poll).toBeDefined();
101
+ expect(new Headers(submit?.[1]?.headers).get('x-api-key')).toBe('action-key');
102
+ expect(new Headers(poll?.[1]?.headers).get('x-api-key')).toBe('action-key');
103
+ });
104
+ });
@@ -1,5 +1,6 @@
1
1
  // packages/dapp-kit/src/hooks/bridge/useBridge.ts
2
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
3
4
  import type { BridgeParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';
4
5
  import { useQueryClient } from '@tanstack/react-query';
5
6
  import type { MutationHookParams } from '../shared/types.js';
@@ -30,8 +31,7 @@ export function useBridge<K extends SpokeChainKey = SpokeChainKey>({
30
31
  ...mutationOptions,
31
32
  mutationFn: async vars => unwrapResult(await sodax.bridge.bridge({ ...vars, raw: false })),
32
33
  onSuccess: async (data, vars, ctx) => {
33
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });
34
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.dstChainKey] });
34
+ invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
35
35
  await mutationOptions?.onSuccess?.(data, vars, ctx);
36
36
  },
37
37
  });
@@ -2,6 +2,7 @@
2
2
  import type { AssetDepositAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -50,7 +51,7 @@ export function useDexDeposit<K extends SpokeChainKey = SpokeChainKey>({
50
51
  queryClient.invalidateQueries({
51
52
  queryKey: ['dex', 'allowance', params.srcChainKey, params.asset, params.amount.toString()],
52
53
  });
53
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
54
+ invalidateBalances(queryClient, params.srcChainKey);
54
55
  await mutationOptions?.onSuccess?.(data, vars, ctx);
55
56
  },
56
57
  });
@@ -2,6 +2,7 @@
2
2
  import type { AssetWithdrawAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -36,7 +37,7 @@ export function useDexWithdraw<K extends SpokeChainKey = SpokeChainKey>({
36
37
  onSuccess: async (data, vars, ctx) => {
37
38
  const { params } = vars;
38
39
  queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });
39
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
40
+ invalidateBalances(queryClient, params.srcChainKey);
40
41
  await mutationOptions?.onSuccess?.(data, vars, ctx);
41
42
  },
42
43
  });
@@ -8,6 +8,7 @@ import type {
8
8
  } from '@sodax/sdk';
9
9
  import { useQueryClient } from '@tanstack/react-query';
10
10
  import { useSodaxContext } from '../shared/useSodaxContext.js';
11
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
11
12
  import type { UseCreateSupplyLiquidityParamsResult } from './useCreateSupplyLiquidityParams.js';
12
13
  import type { MutationHookParams } from '../shared/types.js';
13
14
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
@@ -89,7 +90,7 @@ export function useSupplyLiquidity<K extends SpokeChainKey = SpokeChainKey>({
89
90
  }
90
91
  queryClient.invalidateQueries({ queryKey: ['dex', 'poolData', params.poolKey] });
91
92
  queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });
92
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
93
+ invalidateBalances(queryClient, params.srcChainKey);
93
94
  await mutationOptions?.onSuccess?.(data, vars, ctx);
94
95
  },
95
96
  });
@@ -1,4 +1,5 @@
1
1
  import { useSodaxContext } from '../shared/useSodaxContext.js';
2
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
2
3
  import type { SpokeChainKey, VaultSwapActionParams, VaultSwapResponse } from '@sodax/sdk';
3
4
  import { useQueryClient } from '@tanstack/react-query';
4
5
  import type { MutationHookParams } from '../shared/types.js';
@@ -42,8 +43,7 @@ export function useLeverageYieldVaultSwap<K extends SpokeChainKey = SpokeChainKe
42
43
  ...mutationOptions,
43
44
  mutationFn: async vars => unwrapResult(await sodax.leverageYield.vaultSwap({ ...vars, raw: false })),
44
45
  onSuccess: async (data, vars, ctx) => {
45
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });
46
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.dstChainKey] });
46
+ invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
47
47
  await mutationOptions?.onSuccess?.(data, vars, ctx);
48
48
  },
49
49
  });
@@ -3,6 +3,7 @@ import type { BalnMigrateAction, TxHashPair } from '@sodax/sdk';
3
3
  import { ChainKeys } from '@sodax/sdk';
4
4
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -32,8 +33,7 @@ export function useMigrateBaln({
32
33
  mutationFn: async vars => unwrapResult(await sodax.migration.migrateBaln({ ...vars, raw: false })),
33
34
  onSuccess: async (data, vars, ctx) => {
34
35
  queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });
35
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.ICON_MAINNET] });
36
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.SONIC_MAINNET] });
36
+ invalidateBalances(queryClient, ChainKeys.ICON_MAINNET, ChainKeys.SONIC_MAINNET);
37
37
  // BALN with stake=true affects staking info too; cheap broad invalidation.
38
38
  queryClient.invalidateQueries({ queryKey: ['staking', 'info'] });
39
39
  await mutationOptions?.onSuccess?.(data, vars, ctx);
@@ -3,6 +3,7 @@ import type { IcxMigrateAction, TxHashPair } from '@sodax/sdk';
3
3
  import { ChainKeys } from '@sodax/sdk';
4
4
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -36,8 +37,7 @@ export function useMigrateIcxToSoda({
36
37
  mutationFn: async vars => unwrapResult(await sodax.migration.migrateIcxToSoda({ ...vars, raw: false })),
37
38
  onSuccess: async (data, vars, ctx) => {
38
39
  queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });
39
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });
40
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.SONIC_MAINNET] });
40
+ invalidateBalances(queryClient, vars.params.srcChainKey, ChainKeys.SONIC_MAINNET);
41
41
  await mutationOptions?.onSuccess?.(data, vars, ctx);
42
42
  },
43
43
  });
@@ -2,6 +2,7 @@
2
2
  import type { SpokeChainKey, TxHashPair, UnifiedBnUSDMigrateAction } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -39,8 +40,7 @@ export function useMigratebnUSD<K extends SpokeChainKey = SpokeChainKey>({
39
40
  onSuccess: async (data, vars, ctx) => {
40
41
  const { params } = vars;
41
42
  queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });
42
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
43
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.dstChainKey] });
43
+ invalidateBalances(queryClient, params.srcChainKey, params.dstChainKey);
44
44
  await mutationOptions?.onSuccess?.(data, vars, ctx);
45
45
  },
46
46
  });
@@ -3,6 +3,7 @@ import type { IcxRevertMigrationAction, TxHashPair } from '@sodax/sdk';
3
3
  import { ChainKeys } from '@sodax/sdk';
4
4
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -31,8 +32,7 @@ export function useRevertMigrateSodaToIcx({
31
32
  mutationFn: async vars => unwrapResult(await sodax.migration.revertMigrateSodaToIcx({ ...vars, raw: false })),
32
33
  onSuccess: async (data, vars, ctx) => {
33
34
  queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });
34
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });
35
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.ICON_MAINNET] });
35
+ invalidateBalances(queryClient, vars.params.srcChainKey, ChainKeys.ICON_MAINNET);
36
36
  await mutationOptions?.onSuccess?.(data, vars, ctx);
37
37
  },
38
38
  });
@@ -2,6 +2,7 @@
2
2
  import type { MoneyMarketBorrowActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -39,10 +40,7 @@ export function useBorrow<K extends SpokeChainKey = SpokeChainKey>({
39
40
  queryKey: ['mm', 'userFormattedSummary', params.srcChainKey, params.srcAddress],
40
41
  });
41
42
  queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });
42
- const balanceChains = new Set([params.srcChainKey, params.dstChainKey ?? params.srcChainKey]);
43
- for (const chainKey of balanceChains) {
44
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', chainKey] });
45
- }
43
+ invalidateBalances(queryClient, params.srcChainKey, params.dstChainKey);
46
44
  await mutationOptions?.onSuccess?.(data, vars, ctx);
47
45
  },
48
46
  });
@@ -2,6 +2,7 @@
2
2
  import type { MoneyMarketRepayActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -37,7 +38,7 @@ export function useRepay<K extends SpokeChainKey = SpokeChainKey>({
37
38
  });
38
39
  queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });
39
40
  queryClient.invalidateQueries({ queryKey: ['mm', 'allowance', params.srcChainKey, params.token, params.action] });
40
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
41
+ invalidateBalances(queryClient, params.srcChainKey);
41
42
  await mutationOptions?.onSuccess?.(data, vars, ctx);
42
43
  },
43
44
  });
@@ -2,6 +2,7 @@
2
2
  import type { MoneyMarketSupplyActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -52,7 +53,7 @@ export function useSupply<K extends SpokeChainKey = SpokeChainKey>({
52
53
  });
53
54
  queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });
54
55
  queryClient.invalidateQueries({ queryKey: ['mm', 'allowance', params.srcChainKey, params.token, params.action] });
55
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
56
+ invalidateBalances(queryClient, params.srcChainKey);
56
57
  await mutationOptions?.onSuccess?.(data, vars, ctx);
57
58
  },
58
59
  });
@@ -2,6 +2,7 @@
2
2
  import type { MoneyMarketWithdrawActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -43,10 +44,7 @@ export function useWithdraw<K extends SpokeChainKey = SpokeChainKey>({
43
44
  queryKey: ['mm', 'userFormattedSummary', params.srcChainKey, params.srcAddress],
44
45
  });
45
46
  queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });
46
- const balanceChains = new Set([params.srcChainKey, params.dstChainKey ?? params.srcChainKey]);
47
- for (const chainKey of balanceChains) {
48
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', chainKey] });
49
- }
47
+ invalidateBalances(queryClient, params.srcChainKey, params.dstChainKey);
50
48
  await mutationOptions?.onSuccess?.(data, vars, ctx);
51
49
  },
52
50
  });
@@ -10,6 +10,7 @@ import {
10
10
  } from '@sodax/sdk';
11
11
  import { useQueryClient } from '@tanstack/react-query';
12
12
  import { useSodaxContext } from '../shared/useSodaxContext.js';
13
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
13
14
  import type { MutationHookParams } from '../shared/types.js';
14
15
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
15
16
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -81,7 +82,7 @@ export function useFeeClaimWithdraw({
81
82
  queryClient.invalidateQueries({
82
83
  queryKey: ['partner', 'feeClaim', 'assetsBalances', vars.params.srcAddress],
83
84
  });
84
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.dstChainKey] });
85
+ invalidateBalances(queryClient, vars.params.dstChainKey);
85
86
  await mutationOptions?.onSuccess?.(data, vars, ctx);
86
87
  },
87
88
  });
@@ -2,6 +2,7 @@
2
2
  import type { SpokeChainKey, TxReturnType, WithdrawHubAssetAction } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
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
  import { unwrapResult } from '../shared/unwrapResult.js';
@@ -41,7 +42,7 @@ export function useWithdrawHubAsset<K extends SpokeChainKey = SpokeChainKey>({
41
42
  queryClient.invalidateQueries({
42
43
  queryKey: ['recovery', 'hubAssetBalances', params.srcChainKey, params.srcAddress],
43
44
  });
44
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
45
+ invalidateBalances(queryClient, params.srcChainKey);
45
46
  await mutationOptions?.onSuccess?.(data, vars, ctx);
46
47
  },
47
48
  });
@@ -1,4 +1,5 @@
1
1
  export * from './isUserRejectedError.js';
2
+ export * from './retryUnlessAuthFailure.js';
2
3
  export * from './types.js';
3
4
  export * from './unwrapResult.js';
4
5
  export * from './useSafeMutation.js';
@@ -14,3 +15,5 @@ export * from './useNearStorageGate.js';
14
15
  export * from './useStellarGate.js';
15
16
  export * from './useGetUserHubWalletAddress.js';
16
17
  export * from './useXBalances.js';
18
+ export * from './useBalances.js';
19
+ export * from './invalidateBalances.js';
@@ -0,0 +1,71 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { QueryClient } from '@tanstack/react-query';
3
+ import { ChainKeys } from '@sodax/sdk';
4
+ import { invalidateBalances } from './invalidateBalances.js';
5
+
6
+ const ARB = ChainKeys.ARBITRUM_MAINNET;
7
+ const SONIC = ChainKeys.SONIC_MAINNET;
8
+
9
+ describe('invalidateBalances', () => {
10
+ it('invalidates both balance query families for a chain', () => {
11
+ const queryClient = new QueryClient();
12
+ const spy = vi.spyOn(queryClient, 'invalidateQueries');
13
+
14
+ invalidateBalances(queryClient, ARB);
15
+
16
+ expect(spy).toHaveBeenCalledTimes(2);
17
+ expect(spy).toHaveBeenCalledWith({ queryKey: ['shared', 'balances', ARB] });
18
+ expect(spy).toHaveBeenCalledWith({ queryKey: ['shared', 'xBalances', ARB] });
19
+ });
20
+
21
+ it('collapses duplicate chain keys so src === dst does not double-invalidate', () => {
22
+ const queryClient = new QueryClient();
23
+ const spy = vi.spyOn(queryClient, 'invalidateQueries');
24
+
25
+ invalidateBalances(queryClient, ARB, ARB);
26
+
27
+ expect(spy).toHaveBeenCalledTimes(2);
28
+ });
29
+
30
+ it('skips undefined chain keys so callers need not guard an optional dst', () => {
31
+ const queryClient = new QueryClient();
32
+ const spy = vi.spyOn(queryClient, 'invalidateQueries');
33
+
34
+ invalidateBalances(queryClient, ARB, undefined);
35
+
36
+ expect(spy).toHaveBeenCalledTimes(2);
37
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: ['shared', 'balances', undefined] });
38
+ });
39
+
40
+ it('handles several chains in one call', () => {
41
+ const queryClient = new QueryClient();
42
+ const spy = vi.spyOn(queryClient, 'invalidateQueries');
43
+
44
+ invalidateBalances(queryClient, ARB, SONIC);
45
+
46
+ expect(spy).toHaveBeenCalledTimes(4);
47
+ });
48
+
49
+ it('marks a cached useBalances query stale through the 3-segment prefix', async () => {
50
+ const queryClient = new QueryClient();
51
+ // The full key useBalances builds — the prefix must still match it, so this fails if the
52
+ // helper ever switches to `exact: true`.
53
+ const fullKey = ['shared', 'balances', ARB, [['USDC', '0xaf88']], '0xuser'] as const;
54
+ queryClient.setQueryData(fullKey, { '0xaf88': 1n });
55
+ expect(queryClient.getQueryState(fullKey)?.isInvalidated).toBe(false);
56
+
57
+ invalidateBalances(queryClient, ARB);
58
+
59
+ expect(queryClient.getQueryState(fullKey)?.isInvalidated).toBe(true);
60
+ });
61
+
62
+ it('leaves other chains untouched', () => {
63
+ const queryClient = new QueryClient();
64
+ const otherChainKey = ['shared', 'balances', SONIC, [], '0xuser'] as const;
65
+ queryClient.setQueryData(otherChainKey, {});
66
+
67
+ invalidateBalances(queryClient, ARB);
68
+
69
+ expect(queryClient.getQueryState(otherChainKey)?.isInvalidated).toBe(false);
70
+ });
71
+ });
@@ -0,0 +1,25 @@
1
+ import type { QueryClient } from '@tanstack/react-query';
2
+ import type { SpokeChainKey } from '@sodax/sdk';
3
+
4
+ /**
5
+ * Invalidate every wallet-balance query for the given chains.
6
+ *
7
+ * Two balance hooks ship side by side — {@link useBalances} (SDK-backed, keyed under
8
+ * `['shared','balances', …]`) and {@link useXBalances} (wallet-layer, `['shared','xBalances', …]`) —
9
+ * and an app may mount either. React Query matches query keys element-wise, so one key never
10
+ * matches the other; a mutation hook that invalidates only one silently leaves the other stale.
11
+ * Route every post-transaction balance refresh through here so the two cannot drift apart again.
12
+ *
13
+ * `undefined` chain keys are skipped and duplicates collapse, so callers can pass
14
+ * `(src, dst)` without guarding either.
15
+ */
16
+ export function invalidateBalances(
17
+ queryClient: QueryClient,
18
+ ...chainKeys: readonly (SpokeChainKey | undefined)[]
19
+ ): void {
20
+ for (const chainKey of new Set(chainKeys)) {
21
+ if (!chainKey) continue;
22
+ queryClient.invalidateQueries({ queryKey: ['shared', 'balances', chainKey] });
23
+ queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', chainKey] });
24
+ }
25
+ }
@@ -0,0 +1,38 @@
1
+ import { SodaxError } from '@sodax/sdk';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { retryUnlessAuthFailure } from './retryUnlessAuthFailure.js';
4
+
5
+ /** A backend failure as the swaps API surfaces it: `EXTERNAL_API_ERROR` with the status on context. */
6
+ const apiError = (status?: number): SodaxError =>
7
+ new SodaxError('EXTERNAL_API_ERROR', `responded with ${status}`, {
8
+ feature: 'backend',
9
+ context: { api: 'swaps', endpoint: '/swaps/quote', status },
10
+ });
11
+
12
+ describe('retryUnlessAuthFailure', () => {
13
+ it('never retries a terminal API-key rejection, even on the first attempt', () => {
14
+ // The count check must not rescue a terminal error — order of the two conditions matters.
15
+ for (const status of [401, 403]) {
16
+ expect(retryUnlessAuthFailure(0, apiError(status))).toBe(false);
17
+ }
18
+ });
19
+
20
+ it("retries the apiguard's transient 503 and other server failures", () => {
21
+ // 503 is the one guard outcome that is NOT terminal — the key may be fine, verification is down.
22
+ for (const status of [408, 429, 500, 502, 503, 504]) {
23
+ expect(retryUnlessAuthFailure(0, apiError(status))).toBe(true);
24
+ }
25
+ });
26
+
27
+ it('retries failures that carry no HTTP status (network, timeout, non-SDK throws)', () => {
28
+ expect(retryUnlessAuthFailure(0, apiError(undefined))).toBe(true);
29
+ expect(retryUnlessAuthFailure(0, new Error('ECONNRESET'))).toBe(true);
30
+ expect(retryUnlessAuthFailure(0, undefined)).toBe(true);
31
+ });
32
+
33
+ it('stops after 3 retries of a repeatable failure', () => {
34
+ const err = apiError(500);
35
+ expect(retryUnlessAuthFailure(2, err)).toBe(true);
36
+ expect(retryUnlessAuthFailure(3, err)).toBe(false);
37
+ });
38
+ });
@@ -0,0 +1,18 @@
1
+ import { isAuthFailure } from '@sodax/sdk';
2
+
3
+ /** Retries a repeatable failure gets, matching the `retry: 3` these hooks used before. */
4
+ const MAX_RETRIES = 3;
5
+
6
+ /**
7
+ * Default React Query `retry` policy for the backend swaps-API hooks: replay a transport blip, never a
8
+ * terminal API-key rejection (see `isAuthFailure`). Retrying a rejected key only multiplies doomed
9
+ * requests before the consumer sees the error.
10
+ *
11
+ * Override or compose it through `queryOptions` / `mutationOptions`:
12
+ *
13
+ * ```ts
14
+ * useSwapsApiQuote({ params: { body }, queryOptions: { retry: 5 } });
15
+ * ```
16
+ */
17
+ export const retryUnlessAuthFailure = (failureCount: number, error: unknown): boolean =>
18
+ !isAuthFailure(error) && failureCount < MAX_RETRIES;