@sodax/dapp-kit 2.4.0-rc.1 → 2.4.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 +10 -2
- package/dist/index.d.ts +136 -5
- package/dist/index.mjs +191 -7
- package/package.json +2 -2
- package/src/hooks/_mutationContract.test.ts +1 -0
- package/src/hooks/shared/index.ts +4 -0
- package/src/hooks/shared/useEstablishXrpTrustline.test.ts +113 -0
- package/src/hooks/shared/useEstablishXrpTrustline.ts +65 -0
- package/src/hooks/shared/useXrpDestinationCheck.ts +75 -0
- package/src/hooks/shared/useXrpGate.test.ts +118 -0
- package/src/hooks/shared/useXrpGate.ts +81 -0
- package/src/hooks/shared/useXrpTrustlineReserveCheck.ts +45 -0
- package/src/hooks/swap/useSwapLifecycle.test.ts +46 -0
- package/src/hooks/swap/useSwapLifecycle.ts +29 -5
- package/src/utils/index.ts +1 -0
- package/src/utils/swapLifecycle.test.ts +35 -0
- package/src/utils/swapLifecycle.ts +15 -3
- package/src/utils/xrpGate.test.ts +112 -0
- package/src/utils/xrpGate.ts +72 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { ChainKeys, IndeterminateOutcomeError } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
const invalidateQueries = vi.fn();
|
|
5
|
+
const requestTrustline = vi.fn();
|
|
6
|
+
|
|
7
|
+
// The hook is a pure options builder around useSafeMutation, so stubbing the React-side imports
|
|
8
|
+
// lets the real mutationFn and onSuccess run without a DOM.
|
|
9
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
|
|
10
|
+
vi.mock('./useSodaxContext.js', () => ({
|
|
11
|
+
useSodaxContext: () => ({ sodax: { spoke: { xrp: { requestTrustline } } } }),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('./useSafeMutation.js', () => ({ useSafeMutation: (options: unknown) => options }));
|
|
14
|
+
|
|
15
|
+
const { useEstablishXrpTrustline } = await import('./useEstablishXrpTrustline.js');
|
|
16
|
+
|
|
17
|
+
const TOKEN = 'rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De';
|
|
18
|
+
const ADDRESS = 'rJB8dmrf4JxkLKHPUfdxyPwpXMyxjkQsyG';
|
|
19
|
+
|
|
20
|
+
type OnSuccess = (data: string, vars: unknown, ctx: unknown) => Promise<void>;
|
|
21
|
+
type MutationFn = (vars: unknown) => Promise<string>;
|
|
22
|
+
|
|
23
|
+
const vars = (getWalletAddress: () => Promise<string>) => ({ token: TOKEN, walletProvider: { getWalletAddress } });
|
|
24
|
+
|
|
25
|
+
// The stubbed useSafeMutation returns its options, which the hook's declared return type does not describe.
|
|
26
|
+
const optionsOf = (retry?: number) =>
|
|
27
|
+
useEstablishXrpTrustline({ mutationOptions: { retry } }) as unknown as {
|
|
28
|
+
onSuccess: OnSuccess;
|
|
29
|
+
mutationFn: MutationFn;
|
|
30
|
+
retry: (failureCount: number, error: Error) => boolean;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const invalidatedKeys = () => invalidateQueries.mock.calls.map(([arg]) => arg.queryKey);
|
|
34
|
+
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
invalidateQueries.mockReset();
|
|
37
|
+
requestTrustline.mockReset();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe('useEstablishXrpTrustline', () => {
|
|
41
|
+
it('requests the trustline for the wallet account and returns the validated hash', async () => {
|
|
42
|
+
requestTrustline.mockResolvedValue({ ok: true, value: 'hash' });
|
|
43
|
+
const request = vars(async () => ADDRESS);
|
|
44
|
+
|
|
45
|
+
await expect(optionsOf().mutationFn(request)).resolves.toBe('hash');
|
|
46
|
+
expect(requestTrustline).toHaveBeenCalledWith({
|
|
47
|
+
srcAddress: ADDRESS,
|
|
48
|
+
token: TOKEN,
|
|
49
|
+
walletProvider: request.walletProvider,
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('refuses, before signing, a wallet connected to another account than the one that needs the line', async () => {
|
|
54
|
+
const request = { ...vars(async () => ADDRESS), address: 'rOtherAccount1111111111111111111111' };
|
|
55
|
+
|
|
56
|
+
await expect(optionsOf().mutationFn(request)).rejects.toThrow(/is not rOtherAccount/);
|
|
57
|
+
expect(requestTrustline).not.toHaveBeenCalled();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('proceeds when the wallet controls the account that needs the line', async () => {
|
|
61
|
+
requestTrustline.mockResolvedValue({ ok: true, value: 'hash' });
|
|
62
|
+
|
|
63
|
+
await expect(optionsOf().mutationFn({ ...vars(async () => ADDRESS), address: ADDRESS })).resolves.toBe('hash');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('rejects with the SDK error, so mutateAsyncSafe reports it', async () => {
|
|
67
|
+
const error = new Error('GemWallet transaction was rejected by the user');
|
|
68
|
+
requestTrustline.mockResolvedValue({ ok: false, error });
|
|
69
|
+
|
|
70
|
+
await expect(optionsOf().mutationFn(vars(async () => ADDRESS))).rejects.toBe(error);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('invalidates the destination check for this account, the reserve check, and XRPL balances', async () => {
|
|
74
|
+
await optionsOf().onSuccess(
|
|
75
|
+
'hash',
|
|
76
|
+
vars(async () => ADDRESS),
|
|
77
|
+
undefined,
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
expect(invalidatedKeys()).toEqual([
|
|
81
|
+
['shared', 'xrpDestinationCheck', ChainKeys.XRP_MAINNET, TOKEN, ADDRESS],
|
|
82
|
+
['shared', 'xrpTrustlineReserveCheck'],
|
|
83
|
+
['shared', 'balances', ChainKeys.XRP_MAINNET],
|
|
84
|
+
['shared', 'xBalances', ChainKeys.XRP_MAINNET],
|
|
85
|
+
]);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('invalidates the checked account even after the wallet switched to another one', async () => {
|
|
89
|
+
await optionsOf().onSuccess(
|
|
90
|
+
'hash',
|
|
91
|
+
{ ...vars(async () => 'rOtherAccount1111111111111111111111'), address: ADDRESS },
|
|
92
|
+
undefined,
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
expect(invalidatedKeys()[0]).toEqual(['shared', 'xrpDestinationCheck', ChainKeys.XRP_MAINNET, TOKEN, ADDRESS]);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('never retries a TrustSet that may have been sent, since each one costs a fee', () => {
|
|
99
|
+
const { retry } = optionsOf(3);
|
|
100
|
+
|
|
101
|
+
expect(retry(0, new IndeterminateOutcomeError('outcome unknown', { cause: undefined, txHash: 'AB' }))).toBe(false);
|
|
102
|
+
expect(retry(0, new Error('node unreachable'))).toBe(true);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('still invalidates when the wallet fails right after the TrustSet validated', async () => {
|
|
106
|
+
const locked = vars(async () => {
|
|
107
|
+
throw new Error('wallet is locked');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
await expect(optionsOf().onSuccess('hash', locked, undefined)).resolves.toBeUndefined();
|
|
111
|
+
expect(invalidatedKeys()[0]).toEqual(['shared', 'xrpDestinationCheck']);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { ChainKeys, type IXrpWalletProvider } from '@sodax/sdk';
|
|
2
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
3
|
+
import { invalidateBalances } from './invalidateBalances.js';
|
|
4
|
+
import { retryBeforeSubmission } from './retryBeforeSubmission.js';
|
|
5
|
+
import type { MutationHookParams } from './types.js';
|
|
6
|
+
import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
|
|
7
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
8
|
+
import { unwrapResult } from './unwrapResult.js';
|
|
9
|
+
|
|
10
|
+
export type UseEstablishXrpTrustlineVars = {
|
|
11
|
+
/** The XRPL issued token to hold. */
|
|
12
|
+
token: string;
|
|
13
|
+
/** The account that needs the trustline. When set, the mutation refuses a wallet connected to another account. */
|
|
14
|
+
address?: string;
|
|
15
|
+
walletProvider: IXrpWalletProvider;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Create the XRPL trustline the connected account needs to hold `token`, or raise its limit. Resolves to the
|
|
20
|
+
* TrustSet hash once it validates. The account pays its fee and, unless the ledger waives it, an owner reserve: check with
|
|
21
|
+
* {@link useXrpTrustlineReserveCheck}, or use {@link useXrpGate}, before asking the user to sign.
|
|
22
|
+
*/
|
|
23
|
+
export function useEstablishXrpTrustline({
|
|
24
|
+
mutationOptions,
|
|
25
|
+
}: MutationHookParams<string, UseEstablishXrpTrustlineVars> = {}): SafeUseMutationResult<
|
|
26
|
+
string,
|
|
27
|
+
Error,
|
|
28
|
+
UseEstablishXrpTrustlineVars
|
|
29
|
+
> {
|
|
30
|
+
const { sodax } = useSodaxContext();
|
|
31
|
+
const queryClient = useQueryClient();
|
|
32
|
+
|
|
33
|
+
return useSafeMutation<string, Error, UseEstablishXrpTrustlineVars>({
|
|
34
|
+
mutationKey: ['shared', 'establishXrpTrustline'],
|
|
35
|
+
...mutationOptions,
|
|
36
|
+
// Each TrustSet costs a fee, so one that may have been sent is never signed again automatically.
|
|
37
|
+
retry: retryBeforeSubmission(
|
|
38
|
+
mutationOptions?.retry ??
|
|
39
|
+
queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['shared', 'establishXrpTrustline'])?.retry ??
|
|
40
|
+
queryClient.getDefaultOptions?.().mutations?.retry,
|
|
41
|
+
),
|
|
42
|
+
mutationFn: async ({ token, address, walletProvider }): Promise<string> => {
|
|
43
|
+
const srcAddress = await walletProvider.getWalletAddress();
|
|
44
|
+
if (address !== undefined && address !== srcAddress) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`The connected XRPL account ${srcAddress} is not ${address}, which needs the trustline — connect ${address} to add it`,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
return unwrapResult(await sodax.spoke.xrp.requestTrustline<false>({ srcAddress, token, walletProvider }));
|
|
50
|
+
},
|
|
51
|
+
onSuccess: async (data, vars, ctx) => {
|
|
52
|
+
// The checked account, not whichever account the wallet is on by now.
|
|
53
|
+
const address = vars.address ?? (await vars.walletProvider.getWalletAddress().catch(() => undefined));
|
|
54
|
+
queryClient.invalidateQueries({
|
|
55
|
+
queryKey: address
|
|
56
|
+
? ['shared', 'xrpDestinationCheck', ChainKeys.XRP_MAINNET, vars.token, address]
|
|
57
|
+
: ['shared', 'xrpDestinationCheck'],
|
|
58
|
+
});
|
|
59
|
+
// A new line locks an owner reserve, which changes what the next trustline can afford.
|
|
60
|
+
queryClient.invalidateQueries({ queryKey: ['shared', 'xrpTrustlineReserveCheck'] });
|
|
61
|
+
invalidateBalances(queryClient, ChainKeys.XRP_MAINNET);
|
|
62
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ChainKeys, type Sodax, type SpokeChainKey, type XrpDestinationReadiness } from '@sodax/sdk';
|
|
2
|
+
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
3
|
+
import type { ReadHookParams } from './types.js';
|
|
4
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
5
|
+
|
|
6
|
+
export type UseXrpDestinationCheckParams = ReadHookParams<
|
|
7
|
+
XrpDestinationReadiness,
|
|
8
|
+
{
|
|
9
|
+
chainId: SpokeChainKey | undefined;
|
|
10
|
+
token: string | undefined;
|
|
11
|
+
/** The XRPL account that receives the payout. */
|
|
12
|
+
address: string | undefined;
|
|
13
|
+
/** The least that arrives, in the token's decimals. */
|
|
14
|
+
amount: bigint | undefined;
|
|
15
|
+
/** The most that can arrive, which the trustline needs room for. Defaults to `amount`. */
|
|
16
|
+
maxAmount?: bigint;
|
|
17
|
+
}
|
|
18
|
+
>;
|
|
19
|
+
|
|
20
|
+
type XrpDestinationReader = { spoke: { xrp: Pick<Sodax['spoke']['xrp'], 'checkDestination'> } };
|
|
21
|
+
|
|
22
|
+
export function getXrpDestinationCheckQueryOptions({
|
|
23
|
+
sodax,
|
|
24
|
+
chainId,
|
|
25
|
+
token,
|
|
26
|
+
address,
|
|
27
|
+
amount,
|
|
28
|
+
maxAmount,
|
|
29
|
+
}: {
|
|
30
|
+
sodax: XrpDestinationReader;
|
|
31
|
+
chainId: SpokeChainKey | undefined;
|
|
32
|
+
token: string | undefined;
|
|
33
|
+
address: string | undefined;
|
|
34
|
+
amount: bigint | undefined;
|
|
35
|
+
maxAmount?: bigint;
|
|
36
|
+
}) {
|
|
37
|
+
return {
|
|
38
|
+
queryKey: [
|
|
39
|
+
'shared',
|
|
40
|
+
'xrpDestinationCheck',
|
|
41
|
+
chainId,
|
|
42
|
+
token,
|
|
43
|
+
address,
|
|
44
|
+
amount?.toString(),
|
|
45
|
+
maxAmount?.toString(),
|
|
46
|
+
] as const,
|
|
47
|
+
queryFn: async (): Promise<XrpDestinationReadiness> => {
|
|
48
|
+
if (!address || !token || amount === undefined) throw new Error('address, token and amount are required');
|
|
49
|
+
return sodax.spoke.xrp.checkDestination({ address, token, amount, maxAmount });
|
|
50
|
+
},
|
|
51
|
+
enabled: chainId === ChainKeys.XRP_MAINNET && !!address && !!token && amount !== undefined,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Whether an XRPL account can receive `amount` of `token` (up to `maxAmount`), and if not, why. It reads the
|
|
57
|
+
* same ledger state a swap or withdrawal is refused on before signing.
|
|
58
|
+
*/
|
|
59
|
+
export function useXrpDestinationCheck({
|
|
60
|
+
params,
|
|
61
|
+
queryOptions,
|
|
62
|
+
}: UseXrpDestinationCheckParams = {}): UseQueryResult<XrpDestinationReadiness, Error> {
|
|
63
|
+
const { sodax } = useSodaxContext();
|
|
64
|
+
return useQuery<XrpDestinationReadiness, Error>({
|
|
65
|
+
...getXrpDestinationCheckQueryOptions({
|
|
66
|
+
sodax,
|
|
67
|
+
chainId: params?.chainId,
|
|
68
|
+
token: params?.token,
|
|
69
|
+
address: params?.address,
|
|
70
|
+
amount: params?.amount,
|
|
71
|
+
maxAmount: params?.maxAmount,
|
|
72
|
+
}),
|
|
73
|
+
...queryOptions,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
const destinationCheck = vi.fn();
|
|
5
|
+
const reserveCheck = vi.fn();
|
|
6
|
+
const establish = vi.fn();
|
|
7
|
+
const requiresTrustline = vi.fn(() => true);
|
|
8
|
+
|
|
9
|
+
// Stubbing the child hooks keeps this a DOM-free assertion on the params the gate builds;
|
|
10
|
+
// the resolver itself is covered by utils/xrpGate.test.ts.
|
|
11
|
+
vi.mock('./useXrpDestinationCheck.js', () => ({
|
|
12
|
+
useXrpDestinationCheck: (args: unknown) => destinationCheck(args),
|
|
13
|
+
}));
|
|
14
|
+
vi.mock('./useXrpTrustlineReserveCheck.js', () => ({
|
|
15
|
+
useXrpTrustlineReserveCheck: (args: unknown) => reserveCheck(args),
|
|
16
|
+
}));
|
|
17
|
+
vi.mock('./useEstablishXrpTrustline.js', () => ({
|
|
18
|
+
useEstablishXrpTrustline: () => ({ mutateAsyncSafe: establish, isPending: false }),
|
|
19
|
+
}));
|
|
20
|
+
vi.mock('./useSodaxContext.js', () => ({
|
|
21
|
+
useSodaxContext: () => ({ sodax: { spoke: { xrp: { requiresTrustline } } } }),
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
const { useXrpGate } = await import('./useXrpGate.js');
|
|
25
|
+
|
|
26
|
+
const TOKEN = 'rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De';
|
|
27
|
+
const ADDRESS = 'rJB8dmrf4JxkLKHPUfdxyPwpXMyxjkQsyG';
|
|
28
|
+
const XRP_WALLET = { chainType: 'XRP' };
|
|
29
|
+
|
|
30
|
+
const idle = { isLoading: false, isError: false, data: undefined, error: null, refetch: vi.fn() };
|
|
31
|
+
|
|
32
|
+
const run = (readiness: unknown, overrides: Record<string, unknown> = {}) => {
|
|
33
|
+
destinationCheck.mockReturnValue({ ...idle, data: readiness });
|
|
34
|
+
reserveCheck.mockReturnValue({ ...idle, data: true });
|
|
35
|
+
const gate = useXrpGate({
|
|
36
|
+
dstChainKey: ChainKeys.XRP_MAINNET,
|
|
37
|
+
token: TOKEN,
|
|
38
|
+
address: ADDRESS,
|
|
39
|
+
amount: 1_000_000n,
|
|
40
|
+
maxAmount: 2_000_000n,
|
|
41
|
+
walletProvider: XRP_WALLET,
|
|
42
|
+
...overrides,
|
|
43
|
+
} as never);
|
|
44
|
+
return {
|
|
45
|
+
gate,
|
|
46
|
+
destinationParams: destinationCheck.mock.calls[0]?.[0]?.params,
|
|
47
|
+
reserveParams: reserveCheck.mock.calls[0]?.[0]?.params,
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
beforeEach(() => {
|
|
52
|
+
destinationCheck.mockReset();
|
|
53
|
+
reserveCheck.mockReset();
|
|
54
|
+
establish.mockReset();
|
|
55
|
+
requiresTrustline.mockReset().mockReturnValue(true);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe('useXrpGate', () => {
|
|
59
|
+
it('checks the destination with the amount and the most that can arrive', () => {
|
|
60
|
+
const { destinationParams } = run({ ready: true });
|
|
61
|
+
|
|
62
|
+
expect(destinationParams).toEqual({
|
|
63
|
+
chainId: ChainKeys.XRP_MAINNET,
|
|
64
|
+
token: TOKEN,
|
|
65
|
+
address: ADDRESS,
|
|
66
|
+
amount: 1_000_000n,
|
|
67
|
+
maxAmount: 2_000_000n,
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('reads nothing for native XRP or another chain', () => {
|
|
72
|
+
requiresTrustline.mockReturnValue(false);
|
|
73
|
+
expect(run(undefined).destinationParams?.chainId).toBeUndefined();
|
|
74
|
+
|
|
75
|
+
requiresTrustline.mockReturnValue(true);
|
|
76
|
+
destinationCheck.mockReset();
|
|
77
|
+
expect(run(undefined, { dstChainKey: ChainKeys.STELLAR_MAINNET }).destinationParams?.chainId).toBeUndefined();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('reads the reserve only once the trustline is known to need setting', () => {
|
|
81
|
+
expect(run({ ready: true }).reserveParams).toEqual({ token: undefined, address: undefined });
|
|
82
|
+
|
|
83
|
+
reserveCheck.mockReset();
|
|
84
|
+
destinationCheck.mockReset();
|
|
85
|
+
expect(run({ ready: false, reason: 'issuer_frozen' }).reserveParams).toEqual({
|
|
86
|
+
token: undefined,
|
|
87
|
+
address: undefined,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
reserveCheck.mockReset();
|
|
91
|
+
destinationCheck.mockReset();
|
|
92
|
+
const { gate, reserveParams } = run({ ready: false, reason: 'no_trustline' });
|
|
93
|
+
expect(reserveParams).toEqual({ token: TOKEN, address: ADDRESS });
|
|
94
|
+
expect(gate.needsTrustline).toBe(true);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('requests the trustline with the XRPL destination wallet only', async () => {
|
|
98
|
+
establish.mockResolvedValue({ ok: true, value: 'hash' });
|
|
99
|
+
const { gate } = run({ ready: false, reason: 'trustline_limit' });
|
|
100
|
+
|
|
101
|
+
await expect(gate.requestTrustline()).resolves.toEqual({ ok: true, value: 'hash' });
|
|
102
|
+
// The checked recipient travels with the request, so the mutation can refuse another connected account.
|
|
103
|
+
expect(establish).toHaveBeenCalledWith({ token: TOKEN, address: ADDRESS, walletProvider: XRP_WALLET });
|
|
104
|
+
|
|
105
|
+
establish.mockReset();
|
|
106
|
+
const { gate: evmWallet } = run({ ready: false, reason: 'no_trustline' }, { walletProvider: { chainType: 'EVM' } });
|
|
107
|
+
await expect(evmWallet.requestTrustline()).resolves.toBeUndefined();
|
|
108
|
+
expect(establish).not.toHaveBeenCalled();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('surfaces a refusal no trustline fixes as blockedReason', () => {
|
|
112
|
+
const { gate } = run({ ready: false, reason: 'trustline_unauthorized' });
|
|
113
|
+
|
|
114
|
+
expect(gate.blockedReason).toBe('trustline_unauthorized');
|
|
115
|
+
expect(gate.needsTrustline).toBe(false);
|
|
116
|
+
expect(gate.blocksAction).toBe(true);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { ChainKeys, type GetWalletProviderType, type Result, type SpokeChainKey } from '@sodax/sdk';
|
|
2
|
+
import { resolveXrpGate, type XrpGateState } from '../../utils/xrpGate.js';
|
|
3
|
+
import { useEstablishXrpTrustline } from './useEstablishXrpTrustline.js';
|
|
4
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
5
|
+
import { useXrpDestinationCheck } from './useXrpDestinationCheck.js';
|
|
6
|
+
import { useXrpTrustlineReserveCheck } from './useXrpTrustlineReserveCheck.js';
|
|
7
|
+
|
|
8
|
+
export interface UseXrpGateParams {
|
|
9
|
+
dstChainKey: SpokeChainKey | undefined;
|
|
10
|
+
token: string | undefined;
|
|
11
|
+
/** The XRPL account that receives the payout. */
|
|
12
|
+
address: string | undefined;
|
|
13
|
+
/** The least that arrives, in the token's decimals. */
|
|
14
|
+
amount: bigint | undefined;
|
|
15
|
+
/** The most that can arrive, which the trustline needs room for. Defaults to `amount`. */
|
|
16
|
+
maxAmount?: bigint;
|
|
17
|
+
/** Must control `address`: `requestTrustline` refuses, before signing, a wallet connected to another account. */
|
|
18
|
+
walletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface XrpGate extends XrpGateState {
|
|
22
|
+
isChecking: boolean;
|
|
23
|
+
/** Surface when `checkFailed` is true. */
|
|
24
|
+
error: Error | undefined;
|
|
25
|
+
retry: () => void;
|
|
26
|
+
isRequestingTrustline: boolean;
|
|
27
|
+
/** Returns `undefined` when required inputs are missing. */
|
|
28
|
+
requestTrustline: () => Promise<Result<string> | undefined>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Gate XRPL delivery of an issued token on a trustline with room for the payout, and on enough spendable XRP
|
|
33
|
+
* to set one. Refusals the user's trustline cannot fix surface as `blockedReason`.
|
|
34
|
+
*/
|
|
35
|
+
export function useXrpGate({
|
|
36
|
+
dstChainKey,
|
|
37
|
+
token,
|
|
38
|
+
address,
|
|
39
|
+
amount,
|
|
40
|
+
maxAmount,
|
|
41
|
+
walletProvider,
|
|
42
|
+
}: UseXrpGateParams): XrpGate {
|
|
43
|
+
const { sodax } = useSodaxContext();
|
|
44
|
+
const isXrpDestination = dstChainKey === ChainKeys.XRP_MAINNET;
|
|
45
|
+
const requiresTrustline = isXrpDestination && !!token && sodax.spoke.xrp.requiresTrustline(token);
|
|
46
|
+
const xrpWalletProvider = walletProvider?.chainType === 'XRP' ? walletProvider : undefined;
|
|
47
|
+
|
|
48
|
+
const readinessCheck = useXrpDestinationCheck({
|
|
49
|
+
params: { chainId: requiresTrustline ? dstChainKey : undefined, token, address, amount, maxAmount },
|
|
50
|
+
});
|
|
51
|
+
const trustlineReason =
|
|
52
|
+
readinessCheck.data?.ready === false &&
|
|
53
|
+
(readinessCheck.data.reason === 'no_trustline' || readinessCheck.data.reason === 'trustline_limit');
|
|
54
|
+
// Read the reserve only once the trustline is known to need setting.
|
|
55
|
+
const reserveCheck = useXrpTrustlineReserveCheck({
|
|
56
|
+
params: { token: trustlineReason ? token : undefined, address: trustlineReason ? address : undefined },
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const state = resolveXrpGate(dstChainKey, { readinessCheck, reserveCheck, requiresTrustline });
|
|
60
|
+
|
|
61
|
+
const { mutateAsyncSafe: establishTrustline, isPending: isRequestingTrustline } = useEstablishXrpTrustline();
|
|
62
|
+
|
|
63
|
+
const requestTrustline = async (): Promise<Result<string> | undefined> => {
|
|
64
|
+
if (!xrpWalletProvider || !token || !address) return undefined;
|
|
65
|
+
return establishTrustline({ token, address, walletProvider: xrpWalletProvider });
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const retry = (): void => {
|
|
69
|
+
void readinessCheck.refetch();
|
|
70
|
+
if (trustlineReason) void reserveCheck.refetch();
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
...state,
|
|
75
|
+
isChecking: readinessCheck.isLoading || reserveCheck.isLoading,
|
|
76
|
+
error: readinessCheck.error ?? reserveCheck.error ?? undefined,
|
|
77
|
+
retry,
|
|
78
|
+
isRequestingTrustline,
|
|
79
|
+
requestTrustline,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Sodax } from '@sodax/sdk';
|
|
2
|
+
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
3
|
+
import type { ReadHookParams } from './types.js';
|
|
4
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
5
|
+
|
|
6
|
+
export type UseXrpTrustlineReserveCheckParams = ReadHookParams<
|
|
7
|
+
boolean,
|
|
8
|
+
{
|
|
9
|
+
token: string | undefined;
|
|
10
|
+
address: string | undefined;
|
|
11
|
+
}
|
|
12
|
+
>;
|
|
13
|
+
|
|
14
|
+
type XrpReserveReader = { spoke: { xrp: Pick<Sodax['spoke']['xrp'], 'canAffordTrustline'> } };
|
|
15
|
+
|
|
16
|
+
export function getXrpTrustlineReserveCheckQueryOptions({
|
|
17
|
+
sodax,
|
|
18
|
+
token,
|
|
19
|
+
address,
|
|
20
|
+
}: {
|
|
21
|
+
sodax: XrpReserveReader;
|
|
22
|
+
token: string | undefined;
|
|
23
|
+
address: string | undefined;
|
|
24
|
+
}) {
|
|
25
|
+
return {
|
|
26
|
+
queryKey: ['shared', 'xrpTrustlineReserveCheck', token, address] as const,
|
|
27
|
+
queryFn: async (): Promise<boolean> => {
|
|
28
|
+
if (!address || !token) throw new Error('address and token are required');
|
|
29
|
+
return sodax.spoke.xrp.canAffordTrustline({ address, token });
|
|
30
|
+
},
|
|
31
|
+
enabled: !!address && !!token,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether an XRPL account holds the spendable XRP to set the trustline for an issued `token`. */
|
|
36
|
+
export function useXrpTrustlineReserveCheck({
|
|
37
|
+
params,
|
|
38
|
+
queryOptions,
|
|
39
|
+
}: UseXrpTrustlineReserveCheckParams = {}): UseQueryResult<boolean, Error> {
|
|
40
|
+
const { sodax } = useSodaxContext();
|
|
41
|
+
return useQuery<boolean, Error>({
|
|
42
|
+
...getXrpTrustlineReserveCheckQueryOptions({ sodax, token: params?.token, address: params?.address }),
|
|
43
|
+
...queryOptions,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -13,6 +13,7 @@ const swapHook = vi.fn();
|
|
|
13
13
|
const statusHook = vi.fn();
|
|
14
14
|
const stellarHook = vi.fn();
|
|
15
15
|
const nearHook = vi.fn();
|
|
16
|
+
const xrpHook = vi.fn();
|
|
16
17
|
const fetchingChecks = vi.fn(() => 0);
|
|
17
18
|
|
|
18
19
|
// The lifecycle is composition plus a pure resolver (covered in utils/swapLifecycle.test.ts), so the
|
|
@@ -22,6 +23,7 @@ vi.mock('./useSwapWithApproval.js', () => ({ useSwapWithApproval: (args: unknown
|
|
|
22
23
|
vi.mock('./useDetailedStatus.js', () => ({ useDetailedStatus: (args: unknown) => statusHook(args) }));
|
|
23
24
|
vi.mock('../shared/useStellarGate.js', () => ({ useStellarGate: (args: unknown) => stellarHook(args) }));
|
|
24
25
|
vi.mock('../shared/useNearStorageGate.js', () => ({ useNearStorageGate: (args: unknown) => nearHook(args) }));
|
|
26
|
+
vi.mock('../shared/useXrpGate.js', () => ({ useXrpGate: (args: unknown) => xrpHook(args) }));
|
|
25
27
|
// Its own state is one ref; a fresh one per run() is a fresh mount.
|
|
26
28
|
vi.mock('react', () => ({ useRef: (initial: unknown) => ({ current: initial }) }));
|
|
27
29
|
vi.mock('@tanstack/react-query', () => ({ useIsFetching: () => fetchingChecks() }));
|
|
@@ -56,6 +58,8 @@ const openGate = {
|
|
|
56
58
|
blocksAction: false,
|
|
57
59
|
isNear: false,
|
|
58
60
|
needsRegistration: false,
|
|
61
|
+
isXrpIssuedToken: false,
|
|
62
|
+
blockedReason: undefined,
|
|
59
63
|
activate: vi.fn(),
|
|
60
64
|
requestTrustline: vi.fn(),
|
|
61
65
|
retry: vi.fn(),
|
|
@@ -68,12 +72,14 @@ const stub = ({
|
|
|
68
72
|
status,
|
|
69
73
|
stellar = {},
|
|
70
74
|
near = {},
|
|
75
|
+
xrp = {},
|
|
71
76
|
}: {
|
|
72
77
|
swap?: Record<string, unknown>;
|
|
73
78
|
strategy?: string;
|
|
74
79
|
status?: unknown;
|
|
75
80
|
stellar?: Record<string, unknown>;
|
|
76
81
|
near?: Record<string, unknown>;
|
|
82
|
+
xrp?: Record<string, unknown>;
|
|
77
83
|
} = {}) => {
|
|
78
84
|
strategyHook.mockReturnValue({ data: strategy, error: null, refetch: refetchStrategy });
|
|
79
85
|
swapHook.mockReturnValue({
|
|
@@ -88,6 +94,7 @@ const stub = ({
|
|
|
88
94
|
statusHook.mockReturnValue({ data: status });
|
|
89
95
|
stellarHook.mockReturnValue({ ...openGate, ...stellar });
|
|
90
96
|
nearHook.mockReturnValue({ ...openGate, ...near });
|
|
97
|
+
xrpHook.mockReturnValue({ ...openGate, ...xrp });
|
|
91
98
|
};
|
|
92
99
|
|
|
93
100
|
const run = (overrides: Partial<Parameters<typeof useSwapLifecycle>[0]> = {}) =>
|
|
@@ -192,6 +199,8 @@ describe('useSwapLifecycle', () => {
|
|
|
192
199
|
[{ stellar: { isStellar: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
|
|
193
200
|
[{ stellar: { isStellar: true, checkFailed: true, blocksAction: true } }, 'retry'],
|
|
194
201
|
[{ near: { isNear: true, needsRegistration: true, blocksAction: true } }, 'registerStorage'],
|
|
202
|
+
[{ xrp: { isXrpIssuedToken: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
|
|
203
|
+
[{ xrp: { isXrpIssuedToken: true, checkFailed: true, blocksAction: true } }, 'retry'],
|
|
195
204
|
] as const)('runs the matching setup action', async (gates, action) => {
|
|
196
205
|
stub(gates);
|
|
197
206
|
const lifecycle = run();
|
|
@@ -211,6 +220,43 @@ describe('useSwapLifecycle', () => {
|
|
|
211
220
|
expect(nearHook).toHaveBeenCalledWith(expect.objectContaining({ accountId: PARAMS.dstAddress }));
|
|
212
221
|
});
|
|
213
222
|
|
|
223
|
+
it('sizes the XRPL trustline check as the SDK sizes its check before signing', () => {
|
|
224
|
+
stub();
|
|
225
|
+
run({ intentParams: { ...PARAMS, dstChainKey: ChainKeys.XRP_MAINNET } });
|
|
226
|
+
|
|
227
|
+
expect(xrpHook).toHaveBeenCalledWith(
|
|
228
|
+
expect.objectContaining({
|
|
229
|
+
dstChainKey: ChainKeys.XRP_MAINNET,
|
|
230
|
+
address: PARAMS.dstAddress,
|
|
231
|
+
token: PARAMS.outputToken,
|
|
232
|
+
amount: PARAMS.minOutputAmount,
|
|
233
|
+
maxAmount: PARAMS.minOutputAmount * 2n,
|
|
234
|
+
}),
|
|
235
|
+
);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it.each([
|
|
239
|
+
['xrpBlocked', { blockedReason: 'issuer_frozen' }],
|
|
240
|
+
['xrpFunding', { needsFunding: true }],
|
|
241
|
+
] as const)('leaves %s to the app and sends nothing', async (reason, gate) => {
|
|
242
|
+
stub({ xrp: { isXrpIssuedToken: true, blocksAction: true, ...gate } });
|
|
243
|
+
const lifecycle = run();
|
|
244
|
+
|
|
245
|
+
expect(lifecycle.state).toEqual({ kind: 'needsSetup', reason });
|
|
246
|
+
expect(await lifecycle.next()).toBeUndefined();
|
|
247
|
+
expect(openGate.requestTrustline).not.toHaveBeenCalled();
|
|
248
|
+
expect(mutateAsyncSafe).not.toHaveBeenCalled();
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('holds the XRPL trustline step while its TrustSet is in flight', async () => {
|
|
252
|
+
stub({ xrp: { isXrpIssuedToken: true, needsTrustline: true, blocksAction: true, isRequestingTrustline: true } });
|
|
253
|
+
const lifecycle = run();
|
|
254
|
+
|
|
255
|
+
expect(lifecycle.state).toEqual({ kind: 'checking' });
|
|
256
|
+
await lifecycle.next();
|
|
257
|
+
expect(openGate.requestTrustline).not.toHaveBeenCalled();
|
|
258
|
+
});
|
|
259
|
+
|
|
214
260
|
it('retries a failed NEAR storage check instead of swapping', async () => {
|
|
215
261
|
const nearRetry = vi.fn();
|
|
216
262
|
stub({ near: { isNear: true, checkFailed: true, retry: nearRetry } });
|