@sodax/dapp-kit 2.0.0 → 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 (40) hide show
  1. package/README.md +128 -115
  2. package/dist/index.d.ts +155 -11
  3. package/dist/index.mjs +237 -45
  4. package/package.json +2 -2
  5. package/src/hooks/_mutationContract.test.ts +2 -0
  6. package/src/hooks/backend/types.ts +1 -1
  7. package/src/hooks/bridge/useBridgeApprove.ts +2 -1
  8. package/src/hooks/index.ts +1 -0
  9. package/src/hooks/migrate/useMigrationApprove.ts +1 -3
  10. package/src/hooks/mm/useWithdraw.ts +5 -1
  11. package/src/hooks/partner/useApproveToken.ts +1 -2
  12. package/src/hooks/shared/index.ts +2 -0
  13. package/src/hooks/shared/useEstablishTrustline.test.ts +89 -0
  14. package/src/hooks/shared/useEstablishTrustline.ts +72 -0
  15. package/src/hooks/shared/useRequestTrustline.test.ts +115 -0
  16. package/src/hooks/shared/useRequestTrustline.ts +41 -56
  17. package/src/hooks/shared/useSafeMutation.ts +1 -4
  18. package/src/hooks/shared/useStellarGate.test.ts +99 -0
  19. package/src/hooks/shared/useStellarGate.ts +102 -0
  20. package/src/hooks/shared/useStellarTrustlineCheck.test.ts +2 -2
  21. package/src/hooks/sponsoring/index.ts +4 -0
  22. package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +74 -0
  23. package/src/hooks/sponsoring/useActivateStellarAccount.ts +38 -0
  24. package/src/hooks/sponsoring/useSponsorConfig.test.ts +46 -0
  25. package/src/hooks/sponsoring/useSponsorConfig.ts +31 -0
  26. package/src/hooks/sponsoring/useStellarAccountActive.test.ts +50 -0
  27. package/src/hooks/sponsoring/useStellarAccountActive.ts +45 -0
  28. package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +90 -0
  29. package/src/hooks/sponsoring/useStellarAccountStatus.ts +57 -0
  30. package/src/hooks/staking/useStakingConfig.ts +1 -3
  31. package/src/hooks/staking/useStakingInfo.ts +4 -4
  32. package/src/hooks/staking/useUnstake.ts +5 -1
  33. package/src/hooks/swap/useCreateLimitOrder.ts +1 -2
  34. package/src/hooks/swap/useSwap.ts +1 -5
  35. package/src/index.ts +1 -1
  36. package/src/providers/createSodaxQueryClient.ts +1 -5
  37. package/src/utils/dex-utils.ts +1 -4
  38. package/src/utils/index.ts +1 -0
  39. package/src/utils/stellarGate.test.ts +196 -0
  40. package/src/utils/stellarGate.ts +84 -0
@@ -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
+ });
@@ -0,0 +1,57 @@
1
+ import { STELLAR_TRUSTLINE_MIN_XLM_STROOPS, type Sodax, type StellarAccountStatus } from '@sodax/sdk';
2
+ import { type UseQueryResult, useQuery } from '@tanstack/react-query';
3
+ import type { ReadHookParams } from '../shared/types.js';
4
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+
6
+ export type UseStellarAccountStatusParams = ReadHookParams<
7
+ StellarAccountStatus,
8
+ {
9
+ address: string | undefined;
10
+ }
11
+ >;
12
+
13
+ type StellarAccountStatusReader = { sponsoring: Pick<Sodax['sponsoring'], 'getStellarAccountStatus'> };
14
+
15
+ export function getStellarAccountStatusQueryOptions({
16
+ sodax,
17
+ address,
18
+ }: {
19
+ sodax: StellarAccountStatusReader;
20
+ address: string | undefined;
21
+ }) {
22
+ return {
23
+ queryKey: ['sponsoring', 'stellarAccountStatus', address] as const,
24
+ queryFn: async (): Promise<StellarAccountStatus> => {
25
+ if (!address) {
26
+ return {
27
+ exists: false,
28
+ nativeBalanceStroops: 0n,
29
+ availableBalanceStroops: 0n,
30
+ canAffordTrustline: false,
31
+ // No account to read the network reserve for; the published value is the best guess.
32
+ trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
33
+ };
34
+ }
35
+ const result = await sodax.sponsoring.getStellarAccountStatus({ address });
36
+ // A read failure is not evidence that the account is absent.
37
+ if (!result.ok) throw result.error;
38
+ return result.value;
39
+ },
40
+ enabled: !!address,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Read account existence and trustline affordability in one Horizon request.
46
+ * Prefer {@link useStellarGate} for destination gating.
47
+ */
48
+ export function useStellarAccountStatus({
49
+ params,
50
+ queryOptions,
51
+ }: UseStellarAccountStatusParams = {}): UseQueryResult<StellarAccountStatus, Error> {
52
+ const { sodax } = useSodaxContext();
53
+ return useQuery<StellarAccountStatus, Error>({
54
+ ...getStellarAccountStatusQueryOptions({ sodax, address: params?.address }),
55
+ ...queryOptions,
56
+ });
57
+ }
@@ -9,9 +9,7 @@ export type UseStakingConfigParams = ReadHookParams<StakingConfig>;
9
9
  * React hook to fetch the global staking config (unstaking period, min unstaking period, max
10
10
  * penalty). Hub-only read; no chain context required. Throws on `!ok`.
11
11
  */
12
- export function useStakingConfig({
13
- queryOptions,
14
- }: UseStakingConfigParams = {}): UseQueryResult<StakingConfig, Error> {
12
+ export function useStakingConfig({ queryOptions }: UseStakingConfigParams = {}): UseQueryResult<StakingConfig, Error> {
15
13
  const { sodax } = useSodaxContext();
16
14
 
17
15
  return useQuery<StakingConfig, Error>({
@@ -17,10 +17,10 @@ export type UseStakingInfoParams = ReadHookParams<
17
17
  * deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok` so React
18
18
  * Query lands in `error` state.
19
19
  */
20
- export function useStakingInfo({ params, queryOptions }: UseStakingInfoParams = {}): UseQueryResult<
21
- StakingInfo,
22
- Error
23
- > {
20
+ export function useStakingInfo({
21
+ params,
22
+ queryOptions,
23
+ }: UseStakingInfoParams = {}): UseQueryResult<StakingInfo, Error> {
24
24
  const { sodax } = useSodaxContext();
25
25
  const srcAddress = params?.srcAddress;
26
26
  const srcChainKey = params?.srcChainKey;
@@ -16,7 +16,11 @@ export type UseUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<Unsta
16
16
  */
17
17
  export function useUnstake<K extends SpokeChainKey = SpokeChainKey>({
18
18
  mutationOptions,
19
- }: MutationHookParams<TxHashPair, UseUnstakeVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseUnstakeVars<K>> {
19
+ }: MutationHookParams<TxHashPair, UseUnstakeVars<K>> = {}): SafeUseMutationResult<
20
+ TxHashPair,
21
+ Error,
22
+ UseUnstakeVars<K>
23
+ > {
20
24
  const { sodax } = useSodaxContext();
21
25
  const queryClient = useQueryClient();
22
26
 
@@ -33,7 +33,6 @@ export function useCreateLimitOrder<K extends SpokeChainKey = SpokeChainKey>({
33
33
  return useSafeMutation<SwapResponse, Error, UseCreateLimitOrderVars<K>>({
34
34
  mutationKey: ['swap', 'limitOrder', 'create'],
35
35
  ...mutationOptions,
36
- mutationFn: async vars =>
37
- unwrapResult(await sodax.swaps.createLimitOrder({ ...vars, raw: false })),
36
+ mutationFn: async vars => unwrapResult(await sodax.swaps.createLimitOrder({ ...vars, raw: false })),
38
37
  });
39
38
  }
@@ -21,11 +21,7 @@ export type UseSwapVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SwapActi
21
21
  */
22
22
  export function useSwap<K extends SpokeChainKey = SpokeChainKey>({
23
23
  mutationOptions,
24
- }: MutationHookParams<SwapResponse, UseSwapVars<K>> = {}): SafeUseMutationResult<
25
- SwapResponse,
26
- Error,
27
- UseSwapVars<K>
28
- > {
24
+ }: MutationHookParams<SwapResponse, UseSwapVars<K>> = {}): SafeUseMutationResult<SwapResponse, Error, UseSwapVars<K>> {
29
25
  const { sodax } = useSodaxContext();
30
26
  const queryClient = useQueryClient();
31
27
 
package/src/index.ts CHANGED
@@ -2,4 +2,4 @@ export * from './hooks/index.js';
2
2
  export * from './providers/index.js';
3
3
  export * from './utils/index.js';
4
4
 
5
- export * from '@sodax/sdk' // export all sdk entities
5
+ export * from '@sodax/sdk'; // export all sdk entities
@@ -72,11 +72,7 @@ export function createSodaxQueryClient({
72
72
  // Compose: keep the consumer's cache, attach our observability as an extra subscriber.
73
73
  // The consumer's own `MutationCache.onError` (if any) still fires — subscribe is additive.
74
74
  config.mutationCache.subscribe(event => {
75
- if (
76
- event.type === 'updated' &&
77
- event.action.type === 'error' &&
78
- event.mutation.options.meta?.silent !== true
79
- ) {
75
+ if (event.type === 'updated' && event.action.type === 'error' && event.mutation.options.meta?.silent !== true) {
80
76
  onMutationError(event.action.error);
81
77
  }
82
78
  });
@@ -30,10 +30,7 @@ export type WithdrawParamsCore = Omit<CreateAssetWithdrawParams<SpokeChainKey>,
30
30
  * Subset of {@link ClDecreaseLiquidityParams} produced by {@link createDecreaseLiquidityParamsProps}.
31
31
  * Callers add `srcChainKey` + `srcAddress` at the mutation call site.
32
32
  */
33
- export type DecreaseLiquidityParamsCore = Omit<
34
- ClDecreaseLiquidityParams<SpokeChainKey>,
35
- 'srcChainKey' | 'srcAddress'
36
- >;
33
+ export type DecreaseLiquidityParamsCore = Omit<ClDecreaseLiquidityParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'>;
37
34
 
38
35
  export function createDecreaseLiquidityParamsProps({
39
36
  poolKey,
@@ -1,2 +1,3 @@
1
1
  export * from './dex-utils.js';
2
2
  export * from './nearStorageGate.js';
3
+ export * from './stellarGate.js';
@@ -0,0 +1,196 @@
1
+ import { ChainKeys, type StellarAccountStatus } from '@sodax/sdk';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { resolveStellarGate, type StellarCheckResult } from './stellarGate.js';
4
+
5
+ const STELLAR = ChainKeys.STELLAR_MAINNET;
6
+
7
+ const resolved = <T>(data: T): StellarCheckResult<T> => ({ isLoading: false, isError: false, data });
8
+ const loading = <T>(): StellarCheckResult<T> => ({ isLoading: true, isError: false, data: undefined });
9
+ const errored = <T>(): StellarCheckResult<T> => ({ isLoading: false, isError: true, data: undefined });
10
+ const idle = <T>(): StellarCheckResult<T> => ({ isLoading: false, isError: false, data: undefined });
11
+
12
+ const status = (overrides: Partial<StellarAccountStatus> = {}): StellarAccountStatus => ({
13
+ exists: true,
14
+ nativeBalanceStroops: 10_000_000n,
15
+ availableBalanceStroops: 10_000_000n,
16
+ canAffordTrustline: true,
17
+ trustlineMinXlmStroops: 5_100_000n,
18
+ ...overrides,
19
+ });
20
+
21
+ const gate = (
22
+ chainKey: typeof STELLAR | undefined,
23
+ inputs: {
24
+ statusCheck?: StellarCheckResult<StellarAccountStatus>;
25
+ trustlineCheck?: StellarCheckResult<boolean>;
26
+ isNativeToken?: boolean;
27
+ } = {},
28
+ ) =>
29
+ resolveStellarGate(chainKey, {
30
+ statusCheck: inputs.statusCheck ?? resolved(status()),
31
+ trustlineCheck: inputs.trustlineCheck ?? resolved(true),
32
+ isNativeToken: inputs.isNativeToken ?? false,
33
+ });
34
+
35
+ describe('resolveStellarGate — non-Stellar destinations', () => {
36
+ it.each([[ChainKeys.SONIC_MAINNET], [undefined]])('is inert for %s', chainKey => {
37
+ expect(gate(chainKey as undefined, { statusCheck: idle(), trustlineCheck: idle() })).toEqual({
38
+ isStellar: false,
39
+ needsActivation: false,
40
+ needsFunding: false,
41
+ needsTrustline: false,
42
+ checkFailed: false,
43
+ blocksAction: false,
44
+ });
45
+ });
46
+
47
+ it('does not report a failed check for a non-Stellar destination', () => {
48
+ const result = gate(undefined, { statusCheck: errored(), trustlineCheck: errored() });
49
+ expect(result.checkFailed).toBe(false);
50
+ expect(result.blocksAction).toBe(false);
51
+ });
52
+ });
53
+
54
+ describe('resolveStellarGate — unknown account state blocks without accusing', () => {
55
+ it.each([
56
+ ['loading', loading<StellarAccountStatus>()],
57
+ ['errored', errored<StellarAccountStatus>()],
58
+ ['idle/disabled', idle<StellarAccountStatus>()],
59
+ ])('blocks but does NOT claim needsActivation when the status check is %s', (_label, statusCheck) => {
60
+ // Unknown account state must not be classified as a missing prerequisite.
61
+ const result = gate(STELLAR, { statusCheck });
62
+ expect(result.blocksAction).toBe(true);
63
+ expect(result.needsActivation).toBe(false);
64
+ expect(result.needsFunding).toBe(false);
65
+ expect(result.needsTrustline).toBe(false);
66
+ });
67
+
68
+ it('a disabled trustline query cannot block forever once the account is funded', () => {
69
+ // Disabled React Query checks are idle, not loading.
70
+ expect(gate(STELLAR, { trustlineCheck: idle() }).blocksAction).toBe(true);
71
+ expect(gate(STELLAR, { trustlineCheck: resolved(true) }).blocksAction).toBe(false);
72
+ });
73
+
74
+ it.each([
75
+ ['the status read', { statusCheck: errored<StellarAccountStatus>() }],
76
+ ['the trustline read', { trustlineCheck: errored<boolean>() }],
77
+ ])('reports checkFailed when %s errors, so the UI can offer a retry', (_label, inputs) => {
78
+ const result = gate(STELLAR, inputs);
79
+ expect(result.checkFailed).toBe(true);
80
+ expect(result.blocksAction).toBe(true);
81
+ expect(result.needsActivation).toBe(false);
82
+ expect(result.needsFunding).toBe(false);
83
+ expect(result.needsTrustline).toBe(false);
84
+ });
85
+
86
+ it.each([
87
+ ['loading', { statusCheck: loading<StellarAccountStatus>() }],
88
+ ['idle/disabled', { statusCheck: idle<StellarAccountStatus>() }],
89
+ ['an idle trustline read', { trustlineCheck: idle<boolean>() }],
90
+ ])('does NOT report checkFailed for %s — nothing failed', (_label, inputs) => {
91
+ const result = gate(STELLAR, inputs);
92
+ expect(result.checkFailed).toBe(false);
93
+ expect(result.blocksAction).toBe(true);
94
+ });
95
+ });
96
+
97
+ describe('resolveStellarGate — stage ordering', () => {
98
+ it('reports activation first for a non-existent account, and nothing downstream', () => {
99
+ const result = gate(STELLAR, {
100
+ statusCheck: resolved(status({ exists: false, nativeBalanceStroops: 0n, canAffordTrustline: false })),
101
+ trustlineCheck: resolved(false),
102
+ });
103
+ expect(result).toEqual({
104
+ isStellar: true,
105
+ needsActivation: true,
106
+ needsFunding: false,
107
+ needsTrustline: false,
108
+ checkFailed: false,
109
+ blocksAction: true,
110
+ });
111
+ });
112
+
113
+ it('does NOT ask a broke account to fund itself when it ALREADY holds the trustline', () => {
114
+ // Receiving through an existing trustline requires no recipient reserve or fee.
115
+ const result = gate(STELLAR, {
116
+ statusCheck: resolved(
117
+ status({ nativeBalanceStroops: 0n, availableBalanceStroops: 0n, canAffordTrustline: false }),
118
+ ),
119
+ trustlineCheck: resolved(true),
120
+ });
121
+ expect(result.needsFunding).toBe(false);
122
+ expect(result.needsTrustline).toBe(false);
123
+ expect(result.blocksAction).toBe(false);
124
+ });
125
+
126
+ it('reports funding for a freshly activated 0-XLM account, NOT a trustline', () => {
127
+ const result = gate(STELLAR, {
128
+ statusCheck: resolved(status({ nativeBalanceStroops: 0n, canAffordTrustline: false })),
129
+ trustlineCheck: resolved(false),
130
+ });
131
+ expect(result.needsFunding).toBe(true);
132
+ expect(result.needsTrustline).toBe(false);
133
+ expect(result.blocksAction).toBe(true);
134
+ });
135
+
136
+ it('reports a trustline only once the account exists and can pay for one', () => {
137
+ const result = gate(STELLAR, { trustlineCheck: resolved(false) });
138
+ expect(result).toEqual({
139
+ isStellar: true,
140
+ needsActivation: false,
141
+ needsFunding: false,
142
+ needsTrustline: true,
143
+ checkFailed: false,
144
+ blocksAction: true,
145
+ });
146
+ });
147
+
148
+ it('clears once every prerequisite is met', () => {
149
+ expect(gate(STELLAR, { trustlineCheck: resolved(true) })).toEqual({
150
+ isStellar: true,
151
+ needsActivation: false,
152
+ needsFunding: false,
153
+ needsTrustline: false,
154
+ checkFailed: false,
155
+ blocksAction: false,
156
+ });
157
+ });
158
+
159
+ it('never reports two stages at once', () => {
160
+ const cases = [
161
+ gate(STELLAR, { statusCheck: resolved(status({ exists: false, canAffordTrustline: false })) }),
162
+ gate(STELLAR, {
163
+ statusCheck: resolved(status({ canAffordTrustline: false })),
164
+ trustlineCheck: resolved(false),
165
+ }),
166
+ gate(STELLAR, { trustlineCheck: resolved(false) }),
167
+ ];
168
+ for (const result of cases) {
169
+ const active = [result.needsActivation, result.needsFunding, result.needsTrustline].filter(Boolean);
170
+ expect(active).toHaveLength(1);
171
+ }
172
+ });
173
+ });
174
+
175
+ describe('resolveStellarGate — native XLM skips funding and trustline', () => {
176
+ it('does not gate an activated 0-XLM account on funding when receiving native XLM', () => {
177
+ // Native XLM needs no trustline or recipient fee, so funding cannot gate receipt.
178
+ const result = gate(STELLAR, {
179
+ statusCheck: resolved(status({ nativeBalanceStroops: 0n, canAffordTrustline: false })),
180
+ trustlineCheck: resolved(false),
181
+ isNativeToken: true,
182
+ });
183
+ expect(result.needsFunding).toBe(false);
184
+ expect(result.needsTrustline).toBe(false);
185
+ expect(result.blocksAction).toBe(false);
186
+ });
187
+
188
+ it('still requires the account to EXIST before it can receive native XLM', () => {
189
+ const result = gate(STELLAR, {
190
+ statusCheck: resolved(status({ exists: false, canAffordTrustline: false })),
191
+ isNativeToken: true,
192
+ });
193
+ expect(result.needsActivation).toBe(true);
194
+ expect(result.blocksAction).toBe(true);
195
+ });
196
+ });
@@ -0,0 +1,84 @@
1
+ import { ChainKeys, type SpokeChainKey, type StellarAccountStatus } from '@sodax/sdk';
2
+ import type { UseQueryResult } from '@tanstack/react-query';
3
+
4
+ /**
5
+ * The subset of a query result the gate reads. A full `UseQueryResult<T>` satisfies it.
6
+ *
7
+ * `isLoading` is intentional: `isPending` remains true for disabled queries.
8
+ * Errors remain distinct from unmet prerequisites.
9
+ */
10
+ export type StellarCheckResult<T> = Pick<UseQueryResult<T>, 'isLoading' | 'isError' | 'data'>;
11
+
12
+ export interface StellarGateState {
13
+ isStellar: boolean;
14
+ needsActivation: boolean;
15
+ /**
16
+ * The account needs a trustline but lacks spendable XLM. Never set for
17
+ * native XLM or an existing trustline.
18
+ */
19
+ needsFunding: boolean;
20
+ needsTrustline: boolean;
21
+ /** A query failed; disabled or unresolved queries do not set this. */
22
+ checkFailed: boolean;
23
+ /** Whether the downstream action must remain disabled. */
24
+ blocksAction: boolean;
25
+ }
26
+
27
+ export interface StellarGateInputs {
28
+ /** Account existence and spending capacity from one Horizon read. */
29
+ statusCheck: StellarCheckResult<StellarAccountStatus>;
30
+ trustlineCheck: StellarCheckResult<boolean>;
31
+ /** Resolve from chain config, never by comparing token symbols. */
32
+ isNativeToken: boolean;
33
+ }
34
+
35
+ function unresolved<T>(check: StellarCheckResult<T>): boolean {
36
+ return check.isLoading || check.data === undefined;
37
+ }
38
+
39
+ const NOT_STELLAR: StellarGateState = {
40
+ isStellar: false,
41
+ needsActivation: false,
42
+ needsFunding: false,
43
+ needsTrustline: false,
44
+ checkFailed: false,
45
+ blocksAction: false,
46
+ };
47
+
48
+ /**
49
+ * Resolve activation, trustline, and funding prerequisites in order.
50
+ *
51
+ * Check the trustline before affordability because an existing trustline needs
52
+ * no additional XLM. Unknown states fail closed.
53
+ */
54
+ export function resolveStellarGate(chainKey: SpokeChainKey | undefined, inputs: StellarGateInputs): StellarGateState {
55
+ const { statusCheck, trustlineCheck, isNativeToken } = inputs;
56
+
57
+ if (chainKey !== ChainKeys.STELLAR_MAINNET) return NOT_STELLAR;
58
+ const base = {
59
+ isStellar: true,
60
+ needsActivation: false,
61
+ needsFunding: false,
62
+ needsTrustline: false,
63
+ checkFailed: false,
64
+ };
65
+
66
+ // A failed read is unknown, not evidence that activation is needed.
67
+ if (statusCheck.isError) return { ...base, checkFailed: true, blocksAction: true };
68
+ const status = statusCheck.data;
69
+ if (statusCheck.isLoading || status === undefined) return { ...base, blocksAction: true };
70
+
71
+ if (!status.exists) return { ...base, needsActivation: true, blocksAction: true };
72
+
73
+ // Native XLM can fund an activated zero-balance account without a trustline.
74
+ if (isNativeToken) return { ...base, blocksAction: false };
75
+
76
+ if (trustlineCheck.isError) return { ...base, checkFailed: true, blocksAction: true };
77
+ if (unresolved(trustlineCheck)) return { ...base, blocksAction: true };
78
+
79
+ if (trustlineCheck.data === true) return { ...base, blocksAction: false };
80
+
81
+ if (!status.canAffordTrustline) return { ...base, needsFunding: true, blocksAction: true };
82
+
83
+ return { ...base, needsTrustline: true, blocksAction: true };
84
+ }