Algorithms, Blockchain and Cloud

NodeJs/Javascript Function to Check if a Transaction is Confirmed on Tron Blockchain via TronGrid API


Sometimes, we want to know if a given transaction is confirmed on the Tron Blockchain, and we can easily do this via the TronGrid API.

tron-blockchain NodeJs/Javascript Function to Check if a Transaction is Confirmed on Tron Blockchain via TronGrid API

tron-blockchain

To ensure a transaction is confirmed on Tron, the validation logic should focus on the transaction’s status, which indicates whether it has been successfully processed by the Tron Virtual Machine (TVM). Here’s how you can verify it correctly:

Check the receipt.result

The primary indicator of a successful transaction is the receipt.result field. A value of “SUCCESS” confirms the transaction was processed without errors.

Confirm the Block Number

A transaction is only considered confirmed if it has been included in a block. Ensure transactionInfo.blockNumber is defined and matches the expected block.

Consider Additional Indicators

Some transactions may not produce net_usage but might incur net_fee. Checking for any resource usage, such as net_fee or net_usage, provides more robustness.

Avoid Premature Confirmation

Ensure the transaction is no longer pending and has been broadcasted successfully across the network.

The Validation Logic

Here is the logic that handles edge cases comprehensively:

const isConfirmed = transactionInfo =>
  transactionInfo.blockNumber !== undefined && // Transaction is included in a block
  transactionInfo.receipt && // Receipt is present
  (
    transactionInfo.receipt.result === 'SUCCESS' || // Explicit success result
    transactionInfo.receipt.net_usage > 0 || // Resources were used
    transactionInfo.receipt.net_fee > 0 // Fee was incurred
  );

Explanations:

  • transactionInfo.blockNumber: Ensures the transaction is part of the blockchain.
  • transactionInfo.receipt.result: Confirms the status of the transaction execution.
  • transactionInfo.receipt.net_usage / transactionInfo.receipt.net_fee: Verifies that resources were consumed, ensuring the transaction had a meaningful effect.

Best Practices:

  • Monitor Transaction Events: Use TronGrid’s event subscription capabilities to track confirmation status in real-time.
  • Add a Confirmation Wait: Wait for multiple block confirmations to reduce the risk of a reorganization invalidating the transaction.
  • Log and Handle Errors: If the transaction fails, investigate error details in contractResult and logs.

This approach ensures robust and reliable transaction confirmation for Tron-based systems.

Complete Javascript Function to Verify a Tron Transaction

Below is the NodeJs (Javascript) Function that can be used to confirm or verify a transaction on the Tron Blockchain, via the TronGrid API. You would also need the axios library to perform the HTTPS API call.

const axios = require('axios');

async function isTransactionConfirmed(transactionID, appKey) {
    try {
        const response = await axios.post(
            'https://api.trongrid.io/walletsolidity/gettransactioninfobyid',
            { value: transactionID },
            {
                headers: {
                    'accept': 'application/json',
                    'content-type': 'application/json',
                    'TRON-PRO-API-KEY': appKey
                }
            }
        );
  
        const transactionInfo = response.data;
        const isSuccess = (transactionInfo.receipt && transactionInfo.receipt.result === 'SUCCESS') || ((transactionInfo.blockNumber !== undefined) && (transactionInfo.receipt.net_usage > 0 || (transactionInfo.receipt.net_fee > 0)));
        const blockNumber = transactionInfo.blockNumber;
        
        console.log(`BlockNumber ${blockNumber}, ${JSON.stringify(transactionInfo)} Transaction ID: ${transactionID} - Status: ${isSuccess ? 'Confirmed' : 'Failed'}`);
        if (!isSuccess) {
            console.log(JSON.stringify(transactionInfo));
        }
        return {
          "ok": isSuccess, 
          "block": blockNumber
        };
    } catch (error) {
        console.error('Error verifying transaction:', error);
        throw error;
    }
}

Tron Blockchain Posts

Here are some popular posts regarding the Tron Blockchain:

Tron Blockchain Programming

Here are some popular posts regarding the Tron Blockchain Programming:

–EOF (The Ultimate Computing & Technology Blog) —

627 words
Last Post: Introduction to Pi Coin: Is it Really a Blockchain-Based Cryptocurrency?
Next Post: How to do Leetcoding on LG OLED Smart TV (65 inch)?

The Permanent URL is: NodeJs/Javascript Function to Check if a Transaction is Confirmed on Tron Blockchain via TronGrid API (AMP Version)

Exit mobile version