CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web3-eth

Web3 module to interact with the Ethereum blockchain and smart contracts.

67

0.98x
Overview
Eval results
Files

transaction-utilities.mddocs/

Transaction Utilities

The transaction utilities provide helper functions for transaction building, formatting, validation, type detection, and processing workflows to simplify complex transaction operations.

Transaction Building and Formatting

transactionBuilder

Builds a complete transaction object with proper defaults and validation.

function transactionBuilder(options: TransactionBuilderOptions): Transaction;

interface TransactionBuilderOptions {
  from: Address;
  to?: Address;
  value?: Numbers;
  data?: Bytes;
  gas?: Numbers;
  gasPrice?: Numbers;
  maxFeePerGas?: Numbers;
  maxPriorityFeePerGas?: Numbers;
  nonce?: Numbers;
  type?: Numbers;
  accessList?: AccessList;
  chainId?: Numbers;
}

Usage Example:

import { transactionBuilder } from "web3-eth";

// Build a simple transfer transaction
const transaction = transactionBuilder({
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
  value: "1000000000000000000" // 1 ETH
});

console.log("Built transaction:", transaction);

// Build EIP-1559 transaction with full options
const eip1559Transaction = transactionBuilder({
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x1234567890123456789012345678901234567890",
  value: "500000000000000000",
  data: "0xa9059cbb000000000000000000000000...", // contract call data
  maxFeePerGas: "30000000000",
  maxPriorityFeePerGas: "2000000000",
  type: 2, // EIP-1559
  accessList: []
});

formatTransaction

Formats transaction objects according to specified data format requirements.

function formatTransaction(transaction: Transaction, returnFormat: DataFormat): FormattedTransaction;

Usage Example:

import { formatTransaction, DEFAULT_RETURN_FORMAT } from "web3-eth";

const rawTransaction = {
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
  value: "0xde0b6b3a7640000", // hex
  gas: "0x5208" // hex
};

// Format with different return formats
const formattedTx = formatTransaction(rawTransaction, {
  number: "NUMBER_NUMBER", // Convert hex numbers to decimal
  bytes: "BYTES_HEX" // Keep bytes as hex strings
});

console.log("Formatted transaction:", formattedTx);
// Result: { from: "0x742...", to: "0x8ba...", value: 1000000000000000000, gas: 21000 }

Transaction Type Detection

detectTransactionType

Automatically detects the transaction type based on its properties.

function detectTransactionType(transaction: Transaction): TransactionType;

type TransactionType = "0x0" | "0x1" | "0x2"; // Legacy, EIP-2930, EIP-1559

Usage Example:

import { detectTransactionType } from "web3-eth";

// Legacy transaction
const legacyTx = {
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
  value: "1000000000000000000",
  gasPrice: "20000000000"
};
console.log("Legacy type:", detectTransactionType(legacyTx)); // "0x0"

// EIP-2930 transaction (with access list)
const eip2930Tx = {
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x1234567890123456789012345678901234567890",
  gasPrice: "20000000000",
  accessList: []
};
console.log("EIP-2930 type:", detectTransactionType(eip2930Tx)); // "0x1"

// EIP-1559 transaction
const eip1559Tx = {
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
  maxFeePerGas: "30000000000",
  maxPriorityFeePerGas: "2000000000"
};
console.log("EIP-1559 type:", detectTransactionType(eip1559Tx)); // "0x2"

Transaction Preparation

prepareTransactionForSigning

Prepares a transaction for signing by filling in missing fields and validating parameters.

function prepareTransactionForSigning(
  transaction: Transaction, 
  web3Context: Web3Context, 
  privateKey?: HexString, 
  fillGasPrice?: boolean
): Promise<Transaction>;

Usage Example:

import { prepareTransactionForSigning } from "web3-eth";

// Prepare incomplete transaction
const incompleteTransaction = {
  from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
  to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
  value: "1000000000000000000"
  // Missing: nonce, gas, gasPrice/fees, chainId
};

// Prepare for signing (fills missing fields)
const preparedTx = await prepareTransactionForSigning(
  incompleteTransaction,
  eth, // Web3Eth instance
  undefined, // privateKey (optional)
  true // fillGasPrice
);

console.log("Prepared transaction:", preparedTx);
// Now includes: nonce, gas estimate, gas pricing, chainId

Address Resolution

getTransactionFromOrToAttr

Resolves from/to addresses when using wallet indices instead of addresses.

function getTransactionFromOrToAttr(
  attr: "from" | "to", 
  web3Context: Web3Context
): Promise<Address>;

Usage Example:

import { getTransactionFromOrToAttr } from "web3-eth";

// Transaction using wallet indices
const transactionWithIndices = {
  from: 0, // Use first account in wallet
  to: 1,   // Use second account in wallet  
  value: "1000000000000000000"
};

// Resolve actual addresses
const fromAddress = await getTransactionFromOrToAttr("from", eth);
const toAddress = await getTransactionFromOrToAttr("to", eth);

const resolvedTransaction = {
  ...transactionWithIndices,
  from: fromAddress,
  to: toAddress
};

Transaction Processing

waitForTransactionReceipt

Waits for a transaction to be mined and returns its receipt with configurable confirmation requirements.

function waitForTransactionReceipt(
  web3Context: Web3Context,
  transactionHash: HexString32Bytes,
  returnFormat?: DataFormat,
  options?: TransactionReceiptOptions
): Promise<TransactionReceipt>;

interface TransactionReceiptOptions {
  transactionConfirmationBlocks?: Numbers;
  transactionBlockTimeout?: Numbers;
  transactionReceiptPollingInterval?: Numbers;
}

Usage Example:

import { waitForTransactionReceipt } from "web3-eth";

// Send transaction and get hash
const txHash = "0xabcdef1234567890...";

// Wait with default settings
const receipt = await waitForTransactionReceipt(eth, txHash);
console.log("Transaction mined:", receipt.status === "0x1" ? "Success" : "Failed");

// Wait with custom confirmation requirements
const confirmedReceipt = await waitForTransactionReceipt(
  eth,
  txHash,
  DEFAULT_RETURN_FORMAT,
  {
    transactionConfirmationBlocks: 3, // Wait for 3 confirmations
    transactionBlockTimeout: 100, // Timeout after 100 blocks
    transactionReceiptPollingInterval: 2000 // Poll every 2 seconds
  }
);

console.log(`Transaction confirmed with ${confirmedReceipt.confirmations} confirmations`);

trySendTransaction

Sends a transaction with automatic retry logic and comprehensive error handling.

function trySendTransaction(
  web3Context: Web3Context,
  transaction: Transaction,
  returnFormat?: DataFormat,
  options?: SendTransactionOptions
): Promise<TransactionReceipt>;

Usage Example:

import { trySendTransaction } from "web3-eth";

// Send transaction with retry logic
try {
  const receipt = await trySendTransaction(
    eth,
    {
      from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
      to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
      value: "1000000000000000000"
    },
    DEFAULT_RETURN_FORMAT,
    {
      transactionConfirmationBlocks: 2,
      transactionBlockTimeout: 50
    }
  );
  
  console.log("Transaction successful:", receipt.transactionHash);
} catch (error) {
  console.error("Failed to send transaction after retries:", error);
}

Advanced Transaction Helpers

SendTxHelper

A comprehensive helper class for managing complex transaction sending workflows.

class SendTxHelper {
  constructor(web3Context: Web3Context);
  
  // Methods for transaction processing workflow
  checkRevertBeforeSend(transaction: Transaction): Promise<void>;
  signAndSend(transaction: Transaction): Promise<TransactionReceipt>;
  handleTransaction(transaction: Transaction, options?: SendTransactionOptions): Promise<TransactionReceipt>;
}

Usage Example:

import { SendTxHelper } from "web3-eth";

const txHelper = new SendTxHelper(eth);

// Use helper for complex transaction workflow
try {
  const receipt = await txHelper.handleTransaction({
    from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
    to: "0x1234567890123456789012345678901234567890",
    data: "0xa9059cbb000000000000000000000000..." // contract call
  }, {
    transactionConfirmationBlocks: 3,
    ignoreGasPricing: false
  });
  
  console.log("Complex transaction completed:", receipt);
} catch (error) {
  console.error("Transaction workflow failed:", error);
}

Transaction Validation and Analysis

Validation Helpers

// Validate transaction before sending
function validateTransaction(transaction: Transaction): { valid: boolean; errors: string[] } {
  const errors: string[] = [];
  
  if (!transaction.from) {
    errors.push("Missing 'from' address");
  }
  
  if (!transaction.to && !transaction.data) {
    errors.push("Transaction must have 'to' address or 'data' for contract creation");
  }
  
  if (transaction.value && Number(transaction.value) < 0) {
    errors.push("Transaction value cannot be negative");
  }
  
  if (transaction.gas && Number(transaction.gas) <= 0) {
    errors.push("Gas limit must be positive");
  }
  
  // EIP-1559 validation
  if (transaction.maxFeePerGas && transaction.maxPriorityFeePerGas) {
    if (Number(transaction.maxPriorityFeePerGas) > Number(transaction.maxFeePerGas)) {
      errors.push("Max priority fee cannot exceed max fee per gas");
    }
  }
  
  return { valid: errors.length === 0, errors };
}

// Estimate transaction cost
async function estimateTransactionCost(transaction: Transaction): Promise<TransactionCostEstimate> {
  const gasEstimate = await eth.estimateGas(transaction);
  const feeData = await eth.getFeeData();
  
  let maxCost: bigint;
  let expectedCost: bigint;
  
  if (transaction.maxFeePerGas) {
    // EIP-1559 transaction
    maxCost = BigInt(gasEstimate) * BigInt(transaction.maxFeePerGas);
    expectedCost = BigInt(gasEstimate) * (BigInt(feeData.maxFeePerGas || 0) + BigInt(transaction.maxPriorityFeePerGas || 0));
  } else {
    // Legacy transaction
    const gasPrice = transaction.gasPrice || feeData.gasPrice || "20000000000";
    maxCost = expectedCost = BigInt(gasEstimate) * BigInt(gasPrice);
  }
  
  return {
    gasEstimate: gasEstimate.toString(),
    maxCostWei: maxCost.toString(),
    expectedCostWei: expectedCost.toString(),
    maxCostEth: (Number(maxCost) / 1e18).toFixed(6),
    expectedCostEth: (Number(expectedCost) / 1e18).toFixed(6)
  };
}

Core Types

interface TransactionBuilderOptions {
  from: Address;
  to?: Address;
  value?: Numbers;
  data?: Bytes;
  gas?: Numbers;
  gasPrice?: Numbers;
  maxFeePerGas?: Numbers;
  maxPriorityFeePerGas?: Numbers;
  nonce?: Numbers;
  type?: Numbers;
  accessList?: AccessList;
  chainId?: Numbers;
}

interface TransactionReceiptOptions {
  transactionConfirmationBlocks?: Numbers;
  transactionBlockTimeout?: Numbers;
  transactionReceiptPollingInterval?: Numbers;
}

interface SendTransactionOptions<ResolveType = TransactionReceipt> {
  ignoreGasPricing?: boolean;
  transactionConfirmationBlocks?: Numbers;
  transactionBlockTimeout?: Numbers;
  transactionConfirmationPollingInterval?: Numbers;
  transactionReceiptPollingInterval?: Numbers;
  transactionSendTimeout?: Numbers;
  ignoreFillingGasLimit?: boolean;
  contractAbi?: AbilityType;
}

interface FormattedTransaction extends Transaction {
  // Transaction with values formatted according to DataFormat
}

interface TransactionCostEstimate {
  gasEstimate: string;
  maxCostWei: string;
  expectedCostWei: string;
  maxCostEth: string;
  expectedCostEth: string;
}

type TransactionType = "0x0" | "0x1" | "0x2"; // Legacy, EIP-2930, EIP-1559
type Address = HexString20Bytes;
type Numbers = HexString | number | bigint;
type Bytes = HexString;
type HexString32Bytes = string;

interface DataFormat {
  number: NumberFormat;
  bytes: BytesFormat;
}

Install with Tessl CLI

npx tessl i tessl/npm-web3-eth

docs

account-operations.md

blockchain-state.md

cryptographic-operations.md

event-monitoring.md

gas-fee-management.md

index.md

network-information.md

smart-contract-interaction.md

transaction-management.md

transaction-utilities.md

tile.json