@sodax/dapp-kit 2.0.0 → 2.1.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +128 -115
- package/dist/index.d.ts +342 -12
- package/dist/index.mjs +405 -47
- package/package.json +2 -2
- package/src/hooks/_mutationContract.test.ts +5 -0
- package/src/hooks/backend/types.ts +1 -1
- package/src/hooks/bridge/useBridgeApprove.ts +2 -1
- package/src/hooks/bridgeApi/index.ts +13 -0
- package/src/hooks/bridgeApi/useBridgeApiAllowance.ts +42 -0
- package/src/hooks/bridgeApi/useBridgeApiApprove.ts +42 -0
- package/src/hooks/bridgeApi/useBridgeApiBridgeableAmount.ts +45 -0
- package/src/hooks/bridgeApi/useBridgeApiCreateBridgeIntent.ts +42 -0
- package/src/hooks/bridgeApi/useBridgeApiFee.ts +44 -0
- package/src/hooks/bridgeApi/useBridgeApiIsBridgeable.ts +45 -0
- package/src/hooks/bridgeApi/useBridgeApiSubmitTx.ts +50 -0
- package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.ts +60 -0
- package/src/hooks/bridgeApi/useBridgeApiTokens.ts +35 -0
- package/src/hooks/bridgeApi/useBridgeApiTokensByChain.ts +40 -0
- package/src/hooks/index.ts +2 -0
- package/src/hooks/migrate/useMigrationApprove.ts +1 -3
- package/src/hooks/mm/useWithdraw.ts +5 -1
- package/src/hooks/partner/useApproveToken.ts +1 -2
- package/src/hooks/shared/index.ts +2 -0
- package/src/hooks/shared/useEstablishTrustline.test.ts +89 -0
- package/src/hooks/shared/useEstablishTrustline.ts +72 -0
- package/src/hooks/shared/useRequestTrustline.test.ts +115 -0
- package/src/hooks/shared/useRequestTrustline.ts +41 -56
- package/src/hooks/shared/useSafeMutation.ts +1 -4
- package/src/hooks/shared/useStellarGate.test.ts +99 -0
- package/src/hooks/shared/useStellarGate.ts +102 -0
- package/src/hooks/shared/useStellarTrustlineCheck.test.ts +2 -2
- package/src/hooks/sponsoring/index.ts +4 -0
- package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +74 -0
- package/src/hooks/sponsoring/useActivateStellarAccount.ts +38 -0
- package/src/hooks/sponsoring/useSponsorConfig.test.ts +46 -0
- package/src/hooks/sponsoring/useSponsorConfig.ts +31 -0
- package/src/hooks/sponsoring/useStellarAccountActive.test.ts +50 -0
- package/src/hooks/sponsoring/useStellarAccountActive.ts +45 -0
- package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +90 -0
- package/src/hooks/sponsoring/useStellarAccountStatus.ts +57 -0
- package/src/hooks/staking/useStakingConfig.ts +1 -3
- package/src/hooks/staking/useStakingInfo.ts +4 -4
- package/src/hooks/staking/useUnstake.ts +5 -1
- package/src/hooks/swap/useCreateLimitOrder.ts +1 -2
- package/src/hooks/swap/useSwap.ts +1 -5
- package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +6 -3
- package/src/index.ts +1 -1
- package/src/providers/createSodaxQueryClient.ts +1 -5
- package/src/utils/dex-utils.ts +1 -4
- package/src/utils/index.ts +1 -0
- package/src/utils/stellarGate.test.ts +196 -0
- package/src/utils/stellarGate.ts +84 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
type MutationState = {
|
|
5
|
+
mutateAsync: (vars: unknown) => Promise<string>;
|
|
6
|
+
isPending: boolean;
|
|
7
|
+
isSuccess: boolean;
|
|
8
|
+
error: Error | null;
|
|
9
|
+
data: string | undefined;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
let mutation: MutationState;
|
|
13
|
+
|
|
14
|
+
const refSlots: Array<{ current: unknown }> = [];
|
|
15
|
+
let refCursor = 0;
|
|
16
|
+
|
|
17
|
+
// Only useRef and useCallback are needed, and call order is stable, so this replays React's
|
|
18
|
+
// slot semantics well enough to observe the deprecated hook across renders — no DOM, no renderer.
|
|
19
|
+
vi.mock('react', () => ({
|
|
20
|
+
useRef: (initial: unknown) => {
|
|
21
|
+
const slot = refSlots[refCursor] ?? { current: initial };
|
|
22
|
+
refSlots[refCursor] = slot;
|
|
23
|
+
refCursor += 1;
|
|
24
|
+
return slot;
|
|
25
|
+
},
|
|
26
|
+
useCallback: (fn: unknown) => fn,
|
|
27
|
+
}));
|
|
28
|
+
vi.mock('./useEstablishTrustline.js', () => ({ useEstablishTrustline: () => mutation }));
|
|
29
|
+
|
|
30
|
+
const { useRequestTrustline } = await import('./useRequestTrustline.js');
|
|
31
|
+
|
|
32
|
+
const TOKEN = 'CBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
|
|
33
|
+
|
|
34
|
+
const idle: MutationState = {
|
|
35
|
+
mutateAsync: async () => 'hash',
|
|
36
|
+
isPending: false,
|
|
37
|
+
isSuccess: false,
|
|
38
|
+
error: null,
|
|
39
|
+
data: undefined,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** One render of the hook, with the mutation in `state`. */
|
|
43
|
+
const render = (state: Partial<MutationState> = {}) => {
|
|
44
|
+
mutation = { ...idle, ...state };
|
|
45
|
+
refCursor = 0;
|
|
46
|
+
// The positional argument was ignored in 2.0.0 and still is; passed here because keeping it
|
|
47
|
+
// callable is the point of this wrapper.
|
|
48
|
+
return useRequestTrustline(TOKEN);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
beforeEach(() => {
|
|
52
|
+
refSlots.length = 0;
|
|
53
|
+
refCursor = 0;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('useRequestTrustline — 2.0.0 compatibility wrapper', () => {
|
|
57
|
+
it('exposes the released shape', () => {
|
|
58
|
+
const result = render();
|
|
59
|
+
|
|
60
|
+
expect(Object.keys(result).sort()).toEqual(['data', 'error', 'isLoading', 'isRequested', 'requestTrustline']);
|
|
61
|
+
expect(result.data).toBeNull();
|
|
62
|
+
expect(result.error).toBeNull();
|
|
63
|
+
expect(result.isLoading).toBe(false);
|
|
64
|
+
expect(result.isRequested).toBe(false);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('maps isLoading to the mutation pending state', () => {
|
|
68
|
+
expect(render({ isPending: true }).isLoading).toBe(true);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('surfaces the mutation error', () => {
|
|
72
|
+
const error = new Error('trustline failed');
|
|
73
|
+
|
|
74
|
+
expect(render({ error }).error).toBe(error);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('LATCHES isRequested and data, so a failed retry cannot un-report a live trustline', () => {
|
|
78
|
+
const first = render({ isSuccess: true, data: 'hash' });
|
|
79
|
+
expect(first.isRequested).toBe(true);
|
|
80
|
+
expect(first.data).toBe('hash');
|
|
81
|
+
|
|
82
|
+
// React Query clears data and isSuccess once the next attempt starts; 2.0.0 held both
|
|
83
|
+
// in component state and never cleared them.
|
|
84
|
+
const retrying = render({ isPending: true });
|
|
85
|
+
expect(retrying.isRequested).toBe(true);
|
|
86
|
+
expect(retrying.data).toBe('hash');
|
|
87
|
+
|
|
88
|
+
const failed = render({ error: new Error('nope') });
|
|
89
|
+
expect(failed.isRequested).toBe(true);
|
|
90
|
+
expect(failed.data).toBe('hash');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('forwards vars to the canonical mutation and resolves to the hash', async () => {
|
|
94
|
+
const mutateAsync = vi.fn(async () => 'hash');
|
|
95
|
+
const vars = {
|
|
96
|
+
token: TOKEN,
|
|
97
|
+
amount: 1_000_000n,
|
|
98
|
+
srcChainKey: ChainKeys.STELLAR_MAINNET,
|
|
99
|
+
walletProvider: { getWalletAddress: async () => 'G…' } as never,
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
await expect(render({ mutateAsync }).requestTrustline(vars)).resolves.toBe('hash');
|
|
103
|
+
expect(mutateAsync).toHaveBeenCalledWith(vars);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('rejects with an Error even when the mutation throws a non-Error', async () => {
|
|
107
|
+
const rejecting = render({
|
|
108
|
+
mutateAsync: async () => {
|
|
109
|
+
throw 'string failure';
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
await expect(rejecting.requestTrustline({} as never)).rejects.toThrow('Unknown error occurred');
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -1,70 +1,55 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import type { IStellarWalletProvider, StellarChainKey } from '@sodax/sdk';
|
|
4
|
-
import { useSodaxContext } from './useSodaxContext.js';
|
|
1
|
+
import { useCallback, useRef } from 'react';
|
|
2
|
+
import { useEstablishTrustline, type UseEstablishTrustlineVars } from './useEstablishTrustline.js';
|
|
5
3
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
}) => Promise<string>;
|
|
4
|
+
/**
|
|
5
|
+
* The shape released in 2.0.0. Declared explicitly so a change to it fails
|
|
6
|
+
* `checkTs` here rather than silently breaking consumers.
|
|
7
|
+
*/
|
|
8
|
+
type ReleasedRequestTrustline = {
|
|
9
|
+
requestTrustline: (params: UseEstablishTrustlineVars) => Promise<string>;
|
|
13
10
|
isLoading: boolean;
|
|
14
11
|
isRequested: boolean;
|
|
15
12
|
error: Error | null;
|
|
16
13
|
data: string | null;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Establish a Stellar trustline.
|
|
18
|
+
*
|
|
19
|
+
* @deprecated Use {@link useEstablishTrustline}, the canonical mutation hook, which exposes
|
|
20
|
+
* `mutate` / `mutateAsync` / `mutateAsyncSafe` and accepts `mutationOptions`. This wrapper
|
|
21
|
+
* preserves the shape released in 2.0.0 and will be removed in the next major.
|
|
22
|
+
*
|
|
23
|
+
* @param token - Ignored, as it was in 2.0.0. Accepted only so existing call sites compile.
|
|
24
|
+
*/
|
|
25
|
+
export function useRequestTrustline(token?: string | undefined): ReleasedRequestTrustline {
|
|
26
|
+
const { mutateAsync, isPending, isSuccess, error, data } = useEstablishTrustline();
|
|
27
|
+
|
|
28
|
+
// 2.0.0 held `isRequested` and `data` in component state and never cleared them, whereas
|
|
29
|
+
// React Query resets its equivalents when the next attempt starts. Latch to keep the
|
|
30
|
+
// released semantics: a retry that fails must not un-report the trustline that succeeded.
|
|
31
|
+
const requested = useRef(false);
|
|
32
|
+
const lastData = useRef<string | null>(null);
|
|
33
|
+
if (isSuccess) requested.current = true;
|
|
34
|
+
if (data !== undefined) lastData.current = data;
|
|
24
35
|
|
|
25
36
|
const requestTrustline = useCallback(
|
|
26
|
-
async ({
|
|
27
|
-
token,
|
|
28
|
-
amount,
|
|
29
|
-
srcChainKey,
|
|
30
|
-
walletProvider,
|
|
31
|
-
}: {
|
|
32
|
-
token: string;
|
|
33
|
-
amount: bigint;
|
|
34
|
-
srcChainKey: StellarChainKey;
|
|
35
|
-
walletProvider: IStellarWalletProvider;
|
|
36
|
-
}): Promise<string> => {
|
|
37
|
-
if (!token || !amount) {
|
|
38
|
-
const error = new Error('Token and amount are required');
|
|
39
|
-
setError(error);
|
|
40
|
-
throw error;
|
|
41
|
-
}
|
|
42
|
-
setIsLoading(true);
|
|
43
|
-
setError(null);
|
|
37
|
+
async (params: UseEstablishTrustlineVars): Promise<string> => {
|
|
44
38
|
try {
|
|
45
|
-
|
|
46
|
-
const result = await sodax.spoke.stellar.requestTrustline<false>({
|
|
47
|
-
raw: false,
|
|
48
|
-
srcChainKey,
|
|
49
|
-
srcAddress,
|
|
50
|
-
token,
|
|
51
|
-
amount,
|
|
52
|
-
walletProvider,
|
|
53
|
-
});
|
|
54
|
-
setData(result);
|
|
55
|
-
setIsRequested(true);
|
|
56
|
-
queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck', srcChainKey, token, srcAddress] });
|
|
57
|
-
return result;
|
|
39
|
+
return await mutateAsync(params);
|
|
58
40
|
} catch (err) {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
throw error;
|
|
62
|
-
} finally {
|
|
63
|
-
setIsLoading(false);
|
|
41
|
+
// 2.0.0 guaranteed this callback rejects with an `Error`.
|
|
42
|
+
throw err instanceof Error ? err : new Error('Unknown error occurred');
|
|
64
43
|
}
|
|
65
44
|
},
|
|
66
|
-
[
|
|
45
|
+
[mutateAsync],
|
|
67
46
|
);
|
|
68
47
|
|
|
69
|
-
return {
|
|
48
|
+
return {
|
|
49
|
+
requestTrustline,
|
|
50
|
+
isLoading: isPending,
|
|
51
|
+
isRequested: requested.current,
|
|
52
|
+
error,
|
|
53
|
+
data: lastData.current,
|
|
54
|
+
};
|
|
70
55
|
}
|
|
@@ -30,10 +30,7 @@ export type SafeUseMutationResult<TData, TError, TVars, TContext = unknown> = Us
|
|
|
30
30
|
* `if (!hasAllowance) await approve(...); await action(...)` chains where the user-reject
|
|
31
31
|
* case is the modal failure mode, not an exceptional one.
|
|
32
32
|
*/
|
|
33
|
-
mutateAsyncSafe: (
|
|
34
|
-
vars: TVars,
|
|
35
|
-
options?: MutateOptions<TData, TError, TVars, TContext>,
|
|
36
|
-
) => Promise<Result<TData>>;
|
|
33
|
+
mutateAsyncSafe: (vars: TVars, options?: MutateOptions<TData, TError, TVars, TContext>) => Promise<Result<TData>>;
|
|
37
34
|
};
|
|
38
35
|
|
|
39
36
|
/**
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
const statusCheck = vi.fn();
|
|
5
|
+
const trustlineCheck = vi.fn();
|
|
6
|
+
const requiresTrustline = vi.fn(() => true);
|
|
7
|
+
|
|
8
|
+
// Stubbing the child hooks keeps this a DOM-free assertion on the params the gate builds —
|
|
9
|
+
// the resolver itself is covered by utils/stellarGate.test.ts.
|
|
10
|
+
vi.mock('../sponsoring/useStellarAccountStatus.js', () => ({
|
|
11
|
+
useStellarAccountStatus: (args: unknown) => statusCheck(args),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('./useStellarTrustlineCheck.js', () => ({
|
|
14
|
+
useStellarTrustlineCheck: (args: unknown) => trustlineCheck(args),
|
|
15
|
+
}));
|
|
16
|
+
vi.mock('../sponsoring/useActivateStellarAccount.js', () => ({
|
|
17
|
+
useActivateStellarAccount: () => ({ mutateAsyncSafe: vi.fn(), isPending: false }),
|
|
18
|
+
}));
|
|
19
|
+
vi.mock('./useEstablishTrustline.js', () => ({
|
|
20
|
+
useEstablishTrustline: () => ({ mutateAsyncSafe: vi.fn(), isPending: false }),
|
|
21
|
+
}));
|
|
22
|
+
vi.mock('./useSodaxContext.js', () => ({
|
|
23
|
+
useSodaxContext: () => ({ sodax: { spoke: { stellar: { requiresTrustline } } } }),
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
const { useStellarGate } = await import('./useStellarGate.js');
|
|
27
|
+
|
|
28
|
+
const TOKEN = 'CBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
|
|
29
|
+
const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
|
30
|
+
|
|
31
|
+
const idle = { isLoading: false, isError: false, data: undefined, error: null, refetch: vi.fn() };
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Drive the gate with a given account-status result. An absent `walletAddress` is what
|
|
35
|
+
* leaves `useStellarTrustlineCheck` disabled, so it stands in for "no Horizon read".
|
|
36
|
+
*/
|
|
37
|
+
const run = (status: unknown, overrides: Record<string, unknown> = {}) => {
|
|
38
|
+
statusCheck.mockReturnValue({ ...idle, ...(status as object) });
|
|
39
|
+
trustlineCheck.mockReturnValue(idle);
|
|
40
|
+
|
|
41
|
+
const gate = useStellarGate({
|
|
42
|
+
dstChainKey: ChainKeys.STELLAR_MAINNET,
|
|
43
|
+
token: TOKEN,
|
|
44
|
+
amount: 1_000_000n,
|
|
45
|
+
address: ADDRESS,
|
|
46
|
+
walletProvider: undefined,
|
|
47
|
+
...overrides,
|
|
48
|
+
} as never);
|
|
49
|
+
|
|
50
|
+
return { gate, trustlineAddress: trustlineCheck.mock.calls[0]?.[0]?.params?.walletAddress };
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
beforeEach(() => {
|
|
54
|
+
statusCheck.mockReset();
|
|
55
|
+
trustlineCheck.mockReset();
|
|
56
|
+
requiresTrustline.mockReset().mockReturnValue(true);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('useStellarGate — the trustline read is gated on account existence', () => {
|
|
60
|
+
it('does NOT read the trustline for an account that does not exist', () => {
|
|
61
|
+
// hasSufficientTrustline 404s on a missing account, and React Query would retry it.
|
|
62
|
+
const { gate, trustlineAddress } = run({ data: { exists: false, canAffordTrustline: false } });
|
|
63
|
+
|
|
64
|
+
expect(trustlineAddress).toBeUndefined();
|
|
65
|
+
// The gate still reaches the right conclusion without the trustline read.
|
|
66
|
+
expect(gate.needsActivation).toBe(true);
|
|
67
|
+
expect(gate.blocksAction).toBe(true);
|
|
68
|
+
expect(gate.checkFailed).toBe(false);
|
|
69
|
+
// No spurious error while the UI is showing "activate".
|
|
70
|
+
expect(gate.error).toBeUndefined();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('does NOT read the trustline while account status is still loading', () => {
|
|
74
|
+
expect(run({ isLoading: true }).trustlineAddress).toBeUndefined();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('does NOT read the trustline when the account-status read failed', () => {
|
|
78
|
+
const { gate, trustlineAddress } = run({ isError: true, error: new Error('horizon down') });
|
|
79
|
+
|
|
80
|
+
expect(trustlineAddress).toBeUndefined();
|
|
81
|
+
expect(gate.checkFailed).toBe(true);
|
|
82
|
+
expect(gate.blocksAction).toBe(true);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('reads the trustline once the account is known to exist', () => {
|
|
86
|
+
expect(run({ data: { exists: true, canAffordTrustline: true } }).trustlineAddress).toBe(ADDRESS);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('does not read a Stellar trustline for a non-Stellar destination', () => {
|
|
90
|
+
const { gate, trustlineAddress } = run(
|
|
91
|
+
{ data: { exists: true, canAffordTrustline: true } },
|
|
92
|
+
{ dstChainKey: ChainKeys.SONIC },
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
expect(trustlineAddress).toBeUndefined();
|
|
96
|
+
expect(gate.isStellar).toBe(false);
|
|
97
|
+
expect(gate.blocksAction).toBe(false);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
@@ -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
|
+
}
|
|
@@ -43,8 +43,8 @@ describe('getStellarTrustlineCheckQueryOptions — query key', () => {
|
|
|
43
43
|
);
|
|
44
44
|
});
|
|
45
45
|
|
|
46
|
-
it('shares the
|
|
47
|
-
//
|
|
46
|
+
it('shares the useEstablishTrustline invalidation prefix (chain, token, account) across every amount', () => {
|
|
47
|
+
// useEstablishTrustline invalidates ['shared','stellarTrustlineCheck', srcChainKey, token, srcAddress];
|
|
48
48
|
// amount sits after that prefix, so the invalidation covers the account's checks at any amount.
|
|
49
49
|
const invalidationKey = ['shared', 'stellarTrustlineCheck', STELLAR, TOKEN, WALLET_A];
|
|
50
50
|
for (const amount of [100n, 10_000n]) {
|
|
@@ -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
|
+
}
|