@lifi/sdk-provider-tron 4.1.5 → 4.1.7

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 (88) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +9 -0
  3. package/dist/cjs/actions/getTronBalance.js +2 -1
  4. package/dist/cjs/actions/getTronBalance.js.map +1 -1
  5. package/dist/cjs/core/TronStepExecutor.js +8 -5
  6. package/dist/cjs/core/TronStepExecutor.js.map +1 -1
  7. package/dist/cjs/core/constants.d.ts +3 -0
  8. package/dist/cjs/core/constants.js +6 -0
  9. package/dist/cjs/core/constants.js.map +1 -1
  10. package/dist/cjs/core/tasks/TronCheckAllowanceTask.js +2 -1
  11. package/dist/cjs/core/tasks/TronCheckAllowanceTask.js.map +1 -1
  12. package/dist/cjs/core/tasks/TronSignAndExecuteTask.js +11 -1
  13. package/dist/cjs/core/tasks/TronSignAndExecuteTask.js.map +1 -1
  14. package/dist/cjs/core/tasks/TronWaitForTransactionTask.js +63 -15
  15. package/dist/cjs/core/tasks/TronWaitForTransactionTask.js.map +1 -1
  16. package/dist/cjs/core/tasks/helpers/isTronTransactionDropped.d.ts +22 -0
  17. package/dist/cjs/core/tasks/helpers/isTronTransactionDropped.js +88 -0
  18. package/dist/cjs/core/tasks/helpers/isTronTransactionDropped.js.map +1 -0
  19. package/dist/cjs/rpc/broadcastTronTransaction.d.ts +31 -0
  20. package/dist/cjs/rpc/broadcastTronTransaction.js +68 -0
  21. package/dist/cjs/rpc/broadcastTronTransaction.js.map +1 -0
  22. package/dist/cjs/rpc/waitForTronTxConfirmation.d.ts +5 -3
  23. package/dist/cjs/rpc/waitForTronTxConfirmation.js +7 -5
  24. package/dist/cjs/rpc/waitForTronTxConfirmation.js.map +1 -1
  25. package/dist/cjs/utils/trc20Abi.d.ts +10 -0
  26. package/dist/cjs/utils/trc20Abi.js +39 -0
  27. package/dist/cjs/utils/trc20Abi.js.map +1 -0
  28. package/dist/cjs/utils/tronSignedTransaction.d.ts +19 -0
  29. package/dist/cjs/utils/tronSignedTransaction.js +40 -0
  30. package/dist/cjs/utils/tronSignedTransaction.js.map +1 -0
  31. package/dist/cjs/version.d.ts +1 -1
  32. package/dist/cjs/version.js +1 -1
  33. package/dist/cjs/version.js.map +1 -1
  34. package/dist/esm/actions/getTronBalance.d.ts.map +1 -1
  35. package/dist/esm/actions/getTronBalance.js +2 -1
  36. package/dist/esm/actions/getTronBalance.js.map +1 -1
  37. package/dist/esm/core/TronStepExecutor.d.ts.map +1 -1
  38. package/dist/esm/core/TronStepExecutor.js +9 -6
  39. package/dist/esm/core/TronStepExecutor.js.map +1 -1
  40. package/dist/esm/core/constants.d.ts +3 -0
  41. package/dist/esm/core/constants.d.ts.map +1 -1
  42. package/dist/esm/core/constants.js +4 -1
  43. package/dist/esm/core/constants.js.map +1 -1
  44. package/dist/esm/core/tasks/TronCheckAllowanceTask.d.ts.map +1 -1
  45. package/dist/esm/core/tasks/TronCheckAllowanceTask.js +2 -1
  46. package/dist/esm/core/tasks/TronCheckAllowanceTask.js.map +1 -1
  47. package/dist/esm/core/tasks/TronSignAndExecuteTask.d.ts.map +1 -1
  48. package/dist/esm/core/tasks/TronSignAndExecuteTask.js +12 -2
  49. package/dist/esm/core/tasks/TronSignAndExecuteTask.js.map +1 -1
  50. package/dist/esm/core/tasks/TronWaitForTransactionTask.d.ts.map +1 -1
  51. package/dist/esm/core/tasks/TronWaitForTransactionTask.js +64 -16
  52. package/dist/esm/core/tasks/TronWaitForTransactionTask.js.map +1 -1
  53. package/dist/esm/core/tasks/helpers/isTronTransactionDropped.d.ts +22 -0
  54. package/dist/esm/core/tasks/helpers/isTronTransactionDropped.d.ts.map +1 -0
  55. package/dist/esm/core/tasks/helpers/isTronTransactionDropped.js +87 -0
  56. package/dist/esm/core/tasks/helpers/isTronTransactionDropped.js.map +1 -0
  57. package/dist/esm/rpc/broadcastTronTransaction.d.ts +31 -0
  58. package/dist/esm/rpc/broadcastTronTransaction.d.ts.map +1 -0
  59. package/dist/esm/rpc/broadcastTronTransaction.js +67 -0
  60. package/dist/esm/rpc/broadcastTronTransaction.js.map +1 -0
  61. package/dist/esm/rpc/waitForTronTxConfirmation.d.ts +5 -3
  62. package/dist/esm/rpc/waitForTronTxConfirmation.d.ts.map +1 -1
  63. package/dist/esm/rpc/waitForTronTxConfirmation.js +7 -5
  64. package/dist/esm/rpc/waitForTronTxConfirmation.js.map +1 -1
  65. package/dist/esm/utils/trc20Abi.d.ts +10 -0
  66. package/dist/esm/utils/trc20Abi.d.ts.map +1 -0
  67. package/dist/esm/utils/trc20Abi.js +38 -0
  68. package/dist/esm/utils/trc20Abi.js.map +1 -0
  69. package/dist/esm/utils/tronSignedTransaction.d.ts +19 -0
  70. package/dist/esm/utils/tronSignedTransaction.d.ts.map +1 -0
  71. package/dist/esm/utils/tronSignedTransaction.js +38 -0
  72. package/dist/esm/utils/tronSignedTransaction.js.map +1 -0
  73. package/dist/esm/version.d.ts +1 -1
  74. package/dist/esm/version.js +1 -1
  75. package/dist/esm/version.js.map +1 -1
  76. package/package.json +2 -2
  77. package/src/actions/getTronBalance.ts +2 -1
  78. package/src/core/TronStepExecutor.ts +29 -8
  79. package/src/core/constants.ts +12 -0
  80. package/src/core/tasks/TronCheckAllowanceTask.ts +2 -1
  81. package/src/core/tasks/TronSignAndExecuteTask.ts +32 -0
  82. package/src/core/tasks/TronWaitForTransactionTask.ts +153 -33
  83. package/src/core/tasks/helpers/isTronTransactionDropped.ts +159 -0
  84. package/src/rpc/broadcastTronTransaction.ts +92 -0
  85. package/src/rpc/waitForTronTxConfirmation.ts +13 -5
  86. package/src/utils/trc20Abi.ts +26 -0
  87. package/src/utils/tronSignedTransaction.ts +53 -0
  88. package/src/version.ts +1 -1
@@ -6,6 +6,7 @@ import { callTronRpcsWithRetry } from '../rpc/callTronRpcsWithRetry.js'
6
6
  import { encodeAddressCalldata, toEvmHex } from '../utils/address.js'
7
7
  import { isZeroAddress } from '../utils/isZeroAddress.js'
8
8
  import { multicall3Abi } from '../utils/multicall3Abi.js'
9
+ import { TRC20_ABI } from '../utils/trc20Abi.js'
9
10
  import { getMulticallAddress } from './getMulticallAddress.js'
10
11
 
11
12
  const BALANCE_OF_SELECTOR = TronWeb.sha3('balanceOf(address)').slice(2, 10)
@@ -141,7 +142,7 @@ const getTronBalanceDefault = async (
141
142
  }
142
143
  return withDedupe(
143
144
  async () => {
144
- const contract = await tronWeb.contract().at(token.address)
145
+ const contract = tronWeb.contract(TRC20_ABI, token.address)
145
146
  const balance = await contract
146
147
  .balanceOf(walletAddress)
147
148
  .call({ from: walletAddress })
@@ -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,
@@ -81,25 +82,45 @@ export class TronStepExecutor extends BaseStepExecutor {
81
82
  isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'
82
83
  )
83
84
 
85
+ // A transaction signed for this action may still land (`txHash` after a
86
+ // broadcast, `txHex` right after signing). Resume at the confirmation wait:
87
+ // re-checking the allowance, re-preparing or re-signing could execute the
88
+ // swap twice. A final failure is not open, so "Try again" signs anew.
89
+ const isTransactionOpen = hasOpenTransaction(swapOrBridgeAction)
90
+
84
91
  const doCheckAllowance =
85
- !swapOrBridgeAction?.txHash &&
92
+ !isTransactionOpen &&
86
93
  !isFromNativeToken &&
87
94
  !!step.estimate.approvalAddress &&
88
95
  !step.estimate.skipApproval
89
96
 
90
- let taskName: string
97
+ let firstTask:
98
+ | typeof TronCheckAllowanceTask
99
+ | typeof TronWaitForTransactionTask
100
+ | typeof WaitForTransactionStatusTask
101
+ | typeof CheckBalanceTask
91
102
  if (doCheckAllowance) {
92
- taskName = TronCheckAllowanceTask.name
103
+ firstTask = TronCheckAllowanceTask
104
+ } else if (isTransactionOpen) {
105
+ firstTask =
106
+ swapOrBridgeAction?.status === 'DONE'
107
+ ? WaitForTransactionStatusTask
108
+ : TronWaitForTransactionTask
93
109
  } else {
94
- taskName =
95
- swapOrBridgeAction?.txHash && swapOrBridgeAction?.status === 'DONE'
96
- ? WaitForTransactionStatusTask.name
97
- : CheckBalanceTask.name
110
+ firstTask = CheckBalanceTask
98
111
  }
99
112
 
113
+ // Compare classes, not names: a minifier can give two task classes the
114
+ // same name.
100
115
  const firstTaskIndex = tasks.findIndex(
101
- (task) => task.constructor.name === taskName
116
+ (task) => task.constructor === firstTask
102
117
  )
118
+ if (firstTaskIndex === -1) {
119
+ throw new TransactionError(
120
+ LiFiErrorCode.InternalError,
121
+ 'TronStepExecutor.createPipeline: first task not found'
122
+ )
123
+ }
103
124
 
104
125
  const tasksToRun = tasks.slice(firstTaskIndex)
105
126
 
@@ -7,3 +7,15 @@ export const TRON_POLL_MAX_ERROR_RETRIES = 5
7
7
 
8
8
  // Max tokens per aggregate3 multicall — avoids Tron node CPU timeouts on large lists.
9
9
  export const DEFAULT_MULTICALL_BATCH_SIZE = 50
10
+
11
+ // `getCurrentRefBlockParams` sets `raw_data.expiration` to the ref block time
12
+ // + 60 s. The ref block time is the earliest time the transaction can land.
13
+ export const TRON_EXPIRATION_OFFSET_MS = 60_000
14
+ // A node's "not found" counts only while its head is less than this past the
15
+ // earliest landing time: every node type keeps at least this much history
16
+ // (lite fullnodes keep 65,536 blocks, about 54 h). Tron has no call that
17
+ // proves coverage in the lookup response itself.
18
+ export const TRON_LOOKUP_WINDOW_MS: number = 24 * 60 * 60 * 1000
19
+ // A node's "not found" also needs its head this far past the latest landing
20
+ // time: more than a healthy node lags behind the chain.
21
+ export const TRON_HEAD_MARGIN_MS: number = 5 * 60_000
@@ -6,6 +6,7 @@ import {
6
6
  } from '@lifi/sdk'
7
7
  import { callTronRpcsWithRetry } from '../../rpc/callTronRpcsWithRetry.js'
8
8
  import type { TronStepExecutorContext } from '../../types.js'
9
+ import { TRC20_ABI } from '../../utils/trc20Abi.js'
9
10
 
10
11
  export class TronCheckAllowanceTask extends BaseStepExecutionTask {
11
12
  override async shouldRun(context: TronStepExecutorContext): Promise<boolean> {
@@ -42,7 +43,7 @@ export class TronCheckAllowanceTask extends BaseStepExecutionTask {
42
43
  const fromAmount = BigInt(step.action.fromAmount)
43
44
 
44
45
  const allowance = await callTronRpcsWithRetry(client, async (tronWeb) => {
45
- const contract = await tronWeb.contract().at(tokenAddress)
46
+ const contract = tronWeb.contract(TRC20_ABI, tokenAddress)
46
47
  const result = await contract
47
48
  .allowance(ownerAddress, spenderAddress)
48
49
  .call({ from: ownerAddress })
@@ -1,5 +1,7 @@
1
1
  import {
2
+ assertNoOpenTransaction,
2
3
  BaseStepExecutionTask,
4
+ CLEARED_TRANSACTION_FIELDS,
3
5
  LiFiErrorCode,
4
6
  type TaskResult,
5
7
  TransactionError,
@@ -9,6 +11,7 @@ import { utils } from 'tronweb'
9
11
  import { callTronRpcsWithRetry } from '../../rpc/callTronRpcsWithRetry.js'
10
12
  import type { TronStepExecutorContext } from '../../types.js'
11
13
  import { stripHexPrefix } from '../../utils/stripHexPrefix.js'
14
+ import { serializeTronSignedTransaction } from '../../utils/tronSignedTransaction.js'
12
15
 
13
16
  export class TronSignAndExecuteTask extends BaseStepExecutionTask {
14
17
  async run(context: TronStepExecutorContext): Promise<TaskResult> {
@@ -33,6 +36,10 @@ export class TronSignAndExecuteTask extends BaseStepExecutionTask {
33
36
  )
34
37
  }
35
38
 
39
+ // A transaction signed earlier for this action may still land. Signing a
40
+ // second one could execute the swap twice.
41
+ assertNoOpenTransaction(action)
42
+
36
43
  if (!step.transactionRequest?.data) {
37
44
  throw new TransactionError(
38
45
  LiFiErrorCode.TransactionUnprepared,
@@ -74,9 +81,34 @@ export class TronSignAndExecuteTask extends BaseStepExecutionTask {
74
81
  }
75
82
  )
76
83
 
84
+ // Checked again right before the wallet: a late write of an older run
85
+ // can merge its transaction into this action during the await above.
86
+ assertNoOpenTransaction(statusManager.findAction(step, action.type))
87
+
77
88
  const signedTransaction = await wallet.signTransaction(transaction)
78
89
 
90
+ // Checked once more after the wallet: a stopped run's late write can
91
+ // merge its transaction into this action while the prompt is open.
92
+ // Nothing awaits from here to the write below.
93
+ assertNoOpenTransaction(statusManager.findAction(step, action.type))
94
+
95
+ // Stored before the first broadcast, so a reload after signing resends
96
+ // these bytes instead of asking the user to sign again.
97
+ const txHex = serializeTronSignedTransaction(signedTransaction)
98
+ if (!txHex) {
99
+ // Without a txID and an expiration the transaction could not be tracked
100
+ // once sent. Nothing was sent yet, so "Try again" signs a new one.
101
+ throw new TransactionError(
102
+ LiFiErrorCode.TransactionUnprepared,
103
+ 'Unable to prepare transaction. The signed transaction is incomplete.'
104
+ )
105
+ }
106
+
107
+ // One write: the previous transaction's data is cleared together with
108
+ // storing the new bytes, so no stale hash can look open again.
79
109
  statusManager.updateAction(step, action.type, 'PENDING', {
110
+ ...CLEARED_TRANSACTION_FIELDS,
111
+ txHex,
80
112
  signedAt: Date.now(),
81
113
  })
82
114
 
@@ -1,14 +1,18 @@
1
1
  import {
2
2
  BaseStepExecutionTask,
3
+ type ExecutionAction,
4
+ isFinalTransactionError,
3
5
  LiFiErrorCode,
4
6
  type TaskResult,
5
7
  TransactionError,
6
8
  } from '@lifi/sdk'
7
- import { callTronRpcsWithRetry } from '../../rpc/callTronRpcsWithRetry.js'
9
+ import { broadcastTronTransaction } from '../../rpc/broadcastTronTransaction.js'
8
10
  import { waitForTronTxConfirmation } from '../../rpc/waitForTronTxConfirmation.js'
9
11
  import type { TronStepExecutorContext } from '../../types.js'
10
12
  import { getTronTxLink } from '../../utils/getTronTxLink.js'
11
13
  import { stripHexPrefix } from '../../utils/stripHexPrefix.js'
14
+ import { parseTronSignedTransaction } from '../../utils/tronSignedTransaction.js'
15
+ import { isTronTransactionDropped } from './helpers/isTronTransactionDropped.js'
12
16
 
13
17
  export class TronWaitForTransactionTask extends BaseStepExecutionTask {
14
18
  async run(context: TronStepExecutorContext): Promise<TaskResult> {
@@ -21,13 +25,6 @@ export class TronWaitForTransactionTask extends BaseStepExecutionTask {
21
25
  signedTransaction,
22
26
  } = context
23
27
 
24
- if (!signedTransaction) {
25
- throw new TransactionError(
26
- LiFiErrorCode.TransactionUnprepared,
27
- 'Unable to prepare transaction. Signed transaction is not found.'
28
- )
29
- }
30
-
31
28
  const action = statusManager.findAction(
32
29
  step,
33
30
  isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'
@@ -39,39 +36,162 @@ export class TronWaitForTransactionTask extends BaseStepExecutionTask {
39
36
  )
40
37
  }
41
38
 
42
- const broadcastResult = await callTronRpcsWithRetry(
43
- client,
44
- async (tronWeb) => {
45
- const result = await tronWeb.trx.sendRawTransaction(signedTransaction)
46
-
47
- if (!result.result && String(result.code) !== 'DUP_TRANSACTION_ERROR') {
48
- throw new TransactionError(
49
- LiFiErrorCode.TransactionFailed,
50
- `Transaction broadcast failed: ${result.code || 'Unknown error'}`
51
- )
39
+ if (signedTransaction) {
40
+ const broadcast = await broadcastTronTransaction(
41
+ client,
42
+ signedTransaction
43
+ )
44
+ if (broadcast.status !== 'accepted') {
45
+ if (broadcast.status === 'rejected') {
46
+ // Every node refused the transaction before its pending pool (or
47
+ // no node was tried), so no node holds it. Drop the stored bytes:
48
+ // "Try again" signs a new one.
49
+ statusManager.updateAction(step, action.type, 'PENDING', {
50
+ txHex: undefined,
51
+ })
52
52
  }
53
+ // A network error or a code after the push may leave the transaction
54
+ // on a node, so an unknown outcome keeps the bytes for the resume.
55
+ throw broadcast.error
56
+ }
57
+
58
+ statusManager.updateAction(step, action.type, 'PENDING', {
59
+ txHash: broadcast.txHash,
60
+ txLink: getTronTxLink(fromChain, broadcast.txHash),
61
+ })
62
+
63
+ return confirm(context, action, broadcast.txHash, {
64
+ expiration: signedTransaction.raw_data.expiration,
65
+ })
66
+ }
67
+
68
+ // Resuming: the signing task did not run in this session. Continue with
69
+ // the bytes and the hash persisted on the action; never sign again.
70
+ const storedTransaction = action.txHex
71
+ ? parseTronSignedTransaction(action.txHex)
72
+ : undefined
53
73
 
54
- return result
74
+ if (action.txHex && !storedTransaction) {
75
+ // Damaged stored bytes can never be sent or looked up.
76
+ statusManager.updateAction(step, action.type, 'PENDING', {
77
+ txHex: undefined,
78
+ })
79
+ if (!action.txHash) {
80
+ // No node ever accepted these bytes, so "Try again" signs again.
81
+ throw new TransactionError(
82
+ LiFiErrorCode.TransactionUnprepared,
83
+ 'Unable to resume transaction. The stored signed transaction is invalid.'
84
+ )
55
85
  }
56
- )
86
+ }
57
87
 
58
- // DUP_TRANSACTION_ERROR responses omit the `transaction` field — fall back
59
- // to the txID computed locally from the signed transaction in that case.
60
- const txHash = stripHexPrefix(
61
- broadcastResult.transaction?.txID ?? signedTransaction.txID
62
- )
88
+ const storedTxId = storedTransaction
89
+ ? stripHexPrefix(storedTransaction.txID)
90
+ : undefined
63
91
 
64
- statusManager.updateAction(step, action.type, 'PENDING', {
65
- txHash,
66
- txLink: getTronTxLink(fromChain, txHash),
67
- })
92
+ if (
93
+ storedTxId &&
94
+ action.txHash &&
95
+ storedTxId.toLowerCase() !== stripHexPrefix(action.txHash).toLowerCase()
96
+ ) {
97
+ // Stored bytes whose txID is not the stored txHash (damaged storage)
98
+ // prove nothing about that transaction, and they may have been sent.
99
+ // Then the SDK neither sends nor drops; it only waits by txHash, and
100
+ // the outcome stays unknown.
101
+ return confirm(context, action, action.txHash, { mayDrop: false })
102
+ }
68
103
 
69
- await waitForTronTxConfirmation(client, txHash)
104
+ const txHash = action.txHash ?? storedTxId
70
105
 
71
- if (isBridgeExecution) {
72
- statusManager.updateAction(step, action.type, 'DONE')
106
+ if (!txHash) {
107
+ throw new TransactionError(
108
+ LiFiErrorCode.TransactionUnprepared,
109
+ 'Unable to prepare transaction. Signed transaction is not found.'
110
+ )
73
111
  }
74
112
 
75
- return { status: 'COMPLETED' }
113
+ const expiration = storedTransaction?.raw_data.expiration
114
+
115
+ if (await isTronTransactionDropped(client, step, txHash, expiration)) {
116
+ throw dropped(context, action)
117
+ }
118
+
119
+ if (storedTransaction) {
120
+ // The transaction may already be included, so a refusal says nothing
121
+ // about the outcome. The confirmation wait below decides it.
122
+ const broadcast = await broadcastTronTransaction(
123
+ client,
124
+ storedTransaction
125
+ )
126
+ if (broadcast.status === 'accepted' && !action.txHash) {
127
+ statusManager.updateAction(step, action.type, 'PENDING', {
128
+ txHash,
129
+ txLink: getTronTxLink(fromChain, txHash),
130
+ })
131
+ }
132
+ }
133
+
134
+ return confirm(context, action, txHash, { expiration })
76
135
  }
77
136
  }
137
+
138
+ /**
139
+ * Waits for the inclusion of `txHash`. After a timeout, the dropped rule runs
140
+ * with `options.expiration`; with `{ mayDrop: false }` it never runs, and the
141
+ * outcome stays unknown.
142
+ */
143
+ async function confirm(
144
+ context: TronStepExecutorContext,
145
+ action: ExecutionAction,
146
+ txHash: string,
147
+ options: { expiration: number | undefined } | { mayDrop: false }
148
+ ): Promise<TaskResult> {
149
+ const { client, step, statusManager, fromChain, isBridgeExecution } = context
150
+ // Included in a block: the stored bytes are no longer needed.
151
+ const included = {
152
+ txHash,
153
+ txLink: getTronTxLink(fromChain, txHash),
154
+ txHex: undefined,
155
+ }
156
+
157
+ try {
158
+ await waitForTronTxConfirmation(client, txHash)
159
+ } catch (error) {
160
+ if (isFinalTransactionError(error)) {
161
+ statusManager.updateAction(step, action.type, 'PENDING', included)
162
+ throw error
163
+ }
164
+ // The wait ended without a result. Only an expired transaction that no
165
+ // source knows is final; anything else stays unknown and keeps `txHex`.
166
+ if (
167
+ 'expiration' in options &&
168
+ (await isTronTransactionDropped(client, step, txHash, options.expiration))
169
+ ) {
170
+ throw dropped(context, action)
171
+ }
172
+ throw error
173
+ }
174
+
175
+ statusManager.updateAction(step, action.type, 'PENDING', included)
176
+
177
+ if (isBridgeExecution) {
178
+ statusManager.updateAction(step, action.type, 'DONE')
179
+ }
180
+
181
+ return { status: 'COMPLETED' }
182
+ }
183
+
184
+ function dropped(
185
+ context: TronStepExecutorContext,
186
+ action: ExecutionAction
187
+ ): TransactionError {
188
+ context.statusManager.updateAction(context.step, action.type, 'PENDING', {
189
+ txHex: undefined,
190
+ })
191
+ return new TransactionError(
192
+ LiFiErrorCode.TransactionExpired,
193
+ 'Transaction expired before it was included in a block.',
194
+ undefined,
195
+ { final: true }
196
+ )
197
+ }
@@ -0,0 +1,159 @@
1
+ import {
2
+ CLOCK_SKEW_MARGIN_MS,
3
+ isKnownToStatusApi,
4
+ isOldEnoughToDrop,
5
+ type LiFiStepExtended,
6
+ type SDKClient,
7
+ } from '@lifi/sdk'
8
+ import type { TronWeb } from 'tronweb'
9
+ import { callTronRpcsWithRetry } from '../../../rpc/callTronRpcsWithRetry.js'
10
+ import { stripHexPrefix } from '../../../utils/stripHexPrefix.js'
11
+ import {
12
+ TRON_EXPIRATION_OFFSET_MS,
13
+ TRON_HEAD_MARGIN_MS,
14
+ TRON_LOOKUP_WINDOW_MS,
15
+ } from '../../constants.js'
16
+
17
+ interface LandingWindow {
18
+ /** The earliest time the transaction can land (chain time). */
19
+ earliest: number
20
+ /** The latest time the transaction can land (chain time). */
21
+ latest: number
22
+ }
23
+
24
+ /**
25
+ * True only when the transaction can no longer land and no source knows it
26
+ * (see the resume rules in `transactionState.ts`):
27
+ * (a) it can no longer land: with a stored transaction, a node's head is past
28
+ * `raw_data.expiration` (block time, not `Date.now()`, so a wrong local
29
+ * clock cannot expire it); without one (routes stored before `txHex`),
30
+ * `isOldEnoughToDrop(signedAt)` on the local clock of the same device;
31
+ * (b) at least one covering node answers "not found" and no node returns the
32
+ * transaction. A node covers when its head is more than
33
+ * `TRON_HEAD_MARGIN_MS` past the latest landing time and less than
34
+ * `TRON_LOOKUP_WINDOW_MS` past the earliest one;
35
+ * (c) the LI.FI status API does not know the hash. It is a veto only: an
36
+ * unknown hash says nothing.
37
+ *
38
+ * Any lookup error leaves the outcome unknown and returns false. A `0x` prefix
39
+ * on `txHash` is removed first: a node does not find a prefixed txID.
40
+ */
41
+ export async function isTronTransactionDropped(
42
+ client: SDKClient,
43
+ step: LiFiStepExtended,
44
+ txHash: string,
45
+ expiration: number | undefined
46
+ ): Promise<boolean> {
47
+ try {
48
+ const window = getLandingWindow(step, expiration)
49
+ if (!window) {
50
+ return false
51
+ }
52
+ const txId = stripHexPrefix(txHash)
53
+ if ((await lookUpOnTronNodes(client, txId, window)) !== 'not-found') {
54
+ return false
55
+ }
56
+ return !(await isKnownToStatusApi(client, step, txId))
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ function getLandingWindow(
63
+ step: LiFiStepExtended,
64
+ expiration: number | undefined
65
+ ): LandingWindow | undefined {
66
+ if (expiration !== undefined) {
67
+ // Chain times carried by the transaction itself. The head condition in
68
+ // `lookUpOnTronNodes` is the expiry verdict (a).
69
+ return {
70
+ earliest: expiration - TRON_EXPIRATION_OFFSET_MS,
71
+ latest: expiration,
72
+ }
73
+ }
74
+ const signedAt = step.execution?.signedAt
75
+ if (signedAt === undefined || !isOldEnoughToDrop(signedAt)) {
76
+ return undefined
77
+ }
78
+ // Local signing time: the ref block was fetched just before signing, so the
79
+ // expiration is at most the signing time + 60 s, give or take the clock skew.
80
+ return {
81
+ earliest: signedAt - CLOCK_SKEW_MARGIN_MS,
82
+ latest: signedAt + CLOCK_SKEW_MARGIN_MS + TRON_EXPIRATION_OFFSET_MS,
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Asks every node. `found` as soon as one returns the transaction;
88
+ * `not-found` when none returns it and at least one covering node answered
89
+ * `{}`; `unknown` otherwise (errors, answers other than `{}` without `id`, or
90
+ * no node covers the window). A node without a head is still asked: its
91
+ * transaction vetoes, but its `{}` never counts.
92
+ */
93
+ async function lookUpOnTronNodes(
94
+ client: SDKClient,
95
+ txId: string,
96
+ window: LandingWindow
97
+ ): Promise<'found' | 'not-found' | 'unknown'> {
98
+ let coveringNotFound = 0
99
+ try {
100
+ await callTronRpcsWithRetry(client, async (tronWeb) => {
101
+ // The head comes first, so the lookup below sees at least this head.
102
+ const head = await getHeadTime(tronWeb)
103
+ // The full node answers: unlike `getTransactionInfo`, this call does not
104
+ // wait for the solidity node.
105
+ const txInfo: unknown =
106
+ await tronWeb.trx.getUnconfirmedTransactionInfo(txId)
107
+ if (hasId(txInfo)) {
108
+ return
109
+ }
110
+ // The full node answers `{}` for a transaction it has not included.
111
+ // Any other answer (an `{ Error }` body, an empty response) proves
112
+ // nothing and counts as a lookup error.
113
+ if (!isEmptyObject(txInfo)) {
114
+ throw new Error('The node answered neither the transaction nor {}.')
115
+ }
116
+ const covers =
117
+ head !== undefined &&
118
+ head > window.latest + TRON_HEAD_MARGIN_MS &&
119
+ head - window.earliest < TRON_LOOKUP_WINDOW_MS
120
+ if (covers) {
121
+ coveringNotFound++
122
+ }
123
+ // Throw so that `callTronRpcsWithRetry` asks the next node as well.
124
+ throw new Error('The node does not return the transaction.')
125
+ })
126
+ return 'found'
127
+ } catch {
128
+ return coveringNotFound > 0 ? 'not-found' : 'unknown'
129
+ }
130
+ }
131
+
132
+ /** The node's latest block time, or `undefined` when the request fails. */
133
+ async function getHeadTime(tronWeb: TronWeb): Promise<number | undefined> {
134
+ try {
135
+ const block = await tronWeb.trx.getCurrentBlock()
136
+ return block.block_header.raw_data.timestamp
137
+ } catch {
138
+ return undefined
139
+ }
140
+ }
141
+
142
+ function hasId(txInfo: unknown): boolean {
143
+ return (
144
+ typeof txInfo === 'object' &&
145
+ txInfo !== null &&
146
+ 'id' in txInfo &&
147
+ Boolean(txInfo.id)
148
+ )
149
+ }
150
+
151
+ /** Only a plain object without keys: `null` and `[]` do not count. */
152
+ function isEmptyObject(txInfo: unknown): boolean {
153
+ return (
154
+ typeof txInfo === 'object' &&
155
+ txInfo !== null &&
156
+ !Array.isArray(txInfo) &&
157
+ Object.keys(txInfo).length === 0
158
+ )
159
+ }
@@ -0,0 +1,92 @@
1
+ import { LiFiErrorCode, type SDKClient, TransactionError } from '@lifi/sdk'
2
+ import type { SignedTransaction } from '@tronweb3/tronwallet-abstract-adapter'
3
+ import { stripHexPrefix } from '../utils/stripHexPrefix.js'
4
+ import { callTronRpcsWithRetry } from './callTronRpcsWithRetry.js'
5
+
6
+ export type TronBroadcastResult =
7
+ | { status: 'accepted'; txHash: string }
8
+ | { status: 'rejected'; error: unknown }
9
+ | { status: 'unknown'; error: unknown }
10
+
11
+ /**
12
+ * The codes that java-tron's `Wallet.broadcastTransaction` returns before it
13
+ * puts the transaction into the node's pending pool: a node that answers one
14
+ * of them does not hold the transaction. Any other code proves nothing: for
15
+ * example, java-tron returns `NOT_ENOUGH_EFFECTIVE_CONNECTION` after the push,
16
+ * and `OTHER_ERROR` does not say at which step the broadcast failed.
17
+ */
18
+ const PRE_PUSH_REJECTION_CODES: ReadonlySet<string> = new Set([
19
+ 'SIGERROR',
20
+ 'BLOCK_UNSOLIDIFIED',
21
+ 'NO_CONNECTION',
22
+ 'SERVER_BUSY',
23
+ 'CONTRACT_VALIDATE_ERROR',
24
+ 'CONTRACT_EXE_ERROR',
25
+ // java-tron's spelling (api.proto `BANDWITH_ERROR = 4`). The HTTP API sends
26
+ // the enum name. `BANDWIDTH_ERROR` is a harmless alias.
27
+ 'BANDWITH_ERROR',
28
+ 'BANDWIDTH_ERROR',
29
+ 'TAPOS_ERROR',
30
+ 'TOO_BIG_TRANSACTION_ERROR',
31
+ 'TRANSACTION_EXPIRATION_ERROR',
32
+ ])
33
+
34
+ /**
35
+ * Broadcasts a signed transaction through the Tron RPCs in turn.
36
+ *
37
+ * - `accepted`: a node took the transaction. `DUP_TRANSACTION_ERROR` counts as
38
+ * accepted: the node already has it.
39
+ * - `rejected`: every node refused it with a code of
40
+ * `PRE_PUSH_REJECTION_CODES`, or no node was tried. No node holds the
41
+ * transaction.
42
+ * - `unknown`: at least one attempt failed in another way: a network error, a
43
+ * different code (for example `NOT_ENOUGH_EFFECTIVE_CONNECTION`, which comes
44
+ * after the push) or an answer without a code (such as an `{ Error }` body).
45
+ * That node may hold the transaction.
46
+ *
47
+ * `error` is what `callTronRpcsWithRetry` threw, unchanged.
48
+ */
49
+ export async function broadcastTronTransaction(
50
+ client: SDKClient,
51
+ signedTransaction: SignedTransaction
52
+ ): Promise<TronBroadcastResult> {
53
+ let attempts = 0
54
+ let rejections = 0
55
+ try {
56
+ const broadcastResult = await callTronRpcsWithRetry(
57
+ client,
58
+ async (tronWeb) => {
59
+ attempts++
60
+ const result = await tronWeb.trx.sendRawTransaction(signedTransaction)
61
+
62
+ if (!result.result && String(result.code) !== 'DUP_TRANSACTION_ERROR') {
63
+ // Only a pre-push code is a definite rejection. The message is
64
+ // never read.
65
+ if (PRE_PUSH_REJECTION_CODES.has(String(result.code))) {
66
+ rejections++
67
+ }
68
+ throw new TransactionError(
69
+ LiFiErrorCode.TransactionFailed,
70
+ `Transaction broadcast failed: ${result.code || 'Unknown error'}`
71
+ )
72
+ }
73
+
74
+ return result
75
+ }
76
+ )
77
+
78
+ // DUP_TRANSACTION_ERROR responses omit the `transaction` field — fall back
79
+ // to the txID computed locally from the signed transaction in that case.
80
+ return {
81
+ status: 'accepted',
82
+ txHash: stripHexPrefix(
83
+ broadcastResult.transaction?.txID ?? signedTransaction.txID
84
+ ),
85
+ }
86
+ } catch (error) {
87
+ return {
88
+ status: rejections === attempts ? 'rejected' : 'unknown',
89
+ error,
90
+ }
91
+ }
92
+ }