@sodax/dapp-kit 2.2.0 → 2.3.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.
Files changed (30) hide show
  1. package/README.md +176 -166
  2. package/dist/index.d.ts +313 -30
  3. package/dist/index.mjs +392 -3
  4. package/package.json +5 -5
  5. package/src/hooks/_apiKeyWire.test.ts +10 -0
  6. package/src/hooks/_mutationContract.test.ts +4 -0
  7. package/src/hooks/bridge/index.ts +2 -0
  8. package/src/hooks/bridge/useBridgeApprovalStrategy.test.ts +75 -0
  9. package/src/hooks/bridge/useBridgeApprovalStrategy.ts +53 -0
  10. package/src/hooks/bridge/useBridgeWithApproval.test.ts +73 -0
  11. package/src/hooks/bridge/useBridgeWithApproval.ts +48 -0
  12. package/src/hooks/leverageYield/index.ts +2 -0
  13. package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.test.ts +82 -0
  14. package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.ts +55 -0
  15. package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.test.ts +73 -0
  16. package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.ts +48 -0
  17. package/src/hooks/shared/useNearStorageGate.ts +10 -4
  18. package/src/hooks/swap/index.ts +3 -0
  19. package/src/hooks/swap/useSwapApprovalStrategy.test.ts +92 -0
  20. package/src/hooks/swap/useSwapApprovalStrategy.ts +54 -0
  21. package/src/hooks/swap/useSwapLifecycle.test.ts +329 -0
  22. package/src/hooks/swap/useSwapLifecycle.ts +212 -0
  23. package/src/hooks/swap/useSwapWithApproval.test.ts +63 -0
  24. package/src/hooks/swap/useSwapWithApproval.ts +45 -0
  25. package/src/hooks/swapsApi/index.ts +1 -0
  26. package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.test.ts +331 -0
  27. package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.ts +183 -0
  28. package/src/utils/nearStorageGate.ts +4 -1
  29. package/src/utils/swapLifecycle.test.ts +292 -0
  30. package/src/utils/swapLifecycle.ts +183 -0
@@ -0,0 +1,73 @@
1
+ import { ChainKeys } from '@sodax/sdk';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ const VARS = {
5
+ params: { srcChainKey: ChainKeys.BSC_MAINNET, dstChainKey: ChainKeys.ARBITRUM_MAINNET },
6
+ walletProvider: {},
7
+ };
8
+
9
+ type CapturedMutation = {
10
+ mutationKey: unknown;
11
+ mutationFn: (vars: unknown) => Promise<unknown>;
12
+ onSuccess: (data: unknown, vars: typeof VARS, ctx: unknown) => Promise<void>;
13
+ };
14
+ let captured: CapturedMutation;
15
+ const invalidateQueries = vi.fn();
16
+ const bridgeWithApproval = vi.fn();
17
+
18
+ vi.mock('../shared/useSodaxContext.js', () => ({
19
+ useSodaxContext: () => ({ sodax: { bridge: { bridgeWithApproval } } }),
20
+ }));
21
+ vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
22
+ vi.mock('../shared/useSafeMutation.js', () => ({
23
+ useSafeMutation: (options: CapturedMutation) => {
24
+ captured = options;
25
+ return {};
26
+ },
27
+ }));
28
+
29
+ const { useBridgeWithApproval } = await import('./useBridgeWithApproval.js');
30
+
31
+ beforeEach(() => {
32
+ vi.clearAllMocks();
33
+ });
34
+
35
+ describe('useBridgeWithApproval', () => {
36
+ it('keys the mutation under bridge and calls bridgeWithApproval in signed mode', async () => {
37
+ bridgeWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
38
+ useBridgeWithApproval();
39
+
40
+ expect(captured.mutationKey).toEqual(['bridge', 'bridgeWithApproval']);
41
+ await expect(captured.mutationFn(VARS)).resolves.toEqual({ approvalStrategy: 'atomic-batch' });
42
+ expect(bridgeWithApproval).toHaveBeenCalledWith({ ...VARS, raw: false });
43
+ });
44
+
45
+ it('passes a batch resume through to the SDK', async () => {
46
+ bridgeWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
47
+ useBridgeWithApproval();
48
+ const resume = { ...VARS, resumeBatchId: 'batch-1', resumeBatchCallCount: 2 };
49
+
50
+ await captured.mutationFn(resume);
51
+
52
+ expect(bridgeWithApproval).toHaveBeenCalledWith({ ...resume, raw: false });
53
+ });
54
+
55
+ it('throws the SDK error so React Query sees a failure', async () => {
56
+ const error = new Error('USER_REJECTED');
57
+ bridgeWithApproval.mockResolvedValueOnce({ ok: false, error });
58
+ useBridgeWithApproval();
59
+
60
+ await expect(captured.mutationFn(VARS)).rejects.toBe(error);
61
+ });
62
+
63
+ it('invalidates allowance and approval strategy on success, then runs the consumer callback', async () => {
64
+ const onSuccess = vi.fn();
65
+ useBridgeWithApproval({ mutationOptions: { onSuccess } });
66
+
67
+ await captured.onSuccess({}, VARS, undefined);
68
+
69
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['bridge', 'allowance'] });
70
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['bridge', 'approvalStrategy'] });
71
+ expect(onSuccess).toHaveBeenCalledOnce();
72
+ });
73
+ });
@@ -0,0 +1,48 @@
1
+ import { useQueryClient } from '@tanstack/react-query';
2
+ import type { BridgeWithApprovalParams, BridgeWithApprovalResponse, SpokeChainKey } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
5
+ import type { MutationHookParams } from '../shared/types.js';
6
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
7
+ import { unwrapResult } from '../shared/unwrapResult.js';
8
+
9
+ /**
10
+ * Mutation variables for {@link useBridgeWithApproval}: `useBridge`'s, plus `allowAccountUpgrade`, `resumeBatchId` and
11
+ * `resumeBatchCallCount`.
12
+ */
13
+ export type UseBridgeWithApprovalVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
14
+ BridgeWithApprovalParams<K>,
15
+ 'raw'
16
+ >;
17
+
18
+ /**
19
+ * `useBridge` with the source-token approval folded in (`sodax.bridge.bridgeWithApproval`): no approval
20
+ * when the allowance suffices, approve + deposit as one EIP-5792 batch (one signature) on a
21
+ * batch-capable EVM wallet, otherwise approve, wait for it, then bridge. `data.approvalStrategy`
22
+ * says which ran; {@link useBridgeApprovalStrategy} predicts it.
23
+ *
24
+ * Throws on SDK failure so React Query's error model engages. On success invalidates balances and
25
+ * the bridge allowance and approval-strategy queries.
26
+ */
27
+ export function useBridgeWithApproval<K extends SpokeChainKey = SpokeChainKey>({
28
+ mutationOptions,
29
+ }: MutationHookParams<BridgeWithApprovalResponse, UseBridgeWithApprovalVars<K>> = {}): SafeUseMutationResult<
30
+ BridgeWithApprovalResponse,
31
+ Error,
32
+ UseBridgeWithApprovalVars<K>
33
+ > {
34
+ const { sodax } = useSodaxContext();
35
+ const queryClient = useQueryClient();
36
+
37
+ return useSafeMutation<BridgeWithApprovalResponse, Error, UseBridgeWithApprovalVars<K>>({
38
+ mutationKey: ['bridge', 'bridgeWithApproval'],
39
+ ...mutationOptions,
40
+ mutationFn: async vars => unwrapResult(await sodax.bridge.bridgeWithApproval({ ...vars, raw: false })),
41
+ onSuccess: async (data, vars, ctx) => {
42
+ invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
43
+ queryClient.invalidateQueries({ queryKey: ['bridge', 'allowance'] });
44
+ queryClient.invalidateQueries({ queryKey: ['bridge', 'approvalStrategy'] });
45
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
46
+ },
47
+ });
48
+ }
@@ -8,6 +8,8 @@ export * from './useLeverageYieldDeposit.js';
8
8
  export * from './useLeverageYieldNotifySolver.js';
9
9
  export * from './useLeverageYieldDetailedStatus.js';
10
10
  export * from './useLeverageYieldVaultSwap.js';
11
+ export * from './useLeverageYieldVaultSwapWithApproval.js';
12
+ export * from './useLeverageYieldApprovalStrategy.js';
11
13
  export * from './useLeverageYieldWithdraw.js';
12
14
  export * from './useLeveragePositions.js';
13
15
  export * from './useLeveragePositionAccount.js';
@@ -0,0 +1,82 @@
1
+ import { ChainKeys } from '@sodax/sdk';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ type CapturedQuery = {
5
+ queryKey: unknown[];
6
+ queryFn: () => Promise<unknown>;
7
+ enabled: boolean;
8
+ refetchInterval?: unknown;
9
+ };
10
+ let captured: CapturedQuery;
11
+ const getApprovalStrategy = vi.fn();
12
+
13
+ vi.mock('../shared/useSodaxContext.js', () => ({
14
+ useSodaxContext: () => ({ sodax: { leverageYield: { getApprovalStrategy } } }),
15
+ }));
16
+ vi.mock('@tanstack/react-query', () => ({
17
+ useQuery: (options: CapturedQuery) => {
18
+ captured = options;
19
+ return {};
20
+ },
21
+ }));
22
+
23
+ const { useLeverageYieldApprovalStrategy } = await import('./useLeverageYieldApprovalStrategy.js');
24
+
25
+ const PAYLOAD = {
26
+ params: {
27
+ inputToken: '0x35751007a407ca6FEFfE80b3cB397736D2cf4dbe',
28
+ outputToken: '0xD09de2f5070699A909c0FD32fb5A909d3886701D',
29
+ inputAmount: 1_000_000n,
30
+ minOutputAmount: 900_000n,
31
+ deadline: 0n,
32
+ allowPartialFill: false,
33
+ srcChainKey: ChainKeys.ARBITRUM_MAINNET,
34
+ dstChainKey: ChainKeys.SONIC_MAINNET,
35
+ srcAddress: '0x1111111111111111111111111111111111111111',
36
+ dstAddress: '0x2222222222222222222222222222222222222222',
37
+ solver: '0x0000000000000000000000000000000000000000',
38
+ data: '0x',
39
+ },
40
+ } as const;
41
+ const WALLET = { chainType: 'EVM' } as never;
42
+
43
+ beforeEach(() => {
44
+ vi.clearAllMocks();
45
+ });
46
+
47
+ describe('useLeverageYieldApprovalStrategy', () => {
48
+ it('keys on chain, owner, token, stringified amount and direction', () => {
49
+ useLeverageYieldApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET } });
50
+ expect(captured.queryKey).toEqual([
51
+ 'leverageYield',
52
+ 'approvalStrategy',
53
+ ChainKeys.ARBITRUM_MAINNET,
54
+ PAYLOAD.params.srcAddress,
55
+ PAYLOAD.params.inputToken,
56
+ '1000000',
57
+ false,
58
+ true,
59
+ ]);
60
+ expect(captured.enabled).toBe(true);
61
+ expect(captured.refetchInterval).toBeUndefined();
62
+ });
63
+
64
+ it('spreads the payload into the SDK call and unwraps the strategy', async () => {
65
+ getApprovalStrategy.mockResolvedValueOnce({ ok: true, value: 'atomic-batch' });
66
+ useLeverageYieldApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET } });
67
+
68
+ await expect(captured.queryFn()).resolves.toBe('atomic-batch');
69
+ expect(getApprovalStrategy).toHaveBeenCalledWith({
70
+ ...PAYLOAD,
71
+ walletProvider: WALLET,
72
+ allowAccountUpgrade: true,
73
+ });
74
+ });
75
+
76
+ it('stays disabled until both the payload and the wallet are known', () => {
77
+ useLeverageYieldApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: undefined } });
78
+ expect(captured.enabled).toBe(false);
79
+ useLeverageYieldApprovalStrategy({ params: { payload: undefined, walletProvider: WALLET } });
80
+ expect(captured.enabled).toBe(false);
81
+ });
82
+ });
@@ -0,0 +1,55 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { ApprovalStrategy, GetWalletProviderType, LeverageYieldSwapPayload, SpokeChainKey } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import type { ReadHookParams } from '../shared/types.js';
5
+ import { unwrapResult } from '../shared/unwrapResult.js';
6
+
7
+ export type UseLeverageYieldApprovalStrategyParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<
8
+ ApprovalStrategy,
9
+ {
10
+ /** The payload `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` built. */
11
+ payload: LeverageYieldSwapPayload | undefined;
12
+ walletProvider: GetWalletProviderType<K> | undefined;
13
+ /** `false` keeps a wallet that would first ask to upgrade the account (EIP-5792 `'ready'`) off the batch path. Defaults to `true`. */
14
+ allowAccountUpgrade?: boolean;
15
+ }
16
+ >;
17
+
18
+ /**
19
+ * Which approval path {@link useLeverageYieldVaultSwapWithApproval} would take: `'not-required'`
20
+ * (always for a withdraw), `'atomic-batch'` (approve + deposit in one EIP-5792 signature) or
21
+ * `'sequential'` (approve, then deposit). Use it to label the deposit button. Pass the same
22
+ * `allowAccountUpgrade` you give the vault swap.
23
+ *
24
+ * Not polled: the vault swap invalidates it on success and re-reads the strategy at execution.
25
+ */
26
+ export function useLeverageYieldApprovalStrategy<K extends SpokeChainKey = SpokeChainKey>({
27
+ params,
28
+ queryOptions,
29
+ }: UseLeverageYieldApprovalStrategyParams<K> = {}): UseQueryResult<ApprovalStrategy, Error> {
30
+ const { sodax } = useSodaxContext();
31
+ const payload = params?.payload;
32
+ const walletProvider = params?.walletProvider;
33
+ const allowAccountUpgrade = params?.allowAccountUpgrade ?? true;
34
+
35
+ return useQuery<ApprovalStrategy, Error>({
36
+ queryKey: [
37
+ 'leverageYield',
38
+ 'approvalStrategy',
39
+ payload?.params.srcChainKey,
40
+ payload?.params.srcAddress,
41
+ payload?.params.inputToken,
42
+ payload?.params.inputAmount.toString(),
43
+ payload?.hubWalletSwap ?? false,
44
+ allowAccountUpgrade,
45
+ ],
46
+ queryFn: async () => {
47
+ if (!payload || !walletProvider) throw new Error('payload and walletProvider are required');
48
+ return unwrapResult(
49
+ await sodax.leverageYield.getApprovalStrategy({ ...payload, walletProvider, allowAccountUpgrade }),
50
+ );
51
+ },
52
+ enabled: !!payload && !!walletProvider,
53
+ ...queryOptions,
54
+ });
55
+ }
@@ -0,0 +1,73 @@
1
+ import { ChainKeys } from '@sodax/sdk';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ const VARS = {
5
+ params: { srcChainKey: ChainKeys.ARBITRUM_MAINNET, dstChainKey: ChainKeys.SONIC_MAINNET },
6
+ walletProvider: {},
7
+ };
8
+
9
+ type CapturedMutation = {
10
+ mutationKey: unknown;
11
+ mutationFn: (vars: unknown) => Promise<unknown>;
12
+ onSuccess: (data: unknown, vars: typeof VARS, ctx: unknown) => Promise<void>;
13
+ };
14
+ let captured: CapturedMutation;
15
+ const invalidateQueries = vi.fn();
16
+ const vaultSwapWithApproval = vi.fn();
17
+
18
+ vi.mock('../shared/useSodaxContext.js', () => ({
19
+ useSodaxContext: () => ({ sodax: { leverageYield: { vaultSwapWithApproval } } }),
20
+ }));
21
+ vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
22
+ vi.mock('../shared/useSafeMutation.js', () => ({
23
+ useSafeMutation: (options: CapturedMutation) => {
24
+ captured = options;
25
+ return {};
26
+ },
27
+ }));
28
+
29
+ const { useLeverageYieldVaultSwapWithApproval } = await import('./useLeverageYieldVaultSwapWithApproval.js');
30
+
31
+ beforeEach(() => {
32
+ vi.clearAllMocks();
33
+ });
34
+
35
+ describe('useLeverageYieldVaultSwapWithApproval', () => {
36
+ it('keys the mutation under leverageYield and calls vaultSwapWithApproval in signed mode', async () => {
37
+ vaultSwapWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
38
+ useLeverageYieldVaultSwapWithApproval();
39
+
40
+ expect(captured.mutationKey).toEqual(['leverageYield', 'vaultSwapWithApproval']);
41
+ await expect(captured.mutationFn(VARS)).resolves.toEqual({ approvalStrategy: 'atomic-batch' });
42
+ expect(vaultSwapWithApproval).toHaveBeenCalledWith({ ...VARS, raw: false });
43
+ });
44
+
45
+ it('passes a batch resume through to the SDK', async () => {
46
+ vaultSwapWithApproval.mockResolvedValueOnce({ ok: true, value: { approvalStrategy: 'atomic-batch' } });
47
+ useLeverageYieldVaultSwapWithApproval();
48
+ const resume = { ...VARS, resumeBatchId: 'batch-1', resumeBatchCallCount: 2 };
49
+
50
+ await captured.mutationFn(resume);
51
+
52
+ expect(vaultSwapWithApproval).toHaveBeenCalledWith({ ...resume, raw: false });
53
+ });
54
+
55
+ it('throws the SDK error so React Query sees a failure', async () => {
56
+ const error = new Error('USER_REJECTED');
57
+ vaultSwapWithApproval.mockResolvedValueOnce({ ok: false, error });
58
+ useLeverageYieldVaultSwapWithApproval();
59
+
60
+ await expect(captured.mutationFn(VARS)).rejects.toBe(error);
61
+ });
62
+
63
+ it('invalidates the deposit allowance and approval strategy on success, then runs the consumer callback', async () => {
64
+ const onSuccess = vi.fn();
65
+ useLeverageYieldVaultSwapWithApproval({ mutationOptions: { onSuccess } });
66
+
67
+ await captured.onSuccess({}, VARS, undefined);
68
+
69
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swap', 'allowance'] });
70
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['leverageYield', 'approvalStrategy'] });
71
+ expect(onSuccess).toHaveBeenCalledOnce();
72
+ });
73
+ });
@@ -0,0 +1,48 @@
1
+ import { useQueryClient } from '@tanstack/react-query';
2
+ import type { SpokeChainKey, VaultSwapWithApprovalParams, VaultSwapWithApprovalResponse } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
5
+ import type { MutationHookParams } from '../shared/types.js';
6
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
7
+ import { unwrapResult } from '../shared/unwrapResult.js';
8
+
9
+ /**
10
+ * Mutation variables for {@link useLeverageYieldVaultSwapWithApproval}: `useLeverageYieldVaultSwap`'s, plus
11
+ * `allowAccountUpgrade`, `resumeBatchId` and `resumeBatchCallCount`.
12
+ */
13
+ export type UseLeverageYieldVaultSwapWithApprovalVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
14
+ VaultSwapWithApprovalParams<K>,
15
+ 'raw'
16
+ >;
17
+
18
+ /**
19
+ * `useLeverageYieldVaultSwap` with the deposit's source-token approval folded in
20
+ * (`sodax.leverageYield.vaultSwapWithApproval`): approve + deposit as one EIP-5792 batch (one
21
+ * signature) on a batch-capable EVM wallet, otherwise approve, wait for it, then deposit. A withdraw
22
+ * (`hubWalletSwap`) needs no approval and runs as `useLeverageYieldVaultSwap` does.
23
+ * `data.approvalStrategy` says which path ran; {@link useLeverageYieldApprovalStrategy} predicts it.
24
+ *
25
+ * Throws on SDK failure so React Query's error model engages. On success invalidates balances, the
26
+ * deposit allowance (read through `useSwapAllowance`) and the approval-strategy query.
27
+ */
28
+ export function useLeverageYieldVaultSwapWithApproval<K extends SpokeChainKey = SpokeChainKey>({
29
+ mutationOptions,
30
+ }: MutationHookParams<
31
+ VaultSwapWithApprovalResponse,
32
+ UseLeverageYieldVaultSwapWithApprovalVars<K>
33
+ > = {}): SafeUseMutationResult<VaultSwapWithApprovalResponse, Error, UseLeverageYieldVaultSwapWithApprovalVars<K>> {
34
+ const { sodax } = useSodaxContext();
35
+ const queryClient = useQueryClient();
36
+
37
+ return useSafeMutation<VaultSwapWithApprovalResponse, Error, UseLeverageYieldVaultSwapWithApprovalVars<K>>({
38
+ mutationKey: ['leverageYield', 'vaultSwapWithApproval'],
39
+ ...mutationOptions,
40
+ mutationFn: async vars => unwrapResult(await sodax.leverageYield.vaultSwapWithApproval({ ...vars, raw: false })),
41
+ onSuccess: async (data, vars, ctx) => {
42
+ invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
43
+ queryClient.invalidateQueries({ queryKey: ['swap', 'allowance'] });
44
+ queryClient.invalidateQueries({ queryKey: ['leverageYield', 'approvalStrategy'] });
45
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
46
+ },
47
+ });
48
+ }
@@ -3,9 +3,9 @@ import { resolveNearStorageGate } from '../../utils/nearStorageGate.js';
3
3
  import { useNearStorageCheck } from './useNearStorageCheck.js';
4
4
  import { useRegisterNearStorage } from './useRegisterNearStorage.js';
5
5
 
6
- interface UseNearStorageGateParams {
7
- /** Destination chain the token is delivered on. */
8
- dstChainKey: SpokeChainKey;
6
+ export interface UseNearStorageGateParams {
7
+ /** Destination chain the token is delivered on; `undefined` (not chosen yet) leaves the gate inert. */
8
+ dstChainKey: SpokeChainKey | undefined;
9
9
  /** Destination token address the recipient must be registered for. */
10
10
  token: string | undefined;
11
11
  /** Recipient NEAR account id. */
@@ -14,7 +14,7 @@ interface UseNearStorageGateParams {
14
14
  walletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
15
15
  }
16
16
 
17
- interface NearStorageGate {
17
+ export interface NearStorageGate {
18
18
  /** Destination is NEAR. */
19
19
  isNear: boolean;
20
20
  /** Destination is NEAR and the recipient is not yet storage-registered for `token`. */
@@ -23,6 +23,10 @@ interface NearStorageGate {
23
23
  blocksAction: boolean;
24
24
  /** The registration-status query is actively fetching. */
25
25
  isChecking: boolean;
26
+ /** Destination is NEAR and the registration check failed, so whether the recipient can receive is unknown. */
27
+ checkFailed: boolean;
28
+ /** Re-run the registration check. */
29
+ retry: () => void;
26
30
  /** A `storage_deposit` tx is in flight. */
27
31
  isRegistering: boolean;
28
32
  /** Submit the `storage_deposit`; resolves to the SDK `Result` or `undefined` if inputs are missing. */
@@ -54,6 +58,8 @@ export function useNearStorageGate({
54
58
  needsRegistration,
55
59
  blocksAction,
56
60
  isChecking: storageCheck.isLoading,
61
+ checkFailed: isNear && storageCheck.isError && storageCheck.data === undefined,
62
+ retry: () => void storageCheck.refetch(),
57
63
  isRegistering,
58
64
  registerStorage,
59
65
  };
@@ -4,6 +4,9 @@ export * from './useStatus.js';
4
4
  export * from './useDetailedStatus.js';
5
5
  export * from './useSwapAllowance.js';
6
6
  export * from './useSwapApprove.js';
7
+ export * from './useSwapApprovalStrategy.js';
8
+ export * from './useSwapWithApproval.js';
9
+ export * from './useSwapLifecycle.js';
7
10
  export * from './useCancelSwap.js';
8
11
  export * from './useCreateLimitOrder.js';
9
12
  export * from './useCancelLimitOrder.js';
@@ -0,0 +1,92 @@
1
+ import { ChainKeys } from '@sodax/sdk';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ type CapturedQuery = {
5
+ queryKey: unknown[];
6
+ queryFn: () => Promise<unknown>;
7
+ enabled: boolean;
8
+ refetchInterval?: unknown;
9
+ };
10
+ let captured: CapturedQuery;
11
+ const getApprovalStrategy = vi.fn();
12
+
13
+ vi.mock('../shared/useSodaxContext.js', () => ({
14
+ useSodaxContext: () => ({ sodax: { swaps: { getApprovalStrategy } } }),
15
+ }));
16
+ vi.mock('@tanstack/react-query', () => ({
17
+ useQuery: (options: CapturedQuery) => {
18
+ captured = options;
19
+ return {};
20
+ },
21
+ }));
22
+
23
+ const { useSwapApprovalStrategy } = await import('./useSwapApprovalStrategy.js');
24
+
25
+ const PAYLOAD = {
26
+ inputToken: '0x2170Ed0880ac9A755fd29B2688956BD959F933F8',
27
+ outputToken: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f',
28
+ inputAmount: 1_000_000n,
29
+ minOutputAmount: 900_000n,
30
+ deadline: 0n,
31
+ allowPartialFill: false,
32
+ srcChainKey: ChainKeys.BSC_MAINNET,
33
+ dstChainKey: ChainKeys.ARBITRUM_MAINNET,
34
+ srcAddress: '0x1111111111111111111111111111111111111111',
35
+ dstAddress: '0x2222222222222222222222222222222222222222',
36
+ solver: '0x0000000000000000000000000000000000000000',
37
+ data: '0x',
38
+ } as const;
39
+ const WALLET = { chainType: 'EVM' } as never;
40
+
41
+ beforeEach(() => {
42
+ vi.clearAllMocks();
43
+ });
44
+
45
+ describe('useSwapApprovalStrategy', () => {
46
+ it('keys on chain, owner, token and stringified amount', () => {
47
+ useSwapApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET } });
48
+ expect(captured.queryKey).toEqual([
49
+ 'swap',
50
+ 'approvalStrategy',
51
+ ChainKeys.BSC_MAINNET,
52
+ PAYLOAD.srcAddress,
53
+ PAYLOAD.inputToken,
54
+ '1000000',
55
+ true,
56
+ ]);
57
+ expect(captured.enabled).toBe(true);
58
+ expect(captured.refetchInterval).toBeUndefined();
59
+ });
60
+
61
+ it('unwraps the SDK strategy', async () => {
62
+ getApprovalStrategy.mockResolvedValueOnce({ ok: true, value: 'atomic-batch' });
63
+ useSwapApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET } });
64
+
65
+ await expect(captured.queryFn()).resolves.toBe('atomic-batch');
66
+ expect(getApprovalStrategy).toHaveBeenCalledWith({
67
+ params: PAYLOAD,
68
+ walletProvider: WALLET,
69
+ allowAccountUpgrade: true,
70
+ });
71
+ });
72
+
73
+ it('keys on and forwards allowAccountUpgrade: false', async () => {
74
+ getApprovalStrategy.mockResolvedValueOnce({ ok: true, value: 'sequential' });
75
+ useSwapApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET, allowAccountUpgrade: false } });
76
+
77
+ expect(captured.queryKey.at(-1)).toBe(false);
78
+ await expect(captured.queryFn()).resolves.toBe('sequential');
79
+ expect(getApprovalStrategy).toHaveBeenCalledWith({
80
+ params: PAYLOAD,
81
+ walletProvider: WALLET,
82
+ allowAccountUpgrade: false,
83
+ });
84
+ });
85
+
86
+ it('stays disabled until both the payload and the wallet are known', () => {
87
+ useSwapApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: undefined } });
88
+ expect(captured.enabled).toBe(false);
89
+ useSwapApprovalStrategy({ params: { payload: undefined, walletProvider: WALLET } });
90
+ expect(captured.enabled).toBe(false);
91
+ });
92
+ });
@@ -0,0 +1,54 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { CreateIntentParams, GetWalletProviderType, SpokeChainKey, SwapApprovalStrategy } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import type { ReadHookParams } from '../shared/types.js';
5
+ import { unwrapResult } from '../shared/unwrapResult.js';
6
+
7
+ export type UseSwapApprovalStrategyParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<
8
+ SwapApprovalStrategy,
9
+ {
10
+ payload: CreateIntentParams<K> | undefined;
11
+ walletProvider: GetWalletProviderType<K> | undefined;
12
+ /** `false` keeps a wallet that would first ask to upgrade the account (EIP-5792 `'ready'`) off the batch path. Defaults to `true`. */
13
+ allowAccountUpgrade?: boolean;
14
+ }
15
+ >;
16
+
17
+ /**
18
+ * Which approval path {@link useSwapWithApproval} would take for this swap: `'not-required'`,
19
+ * `'atomic-batch'` (approve + swap in one EIP-5792 signature) or `'sequential'` (approve, then
20
+ * swap). Use it to label the swap button before the user clicks. Pass the same `allowAccountUpgrade`
21
+ * you give the swap.
22
+ *
23
+ * Not polled: `useSwapWithApproval` invalidates it after a successful swap, and the swap itself
24
+ * re-reads the strategy at execution, so a stale label never picks the wrong path.
25
+ */
26
+ export function useSwapApprovalStrategy<K extends SpokeChainKey = SpokeChainKey>({
27
+ params,
28
+ queryOptions,
29
+ }: UseSwapApprovalStrategyParams<K> = {}): UseQueryResult<SwapApprovalStrategy, Error> {
30
+ const { sodax } = useSodaxContext();
31
+ const payload = params?.payload;
32
+ const walletProvider = params?.walletProvider;
33
+ const allowAccountUpgrade = params?.allowAccountUpgrade ?? true;
34
+
35
+ return useQuery<SwapApprovalStrategy, Error>({
36
+ queryKey: [
37
+ 'swap',
38
+ 'approvalStrategy',
39
+ payload?.srcChainKey,
40
+ payload?.srcAddress,
41
+ payload?.inputToken,
42
+ payload?.inputAmount.toString(),
43
+ allowAccountUpgrade,
44
+ ],
45
+ queryFn: async () => {
46
+ if (!payload || !walletProvider) throw new Error('payload and walletProvider are required');
47
+ return unwrapResult(
48
+ await sodax.swaps.getApprovalStrategy({ params: payload, walletProvider, allowAccountUpgrade }),
49
+ );
50
+ },
51
+ enabled: !!payload && !!walletProvider,
52
+ ...queryOptions,
53
+ });
54
+ }