Caravan Documentation
    Preparing search index...

    Class TransactionAnalyzer

    TransactionAnalyzer Class

    This class provides comprehensive analysis of Bitcoin transactions, including fee estimation, RBF (Replace-By-Fee) and CPFP (Child-Pays-For-Parent) capabilities. It's designed to help wallet developers make informed decisions about fee bumping strategies for unconfirmed transactions.

    Key Features:

    • Analyzes transaction inputs, outputs, fees, and size
    • Determines RBF and CPFP eligibility
    • Recommends optimal fee bumping strategy
    • Estimates fees for RBF and CPFP operations
    • Provides detailed transaction information for wallet integration

    Usage: const analyzer = new TransactionAnalyzer({txHex,...other-options}); const analysis = analyzer.analyze();

    As this is a public-facing class, any input transaction IDs (txid) returned by its methods are provided in big-endian format, consistent with how they appear in UIs and block explorers.

    If you are using these txids internally for raw Bitcoin protocol operations, you may need to reverse them to little-endian using a helper such as reverseHex().

    For more information on byte order in Bitcoin, see:

    Index

    Constructors

    Accessors

    • get canRBF(): boolean

      Checks if RBF (Replace-By-Fee) can be performed on this transaction.

      RBF allows unconfirmed transactions to be replaced with a new version that pays a higher fee. There are two types of RBF:

      1. Signaled RBF (BIP125): At least one input has a sequence number < 0xfffffffe.
      2. Full RBF: Replacing any unconfirmed transaction, regardless of signaling.

      This method determines if RBF is possible based on three criteria:

      1. The transaction signals RBF (or full RBF is assumed).
      2. The wallet controls at least one input of the transaction.
      3. The necessary input is available in the wallet's UTXO set.

      It uses the transaction's input templates and compares them against the available UTXOs to ensure that the wallet has control over at least one input, which is necessary for RBF.

      While BIP125 defines the standard for signaled RBF, some nodes and miners may accept full RBF, allowing replacement of any unconfirmed transaction.

      CAUTION: Assuming full RBF when a transaction doesn't signal it may lead to:

      • Rejected replacements by nodes not accepting full RBF
      • Delayed or failed transaction replacement
      • Potential double-spend risks if recipients accept unconfirmed transactions

      Returns boolean

      True if RBF can be performed (signaled or assumed), false otherwise

    • get CPFPPackageSize(): number

      Calculates the total package size for a potential CPFP transaction. This includes the size of the current (parent) transaction and the estimated size of the child transaction.

      Returns number

      The total package size in vbytes

    • get minimumCPFPFee(): string

      Calculates the minimum total fee required for a successful CPFP (Child-Pays-For-Parent) operation.

      This method calculates the fee needed for a child transaction to boost the fee rate of the current (parent) transaction using the CPFP technique. It considers:

      1. The current transaction's size and fee
      2. An estimated size for a simple child transaction (1 input, 1 output)
      3. The target fee rate for the combined package (parent + child)

      The calculation aims to determine how much additional fee the child transaction needs to contribute to bring the overall package fee rate up to the target.

      Assumptions:

      • The child transaction will have 1 input (spending an output from this transaction)
      • The child transaction will have 1 output (change back to the user's wallet)
      • The multisig configuration (m-of-n) is the same as the parent transaction

      References:

      Returns string

      The estimated additional CPFP fee in satoshis. This value represents how much extra fee the child transaction should include above its own minimum required fee. A positive value indicates the amount of additional fee required. A zero or negative value (rare) could indicate that the current transaction's fee is already sufficient for the desired rate.

    • get minimumRBFFee(): string

      Calculates the minimum total fee required for a valid RBF (Replace-By-Fee) replacement transaction.

      This method determines the minimum fee needed to replace the current transaction using the RBF protocol, as defined in BIP 125. It considers two key factors:

      1. The current transaction fee
      2. The minimum required fee increase (incremental relay fee * transaction size)

      Key considerations:

      • BIP 125 Rule 4: Replacement must pay for its own bandwidth at minimum relay fee This rule doesn't explicitly consider fee rates, focusing on anti-DDoS protection.
      • Modern mining preferences favor higher fee rates over absolute fees.

      The calculation ensures that the new transaction meets the minimum fee increase required by the RBF rules, which is: minimum_fee = original_fee + (incremental_relay_fee * transaction_size)

      References:

      Returns string

      The minimum total fee required for the replacement transaction in satoshis. This is always at least the current fee plus the minimum required increase. * Note: This getter does not consider the user's target fee rate. It's the responsibility of the RBF function to ensure that the new transaction's fee is the maximum of this minimum fee and the fee calculated using the user's target fee rate.

    • get vsize(): number

      Gets the virtual size (vsize) of the transaction in virtual bytes. Note: This uses bitcoinjs-lib's implementation which applies Math.ceil() for segwit transactions, potentially slightly overestimating the vsize. This is generally acceptable, especially for fee bumping scenarios.

      Returns number

      The virtual size of the transaction

    Methods

    • Performs a comprehensive analysis of the Bitcoin transaction.

      This method aggregates various metrics and properties of the transaction, including size, fees, RBF and CPFP capabilities, and the recommended fee bumping strategy. It utilizes internal calculations and checks performed by other methods of the TransactionAnalyzer class.

      Returns TxAnalysis

      A TxAnalysis object containing detailed information about the transaction.

      May throw an error if any of the internal calculations fail.

      const txAnalyzer = new TransactionAnalyzer(options);
      try {
      const analysis = txAnalyzer.analyze();
      console.log(`Transaction ${analysis.txid} analysis:`);
      console.log(`Fee rate: ${analysis.feeRate} sat/vB`);
      console.log(`Can RBF: ${analysis.canRBF}`);
      console.log(`Can CPFP: ${analysis.canCPFP}`);
      console.log(`Recommended strategy: ${analysis.recommendedStrategy}`);
      } catch (error) {
      console.error('Analysis failed:', error);
      }
    • Protected

      Deserializes and formats the transaction inputs.

      This method processes the raw input data from the original transaction and converts it into a more easily manageable format. It performs the following operations for each input:

      1. Reverses the transaction ID (txid) from little-endian to big-endian format.
      2. Extracts the output index (vout) being spent.
      3. Captures the sequence number, which is used for RBF signaling.

      Returns BtcTxInputTemplate[]

    • Protected

      Deserializes and formats the transaction outputs.

      This method processes the raw output data from the original transaction and converts it into a more easily manageable format. It performs the following operations for each output:

      1. Extracts the output value in satoshis.
      2. Derives the recipient address from the scriptPubKey.
      3. Determines if the output is spendable (i.e., if it's a change output).

      Returns BtcTxOutputTemplate[]

    • Creates input templates from the transaction's inputs.

      This method maps each input of the analyzed transaction to a BtcTxInputTemplate. It extracts the transaction ID (txid) and output index (vout) from each input to create the templates. Note that the amount in satoshis is not included, as this information is not available in the raw transaction data.

      Returns BtcTxInputTemplate[]

      An array of BtcTxInputTemplate objects representing the inputs of the analyzed transaction. These templates will not have amounts set and will need to be populated later with data from an external source (e.g., bitcoind wallet, blockchain explorer, or local UTXO set).

      Each input's txid will be in big-endian format, consistent with how TXIDs are typically displayed in block explorers and user interfaces.

      If you are performing any low-level Bitcoin protocol operations with these inputs (e.g. signing, hashing, or PSBT creation), ensure that you convert the txid to little-endian byte order as required by the Bitcoin protocol.

    • Creates output templates from the transaction's outputs.

      This method maps each output of the analyzed transaction to a BtcTxOutputTemplate. It extracts the recipient address, determines whether it's a change output or not, and includes the amount in satoshis. The output type is set to "change" if the output is spendable (typically indicating a change output), and "destination" otherwise.

      Returns BtcTxOutputTemplate[]

      An array of BtcTxOutputTemplate objects representing the outputs of the analyzed transaction.