eth_getTransactionCount
Obtains the total number of transactions executed by a specific account on the Polygon PoS (Proof-of-Stake) network. This method returns the account's nonce value, which is critical for maintaining transaction order and ensuring secure blockchain interactions on Polygon's high-performance network.
Method Description​
The eth_getTransactionCount
method is a core function for Polygon blockchain interaction, returning the transaction count that doubles as the nonce for subsequent transactions. On Polygon's PoS chain, this enables fast, low-cost transactions while maintaining Ethereum compatibility and security standards.
Parameters​
Parameter | Type | Required | Description |
---|---|---|---|
address | string | Yes | Target Ethereum address (20-byte hex with 0x prefix) for transaction count query |
blockNumber | string | Yes | Block reference point: hex block number or tag ("latest", "earliest", "pending", "safe", "finalized") |
Block Tag Specifications​
"latest"
- Most recent confirmed block (recommended for confirmed count)"pending"
- Include unconfirmed transactions in mempool (use for next nonce)"earliest"
- Genesis block"safe"
- Latest safe block confirmed by network consensus"finalized"
- Latest block with finality guarantee"0x..."
- Specific block height in hexadecimal notation
Return Value​
Type: string
Returns transaction count as hexadecimal string (e.g., "0x3e" = 62 transactions). The value indicates:
- For EOAs: Total number of transactions initiated by the address
- For Smart Contracts: Number of internal contract deployments created by this address
Application Scenarios​
- DeFi Operations: Calculate next nonce for decentralized finance transactions
- Gaming Applications: Manage in-game transaction sequencing and NFT operations
- Wallet Services: Track user activity and provide transaction history
- Cross-chain Bridges: Coordinate transaction ordering between Polygon and other networks
- Analytics Tools: Monitor network activity and address behavior patterns
Code Implementations​
- cURL
- JavaScript
- Python
# Get confirmed transaction count
curl -X POST https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
"latest"
],
"id": 1
}'
# Get pending transaction count with mempool
curl -X POST https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
"pending"
],
"id": 2
}'
# Historical transaction count at specific block
curl -X POST https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
"0x2DC6C0"
],
"id": 3
}'
// Polygon transaction count management utility
class PolygonNonceTracker {
constructor(apiKey) {
this.rpcUrl = `https://api-polygon-mainnet-full.n.dwellir.com/${apiKey}`;
this.requestId = 1;
}
async getTransactionCount(address, blockTag = 'latest') {
try {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getTransactionCount',
params: [address, blockTag],
id: this.requestId++
})
});
const data = await response.json();
if (data.error) {
throw new Error(`Polygon RPC Error: ${data.error.message}`);
}
return data.result;
} catch (error) {
throw new Error(`Network error: ${error.message}`);
}
}
async getDetailedAccountInfo(address) {
// Parallel requests for efficiency
const [confirmedHex, pendingHex] = await Promise.all([
this.getTransactionCount(address, 'latest'),
this.getTransactionCount(address, 'pending')
]);
const confirmed = parseInt(confirmedHex, 16);
const pending = parseInt(pendingHex, 16);
const pendingCount = pending - confirmed;
return {
address,
confirmedTransactions: confirmed,
pendingTransactions: pendingCount,
totalPendingCount: pending,
nextNonce: pendingHex,
nextNonceDecimal: pending,
isActiveAccount: confirmed > 0,
hasPendingTxs: pendingCount > 0,
activityLevel: this.categorizeActivity(confirmed)
};
}
categorizeActivity(txCount) {
if (txCount === 0) return 'new';
if (txCount < 10) return 'low';
if (txCount < 100) return 'moderate';
if (txCount < 1000) return 'high';
return 'very_high';
}
async monitorNonceChanges(address, callback, interval = 5000) {
let lastNonce = await this.getTransactionCount(address, 'latest');
const monitor = setInterval(async () => {
try {
const currentNonce = await this.getTransactionCount(address, 'latest');
if (currentNonce !== lastNonce) {
const oldCount = parseInt(lastNonce, 16);
const newCount = parseInt(currentNonce, 16);
callback({
address,
oldNonce: lastNonce,
newNonce: currentNonce,
oldCount,
newCount,
newTransactions: newCount - oldCount,
timestamp: new Date().toISOString()
});
lastNonce = currentNonce;
}
} catch (error) {
console.error('Monitor error:', error);
}
}, interval);
return monitor; // Return interval ID for cleanup
}
}
// Usage examples
const polygonTracker = new PolygonNonceTracker('YOUR_API_KEY');
// Popular Polygon addresses for testing
const wethPolygon = '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619'; // WETH on Polygon
const usdcPolygon = '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'; // USDC on Polygon
// Get comprehensive account analysis
polygonTracker.getDetailedAccountInfo(wethPolygon)
.then(info => {
console.log('Polygon Account Analysis:');
console.log(`Address: ${info.address}`);
console.log(`Confirmed Transactions: ${info.confirmedTransactions}`);
console.log(`Pending Transactions: ${info.pendingTransactions}`);
console.log(`Activity Level: ${info.activityLevel}`);
console.log(`Next Nonce: ${info.nextNonce}`);
})
.catch(error => console.error('Error:', error));
// Monitor address for new transactions
const monitorId = await polygonTracker.monitorNonceChanges(
wethPolygon,
(change) => {
console.log(`New transactions detected: ${change.newTransactions}`);
console.log(`Nonce updated: ${change.oldNonce} → ${change.newNonce}`);
}
);
// Cleanup monitor after 1 minute
setTimeout(() => clearInterval(monitorId), 60000);
import requests
import time
import threading
from typing import Dict, Optional, Callable, Any
from dataclasses import dataclass
@dataclass
class AccountActivity:
address: str
confirmed_transactions: int
pending_transactions: int
next_nonce: str
next_nonce_decimal: int
is_active: bool
activity_level: str
class PolygonTransactionAnalyzer:
def __init__(self, api_key: str):
self.endpoint = f"https://api-polygon-mainnet-full.n.dwellir.com/{api_key}"
self.session = requests.Session()
self.request_id = 1
def get_transaction_count(self, address: str, block_tag: str = "latest") -> str:
"""Get transaction count for an address on Polygon"""
payload = {
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [address, block_tag],
"id": self.request_id
}
self.request_id += 1
try:
response = self.session.post(self.endpoint, json=payload, timeout=30)
response.raise_for_status()
result = response.json()
if 'error' in result:
raise Exception(f"Polygon RPC Error: {result['error']['message']}")
return result['result']
except requests.exceptions.RequestException as e:
raise Exception(f"Network error: {str(e)}")
def analyze_account_activity(self, address: str) -> AccountActivity:
"""Comprehensive account activity analysis"""
try:
# Get both confirmed and pending counts
confirmed_hex = self.get_transaction_count(address, "latest")
pending_hex = self.get_transaction_count(address, "pending")
confirmed_count = int(confirmed_hex, 16)
pending_count = int(pending_hex, 16)
pending_txs = pending_count - confirmed_count
activity_level = self._categorize_activity(confirmed_count)
return AccountActivity(
address=address,
confirmed_transactions=confirmed_count,
pending_transactions=pending_txs,
next_nonce=pending_hex,
next_nonce_decimal=pending_count,
is_active=confirmed_count > 0,
activity_level=activity_level
)
except Exception as e:
raise Exception(f"Analysis failed for {address}: {str(e)}")
def _categorize_activity(self, tx_count: int) -> str:
"""Categorize account activity level"""
if tx_count == 0:
return "new"
elif tx_count < 10:
return "low"
elif tx_count < 100:
return "moderate"
elif tx_count < 1000:
return "high"
else:
return "very_high"
def compare_addresses(self, addresses: list) -> Dict[str, AccountActivity]:
"""Compare activity across multiple addresses"""
results = {}
for address in addresses:
try:
results[address] = self.analyze_account_activity(address)
except Exception as e:
results[address] = f"Error: {str(e)}"
return results
def track_nonce_history(self, address: str, duration_minutes: int = 5) -> list:
"""Track nonce changes over time"""
history = []
start_time = time.time()
end_time = start_time + (duration_minutes * 60)
print(f"Tracking {address} for {duration_minutes} minutes...")
while time.time() < end_time:
try:
nonce = self.get_transaction_count(address, "latest")
timestamp = time.time()
entry = {
'timestamp': timestamp,
'iso_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)),
'nonce': nonce,
'decimal': int(nonce, 16),
'elapsed_seconds': timestamp - start_time
}
history.append(entry)
# Check if nonce changed
if len(history) > 1 and history[-1]['nonce'] != history[-2]['nonce']:
print(f"Nonce changed: {history[-2]['nonce']} → {nonce}")
time.sleep(10) # Check every 10 seconds
except Exception as e:
print(f"Tracking error: {e}")
time.sleep(10)
return history
def get_batch_nonces(self, addresses: list, block_tag: str = "latest") -> Dict[str, str]:
"""Get nonces for multiple addresses efficiently"""
nonces = {}
for address in addresses:
try:
nonce = self.get_transaction_count(address, block_tag)
nonces[address] = nonce
except Exception as e:
nonces[address] = f"Error: {str(e)}"
return nonces
# Example usage and demonstrations
if __name__ == "__main__":
# Initialize analyzer
analyzer = PolygonTransactionAnalyzer("YOUR_API_KEY")
# Popular Polygon token contracts and addresses
test_addresses = [
"0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619", # WETH on Polygon
"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", # USDC on Polygon
"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", # WMATIC
"0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063", # DAI on Polygon
]
# Analyze individual address
weth_address = test_addresses[0]
try:
activity = analyzer.analyze_account_activity(weth_address)
print("\n=== Individual Address Analysis ===")
print(f"Address: {activity.address}")
print(f"Confirmed Transactions: {activity.confirmed_transactions}")
print(f"Pending Transactions: {activity.pending_transactions}")
print(f"Next Nonce: {activity.next_nonce} ({activity.next_nonce_decimal})")
print(f"Activity Level: {activity.activity_level}")
print(f"Is Active: {activity.is_active}")
except Exception as e:
print(f"Analysis error: {e}")
# Batch comparison
print("\n=== Batch Address Comparison ===")
comparisons = analyzer.compare_addresses(test_addresses[:3])
for addr, result in comparisons.items():
if isinstance(result, AccountActivity):
print(f"{addr}: {result.confirmed_transactions} transactions ({result.activity_level})")
else:
print(f"{addr}: {result}")
# Get current nonces for all addresses
print("\n=== Current Nonces ===")
current_nonces = analyzer.get_batch_nonces(test_addresses)
for addr, nonce in current_nonces.items():
if nonce.startswith("0x"):
decimal_nonce = int(nonce, 16)
print(f"{addr}: {nonce} ({decimal_nonce})")
else:
print(f"{addr}: {nonce}")
Response Examples​
Confirmed Transaction Count​
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x3e"
}
Pending Count with Mempool​
{
"jsonrpc": "2.0",
"id": 2,
"result": "0x41"
}
Historical Transaction Count​
{
"jsonrpc": "2.0",
"id": 3,
"result": "0x1a"
}
Polygon-Specific Considerations​
Network Characteristics​
- Fast Block Times: ~2 second block intervals enable rapid transaction confirmation
- Low Gas Fees: MATIC token provides cost-effective transaction processing
- High Throughput: Network handles thousands of transactions per second
- EVM Compatibility: Full Ethereum tooling and smart contract compatibility
Nonce Management on Polygon​
- Rapid Updates: Faster block times mean nonces update more frequently
- Gas Optimization: Lower costs allow for more experimental transaction patterns
- Mempool Behavior: Shorter confirmation times reduce pending transaction windows
- Bridge Coordination: Consider L1 Ethereum nonce synchronization for cross-chain operations
Performance Optimizations​
- Batch Requests: Combine multiple nonce queries for efficiency
- Caching Strategy: Brief caching acceptable due to fast block times
- Pending State: Always check pending for real-time transaction building
- Monitoring: Real-time tracking more practical due to network speed
Integration Best Practices​
- Gaming DApps: Leverage fast transactions for real-time gameplay
- DeFi Protocols: Implement rapid transaction sequencing for MEV protection
- NFT Marketplaces: Handle high-frequency minting and trading operations
- Cross-chain Bridges: Coordinate nonce management across multiple networks
- Enterprise Applications: Build high-throughput business process automation
Common Patterns​
- Micro-transactions: Utilize low fees for small-value operations
- Batch Processing: Group related transactions for gas efficiency
- Real-time Updates: Implement live nonce tracking for responsive UIs
- Multi-sig Coordination: Handle complex signing workflows efficiently
Error Scenarios​
- Network Congestion: Rare but possible during high activity periods
- Invalid Addresses: Standard Ethereum address validation applies
- Historical Limits: Some archive data may have retention limits
- Rate Limits: Respect API quotas for production applications
Need help? Contact our support team or check the Polygon documentation.