@sodax/dapp-kit 2.2.0 → 2.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +176 -166
  2. package/dist/index.d.ts +313 -30
  3. package/dist/index.mjs +392 -3
  4. package/package.json +5 -5
  5. package/src/hooks/_apiKeyWire.test.ts +10 -0
  6. package/src/hooks/_mutationContract.test.ts +4 -0
  7. package/src/hooks/bridge/index.ts +2 -0
  8. package/src/hooks/bridge/useBridgeApprovalStrategy.test.ts +75 -0
  9. package/src/hooks/bridge/useBridgeApprovalStrategy.ts +53 -0
  10. package/src/hooks/bridge/useBridgeWithApproval.test.ts +73 -0
  11. package/src/hooks/bridge/useBridgeWithApproval.ts +48 -0
  12. package/src/hooks/leverageYield/index.ts +2 -0
  13. package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.test.ts +82 -0
  14. package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.ts +55 -0
  15. package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.test.ts +73 -0
  16. package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.ts +48 -0
  17. package/src/hooks/shared/useNearStorageGate.ts +10 -4
  18. package/src/hooks/swap/index.ts +3 -0
  19. package/src/hooks/swap/useSwapApprovalStrategy.test.ts +92 -0
  20. package/src/hooks/swap/useSwapApprovalStrategy.ts +54 -0
  21. package/src/hooks/swap/useSwapLifecycle.test.ts +329 -0
  22. package/src/hooks/swap/useSwapLifecycle.ts +212 -0
  23. package/src/hooks/swap/useSwapWithApproval.test.ts +63 -0
  24. package/src/hooks/swap/useSwapWithApproval.ts +45 -0
  25. package/src/hooks/swapsApi/index.ts +1 -0
  26. package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.test.ts +331 -0
  27. package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.ts +183 -0
  28. package/src/utils/nearStorageGate.ts +4 -1
  29. package/src/utils/swapLifecycle.test.ts +292 -0
  30. package/src/utils/swapLifecycle.ts +183 -0
@@ -0,0 +1,292 @@
1
+ import {
2
+ ATOMIC_BATCH_UNCONFIRMED,
3
+ ChainKeys,
4
+ HookKind,
5
+ SodaxError,
6
+ type CreateIntentParams,
7
+ type SwapWithApprovalResponse,
8
+ } from '@sodax/sdk';
9
+ import { describe, expect, it } from 'vitest';
10
+ import type { NearStorageGateState } from './nearStorageGate.js';
11
+ import type { StellarGateState } from './stellarGate.js';
12
+ import {
13
+ isSameIntent,
14
+ resolveSwapLifecycle,
15
+ toSwapAttempt,
16
+ type SwapAttemptSource,
17
+ type SwapLifecycleInputs,
18
+ } from './swapLifecycle.js';
19
+
20
+ const PARAMS: CreateIntentParams = {
21
+ inputToken: '0x2170Ed0880ac9A755fd29B2688956BD959F933F8',
22
+ outputToken: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f',
23
+ inputAmount: 1_000_000n,
24
+ minOutputAmount: 900_000n,
25
+ deadline: 100n,
26
+ allowPartialFill: false,
27
+ srcChainKey: ChainKeys.BSC_MAINNET,
28
+ dstChainKey: ChainKeys.ARBITRUM_MAINNET,
29
+ srcAddress: '0x1111111111111111111111111111111111111111',
30
+ dstAddress: '0x2222222222222222222222222222222222222222',
31
+ solver: '0x0000000000000000000000000000000000000000',
32
+ data: '0x',
33
+ };
34
+
35
+ const RESPONSE = {
36
+ intentDeliveryInfo: { srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc' },
37
+ approvalStrategy: 'atomic-batch',
38
+ } as unknown as SwapWithApprovalResponse; // Only intentDeliveryInfo is read; the rest is irrelevant here.
39
+
40
+ const mutation = (overrides: Partial<SwapAttemptSource> = {}): SwapAttemptSource => ({
41
+ status: 'idle',
42
+ data: undefined,
43
+ error: null,
44
+ variables: undefined,
45
+ ...overrides,
46
+ });
47
+
48
+ const OPEN_STELLAR: StellarGateState = {
49
+ isStellar: false,
50
+ needsActivation: false,
51
+ needsFunding: false,
52
+ needsTrustline: false,
53
+ checkFailed: false,
54
+ blocksAction: false,
55
+ };
56
+ const OPEN_NEAR: NearStorageGateState = { isNear: false, needsRegistration: false, blocksAction: false };
57
+
58
+ const inputs = (overrides: Partial<SwapLifecycleInputs> = {}): SwapLifecycleInputs => ({
59
+ attempt: { phase: 'none' },
60
+ status: undefined,
61
+ statusError: undefined,
62
+ hasInputs: true,
63
+ stellar: OPEN_STELLAR,
64
+ nearStorage: OPEN_NEAR,
65
+ externalBlocked: false,
66
+ setupBusy: false,
67
+ isWrongChain: false,
68
+ strategy: { data: 'atomic-batch', error: null },
69
+ ...overrides,
70
+ });
71
+
72
+ describe('isSameIntent', () => {
73
+ it('treats a rebuilt deadline as the same swap', () => {
74
+ expect(isSameIntent(PARAMS, { ...PARAMS, deadline: 999n })).toBe(true);
75
+ });
76
+
77
+ it('treats a different amount or recipient as a different swap', () => {
78
+ expect(isSameIntent(PARAMS, { ...PARAMS, inputAmount: 2n })).toBe(false);
79
+ expect(isSameIntent(PARAMS, { ...PARAMS, dstAddress: '0x3333333333333333333333333333333333333333' })).toBe(false);
80
+ });
81
+
82
+ it('treats turning a delivery hook on, or changing data or fill mode, as a different swap', () => {
83
+ expect(isSameIntent(PARAMS, { ...PARAMS, hook: { kind: HookKind.FLINT_DEPOSIT } })).toBe(false);
84
+ expect(isSameIntent(PARAMS, { ...PARAMS, data: '0x01' })).toBe(false);
85
+ expect(isSameIntent(PARAMS, { ...PARAMS, allowPartialFill: true })).toBe(false);
86
+ expect(isSameIntent(PARAMS, { ...PARAMS, deliveryData: '0x02' })).toBe(false);
87
+ });
88
+ });
89
+
90
+ describe('toSwapAttempt', () => {
91
+ it('has no attempt before the first swap', () => {
92
+ expect(toSwapAttempt(mutation(), PARAMS)).toEqual({ phase: 'none' });
93
+ });
94
+
95
+ it('reports any in-flight swap, even after the params changed', () => {
96
+ const pending = mutation({ status: 'pending', variables: { params: PARAMS } });
97
+ expect(toSwapAttempt(pending, { ...PARAMS, inputAmount: 5n })).toEqual({ phase: 'submitting' });
98
+ });
99
+
100
+ it('tracks a successful swap by its source tx while the params are unchanged', () => {
101
+ const done = mutation({ status: 'success', data: RESPONSE, variables: { params: PARAMS } });
102
+ expect(toSwapAttempt(done, PARAMS)).toEqual({
103
+ phase: 'broadcast',
104
+ srcChainKey: ChainKeys.BSC_MAINNET,
105
+ srcTxHash: '0xsrc',
106
+ });
107
+ });
108
+
109
+ it('forgets a finished swap once the params change', () => {
110
+ const done = mutation({ status: 'success', data: RESPONSE, variables: { params: PARAMS } });
111
+ expect(toSwapAttempt(done, { ...PARAMS, inputAmount: 5n })).toEqual({ phase: 'none' });
112
+ expect(toSwapAttempt(done, undefined)).toEqual({ phase: 'none' });
113
+ });
114
+
115
+ // A refreshed quote rebuilds the params with a new minimum output.
116
+ const REQUOTED: CreateIntentParams = { ...PARAMS, minOutputAmount: 899_000n };
117
+
118
+ it('keeps tracking a swap that failed after broadcast, even after the params changed', () => {
119
+ const error = new SodaxError('RELAY_TIMEOUT', 'relay timed out', {
120
+ feature: 'swap',
121
+ context: { srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc' },
122
+ });
123
+ const failed = mutation({ status: 'error', error, variables: { params: PARAMS } });
124
+ const tracked = { phase: 'broadcast', srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc', error };
125
+ expect(toSwapAttempt(failed, PARAMS)).toEqual(tracked);
126
+ expect(toSwapAttempt(failed, REQUOTED)).toEqual(tracked);
127
+ expect(toSwapAttempt(failed, undefined)).toEqual(tracked);
128
+ });
129
+
130
+ it('holds a batch the wallet accepted but never confirmed as unconfirmed, never as a retryable failure', () => {
131
+ const error = new SodaxError('TX_VERIFICATION_FAILED', 'batch not confirmed', {
132
+ feature: 'swap',
133
+ context: { reason: ATOMIC_BATCH_UNCONFIRMED, batchId: 'batch-1' },
134
+ });
135
+ const failed = mutation({ status: 'error', error, variables: { params: PARAMS } });
136
+ expect(toSwapAttempt(failed, PARAMS)).toEqual({ phase: 'unconfirmed', batchId: 'batch-1', error });
137
+ // It may still land, so new params must not re-enable the swap.
138
+ expect(toSwapAttempt(failed, REQUOTED)).toEqual({ phase: 'unconfirmed', batchId: 'batch-1', error });
139
+ });
140
+
141
+ it('keeps the call count of an unconfirmed batch, so resuming can match one receipt per call', () => {
142
+ const error = new SodaxError('TX_VERIFICATION_FAILED', 'batch not confirmed', {
143
+ feature: 'swap',
144
+ context: { reason: ATOMIC_BATCH_UNCONFIRMED, batchId: 'batch-1', callCount: 2 },
145
+ });
146
+ const failed = mutation({ status: 'error', error, variables: { params: PARAMS } });
147
+ expect(toSwapAttempt(failed, PARAMS)).toEqual({ phase: 'unconfirmed', batchId: 'batch-1', callCount: 2, error });
148
+ });
149
+
150
+ it('reports a failure before broadcast as failed', () => {
151
+ const error = new SodaxError('USER_REJECTED', 'User rejected the request', { feature: 'swap' });
152
+ const failed = mutation({ status: 'error', error, variables: { params: PARAMS } });
153
+ expect(toSwapAttempt(failed, PARAMS)).toEqual({ phase: 'failed', error });
154
+ expect(toSwapAttempt(failed, REQUOTED)).toEqual({ phase: 'none' });
155
+ });
156
+ });
157
+
158
+ describe('resolveSwapLifecycle', () => {
159
+ const broadcast = { phase: 'broadcast', srcChainKey: ChainKeys.BSC_MAINNET, srcTxHash: '0xsrc' } as const;
160
+
161
+ it('is ready with the approval strategy once nothing blocks', () => {
162
+ expect(resolveSwapLifecycle(inputs())).toEqual({ kind: 'ready', approvalStrategy: 'atomic-batch' });
163
+ });
164
+
165
+ it('is idle without intent params or a wallet', () => {
166
+ expect(resolveSwapLifecycle(inputs({ hasInputs: false }))).toEqual({ kind: 'idle' });
167
+ });
168
+
169
+ it('is submitting while the swap is in flight, whatever else holds', () => {
170
+ expect(resolveSwapLifecycle(inputs({ attempt: { phase: 'submitting' }, isWrongChain: true }))).toEqual({
171
+ kind: 'submitting',
172
+ });
173
+ });
174
+
175
+ it('follows a broadcast swap through pending, settled and failed', () => {
176
+ expect(resolveSwapLifecycle(inputs({ attempt: broadcast }))).toEqual({ kind: 'pending', ...stripPhase(broadcast) });
177
+ expect(
178
+ resolveSwapLifecycle(inputs({ attempt: broadcast, status: { state: 'solved', fillTxHash: '0xfill' } })),
179
+ ).toEqual({ kind: 'settled', ...stripPhase(broadcast), fillTxHash: '0xfill' });
180
+ const failed = resolveSwapLifecycle(inputs({ attempt: broadcast, status: { state: 'failed' } }));
181
+ expect(failed).toMatchObject({ kind: 'failed', ...stripPhase(broadcast) });
182
+ });
183
+
184
+ it('keeps a post-broadcast failure pending, with its error, until the status says otherwise', () => {
185
+ const error = new Error('relay timed out');
186
+ expect(resolveSwapLifecycle(inputs({ attempt: { ...broadcast, error } }))).toEqual({
187
+ kind: 'pending',
188
+ ...stripPhase(broadcast),
189
+ error,
190
+ });
191
+ expect(resolveSwapLifecycle(inputs({ attempt: { ...broadcast, error }, status: { state: 'failed' } }))).toEqual({
192
+ kind: 'failed',
193
+ error,
194
+ ...stripPhase(broadcast),
195
+ });
196
+ });
197
+
198
+ it('surfaces a status read that cannot recover on the pending state', () => {
199
+ const statusError = new Error('API key rejected');
200
+ expect(resolveSwapLifecycle(inputs({ attempt: broadcast, statusError }))).toEqual({
201
+ kind: 'pending',
202
+ ...stripPhase(broadcast),
203
+ error: statusError,
204
+ });
205
+ });
206
+
207
+ it('reports an unconfirmed batch as unconfirmed, whatever else holds', () => {
208
+ const error = new Error('batch not confirmed');
209
+ expect(
210
+ resolveSwapLifecycle(
211
+ inputs({ attempt: { phase: 'unconfirmed', batchId: 'batch-1', callCount: 2, error }, isWrongChain: true }),
212
+ ),
213
+ ).toEqual({ kind: 'unconfirmed', batchId: 'batch-1', callCount: 2, error });
214
+ });
215
+
216
+ it('reports a failure before broadcast', () => {
217
+ const error = new Error('User rejected the request');
218
+ expect(resolveSwapLifecycle(inputs({ attempt: { phase: 'failed', error } }))).toEqual({ kind: 'failed', error });
219
+ });
220
+
221
+ it.each([
222
+ [{ needsActivation: true, blocksAction: true }, 'stellarActivation'],
223
+ [{ needsFunding: true, blocksAction: true }, 'stellarFunding'],
224
+ [{ needsTrustline: true, blocksAction: true }, 'stellarTrustline'],
225
+ [{ checkFailed: true, blocksAction: true }, 'stellarCheckFailed'],
226
+ ] as const)('blocks on the Stellar gate (%o → %s)', (gate, reason) => {
227
+ expect(resolveSwapLifecycle(inputs({ stellar: { ...OPEN_STELLAR, isStellar: true, ...gate } }))).toEqual({
228
+ kind: 'needsSetup',
229
+ reason,
230
+ });
231
+ });
232
+
233
+ it('blocks on NEAR storage, then on the app-owned prerequisite', () => {
234
+ expect(
235
+ resolveSwapLifecycle(inputs({ nearStorage: { isNear: true, needsRegistration: true, blocksAction: true } })),
236
+ ).toEqual({ kind: 'needsSetup', reason: 'nearStorage' });
237
+ // An errored check leaves `blocksAction` false; the lifecycle must not read that as "registered".
238
+ expect(
239
+ resolveSwapLifecycle(
240
+ inputs({ nearStorage: { isNear: true, needsRegistration: false, blocksAction: false, checkFailed: true } }),
241
+ ),
242
+ ).toEqual({ kind: 'needsSetup', reason: 'nearStorageCheckFailed' });
243
+ expect(resolveSwapLifecycle(inputs({ externalBlocked: true }))).toEqual({ kind: 'needsSetup', reason: 'external' });
244
+ });
245
+
246
+ it('is checking, not needsSetup, while a setup tx or its refreshed check is still running', () => {
247
+ const trustline = { stellar: { ...OPEN_STELLAR, isStellar: true, needsTrustline: true, blocksAction: true } };
248
+ expect(resolveSwapLifecycle(inputs({ ...trustline, setupBusy: true }))).toEqual({ kind: 'checking' });
249
+ expect(resolveSwapLifecycle(inputs({ externalBlocked: true, setupBusy: true }))).toEqual({ kind: 'checking' });
250
+ // Nothing to set up: a busy flag alone does not hold a ready swap.
251
+ expect(resolveSwapLifecycle(inputs({ setupBusy: true }))).toEqual({
252
+ kind: 'ready',
253
+ approvalStrategy: 'atomic-batch',
254
+ });
255
+ });
256
+
257
+ it('is checking while a gate is still resolving', () => {
258
+ expect(resolveSwapLifecycle(inputs({ stellar: { ...OPEN_STELLAR, isStellar: true, blocksAction: true } }))).toEqual(
259
+ {
260
+ kind: 'checking',
261
+ },
262
+ );
263
+ expect(
264
+ resolveSwapLifecycle(inputs({ nearStorage: { isNear: true, needsRegistration: false, blocksAction: true } })),
265
+ ).toEqual({
266
+ kind: 'checking',
267
+ });
268
+ });
269
+
270
+ it('asks for a chain switch only once the destination is clear', () => {
271
+ expect(resolveSwapLifecycle(inputs({ isWrongChain: true }))).toEqual({ kind: 'needsChainSwitch' });
272
+ expect(resolveSwapLifecycle(inputs({ isWrongChain: true, externalBlocked: true }))).toEqual({
273
+ kind: 'needsSetup',
274
+ reason: 'external',
275
+ });
276
+ });
277
+
278
+ it('waits for the approval strategy, and fails when it cannot be read', () => {
279
+ expect(resolveSwapLifecycle(inputs({ strategy: { data: undefined, error: null } }))).toEqual({ kind: 'checking' });
280
+ const error = new Error('allowance read failed');
281
+ expect(resolveSwapLifecycle(inputs({ strategy: { data: undefined, error } }))).toEqual({ kind: 'failed', error });
282
+ // A failed background refetch keeps the cached strategy, so a ready form stays ready.
283
+ expect(resolveSwapLifecycle(inputs({ strategy: { data: 'sequential', error } }))).toEqual({
284
+ kind: 'ready',
285
+ approvalStrategy: 'sequential',
286
+ });
287
+ });
288
+ });
289
+
290
+ function stripPhase({ srcChainKey, srcTxHash }: { srcChainKey: string; srcTxHash: string }) {
291
+ return { srcChainKey, srcTxHash };
292
+ }
@@ -0,0 +1,183 @@
1
+ import {
2
+ ATOMIC_BATCH_UNCONFIRMED,
3
+ isSodaxError,
4
+ type CreateIntentParams,
5
+ type Hex,
6
+ type SpokeChainKey,
7
+ type SwapApprovalStrategy,
8
+ type SwapStatusSummary,
9
+ type SwapWithApprovalResponse,
10
+ } from '@sodax/sdk';
11
+ import type { NearStorageGateState } from './nearStorageGate.js';
12
+ import type { StellarGateState } from './stellarGate.js';
13
+
14
+ /** A prerequisite the user must resolve before the swap can go out. */
15
+ export type SwapSetupReason =
16
+ | 'stellarActivation'
17
+ | 'stellarFunding'
18
+ | 'stellarTrustline'
19
+ | 'stellarCheckFailed'
20
+ | 'nearStorage'
21
+ | 'nearStorageCheckFailed'
22
+ | 'external';
23
+
24
+ /**
25
+ * Where a swap form stands, discriminated on `kind`. `useSwapLifecycle`'s `next()` acts on it.
26
+ *
27
+ * - `checking` — waiting before anything can be done: a gate or the approval strategy is still reading, or a
28
+ * setup tx (activation, trustline, NEAR storage) is in flight or its check is refreshing.
29
+ * - `submitting` — the swap call is in flight: signing, and on the default backend path settlement too.
30
+ * - `pending` — the source tx is on-chain and its status is being read. `error` is set when the swap call
31
+ * failed after broadcast, or when the status read cannot recover (a rejected API key); the swap may
32
+ * still complete either way. The read can also stop polling without an error (after its budget of
33
+ * ambiguous reads), so keep `reset()` reachable here.
34
+ * - `unconfirmed` — the wallet accepted an approve + swap batch that was not confirmed in time. It may
35
+ * still land, so `next()` never sends it again: it waits for that batch and finishes the swap once it
36
+ * lands. `reset()` stops tracking it.
37
+ */
38
+ export type SwapLifecycleState =
39
+ | { kind: 'idle' }
40
+ | { kind: 'checking' }
41
+ | { kind: 'needsChainSwitch' }
42
+ | { kind: 'needsSetup'; reason: SwapSetupReason }
43
+ | { kind: 'ready'; approvalStrategy: SwapApprovalStrategy }
44
+ | { kind: 'submitting' }
45
+ | { kind: 'pending'; srcChainKey: SpokeChainKey; srcTxHash: string; error?: Error }
46
+ | { kind: 'unconfirmed'; batchId: string; callCount?: number; error: Error }
47
+ | { kind: 'settled'; srcChainKey: SpokeChainKey; srcTxHash: string; fillTxHash?: Hex }
48
+ | { kind: 'failed'; error: Error; srcChainKey?: SpokeChainKey; srcTxHash?: string };
49
+
50
+ /** The swap-mutation fields the lifecycle reads. A `useSwapWithApproval` result satisfies it. */
51
+ export type SwapAttemptSource = {
52
+ status: 'idle' | 'pending' | 'success' | 'error';
53
+ data: SwapWithApprovalResponse | undefined;
54
+ error: Error | null;
55
+ variables: { params: CreateIntentParams } | undefined;
56
+ };
57
+
58
+ /** The swap attempt for the current params, reduced to what the state needs. */
59
+ export type SwapAttempt =
60
+ | { phase: 'none' }
61
+ | { phase: 'submitting' }
62
+ | { phase: 'broadcast'; srcChainKey: SpokeChainKey; srcTxHash: string; error?: Error }
63
+ | { phase: 'unconfirmed'; batchId: string; callCount?: number; error: Error }
64
+ | { phase: 'failed'; error: Error };
65
+
66
+ export type SwapLifecycleInputs = {
67
+ attempt: SwapAttempt;
68
+ /** `summarizeSwapStatus` of the attempt's detailed status, once one is read. */
69
+ status: SwapStatusSummary | undefined;
70
+ /** A status-read error that will not clear by polling again (a rejected API key). */
71
+ statusError: Error | undefined;
72
+ /** Intent params and a source wallet provider are both present. */
73
+ hasInputs: boolean;
74
+ stellar: StellarGateState;
75
+ /** `checkFailed`: the registration check errored, so the swap waits for a retry rather than going out blind. */
76
+ nearStorage: NearStorageGateState & { checkFailed?: boolean };
77
+ externalBlocked: boolean;
78
+ /** A setup tx is in flight, or the check it invalidated is still refreshing: acting now would resend it. */
79
+ setupBusy: boolean;
80
+ isWrongChain: boolean;
81
+ strategy: { data: SwapApprovalStrategy | undefined; error: Error | null };
82
+ };
83
+
84
+ /** Same swap: every field but the deadline, so rebuilding the params with a fresh deadline is not a new swap. */
85
+ export function isSameIntent(a: CreateIntentParams, b: CreateIntentParams): boolean {
86
+ return (
87
+ a.srcChainKey === b.srcChainKey &&
88
+ a.dstChainKey === b.dstChainKey &&
89
+ a.srcAddress === b.srcAddress &&
90
+ a.dstAddress === b.dstAddress &&
91
+ a.inputToken === b.inputToken &&
92
+ a.outputToken === b.outputToken &&
93
+ a.inputAmount === b.inputAmount &&
94
+ a.minOutputAmount === b.minOutputAmount &&
95
+ a.allowPartialFill === b.allowPartialFill &&
96
+ a.solver === b.solver &&
97
+ a.data === b.data &&
98
+ a.hook?.kind === b.hook?.kind &&
99
+ a.deliveryData === b.deliveryData
100
+ );
101
+ }
102
+
103
+ /**
104
+ * The attempt the lifecycle tracks. A swap in flight, or one that may still land (a failure after
105
+ * broadcast, which keeps its source tx from `error.context.srcTxHash`, or an unconfirmed batch), counts
106
+ * until `reset()` whatever the params, so a param edit cannot re-enable the button and swap twice. A
107
+ * completed or never-sent swap counts only while it is for the current params.
108
+ */
109
+ export function toSwapAttempt(mutation: SwapAttemptSource, intentParams: CreateIntentParams | undefined): SwapAttempt {
110
+ if (mutation.status === 'pending') return { phase: 'submitting' };
111
+ const attempted = mutation.variables?.params;
112
+ if (mutation.status === 'idle' || !attempted) return { phase: 'none' };
113
+ const attempt = toFinishedAttempt(mutation, attempted);
114
+ const mayStillLand =
115
+ attempt.phase === 'unconfirmed' || (attempt.phase === 'broadcast' && attempt.error !== undefined);
116
+ if (mayStillLand || (intentParams && isSameIntent(attempted, intentParams))) return attempt;
117
+ return { phase: 'none' };
118
+ }
119
+
120
+ function toFinishedAttempt(mutation: SwapAttemptSource, attempted: CreateIntentParams): SwapAttempt {
121
+ if (mutation.status === 'success' && mutation.data) {
122
+ const { srcChainKey, srcTxHash } = mutation.data.intentDeliveryInfo;
123
+ return { phase: 'broadcast', srcChainKey, srcTxHash };
124
+ }
125
+ const error = mutation.error ?? new Error('Swap failed');
126
+ const context = isSodaxError(error) ? error.context : undefined;
127
+ if (typeof context?.srcTxHash === 'string') {
128
+ return { phase: 'broadcast', srcChainKey: attempted.srcChainKey, srcTxHash: context.srcTxHash, error };
129
+ }
130
+ if (context?.reason === ATOMIC_BATCH_UNCONFIRMED && typeof context.batchId === 'string') {
131
+ return typeof context.callCount === 'number'
132
+ ? { phase: 'unconfirmed', batchId: context.batchId, callCount: context.callCount, error }
133
+ : { phase: 'unconfirmed', batchId: context.batchId, error };
134
+ }
135
+ return { phase: 'failed', error };
136
+ }
137
+
138
+ /**
139
+ * Derives the lifecycle state. Order: an attempt in flight or broadcast wins; then missing inputs;
140
+ * then destination prerequisites (Stellar, NEAR, app-owned); then the source chain; then the
141
+ * approval strategy. Pure — `useSwapLifecycle` feeds it from its sub-hooks.
142
+ */
143
+ export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycleState {
144
+ const { attempt, status } = inputs;
145
+ if (attempt.phase === 'submitting') return { kind: 'submitting' };
146
+ if (attempt.phase === 'broadcast') {
147
+ const { srcChainKey, srcTxHash } = attempt;
148
+ if (status?.state === 'solved') return { kind: 'settled', srcChainKey, srcTxHash, fillTxHash: status.fillTxHash };
149
+ if (status?.state === 'failed') {
150
+ return { kind: 'failed', error: attempt.error ?? new Error('Swap failed to settle'), srcChainKey, srcTxHash };
151
+ }
152
+ const error = attempt.error ?? inputs.statusError;
153
+ return error ? { kind: 'pending', srcChainKey, srcTxHash, error } : { kind: 'pending', srcChainKey, srcTxHash };
154
+ }
155
+ if (attempt.phase === 'unconfirmed') {
156
+ const { batchId, callCount, error } = attempt;
157
+ return callCount === undefined
158
+ ? { kind: 'unconfirmed', batchId, error }
159
+ : { kind: 'unconfirmed', batchId, callCount, error };
160
+ }
161
+ if (attempt.phase === 'failed') return { kind: 'failed', error: attempt.error };
162
+ if (!inputs.hasInputs) return { kind: 'idle' };
163
+
164
+ const reason = setupReason(inputs);
165
+ if (reason) return inputs.setupBusy ? { kind: 'checking' } : { kind: 'needsSetup', reason };
166
+ if (inputs.stellar.blocksAction || inputs.nearStorage.blocksAction) return { kind: 'checking' };
167
+ if (inputs.isWrongChain) return { kind: 'needsChainSwitch' };
168
+ // A failed refetch keeps the last strategy; `swapWithApproval` resolves its own before sending anyway.
169
+ if (inputs.strategy.error && !inputs.strategy.data) return { kind: 'failed', error: inputs.strategy.error };
170
+ if (!inputs.strategy.data) return { kind: 'checking' };
171
+ return { kind: 'ready', approvalStrategy: inputs.strategy.data };
172
+ }
173
+
174
+ function setupReason({ stellar, nearStorage, externalBlocked }: SwapLifecycleInputs): SwapSetupReason | undefined {
175
+ if (stellar.needsActivation) return 'stellarActivation';
176
+ if (stellar.needsFunding) return 'stellarFunding';
177
+ if (stellar.needsTrustline) return 'stellarTrustline';
178
+ if (stellar.checkFailed) return 'stellarCheckFailed';
179
+ if (nearStorage.needsRegistration) return 'nearStorage';
180
+ if (nearStorage.checkFailed) return 'nearStorageCheckFailed';
181
+ if (externalBlocked) return 'external';
182
+ return undefined;
183
+ }