@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,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
+ });
@@ -0,0 +1,83 @@
1
+ import type {
2
+ DetailedLeverageYieldStatus,
3
+ LeverageYieldDetailedStatusError,
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
+ getSolverDetailedStatusRefetchInterval,
15
+ isSolverNotFound,
16
+ toNotFoundBudgetRead,
17
+ } from '../shared/solverStatusPolicy.js';
18
+
19
+ export type UseLeverageYieldDetailedStatusResult =
20
+ | Result<DetailedLeverageYieldStatus, LeverageYieldDetailedStatusError>
21
+ | undefined;
22
+
23
+ export type UseLeverageYieldDetailedStatusParams = ReadHookParams<
24
+ UseLeverageYieldDetailedStatusResult,
25
+ {
26
+ srcChainKey: SpokeChainKey | undefined;
27
+ srcTxHash: string | undefined;
28
+ apiConfig?: RequestOverrideConfig;
29
+ }
30
+ >;
31
+
32
+ /**
33
+ * Hook for monitoring a leverage-yield vault swap from its source-chain transaction.
34
+ *
35
+ * `useLeverageYieldApiSubmitTxStatus` needs the backend to still hold a usable record; this takes
36
+ * `(srcChainKey, srcTxHash)` — the pair you hold after `vaultSwap()` — and routes to whichever
37
+ * source can answer, so it also covers a vault swap the client-side fallback completed. `data.value`
38
+ * is discriminated on `source`, and each variant carries that source's payload unmodified.
39
+ *
40
+ * Polls every 3s. Stops once the answering source is terminal, once the backend rejects the API
41
+ * key, and — like `useDetailedStatus` — after 40 consecutive *ambiguous* reads: a solver
42
+ * `NOT_FOUND`, or a `LOOKUP_FAILED` whose relay has no packet for the tx. Neither can distinguish "still in flight" from "never will be", so the
43
+ * budget is what stops a vault swap nothing can resolve. A dependency outage — relay unreachable,
44
+ * solver down — keeps polling instead, so the read recovers by itself; any real status resets the
45
+ * budget. Override with `queryOptions.refetchInterval`.
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const { data } = useLeverageYieldDetailedStatus({ params: { srcChainKey, srcTxHash } });
50
+ * if (data?.ok && data.value.source === 'backend') console.log(data.value.data.status);
51
+ * ```
52
+ */
53
+ export const useLeverageYieldDetailedStatus = ({
54
+ params,
55
+ queryOptions,
56
+ }: UseLeverageYieldDetailedStatusParams = {}): UseQueryResult<UseLeverageYieldDetailedStatusResult> => {
57
+ const { sodax } = useSodaxContext();
58
+ const srcChainKey = params?.srcChainKey;
59
+ const srcTxHash = params?.srcTxHash;
60
+ const apiConfig = params?.apiConfig;
61
+ // Composite identity: a new vault swap must start its own NOT_FOUND budget.
62
+ const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : undefined;
63
+ const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
64
+
65
+ return useQuery({
66
+ queryKey: ['leverageYield', 'detailedStatus', srcChainKey, srcTxHash],
67
+ queryFn: async () => {
68
+ if (!srcChainKey || !srcTxHash) return undefined;
69
+ return sodax.leverageYield.getDetailedStatus({ srcChainKey, srcTxHash }, apiConfig);
70
+ },
71
+ enabled: !!srcChainKey && !!srcTxHash,
72
+ refetchInterval: query => {
73
+ notFoundStreakRef.current = advanceNotFoundStreak(
74
+ notFoundStreakRef.current,
75
+ pollKey,
76
+ isSolverNotFound(toNotFoundBudgetRead(query.state.data)),
77
+ query.state.dataUpdateCount,
78
+ );
79
+ return getSolverDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
80
+ },
81
+ ...queryOptions,
82
+ });
83
+ };
@@ -21,9 +21,19 @@ export type UseLeverageYieldVaultSwapVars<K extends SpokeChainKey = SpokeChainKe
21
21
  *
22
22
  * Spread a `LeverageYieldSwapPayload` built by {@link useLeverageYieldDeposit} /
23
23
  * {@link useLeverageYieldWithdraw} into `mutate` alongside the wallet provider:
24
- * `vaultSwap({ ...payload, walletProvider })`. Runs `sodax.leverageYield.vaultSwap` —
25
- * create intent → verify → relay → notify solver — so vault flows never touch the
26
- * generic swap surface.
24
+ * `vaultSwap({ ...payload, walletProvider })`. Runs `sodax.leverageYield.vaultSwap`, so vault flows
25
+ * never touch the generic swap surface.
26
+ *
27
+ * Which transport it takes is config, not an argument. With `leverageYield.useBackendSubmitTx` on,
28
+ * it creates the intent and hands the broadcast tx to the leverage-yield API, which relays and
29
+ * post-executes server-side, falling back to the client-side path (verify → relay → notify solver)
30
+ * on any non-success. With it off, that client-side path runs outright. Read the effective value on
31
+ * `sodax.config.leverageYieldUseBackendSubmitTx` rather than assuming which way it points.
32
+ * Either way the resolved value is the same `VaultSwapResponse`.
33
+ *
34
+ * Pass `extras.apiKey` to key the backend leg per action, overriding the instance key. Poll the
35
+ * result with {@link useLeverageYieldDetailedStatus}, which reads a vault swap's status from the
36
+ * source-chain tx hash whichever transport completed it.
27
37
  *
28
38
  * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
29
39
  * `onError`, `retry`). Returns the unwrapped `VaultSwapResponse` on success.
@@ -0,0 +1,59 @@
1
+ import { useQueryClient } from '@tanstack/react-query';
2
+ import type {
3
+ LeveragePositionIntentResult,
4
+ OpenPositionFromDebtTokenParams,
5
+ OpenPositionParams,
6
+ SpokeChainKey,
7
+ SpokeExecActionParams,
8
+ } from '@sodax/sdk';
9
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
10
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
11
+ import type { MutationHookParams } from '../shared/types.js';
12
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
13
+ import { unwrapResult } from '../shared/unwrapResult.js';
14
+
15
+ /**
16
+ * Mutation variables for {@link useOpenLeveragePosition}.
17
+ *
18
+ * `side` picks which asset funds the open, and the two take different params — so the union is
19
+ * discriminated rather than merged, and the wrong field set is a type error instead of a revert.
20
+ */
21
+ export type UseOpenLeveragePositionVars<K extends SpokeChainKey = SpokeChainKey> =
22
+ | ({ side?: 'collateral' } & Omit<SpokeExecActionParams<K, false, OpenPositionParams<K>>, 'raw'>)
23
+ | ({ side: 'debt' } & Omit<SpokeExecActionParams<K, false, OpenPositionFromDebtTokenParams<K>>, 'raw'>);
24
+
25
+ /**
26
+ * Opens a leveraged position, funded from any chain, and reports the intent it posts.
27
+ *
28
+ * Thin over `sodax.leverageYield.openLeveragePosition`, which owns the pairing — a non-React caller
29
+ * gets the same guarantee. Resolving means the intent is LIVE, not that the position is open: read
30
+ * `notified` before telling the owner to wait, since a failed notification still resolves.
31
+ *
32
+ * Positions are owned by the hub wallet, never the signing address — pass the signer as
33
+ * `params.srcAddress` and the SDK resolves the owner.
34
+ *
35
+ * @experimental Off-hub (spoke) origins are unverified on-chain; see the SDK method.
36
+ */
37
+ export function useOpenLeveragePosition<K extends SpokeChainKey = SpokeChainKey>({
38
+ mutationOptions,
39
+ }: MutationHookParams<LeveragePositionIntentResult, UseOpenLeveragePositionVars<K>> = {}): SafeUseMutationResult<
40
+ LeveragePositionIntentResult,
41
+ Error,
42
+ UseOpenLeveragePositionVars<K>
43
+ > {
44
+ const { sodax } = useSodaxContext();
45
+ const queryClient = useQueryClient();
46
+
47
+ return useSafeMutation<LeveragePositionIntentResult, Error, UseOpenLeveragePositionVars<K>>({
48
+ mutationKey: ['leverageYield', 'openPosition'],
49
+ ...mutationOptions,
50
+ mutationFn: async vars => unwrapResult(await sodax.leverageYield.openLeveragePosition({ ...vars, raw: false })),
51
+ onSuccess: async (data, vars, ctx) => {
52
+ invalidateBalances(queryClient, vars.params.srcChainKey);
53
+ // A position write changes every position read — account, pending slot, the list itself — and a
54
+ // partner that has to remember this leaves the UI stale after the one action it just took.
55
+ queryClient.invalidateQueries({ queryKey: ['leverageYield'] });
56
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
57
+ },
58
+ });
59
+ }
@@ -0,0 +1,63 @@
1
+ import { useQueryClient } from '@tanstack/react-query';
2
+ import type {
3
+ PositionDirectCall,
4
+ PositionOperationParams,
5
+ SpokeChainKey,
6
+ SpokeExecActionParams,
7
+ TxHashPair,
8
+ } from '@sodax/sdk';
9
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
10
+ import { invalidateBalances } from '../shared/invalidateBalances.js';
11
+ import type { MutationHookParams } from '../shared/types.js';
12
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
13
+ import { unwrapResult } from '../shared/unwrapResult.js';
14
+
15
+ /** Mutation variables for {@link useRunLeveragePositionOperation} — the calls to run as the owner. */
16
+ export type UseRunLeveragePositionOperationVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
17
+ SpokeExecActionParams<K, false, PositionOperationParams<K, PositionDirectCall>>,
18
+ 'raw'
19
+ >;
20
+
21
+ /**
22
+ * Runs position calls that DO NOT post an intent — `withdraw`, `settle` and `cancel` — as the owning
23
+ * hub wallet. They are synchronous on the hub, so resolving means the work is done.
24
+ *
25
+ * Still routed, never sent directly: the position's `onlyOwner` is the hub wallet, so a call sent
26
+ * from the signer reverts `NotOwner`. Locally through the wallet router on the hub, relayed from
27
+ * anywhere else.
28
+ *
29
+ * USE {@link useSubmitLeveragePositionIntent} FOR `increaseLeverage` AND `decreaseLeverage`. Those
30
+ * only post a request a solver fills later, and this hook does not notify the solver, so sending one
31
+ * through here creates an intent nothing will fill. It expires silently and the operation is lost.
32
+ * The other direction is harmless by comparison: notifying about a withdraw is noise, not damage.
33
+ *
34
+ * Balances are invalidated for `srcChainKey` because a withdraw pays out.
35
+ *
36
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN, and this is the hook that carries the
37
+ * worst of it: an exit or cancellation delivering the underlying back to the spoke it
38
+ * came from has never run on mainnet. Bitcoin is refused outright.
39
+ */
40
+ export function useRunLeveragePositionOperation<K extends SpokeChainKey = SpokeChainKey>({
41
+ mutationOptions,
42
+ }: MutationHookParams<TxHashPair, UseRunLeveragePositionOperationVars<K>> = {}): SafeUseMutationResult<
43
+ TxHashPair,
44
+ Error,
45
+ UseRunLeveragePositionOperationVars<K>
46
+ > {
47
+ const { sodax } = useSodaxContext();
48
+ const queryClient = useQueryClient();
49
+
50
+ return useSafeMutation<TxHashPair, Error, UseRunLeveragePositionOperationVars<K>>({
51
+ mutationKey: ['leverageYield', 'runPositionOperation'],
52
+ ...mutationOptions,
53
+ mutationFn: async vars =>
54
+ unwrapResult(await sodax.leverageYield.runLeveragePositionOperation({ ...vars, raw: false })),
55
+ onSuccess: async (data, vars, ctx) => {
56
+ invalidateBalances(queryClient, vars.params.srcChainKey);
57
+ // A position write changes every position read — account, pending slot, the list itself — and a
58
+ // partner that has to remember this leaves the UI stale after the one action it just took.
59
+ queryClient.invalidateQueries({ queryKey: ['leverageYield'] });
60
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
61
+ },
62
+ });
63
+ }
@@ -0,0 +1,55 @@
1
+ import type {
2
+ PositionBatchCall,
3
+ LeveragePositionIntentResult,
4
+ PositionOperationParams,
5
+ SpokeChainKey,
6
+ SpokeExecActionParams,
7
+ } from '@sodax/sdk';
8
+ import { useQueryClient } from '@tanstack/react-query';
9
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
10
+ import type { MutationHookParams } from '../shared/types.js';
11
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
12
+ import { unwrapResult } from '../shared/unwrapResult.js';
13
+
14
+ /** Mutation variables for {@link useSubmitLeveragePositionIntent} — the calls to run as the owner. */
15
+ export type UseSubmitLeveragePositionIntentVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
16
+ SpokeExecActionParams<K, false, PositionOperationParams<K, PositionBatchCall>>,
17
+ 'raw'
18
+ >;
19
+
20
+ /**
21
+ * Runs position calls that POST A SOLVER INTENT — `increaseLeverage` and `decreaseLeverage` — as the
22
+ * owning hub wallet, then reports it.
23
+ *
24
+ * USE {@link useRunLeveragePositionOperation} for `withdraw`, `settle` and `cancel`. The split is the
25
+ * SDK's: those three are synchronous on the hub and need no notification, while these two only post
26
+ * a request a solver fills later. Sending a leverage change through the other hook leaves an intent
27
+ * nothing will fill, and it expires without a word.
28
+ *
29
+ * A position permits one intent at a time, so poll `useLeveragePositionPending` rather than assuming
30
+ * the next call may go out.
31
+ *
32
+ * @experimental Off-hub (spoke) origins are unverified on-chain; see the SDK method.
33
+ */
34
+ export function useSubmitLeveragePositionIntent<K extends SpokeChainKey = SpokeChainKey>({
35
+ mutationOptions,
36
+ }: MutationHookParams<
37
+ LeveragePositionIntentResult,
38
+ UseSubmitLeveragePositionIntentVars<K>
39
+ > = {}): SafeUseMutationResult<LeveragePositionIntentResult, Error, UseSubmitLeveragePositionIntentVars<K>> {
40
+ const { sodax } = useSodaxContext();
41
+ const queryClient = useQueryClient();
42
+
43
+ return useSafeMutation<LeveragePositionIntentResult, Error, UseSubmitLeveragePositionIntentVars<K>>({
44
+ mutationKey: ['leverageYield', 'submitPositionIntent'],
45
+ ...mutationOptions,
46
+ mutationFn: async vars =>
47
+ unwrapResult(await sodax.leverageYield.submitLeveragePositionIntent({ ...vars, raw: false })),
48
+ onSuccess: async (data, vars, ctx) => {
49
+ // The slot is occupied the moment this resolves, and the row's controls gate on it — so the
50
+ // pending read has to be refetched even though nothing has filled yet.
51
+ queryClient.invalidateQueries({ queryKey: ['leverageYield'] });
52
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
53
+ },
54
+ });
55
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Leverage Yield API v2 hooks — typed React Query wrappers over `sodax.api.leverageYield.*` (the
3
- * LeverageYieldApiService HTTP client). One hook per endpoint of the backend Leverage Yield API v2.
2
+ * Leverage Yield API hooks — typed React Query wrappers over `sodax.api.leverageYield.*` (the
3
+ * LeverageYieldApiService HTTP client). One hook per endpoint of the backend Leverage Yield API.
4
4
  *
5
5
  * Distinct from the on-chain `leverageYield/` hooks (`useLeverageYieldDeposit`/…), which drive the
6
6
  * `LeverageYieldService` path (wallet → hub chain). These hooks call the backend HTTP API instead.
@@ -12,3 +12,4 @@ export * from './useAToken.js';
12
12
  export * from './useATokensBalances.js';
13
13
  export * from './useReservesUsdFormat.js';
14
14
  export * from './useUserFormattedSummary.js';
15
+ export * from './useEModes.js';
@@ -0,0 +1,31 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import type { EmodeDataHumanized } from '@sodax/sdk';
4
+ import type { ReadHookParams } from '../shared/types.js';
5
+
6
+ export type UseEModesParams = ReadHookParams<EmodeDataHumanized[]>;
7
+
8
+ /**
9
+ * Reads the pool's configured eMode categories — LTV, liquidation threshold and bonus in basis
10
+ * points, plus the collateral/borrowable bitmaps and label.
11
+ *
12
+ * A category's LTV replaces the reserve's own when a user opts into it, so anything projecting
13
+ * borrowing power for an eMode position must read it from here rather than from the reserve.
14
+ * Categories only change by governance, so this is not polled.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const { data: categories } = useEModes();
19
+ * const cat = categories?.find(c => Number(c.id) === selected);
20
+ * const ltv = Number(cat?.eMode.ltv ?? 0) / 10_000;
21
+ * ```
22
+ */
23
+ export function useEModes({ queryOptions }: UseEModesParams = {}): UseQueryResult<EmodeDataHumanized[], Error> {
24
+ const { sodax } = useSodaxContext();
25
+
26
+ return useQuery<EmodeDataHumanized[], Error>({
27
+ queryKey: ['moneyMarket', 'eModes'],
28
+ queryFn: () => sodax.moneyMarket.data.getEModesHumanized(),
29
+ ...queryOptions,
30
+ });
31
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The consecutive-ambiguous-read budget shared by the status polls.
3
+ *
4
+ * Some reads cannot distinguish "still in flight" from "will never resolve" — a solver that has not
5
+ * seen an intent, a relay with no packet for a source tx. Polling those forever is the failure mode
6
+ * a budget exists to stop, but only for that shape: a dependency failing *right now* must keep
7
+ * polling, or a two-minute outage would permanently stick a transfer that is fine.
8
+ *
9
+ * Each feature decides what counts as an ambiguous miss and passes a boolean; the counting,
10
+ * identity and de-duplication are the same everywhere and live here.
11
+ *
12
+ * Kept free of React and context imports so it is unit-testable in dapp-kit's `node` test
13
+ * environment — importing a hook pulls in `useSodaxContext`.
14
+ */
15
+
16
+ export const STATUS_POLL_MS = 3000;
17
+ /** Cap consecutive ambiguous polls (~2 min at 3s). The first one is a race, not a stop. */
18
+ export const MAX_NOT_FOUND_POLLS = 40;
19
+
20
+ export type NotFoundStreakState = {
21
+ /** Identity of what is being polled — an intent tx hash, or a composite source-chain/tx key. */
22
+ pollKey: string | undefined;
23
+ seenUpdates: number;
24
+ consecutiveNotFound: number;
25
+ };
26
+
27
+ export const INITIAL_NOT_FOUND_STREAK: NotFoundStreakState = {
28
+ pollKey: undefined,
29
+ seenUpdates: 0,
30
+ consecutiveNotFound: 0,
31
+ };
32
+
33
+ export function nextNotFoundStreak(isAmbiguousMiss: boolean, previousStreak: number): number {
34
+ return isAmbiguousMiss ? previousStreak + 1 : 0;
35
+ }
36
+
37
+ /**
38
+ * Advances the counter once per successful query update. A `pollKey` change starts a new streak so
39
+ * a prior transfer's count cannot stop the next one. React Query may call `refetchInterval` more
40
+ * than once per fetch — same `dataUpdateCount` is a no-op.
41
+ */
42
+ export function advanceNotFoundStreak(
43
+ state: NotFoundStreakState,
44
+ pollKey: string | undefined,
45
+ isAmbiguousMiss: boolean,
46
+ dataUpdateCount: number,
47
+ ): NotFoundStreakState {
48
+ if (state.pollKey !== pollKey) {
49
+ state = { pollKey, seenUpdates: 0, consecutiveNotFound: 0 };
50
+ }
51
+ if (state.seenUpdates === dataUpdateCount) {
52
+ return state;
53
+ }
54
+ return {
55
+ pollKey,
56
+ seenUpdates: dataUpdateCount,
57
+ consecutiveNotFound: nextNotFoundStreak(isAmbiguousMiss, state.consecutiveNotFound),
58
+ };
59
+ }
@@ -4,7 +4,7 @@ import { isAuthFailure } from '@sodax/sdk';
4
4
  const MAX_RETRIES = 3;
5
5
 
6
6
  /**
7
- * Default React Query `retry` policy for the backend swaps-API hooks: replay a transport blip, never a
7
+ * Default React Query `retry` policy for the backend API hooks (swaps, leverage-yield, bridge): replay a transport blip, never a
8
8
  * terminal API-key rejection (see `isAuthFailure`). Retrying a rejected key only multiplies doomed
9
9
  * requests before the consumer sees the error.
10
10
  *
@@ -2,12 +2,12 @@ import { SolverIntentErrorCode, SolverIntentStatusCode } from '@sodax/sdk';
2
2
  import { describe, expect, it } from 'vitest';
3
3
  import {
4
4
  advanceNotFoundStreak,
5
- getSwapStatusRefetchInterval,
6
5
  INITIAL_NOT_FOUND_STREAK,
7
6
  MAX_NOT_FOUND_POLLS,
8
7
  nextNotFoundStreak,
9
8
  STATUS_POLL_MS,
10
- } from './getSwapStatusRefetchInterval.js';
9
+ } from './notFoundStreak.js';
10
+ import { getSolverStatusRefetchInterval, isSolverNotFound } from './solverStatusPolicy.js';
11
11
 
12
12
  /**
13
13
  * Guards the polling-stop invariant for `useStatus.refetchInterval`: keep polling until SOLVED/
@@ -23,52 +23,52 @@ const solverError = {
23
23
  error: { detail: { code: SolverIntentErrorCode.INTENT_NOT_FOUND, message: 'missing' } },
24
24
  };
25
25
 
26
- describe('getSwapStatusRefetchInterval', () => {
26
+ describe('getSolverStatusRefetchInterval', () => {
27
27
  it('stops immediately on SOLVED (3) and FAILED (4), even at consecutive count 1', () => {
28
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.SOLVED), 1)).toBe(false);
29
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.FAILED), 1)).toBe(false);
28
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.SOLVED), 1)).toBe(false);
29
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.FAILED), 1)).toBe(false);
30
30
  });
31
31
 
32
32
  it('keeps polling NOT_FOUND until MAX_NOT_FOUND_POLLS consecutive, then stops', () => {
33
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), MAX_NOT_FOUND_POLLS - 1)).toBe(
33
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), MAX_NOT_FOUND_POLLS - 1)).toBe(
34
34
  STATUS_POLL_MS,
35
35
  );
36
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), MAX_NOT_FOUND_POLLS)).toBe(false);
36
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), MAX_NOT_FOUND_POLLS)).toBe(false);
37
37
  });
38
38
 
39
39
  it('never stops in-flight NOT_STARTED_YET (1) or STARTED_NOT_FINISHED (2), even at a high count', () => {
40
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_STARTED_YET), 100)).toBe(STATUS_POLL_MS);
41
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 100)).toBe(STATUS_POLL_MS);
40
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_STARTED_YET), 100)).toBe(STATUS_POLL_MS);
41
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 100)).toBe(STATUS_POLL_MS);
42
42
  });
43
43
 
44
44
  it('keeps polling the first NOT_FOUND after a long in-flight streak', () => {
45
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), 1)).toBe(STATUS_POLL_MS);
45
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), 1)).toBe(STATUS_POLL_MS);
46
46
  });
47
47
 
48
48
  it('keeps polling when no status has arrived yet (undefined) or the Result is ok: false', () => {
49
- expect(getSwapStatusRefetchInterval(undefined, 1)).toBe(STATUS_POLL_MS);
50
- expect(getSwapStatusRefetchInterval(solverError, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
49
+ expect(getSolverStatusRefetchInterval(undefined, 1)).toBe(STATUS_POLL_MS);
50
+ expect(getSolverStatusRefetchInterval(solverError, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
51
51
  });
52
52
  });
53
53
 
54
54
  describe('nextNotFoundStreak', () => {
55
55
  it('increments only while status is NOT_FOUND and resets otherwise', () => {
56
- expect(nextNotFoundStreak(ok(SolverIntentStatusCode.NOT_FOUND), 0)).toBe(1);
57
- expect(nextNotFoundStreak(ok(SolverIntentStatusCode.NOT_FOUND), 39)).toBe(40);
58
- expect(nextNotFoundStreak(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 39)).toBe(0);
59
- expect(nextNotFoundStreak(undefined, 5)).toBe(0);
60
- expect(nextNotFoundStreak(solverError, 5)).toBe(0);
56
+ expect(nextNotFoundStreak(isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)), 0)).toBe(1);
57
+ expect(nextNotFoundStreak(isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)), 39)).toBe(40);
58
+ expect(nextNotFoundStreak(isSolverNotFound(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED)), 39)).toBe(0);
59
+ expect(nextNotFoundStreak(isSolverNotFound(undefined), 5)).toBe(0);
60
+ expect(nextNotFoundStreak(isSolverNotFound(solverError), 5)).toBe(0);
61
61
  });
62
62
  });
63
63
 
64
64
  describe('advanceNotFoundStreak', () => {
65
65
  it('increments consecutive NOT_FOUND once per dataUpdateCount, not per refetchInterval call', () => {
66
66
  let state = INITIAL_NOT_FOUND_STREAK;
67
- state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 1);
67
+ state = advanceNotFoundStreak(state, HASH_A, isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)), 1);
68
68
  expect(state.consecutiveNotFound).toBe(1);
69
- state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 1);
69
+ state = advanceNotFoundStreak(state, HASH_A, isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)), 1);
70
70
  expect(state.consecutiveNotFound).toBe(1);
71
- state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 2);
71
+ state = advanceNotFoundStreak(state, HASH_A, isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)), 2);
72
72
  expect(state.consecutiveNotFound).toBe(2);
73
73
  });
74
74
 
@@ -76,7 +76,7 @@ describe('advanceNotFoundStreak', () => {
76
76
  const started = advanceNotFoundStreak(
77
77
  { pollKey: HASH_A, seenUpdates: 39, consecutiveNotFound: 39 },
78
78
  HASH_A,
79
- ok(SolverIntentStatusCode.STARTED_NOT_FINISHED),
79
+ isSolverNotFound(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED)),
80
80
  40,
81
81
  );
82
82
  expect(started.consecutiveNotFound).toBe(0);
@@ -84,10 +84,10 @@ describe('advanceNotFoundStreak', () => {
84
84
 
85
85
  it('starts a new streak at 1 after in-flight polls, so a solver restart cannot stop the query', () => {
86
86
  let state = INITIAL_NOT_FOUND_STREAK;
87
- state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 40);
88
- state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 41);
87
+ state = advanceNotFoundStreak(state, HASH_A, isSolverNotFound(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED)), 40);
88
+ state = advanceNotFoundStreak(state, HASH_A, isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)), 41);
89
89
  expect(state.consecutiveNotFound).toBe(1);
90
- expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), state.consecutiveNotFound)).toBe(
90
+ expect(getSolverStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), state.consecutiveNotFound)).toBe(
91
91
  STATUS_POLL_MS,
92
92
  );
93
93
  });
@@ -96,7 +96,7 @@ describe('advanceNotFoundStreak', () => {
96
96
  const state = advanceNotFoundStreak(
97
97
  { pollKey: HASH_A, seenUpdates: 39, consecutiveNotFound: 39 },
98
98
  HASH_B,
99
- ok(SolverIntentStatusCode.NOT_FOUND),
99
+ isSolverNotFound(ok(SolverIntentStatusCode.NOT_FOUND)),
100
100
  1,
101
101
  );
102
102
  expect(state.consecutiveNotFound).toBe(1);