@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
@@ -1 +1 @@
1
- {"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["/**\n * Map with a LRU (Least recently used) policy.\n *\n * https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override set(key: string, value: value): this {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value!)\n }\n return this\n }\n}\n\ntype Caller = {\n resolve: (value: any) => void\n reject: (error: unknown) => void\n}\n\ntype InFlight = {\n promise: Promise<any>\n /** Absent when the first caller had no signal: then nothing can abort it. */\n controller?: AbortController | undefined\n /** Callers with a signal that are still waiting, once the first one joins. */\n callers?: Set<Caller> | undefined\n /** A caller without a signal joined, so the request must run to the end. */\n pinned: boolean\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<InFlight>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n /** Lets this caller leave a shared request without aborting it for others. */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Deduplicates in-flight promises.\n *\n * When the first caller passes a signal, `fn` receives the signal to hand on\n * to its request. A caller that aborts leaves the shared request at once; the\n * request itself is aborted only when every caller has aborted. The next\n * caller then starts a new request, so `fn` should pass the signal on: a run\n * that ignores it keeps going alongside the new one.\n */\nexport function withDedupe<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: WithDedupeOptions\n): Promise<T>\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n options: WithDedupeOptions & { signal?: undefined }\n): Promise<T>\nexport function withDedupe<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n { enabled = true, id, signal }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn(signal)\n }\n if (signal?.aborted) {\n return Promise.reject(abortReason(signal))\n }\n let inFlight = promiseCache.get(id)\n if (!inFlight) {\n const controller = signal ? new AbortController() : undefined\n const promise = fn(controller?.signal).finally(() => evict(id, promise))\n inFlight = { promise, controller, pinned: false }\n promiseCache.set(id, inFlight)\n }\n return join<T>(id, inFlight, signal)\n}\n\nfunction join<T>(\n id: string,\n inFlight: InFlight,\n signal: AbortSignal | undefined\n): Promise<T> {\n if (!signal) {\n inFlight.pinned = true\n return inFlight.promise\n }\n const callers = inFlight.callers ?? subscribe(inFlight)\n return new Promise<T>((resolve, reject) => {\n // Stop listening before settling, so a later abort cannot reach the request.\n const caller: Caller = {\n resolve: (value) => {\n signal.removeEventListener('abort', leave)\n resolve(value)\n },\n reject: (error) => {\n signal.removeEventListener('abort', leave)\n reject(error)\n },\n }\n const leave = () => {\n // `leave` can run without the event, so the listener is not always gone.\n signal.removeEventListener('abort', leave)\n callers.delete(caller)\n const reason = abortReason(signal)\n reject(reason)\n if (!inFlight.pinned && callers.size === 0) {\n // A caller arriving now must start a new request, not join this one.\n evict(id, inFlight.promise)\n inFlight.controller?.abort(reason)\n }\n }\n callers.add(caller)\n signal.addEventListener('abort', leave, { once: true })\n // `fn` runs before this listener exists and may have aborted the signal.\n if (signal.aborted) {\n leave()\n }\n })\n}\n\n/**\n * Hands the result to the callers with a signal, through one reaction per\n * request, so a caller that leaves holds nothing here. It is added only when\n * the first such caller joins: a request shared only by callers without a\n * signal gets no handler of ours, and a failure they all ignore is still\n * reported as an unhandled rejection.\n */\nfunction subscribe(inFlight: InFlight): Set<Caller> {\n const callers = new Set<Caller>()\n inFlight.callers = callers\n inFlight.promise.then(\n (value) => {\n for (const caller of callers) {\n caller.resolve(value)\n }\n },\n (error) => {\n for (const caller of callers) {\n caller.reject(error)\n }\n }\n )\n return callers\n}\n\n/** Drops the entry for `id` only while it still holds this request. */\nfunction evict(id: string, promise: Promise<unknown>): void {\n if (promiseCache.get(id)?.promise === promise) {\n promiseCache.delete(id)\n }\n}\n\n/** Older runtimes and polyfills can abort a signal without a `reason`. */\nconst abortReason = (signal: AbortSignal): unknown =>\n signal.reason ??\n Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })\n"],"mappings":";;;;;;AAKA,IAAa,SAAb,cAA6C,IAAmB;CAC9D;CAEA,YAAY,MAAc;EACxB,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,IAAa,KAAa,OAAoB;EAC5C,MAAM,IAAI,KAAK,KAAK;EACpB,IAAI,KAAK,WAAW,KAAK,OAAO,KAAK,SACnC,KAAK,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;EAEvC,OAAO;CACT;AACF;;AAkBA,MAAM,6BAA6B,IAAI,OAAiB,IAAI;AA0B5D,SAAgB,WACd,IACA,EAAE,UAAU,MAAM,IAAI,UACV;CACZ,IAAI,CAAC,WAAW,CAAC,IACf,OAAO,GAAG,MAAM;CAElB,IAAI,QAAQ,SACV,OAAO,QAAQ,OAAO,YAAY,MAAM,CAAC;CAE3C,IAAI,WAAW,aAAa,IAAI,EAAE;CAClC,IAAI,CAAC,UAAU;EACb,MAAM,aAAa,SAAS,IAAI,gBAAgB,IAAI,KAAA;EACpD,MAAM,UAAU,GAAG,YAAY,MAAM,CAAC,CAAC,cAAc,MAAM,IAAI,OAAO,CAAC;EACvE,WAAW;GAAE;GAAS;GAAY,QAAQ;EAAM;EAChD,aAAa,IAAI,IAAI,QAAQ;CAC/B;CACA,OAAO,KAAQ,IAAI,UAAU,MAAM;AACrC;AAEA,SAAS,KACP,IACA,UACA,QACY;CACZ,IAAI,CAAC,QAAQ;EACX,SAAS,SAAS;EAClB,OAAO,SAAS;CAClB;CACA,MAAM,UAAU,SAAS,WAAW,UAAU,QAAQ;CACtD,OAAO,IAAI,SAAY,SAAS,WAAW;EAEzC,MAAM,SAAiB;GACrB,UAAU,UAAU;IAClB,OAAO,oBAAoB,SAAS,KAAK;IACzC,QAAQ,KAAK;GACf;GACA,SAAS,UAAU;IACjB,OAAO,oBAAoB,SAAS,KAAK;IACzC,OAAO,KAAK;GACd;EACF;EACA,MAAM,cAAc;GAElB,OAAO,oBAAoB,SAAS,KAAK;GACzC,QAAQ,OAAO,MAAM;GACrB,MAAM,SAAS,YAAY,MAAM;GACjC,OAAO,MAAM;GACb,IAAI,CAAC,SAAS,UAAU,QAAQ,SAAS,GAAG;IAE1C,MAAM,IAAI,SAAS,OAAO;IAC1B,SAAS,YAAY,MAAM,MAAM;GACnC;EACF;EACA,QAAQ,IAAI,MAAM;EAClB,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EAEtD,IAAI,OAAO,SACT,MAAM;CAEV,CAAC;AACH;;;;;;;;AASA,SAAS,UAAU,UAAiC;CAClD,MAAM,0BAAU,IAAI,IAAY;CAChC,SAAS,UAAU;CACnB,SAAS,QAAQ,MACd,UAAU;EACT,KAAK,MAAM,UAAU,SACnB,OAAO,QAAQ,KAAK;CAExB,IACC,UAAU;EACT,KAAK,MAAM,UAAU,SACnB,OAAO,OAAO,KAAK;CAEvB,CACF;CACA,OAAO;AACT;;AAGA,SAAS,MAAM,IAAY,SAAiC;CAC1D,IAAI,aAAa,IAAI,EAAE,CAAC,EAAE,YAAY,SACpC,aAAa,OAAO,EAAE;AAE1B;;AAGA,MAAM,eAAe,WACnB,OAAO,UACP,OAAO,uBAAO,IAAI,MAAM,4BAA4B,GAAG,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["import { getAbortError } from './abort.js'\nimport { LruMap } from './lru.js'\n\ntype Caller = {\n resolve: (value: any) => void\n reject: (error: unknown) => void\n}\n\ntype InFlight = {\n promise: Promise<any>\n /** Absent when the first caller had no signal: then nothing can abort it. */\n controller?: AbortController | undefined\n /** Callers with a signal that are still waiting, once the first one joins. */\n callers?: Set<Caller> | undefined\n /** A caller without a signal joined, so the request must run to the end. */\n pinned: boolean\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<InFlight>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n /** Lets this caller leave a shared request without aborting it for others. */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Deduplicates in-flight promises.\n *\n * When the first caller passes a signal, `fn` receives the signal to hand on\n * to its request. A caller that aborts leaves the shared request at once; the\n * request itself is aborted only when every caller has aborted. The next\n * caller then starts a new request, so `fn` should pass the signal on: a run\n * that ignores it keeps going alongside the new one.\n */\nexport function withDedupe<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: WithDedupeOptions\n): Promise<T>\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n options: WithDedupeOptions & { signal?: undefined }\n): Promise<T>\nexport function withDedupe<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n { enabled = true, id, signal }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn(signal)\n }\n if (signal?.aborted) {\n return Promise.reject(getAbortError(signal))\n }\n let inFlight = promiseCache.get(id)\n if (!inFlight) {\n const controller = signal ? new AbortController() : undefined\n const promise = fn(controller?.signal).finally(() => evict(id, promise))\n inFlight = { promise, controller, pinned: false }\n promiseCache.set(id, inFlight)\n }\n return join<T>(id, inFlight, signal)\n}\n\nfunction join<T>(\n id: string,\n inFlight: InFlight,\n signal: AbortSignal | undefined\n): Promise<T> {\n if (!signal) {\n inFlight.pinned = true\n return inFlight.promise\n }\n const callers = inFlight.callers ?? subscribe(inFlight)\n return new Promise<T>((resolve, reject) => {\n // Stop listening before settling, so a later abort cannot reach the request.\n const caller: Caller = {\n resolve: (value) => {\n signal.removeEventListener('abort', leave)\n resolve(value)\n },\n reject: (error) => {\n signal.removeEventListener('abort', leave)\n reject(error)\n },\n }\n const leave = () => {\n // `leave` can run without the event, so the listener is not always gone.\n signal.removeEventListener('abort', leave)\n callers.delete(caller)\n const reason = getAbortError(signal)\n reject(reason)\n if (!inFlight.pinned && callers.size === 0) {\n // A caller arriving now must start a new request, not join this one.\n evict(id, inFlight.promise)\n inFlight.controller?.abort(reason)\n }\n }\n callers.add(caller)\n signal.addEventListener('abort', leave, { once: true })\n // `fn` runs before this listener exists and may have aborted the signal.\n if (signal.aborted) {\n leave()\n }\n })\n}\n\n/**\n * Hands the result to the callers with a signal, through one reaction per\n * request, so a caller that leaves holds nothing here. It is added only when\n * the first such caller joins: a request shared only by callers without a\n * signal gets no handler of ours, and a failure they all ignore is still\n * reported as an unhandled rejection.\n */\nfunction subscribe(inFlight: InFlight): Set<Caller> {\n const callers = new Set<Caller>()\n inFlight.callers = callers\n inFlight.promise.then(\n (value) => {\n for (const caller of callers) {\n caller.resolve(value)\n }\n },\n (error) => {\n for (const caller of callers) {\n caller.reject(error)\n }\n }\n )\n return callers\n}\n\n/** Drops the entry for `id` only while it still holds this request. */\nfunction evict(id: string, promise: Promise<unknown>): void {\n if (promiseCache.get(id)?.promise === promise) {\n promiseCache.delete(id)\n }\n}\n"],"mappings":";;;;AAmBA,MAAM,6BAA6B,IAAI,OAAiB,IAAI;AA0B5D,SAAgB,WACd,IACA,EAAE,UAAU,MAAM,IAAI,UACV;CACZ,IAAI,CAAC,WAAW,CAAC,IACf,OAAO,GAAG,MAAM;CAElB,IAAI,QAAQ,SACV,OAAO,QAAQ,OAAO,cAAc,MAAM,CAAC;CAE7C,IAAI,WAAW,aAAa,IAAI,EAAE;CAClC,IAAI,CAAC,UAAU;EACb,MAAM,aAAa,SAAS,IAAI,gBAAgB,IAAI,KAAA;EACpD,MAAM,UAAU,GAAG,YAAY,MAAM,CAAC,CAAC,cAAc,MAAM,IAAI,OAAO,CAAC;EACvE,WAAW;GAAE;GAAS;GAAY,QAAQ;EAAM;EAChD,aAAa,IAAI,IAAI,QAAQ;CAC/B;CACA,OAAO,KAAQ,IAAI,UAAU,MAAM;AACrC;AAEA,SAAS,KACP,IACA,UACA,QACY;CACZ,IAAI,CAAC,QAAQ;EACX,SAAS,SAAS;EAClB,OAAO,SAAS;CAClB;CACA,MAAM,UAAU,SAAS,WAAW,UAAU,QAAQ;CACtD,OAAO,IAAI,SAAY,SAAS,WAAW;EAEzC,MAAM,SAAiB;GACrB,UAAU,UAAU;IAClB,OAAO,oBAAoB,SAAS,KAAK;IACzC,QAAQ,KAAK;GACf;GACA,SAAS,UAAU;IACjB,OAAO,oBAAoB,SAAS,KAAK;IACzC,OAAO,KAAK;GACd;EACF;EACA,MAAM,cAAc;GAElB,OAAO,oBAAoB,SAAS,KAAK;GACzC,QAAQ,OAAO,MAAM;GACrB,MAAM,SAAS,cAAc,MAAM;GACnC,OAAO,MAAM;GACb,IAAI,CAAC,SAAS,UAAU,QAAQ,SAAS,GAAG;IAE1C,MAAM,IAAI,SAAS,OAAO;IAC1B,SAAS,YAAY,MAAM,MAAM;GACnC;EACF;EACA,QAAQ,IAAI,MAAM;EAClB,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EAEtD,IAAI,OAAO,SACT,MAAM;CAEV,CAAC;AACH;;;;;;;;AASA,SAAS,UAAU,UAAiC;CAClD,MAAM,0BAAU,IAAI,IAAY;CAChC,SAAS,UAAU;CACnB,SAAS,QAAQ,MACd,UAAU;EACT,KAAK,MAAM,UAAU,SACnB,OAAO,QAAQ,KAAK;CAExB,IACC,UAAU;EACT,KAAK,MAAM,UAAU,SACnB,OAAO,OAAO,KAAK;CAEvB,CACF;CACA,OAAO;AACT;;AAGA,SAAS,MAAM,IAAY,SAAiC;CAC1D,IAAI,aAAa,IAAI,EAAE,CAAC,EAAE,YAAY,SACpC,aAAa,OAAO,EAAE;AAE1B"}
@@ -1 +1 @@
1
- {"version":3,"file":"withTimeout.d.ts","names":[],"sources":["../../../src/utils/withTimeout.ts"],"mappings":";;;;;;;;;;wBASgB,YAAY,GAC1B,OAAO;EAAY,QAAQ;MAAuC,QAAQ,MAExE,eACA,SACA;EAGA,gBAAgB;EAEhB;EAEA;IAED,QAAQ"}
1
+ {"version":3,"file":"withTimeout.d.ts","names":[],"sources":["../../../src/utils/withTimeout.ts"],"mappings":";;;;;;;;;;wBAWgB,YAAY,GAC1B,OAAO;EAAY,QAAQ;MAAuC,QAAQ,MAExE,eACA,SACA;EAGA,gBAAgB;EAEhB;EAEA;IAED,QAAQ"}
@@ -1,3 +1,4 @@
1
+ import { isAbortError } from "./abort.js";
1
2
  //#region src/utils/withTimeout.ts
2
3
  /**
3
4
  * Wraps a function in a timeout.
@@ -12,15 +13,18 @@ function withTimeout(fn, { errorInstance = /* @__PURE__ */ new Error("Timed out
12
13
  return new Promise((resolve, reject) => {
13
14
  (async () => {
14
15
  let timeoutId;
16
+ const controller = new AbortController();
15
17
  try {
16
- const controller = new AbortController();
17
18
  if (timeout > 0) timeoutId = setTimeout(() => {
18
19
  if (signal) controller.abort();
19
20
  else reject(errorInstance);
20
21
  }, timeout);
21
22
  resolve(await fn({ signal: controller?.signal || null }));
22
23
  } catch (err) {
23
- if (err?.name === "AbortError") reject(errorInstance);
24
+ if (controller.signal.aborted && isAbortError(err)) {
25
+ reject(errorInstance);
26
+ return;
27
+ }
24
28
  reject(err);
25
29
  } finally {
26
30
  clearTimeout(timeoutId);
@@ -1 +1 @@
1
- {"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') {\n reject(errorInstance)\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,IAAI;IACF,MAAM,aAAa,IAAI,gBAAgB;IACvC,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IACZ,IAAK,KAAe,SAAS,cAC3B,OAAO,aAAa;IAEtB,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,EAAA,CAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["import { isAbortError } from './abort.js'\n\n/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n const controller = new AbortController()\n try {\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n // Only an abort from our own timeout is a timeout. Any other\n // AbortError belongs to the caller and passes through.\n if (controller.signal.aborted && isAbortError(err)) {\n reject(errorInstance)\n return\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,MAAM,aAAa,IAAI,gBAAgB;GACvC,IAAI;IACF,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IAGZ,IAAI,WAAW,OAAO,WAAW,aAAa,GAAG,GAAG;KAClD,OAAO,aAAa;KACpB;IACF;IACA,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,EAAA,CAAG;CACL,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
  //#region src/version.d.ts
2
2
  export declare const name = "@lifi/sdk";
3
- export declare const version = "4.9.0";
3
+ export declare const version = "4.11.0";
4
4
  //#endregion
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  //#region src/version.ts
2
2
  const name = "@lifi/sdk";
3
- const version = "4.9.0";
3
+ const version = "4.11.0";
4
4
  //#endregion
5
5
  export { name, version };
6
6
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.9.0'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.11.0'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/sdk",
3
- "version": "4.9.0",
3
+ "version": "4.11.0",
4
4
  "description": "LI.FI SDK for Any-to-Any Cross-Chain-Swap",
5
5
  "homepage": "https://github.com/lifinance/sdk",
6
6
  "bugs": {
@@ -28,7 +28,7 @@
28
28
  "./package.json": "./package.json"
29
29
  },
30
30
  "dependencies": {
31
- "@lifi/types": "^18.10.0"
31
+ "@lifi/types": "^18.13.0"
32
32
  },
33
33
  "publishConfig": {
34
34
  "access": "public"
@@ -8,8 +8,16 @@ import type {
8
8
  } from '../types/core.js'
9
9
  import { checkPackageUpdates } from '../utils/checkPackageUpdates.js'
10
10
  import { name, version } from '../version.js'
11
+ import { findProvider } from './findProvider.js'
11
12
  import { getClientStorage } from './getClientStorage.js'
12
13
 
14
+ // A provider replaces only one that serves the same chains. A provider that
15
+ // lists no chains keeps the bare type, so even an empty list stays apart.
16
+ const providerScope = (provider: SDKProvider): string =>
17
+ provider.chainIds
18
+ ? `${provider.type}:${[...provider.chainIds].sort().join(',')}`
19
+ : provider.type
20
+
13
21
  export function createClient(options: SDKConfig): SDKClient {
14
22
  if (!options.integrator) {
15
23
  throw new Error(
@@ -68,15 +76,15 @@ export function createClient(options: SDKConfig): SDKClient {
68
76
  get providers() {
69
77
  return _providers
70
78
  },
71
- getProvider(type: ChainType) {
72
- return this.providers.find((provider) => provider.type === type)
79
+ getProvider(type: ChainType, chainId?: ChainId) {
80
+ return findProvider(this.providers, type, chainId)
73
81
  },
74
82
  setProviders(newProviders: SDKProvider[]) {
75
83
  const providerMap = new Map(
76
- this.providers.map((provider) => [provider.type, provider])
84
+ this.providers.map((provider) => [providerScope(provider), provider])
77
85
  )
78
86
  for (const provider of newProviders) {
79
- providerMap.set(provider.type, provider)
87
+ providerMap.set(providerScope(provider), provider)
80
88
  }
81
89
  _providers = Array.from(providerMap.values())
82
90
  },
@@ -0,0 +1,21 @@
1
+ import type { ChainId, ChainType } from '@lifi/types'
2
+ import type { SDKProvider } from '../types/core.js'
3
+
4
+ /**
5
+ * The provider that serves a chain: the one that lists `chainId` in its
6
+ * `chainIds`, otherwise the provider of `chainType` that lists no chains.
7
+ */
8
+ export const findProvider = <T extends Pick<SDKProvider, 'type' | 'chainIds'>>(
9
+ providers: readonly T[],
10
+ chainType: ChainType,
11
+ chainId?: ChainId
12
+ ): T | undefined =>
13
+ (chainId === undefined
14
+ ? undefined
15
+ : providers.find(
16
+ (provider) =>
17
+ provider.type === chainType && provider.chainIds?.includes(chainId)
18
+ )) ??
19
+ providers.find(
20
+ (provider) => provider.type === chainType && !provider.chainIds
21
+ )
@@ -1,5 +1,6 @@
1
- import { ExecuteStepRetryError } from '../errors/errors.js'
2
- import type { SDKError } from '../errors/SDKError.js'
1
+ import { BaseError } from '../errors/baseError.js'
2
+ import { ExecuteStepRetryError, UnknownError } from '../errors/errors.js'
3
+ import { SDKError } from '../errors/SDKError.js'
3
4
  import type {
4
5
  ExecuteStepRetryParams,
5
6
  ExecutionAction,
@@ -16,6 +17,11 @@ import type {
16
17
  } from '../types/execution.js'
17
18
  import { StatusManager } from './StatusManager.js'
18
19
  import type { TaskPipeline } from './TaskPipeline.js'
20
+ import {
21
+ hasStepOpenTransaction,
22
+ isFinalTransactionError,
23
+ transactionConflictError,
24
+ } from './transactionState.js'
19
25
 
20
26
  // Please be careful when changing the defaults as it may break the behavior (e.g., background execution)
21
27
  const defaultInteractionSettings = {
@@ -49,7 +55,8 @@ export abstract class BaseStepExecutor implements StepExecutor {
49
55
  private createBaseContext = async (
50
56
  client: SDKClient,
51
57
  step: LiFiStepExtended,
52
- retryParams?: ExecuteStepRetryParams
58
+ retryParams?: ExecuteStepRetryParams,
59
+ signal?: AbortSignal
53
60
  ): Promise<StepExecutorBaseContext> => {
54
61
  const fromChain = await client.getChainById(step.action.fromChainId)
55
62
  const toChain = await client.getChainById(step.action.toChainId)
@@ -66,6 +73,7 @@ export abstract class BaseStepExecutor implements StepExecutor {
66
73
  statusManager: this.statusManager,
67
74
  executionOptions: this.executionOptions,
68
75
  allowUserInteraction: this.allowUserInteraction,
76
+ signal,
69
77
  }
70
78
  }
71
79
 
@@ -85,7 +93,8 @@ export abstract class BaseStepExecutor implements StepExecutor {
85
93
  executeStep = async (
86
94
  client: SDKClient,
87
95
  step: LiFiStepExtended,
88
- retryParams?: ExecuteStepRetryParams
96
+ retryParams?: ExecuteStepRetryParams,
97
+ signal?: AbortSignal
89
98
  ): Promise<LiFiStepExtended> => {
90
99
  try {
91
100
  step.execution = this.statusManager.initializeExecution(step)
@@ -93,7 +102,8 @@ export abstract class BaseStepExecutor implements StepExecutor {
93
102
  const baseContext = await this.createBaseContext(
94
103
  client,
95
104
  step,
96
- retryParams
105
+ retryParams,
106
+ signal
97
107
  )
98
108
  const context = await this.createContext(baseContext)
99
109
  const pipeline = this.createPipeline(context)
@@ -104,7 +114,30 @@ export abstract class BaseStepExecutor implements StepExecutor {
104
114
  } catch (error: any) {
105
115
  // Derive failing action from last in execution.actions
106
116
  const action = step.execution?.actions?.at(-1)
107
- const parsed = await this.parseErrors(error, step, action, retryParams)
117
+ // Read before parsing: parsers may rebuild the error and drop the marker.
118
+ let isFinal = isFinalTransactionError(error)
119
+ let parsed = await this.parseErrors(error, step, action, retryParams)
120
+ if (
121
+ parsed instanceof ExecuteStepRetryError &&
122
+ hasStepOpenTransaction(step)
123
+ ) {
124
+ // A retry runs the step again on an empty execution, which would erase
125
+ // the hash of a transaction that may still land. Fail with the original
126
+ // error instead, and keep the outcome unknown so a resume re-checks it.
127
+ // A BaseError keeps its code, so the widget shows its text. A replay
128
+ // that a task asked for has no error of its own: it fails as a sign
129
+ // task fails for the same state (`TransactionConflict`).
130
+ parsed = new SDKError(
131
+ error instanceof ExecuteStepRetryError
132
+ ? transactionConflictError()
133
+ : error instanceof BaseError
134
+ ? error
135
+ : new UnknownError(error?.message || parsed.message, error),
136
+ step,
137
+ action
138
+ )
139
+ isFinal = false
140
+ }
108
141
  if (!(parsed instanceof ExecuteStepRetryError)) {
109
142
  if (action) {
110
143
  this.statusManager.updateAction(step, action.type, 'FAILED', {
@@ -112,6 +145,7 @@ export abstract class BaseStepExecutor implements StepExecutor {
112
145
  message: parsed.cause?.message,
113
146
  code: parsed.code,
114
147
  },
148
+ ...(isFinal && { txFinal: true }),
115
149
  })
116
150
  } else {
117
151
  this.statusManager.updateExecution(step, {
@@ -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
  }