@lifi/sdk-provider-sui 4.2.7 → 4.2.9

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 (56) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +9 -0
  3. package/dist/esm/actions/getSuiBalance.d.ts.map +1 -1
  4. package/dist/esm/actions/getSuiBalance.js +5 -4
  5. package/dist/esm/actions/getSuiBalance.js.map +1 -1
  6. package/dist/esm/client/suiClient.d.ts +2 -1
  7. package/dist/esm/client/suiClient.d.ts.map +1 -1
  8. package/dist/esm/client/suiClient.js +14 -15
  9. package/dist/esm/client/suiClient.js.map +1 -1
  10. package/dist/esm/core/SuiStepExecutor.d.ts.map +1 -1
  11. package/dist/esm/core/SuiStepExecutor.js +2 -2
  12. package/dist/esm/core/SuiStepExecutor.js.map +1 -1
  13. package/dist/esm/core/constants.d.ts +7 -0
  14. package/dist/esm/core/constants.d.ts.map +1 -0
  15. package/dist/esm/core/constants.js +9 -0
  16. package/dist/esm/core/constants.js.map +1 -0
  17. package/dist/esm/core/tasks/SuiSignAndExecuteTask.d.ts.map +1 -1
  18. package/dist/esm/core/tasks/SuiSignAndExecuteTask.js +54 -7
  19. package/dist/esm/core/tasks/SuiSignAndExecuteTask.js.map +1 -1
  20. package/dist/esm/core/tasks/SuiWaitForTransactionTask.d.ts.map +1 -1
  21. package/dist/esm/core/tasks/SuiWaitForTransactionTask.js +110 -12
  22. package/dist/esm/core/tasks/SuiWaitForTransactionTask.js.map +1 -1
  23. package/dist/esm/core/tasks/helpers/callWithinDeadline.d.ts +19 -0
  24. package/dist/esm/core/tasks/helpers/callWithinDeadline.d.ts.map +1 -0
  25. package/dist/esm/core/tasks/helpers/callWithinDeadline.js +45 -0
  26. package/dist/esm/core/tasks/helpers/callWithinDeadline.js.map +1 -0
  27. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.d.ts +24 -0
  28. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.d.ts.map +1 -0
  29. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.js +141 -0
  30. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.js.map +1 -0
  31. package/dist/esm/errors/parseSuiErrors.js +5 -4
  32. package/dist/esm/errors/parseSuiErrors.js.map +1 -1
  33. package/dist/esm/utils/getSuiTxLink.d.ts +5 -0
  34. package/dist/esm/utils/getSuiTxLink.d.ts.map +1 -0
  35. package/dist/esm/utils/getSuiTxLink.js +6 -0
  36. package/dist/esm/utils/getSuiTxLink.js.map +1 -0
  37. package/dist/esm/utils/suiSignedTransaction.d.ts +39 -0
  38. package/dist/esm/utils/suiSignedTransaction.d.ts.map +1 -0
  39. package/dist/esm/utils/suiSignedTransaction.js +73 -0
  40. package/dist/esm/utils/suiSignedTransaction.js.map +1 -0
  41. package/dist/esm/version.d.ts +1 -1
  42. package/dist/esm/version.js +1 -1
  43. package/dist/esm/version.js.map +1 -1
  44. package/package.json +3 -3
  45. package/src/actions/getSuiBalance.ts +40 -24
  46. package/src/client/suiClient.ts +21 -18
  47. package/src/core/SuiStepExecutor.ts +9 -3
  48. package/src/core/constants.ts +21 -0
  49. package/src/core/tasks/SuiSignAndExecuteTask.ts +107 -8
  50. package/src/core/tasks/SuiWaitForTransactionTask.ts +249 -22
  51. package/src/core/tasks/helpers/callWithinDeadline.ts +48 -0
  52. package/src/core/tasks/helpers/isSuiTransactionDropped.ts +292 -0
  53. package/src/errors/parseSuiErrors.ts +19 -19
  54. package/src/utils/getSuiTxLink.ts +4 -0
  55. package/src/utils/suiSignedTransaction.ts +109 -0
  56. package/src/version.ts +1 -1
@@ -2,6 +2,7 @@ import {
2
2
  BaseStepExecutor,
3
3
  CheckBalanceTask,
4
4
  type ExecutionAction,
5
+ hasOpenTransaction,
5
6
  LiFiErrorCode,
6
7
  type LiFiStepExtended,
7
8
  PrepareTransactionTask,
@@ -77,10 +78,15 @@ export class SuiStepExecutor extends BaseStepExecutor {
77
78
  isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'
78
79
  )
79
80
 
80
- const firstTask =
81
- swapOrBridgeAction?.txHash && swapOrBridgeAction?.status === 'DONE'
81
+ // A transaction signed for this action may still land (`txHex` from
82
+ // signing, `txHash` after execution). Resume at the confirmation wait:
83
+ // re-preparing or re-signing could execute the swap twice. A final failure
84
+ // is not open, so "Try again" signs anew.
85
+ const firstTask = hasOpenTransaction(swapOrBridgeAction)
86
+ ? swapOrBridgeAction?.status === 'DONE'
82
87
  ? WaitForTransactionStatusTask
83
- : CheckBalanceTask
88
+ : SuiWaitForTransactionTask
89
+ : CheckBalanceTask
84
90
 
85
91
  // Compare classes, not names: a minifier can give two task classes the
86
92
  // same name.
@@ -0,0 +1,21 @@
1
+ // Added after the latest landing time (signing + resend age cap + clock skew)
2
+ // before a checkpoint counts as past it: fullnode retries and node lag.
3
+ export const SUI_HEAD_MARGIN_MS: number = 5 * 60_000
4
+
5
+ // The head canary comes from this many checkpoints behind the tip (about
6
+ // 30 s on mainnet), so every backend behind a load-balanced RPC has it.
7
+ export const SUI_CANARY_TIP_OFFSET = 120n
8
+
9
+ // A lower bound of the checkpoint interval. Estimating a checkpoint for a
10
+ // time with it lands at or before that time.
11
+ export const SUI_MIN_CHECKPOINT_INTERVAL_MS = 200
12
+
13
+ // The budget of each resume lookup call to one node: the digest lookup, a
14
+ // checkpoint read and the batch lookup. A node that has not answered by then
15
+ // counts as failed and the next node is asked; a timeout alone never decides
16
+ // the outcome. A healthy node answers in well under a second. Each node gets
17
+ // the full 10 s, so a slow pool can use up the two-minute resend age cap
18
+ // before the resend decision. Then the resend is lost, but it is never sent
19
+ // late: the re-execution checks the cap before each node and aborts when the
20
+ // cap passes.
21
+ export const SUI_LOOKUP_TIMEOUT_MS = 10_000
@@ -1,5 +1,8 @@
1
1
  import {
2
+ assertNoOpenTransaction,
3
+ BaseError,
2
4
  BaseStepExecutionTask,
5
+ CLEARED_TRANSACTION_FIELDS,
3
6
  getTransactionRequestData,
4
7
  LiFiErrorCode,
5
8
  type TaskResult,
@@ -7,6 +10,8 @@ import {
7
10
  } from '@lifi/sdk'
8
11
  import { Transaction } from '@mysten/sui/transactions'
9
12
  import type { SuiStepExecutorContext } from '../../types.js'
13
+ import { getSuiTxLink } from '../../utils/getSuiTxLink.js'
14
+ import { serializeSuiSignedTransaction } from '../../utils/suiSignedTransaction.js'
10
15
 
11
16
  export class SuiSignAndExecuteTask extends BaseStepExecutionTask {
12
17
  async run(context: SuiStepExecutorContext): Promise<TaskResult> {
@@ -18,6 +23,7 @@ export class SuiSignAndExecuteTask extends BaseStepExecutionTask {
18
23
  executionOptions,
19
24
  isBridgeExecution,
20
25
  checkWallet,
26
+ fromChain,
21
27
  } = context
22
28
 
23
29
  const action = statusManager.findAction(
@@ -32,6 +38,10 @@ export class SuiSignAndExecuteTask extends BaseStepExecutionTask {
32
38
  )
33
39
  }
34
40
 
41
+ // A transaction signed earlier for this action may still land. Signing a
42
+ // second one could execute the swap twice.
43
+ assertNoOpenTransaction(action)
44
+
35
45
  const transactionRequestData = await getTransactionRequestData(
36
46
  step,
37
47
  executionOptions
@@ -39,24 +49,78 @@ export class SuiSignAndExecuteTask extends BaseStepExecutionTask {
39
49
 
40
50
  checkWallet(step)
41
51
 
42
- // We give users 2 minutes to sign the transaction
52
+ // Built and signed exactly as `suiClient.core.signAndExecuteTransaction`
53
+ // does, in two steps: the signed bytes are stored before they are sent,
54
+ // so a reload re-executes them instead of asking for a second signature.
55
+ const transaction = Transaction.from(transactionRequestData)
56
+ transaction.setSenderIfNotSet(signer.toSuiAddress())
57
+ const transactionBytes = await transaction.build({ client: suiClient })
58
+
59
+ // Checked again right before the wallet: a late write of an older run
60
+ // can merge its transaction into this action during the awaits above.
61
+ assertNoOpenTransaction(statusManager.findAction(step, action.type))
62
+
63
+ // Only the wallet's own answer is classified: an error from building the
64
+ // transaction above can quote a node that "rejected" it.
65
+ let signature: string
66
+ try {
67
+ signature = (await signer.signTransaction(transactionBytes)).signature
68
+ } catch (error) {
69
+ throw toSuiSignerError(error)
70
+ }
71
+
72
+ // Checked once more after the wallet: a stopped run's late write can
73
+ // merge its transaction into this action while the prompt is open.
74
+ // Nothing awaits from here to the write below.
75
+ assertNoOpenTransaction(statusManager.findAction(step, action.type))
76
+
77
+ const txHex = serializeSuiSignedTransaction(transactionBytes, signature)
78
+ if (!txHex) {
79
+ // Nothing was sent yet, so "Try again" signs a new transaction.
80
+ throw new TransactionError(
81
+ LiFiErrorCode.TransactionUnprepared,
82
+ 'Unable to prepare transaction. The signed transaction is incomplete.'
83
+ )
84
+ }
85
+
86
+ // One write: the previous transaction's data is cleared together with
87
+ // storing the new bytes, so no stale hash can look open again.
88
+ statusManager.updateAction(step, action.type, 'PENDING', {
89
+ ...CLEARED_TRANSACTION_FIELDS,
90
+ txHex,
91
+ signedAt: Date.now(),
92
+ })
93
+
43
94
  const {
44
95
  $kind,
45
96
  FailedTransaction,
46
97
  Transaction: TransactionResult,
47
- } = await suiClient.core.signAndExecuteTransaction({
48
- signer,
49
- transaction: Transaction.from(transactionRequestData),
98
+ } = await suiClient.core.executeTransaction({
99
+ transaction: transactionBytes,
100
+ signatures: [signature],
50
101
  })
51
102
 
52
- statusManager.updateAction(step, action.type, 'PENDING', {
53
- signedAt: Date.now(),
54
- })
103
+ // A failed transaction has a digest too: it is on chain.
104
+ const executedTransaction = TransactionResult ?? FailedTransaction
105
+ if (executedTransaction) {
106
+ statusManager.updateAction(step, action.type, 'PENDING', {
107
+ txHash: executedTransaction.digest,
108
+ txLink: getSuiTxLink(fromChain, executedTransaction.digest),
109
+ })
110
+ }
55
111
 
56
112
  if ($kind !== 'Transaction' || !TransactionResult) {
113
+ if (FailedTransaction) {
114
+ // Executed and failed: the outcome is final and the bytes are spent.
115
+ statusManager.updateAction(step, action.type, 'PENDING', {
116
+ txHex: undefined,
117
+ })
118
+ }
57
119
  throw new TransactionError(
58
120
  LiFiErrorCode.TransactionFailed,
59
- `Transaction failed: ${FailedTransaction?.status.error ?? `Unexpected transaction result: ${$kind}`}`
121
+ `Transaction failed: ${FailedTransaction?.status.error?.message ?? `Unexpected transaction result: ${$kind}`}`,
122
+ undefined,
123
+ FailedTransaction ? { final: true } : undefined
60
124
  )
61
125
  }
62
126
 
@@ -66,3 +130,38 @@ export class SuiSignAndExecuteTask extends BaseStepExecutionTask {
66
130
  }
67
131
  }
68
132
  }
133
+
134
+ /** For a wallet that rejects with code 4001 and gives no message. */
135
+ const SIGNATURE_REJECTED_MESSAGE = 'The wallet rejected the signature request.'
136
+
137
+ /**
138
+ * Classifies an error thrown by `signer.signTransaction`, the only call to the
139
+ * user's signer in this package. The wallet refused to sign when its error
140
+ * says "reject" (in any case) or carries the EIP-1193 code 4001. Wallets throw
141
+ * an Error, a plain object or a string, so no shape is assumed. An SDK error
142
+ * keeps its code, and any other value is returned as it is.
143
+ *
144
+ * A remote or zkLogin signer whose own network call says "reject" is tagged
145
+ * too. That is the safe direction: nothing was signed, so nothing can land.
146
+ */
147
+ function toSuiSignerError(error: unknown): unknown {
148
+ if (error instanceof BaseError) {
149
+ return error
150
+ }
151
+ const fields = (error ?? {}) as { code?: unknown; message?: unknown }
152
+ const message =
153
+ typeof error === 'string'
154
+ ? error
155
+ : typeof fields.message === 'string'
156
+ ? fields.message
157
+ : undefined
158
+ if (fields.code === 4001 || message?.toLowerCase().includes('reject')) {
159
+ return new TransactionError(
160
+ LiFiErrorCode.SignatureRejected,
161
+ message || SIGNATURE_REJECTED_MESSAGE,
162
+ // Kept as thrown, also when it is a string or a plain object.
163
+ error as Error
164
+ )
165
+ }
166
+ return error
167
+ }
@@ -1,11 +1,29 @@
1
1
  import {
2
2
  BaseStepExecutionTask,
3
+ type ExecutionAction,
4
+ isResendAllowed,
3
5
  LiFiErrorCode,
6
+ MAX_RESEND_AGE_MS,
7
+ type SDKClient,
4
8
  type TaskResult,
5
9
  TransactionError,
6
10
  } from '@lifi/sdk'
11
+ import {
12
+ TransactionError as SuiClientTransactionError,
13
+ type SuiClientTypes,
14
+ } from '@mysten/sui/client'
15
+ import { GrpcStatusCode, RpcError } from '@mysten/sui/grpc'
7
16
  import { callSuiWithRetry } from '../../client/suiClient.js'
8
17
  import type { SuiStepExecutorContext } from '../../types.js'
18
+ import { getSuiTxLink } from '../../utils/getSuiTxLink.js'
19
+ import {
20
+ parseSuiSignedTransaction,
21
+ type SuiSignedTransaction,
22
+ verifySuiSignedTransaction,
23
+ } from '../../utils/suiSignedTransaction.js'
24
+ import { SUI_LOOKUP_TIMEOUT_MS } from '../constants.js'
25
+ import { callWithinDeadline } from './helpers/callWithinDeadline.js'
26
+ import { isSuiTransactionDropped } from './helpers/isSuiTransactionDropped.js'
9
27
 
10
28
  export class SuiWaitForTransactionTask extends BaseStepExecutionTask {
11
29
  async run(context: SuiStepExecutorContext): Promise<TaskResult> {
@@ -13,18 +31,10 @@ export class SuiWaitForTransactionTask extends BaseStepExecutionTask {
13
31
  client,
14
32
  step,
15
33
  statusManager,
16
- fromChain,
17
34
  isBridgeExecution,
18
35
  signedTransaction,
19
36
  } = context
20
37
 
21
- if (!signedTransaction) {
22
- throw new TransactionError(
23
- LiFiErrorCode.TransactionUnprepared,
24
- 'Unable to prepare transaction. Signed transaction is not found.'
25
- )
26
- }
27
-
28
38
  const action = statusManager.findAction(
29
39
  step,
30
40
  isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'
@@ -36,30 +46,247 @@ export class SuiWaitForTransactionTask extends BaseStepExecutionTask {
36
46
  )
37
47
  }
38
48
 
39
- const result = await callSuiWithRetry(client, (client) =>
40
- client.core.waitForTransaction({
41
- digest: signedTransaction.digest,
49
+ if (signedTransaction) {
50
+ const result = await callSuiWithRetry(client, (client) =>
51
+ client.core.waitForTransaction({
52
+ digest: signedTransaction.digest,
53
+ })
54
+ )
55
+ return complete(context, action, result)
56
+ }
57
+
58
+ // Resuming: the signing task did not run in this session. Continue with
59
+ // the bytes and the digest persisted on the action; never sign again.
60
+ const storedTransaction = action.txHex
61
+ ? parseSuiSignedTransaction(action.txHex)
62
+ : undefined
63
+
64
+ if (action.txHex && !storedTransaction) {
65
+ // Bytes that do not decode, or that are not canonical, can never be
66
+ // executed or looked up.
67
+ statusManager.updateAction(step, action.type, 'PENDING', {
68
+ txHex: undefined,
42
69
  })
43
- )
70
+ if (!action.txHash) {
71
+ // No execution ever returned for these bytes, so "Try again" signs again.
72
+ throw new TransactionError(
73
+ LiFiErrorCode.TransactionUnprepared,
74
+ 'Unable to resume transaction. The stored signed transaction is invalid.'
75
+ )
76
+ }
77
+ }
44
78
 
45
- const transaction = result.Transaction ?? result.FailedTransaction
46
- if (!transaction?.status.success) {
79
+ const digest = action.txHash ?? storedTransaction?.digest
80
+ if (!digest) {
47
81
  throw new TransactionError(
48
- LiFiErrorCode.TransactionFailed,
49
- `Transaction failed: ${transaction?.status.error?.message ?? `Unexpected transaction result: ${result.$kind}`}`
82
+ LiFiErrorCode.TransactionUnprepared,
83
+ 'Unable to prepare transaction. Signed transaction is not found.'
84
+ )
85
+ }
86
+
87
+ const found = await findSuiTransaction(client, digest)
88
+ if (found) {
89
+ return complete(context, action, found)
90
+ }
91
+
92
+ // Stored bytes prove nothing when their digest is not the stored txHash
93
+ // (damaged storage) or their signature does not verify: the check also
94
+ // fails for a scheme it cannot parse or cannot run, and the bytes may
95
+ // have been sent. Then the SDK neither sends nor drops; it only waits,
96
+ // and the outcome stays unknown.
97
+ const doubtful =
98
+ !!storedTransaction &&
99
+ (storedTransaction.digest !== digest ||
100
+ !(await isVerifiedSuiTransaction(storedTransaction)))
101
+
102
+ const signedAt = step.execution?.signedAt
103
+ if (
104
+ !doubtful &&
105
+ storedTransaction &&
106
+ signedAt !== undefined &&
107
+ isResendAllowed(signedAt)
108
+ ) {
109
+ // A digest executes at most once, so re-executing the stored bytes can
110
+ // never run the swap twice.
111
+ try {
112
+ await reexecuteWithinAgeCap(client, storedTransaction, signedAt)
113
+ } catch (error) {
114
+ if (!isDefiniteSuiRejection(error)) {
115
+ throw error
116
+ }
117
+ // The first execution may have landed meanwhile; then the refusal
118
+ // only says that its inputs are spent.
119
+ const landed = await findSuiTransaction(client, digest)
120
+ if (landed) {
121
+ return complete(context, action, landed)
122
+ }
123
+ // A node refusal does not prove the transaction absent, so the
124
+ // outcome stays unknown.
125
+ throw error
126
+ }
127
+ } else if (
128
+ !doubtful &&
129
+ (await isSuiTransactionDropped(client, step, digest))
130
+ ) {
131
+ // No resend: past the age cap, with no stored bytes, or with an unknown
132
+ // signing time. Past the cap the bytes are never sent again, so a swap
133
+ // on an old quote cannot execute hours later; the batch lookup proves
134
+ // absence. Within the cap with only a txHash, and with an unknown
135
+ // signing time, `isSuiTransactionDropped` returns false, so the task
136
+ // waits.
137
+ throw dropped(context, action)
138
+ }
139
+
140
+ const result = await callSuiWithRetry(client, (client) =>
141
+ client.core.waitForTransaction({ digest })
142
+ )
143
+ return complete(context, action, result)
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Looks the digest up once. Resolves `undefined` only when the RPCs answer
149
+ * that it is unknown; any other error propagates as an unknown outcome.
150
+ * Each node has `SUI_LOOKUP_TIMEOUT_MS` to answer; a node that does not
151
+ * counts as failed, so the next node is asked.
152
+ */
153
+ async function findSuiTransaction(
154
+ client: SDKClient,
155
+ digest: string
156
+ ): Promise<SuiClientTypes.TransactionResult | undefined> {
157
+ try {
158
+ return await callSuiWithRetry(client, (client) =>
159
+ callWithinDeadline(
160
+ (signal) => client.core.getTransaction({ digest, signal }),
161
+ SUI_LOOKUP_TIMEOUT_MS
50
162
  )
163
+ )
164
+ } catch (error) {
165
+ if (
166
+ error instanceof SuiClientTransactionError &&
167
+ error.reason === 'notFound'
168
+ ) {
169
+ return undefined
170
+ }
171
+ throw error
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Re-executes the stored bytes. `callSuiWithRetry` tries the nodes one by
177
+ * one, so the age cap is checked before every try, and each try aborts when
178
+ * the cap passes. Past the cap it throws a plain error, which is
179
+ * not a definite rejection, so the outcome stays unknown.
180
+ *
181
+ * Not `AbortSignal.timeout`: a published SDK should not raise its runtime
182
+ * floor for it; one controller and one timer cover it.
183
+ */
184
+ async function reexecuteWithinAgeCap(
185
+ client: SDKClient,
186
+ transaction: SuiSignedTransaction,
187
+ signedAt: number
188
+ ): Promise<void> {
189
+ await callSuiWithRetry(client, async (client) => {
190
+ if (!isResendAllowed(signedAt)) {
191
+ throw createAgeCapError()
192
+ }
193
+ const controller = new AbortController()
194
+ const timer = setTimeout(
195
+ () => controller.abort(createAgeCapError()),
196
+ Math.max(0, signedAt + MAX_RESEND_AGE_MS - Date.now())
197
+ )
198
+ // A pending timer keeps Node's event loop alive. The `finally` clears it;
199
+ // the unref only covers a path that skips it.
200
+ const handle = timer as unknown as { unref?: () => void }
201
+ handle.unref?.()
202
+ try {
203
+ return await client.core.executeTransaction({
204
+ transaction: transaction.bytes,
205
+ signatures: [transaction.signature],
206
+ signal: controller.signal,
207
+ })
208
+ } finally {
209
+ clearTimeout(timer)
51
210
  }
211
+ })
212
+ }
213
+
214
+ /**
215
+ * The resend age cap passed. The name makes the gRPC transport report an
216
+ * abort with this reason as DEADLINE_EXCEEDED, as for any timeout.
217
+ */
218
+ function createAgeCapError(): Error {
219
+ const error = new Error('The resend age cap passed before the re-execution.')
220
+ error.name = 'TimeoutError'
221
+ return error
222
+ }
52
223
 
53
- // Transaction has been confirmed and we can update the action
224
+ /** True only when the check runs and confirms the sender's signature. */
225
+ async function isVerifiedSuiTransaction(
226
+ transaction: SuiSignedTransaction
227
+ ): Promise<boolean> {
228
+ try {
229
+ return (await verifySuiSignedTransaction(transaction)) === true
230
+ } catch {
231
+ return false
232
+ }
233
+ }
234
+
235
+ // The validators refused the transaction itself, e.g. because its input object
236
+ // versions are no longer available. Network errors and overloaded nodes do not
237
+ // count: the transaction may still land.
238
+ function isDefiniteSuiRejection(error: unknown): boolean {
239
+ return (
240
+ error instanceof RpcError &&
241
+ error.code === GrpcStatusCode[GrpcStatusCode.INVALID_ARGUMENT]
242
+ )
243
+ }
244
+
245
+ function complete(
246
+ context: SuiStepExecutorContext,
247
+ action: ExecutionAction,
248
+ result: SuiClientTypes.TransactionResult
249
+ ): TaskResult {
250
+ const { step, statusManager, fromChain, isBridgeExecution } = context
251
+
252
+ const transaction = result.Transaction ?? result.FailedTransaction
253
+ if (transaction) {
254
+ // Executed: the stored bytes are no longer needed.
54
255
  statusManager.updateAction(step, action.type, 'PENDING', {
55
256
  txHash: transaction.digest,
56
- txLink: `${fromChain.metamask.blockExplorerUrls[0]}txblock/${transaction.digest}`,
257
+ txLink: getSuiTxLink(fromChain, transaction.digest),
258
+ txHex: undefined,
57
259
  })
260
+ }
58
261
 
59
- if (isBridgeExecution) {
60
- statusManager.updateAction(step, action.type, 'DONE')
61
- }
262
+ if (!transaction?.status.success) {
263
+ throw new TransactionError(
264
+ LiFiErrorCode.TransactionFailed,
265
+ `Transaction failed: ${transaction?.status.error?.message ?? `Unexpected transaction result: ${result.$kind}`}`,
266
+ undefined,
267
+ // Executed and failed on chain: final. A malformed answer is not.
268
+ transaction ? { final: true } : undefined
269
+ )
270
+ }
62
271
 
63
- return { status: 'COMPLETED' }
272
+ if (isBridgeExecution) {
273
+ statusManager.updateAction(step, action.type, 'DONE')
64
274
  }
275
+
276
+ return { status: 'COMPLETED' }
277
+ }
278
+
279
+ function dropped(
280
+ context: SuiStepExecutorContext,
281
+ action: ExecutionAction
282
+ ): TransactionError {
283
+ context.statusManager.updateAction(context.step, action.type, 'PENDING', {
284
+ txHex: undefined,
285
+ })
286
+ return new TransactionError(
287
+ LiFiErrorCode.TransactionExpired,
288
+ 'Transaction expired before it was executed.',
289
+ undefined,
290
+ { final: true }
291
+ )
65
292
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Runs one call to one node with its own abort signal and a budget of
3
+ * `timeoutMs`. Past the budget it aborts the call and rejects with a
4
+ * `TimeoutError`, so a node that accepts the connection and never answers
5
+ * cannot hold the caller open. The race does not rely on the transport to
6
+ * honour the abort, and the `finally` clears the timer on every exit.
7
+ *
8
+ * A timeout says nothing about the transaction: it is never a "not found",
9
+ * so the outcome stays unknown.
10
+ *
11
+ * The gRPC `timeout` call option is not enough: the gRPC-web transport only
12
+ * sends it as the `grpc-timeout` header, which a node that never answers
13
+ * ignores. Not `AbortSignal.timeout`: a published SDK should not raise its
14
+ * runtime floor for it.
15
+ */
16
+ export async function callWithinDeadline<T>(
17
+ call: (signal: AbortSignal) => PromiseLike<T>,
18
+ timeoutMs: number
19
+ ): Promise<T> {
20
+ const controller = new AbortController()
21
+ let timer: ReturnType<typeof setTimeout> | undefined
22
+ const deadline = new Promise<never>((_resolve, reject) => {
23
+ timer = setTimeout(() => {
24
+ const error = createTimeoutError(timeoutMs)
25
+ controller.abort(error)
26
+ reject(error)
27
+ }, timeoutMs)
28
+ })
29
+ try {
30
+ return await Promise.race([
31
+ // A synchronous throw of `call` becomes a rejection too.
32
+ new Promise<T>((resolve) => resolve(call(controller.signal))),
33
+ deadline,
34
+ ])
35
+ } finally {
36
+ clearTimeout(timer)
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The name makes the gRPC transport report the abort as DEADLINE_EXCEEDED,
42
+ * as for any timeout.
43
+ */
44
+ function createTimeoutError(timeoutMs: number): Error {
45
+ const error = new Error(`The Sui node did not answer within ${timeoutMs} ms.`)
46
+ error.name = 'TimeoutError'
47
+ return error
48
+ }