@lifi/sdk 4.10.0 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +9 -0
  3. package/dist/cjs/client/createClient.js +6 -4
  4. package/dist/cjs/client/createClient.js.map +1 -1
  5. package/dist/cjs/client/findProvider.d.ts +10 -0
  6. package/dist/cjs/client/findProvider.js +11 -0
  7. package/dist/cjs/client/findProvider.js.map +1 -0
  8. package/dist/cjs/core/BaseStepExecutor.d.ts +1 -1
  9. package/dist/cjs/core/BaseStepExecutor.js +21 -9
  10. package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
  11. package/dist/cjs/core/StatusManager.d.ts +10 -0
  12. package/dist/cjs/core/StatusManager.js +105 -3
  13. package/dist/cjs/core/StatusManager.js.map +1 -1
  14. package/dist/cjs/core/execution.js +30 -14
  15. package/dist/cjs/core/execution.js.map +1 -1
  16. package/dist/cjs/core/executionState.d.ts +34 -2
  17. package/dist/cjs/core/executionState.js +44 -1
  18. package/dist/cjs/core/executionState.js.map +1 -1
  19. package/dist/cjs/core/prepareRestart.js +14 -6
  20. package/dist/cjs/core/prepareRestart.js.map +1 -1
  21. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js +4 -2
  22. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  23. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  24. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js +20 -0
  25. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  26. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  27. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js +44 -0
  28. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  29. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  30. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js +76 -17
  31. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  32. package/dist/cjs/core/transactionState.d.ts +121 -0
  33. package/dist/cjs/core/transactionState.js +164 -0
  34. package/dist/cjs/core/transactionState.js.map +1 -0
  35. package/dist/cjs/errors/errors.d.ts +13 -2
  36. package/dist/cjs/errors/errors.js +5 -2
  37. package/dist/cjs/errors/errors.js.map +1 -1
  38. package/dist/cjs/index.d.ts +5 -2
  39. package/dist/cjs/index.js +14 -0
  40. package/dist/cjs/types/core.d.ts +49 -3
  41. package/dist/cjs/types/execution.d.ts +8 -0
  42. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  43. package/dist/cjs/utils/waitForResult.d.ts +3 -1
  44. package/dist/cjs/utils/waitForResult.js +15 -10
  45. package/dist/cjs/utils/waitForResult.js.map +1 -1
  46. package/dist/cjs/version.d.ts +1 -1
  47. package/dist/cjs/version.js +1 -1
  48. package/dist/cjs/version.js.map +1 -1
  49. package/dist/esm/actions/getRoutes.d.ts.map +1 -1
  50. package/dist/esm/actions/index.d.ts.map +1 -1
  51. package/dist/esm/client/createClient.d.ts.map +1 -1
  52. package/dist/esm/client/createClient.js +6 -4
  53. package/dist/esm/client/createClient.js.map +1 -1
  54. package/dist/esm/client/findProvider.d.ts +10 -0
  55. package/dist/esm/client/findProvider.d.ts.map +1 -0
  56. package/dist/esm/client/findProvider.js +10 -0
  57. package/dist/esm/client/findProvider.js.map +1 -0
  58. package/dist/esm/core/BaseStepExecutor.d.ts +1 -1
  59. package/dist/esm/core/BaseStepExecutor.d.ts.map +1 -1
  60. package/dist/esm/core/BaseStepExecutor.js +22 -10
  61. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  62. package/dist/esm/core/StatusManager.d.ts +10 -0
  63. package/dist/esm/core/StatusManager.d.ts.map +1 -1
  64. package/dist/esm/core/StatusManager.js +105 -3
  65. package/dist/esm/core/StatusManager.js.map +1 -1
  66. package/dist/esm/core/execution.d.ts.map +1 -1
  67. package/dist/esm/core/execution.js +30 -14
  68. package/dist/esm/core/execution.js.map +1 -1
  69. package/dist/esm/core/executionState.d.ts +34 -2
  70. package/dist/esm/core/executionState.d.ts.map +1 -1
  71. package/dist/esm/core/executionState.js +44 -1
  72. package/dist/esm/core/executionState.js.map +1 -1
  73. package/dist/esm/core/prepareRestart.d.ts.map +1 -1
  74. package/dist/esm/core/prepareRestart.js +14 -6
  75. package/dist/esm/core/prepareRestart.js.map +1 -1
  76. package/dist/esm/core/tasks/WaitForTransactionStatusTask.d.ts.map +1 -1
  77. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +4 -2
  78. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  79. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  80. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts.map +1 -0
  81. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js +19 -0
  82. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  83. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  84. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts.map +1 -0
  85. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js +43 -0
  86. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  87. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  88. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts.map +1 -1
  89. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js +76 -18
  90. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  91. package/dist/esm/core/transactionState.d.ts +121 -0
  92. package/dist/esm/core/transactionState.d.ts.map +1 -0
  93. package/dist/esm/core/transactionState.js +152 -0
  94. package/dist/esm/core/transactionState.js.map +1 -0
  95. package/dist/esm/errors/errors.d.ts +13 -2
  96. package/dist/esm/errors/errors.d.ts.map +1 -1
  97. package/dist/esm/errors/errors.js +5 -2
  98. package/dist/esm/errors/errors.js.map +1 -1
  99. package/dist/esm/index.d.ts +5 -2
  100. package/dist/esm/index.js +4 -1
  101. package/dist/esm/types/actions.d.ts.map +1 -1
  102. package/dist/esm/types/core.d.ts +49 -3
  103. package/dist/esm/types/core.d.ts.map +1 -1
  104. package/dist/esm/types/execution.d.ts +8 -0
  105. package/dist/esm/types/execution.d.ts.map +1 -1
  106. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  107. package/dist/esm/utils/waitForResult.d.ts +3 -1
  108. package/dist/esm/utils/waitForResult.d.ts.map +1 -1
  109. package/dist/esm/utils/waitForResult.js +15 -10
  110. package/dist/esm/utils/waitForResult.js.map +1 -1
  111. package/dist/esm/version.d.ts +1 -1
  112. package/dist/esm/version.js +1 -1
  113. package/dist/esm/version.js.map +1 -1
  114. package/package.json +2 -2
  115. package/src/client/createClient.ts +12 -4
  116. package/src/client/findProvider.ts +21 -0
  117. package/src/core/BaseStepExecutor.ts +40 -6
  118. package/src/core/StatusManager.ts +211 -2
  119. package/src/core/execution.ts +69 -20
  120. package/src/core/executionState.ts +84 -1
  121. package/src/core/prepareRestart.ts +29 -13
  122. package/src/core/tasks/WaitForTransactionStatusTask.ts +10 -1
  123. package/src/core/tasks/helpers/getStepStatusRequest.ts +20 -0
  124. package/src/core/tasks/helpers/isKnownToStatusApi.ts +57 -0
  125. package/src/core/tasks/helpers/waitForTransactionStatus.ts +128 -17
  126. package/src/core/transactionState.ts +194 -0
  127. package/src/errors/errors.ts +21 -2
  128. package/src/index.ts +14 -0
  129. package/src/types/core.ts +50 -3
  130. package/src/types/execution.ts +8 -0
  131. package/src/utils/waitForResult.ts +16 -6
  132. package/src/version.ts +1 -1
@@ -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 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,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAE7C,IAAI,WAIE;MAAA,CAHoB,UAAU,UAAU,MACzC,aAAa,CAAC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AChC,QACA,MACA,EAAE,WACJ;IACF,OACE,MAAM;GAEV;GAGA,IAAI,aAAa,WAAW,WAAW,QACrC,mBAAmB,KAAK;GAI1B,IAAI,CAAC,aAAa,gBAChB,OAAO;EAEX,SAAS,GAAG;GACV,mBAAmB,KAAK;GACxB,MAAM;EACR;CACF;CAGA,4BAAA,eAAe,OAAO,MAAM,EAAE;CAC9B,OAAO;AACT;;;;;;AAOA,MAAa,wBACX,OACA,YACS;CACT,MAAM,YAAYF,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAC7C,IAAI,CAAC,WACH;CAGF,IAAI,yBAAyB,SAC3B,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB,CAAC,SAAS;EAC5B,cAAc;CAChB,CAAC;CAIL,UAAU,mBAAmB;EAC3B,GAAG,UAAU;EACb,GAAG;CACL;AACF;;;;;;AAOA,MAAa,sBAAsB,UAAwB;CACzD,MAAM,YAAYA,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAC7C,IAAI,CAAC,WACH,OAAO;CAGT,KAAK,MAAM,YAAY,UAAU,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,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAE7C,IAAI,WAIE;MAAA,CAHoB,UAAU,UAAU,MACzC,aAAa,CAAC,SAAS,cAEP,GAAG;GAEpB,qBAAqB,OAAO,EAC1B,qBAAqB,kBAAkB,oBACzC,CAAC;GACD,IAAI,CAAC,UAAU,SAEb,MAAM,IAAI,MAAM,oCAAoC;GAEtD,OAAO,UAAU;EACnB;;CAKF,MAAM,eAAe,gBAA+B,KAAK;CACzD,4BAAA,eAAe,YAAY;CAE3B,OAAO,aAAa,QAAQ,cAAc,gBAAgB;AAC5D;;;;;;AAOA,MAAM,iBAAiB,UACrBA,4BAAAA,eAAe,IAAI,MAAM,EAAE,CAAC,EAAE,UAAU;AAE1C,MAAM,eAAe,OACnB,QACA,UAC2B;CAE3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,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AAK,GAClE,mBAAmB,KAAK;GAI1B,IAAI,CAAC,aAAa,gBAChB,OAAO;EAEX,SAAS,GAAG;GACV,IAAI,cAAc,KAAK,GACrB,mBAAmB,KAAK;GAE1B,MAAM;EACR;CACF;CAGA,IAAI,cAAc,KAAK,GACrB,4BAAA,eAAe,OAAO,MAAM,EAAE;CAEhC,OAAO;AACT;;;;;;AAOA,MAAa,wBACX,OACA,YACS;CACT,MAAM,YAAYF,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAC7C,IAAI,CAAC,WACH;CAGF,IAAI,yBAAyB,SAC3B,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB,CAAC,SAAS;EAC5B,cAAc;CAChB,CAAC;CAIL,UAAU,mBAAmB;EAC3B,GAAG,UAAU;EACb,GAAG;CACL;AACF;;;;;;AAOA,MAAa,sBAAsB,UAAwB;CACzD,MAAM,YAAYA,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAC7C,IAAI,CAAC,WACH,OAAO;CAGT,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,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;EAC3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,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;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R,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"}
@@ -0,0 +1,10 @@
1
+ import { GetStatusRequestExtended } from "../../../types/actions.js";
2
+ import { LiFiStep } from "@lifi/types";
3
+ //#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
@@ -1,20 +1,23 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_errors_errors = require("../../../errors/errors.js");
3
+ const require_utils_abort = require("../../../utils/abort.js");
3
4
  const require_actions_getStatus = require("../../../actions/getStatus.js");
4
5
  const require_core_actionMessages = require("../../actionMessages.js");
6
+ const require_core_tasks_helpers_getStepStatusRequest = require("./getStepStatusRequest.js");
5
7
  const require_utils_waitForResult = require("../../../utils/waitForResult.js");
6
8
  //#region src/core/tasks/helpers/waitForTransactionStatus.ts
9
+ /** @internal The running poll per transaction hash. Exported for tests. */
7
10
  const TRANSACTION_HASH_OBSERVERS = {};
8
- async function waitForTransactionStatus(client, statusManager, txHash, step, actionType, interval = 5e3) {
9
- const _getStatus = () => {
10
- return require_actions_getStatus.getStatus(client, {
11
- fromChain: step.action.fromChainId,
12
- fromAddress: step.action.fromAddress,
13
- toChain: step.action.toChainId,
14
- txHash,
15
- ...step.tool !== "custom" && { bridge: step.tool },
16
- ...step.transactionId && { transactionId: step.transactionId }
17
- }).then((statusResponse) => {
11
+ /**
12
+ * Waits for the final status of `txHash`. Callers that wait for the same hash
13
+ * share one poll. A caller whose `signal` aborts leaves at once with the abort
14
+ * reason; the poll itself ends only when every caller with a signal has left
15
+ * and no caller without a signal joined it.
16
+ */
17
+ async function waitForTransactionStatus(client, statusManager, txHash, step, actionType, interval = 5e3, signal) {
18
+ if (signal?.aborted) throw require_utils_abort.getAbortError(signal);
19
+ const _getStatus = (pollSignal) => {
20
+ return require_actions_getStatus.getStatus(client, require_core_tasks_helpers_getStepStatusRequest.getStepStatusRequest(step, txHash), { signal: pollSignal }).then((statusResponse) => {
18
21
  switch (statusResponse.status) {
19
22
  case "DONE": return statusResponse;
20
23
  case "PENDING": {
@@ -33,18 +36,74 @@ async function waitForTransactionStatus(client, statusManager, txHash, step, act
33
36
  if (process.env.NODE_ENV === "development") console.debug("Fetching status from backend failed.", e);
34
37
  });
35
38
  };
36
- let status = TRANSACTION_HASH_OBSERVERS[txHash];
37
- if (!status) {
38
- status = require_utils_waitForResult.waitForResult(_getStatus, interval).finally(() => {
39
- delete TRANSACTION_HASH_OBSERVERS[txHash];
40
- });
41
- TRANSACTION_HASH_OBSERVERS[txHash] = status;
39
+ let poll = TRANSACTION_HASH_OBSERVERS[txHash];
40
+ if (!poll) {
41
+ const controller = new AbortController();
42
+ const promise = require_utils_waitForResult.waitForResult(() => _getStatus(controller.signal), interval, void 0, void 0, controller.signal).finally(() => removePoll(txHash, promise));
43
+ poll = {
44
+ promise,
45
+ controller,
46
+ pinned: false
47
+ };
48
+ TRANSACTION_HASH_OBSERVERS[txHash] = poll;
42
49
  }
43
- const resolvedStatus = await status;
50
+ const resolvedStatus = await joinPoll(txHash, poll, signal);
44
51
  if (!("receiving" in resolvedStatus)) throw new require_errors_errors.ServerError("Status doesn't contain destination chain information.");
45
52
  return resolvedStatus;
46
53
  }
54
+ function joinPoll(txHash, poll, signal) {
55
+ if (!signal) {
56
+ poll.pinned = true;
57
+ return poll.promise;
58
+ }
59
+ const waiters = poll.waiters ?? subscribe(poll);
60
+ return new Promise((resolve, reject) => {
61
+ const waiter = {
62
+ resolve: (status) => {
63
+ signal.removeEventListener("abort", leave);
64
+ resolve(status);
65
+ },
66
+ reject: (error) => {
67
+ signal.removeEventListener("abort", leave);
68
+ reject(error);
69
+ }
70
+ };
71
+ const leave = () => {
72
+ signal.removeEventListener("abort", leave);
73
+ waiters.delete(waiter);
74
+ const reason = require_utils_abort.getAbortError(signal);
75
+ reject(reason);
76
+ if (!poll.pinned && waiters.size === 0) {
77
+ removePoll(txHash, poll.promise);
78
+ poll.controller.abort(reason);
79
+ }
80
+ };
81
+ waiters.add(waiter);
82
+ signal.addEventListener("abort", leave, { once: true });
83
+ if (signal.aborted) leave();
84
+ });
85
+ }
86
+ /**
87
+ * Hands the result to the callers with a signal, through one reaction per
88
+ * poll, so a caller that leaves holds nothing here. It also handles the
89
+ * rejection of a poll that every caller left.
90
+ */
91
+ function subscribe(poll) {
92
+ const waiters = /* @__PURE__ */ new Set();
93
+ poll.waiters = waiters;
94
+ poll.promise.then((status) => {
95
+ for (const waiter of waiters) waiter.resolve(status);
96
+ }, (error) => {
97
+ for (const waiter of waiters) waiter.reject(error);
98
+ });
99
+ return waiters;
100
+ }
101
+ /** Drops the entry for `txHash` only while it still holds this poll. */
102
+ function removePoll(txHash, promise) {
103
+ if (TRANSACTION_HASH_OBSERVERS[txHash]?.promise === promise) delete TRANSACTION_HASH_OBSERVERS[txHash];
104
+ }
47
105
  //#endregion
106
+ exports.TRANSACTION_HASH_OBSERVERS = TRANSACTION_HASH_OBSERVERS;
48
107
  exports.waitForTransactionStatus = waitForTransactionStatus;
49
108
 
50
109
  //# sourceMappingURL=waitForTransactionStatus.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"waitForTransactionStatus.js","names":["getStatus","getSubstatusMessage","waitForResult","ServerError"],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\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 .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING': {\n const pendingStatus = statusResponse as FullStatusData\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n // Most bridges implement no `getExplorerLink`, so fall back to\n // the LI.FI explorer rather than leave the user with no link.\n txLink:\n pendingStatus.bridgeExplorerLink ??\n pendingStatus.lifiExplorerLink,\n })\n return undefined\n }\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;;AAQA,MAAM,6BAAsE,CAAC;AAE7E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;EAC5D,OAAOA,0BAAAA,UAAU,QAAQ;GACvB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,SAAS,KAAK,OAAO;GACrB;GACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,KAAK;GAClD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,cAAc;EAChE,CAAC,CAAC,CACC,MAAM,mBAAmB;GACxB,QAAQ,eAAe,QAAvB;IACE,KAAK,QACH,OAAO;IACT,KAAK,WAAW;KACd,MAAM,gBAAgB;KACtB,eAAe,aAAa,MAAM,YAAY,WAAW;MACvD,WAAW,eAAe;MAC1B,kBACE,eAAe,oBACfC,4BAAAA,oBACE,eAAe,QACf,eAAe,SACjB;MAGF,QACE,cAAc,sBACd,cAAc;KAClB,CAAC;KACD;IACF;IACA,KAAK,aACH;IACF,SACE,OAAO,QAAQ,OAAO;GAC1B;EACF,CAAC,CAAC,CACD,OAAO,MAAM;GACZ,IAAI,QAAQ,IAAI,aAAa,eAC3B,QAAQ,MAAM,wCAAwC,CAAC;EAG3D,CAAC;CACL;CAEA,IAAI,SAAS,2BAA2B;CAExC,IAAI,CAAC,QAAQ;EACX,SAASC,4BAAAA,cAAc,YAAY,QAAQ,CAAC,CAAC,cAAc;GACzD,OAAO,2BAA2B;EACpC,CAAC;EACD,2BAA2B,UAAU;CACvC;CAEA,MAAM,iBAAiB,MAAM;CAE7B,IAAI,EAAE,eAAe,iBACnB,MAAM,IAAIC,sBAAAA,YACR,uDACF;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"waitForTransactionStatus.js","names":["getAbortError","getStatus","getStepStatusRequest","getSubstatusMessage","waitForResult","ServerError"],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { getAbortError } from '../../../utils/abort.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\nimport { getStepStatusRequest } from './getStepStatusRequest.js'\n\ntype Waiter = {\n resolve: (status: StatusResponse) => void\n reject: (error: unknown) => void\n}\n\n/** The `/status` poll of one transaction hash, shared by all its callers. */\ntype StatusPoll = {\n promise: Promise<StatusResponse>\n controller: AbortController\n /** Callers with a signal that still wait, once the first one joined. */\n waiters?: Set<Waiter>\n /** A caller without a signal joined, so the poll runs until it settles. */\n pinned: boolean\n}\n\n/** @internal The running poll per transaction hash. Exported for tests. */\nexport const TRANSACTION_HASH_OBSERVERS: Partial<Record<string, StatusPoll>> =\n {}\n\n/**\n * Waits for the final status of `txHash`. Callers that wait for the same hash\n * share one poll. A caller whose `signal` aborts leaves at once with the abort\n * reason; the poll itself ends only when every caller with a signal has left\n * and no caller without a signal joined it.\n */\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000,\n signal?: AbortSignal\n): Promise<StatusResponse> {\n if (signal?.aborted) {\n throw getAbortError(signal)\n }\n\n const _getStatus = (\n pollSignal: AbortSignal\n ): Promise<StatusResponse | undefined> => {\n return getStatus(client, getStepStatusRequest(step, txHash), {\n signal: pollSignal,\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING': {\n const pendingStatus = statusResponse as FullStatusData\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n // Most bridges implement no `getExplorerLink`, so fall back to\n // the LI.FI explorer rather than leave the user with no link.\n txLink:\n pendingStatus.bridgeExplorerLink ??\n pendingStatus.lifiExplorerLink,\n })\n return undefined\n }\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let poll = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!poll) {\n const controller = new AbortController()\n const promise: Promise<StatusResponse> = waitForResult(\n () => _getStatus(controller.signal),\n interval,\n undefined,\n undefined,\n controller.signal\n ).finally(() => removePoll(txHash, promise))\n poll = { promise, controller, pinned: false }\n TRANSACTION_HASH_OBSERVERS[txHash] = poll\n }\n\n const resolvedStatus = await joinPoll(txHash, poll, signal)\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n\nfunction joinPoll(\n txHash: string,\n poll: StatusPoll,\n signal: AbortSignal | undefined\n): Promise<StatusResponse> {\n if (!signal) {\n poll.pinned = true\n return poll.promise\n }\n const waiters = poll.waiters ?? subscribe(poll)\n return new Promise<StatusResponse>((resolve, reject) => {\n // Stop listening before settling, so a later abort cannot reach the poll.\n const waiter: Waiter = {\n resolve: (status) => {\n signal.removeEventListener('abort', leave)\n resolve(status)\n },\n reject: (error) => {\n signal.removeEventListener('abort', leave)\n reject(error)\n },\n }\n const leave = (): void => {\n // `leave` can run without the event, so the listener is not always gone.\n signal.removeEventListener('abort', leave)\n waiters.delete(waiter)\n const reason = getAbortError(signal)\n reject(reason)\n if (!poll.pinned && waiters.size === 0) {\n // A caller arriving now must start a new poll, not join this one.\n removePoll(txHash, poll.promise)\n poll.controller.abort(reason)\n }\n }\n waiters.add(waiter)\n signal.addEventListener('abort', leave, { once: true })\n // Defensive; this branch does not run today. The check at the top of\n // `waitForTransactionStatus` throws for an aborted signal, and no await\n // runs between that check and this one. An aborted signal fires no more\n // abort event, so without the branch a caller that joins with an aborted\n // signal would not leave: it would wait, and keep the poll running,\n // until the poll settles.\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 * poll, so a caller that leaves holds nothing here. It also handles the\n * rejection of a poll that every caller left.\n */\nfunction subscribe(poll: StatusPoll): Set<Waiter> {\n const waiters = new Set<Waiter>()\n poll.waiters = waiters\n poll.promise.then(\n (status) => {\n for (const waiter of waiters) {\n waiter.resolve(status)\n }\n },\n (error: unknown) => {\n for (const waiter of waiters) {\n waiter.reject(error)\n }\n }\n )\n return waiters\n}\n\n/** Drops the entry for `txHash` only while it still holds this poll. */\nfunction removePoll(txHash: string, promise: Promise<StatusResponse>): void {\n if (TRANSACTION_HASH_OBSERVERS[txHash]?.promise === promise) {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,MAAa,6BACX,CAAC;;;;;;;AAQH,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACX,QACyB;CACzB,IAAI,QAAQ,SACV,MAAMA,oBAAAA,cAAc,MAAM;CAG5B,MAAM,cACJ,eACwC;EACxC,OAAOC,0BAAAA,UAAU,QAAQC,gDAAAA,qBAAqB,MAAM,MAAM,GAAG,EAC3D,QAAQ,WACV,CAAC,CAAC,CACC,MAAM,mBAAmB;GACxB,QAAQ,eAAe,QAAvB;IACE,KAAK,QACH,OAAO;IACT,KAAK,WAAW;KACd,MAAM,gBAAgB;KACtB,eAAe,aAAa,MAAM,YAAY,WAAW;MACvD,WAAW,eAAe;MAC1B,kBACE,eAAe,oBACfC,4BAAAA,oBACE,eAAe,QACf,eAAe,SACjB;MAGF,QACE,cAAc,sBACd,cAAc;KAClB,CAAC;KACD;IACF;IACA,KAAK,aACH;IACF,SACE,OAAO,QAAQ,OAAO;GAC1B;EACF,CAAC,CAAC,CACD,OAAO,MAAM;GACZ,IAAI,QAAQ,IAAI,aAAa,eAC3B,QAAQ,MAAM,wCAAwC,CAAC;EAG3D,CAAC;CACL;CAEA,IAAI,OAAO,2BAA2B;CAEtC,IAAI,CAAC,MAAM;EACT,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,UAAmCC,4BAAAA,oBACjC,WAAW,WAAW,MAAM,GAClC,UACA,KAAA,GACA,KAAA,GACA,WAAW,MACb,CAAC,CAAC,cAAc,WAAW,QAAQ,OAAO,CAAC;EAC3C,OAAO;GAAE;GAAS;GAAY,QAAQ;EAAM;EAC5C,2BAA2B,UAAU;CACvC;CAEA,MAAM,iBAAiB,MAAM,SAAS,QA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