@sodax/dapp-kit 2.2.0-rc.1 → 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 (45) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +96 -3
  3. package/dist/index.mjs +98 -39
  4. package/package.json +3 -3
  5. package/src/hooks/_apiKeyWire.test.ts +1 -1
  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.ts +2 -2
  13. package/src/hooks/dex/useDexDeposit.ts +2 -1
  14. package/src/hooks/dex/useDexWithdraw.ts +2 -1
  15. package/src/hooks/dex/useSupplyLiquidity.ts +2 -1
  16. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +2 -2
  17. package/src/hooks/migrate/useMigrateBaln.ts +2 -2
  18. package/src/hooks/migrate/useMigrateIcxToSoda.ts +2 -2
  19. package/src/hooks/migrate/useMigratebnUSD.ts +2 -2
  20. package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +2 -2
  21. package/src/hooks/mm/useBorrow.ts +2 -4
  22. package/src/hooks/mm/useRepay.ts +2 -1
  23. package/src/hooks/mm/useSupply.ts +2 -1
  24. package/src/hooks/mm/useWithdraw.ts +2 -4
  25. package/src/hooks/partner/useFeeClaimWithdraw.ts +2 -1
  26. package/src/hooks/recovery/useWithdrawHubAsset.ts +2 -1
  27. package/src/hooks/shared/index.ts +2 -0
  28. package/src/hooks/shared/invalidateBalances.test.ts +71 -0
  29. package/src/hooks/shared/invalidateBalances.ts +25 -0
  30. package/src/hooks/shared/useBalances.test.ts +118 -0
  31. package/src/hooks/shared/useBalances.ts +81 -0
  32. package/src/hooks/shared/useEstablishTrustline.test.ts +2 -0
  33. package/src/hooks/shared/useEstablishTrustline.ts +2 -1
  34. package/src/hooks/shared/useStellarGate.test.ts +1 -1
  35. package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +6 -4
  36. package/src/hooks/sponsoring/useActivateStellarAccount.ts +2 -1
  37. package/src/hooks/sponsoring/useSponsorConfig.test.ts +8 -2
  38. package/src/hooks/sponsoring/useStellarAccountActive.test.ts +2 -2
  39. package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +8 -2
  40. package/src/hooks/staking/useClaim.ts +2 -1
  41. package/src/hooks/staking/useInstantUnstake.ts +2 -1
  42. package/src/hooks/staking/useStake.ts +2 -1
  43. package/src/hooks/swap/useDetailedStatus.test.ts +2 -2
  44. package/src/hooks/swap/useSwap.ts +2 -2
  45. package/src/providers/SodaxProvider.test.ts +1 -1
@@ -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
  });
@@ -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
  });
@@ -15,3 +15,5 @@ export * from './useNearStorageGate.js';
15
15
  export * from './useStellarGate.js';
16
16
  export * from './useGetUserHubWalletAddress.js';
17
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,118 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import type { Result, Sodax, XToken } from '@sodax/sdk';
3
+ import { getBalancesQueryOptions } from './useBalances.js';
4
+
5
+ const makeToken = (symbol: string, address: string): XToken =>
6
+ ({
7
+ symbol,
8
+ name: symbol,
9
+ decimals: 18,
10
+ address,
11
+ chainKey: 'sonic',
12
+ hubAsset: '0x0000000000000000000000000000000000000000',
13
+ vault: '0x0000000000000000000000000000000000000000',
14
+ }) as XToken;
15
+
16
+ const makeSodax = (result: Result<Record<string, bigint>>) =>
17
+ ({
18
+ spoke: {
19
+ getWalletBalances: vi.fn().mockResolvedValue(result),
20
+ },
21
+ }) as unknown as Sodax; // Minimal stub: only the `spoke.getWalletBalances` path the hook uses.
22
+
23
+ describe('getBalancesQueryOptions', () => {
24
+ const tokenA = makeToken('AAA', '0xaaa');
25
+ const tokenB = makeToken('BBB', '0xbbb');
26
+
27
+ it('builds a queryKey pairing each token symbol with its address', () => {
28
+ const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
29
+ chainKey: 'sonic',
30
+ tokens: [tokenA, tokenB],
31
+ address: '0xuser',
32
+ });
33
+
34
+ expect(opts.queryKey).toEqual([
35
+ 'shared',
36
+ 'balances',
37
+ 'sonic',
38
+ [
39
+ ['AAA', '0xaaa'],
40
+ ['BBB', '0xbbb'],
41
+ ],
42
+ '0xuser',
43
+ ]);
44
+ });
45
+
46
+ it('is disabled when chainKey is missing', () => {
47
+ const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
48
+ chainKey: undefined,
49
+ tokens: [tokenA],
50
+ address: '0xuser',
51
+ });
52
+ expect(opts.enabled).toBe(false);
53
+ });
54
+
55
+ it('is disabled when address is missing', () => {
56
+ const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
57
+ chainKey: 'sonic',
58
+ tokens: [tokenA],
59
+ address: undefined,
60
+ });
61
+ expect(opts.enabled).toBe(false);
62
+ });
63
+
64
+ it('is disabled when tokens is empty', () => {
65
+ const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
66
+ chainKey: 'sonic',
67
+ tokens: [],
68
+ address: '0xuser',
69
+ });
70
+ expect(opts.enabled).toBe(false);
71
+ });
72
+
73
+ it('is enabled when all inputs are present', () => {
74
+ const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
75
+ chainKey: 'sonic',
76
+ tokens: [tokenA],
77
+ address: '0xuser',
78
+ });
79
+ expect(opts.enabled).toBe(true);
80
+ });
81
+
82
+ it('queryFn delegates to sodax.spoke.getWalletBalances and unwraps the Result value', async () => {
83
+ const expected = { '0xaaa': 42n, '0xbbb': 0n };
84
+ const sodax = makeSodax({ ok: true, value: expected });
85
+
86
+ const opts = getBalancesQueryOptions(sodax, { chainKey: 'sonic', tokens: [tokenA, tokenB], address: '0xuser' });
87
+
88
+ const result = await opts.queryFn();
89
+ expect(result).toEqual(expected);
90
+ expect(sodax.spoke.getWalletBalances).toHaveBeenCalledWith({
91
+ srcChainKey: 'sonic',
92
+ srcAddress: '0xuser',
93
+ tokens: [tokenA, tokenB],
94
+ });
95
+ });
96
+
97
+ it('queryFn throws when the SDK returns an unsuccessful Result', async () => {
98
+ const boom = new Error('rpc down');
99
+ const opts = getBalancesQueryOptions(makeSodax({ ok: false, error: boom }), {
100
+ chainKey: 'sonic',
101
+ tokens: [tokenA],
102
+ address: '0xuser',
103
+ });
104
+
105
+ await expect(opts.queryFn()).rejects.toThrow('rpc down');
106
+ });
107
+
108
+ it('queryFn returns {} when chainKey/address are missing (defensive, enabled should prevent this)', async () => {
109
+ const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
110
+ chainKey: undefined,
111
+ tokens: [tokenA],
112
+ address: undefined,
113
+ });
114
+
115
+ const result = await opts.queryFn();
116
+ expect(result).toEqual({});
117
+ });
118
+ });
@@ -0,0 +1,81 @@
1
+ import { type UseQueryResult, useQuery } from '@tanstack/react-query';
2
+ import type { Sodax, SpokeChainKey, XToken } from '@sodax/sdk';
3
+ import { useSodaxContext } from './useSodaxContext.js';
4
+ import { unwrapResult } from './unwrapResult.js';
5
+ import type { ReadHookParams } from './types.js';
6
+
7
+ /**
8
+ * Domain inputs for {@link useBalances}. `chainKey` is optional so the hook can be mounted before a
9
+ * chain is selected; `enabled` gates execution on every required field being present.
10
+ *
11
+ * The SDK reads the chain named by `chainKey` and ignores `token.chainKey`, so a token that does
12
+ * not live on that chain reads as `0n` rather than erroring — keep the two in step.
13
+ */
14
+ export interface BalancesInputs {
15
+ chainKey: SpokeChainKey | undefined;
16
+ tokens: readonly XToken[];
17
+ address: string | undefined;
18
+ }
19
+
20
+ export type UseBalancesParams = ReadHookParams<Record<string, bigint>, BalancesInputs>;
21
+
22
+ const REFETCH_INTERVAL_MS = 5_000;
23
+
24
+ /**
25
+ * Pure builder for {@link useBalances} query options. Exported for unit tests and for advanced
26
+ * callers that compose their own `useQuery` wrapper. Takes the SDK instance explicitly (the hook
27
+ * supplies it from context).
28
+ */
29
+ export function getBalancesQueryOptions(sodax: Sodax, { chainKey, tokens, address }: BalancesInputs) {
30
+ return {
31
+ // Pair symbol + address: readable in devtools, unique on-chain (symbol alone can collide —
32
+ // e.g. scam tokens copying a legitimate ticker).
33
+ queryKey: ['shared', 'balances', chainKey, tokens.map(t => [t.symbol, t.address] as const), address] as const,
34
+ queryFn: async (): Promise<Record<string, bigint>> => {
35
+ if (!chainKey || !address) return {};
36
+ return unwrapResult(await sodax.spoke.getWalletBalances({ srcChainKey: chainKey, srcAddress: address, tokens }));
37
+ },
38
+ enabled: !!chainKey && !!address && tokens.length > 0,
39
+ refetchInterval: REFETCH_INTERVAL_MS,
40
+ // Deliberately NOT `placeholderData: keepPreviousData`: the query key carries the chain, so a
41
+ // chain switch would surface the previous chain's map — and every EVM chain shares the native
42
+ // token address, so its native balance would render as the new chain's until the fetch lands.
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Fetch a user's own wallet balances for multiple tokens on a specific chain, straight from the
48
+ * core SDK (`sodax.spoke.getWalletBalances`) — no wallet SDK / `xService` required. Returns an
49
+ * object mapping each token's address to its balance in smallest units.
50
+ *
51
+ * This is the SDK-backed successor to {@link useXBalances} (which wraps a wallet-layer `xService`).
52
+ * Prefer this when the app already has a `SodaxProvider`.
53
+ *
54
+ * Failure model: a token that could not be read is logged by the SDK and reported as `0n`, so a
55
+ * flaky RPC is indistinguishable from an empty wallet — always the conservative direction, since
56
+ * under-reporting blocks a spend rather than permitting one. The query only errors when the whole
57
+ * batch is unusable: a shared round-trip every token depends on, or a batch in which no token
58
+ * could be read at all.
59
+ *
60
+ * Chain-specific notes: Stellar XLM reports the *spendable* amount (total minus the minimum reserve
61
+ * and selling liabilities); Bitcoin returns `0n` for Rune tokens, whose amounts are not exposed by
62
+ * the UTXO endpoint.
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * const { data: balances } = useBalances({ params: { chainKey, address, tokens } });
67
+ * const usdcBalance = balances?.[usdc.address] ?? 0n;
68
+ * ```
69
+ */
70
+ export function useBalances({ params, queryOptions }: UseBalancesParams = {}): UseQueryResult<Record<string, bigint>> {
71
+ const { sodax } = useSodaxContext();
72
+
73
+ return useQuery({
74
+ ...getBalancesQueryOptions(sodax, {
75
+ chainKey: params?.chainKey,
76
+ tokens: params?.tokens ?? [],
77
+ address: params?.address,
78
+ }),
79
+ ...queryOptions,
80
+ });
81
+ }