@sodax/dapp-kit 2.2.0-rc.1 → 2.2.0-rc.3

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 (84) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +599 -3
  3. package/dist/index.mjs +705 -41
  4. package/package.json +3 -3
  5. package/src/hooks/_apiKeyWire.test.ts +384 -18
  6. package/src/hooks/_mutationContract.test.ts +13 -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/index.ts +1 -0
  17. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +2 -2
  18. package/src/hooks/leverageYieldApi/index.ts +55 -0
  19. package/src/hooks/leverageYieldApi/useLeverageYieldApiAllowance.ts +50 -0
  20. package/src/hooks/leverageYieldApi/useLeverageYieldApiApprove.ts +37 -0
  21. package/src/hooks/leverageYieldApi/useLeverageYieldApiApproveAndBroadcast.test.ts +176 -0
  22. package/src/hooks/leverageYieldApi/useLeverageYieldApiApproveAndBroadcast.ts +83 -0
  23. package/src/hooks/leverageYieldApi/useLeverageYieldApiApr.ts +41 -0
  24. package/src/hooks/leverageYieldApi/useLeverageYieldApiAsset.ts +41 -0
  25. package/src/hooks/leverageYieldApi/useLeverageYieldApiCancelIntent.ts +37 -0
  26. package/src/hooks/leverageYieldApi/useLeverageYieldApiCreateDepositIntent.ts +37 -0
  27. package/src/hooks/leverageYieldApi/useLeverageYieldApiCreateWithdrawIntent.ts +37 -0
  28. package/src/hooks/leverageYieldApi/useLeverageYieldApiDeadline.ts +38 -0
  29. package/src/hooks/leverageYieldApi/useLeverageYieldApiDepositQuote.ts +57 -0
  30. package/src/hooks/leverageYieldApi/useLeverageYieldApiEffectiveApr.ts +41 -0
  31. package/src/hooks/leverageYieldApi/useLeverageYieldApiEstimateGas.ts +41 -0
  32. package/src/hooks/leverageYieldApi/useLeverageYieldApiFilledIntent.ts +40 -0
  33. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntent.ts +40 -0
  34. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntentExtraData.ts +42 -0
  35. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntentHash.ts +41 -0
  36. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntentPacket.ts +41 -0
  37. package/src/hooks/leverageYieldApi/useLeverageYieldApiLsdApr.ts +41 -0
  38. package/src/hooks/leverageYieldApi/useLeverageYieldApiMaxWithdraw.ts +43 -0
  39. package/src/hooks/leverageYieldApi/useLeverageYieldApiPartnerFee.ts +41 -0
  40. package/src/hooks/leverageYieldApi/useLeverageYieldApiPosition.ts +41 -0
  41. package/src/hooks/leverageYieldApi/useLeverageYieldApiPreviewDeposit.ts +43 -0
  42. package/src/hooks/leverageYieldApi/useLeverageYieldApiPreviewRedeem.ts +43 -0
  43. package/src/hooks/leverageYieldApi/useLeverageYieldApiPreviewWithdraw.ts +43 -0
  44. package/src/hooks/leverageYieldApi/useLeverageYieldApiShareBalance.ts +43 -0
  45. package/src/hooks/leverageYieldApi/useLeverageYieldApiSolverFee.ts +41 -0
  46. package/src/hooks/leverageYieldApi/useLeverageYieldApiStatus.ts +48 -0
  47. package/src/hooks/leverageYieldApi/useLeverageYieldApiSubmitIntent.ts +36 -0
  48. package/src/hooks/leverageYieldApi/useLeverageYieldApiSubmitTx.ts +37 -0
  49. package/src/hooks/leverageYieldApi/useLeverageYieldApiSubmitTxStatus.ts +60 -0
  50. package/src/hooks/leverageYieldApi/useLeverageYieldApiTotalAssets.ts +41 -0
  51. package/src/hooks/leverageYieldApi/useLeverageYieldApiVault.ts +41 -0
  52. package/src/hooks/leverageYieldApi/useLeverageYieldApiVaults.ts +36 -0
  53. package/src/hooks/leverageYieldApi/useLeverageYieldApiWithdrawQuote.ts +56 -0
  54. package/src/hooks/migrate/useMigrateBaln.ts +2 -2
  55. package/src/hooks/migrate/useMigrateIcxToSoda.ts +2 -2
  56. package/src/hooks/migrate/useMigratebnUSD.ts +2 -2
  57. package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +2 -2
  58. package/src/hooks/mm/useBorrow.ts +2 -4
  59. package/src/hooks/mm/useRepay.ts +2 -1
  60. package/src/hooks/mm/useSupply.ts +2 -1
  61. package/src/hooks/mm/useWithdraw.ts +2 -4
  62. package/src/hooks/partner/useFeeClaimWithdraw.ts +2 -1
  63. package/src/hooks/recovery/useWithdrawHubAsset.ts +2 -1
  64. package/src/hooks/shared/index.ts +2 -0
  65. package/src/hooks/shared/invalidateBalances.test.ts +71 -0
  66. package/src/hooks/shared/invalidateBalances.ts +25 -0
  67. package/src/hooks/shared/useBalances.test.ts +118 -0
  68. package/src/hooks/shared/useBalances.ts +81 -0
  69. package/src/hooks/shared/useEstablishTrustline.test.ts +2 -0
  70. package/src/hooks/shared/useEstablishTrustline.ts +2 -1
  71. package/src/hooks/shared/useStellarGate.test.ts +1 -1
  72. package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +6 -4
  73. package/src/hooks/sponsoring/useActivateStellarAccount.ts +2 -1
  74. package/src/hooks/sponsoring/useSponsorConfig.test.ts +8 -2
  75. package/src/hooks/sponsoring/useStellarAccountActive.test.ts +2 -2
  76. package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +8 -2
  77. package/src/hooks/staking/useClaim.ts +2 -1
  78. package/src/hooks/staking/useInstantUnstake.ts +2 -1
  79. package/src/hooks/staking/useStake.ts +2 -1
  80. package/src/hooks/swap/useDetailedStatus.test.ts +2 -2
  81. package/src/hooks/swap/useSwap.ts +2 -2
  82. package/src/hooks/swapsApi/useSwapsApiApproveAndBroadcast.test.ts +5 -1
  83. package/src/providers/SodaxProvider.test.ts +1 -1
  84. package/src/utils/approvalPlan.ts +4 -1
@@ -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
+ }
@@ -47,6 +47,7 @@ describe('useEstablishTrustline — invalidation after a broadcast trustline', (
47
47
  expect(invalidatedKeys()).toEqual([
48
48
  ['shared', 'stellarTrustlineCheck', ChainKeys.STELLAR_MAINNET, TOKEN, ADDRESS],
49
49
  ['sponsoring', 'stellarAccountStatus', ADDRESS],
50
+ ['shared', 'balances', ChainKeys.STELLAR_MAINNET],
50
51
  ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
51
52
  ]);
52
53
  });
@@ -64,6 +65,7 @@ describe('useEstablishTrustline — invalidation after a broadcast trustline', (
64
65
  expect(invalidatedKeys()).toEqual([
65
66
  ['shared', 'stellarTrustlineCheck'],
66
67
  ['sponsoring', 'stellarAccountStatus'],
68
+ ['shared', 'balances', ChainKeys.STELLAR_MAINNET],
67
69
  ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
68
70
  ]);
69
71
  });
@@ -1,6 +1,7 @@
1
1
  import type { IStellarWalletProvider, StellarChainKey } from '@sodax/sdk';
2
2
  import { ChainKeys } from '@sodax/sdk';
3
3
  import { useQueryClient } from '@tanstack/react-query';
4
+ import { invalidateBalances } from './invalidateBalances.js';
4
5
  import type { MutationHookParams } from './types.js';
5
6
  import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
6
7
  import { useSodaxContext } from './useSodaxContext.js';
@@ -65,7 +66,7 @@ export function useEstablishTrustline({
65
66
  ? ['sponsoring', 'stellarAccountStatus', srcAddress]
66
67
  : ['sponsoring', 'stellarAccountStatus'],
67
68
  });
68
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET] });
69
+ invalidateBalances(queryClient, ChainKeys.STELLAR_MAINNET);
69
70
  await mutationOptions?.onSuccess?.(data, vars, ctx);
70
71
  },
71
72
  });
@@ -89,7 +89,7 @@ describe('useStellarGate — the trustline read is gated on account existence',
89
89
  it('does not read a Stellar trustline for a non-Stellar destination', () => {
90
90
  const { gate, trustlineAddress } = run(
91
91
  { data: { exists: true, canAffordTrustline: true } },
92
- { dstChainKey: ChainKeys.SONIC },
92
+ { dstChainKey: ChainKeys.SONIC_MAINNET },
93
93
  );
94
94
 
95
95
  expect(trustlineAddress).toBeUndefined();
@@ -23,8 +23,8 @@ function invalidatedKeyPrefixes(): string[][] {
23
23
  }
24
24
 
25
25
  describe('useActivateStellarAccount — cache invalidation', () => {
26
- it('invalidates exactly four queries on success', () => {
27
- expect(invalidatedKeyPrefixes()).toHaveLength(4);
26
+ it('hand-rolls exactly three query invalidations on success, the fourth routed through invalidateBalances', () => {
27
+ expect(invalidatedKeyPrefixes()).toHaveLength(3);
28
28
  });
29
29
 
30
30
  it("invalidates the account-active query using that query's own key prefix", () => {
@@ -63,8 +63,10 @@ describe('useActivateStellarAccount — cache invalidation', () => {
63
63
  expect(invalidatedKeyPrefixes()).toContainEqual(['shared', 'stellarTrustlineCheck']);
64
64
  });
65
65
 
66
- it('invalidates the Stellar balance query', () => {
67
- expect(invalidatedKeyPrefixes()).toContainEqual(['shared', 'xBalances']);
66
+ it('invalidates Stellar balances through the shared invalidateBalances helper', () => {
67
+ // Routed through invalidateBalances (covers both useBalances and useXBalances) rather than a
68
+ // hand-rolled invalidateQueries call, so it is not one of the literal matches above.
69
+ expect(SRC).toMatch(/invalidateBalances\(queryClient,\s*ChainKeys\.STELLAR_MAINNET\)/);
68
70
  });
69
71
 
70
72
  it('passes the whole mutation vars through to the SDK', () => {
@@ -1,6 +1,7 @@
1
1
  import { ChainKeys, type ActivateStellarAccountParams, type ActivateStellarAccountResult } from '@sodax/sdk';
2
2
  import { useQueryClient } from '@tanstack/react-query';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
4
5
  import type { MutationHookParams } from '../shared/types.js';
5
6
  import { unwrapResult } from '../shared/unwrapResult.js';
6
7
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
@@ -31,7 +32,7 @@ export function useActivateStellarAccount({
31
32
  queryClient.invalidateQueries({ queryKey: ['sponsoring', 'stellarAccountStatus', vars.address] });
32
33
  // Clear trustline errors cached while the account did not exist.
33
34
  queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck'] });
34
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET] });
35
+ invalidateBalances(queryClient, ChainKeys.STELLAR_MAINNET);
35
36
  await mutationOptions?.onSuccess?.(data, vars, ctx);
36
37
  },
37
38
  });
@@ -1,4 +1,10 @@
1
- import { SodaxError, SPONSOR_CONFIG_TTL_MS, type StellarSponsorConfig } from '@sodax/sdk';
1
+ import {
2
+ SodaxError,
3
+ SPONSOR_CONFIG_TTL_MS,
4
+ type Result,
5
+ type SponsoringConfigError,
6
+ type StellarSponsorConfig,
7
+ } from '@sodax/sdk';
2
8
  import { describe, expect, it, vi } from 'vitest';
3
9
  import { getSponsorConfigQueryOptions } from './useSponsorConfig.js';
4
10
 
@@ -15,7 +21,7 @@ const CONFIG: StellarSponsorConfig = {
15
21
  requiredStartingBalance: '0',
16
22
  };
17
23
 
18
- const makeSodax = (result: { ok: true; value: StellarSponsorConfig } | { ok: false; error: SodaxError }) => {
24
+ const makeSodax = (result: Result<StellarSponsorConfig, SponsoringConfigError>) => {
19
25
  const getStellarSponsorConfig = vi.fn(async () => result);
20
26
  return { sodax: { sponsoring: { getStellarSponsorConfig } }, getStellarSponsorConfig };
21
27
  };
@@ -1,11 +1,11 @@
1
- import { SodaxError } from '@sodax/sdk';
1
+ import { SodaxError, type Result, type SponsoringLookupError } from '@sodax/sdk';
2
2
  import { describe, expect, it, vi } from 'vitest';
3
3
  import { getStellarAccountActiveQueryOptions } from './useStellarAccountActive.js';
4
4
 
5
5
  const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
6
6
  const OTHER = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
7
7
 
8
- const makeSodax = (result: { ok: true; value: boolean } | { ok: false; error: SodaxError }) => {
8
+ const makeSodax = (result: Result<boolean, SponsoringLookupError>) => {
9
9
  const isStellarAccountActive = vi.fn(async () => result);
10
10
  return { sodax: { sponsoring: { isStellarAccountActive } }, isStellarAccountActive };
11
11
  };
@@ -1,4 +1,10 @@
1
- import { SodaxError, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, type StellarAccountStatus } from '@sodax/sdk';
1
+ import {
2
+ SodaxError,
3
+ STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
4
+ type Result,
5
+ type SponsoringLookupError,
6
+ type StellarAccountStatus,
7
+ } from '@sodax/sdk';
2
8
  import { describe, expect, it, vi } from 'vitest';
3
9
  import { getStellarAccountStatusQueryOptions } from './useStellarAccountStatus.js';
4
10
 
@@ -13,7 +19,7 @@ const FUNDED: StellarAccountStatus = {
13
19
  trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
14
20
  };
15
21
 
16
- const makeSodax = (result: { ok: true; value: StellarAccountStatus } | { ok: false; error: SodaxError }) => {
22
+ const makeSodax = (result: Result<StellarAccountStatus, SponsoringLookupError>) => {
17
23
  const getStellarAccountStatus = vi.fn(async () => result);
18
24
  return { sodax: { sponsoring: { getStellarAccountStatus } }, getStellarAccountStatus };
19
25
  };
@@ -2,6 +2,7 @@
2
2
  import type { ClaimAction, 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';
@@ -30,7 +31,7 @@ export function useClaim<K extends SpokeChainKey = SpokeChainKey>({
30
31
  queryClient.invalidateQueries({
31
32
  queryKey: ['staking', 'unstakingInfoWithPenalty', params.srcChainKey, params.srcAddress],
32
33
  });
33
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
34
+ invalidateBalances(queryClient, params.srcChainKey);
34
35
  await mutationOptions?.onSuccess?.(data, vars, ctx);
35
36
  },
36
37
  });
@@ -2,6 +2,7 @@
2
2
  import type { InstantUnstakeAction, 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 useInstantUnstake<K extends SpokeChainKey = SpokeChainKey>({
36
37
  queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });
37
38
  queryClient.invalidateQueries({ queryKey: ['staking', 'instantUnstakeRatio'] });
38
39
  queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'instantUnstake'] });
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
  });
@@ -2,6 +2,7 @@
2
2
  import type { SpokeChainKey, StakeAction, 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';
@@ -35,7 +36,7 @@ export function useStake<K extends SpokeChainKey = SpokeChainKey>({
35
36
  queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'stake'] });
36
37
  queryClient.invalidateQueries({ queryKey: ['staking', 'stakeRatio'] });
37
38
  queryClient.invalidateQueries({ queryKey: ['staking', 'convertedAssets'] });
38
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
39
+ invalidateBalances(queryClient, params.srcChainKey);
39
40
  await mutationOptions?.onSuccess?.(data, vars, ctx);
40
41
  },
41
42
  });
@@ -63,7 +63,7 @@ describe('getDetailedStatusRefetchInterval', () => {
63
63
  // Both terminal states of the `SubmitSwapTxStatusV2` wire contract. `'failed'` is unreachable via
64
64
  // `getDetailedStatus` today (the SDK routes abandoned records to the solver) — asserted here as
65
65
  // the hook's own contract, so a terminal record is never polled forever if that routing changes.
66
- it.each(['solved', 'failed'])('stops on a backend record at the terminal status %s', status => {
66
+ it.each(['solved', 'failed'] as const)('stops on a backend record at the terminal status %s', status => {
67
67
  expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(false);
68
68
  });
69
69
 
@@ -73,7 +73,7 @@ describe('getDetailedStatusRefetchInterval', () => {
73
73
  'relayed',
74
74
  'posting_execution',
75
75
  'posted_execution',
76
- ])('keeps polling a backend record at %s', status => {
76
+ ] as const)('keeps polling a backend record at %s', status => {
77
77
  expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(STATUS_POLL_MS);
78
78
  });
79
79
 
@@ -1,5 +1,6 @@
1
1
  // packages/dapp-kit/src/hooks/swap/useSwap.ts
2
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
3
4
  import type { SpokeChainKey, SwapActionParams, SwapResponse } 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 useSwap<K extends SpokeChainKey = SpokeChainKey>({
30
31
  ...mutationOptions,
31
32
  mutationFn: async vars => unwrapResult(await sodax.swaps.swap({ ...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
  });
@@ -8,7 +8,7 @@
8
8
  * mocked so `mutationFn` can be captured and driven directly.
9
9
  */
10
10
 
11
- import { ChainKeys } from '@sodax/sdk';
11
+ import { ChainKeys, getEvmViemChain } from '@sodax/sdk';
12
12
  import type { ApprovalProgress } from '../../utils/approvalPlan.js';
13
13
  import { beforeEach, describe, expect, it, vi } from 'vitest';
14
14
 
@@ -129,6 +129,10 @@ describe('useSwapsApiApproveAndBroadcast', () => {
129
129
 
130
130
  expect(result).toEqual({ approveTxHash: APPROVE_HASH });
131
131
  expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
132
+ // Backend-built approvals are chain-bound: the runner must pass the source chain's id.
133
+ expect(walletProvider.sendTransaction).toHaveBeenCalledWith(expect.anything(), {
134
+ expectedChainId: getEvmViemChain(ChainKeys.ARBITRUM_MAINNET).id,
135
+ });
132
136
  });
133
137
 
134
138
  it('works on the hub chain, not just EVM spokes', async () => {
@@ -19,7 +19,7 @@ vi.mock('react', async importOriginal => ({
19
19
 
20
20
  const { SodaxProvider } = await import('./SodaxProvider.js');
21
21
 
22
- const fetchMock = vi.fn(
22
+ const fetchMock = vi.fn<typeof globalThis.fetch>(
23
23
  async () => new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }),
24
24
  );
25
25
  vi.stubGlobal('fetch', fetchMock);
@@ -9,6 +9,7 @@ import type {
9
9
  StellarRawTransaction,
10
10
  } from '@sodax/sdk';
11
11
  import {
12
+ getEvmViemChain,
12
13
  isApprovalSupportedChainKeyType,
13
14
  isEvmSpokeOnlyChainKeyType,
14
15
  isHubChainKeyType,
@@ -91,7 +92,9 @@ function resolveChainSender(
91
92
  const evm = walletProvider as IEvmWalletProvider;
92
93
 
93
94
  return {
94
- send: raw => evm.sendTransaction(raw as EvmRawTransaction),
95
+ // Chain-bind the send: the wallet broadcasts on ITS active chain, so refuse when that differs
96
+ // from the srcChainKey the user asked for. (Verifying the tx CONTENT is a separate concern.)
97
+ send: raw => evm.sendTransaction(raw as EvmRawTransaction, { expectedChainId: getEvmViemChain(srcChainKey).id }),
95
98
  confirm: async (hash, step) => {
96
99
  const receipt = await evm.waitForTransactionReceipt(hash as Hex);
97
100
  // Mined is not succeeded: a revert here would let the approve go out over an unmoved allowance.