@lifi/sdk 4.10.0 → 4.11.0

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 (132) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +9 -0
  3. package/dist/cjs/client/createClient.js +6 -4
  4. package/dist/cjs/client/createClient.js.map +1 -1
  5. package/dist/cjs/client/findProvider.d.ts +10 -0
  6. package/dist/cjs/client/findProvider.js +11 -0
  7. package/dist/cjs/client/findProvider.js.map +1 -0
  8. package/dist/cjs/core/BaseStepExecutor.d.ts +1 -1
  9. package/dist/cjs/core/BaseStepExecutor.js +21 -9
  10. package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
  11. package/dist/cjs/core/StatusManager.d.ts +10 -0
  12. package/dist/cjs/core/StatusManager.js +105 -3
  13. package/dist/cjs/core/StatusManager.js.map +1 -1
  14. package/dist/cjs/core/execution.js +30 -14
  15. package/dist/cjs/core/execution.js.map +1 -1
  16. package/dist/cjs/core/executionState.d.ts +34 -2
  17. package/dist/cjs/core/executionState.js +44 -1
  18. package/dist/cjs/core/executionState.js.map +1 -1
  19. package/dist/cjs/core/prepareRestart.js +14 -6
  20. package/dist/cjs/core/prepareRestart.js.map +1 -1
  21. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js +4 -2
  22. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  23. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  24. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js +20 -0
  25. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  26. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  27. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js +44 -0
  28. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  29. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  30. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js +76 -17
  31. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  32. package/dist/cjs/core/transactionState.d.ts +121 -0
  33. package/dist/cjs/core/transactionState.js +164 -0
  34. package/dist/cjs/core/transactionState.js.map +1 -0
  35. package/dist/cjs/errors/errors.d.ts +13 -2
  36. package/dist/cjs/errors/errors.js +5 -2
  37. package/dist/cjs/errors/errors.js.map +1 -1
  38. package/dist/cjs/index.d.ts +5 -2
  39. package/dist/cjs/index.js +14 -0
  40. package/dist/cjs/types/core.d.ts +49 -3
  41. package/dist/cjs/types/execution.d.ts +8 -0
  42. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  43. package/dist/cjs/utils/waitForResult.d.ts +3 -1
  44. package/dist/cjs/utils/waitForResult.js +15 -10
  45. package/dist/cjs/utils/waitForResult.js.map +1 -1
  46. package/dist/cjs/version.d.ts +1 -1
  47. package/dist/cjs/version.js +1 -1
  48. package/dist/cjs/version.js.map +1 -1
  49. package/dist/esm/actions/getRoutes.d.ts.map +1 -1
  50. package/dist/esm/actions/index.d.ts.map +1 -1
  51. package/dist/esm/client/createClient.d.ts.map +1 -1
  52. package/dist/esm/client/createClient.js +6 -4
  53. package/dist/esm/client/createClient.js.map +1 -1
  54. package/dist/esm/client/findProvider.d.ts +10 -0
  55. package/dist/esm/client/findProvider.d.ts.map +1 -0
  56. package/dist/esm/client/findProvider.js +10 -0
  57. package/dist/esm/client/findProvider.js.map +1 -0
  58. package/dist/esm/core/BaseStepExecutor.d.ts +1 -1
  59. package/dist/esm/core/BaseStepExecutor.d.ts.map +1 -1
  60. package/dist/esm/core/BaseStepExecutor.js +22 -10
  61. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  62. package/dist/esm/core/StatusManager.d.ts +10 -0
  63. package/dist/esm/core/StatusManager.d.ts.map +1 -1
  64. package/dist/esm/core/StatusManager.js +105 -3
  65. package/dist/esm/core/StatusManager.js.map +1 -1
  66. package/dist/esm/core/execution.d.ts.map +1 -1
  67. package/dist/esm/core/execution.js +30 -14
  68. package/dist/esm/core/execution.js.map +1 -1
  69. package/dist/esm/core/executionState.d.ts +34 -2
  70. package/dist/esm/core/executionState.d.ts.map +1 -1
  71. package/dist/esm/core/executionState.js +44 -1
  72. package/dist/esm/core/executionState.js.map +1 -1
  73. package/dist/esm/core/prepareRestart.d.ts.map +1 -1
  74. package/dist/esm/core/prepareRestart.js +14 -6
  75. package/dist/esm/core/prepareRestart.js.map +1 -1
  76. package/dist/esm/core/tasks/WaitForTransactionStatusTask.d.ts.map +1 -1
  77. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +4 -2
  78. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  79. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  80. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts.map +1 -0
  81. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js +19 -0
  82. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  83. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  84. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts.map +1 -0
  85. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js +43 -0
  86. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  87. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  88. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts.map +1 -1
  89. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js +76 -18
  90. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  91. package/dist/esm/core/transactionState.d.ts +121 -0
  92. package/dist/esm/core/transactionState.d.ts.map +1 -0
  93. package/dist/esm/core/transactionState.js +152 -0
  94. package/dist/esm/core/transactionState.js.map +1 -0
  95. package/dist/esm/errors/errors.d.ts +13 -2
  96. package/dist/esm/errors/errors.d.ts.map +1 -1
  97. package/dist/esm/errors/errors.js +5 -2
  98. package/dist/esm/errors/errors.js.map +1 -1
  99. package/dist/esm/index.d.ts +5 -2
  100. package/dist/esm/index.js +4 -1
  101. package/dist/esm/types/actions.d.ts.map +1 -1
  102. package/dist/esm/types/core.d.ts +49 -3
  103. package/dist/esm/types/core.d.ts.map +1 -1
  104. package/dist/esm/types/execution.d.ts +8 -0
  105. package/dist/esm/types/execution.d.ts.map +1 -1
  106. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  107. package/dist/esm/utils/waitForResult.d.ts +3 -1
  108. package/dist/esm/utils/waitForResult.d.ts.map +1 -1
  109. package/dist/esm/utils/waitForResult.js +15 -10
  110. package/dist/esm/utils/waitForResult.js.map +1 -1
  111. package/dist/esm/version.d.ts +1 -1
  112. package/dist/esm/version.js +1 -1
  113. package/dist/esm/version.js.map +1 -1
  114. package/package.json +2 -2
  115. package/src/client/createClient.ts +12 -4
  116. package/src/client/findProvider.ts +21 -0
  117. package/src/core/BaseStepExecutor.ts +40 -6
  118. package/src/core/StatusManager.ts +211 -2
  119. package/src/core/execution.ts +69 -20
  120. package/src/core/executionState.ts +84 -1
  121. package/src/core/prepareRestart.ts +29 -13
  122. package/src/core/tasks/WaitForTransactionStatusTask.ts +10 -1
  123. package/src/core/tasks/helpers/getStepStatusRequest.ts +20 -0
  124. package/src/core/tasks/helpers/isKnownToStatusApi.ts +57 -0
  125. package/src/core/tasks/helpers/waitForTransactionStatus.ts +128 -17
  126. package/src/core/transactionState.ts +194 -0
  127. package/src/errors/errors.ts +21 -2
  128. package/src/index.ts +14 -0
  129. package/src/types/core.ts +50 -3
  130. package/src/types/execution.ts +8 -0
  131. package/src/utils/waitForResult.ts +16 -6
  132. package/src/version.ts +1 -1
@@ -0,0 +1,57 @@
1
+ import type { LiFiStep } from '@lifi/types'
2
+ import { getStatus } from '../../../actions/getStatus.js'
3
+ import type { SDKClient } from '../../../types/core.js'
4
+ import { getStepStatusRequest } from './getStepStatusRequest.js'
5
+
6
+ /** The status API gets this long before its silence counts as a miss. */
7
+ const STATUS_API_TIMEOUT_MS = 10_000
8
+
9
+ /**
10
+ * The status-API veto of the "dropped" rule. True only when the API answers
11
+ * with a status other than NOT_FOUND: the transaction then exists and is never
12
+ * dropped. The API answers HTTP 404 for unknown hashes and also for landed
13
+ * transactions it does not index, so a miss or an error says nothing and only
14
+ * a chain node whose history covers the signing time can prove absence.
15
+ *
16
+ * No answer within `STATUS_API_TIMEOUT_MS` is a miss too, so a hung API cannot
17
+ * stop the wait task at its final verdict. The timer aborts the request and
18
+ * also settles the call, in case a request interceptor dropped the signal.
19
+ * Not `AbortSignal.timeout`: a published SDK should not raise its runtime
20
+ * floor for it; one controller and one timer cover it.
21
+ *
22
+ * @internal
23
+ */
24
+ export async function isKnownToStatusApi(
25
+ client: SDKClient,
26
+ step: LiFiStep,
27
+ txHash: string
28
+ ): Promise<boolean> {
29
+ const controller = new AbortController()
30
+ let timer: ReturnType<typeof setTimeout> | undefined
31
+ const timeout = new Promise<never>((_, reject) => {
32
+ timer = setTimeout(() => {
33
+ const error = new Error(
34
+ `The status API did not answer within ${STATUS_API_TIMEOUT_MS}ms.`
35
+ )
36
+ controller.abort(error)
37
+ reject(error)
38
+ }, STATUS_API_TIMEOUT_MS)
39
+ // A pending timer keeps Node's event loop alive. The `finally` clears it;
40
+ // the unref only covers a path that skips it.
41
+ const handle = timer as unknown as { unref?: () => void }
42
+ handle.unref?.()
43
+ })
44
+ try {
45
+ const response = await Promise.race([
46
+ getStatus(client, getStepStatusRequest(step, txHash), {
47
+ signal: controller.signal,
48
+ }),
49
+ timeout,
50
+ ])
51
+ return response.status !== 'NOT_FOUND'
52
+ } catch (_) {
53
+ return false
54
+ } finally {
55
+ clearTimeout(timer)
56
+ }
57
+ }
@@ -2,28 +2,55 @@ import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'
2
2
  import { getStatus } from '../../../actions/getStatus.js'
3
3
  import { ServerError } from '../../../errors/errors.js'
4
4
  import type { ExecutionActionType, SDKClient } from '../../../types/core.js'
5
+ import { getAbortError } from '../../../utils/abort.js'
5
6
  import { waitForResult } from '../../../utils/waitForResult.js'
6
7
  import { getSubstatusMessage } from '../../actionMessages.js'
7
8
  import type { StatusManager } from '../../StatusManager.js'
9
+ import { getStepStatusRequest } from './getStepStatusRequest.js'
8
10
 
9
- const TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}
11
+ type Waiter = {
12
+ resolve: (status: StatusResponse) => void
13
+ reject: (error: unknown) => void
14
+ }
15
+
16
+ /** The `/status` poll of one transaction hash, shared by all its callers. */
17
+ type StatusPoll = {
18
+ promise: Promise<StatusResponse>
19
+ controller: AbortController
20
+ /** Callers with a signal that still wait, once the first one joined. */
21
+ waiters?: Set<Waiter>
22
+ /** A caller without a signal joined, so the poll runs until it settles. */
23
+ pinned: boolean
24
+ }
10
25
 
26
+ /** @internal The running poll per transaction hash. Exported for tests. */
27
+ export const TRANSACTION_HASH_OBSERVERS: Partial<Record<string, StatusPoll>> =
28
+ {}
29
+
30
+ /**
31
+ * Waits for the final status of `txHash`. Callers that wait for the same hash
32
+ * share one poll. A caller whose `signal` aborts leaves at once with the abort
33
+ * reason; the poll itself ends only when every caller with a signal has left
34
+ * and no caller without a signal joined it.
35
+ */
11
36
  export async function waitForTransactionStatus(
12
37
  client: SDKClient,
13
38
  statusManager: StatusManager,
14
39
  txHash: string,
15
40
  step: LiFiStep,
16
41
  actionType: ExecutionActionType,
17
- interval = 5_000
42
+ interval = 5_000,
43
+ signal?: AbortSignal
18
44
  ): Promise<StatusResponse> {
19
- const _getStatus = (): Promise<StatusResponse | undefined> => {
20
- return getStatus(client, {
21
- fromChain: step.action.fromChainId,
22
- fromAddress: step.action.fromAddress,
23
- toChain: step.action.toChainId,
24
- txHash,
25
- ...(step.tool !== 'custom' && { bridge: step.tool }),
26
- ...(step.transactionId && { transactionId: step.transactionId }),
45
+ if (signal?.aborted) {
46
+ throw getAbortError(signal)
47
+ }
48
+
49
+ const _getStatus = (
50
+ pollSignal: AbortSignal
51
+ ): Promise<StatusResponse | undefined> => {
52
+ return getStatus(client, getStepStatusRequest(step, txHash), {
53
+ signal: pollSignal,
27
54
  })
28
55
  .then((statusResponse) => {
29
56
  switch (statusResponse.status) {
@@ -61,16 +88,22 @@ export async function waitForTransactionStatus(
61
88
  })
62
89
  }
63
90
 
64
- let status = TRANSACTION_HASH_OBSERVERS[txHash]
91
+ let poll = TRANSACTION_HASH_OBSERVERS[txHash]
65
92
 
66
- if (!status) {
67
- status = waitForResult(_getStatus, interval).finally(() => {
68
- delete TRANSACTION_HASH_OBSERVERS[txHash]
69
- })
70
- TRANSACTION_HASH_OBSERVERS[txHash] = status
93
+ if (!poll) {
94
+ const controller = new AbortController()
95
+ const promise: Promise<StatusResponse> = waitForResult(
96
+ () => _getStatus(controller.signal),
97
+ interval,
98
+ undefined,
99
+ undefined,
100
+ controller.signal
101
+ ).finally(() => removePoll(txHash, promise))
102
+ poll = { promise, controller, pinned: false }
103
+ TRANSACTION_HASH_OBSERVERS[txHash] = poll
71
104
  }
72
105
 
73
- const resolvedStatus = await status
106
+ const resolvedStatus = await joinPoll(txHash, poll, signal)
74
107
 
75
108
  if (!('receiving' in resolvedStatus)) {
76
109
  throw new ServerError(
@@ -80,3 +113,81 @@ export async function waitForTransactionStatus(
80
113
 
81
114
  return resolvedStatus
82
115
  }
116
+
117
+ function joinPoll(
118
+ txHash: string,
119
+ poll: StatusPoll,
120
+ signal: AbortSignal | undefined
121
+ ): Promise<StatusResponse> {
122
+ if (!signal) {
123
+ poll.pinned = true
124
+ return poll.promise
125
+ }
126
+ const waiters = poll.waiters ?? subscribe(poll)
127
+ return new Promise<StatusResponse>((resolve, reject) => {
128
+ // Stop listening before settling, so a later abort cannot reach the poll.
129
+ const waiter: Waiter = {
130
+ resolve: (status) => {
131
+ signal.removeEventListener('abort', leave)
132
+ resolve(status)
133
+ },
134
+ reject: (error) => {
135
+ signal.removeEventListener('abort', leave)
136
+ reject(error)
137
+ },
138
+ }
139
+ const leave = (): void => {
140
+ // `leave` can run without the event, so the listener is not always gone.
141
+ signal.removeEventListener('abort', leave)
142
+ waiters.delete(waiter)
143
+ const reason = getAbortError(signal)
144
+ reject(reason)
145
+ if (!poll.pinned && waiters.size === 0) {
146
+ // A caller arriving now must start a new poll, not join this one.
147
+ removePoll(txHash, poll.promise)
148
+ poll.controller.abort(reason)
149
+ }
150
+ }
151
+ waiters.add(waiter)
152
+ signal.addEventListener('abort', leave, { once: true })
153
+ // Defensive; this branch does not run today. The check at the top of
154
+ // `waitForTransactionStatus` throws for an aborted signal, and no await
155
+ // runs between that check and this one. An aborted signal fires no more
156
+ // abort event, so without the branch a caller that joins with an aborted
157
+ // signal would not leave: it would wait, and keep the poll running,
158
+ // until the poll settles.
159
+ if (signal.aborted) {
160
+ leave()
161
+ }
162
+ })
163
+ }
164
+
165
+ /**
166
+ * Hands the result to the callers with a signal, through one reaction per
167
+ * poll, so a caller that leaves holds nothing here. It also handles the
168
+ * rejection of a poll that every caller left.
169
+ */
170
+ function subscribe(poll: StatusPoll): Set<Waiter> {
171
+ const waiters = new Set<Waiter>()
172
+ poll.waiters = waiters
173
+ poll.promise.then(
174
+ (status) => {
175
+ for (const waiter of waiters) {
176
+ waiter.resolve(status)
177
+ }
178
+ },
179
+ (error: unknown) => {
180
+ for (const waiter of waiters) {
181
+ waiter.reject(error)
182
+ }
183
+ }
184
+ )
185
+ return waiters
186
+ }
187
+
188
+ /** Drops the entry for `txHash` only while it still holds this poll. */
189
+ function removePoll(txHash: string, promise: Promise<StatusResponse>): void {
190
+ if (TRANSACTION_HASH_OBSERVERS[txHash]?.promise === promise) {
191
+ delete TRANSACTION_HASH_OBSERVERS[txHash]
192
+ }
193
+ }
@@ -0,0 +1,194 @@
1
+ import { LiFiErrorCode } from '../errors/constants.js'
2
+ import { TransactionError } from '../errors/errors.js'
3
+ import type {
4
+ ExecutionAction,
5
+ ExecutionActionType,
6
+ LiFiStepExtended,
7
+ } from '../types/core.js'
8
+
9
+ /**
10
+ * Action types that carry the step's own transaction.
11
+ *
12
+ * @internal
13
+ */
14
+ export const TRANSACTION_ACTION_TYPES: readonly ExecutionActionType[] = [
15
+ 'SWAP',
16
+ 'CROSS_CHAIN',
17
+ ]
18
+
19
+ /**
20
+ * Stored bytes on a chain without its own expiry (Sui, Solana with a durable
21
+ * nonce, Bitcoin) are resent only this long after signing. Past it, a page
22
+ * load could otherwise execute a swap on a quote the user no longer expects.
23
+ *
24
+ * @internal
25
+ */
26
+ export const MAX_RESEND_AGE_MS = 120_000
27
+
28
+ /**
29
+ * Without an expiry verdict, a signature younger than this is never declared
30
+ * dropped. Solana blockhashes and Tron transactions expire well before it.
31
+ *
32
+ * @internal
33
+ */
34
+ export const DROPPED_FALLBACK_AGE_MS = 300_000
35
+
36
+ /**
37
+ * Subtracted from `execution.signedAt` (the device clock) when it anchors a
38
+ * history-coverage check, so a device clock that runs fast cannot make a node
39
+ * look like it covers the signing time when it does not.
40
+ *
41
+ * @internal
42
+ */
43
+ export const CLOCK_SKEW_MARGIN_MS = 600_000
44
+
45
+ /**
46
+ * Fields a sign task clears before it writes a new transaction's data, and
47
+ * that re-initializing a final-failed action clears. `taskId` is included: a
48
+ * stale relayed or batched task id would otherwise keep the action open.
49
+ *
50
+ * @internal
51
+ */
52
+ export const CLEARED_TRANSACTION_FIELDS: Readonly<
53
+ Pick<ExecutionAction, 'txHash' | 'txLink' | 'txHex' | 'txFinal' | 'taskId'>
54
+ > = Object.freeze({
55
+ txHash: undefined,
56
+ txLink: undefined,
57
+ txHex: undefined,
58
+ txFinal: undefined,
59
+ taskId: undefined,
60
+ })
61
+
62
+ /**
63
+ * True when the action has a transaction to follow, landed or not: a hash, a
64
+ * task id or stored signed bytes, unless the action FAILED with a final
65
+ * outcome. Every resume decision uses this one predicate, so the pipeline
66
+ * selector and the pre-sign guard can never disagree.
67
+ *
68
+ * Resume rules for providers. A step never signs or sends a second
69
+ * transaction while an earlier one can still land:
70
+ * 1. Pick the first task with this predicate: open and DONE, the status
71
+ * wait; open, the provider's wait task; otherwise the first task.
72
+ * 2. In the sign task, call `assertNoOpenTransaction` at the start, right
73
+ * before each wallet call and, where the SDK sends, right after the
74
+ * wallet returns. Write the new data with `CLEARED_TRANSACTION_FIELDS`
75
+ * and `signedAt`.
76
+ * 3. From the last check, nothing awaits until the send or, where the SDK
77
+ * sends signed bytes, until they are stored as `txHex`, before the first
78
+ * send. Clear `txHex` only when the outcome is known, no node can still
79
+ * hold the bytes, or they no longer decode.
80
+ * 4. A resume never signs. It looks the transaction up and resends the
81
+ * stored bytes only while `isResendAllowed` (or the chain's own expiry)
82
+ * allows it; otherwise it only waits.
83
+ * 5. Mark an error final only on a verdict about the transaction: failed
84
+ * or reverted (on chain or at the relayer), cancelled, replaced, or
85
+ * dropped with proof. Dropped needs all three: the transaction can no
86
+ * longer land, a node that covers its window reports it absent (in the
87
+ * same response where the chain allows it), and `isKnownToStatusApi` is
88
+ * false. In doubt, throw without the marker and keep the fields.
89
+ * 6. Give `context.signal` only to waits that start after the broadcast. On
90
+ * abort, return `PAUSED` and write nothing.
91
+ */
92
+ export function hasOpenTransaction(action?: ExecutionAction): boolean {
93
+ if (!action) {
94
+ return false
95
+ }
96
+ if (!(action.txHash || action.taskId || action.txHex)) {
97
+ return false
98
+ }
99
+ return !(action.status === 'FAILED' && action.txFinal === true)
100
+ }
101
+
102
+ /**
103
+ * True when any SWAP / CROSS_CHAIN action of the step has an open transaction.
104
+ *
105
+ * @internal
106
+ */
107
+ export function hasStepOpenTransaction(step: LiFiStepExtended): boolean {
108
+ return !!step.execution?.actions?.some(
109
+ (action) =>
110
+ TRANSACTION_ACTION_TYPES.includes(action.type) &&
111
+ hasOpenTransaction(action)
112
+ )
113
+ }
114
+
115
+ /**
116
+ * Walks the error and its `cause` chain. Parsers may rebuild errors, so the
117
+ * marker is read from the original error. A property check instead of
118
+ * `instanceof` keeps it working across duplicated installs.
119
+ *
120
+ * @internal
121
+ */
122
+ export function isFinalTransactionError(error: unknown): boolean {
123
+ const seen = new Set<unknown>()
124
+ let current: unknown = error
125
+ while (current && typeof current === 'object' && !seen.has(current)) {
126
+ seen.add(current)
127
+ if ((current as { final?: unknown }).final === true) {
128
+ return true
129
+ }
130
+ current = (current as { cause?: unknown }).cause
131
+ }
132
+ return false
133
+ }
134
+
135
+ /**
136
+ * The error of a step that would sign a second transaction while its first
137
+ * one may still land.
138
+ *
139
+ * @internal
140
+ */
141
+ export function transactionConflictError(): TransactionError {
142
+ return new TransactionError(
143
+ LiFiErrorCode.TransactionConflict,
144
+ 'A transaction for this step was already signed and may still land. Resume the route to wait for it instead of signing a new one.'
145
+ )
146
+ }
147
+
148
+ /**
149
+ * Called first in every sign task. With correct pipeline selectors it never
150
+ * throws; it stops a second signature if a selector ever routes an open
151
+ * transaction back to signing. Every sign task calls it again on the freshly
152
+ * found action right before its wallet call: a late write of an older run can
153
+ * merge a transaction into the action during the awaits in between. A sign
154
+ * task that sends the transaction itself calls it once more after the wallet
155
+ * returns, before it writes or sends anything: the merge can also land while
156
+ * the prompt is open.
157
+ *
158
+ * @internal
159
+ */
160
+ export function assertNoOpenTransaction(action?: ExecutionAction): void {
161
+ if (hasOpenTransaction(action)) {
162
+ throw transactionConflictError()
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Unknown signing time never allows a resend. Nor does a signing time in the
168
+ * future: a device clock that ran ahead at signing and was corrected later
169
+ * would otherwise stretch the cap by the clock error.
170
+ *
171
+ * @internal
172
+ */
173
+ export function isResendAllowed(
174
+ signedAt: number | undefined,
175
+ now: number = Date.now()
176
+ ): boolean {
177
+ return (
178
+ signedAt !== undefined &&
179
+ now >= signedAt &&
180
+ now - signedAt < MAX_RESEND_AGE_MS
181
+ )
182
+ }
183
+
184
+ /**
185
+ * Unknown signing time never allows a drop.
186
+ *
187
+ * @internal
188
+ */
189
+ export function isOldEnoughToDrop(
190
+ signedAt: number | undefined,
191
+ now: number = Date.now()
192
+ ): boolean {
193
+ return signedAt !== undefined && now - signedAt > DROPPED_FALLBACK_AGE_MS
194
+ }
@@ -14,9 +14,27 @@ export class ProviderError extends BaseError {
14
14
  }
15
15
  }
16
16
 
17
+ export interface TransactionErrorOptions {
18
+ /**
19
+ * A definite verdict about the transaction (failed or reverted on chain or
20
+ * at the relayer, cancelled, replaced, or dropped with proof). The step
21
+ * executor then flags the failed action with `txFinal`, so a restart signs
22
+ * a new transaction.
23
+ */
24
+ final?: boolean
25
+ }
26
+
17
27
  export class TransactionError extends BaseError {
18
- constructor(code: LiFiErrorCode, message: string, cause?: Error) {
28
+ readonly final: boolean
29
+
30
+ constructor(
31
+ code: LiFiErrorCode,
32
+ message: string,
33
+ cause?: Error,
34
+ options?: TransactionErrorOptions
35
+ ) {
19
36
  super(ErrorName.TransactionError, code, message, cause)
37
+ this.final = options?.final ?? false
20
38
  }
21
39
  }
22
40
 
@@ -47,7 +65,8 @@ export class ValidationError extends BaseError {
47
65
  /**
48
66
  * Thrown by a step executor when executeStep should be retried with the given params
49
67
  * (e.g. wallet rejected 7702 upgrade → retry with atomicityNotReady).
50
- * The execution layer catches this and retries executeStep(client, step, retryParams).
68
+ * The execution layer catches this and retries executeStep(client, step, retryParams),
69
+ * unless the route was stopped or the step has an open transaction.
51
70
  */
52
71
  export class ExecuteStepRetryError extends BaseError {
53
72
  readonly retryParams: ExecuteStepRetryParams
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ export { actions } from './actions/index.js'
23
23
  export { patchContractCalls } from './actions/patchContractCalls.js'
24
24
  export { relayTransaction } from './actions/relayTransaction.js'
25
25
  export { createClient } from './client/createClient.js'
26
+ export { findProvider } from './client/findProvider.js'
26
27
  export { getActionMessage, getSubstatusMessage } from './core/actionMessages.js'
27
28
  export { BaseStepExecutionTask } from './core/BaseStepExecutionTask.js'
28
29
  export { BaseStepExecutor } from './core/BaseStepExecutor.js'
@@ -48,12 +49,25 @@ export {
48
49
  checkBalance,
49
50
  } from './core/tasks/helpers/checkBalance.js'
50
51
  export { getTransactionRequestData } from './core/tasks/helpers/getTransactionRequestData.js'
52
+ export { isKnownToStatusApi } from './core/tasks/helpers/isKnownToStatusApi.js'
51
53
  export { stepComparison } from './core/tasks/helpers/stepComparison.js'
52
54
  export { PrepareTransactionTask } from './core/tasks/PrepareTransactionTask.js'
53
55
  export { WaitForTransactionStatusTask } from './core/tasks/WaitForTransactionStatusTask.js'
56
+ export {
57
+ assertNoOpenTransaction,
58
+ CLEARED_TRANSACTION_FIELDS,
59
+ CLOCK_SKEW_MARGIN_MS,
60
+ DROPPED_FALLBACK_AGE_MS,
61
+ hasOpenTransaction,
62
+ isFinalTransactionError,
63
+ isOldEnoughToDrop,
64
+ isResendAllowed,
65
+ MAX_RESEND_AGE_MS,
66
+ } from './core/transactionState.js'
54
67
  export { BaseError } from './errors/baseError.js'
55
68
  export type { ErrorCode } from './errors/constants.js'
56
69
  export { ErrorMessage, ErrorName, LiFiErrorCode } from './errors/constants.js'
70
+ export type { TransactionErrorOptions } from './errors/errors.js'
57
71
  export {
58
72
  BalanceError,
59
73
  ExecuteStepRetryError,
package/src/types/core.ts CHANGED
@@ -91,7 +91,18 @@ export type RPCUrls = Partial<Record<ChainId, string[]>>
91
91
 
92
92
  export interface SDKProvider {
93
93
  readonly type: ChainType
94
- isAddress(address: string): boolean
94
+ /**
95
+ * The chains this provider serves. Omit it to serve every chain of `type`
96
+ * that no other provider lists.
97
+ */
98
+ readonly chainIds?: readonly ChainId[]
99
+ /**
100
+ * Validates a wallet address. With `chainId`, a provider whose chains use
101
+ * different address formats accepts only that chain's format and refuses a
102
+ * chain it does not know. Never forward `chainId` to a library function whose
103
+ * second parameter means something else.
104
+ */
105
+ isAddress(address: string, chainId?: ChainId): boolean
95
106
  /**
96
107
  * Validates a token identifier, which several ecosystems shape unlike a
97
108
  * wallet address. A provider that omits the method has no token address
@@ -115,7 +126,7 @@ export interface SDKProvider {
115
126
  export interface SDKClient {
116
127
  config: SDKBaseConfig
117
128
  providers: SDKProvider[]
118
- getProvider(type: ChainType): SDKProvider | undefined
129
+ getProvider(type: ChainType, chainId?: ChainId): SDKProvider | undefined
119
130
  setProviders(providers: SDKProvider[]): void
120
131
  setChains(chains: ExtendedChain[]): void
121
132
  getChains(): Promise<ExtendedChain[]>
@@ -159,10 +170,15 @@ export interface StepExecutor {
159
170
  allowUserInteraction: boolean
160
171
  allowExecution: boolean
161
172
  setInteraction(settings?: InteractionSettings): void
173
+ /**
174
+ * @param signal Aborts when the execution stops. Only waits that start
175
+ * after the broadcast may use it (`StepExecutorBaseContext.signal`).
176
+ */
162
177
  executeStep(
163
178
  client: SDKClient,
164
179
  step: LiFiStepExtended,
165
- retryParams?: ExecuteStepRetryParams
180
+ retryParams?: ExecuteStepRetryParams,
181
+ signal?: AbortSignal
166
182
  ): Promise<LiFiStepExtended>
167
183
  }
168
184
 
@@ -203,6 +219,18 @@ export type TransactionParameters = {
203
219
 
204
220
  export type RouteExecutionDictionary = Partial<Record<string, Promise<Route>>>
205
221
 
222
+ /**
223
+ * Called on every update of the route. It receives the SDK's working copy of
224
+ * the route: the same object on every call of one execution, which the SDK
225
+ * keeps changing after the hook returns. Copy or serialize it before you
226
+ * store it.
227
+ *
228
+ * After `stopRouteExecution` it can still be called, but only to deliver the
229
+ * transaction data (`txHash`, `txHex`, `taskId`, `txFinal`) of a task that
230
+ * was still running at the stop, for example in an open wallet prompt. Store
231
+ * that data, so a resume waits for that transaction instead of signing
232
+ * again. If you deleted the route, ignore the call.
233
+ */
206
234
  export type UpdateRouteHook = (updatedRoute: RouteExtended) => void
207
235
 
208
236
  export interface TransactionRequestParameters extends TransactionParameters {
@@ -264,6 +292,11 @@ export type GetContractCallsHook = (
264
292
 
265
293
  export interface ExecutionOptions {
266
294
  acceptExchangeRateUpdateHook?: AcceptExchangeRateUpdateHook
295
+ /**
296
+ * Receives the route on every update, and after `stopRouteExecution` the
297
+ * late transaction data of a task that was still running. See
298
+ * {@link UpdateRouteHook}.
299
+ */
267
300
  updateRouteHook?: UpdateRouteHook
268
301
  updateTransactionRequestHook?: TransactionRequestUpdateHook
269
302
  getContractCalls?: GetContractCallsHook
@@ -304,7 +337,21 @@ export type ExecutionAction = {
304
337
  txLink?: string
305
338
  taskId?: string
306
339
  txType?: TransactionMethodType
340
+ /**
341
+ * Provider-specific serialized signed transaction (hex, XDR, base64 or JSON).
342
+ * Present while the transaction may still need to be (re)sent or looked up.
343
+ * Stellar keeps it, and Bitcoin keeps it unless every node refuses its first
344
+ * send; Solana, Tron and Sui clear it when no longer needed.
345
+ */
307
346
  txHex?: string
347
+ /**
348
+ * Set together with status `FAILED` when the outcome of this action's
349
+ * transaction is known and final (failed or reverted on chain or at the
350
+ * relayer, cancelled, replaced, or dropped with proof).
351
+ * A FAILED action without this flag has an unknown outcome and is re-checked
352
+ * on resume instead of being signed again.
353
+ */
354
+ txFinal?: boolean
308
355
  // Errors occured during the action execution (within tasks)
309
356
  error?: { code: string | number; message: string; htmlMessage?: string }
310
357
  }
@@ -17,6 +17,14 @@ export interface StepExecutorBaseContext {
17
17
  step: LiFiStepExtended
18
18
  allowUserInteraction: boolean
19
19
  retryParams?: ExecuteStepRetryParams
20
+ /**
21
+ * Aborts when `stopRouteExecution` stops the execution. Give it only to a
22
+ * wait that starts after the transaction is broadcast, such as the
23
+ * `/status` poll. Never give it to a sign, send or wallet call: a stopped
24
+ * run must finish those, so its late transaction data still reaches the
25
+ * stored route and a resume does not sign again.
26
+ */
27
+ signal?: AbortSignal
20
28
  }
21
29
 
22
30
  export interface StepExecutorContext extends StepExecutorBaseContext {
@@ -1,3 +1,4 @@
1
+ import { getAbortError } from './abort.js'
1
2
  import { sleep } from './sleep.js'
2
3
 
3
4
  /**
@@ -6,14 +7,17 @@ import { sleep } from './sleep.js'
6
7
  * @param interval The timeout in milliseconds between retries, or a function that receives the current poll count and returns the interval. Defaults to 5000
7
8
  * @param maxRetries Maximum number of calls that throw before the error is rethrown, defaults to 3
8
9
  * @param shouldRetry Optional predicate to determine if an error should trigger a retry
10
+ * @param signal Optional signal that ends the wait: no call starts after it aborts, and the sleep between calls ends at once
9
11
  * @returns The result of the fn function
10
12
  * @throws The error of fn if maximum retries is reached, or if shouldRetry returns false
13
+ * @throws The abort reason of `signal` once it aborts
11
14
  */
12
15
  export const waitForResult = async <T>(
13
16
  fn: () => Promise<T | undefined>,
14
17
  interval: number | ((poll: number) => number) = 5000,
15
18
  maxRetries = 3,
16
- shouldRetry: (count: number, error: unknown) => boolean = () => true
19
+ shouldRetry: (count: number, error: unknown) => boolean = () => true,
20
+ signal?: AbortSignal
17
21
  ): Promise<T> => {
18
22
  let result: T | undefined
19
23
  let attempts = 0
@@ -22,13 +26,16 @@ export const waitForResult = async <T>(
22
26
  const getInterval = typeof interval === 'function' ? interval : () => interval
23
27
 
24
28
  while (!result) {
29
+ if (signal?.aborted) {
30
+ throw getAbortError(signal)
31
+ }
25
32
  try {
26
33
  result = await fn()
27
- if (!result) {
28
- await sleep(getInterval(polls))
29
- polls++
30
- }
31
34
  } catch (error) {
35
+ // An error of a call that the abort cut short is not a reason to retry.
36
+ if (signal?.aborted) {
37
+ throw getAbortError(signal)
38
+ }
32
39
  if (!shouldRetry(attempts, error)) {
33
40
  throw error
34
41
  }
@@ -36,7 +43,10 @@ export const waitForResult = async <T>(
36
43
  if (attempts === maxRetries) {
37
44
  throw error
38
45
  }
39
- await sleep(getInterval(polls))
46
+ }
47
+ if (!result) {
48
+ // Rejects at once, also when the signal aborted during the call.
49
+ await sleep(getInterval(polls), { signal })
40
50
  polls++
41
51
  }
42
52
  }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export const name = '@lifi/sdk'
2
- export const version = '4.10.0'
2
+ export const version = '4.11.0'