@sodax/dapp-kit 2.0.0-rc.9 → 2.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -119
- package/dist/index.d.ts +939 -63
- package/dist/index.mjs +1086 -180
- package/package.json +3 -3
- package/src/hooks/_mutationContract.test.ts +17 -2
- package/src/hooks/backend/index.ts +1 -5
- package/src/hooks/backend/types.ts +1 -1
- package/src/hooks/bitcoin/index.ts +2 -0
- package/src/hooks/bitcoin/resolveBtcReadAddress.test.ts +54 -0
- package/src/hooks/bitcoin/resolveBtcReadAddress.ts +21 -0
- package/src/hooks/bitcoin/useBitcoinTradingSetup.ts +45 -0
- package/src/hooks/bitcoin/useEnsureRadfiAccessToken.ts +57 -0
- package/src/hooks/bitcoin/useFundTradingWallet.ts +1 -1
- package/src/hooks/bitcoin/useRadfiAuth.ts +2 -2
- package/src/hooks/bitcoin/useRadfiWithdraw.ts +2 -2
- package/src/hooks/bitcoin/useRenewUtxos.ts +2 -2
- package/src/hooks/bitcoin/useTradingWallet.ts +1 -1
- package/src/hooks/bridge/useBridgeApprove.ts +2 -1
- package/src/hooks/index.ts +3 -0
- package/src/hooks/leverageYield/index.ts +9 -0
- package/src/hooks/leverageYield/useLeverageYieldDeposit.ts +40 -0
- package/src/hooks/leverageYield/useLeverageYieldEffectiveApr.ts +42 -0
- package/src/hooks/leverageYield/useLeverageYieldNotifySolver.ts +34 -0
- package/src/hooks/leverageYield/useLeverageYieldPosition.ts +40 -0
- package/src/hooks/leverageYield/useLeverageYieldPreviewRedeem.ts +43 -0
- package/src/hooks/leverageYield/useLeverageYieldShareBalances.ts +74 -0
- package/src/hooks/leverageYield/useLeverageYieldTotalAssets.ts +36 -0
- package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +50 -0
- package/src/hooks/leverageYield/useLeverageYieldWithdraw.ts +40 -0
- package/src/hooks/migrate/useMigrationApprove.ts +1 -3
- package/src/hooks/mm/useATokensBalances.ts +7 -1
- package/src/hooks/mm/useUserFormattedSummary.ts +5 -1
- package/src/hooks/mm/useUserReservesData.ts +5 -1
- package/src/hooks/mm/useWithdraw.ts +5 -1
- package/src/hooks/partner/index.ts +4 -0
- package/src/hooks/partner/useApproveToken.ts +1 -2
- package/src/hooks/partner/useFeeClaimWithdraw.ts +88 -0
- package/src/hooks/partner/useGetIntentDetails.ts +39 -0
- package/src/hooks/partner/useGetUserIntent.ts +35 -0
- package/src/hooks/partner/usePartnerCancelIntent.ts +52 -0
- package/src/hooks/shared/index.ts +6 -0
- package/src/hooks/shared/isUserRejectedError.test.ts +42 -0
- package/src/hooks/shared/isUserRejectedError.ts +30 -0
- package/src/hooks/shared/useEstablishTrustline.test.ts +89 -0
- package/src/hooks/shared/useEstablishTrustline.ts +72 -0
- package/src/hooks/shared/useGetUserHubWalletAddress.ts +5 -1
- package/src/hooks/shared/useNearStorageCheck.ts +45 -0
- package/src/hooks/shared/useNearStorageGate.ts +60 -0
- package/src/hooks/shared/useRegisterNearStorage.ts +46 -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 +74 -0
- package/src/hooks/shared/useStellarTrustlineCheck.ts +39 -15
- 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/index.ts +41 -0
- package/src/hooks/swapsApi/isTerminalSwapIntentStatus.test.ts +24 -0
- package/src/hooks/swapsApi/isTerminalSwapIntentStatus.ts +11 -0
- package/src/hooks/swapsApi/useSwapsApiAllowance.ts +40 -0
- package/src/hooks/swapsApi/useSwapsApiApprove.ts +42 -0
- package/src/hooks/swapsApi/useSwapsApiCancelIntent.ts +41 -0
- package/src/hooks/swapsApi/useSwapsApiCreateIntent.ts +41 -0
- package/src/hooks/swapsApi/useSwapsApiCreateLimitOrder.ts +41 -0
- package/src/hooks/swapsApi/useSwapsApiDeadline.ts +36 -0
- package/src/hooks/swapsApi/useSwapsApiEstimateGas.ts +40 -0
- package/src/hooks/swapsApi/useSwapsApiFilledIntent.ts +41 -0
- package/src/hooks/swapsApi/useSwapsApiIntent.ts +40 -0
- package/src/hooks/swapsApi/useSwapsApiIntentExtraData.ts +41 -0
- package/src/hooks/swapsApi/useSwapsApiIntentHash.ts +40 -0
- package/src/hooks/swapsApi/useSwapsApiIntentPacket.ts +43 -0
- package/src/hooks/swapsApi/useSwapsApiPartnerFee.ts +40 -0
- package/src/hooks/swapsApi/useSwapsApiQuote.ts +55 -0
- package/src/hooks/swapsApi/useSwapsApiSolverFee.ts +40 -0
- package/src/hooks/swapsApi/useSwapsApiStatus.ts +45 -0
- package/src/hooks/swapsApi/useSwapsApiSubmitIntent.ts +43 -0
- package/src/hooks/{backend/useBackendSubmitSwapTx.ts → swapsApi/useSwapsApiSubmitTx.ts} +16 -17
- package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +55 -0
- package/src/hooks/swapsApi/useSwapsApiTokens.ts +34 -0
- package/src/hooks/swapsApi/useSwapsApiTokensByChain.ts +40 -0
- package/src/index.ts +1 -1
- package/src/providers/SodaxProvider.tsx +2 -3
- package/src/providers/createSodaxQueryClient.ts +1 -5
- package/src/utils/dex-utils.ts +1 -4
- package/src/utils/index.ts +2 -0
- package/src/utils/nearStorageGate.test.ts +46 -0
- package/src/utils/nearStorageGate.ts +39 -0
- package/src/utils/stellarGate.test.ts +196 -0
- package/src/utils/stellarGate.ts +84 -0
- package/src/hooks/backend/useBackendSubmitSwapTxStatus.ts +0 -59
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ChainKeys } 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 three
|
|
8
|
+
// React-side imports lets the real onSuccess run without a DOM.
|
|
9
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
|
|
10
|
+
vi.mock('./useSodaxContext.js', () => ({
|
|
11
|
+
useSodaxContext: () => ({ sodax: { spoke: { stellar: { requestTrustline } } } }),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('./useSafeMutation.js', () => ({ useSafeMutation: (options: unknown) => options }));
|
|
14
|
+
|
|
15
|
+
const { useEstablishTrustline } = await import('./useEstablishTrustline.js');
|
|
16
|
+
|
|
17
|
+
const TOKEN = 'CBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
|
|
18
|
+
const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
|
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>) => ({
|
|
24
|
+
token: TOKEN,
|
|
25
|
+
amount: 1_000_000n,
|
|
26
|
+
srcChainKey: ChainKeys.STELLAR_MAINNET,
|
|
27
|
+
walletProvider: { getWalletAddress } as never,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const optionsOf = () => useEstablishTrustline() as unknown as { onSuccess: OnSuccess; mutationFn: MutationFn };
|
|
31
|
+
|
|
32
|
+
const invalidatedKeys = () => invalidateQueries.mock.calls.map(([arg]) => arg.queryKey);
|
|
33
|
+
|
|
34
|
+
beforeEach(() => {
|
|
35
|
+
invalidateQueries.mockReset();
|
|
36
|
+
requestTrustline.mockReset();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe('useEstablishTrustline — invalidation after a broadcast trustline', () => {
|
|
40
|
+
it('invalidates the account-scoped keys when the address is readable', async () => {
|
|
41
|
+
await optionsOf().onSuccess(
|
|
42
|
+
'hash',
|
|
43
|
+
vars(async () => ADDRESS),
|
|
44
|
+
undefined,
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
expect(invalidatedKeys()).toEqual([
|
|
48
|
+
['shared', 'stellarTrustlineCheck', ChainKeys.STELLAR_MAINNET, TOKEN, ADDRESS],
|
|
49
|
+
['sponsoring', 'stellarAccountStatus', ADDRESS],
|
|
50
|
+
['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
|
|
51
|
+
]);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('SURVIVES a wallet that fails right after signing, and still invalidates', async () => {
|
|
55
|
+
// The trustline is already on-chain here: throwing would report success as an
|
|
56
|
+
// error and leave the gate showing "needs a trustline" until a manual refetch.
|
|
57
|
+
const rejecting = vars(async () => {
|
|
58
|
+
throw new Error('wallet is locked');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
await expect(optionsOf().onSuccess('hash', rejecting, undefined)).resolves.toBeUndefined();
|
|
62
|
+
|
|
63
|
+
// Falls back to the whole prefix, because the account is no longer identifiable.
|
|
64
|
+
expect(invalidatedKeys()).toEqual([
|
|
65
|
+
['shared', 'stellarTrustlineCheck'],
|
|
66
|
+
['sponsoring', 'stellarAccountStatus'],
|
|
67
|
+
['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
|
|
68
|
+
]);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe('useEstablishTrustline — input guard carried over from useRequestTrustline', () => {
|
|
73
|
+
it.each([
|
|
74
|
+
['a zero amount', { amount: 0n }],
|
|
75
|
+
['an empty token', { token: '' }],
|
|
76
|
+
])('rejects %s without reaching the wallet', async (_label, override) => {
|
|
77
|
+
const invalid = { ...vars(async () => ADDRESS), ...override };
|
|
78
|
+
|
|
79
|
+
await expect(optionsOf().mutationFn(invalid)).rejects.toThrow('Token and amount are required');
|
|
80
|
+
expect(requestTrustline).not.toHaveBeenCalled();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('derives srcAddress from the wallet provider for a valid request', async () => {
|
|
84
|
+
requestTrustline.mockResolvedValue('hash');
|
|
85
|
+
|
|
86
|
+
await expect(optionsOf().mutationFn(vars(async () => ADDRESS))).resolves.toBe('hash');
|
|
87
|
+
expect(requestTrustline).toHaveBeenCalledWith(expect.objectContaining({ raw: false, srcAddress: ADDRESS }));
|
|
88
|
+
});
|
|
89
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { IStellarWalletProvider, StellarChainKey } from '@sodax/sdk';
|
|
2
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
3
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import type { MutationHookParams } from './types.js';
|
|
5
|
+
import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
|
|
6
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
7
|
+
|
|
8
|
+
export type UseEstablishTrustlineVars = {
|
|
9
|
+
token: string;
|
|
10
|
+
amount: bigint;
|
|
11
|
+
srcChainKey: StellarChainKey;
|
|
12
|
+
walletProvider: IStellarWalletProvider;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Establish a Stellar trustline. The account pays its fee and reserve; use
|
|
17
|
+
* {@link useStellarGate} to verify it can afford them.
|
|
18
|
+
*
|
|
19
|
+
* Supersedes the deprecated `useRequestTrustline`, which keeps the hand-rolled
|
|
20
|
+
* shape released in 2.0.0.
|
|
21
|
+
*/
|
|
22
|
+
export function useEstablishTrustline({
|
|
23
|
+
mutationOptions,
|
|
24
|
+
}: MutationHookParams<string, UseEstablishTrustlineVars> = {}): SafeUseMutationResult<
|
|
25
|
+
string,
|
|
26
|
+
Error,
|
|
27
|
+
UseEstablishTrustlineVars
|
|
28
|
+
> {
|
|
29
|
+
const { sodax } = useSodaxContext();
|
|
30
|
+
const queryClient = useQueryClient();
|
|
31
|
+
|
|
32
|
+
return useSafeMutation<string, Error, UseEstablishTrustlineVars>({
|
|
33
|
+
mutationKey: ['shared', 'establishTrustline'],
|
|
34
|
+
...mutationOptions,
|
|
35
|
+
mutationFn: async ({ token, amount, srcChainKey, walletProvider }): Promise<string> => {
|
|
36
|
+
// Rejecting `0n` preserves the behaviour of the hook this replaced: an amount
|
|
37
|
+
// sizes the trustline check, so zero is a caller bug rather than a request.
|
|
38
|
+
if (!token || !amount) {
|
|
39
|
+
throw new Error('Token and amount are required');
|
|
40
|
+
}
|
|
41
|
+
const srcAddress = await walletProvider.getWalletAddress();
|
|
42
|
+
return sodax.spoke.stellar.requestTrustline<false>({
|
|
43
|
+
raw: false,
|
|
44
|
+
srcChainKey,
|
|
45
|
+
srcAddress,
|
|
46
|
+
token,
|
|
47
|
+
amount,
|
|
48
|
+
walletProvider,
|
|
49
|
+
});
|
|
50
|
+
},
|
|
51
|
+
onSuccess: async (data, vars, ctx) => {
|
|
52
|
+
// The trustline is already broadcast here, so a wallet that locks or switches
|
|
53
|
+
// accounts mid-flow must not turn success into an error — nor skip the
|
|
54
|
+
// invalidations below, which is what an unguarded throw would do.
|
|
55
|
+
const srcAddress = await vars.walletProvider.getWalletAddress().catch(() => undefined);
|
|
56
|
+
// Without the address, invalidate the whole prefix rather than nothing.
|
|
57
|
+
queryClient.invalidateQueries({
|
|
58
|
+
queryKey: srcAddress
|
|
59
|
+
? ['shared', 'stellarTrustlineCheck', vars.srcChainKey, vars.token, srcAddress]
|
|
60
|
+
: ['shared', 'stellarTrustlineCheck'],
|
|
61
|
+
});
|
|
62
|
+
// A new trustline changes spendable XLM for subsequent trustlines.
|
|
63
|
+
queryClient.invalidateQueries({
|
|
64
|
+
queryKey: srcAddress
|
|
65
|
+
? ['sponsoring', 'stellarAccountStatus', srcAddress]
|
|
66
|
+
: ['sponsoring', 'stellarAccountStatus'],
|
|
67
|
+
});
|
|
68
|
+
queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET] });
|
|
69
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { SpokeChainKey } from '@sodax/sdk';
|
|
2
2
|
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
import { useSodaxContext } from './useSodaxContext.js';
|
|
4
|
+
import { resolveBtcReadAddress } from '../bitcoin/resolveBtcReadAddress.js';
|
|
4
5
|
import type { Address } from 'viem';
|
|
5
6
|
import type { ReadHookParams } from './types.js';
|
|
6
7
|
|
|
@@ -44,7 +45,10 @@ export function useGetUserHubWalletAddress({
|
|
|
44
45
|
if (!spokeChainId || !spokeAddress) {
|
|
45
46
|
throw new Error('Spoke chain id and address are required');
|
|
46
47
|
}
|
|
47
|
-
return await sodax.hubProvider.getUserHubWalletAddress(
|
|
48
|
+
return await sodax.hubProvider.getUserHubWalletAddress(
|
|
49
|
+
resolveBtcReadAddress(spokeChainId, spokeAddress),
|
|
50
|
+
spokeChainId,
|
|
51
|
+
);
|
|
48
52
|
},
|
|
49
53
|
enabled: !!spokeChainId && !!spokeAddress,
|
|
50
54
|
refetchInterval: false,
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { ChainKeys, type SpokeChainKey } from '@sodax/sdk';
|
|
2
|
+
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
3
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
4
|
+
import type { ReadHookParams } from './types.js';
|
|
5
|
+
|
|
6
|
+
export type UseNearStorageCheckParams = ReadHookParams<
|
|
7
|
+
boolean,
|
|
8
|
+
{
|
|
9
|
+
token: string | undefined;
|
|
10
|
+
accountId: string | undefined;
|
|
11
|
+
chainId: SpokeChainKey | undefined;
|
|
12
|
+
}
|
|
13
|
+
>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether `accountId` is NEP-141 storage-registered for `token` on NEAR — the receive-side
|
|
17
|
+
* prerequisite for any leg that delivers a token to the user on NEAR (swap output on NEAR, bridge
|
|
18
|
+
* into NEAR, money-market borrow/withdraw to NEAR). NEAR's analogue of a Stellar trustline.
|
|
19
|
+
*
|
|
20
|
+
* Returns `true` (no gate) when `chainId` is not NEAR, mirroring how the Stellar trustline check
|
|
21
|
+
* short-circuits off-chain. Native NEAR is not a NEP-141 token, so the SDK reports it as registered.
|
|
22
|
+
*
|
|
23
|
+
* Pair with {@link useRegisterNearStorage} to perform the one-time `storage_deposit` when this
|
|
24
|
+
* resolves to `false`.
|
|
25
|
+
*/
|
|
26
|
+
export function useNearStorageCheck({
|
|
27
|
+
params,
|
|
28
|
+
queryOptions,
|
|
29
|
+
}: UseNearStorageCheckParams = {}): UseQueryResult<boolean, Error> {
|
|
30
|
+
const { sodax } = useSodaxContext();
|
|
31
|
+
const token = params?.token;
|
|
32
|
+
const accountId = params?.accountId;
|
|
33
|
+
const chainId = params?.chainId;
|
|
34
|
+
|
|
35
|
+
return useQuery<boolean, Error>({
|
|
36
|
+
queryKey: ['shared', 'nearStorageCheck', chainId, token, accountId],
|
|
37
|
+
queryFn: async () => {
|
|
38
|
+
if (chainId !== ChainKeys.NEAR_MAINNET) return true;
|
|
39
|
+
if (!token || !accountId) return false;
|
|
40
|
+
return sodax.spoke.near.isStorageRegistered(token, accountId);
|
|
41
|
+
},
|
|
42
|
+
enabled: !!token && !!accountId,
|
|
43
|
+
...queryOptions,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { GetWalletProviderType, INearWalletProvider, Result, SpokeChainKey } from '@sodax/sdk';
|
|
2
|
+
import { resolveNearStorageGate } from '../../utils/nearStorageGate.js';
|
|
3
|
+
import { useNearStorageCheck } from './useNearStorageCheck.js';
|
|
4
|
+
import { useRegisterNearStorage } from './useRegisterNearStorage.js';
|
|
5
|
+
|
|
6
|
+
interface UseNearStorageGateParams {
|
|
7
|
+
/** Destination chain the token is delivered on. */
|
|
8
|
+
dstChainKey: SpokeChainKey;
|
|
9
|
+
/** Destination token address the recipient must be registered for. */
|
|
10
|
+
token: string | undefined;
|
|
11
|
+
/** Recipient NEAR account id. */
|
|
12
|
+
accountId: string | undefined;
|
|
13
|
+
/** Destination wallet provider; only consumed when it is the NEAR provider. */
|
|
14
|
+
walletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface NearStorageGate {
|
|
18
|
+
/** Destination is NEAR. */
|
|
19
|
+
isNear: boolean;
|
|
20
|
+
/** Destination is NEAR and the recipient is not yet storage-registered for `token`. */
|
|
21
|
+
needsRegistration: boolean;
|
|
22
|
+
/** The downstream action must stay disabled while the gate is unresolved or unmet. */
|
|
23
|
+
blocksAction: boolean;
|
|
24
|
+
/** The registration-status query is actively fetching. */
|
|
25
|
+
isChecking: boolean;
|
|
26
|
+
/** A `storage_deposit` tx is in flight. */
|
|
27
|
+
isRegistering: boolean;
|
|
28
|
+
/** Submit the `storage_deposit`; resolves to the SDK `Result` or `undefined` if inputs are missing. */
|
|
29
|
+
registerStorage: () => Promise<Result<string> | undefined>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* NEP-141 storage-registration gate for flows that deliver a token to a user on NEAR.
|
|
34
|
+
*/
|
|
35
|
+
export function useNearStorageGate({
|
|
36
|
+
dstChainKey,
|
|
37
|
+
token,
|
|
38
|
+
accountId,
|
|
39
|
+
walletProvider,
|
|
40
|
+
}: UseNearStorageGateParams): NearStorageGate {
|
|
41
|
+
const nearWalletProvider = walletProvider?.chainType === 'NEAR' ? (walletProvider as INearWalletProvider) : undefined;
|
|
42
|
+
|
|
43
|
+
const storageCheck = useNearStorageCheck({ params: { token, accountId, chainId: dstChainKey } });
|
|
44
|
+
const { mutateAsyncSafe: register, isPending: isRegistering } = useRegisterNearStorage();
|
|
45
|
+
const { isNear, needsRegistration, blocksAction } = resolveNearStorageGate(dstChainKey, storageCheck);
|
|
46
|
+
|
|
47
|
+
const registerStorage = async (): Promise<Result<string> | undefined> => {
|
|
48
|
+
if (!nearWalletProvider || !token || !accountId) return undefined;
|
|
49
|
+
return register({ token, accountId, walletProvider: nearWalletProvider });
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
isNear,
|
|
54
|
+
needsRegistration,
|
|
55
|
+
blocksAction,
|
|
56
|
+
isChecking: storageCheck.isLoading,
|
|
57
|
+
isRegistering,
|
|
58
|
+
registerStorage,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { ChainKeys, type INearWalletProvider } from '@sodax/sdk';
|
|
2
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
3
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
4
|
+
import type { MutationHookParams } from './types.js';
|
|
5
|
+
import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
|
|
6
|
+
|
|
7
|
+
export type UseRegisterNearStorageVars = {
|
|
8
|
+
token: string;
|
|
9
|
+
accountId: string;
|
|
10
|
+
walletProvider: INearWalletProvider;
|
|
11
|
+
/** Storage bond override; defaults to the SDK's `NEAR_STORAGE_DEPOSIT` (0.00125 NEAR). */
|
|
12
|
+
deposit?: bigint;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Submit a NEP-141 `storage_deposit` so `accountId` can receive `token` on NEAR. NEAR's analogue of
|
|
17
|
+
* requesting a Stellar trustline; pair with {@link useNearStorageCheck} and call this when the check
|
|
18
|
+
* resolves to `false`. The recipient's NEAR wallet signs the registration tx.
|
|
19
|
+
*
|
|
20
|
+
* Pure mutation: pass `{ token, accountId, walletProvider }` to `mutate(...)`. The hook itself only
|
|
21
|
+
* takes the structural `mutationOptions` slot. `registerStorage` throws natively (no `Result<T>`),
|
|
22
|
+
* so this hook is registered as `nativeThrow` in the mutation contract. On success it invalidates
|
|
23
|
+
* the matching {@link useNearStorageCheck} query.
|
|
24
|
+
*/
|
|
25
|
+
export function useRegisterNearStorage({
|
|
26
|
+
mutationOptions,
|
|
27
|
+
}: MutationHookParams<string, UseRegisterNearStorageVars> = {}): SafeUseMutationResult<
|
|
28
|
+
string,
|
|
29
|
+
Error,
|
|
30
|
+
UseRegisterNearStorageVars
|
|
31
|
+
> {
|
|
32
|
+
const { sodax } = useSodaxContext();
|
|
33
|
+
const queryClient = useQueryClient();
|
|
34
|
+
return useSafeMutation<string, Error, UseRegisterNearStorageVars>({
|
|
35
|
+
mutationKey: ['shared', 'registerNearStorage'],
|
|
36
|
+
...mutationOptions,
|
|
37
|
+
mutationFn: async ({ token, accountId, walletProvider, deposit }) =>
|
|
38
|
+
sodax.spoke.near.registerStorage({ token, accountId, walletProvider, deposit, raw: false }),
|
|
39
|
+
onSuccess: async (data, vars, ctx) => {
|
|
40
|
+
queryClient.invalidateQueries({
|
|
41
|
+
queryKey: ['shared', 'nearStorageCheck', ChainKeys.NEAR_MAINNET, vars.token, vars.accountId],
|
|
42
|
+
});
|
|
43
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
}
|
|
@@ -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', token] });
|
|
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
|
+
});
|