@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
@@ -5,9 +5,17 @@ import type {
5
5
  ExecutionActionStatus,
6
6
  ExecutionActionType,
7
7
  LiFiStepExtended,
8
+ RouteExtended,
9
+ UpdateRouteHook,
8
10
  } from '../types/core.js'
9
11
  import { getActionMessage } from './actionMessages.js'
10
12
  import { executionState } from './executionState.js'
13
+ import {
14
+ CLEARED_TRANSACTION_FIELDS,
15
+ hasOpenTransaction,
16
+ hasStepOpenTransaction,
17
+ TRANSACTION_ACTION_TYPES,
18
+ } from './transactionState.js'
11
19
 
12
20
  type ActionProps = {
13
21
  step: LiFiStepExtended
@@ -16,12 +24,113 @@ type ActionProps = {
16
24
  status: ExecutionActionStatus
17
25
  }
18
26
 
27
+ /**
28
+ * The route and hook of an execution that `stopRouteExecution` ended. A task
29
+ * that was still running (e.g. waiting in the wallet prompt) writes its
30
+ * transaction data later; without these the write would never reach the
31
+ * integrator, and a resume of the stored route would sign again.
32
+ * `startCount` is `executionState.startCount` at the stop.
33
+ */
34
+ type StoppedExecution = {
35
+ route: RouteExtended
36
+ updateRouteHook?: UpdateRouteHook
37
+ startCount: number
38
+ }
39
+
40
+ /**
41
+ * A write is transaction data when it changes one of these fields. `txLink`
42
+ * and `signedAt` travel with such a write but never trigger one: the status
43
+ * poll rewrites `txLink` every few seconds.
44
+ */
45
+ const TRANSACTION_KEYS = ['txHash', 'txHex', 'taskId', 'txFinal'] as const
46
+
47
+ type TransactionFields = Pick<
48
+ ExecutionAction,
49
+ (typeof TRANSACTION_KEYS)[number]
50
+ >
51
+
52
+ const readTransaction = (action: ExecutionAction): TransactionFields => ({
53
+ txHash: action.txHash,
54
+ txHex: action.txHex,
55
+ taskId: action.taskId,
56
+ txFinal: action.txFinal,
57
+ })
58
+
59
+ /** True when the write changed a transaction field, also to `undefined`. */
60
+ const changesTransaction = (
61
+ before: TransactionFields,
62
+ action: ExecutionAction
63
+ ): boolean => TRANSACTION_KEYS.some((key) => action[key] !== before[key])
64
+
65
+ /**
66
+ * Copies a late transaction into the route of a newer execution of the same
67
+ * route id, running or ended. The step's objects are changed in place: a
68
+ * running executor holds them, so its selector and its pre-sign guard see
69
+ * the transaction. Returns true when something changed.
70
+ */
71
+ const mergeLateTransaction = (
72
+ liveRoute: RouteExtended,
73
+ lateStep: LiFiStepExtended,
74
+ lateAction: ExecutionAction
75
+ ): boolean => {
76
+ // Cleared or final: the newer execution needs nothing from it.
77
+ if (!hasOpenTransaction(lateAction)) {
78
+ return false
79
+ }
80
+ const liveStep = liveRoute.steps.find(
81
+ (routeStep) => routeStep.id === lateStep.id
82
+ )
83
+ if (!liveStep) {
84
+ return false
85
+ }
86
+ if (!liveStep.execution) {
87
+ liveStep.execution = {
88
+ startedAt: Date.now(),
89
+ status: 'PENDING',
90
+ actions: [structuredClone(lateAction)],
91
+ }
92
+ } else {
93
+ const liveAction = liveStep.execution.actions.find(
94
+ (action) => action.type === lateAction.type
95
+ )
96
+ if (!liveAction) {
97
+ liveStep.execution.actions.push(structuredClone(lateAction))
98
+ } else if (hasOpenTransaction(liveAction)) {
99
+ // The live action already has an open transaction (its own, or one
100
+ // merged earlier); it is kept.
101
+ return false
102
+ } else {
103
+ // All five fields, so a stale `txFinal` goes and the action is open.
104
+ // `txType` goes with them: the live one described no open transaction.
105
+ Object.assign(liveAction, {
106
+ txHash: lateAction.txHash,
107
+ txLink: lateAction.txLink,
108
+ txHex: lateAction.txHex,
109
+ txFinal: lateAction.txFinal,
110
+ taskId: lateAction.taskId,
111
+ txType: lateAction.txType,
112
+ })
113
+ }
114
+ }
115
+ // `signedAt` is the signing time of the step's own transaction: an
116
+ // allowance does not set it, and a write without one keeps the live time.
117
+ const signedAt = lateStep.execution?.signedAt
118
+ if (
119
+ TRANSACTION_ACTION_TYPES.includes(lateAction.type) &&
120
+ signedAt !== undefined
121
+ ) {
122
+ liveStep.execution.signedAt = signedAt
123
+ }
124
+ return true
125
+ }
126
+
19
127
  /**
20
128
  * Manages status updates of a route and provides various functions for tracking actions.
21
129
  */
22
130
  export class StatusManager {
23
131
  private readonly routeId: string
24
132
  private shouldUpdate = true
133
+ private stoppedExecution?: StoppedExecution
25
134
 
26
135
  constructor(routeId: string) {
27
136
  this.routeId = routeId
@@ -46,7 +155,12 @@ export class StatusManager {
46
155
  if (step.execution.status === 'FAILED') {
47
156
  step.execution.startedAt = Date.now()
48
157
  step.execution.status = 'PENDING'
49
- step.execution.signedAt = undefined
158
+ // Keep the signing time while a signed transaction may still land: the
159
+ // resume path uses it to decide when stored bytes are too old to resend
160
+ // or old enough to be declared dropped.
161
+ if (!hasStepOpenTransaction(step)) {
162
+ step.execution.signedAt = undefined
163
+ }
50
164
  step.execution.error = undefined
51
165
  this.updateStepInRoute(step)
52
166
  }
@@ -144,6 +258,12 @@ export class StatusManager {
144
258
  if (action) {
145
259
  return this.updateAction(step, type, status, {
146
260
  error: undefined,
261
+ // A final outcome is dead. A new attempt starts without its data, so
262
+ // the pre-sign guard does not mistake it for an open transaction (the
263
+ // route was run again without `prepareRestart`, e.g. `executeRoute`).
264
+ ...(action.status === 'FAILED' &&
265
+ action.txFinal === true &&
266
+ CLEARED_TRANSACTION_FIELDS),
147
267
  })
148
268
  }
149
269
 
@@ -172,6 +292,11 @@ export class StatusManager {
172
292
  if (!currentAction) {
173
293
  throw new Error("Can't find an action for the given type.")
174
294
  }
295
+ // Read before the write: after a stop, only a write that changes the
296
+ // transaction reaches the integrator.
297
+ const transactionBefore = this.shouldUpdate
298
+ ? undefined
299
+ : readTransaction(currentAction)
175
300
 
176
301
  switch (status) {
177
302
  case 'CANCELLED':
@@ -211,7 +336,14 @@ export class StatusManager {
211
336
  ...step.execution.actions.filter((action) => action.status === 'DONE'),
212
337
  ...step.execution.actions.filter((action) => action.status !== 'DONE'),
213
338
  ]
214
- this.updateStepInRoute(step) // updates the step in the route
339
+ if (
340
+ transactionBefore &&
341
+ changesTransaction(transactionBefore, currentAction)
342
+ ) {
343
+ this.deliverLateTransactionData(step, currentAction)
344
+ } else {
345
+ this.updateStepInRoute(step) // updates the step in the route
346
+ }
215
347
  return currentAction
216
348
  }
217
349
 
@@ -233,6 +365,11 @@ export class StatusManager {
233
365
  throw new Error("Couldn't find a step to update.")
234
366
  }
235
367
 
368
+ // A shallow copy on purpose: the route's step must keep sharing the
369
+ // step's `execution` object. `mergeLateTransaction` changes the live
370
+ // route in place, and the running sign task's check after the wallet
371
+ // must see the merge (pinned by the stop-and-resume race test in
372
+ // `sdk-provider-ethereum/src/core/flows/reload.unit.spec.ts`).
236
373
  data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }
237
374
 
238
375
  data.executionOptions?.updateRouteHook?.(data.route)
@@ -241,5 +378,77 @@ export class StatusManager {
241
378
 
242
379
  allowUpdates(value: boolean): void {
243
380
  this.shouldUpdate = value
381
+ if (value) {
382
+ this.stoppedExecution = undefined
383
+ return
384
+ }
385
+ // `stopRouteExecution` turns updates off right before it deletes the
386
+ // execution state, so the state is still here to keep.
387
+ const data = executionState.get(this.routeId)
388
+ if (data) {
389
+ this.stoppedExecution = {
390
+ route: data.route,
391
+ updateRouteHook: data.executionOptions?.updateRouteHook,
392
+ startCount: executionState.startCount(this.routeId),
393
+ }
394
+ }
395
+ }
396
+
397
+ /**
398
+ * A write of transaction data after `stopRouteExecution`. With a newer
399
+ * execution of the same route id running, the transaction is merged into
400
+ * it. If no execution of the route started since the stop, the kept route
401
+ * is updated and the kept hook is called. If a newer execution started and
402
+ * ended since the stop, the transaction is merged into the route of the
403
+ * last ended execution, and its hook is called.
404
+ */
405
+ private deliverLateTransactionData(
406
+ step: LiFiStepExtended,
407
+ lateAction: ExecutionAction
408
+ ): void {
409
+ const stopped = this.stoppedExecution
410
+ if (!stopped) {
411
+ return
412
+ }
413
+ // A late write must never fail the task that made it: its catch block
414
+ // would mark the action FAILED while the transaction may still land.
415
+ try {
416
+ // Always a newer execution: `stopRouteExecution` deleted this one.
417
+ const live = executionState.get(this.routeId)
418
+ if (live) {
419
+ if (mergeLateTransaction(live.route, step, lateAction)) {
420
+ live.executionOptions?.updateRouteHook?.(live.route)
421
+ }
422
+ return
423
+ }
424
+ // A newer execution started and ended since the stop: the integrator
425
+ // stored its route, which the kept one would roll back. The late
426
+ // transaction goes into that route instead. With the records of the
427
+ // route freed (no run in flight, `startCount` 0) the write is dropped.
428
+ if (executionState.startCount(this.routeId) !== stopped.startCount) {
429
+ const ended = executionState.lastEnded(this.routeId)
430
+ if (ended && mergeLateTransaction(ended.route, step, lateAction)) {
431
+ ended.updateRouteHook?.(ended.route)
432
+ }
433
+ return
434
+ }
435
+ const stepIndex = stopped.route.steps.findIndex(
436
+ (routeStep) => routeStep.id === step.id
437
+ )
438
+ if (stepIndex === -1) {
439
+ return
440
+ }
441
+ stopped.route.steps[stepIndex] = {
442
+ ...stopped.route.steps[stepIndex],
443
+ ...step,
444
+ }
445
+ stopped.updateRouteHook?.(stopped.route)
446
+ } catch (error) {
447
+ // Not rethrown, see above. The integrator's hook can throw here, so
448
+ // the error is reported in development, as other swallowed errors are.
449
+ if (process.env.NODE_ENV === 'development') {
450
+ console.debug('Delivering late transaction data failed.', error)
451
+ }
452
+ }
244
453
  }
245
454
  }
@@ -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,
@@ -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
+ }