⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

eth_getTransactionByHash

Returns the information about a transaction requested by transaction hash on Berachain.

When to Use This Method

eth_getTransactionByHash is essential for:

  • Transaction Tracking - Monitor transaction status and confirmation
  • Blockchain Analysis - Analyze transaction patterns and flows
  • Wallet Applications - Display transaction history and details
  • DeFi Integration - Track token transfers and contract interactions
  • Audit and Compliance - Verify transaction details for reporting

Parameters

  1. Transaction Hash - DATA, 32 bytes
    • The hash of a transaction
    • Format: 0x prefixed, 64 hex characters
    • Example: 0x1e2910a262b2a9ed0b4b0c8e5e6e2b4d8e1e2b3c4d5f6a7b8c9d0e1f2a3b4c5d
{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": [
"0x1e2910a262b2a9ed0b4b0c8e5e6e2b4d8e1e2b3c4d5f6a7b8c9d0e1f2a3b4c5d"
],
"id": 1
}

Returns

Transaction Object or null if no transaction is found:

  • hash - DATA, 32 bytes: Hash of the transaction
  • nonce - QUANTITY: Number of transactions sent by the sender prior to this one
  • blockHash - DATA, 32 bytes: Hash of the block containing this transaction (null if pending)
  • blockNumber - QUANTITY: Block number containing this transaction (null if pending)
  • transactionIndex - QUANTITY: Integer position in the block (null if pending)
  • from - DATA, 20 bytes: Address of the sender
  • to - DATA, 20 bytes: Address of the receiver (null for contract creation)
  • value - QUANTITY: Value transferred in wei
  • gasPrice - QUANTITY: Gas price provided by the sender in wei
  • gas - QUANTITY: Gas limit provided by the sender
  • input - DATA: Data sent along with the transaction
  • v, r, s - QUANTITY: ECDSA signature values
  • type - QUANTITY: Transaction type (0x0 for legacy, 0x2 for EIP-1559)
  • maxFeePerGas - QUANTITY: Maximum fee per gas (EIP-1559 transactions)
  • maxPriorityFeePerGas - QUANTITY: Maximum priority fee per gas (EIP-1559 transactions)
  • accessList - Array of access list entries (EIP-2930/EIP-1559 transactions)

Implementation Examples

# Get transaction details by hash
curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": [
"0x1e2910a262b2a9ed0b4b0c8e5e6e2b4d8e1e2b3c4d5f6a7b8c9d0e1f2a3b4c5d"
],
"id": 1
}'

# Check if transaction exists
curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": [
"0xnonexistenthash000000000000000000000000000000000000000000000000"
],
"id": 1
}'

Response Example

Successful Response (Confirmed Transaction)

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"hash": "0x1e2910a262b2a9ed0b4b0c8e5e6e2b4d8e1e2b3c4d5f6a7b8c9d0e1f2a3b4c5d",
"nonce": "0x15",
"blockHash": "0x8b535bf5c6cf7e1b5f9b8f7a9b5e9b3a2b8f7c6d5e4f3a2b1c0d9e8f7a6b5c4d",
"blockNumber": "0x5bad55",
"transactionIndex": "0x2",
"from": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"to": "0x8ba1f109551bD432803012645Hac136c8ab3b",
"value": "0x1bc16d674ec80000",
"gas": "0x5208",
"gasPrice": "0x174876e800",
"input": "0x",
"v": "0x1c",
"r": "0x9a3d...af6c",
"s": "0x6f1a...7b2e",
"type": "0x0"
}
}

Successful Response (Pending Transaction)

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"hash": "0x1e2910a262b2a9ed0b4b0c8e5e6e2b4d8e1e2b3c4d5f6a7b8c9d0e1f2a3b4c5d",
"nonce": "0x16",
"blockHash": null,
"blockNumber": null,
"transactionIndex": null,
"from": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"to": "0x8ba1f109551bD432803012645Hac136c8ab3b",
"value": "0x1bc16d674ec80000",
"gas": "0x5208",
"gasPrice": "0x174876e800",
"input": "0x",
"v": "0x1c",
"r": "0x9a3d...af6c",
"s": "0x6f1a...7b2e",
"type": "0x0"
}
}

Transaction Not Found

{
"jsonrpc": "2.0",
"id": 1,
"result": null
}

Common Use Cases

1. Transaction Status Tracking

Monitor transaction confirmation status:

class TransactionTracker {
constructor(provider) {
this.provider = provider;
}

async trackTransaction(txHash) {
const tx = await this.provider.getTransaction(txHash);

if (!tx) {
return { status: 'not_found' };
}

if (!tx.blockNumber) {
return {
status: 'pending',
transaction: tx
};
}

const currentBlock = await this.provider.getBlockNumber();
const confirmations = currentBlock - tx.blockNumber + 1;

const receipt = await this.provider.getTransactionReceipt(txHash);

return {
status: 'confirmed',
confirmations,
success: receipt.status === 1,
transaction: tx,
receipt
};
}

async waitForConfirmations(txHash, requiredConfirmations = 6) {
while (true) {
const result = await this.trackTransaction(txHash);

if (result.status === 'not_found') {
throw new Error('Transaction not found');
}

if (result.status === 'confirmed' && result.confirmations >= requiredConfirmations) {
return result;
}

console.log(`Confirmations: ${result.confirmations || 0}/${requiredConfirmations}`);
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
}

2. Transaction Analysis

Analyze transaction patterns and details:

async function analyzeTransaction(provider, txHash) {
const tx = await provider.getTransaction(txHash);
if (!tx) return null;

const analysis = {
hash: tx.hash,
type: 'unknown',
value: ethers.formatEther(tx.value),
gasPrice: ethers.formatUnits(tx.gasPrice, 'gwei'),
gasLimit: tx.gas.toString(),
from: tx.from,
to: tx.to
};

// Determine transaction type
if (!tx.to) {
analysis.type = 'contract_creation';
} else if (tx.data && tx.data !== '0x') {
analysis.type = 'contract_interaction';
analysis.inputSize = (tx.data.length - 2) / 2; // bytes
} else {
analysis.type = 'simple_transfer';
}

// Get execution results if available
if (tx.blockNumber) {
const receipt = await provider.getTransactionReceipt(txHash);
analysis.gasUsed = receipt.gasUsed.toString();
analysis.gasEfficiency = (Number(receipt.gasUsed) / Number(tx.gas) * 100).toFixed(2);
analysis.success = receipt.status === 1;
analysis.logCount = receipt.logs.length;
}

return analysis;
}

3. Batch Transaction Lookup

Efficiently look up multiple transactions:

async function batchGetTransactions(provider, txHashes) {
const batch = txHashes.map((hash, index) => ({
jsonrpc: '2.0',
method: 'eth_getTransactionByHash',
params: [hash],
id: index + 1
}));

const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});

const results = await response.json();

return results.map((result, index) => ({
hash: txHashes[index],
transaction: result.result,
found: result.result !== null
}));
}

4. Transaction History Builder

Build transaction history for an address:

async function buildTransactionHistory(provider, address, startBlock, endBlock) {
const history = [];

// This would typically use eth_getLogs or other methods to find transactions
// This is a simplified example
for (let blockNumber = startBlock; blockNumber <= endBlock; blockNumber++) {
const block = await provider.getBlock(blockNumber, true);

const relevantTxs = block.transactions.filter(tx =>
tx.from.toLowerCase() === address.toLowerCase() ||
tx.to?.toLowerCase() === address.toLowerCase()
);

for (const tx of relevantTxs) {
const receipt = await provider.getTransactionReceipt(tx.hash);

history.push({
hash: tx.hash,
blockNumber: tx.blockNumber,
timestamp: block.timestamp,
from: tx.from,
to: tx.to,
value: ethers.formatEther(tx.value),
gasUsed: receipt.gasUsed.toString(),
success: receipt.status === 1,
type: tx.from.toLowerCase() === address.toLowerCase() ? 'sent' : 'received'
});
}
}

return history.sort((a, b) => b.blockNumber - a.blockNumber);
}

Performance Optimization

Transaction Result Caching

Cache transaction results to reduce API calls:

class TransactionCache {
constructor(ttl = 300000) { // 5 minute cache for confirmed txs
this.cache = new Map();
this.ttl = ttl;
}

async getTransaction(provider, txHash) {
const cached = this.cache.get(txHash);

if (cached) {
// For pending transactions, check more frequently
if (!cached.data.blockNumber) {
if (Date.now() - cached.timestamp < 10000) { // 10 second cache for pending
return cached.data;
}
} else if (Date.now() - cached.timestamp < this.ttl) {
return cached.data;
}
}

const tx = await provider.getTransaction(txHash);

if (tx) {
this.cache.set(txHash, {
data: tx,
timestamp: Date.now()
});
}

return tx;
}

invalidate(txHash) {
this.cache.delete(txHash);
}

clear() {
this.cache.clear();
}
}

Batch Processing

Process multiple transaction lookups efficiently:

async function processTransactionBatch(provider, txHashes, concurrency = 10) {
const results = [];

for (let i = 0; i < txHashes.length; i += concurrency) {
const batch = txHashes.slice(i, i + concurrency);

const batchPromises = batch.map(async (hash) => {
try {
const tx = await provider.getTransaction(hash);
return { hash, transaction: tx, success: true };
} catch (error) {
return { hash, error: error.message, success: false };
}
});

const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
}

return results;
}

Error Handling

Common errors and solutions:

Error CodeDescriptionSolution
-32602Invalid paramsCheck transaction hash format (64 hex chars)
-32603Internal errorRetry with exponential backoff
-32000Transaction not foundVerify hash or wait if recently submitted
async function safeGetTransaction(provider, txHash, maxRetries = 3) {
// Validate hash format
if (!/^0x[a-fA-F0-9]{64}$/.test(txHash)) {
throw new Error('Invalid transaction hash format');
}

for (let i = 0; i < maxRetries; i++) {
try {
return await provider.getTransaction(txHash);
} catch (error) {
console.error(`Attempt ${i + 1} failed:`, error.message);

if (error.code === -32602) {
throw new Error(`Invalid transaction hash: ${error.message}`);
}

if (i === maxRetries - 1) {
throw error;
}

// Exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}

// Usage with comprehensive error handling
try {
const tx = await safeGetTransaction(provider, txHash);

if (!tx) {
console.log('Transaction not found - may not exist or not yet propagated');
return;
}

if (!tx.blockNumber) {
console.log('Transaction is pending');
} else {
console.log(`Transaction confirmed in block ${tx.blockNumber}`);
}

} catch (error) {
console.error('Failed to retrieve transaction:', error.message);
}

Transaction Validation Utilities

Hash Format Validation

function isValidTransactionHash(hash) {
return /^0x[a-fA-F0-9]{64}$/.test(hash);
}

function normalizeTransactionHash(hash) {
if (!hash.startsWith('0x')) {
hash = '0x' + hash;
}
return hash.toLowerCase();
}

Transaction Analysis

function analyzeTransactionGas(tx, receipt = null) {
const gasLimit = Number(tx.gas);
const gasPrice = Number(tx.gasPrice);
const maxCost = gasLimit * gasPrice;

const analysis = {
gasLimit,
gasPrice: gasPrice / 1e9, // in Gwei
maxCostWei: maxCost,
maxCostBera: maxCost / 1e18
};

if (receipt) {
const gasUsed = Number(receipt.gasUsed);
analysis.gasUsed = gasUsed;
analysis.actualCostWei = gasUsed * gasPrice;
analysis.actualCostBera = analysis.actualCostWei / 1e18;
analysis.gasEfficiency = (gasUsed / gasLimit * 100).toFixed(2) + '%';
}

return analysis;
}

Need help? Contact our support team or check the Berachain documentation.