Understanding Ethereum Transaction Queries
When interacting with Ethereum smart contracts, retrieving transaction details is a fundamental task. There are two primary methods to obtain transaction information from the Ethereum network:
Method 1: Using eth_getTransactionByHash
This RPC call returns the complete transaction details when provided with a valid transaction hash.
func (eth *Http) GetTransactionByHash(hash string) (interface{}, error) {
if len(hash) != 66 {
return nil, errors.New("Invalid transaction hash length")
}
args := []interface{}{hash}
params := NewHttpParams("eth_getTransactionByHash", args)
resBody, err := eth.rpc.HttpRequest(params)
if err != nil {
return nil, err
}
return eth.ParseJsonRPCResponse(resBody)
}
Method 2: Using eth_getTransactionReceipt
This returns the transaction receipt containing important execution details like gas used and contract events.
func (eth *Http) GetTransactionReceipt(hash string) (interface{}, error) {
if len(hash) != 66 {
return nil, errors.New("Invalid transaction hash length")
}
args := []interface{}{hash}
params := NewHttpParams("eth_getTransactionReceipt", args)
resBody, err := eth.rpc.HttpRequest(params)
if err != nil {
return nil, err
}
return eth.ParseJsonRPCResponse(resBody)
}
Calculating Transaction Confirmations
Ethereum transactions gain confirmations as new blocks are added to the blockchain. Here's how to calculate them:
Step-by-Step Process
- Get the transaction's block number from the receipt
- Query the current latest block number
- Calculate:
Confirmations = LatestBlock - TxBlock + 1
func (eth *Http) getTxConfirms(hash string) (int, error) {
receipt, err := eth.GetTransactionReceipt(hash)
if err != nil {
return 0, err
}
currentBlockRes, err := eth.rpc.HttpRequest(
NewHttpParams("eth_blockNumber", []interface{}{}))
if err != nil {
return 0, err
}
currentBlock, _ := strconv.ParseInt(currentBlockRes.(string), 0, 64)
txBlock, _ := strconv.ParseInt(receipt.BlockNumber, 0, 64)
return int(currentBlock - txBlock + 1), nil
}
๐ Learn more about Ethereum development
Best Practices for Transaction Monitoring
- Always validate hash length (66 characters)
- Implement proper error handling
- Cache frequent queries to reduce RPC calls
- Consider using WebSocket subscriptions for real-time updates
FAQ
Q: How many confirmations are considered safe?
A: For most applications, 12-15 confirmations provide adequate security. High-value transactions may require more.
Q: Can I query pending transactions?
A: Yes, but they won't have block numbers or confirmations until mined.
Q: What's the difference between transaction and receipt?
A: The transaction contains input data, while the receipt contains execution results like gas used and logs.
Q: How long do Ethereum transactions typically take?
A: Under normal network conditions, transactions usually confirm within 15-30 seconds.
๐ Explore advanced blockchain tools