Skip to content

Conversation

@sourovafrin
Copy link
Contributor

@sourovafrin sourovafrin commented Nov 7, 2025

enhance error handling

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling for TRON transaction submissions. Transactions now properly validate responses and return decoded error messages on failure, providing consistent and clear feedback across all transaction types instead of silent failures.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 7, 2025

📝 Walkthrough

Walkthrough

The TRON client's transaction sending logic was refactored to validate transaction success via the returned result flag from sendRawTransaction(). When the result is falsy, an error is thrown with a decoded UTF-8 message instead of proceeding with a potentially invalid transaction ID. This error handling is applied consistently across memo-augmented TRX transfers, standard TRX transfers, and TRC20 transfers.

Changes

Cohort / File(s) Summary
TRON client transaction error handling
packages/xchain-tron/src/client.ts
Added validation of the result flag from sendRawTransaction() across all transaction paths. Now throws exceptions with decoded error messages when result is falsy, replacing silent failures or invalid txid returns. Applied to memo-augmented TRX, non-memo TRX, and TRC20 transfer code paths.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Multiple transaction paths affected with consistent pattern changes (memo-augmented TRX, standard TRX, TRC20)
  • Error message decoding logic requires verification
  • Core functionality change that impacts transaction validation—ensure proper error propagation and that existing tests account for new exception handling

Suggested reviewers

  • Naq302

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is vague and generic, using non-descriptive language that fails to convey the specific nature of the changes in the changeset. Consider using a more specific title such as 'Add error handling for sendRawTransaction in TRON client' to better describe the actual changes made.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/xchain-tron/src/client.ts (2)

587-593: Apply consistent error handling to the approve() method.

The approve() method calls sendRawTransaction but doesn't check the result flag like the updated transfer() method does. This inconsistency means approval failures may not be caught or reported properly.

Apply this diff:

 const signedTx = await this.signTransaction(transaction, walletIndex)
-const { txid } = await this.tronWeb.trx.sendRawTransaction(signedTx)
-
-if (!txid) {
-  throw new Error('TRC20 Approve Failed')
-}
-
-return txid
+const { result, txid, message } = await this.tronWeb.trx.sendRawTransaction(signedTx)
+if (!result) {
+  const errorMessage = message 
+    ? Buffer.from(message, 'hex').toString('utf8') 
+    : 'TRC20 Approve Failed'
+  throw new Error(errorMessage)
+}
+return txid

596-599: Apply consistent error handling to the broadcastTransaction() method.

This public method calls sendRawTransaction without checking the result flag, which is inconsistent with the enhanced error handling added to transfer(). Callers won't receive proper error feedback when broadcasts fail.

Apply this diff:

 public async broadcastTransaction(signedTx: TronSignedTransaction): Promise<TxHash> {
-  const { txid } = await this.tronWeb.trx.sendRawTransaction(signedTx)
-  return txid
+  const { result, txid, message } = await this.tronWeb.trx.sendRawTransaction(signedTx)
+  if (!result) {
+    const errorMessage = message 
+      ? Buffer.from(message, 'hex').toString('utf8') 
+      : 'Transaction broadcast failed'
+    throw new Error(errorMessage)
+  }
+  return txid
 }
🧹 Nitpick comments (1)
packages/xchain-tron/src/client.ts (1)

483-486: Extract repeated error handling logic into a helper function.

The error handling pattern for sendRawTransaction is duplicated three times. This violates the DRY principle and makes the code harder to maintain.

Add a helper method to the class:

private async sendRawTransactionWithErrorHandling(signedTx: TronSignedTransaction): Promise<string> {
  const { result, txid, message } = await this.tronWeb.trx.sendRawTransaction(signedTx)
  if (!result) {
    const errorMessage = message 
      ? Buffer.from(message, 'hex').toString('utf8') 
      : 'Transaction broadcast failed'
    throw new Error(errorMessage)
  }
  return txid
}

Then replace all three occurrences:

 const signedTx = await this.signTransaction(transactionWithMemo, walletIndex)
-const { result, txid, message } = await this.tronWeb.trx.sendRawTransaction(signedTx)
-if (!result) {
-  throw new Error(Buffer.from(message, 'hex').toString('utf8'))
-}
-return txid
+return await this.sendRawTransactionWithErrorHandling(signedTx)

Also applies to: 491-494, 502-506

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a79ac42 and d4dff4a.

📒 Files selected for processing (1)
  • packages/xchain-tron/src/client.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: mrtommyit
Repo: xchainjs/xchainjs-lib PR: 1536
File: packages/xchain-tron/src/clientKeystore.ts:33-36
Timestamp: 2025-09-16T14:38:22.826Z
Learning: In packages/xchain-tron/src/clientKeystore.ts, the signTransaction method within getSigner() should not have additional error handling wrapped around this.tronWeb.trx.sign() calls, as the method is used internally and the maintainer prefers the current error handling approach.
📚 Learning: 2025-09-16T14:38:22.826Z
Learnt from: mrtommyit
Repo: xchainjs/xchainjs-lib PR: 1536
File: packages/xchain-tron/src/clientKeystore.ts:33-36
Timestamp: 2025-09-16T14:38:22.826Z
Learning: In packages/xchain-tron/src/clientKeystore.ts, the signTransaction method within getSigner() should not have additional error handling wrapped around this.tronWeb.trx.sign() calls, as the method is used internally and the maintainer prefers the current error handling approach.

Applied to files:

  • packages/xchain-tron/src/client.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build

Comment on lines +483 to +486
const { result, txid, message } = await this.tronWeb.trx.sendRawTransaction(signedTx)
if (!result) {
throw new Error(Buffer.from(message, 'hex').toString('utf8'))
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add defensive handling for the error message field.

The code assumes message is always a valid hex-encoded string, but if it's undefined, null, or contains non-hex data, the decoded error message could be empty or produce unexpected output.

Apply this diff to handle edge cases:

 const { result, txid, message } = await this.tronWeb.trx.sendRawTransaction(signedTx)
 if (!result) {
-  throw new Error(Buffer.from(message, 'hex').toString('utf8'))
+  const errorMessage = message 
+    ? Buffer.from(message, 'hex').toString('utf8') 
+    : 'Transaction broadcast failed'
+  throw new Error(errorMessage)
 }
🤖 Prompt for AI Agents
In packages/xchain-tron/src/client.ts around lines 483 to 486, the code assumes
message is always a hex string; add defensive handling so that before decoding
you check message is a non-empty string and matches hex characters, decode only
when valid, otherwise fall back to using the raw message or a default like
'Unknown error'; wrap the decode in a try/catch to guard against Buffer.from
errors and construct the thrown Error with the decoded text or the fallback
value so you never attempt to decode undefined/null or non-hex input.

@Thorian1te
Copy link
Collaborator

Thorian1te commented Nov 11, 2025

looks good, can you run yarn update-packages from the base folder for changeset and follow the prompts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants