eth_getTransactionCount
Returns the total number of transactions sent from a specified account on the IoTeX network. This method provides the account's current nonce, which is fundamental for transaction sequencing and ensuring proper execution order on IoTeX's Layer 2 infrastructure.
Overview​
The eth_getTransactionCount
method is essential for IoTeX blockchain development, providing the transaction count that serves as the nonce for new transactions. On IoTeX's Optimistic Rollup, proper nonce management ensures transaction ordering and prevents replay attacks while maintaining compatibility with Ethereum tooling.
Parameters​
Parameter | Type | Required | Description |
---|---|---|---|
address | string | Yes | Ethereum address (20-byte hex with 0x prefix) to query transaction count |
blockNumber | string | Yes | Block reference: hex number, "latest", "earliest", "pending", "safe", "finalized" |
Block Reference Options​
"latest"
- Most recently mined block (recommended for confirmed count)"pending"
- Include pending transactions in mempool (use for next nonce)"earliest"
- Genesis block"safe"
- Latest safe block (L2 equivalent)"finalized"
- Latest finalized block on L1"0x..."
- Specific block number in hexadecimal format
Returns​
Type: string
Returns the transaction count as hexadecimal string (e.g., "0x2a" = 42 transactions). This represents:
- EOA (Externally Owned Account): Total transactions sent from this address
- Contract Account: Number of contract creations performed by this account
Use Cases​
- Transaction Sequencing: Obtain next nonce for transaction construction
- Wallet Applications: Display transaction history and account activity
- DApp Integration: Manage transaction ordering for smart contract interactions
- Account Monitoring: Track address activity and usage patterns
- IoTeX Bridge Operations: Coordinate L1/L2 transaction sequencing
Implementation Examples​
- cURL
- JavaScript
- Python
# Get confirmed transaction count
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"latest"
],
"id": 1
}'
# Get pending transaction count for next nonce
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"pending"
],
"id": 2
}'
# Get transaction count at specific block
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"0x1000000"
],
"id": 3
}'
// IoTeX transaction count utility
class IoTeXNonceManager {
constructor(apiKey) {
this.endpoint = `https://api-iotex-mainnet.n.dwellir.com/${apiKey}`;
}
async getTransactionCount(address, blockTag = 'latest') {
const response = await fetch(this.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getTransactionCount',
params: [address, blockTag],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`IoTeX RPC Error: ${data.error.message}`);
}
return data.result;
}
async getAccountActivity(address) {
// Get both confirmed and pending counts
const [confirmed, pending] = await Promise.all([
this.getTransactionCount(address, 'latest'),
this.getTransactionCount(address, 'pending')
]);
const confirmedCount = parseInt(confirmed, 16);
const pendingCount = parseInt(pending, 16);
return {
confirmed: confirmedCount,
pending: pendingCount,
pendingTxs: pendingCount - confirmedCount,
nextNonce: pending,
isActive: confirmedCount > 0
};
}
async waitForNonceUpdate(address, currentNonce, timeout = 30000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const latestNonce = await this.getTransactionCount(address, 'latest');
if (parseInt(latestNonce, 16) > parseInt(currentNonce, 16)) {
return latestNonce;
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
throw new Error('Timeout waiting for nonce update');
}
}
// Usage examples
const nonceManager = new IoTeXNonceManager('YOUR_API_KEY');
const uniswapAddress = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984';
// Get comprehensive account info
nonceManager.getAccountActivity(uniswapAddress)
.then(activity => {
console.log('IoTeX Account Activity:', activity);
console.log(`Total confirmed transactions: ${activity.confirmed}`);
console.log(`Pending transactions: ${activity.pendingTxs}`);
console.log(`Next nonce to use: ${activity.nextNonce}`);
});
import requests
import time
import asyncio
import aiohttp
class IoTeXTransactionCounter:
def __init__(self, api_key):
self.endpoint = f"https://api-iotex-mainnet.n.dwellir.com/{api_key}"
def get_transaction_count(self, address, block_tag="latest"):
"""Get transaction count for address on IoTeX"""
payload = {
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [address, block_tag],
"id": 1
}
response = requests.post(self.endpoint, json=payload)
result = response.json()
if 'error' in result:
raise Exception(f"IoTeX RPC Error: {result['error']['message']}")
return result['result']
def analyze_account_activity(self, address):
"""Comprehensive account analysis"""
try:
# Get transaction counts for different states
latest_hex = self.get_transaction_count(address, "latest")
pending_hex = self.get_transaction_count(address, "pending")
latest_count = int(latest_hex, 16)
pending_count = int(pending_hex, 16)
# Calculate activity metrics
pending_txs = pending_count - latest_count
analysis = {
'address': address,
'confirmed_transactions': latest_count,
'pending_transactions': pending_txs,
'total_pending_count': pending_count,
'next_nonce': pending_hex,
'next_nonce_decimal': pending_count,
'account_status': 'active' if latest_count > 0 else 'new',
'has_pending': pending_txs > 0
}
return analysis
except Exception as e:
return {'error': str(e), 'address': address}
def track_nonce_progression(self, address, start_nonce, max_wait=60):
"""Track nonce changes over time"""
start_time = time.time()
start_nonce_int = int(start_nonce, 16) if isinstance(start_nonce, str) else start_nonce
progression = []
while time.time() - start_time < max_wait:
current_nonce = self.get_transaction_count(address, "latest")
current_nonce_int = int(current_nonce, 16)
progression.append({
'timestamp': time.time(),
'nonce': current_nonce,
'decimal': current_nonce_int,
'elapsed': time.time() - start_time
})
if current_nonce_int > start_nonce_int:
break
time.sleep(2) # Check every 2 seconds
return progression
# Example usage
arbitrum_counter = IoTeXTransactionCounter("YOUR_API_KEY")
# Analyze Uniswap token contract activity
uniswap_token = "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"
analysis = arbitrum_counter.analyze_account_activity(uniswap_token)
print("IoTeX Account Analysis:")
print(f"Address: {analysis['address']}")
print(f"Confirmed Transactions: {analysis['confirmed_transactions']}")
print(f"Pending Transactions: {analysis['pending_transactions']}")
print(f"Next Nonce: {analysis['next_nonce']} ({analysis['next_nonce_decimal']})")
print(f"Account Status: {analysis['account_status']}")
# Example: Get transaction count for multiple addresses
addresses = [
"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", # UNI token
"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", # USDT on IoTeX
]
for addr in addresses:
count = arbitrum_counter.get_transaction_count(addr)
print(f"{addr}: {int(count, 16)} transactions")
Response Examples​
Confirmed Transaction Count​
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x2a"
}
Pending Transaction Count​
{
"jsonrpc": "2.0",
"id": 2,
"result": "0x2c"
}
Historical Block Count​
{
"jsonrpc": "2.0",
"id": 3,
"result": "0x15"
}
Key Considerations​
IoTeX-Specific Behavior​
- L2 Finality: Transactions finalize faster than Ethereum mainnet
- Sequencer Ordering: IoTeX sequencer processes transactions in order
- L1/L2 Bridging: Cross-layer transactions may affect nonce sequencing
- Gas Efficiency: Lower costs enable more frequent transactions
Nonce Management Best Practices​
- Always Use Pending: Query "pending" state when building new transactions
- Concurrent Handling: Implement nonce queuing for high-frequency applications
- Error Recovery: Handle nonce gaps and resubmission scenarios
- Monitoring: Track both confirmed and pending states for wallet applications
Transaction Sequencing​
- Sequential Requirement: Nonces must be used in consecutive order
- Gap Handling: Missing nonces block subsequent transactions
- Reorg Resistance: IoTeX's finality model reduces reorganization risks
- Batch Operations: Consider transaction batching for complex workflows
Integration Patterns​
- Wallet Development: Real-time nonce tracking for user transactions
- DeFi Protocols: Smart contract interaction sequencing
- Trading Bots: High-frequency transaction management
- Bridge Applications: Cross-layer transaction coordination
- Analytics Platforms: Account activity monitoring and reporting
Error Handling​
- Invalid Address: Returns error for malformed addresses
- Block Not Found: Historical queries may fail for pruned blocks
- Network Issues: Implement retry logic with exponential backoff
- Rate Limiting: Respect API rate limits for production applications
Need help? Contact our support team or check the IoTeX documentation.