@lifi/sdk 4.10.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +9 -0
  3. package/dist/cjs/client/createClient.js +6 -4
  4. package/dist/cjs/client/createClient.js.map +1 -1
  5. package/dist/cjs/client/findProvider.d.ts +10 -0
  6. package/dist/cjs/client/findProvider.js +11 -0
  7. package/dist/cjs/client/findProvider.js.map +1 -0
  8. package/dist/cjs/core/BaseStepExecutor.d.ts +1 -1
  9. package/dist/cjs/core/BaseStepExecutor.js +21 -9
  10. package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
  11. package/dist/cjs/core/StatusManager.d.ts +10 -0
  12. package/dist/cjs/core/StatusManager.js +107 -3
  13. package/dist/cjs/core/StatusManager.js.map +1 -1
  14. package/dist/cjs/core/execution.js +30 -14
  15. package/dist/cjs/core/execution.js.map +1 -1
  16. package/dist/cjs/core/executionState.d.ts +34 -2
  17. package/dist/cjs/core/executionState.js +44 -1
  18. package/dist/cjs/core/executionState.js.map +1 -1
  19. package/dist/cjs/core/prepareRestart.js +14 -6
  20. package/dist/cjs/core/prepareRestart.js.map +1 -1
  21. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js +4 -2
  22. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  23. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  24. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js +20 -0
  25. package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  26. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  27. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js +44 -0
  28. package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  29. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  30. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js +76 -17
  31. package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  32. package/dist/cjs/core/transactionState.d.ts +123 -0
  33. package/dist/cjs/core/transactionState.js +167 -0
  34. package/dist/cjs/core/transactionState.js.map +1 -0
  35. package/dist/cjs/errors/constants.d.ts +2 -1
  36. package/dist/cjs/errors/constants.js +1 -0
  37. package/dist/cjs/errors/constants.js.map +1 -1
  38. package/dist/cjs/errors/errors.d.ts +13 -2
  39. package/dist/cjs/errors/errors.js +5 -2
  40. package/dist/cjs/errors/errors.js.map +1 -1
  41. package/dist/cjs/index.d.ts +5 -2
  42. package/dist/cjs/index.js +14 -0
  43. package/dist/cjs/types/core.d.ts +56 -3
  44. package/dist/cjs/types/execution.d.ts +8 -0
  45. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  46. package/dist/cjs/utils/waitForResult.d.ts +3 -1
  47. package/dist/cjs/utils/waitForResult.js +15 -10
  48. package/dist/cjs/utils/waitForResult.js.map +1 -1
  49. package/dist/cjs/version.d.ts +1 -1
  50. package/dist/cjs/version.js +1 -1
  51. package/dist/cjs/version.js.map +1 -1
  52. package/dist/esm/actions/getRoutes.d.ts.map +1 -1
  53. package/dist/esm/actions/index.d.ts.map +1 -1
  54. package/dist/esm/client/createClient.d.ts.map +1 -1
  55. package/dist/esm/client/createClient.js +6 -4
  56. package/dist/esm/client/createClient.js.map +1 -1
  57. package/dist/esm/client/findProvider.d.ts +10 -0
  58. package/dist/esm/client/findProvider.d.ts.map +1 -0
  59. package/dist/esm/client/findProvider.js +10 -0
  60. package/dist/esm/client/findProvider.js.map +1 -0
  61. package/dist/esm/core/BaseStepExecutor.d.ts +1 -1
  62. package/dist/esm/core/BaseStepExecutor.d.ts.map +1 -1
  63. package/dist/esm/core/BaseStepExecutor.js +22 -10
  64. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  65. package/dist/esm/core/StatusManager.d.ts +10 -0
  66. package/dist/esm/core/StatusManager.d.ts.map +1 -1
  67. package/dist/esm/core/StatusManager.js +107 -3
  68. package/dist/esm/core/StatusManager.js.map +1 -1
  69. package/dist/esm/core/execution.d.ts.map +1 -1
  70. package/dist/esm/core/execution.js +30 -14
  71. package/dist/esm/core/execution.js.map +1 -1
  72. package/dist/esm/core/executionState.d.ts +34 -2
  73. package/dist/esm/core/executionState.d.ts.map +1 -1
  74. package/dist/esm/core/executionState.js +44 -1
  75. package/dist/esm/core/executionState.js.map +1 -1
  76. package/dist/esm/core/prepareRestart.d.ts.map +1 -1
  77. package/dist/esm/core/prepareRestart.js +14 -6
  78. package/dist/esm/core/prepareRestart.js.map +1 -1
  79. package/dist/esm/core/tasks/WaitForTransactionStatusTask.d.ts.map +1 -1
  80. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +4 -2
  81. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  82. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
  83. package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts.map +1 -0
  84. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js +19 -0
  85. package/dist/esm/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
  86. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
  87. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts.map +1 -0
  88. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js +43 -0
  89. package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
  90. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
  91. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts.map +1 -1
  92. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js +76 -18
  93. package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
  94. package/dist/esm/core/transactionState.d.ts +123 -0
  95. package/dist/esm/core/transactionState.d.ts.map +1 -0
  96. package/dist/esm/core/transactionState.js +155 -0
  97. package/dist/esm/core/transactionState.js.map +1 -0
  98. package/dist/esm/errors/constants.d.ts +2 -1
  99. package/dist/esm/errors/constants.d.ts.map +1 -1
  100. package/dist/esm/errors/constants.js +1 -0
  101. package/dist/esm/errors/constants.js.map +1 -1
  102. package/dist/esm/errors/errors.d.ts +13 -2
  103. package/dist/esm/errors/errors.d.ts.map +1 -1
  104. package/dist/esm/errors/errors.js +5 -2
  105. package/dist/esm/errors/errors.js.map +1 -1
  106. package/dist/esm/index.d.ts +5 -2
  107. package/dist/esm/index.js +4 -1
  108. package/dist/esm/types/actions.d.ts.map +1 -1
  109. package/dist/esm/types/core.d.ts +56 -3
  110. package/dist/esm/types/core.d.ts.map +1 -1
  111. package/dist/esm/types/execution.d.ts +8 -0
  112. package/dist/esm/types/execution.d.ts.map +1 -1
  113. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  114. package/dist/esm/utils/waitForResult.d.ts +3 -1
  115. package/dist/esm/utils/waitForResult.d.ts.map +1 -1
  116. package/dist/esm/utils/waitForResult.js +15 -10
  117. package/dist/esm/utils/waitForResult.js.map +1 -1
  118. package/dist/esm/version.d.ts +1 -1
  119. package/dist/esm/version.js +1 -1
  120. package/dist/esm/version.js.map +1 -1
  121. package/package.json +2 -2
  122. package/src/client/createClient.ts +12 -4
  123. package/src/client/findProvider.ts +21 -0
  124. package/src/core/BaseStepExecutor.ts +40 -6
  125. package/src/core/StatusManager.ts +214 -2
  126. package/src/core/execution.ts +69 -20
  127. package/src/core/executionState.ts +84 -1
  128. package/src/core/prepareRestart.ts +29 -13
  129. package/src/core/tasks/WaitForTransactionStatusTask.ts +10 -1
  130. package/src/core/tasks/helpers/getStepStatusRequest.ts +20 -0
  131. package/src/core/tasks/helpers/isKnownToStatusApi.ts +57 -0
  132. package/src/core/tasks/helpers/waitForTransactionStatus.ts +128 -17
  133. package/src/core/transactionState.ts +200 -0
  134. package/src/errors/constants.ts +1 -0
  135. package/src/errors/errors.ts +21 -2
  136. package/src/index.ts +14 -0
  137. package/src/types/core.ts +57 -3
  138. package/src/types/execution.ts +8 -0
  139. package/src/utils/waitForResult.ts +16 -6
  140. package/src/version.ts +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # @lifi/sdk
2
2
 
3
+ ## 4.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#514](https://github.com/lifinance/sdk/pull/514) [`5dc9cc5`](https://github.com/lifinance/sdk/commit/5dc9cc5f52b0308962b822cfacd766dbf27bab3c) Thanks [@chybisov](https://github.com/chybisov)! - `LiFiErrorCode` has a new code, `CallBundleNotFound` (1028). A step fails with this code when the wallet has no record of an EIP-5792 bundle. The SDK uses it only when it cannot prove that the wallet did not send the bundle. The outcome stays unknown: the action keeps the bundle id, and a resume waits for the bundle again and does not sign.
8
+
9
+ `ExecutionAction` has a new optional field, `callCount`. It is the number of calls of a batched (EIP-5792) transaction. The Ethereum provider sets it together with `taskId` for a batched transaction.
10
+
11
+ ## 4.11.0
12
+
13
+ ### Minor Changes
14
+
15
+ - [#492](https://github.com/lifinance/sdk/pull/492) [`48af3ae`](https://github.com/lifinance/sdk/commit/48af3aeb250299ef9d2ff9eb79a38a6b8f52d409) Thanks [@chybisov](https://github.com/chybisov)! - `SDKProvider.isAddress` accepts an optional `chainId`. Without it, a provider answers as before. With it, a provider whose chains use different address formats accepts only that chain's format and refuses a chain it does not know. A provider must never forward the chain ID to a library function whose second parameter means something else. A custom provider that assigns such a function directly as `isAddress`, for example viem's `isAddress` or bigmi's `isUTXOAddress`, no longer type-checks; wrap it in a one-argument function, as `EthereumProvider` and `BitcoinProvider` do.
16
+
17
+ A provider can declare the `chainIds` it serves, so a chain-specific provider can sit beside the generic provider of the same chain type. `client.getProvider(type, chainId?)` returns the provider that lists the chain, otherwise the provider of that type that lists no chains; `getProvider(type)` answers as before. The new `findProvider(providers, chainType, chainId?)` applies the same rule to any provider list. `setProviders` replaces only a provider with the same type and the same `chainIds`.
18
+
19
+ - [#507](https://github.com/lifinance/sdk/pull/507) [`14f4ecc`](https://github.com/lifinance/sdk/commit/14f4ecc2714799449d57b61ff06b040df505184e) Thanks [@chybisov](https://github.com/chybisov)! - Never sign a second transaction on resume while the first one may still land.
20
+
21
+ - `prepareRestart` keeps a FAILED action with an unknown outcome and re-checks it on chain. Only a final outcome is dropped, so "Try again" signs anew.
22
+ - After `stopRouteExecution`, `updateRouteHook` can still be called for a route whose task was running, but only for a write that changes `txHash`, `txHex`, `taskId` or `txFinal`. An integrator that deleted the route should ignore that call. An error the hook throws in such a late call does not reach the run; in development it is logged with `console.debug`. If a new execution of the same route is running, a late transaction that may still land is merged into its action instead, so it does not sign again unless its wallet call has already started. If a newer execution already ended, the late transaction is merged into the route of the last ended execution, and that execution's `updateRouteHook` is called.
23
+ - The new `ExecutionAction.txFinal` flags a final outcome.
24
+ - `TransactionError` takes a new `final` option. Every `TransactionError` now has an own `final` property (`false` unless set), which changes its JSON shape.
25
+ - `resumeRoute` no longer mutates the route it is given. A restart keeps `execution.signedAt` while a transaction is open.
26
+ - In the EVM relayed lane and in the Solana, Sui, Tron, Bitcoin and Stellar providers, the SDK sends the transaction and checks the action again after the wallet returns. A prompt that was already open can still be signed, but when the late transaction merged first, those bytes are never sent or stored. A caught merge makes the newer run fail with `TransactionConflict`, and "Try again" then resumes and waits for the transaction. A step that asks for a replay (`ExecuteStepRetryError`) after such a merge also fails with `TransactionConflict`.
27
+ - An older run no longer stops or ends a newer execution of the same route.
28
+ - After `stopRouteExecution`, a run that waits for `/status` stops polling. Before, it polled every few seconds until the API answered DONE, and forever on FAILED, INVALID, NOT_FOUND or HTTP/network errors. The wait ends at once without a write to the route, so the step stays PENDING, and the run's `executeRoute` promise resolves with the route. A resume waits for the outcome of the same transaction.
29
+ - A stop during the first attempt of a step that then asks for a replay (`ExecuteStepRetryError`) also ends the run. The step does not run again, so the replay's re-quote, chain reads and integrator callbacks do not run after the stop, and `executeRoute` resolves with the route.
30
+ - `waitForResult` and `StepExecutor.executeStep` take an optional `signal`. Provider authors get it as `StepExecutorBaseContext.signal`, which aborts on `stopRouteExecution`. Give it only to a wait that starts after the transaction is broadcast, never to a sign, send or wallet call.
31
+ - New `hasOpenTransaction`. `assertNoOpenTransaction`, `isKnownToStatusApi`, `isFinalTransactionError`, `isResendAllowed`, `isOldEnoughToDrop`, `CLEARED_TRANSACTION_FIELDS`, `MAX_RESEND_AGE_MS`, `DROPPED_FALLBACK_AGE_MS` and `CLOCK_SKEW_MARGIN_MS` are exported for provider packages; they are not part of the integrator API (`@internal`).
32
+ - Remaining limits:
33
+ - In the lanes where the SDK sends, if the newer prompt is approved before the older run stores its transaction (in the EVM relayed lane, before the older run's relay request returns), nothing is merged yet, and both transactions can be sent.
34
+ - In the EVM standard and batched lanes the wallet sends, so a wallet call that has already started can still send a second transaction.
35
+ - A FAILED route from before the upgrade, or one resumed after node history no longer covers its signing time, can stay unknown. The exit is to delete the route.
36
+
37
+ ### Patch Changes
38
+
39
+ - [#510](https://github.com/lifinance/sdk/pull/510) [`bb964c0`](https://github.com/lifinance/sdk/commit/bb964c03d8ea1770303ab1bba803373a80e6388f) Thanks [@chybisov](https://github.com/chybisov)! - Bump runtime dependencies: viem to 2.57.3, @stellar/stellar-sdk to 17.2.1,
40
+ @mysten/sui to 2.35.0, @lifi/types to 18.13.0 and @bigmi/core to 0.9.3.
41
+
3
42
  ## 4.10.0
4
43
 
5
44
  ### Minor Changes
package/README.md CHANGED
@@ -83,6 +83,13 @@ needs no ecosystem library. To discover and connect browser wallets such as Frei
83
83
  xBull, or Lobstr, we recommend
84
84
  [Stellar Wallets Kit](https://github.com/Creit-Tech/Stellar-Wallets-Kit).
85
85
 
86
+ **Zcash**
87
+ ```bash
88
+ pnpm add @lifi/sdk-provider-zcash
89
+ ```
90
+
91
+ ZEC is a destination-only chain: `ZcashProvider` validates transparent `t1` and `t3` receivers, and unified `u1` receivers that carry an Orchard receiver, and needs no wallet. Register it after `BitcoinProvider`; it serves ZEC only.
92
+
86
93
  ## Architecture
87
94
 
88
95
  The LI.FI SDK uses a modular provider architecture:
@@ -134,6 +141,7 @@ import { BitcoinProvider } from '@lifi/sdk-provider-bitcoin'
134
141
  import { SuiProvider } from '@lifi/sdk-provider-sui'
135
142
  import { TronProvider } from '@lifi/sdk-provider-tron'
136
143
  import { StellarProvider } from '@lifi/sdk-provider-stellar'
144
+ import { ZcashProvider } from '@lifi/sdk-provider-zcash'
137
145
 
138
146
  const client = createClient({
139
147
  integrator: 'Your dApp/company name',
@@ -144,6 +152,7 @@ const client = createClient({
144
152
  SuiProvider({ /* options */ }),
145
153
  TronProvider({ /* options */ }),
146
154
  StellarProvider({ /* options */ }),
155
+ ZcashProvider(),
147
156
  ],
148
157
  })
149
158
  ```
@@ -1,8 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_version = require("../version.js");
3
3
  const require_utils_checkPackageUpdates = require("../utils/checkPackageUpdates.js");
4
+ const require_client_findProvider = require("./findProvider.js");
4
5
  const require_client_getClientStorage = require("./getClientStorage.js");
5
6
  //#region src/client/createClient.ts
7
+ const providerScope = (provider) => provider.chainIds ? `${provider.type}:${[...provider.chainIds].sort().join(",")}` : provider.type;
6
8
  function createClient(options) {
7
9
  if (!options.integrator) throw new Error("Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk");
8
10
  if (!options.disableVersionCheck && process.env.NODE_ENV === "development") require_utils_checkPackageUpdates.checkPackageUpdates(require_version.name, require_version.version);
@@ -39,12 +41,12 @@ function createClient(options) {
39
41
  get providers() {
40
42
  return _providers;
41
43
  },
42
- getProvider(type) {
43
- return this.providers.find((provider) => provider.type === type);
44
+ getProvider(type, chainId) {
45
+ return require_client_findProvider.findProvider(this.providers, type, chainId);
44
46
  },
45
47
  setProviders(newProviders) {
46
- const providerMap = new Map(this.providers.map((provider) => [provider.type, provider]));
47
- for (const provider of newProviders) providerMap.set(provider.type, provider);
48
+ const providerMap = new Map(this.providers.map((provider) => [providerScope(provider), provider]));
49
+ for (const provider of newProviders) providerMap.set(providerScope(provider), provider);
48
50
  _providers = Array.from(providerMap.values());
49
51
  },
50
52
  setChains(chains) {
@@ -1 +1 @@
1
- {"version":3,"file":"createClient.js","names":["name","version","getClientStorage"],"sources":["../../../src/client/createClient.ts"],"sourcesContent":["import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'\nimport type {\n RPCUrls,\n SDKBaseConfig,\n SDKClient,\n SDKConfig,\n SDKProvider,\n} from '../types/core.js'\nimport { checkPackageUpdates } from '../utils/checkPackageUpdates.js'\nimport { name, version } from '../version.js'\nimport { getClientStorage } from './getClientStorage.js'\n\nexport function createClient(options: SDKConfig): SDKClient {\n if (!options.integrator) {\n throw new Error(\n 'Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk'\n )\n }\n\n if (!options.disableVersionCheck && process.env.NODE_ENV === 'development') {\n checkPackageUpdates(name, version)\n }\n\n const { providers, rpcUrls, ...configOptions } = options\n\n // Role entries split once, here: the config keeps plain read lists, so\n // everything that reads `config.rpcUrls` sees `string[]` as before.\n const readRpcUrls: RPCUrls = {}\n const writeRpcUrls: RPCUrls = {}\n const bundleRpcUrls: RPCUrls = {}\n let hasRoles = false\n for (const key in rpcUrls) {\n const chainId = Number(key) as ChainId\n const entry = rpcUrls[chainId]\n if (Array.isArray(entry)) {\n readRpcUrls[chainId] = entry\n } else if (entry) {\n hasRoles = true\n if (entry.read) {\n readRpcUrls[chainId] = entry.read\n }\n if (entry.write?.length) {\n writeRpcUrls[chainId] = entry.write\n }\n if (entry.bundle?.length) {\n bundleRpcUrls[chainId] = entry.bundle\n }\n }\n }\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n // Plain lists only: the caller's own object, exactly as before.\n rpcUrls: hasRoles ? readRpcUrls : ((rpcUrls ?? {}) as RPCUrls),\n debug: configOptions?.debug ?? false,\n preloadChains: configOptions?.preloadChains ?? true,\n integrator: configOptions?.integrator ?? 'lifi-sdk',\n }\n\n let _providers: SDKProvider[] = providers ?? []\n const _storage = getClientStorage(_config)\n\n const client: SDKClient = {\n get config() {\n return _config\n },\n get providers() {\n return _providers\n },\n getProvider(type: ChainType) {\n return this.providers.find((provider) => provider.type === type)\n },\n setProviders(newProviders: SDKProvider[]) {\n const providerMap = new Map(\n this.providers.map((provider) => [provider.type, provider])\n )\n for (const provider of newProviders) {\n providerMap.set(provider.type, provider)\n }\n _providers = Array.from(providerMap.values())\n },\n setChains(chains: ExtendedChain[]) {\n _storage.setChains(chains)\n },\n async getChains() {\n return await _storage.getChains()\n },\n async getChainById(chainId: ChainId) {\n const chains = await this.getChains()\n const chain = chains?.find((chain) => chain.id === chainId)\n if (!chain) {\n throw new Error(`ChainId ${chainId} not found`)\n }\n return chain\n },\n async getRpcUrls() {\n return await _storage.getRpcUrls()\n },\n async getRpcUrlsByChainId(chainId: ChainId) {\n const rpcUrls = await this.getRpcUrls()\n const chainRpcUrls = rpcUrls[chainId]\n if (!chainRpcUrls?.length) {\n throw new Error(`RPC URL not found for chainId: ${chainId}`)\n }\n return chainRpcUrls\n },\n async getWriteRpcUrlsByChainId(chainId: ChainId) {\n return writeRpcUrls[chainId] ?? []\n },\n async getBundleRpcUrlsByChainId(chainId: ChainId) {\n return bundleRpcUrls[chainId] ?? []\n },\n }\n\n function extend<TClient extends SDKClient>(\n base: TClient\n ): <TExtensions extends Record<string, any>>(\n extendFn: (client: TClient) => TExtensions\n ) => TClient & TExtensions {\n return (extendFn) => {\n const extensions = extendFn(base)\n // Copy descriptors rather than spreading. `config` and `providers` are\n // accessors over closure variables, and `setProviders` reassigns\n // `_providers` — so a spread would freeze the extension on the values\n // those getters happened to return at extend time, leaving it with a\n // provider list that never updates.\n const extended = Object.defineProperties(\n {},\n {\n ...Object.getOwnPropertyDescriptors(base),\n ...Object.getOwnPropertyDescriptors(extensions),\n }\n ) as TClient & typeof extensions\n\n // Preserve the extend function for further extensions\n return Object.assign(extended, {\n extend: extend(extended),\n })\n }\n }\n\n return Object.assign(client, { extend: extend(client) })\n}\n"],"mappings":";;;;;AAYA,SAAgB,aAAa,SAA+B;CAC1D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,yGACF;CAGF,IAAI,CAAC,QAAQ,uBAAuB,QAAQ,IAAI,aAAa,eAC3D,kCAAA,oBAAoBA,gBAAAA,MAAMC,gBAAAA,OAAO;CAGnC,MAAM,EAAE,WAAW,SAAS,GAAG,kBAAkB;CAIjD,MAAM,cAAuB,CAAC;CAC9B,MAAM,eAAwB,CAAC;CAC/B,MAAM,gBAAyB,CAAC;CAChC,IAAI,WAAW;CACf,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,UAAU,OAAO,GAAG;EAC1B,MAAM,QAAQ,QAAQ;EACtB,IAAI,MAAM,QAAQ,KAAK,GACrB,YAAY,WAAW;OAClB,IAAI,OAAO;GAChB,WAAW;GACX,IAAI,MAAM,MACR,YAAY,WAAW,MAAM;GAE/B,IAAI,MAAM,OAAO,QACf,aAAa,WAAW,MAAM;GAEhC,IAAI,MAAM,QAAQ,QAChB,cAAc,WAAW,MAAM;EAEnC;CACF;CAEA,MAAM,UAAyB;EAC7B,GAAG;EACH,QAAQ,eAAe,UAAU;EAEjC,SAAS,WAAW,cAAgB,WAAW,CAAC;EAChD,OAAO,eAAe,SAAS;EAC/B,eAAe,eAAe,iBAAiB;EAC/C,YAAY,eAAe,cAAc;CAC3C;CAEA,IAAI,aAA4B,aAAa,CAAC;CAC9C,MAAM,WAAWC,gCAAAA,iBAAiB,OAAO;CAEzC,MAAM,SAAoB;EACxB,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,YAAY;GACd,OAAO;EACT;EACA,YAAY,MAAiB;GAC3B,OAAO,KAAK,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI;EACjE;EACA,aAAa,cAA6B;GACxC,MAAM,cAAc,IAAI,IACtB,KAAK,UAAU,KAAK,aAAa,CAAC,SAAS,MAAM,QAAQ,CAAC,CAC5D;GACA,KAAK,MAAM,YAAY,cACrB,YAAY,IAAI,SAAS,MAAM,QAAQ;GAEzC,aAAa,MAAM,KAAK,YAAY,OAAO,CAAC;EAC9C;EACA,UAAU,QAAyB;GACjC,SAAS,UAAU,MAAM;EAC3B;EACA,MAAM,YAAY;GAChB,OAAO,MAAM,SAAS,UAAU;EAClC;EACA,MAAM,aAAa,SAAkB;GAEnC,MAAM,SAAQ,MADO,KAAK,UAAU,EAAA,EACd,MAAM,UAAU,MAAM,OAAO,OAAO;GAC1D,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,WAAW,QAAQ,WAAW;GAEhD,OAAO;EACT;EACA,MAAM,aAAa;GACjB,OAAO,MAAM,SAAS,WAAW;EACnC;EACA,MAAM,oBAAoB,SAAkB;GAE1C,MAAM,gBAAe,MADC,KAAK,WAAW,EAAA,CACT;GAC7B,IAAI,CAAC,cAAc,QACjB,MAAM,IAAI,MAAM,kCAAkC,SAAS;GAE7D,OAAO;EACT;EACA,MAAM,yBAAyB,SAAkB;GAC/C,OAAO,aAAa,YAAY,CAAC;EACnC;EACA,MAAM,0BAA0B,SAAkB;GAChD,OAAO,cAAc,YAAY,CAAC;EACpC;CACF;CAEA,SAAS,OACP,MAGyB;EACzB,QAAQ,aAAa;GACnB,MAAM,aAAa,SAAS,IAAI;GAMhC,MAAM,WAAW,OAAO,iBACtB,CAAC,GACD;IACE,GAAG,OAAO,0BAA0B,IAAI;IACxC,GAAG,OAAO,0BAA0B,UAAU;GAChD,CACF;GAGA,OAAO,OAAO,OAAO,UAAU,EAC7B,QAAQ,OAAO,QAAQ,EACzB,CAAC;EACH;CACF;CAEA,OAAO,OAAO,OAAO,QAAQ,EAAE,QAAQ,OAAO,MAAM,EAAE,CAAC;AACzD"}
1
+ {"version":3,"file":"createClient.js","names":["name","version","getClientStorage","findProvider"],"sources":["../../../src/client/createClient.ts"],"sourcesContent":["import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'\nimport type {\n RPCUrls,\n SDKBaseConfig,\n SDKClient,\n SDKConfig,\n SDKProvider,\n} from '../types/core.js'\nimport { checkPackageUpdates } from '../utils/checkPackageUpdates.js'\nimport { name, version } from '../version.js'\nimport { findProvider } from './findProvider.js'\nimport { getClientStorage } from './getClientStorage.js'\n\n// A provider replaces only one that serves the same chains. A provider that\n// lists no chains keeps the bare type, so even an empty list stays apart.\nconst providerScope = (provider: SDKProvider): string =>\n provider.chainIds\n ? `${provider.type}:${[...provider.chainIds].sort().join(',')}`\n : provider.type\n\nexport function createClient(options: SDKConfig): SDKClient {\n if (!options.integrator) {\n throw new Error(\n 'Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk'\n )\n }\n\n if (!options.disableVersionCheck && process.env.NODE_ENV === 'development') {\n checkPackageUpdates(name, version)\n }\n\n const { providers, rpcUrls, ...configOptions } = options\n\n // Role entries split once, here: the config keeps plain read lists, so\n // everything that reads `config.rpcUrls` sees `string[]` as before.\n const readRpcUrls: RPCUrls = {}\n const writeRpcUrls: RPCUrls = {}\n const bundleRpcUrls: RPCUrls = {}\n let hasRoles = false\n for (const key in rpcUrls) {\n const chainId = Number(key) as ChainId\n const entry = rpcUrls[chainId]\n if (Array.isArray(entry)) {\n readRpcUrls[chainId] = entry\n } else if (entry) {\n hasRoles = true\n if (entry.read) {\n readRpcUrls[chainId] = entry.read\n }\n if (entry.write?.length) {\n writeRpcUrls[chainId] = entry.write\n }\n if (entry.bundle?.length) {\n bundleRpcUrls[chainId] = entry.bundle\n }\n }\n }\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n // Plain lists only: the caller's own object, exactly as before.\n rpcUrls: hasRoles ? readRpcUrls : ((rpcUrls ?? {}) as RPCUrls),\n debug: configOptions?.debug ?? false,\n preloadChains: configOptions?.preloadChains ?? true,\n integrator: configOptions?.integrator ?? 'lifi-sdk',\n }\n\n let _providers: SDKProvider[] = providers ?? []\n const _storage = getClientStorage(_config)\n\n const client: SDKClient = {\n get config() {\n return _config\n },\n get providers() {\n return _providers\n },\n getProvider(type: ChainType, chainId?: ChainId) {\n return findProvider(this.providers, type, chainId)\n },\n setProviders(newProviders: SDKProvider[]) {\n const providerMap = new Map(\n this.providers.map((provider) => [providerScope(provider), provider])\n )\n for (const provider of newProviders) {\n providerMap.set(providerScope(provider), provider)\n }\n _providers = Array.from(providerMap.values())\n },\n setChains(chains: ExtendedChain[]) {\n _storage.setChains(chains)\n },\n async getChains() {\n return await _storage.getChains()\n },\n async getChainById(chainId: ChainId) {\n const chains = await this.getChains()\n const chain = chains?.find((chain) => chain.id === chainId)\n if (!chain) {\n throw new Error(`ChainId ${chainId} not found`)\n }\n return chain\n },\n async getRpcUrls() {\n return await _storage.getRpcUrls()\n },\n async getRpcUrlsByChainId(chainId: ChainId) {\n const rpcUrls = await this.getRpcUrls()\n const chainRpcUrls = rpcUrls[chainId]\n if (!chainRpcUrls?.length) {\n throw new Error(`RPC URL not found for chainId: ${chainId}`)\n }\n return chainRpcUrls\n },\n async getWriteRpcUrlsByChainId(chainId: ChainId) {\n return writeRpcUrls[chainId] ?? []\n },\n async getBundleRpcUrlsByChainId(chainId: ChainId) {\n return bundleRpcUrls[chainId] ?? []\n },\n }\n\n function extend<TClient extends SDKClient>(\n base: TClient\n ): <TExtensions extends Record<string, any>>(\n extendFn: (client: TClient) => TExtensions\n ) => TClient & TExtensions {\n return (extendFn) => {\n const extensions = extendFn(base)\n // Copy descriptors rather than spreading. `config` and `providers` are\n // accessors over closure variables, and `setProviders` reassigns\n // `_providers` — so a spread would freeze the extension on the values\n // those getters happened to return at extend time, leaving it with a\n // provider list that never updates.\n const extended = Object.defineProperties(\n {},\n {\n ...Object.getOwnPropertyDescriptors(base),\n ...Object.getOwnPropertyDescriptors(extensions),\n }\n ) as TClient & typeof extensions\n\n // Preserve the extend function for further extensions\n return Object.assign(extended, {\n extend: extend(extended),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AE,CAAC;AACzD"}
@@ -0,0 +1,10 @@
1
+ import { SDKProvider } from "../types/core.js";
2
+ import { ChainId, ChainType } from "@lifi/types";
3
+ //#region src/client/findProvider.d.ts
4
+ /**
5
+ * The provider that serves a chain: the one that lists `chainId` in its
6
+ * `chainIds`, otherwise the provider of `chainType` that lists no chains.
7
+ */
8
+ export declare const findProvider: <T extends Pick<SDKProvider, "type" | "chainIds">>(providers: readonly T[], chainType: ChainType, chainId?: ChainId) => T | undefined;
9
+ //#endregion
10
+ //# sourceMappingURL=findProvider.d.ts.map
@@ -0,0 +1,11 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/client/findProvider.ts
3
+ /**
4
+ * The provider that serves a chain: the one that lists `chainId` in its
5
+ * `chainIds`, otherwise the provider of `chainType` that lists no chains.
6
+ */
7
+ const findProvider = (providers, chainType, chainId) => (chainId === void 0 ? void 0 : providers.find((provider) => provider.type === chainType && provider.chainIds?.includes(chainId))) ?? providers.find((provider) => provider.type === chainType && !provider.chainIds);
8
+ //#endregion
9
+ exports.findProvider = findProvider;
10
+
11
+ //# sourceMappingURL=findProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"findProvider.js","names":[],"sources":["../../../src/client/findProvider.ts"],"sourcesContent":["import type { ChainId, ChainType } from '@lifi/types'\nimport type { SDKProvider } from '../types/core.js'\n\n/**\n * The provider that serves a chain: the one that lists `chainId` in its\n * `chainIds`, otherwise the provider of `chainType` that lists no chains.\n */\nexport const findProvider = <T extends Pick<SDKProvider, 'type' | 'chainIds'>>(\n providers: readonly T[],\n chainType: ChainType,\n chainId?: ChainId\n): T | undefined =>\n (chainId === undefined\n ? undefined\n : providers.find(\n (provider) =>\n provider.type === chainType && provider.chainIds?.includes(chainId)\n )) ??\n providers.find(\n (provider) => provider.type === chainType && !provider.chainIds\n )\n"],"mappings":";;;;;;AAOA,MAAa,gBACX,WACA,WACA,aAEC,YAAY,KAAA,IACT,KAAA,IACA,UAAU,MACP,aACC,SAAS,SAAS,aAAa,SAAS,UAAU,SAAS,OAAO,CACtE,MACJ,UAAU,MACP,aAAa,SAAS,SAAS,aAAa,CAAC,SAAS,QACzD"}
@@ -16,7 +16,7 @@ export declare abstract class BaseStepExecutor implements StepExecutor {
16
16
  abstract createContext(baseContext: StepExecutorBaseContext): Promise<StepExecutorContext>;
17
17
  abstract createPipeline(context: StepExecutorContext): TaskPipeline;
18
18
  abstract parseErrors(error: Error, step?: LiFiStepExtended, action?: ExecutionAction, retryParams?: ExecuteStepRetryParams): Promise<SDKError | ExecuteStepRetryError>;
19
- executeStep: (client: SDKClient, step: LiFiStepExtended, retryParams?: ExecuteStepRetryParams) => Promise<LiFiStepExtended>;
19
+ executeStep: (client: SDKClient, step: LiFiStepExtended, retryParams?: ExecuteStepRetryParams, signal?: AbortSignal) => Promise<LiFiStepExtended>;
20
20
  }
21
21
  //#endregion
22
22
  //# sourceMappingURL=BaseStepExecutor.d.ts.map
@@ -1,5 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_errors_SDKError = require("../errors/SDKError.js");
3
+ const require_errors_baseError = require("../errors/baseError.js");
2
4
  const require_errors_errors = require("../errors/errors.js");
5
+ const require_core_transactionState = require("./transactionState.js");
3
6
  const require_core_StatusManager = require("./StatusManager.js");
4
7
  //#region src/core/BaseStepExecutor.ts
5
8
  const defaultInteractionSettings = {
@@ -25,7 +28,7 @@ var BaseStepExecutor = class {
25
28
  this.statusManager.allowUpdates(interactionSettings.allowUpdates);
26
29
  this.allowExecution = interactionSettings.allowExecution;
27
30
  };
28
- createBaseContext = async (client, step, retryParams) => {
31
+ createBaseContext = async (client, step, retryParams, signal) => {
29
32
  const fromChain = await client.getChainById(step.action.fromChainId);
30
33
  const toChain = await client.getChainById(step.action.toChainId);
31
34
  return {
@@ -37,24 +40,33 @@ var BaseStepExecutor = class {
37
40
  retryParams,
38
41
  statusManager: this.statusManager,
39
42
  executionOptions: this.executionOptions,
40
- allowUserInteraction: this.allowUserInteraction
43
+ allowUserInteraction: this.allowUserInteraction,
44
+ signal
41
45
  };
42
46
  };
43
- executeStep = async (client, step, retryParams) => {
47
+ executeStep = async (client, step, retryParams, signal) => {
44
48
  try {
45
49
  step.execution = this.statusManager.initializeExecution(step);
46
- const baseContext = await this.createBaseContext(client, step, retryParams);
50
+ const baseContext = await this.createBaseContext(client, step, retryParams, signal);
47
51
  const context = await this.createContext(baseContext);
48
52
  await this.createPipeline(context).run(context);
49
53
  return step;
50
54
  } catch (error) {
51
55
  const action = step.execution?.actions?.at(-1);
52
- const parsed = await this.parseErrors(error, step, action, retryParams);
56
+ let isFinal = require_core_transactionState.isFinalTransactionError(error);
57
+ let parsed = await this.parseErrors(error, step, action, retryParams);
58
+ if (parsed instanceof require_errors_errors.ExecuteStepRetryError && require_core_transactionState.hasStepOpenTransaction(step)) {
59
+ parsed = new require_errors_SDKError.SDKError(error instanceof require_errors_errors.ExecuteStepRetryError ? require_core_transactionState.transactionConflictError() : error instanceof require_errors_baseError.BaseError ? error : new require_errors_errors.UnknownError(error?.message || parsed.message, error), step, action);
60
+ isFinal = false;
61
+ }
53
62
  if (!(parsed instanceof require_errors_errors.ExecuteStepRetryError)) {
54
- if (action) this.statusManager.updateAction(step, action.type, "FAILED", { error: {
55
- message: parsed.cause?.message,
56
- code: parsed.code
57
- } });
63
+ if (action) this.statusManager.updateAction(step, action.type, "FAILED", {
64
+ error: {
65
+ message: parsed.cause?.message,
66
+ code: parsed.code
67
+ },
68
+ ...isFinal && { txFinal: true }
69
+ });
58
70
  else this.statusManager.updateExecution(step, {
59
71
  status: "FAILED",
60
72
  error: {
@@ -1 +1 @@
1
- {"version":3,"file":"BaseStepExecutor.js","names":["StatusManager","ExecuteStepRetryError"],"sources":["../../../src/core/BaseStepExecutor.ts"],"sourcesContent":["import { ExecuteStepRetryError } from '../errors/errors.js'\nimport type { SDKError } from '../errors/SDKError.js'\nimport type {\n ExecuteStepRetryParams,\n ExecutionAction,\n ExecutionOptions,\n InteractionSettings,\n LiFiStepExtended,\n SDKClient,\n StepExecutor,\n StepExecutorOptions,\n} from '../types/core.js'\nimport type {\n StepExecutorBaseContext,\n StepExecutorContext,\n} from '../types/execution.js'\nimport { StatusManager } from './StatusManager.js'\nimport type { TaskPipeline } from './TaskPipeline.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n private createBaseContext = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<StepExecutorBaseContext> => {\n const fromChain = await client.getChainById(step.action.fromChainId)\n const toChain = await client.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n\n return {\n client,\n step,\n fromChain,\n toChain,\n isBridgeExecution,\n retryParams,\n statusManager: this.statusManager,\n executionOptions: this.executionOptions,\n allowUserInteraction: this.allowUserInteraction,\n }\n }\n\n abstract createContext(\n baseContext: StepExecutorBaseContext\n ): Promise<StepExecutorContext>\n\n abstract createPipeline(context: StepExecutorContext): TaskPipeline\n\n abstract parseErrors(\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction,\n retryParams?: ExecuteStepRetryParams\n ): Promise<SDKError | ExecuteStepRetryError>\n\n executeStep = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<LiFiStepExtended> => {\n try {\n step.execution = this.statusManager.initializeExecution(step)\n\n const baseContext = await this.createBaseContext(\n client,\n step,\n retryParams\n )\n const context = await this.createContext(baseContext)\n const pipeline = this.createPipeline(context)\n\n await pipeline.run(context)\n\n return step\n } catch (error: any) {\n // Derive failing action from last in execution.actions\n const action = step.execution?.actions?.at(-1)\n const parsed = await this.parseErrors(error, step, action, retryParams)\n if (!(parsed instanceof ExecuteStepRetryError)) {\n if (action) {\n this.statusManager.updateAction(step, action.type, 'FAILED', {\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n } else {\n this.statusManager.updateExecution(step, {\n status: 'FAILED',\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n }\n }\n throw parsed\n }\n }\n}\n"],"mappings":";;;;AAoBA,MAAM,6BAA6B;CACjC,kBAAkB;CAClB,cAAc;CACd,gBAAgB;AAClB;AAEA,IAAsB,mBAAtB,MAA+D;CAC7D;CACA;CAEA,uBAA8B;CAC9B,iBAAwB;CAExB,YAAY,SAA8B;EACxC,KAAK,gBAAgB,IAAIA,2BAAAA,cAAc,QAAQ,OAAO;EACtD,KAAK,mBAAmB,QAAQ;CAClC;CAEA,kBAAkB,aAAyC;EACzD,MAAM,sBAAsB;GAC1B,GAAG;GACH,GAAG;EACL;EACA,KAAK,uBAAuB,oBAAoB;EAChD,KAAK,cAAc,aAAa,oBAAoB,YAAY;EAChE,KAAK,iBAAiB,oBAAoB;CAC5C;CAEA,oBAA4B,OAC1B,QACA,MACA,gBACqC;EACrC,MAAM,YAAY,MAAM,OAAO,aAAa,KAAK,OAAO,WAAW;EACnE,MAAM,UAAU,MAAM,OAAO,aAAa,KAAK,OAAO,SAAS;EAI/D,OAAO;GACL;GACA;GACA;GACA;GACA,mBAPwB,UAAU,OAAO,QAAQ;GAQjD;GACA,eAAe,KAAK;GACpB,kBAAkB,KAAK;GACvB,sBAAsB,KAAK;EAC7B;CACF;CAeA,cAAc,OACZ,QACA,MACA,gBAC8B;EAC9B,IAAI;GACF,KAAK,YAAY,KAAK,cAAc,oBAAoB,IAAI;GAE5D,MAAM,cAAc,MAAM,KAAK,kBAC7B,QACA,MACA,WACF;GACA,MAAM,UAAU,MAAM,KAAK,cAAc,WAAW;GAGpD,MAFiB,KAAK,eAAe,OAExB,CAAC,CAAC,IAAI,OAAO;GAE1B,OAAO;EACT,SAAS,OAAY;GAEnB,MAAM,SAAS,KAAK,WAAW,SAAS,GAAG,EAAE;GAC7C,MAAM,SAAS,MAAM,KAAK,YAAY,OAAO,MAAM,QAAQ,WAAW;GACtE,IAAI,EAAE,kBAAkBC,sBAAAA,wBAAwB;IAC9C,IAAI,QACF,KAAK,cAAc,aAAa,MAAM,OAAO,MAAM,UAAU,EAC3D,OAAO;KACL,SAAS,OAAO,OAAO;KACvB,MAAM,OAAO;IACf,EACF,CAAC;SAED,KAAK,cAAc,gBAAgB,MAAM;KACvC,QAAQ;KACR,OAAO;MACL,SAAS,OAAO,OAAO;MACvB,MAAM,OAAO;KACf;IACF,CAAC;GAEL;GACA,MAAM;EACR;CACF;AACF"}
1
+ {"version":3,"file":"BaseStepExecutor.js","names":["StatusManager","isFinalTransactionError","ExecuteStepRetryError","hasStepOpenTransaction","SDKError","transactionConflictError","BaseError","UnknownError"],"sources":["../../../src/core/BaseStepExecutor.ts"],"sourcesContent":["import { BaseError } from '../errors/baseError.js'\nimport { ExecuteStepRetryError, UnknownError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type {\n ExecuteStepRetryParams,\n ExecutionAction,\n ExecutionOptions,\n InteractionSettings,\n LiFiStepExtended,\n SDKClient,\n StepExecutor,\n StepExecutorOptions,\n} from '../types/core.js'\nimport type {\n StepExecutorBaseContext,\n StepExecutorContext,\n} from '../types/execution.js'\nimport { StatusManager } from './StatusManager.js'\nimport type { TaskPipeline } from './TaskPipeline.js'\nimport {\n hasStepOpenTransaction,\n isFinalTransactionError,\n transactionConflictError,\n} from './transactionState.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n private createBaseContext = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams,\n signal?: AbortSignal\n ): Promise<StepExecutorBaseContext> => {\n const fromChain = await client.getChainById(step.action.fromChainId)\n const toChain = await client.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n\n return {\n client,\n step,\n fromChain,\n toChain,\n isBridgeExecution,\n retryParams,\n statusManager: this.statusManager,\n executionOptions: this.executionOptions,\n allowUserInteraction: this.allowUserInteraction,\n signal,\n }\n }\n\n abstract createContext(\n baseContext: StepExecutorBaseContext\n ): Promise<StepExecutorContext>\n\n abstract createPipeline(context: StepExecutorContext): TaskPipeline\n\n abstract parseErrors(\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction,\n retryParams?: ExecuteStepRetryParams\n ): Promise<SDKError | ExecuteStepRetryError>\n\n executeStep = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams,\n signal?: AbortSignal\n ): Promise<LiFiStepExtended> => {\n try {\n step.execution = this.statusManager.initializeExecution(step)\n\n const baseContext = await this.createBaseContext(\n client,\n step,\n retryParams,\n signal\n )\n const context = await this.createContext(baseContext)\n const pipeline = this.createPipeline(context)\n\n await pipeline.run(context)\n\n return step\n } catch (error: any) {\n // Derive failing action from last in execution.actions\n const action = step.execution?.actions?.at(-1)\n // Read before parsing: parsers may rebuild the error and drop the marker.\n let isFinal = isFinalTransactionError(error)\n let parsed = await this.parseErrors(error, step, action, retryParams)\n if (\n parsed instanceof ExecuteStepRetryError &&\n hasStepOpenTransaction(step)\n ) {\n // A retry runs the step again on an empty execution, which would erase\n // the hash of a transaction that may still land. Fail with the original\n // error instead, and keep the outcome unknown so a resume re-checks it.\n // A BaseError keeps its code, so the widget shows its text. A replay\n // that a task asked for has no error of its own: it fails as a sign\n // task fails for the same state (`TransactionConflict`).\n parsed = new SDKError(\n error instanceof ExecuteStepRetryError\n ? transactionConflictError()\n : error instanceof BaseError\n ? error\n : new UnknownError(error?.message || parsed.message, error),\n step,\n action\n )\n isFinal = false\n }\n if (!(parsed instanceof ExecuteStepRetryError)) {\n if (action) {\n this.statusManager.updateAction(step, action.type, 'FAILED', {\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n ...(isFinal && { txFinal: true }),\n })\n } else {\n this.statusManager.updateExecution(step, {\n status: 'FAILED',\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n }\n }\n throw parsed\n }\n }\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,6BAA6B;CACjC,kBAAkB;CAClB,cAAc;CACd,gBAAgB;AAClB;AAEA,IAAsB,mBAAtB,MAA+D;CAC7D;CACA;CAEA,uBAA8B;CAC9B,iBAAwB;CAExB,YAAY,SAA8B;EACxC,KAAK,gBAAgB,IAAIA,2BAAAA,cAAc,QAAQ,OAAO;EACtD,KAAK,mBAAmB,QAAQ;CAClC;CAEA,kBAAkB,aAAyC;EACzD,MAAM,sBAAsB;GAC1B,GAAG;GACH,GAAG;EACL;EACA,KAAK,uBAAuB,oBAAoB;EAChD,KAAK,cAAc,aAAa,oBAAoB,YAAY;EAChE,KAAK,iBAAiB,oBAAoB;CAC5C;CAEA,oBAA4B,OAC1B,QACA,MACA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ACL,SAAS,OAAO,OAAO;MACvB,MAAM,OAAO;KACf;IACF,CAAC;GAEL;GACA,MAAM;EACR;CACF;AACF"}
@@ -13,6 +13,7 @@ type ActionProps = {
13
13
  export declare class StatusManager {
14
14
  private readonly routeId;
15
15
  private shouldUpdate;
16
+ private stoppedExecution?;
16
17
  constructor(routeId: string);
17
18
  /**
18
19
  * Initializes the execution object of a Step.
@@ -66,6 +67,15 @@ export declare class StatusManager {
66
67
  }>) => ExecutionAction;
67
68
  updateStepInRoute: (step: LiFiStep) => LiFiStep;
68
69
  allowUpdates(value: boolean): void;
70
+ /**
71
+ * A write of transaction data after `stopRouteExecution`. With a newer
72
+ * execution of the same route id running, the transaction is merged into
73
+ * it. If no execution of the route started since the stop, the kept route
74
+ * is updated and the kept hook is called. If a newer execution started and
75
+ * ended since the stop, the transaction is merged into the route of the
76
+ * last ended execution, and its hook is called.
77
+ */
78
+ private deliverLateTransactionData;
69
79
  }
70
80
  //#endregion
71
81
  //# sourceMappingURL=StatusManager.d.ts.map
@@ -1,13 +1,68 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_core_actionMessages = require("./actionMessages.js");
3
3
  const require_core_executionState = require("./executionState.js");
4
+ const require_core_transactionState = require("./transactionState.js");
4
5
  //#region src/core/StatusManager.ts
5
6
  /**
7
+ * A write is transaction data when it changes one of these fields. `txLink`,
8
+ * `signedAt` and `callCount` travel with such a write but never trigger one:
9
+ * the status poll rewrites `txLink` every few seconds, and `callCount` comes
10
+ * only with a `taskId`.
11
+ */
12
+ const TRANSACTION_KEYS = [
13
+ "txHash",
14
+ "txHex",
15
+ "taskId",
16
+ "txFinal"
17
+ ];
18
+ const readTransaction = (action) => ({
19
+ txHash: action.txHash,
20
+ txHex: action.txHex,
21
+ taskId: action.taskId,
22
+ txFinal: action.txFinal
23
+ });
24
+ /** True when the write changed a transaction field, also to `undefined`. */
25
+ const changesTransaction = (before, action) => TRANSACTION_KEYS.some((key) => action[key] !== before[key]);
26
+ /**
27
+ * Copies a late transaction into the route of a newer execution of the same
28
+ * route id, running or ended. The step's objects are changed in place: a
29
+ * running executor holds them, so its selector and its pre-sign guard see
30
+ * the transaction. Returns true when something changed.
31
+ */
32
+ const mergeLateTransaction = (liveRoute, lateStep, lateAction) => {
33
+ if (!require_core_transactionState.hasOpenTransaction(lateAction)) return false;
34
+ const liveStep = liveRoute.steps.find((routeStep) => routeStep.id === lateStep.id);
35
+ if (!liveStep) return false;
36
+ if (!liveStep.execution) liveStep.execution = {
37
+ startedAt: Date.now(),
38
+ status: "PENDING",
39
+ actions: [structuredClone(lateAction)]
40
+ };
41
+ else {
42
+ const liveAction = liveStep.execution.actions.find((action) => action.type === lateAction.type);
43
+ if (!liveAction) liveStep.execution.actions.push(structuredClone(lateAction));
44
+ else if (require_core_transactionState.hasOpenTransaction(liveAction)) return false;
45
+ else Object.assign(liveAction, {
46
+ txHash: lateAction.txHash,
47
+ txLink: lateAction.txLink,
48
+ txHex: lateAction.txHex,
49
+ txFinal: lateAction.txFinal,
50
+ taskId: lateAction.taskId,
51
+ callCount: lateAction.callCount,
52
+ txType: lateAction.txType
53
+ });
54
+ }
55
+ const signedAt = lateStep.execution?.signedAt;
56
+ if (require_core_transactionState.TRANSACTION_ACTION_TYPES.includes(lateAction.type) && signedAt !== void 0) liveStep.execution.signedAt = signedAt;
57
+ return true;
58
+ };
59
+ /**
6
60
  * Manages status updates of a route and provides various functions for tracking actions.
7
61
  */
8
62
  var StatusManager = class {
9
63
  routeId;
10
64
  shouldUpdate = true;
65
+ stoppedExecution;
11
66
  constructor(routeId) {
12
67
  this.routeId = routeId;
13
68
  }
@@ -28,7 +83,7 @@ var StatusManager = class {
28
83
  if (step.execution.status === "FAILED") {
29
84
  step.execution.startedAt = Date.now();
30
85
  step.execution.status = "PENDING";
31
- step.execution.signedAt = void 0;
86
+ if (!require_core_transactionState.hasStepOpenTransaction(step)) step.execution.signedAt = void 0;
32
87
  step.execution.error = void 0;
33
88
  this.updateStepInRoute(step);
34
89
  }
@@ -89,7 +144,11 @@ var StatusManager = class {
89
144
  * @returns The updated or newly created action.
90
145
  */
91
146
  initializeAction = ({ step, type, chainId, status }) => {
92
- if (this.findAction(step, type)) return this.updateAction(step, type, status, { error: void 0 });
147
+ const action = this.findAction(step, type);
148
+ if (action) return this.updateAction(step, type, status, {
149
+ error: void 0,
150
+ ...action.status === "FAILED" && action.txFinal === true && require_core_transactionState.CLEARED_TRANSACTION_FIELDS
151
+ });
93
152
  return this.createAction({
94
153
  step,
95
154
  type,
@@ -109,6 +168,7 @@ var StatusManager = class {
109
168
  if (!step.execution) throw new Error("Can't update an empty step execution.");
110
169
  const currentAction = this.findAction(step, type);
111
170
  if (!currentAction) throw new Error("Can't find an action for the given type.");
171
+ const transactionBefore = this.shouldUpdate ? void 0 : readTransaction(currentAction);
112
172
  switch (status) {
113
173
  case "CANCELLED": break;
114
174
  case "FAILED":
@@ -131,7 +191,8 @@ var StatusManager = class {
131
191
  Object.assign(currentAction, rest);
132
192
  }
133
193
  step.execution.actions = [...step.execution.actions.filter((action) => action.status === "DONE"), ...step.execution.actions.filter((action) => action.status !== "DONE")];
134
- this.updateStepInRoute(step);
194
+ if (transactionBefore && changesTransaction(transactionBefore, currentAction)) this.deliverLateTransactionData(step, currentAction);
195
+ else this.updateStepInRoute(step);
135
196
  return currentAction;
136
197
  };
137
198
  updateStepInRoute = (step) => {
@@ -149,6 +210,49 @@ var StatusManager = class {
149
210
  };
150
211
  allowUpdates(value) {
151
212
  this.shouldUpdate = value;
213
+ if (value) {
214
+ this.stoppedExecution = void 0;
215
+ return;
216
+ }
217
+ const data = require_core_executionState.executionState.get(this.routeId);
218
+ if (data) this.stoppedExecution = {
219
+ route: data.route,
220
+ updateRouteHook: data.executionOptions?.updateRouteHook,
221
+ startCount: require_core_executionState.executionState.startCount(this.routeId)
222
+ };
223
+ }
224
+ /**
225
+ * A write of transaction data after `stopRouteExecution`. With a newer
226
+ * execution of the same route id running, the transaction is merged into
227
+ * it. If no execution of the route started since the stop, the kept route
228
+ * is updated and the kept hook is called. If a newer execution started and
229
+ * ended since the stop, the transaction is merged into the route of the
230
+ * last ended execution, and its hook is called.
231
+ */
232
+ deliverLateTransactionData(step, lateAction) {
233
+ const stopped = this.stoppedExecution;
234
+ if (!stopped) return;
235
+ try {
236
+ const live = require_core_executionState.executionState.get(this.routeId);
237
+ if (live) {
238
+ if (mergeLateTransaction(live.route, step, lateAction)) live.executionOptions?.updateRouteHook?.(live.route);
239
+ return;
240
+ }
241
+ if (require_core_executionState.executionState.startCount(this.routeId) !== stopped.startCount) {
242
+ const ended = require_core_executionState.executionState.lastEnded(this.routeId);
243
+ if (ended && mergeLateTransaction(ended.route, step, lateAction)) ended.updateRouteHook?.(ended.route);
244
+ return;
245
+ }
246
+ const stepIndex = stopped.route.steps.findIndex((routeStep) => routeStep.id === step.id);
247
+ if (stepIndex === -1) return;
248
+ stopped.route.steps[stepIndex] = {
249
+ ...stopped.route.steps[stepIndex],
250
+ ...step
251
+ };
252
+ stopped.updateRouteHook?.(stopped.route);
253
+ } catch (error) {
254
+ if (process.env.NODE_ENV === "development") console.debug("Delivering late transaction data failed.", error);
255
+ }
152
256
  }
153
257
  };
154
258
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"StatusManager.js","names":["getActionMessage","executionState"],"sources":["../../../src/core/StatusManager.ts"],"sourcesContent":["import type { ChainId, LiFiStep } from '@lifi/types'\nimport type {\n Execution,\n ExecutionAction,\n ExecutionActionStatus,\n ExecutionActionType,\n LiFiStepExtended,\n} from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { executionState } from './executionState.js'\n\ntype ActionProps = {\n step: LiFiStepExtended\n type: ExecutionActionType\n chainId: ChainId\n status: ExecutionActionStatus\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking actions.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step\n */\n initializeExecution = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.startedAt = Date.now()\n step.execution.status = 'PENDING'\n step.execution.signedAt = undefined\n step.execution.error = undefined\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param execution Partial execution data to merge\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n execution: Partial<Execution>\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution = {\n ...step.execution,\n ...execution,\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Finds an action of the specified type in the step's execution\n * @param step The step to search in\n * @param type The action type to find\n * @returns The found action or undefined if not found\n */\n findAction(\n step: LiFiStepExtended,\n type: ExecutionActionType\n ): ExecutionAction | undefined {\n if (!step.execution?.actions) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const action = step.execution.actions.find((p) => p.type === type)\n\n return action\n }\n\n /**\n * Create and push a new action into the execution.\n * Caller is responsible for ensuring an action of this type does not already exist.\n * @param step The step that should contain the new action.\n * @param type Type of the action.\n * @param chainId Chain Id of the action.\n * @param status The initial status for the new action.\n * @returns The created action.\n */\n createAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const newAction: ExecutionAction = {\n type,\n message: getActionMessage(type, status),\n status,\n chainId,\n }\n\n step.execution.actions.push(newAction)\n this.updateStepInRoute(step)\n return newAction\n }\n\n /**\n * Find an existing action by type and update it, or create a new one if none exists.\n * @param step The step that should contain the action.\n * @param type Type of the action. Used to identify already existing actions.\n * @param chainId Chain Id of the action (used when creating).\n * @param status The status to set on the found or newly created action.\n * @returns The updated or newly created action.\n */\n initializeAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n const action = this.findAction(step, type)\n\n if (action) {\n return this.updateAction(step, type, status, {\n error: undefined,\n })\n }\n\n return this.createAction({ step, type, chainId, status })\n }\n\n /**\n * Update an action object.\n * @param step The step where the action should be updated\n * @param type The action type to update\n * @param status The status the action gets.\n * @param [params] Additional parameters to append to the action.\n * @returns The updated action\n */\n updateAction = (\n step: LiFiStepExtended,\n type: ExecutionActionType,\n status: ExecutionActionStatus,\n params?: Partial<ExecutionAction & { signedAt?: number }>\n ): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentAction = this.findAction(step, type)\n\n if (!currentAction) {\n throw new Error(\"Can't find an action for the given type.\")\n }\n\n switch (status) {\n case 'CANCELLED':\n break\n case 'FAILED':\n step.execution.status = 'FAILED'\n if (params?.error) {\n step.execution.error = params.error\n }\n break\n case 'DONE':\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n if (params?.signedAt) {\n step.execution.signedAt = params.signedAt\n }\n break\n case 'RESET_REQUIRED':\n case 'MESSAGE_REQUIRED':\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentAction.status = status\n currentAction.message = getActionMessage(type, status)\n // set extra parameters or overwrite the standard params set in the switch statement\n if (params) {\n const { signedAt: _signedAt, ...rest } = params\n Object.assign(currentAction, rest)\n }\n // Sort actions, the ones with DONE status go first\n step.execution.actions = [\n ...step.execution.actions.filter((action) => action.status === 'DONE'),\n ...step.execution.actions.filter((action) => action.status !== 'DONE'),\n ]\n this.updateStepInRoute(step) // updates the step in the route\n return currentAction\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n }\n}\n"],"mappings":";;;;;;;AAqBA,IAAa,gBAAb,MAA2B;CACzB;CACA,eAAuB;CAEvB,YAAY,SAAiB;EAC3B,KAAK,UAAU;CACjB;;;;;;CAOA,uBAAuB,SAAsC;EAC3D,IAAI,CAAC,KAAK,WAAW;GACnB,KAAK,YAAY;IACf,WAAW,KAAK,IAAI;IACpB,QAAQ;IACR,SAAS,CAAC;GACZ;GACA,KAAK,kBAAkB,IAAI;EAC7B;EAGA,IAAI,KAAK,UAAU,WAAW,UAAU;GACtC,KAAK,UAAU,YAAY,KAAK,IAAI;GACpC,KAAK,UAAU,SAAS;GACxB,KAAK,UAAU,WAAW,KAAA;GAC1B,KAAK,UAAU,QAAQ,KAAA;GACvB,KAAK,kBAAkB,IAAI;EAC7B;EAEA,OAAO,KAAK;CACd;;;;;;;CAQA,gBACE,MACA,WACU;EACV,IAAI,CAAC,KAAK,WACR,MAAM,MAAM,+BAA+B;EAE7C,KAAK,YAAY;GACf,GAAG,KAAK;GACR,GAAG;EACL;EACA,KAAK,kBAAkB,IAAI;EAC3B,OAAO;CACT;;;;;;;CAQA,WACE,MACA,MAC6B;EAC7B,IAAI,CAAC,KAAK,WAAW,SACnB,MAAM,IAAI,MAAM,oCAAoC;EAKtD,OAFe,KAAK,UAAU,QAAQ,MAAM,MAAM,EAAE,SAAS,IAEjD;CACd;;;;;;;;;;CAWA,gBAAgB,EACd,MACA,MACA,SACA,aACkC;EAClC,IAAI,CAAC,KAAK,WACR,MAAM,IAAI,MAAM,oCAAoC;EAGtD,MAAM,YAA6B;GACjC;GACA,SAASA,4BAAAA,iB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,KAAK,cACR,OAAO;EAET,MAAM,OAAOC,4BAAAA,eAAe,IAAI,KAAK,OAAO;EAE5C,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,2BAA2B;EAG7C,MAAM,YAAY,KAAK,MAAM,MAAM,WAChC,cAAc,UAAU,OAAO,KAAK,EACvC;EAEA,IAAI,cAAc,IAChB,MAAM,IAAI,MAAM,iCAAiC;EAGnD,KAAK,MAAM,MAAM,aAAa;GAAE,GAAG,KAAK,MAAM,MAAM;GAAY,GAAG;EAAK;EAExE,KAAK,kBAAkB,kBAAkB,KAAK,KAAK;EACnD,OAAO,KAAK,MAAM,MAAM;CAC1B;CAEA,aAAa,OAAsB;EACjC,KAAK,eAAe;CACtB;AACF"}
1
+ {"version":3,"file":"StatusManager.js","names":["hasOpenTransaction","TRANSACTION_ACTION_TYPES","hasStepOpenTransaction","getActionMessage","CLEARED_TRANSACTION_FIELDS","executionState"],"sources":["../../../src/core/StatusManager.ts"],"sourcesContent":["import type { ChainId, LiFiStep } from '@lifi/types'\nimport type {\n Execution,\n ExecutionAction,\n ExecutionActionStatus,\n ExecutionActionType,\n LiFiStepExtended,\n RouteExtended,\n UpdateRouteHook,\n} from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { executionState } from './executionState.js'\nimport {\n CLEARED_TRANSACTION_FIELDS,\n hasOpenTransaction,\n hasStepOpenTransaction,\n TRANSACTION_ACTION_TYPES,\n} from './transactionState.js'\n\ntype ActionProps = {\n step: LiFiStepExtended\n type: ExecutionActionType\n chainId: ChainId\n status: ExecutionActionStatus\n}\n\n/**\n * The route and hook of an execution that `stopRouteExecution` ended. A task\n * that was still running (e.g. waiting in the wallet prompt) writes its\n * transaction data later; without these the write would never reach the\n * integrator, and a resume of the stored route would sign again.\n * `startCount` is `executionState.startCount` at the stop.\n */\ntype StoppedExecution = {\n route: RouteExtended\n updateRouteHook?: UpdateRouteHook\n startCount: number\n}\n\n/**\n * A write is transaction data when it changes one of these fields. `txLink`,\n * `signedAt` and `callCount` travel with such a write but never trigger one:\n * the status poll rewrites `txLink` every few seconds, and `callCount` comes\n * only with a `taskId`.\n */\nconst TRANSACTION_KEYS = ['txHash', 'txHex', 'taskId', 'txFinal'] as const\n\ntype TransactionFields = Pick<\n ExecutionAction,\n (typeof TRANSACTION_KEYS)[number]\n>\n\nconst readTransaction = (action: ExecutionAction): TransactionFields => ({\n txHash: action.txHash,\n txHex: action.txHex,\n taskId: action.taskId,\n txFinal: action.txFinal,\n})\n\n/** True when the write changed a transaction field, also to `undefined`. */\nconst changesTransaction = (\n before: TransactionFields,\n action: ExecutionAction\n): boolean => TRANSACTION_KEYS.some((key) => action[key] !== before[key])\n\n/**\n * Copies a late transaction into the route of a newer execution of the same\n * route id, running or ended. The step's objects are changed in place: a\n * running executor holds them, so its selector and its pre-sign guard see\n * the transaction. Returns true when something changed.\n */\nconst mergeLateTransaction = (\n liveRoute: RouteExtended,\n lateStep: LiFiStepExtended,\n lateAction: ExecutionAction\n): boolean => {\n // Cleared or final: the newer execution needs nothing from it.\n if (!hasOpenTransaction(lateAction)) {\n return false\n }\n const liveStep = liveRoute.steps.find(\n (routeStep) => routeStep.id === lateStep.id\n )\n if (!liveStep) {\n return false\n }\n if (!liveStep.execution) {\n liveStep.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [structuredClone(lateAction)],\n }\n } else {\n const liveAction = liveStep.execution.actions.find(\n (action) => action.type === lateAction.type\n )\n if (!liveAction) {\n liveStep.execution.actions.push(structuredClone(lateAction))\n } else if (hasOpenTransaction(liveAction)) {\n // The live action already has an open transaction (its own, or one\n // merged earlier); it is kept.\n return false\n } else {\n // Every field of `CLEARED_TRANSACTION_FIELDS`, so a stale `txFinal`\n // goes and the action is open. `txType` goes with them: the live one\n // described no open transaction.\n Object.assign(liveAction, {\n txHash: lateAction.txHash,\n txLink: lateAction.txLink,\n txHex: lateAction.txHex,\n txFinal: lateAction.txFinal,\n taskId: lateAction.taskId,\n callCount: lateAction.callCount,\n txType: lateAction.txType,\n })\n }\n }\n // `signedAt` is the signing time of the step's own transaction: an\n // allowance does not set it, and a write without one keeps the live time.\n const signedAt = lateStep.execution?.signedAt\n if (\n TRANSACTION_ACTION_TYPES.includes(lateAction.type) &&\n signedAt !== undefined\n ) {\n liveStep.execution.signedAt = signedAt\n }\n return true\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking actions.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n private stoppedExecution?: StoppedExecution\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step\n */\n initializeExecution = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.startedAt = Date.now()\n step.execution.status = 'PENDING'\n // Keep the signing time while a signed transaction may still land: the\n // resume path uses it to decide when stored bytes are too old to resend\n // or old enough to be declared dropped.\n if (!hasStepOpenTransaction(step)) {\n step.execution.signedAt = undefined\n }\n step.execution.error = undefined\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param execution Partial execution data to merge\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n execution: Partial<Execution>\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution = {\n ...step.execution,\n ...execution,\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Finds an action of the specified type in the step's execution\n * @param step The step to search in\n * @param type The action type to find\n * @returns The found action or undefined if not found\n */\n findAction(\n step: LiFiStepExtended,\n type: ExecutionActionType\n ): ExecutionAction | undefined {\n if (!step.execution?.actions) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const action = step.execution.actions.find((p) => p.type === type)\n\n return action\n }\n\n /**\n * Create and push a new action into the execution.\n * Caller is responsible for ensuring an action of this type does not already exist.\n * @param step The step that should contain the new action.\n * @param type Type of the action.\n * @param chainId Chain Id of the action.\n * @param status The initial status for the new action.\n * @returns The created action.\n */\n createAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const newAction: ExecutionAction = {\n type,\n message: getActionMessage(type, status),\n status,\n chainId,\n }\n\n step.execution.actions.push(newAction)\n this.updateStepInRoute(step)\n return newAction\n }\n\n /**\n * Find an existing action by type and update it, or create a new one if none exists.\n * @param step The step that should contain the action.\n * @param type Type of the action. Used to identify already existing actions.\n * @param chainId Chain Id of the action (used when creating).\n * @param status The status to set on the found or newly created action.\n * @returns The updated or newly created action.\n */\n initializeAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n const action = this.findAction(step, type)\n\n if (action) {\n return this.updateAction(step, type, status, {\n error: undefined,\n // A final outcome is dead. A new attempt starts without its data, so\n // the pre-sign guard does not mistake it for an open transaction (the\n // route was run again without `prepareRestart`, e.g. `executeRoute`).\n ...(action.status === 'FAILED' &&\n action.txFinal === true &&\n CLEARED_TRANSACTION_FIELDS),\n })\n }\n\n return this.createAction({ step, type, chainId, status })\n }\n\n /**\n * Update an action object.\n * @param step The step where the action should be updated\n * @param type The action type to update\n * @param status The status the action gets.\n * @param [params] Additional parameters to append to the action.\n * @returns The updated action\n */\n updateAction = (\n step: LiFiStepExtended,\n type: ExecutionActionType,\n status: ExecutionActionStatus,\n params?: Partial<ExecutionAction & { signedAt?: number }>\n ): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentAction = this.findAction(step, type)\n\n if (!currentAction) {\n throw new Error(\"Can't find an action for the given type.\")\n }\n // Read before the write: after a stop, only a write that changes the\n // transaction reaches the integrator.\n const transactionBefore = this.shouldUpdate\n ? undefined\n : readTransaction(currentAction)\n\n switch (status) {\n case 'CANCELLED':\n break\n case 'FAILED':\n step.execution.status = 'FAILED'\n if (params?.error) {\n step.execution.error = params.error\n }\n break\n case 'DONE':\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n if (params?.signedAt) {\n step.execution.signedAt = params.signedAt\n }\n break\n case 'RESET_REQUIRED':\n case 'MESSAGE_REQUIRED':\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentAction.status = status\n currentAction.message = getActionMessage(type, status)\n // set extra parameters or overwrite the standard params set in the switch statement\n if (params) {\n const { signedAt: _signedAt, ...rest } = params\n Object.assign(currentAction, rest)\n }\n // Sort actions, the ones with DONE status go first\n step.execution.actions = [\n ...step.execution.actions.filter((action) => action.status === 'DONE'),\n ...step.execution.actions.filter((action) => action.status !== 'DONE'),\n ]\n if (\n transactionBefore &&\n changesTransaction(transactionBefore, currentAction)\n ) {\n this.deliverLateTransactionData(step, currentAction)\n } else {\n this.updateStepInRoute(step) // updates the step in the route\n }\n return currentAction\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n // A shallow copy on purpose: the route's step must keep sharing the\n // step's `execution` object. `mergeLateTransaction` changes the live\n // route in place, and the running sign task's check after the wallet\n // must see the merge (pinned by the stop-and-resume race test in\n // `sdk-provider-ethereum/src/core/flows/reload.unit.spec.ts`).\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n if (value) {\n this.stoppedExecution = undefined\n return\n }\n // `stopRouteExecution` turns updates off right before it deletes the\n // execution state, so the state is still here to keep.\n const data = executionState.get(this.routeId)\n if (data) {\n this.stoppedExecution = {\n route: data.route,\n updateRouteHook: data.executionOptions?.updateRouteHook,\n startCount: executionState.startCount(this.routeId),\n }\n }\n }\n\n /**\n * A write of transaction data after `stopRouteExecution`. With a newer\n * execution of the same route id running, the transaction is merged into\n * it. If no execution of the route started since the stop, the kept route\n * is updated and the kept hook is called. If a newer execution started and\n * ended since the stop, the transaction is merged into the route of the\n * last ended execution, and its hook is called.\n */\n private deliverLateTransactionData(\n step: LiFiStepExtended,\n lateAction: ExecutionAction\n ): void {\n const stopped = this.stoppedExecution\n if (!stopped) {\n return\n }\n // A late write must never fail the task that made it: its catch block\n // would mark the action FAILED while the transaction may still land.\n try {\n // Always a newer execution: `stopRouteExecution` deleted this one.\n const live = executionState.get(this.routeId)\n if (live) {\n if (mergeLateTransaction(live.route, step, lateAction)) {\n live.executionOptions?.updateRouteHook?.(live.route)\n }\n return\n }\n // A newer execution started and ended since the stop: the integrator\n // stored its route, which the kept one would roll back. The late\n // transaction goes into that route instead. With the records of the\n // route freed (no run in flight, `startCount` 0) the write is dropped.\n if (executionState.startCount(this.routeId) !== stopped.startCount) {\n const ended = executionState.lastEnded(this.routeId)\n if (ended && mergeLateTransaction(ended.route, step, lateAction)) {\n ended.updateRouteHook?.(ended.route)\n }\n return\n }\n const stepIndex = stopped.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n if (stepIndex === -1) {\n return\n }\n stopped.route.steps[stepIndex] = {\n ...stopped.route.steps[stepIndex],\n ...step,\n }\n stopped.updateRouteHook?.(stopped.route)\n } catch (error) {\n // Not rethrown, see above. The integrator's hook can throw here, so\n // the error is reported in development, as other swallowed errors are.\n if (process.env.NODE_ENV === 'development') {\n console.debug('Delivering late transaction data failed.', error)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA6CA,MAAM,mBAAmB;CAAC;CAAU;CAAS;CAAU;AAAS;AAOh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 @@ const resumeRoute = async (client, route, executionOptions) => {
44
44
  return execution.promise;
45
45
  }
46
46
  }
47
- require_core_prepareRestart.prepareRestart(route);
48
- return executeRoute(client, route, executionOptions);
47
+ const restartRoute = structuredClone(route);
48
+ require_core_prepareRestart.prepareRestart(restartRoute);
49
+ return executeRoute(client, restartRoute, executionOptions);
49
50
  };
51
+ /**
52
+ * True while `route` is the execution registered for its id. A stopped run
53
+ * keeps going until its step ends; it must not stop or delete a newer
54
+ * execution of the same route.
55
+ */
56
+ const ownsExecution = (route) => require_core_executionState.executionState.get(route.id)?.route === route;
50
57
  const executeSteps = async (client, route) => {
51
58
  for (let index = 0; index < route.steps.length; index++) {
52
59
  const execution = require_core_executionState.executionState.get(route.id);
53
- if (!execution) break;
60
+ if (!execution || execution.route !== route) break;
54
61
  const step = route.steps[index];
55
62
  const previousStep = route.steps[index - 1];
56
63
  if (step.execution?.status === "DONE") continue;
@@ -67,25 +74,33 @@ const executeSteps = async (client, route) => {
67
74
  routeId: route.id,
68
75
  executionOptions: execution.executionOptions
69
76
  });
70
- execution.executors.push(stepExecutor);
71
- if (execution.executionOptions) updateRouteExecution(route, execution.executionOptions);
77
+ if (!ownsExecution(route)) return route;
78
+ require_core_executionState.executionState.retain(route.id);
79
+ const { signal } = execution.abortController;
72
80
  let executedStep;
73
81
  try {
74
- executedStep = await stepExecutor.executeStep(client, step);
75
- } catch (e) {
76
- if (e instanceof require_errors_errors.ExecuteStepRetryError) {
77
- step.execution = void 0;
78
- executedStep = await stepExecutor.executeStep(client, step, e.retryParams);
79
- } else throw e;
82
+ execution.executors.push(stepExecutor);
83
+ if (execution.executionOptions) updateRouteExecution(route, execution.executionOptions);
84
+ try {
85
+ executedStep = await stepExecutor.executeStep(client, step, void 0, signal);
86
+ } catch (e) {
87
+ if (e instanceof require_errors_errors.ExecuteStepRetryError) {
88
+ if (!stepExecutor.allowExecution) return route;
89
+ step.execution = void 0;
90
+ executedStep = await stepExecutor.executeStep(client, step, e.retryParams, signal);
91
+ } else throw e;
92
+ }
93
+ } finally {
94
+ require_core_executionState.executionState.release(route.id);
80
95
  }
81
- if (executedStep.execution?.status !== "DONE") stopRouteExecution(route);
96
+ if (executedStep.execution?.status !== "DONE" && ownsExecution(route)) stopRouteExecution(route);
82
97
  if (!stepExecutor.allowExecution) return route;
83
98
  } catch (e) {
84
- stopRouteExecution(route);
99
+ if (ownsExecution(route)) stopRouteExecution(route);
85
100
  throw e;
86
101
  }
87
102
  }
88
- require_core_executionState.executionState.delete(route.id);
103
+ if (ownsExecution(route)) require_core_executionState.executionState.delete(route.id);
89
104
  return route;
90
105
  };
91
106
  /**
@@ -119,6 +134,7 @@ const stopRouteExecution = (route) => {
119
134
  allowExecution: false
120
135
  });
121
136
  require_core_executionState.executionState.delete(route.id);
137
+ execution.abortController.abort();
122
138
  return execution.route;
123
139
  };
124
140
  /**