@sodax/dapp-kit 2.2.0-rc.6 → 2.2.0-rc.7

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 (34) hide show
  1. package/README.md +20 -3
  2. package/dist/index.d.ts +107 -13
  3. package/dist/index.mjs +118 -38
  4. package/package.json +4 -4
  5. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.test.ts +144 -0
  6. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.ts +52 -0
  7. package/src/hooks/bridge/index.ts +2 -0
  8. package/src/hooks/bridge/useBridgeDetailedStatus.test.ts +93 -0
  9. package/src/hooks/bridge/useBridgeDetailedStatus.ts +79 -0
  10. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.test.ts +81 -0
  11. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.ts +25 -0
  12. package/src/hooks/bridgeApi/useBridgeApiAllowance.ts +2 -1
  13. package/src/hooks/bridgeApi/useBridgeApiApprove.ts +2 -1
  14. package/src/hooks/bridgeApi/useBridgeApiBridgeableAmount.ts +2 -1
  15. package/src/hooks/bridgeApi/useBridgeApiCreateBridgeIntent.ts +2 -1
  16. package/src/hooks/bridgeApi/useBridgeApiFee.ts +2 -1
  17. package/src/hooks/bridgeApi/useBridgeApiIsBridgeable.ts +2 -1
  18. package/src/hooks/bridgeApi/useBridgeApiSubmitTx.ts +5 -3
  19. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.test.ts +63 -0
  20. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.ts +7 -10
  21. package/src/hooks/bridgeApi/useBridgeApiTokens.ts +2 -1
  22. package/src/hooks/bridgeApi/useBridgeApiTokensByChain.ts +2 -1
  23. package/src/hooks/leverageYield/index.ts +1 -0
  24. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.test.ts +131 -0
  25. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.ts +83 -0
  26. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +13 -3
  27. package/src/hooks/shared/notFoundStreak.ts +59 -0
  28. package/src/hooks/shared/retryUnlessAuthFailure.ts +1 -1
  29. package/src/hooks/{swap/getSwapStatusRefetchInterval.test.ts → shared/solverStatusPolicy.test.ts} +25 -25
  30. package/src/hooks/shared/solverStatusPolicy.ts +117 -0
  31. package/src/hooks/swap/useDetailedStatus.test.ts +65 -21
  32. package/src/hooks/swap/useDetailedStatus.ts +9 -9
  33. package/src/hooks/swap/useStatus.ts +4 -7
  34. package/src/hooks/swap/getSwapStatusRefetchInterval.ts +0 -126
@@ -0,0 +1,79 @@
1
+ import type {
2
+ BridgeDetailedStatusError,
3
+ DetailedBridgeStatus,
4
+ RequestOverrideConfig,
5
+ Result,
6
+ SpokeChainKey,
7
+ } from '@sodax/sdk';
8
+ import { useRef } from 'react';
9
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
10
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
11
+ import type { ReadHookParams } from '../shared/types.js';
12
+ import { advanceNotFoundStreak, INITIAL_NOT_FOUND_STREAK } from '../shared/notFoundStreak.js';
13
+ import {
14
+ getBridgeDetailedStatusRefetchInterval,
15
+ isBridgeNotDelivered,
16
+ } from './getBridgeDetailedStatusRefetchInterval.js';
17
+
18
+ export type UseBridgeDetailedStatusResult = Result<DetailedBridgeStatus, BridgeDetailedStatusError> | undefined;
19
+
20
+ export type UseBridgeDetailedStatusParams = ReadHookParams<
21
+ UseBridgeDetailedStatusResult,
22
+ {
23
+ srcChainKey: SpokeChainKey | undefined;
24
+ srcTxHash: string | undefined;
25
+ apiConfig?: RequestOverrideConfig;
26
+ }
27
+ >;
28
+
29
+ /**
30
+ * Hook for monitoring a bridge from its source-chain transaction.
31
+ *
32
+ * `useBridgeApiSubmitTxStatus` needs the backend to still hold a usable record; this takes
33
+ * `(srcChainKey, srcTxHash)` — the pair you hold after `bridge()` — and routes to whichever source
34
+ * can answer, so it also covers a bridge the client-side fallback completed. `data.value` is
35
+ * discriminated on `source`, and each variant carries that source's payload unmodified.
36
+ *
37
+ * Polls every 3s. Stops once the answering source is terminal (a relay packet always is), once the
38
+ * backend rejects the API key, and — like `useDetailedStatus` — after 40 consecutive *ambiguous*
39
+ * reads, meaning a `LOOKUP_FAILED` whose relay has no packet for the tx. A dependency outage keeps
40
+ * polling instead, so the read recovers by itself; any real answer resets the budget. Override with
41
+ * `queryOptions.refetchInterval`.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const { data } = useBridgeDetailedStatus({ params: { srcChainKey, srcTxHash } });
46
+ * if (data?.ok && data.value.source === 'relay') console.log(data.value.data.dst_tx_hash);
47
+ * ```
48
+ */
49
+ export const useBridgeDetailedStatus = ({
50
+ params,
51
+ queryOptions,
52
+ }: UseBridgeDetailedStatusParams = {}): UseQueryResult<UseBridgeDetailedStatusResult> => {
53
+ const { sodax } = useSodaxContext();
54
+ const srcChainKey = params?.srcChainKey;
55
+ const srcTxHash = params?.srcTxHash;
56
+ const apiConfig = params?.apiConfig;
57
+ // Composite identity: a new bridge must start its own not-delivered budget.
58
+ const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : undefined;
59
+ const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
60
+
61
+ return useQuery({
62
+ queryKey: ['bridge', 'detailedStatus', srcChainKey, srcTxHash],
63
+ queryFn: async () => {
64
+ if (!srcChainKey || !srcTxHash) return undefined;
65
+ return sodax.bridge.getDetailedStatus({ srcChainKey, srcTxHash }, apiConfig);
66
+ },
67
+ enabled: !!srcChainKey && !!srcTxHash,
68
+ refetchInterval: query => {
69
+ notFoundStreakRef.current = advanceNotFoundStreak(
70
+ notFoundStreakRef.current,
71
+ pollKey,
72
+ isBridgeNotDelivered(query.state.data),
73
+ query.state.dataUpdateCount,
74
+ );
75
+ return getBridgeDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
76
+ },
77
+ ...queryOptions,
78
+ });
79
+ };
@@ -0,0 +1,81 @@
1
+ import { SodaxError, type BridgeSubmitTxStatusDataV2 } from '@sodax/sdk';
2
+ import { describe, expect, it } from 'vitest';
3
+ import {
4
+ BRIDGE_SUBMIT_TX_STATUS_POLL_MS,
5
+ getBridgeSubmitTxStatusRefetchInterval,
6
+ } from './getBridgeSubmitTxStatusRefetchInterval.js';
7
+
8
+ /**
9
+ * Guards the polling-stop invariant for `useBridgeApiSubmitTxStatus.refetchInterval`: keep polling
10
+ * a live record, stop on a terminal or abandoned one, and stop on a rejected API key. Tested as a
11
+ * pure function because dapp-kit's vitest runs in the `node` environment.
12
+ */
13
+ const record = (data: Partial<BridgeSubmitTxStatusDataV2>): BridgeSubmitTxStatusDataV2 => ({
14
+ txHash: '0xabc',
15
+ srcChainKey: '0xa4b1.arbitrum',
16
+ status: 'pending',
17
+ processingAttempts: 1,
18
+ ...data,
19
+ });
20
+
21
+ /** A backend failure as `BridgeApiService` surfaces it: the HTTP status lifted onto `context`. */
22
+ const apiError = (status?: number): SodaxError =>
23
+ new SodaxError('EXTERNAL_API_ERROR', `responded with ${status}`, {
24
+ feature: 'backend',
25
+ context: { api: 'bridge', endpoint: '/bridge/submit-tx/status', status },
26
+ });
27
+
28
+ describe('getBridgeSubmitTxStatusRefetchInterval', () => {
29
+ it('polls at the 1s cadence the docs and skills advertise', () => {
30
+ expect(BRIDGE_SUBMIT_TX_STATUS_POLL_MS).toBe(1000);
31
+ });
32
+
33
+ it('keeps polling every in-flight status', () => {
34
+ for (const status of ['pending', 'relaying', 'relayed']) {
35
+ expect(getBridgeSubmitTxStatusRefetchInterval(undefined, record({ status }))).toBe(
36
+ BRIDGE_SUBMIT_TX_STATUS_POLL_MS,
37
+ );
38
+ }
39
+ });
40
+
41
+ it('keeps polling before the first response has landed', () => {
42
+ expect(getBridgeSubmitTxStatusRefetchInterval(undefined, undefined)).toBe(BRIDGE_SUBMIT_TX_STATUS_POLL_MS);
43
+ });
44
+
45
+ it('stops on the two terminal statuses', () => {
46
+ expect(getBridgeSubmitTxStatusRefetchInterval(undefined, record({ status: 'executed' }))).toBe(false);
47
+ expect(getBridgeSubmitTxStatusRefetchInterval(undefined, record({ status: 'failed' }))).toBe(false);
48
+ });
49
+
50
+ it('stops on an abandoned record even while its status is still non-terminal', () => {
51
+ // The backend gave up mid-flight; the record never self-heals, so polling it is dead weight.
52
+ expect(
53
+ getBridgeSubmitTxStatusRefetchInterval(
54
+ undefined,
55
+ record({ status: 'relayed', abandonedAt: '2026-09-17T00:00:00.000Z' }),
56
+ ),
57
+ ).toBe(false);
58
+ });
59
+
60
+ it('stops on a terminal API-key rejection — the defect `retry` alone cannot fix', () => {
61
+ for (const status of [401, 403]) {
62
+ expect(getBridgeSubmitTxStatusRefetchInterval(apiError(status), undefined)).toBe(false);
63
+ }
64
+ });
65
+
66
+ it("keeps polling the apiguard's transient 503 and other non-auth failures", () => {
67
+ // 503 is verification being down, not a rejected key — the SDK excludes it deliberately.
68
+ for (const status of [408, 429, 500, 502, 503, 504]) {
69
+ expect(getBridgeSubmitTxStatusRefetchInterval(apiError(status), undefined)).toBe(BRIDGE_SUBMIT_TX_STATUS_POLL_MS);
70
+ }
71
+ expect(getBridgeSubmitTxStatusRefetchInterval(new Error('ECONNRESET'), undefined)).toBe(
72
+ BRIDGE_SUBMIT_TX_STATUS_POLL_MS,
73
+ );
74
+ });
75
+
76
+ it('stops on an auth failure even when a live record is still cached', () => {
77
+ // Order matters: the key was rejected on a later poll, so the stale in-flight record must not
78
+ // keep the interval alive.
79
+ expect(getBridgeSubmitTxStatusRefetchInterval(apiError(401), record({ status: 'relaying' }))).toBe(false);
80
+ });
81
+ });
@@ -0,0 +1,25 @@
1
+ import { isAuthFailure, type BridgeSubmitTxStatusDataV2 } from '@sodax/sdk';
2
+
3
+ export const BRIDGE_SUBMIT_TX_STATUS_POLL_MS = 1000;
4
+
5
+ /**
6
+ * Polling interval for {@link useBridgeApiSubmitTxStatus}. Stops on a terminal record, on a record
7
+ * the backend abandoned, and on a terminal API-key rejection.
8
+ *
9
+ * `abandonedAt` is terminal even when `status` is still non-terminal (e.g. `'relayed'`) — same rule
10
+ * as the SDK's `pollBackendSubmitTx`. The auth stop is separate from the hook's `retry` policy:
11
+ * `retry` bounds attempts *within* a tick, so without this the interval would keep firing a request
12
+ * a corrected key is the only fix for.
13
+ *
14
+ * Kept in its own pure module (no React/context imports) so it is unit-testable in dapp-kit's
15
+ * `node` test environment — importing the hook itself pulls in `useSodaxContext`. Same reason as
16
+ * `swapsApi/isTerminalSwapIntentStatus`.
17
+ */
18
+ export function getBridgeSubmitTxStatusRefetchInterval(
19
+ error: unknown,
20
+ data: BridgeSubmitTxStatusDataV2 | undefined,
21
+ ): number | false {
22
+ if (isAuthFailure(error)) return false;
23
+ if (data?.status === 'executed' || data?.status === 'failed' || data?.abandonedAt) return false;
24
+ return BRIDGE_SUBMIT_TX_STATUS_POLL_MS;
25
+ }
@@ -1,6 +1,7 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { BridgeAllowanceCheckResponseV2, CreateBridgeIntentParamsV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
6
7
 
@@ -36,7 +37,7 @@ export const useBridgeApiAllowance = ({
36
37
  return unwrapResult(await sodax.api.bridge.checkAllowance(body, apiConfig));
37
38
  },
38
39
  enabled: !!body,
39
- retry: 3,
40
+ retry: retryUnlessAuthFailure,
40
41
  ...queryOptions,
41
42
  });
42
43
  };
@@ -1,5 +1,6 @@
1
1
  import type { BridgeApproveResponseV2, CreateBridgeIntentParamsV2, RequestOverrideConfig } from '@sodax/sdk';
2
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
3
4
  import { unwrapResult } from '../shared/unwrapResult.js';
4
5
  import type { MutationHookParams } from '../shared/types.js';
5
6
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
@@ -37,7 +38,7 @@ export const useBridgeApiApprove = ({
37
38
 
38
39
  return useSafeMutation<BridgeApproveResponseV2, Error, UseBridgeApiApproveVars>({
39
40
  mutationKey: ['bridgeApi', 'approve'],
40
- retry: 3,
41
+ retry: retryUnlessAuthFailure,
41
42
  ...mutationOptions,
42
43
  mutationFn: async ({ body, apiConfig }): Promise<BridgeApproveResponseV2> =>
43
44
  unwrapResult(await sodax.api.bridge.approve(body, apiConfig)),
@@ -1,6 +1,7 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { BridgeableAmountResponseV2, BridgeQuoteRequestV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
6
7
 
@@ -39,7 +40,7 @@ export const useBridgeApiBridgeableAmount = ({
39
40
  return unwrapResult(await sodax.api.bridge.getBridgeableAmount(body, apiConfig));
40
41
  },
41
42
  enabled: !!body,
42
- retry: 3,
43
+ retry: retryUnlessAuthFailure,
43
44
  ...queryOptions,
44
45
  });
45
46
  };
@@ -1,5 +1,6 @@
1
1
  import type { CreateBridgeIntentParamsV2, CreateBridgeIntentResponseV2, RequestOverrideConfig } from '@sodax/sdk';
2
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
3
4
  import { unwrapResult } from '../shared/unwrapResult.js';
4
5
  import type { MutationHookParams } from '../shared/types.js';
5
6
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
@@ -34,7 +35,7 @@ export const useBridgeApiCreateBridgeIntent = ({
34
35
 
35
36
  return useSafeMutation<CreateBridgeIntentResponseV2, Error, UseBridgeApiCreateBridgeIntentVars>({
36
37
  mutationKey: ['bridgeApi', 'createBridgeIntent'],
37
- retry: 3,
38
+ retry: retryUnlessAuthFailure,
38
39
  ...mutationOptions,
39
40
  mutationFn: async ({ body, apiConfig }): Promise<CreateBridgeIntentResponseV2> =>
40
41
  unwrapResult(await sodax.api.bridge.createBridgeIntent(body, apiConfig)),
@@ -1,6 +1,7 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { BridgeFeeRequestV2, BridgeFeeResponseV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
6
7
 
@@ -38,7 +39,7 @@ export const useBridgeApiFee = ({
38
39
  return unwrapResult(await sodax.api.bridge.getFee(body, apiConfig));
39
40
  },
40
41
  enabled: !!body,
41
- retry: 3,
42
+ retry: retryUnlessAuthFailure,
42
43
  ...queryOptions,
43
44
  });
44
45
  };
@@ -1,6 +1,7 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { BridgeableCheckResponseV2, BridgeQuoteRequestV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
6
7
 
@@ -39,7 +40,7 @@ export const useBridgeApiIsBridgeable = ({
39
40
  return unwrapResult(await sodax.api.bridge.isBridgeable(body, apiConfig));
40
41
  },
41
42
  enabled: !!body,
42
- retry: 3,
43
+ retry: retryUnlessAuthFailure,
43
44
  ...queryOptions,
44
45
  });
45
46
  };
@@ -1,5 +1,6 @@
1
1
  import type { BridgeSubmitTxRequestV2, BridgeSubmitTxResponseV2, RequestOverrideConfig } from '@sodax/sdk';
2
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
3
4
  import { unwrapResult } from '../shared/unwrapResult.js';
4
5
  import type { MutationHookParams } from '../shared/types.js';
5
6
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
@@ -20,8 +21,9 @@ export type UseBridgeApiSubmitTxVars = {
20
21
  * broadcasting the spoke-deposit tx, handing it (with the FULL `relayData { address, payload }`
21
22
  * envelope) to the backend.
22
23
  *
23
- * Pure mutation: pass `{ request, apiConfig? }` to `mutate({...})`. Default `retry: 3` is applied
24
- * at the hook level — consumers can override via `mutationOptions.retry`.
24
+ * Pure mutation: pass `{ request, apiConfig? }` to `mutate({...})`. Retries up to 3 times at the
25
+ * hook level, except on a terminal API-key rejection (401/403) — see `retryUnlessAuthFailure`.
26
+ * Consumers can override via `mutationOptions.retry`.
25
27
  *
26
28
  * @example
27
29
  * const { mutateAsync: submitBridgeTx, isPending, error } = useBridgeApiSubmitTx();
@@ -42,7 +44,7 @@ export const useBridgeApiSubmitTx = ({
42
44
 
43
45
  return useSafeMutation<BridgeSubmitTxResponseV2, Error, UseBridgeApiSubmitTxVars>({
44
46
  mutationKey: ['bridgeApi', 'submitTx'],
45
- retry: 3,
47
+ retry: retryUnlessAuthFailure,
46
48
  ...mutationOptions,
47
49
  mutationFn: async ({ request, apiConfig }): Promise<BridgeSubmitTxResponseV2> =>
48
50
  unwrapResult(await sodax.api.bridge.submitTx(request, apiConfig)),
@@ -0,0 +1,63 @@
1
+ import { SodaxError } from '@sodax/sdk';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
+
5
+ /**
6
+ * Pins the WIRING of the auth stop, which `getBridgeSubmitTxStatusRefetchInterval.test.ts` cannot
7
+ * see: the policy is only reached if the hook hands it `query.state.error`. Passing the wrong
8
+ * argument (or none) reproduces the original defect — a rejected key re-requested every second —
9
+ * with the policy's own unit tests still green.
10
+ *
11
+ * No renderer, per the package convention (see `_apiKeyWire.test.ts`): the React Query wrapper is
12
+ * mocked so the captured options bag can be driven directly.
13
+ */
14
+
15
+ // The captured options bag is opaque, like the real wrapper's.
16
+ let captured: any;
17
+
18
+ vi.mock('../shared/useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax: {} }) }));
19
+ vi.mock('@tanstack/react-query', () => ({
20
+ useQuery: (options: any) => {
21
+ captured = options;
22
+ return {};
23
+ },
24
+ }));
25
+
26
+ const { useBridgeApiSubmitTxStatus } = await import('./useBridgeApiSubmitTxStatus.js');
27
+
28
+ const authError = new SodaxError('EXTERNAL_API_ERROR', 'responded with 401', {
29
+ feature: 'backend',
30
+ context: { api: 'bridge', endpoint: '/bridge/submit-tx/status', status: 401 },
31
+ });
32
+
33
+ const render = () => useBridgeApiSubmitTxStatus({ params: { txHash: '0xabc', srcChainKey: '0xa4b1.arbitrum' } });
34
+
35
+ describe('useBridgeApiSubmitTxStatus wiring', () => {
36
+ it('delegates its retry policy instead of hard-coding a count', () => {
37
+ render();
38
+ expect(captured.retry).toBe(retryUnlessAuthFailure);
39
+ });
40
+
41
+ it('feeds the query error into the interval policy, so a rejected key stops the poll', () => {
42
+ render();
43
+ expect(captured.refetchInterval({ state: { error: authError, data: undefined } })).toBe(false);
44
+ });
45
+
46
+ it('still polls a live record', () => {
47
+ render();
48
+ expect(
49
+ captured.refetchInterval({
50
+ state: { error: null, data: { success: true, data: { status: 'relaying' } } },
51
+ }),
52
+ ).toBe(1000);
53
+ });
54
+
55
+ it('feeds the record into the policy, so a terminal status stops the poll', () => {
56
+ render();
57
+ expect(
58
+ captured.refetchInterval({
59
+ state: { error: null, data: { success: true, data: { status: 'executed' } } },
60
+ }),
61
+ ).toBe(false);
62
+ });
63
+ });
@@ -1,8 +1,10 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { BridgeSubmitTxStatusResponseV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
7
+ import { getBridgeSubmitTxStatusRefetchInterval } from './getBridgeSubmitTxStatusRefetchInterval.js';
6
8
 
7
9
  export type UseBridgeApiSubmitTxStatusParams = ReadHookParams<
8
10
  BridgeSubmitTxStatusResponseV2 | undefined,
@@ -24,8 +26,9 @@ export type UseBridgeApiSubmitTxStatusParams = ReadHookParams<
24
26
  * });
25
27
  *
26
28
  * @remarks
27
- * - Default refetch interval is 1 second; stops on 'executed' or 'failed' status, or when the
28
- * backend marks the submission abandoned (`abandonedAt`) while `status` stays non-terminal —
29
+ * - Default refetch interval is 1 second; stops on 'executed' or 'failed' status, when the
30
+ * backend marks the submission abandoned (`abandonedAt`) while `status` stays non-terminal, or
31
+ * once the backend rejects the API key (401/403 is terminal — a retry cannot fix it) —
29
32
  * mirroring the SDK's backend submit-tx poll (no solver `posting_execution` state — bridge has
30
33
  * no post-execution).
31
34
  */
@@ -47,14 +50,8 @@ export const useBridgeApiSubmitTxStatus = ({
47
50
  return unwrapResult(await sodax.api.bridge.getSubmitTxStatus({ txHash, srcChainKey }, apiConfig));
48
51
  },
49
52
  enabled: !!txHash && txHash.length > 0 && !!srcChainKey,
50
- retry: 3,
51
- refetchInterval: query => {
52
- const data = query.state.data?.data;
53
- // `abandonedAt` is terminal even when `status` is still non-terminal (e.g. 'relayed') —
54
- // same rule as the SDK's pollBackendSubmitTx.
55
- if (data?.status === 'executed' || data?.status === 'failed' || data?.abandonedAt) return false;
56
- return 1000;
57
- },
53
+ retry: retryUnlessAuthFailure,
54
+ refetchInterval: query => getBridgeSubmitTxStatusRefetchInterval(query.state.error, query.state.data?.data),
58
55
  ...queryOptions,
59
56
  });
60
57
  };
@@ -1,6 +1,7 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { GetBridgeTokensResponseV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
6
7
 
@@ -29,7 +30,7 @@ export const useBridgeApiTokens = ({
29
30
  return useQuery<GetBridgeTokensResponseV2, Error>({
30
31
  queryKey: ['bridgeApi', 'tokens'],
31
32
  queryFn: async (): Promise<GetBridgeTokensResponseV2> => unwrapResult(await sodax.api.bridge.getTokens(apiConfig)),
32
- retry: 3,
33
+ retry: retryUnlessAuthFailure,
33
34
  ...queryOptions,
34
35
  });
35
36
  };
@@ -1,6 +1,7 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import type { GetBridgeTokensByChainResponseV2, RequestOverrideConfig } from '@sodax/sdk';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { retryUnlessAuthFailure } from '../shared/retryUnlessAuthFailure.js';
4
5
  import { unwrapResult } from '../shared/unwrapResult.js';
5
6
  import type { ReadHookParams } from '../shared/types.js';
6
7
 
@@ -34,7 +35,7 @@ export const useBridgeApiTokensByChain = ({
34
35
  return unwrapResult(await sodax.api.bridge.getTokensByChain(chainKey, apiConfig));
35
36
  },
36
37
  enabled: !!chainKey && chainKey.length > 0,
37
- retry: 3,
38
+ retry: retryUnlessAuthFailure,
38
39
  ...queryOptions,
39
40
  });
40
41
  };
@@ -6,6 +6,7 @@ export * from './useLeverageYieldPreviewRedeem.js';
6
6
  export * from './useLeverageYieldShareBalances.js';
7
7
  export * from './useLeverageYieldDeposit.js';
8
8
  export * from './useLeverageYieldNotifySolver.js';
9
+ export * from './useLeverageYieldDetailedStatus.js';
9
10
  export * from './useLeverageYieldVaultSwap.js';
10
11
  export * from './useLeverageYieldWithdraw.js';
11
12
  export * from './useLeveragePositions.js';
@@ -0,0 +1,131 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { SodaxError, SolverIntentStatusCode } from '@sodax/sdk';
3
+ import { MAX_NOT_FOUND_POLLS, STATUS_POLL_MS } from '../shared/notFoundStreak.js';
4
+
5
+ /**
6
+ * Pins the WIRING the pure-policy test cannot see: the hook must pass the read into the policy and
7
+ * advance the budget once per query update. Feeding the policy the wrong argument reproduces a poll
8
+ * that never stops, with the policy's own tests still green.
9
+ *
10
+ * No renderer, per the package convention (see `_apiKeyWire.test.ts`): the React Query wrapper is
11
+ * mocked so the captured options bag can be driven directly.
12
+ */
13
+
14
+ // The captured options bag is opaque, like the real wrapper's.
15
+ let captured: any;
16
+
17
+ const refSlots: Array<{ current: unknown }> = [];
18
+ let refCursor = 0;
19
+
20
+ // Only useRef is needed, and call order is stable, so this replays React's slot semantics well
21
+ // enough to observe the budget across refetchInterval calls.
22
+ vi.mock('react', () => ({
23
+ useRef: (initial: unknown) => {
24
+ const slot = refSlots[refCursor] ?? { current: initial };
25
+ refSlots[refCursor] = slot;
26
+ refCursor += 1;
27
+ return slot;
28
+ },
29
+ }));
30
+
31
+ const getDetailedStatus = vi.fn();
32
+ vi.mock('../shared/useSodaxContext.js', () => ({
33
+ useSodaxContext: () => ({ sodax: { leverageYield: { getDetailedStatus } } }),
34
+ }));
35
+ vi.mock('@tanstack/react-query', () => ({
36
+ useQuery: (options: any) => {
37
+ captured = options;
38
+ return {};
39
+ },
40
+ }));
41
+
42
+ const { useLeverageYieldDetailedStatus } = await import('./useLeverageYieldDetailedStatus.js');
43
+
44
+ const SRC_CHAIN = '0xa4b1.arbitrum';
45
+ const SRC_TX = '0xaaa';
46
+ const render = (apiConfig?: { apiKey: string }) => {
47
+ refCursor = 0;
48
+ return useLeverageYieldDetailedStatus({ params: { srcChainKey: SRC_CHAIN, srcTxHash: SRC_TX, apiConfig } });
49
+ };
50
+
51
+ const notDeliveredRead = {
52
+ ok: false,
53
+ error: { code: 'LOOKUP_FAILED', context: { reason: 'relay_not_delivered' } },
54
+ };
55
+
56
+ const solverRead = (status: SolverIntentStatusCode) => ({
57
+ ok: true,
58
+ value: { source: 'solver', dstTxHash: '0xhub', data: { status } },
59
+ });
60
+
61
+ describe('useLeverageYieldDetailedStatus wiring', () => {
62
+ it('keys the query on the source tx and runs only when both identifiers are present', () => {
63
+ render();
64
+ expect(captured.queryKey).toEqual(['leverageYield', 'detailedStatus', SRC_CHAIN, SRC_TX]);
65
+ expect(captured.enabled).toBe(true);
66
+
67
+ refCursor = 0;
68
+ useLeverageYieldDetailedStatus({ params: { srcChainKey: SRC_CHAIN, srcTxHash: undefined } });
69
+ expect(captured.enabled).toBe(false);
70
+ });
71
+
72
+ it('threads a per-request override into the SDK call', async () => {
73
+ render({ apiKey: 'per-action-key' });
74
+ await captured.queryFn();
75
+ expect(getDetailedStatus).toHaveBeenCalledWith(
76
+ { srcChainKey: SRC_CHAIN, srcTxHash: SRC_TX },
77
+ { apiKey: 'per-action-key' },
78
+ );
79
+ });
80
+
81
+ it('feeds the read into the policy, so a terminal answer stops the poll', () => {
82
+ render();
83
+ expect(
84
+ captured.refetchInterval({ state: { data: solverRead(SolverIntentStatusCode.SOLVED), dataUpdateCount: 1 } }),
85
+ ).toBe(false);
86
+ // A backend record reports terminality in its own vocabulary, not the solver's.
87
+ const solvedRecord = { ok: true, value: { source: 'backend', data: { status: 'solved' } } };
88
+ expect(captured.refetchInterval({ state: { data: solvedRecord, dataUpdateCount: 2 } })).toBe(false);
89
+ const inFlightRecord = { ok: true, value: { source: 'backend', data: { status: 'relaying' } } };
90
+ expect(captured.refetchInterval({ state: { data: inFlightRecord, dataUpdateCount: 3 } })).toBe(STATUS_POLL_MS);
91
+ });
92
+
93
+ it('stops outright on a rejected API key, without spending the budget', () => {
94
+ refSlots.length = 0;
95
+ render();
96
+ // A real SodaxError, not a shaped literal: `isAuthFailure` goes through `isSodaxError`, which
97
+ // checks the instance. The SDK returns 401/403 as a Result, so React Query never sees an error
98
+ // to withhold a retry from — the policy is the only thing that can stop this poll.
99
+ const rejected = {
100
+ ok: false,
101
+ error: new SodaxError('LOOKUP_FAILED', 'rejected', { feature: 'leverageYield', context: { status: 401 } }),
102
+ };
103
+ expect(captured.refetchInterval({ state: { data: rejected, dataUpdateCount: 1 } })).toBe(false);
104
+ });
105
+
106
+ it('advances the not-delivered budget once per update, and stops when it is spent', () => {
107
+ refSlots.length = 0;
108
+ render();
109
+ // Same dataUpdateCount twice must not double-count, so the cap is reached on update 40, not 20.
110
+ for (let update = 1; update <= MAX_NOT_FOUND_POLLS - 1; update++) {
111
+ captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: update } });
112
+ captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: update } });
113
+ }
114
+ expect(captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: 39 } })).toBe(STATUS_POLL_MS);
115
+ expect(captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: 40 } })).toBe(false);
116
+ });
117
+
118
+ it('counts a solver NOT_FOUND on the same budget, and a real status resets it', () => {
119
+ refSlots.length = 0;
120
+ render();
121
+ const notFound = solverRead(SolverIntentStatusCode.NOT_FOUND);
122
+ for (let update = 1; update <= MAX_NOT_FOUND_POLLS - 1; update++) {
123
+ captured.refetchInterval({ state: { data: notFound, dataUpdateCount: update } });
124
+ }
125
+ // One real answer in between clears the streak, so the next miss starts from zero.
126
+ captured.refetchInterval({
127
+ state: { data: solverRead(SolverIntentStatusCode.NOT_STARTED_YET), dataUpdateCount: 40 },
128
+ });
129
+ expect(captured.refetchInterval({ state: { data: notFound, dataUpdateCount: 41 } })).toBe(STATUS_POLL_MS);
130
+ });
131
+ });