@sodax/dapp-kit 2.0.0-rc.9 → 2.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +141 -119
  2. package/dist/index.d.ts +939 -63
  3. package/dist/index.mjs +1086 -180
  4. package/package.json +3 -3
  5. package/src/hooks/_mutationContract.test.ts +17 -2
  6. package/src/hooks/backend/index.ts +1 -5
  7. package/src/hooks/backend/types.ts +1 -1
  8. package/src/hooks/bitcoin/index.ts +2 -0
  9. package/src/hooks/bitcoin/resolveBtcReadAddress.test.ts +54 -0
  10. package/src/hooks/bitcoin/resolveBtcReadAddress.ts +21 -0
  11. package/src/hooks/bitcoin/useBitcoinTradingSetup.ts +45 -0
  12. package/src/hooks/bitcoin/useEnsureRadfiAccessToken.ts +57 -0
  13. package/src/hooks/bitcoin/useFundTradingWallet.ts +1 -1
  14. package/src/hooks/bitcoin/useRadfiAuth.ts +2 -2
  15. package/src/hooks/bitcoin/useRadfiWithdraw.ts +2 -2
  16. package/src/hooks/bitcoin/useRenewUtxos.ts +2 -2
  17. package/src/hooks/bitcoin/useTradingWallet.ts +1 -1
  18. package/src/hooks/bridge/useBridgeApprove.ts +2 -1
  19. package/src/hooks/index.ts +3 -0
  20. package/src/hooks/leverageYield/index.ts +9 -0
  21. package/src/hooks/leverageYield/useLeverageYieldDeposit.ts +40 -0
  22. package/src/hooks/leverageYield/useLeverageYieldEffectiveApr.ts +42 -0
  23. package/src/hooks/leverageYield/useLeverageYieldNotifySolver.ts +34 -0
  24. package/src/hooks/leverageYield/useLeverageYieldPosition.ts +40 -0
  25. package/src/hooks/leverageYield/useLeverageYieldPreviewRedeem.ts +43 -0
  26. package/src/hooks/leverageYield/useLeverageYieldShareBalances.ts +74 -0
  27. package/src/hooks/leverageYield/useLeverageYieldTotalAssets.ts +36 -0
  28. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +50 -0
  29. package/src/hooks/leverageYield/useLeverageYieldWithdraw.ts +40 -0
  30. package/src/hooks/migrate/useMigrationApprove.ts +1 -3
  31. package/src/hooks/mm/useATokensBalances.ts +7 -1
  32. package/src/hooks/mm/useUserFormattedSummary.ts +5 -1
  33. package/src/hooks/mm/useUserReservesData.ts +5 -1
  34. package/src/hooks/mm/useWithdraw.ts +5 -1
  35. package/src/hooks/partner/index.ts +4 -0
  36. package/src/hooks/partner/useApproveToken.ts +1 -2
  37. package/src/hooks/partner/useFeeClaimWithdraw.ts +88 -0
  38. package/src/hooks/partner/useGetIntentDetails.ts +39 -0
  39. package/src/hooks/partner/useGetUserIntent.ts +35 -0
  40. package/src/hooks/partner/usePartnerCancelIntent.ts +52 -0
  41. package/src/hooks/shared/index.ts +6 -0
  42. package/src/hooks/shared/isUserRejectedError.test.ts +42 -0
  43. package/src/hooks/shared/isUserRejectedError.ts +30 -0
  44. package/src/hooks/shared/useEstablishTrustline.test.ts +89 -0
  45. package/src/hooks/shared/useEstablishTrustline.ts +72 -0
  46. package/src/hooks/shared/useGetUserHubWalletAddress.ts +5 -1
  47. package/src/hooks/shared/useNearStorageCheck.ts +45 -0
  48. package/src/hooks/shared/useNearStorageGate.ts +60 -0
  49. package/src/hooks/shared/useRegisterNearStorage.ts +46 -0
  50. package/src/hooks/shared/useRequestTrustline.test.ts +115 -0
  51. package/src/hooks/shared/useRequestTrustline.ts +41 -56
  52. package/src/hooks/shared/useSafeMutation.ts +1 -4
  53. package/src/hooks/shared/useStellarGate.test.ts +99 -0
  54. package/src/hooks/shared/useStellarGate.ts +102 -0
  55. package/src/hooks/shared/useStellarTrustlineCheck.test.ts +74 -0
  56. package/src/hooks/shared/useStellarTrustlineCheck.ts +39 -15
  57. package/src/hooks/sponsoring/index.ts +4 -0
  58. package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +74 -0
  59. package/src/hooks/sponsoring/useActivateStellarAccount.ts +38 -0
  60. package/src/hooks/sponsoring/useSponsorConfig.test.ts +46 -0
  61. package/src/hooks/sponsoring/useSponsorConfig.ts +31 -0
  62. package/src/hooks/sponsoring/useStellarAccountActive.test.ts +50 -0
  63. package/src/hooks/sponsoring/useStellarAccountActive.ts +45 -0
  64. package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +90 -0
  65. package/src/hooks/sponsoring/useStellarAccountStatus.ts +57 -0
  66. package/src/hooks/staking/useStakingConfig.ts +1 -3
  67. package/src/hooks/staking/useStakingInfo.ts +4 -4
  68. package/src/hooks/staking/useUnstake.ts +5 -1
  69. package/src/hooks/swap/useCreateLimitOrder.ts +1 -2
  70. package/src/hooks/swap/useSwap.ts +1 -5
  71. package/src/hooks/swapsApi/index.ts +41 -0
  72. package/src/hooks/swapsApi/isTerminalSwapIntentStatus.test.ts +24 -0
  73. package/src/hooks/swapsApi/isTerminalSwapIntentStatus.ts +11 -0
  74. package/src/hooks/swapsApi/useSwapsApiAllowance.ts +40 -0
  75. package/src/hooks/swapsApi/useSwapsApiApprove.ts +42 -0
  76. package/src/hooks/swapsApi/useSwapsApiCancelIntent.ts +41 -0
  77. package/src/hooks/swapsApi/useSwapsApiCreateIntent.ts +41 -0
  78. package/src/hooks/swapsApi/useSwapsApiCreateLimitOrder.ts +41 -0
  79. package/src/hooks/swapsApi/useSwapsApiDeadline.ts +36 -0
  80. package/src/hooks/swapsApi/useSwapsApiEstimateGas.ts +40 -0
  81. package/src/hooks/swapsApi/useSwapsApiFilledIntent.ts +41 -0
  82. package/src/hooks/swapsApi/useSwapsApiIntent.ts +40 -0
  83. package/src/hooks/swapsApi/useSwapsApiIntentExtraData.ts +41 -0
  84. package/src/hooks/swapsApi/useSwapsApiIntentHash.ts +40 -0
  85. package/src/hooks/swapsApi/useSwapsApiIntentPacket.ts +43 -0
  86. package/src/hooks/swapsApi/useSwapsApiPartnerFee.ts +40 -0
  87. package/src/hooks/swapsApi/useSwapsApiQuote.ts +55 -0
  88. package/src/hooks/swapsApi/useSwapsApiSolverFee.ts +40 -0
  89. package/src/hooks/swapsApi/useSwapsApiStatus.ts +45 -0
  90. package/src/hooks/swapsApi/useSwapsApiSubmitIntent.ts +43 -0
  91. package/src/hooks/{backend/useBackendSubmitSwapTx.ts → swapsApi/useSwapsApiSubmitTx.ts} +16 -17
  92. package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +55 -0
  93. package/src/hooks/swapsApi/useSwapsApiTokens.ts +34 -0
  94. package/src/hooks/swapsApi/useSwapsApiTokensByChain.ts +40 -0
  95. package/src/index.ts +1 -1
  96. package/src/providers/SodaxProvider.tsx +2 -3
  97. package/src/providers/createSodaxQueryClient.ts +1 -5
  98. package/src/utils/dex-utils.ts +1 -4
  99. package/src/utils/index.ts +2 -0
  100. package/src/utils/nearStorageGate.test.ts +46 -0
  101. package/src/utils/nearStorageGate.ts +39 -0
  102. package/src/utils/stellarGate.test.ts +196 -0
  103. package/src/utils/stellarGate.ts +84 -0
  104. package/src/hooks/backend/useBackendSubmitSwapTxStatus.ts +0 -59
@@ -0,0 +1,102 @@
1
+ import {
2
+ ChainKeys,
3
+ type ActivateStellarAccountResult,
4
+ type GetWalletProviderType,
5
+ type Result,
6
+ type SpokeChainKey,
7
+ } from '@sodax/sdk';
8
+ import { resolveStellarGate, type StellarGateState } from '../../utils/stellarGate.js';
9
+ import { useActivateStellarAccount } from '../sponsoring/useActivateStellarAccount.js';
10
+ import { useStellarAccountStatus } from '../sponsoring/useStellarAccountStatus.js';
11
+ import { useEstablishTrustline } from './useEstablishTrustline.js';
12
+ import { useSodaxContext } from './useSodaxContext.js';
13
+ import { useStellarTrustlineCheck } from './useStellarTrustlineCheck.js';
14
+
15
+ export interface UseStellarGateParams {
16
+ dstChainKey: SpokeChainKey | undefined;
17
+ token: string | undefined;
18
+ amount: bigint | undefined;
19
+ address: string | undefined;
20
+ walletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
21
+ }
22
+
23
+ export interface StellarGate extends StellarGateState {
24
+ isChecking: boolean;
25
+ /** Surface when `checkFailed` is true. */
26
+ error: Error | undefined;
27
+ retry: () => void;
28
+ isActivating: boolean;
29
+ isRequestingTrustline: boolean;
30
+ /** Returns `undefined` when required inputs are missing. */
31
+ activate: () => Promise<Result<ActivateStellarAccountResult> | undefined>;
32
+ /** Returns `undefined` when required inputs are missing. */
33
+ requestTrustline: () => Promise<Result<string> | undefined>;
34
+ }
35
+
36
+ /**
37
+ * Gate Stellar delivery on account activation, trustline availability, and
38
+ * enough spendable XLM to create a missing trustline.
39
+ */
40
+ export function useStellarGate({
41
+ dstChainKey,
42
+ token,
43
+ amount,
44
+ address,
45
+ walletProvider,
46
+ }: UseStellarGateParams): StellarGate {
47
+ const { sodax } = useSodaxContext();
48
+ const isStellarDestination = dstChainKey === ChainKeys.STELLAR_MAINNET;
49
+ const stellarWalletProvider = walletProvider?.chainType === 'STELLAR' ? walletProvider : undefined;
50
+
51
+ const gatedAddress = isStellarDestination ? address : undefined;
52
+
53
+ const statusCheck = useStellarAccountStatus({ params: { address: gatedAddress } });
54
+ // Withhold the address until the account is known to exist, which leaves the trustline query
55
+ // disabled: `hasSufficientTrustline` 404s on a missing account, and React Query would retry it
56
+ // and surface the failure on `error` while the gate is correctly reporting `needsActivation`.
57
+ // `resolveStellarGate` decides activation from `statusCheck` alone and reads the unresolved
58
+ // trustline query as blocking, so this never changes the gate's outcome.
59
+ const trustlineAddress = statusCheck.data?.exists === true ? gatedAddress : undefined;
60
+ const trustlineCheck = useStellarTrustlineCheck({
61
+ params: { token, amount, chainId: dstChainKey, walletAddress: trustlineAddress },
62
+ });
63
+
64
+ // Trustline exemptions come from chain config, not token symbols.
65
+ const isNativeToken = isStellarDestination && !!token && !sodax.spoke.stellar.requiresTrustline(token);
66
+
67
+ const state = resolveStellarGate(dstChainKey, { statusCheck, trustlineCheck, isNativeToken });
68
+
69
+ const { mutateAsyncSafe: activateAccount, isPending: isActivating } = useActivateStellarAccount();
70
+ const { mutateAsyncSafe: establishTrustline, isPending: isRequestingTrustline } = useEstablishTrustline();
71
+
72
+ const activate = async (): Promise<Result<ActivateStellarAccountResult> | undefined> => {
73
+ if (!stellarWalletProvider || !address) return undefined;
74
+ return activateAccount({ address, walletProvider: stellarWalletProvider });
75
+ };
76
+
77
+ const requestTrustline = async (): Promise<Result<string> | undefined> => {
78
+ if (!stellarWalletProvider || !token || amount === undefined) return undefined;
79
+ return establishTrustline({
80
+ token,
81
+ amount,
82
+ srcChainKey: ChainKeys.STELLAR_MAINNET,
83
+ walletProvider: stellarWalletProvider,
84
+ });
85
+ };
86
+
87
+ const retry = (): void => {
88
+ void statusCheck.refetch();
89
+ void trustlineCheck.refetch();
90
+ };
91
+
92
+ return {
93
+ ...state,
94
+ isChecking: statusCheck.isLoading || trustlineCheck.isLoading,
95
+ error: statusCheck.error ?? trustlineCheck.error ?? undefined,
96
+ retry,
97
+ isActivating,
98
+ isRequestingTrustline,
99
+ activate,
100
+ requestTrustline,
101
+ };
102
+ }
@@ -0,0 +1,74 @@
1
+ import { ChainKeys } from '@sodax/sdk';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { getStellarTrustlineCheckQueryOptions } from './useStellarTrustlineCheck.js';
4
+
5
+ const TOKEN = 'CTOKEN';
6
+ const STELLAR = ChainKeys.STELLAR_MAINNET;
7
+ const WALLET_A = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
8
+ const WALLET_B = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
9
+
10
+ const makeSodax = (result: boolean) => {
11
+ const hasSufficientTrustline = vi.fn(async () => result);
12
+ return { sodax: { spoke: { stellar: { hasSufficientTrustline } } }, hasSufficientTrustline };
13
+ };
14
+
15
+ const optionsFor = (overrides: Partial<Parameters<typeof getStellarTrustlineCheckQueryOptions>[0]> = {}) =>
16
+ getStellarTrustlineCheckQueryOptions({
17
+ sodax: makeSodax(true).sodax,
18
+ token: TOKEN,
19
+ amount: 100n,
20
+ chainId: STELLAR,
21
+ walletAddress: WALLET_A,
22
+ ...overrides,
23
+ });
24
+
25
+ describe('getStellarTrustlineCheckQueryOptions — query key', () => {
26
+ it('keys on chain, token, account, and stringified amount', () => {
27
+ expect(optionsFor().queryKey).toEqual(['shared', 'stellarTrustlineCheck', STELLAR, TOKEN, WALLET_A, '100']);
28
+ });
29
+
30
+ it('produces independent keys for two accounts with the same token/amount/chain', () => {
31
+ expect(optionsFor({ walletAddress: WALLET_A }).queryKey).not.toEqual(
32
+ optionsFor({ walletAddress: WALLET_B }).queryKey,
33
+ );
34
+ });
35
+
36
+ it('produces a different key when the amount changes', () => {
37
+ expect(optionsFor({ amount: 100n }).queryKey).not.toEqual(optionsFor({ amount: 10_000n }).queryKey);
38
+ });
39
+
40
+ it('produces a different key when the chain changes', () => {
41
+ expect(optionsFor({ chainId: STELLAR }).queryKey).not.toEqual(
42
+ optionsFor({ chainId: ChainKeys.SONIC_MAINNET }).queryKey,
43
+ );
44
+ });
45
+
46
+ it('shares the useEstablishTrustline invalidation prefix (chain, token, account) across every amount', () => {
47
+ // useEstablishTrustline invalidates ['shared','stellarTrustlineCheck', srcChainKey, token, srcAddress];
48
+ // amount sits after that prefix, so the invalidation covers the account's checks at any amount.
49
+ const invalidationKey = ['shared', 'stellarTrustlineCheck', STELLAR, TOKEN, WALLET_A];
50
+ for (const amount of [100n, 10_000n]) {
51
+ expect(optionsFor({ amount }).queryKey.slice(0, invalidationKey.length)).toEqual(invalidationKey);
52
+ }
53
+ });
54
+ });
55
+
56
+ describe('getStellarTrustlineCheckQueryOptions — enabled + queryFn', () => {
57
+ it('is enabled only when walletAddress, token, and amount are present', () => {
58
+ expect(optionsFor({ walletAddress: WALLET_A }).enabled).toBe(true);
59
+ expect(optionsFor({ walletAddress: undefined }).enabled).toBe(false);
60
+ expect(optionsFor({ token: undefined }).enabled).toBe(false);
61
+ expect(optionsFor({ amount: undefined }).enabled).toBe(false);
62
+ });
63
+
64
+ it('checks the trustline for the given account address', async () => {
65
+ const { sodax, hasSufficientTrustline } = makeSodax(false);
66
+ const result = await optionsFor({ sodax, walletAddress: WALLET_A }).queryFn();
67
+ expect(hasSufficientTrustline).toHaveBeenCalledWith(TOKEN, 100n, WALLET_A);
68
+ expect(result).toBe(false);
69
+ });
70
+
71
+ it('returns true (no trustline needed) for a non-Stellar chain', async () => {
72
+ expect(await optionsFor({ chainId: ChainKeys.SONIC_MAINNET }).queryFn()).toBe(true);
73
+ });
74
+ });
@@ -1,4 +1,4 @@
1
- import { ChainKeys, type IStellarWalletProvider, type SpokeChainKey } from '@sodax/sdk';
1
+ import { ChainKeys, type Sodax, type SpokeChainKey } from '@sodax/sdk';
2
2
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
3
  import { useSodaxContext } from './useSodaxContext.js';
4
4
  import type { ReadHookParams } from './types.js';
@@ -9,29 +9,53 @@ export type UseStellarTrustlineCheckParams = ReadHookParams<
9
9
  token: string | undefined;
10
10
  amount: bigint | undefined;
11
11
  chainId: SpokeChainKey | undefined;
12
- walletProvider: IStellarWalletProvider | undefined;
12
+ /** Resolved Stellar account address (e.g. `useXAccount('STELLAR').address`) — keys the cache per account. */
13
+ walletAddress: string | undefined;
13
14
  }
14
15
  >;
15
16
 
17
+ // Narrow slice of the SDK this query reads — lets tests pass a minimal stub without casting `Sodax`.
18
+ type StellarTrustlineReader = { spoke: { stellar: Pick<Sodax['spoke']['stellar'], 'hasSufficientTrustline'> } };
19
+
20
+ // Pure query options, extracted for unit testing (mirrors `getXBalancesQueryOptions`).
21
+ export function getStellarTrustlineCheckQueryOptions({
22
+ sodax,
23
+ token,
24
+ amount,
25
+ chainId,
26
+ walletAddress,
27
+ }: {
28
+ sodax: StellarTrustlineReader;
29
+ token: string | undefined;
30
+ amount: bigint | undefined;
31
+ chainId: SpokeChainKey | undefined;
32
+ walletAddress: string | undefined;
33
+ }) {
34
+ return {
35
+ // Key on chain, token, account, amount so editing the amount (or switching account/chain) re-queries.
36
+ queryKey: ['shared', 'stellarTrustlineCheck', chainId, token, walletAddress, amount?.toString()] as const,
37
+ queryFn: async (): Promise<boolean> => {
38
+ if (chainId !== ChainKeys.STELLAR_MAINNET) return true;
39
+ if (!walletAddress || !token || !amount) return false;
40
+ return sodax.spoke.stellar.hasSufficientTrustline(token, amount, walletAddress);
41
+ },
42
+ enabled: !!walletAddress && !!token && !!amount,
43
+ };
44
+ }
45
+
16
46
  export function useStellarTrustlineCheck({
17
47
  params,
18
48
  queryOptions,
19
49
  }: UseStellarTrustlineCheckParams = {}): UseQueryResult<boolean, Error> {
20
50
  const { sodax } = useSodaxContext();
21
- const token = params?.token;
22
- const amount = params?.amount;
23
- const chainId = params?.chainId;
24
- const walletProvider = params?.walletProvider;
25
-
26
51
  return useQuery<boolean, Error>({
27
- queryKey: ['shared', 'stellarTrustlineCheck', token],
28
- queryFn: async () => {
29
- if (chainId !== ChainKeys.STELLAR_MAINNET) return true;
30
- if (!walletProvider || !token || !amount) return false;
31
- const walletAddress = await walletProvider.getWalletAddress();
32
- return sodax.spoke.stellar.hasSufficientTrustline(token, amount, walletAddress);
33
- },
34
- enabled: !!walletProvider && !!token && !!amount,
52
+ ...getStellarTrustlineCheckQueryOptions({
53
+ sodax,
54
+ token: params?.token,
55
+ amount: params?.amount,
56
+ chainId: params?.chainId,
57
+ walletAddress: params?.walletAddress,
58
+ }),
35
59
  ...queryOptions,
36
60
  });
37
61
  }
@@ -0,0 +1,4 @@
1
+ export * from './useActivateStellarAccount.js';
2
+ export * from './useSponsorConfig.js';
3
+ export * from './useStellarAccountActive.js';
4
+ export * from './useStellarAccountStatus.js';
@@ -0,0 +1,74 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+ import { getStellarAccountActiveQueryOptions } from './useStellarAccountActive.js';
6
+ import { getStellarAccountStatusQueryOptions } from './useStellarAccountStatus.js';
7
+
8
+ // The mutation contract test cannot verify invalidation keys, so compare them with query factories here.
9
+ const SRC = readFileSync(resolve(fileURLToPath(import.meta.url), '..', 'useActivateStellarAccount.ts'), 'utf8');
10
+
11
+ const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
12
+
13
+ function invalidatedKeyPrefixes(): string[][] {
14
+ return [...SRC.matchAll(/invalidateQueries\(\{\s*queryKey:\s*\[([^\]]*)\]/g)].map(match =>
15
+ (match[1] ?? '')
16
+ .split(',')
17
+ .map(segment => segment.trim())
18
+ .filter(segment => segment.length > 0)
19
+ // Runtime key segments are excluded because this helper compares literal prefixes.
20
+ .filter(segment => /^'[^']*'$/.test(segment))
21
+ .map(segment => segment.slice(1, -1)),
22
+ );
23
+ }
24
+
25
+ describe('useActivateStellarAccount — cache invalidation', () => {
26
+ it('invalidates exactly four queries on success', () => {
27
+ expect(invalidatedKeyPrefixes()).toHaveLength(4);
28
+ });
29
+
30
+ it("invalidates the account-active query using that query's own key prefix", () => {
31
+ const { sodax } = {
32
+ sodax: { sponsoring: { isStellarAccountActive: vi.fn(async () => ({ ok: true as const, value: true })) } },
33
+ };
34
+ const produced = getStellarAccountActiveQueryOptions({ sodax, address: ADDRESS }).queryKey;
35
+ const expected = produced.slice(0, -1);
36
+
37
+ expect(invalidatedKeyPrefixes()).toContainEqual(expected);
38
+ });
39
+
40
+ it("invalidates the account-status query using that query's own key prefix", () => {
41
+ // The status and active checks use independent cache entries.
42
+ const sodax = {
43
+ sponsoring: {
44
+ getStellarAccountStatus: vi.fn(async () => ({
45
+ ok: true as const,
46
+ value: {
47
+ exists: true,
48
+ nativeBalanceStroops: 0n,
49
+ availableBalanceStroops: 0n,
50
+ canAffordTrustline: false,
51
+ trustlineMinXlmStroops: 5_100_000n,
52
+ },
53
+ })),
54
+ },
55
+ };
56
+ const produced = getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryKey;
57
+
58
+ expect(invalidatedKeyPrefixes()).toContainEqual(produced.slice(0, -1));
59
+ });
60
+
61
+ it('invalidates the trustline check, whose pre-activation entry is a cached Horizon 404', () => {
62
+ // Clear cached pre-activation 404s for every token and amount.
63
+ expect(invalidatedKeyPrefixes()).toContainEqual(['shared', 'stellarTrustlineCheck']);
64
+ });
65
+
66
+ it('invalidates the Stellar balance query', () => {
67
+ expect(invalidatedKeyPrefixes()).toContainEqual(['shared', 'xBalances']);
68
+ });
69
+
70
+ it('passes the whole mutation vars through to the SDK', () => {
71
+ // Forwarding wholesale preserves retry and signature callback options.
72
+ expect(SRC).toMatch(/activateStellarAccount\(vars\)/);
73
+ });
74
+ });
@@ -0,0 +1,38 @@
1
+ import { ChainKeys, type ActivateStellarAccountParams, type ActivateStellarAccountResult } from '@sodax/sdk';
2
+ import { useQueryClient } from '@tanstack/react-query';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { unwrapResult } from '../shared/unwrapResult.js';
6
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
7
+
8
+ /** Keep mutation variables aligned with the SDK operation. */
9
+ export type UseActivateStellarAccountVars = ActivateStellarAccountParams;
10
+
11
+ /**
12
+ * Activate a Stellar account through the sponsoring service. Both `submitted`
13
+ * and `alreadyActive` are successful outcomes.
14
+ */
15
+ export function useActivateStellarAccount({
16
+ mutationOptions,
17
+ }: MutationHookParams<ActivateStellarAccountResult, UseActivateStellarAccountVars> = {}): SafeUseMutationResult<
18
+ ActivateStellarAccountResult,
19
+ Error,
20
+ UseActivateStellarAccountVars
21
+ > {
22
+ const { sodax } = useSodaxContext();
23
+ const queryClient = useQueryClient();
24
+
25
+ return useSafeMutation<ActivateStellarAccountResult, Error, UseActivateStellarAccountVars>({
26
+ mutationKey: ['sponsoring', 'activateStellarAccount'],
27
+ ...mutationOptions,
28
+ mutationFn: async vars => unwrapResult(await sodax.sponsoring.activateStellarAccount(vars)),
29
+ onSuccess: async (data, vars, ctx) => {
30
+ queryClient.invalidateQueries({ queryKey: ['sponsoring', 'stellarAccountActive', vars.address] });
31
+ queryClient.invalidateQueries({ queryKey: ['sponsoring', 'stellarAccountStatus', vars.address] });
32
+ // Clear trustline errors cached while the account did not exist.
33
+ queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck'] });
34
+ queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET] });
35
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
36
+ },
37
+ });
38
+ }
@@ -0,0 +1,46 @@
1
+ import { SodaxError, SPONSOR_CONFIG_TTL_MS, type StellarSponsorConfig } from '@sodax/sdk';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { getSponsorConfigQueryOptions } from './useSponsorConfig.js';
4
+
5
+ const CONFIG: StellarSponsorConfig = {
6
+ sponsorAccount: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',
7
+ networkPassphrase: 'Public Global Stellar Network ; September 2015',
8
+ minTotalFeeStroops: '3000',
9
+ maxTotalFeeStroops: '10000',
10
+ operationCount: 3,
11
+ minPerOperationFeeStroops: '1000',
12
+ maxPerOperationFeeStroops: '3333',
13
+ recommendedPerOperationFeeStroops: '1000',
14
+ maxTimeboundSeconds: 3600,
15
+ requiredStartingBalance: '0',
16
+ };
17
+
18
+ const makeSodax = (result: { ok: true; value: StellarSponsorConfig } | { ok: false; error: SodaxError }) => {
19
+ const getStellarSponsorConfig = vi.fn(async () => result);
20
+ return { sodax: { sponsoring: { getStellarSponsorConfig } }, getStellarSponsorConfig };
21
+ };
22
+
23
+ const configError = new SodaxError('EXTERNAL_API_ERROR', 'sponsoring API unreachable', { feature: 'backend' });
24
+
25
+ describe('getSponsorConfigQueryOptions', () => {
26
+ it('uses a fixed key — the config is not parameterised', () => {
27
+ const { sodax } = makeSodax({ ok: true, value: CONFIG });
28
+ expect(getSponsorConfigQueryOptions({ sodax }).queryKey).toEqual(['sponsoring', 'sponsorConfig']);
29
+ });
30
+
31
+ it("reuses the SDK's TTL so both mirror the server's max-age=60", () => {
32
+ const { sodax } = makeSodax({ ok: true, value: CONFIG });
33
+ expect(getSponsorConfigQueryOptions({ sodax }).staleTime).toBe(SPONSOR_CONFIG_TTL_MS);
34
+ });
35
+
36
+ it('returns the published build parameters', async () => {
37
+ const { sodax, getStellarSponsorConfig } = makeSodax({ ok: true, value: CONFIG });
38
+ await expect(getSponsorConfigQueryOptions({ sodax }).queryFn()).resolves.toEqual(CONFIG);
39
+ expect(getStellarSponsorConfig).toHaveBeenCalledOnce();
40
+ });
41
+
42
+ it('THROWS on failure so React Query reports isError and caches nothing', async () => {
43
+ const { sodax } = makeSodax({ ok: false, error: configError });
44
+ await expect(getSponsorConfigQueryOptions({ sodax }).queryFn()).rejects.toBe(configError);
45
+ });
46
+ });
@@ -0,0 +1,31 @@
1
+ import { SPONSOR_CONFIG_TTL_MS, type Sodax, type StellarSponsorConfig } from '@sodax/sdk';
2
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import type { ReadHookParams } from '../shared/types.js';
5
+
6
+ export type UseSponsorConfigParams = ReadHookParams<StellarSponsorConfig>;
7
+
8
+ type SponsorConfigReader = { sponsoring: Pick<Sodax['sponsoring'], 'getStellarSponsorConfig'> };
9
+
10
+ export function getSponsorConfigQueryOptions({ sodax }: { sodax: SponsorConfigReader }) {
11
+ return {
12
+ queryKey: ['sponsoring', 'sponsorConfig'] as const,
13
+ queryFn: async (): Promise<StellarSponsorConfig> => {
14
+ const result = await sodax.sponsoring.getStellarSponsorConfig();
15
+ if (!result.ok) throw result.error;
16
+ return result.value;
17
+ },
18
+ staleTime: SPONSOR_CONFIG_TTL_MS,
19
+ };
20
+ }
21
+
22
+ /** Read the sponsoring service's published transaction parameters. */
23
+ export function useSponsorConfig({
24
+ queryOptions,
25
+ }: UseSponsorConfigParams = {}): UseQueryResult<StellarSponsorConfig, Error> {
26
+ const { sodax } = useSodaxContext();
27
+ return useQuery<StellarSponsorConfig, Error>({
28
+ ...getSponsorConfigQueryOptions({ sodax }),
29
+ ...queryOptions,
30
+ });
31
+ }
@@ -0,0 +1,50 @@
1
+ import { SodaxError } from '@sodax/sdk';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { getStellarAccountActiveQueryOptions } from './useStellarAccountActive.js';
4
+
5
+ const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
6
+ const OTHER = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
7
+
8
+ const makeSodax = (result: { ok: true; value: boolean } | { ok: false; error: SodaxError }) => {
9
+ const isStellarAccountActive = vi.fn(async () => result);
10
+ return { sodax: { sponsoring: { isStellarAccountActive } }, isStellarAccountActive };
11
+ };
12
+
13
+ const lookupError = new SodaxError('LOOKUP_FAILED', 'Horizon unreachable', { feature: 'sponsoring' });
14
+
15
+ describe('getStellarAccountActiveQueryOptions — query key', () => {
16
+ it('keys on the address', () => {
17
+ const { sodax } = makeSodax({ ok: true, value: true });
18
+ expect(getStellarAccountActiveQueryOptions({ sodax, address: ADDRESS }).queryKey).toEqual([
19
+ 'sponsoring',
20
+ 'stellarAccountActive',
21
+ ADDRESS,
22
+ ]);
23
+ });
24
+
25
+ it('produces independent keys per account', () => {
26
+ const { sodax } = makeSodax({ ok: true, value: true });
27
+ expect(getStellarAccountActiveQueryOptions({ sodax, address: ADDRESS }).queryKey).not.toEqual(
28
+ getStellarAccountActiveQueryOptions({ sodax, address: OTHER }).queryKey,
29
+ );
30
+ });
31
+ });
32
+
33
+ describe('getStellarAccountActiveQueryOptions — enablement and fetching', () => {
34
+ it('is disabled without an address', () => {
35
+ const { sodax } = makeSodax({ ok: true, value: true });
36
+ expect(getStellarAccountActiveQueryOptions({ sodax, address: undefined }).enabled).toBe(false);
37
+ expect(getStellarAccountActiveQueryOptions({ sodax, address: ADDRESS }).enabled).toBe(true);
38
+ });
39
+
40
+ it.each([true, false])('returns the SDK result (%s)', async value => {
41
+ const { sodax, isStellarAccountActive } = makeSodax({ ok: true, value });
42
+ await expect(getStellarAccountActiveQueryOptions({ sodax, address: ADDRESS }).queryFn()).resolves.toBe(value);
43
+ expect(isStellarAccountActive).toHaveBeenCalledWith({ address: ADDRESS });
44
+ });
45
+
46
+ it('THROWS on a lookup failure rather than reporting "not active"', async () => {
47
+ const { sodax } = makeSodax({ ok: false, error: lookupError });
48
+ await expect(getStellarAccountActiveQueryOptions({ sodax, address: ADDRESS }).queryFn()).rejects.toBe(lookupError);
49
+ });
50
+ });
@@ -0,0 +1,45 @@
1
+ import type { Sodax } from '@sodax/sdk';
2
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import type { ReadHookParams } from '../shared/types.js';
5
+
6
+ export type UseStellarAccountActiveParams = ReadHookParams<
7
+ boolean,
8
+ {
9
+ address: string | undefined;
10
+ }
11
+ >;
12
+
13
+ type StellarAccountReader = { sponsoring: Pick<Sodax['sponsoring'], 'isStellarAccountActive'> };
14
+
15
+ export function getStellarAccountActiveQueryOptions({
16
+ sodax,
17
+ address,
18
+ }: {
19
+ sodax: StellarAccountReader;
20
+ address: string | undefined;
21
+ }) {
22
+ return {
23
+ queryKey: ['sponsoring', 'stellarAccountActive', address] as const,
24
+ queryFn: async (): Promise<boolean> => {
25
+ if (!address) return false;
26
+ const result = await sodax.sponsoring.isStellarAccountActive({ address });
27
+ // A read failure is not evidence that the account is inactive.
28
+ if (!result.ok) throw result.error;
29
+ return result.value;
30
+ },
31
+ enabled: !!address,
32
+ };
33
+ }
34
+
35
+ /** Whether a Stellar account exists on-chain. */
36
+ export function useStellarAccountActive({
37
+ params,
38
+ queryOptions,
39
+ }: UseStellarAccountActiveParams = {}): UseQueryResult<boolean, Error> {
40
+ const { sodax } = useSodaxContext();
41
+ return useQuery<boolean, Error>({
42
+ ...getStellarAccountActiveQueryOptions({ sodax, address: params?.address }),
43
+ ...queryOptions,
44
+ });
45
+ }
@@ -0,0 +1,90 @@
1
+ import { SodaxError, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, type StellarAccountStatus } from '@sodax/sdk';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { getStellarAccountStatusQueryOptions } from './useStellarAccountStatus.js';
4
+
5
+ const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
6
+ const OTHER = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
7
+
8
+ const FUNDED: StellarAccountStatus = {
9
+ exists: true,
10
+ nativeBalanceStroops: 50_000_000n,
11
+ availableBalanceStroops: 40_000_000n,
12
+ canAffordTrustline: true,
13
+ trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
14
+ };
15
+
16
+ const makeSodax = (result: { ok: true; value: StellarAccountStatus } | { ok: false; error: SodaxError }) => {
17
+ const getStellarAccountStatus = vi.fn(async () => result);
18
+ return { sodax: { sponsoring: { getStellarAccountStatus } }, getStellarAccountStatus };
19
+ };
20
+
21
+ const lookupError = new SodaxError('LOOKUP_FAILED', 'Horizon unreachable', { feature: 'sponsoring' });
22
+
23
+ describe('getStellarAccountStatusQueryOptions — query key', () => {
24
+ it('keys on the address', () => {
25
+ const { sodax } = makeSodax({ ok: true, value: FUNDED });
26
+ expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryKey).toEqual([
27
+ 'sponsoring',
28
+ 'stellarAccountStatus',
29
+ ADDRESS,
30
+ ]);
31
+ });
32
+
33
+ it('produces independent keys per account', () => {
34
+ const { sodax } = makeSodax({ ok: true, value: FUNDED });
35
+ expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryKey).not.toEqual(
36
+ getStellarAccountStatusQueryOptions({ sodax, address: OTHER }).queryKey,
37
+ );
38
+ });
39
+
40
+ it('uses a key distinct from the boolean active-check, so the two do not share a cache entry', () => {
41
+ const { sodax } = makeSodax({ ok: true, value: FUNDED });
42
+ expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryKey[1]).toBe('stellarAccountStatus');
43
+ });
44
+ });
45
+
46
+ describe('getStellarAccountStatusQueryOptions — enablement and fetching', () => {
47
+ it('is disabled without an address', () => {
48
+ const { sodax } = makeSodax({ ok: true, value: FUNDED });
49
+ expect(getStellarAccountStatusQueryOptions({ sodax, address: undefined }).enabled).toBe(false);
50
+ expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).enabled).toBe(true);
51
+ });
52
+
53
+ it('returns the SDK status verbatim', async () => {
54
+ const { sodax, getStellarAccountStatus } = makeSodax({ ok: true, value: FUNDED });
55
+ await expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryFn()).resolves.toEqual(FUNDED);
56
+ expect(getStellarAccountStatus).toHaveBeenCalledWith({ address: ADDRESS });
57
+ });
58
+
59
+ it('resolves to a zero-value without an address instead of throwing', async () => {
60
+ // Manual fetches can execute this query even while React Query marks it disabled.
61
+ const { sodax, getStellarAccountStatus } = makeSodax({ ok: true, value: FUNDED });
62
+ await expect(getStellarAccountStatusQueryOptions({ sodax, address: undefined }).queryFn()).resolves.toEqual({
63
+ exists: false,
64
+ nativeBalanceStroops: 0n,
65
+ availableBalanceStroops: 0n,
66
+ canAffordTrustline: false,
67
+ trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
68
+ });
69
+ expect(getStellarAccountStatus).not.toHaveBeenCalled();
70
+ });
71
+
72
+ it('THROWS on a lookup failure rather than reporting the account absent', async () => {
73
+ const { sodax } = makeSodax({ ok: false, error: lookupError });
74
+ await expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryFn()).rejects.toBe(lookupError);
75
+ });
76
+
77
+ it('reports an existing account that cannot afford a trustline — the post-activation state', async () => {
78
+ const sponsoredEmpty: StellarAccountStatus = {
79
+ exists: true,
80
+ nativeBalanceStroops: 0n,
81
+ availableBalanceStroops: 0n,
82
+ canAffordTrustline: false,
83
+ trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
84
+ };
85
+ const { sodax } = makeSodax({ ok: true, value: sponsoredEmpty });
86
+ await expect(getStellarAccountStatusQueryOptions({ sodax, address: ADDRESS }).queryFn()).resolves.toEqual(
87
+ sponsoredEmpty,
88
+ );
89
+ });
90
+ });