@lifi/sdk 4.9.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 (185) hide show
  1. package/CHANGELOG.md +50 -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/checkBalance.js +6 -3
  24. package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
  25. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  26. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js +20 -0
  27. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  28. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  29. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js +44 -0
  30. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  31. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  32. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js +76 -17
  33. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  34. package/dist/cjs/core/transactionState.d.ts +121 -0
  35. package/dist/cjs/core/transactionState.js +164 -0
  36. package/dist/cjs/core/transactionState.js.map +1 -0
  37. package/dist/cjs/errors/errors.d.ts +13 -2
  38. package/dist/cjs/errors/errors.js +5 -2
  39. package/dist/cjs/errors/errors.js.map +1 -1
  40. package/dist/cjs/index.d.ts +7 -3
  41. package/dist/cjs/index.js +16 -1
  42. package/dist/cjs/types/core.d.ts +49 -3
  43. package/dist/cjs/types/execution.d.ts +8 -0
  44. package/dist/cjs/utils/abort.d.ts +6 -0
  45. package/dist/cjs/utils/abort.js +10 -0
  46. package/dist/cjs/utils/abort.js.map +1 -0
  47. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  48. package/dist/cjs/utils/formatUnits.js +1 -0
  49. package/dist/cjs/utils/formatUnits.js.map +1 -1
  50. package/dist/cjs/utils/lru.d.ts +14 -0
  51. package/dist/cjs/utils/lru.js +35 -0
  52. package/dist/cjs/utils/lru.js.map +1 -0
  53. package/dist/cjs/utils/parseUnits.js +30 -16
  54. package/dist/cjs/utils/parseUnits.js.map +1 -1
  55. package/dist/cjs/utils/sleep.d.ts +7 -1
  56. package/dist/cjs/utils/sleep.js +22 -3
  57. package/dist/cjs/utils/sleep.js.map +1 -1
  58. package/dist/cjs/utils/waitForResult.d.ts +7 -5
  59. package/dist/cjs/utils/waitForResult.js +19 -14
  60. package/dist/cjs/utils/waitForResult.js.map +1 -1
  61. package/dist/cjs/utils/withDedupe.d.ts +0 -10
  62. package/dist/cjs/utils/withDedupe.js +4 -23
  63. package/dist/cjs/utils/withDedupe.js.map +1 -1
  64. package/dist/cjs/utils/withTimeout.js +6 -2
  65. package/dist/cjs/utils/withTimeout.js.map +1 -1
  66. package/dist/cjs/version.d.ts +1 -1
  67. package/dist/cjs/version.js +1 -1
  68. package/dist/cjs/version.js.map +1 -1
  69. package/dist/esm/actions/getRoutes.d.ts.map +1 -1
  70. package/dist/esm/actions/index.d.ts.map +1 -1
  71. package/dist/esm/client/createClient.d.ts.map +1 -1
  72. package/dist/esm/client/createClient.js +6 -4
  73. package/dist/esm/client/createClient.js.map +1 -1
  74. package/dist/esm/client/findProvider.d.ts +10 -0
  75. package/dist/esm/client/findProvider.d.ts.map +1 -0
  76. package/dist/esm/client/findProvider.js +10 -0
  77. package/dist/esm/client/findProvider.js.map +1 -0
  78. package/dist/esm/core/BaseStepExecutor.d.ts +1 -1
  79. package/dist/esm/core/BaseStepExecutor.d.ts.map +1 -1
  80. package/dist/esm/core/BaseStepExecutor.js +22 -10
  81. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  82. package/dist/esm/core/StatusManager.d.ts +10 -0
  83. package/dist/esm/core/StatusManager.d.ts.map +1 -1
  84. package/dist/esm/core/StatusManager.js +105 -3
  85. package/dist/esm/core/StatusManager.js.map +1 -1
  86. package/dist/esm/core/execution.d.ts.map +1 -1
  87. package/dist/esm/core/execution.js +30 -14
  88. package/dist/esm/core/execution.js.map +1 -1
  89. package/dist/esm/core/executionState.d.ts +34 -2
  90. package/dist/esm/core/executionState.d.ts.map +1 -1
  91. package/dist/esm/core/executionState.js +44 -1
  92. package/dist/esm/core/executionState.js.map +1 -1
  93. package/dist/esm/core/prepareRestart.d.ts.map +1 -1
  94. package/dist/esm/core/prepareRestart.js +14 -6
  95. package/dist/esm/core/prepareRestart.js.map +1 -1
  96. package/dist/esm/core/tasks/WaitForTransactionStatusTask.d.ts.map +1 -1
  97. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +4 -2
  98. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  99. package/dist/esm/core/tasks/helpers/checkBalance.js +6 -3
  100. package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
  101. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  102. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts.map +1 -0
  103. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js +19 -0
  104. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  105. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  106. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts.map +1 -0
  107. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js +43 -0
  108. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  109. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  110. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts.map +1 -1
  111. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js +76 -18
  112. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  113. package/dist/esm/core/transactionState.d.ts +121 -0
  114. package/dist/esm/core/transactionState.d.ts.map +1 -0
  115. package/dist/esm/core/transactionState.js +152 -0
  116. package/dist/esm/core/transactionState.js.map +1 -0
  117. package/dist/esm/errors/errors.d.ts +13 -2
  118. package/dist/esm/errors/errors.d.ts.map +1 -1
  119. package/dist/esm/errors/errors.js +5 -2
  120. package/dist/esm/errors/errors.js.map +1 -1
  121. package/dist/esm/index.d.ts +7 -3
  122. package/dist/esm/index.js +6 -2
  123. package/dist/esm/types/actions.d.ts.map +1 -1
  124. package/dist/esm/types/core.d.ts +49 -3
  125. package/dist/esm/types/core.d.ts.map +1 -1
  126. package/dist/esm/types/execution.d.ts +8 -0
  127. package/dist/esm/types/execution.d.ts.map +1 -1
  128. package/dist/esm/utils/abort.d.ts +6 -0
  129. package/dist/esm/utils/abort.d.ts.map +1 -0
  130. package/dist/esm/utils/abort.js +8 -0
  131. package/dist/esm/utils/abort.js.map +1 -0
  132. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  133. package/dist/esm/utils/formatUnits.js +1 -0
  134. package/dist/esm/utils/formatUnits.js.map +1 -1
  135. package/dist/esm/utils/lru.d.ts +14 -0
  136. package/dist/esm/utils/lru.d.ts.map +1 -0
  137. package/dist/esm/utils/lru.js +34 -0
  138. package/dist/esm/utils/lru.js.map +1 -0
  139. package/dist/esm/utils/parseUnits.js +30 -16
  140. package/dist/esm/utils/parseUnits.js.map +1 -1
  141. package/dist/esm/utils/sleep.d.ts +7 -1
  142. package/dist/esm/utils/sleep.d.ts.map +1 -1
  143. package/dist/esm/utils/sleep.js +22 -3
  144. package/dist/esm/utils/sleep.js.map +1 -1
  145. package/dist/esm/utils/waitForResult.d.ts +7 -5
  146. package/dist/esm/utils/waitForResult.d.ts.map +1 -1
  147. package/dist/esm/utils/waitForResult.js +19 -14
  148. package/dist/esm/utils/waitForResult.js.map +1 -1
  149. package/dist/esm/utils/withDedupe.d.ts +0 -10
  150. package/dist/esm/utils/withDedupe.d.ts.map +1 -1
  151. package/dist/esm/utils/withDedupe.js +5 -22
  152. package/dist/esm/utils/withDedupe.js.map +1 -1
  153. package/dist/esm/utils/withTimeout.d.ts.map +1 -1
  154. package/dist/esm/utils/withTimeout.js +6 -2
  155. package/dist/esm/utils/withTimeout.js.map +1 -1
  156. package/dist/esm/version.d.ts +1 -1
  157. package/dist/esm/version.js +1 -1
  158. package/dist/esm/version.js.map +1 -1
  159. package/package.json +2 -2
  160. package/src/client/createClient.ts +12 -4
  161. package/src/client/findProvider.ts +21 -0
  162. package/src/core/BaseStepExecutor.ts +40 -6
  163. package/src/core/StatusManager.ts +211 -2
  164. package/src/core/execution.ts +69 -20
  165. package/src/core/executionState.ts +84 -1
  166. package/src/core/prepareRestart.ts +29 -13
  167. package/src/core/tasks/WaitForTransactionStatusTask.ts +10 -1
  168. package/src/core/tasks/helpers/checkBalance.ts +11 -3
  169. package/src/core/tasks/helpers/getStepStatusRequest.ts +20 -0
  170. package/src/core/tasks/helpers/isKnownToStatusApi.ts +57 -0
  171. package/src/core/tasks/helpers/waitForTransactionStatus.ts +128 -17
  172. package/src/core/transactionState.ts +194 -0
  173. package/src/errors/errors.ts +21 -2
  174. package/src/index.ts +16 -1
  175. package/src/types/core.ts +50 -3
  176. package/src/types/execution.ts +8 -0
  177. package/src/utils/abort.ts +10 -0
  178. package/src/utils/formatUnits.ts +6 -0
  179. package/src/utils/lru.ts +38 -0
  180. package/src/utils/parseUnits.ts +53 -20
  181. package/src/utils/sleep.ts +27 -3
  182. package/src/utils/waitForResult.ts +20 -10
  183. package/src/utils/withDedupe.ts +4 -28
  184. package/src/utils/withTimeout.ts +7 -2
  185. package/src/version.ts +1 -1
@@ -75,11 +75,22 @@ export const resumeRoute = async (
75
75
  }
76
76
  }
77
77
 
78
- prepareRestart(route)
78
+ // Restart from a copy: the caller's route (e.g. an integrator's store) must
79
+ // only change through `updateRouteHook`.
80
+ const restartRoute = structuredClone<RouteExtended>(route)
81
+ prepareRestart(restartRoute)
79
82
 
80
- return executeRoute(client, route, executionOptions)
83
+ return executeRoute(client, restartRoute, executionOptions)
81
84
  }
82
85
 
86
+ /**
87
+ * True while `route` is the execution registered for its id. A stopped run
88
+ * keeps going until its step ends; it must not stop or delete a newer
89
+ * execution of the same route.
90
+ */
91
+ const ownsExecution = (route: RouteExtended): boolean =>
92
+ executionState.get(route.id)?.route === route
93
+
83
94
  const executeSteps = async (
84
95
  client: SDKClient,
85
96
  route: RouteExtended
@@ -87,8 +98,9 @@ const executeSteps = async (
87
98
  // Loop over steps and execute them
88
99
  for (let index = 0; index < route.steps.length; index++) {
89
100
  const execution = executionState.get(route.id)
90
- // Check if execution has stopped in the meantime
91
- if (!execution) {
101
+ // Check if execution has stopped in the meantime. A newer execution of the
102
+ // same route id is not ours, also when our executor ignored the stop.
103
+ if (!execution || execution.route !== route) {
92
104
  break
93
105
  }
94
106
 
@@ -129,31 +141,57 @@ const executeSteps = async (
129
141
  routeId: route.id,
130
142
  executionOptions: execution.executionOptions,
131
143
  })
132
- execution.executors.push(stepExecutor)
133
-
134
- // Check if we want to execute this step in the background
135
- if (execution.executionOptions) {
136
- updateRouteExecution(route, execution.executionOptions)
144
+ // A stop during the await did not reach this executor, and a newer
145
+ // execution of the route may run now: do not start the step.
146
+ if (!ownsExecution(route)) {
147
+ return route
137
148
  }
138
-
149
+ // In flight until the step settles, the retry included: a stop keeps
150
+ // the records a late write of this run needs (`executionState`).
151
+ executionState.retain(route.id)
152
+ // Taken from this execution, not looked up again for the retry: a
153
+ // newer execution of the route id has its own.
154
+ const { signal } = execution.abortController
139
155
  let executedStep: LiFiStepExtended
140
156
  try {
141
- executedStep = await stepExecutor.executeStep(client, step)
142
- } catch (e) {
143
- if (e instanceof ExecuteStepRetryError) {
144
- step.execution = undefined
157
+ execution.executors.push(stepExecutor)
158
+
159
+ // Check if we want to execute this step in the background
160
+ if (execution.executionOptions) {
161
+ updateRouteExecution(route, execution.executionOptions)
162
+ }
163
+
164
+ try {
145
165
  executedStep = await stepExecutor.executeStep(
146
166
  client,
147
167
  step,
148
- e.retryParams
168
+ undefined,
169
+ signal
149
170
  )
150
- } else {
151
- throw e
171
+ } catch (e) {
172
+ if (e instanceof ExecuteStepRetryError) {
173
+ // A stop ended this run while its first attempt ran: the replay
174
+ // would be new work on a stopped executor.
175
+ if (!stepExecutor.allowExecution) {
176
+ return route
177
+ }
178
+ step.execution = undefined
179
+ executedStep = await stepExecutor.executeStep(
180
+ client,
181
+ step,
182
+ e.retryParams,
183
+ signal
184
+ )
185
+ } else {
186
+ throw e
187
+ }
152
188
  }
189
+ } finally {
190
+ executionState.release(route.id)
153
191
  }
154
192
 
155
193
  // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it
156
- if (executedStep.execution?.status !== 'DONE') {
194
+ if (executedStep.execution?.status !== 'DONE' && ownsExecution(route)) {
157
195
  stopRouteExecution(route)
158
196
  }
159
197
 
@@ -162,13 +200,17 @@ const executeSteps = async (
162
200
  return route
163
201
  }
164
202
  } catch (e) {
165
- stopRouteExecution(route)
203
+ if (ownsExecution(route)) {
204
+ stopRouteExecution(route)
205
+ }
166
206
  throw e
167
207
  }
168
208
  }
169
209
 
170
210
  // Clean up after the execution
171
- executionState.delete(route.id)
211
+ if (ownsExecution(route)) {
212
+ executionState.delete(route.id)
213
+ }
172
214
  return route
173
215
  }
174
216
 
@@ -220,6 +262,13 @@ export const stopRouteExecution = (route: Route): Route => {
220
262
  })
221
263
  }
222
264
  executionState.delete(route.id)
265
+ // The abort can run before or after the two steps above: its listeners
266
+ // only clear timers, drop the shared poll and reject promises, and the
267
+ // tasks handle the rejections after this function returns. The
268
+ // `setInteraction` loop must run before `executionState.delete`, because
269
+ // `StatusManager.allowUpdates(false)` keeps the route and hook from the
270
+ // execution state.
271
+ execution.abortController.abort()
223
272
  return execution.route
224
273
  }
225
274
 
@@ -2,6 +2,7 @@ import type {
2
2
  ExecutionOptions,
3
3
  RouteExtended,
4
4
  StepExecutor,
5
+ UpdateRouteHook,
5
6
  } from '../types/core.js'
6
7
 
7
8
  interface ExecutionData {
@@ -9,28 +10,74 @@ interface ExecutionData {
9
10
  executors: StepExecutor[]
10
11
  executionOptions?: ExecutionOptions
11
12
  promise?: Promise<RouteExtended>
13
+ /**
14
+ * One per execution: `stopRouteExecution` aborts it, so the waits of the
15
+ * stopped run that take its signal end.
16
+ */
17
+ abortController: AbortController
12
18
  }
13
19
 
14
- type ExecutionStateParams = Omit<ExecutionData, 'executors'>
20
+ type ExecutionStateParams = Omit<ExecutionData, 'executors' | 'abortController'>
21
+
22
+ /** The route and hook of an execution that ended (stopped or finished). */
23
+ interface EndedExecution {
24
+ route: RouteExtended
25
+ updateRouteHook?: UpdateRouteHook
26
+ }
15
27
 
16
28
  interface ExecutionState {
17
29
  state: Partial<Record<string, ExecutionData>>
30
+ /**
31
+ * The start number of the last execution per route id. Survives `delete`
32
+ * while a run of the route is in flight, so a stopped run can tell whether
33
+ * a newer execution of its route started since its stop.
34
+ */
35
+ starts: Partial<Record<string, number>>
36
+ /**
37
+ * The last ended execution per route id. Kept only while a run of the
38
+ * route is in flight, so a late write of a stopped run can reach the route
39
+ * of a newer execution that ended.
40
+ */
41
+ ended: Partial<Record<string, EndedExecution>>
42
+ /** Runs per route id inside a step (`retain` to `release`). */
43
+ inFlight: Partial<Record<string, number>>
18
44
  get(routeId: string): ExecutionData | undefined
19
45
  create(params: ExecutionStateParams): ExecutionData
20
46
  update(params: ExecutionStateParams): void
21
47
  delete(routeId: string): void
48
+ retain(routeId: string): void
49
+ release(routeId: string): void
50
+ /**
51
+ * The start number of the last execution of the route id, or 0 when the
52
+ * route has no records. A new start always gets a higher number.
53
+ */
54
+ startCount(routeId: string): number
55
+ lastEnded(routeId: string): EndedExecution | undefined
22
56
  }
23
57
 
58
+ /**
59
+ * The last start number given to any route id. A number is never given
60
+ * twice, so a route id whose records were freed and that started again never
61
+ * shows the number a stopped run took at its stop.
62
+ */
63
+ let lastStart = 0
64
+
24
65
  export const executionState: ExecutionState = {
25
66
  state: {},
67
+ starts: {},
68
+ ended: {},
69
+ inFlight: {},
26
70
  get(routeId: string) {
27
71
  return this.state[routeId]
28
72
  },
29
73
  create(params) {
74
+ lastStart += 1
75
+ this.starts[params.route.id] = lastStart
30
76
  this.state[params.route.id] = {
31
77
  ...this.state[params.route.id],
32
78
  ...params,
33
79
  executors: this.state[params.route.id]?.executors ?? [],
80
+ abortController: new AbortController(),
34
81
  }
35
82
  return this.state[params.route.id]!
36
83
  },
@@ -43,6 +90,42 @@ export const executionState: ExecutionState = {
43
90
  }
44
91
  },
45
92
  delete(routeId) {
93
+ const data = this.state[routeId]
46
94
  delete this.state[routeId]
95
+ // No run of the route is in flight, so no stopped run can write late:
96
+ // nothing is kept. (A normal finish releases its run before its delete.)
97
+ if (!this.inFlight[routeId]) {
98
+ delete this.starts[routeId]
99
+ delete this.ended[routeId]
100
+ return
101
+ }
102
+ if (data) {
103
+ this.ended[routeId] = {
104
+ route: data.route,
105
+ updateRouteHook: data.executionOptions?.updateRouteHook,
106
+ }
107
+ }
108
+ },
109
+ retain(routeId) {
110
+ this.inFlight[routeId] = (this.inFlight[routeId] ?? 0) + 1
111
+ },
112
+ release(routeId) {
113
+ const count = (this.inFlight[routeId] ?? 0) - 1
114
+ if (count > 0) {
115
+ this.inFlight[routeId] = count
116
+ return
117
+ }
118
+ delete this.inFlight[routeId]
119
+ // A running execution keeps its records until its own `delete`.
120
+ if (!this.state[routeId]) {
121
+ delete this.starts[routeId]
122
+ delete this.ended[routeId]
123
+ }
124
+ },
125
+ startCount(routeId: string): number {
126
+ return this.starts[routeId] ?? 0
127
+ },
128
+ lastEnded(routeId: string): EndedExecution | undefined {
129
+ return this.ended[routeId]
47
130
  },
48
131
  }
@@ -1,25 +1,41 @@
1
- import type { RouteExtended } from '../types/core.js'
1
+ import type { ExecutionActionType, RouteExtended } from '../types/core.js'
2
+ import { getActionMessage } from './actionMessages.js'
3
+ import { hasOpenTransaction } from './transactionState.js'
4
+
5
+ const RESTART_ACTION_TYPES: readonly ExecutionActionType[] = [
6
+ 'SWAP',
7
+ 'CROSS_CHAIN',
8
+ 'RECEIVING_CHAIN',
9
+ ]
2
10
 
3
11
  export const prepareRestart = (route: RouteExtended): void => {
4
12
  for (let index = 0; index < route.steps.length; index++) {
5
13
  const step = route.steps[index]
6
14
  if (step.execution) {
7
- // Find the index of the last action that has tx hash, taskId, or signed messages
8
- const lastValidIndex = step.execution.actions.findLastIndex(
15
+ // Keep everything up to the last action whose transaction may still
16
+ // land. A FAILED action without `txFinal` has an unknown outcome: it is
17
+ // kept and re-checked on chain instead of being signed again. A FAILED
18
+ // action with `txFinal` is dropped, so the restart signs a new one.
19
+ const lastOpenIndex = step.execution.actions.findLastIndex(
9
20
  (action) =>
10
- ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&
11
- (!!action.txHash || !!action.taskId) &&
12
- action.status !== 'FAILED'
21
+ RESTART_ACTION_TYPES.includes(action.type) &&
22
+ hasOpenTransaction(action)
13
23
  )
14
24
 
15
- // Keep all actions up to the one with tx hash
16
- if (lastValidIndex >= 0) {
17
- step.execution.actions = step.execution.actions.slice(
18
- 0,
19
- lastValidIndex + 1
20
- )
25
+ if (lastOpenIndex >= 0) {
26
+ step.execution.actions = step.execution.actions
27
+ .slice(0, lastOpenIndex + 1)
28
+ .map((action) =>
29
+ action.status === 'FAILED' && hasOpenTransaction(action)
30
+ ? {
31
+ ...action,
32
+ status: 'PENDING',
33
+ message: getActionMessage(action.type, 'PENDING'),
34
+ error: undefined,
35
+ }
36
+ : action
37
+ )
21
38
  } else {
22
- // If no tx hash exists, reset the actions array
23
39
  step.execution.actions = []
24
40
  }
25
41
  }
@@ -3,6 +3,7 @@ import { LiFiErrorCode } from '../../errors/constants.js'
3
3
  import { TransactionError } from '../../errors/errors.js'
4
4
  import type { ExecutionActionType } from '../../types/core.js'
5
5
  import type { StepExecutorContext, TaskResult } from '../../types/execution.js'
6
+ import { isAbortError } from '../../utils/abort.js'
6
7
  import { getTransactionFailedMessage } from '../../utils/getTransactionMessage.js'
7
8
  import { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'
8
9
  import { waitForTransactionStatus } from './helpers/waitForTransactionStatus.js'
@@ -23,6 +24,7 @@ export class WaitForTransactionStatusTask extends BaseStepExecutionTask {
23
24
  pollingIntervalMs,
24
25
  toChain,
25
26
  isBridgeExecution,
27
+ signal,
26
28
  } = context
27
29
 
28
30
  // At this point, we should have a txHash or taskId
@@ -56,7 +58,8 @@ export class WaitForTransactionStatusTask extends BaseStepExecutionTask {
56
58
  transactionHash,
57
59
  step,
58
60
  action.type,
59
- pollingIntervalMs
61
+ pollingIntervalMs,
62
+ signal
60
63
  )) as FullStatusData
61
64
 
62
65
  const statusReceiving =
@@ -98,6 +101,12 @@ export class WaitForTransactionStatusTask extends BaseStepExecutionTask {
98
101
 
99
102
  return { status: 'COMPLETED' }
100
103
  } catch (e: any) {
104
+ // `stopRouteExecution` ended the wait; the outcome of the transaction is
105
+ // still unknown. Pause like a stopped step, with no write: the stored
106
+ // action keeps its hash, and a resume waits for it again.
107
+ if (signal?.aborted && isAbortError(e)) {
108
+ return { status: 'PAUSED' }
109
+ }
101
110
  const htmlMessage = await getTransactionFailedMessage(
102
111
  client,
103
112
  step,
@@ -118,6 +118,11 @@ export const checkBalance = async (
118
118
  Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))
119
119
  )
120
120
 
121
+ // Aborted once `withTimeout` settles. A timeout rejects at once, but the
122
+ // loop keeps running; the signal stops it before it can change `step`.
123
+ const controller = new AbortController()
124
+ const { signal } = controller
125
+
121
126
  await withTimeout(
122
127
  async () => {
123
128
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
@@ -133,9 +138,12 @@ export const checkBalance = async (
133
138
  error as Error
134
139
  )
135
140
  }
136
- await sleep(BACKOFF_BASE_MS * 2 ** attempt)
141
+ await sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal })
137
142
  continue
138
143
  }
144
+ if (signal.aborted) {
145
+ return
146
+ }
139
147
 
140
148
  const balanceByAddress = new Map(
141
149
  balances.map((b) => [b.address.toLowerCase(), b.amount] as const)
@@ -207,12 +215,12 @@ export const checkBalance = async (
207
215
  )
208
216
  }
209
217
 
210
- await sleep(BACKOFF_BASE_MS * 2 ** attempt)
218
+ await sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal })
211
219
  }
212
220
  },
213
221
  {
214
222
  timeout: OVERALL_TIMEOUT_MS,
215
223
  errorInstance: new BalanceError('Could not read wallet balance.'),
216
224
  }
217
- )
225
+ ).finally(() => controller.abort())
218
226
  }
@@ -0,0 +1,20 @@
1
+ import type { LiFiStep } from '@lifi/types'
2
+ import type { GetStatusRequestExtended } from '../../../types/actions.js'
3
+
4
+ /**
5
+ * The status request for a transaction of a step. The status poll and the
6
+ * status-API veto send the same fields, so both build them here.
7
+ */
8
+ export function getStepStatusRequest(
9
+ step: LiFiStep,
10
+ txHash: string
11
+ ): GetStatusRequestExtended {
12
+ return {
13
+ fromChain: step.action.fromChainId,
14
+ fromAddress: step.action.fromAddress,
15
+ toChain: step.action.toChainId,
16
+ txHash,
17
+ ...(step.tool !== 'custom' && { bridge: step.tool }),
18
+ ...(step.transactionId && { transactionId: step.transactionId }),
19
+ }
20
+ }
@@ -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
+ }