@sodax/dapp-kit 2.3.0 → 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 +182 -31
- package/dist/index.mjs +297 -25
- package/package.json +10 -5
- package/src/hooks/_mutationContract.test.ts +1 -0
- package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.test.ts +28 -3
- package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.ts +17 -8
- package/src/hooks/bridge/useBridge.ts +6 -0
- package/src/hooks/bridge/useBridgeDetailedStatus.test.ts +56 -1
- package/src/hooks/bridge/useBridgeDetailedStatus.ts +26 -9
- package/src/hooks/bridge/useBridgeWithApproval.test.ts +24 -1
- package/src/hooks/bridge/useBridgeWithApproval.ts +6 -0
- package/src/hooks/dex/useDexDeposit.ts +6 -0
- package/src/hooks/dex/useDexWithdraw.ts +12 -5
- package/src/hooks/mm/useBorrow.ts +15 -4
- package/src/hooks/mm/useRepay.ts +6 -0
- package/src/hooks/mm/useSupply.ts +6 -0
- package/src/hooks/mm/useWithdraw.ts +12 -5
- package/src/hooks/recovery/useWithdrawHubAsset.ts +12 -5
- package/src/hooks/shared/index.ts +4 -0
- package/src/hooks/shared/notFoundStreak.ts +5 -0
- package/src/hooks/shared/retryBeforeSubmission.ts +26 -0
- package/src/hooks/shared/useBalances.test.ts +10 -0
- package/src/hooks/shared/useBalances.ts +17 -4
- package/src/hooks/shared/useEstablishXrpTrustline.test.ts +113 -0
- package/src/hooks/shared/useEstablishXrpTrustline.ts +65 -0
- package/src/hooks/shared/useSafeMutation.retry.test.ts +47 -0
- package/src/hooks/shared/useSafeMutation.ts +8 -1
- 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/useCreateLimitOrder.ts +8 -0
- package/src/hooks/swap/useSwap.ts +6 -0
- package/src/hooks/swap/useSwapLifecycle.test.ts +73 -1
- package/src/hooks/swap/useSwapLifecycle.ts +29 -5
- package/src/hooks/swap/useSwapWithApproval.test.ts +24 -1
- package/src/hooks/swap/useSwapWithApproval.ts +6 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/swapLifecycle.test.ts +35 -0
- package/src/utils/swapLifecycle.ts +29 -5
- package/src/utils/xrpGate.test.ts +112 -0
- package/src/utils/xrpGate.ts +72 -0
|
@@ -16,6 +16,11 @@
|
|
|
16
16
|
export const STATUS_POLL_MS = 3000;
|
|
17
17
|
/** Cap consecutive ambiguous polls (~2 min at 3s). The first one is a race, not a stop. */
|
|
18
18
|
export const MAX_NOT_FOUND_POLLS = 40;
|
|
19
|
+
/**
|
|
20
|
+
* The cap for a read the SDK tags `context.mpcRelay` (~5 min at 3s). An MPC-relay leg waits on confirmations,
|
|
21
|
+
* the NEAR signature and the hub tx, and the SDK itself allows it at least 5 minutes.
|
|
22
|
+
*/
|
|
23
|
+
export const MAX_MPC_RELAY_NOT_FOUND_POLLS = 100;
|
|
19
24
|
|
|
20
25
|
export type NotFoundStreakState = {
|
|
21
26
|
/** Identity of what is being polled — an intent tx hash, or a composite source-chain/tx key. */
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ATOMIC_BATCH_UNCONFIRMED, isIndeterminateOutcomeError, isSodaxError } from '@sodax/sdk';
|
|
2
|
+
import type { UseMutationOptions } from '@tanstack/react-query';
|
|
3
|
+
|
|
4
|
+
/** A mutation may have moved funds. Only retry errors without an existing operation to resume. */
|
|
5
|
+
export function retryBeforeSubmission<TError>(retry: UseMutationOptions<unknown, TError>['retry']) {
|
|
6
|
+
return (failureCount: number, error: TError): boolean => {
|
|
7
|
+
if (isIndeterminateOutcomeError(error)) return false;
|
|
8
|
+
if (isSodaxError(error)) {
|
|
9
|
+
const { srcTxHash, hubTxHash, dstTxHash, trackingId, recovery, batchId, reason } = error.context ?? {};
|
|
10
|
+
if (
|
|
11
|
+
srcTxHash ||
|
|
12
|
+
hubTxHash ||
|
|
13
|
+
dstTxHash ||
|
|
14
|
+
trackingId ||
|
|
15
|
+
recovery ||
|
|
16
|
+
batchId ||
|
|
17
|
+
reason === ATOMIC_BATCH_UNCONFIRMED
|
|
18
|
+
) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (typeof retry === 'function') return retry(failureCount, error);
|
|
23
|
+
if (typeof retry === 'number') return failureCount < retry;
|
|
24
|
+
return retry === true;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -43,6 +43,16 @@ describe('getBalancesQueryOptions', () => {
|
|
|
43
43
|
]);
|
|
44
44
|
});
|
|
45
45
|
|
|
46
|
+
it('keys TON wallet balances by the account address and forwards it to the SDK', async () => {
|
|
47
|
+
const sodax = makeSodax({ ok: true, value: {} });
|
|
48
|
+
const inputs = { chainKey: 'ton' as const, tokens: [tokenA], address: '0xpubkey' };
|
|
49
|
+
const accountAddress = 'EQ-wallet';
|
|
50
|
+
const opts = getBalancesQueryOptions(sodax, { ...inputs, accountAddress });
|
|
51
|
+
expect(opts.queryKey).not.toEqual(getBalancesQueryOptions(sodax, inputs).queryKey);
|
|
52
|
+
await opts.queryFn();
|
|
53
|
+
expect(sodax.spoke.getWalletBalances).toHaveBeenCalledWith(expect.objectContaining({ accountAddress }));
|
|
54
|
+
});
|
|
55
|
+
|
|
46
56
|
it('is disabled when chainKey is missing', () => {
|
|
47
57
|
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
48
58
|
chainKey: undefined,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type UseQueryResult, useQuery } from '@tanstack/react-query';
|
|
2
|
-
import type
|
|
2
|
+
import { ChainKeys, type Sodax, type SpokeChainKey, type XToken } from '@sodax/sdk';
|
|
3
3
|
import { useSodaxContext } from './useSodaxContext.js';
|
|
4
4
|
import { unwrapResult } from './unwrapResult.js';
|
|
5
5
|
import type { ReadHookParams } from './types.js';
|
|
@@ -15,6 +15,8 @@ export interface BalancesInputs {
|
|
|
15
15
|
chainKey: SpokeChainKey | undefined;
|
|
16
16
|
tokens: readonly XToken[];
|
|
17
17
|
address: string | undefined;
|
|
18
|
+
/** TON only: wallet account to read. Defaults to the public key’s wallet-v4R2 address. */
|
|
19
|
+
accountAddress?: string;
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
export type UseBalancesParams = ReadHookParams<Record<string, bigint>, BalancesInputs>;
|
|
@@ -26,14 +28,24 @@ const REFETCH_INTERVAL_MS = 5_000;
|
|
|
26
28
|
* callers that compose their own `useQuery` wrapper. Takes the SDK instance explicitly (the hook
|
|
27
29
|
* supplies it from context).
|
|
28
30
|
*/
|
|
29
|
-
export function getBalancesQueryOptions(sodax: Sodax, { chainKey, tokens, address }: BalancesInputs) {
|
|
31
|
+
export function getBalancesQueryOptions(sodax: Sodax, { chainKey, tokens, address, accountAddress }: BalancesInputs) {
|
|
32
|
+
const tonAccount = chainKey === ChainKeys.TON_MAINNET && accountAddress ? { accountAddress } : undefined;
|
|
30
33
|
return {
|
|
31
34
|
// Pair symbol + address: readable in devtools, unique on-chain (symbol alone can collide —
|
|
32
35
|
// e.g. scam tokens copying a legitimate ticker).
|
|
33
|
-
queryKey: [
|
|
36
|
+
queryKey: [
|
|
37
|
+
'shared',
|
|
38
|
+
'balances',
|
|
39
|
+
chainKey,
|
|
40
|
+
tokens.map(t => [t.symbol, t.address] as const),
|
|
41
|
+
address,
|
|
42
|
+
...(tonAccount ? [tonAccount.accountAddress] : []),
|
|
43
|
+
] as const,
|
|
34
44
|
queryFn: async (): Promise<Record<string, bigint>> => {
|
|
35
45
|
if (!chainKey || !address) return {};
|
|
36
|
-
return unwrapResult(
|
|
46
|
+
return unwrapResult(
|
|
47
|
+
await sodax.spoke.getWalletBalances({ srcChainKey: chainKey, srcAddress: address, tokens, ...tonAccount }),
|
|
48
|
+
);
|
|
37
49
|
},
|
|
38
50
|
enabled: !!chainKey && !!address && tokens.length > 0,
|
|
39
51
|
refetchInterval: REFETCH_INTERVAL_MS,
|
|
@@ -75,6 +87,7 @@ export function useBalances({ params, queryOptions }: UseBalancesParams = {}): U
|
|
|
75
87
|
chainKey: params?.chainKey,
|
|
76
88
|
tokens: params?.tokens ?? [],
|
|
77
89
|
address: params?.address,
|
|
90
|
+
accountAddress: params?.accountAddress,
|
|
78
91
|
}),
|
|
79
92
|
...queryOptions,
|
|
80
93
|
});
|
|
@@ -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,47 @@
|
|
|
1
|
+
import { SodaxError } from '@sodax/sdk';
|
|
2
|
+
import { QueryClient, type UseMutationOptions } from '@tanstack/react-query';
|
|
3
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
4
|
+
import { useLeverageYieldVaultSwap } from '../leverageYield/useLeverageYieldVaultSwap.js';
|
|
5
|
+
import { useLeverageYieldVaultSwapWithApproval } from '../leverageYield/useLeverageYieldVaultSwapWithApproval.js';
|
|
6
|
+
import { useFeeClaimWithdraw } from '../partner/useFeeClaimWithdraw.js';
|
|
7
|
+
import { useSwapsApiBroadcastWithApproval } from '../swapsApi/useSwapsApiBroadcastWithApproval.js';
|
|
8
|
+
|
|
9
|
+
let queryClient: QueryClient;
|
|
10
|
+
let options: UseMutationOptions<unknown, Error, unknown>;
|
|
11
|
+
|
|
12
|
+
vi.mock('./useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax: {} }) }));
|
|
13
|
+
vi.mock('react', async importOriginal => ({
|
|
14
|
+
...(await importOriginal<typeof import('react')>()),
|
|
15
|
+
useCallback: (fn: unknown) => fn,
|
|
16
|
+
}));
|
|
17
|
+
vi.mock('@tanstack/react-query', async importOriginal => ({
|
|
18
|
+
...(await importOriginal<typeof import('@tanstack/react-query')>()),
|
|
19
|
+
useQueryClient: () => queryClient,
|
|
20
|
+
useMutation: (value: typeof options) => {
|
|
21
|
+
options = value;
|
|
22
|
+
return {};
|
|
23
|
+
},
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false, retryDelay: 0 } } });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it.each([
|
|
31
|
+
{ hook: useLeverageYieldVaultSwap, name: 'useLeverageYieldVaultSwap' },
|
|
32
|
+
{ hook: useLeverageYieldVaultSwapWithApproval, name: 'useLeverageYieldVaultSwapWithApproval' },
|
|
33
|
+
{ hook: useSwapsApiBroadcastWithApproval, name: 'useSwapsApiBroadcastWithApproval' },
|
|
34
|
+
{ hook: useFeeClaimWithdraw, name: 'useFeeClaimWithdraw' },
|
|
35
|
+
])('$name preserves keyed retries before submission and stops after submission', async ({ hook }) => {
|
|
36
|
+
queryClient.setMutationDefaults(['retry-test'], { retry: 2 });
|
|
37
|
+
hook({ mutationOptions: { mutationKey: ['retry-test'] } });
|
|
38
|
+
const pending = new SodaxError('RELAY_TIMEOUT', 'Settlement pending', {
|
|
39
|
+
feature: 'bridge',
|
|
40
|
+
context: { srcTxHash: '0x1234' },
|
|
41
|
+
});
|
|
42
|
+
const submit = vi.fn().mockRejectedValueOnce(new Error('Before submission')).mockRejectedValue(pending);
|
|
43
|
+
const mutation = queryClient.getMutationCache().build(queryClient, { ...options, mutationFn: submit });
|
|
44
|
+
|
|
45
|
+
await expect(mutation.execute(undefined)).rejects.toBe(pending);
|
|
46
|
+
expect(submit).toHaveBeenCalledTimes(2);
|
|
47
|
+
});
|
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
import type { Result } from '@sodax/sdk';
|
|
3
3
|
import {
|
|
4
4
|
useMutation,
|
|
5
|
+
useQueryClient,
|
|
5
6
|
type MutateOptions,
|
|
6
7
|
type UseMutationOptions,
|
|
7
8
|
type UseMutationResult,
|
|
8
9
|
} from '@tanstack/react-query';
|
|
9
10
|
import { useCallback } from 'react';
|
|
11
|
+
import { retryBeforeSubmission } from './retryBeforeSubmission.js';
|
|
10
12
|
|
|
11
13
|
/**
|
|
12
14
|
* Return shape of every dapp-kit mutation hook. Extends `UseMutationResult` with one extra
|
|
@@ -54,7 +56,12 @@ export async function toResult<T>(promise: Promise<T>): Promise<Result<T>> {
|
|
|
54
56
|
export function useSafeMutation<TData, TError, TVars, TContext = unknown>(
|
|
55
57
|
options: UseMutationOptions<TData, TError, TVars, TContext>,
|
|
56
58
|
): SafeUseMutationResult<TData, TError, TVars, TContext> {
|
|
57
|
-
const
|
|
59
|
+
const queryClient = useQueryClient();
|
|
60
|
+
const { retry } = queryClient.defaultMutationOptions(options);
|
|
61
|
+
const mutation = useMutation<TData, TError, TVars, TContext>({
|
|
62
|
+
...options,
|
|
63
|
+
retry: retryBeforeSubmission(retry),
|
|
64
|
+
});
|
|
58
65
|
const { mutateAsync } = mutation;
|
|
59
66
|
const mutateAsyncSafe = useCallback(
|
|
60
67
|
(vars: TVars, opts?: MutateOptions<TData, TError, TVars, TContext>): Promise<Result<TData>> =>
|
|
@@ -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
|
+
}
|