@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":"execution.js","names":["executionState","ProviderError","ExecuteStepRetryError"],"sources":["../../../src/core/execution.ts"],"sourcesContent":["import type { Route } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { ExecuteStepRetryError, ProviderError } from '../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n RouteExtended,\n SDKClient,\n SDKProvider,\n} from '../types/core.js'\nimport { executionState } from './executionState.js'\nimport { prepareRestart } from './prepareRestart.js'\n\n/**\n * Execute a route.\n * @param client - The SDK client.\n * @param route - The route that should be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const executeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n // Deep clone to prevent side effects\n const clonedRoute = structuredClone<Route>(route)\n\n let executionPromise = executionState.get(clonedRoute.id)?.promise\n // Check if route is already running\n if (executionPromise) {\n return executionPromise\n }\n\n executionState.create({ route: clonedRoute, executionOptions })\n executionPromise = executeSteps(client, clonedRoute)\n executionState.update({\n route: clonedRoute,\n promise: executionPromise,\n })\n\n return executionPromise\n}\n\n/**\n * Resume the execution of a route that has been stopped or had an error while executing.\n * @param client - The SDK client.\n * @param route - The route that is to be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const resumeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n const execution = executionState.get(route.id)\n\n if (execution) {\n const executionHalted = execution.executors.some(\n (executor) => !executor.allowExecution\n )\n if (!executionHalted) {\n // Check if we want to resume route execution in the background\n updateRouteExecution(route, {\n executeInBackground: executionOptions?.executeInBackground,\n })\n if (!execution.promise) {\n // We should never reach this point if we do clean-up properly\n throw new Error('Route execution promise not found.')\n }\n return execution.promise\n }\n }\n\n prepareRestart(route)\n\n return executeRoute(client, route, executionOptions)\n}\n\nconst executeSteps = async (\n client: SDKClient,\n route: RouteExtended\n): Promise<RouteExtended> => {\n // Loop over steps and execute them\n for (let index = 0; index < route.steps.length; index++) {\n const execution = executionState.get(route.id)\n // Check if execution has stopped in the meantime\n if (!execution) {\n break\n }\n\n const step = route.steps[index]\n const previousStep = route.steps[index - 1]\n // Check if the step is already done\n if (step.execution?.status === 'DONE') {\n continue\n }\n\n // Update step fromAmount using output of the previous step execution. In the future this should be handled by calling `updateRoute`\n if (previousStep?.execution?.toAmount) {\n step.action.fromAmount = previousStep.execution.toAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount =\n previousStep.execution.toAmount\n }\n }\n\n try {\n const fromAddress = step.action.fromAddress\n if (!fromAddress) {\n throw new Error('Action fromAddress is not specified.')\n }\n\n const provider = client.providers.find((provider: SDKProvider) =>\n provider.isAddress(fromAddress)\n )\n\n if (!provider) {\n throw new ProviderError(\n LiFiErrorCode.ProviderUnavailable,\n 'SDK Execution Provider not found.'\n )\n }\n\n const stepExecutor = await provider.getStepExecutor({\n routeId: route.id,\n executionOptions: execution.executionOptions,\n })\n execution.executors.push(stepExecutor)\n\n // Check if we want to execute this step in the background\n if (execution.executionOptions) {\n updateRouteExecution(route, execution.executionOptions)\n }\n\n let executedStep: LiFiStepExtended\n try {\n executedStep = await stepExecutor.executeStep(client, step)\n } catch (e) {\n if (e instanceof ExecuteStepRetryError) {\n step.execution = undefined\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n e.retryParams\n )\n } else {\n throw e\n }\n }\n\n // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it\n if (executedStep.execution?.status !== 'DONE') {\n stopRouteExecution(route)\n }\n\n // Execution stopped during the current step, we don't want to continue to the next step so we return already\n if (!stepExecutor.allowExecution) {\n return route\n }\n } catch (e) {\n stopRouteExecution(route)\n throw e\n }\n }\n\n // Clean up after the execution\n executionState.delete(route.id)\n return route\n}\n\n/**\n * Updates route execution to background or foreground state.\n * @param route - A route that is currently in execution.\n * @param options - An object with execution settings.\n */\nexport const updateRouteExecution = (\n route: Route,\n options: ExecutionOptions\n): void => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return\n }\n\n if ('executeInBackground' in options) {\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: !options?.executeInBackground,\n allowUpdates: true,\n })\n }\n }\n // Update active route settings so we know what the current state of execution is\n execution.executionOptions = {\n ...execution.executionOptions,\n ...options,\n }\n}\n\n/**\n * Stops the execution of an active route.\n * @param route - A route that is currently in execution.\n * @returns The stopped route.\n */\nexport const stopRouteExecution = (route: Route): Route => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return route\n }\n\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: false,\n allowUpdates: false,\n allowExecution: false,\n })\n }\n executionState.delete(route.id)\n return execution.route\n}\n\n/**\n * Get the list of active routes.\n * @returns A list of routes.\n */\nexport const getActiveRoutes = (): RouteExtended[] => {\n return Object.values(executionState.state)\n .map((dict) => dict?.route)\n .filter(Boolean) as RouteExtended[]\n}\n\n/**\n * Return the current route information for given route. The route has to be active.\n * @param routeId - A route id.\n * @returns The updated route.\n */\nexport const getActiveRoute = (routeId: string): RouteExtended | undefined => {\n return execution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AU,WAC/B,SAAS,eAAe;EACtB,kBAAkB;EAClB,cAAc;EACd,gBAAgB;CAClB,CAAC;CAEH,4BAAA,eAAe,OAAO,MAAM,EAAE;CAC9B,OAAO,UAAU;AACnB;;;;;AAMA,MAAa,wBAAyC;CACpD,OAAO,OAAO,OAAOA,4BAAAA,eAAe,KAAK,CAAC,CACvC,KAAK,SAAS,MAAM,KAAK,CAAC,CAC1B,OAAO,OAAO;AACnB;;;;;;AAOA,MAAa,kBAAkB,YAA+C;CAC5E,OAAOA,4BAAAA,eAAe,IAAI,OAAO,CAAC,EAAE;AACtC"}
1
+ {"version":3,"file":"execution.js","names":["executionState","ProviderError","ExecuteStepRetryError"],"sources":["../../../src/core/execution.ts"],"sourcesContent":["import type { Route } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { ExecuteStepRetryError, ProviderError } from '../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n RouteExtended,\n SDKClient,\n SDKProvider,\n} from '../types/core.js'\nimport { executionState } from './executionState.js'\nimport { prepareRestart } from './prepareRestart.js'\n\n/**\n * Execute a route.\n * @param client - The SDK client.\n * @param route - The route that should be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const executeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n // Deep clone to prevent side effects\n const clonedRoute = structuredClone<Route>(route)\n\n let executionPromise = executionState.get(clonedRoute.id)?.promise\n // Check if route is already running\n if (executionPromise) {\n return executionPromise\n }\n\n executionState.create({ route: clonedRoute, executionOptions })\n executionPromise = executeSteps(client, clonedRoute)\n executionState.update({\n route: clonedRoute,\n promise: executionPromise,\n })\n\n return executionPromise\n}\n\n/**\n * Resume the execution of a route that has been stopped or had an error while executing.\n * @param client - The SDK client.\n * @param route - The route that is to be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const resumeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n const execution = executionState.get(route.id)\n\n if (execution) {\n const executionHalted = execution.executors.some(\n (executor) => !executor.allowExecution\n )\n if (!executionHalted) {\n // Check if we want to resume route execution in the background\n updateRouteExecution(route, {\n executeInBackground: executionOptions?.executeInBackground,\n })\n if (!execution.promise) {\n // We should never reach this point if we do clean-up properly\n throw new Error('Route execution promise not found.')\n }\n return execution.promise\n }\n }\n\n // Restart from a copy: the caller's route (e.g. an integrator's store) must\n // only change through `updateRouteHook`.\n const restartRoute = structuredClone<RouteExtended>(route)\n prepareRestart(restartRoute)\n\n return executeRoute(client, restartRoute, executionOptions)\n}\n\n/**\n * True while `route` is the execution registered for its id. A stopped run\n * keeps going until its step ends; it must not stop or delete a newer\n * execution of the same route.\n */\nconst ownsExecution = (route: RouteExtended): boolean =>\n executionState.get(route.id)?.route === route\n\nconst executeSteps = async (\n client: SDKClient,\n route: RouteExtended\n): Promise<RouteExtended> => {\n // Loop over steps and execute them\n for (let index = 0; index < route.steps.length; index++) {\n const execution = executionState.get(route.id)\n // Check if execution has stopped in the meantime. A newer execution of the\n // same route id is not ours, also when our executor ignored the stop.\n if (!execution || execution.route !== route) {\n break\n }\n\n const step = route.steps[index]\n const previousStep = route.steps[index - 1]\n // Check if the step is already done\n if (step.execution?.status === 'DONE') {\n continue\n }\n\n // Update step fromAmount using output of the previous step execution. In the future this should be handled by calling `updateRoute`\n if (previousStep?.execution?.toAmount) {\n step.action.fromAmount = previousStep.execution.toAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount =\n previousStep.execution.toAmount\n }\n }\n\n try {\n const fromAddress = step.action.fromAddress\n if (!fromAddress) {\n throw new Error('Action fromAddress is not specified.')\n }\n\n const provider = client.providers.find((provider: SDKProvider) =>\n provider.isAddress(fromAddress)\n )\n\n if (!provider) {\n throw new ProviderError(\n LiFiErrorCode.ProviderUnavailable,\n 'SDK Execution Provider not found.'\n )\n }\n\n const stepExecutor = await provider.getStepExecutor({\n routeId: route.id,\n executionOptions: execution.executionOptions,\n })\n // A stop during the await did not reach this executor, and a newer\n // execution of the route may run now: do not start the step.\n if (!ownsExecution(route)) {\n return route\n }\n // In flight until the step settles, the retry included: a stop keeps\n // the records a late write of this run needs (`executionState`).\n executionState.retain(route.id)\n // Taken from this execution, not looked up again for the retry: a\n // newer execution of the route id has its own.\n const { signal } = execution.abortController\n let executedStep: LiFiStepExtended\n try {\n execution.executors.push(stepExecutor)\n\n // Check if we want to execute this step in the background\n if (execution.executionOptions) {\n updateRouteExecution(route, execution.executionOptions)\n }\n\n try {\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n undefined,\n signal\n )\n } catch (e) {\n if (e instanceof ExecuteStepRetryError) {\n // A stop ended this run while its first attempt ran: the replay\n // would be new work on a stopped executor.\n if (!stepExecutor.allowExecution) {\n return route\n }\n step.execution = undefined\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n e.retryParams,\n signal\n )\n } else {\n throw e\n }\n }\n } finally {\n executionState.release(route.id)\n }\n\n // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it\n if (executedStep.execution?.status !== 'DONE' && ownsExecution(route)) {\n stopRouteExecution(route)\n }\n\n // Execution stopped during the current step, we don't want to continue to the next step so we return already\n if (!stepExecutor.allowExecution) {\n return route\n }\n } catch (e) {\n if (ownsExecution(route)) {\n stopRouteExecution(route)\n }\n throw e\n }\n }\n\n // Clean up after the execution\n if (ownsExecution(route)) {\n executionState.delete(route.id)\n }\n return route\n}\n\n/**\n * Updates route execution to background or foreground state.\n * @param route - A route that is currently in execution.\n * @param options - An object with execution settings.\n */\nexport const updateRouteExecution = (\n route: Route,\n options: ExecutionOptions\n): void => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return\n }\n\n if ('executeInBackground' in options) {\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: !options?.executeInBackground,\n allowUpdates: true,\n })\n }\n }\n // Update active route settings so we know what the current state of execution is\n execution.executionOptions = {\n ...execution.executionOptions,\n ...options,\n }\n}\n\n/**\n * Stops the execution of an active route.\n * @param route - A route that is currently in execution.\n * @returns The stopped route.\n */\nexport const stopRouteExecution = (route: Route): Route => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return route\n }\n\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: false,\n allowUpdates: false,\n allowExecution: false,\n })\n }\n executionState.delete(route.id)\n // The abort can run before or after the two steps above: its listeners\n // only clear timers, drop the shared poll and reject promises, and the\n // tasks handle the rejections after this function returns. The\n // `setInteraction` loop must run before `executionState.delete`, because\n // `StatusManager.allowUpdates(false)` keeps the route and hook from the\n // execution state.\n execution.abortController.abort()\n return execution.route\n}\n\n/**\n * Get the list of active routes.\n * @returns A list of routes.\n */\nexport const getActiveRoutes = (): RouteExtended[] => {\n return Object.values(executionState.state)\n .map((dict) => dict?.route)\n .filter(Boolean) as RouteExtended[]\n}\n\n/**\n * Return the current route information for given route. The route has to be active.\n * @param routeId - A route id.\n * @returns The updated route.\n */\nexport const getActiveRoute = (routeId: string): RouteExtended | undefined => {\n return executionState.get(routeId)?.route\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAa,eAAe,OAC1B,QACA,OACA,qBAC2B;CAE3B,MAAM,cAAc,gBAAuB,KAAK;CAEhD,IAAI,mBAAmBA,4BAAAA,eAAe,IAAI,YAAY,EAAE,CAAC,EAAE;CAE3D,IAAI,kBACF,OAAO;CAGT,4BAAA,eAAe,OAAO;EAAE,OAAO;EAAa;CAAiB,CAAC;CAC9D,mBAAmB,aAAa,QAAQ,WAAW;CACnD,4BAAA,eAAe,OAAO;EACpB,OAAO;EACP,SAAS;CACX,CAAC;CAED,OAAO;AACT;;;;;;;;;AAUA,MAAa,cAAc,OACzB,QACA,OACA,qBAC2B;CAC3B,MAAM,YAAYA,4BAA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ACtB,kBAAkB;EAClB,cAAc;EACd,gBAAgB;CAClB,CAAC;CAEH,4BAAA,eAAe,OAAO,MAAM,EAAE;CAO9B,UAAU,gBAAgB,MAAM;CAChC,OAAO,UAAU;AACnB;;;;;AAMA,MAAa,wBAAyC;CACpD,OAAO,OAAO,OAAOA,4BAAAA,eAAe,KAAK,CAAC,CACvC,KAAK,SAAS,MAAM,KAAK,CAAC,CAC1B,OAAO,OAAO;AACnB;;;;;;AAOA,MAAa,kBAAkB,YAA+C;CAC5E,OAAOA,4BAAAA,eAAe,IAAI,OAAO,CAAC,EAAE;AACtC"}
@@ -1,18 +1,50 @@
1
- import { ExecutionOptions, RouteExtended, StepExecutor } from "../types/core.js";
1
+ import { ExecutionOptions, RouteExtended, StepExecutor, UpdateRouteHook } from "../types/core.js";
2
2
  //#region src/core/executionState.d.ts
3
3
  interface ExecutionData {
4
4
  route: RouteExtended;
5
5
  executors: StepExecutor[];
6
6
  executionOptions?: ExecutionOptions;
7
7
  promise?: Promise<RouteExtended>;
8
+ /**
9
+ * One per execution: `stopRouteExecution` aborts it, so the waits of the
10
+ * stopped run that take its signal end.
11
+ */
12
+ abortController: AbortController;
13
+ }
14
+ type ExecutionStateParams = Omit<ExecutionData, "executors" | "abortController">;
15
+ /** The route and hook of an execution that ended (stopped or finished). */
16
+ interface EndedExecution {
17
+ route: RouteExtended;
18
+ updateRouteHook?: UpdateRouteHook;
8
19
  }
9
- type ExecutionStateParams = Omit<ExecutionData, "executors">;
10
20
  interface ExecutionState {
11
21
  state: Partial<Record<string, ExecutionData>>;
22
+ /**
23
+ * The start number of the last execution per route id. Survives `delete`
24
+ * while a run of the route is in flight, so a stopped run can tell whether
25
+ * a newer execution of its route started since its stop.
26
+ */
27
+ starts: Partial<Record<string, number>>;
28
+ /**
29
+ * The last ended execution per route id. Kept only while a run of the
30
+ * route is in flight, so a late write of a stopped run can reach the route
31
+ * of a newer execution that ended.
32
+ */
33
+ ended: Partial<Record<string, EndedExecution>>;
34
+ /** Runs per route id inside a step (`retain` to `release`). */
35
+ inFlight: Partial<Record<string, number>>;
12
36
  get(routeId: string): ExecutionData | undefined;
13
37
  create(params: ExecutionStateParams): ExecutionData;
14
38
  update(params: ExecutionStateParams): void;
15
39
  delete(routeId: string): void;
40
+ retain(routeId: string): void;
41
+ release(routeId: string): void;
42
+ /**
43
+ * The start number of the last execution of the route id, or 0 when the
44
+ * route has no records. A new start always gets a higher number.
45
+ */
46
+ startCount(routeId: string): number;
47
+ lastEnded(routeId: string): EndedExecution | undefined;
16
48
  }
17
49
  export declare const executionState: ExecutionState;
18
50
  //#endregion
@@ -1,15 +1,27 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  //#region src/core/executionState.ts
3
+ /**
4
+ * The last start number given to any route id. A number is never given
5
+ * twice, so a route id whose records were freed and that started again never
6
+ * shows the number a stopped run took at its stop.
7
+ */
8
+ let lastStart = 0;
3
9
  const executionState = {
4
10
  state: {},
11
+ starts: {},
12
+ ended: {},
13
+ inFlight: {},
5
14
  get(routeId) {
6
15
  return this.state[routeId];
7
16
  },
8
17
  create(params) {
18
+ lastStart += 1;
19
+ this.starts[params.route.id] = lastStart;
9
20
  this.state[params.route.id] = {
10
21
  ...this.state[params.route.id],
11
22
  ...params,
12
- executors: this.state[params.route.id]?.executors ?? []
23
+ executors: this.state[params.route.id]?.executors ?? [],
24
+ abortController: new AbortController()
13
25
  };
14
26
  return this.state[params.route.id];
15
27
  },
@@ -20,7 +32,38 @@ const executionState = {
20
32
  };
21
33
  },
22
34
  delete(routeId) {
35
+ const data = this.state[routeId];
23
36
  delete this.state[routeId];
37
+ if (!this.inFlight[routeId]) {
38
+ delete this.starts[routeId];
39
+ delete this.ended[routeId];
40
+ return;
41
+ }
42
+ if (data) this.ended[routeId] = {
43
+ route: data.route,
44
+ updateRouteHook: data.executionOptions?.updateRouteHook
45
+ };
46
+ },
47
+ retain(routeId) {
48
+ this.inFlight[routeId] = (this.inFlight[routeId] ?? 0) + 1;
49
+ },
50
+ release(routeId) {
51
+ const count = (this.inFlight[routeId] ?? 0) - 1;
52
+ if (count > 0) {
53
+ this.inFlight[routeId] = count;
54
+ return;
55
+ }
56
+ delete this.inFlight[routeId];
57
+ if (!this.state[routeId]) {
58
+ delete this.starts[routeId];
59
+ delete this.ended[routeId];
60
+ }
61
+ },
62
+ startCount(routeId) {
63
+ return this.starts[routeId] ?? 0;
64
+ },
65
+ lastEnded(routeId) {
66
+ return this.ended[routeId];
24
67
  }
25
68
  };
26
69
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";;AAuBA,MAAa,iBAAiC;CAC5C,OAAO,CAAC;CACR,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;CACpB;CACA,OAAO,QAAQ;EACb,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,GAAG,EAAE,aAAa,CAAC;EACxD;EACA,OAAO,KAAK,MAAM,OAAO,MAAM;CACjC;CACA,OAAO,OAAO;EACZ,IAAI,KAAK,MAAM,MAAM,MAAM,KACzB,KAAK,MAAM,MAAM,MAAM,MAAM;GAC3B,GAAG,KAAK,MAAM,MAAM,MAAM;GAC1B,GAAG;EACL;CAEJ;CACA,OAAO,SAAS;EACd,OAAO,KAAK,MAAM;CACpB;AACF"}
1
+ {"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n UpdateRouteHook,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n /**\n * One per execution: `stopRouteExecution` aborts it, so the waits of the\n * stopped run that take its signal end.\n */\n abortController: AbortController\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors' | 'abortController'>\n\n/** The route and hook of an execution that ended (stopped or finished). */\ninterface EndedExecution {\n route: RouteExtended\n updateRouteHook?: UpdateRouteHook\n}\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n /**\n * The start number of the last execution per route id. Survives `delete`\n * while a run of the route is in flight, so a stopped run can tell whether\n * a newer execution of its route started since its stop.\n */\n starts: Partial<Record<string, number>>\n /**\n * The last ended execution per route id. Kept only while a run of the\n * route is in flight, so a late write of a stopped run can reach the route\n * of a newer execution that ended.\n */\n ended: Partial<Record<string, EndedExecution>>\n /** Runs per route id inside a step (`retain` to `release`). */\n inFlight: Partial<Record<string, number>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n retain(routeId: string): void\n release(routeId: string): void\n /**\n * The start number of the last execution of the route id, or 0 when the\n * route has no records. A new start always gets a higher number.\n */\n startCount(routeId: string): number\n lastEnded(routeId: string): EndedExecution | undefined\n}\n\n/**\n * The last start number given to any route id. A number is never given\n * twice, so a route id whose records were freed and that started again never\n * shows the number a stopped run took at its stop.\n */\nlet lastStart = 0\n\nexport const executionState: ExecutionState = {\n state: {},\n starts: {},\n ended: {},\n inFlight: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n lastStart += 1\n this.starts[params.route.id] = lastStart\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n abortController: new AbortController(),\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n const data = this.state[routeId]\n delete this.state[routeId]\n // No run of the route is in flight, so no stopped run can write late:\n // nothing is kept. (A normal finish releases its run before its delete.)\n if (!this.inFlight[routeId]) {\n delete this.starts[routeId]\n delete this.ended[routeId]\n return\n }\n if (data) {\n this.ended[routeId] = {\n route: data.route,\n updateRouteHook: data.executionOptions?.updateRouteHook,\n }\n }\n },\n retain(routeId) {\n this.inFlight[routeId] = (this.inFlight[routeId] ?? 0) + 1\n },\n release(routeId) {\n const count = (this.inFlight[routeId] ?? 0) - 1\n if (count > 0) {\n this.inFlight[routeId] = count\n return\n }\n delete this.inFlight[routeId]\n // A running execution keeps its records until its own `delete`.\n if (!this.state[routeId]) {\n delete this.starts[routeId]\n delete this.ended[routeId]\n }\n },\n startCount(routeId: string): number {\n return this.starts[routeId] ?? 0\n },\n lastEnded(routeId: string): EndedExecution | undefined {\n return this.ended[routeId]\n },\n}\n"],"mappings":";;;;;;;AA8DA,IAAI,YAAY;AAEhB,MAAa,iBAAiC;CAC5C,OAAO,CAAC;CACR,QAAQ,CAAC;CACT,OAAO,CAAC;CACR,UAAU,CAAC;CACX,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;CACpB;CACA,OAAO,QAAQ;EACb,aAAa;EACb,KAAK,OAAO,OAAO,MAAM,MAAM;EAC/B,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,GAAG,EAAE,aAAa,CAAC;GACtD,iBAAiB,IAAI,gBAAgB;EACvC;EACA,OAAO,KAAK,MAAM,OAAO,MAAM;CACjC;CACA,OAAO,OAAO;EACZ,IAAI,KAAK,MAAM,MAAM,MAAM,KACzB,KAAK,MAAM,MAAM,MAAM,MAAM;GAC3B,GAAG,KAAK,MAAM,MAAM,MAAM;GAC1B,GAAG;EACL;CAEJ;CACA,OAAO,SAAS;EACd,MAAM,OAAO,KAAK,MAAM;EACxB,OAAO,KAAK,MAAM;EAGlB,IAAI,CAAC,KAAK,SAAS,UAAU;GAC3B,OAAO,KAAK,OAAO;GACnB,OAAO,KAAK,MAAM;GAClB;EACF;EACA,IAAI,MACF,KAAK,MAAM,WAAW;GACpB,OAAO,KAAK;GACZ,iBAAiB,KAAK,kBAAkB;EAC1C;CAEJ;CACA,OAAO,SAAS;EACd,KAAK,SAAS,YAAY,KAAK,SAAS,YAAY,KAAK;CAC3D;CACA,QAAQ,SAAS;EACf,MAAM,SAAS,KAAK,SAAS,YAAY,KAAK;EAC9C,IAAI,QAAQ,GAAG;GACb,KAAK,SAAS,WAAW;GACzB;EACF;EACA,OAAO,KAAK,SAAS;EAErB,IAAI,CAAC,KAAK,MAAM,UAAU;GACxB,OAAO,KAAK,OAAO;GACnB,OAAO,KAAK,MAAM;EACpB;CACF;CACA,WAAW,SAAyB;EAClC,OAAO,KAAK,OAAO,YAAY;CACjC;CACA,UAAU,SAA6C;EACrD,OAAO,KAAK,MAAM;CACpB;AACF"}
@@ -1,15 +1,23 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_core_actionMessages = require("./actionMessages.js");
3
+ const require_core_transactionState = require("./transactionState.js");
2
4
  //#region src/core/prepareRestart.ts
5
+ const RESTART_ACTION_TYPES = [
6
+ "SWAP",
7
+ "CROSS_CHAIN",
8
+ "RECEIVING_CHAIN"
9
+ ];
3
10
  const prepareRestart = (route) => {
4
11
  for (let index = 0; index < route.steps.length; index++) {
5
12
  const step = route.steps[index];
6
13
  if (step.execution) {
7
- const lastValidIndex = step.execution.actions.findLastIndex((action) => [
8
- "SWAP",
9
- "CROSS_CHAIN",
10
- "RECEIVING_CHAIN"
11
- ].includes(action.type) && (!!action.txHash || !!action.taskId) && action.status !== "FAILED");
12
- if (lastValidIndex >= 0) step.execution.actions = step.execution.actions.slice(0, lastValidIndex + 1);
14
+ const lastOpenIndex = step.execution.actions.findLastIndex((action) => RESTART_ACTION_TYPES.includes(action.type) && require_core_transactionState.hasOpenTransaction(action));
15
+ if (lastOpenIndex >= 0) step.execution.actions = step.execution.actions.slice(0, lastOpenIndex + 1).map((action) => action.status === "FAILED" && require_core_transactionState.hasOpenTransaction(action) ? {
16
+ ...action,
17
+ status: "PENDING",
18
+ message: require_core_actionMessages.getActionMessage(action.type, "PENDING"),
19
+ error: void 0
20
+ } : action);
13
21
  else step.execution.actions = [];
14
22
  }
15
23
  step.transactionRequest = void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";;AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAElB,MAAM,iBAAiB,KAAK,UAAU,QAAQ,eAC3C,WACC;IAAC;IAAQ;IAAe;GAAiB,CAAC,CAAC,SAAS,OAAO,IAAI,MAC9D,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,WAC7B,OAAO,WAAW,QACtB;GAGA,IAAI,kBAAkB,GACpB,KAAK,UAAU,UAAU,KAAK,UAAU,QAAQ,MAC9C,GACA,iBAAiB,CACnB;QAGA,KAAK,UAAU,UAAU,CAAC;EAE9B;EACA,KAAK,qBAAqB,KAAA;CAC5B;AACF"}
1
+ {"version":3,"file":"prepareRestart.js","names":["hasOpenTransaction","getActionMessage"],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { ExecutionActionType, RouteExtended } from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { hasOpenTransaction } from './transactionState.js'\n\nconst RESTART_ACTION_TYPES: readonly ExecutionActionType[] = [\n 'SWAP',\n 'CROSS_CHAIN',\n 'RECEIVING_CHAIN',\n]\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Keep everything up to the last action whose transaction may still\n // land. A FAILED action without `txFinal` has an unknown outcome: it is\n // kept and re-checked on chain instead of being signed again. A FAILED\n // action with `txFinal` is dropped, so the restart signs a new one.\n const lastOpenIndex = step.execution.actions.findLastIndex(\n (action) =>\n RESTART_ACTION_TYPES.includes(action.type) &&\n hasOpenTransaction(action)\n )\n\n if (lastOpenIndex >= 0) {\n step.execution.actions = step.execution.actions\n .slice(0, lastOpenIndex + 1)\n .map((action) =>\n action.status === 'FAILED' && hasOpenTransaction(action)\n ? {\n ...action,\n status: 'PENDING',\n message: getActionMessage(action.type, 'PENDING'),\n error: undefined,\n }\n : action\n )\n } else {\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";;;;AAIA,MAAM,uBAAuD;CAC3D;CACA;CACA;AACF;AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAKlB,MAAM,gBAAgB,KAAK,UAAU,QAAQ,eAC1C,WACC,qBAAqB,SAAS,OAAO,IAAI,KACzCA,8BAAAA,mBAAmB,MAAM,CAC7B;GAEA,IAAI,iBAAiB,GACnB,KAAK,UAAU,UAAU,KAAK,UAAU,QACrC,MAAM,GAAG,gBAAgB,CAAC,CAAC,CAC3B,KAAK,WACJ,OAAO,WAAW,YAAYA,8BAAAA,mBAAmB,MAAM,IACnD;IACE,GAAG;IACH,QAAQ;IACR,SAASC,4BAAAA,iBAAiB,OAAO,MAAM,SAAS;IAChD,OAAO,KAAA;GACT,IACA,MACN;QAEF,KAAK,UAAU,UAAU,CAAC;EAE9B;EACA,KAAK,qBAAqB,KAAA;CAC5B;AACF"}
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  require("../../errors/constants.js");
3
3
  const require_errors_errors = require("../../errors/errors.js");
4
+ const require_utils_abort = require("../../utils/abort.js");
4
5
  const require_core_BaseStepExecutionTask = require("../BaseStepExecutionTask.js");
5
6
  const require_utils_getTransactionMessage = require("../../utils/getTransactionMessage.js");
6
7
  const require_core_tasks_helpers_waitForTransactionStatus = require("./helpers/waitForTransactionStatus.js");
@@ -12,7 +13,7 @@ var WaitForTransactionStatusTask = class extends require_core_BaseStepExecutionT
12
13
  this.actionType = actionType;
13
14
  }
14
15
  async run(context) {
15
- const { client, step, statusManager, pollingIntervalMs, toChain, isBridgeExecution } = context;
16
+ const { client, step, statusManager, pollingIntervalMs, toChain, isBridgeExecution, signal } = context;
16
17
  let transactionHash;
17
18
  try {
18
19
  const swapOrBridgeAction = statusManager.findAction(step, isBridgeExecution ? "CROSS_CHAIN" : "SWAP");
@@ -24,7 +25,7 @@ var WaitForTransactionStatusTask = class extends require_core_BaseStepExecutionT
24
25
  chainId: this.actionType === "RECEIVING_CHAIN" ? step.action.toChainId : step.action.fromChainId,
25
26
  status: "PENDING"
26
27
  });
27
- const statusResponse = await require_core_tasks_helpers_waitForTransactionStatus.waitForTransactionStatus(client, statusManager, transactionHash, step, action.type, pollingIntervalMs);
28
+ const statusResponse = await require_core_tasks_helpers_waitForTransactionStatus.waitForTransactionStatus(client, statusManager, transactionHash, step, action.type, pollingIntervalMs, signal);
28
29
  const statusReceiving = statusResponse.receiving;
29
30
  statusManager.updateAction(step, action.type, "DONE", {
30
31
  chainId: statusReceiving?.chainId || toChain.id,
@@ -52,6 +53,7 @@ var WaitForTransactionStatusTask = class extends require_core_BaseStepExecutionT
52
53
  });
53
54
  return { status: "COMPLETED" };
54
55
  } catch (e) {
56
+ if (signal?.aborted && require_utils_abort.isAbortError(e)) return { status: "PAUSED" };
55
57
  const htmlMessage = await require_utils_getTransactionMessage.getTransactionFailedMessage(client, step, `${toChain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`);
56
58
  throw new require_errors_errors.TransactionError(1003, htmlMessage ?? "Failed while waiting for status of destination chain transaction.", e);
57
59
  }
@@ -1 +1 @@
1
- {"version":3,"file":"WaitForTransactionStatusTask.js","names":["BaseStepExecutionTask","waitForTransactionStatus","getTransactionFailedMessage","TransactionError"],"sources":["../../../../src/core/tasks/WaitForTransactionStatusTask.ts"],"sourcesContent":["import type { ExtendedTransactionInfo, FullStatusData } from '@lifi/types'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { ExecutionActionType } from '../../types/core.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { getTransactionFailedMessage } from '../../utils/getTransactionMessage.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { waitForTransactionStatus } from './helpers/waitForTransactionStatus.js'\n\nexport class WaitForTransactionStatusTask extends BaseStepExecutionTask {\n readonly actionType: ExecutionActionType\n\n constructor(actionType: ExecutionActionType) {\n super()\n this.actionType = actionType\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n pollingIntervalMs,\n toChain,\n isBridgeExecution,\n } = context\n\n // At this point, we should have a txHash or taskId\n // taskId is used for custom integrations that don't use the standard transaction hash\n let transactionHash: string | undefined\n try {\n const swapOrBridgeAction = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n transactionHash = swapOrBridgeAction?.txHash || swapOrBridgeAction?.taskId\n\n // Wait for the transaction status on the destination chain\n if (!transactionHash) {\n throw new Error('Transaction hash is undefined.')\n }\n\n const action = statusManager.initializeAction({\n step,\n type: this.actionType,\n chainId:\n this.actionType === 'RECEIVING_CHAIN'\n ? step.action.toChainId\n : step.action.fromChainId,\n status: 'PENDING',\n })\n\n const statusResponse = (await waitForTransactionStatus(\n client,\n statusManager,\n transactionHash,\n step,\n action.type,\n pollingIntervalMs\n )) as FullStatusData\n\n const statusReceiving =\n statusResponse.receiving as ExtendedTransactionInfo\n\n // Update action status\n statusManager.updateAction(step, action.type, 'DONE', {\n chainId: statusReceiving?.chainId || toChain.id,\n substatus: statusResponse.substatus,\n substatusMessage: statusResponse.substatusMessage,\n txHash: statusReceiving?.txHash,\n txLink:\n statusReceiving?.txLink ||\n `${toChain.metamask.blockExplorerUrls[0]}tx/${statusReceiving?.txHash}`,\n })\n\n // Update execution status\n statusManager.updateExecution(step, {\n status: 'DONE',\n ...(statusResponse.sending.amount && {\n fromAmount: statusResponse.sending.amount,\n }),\n ...(statusReceiving?.amount && { toAmount: statusReceiving.amount }),\n ...(statusReceiving?.token && { toToken: statusReceiving.token }),\n internalTxLink: statusResponse?.lifiExplorerLink,\n externalTxLink: statusResponse?.bridgeExplorerLink,\n gasCosts: [\n {\n amount: statusResponse.sending.gasAmount,\n amountUSD: statusResponse.sending.gasAmountUSD,\n token: statusResponse.sending.gasToken,\n estimate: statusResponse.sending.gasUsed,\n limit: statusResponse.sending.gasUsed,\n price: statusResponse.sending.gasPrice,\n type: 'SEND',\n },\n ],\n })\n\n return { status: 'COMPLETED' }\n } catch (e: any) {\n const htmlMessage = await getTransactionFailedMessage(\n client,\n step,\n `${toChain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`\n )\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n htmlMessage ??\n 'Failed while waiting for status of destination chain transaction.',\n e\n )\n }\n }\n}\n"],"mappings":";;;;;;;AASA,IAAa,+BAAb,cAAkDA,mCAAAA,sBAAsB;CACtE;CAEA,YAAY,YAAiC;EAC3C,MAAM;EACN,KAAK,aAAa;CACpB;CAEA,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,mBACA,SACA,sBACE;EAIJ,IAAI;EACJ,IAAI;GACF,MAAM,qBAAqB,cAAc,WACvC,MACA,oBAAoB,gBAAgB,MACtC;GACA,kBAAkB,oBAAoB,UAAU,oBAAoB;GAGpE,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,gCAAgC;GAGlD,MAAM,SAAS,cAAc,iBAAiB;IAC5C;IACA,MAAM,KAAK;IACX,SACE,KAAK,eAAe,oBAChB,KAAK,OAAO,YACZ,KAAK,OAAO;IAClB,QAAQ;GACV,CAAC;GAED,MAAM,iBAAkB,MAAMC,oDAAAA,yBAC5B,QACA,eACA,iBACA,MACA,OAAO,MACP,iBACF;GAEA,MAAM,kBACJ,eAAe;GAGjB,cAAc,aAAa,MAAM,OAAO,MAAM,QAAQ;IACpD,SAAS,iBAAiB,WAAW,QAAQ;IAC7C,WAAW,eAAe;IAC1B,kBAAkB,eAAe;IACjC,QAAQ,iBAAiB;IACzB,QACE,iBAAiB,UACjB,GAAG,QAAQ,SAAS,kBAAkB,GAAG,KAAK,iBAAiB;GACnE,CAAC;GAGD,cAAc,gBAAgB,MAAM;IAClC,QAAQ;IACR,GAAI,eAAe,QAAQ,UAAU,EACnC,YAAY,eAAe,QAAQ,OACrC;IACA,GAAI,iBAAiB,UAAU,EAAE,UAAU,gBAAgB,OAAO;IAClE,GAAI,iBAAiB,SAAS,EAAE,SAAS,gBAAgB,MAAM;IAC/D,gBAAgB,gBAAgB;IAChC,gBAAgB,gBAAgB;IAChC,UAAU,CACR;KACE,QAAQ,eAAe,QAAQ;KAC/B,WAAW,eAAe,QAAQ;KAClC,OAAO,eAAe,QAAQ;KAC9B,UAAU,eAAe,QAAQ;KACjC,OAAO,eAAe,QAAQ;KAC9B,OAAO,eAAe,QAAQ;KAC9B,MAAM;IACR,CACF;GACF,CAAC;GAED,OAAO,EAAE,QAAQ,YAAY;EAC/B,SAAS,GAAQ;GACf,MAAM,cAAc,MAAMC,oCAAAA,4BACxB,QACA,MACA,GAAG,QAAQ,SAAS,kBAAkB,GAAG,KAAK,iBAChD;GACA,MAAM,IAAIC,sBAAAA,iBAAAA,MAER,eACE,qEACF,CACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"WaitForTransactionStatusTask.js","names":["BaseStepExecutionTask","waitForTransactionStatus","isAbortError","getTransactionFailedMessage","TransactionError"],"sources":["../../../../src/core/tasks/WaitForTransactionStatusTask.ts"],"sourcesContent":["import type { ExtendedTransactionInfo, FullStatusData } from '@lifi/types'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { ExecutionActionType } from '../../types/core.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { isAbortError } from '../../utils/abort.js'\nimport { getTransactionFailedMessage } from '../../utils/getTransactionMessage.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { waitForTransactionStatus } from './helpers/waitForTransactionStatus.js'\n\nexport class WaitForTransactionStatusTask extends BaseStepExecutionTask {\n readonly actionType: ExecutionActionType\n\n constructor(actionType: ExecutionActionType) {\n super()\n this.actionType = actionType\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n pollingIntervalMs,\n toChain,\n isBridgeExecution,\n signal,\n } = context\n\n // At this point, we should have a txHash or taskId\n // taskId is used for custom integrations that don't use the standard transaction hash\n let transactionHash: string | undefined\n try {\n const swapOrBridgeAction = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n transactionHash = swapOrBridgeAction?.txHash || swapOrBridgeAction?.taskId\n\n // Wait for the transaction status on the destination chain\n if (!transactionHash) {\n throw new Error('Transaction hash is undefined.')\n }\n\n const action = statusManager.initializeAction({\n step,\n type: this.actionType,\n chainId:\n this.actionType === 'RECEIVING_CHAIN'\n ? step.action.toChainId\n : step.action.fromChainId,\n status: 'PENDING',\n })\n\n const statusResponse = (await waitForTransactionStatus(\n client,\n statusManager,\n transactionHash,\n step,\n action.type,\n pollingIntervalMs,\n signal\n )) as FullStatusData\n\n const statusReceiving =\n statusResponse.receiving as ExtendedTransactionInfo\n\n // Update action status\n statusManager.updateAction(step, action.type, 'DONE', {\n chainId: statusReceiving?.chainId || toChain.id,\n substatus: statusResponse.substatus,\n substatusMessage: statusResponse.substatusMessage,\n txHash: statusReceiving?.txHash,\n txLink:\n statusReceiving?.txLink ||\n `${toChain.metamask.blockExplorerUrls[0]}tx/${statusReceiving?.txHash}`,\n })\n\n // Update execution status\n statusManager.updateExecution(step, {\n status: 'DONE',\n ...(statusResponse.sending.amount && {\n fromAmount: statusResponse.sending.amount,\n }),\n ...(statusReceiving?.amount && { toAmount: statusReceiving.amount }),\n ...(statusReceiving?.token && { toToken: statusReceiving.token }),\n internalTxLink: statusResponse?.lifiExplorerLink,\n externalTxLink: statusResponse?.bridgeExplorerLink,\n gasCosts: [\n {\n amount: statusResponse.sending.gasAmount,\n amountUSD: statusResponse.sending.gasAmountUSD,\n token: statusResponse.sending.gasToken,\n estimate: statusResponse.sending.gasUsed,\n limit: statusResponse.sending.gasUsed,\n price: statusResponse.sending.gasPrice,\n type: 'SEND',\n },\n ],\n })\n\n return { status: 'COMPLETED' }\n } catch (e: any) {\n // `stopRouteExecution` ended the wait; the outcome of the transaction is\n // still unknown. Pause like a stopped step, with no write: the stored\n // action keeps its hash, and a resume waits for it again.\n if (signal?.aborted && isAbortError(e)) {\n return { status: 'PAUSED' }\n }\n const htmlMessage = await getTransactionFailedMessage(\n client,\n step,\n `${toChain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`\n )\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n htmlMessage ??\n 'Failed while waiting for status of destination chain transaction.',\n e\n )\n }\n }\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,+BAAb,cAAkDA,mCAAAA,sBAAsB;CACtE;CAEA,YAAY,YAAiC;EAC3C,MAAM;EACN,KAAK,aAAa;CACpB;CAEA,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,mBACA,SACA,mBACA,WACE;EAIJ,IAAI;EACJ,IAAI;GACF,MAAM,qBAAqB,cAAc,WACvC,MACA,oBAAoB,gBAAgB,MACtC;GACA,kBAAkB,oBAAoB,UAAU,oBAAoB;GAGpE,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,gCAAgC;GAGlD,MAAM,SAAS,cAAc,iBAAiB;IAC5C;IACA,MAAM,KAAK;IACX,SACE,KAAK,eAAe,oBAChB,KAAK,OAAO,YACZ,KAAK,OAAO;IAClB,QAAQ;GACV,CAAC;GAED,MAAM,iBAAkB,MAAMC,oDAAAA,yBAC5B,QACA,eACA,iBACA,MACA,OAAO,MACP,mBACA,MACF;GAEA,MAAM,kBACJ,eAAe;GAGjB,cAAc,aAAa,MAAM,OAAO,MAAM,QAAQ;IACpD,SAAS,iBAAiB,WAAW,QAAQ;IAC7C,WAAW,eAAe;IAC1B,kBAAkB,eAAe;IACjC,QAAQ,iBAAiB;IACzB,QACE,iBAAiB,UACjB,GAAG,QAAQ,SAAS,kBAAkB,GAAG,KAAK,iBAAiB;GACnE,CAAC;GAGD,cAAc,gBAAgB,MAAM;IAClC,QAAQ;IACR,GAAI,eAAe,QAAQ,UAAU,EACnC,YAAY,eAAe,QAAQ,OACrC;IACA,GAAI,iBAAiB,UAAU,EAAE,UAAU,gBAAgB,OAAO;IAClE,GAAI,iBAAiB,SAAS,EAAE,SAAS,gBAAgB,MAAM;IAC/D,gBAAgB,gBAAgB;IAChC,gBAAgB,gBAAgB;IAChC,UAAU,CACR;KACE,QAAQ,eAAe,QAAQ;KAC/B,WAAW,eAAe,QAAQ;KAClC,OAAO,eAAe,QAAQ;KAC9B,UAAU,eAAe,QAAQ;KACjC,OAAO,eAAe,QAAQ;KAC9B,OAAO,eAAe,QAAQ;KAC9B,MAAM;IACR,CACF;GACF,CAAC;GAED,OAAO,EAAE,QAAQ,YAAY;EAC/B,SAAS,GAAQ;GAIf,IAAI,QAAQ,WAAWC,oBAAAA,aAAa,CAAC,GACnC,OAAO,EAAE,QAAQ,SAAS;GAE5B,MAAM,cAAc,MAAMC,oCAAAA,4BACxB,QACA,MACA,GAAG,QAAQ,SAAS,kBAAkB,GAAG,KAAK,iBAChD;GACA,MAAM,IAAIC,sBAAAA,iBAAAA,MAER,eACE,qEACF,CACF;EACF;CACF;AACF"}
@@ -52,6 +52,8 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
52
52
  const tokens = reqs.map((r) => r.token);
53
53
  const slippage = step.action.slippage ?? 0;
54
54
  const slippageScaled = BigInt(Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION)));
55
+ const controller = new AbortController();
56
+ const { signal } = controller;
55
57
  await require_utils_withTimeout.withTimeout(async () => {
56
58
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
57
59
  const isFinal = attempt === 5;
@@ -60,9 +62,10 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
60
62
  balances = await provider.getBalance(client, walletAddress, tokens);
61
63
  } catch (error) {
62
64
  if (isFinal) throw new require_errors_errors.BalanceError("Could not read wallet balance.", error);
63
- await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt);
65
+ await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal });
64
66
  continue;
65
67
  }
68
+ if (signal.aborted) return;
66
69
  const balanceByAddress = new Map(balances.map((b) => [b.address.toLowerCase(), b.amount]));
67
70
  const unknown = [];
68
71
  const insufficient = [];
@@ -95,12 +98,12 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
95
98
  });
96
99
  throw new require_errors_errors.BalanceError("The balance is too low.", /* @__PURE__ */ new Error(`${lines.join(" ")} No funds have been sent.`));
97
100
  }
98
- await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt);
101
+ await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal });
99
102
  }
100
103
  }, {
101
104
  timeout: OVERALL_TIMEOUT_MS,
102
105
  errorInstance: new require_errors_errors.BalanceError("Could not read wallet balance.")
103
- });
106
+ }).finally(() => controller.abort());
104
107
  };
105
108
  //#endregion
106
109
  exports.checkBalance = checkBalance;
@@ -1 +1 @@
1
- {"version":3,"file":"checkBalance.js","names":["withTimeout","BalanceError","sleep","formatUnits"],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,CAAC,MACd;CAClB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;GAEA,IAAI,SAAS;IACX,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAID,sBAAAA,aACR,kDACA,IAAI,MACF,+BAA+B,QAC5B,KAAK,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CACjC,KAAK,IAAI,EAAE,EAChB,CACF;IAEF,MAAM,QAAQ,aAAa,KAAK,EAAE,KAAK,WAAW;KAChD,MAAM,SAASE,0BAAAA,YAAY,KAAK,GAAG,GAAG,IAAI,MAAM,QAAQ;KACxD,MAAM,UAAUA,0BAAAA,YAAY,MAAM,IAAI,MAAM,QAAQ;KACpD,MAAM,SAAS,IAAI,MAAM;KAIzB,OAAO,IAAI,aAAa,KACpB,QAAQ,OAAO,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;IAC3F,CAAC;IACD,MAAM,IAAIF,sBAAAA,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAMC,oBAAAA,MAAM,kBAAkB,KAAK,OAAO;EAC5C;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAID,sBAAAA,aAAa,gCAAgC;CAClE,CACF;AACF"}
1
+ {"version":3,"file":"checkBalance.js","names":["withTimeout","BalanceError","sleep","formatUnits"],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n // Aborted once `withTimeout` settles. A timeout rejects at once, but the\n // loop keeps running; the signal stops it before it can change `step`.\n const controller = new AbortController()\n const { signal } = controller\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal })\n continue\n }\n if (signal.aborted) {\n return\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal })\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n ).finally(() => controller.abort())\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region src/core/tasks/helpers/getStepStatusRequest.d.ts
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 declare function getStepStatusRequest(step: LiFiStep, txHash: string): GetStatusRequestExtended;
9
+ //#endregion
10
+ //# sourceMappingURL=getStepStatusRequest.d.ts.map
@@ -0,0 +1,20 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/core/tasks/helpers/getStepStatusRequest.ts
3
+ /**
4
+ * The status request for a transaction of a step. The status poll and the
5
+ * status-API veto send the same fields, so both build them here.
6
+ */
7
+ function getStepStatusRequest(step, txHash) {
8
+ return {
9
+ fromChain: step.action.fromChainId,
10
+ fromAddress: step.action.fromAddress,
11
+ toChain: step.action.toChainId,
12
+ txHash,
13
+ ...step.tool !== "custom" && { bridge: step.tool },
14
+ ...step.transactionId && { transactionId: step.transactionId }
15
+ };
16
+ }
17
+ //#endregion
18
+ exports.getStepStatusRequest = getStepStatusRequest;
19
+
20
+ //# sourceMappingURL=getStepStatusRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getStepStatusRequest.js","names":[],"sources":["../../../../../src/core/tasks/helpers/getStepStatusRequest.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { GetStatusRequestExtended } from '../../../types/actions.js'\n\n/**\n * The status request for a transaction of a step. The status poll and the\n * status-API veto send the same fields, so both build them here.\n */\nexport function getStepStatusRequest(\n step: LiFiStep,\n txHash: string\n): GetStatusRequestExtended {\n return {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n }\n}\n"],"mappings":";;;;;;AAOA,SAAgB,qBACd,MACA,QAC0B;CAC1B,OAAO;EACL,WAAW,KAAK,OAAO;EACvB,aAAa,KAAK,OAAO;EACzB,SAAS,KAAK,OAAO;EACrB;EACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,KAAK;EAClD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,cAAc;CAChE;AACF"}
@@ -0,0 +1,21 @@
1
+ import { SDKClient } from "../../../types/core.js";
2
+ import { LiFiStep } from "@lifi/types";
3
+ //#region src/core/tasks/helpers/isKnownToStatusApi.d.ts
4
+ /**
5
+ * The status-API veto of the "dropped" rule. True only when the API answers
6
+ * with a status other than NOT_FOUND: the transaction then exists and is never
7
+ * dropped. The API answers HTTP 404 for unknown hashes and also for landed
8
+ * transactions it does not index, so a miss or an error says nothing and only
9
+ * a chain node whose history covers the signing time can prove absence.
10
+ *
11
+ * No answer within `STATUS_API_TIMEOUT_MS` is a miss too, so a hung API cannot
12
+ * stop the wait task at its final verdict. The timer aborts the request and
13
+ * also settles the call, in case a request interceptor dropped the signal.
14
+ * Not `AbortSignal.timeout`: a published SDK should not raise its runtime
15
+ * floor for it; one controller and one timer cover it.
16
+ *
17
+ * @internal
18
+ */
19
+ export declare function isKnownToStatusApi(client: SDKClient, step: LiFiStep, txHash: string): Promise<boolean>;
20
+ //#endregion
21
+ //# sourceMappingURL=isKnownToStatusApi.d.ts.map
@@ -0,0 +1,44 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_actions_getStatus = require("../../../actions/getStatus.js");
3
+ const require_core_tasks_helpers_getStepStatusRequest = require("./getStepStatusRequest.js");
4
+ //#region src/core/tasks/helpers/isKnownToStatusApi.ts
5
+ /** The status API gets this long before its silence counts as a miss. */
6
+ const STATUS_API_TIMEOUT_MS = 1e4;
7
+ /**
8
+ * The status-API veto of the "dropped" rule. True only when the API answers
9
+ * with a status other than NOT_FOUND: the transaction then exists and is never
10
+ * dropped. The API answers HTTP 404 for unknown hashes and also for landed
11
+ * transactions it does not index, so a miss or an error says nothing and only
12
+ * a chain node whose history covers the signing time can prove absence.
13
+ *
14
+ * No answer within `STATUS_API_TIMEOUT_MS` is a miss too, so a hung API cannot
15
+ * stop the wait task at its final verdict. The timer aborts the request and
16
+ * also settles the call, in case a request interceptor dropped the signal.
17
+ * Not `AbortSignal.timeout`: a published SDK should not raise its runtime
18
+ * floor for it; one controller and one timer cover it.
19
+ *
20
+ * @internal
21
+ */
22
+ async function isKnownToStatusApi(client, step, txHash) {
23
+ const controller = new AbortController();
24
+ let timer;
25
+ const timeout = new Promise((_, reject) => {
26
+ timer = setTimeout(() => {
27
+ const error = /* @__PURE__ */ new Error(`The status API did not answer within ${STATUS_API_TIMEOUT_MS}ms.`);
28
+ controller.abort(error);
29
+ reject(error);
30
+ }, STATUS_API_TIMEOUT_MS);
31
+ timer.unref?.();
32
+ });
33
+ try {
34
+ return (await Promise.race([require_actions_getStatus.getStatus(client, require_core_tasks_helpers_getStepStatusRequest.getStepStatusRequest(step, txHash), { signal: controller.signal }), timeout])).status !== "NOT_FOUND";
35
+ } catch (_) {
36
+ return false;
37
+ } finally {
38
+ clearTimeout(timer);
39
+ }
40
+ }
41
+ //#endregion
42
+ exports.isKnownToStatusApi = isKnownToStatusApi;
43
+
44
+ //# sourceMappingURL=isKnownToStatusApi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isKnownToStatusApi.js","names":["getStatus","getStepStatusRequest"],"sources":["../../../../../src/core/tasks/helpers/isKnownToStatusApi.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { getStepStatusRequest } from './getStepStatusRequest.js'\n\n/** The status API gets this long before its silence counts as a miss. */\nconst STATUS_API_TIMEOUT_MS = 10_000\n\n/**\n * The status-API veto of the \"dropped\" rule. True only when the API answers\n * with a status other than NOT_FOUND: the transaction then exists and is never\n * dropped. The API answers HTTP 404 for unknown hashes and also for landed\n * transactions it does not index, so a miss or an error says nothing and only\n * a chain node whose history covers the signing time can prove absence.\n *\n * No answer within `STATUS_API_TIMEOUT_MS` is a miss too, so a hung API cannot\n * stop the wait task at its final verdict. The timer aborts the request and\n * also settles the call, in case a request interceptor dropped the signal.\n * Not `AbortSignal.timeout`: a published SDK should not raise its runtime\n * floor for it; one controller and one timer cover it.\n *\n * @internal\n */\nexport async function isKnownToStatusApi(\n client: SDKClient,\n step: LiFiStep,\n txHash: string\n): Promise<boolean> {\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new Error(\n `The status API did not answer within ${STATUS_API_TIMEOUT_MS}ms.`\n )\n controller.abort(error)\n reject(error)\n }, STATUS_API_TIMEOUT_MS)\n // A pending timer keeps Node's event loop alive. The `finally` clears it;\n // the unref only covers a path that skips it.\n const handle = timer as unknown as { unref?: () => void }\n handle.unref?.()\n })\n try {\n const response = await Promise.race([\n getStatus(client, getStepStatusRequest(step, txHash), {\n signal: controller.signal,\n }),\n timeout,\n ])\n return response.status !== 'NOT_FOUND'\n } catch (_) {\n return false\n } finally {\n clearTimeout(timer)\n }\n}\n"],"mappings":";;;;;AAMA,MAAM,wBAAwB;;;;;;;;;;;;;;;;AAiB9B,eAAsB,mBACpB,QACA,MACA,QACkB;CAClB,MAAM,aAAa,IAAI,gBAAgB;CACvC,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,GAAG,WAAW;EAChD,QAAQ,iBAAiB;GACvB,MAAM,wBAAQ,IAAI,MAChB,wCAAwC,sBAAsB,IAChE;GACA,WAAW,MAAM,KAAK;GACtB,OAAO,KAAK;EACd,GAAG,qBAAqB;EAIxB,MAAO,QAAQ;CACjB,CAAC;CACD,IAAI;EAOF,QAAO,MANgB,QAAQ,KAAK,CAClCA,0BAAAA,UAAU,QAAQC,gDAAAA,qBAAqB,MAAM,MAAM,GAAG,EACpD,QAAQ,WAAW,OACrB,CAAC,GACD,OACF,CAAC,EAAA,CACe,WAAW;CAC7B,SAAS,GAAG;EACV,OAAO;CACT,UAAU;EACR,aAAa,KAAK;CACpB;AACF"}
@@ -2,6 +2,27 @@ import { ExecutionActionType, SDKClient } from "../../../types/core.js";
2
2
  import { StatusManager } from "../../StatusManager.js";
3
3
  import { LiFiStep, StatusResponse } from "@lifi/types";
4
4
  //#region src/core/tasks/helpers/waitForTransactionStatus.d.ts
5
- export declare function waitForTransactionStatus(client: SDKClient, statusManager: StatusManager, txHash: string, step: LiFiStep, actionType: ExecutionActionType, interval?: number): Promise<StatusResponse>;
5
+ type Waiter = {
6
+ resolve: (status: StatusResponse) => void;
7
+ reject: (error: unknown) => void;
8
+ };
9
+ /** The `/status` poll of one transaction hash, shared by all its callers. */
10
+ type StatusPoll = {
11
+ promise: Promise<StatusResponse>;
12
+ controller: AbortController;
13
+ /** Callers with a signal that still wait, once the first one joined. */
14
+ waiters?: Set<Waiter>;
15
+ /** A caller without a signal joined, so the poll runs until it settles. */
16
+ pinned: boolean;
17
+ };
18
+ /** @internal The running poll per transaction hash. Exported for tests. */
19
+ export declare const TRANSACTION_HASH_OBSERVERS: Partial<Record<string, StatusPoll>>;
20
+ /**
21
+ * Waits for the final status of `txHash`. Callers that wait for the same hash
22
+ * share one poll. A caller whose `signal` aborts leaves at once with the abort
23
+ * reason; the poll itself ends only when every caller with a signal has left
24
+ * and no caller without a signal joined it.
25
+ */
26
+ export declare function waitForTransactionStatus(client: SDKClient, statusManager: StatusManager, txHash: string, step: LiFiStep, actionType: ExecutionActionType, interval?: number, signal?: AbortSignal): Promise<StatusResponse>;
6
27
  //#endregion
7
28
  //# sourceMappingURL=waitForTransactionStatus.d.ts.map