@sodax/dapp-kit 2.2.0-rc.5 → 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 (52) hide show
  1. package/README.md +77 -7
  2. package/dist/index.d.ts +382 -14
  3. package/dist/index.mjs +336 -38
  4. package/package.json +4 -4
  5. package/src/hooks/_mutationContract.test.ts +4 -0
  6. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.test.ts +144 -0
  7. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.ts +52 -0
  8. package/src/hooks/bridge/index.ts +2 -0
  9. package/src/hooks/bridge/useBridgeDetailedStatus.test.ts +93 -0
  10. package/src/hooks/bridge/useBridgeDetailedStatus.ts +79 -0
  11. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.test.ts +81 -0
  12. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.ts +25 -0
  13. package/src/hooks/bridgeApi/useBridgeApiAllowance.ts +2 -1
  14. package/src/hooks/bridgeApi/useBridgeApiApprove.ts +2 -1
  15. package/src/hooks/bridgeApi/useBridgeApiBridgeableAmount.ts +2 -1
  16. package/src/hooks/bridgeApi/useBridgeApiCreateBridgeIntent.ts +2 -1
  17. package/src/hooks/bridgeApi/useBridgeApiFee.ts +2 -1
  18. package/src/hooks/bridgeApi/useBridgeApiIsBridgeable.ts +2 -1
  19. package/src/hooks/bridgeApi/useBridgeApiSubmitTx.ts +5 -3
  20. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.test.ts +63 -0
  21. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.ts +7 -10
  22. package/src/hooks/bridgeApi/useBridgeApiTokens.ts +2 -1
  23. package/src/hooks/bridgeApi/useBridgeApiTokensByChain.ts +2 -1
  24. package/src/hooks/leverageYield/index.ts +13 -0
  25. package/src/hooks/leverageYield/useApproveLeveragePositionFunding.ts +48 -0
  26. package/src/hooks/leverageYield/useLeveragePositionAccount.ts +45 -0
  27. package/src/hooks/leverageYield/useLeveragePositionCollateral.ts +47 -0
  28. package/src/hooks/leverageYield/useLeveragePositionFundingAllowance.ts +51 -0
  29. package/src/hooks/leverageYield/useLeveragePositionInfo.ts +39 -0
  30. package/src/hooks/leverageYield/useLeveragePositionPayoutAddress.ts +36 -0
  31. package/src/hooks/leverageYield/useLeveragePositionPending.ts +48 -0
  32. package/src/hooks/leverageYield/useLeveragePositions.ts +41 -0
  33. package/src/hooks/leverageYield/useLeveragePositionsForUser.ts +45 -0
  34. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.test.ts +131 -0
  35. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.ts +83 -0
  36. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +13 -3
  37. package/src/hooks/leverageYield/useOpenLeveragePosition.ts +59 -0
  38. package/src/hooks/leverageYield/useRunLeveragePositionOperation.ts +63 -0
  39. package/src/hooks/leverageYield/useSubmitLeveragePositionIntent.ts +55 -0
  40. package/src/hooks/leverageYieldApi/index.ts +2 -2
  41. package/src/hooks/mm/index.ts +1 -0
  42. package/src/hooks/mm/useEModes.ts +31 -0
  43. package/src/hooks/shared/notFoundStreak.ts +59 -0
  44. package/src/hooks/shared/retryUnlessAuthFailure.ts +1 -1
  45. package/src/hooks/{swap/getSwapStatusRefetchInterval.test.ts → shared/solverStatusPolicy.test.ts} +25 -25
  46. package/src/hooks/shared/solverStatusPolicy.ts +117 -0
  47. package/src/hooks/swap/useDetailedStatus.test.ts +65 -21
  48. package/src/hooks/swap/useDetailedStatus.ts +9 -9
  49. package/src/hooks/swap/useStatus.ts +4 -7
  50. package/src/hooks/swapsApi/index.ts +2 -2
  51. package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +2 -2
  52. package/src/hooks/swap/getSwapStatusRefetchInterval.ts +0 -126
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The polling policy shared by every solver-backed status read.
3
+ *
4
+ * Two features now resolve a source tx to a solver answer — swap and leverage yield — and their
5
+ * status unions are structurally the same, so the terminality rules and the ambiguous-miss mapping
6
+ * are identical. They live here rather than in one feature's folder: `hooks/` has no cross-feature
7
+ * imports anywhere else, and a second verbatim copy is what this extraction exists to prevent.
8
+ * Bridge keeps its own policy beside its hook, because its second arm is a relay packet that is
9
+ * terminal on arrival and has no solver vocabulary at all.
10
+ *
11
+ * The read types are declared structurally rather than imported from either feature: this module
12
+ * must not own another hook's public contract, and both `DetailedSwapStatus` and
13
+ * `DetailedLeverageYieldStatus` satisfy the shape below.
14
+ *
15
+ * Kept free of React and context imports so it is unit-testable in dapp-kit's `node` test
16
+ * environment — importing a hook pulls in `useSodaxContext`.
17
+ */
18
+ import {
19
+ DETAILED_STATUS_NOT_DELIVERED,
20
+ isAuthFailure,
21
+ SolverIntentStatusCode,
22
+ type Result,
23
+ type SodaxError,
24
+ type SolverErrorResponse,
25
+ type SolverIntentStatusResponse,
26
+ } from '@sodax/sdk';
27
+
28
+ import { MAX_NOT_FOUND_POLLS, STATUS_POLL_MS } from './notFoundStreak.js';
29
+
30
+ /** A solver status read, as `useStatus` holds it. */
31
+ export type SolverStatusRead = Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined;
32
+
33
+ /**
34
+ * The structural minimum a detailed-status read must satisfy to use this policy: a backend arm
35
+ * reporting terminality in the submit-tx vocabulary, and a solver arm carrying the solver's own
36
+ * response. A feature's arm may carry more (leverage yield and swap both hoist `dstTxHash`); only
37
+ * what is read here is required.
38
+ */
39
+ export type SolverDetailedStatusRead =
40
+ | Result<
41
+ { source: 'backend'; data: { status: string } } | { source: 'solver'; data: SolverIntentStatusResponse },
42
+ SodaxError<'LOOKUP_FAILED'>
43
+ >
44
+ | undefined;
45
+
46
+ /**
47
+ * Polling interval for a plain solver status read (`useStatus`). Stops on SOLVED/FAILED immediately;
48
+ * stops on NOT_FOUND only after `MAX_NOT_FOUND_POLLS` consecutive successful fetches (solver forgot /
49
+ * never saw the intent). In-flight statuses keep polling with no global cap.
50
+ */
51
+ export function getSolverStatusRefetchInterval(data: SolverStatusRead, consecutiveNotFound: number): number | false {
52
+ const status = data?.ok ? data.value.status : undefined;
53
+ if (status === SolverIntentStatusCode.SOLVED || status === SolverIntentStatusCode.FAILED) {
54
+ return false;
55
+ }
56
+ if (status === SolverIntentStatusCode.NOT_FOUND && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) {
57
+ return false;
58
+ }
59
+ return STATUS_POLL_MS;
60
+ }
61
+
62
+ /** The read shape the budget counts: a solver that has not seen this intent. */
63
+ export function isSolverNotFound(data: SolverStatusRead): boolean {
64
+ return (data?.ok ? data.value.status : undefined) === SolverIntentStatusCode.NOT_FOUND;
65
+ }
66
+
67
+ /**
68
+ * Maps a detailed-status read onto the shape the shared NOT_FOUND policy consumes, three ways:
69
+ *
70
+ * - solver arm → passes through, so its status drives the budget as it does for `useStatus`;
71
+ * - backend arm → `undefined`, which resets the budget; the solver is not the one being asked;
72
+ * - failed read → counts as `NOT_FOUND` **only** when the relay has no packet for this source tx
73
+ * (`DETAILED_STATUS_NOT_DELIVERED`). That miss is ambiguous — a transfer still in flight and one
74
+ * whose tx never relayed look the same — so a budget is the only way to stop the second case.
75
+ *
76
+ * Every other `LOOKUP_FAILED` is a dependency failing right now: the relay unreachable, a malformed
77
+ * response, the solver down. Those reset the budget and keep polling, because that is how the read
78
+ * recovers when the outage ends. Counting them would stop polling a healthy transfer after ~2 min of
79
+ * downtime and never resume.
80
+ */
81
+ export function toNotFoundBudgetRead(data: SolverDetailedStatusRead): SolverStatusRead {
82
+ if (data === undefined) return undefined;
83
+ if (data.ok) {
84
+ return data.value.source === 'solver' ? { ok: true, value: data.value.data } : undefined;
85
+ }
86
+ return data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED
87
+ ? { ok: true, value: { status: SolverIntentStatusCode.NOT_FOUND } }
88
+ : undefined;
89
+ }
90
+
91
+ /**
92
+ * Polling interval for a detailed-status read. Backend records report terminality in their own
93
+ * vocabulary; everything else reuses the solver policy verbatim, so `MAX_NOT_FOUND_POLLS` stays the
94
+ * single cutoff — for a forgotten intent and for a transfer no source can resolve.
95
+ *
96
+ * A rejected API key is the one stop that sits outside both: `retryUnlessAuthFailure` cannot catch
97
+ * it, because the SDK returns the 401/403 as a `Result` rather than throwing, so React Query never
98
+ * sees an error to withhold a retry from. Without this branch a bad key polls forever whenever the
99
+ * relay has also not delivered — the miss is unprovable behind an unanswered backend, so it never
100
+ * consumes the not-delivered budget either.
101
+ */
102
+ export function getSolverDetailedStatusRefetchInterval(
103
+ data: SolverDetailedStatusRead,
104
+ consecutiveNotFound: number,
105
+ ): number | false {
106
+ // A rejected key is terminal — only a corrected key changes the answer, so stop asking.
107
+ if (data && !data.ok && isAuthFailure(data.error)) return false;
108
+ if (data?.ok && data.value.source === 'backend') {
109
+ // Both terminal states of the submit-tx status vocabulary. Today the SDK routes `'failed'`
110
+ // records to the solver so only `'solved'` reaches us, but that is its routing rule, not this
111
+ // hook's contract — encoding the wire contract keeps a terminal record from being polled forever
112
+ // if it changes.
113
+ const { status } = data.value.data;
114
+ return status === 'solved' || status === 'failed' ? false : STATUS_POLL_MS;
115
+ }
116
+ return getSolverStatusRefetchInterval(toNotFoundBudgetRead(data), consecutiveNotFound);
117
+ }
@@ -2,12 +2,15 @@ import { DETAILED_STATUS_NOT_DELIVERED, SodaxError, SolverIntentStatusCode, type
2
2
  import { describe, expect, it } from 'vitest';
3
3
  import {
4
4
  advanceNotFoundStreak,
5
- getDetailedStatusRefetchInterval,
6
5
  INITIAL_NOT_FOUND_STREAK,
7
6
  MAX_NOT_FOUND_POLLS,
8
7
  STATUS_POLL_MS,
8
+ } from '../shared/notFoundStreak.js';
9
+ import {
10
+ getSolverDetailedStatusRefetchInterval,
11
+ isSolverNotFound,
9
12
  toNotFoundBudgetRead,
10
- } from './getSwapStatusRefetchInterval.js';
13
+ } from '../shared/solverStatusPolicy.js';
11
14
 
12
15
  /**
13
16
  * Guards the polling-stop invariant for `useDetailedStatus`. The two variants report terminality in
@@ -48,23 +51,33 @@ const outage = {
48
51
  error: new SodaxError('LOOKUP_FAILED', 'relay down', { feature: 'swap' }),
49
52
  };
50
53
 
54
+ /** A key the backend rejected. Terminal, and reached before any budget — see the stop below. */
55
+ const rejectedKey = {
56
+ ok: false as const,
57
+ error: new SodaxError('LOOKUP_FAILED', 'rejected', { feature: 'swap', context: { status: 401 } }),
58
+ };
59
+
51
60
  const KEY_A = 'arb:0xaaa';
52
61
  const KEY_B = 'arb:0xbbb';
53
62
 
54
63
  /** Drives the streak the way the hook does, one query update per call. */
55
64
  const advance = (
56
65
  state: typeof INITIAL_NOT_FOUND_STREAK,
57
- reads: (ReturnType<typeof ok> | typeof notDelivered | typeof outage)[],
66
+ reads: (ReturnType<typeof ok> | typeof notDelivered | typeof outage | typeof rejectedKey)[],
58
67
  key = KEY_A,
59
68
  from = 1,
60
- ) => reads.reduce((acc, read, i) => advanceNotFoundStreak(acc, key, toNotFoundBudgetRead(read), from + i), state);
69
+ ) =>
70
+ reads.reduce(
71
+ (acc, read, i) => advanceNotFoundStreak(acc, key, isSolverNotFound(toNotFoundBudgetRead(read)), from + i),
72
+ state,
73
+ );
61
74
 
62
- describe('getDetailedStatusRefetchInterval', () => {
75
+ describe('getSolverDetailedStatusRefetchInterval', () => {
63
76
  // Both terminal states of the `SubmitSwapTxStatusV2` wire contract. `'failed'` is unreachable via
64
77
  // `getDetailedStatus` today (the SDK routes abandoned records to the solver) — asserted here as
65
78
  // the hook's own contract, so a terminal record is never polled forever if that routing changes.
66
79
  it.each(['solved', 'failed'] as const)('stops on a backend record at the terminal status %s', status => {
67
- expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(false);
80
+ expect(getSolverDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(false);
68
81
  });
69
82
 
70
83
  it.each([
@@ -74,44 +87,73 @@ describe('getDetailedStatusRefetchInterval', () => {
74
87
  'posting_execution',
75
88
  'posted_execution',
76
89
  ] as const)('keeps polling a backend record at %s', status => {
77
- expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(STATUS_POLL_MS);
90
+ expect(getSolverDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(STATUS_POLL_MS);
78
91
  });
79
92
 
80
93
  // A backend record is never stopped by the solver's budget — different vocabulary.
81
94
  it('keeps polling an in-flight backend record even at the cutoff', () => {
82
- expect(getDetailedStatusRefetchInterval(ok(backend('relaying')), MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
95
+ expect(getSolverDetailedStatusRefetchInterval(ok(backend('relaying')), MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
83
96
  });
84
97
 
85
98
  it.each([SolverIntentStatusCode.SOLVED, SolverIntentStatusCode.FAILED])('stops on solver code %s', status => {
86
- expect(getDetailedStatusRefetchInterval(ok(solver(status)), 0)).toBe(false);
99
+ expect(getSolverDetailedStatusRefetchInterval(ok(solver(status)), 0)).toBe(false);
87
100
  });
88
101
 
89
102
  it.each([
90
103
  SolverIntentStatusCode.NOT_STARTED_YET,
91
104
  SolverIntentStatusCode.STARTED_NOT_FINISHED,
92
105
  ])('never stops in-flight solver code %s, even at a high count', status => {
93
- expect(getDetailedStatusRefetchInterval(ok(solver(status)), 100)).toBe(STATUS_POLL_MS);
106
+ expect(getSolverDetailedStatusRefetchInterval(ok(solver(status)), 100)).toBe(STATUS_POLL_MS);
94
107
  });
95
108
 
96
109
  it('inherits the useStatus NOT_FOUND cutoff: polls below it, stops at it', () => {
97
110
  const notFound = ok(solver(SolverIntentStatusCode.NOT_FOUND));
98
- expect(getDetailedStatusRefetchInterval(notFound, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
99
- expect(getDetailedStatusRefetchInterval(notFound, MAX_NOT_FOUND_POLLS)).toBe(false);
111
+ expect(getSolverDetailedStatusRefetchInterval(notFound, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
112
+ expect(getSolverDetailedStatusRefetchInterval(notFound, MAX_NOT_FOUND_POLLS)).toBe(false);
100
113
  });
101
114
 
102
115
  it('spends the budget on an undelivered relay packet, rather than polling it forever', () => {
103
- expect(getDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
104
- expect(getDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS)).toBe(false);
116
+ expect(getSolverDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
117
+ expect(getSolverDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS)).toBe(false);
105
118
  });
106
119
 
107
120
  // An outage is recoverable and polling is how it recovers — budgeting it would strand the read.
108
121
  it('never stops on a dependency outage, however long it lasts', () => {
109
- expect(getDetailedStatusRefetchInterval(outage, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
110
- expect(getDetailedStatusRefetchInterval(outage, 10_000)).toBe(STATUS_POLL_MS);
122
+ expect(getSolverDetailedStatusRefetchInterval(outage, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
123
+ expect(getSolverDetailedStatusRefetchInterval(outage, 10_000)).toBe(STATUS_POLL_MS);
111
124
  });
112
125
 
113
126
  it('keeps polling before the first read lands', () => {
114
- expect(getDetailedStatusRefetchInterval(undefined, 0)).toBe(STATUS_POLL_MS);
127
+ expect(getSolverDetailedStatusRefetchInterval(undefined, 0)).toBe(STATUS_POLL_MS);
128
+ });
129
+
130
+ // Only a corrected key changes the answer, so there is nothing to wait for and no budget to spend.
131
+ it.each([401, 403])('stops on a rejected API key at the first read (%i)', status => {
132
+ const rejected = {
133
+ ok: false as const,
134
+ error: new SodaxError('LOOKUP_FAILED', 'rejected', { feature: 'swap', context: { status } }),
135
+ };
136
+ expect(getSolverDetailedStatusRefetchInterval(rejected, 0)).toBe(false);
137
+ });
138
+
139
+ // The regression this guards: a rejected key leaves the backend unanswered, so a relay miss behind
140
+ // it is unprovable and never tagged `DETAILED_STATUS_NOT_DELIVERED`. Without its own stop the read
141
+ // would poll both endpoints forever, because the budget it would need to exhaust never advances.
142
+ it('stops a rejected key even though the not-delivered budget never advances', () => {
143
+ expect(advance(INITIAL_NOT_FOUND_STREAK, Array(MAX_NOT_FOUND_POLLS).fill(rejectedKey)).consecutiveNotFound).toBe(0);
144
+ expect(getSolverDetailedStatusRefetchInterval(rejectedKey, 0)).toBe(false);
145
+ });
146
+
147
+ // 503 is the transient key-verification failure, which is retried rather than surfaced.
148
+ it('keeps polling a 503 from the key-verification path', () => {
149
+ const unavailable = {
150
+ ok: false as const,
151
+ error: new SodaxError('LOOKUP_FAILED', 'verification unavailable', {
152
+ feature: 'swap',
153
+ context: { status: 503 },
154
+ }),
155
+ };
156
+ expect(getSolverDetailedStatusRefetchInterval(unavailable, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
115
157
  });
116
158
  });
117
159
 
@@ -138,7 +180,7 @@ describe('detailed-status budget', () => {
138
180
  const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS).fill(notFound));
139
181
 
140
182
  expect(state.consecutiveNotFound).toBe(MAX_NOT_FOUND_POLLS);
141
- expect(getDetailedStatusRefetchInterval(notFound, state.consecutiveNotFound)).toBe(false);
183
+ expect(getSolverDetailedStatusRefetchInterval(notFound, state.consecutiveNotFound)).toBe(false);
142
184
  });
143
185
 
144
186
  // The regression this guards: a swap whose relay packet never lands used to poll forever, because
@@ -147,7 +189,7 @@ describe('detailed-status budget', () => {
147
189
  const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS).fill(notDelivered));
148
190
 
149
191
  expect(state.consecutiveNotFound).toBe(MAX_NOT_FOUND_POLLS);
150
- expect(getDetailedStatusRefetchInterval(notDelivered, state.consecutiveNotFound)).toBe(false);
192
+ expect(getSolverDetailedStatusRefetchInterval(notDelivered, state.consecutiveNotFound)).toBe(false);
151
193
  });
152
194
 
153
195
  // The regression this guards: a 2-minute solver or relay outage used to exhaust the budget and
@@ -156,7 +198,7 @@ describe('detailed-status budget', () => {
156
198
  const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS * 2).fill(outage));
157
199
 
158
200
  expect(state.consecutiveNotFound).toBe(0);
159
- expect(getDetailedStatusRefetchInterval(outage, state.consecutiveNotFound)).toBe(STATUS_POLL_MS);
201
+ expect(getSolverDetailedStatusRefetchInterval(outage, state.consecutiveNotFound)).toBe(STATUS_POLL_MS);
160
202
  });
161
203
 
162
204
  it('lets a transient failure be forgiven once a real status arrives', () => {
@@ -179,7 +221,9 @@ describe('detailed-status budget', () => {
179
221
  );
180
222
 
181
223
  expect(state.consecutiveNotFound).toBe(0);
182
- expect(getDetailedStatusRefetchInterval(ok(backend('relaying')), state.consecutiveNotFound)).toBe(STATUS_POLL_MS);
224
+ expect(getSolverDetailedStatusRefetchInterval(ok(backend('relaying')), state.consecutiveNotFound)).toBe(
225
+ STATUS_POLL_MS,
226
+ );
183
227
  });
184
228
 
185
229
  it('starts a fresh budget when the composite pollKey changes', () => {
@@ -3,12 +3,12 @@ import { useRef } from 'react';
3
3
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
4
4
  import { useSodaxContext } from '../shared/useSodaxContext.js';
5
5
  import type { ReadHookParams } from '../shared/types.js';
6
+ import { advanceNotFoundStreak, INITIAL_NOT_FOUND_STREAK } from '../shared/notFoundStreak.js';
6
7
  import {
7
- advanceNotFoundStreak,
8
- getDetailedStatusRefetchInterval,
9
- INITIAL_NOT_FOUND_STREAK,
8
+ getSolverDetailedStatusRefetchInterval,
9
+ isSolverNotFound,
10
10
  toNotFoundBudgetRead,
11
- } from './getSwapStatusRefetchInterval.js';
11
+ } from '../shared/solverStatusPolicy.js';
12
12
 
13
13
  export type UseDetailedStatusResult = Result<DetailedSwapStatus, DetailedStatusError> | undefined;
14
14
 
@@ -25,9 +25,9 @@ export type UseDetailedStatusParams = ReadHookParams<
25
25
  * `data.value` is discriminated on `source`, and each variant carries that source's payload
26
26
  * unmodified.
27
27
  *
28
- * Polls every 3s. Stops once the answering source is terminal, and — like `useStatus` — after 40
29
- * consecutive *ambiguous* reads: a solver `NOT_FOUND`, or a `LOOKUP_FAILED` whose relay has no
30
- * packet for the tx. Neither can distinguish "still in flight" from "never will be", so the budget
28
+ * Polls every 3s. Stops once the answering source is terminal, once the backend rejects the API
29
+ * key, and — like `useStatus` — after 40 consecutive *ambiguous* reads: a solver `NOT_FOUND`, or a
30
+ * `LOOKUP_FAILED` whose relay has no packet for the tx. Neither can distinguish "still in flight" from "never will be", so the budget
31
31
  * is what stops a swap nothing can resolve. A dependency outage — relay unreachable, solver down —
32
32
  * keeps polling instead, so the read recovers by itself; any real status resets the budget.
33
33
  * Override with `queryOptions.refetchInterval`.
@@ -60,10 +60,10 @@ export const useDetailedStatus = ({
60
60
  notFoundStreakRef.current = advanceNotFoundStreak(
61
61
  notFoundStreakRef.current,
62
62
  pollKey,
63
- toNotFoundBudgetRead(query.state.data),
63
+ isSolverNotFound(toNotFoundBudgetRead(query.state.data)),
64
64
  query.state.dataUpdateCount,
65
65
  );
66
- return getDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
66
+ return getSolverDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
67
67
  },
68
68
  ...queryOptions,
69
69
  });
@@ -4,11 +4,8 @@ import { useRef } from 'react';
4
4
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
5
5
  import { useSodaxContext } from '../shared/useSodaxContext.js';
6
6
  import type { ReadHookParams } from '../shared/types.js';
7
- import {
8
- advanceNotFoundStreak,
9
- getSwapStatusRefetchInterval,
10
- INITIAL_NOT_FOUND_STREAK,
11
- } from './getSwapStatusRefetchInterval.js';
7
+ import { advanceNotFoundStreak, INITIAL_NOT_FOUND_STREAK } from '../shared/notFoundStreak.js';
8
+ import { getSolverStatusRefetchInterval, isSolverNotFound } from '../shared/solverStatusPolicy.js';
12
9
 
13
10
  export type UseStatusParams = ReadHookParams<
14
11
  Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined,
@@ -46,10 +43,10 @@ export const useStatus = ({
46
43
  notFoundStreakRef.current = advanceNotFoundStreak(
47
44
  notFoundStreakRef.current,
48
45
  intentTxHash,
49
- query.state.data,
46
+ isSolverNotFound(query.state.data),
50
47
  query.state.dataUpdateCount,
51
48
  );
52
- return getSwapStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
49
+ return getSolverStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
53
50
  },
54
51
  ...queryOptions,
55
52
  });
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Swaps API v2 hooks — typed React Query wrappers over `sodax.api.swaps.*` (the SwapsApiService
3
- * HTTP client). One hook per endpoint of the backend Swaps API v2.
2
+ * Swaps API hooks — typed React Query wrappers over `sodax.api.swaps.*` (the SwapsApiService
3
+ * HTTP client). One hook per endpoint of the backend Swaps API.
4
4
  *
5
5
  * Distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive the
6
6
  * `SwapService` path (wallet → hub chain). These hooks call the backend HTTP API instead.
@@ -17,7 +17,7 @@ export type UseSwapsApiSubmitTxStatusParams = ReadHookParams<
17
17
  /**
18
18
  * React hook for polling the processing status of a submitted swap transaction via the swaps API —
19
19
  * `sodax.api.swaps.getSubmitTxStatus`. Both `txHash` and `srcChainKey` are required for the query
20
- * to run (the swaps API v2 status query requires the source chain key).
20
+ * to run (the swaps API status query requires the source chain key).
21
21
  *
22
22
  * @example
23
23
  * const { data: status } = useSwapsApiSubmitTxStatus({
@@ -41,7 +41,7 @@ export const useSwapsApiSubmitTxStatus = ({
41
41
  return useQuery({
42
42
  queryKey: ['swapsApi', 'submitTx', 'status', txHash, srcChainKey],
43
43
  queryFn: async (): Promise<SubmitTxStatusResponseV2 | undefined> => {
44
- // `srcChainKey` is required by the swaps API v2 status query. The `enabled` gate below
44
+ // `srcChainKey` is required by the swaps API status query. The `enabled` gate below
45
45
  // ensures both are present; this guard also narrows the types for the call.
46
46
  if (!txHash || !srcChainKey) return undefined;
47
47
  return unwrapResult(await sodax.api.swaps.getSubmitTxStatus({ txHash, srcChainKey }, apiConfig));
@@ -1,126 +0,0 @@
1
- import {
2
- DETAILED_STATUS_NOT_DELIVERED,
3
- SolverIntentStatusCode,
4
- type DetailedStatusError,
5
- type DetailedSwapStatus,
6
- type Result,
7
- type SolverErrorResponse,
8
- type SolverIntentStatusResponse,
9
- } from '@sodax/sdk';
10
-
11
- export const STATUS_POLL_MS = 3000;
12
- /** Cap consecutive NOT_FOUND polls (~2 min at 3s). First NOT_FOUND is a race, not a stop. */
13
- export const MAX_NOT_FOUND_POLLS = 40;
14
-
15
- export type SwapStatusResult = Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined;
16
-
17
- export type NotFoundStreakState = {
18
- /** Identity of what is being polled — an intent tx hash, or a composite source-chain/tx key. */
19
- pollKey: string | undefined;
20
- seenUpdates: number;
21
- consecutiveNotFound: number;
22
- };
23
-
24
- export const INITIAL_NOT_FOUND_STREAK: NotFoundStreakState = {
25
- pollKey: undefined,
26
- seenUpdates: 0,
27
- consecutiveNotFound: 0,
28
- };
29
-
30
- /**
31
- * Polling interval for `useStatus`. Stops on SOLVED/FAILED immediately; stops on NOT_FOUND only
32
- * after `MAX_NOT_FOUND_POLLS` consecutive successful fetches (solver forgot / never saw the intent).
33
- * In-flight statuses keep polling with no global cap.
34
- *
35
- * Kept in its own pure module (no React/context imports) so it is unit-testable in dapp-kit's
36
- * `node` test environment — importing the hook itself pulls in `useSodaxContext`.
37
- */
38
- export function getSwapStatusRefetchInterval(data: SwapStatusResult, consecutiveNotFound: number): number | false {
39
- const status = data?.ok ? data.value.status : undefined;
40
- if (status === SolverIntentStatusCode.SOLVED || status === SolverIntentStatusCode.FAILED) {
41
- return false;
42
- }
43
- if (status === SolverIntentStatusCode.NOT_FOUND && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) {
44
- return false;
45
- }
46
- return STATUS_POLL_MS;
47
- }
48
-
49
- export function nextNotFoundStreak(data: SwapStatusResult, previousStreak: number): number {
50
- const status = data?.ok ? data.value.status : undefined;
51
- return status === SolverIntentStatusCode.NOT_FOUND ? previousStreak + 1 : 0;
52
- }
53
-
54
- /**
55
- * Advances the consecutive-NOT_FOUND counter once per successful query update. A `pollKey` change
56
- * starts a new streak so a prior intent's count cannot stop the next one. React Query may call
57
- * `refetchInterval` more than once per fetch — same `dataUpdateCount` is a no-op.
58
- */
59
- export function advanceNotFoundStreak(
60
- state: NotFoundStreakState,
61
- pollKey: string | undefined,
62
- data: SwapStatusResult,
63
- dataUpdateCount: number,
64
- ): NotFoundStreakState {
65
- if (state.pollKey !== pollKey) {
66
- state = { pollKey, seenUpdates: 0, consecutiveNotFound: 0 };
67
- }
68
- if (state.seenUpdates === dataUpdateCount) {
69
- return state;
70
- }
71
- return {
72
- pollKey,
73
- seenUpdates: dataUpdateCount,
74
- consecutiveNotFound: nextNotFoundStreak(data, state.consecutiveNotFound),
75
- };
76
- }
77
-
78
- /**
79
- * Structural mirror of `useDetailedStatus`'s data type. Declared locally rather than imported so
80
- * this module does not own another hook's public contract — `UseDetailedStatusResult` lives with
81
- * the hook.
82
- */
83
- type DetailedStatusRead = Result<DetailedSwapStatus, DetailedStatusError> | undefined;
84
-
85
- /**
86
- * Maps a detailed-status read onto the shape the shared NOT_FOUND policy consumes, three ways:
87
- *
88
- * - solver arm → passes through, so its status drives the budget as it does for `useStatus`;
89
- * - backend arm → `undefined`, which resets the budget; the solver is not the one being asked;
90
- * - failed read → counts as `NOT_FOUND` **only** when the relay has no packet for this source tx
91
- * (`DETAILED_STATUS_NOT_DELIVERED`). That miss is ambiguous — a swap still in flight and one whose
92
- * tx never relayed look the same — so a budget is the only way to stop the second case.
93
- *
94
- * Every other `LOOKUP_FAILED` is a dependency failing right now: the relay unreachable, a malformed
95
- * response, the solver down. Those reset the budget and keep polling, because that is how the read
96
- * recovers when the outage ends. Counting them would stop polling a healthy swap after ~2 min of
97
- * downtime and never resume.
98
- */
99
- export function toNotFoundBudgetRead(data: DetailedStatusRead): SwapStatusResult {
100
- if (data === undefined) return undefined;
101
- if (data.ok) {
102
- return data.value.source === 'solver' ? { ok: true, value: data.value.data } : undefined;
103
- }
104
- return data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED
105
- ? { ok: true, value: { status: SolverIntentStatusCode.NOT_FOUND } }
106
- : undefined;
107
- }
108
-
109
- /**
110
- * Polling interval for `useDetailedStatus`. Backend records report terminality in their own
111
- * vocabulary; everything else reuses `useStatus`'s policy verbatim, so `MAX_NOT_FOUND_POLLS` stays
112
- * the single cutoff — for a forgotten intent and for a swap no source can resolve.
113
- */
114
- export function getDetailedStatusRefetchInterval(
115
- data: DetailedStatusRead,
116
- consecutiveNotFound: number,
117
- ): number | false {
118
- if (data?.ok && data.value.source === 'backend') {
119
- // Both terminal states of `SubmitSwapTxStatusV2`. Today the SDK routes `'failed'` records to the
120
- // solver so only `'solved'` reaches us, but that is its routing rule, not this hook's contract —
121
- // encoding the wire contract keeps a terminal record from being polled forever if it changes.
122
- const { status } = data.value.data;
123
- return status === 'solved' || status === 'failed' ? false : STATUS_POLL_MS;
124
- }
125
- return getSwapStatusRefetchInterval(toNotFoundBudgetRead(data), consecutiveNotFound);
126
- }