eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Avalanche C-Chain.
When to Use This Method
eth_getTransactionReceipt
is essential for:
- Transaction Confirmation - Check if transaction was successful
- Event Log Retrieval - Get contract event logs from transaction
- Gas Usage Analysis - See actual gas used vs estimated
- Error Debugging - Retrieve revert reasons and failure details
Parameters
- Transaction Hash -
DATA
, 32 bytes- The hash of the transaction to get receipt for
- Format:
0x
prefixed, 64 hex characters
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": [
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
],
"id": 1
}
Returns
Object
- A transaction receipt object, or null
when no receipt was found:
transactionHash
- 32-byte hash of the transactiontransactionIndex
- Position in the blockblockHash
- Hash of the block containing the transactionblockNumber
- Block number in hexfrom
- Address of the senderto
- Address of the receiver (null for contract creation)cumulativeGasUsed
- Total gas used in block up to this transactiongasUsed
- Gas used by this specific transactioncontractAddress
- Address of contract created (if any)logs
- Array of log objects generated by this transactionstatus
- 1 for success, 0 for failureeffectiveGasPrice
- Actual gas price paid
Implementation Examples
- cURL
- JavaScript
- Python
- Go
curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": [
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
],
"id": 1
}'
import { JsonRpcProvider, formatEther } from 'ethers';
const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc');
// Get transaction receipt
async function getTransactionReceipt(txHash) {
const receipt = await provider.getTransactionReceipt(txHash);
if (!receipt) {
console.log('Transaction not found or not yet mined');
return null;
}
console.log('Transaction Status:', receipt.status === 1 ? 'Success' : 'Failed');
console.log('Block Number:', receipt.blockNumber);
console.log('Gas Used:', receipt.gasUsed.toString());
console.log('Effective Gas Price:', formatEther(receipt.effectiveGasPrice || 0));
console.log('Event Logs:', receipt.logs.length);
return receipt;
}
// Wait for transaction confirmation
async function waitForTransaction(txHash) {
console.log('Waiting for transaction confirmation...');
try {
// Wait for 1 confirmation (usually sufficient on Avalanche)
const receipt = await provider.waitForTransaction(txHash, 1);
if (receipt.status === 1) {
console.log('✅ Transaction confirmed successfully');
return { success: true, receipt };
} else {
console.log('❌ Transaction failed');
return { success: false, receipt };
}
} catch (error) {
console.error('Transaction failed:', error);
return { success: false, error: error.message };
}
}
// Analyze transaction costs
async function analyzeTxCosts(txHash) {
const receipt = await provider.getTransactionReceipt(txHash);
const tx = await provider.getTransaction(txHash);
if (!receipt || !tx) {
throw new Error('Transaction not found');
}
const gasUsed = Number(receipt.gasUsed);
const gasPrice = Number(receipt.effectiveGasPrice || tx.gasPrice);
const totalCost = gasUsed * gasPrice;
return {
gasLimit: Number(tx.gasLimit),
gasUsed: gasUsed,
gasEfficiency: ((gasUsed / Number(tx.gasLimit)) * 100).toFixed(2) + '%',
gasPrice: formatEther(gasPrice.toString()) + ' AVAX',
totalCost: formatEther(totalCost.toString()) + ' AVAX'
};
}
from web3 import Web3
import time
w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'))
def get_transaction_receipt(tx_hash):
"""Get transaction receipt by hash"""
try:
receipt = w3.eth.get_transaction_receipt(tx_hash)
return {
'status': 'Success' if receipt['status'] == 1 else 'Failed',
'block_number': receipt['blockNumber'],
'gas_used': receipt['gasUsed'],
'cumulative_gas_used': receipt['cumulativeGasUsed'],
'effective_gas_price': receipt.get('effectiveGasPrice', 0),
'logs_count': len(receipt['logs']),
'contract_address': receipt.get('contractAddress'),
'transaction_index': receipt['transactionIndex']
}
except Exception as e:
return {'error': str(e)}
def wait_for_transaction(tx_hash, timeout=60):
"""Wait for transaction to be mined"""
start_time = time.time()
while time.time() - start_time < timeout:
try:
receipt = w3.eth.get_transaction_receipt(tx_hash)
return receipt
except:
print(f"Transaction {tx_hash} not yet mined, waiting...")
time.sleep(2) # Check every 2 seconds
raise Exception(f"Transaction {tx_hash} not mined within {timeout} seconds")
def analyze_gas_usage(tx_hash):
"""Analyze gas usage efficiency"""
receipt = w3.eth.get_transaction_receipt(tx_hash)
tx = w3.eth.get_transaction(tx_hash)
gas_used = receipt['gasUsed']
gas_limit = tx['gas']
gas_price = receipt.get('effectiveGasPrice', tx['gasPrice'])
return {
'gas_limit': gas_limit,
'gas_used': gas_used,
'gas_efficiency': (gas_used / gas_limit) * 100,
'gas_price_gwei': w3.from_wei(gas_price, 'gwei'),
'total_cost_avax': w3.from_wei(gas_used * gas_price, 'ether')
}
package main
import (
"context"
"fmt"
"log"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238")
// Get transaction receipt
receipt, err := client.TransactionReceipt(context.Background(), txHash)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Transaction Status: %d\n", receipt.Status)
fmt.Printf("Block Number: %d\n", receipt.BlockNumber.Uint64())
fmt.Printf("Gas Used: %d\n", receipt.GasUsed)
fmt.Printf("Cumulative Gas Used: %d\n", receipt.CumulativeGasUsed)
fmt.Printf("Contract Address: %s\n", receipt.ContractAddress.Hex())
fmt.Printf("Logs Count: %d\n", len(receipt.Logs))
}
func waitForTransaction(client *ethclient.Client, txHash common.Hash) error {
for {
_, isPending, err := client.TransactionByHash(context.Background(), txHash)
if err != nil {
return err
}
if !isPending {
fmt.Println("Transaction mined!")
return nil
}
fmt.Println("Transaction pending, waiting...")
time.Sleep(2 * time.Second)
}
}
Response Example
Successful Response
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"transactionHash": "0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238",
"transactionIndex": "0x1",
"blockHash": "0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"blockNumber": "0xb",
"from": "0xaff3454fce5edbc8cca8697c15331677e6ebcccc",
"to": "0xfff7ac99c8e4feb60c9750054bdc14a3b2f0fb8",
"cumulativeGasUsed": "0x33bc",
"gasUsed": "0x4dc",
"contractAddress": null,
"logs": [
{
"address": "0xfff7ac99c8e4feb60c9750054bdc14a3b2f0fb8",
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0x000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebcccc",
"0x000000000000000000000000eff8bf1e28ffb1bfa76b6dc3e619d5a6e3b6b9b9"
],
"data": "0x000000000000000000000000000000000000000000000000000000000000000a"
}
],
"status": "0x1",
"effectiveGasPrice": "0x4a817c800"
}
}
Common Use Cases
1. Transaction Status Monitoring
Monitor transaction status in real-time:
class TransactionMonitor {
constructor(provider) {
this.provider = provider;
this.monitoring = new Map();
}
async startMonitoring(txHash, callback) {
if (this.monitoring.has(txHash)) {
return; // Already monitoring
}
const monitor = setInterval(async () => {
try {
const receipt = await this.provider.getTransactionReceipt(txHash);
if (receipt) {
clearInterval(monitor);
this.monitoring.delete(txHash);
callback({
success: receipt.status === 1,
receipt,
gasUsed: receipt.gasUsed.toString(),
blockNumber: receipt.blockNumber,
logs: receipt.logs
});
}
} catch (error) {
console.error('Error monitoring transaction:', error);
}
}, 1000); // Check every second
this.monitoring.set(txHash, monitor);
}
stopMonitoring(txHash) {
const monitor = this.monitoring.get(txHash);
if (monitor) {
clearInterval(monitor);
this.monitoring.delete(txHash);
}
}
}
2. Event Log Processing
Process contract events from transaction receipts:
async function processTransactionEvents(txHash) {
const receipt = await provider.getTransactionReceipt(txHash);
if (!receipt || !receipt.logs) {
return { events: [], status: 'no_events' };
}
const events = [];
// Process each log
for (const log of receipt.logs) {
// ERC20 Transfer event signature
const transferTopic = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
if (log.topics[0] === transferTopic && log.topics.length >= 3) {
events.push({
type: 'Transfer',
contract: log.address,
from: '0x' + log.topics[1].slice(26),
to: '0x' + log.topics[2].slice(26),
value: BigInt(log.data).toString()
});
}
// Add more event types as needed
}
return {
events,
status: receipt.status === 1 ? 'success' : 'failed',
gasUsed: receipt.gasUsed.toString(),
blockNumber: receipt.blockNumber
};
}
3. Gas Optimization Analysis
Analyze gas usage patterns:
async function analyzeGasOptimization(txHashes) {
const analyses = [];
for (const txHash of txHashes) {
const receipt = await provider.getTransactionReceipt(txHash);
const tx = await provider.getTransaction(txHash);
if (receipt && tx) {
const gasUsed = Number(receipt.gasUsed);
const gasLimit = Number(tx.gasLimit);
const efficiency = (gasUsed / gasLimit) * 100;
analyses.push({
txHash,
gasLimit,
gasUsed,
efficiency: efficiency.toFixed(2) + '%',
status: receipt.status === 1 ? 'Success' : 'Failed',
gasSaved: gasLimit - gasUsed,
recommendation: efficiency > 95 ? 'Consider increasing gas limit' :
efficiency < 50 ? 'Gas limit too high' : 'Optimal'
});
}
}
// Calculate overall statistics
const avgEfficiency = analyses.reduce((sum, a) =>
sum + parseFloat(a.efficiency), 0) / analyses.length;
return {
transactions: analyses,
stats: {
totalTransactions: analyses.length,
avgEfficiency: avgEfficiency.toFixed(2) + '%',
successRate: (analyses.filter(a => a.status === 'Success').length / analyses.length * 100).toFixed(2) + '%'
}
};
}
4. Contract Creation Detection
Detect and analyze contract deployments:
async function analyzeContractDeployment(txHash) {
const receipt = await provider.getTransactionReceipt(txHash);
const tx = await provider.getTransaction(txHash);
if (!receipt || !tx) {
throw new Error('Transaction not found');
}
// Check if it's a contract creation
if (receipt.contractAddress) {
// Get contract code to verify deployment
const code = await provider.getCode(receipt.contractAddress);
return {
isContractDeployment: true,
contractAddress: receipt.contractAddress,
deploymentSuccessful: code !== '0x' && receipt.status === 1,
deployerAddress: tx.from,
gasUsedForDeployment: receipt.gasUsed.toString(),
blockNumber: receipt.blockNumber,
constructorEvents: receipt.logs.length
};
}
return {
isContractDeployment: false,
transactionType: 'regular_transaction'
};
}
Performance Optimization
Receipt Caching
Cache transaction receipts (they're immutable once mined):
class ReceiptCache {
constructor() {
this.cache = new Map();
}
async getReceipt(provider, txHash) {
if (this.cache.has(txHash)) {
return this.cache.get(txHash);
}
const receipt = await provider.getTransactionReceipt(txHash);
// Only cache confirmed receipts
if (receipt && receipt.blockNumber) {
this.cache.set(txHash, receipt);
}
return receipt;
}
clear() {
this.cache.clear();
}
}
Batch Receipt Queries
Query multiple receipts efficiently:
async function batchGetReceipts(txHashes) {
const batch = txHashes.map((hash, i) => ({
jsonrpc: '2.0',
method: 'eth_getTransactionReceipt',
params: [hash],
id: i
}));
const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
const results = await response.json();
return results.map((r, i) => ({
txHash: txHashes[i],
receipt: r.result
}));
}
Error Handling
Common errors and solutions:
Error Code | Description | Solution |
---|---|---|
-32602 | Invalid transaction hash | Ensure hash is 64 hex chars with 0x prefix |
-32000 | Transaction not found | Transaction may not be mined yet |
null result | Transaction pending | Wait and retry |
async function safeGetTransactionReceipt(txHash, maxRetries = 10) {
for (let i = 0; i < maxRetries; i++) {
try {
const receipt = await provider.getTransactionReceipt(txHash);
if (receipt) {
return { success: true, receipt };
}
// Transaction might be pending
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
}
} catch (error) {
if (error.code === -32602) {
return { success: false, error: 'Invalid transaction hash format' };
}
if (i === maxRetries - 1) {
return { success: false, error: error.message };
}
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before retry
}
}
return { success: false, error: 'Transaction not found after maximum retries' };
}
Need help? Contact our support team or check the Avalanche documentation.