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