Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify TronTransaction raw transaction handling and remov… #126

Merged
merged 4 commits into from
Dec 19, 2024

Conversation

nomo-app
Copy link
Owner

@nomo-app nomo-app commented Dec 19, 2024

…e unused import

Summary by CodeRabbit

  • New Features

    • Enhanced JSON handling for different transaction types in the TronTransaction class, improving readability and structure.
    • Improved transaction fetching and processing logic in the UTXO analyzer, enhancing accuracy for unsupported and pending transactions.
  • Bug Fixes

    • Improved error handling for unsupported contract types in RPC transactions.
    • Enhanced error handling and logging in transaction simulation tests, providing better insights into failures.
  • Chores

    • Removed unused Tron protocol import from the generic_transaction.dart file.
    • Updated documentation generation workflow to trigger only on the main branch.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request introduces modifications to the Tron transaction handling in the codebase. The primary changes are in the TronTransaction class, where the fromJson method has been refactored to use pattern matching for parsing different transaction types. The method now handles TRC20, TRX, and RPC transactions with more structured and readable code. An import related to the Tron protocol has been removed from the generic_transaction.dart file, indicating potential changes in Tron transaction support. Additionally, the GitHub Actions workflow has been updated to restrict documentation generation to the main branch.

Changes

File Change Summary
lib/src/crypto/tron/entities/tron_transaction.dart - Refactored fromJson method with pattern matching
- Added specific handling for TRC20, TRX, and RPC transactions
- Improved JSON parsing logic and error handling
lib/src/domain/entities/generic_transaction.dart - Removed Tron-related import Tron.pb.dart
.github/workflows/dart.yml - Added job condition to restrict generate-docs execution to the main branch
lib/src/crypto/utxo/repositories/electrum_json_rpc_client.dart - Updated fetchPeers and getTransactionForSimulation methods for better handling of outputs and peers
lib/src/crypto/utxo/utils/send.dart - Enhanced error message in signInputs function for clarity
lib/src/crypto/utxo/utxo_analyzer.dart - Improved transaction fetching logic and added logging in fetchUTXOTransactions
test/no_ci/input_simulation_test.dart - Enhanced error handling in fetchUTXOTXByHash and simulateTx functions

Possibly Related PRs

  • Draft: adjust EVM feeInformation #123: The changes in this PR involve modifications to the EvmRpcInterface and related classes that handle transaction fees, which may relate to the fee handling logic in the fromJson method of the TronTransaction class in the main PR.

Suggested Reviewers

  • ThomasFercher

Poem

🐰 A Rabbit's Ode to Tron Transactions 🚀

Pattern matching, JSON so neat,
Transactions parsed with code so sweet.
TRC20 and TRX, a crypto dance,
Refactored logic takes its stance.
Hopping through bytes with rabbit might! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a5aba3 and c9b3c8a.

📒 Files selected for processing (2)
  • lib/src/crypto/tron/entities/tron_transaction.dart (1 hunks)
  • lib/src/domain/entities/generic_transaction.dart (0 hunks)
💤 Files with no reviewable changes (1)
  • lib/src/domain/entities/generic_transaction.dart

@@ -140,8 +140,7 @@ base class TronTransaction extends EVMTransaction {
);

final rawData = raw_data_hex.hexToBytes;
final tron.Transaction_raw rawTx =
tron.Transaction_raw.fromBuffer(rawData);
final Transaction_raw rawTx = Transaction_raw.fromBuffer(rawData);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add a null or empty-check for rawTx.contract to prevent runtime errors.

If rawTx.contract is empty, calling rawTx.contract.first will cause an out-of-range error. Consider adding a guard clause before accessing .first.

Proposed fix:

 if (json
     case {
       "txID": String hash,
       "net_usage": int _,
       "net_fee": int netFee,
       "energy_usage": int _,
       "energy_fee": int energyFee,
       "blockNumber": int block,
       "block_timestamp": int block_timestamp,
       "raw_data_hex": String raw_data_hex,
     }) {
   final fee = Amount(
     value: BigInt.from(netFee + energyFee),
     decimals: 6,
   );

   final rawData = raw_data_hex.hexToBytes;
+  // Guard check for empty contract list
+  if (rawData.isEmpty) {
+    return null; // or handle appropriately
+  }
 
-  final Transaction_raw rawTx = Transaction_raw.fromBuffer(rawData);
+  final rawTx = Transaction_raw.fromBuffer(rawData);
+  if (rawTx.contract.isEmpty) {
+    return null; // or handle appropriately
+  }
   final contract = rawTx.contract.first;
   ...
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link

@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: 0

🧹 Nitpick comments (2)
.github/workflows/dart.yml (2)

57-57: LGTM! Remove trailing space.

The condition to restrict documentation generation to the main branch is a good security practice. It prevents unintended documentation updates from pull requests.

-    if: github.ref == 'refs/heads/main' 
+    if: github.ref == 'refs/heads/main'
🧰 Tools
🪛 yamllint (1.35.1)

[error] 57-57: trailing spaces

(trailing-spaces)


Line range hint 19-99: Consider optimizing the workflow structure.

The workflow could benefit from the following improvements:

  1. Extract common setup steps (Dart SDK, dependencies) into a reusable composite action
  2. Consider using GitHub Actions artifacts to pass documentation between jobs
  3. Add a dependency between jobs to ensure linting passes before documentation generation

Example optimization:

jobs:
  setup:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Dart SDK
        uses: dart-lang/setup-dart@v1
        with:
          sdk: 'stable'
      - name: Get dependencies
        run: |
          dart pub get
          cd packages/bip39 && dart pub get
      - name: Cache Dart setup
        uses: actions/cache@v3
        with:
          path: |
            .dart_tool
            packages/bip39/.dart_tool
          key: ${{ runner.os }}-dart-${{ hashFiles('**/pubspec.lock') }}

  lint:
    needs: setup
    # ... rest of lint job

  generate-docs:
    needs: [setup, lint]
    if: github.ref == 'refs/heads/main'
    # ... rest of generate-docs job
🧰 Tools
🪛 yamllint (1.35.1)

[error] 57-57: trailing spaces

(trailing-spaces)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c9b3c8a and 54e18d3.

📒 Files selected for processing (1)
  • .github/workflows/dart.yml (1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
.github/workflows/dart.yml

[error] 57-57: trailing spaces

(trailing-spaces)

Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 54e18d3 and d983fa7.

📒 Files selected for processing (4)
  • lib/src/crypto/utxo/repositories/electrum_json_rpc_client.dart (1 hunks)
  • lib/src/crypto/utxo/utils/send.dart (1 hunks)
  • lib/src/crypto/utxo/utxo_analyzer.dart (1 hunks)
  • test/no_ci/input_simulation_test.dart (2 hunks)
🔇 Additional comments (4)
lib/src/crypto/utxo/repositories/electrum_json_rpc_client.dart (1)

156-163: LGTM! Good simplification of output handling.

The changes improve code clarity by using .nonNulls and directly passing the outputs list, while maintaining the same functionality.

test/no_ci/input_simulation_test.dart (1)

206-206: LGTM! Enhanced error handling for electrum node operations.

The addition of error capture and assertion improves the robustness of the transaction fetching process.

Also applies to: 224-225

lib/src/crypto/utxo/utils/send.dart (2)

294-294: LGTM! More descriptive error message for signing failures.

The enhanced error message now includes output and input details, which will help with debugging when signing fails due to a missing node.


Line range hint 156-163: Verify the impact of output handling changes.

Let's verify that the simplified output handling doesn't affect other parts of the codebase.

✅ Verification successful

Let me gather more context about the usage of this function to ensure a thorough verification.


Let me check one more aspect to verify the output handling changes.


Output handling changes are localized and safe

The verification shows that:

  • The assertion logic for total input/output value matching is unique to this file
  • The getTransactionForSimulation usage in tests and repository is independent of these output handling changes
  • No other parts of the codebase rely on or replicate this specific output validation pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other uses of getTransactionForSimulation to ensure compatibility
rg -l "getTransactionForSimulation" --type dart

# Search for patterns that might be affected by the .nonNulls change
ast-grep --pattern 'getTransactionForSimulation($$$).then($$$outputs$$$)'

Length of output: 224


Script:

#!/bin/bash
# Check the actual implementation and usage in the test file
rg "getTransactionForSimulation" test/no_ci/input_simulation_test.dart -B 2 -A 2

# Check the implementation in the repository file
rg "getTransactionForSimulation" lib/src/crypto/utxo/repositories/electrum_json_rpc_client.dart -B 2 -A 2

# Look for related output handling patterns
ast-grep --pattern 'buildOutputs($$$)'

Length of output: 499


Script:

#!/bin/bash
# Check for any direct references to totalInputValue and output handling
rg "totalInputValue.*==.*targetValue.*changeValue.*estimatedFee" --type dart -B 2 -A 2

# Look for similar assertion patterns in the codebase
rg "assert.*Total.*Input.*Value.*match.*Output.*Value" --type dart -B 2 -A 2

# Check for any other similar output building patterns
rg "buildOutputs.*targetValue.*changeValue" --type dart -B 2 -A 2

Length of output: 555

Comment on lines +260 to +265
print(
"Selected ${endpoints.map(
(e) => "$e",
)}",
);

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace print statement with Logger utility

The code already imports and uses a Logger utility throughout the file (e.g., Logger.log, Logger.logFetch). For consistency and better control over logging, consider using the Logger utility instead of print.

-  print(
-    "Selected ${endpoints.map(
-      (e) => "$e",
-    )}",
-  );
+  Logger.log(
+    "Selected ${endpoints.map(
+      (e) => "$e",
+    )}",
+  );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
print(
"Selected ${endpoints.map(
(e) => "$e",
)}",
);
Logger.log(
"Selected ${endpoints.map(
(e) => "$e",
)}",
);

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.

3 participants