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

wallet/getnowblock

Real-Time Block Data

Dwellir's TRON endpoints deliver the latest block information in under 20ms with 99.9% uptime. Stay synchronized with TRON's 3-second block times for real-time applications.

Get instant block data →

Retrieves the latest block information from the TRON network, including block number, timestamp, transactions, and block hash.

When to Use This Method

wallet/getnowblock is essential for:

  • Real-Time Monitoring - Track latest network activity and block production
  • Block Synchronization - Keep applications synchronized with network state
  • Transaction Confirmation - Monitor for transaction inclusion in new blocks
  • Network Health Monitoring - Check block times and network performance
  • Block Explorer Development - Display latest blocks and transactions

Parameters

No parameters required - This method returns the current latest block.

// No request body needed for this method

Returns

Block Object containing:

  • blockID - Unique block identifier (hash)
  • block_header - Block header with metadata
  • transactions - Array of transactions in the block

Block Header Structure

  • raw_data - Raw block data
    • number - Block number
    • txTrieRoot - Transaction merkle root
    • witness_address - Block producer address
    • parentHash - Previous block hash
    • version - Protocol version
    • timestamp - Block timestamp in milliseconds
  • witness_signature - Block producer signature

Implementation Examples

# Get the latest block
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getnowblock" \
-H "Content-Type: application/json"

# Extract key information from latest block
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getnowblock" \
-H "Content-Type: application/json" | jq '{
block_number: .block_header.raw_data.number,
block_hash: .blockID,
timestamp: .block_header.raw_data.timestamp,
datetime: (.block_header.raw_data.timestamp / 1000 | strftime("%Y-%m-%d %H:%M:%S")),
transaction_count: (.transactions // [] | length),
producer: .block_header.raw_data.witness_address
}'

# Monitor for new blocks (bash script)
#!/bin/bash
API_KEY="YOUR_API_KEY"
LAST_BLOCK=0

echo "Starting TRON block monitor..."

while true; do
# Get latest block
RESPONSE=$(curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/getnowblock" \
-H "Content-Type: application/json")

# Extract block number
CURRENT_BLOCK=$(echo "$RESPONSE" | jq -r '.block_header.raw_data.number')

if [ "$CURRENT_BLOCK" != "null" ] && [ "$CURRENT_BLOCK" -gt "$LAST_BLOCK" ]; then
# Extract block info
BLOCK_HASH=$(echo "$RESPONSE" | jq -r '.blockID')
TIMESTAMP=$(echo "$RESPONSE" | jq -r '.block_header.raw_data.timestamp')
TX_COUNT=$(echo "$RESPONSE" | jq -r '(.transactions // [] | length)')
PRODUCER=$(echo "$RESPONSE" | jq -r '.block_header.raw_data.witness_address')

# Convert timestamp to readable format
DATETIME=$(date -d "@$((TIMESTAMP / 1000))" "+%Y-%m-%d %H:%M:%S")

echo "📦 Block #$CURRENT_BLOCK | $TX_COUNT txs | $DATETIME | Producer: $PRODUCER"

# Log transactions in block
if [ "$TX_COUNT" -gt 0 ]; then
echo "$RESPONSE" | jq -r '.transactions[]?.txID' | while read -r txid; do
echo " 💸 Transaction: $txid"
done
fi

LAST_BLOCK=$CURRENT_BLOCK
fi

sleep 3 # Check every 3 seconds (TRON block time)
done

# Network performance analysis script
#!/bin/bash
API_KEY="YOUR_API_KEY"
DURATION=${1:-60} # Duration in seconds, default 60

echo "Collecting TRON network statistics for $DURATION seconds..."

START_TIME=$(date +%s)
END_TIME=$((START_TIME + DURATION))
TOTAL_BLOCKS=0
TOTAL_TXS=0
BLOCKS_FILE="/tmp/tron_blocks.json"

> "$BLOCKS_FILE" # Clear file

while [ $(date +%s) -lt $END_TIME ]; do
RESPONSE=$(curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/getnowblock" \
-H "Content-Type: application/json")

BLOCK_NUMBER=$(echo "$RESPONSE" | jq -r '.block_header.raw_data.number')
TX_COUNT=$(echo "$RESPONSE" | jq -r '(.transactions // [] | length)')

if [ "$BLOCK_NUMBER" != "null" ]; then
echo "$RESPONSE" >> "$BLOCKS_FILE"
echo "Block #$BLOCK_NUMBER with $TX_COUNT transactions"
((TOTAL_BLOCKS++))
TOTAL_TXS=$((TOTAL_TXS + TX_COUNT))
fi

sleep 3
done

# Calculate statistics
if [ $TOTAL_BLOCKS -gt 0 ]; then
AVG_TXS_PER_BLOCK=$((TOTAL_TXS / TOTAL_BLOCKS))
AVG_TPS=$((TOTAL_TXS / DURATION))

echo ""
echo "=== TRON Network Statistics ==="
echo "Duration: $DURATION seconds"
echo "Total blocks observed: $TOTAL_BLOCKS"
echo "Total transactions: $TOTAL_TXS"
echo "Average transactions per block: $AVG_TXS_PER_BLOCK"
echo "Average TPS: $AVG_TPS"

# Find most active producer
echo ""
echo "Block producers:"
jq -r '.block_header.raw_data.witness_address' "$BLOCKS_FILE" | sort | uniq -c | sort -nr | head -5
else
echo "No blocks collected during monitoring period"
fi

# Cleanup
rm -f "$BLOCKS_FILE"

# Real-time transaction finder
find_transaction_in_blocks() {
local TX_ID=$1
local MAX_CHECKS=${2:-20}
local CHECK_COUNT=0

echo "Searching for transaction $TX_ID in recent blocks..."

while [ $CHECK_COUNT -lt $MAX_CHECKS ]; do
RESPONSE=$(curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/getnowblock" \
-H "Content-Type: application/json")

# Check if transaction is in this block
FOUND=$(echo "$RESPONSE" | jq -r --arg txid "$TX_ID" '
.transactions[]? | select(.txID == $txid) | .txID
')

if [ "$FOUND" = "$TX_ID" ]; then
BLOCK_NUMBER=$(echo "$RESPONSE" | jq -r '.block_header.raw_data.number')
BLOCK_HASH=$(echo "$RESPONSE" | jq -r '.blockID')
echo "✓ Transaction found in block #$BLOCK_NUMBER ($BLOCK_HASH)"
return 0
fi

echo "Checking block... ($((CHECK_COUNT + 1))/$MAX_CHECKS)"
((CHECK_COUNT++))
sleep 3
done

echo "✗ Transaction not found in the last $MAX_CHECKS blocks"
return 1
}

# Usage examples:
# ./script.sh # Monitor blocks
# ./script.sh performance 120 # Collect stats for 2 minutes
# ./script.sh find TX_ID_HERE # Find transaction in recent blocks

case "${1:-monitor}" in
"performance")
# Run performance analysis
;;
"find")
find_transaction_in_blocks "$2"
;;
*)
# Default: monitor blocks
;;
esac

Response Examples

Latest Block Response

{
"blockID": "00000000032a9c4bd8b6b8e1a8e8d6c4b2a09f8e7d6c5b4a39291807f6e5d4c3b2",
"block_header": {
"raw_data": {
"number": 52895819,
"txTrieRoot": "0000000000000000000000000000000000000000000000000000000000000000",
"witness_address": "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH",
"parentHash": "00000000032a9c4a9d8b6b8e1a8e8d6c4b2a09f8e7d6c5b4a39291807f6e5d4c3",
"version": 27,
"timestamp": 1734567890000
},
"witness_signature": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234567890"
},
"transactions": [
{
"ret": [{"contractRet": "SUCCESS"}],
"signature": ["7a8b9c0d1e2f3456789012345678901234567890123456789012345678901234567890"],
"txID": "94eea63bb6774c8fc4f4c9d1b62c1e8c2f7c8c2e4d3a2b1c0d9e8f7a6b5c4d3e2f1",
"raw_data": {
"contract": [
{
"parameter": {
"value": {
"amount": 1000000,
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"to_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"type_url": "type.googleapis.com/protocol.TransferContract"
},
"type": "TransferContract"
}
],
"ref_block_bytes": "9c4a",
"ref_block_hash": "b8e1a8e8d6c4b2a0",
"expiration": 1734567950000,
"timestamp": 1734567890000
}
}
]
}

Empty Block Response

{
"blockID": "00000000032a9c4bd8b6b8e1a8e8d6c4b2a09f8e7d6c5b4a39291807f6e5d4c3b2",
"block_header": {
"raw_data": {
"number": 52895820,
"txTrieRoot": "0000000000000000000000000000000000000000000000000000000000000000",
"witness_address": "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH",
"parentHash": "00000000032a9c4a9d8b6b8e1a8e8d6c4b2a09f8e7d6c5b4a39291807f6e5d4c3",
"version": 27,
"timestamp": 1734567893000
},
"witness_signature": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234567890"
}
}

Common Use Cases

1. Real-Time Block Explorer

class TronBlockExplorer {
constructor(apiKey) {
this.client = new TronBlockClient(apiKey);
this.blockCache = new Map();
this.subscribers = new Set();
}

async getLatestBlockData() {
try {
const blockInfo = await this.client.getBlockInfo();

// Cache block data
this.blockCache.set(blockInfo.blockNumber, blockInfo);

// Keep only last 100 blocks in cache
if (this.blockCache.size > 100) {
const oldestBlock = Math.min(...this.blockCache.keys());
this.blockCache.delete(oldestBlock);
}

return {
...blockInfo,
cached: false,
timeAgo: this.calculateTimeAgo(blockInfo.timestamp)
};
} catch (error) {
console.error('Failed to fetch block data:', error);
throw error;
}
}

calculateTimeAgo(timestamp) {
const now = Date.now();
const diff = now - timestamp;

if (diff < 10000) return 'just now';
if (diff < 60000) return `${Math.floor(diff / 1000)}s ago`;
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
return `${Math.floor(diff / 3600000)}h ago`;
}

subscribeToBlocks(callback) {
this.subscribers.add(callback);
return () => this.subscribers.delete(callback);
}

async startRealTimeUpdates() {
setInterval(async () => {
try {
const blockData = await this.getLatestBlockData();
this.subscribers.forEach(callback => callback(blockData));
} catch (error) {
console.error('Real-time update failed:', error);
}
}, 3000);
}
}

2. Transaction Confirmation Tracker

class TransactionConfirmationTracker {
constructor(apiKey) {
this.client = new TronBlockClient(apiKey);
this.pendingTransactions = new Map();
this.confirmedTransactions = new Map();
}

async trackTransaction(txId, requiredConfirmations = 1) {
this.pendingTransactions.set(txId, {
txId,
requiredConfirmations,
currentConfirmations: 0,
firstSeenBlock: null,
startTime: Date.now()
});

return new Promise((resolve, reject) => {
const checkConfirmation = async () => {
try {
const found = await this.client.findTransactionInLatestBlock(txId);

if (found.found) {
const tracking = this.pendingTransactions.get(txId);
if (!tracking.firstSeenBlock) {
tracking.firstSeenBlock = found.blockNumber;
}

// Calculate confirmations based on current block
const latestBlock = await this.client.getBlockInfo();
const confirmations = latestBlock.blockNumber - tracking.firstSeenBlock + 1;
tracking.currentConfirmations = confirmations;

if (confirmations >= requiredConfirmations) {
this.pendingTransactions.delete(txId);
this.confirmedTransactions.set(txId, {
...tracking,
confirmedAt: Date.now(),
finalBlockNumber: latestBlock.blockNumber
});

resolve({
confirmed: true,
confirmations,
blockNumber: tracking.firstSeenBlock,
confirmationTime: Date.now() - tracking.startTime
});
}
}

// Continue checking
setTimeout(checkConfirmation, 3000);
} catch (error) {
reject(error);
}
};

checkConfirmation();
});
}

getTransactionStatus(txId) {
if (this.confirmedTransactions.has(txId)) {
return { status: 'confirmed', ...this.confirmedTransactions.get(txId) };
}

if (this.pendingTransactions.has(txId)) {
return { status: 'pending', ...this.pendingTransactions.get(txId) };
}

return { status: 'unknown' };
}
}

3. Network Health Monitor

class TronNetworkHealthMonitor {
constructor(apiKey) {
this.client = new TronBlockClient(apiKey);
this.healthMetrics = {
blockTimes: [],
transactionCounts: [],
producers: new Map(),
lastUpdate: null
};
}

async startMonitoring(durationMinutes = 60) {
const endTime = Date.now() + (durationMinutes * 60 * 1000);
let lastBlockNumber = 0;
let lastBlockTime = null;

console.log(`Starting network health monitoring for ${durationMinutes} minutes...`);

while (Date.now() < endTime) {
try {
const blockInfo = await this.client.getBlockInfo();

if (blockInfo.blockNumber > lastBlockNumber) {
// Calculate block time
if (lastBlockTime) {
const blockTime = blockInfo.timestamp - lastBlockTime;
this.healthMetrics.blockTimes.push(blockTime);
}

// Track transaction count
this.healthMetrics.transactionCounts.push(blockInfo.transactionCount);

// Track producer
const producer = blockInfo.producer;
this.healthMetrics.producers.set(
producer,
(this.healthMetrics.producers.get(producer) || 0) + 1
);

lastBlockNumber = blockInfo.blockNumber;
lastBlockTime = blockInfo.timestamp;

console.log(`Block #${blockInfo.blockNumber}: ${blockInfo.transactionCount} txs, Producer: ${producer}`);
}

await new Promise(resolve => setTimeout(resolve, 3000));

} catch (error) {
console.error('Health monitoring error:', error);
await new Promise(resolve => setTimeout(resolve, 5000));
}
}

return this.generateHealthReport();
}

generateHealthReport() {
const { blockTimes, transactionCounts, producers } = this.healthMetrics;

const avgBlockTime = blockTimes.length > 0
? blockTimes.reduce((a, b) => a + b, 0) / blockTimes.length
: 0;

const avgTxPerBlock = transactionCounts.length > 0
? transactionCounts.reduce((a, b) => a + b, 0) / transactionCounts.length
: 0;

const totalTx = transactionCounts.reduce((a, b) => a + b, 0);
const avgTPS = totalTx / (blockTimes.length * (avgBlockTime / 1000));

// Analyze producer distribution
const totalBlocks = producers.size > 0
? Array.from(producers.values()).reduce((a, b) => a + b, 0)
: 0;

const producerStats = Array.from(producers.entries())
.map(([address, count]) => ({
address,
blocks: count,
percentage: (count / totalBlocks * 100).toFixed(2)
}))
.sort((a, b) => b.blocks - a.blocks);

return {
monitoringPeriod: {
blocksObserved: blockTimes.length,
totalTransactions: totalTx,
uniqueProducers: producers.size
},
performance: {
averageBlockTime: avgBlockTime.toFixed(2) + 'ms',
targetBlockTime: '3000ms',
blockTimeVariance: this.calculateVariance(blockTimes).toFixed(2),
averageTransactionsPerBlock: avgTxPerBlock.toFixed(2),
averageTPS: avgTPS.toFixed(2)
},
networkHealth: {
status: avgBlockTime < 4000 && avgBlockTime > 2000 ? 'healthy' : 'concerning',
blockTimeHealth: avgBlockTime < 4000 ? 'good' : 'slow',
transactionActivity: avgTxPerBlock > 1 ? 'active' : 'low'
},
producers: producerStats.slice(0, 10), // Top 10 producers
recommendations: this.generateRecommendations(avgBlockTime, avgTxPerBlock, producers.size)
};
}

calculateVariance(values) {
if (values.length === 0) return 0;
const mean = values.reduce((a, b) => a + b, 0) / values.length;
const variance = values.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / values.length;
return Math.sqrt(variance);
}

generateRecommendations(avgBlockTime, avgTxPerBlock, producerCount) {
const recommendations = [];

if (avgBlockTime > 4000) {
recommendations.push('Block times are slower than expected - monitor network congestion');
}

if (avgTxPerBlock < 1) {
recommendations.push('Low transaction activity - network may be underutilized');
}

if (producerCount < 20) {
recommendations.push('Limited producer diversity observed - consider longer monitoring period');
}

if (recommendations.length === 0) {
recommendations.push('Network appears to be operating normally');
}

return recommendations;
}
}

4. DApp Synchronization Service

class TronDAppSync {
constructor(apiKey, contractAddresses = []) {
this.client = new TronBlockClient(apiKey);
this.contractAddresses = contractAddresses;
this.lastSyncedBlock = 0;
this.eventHandlers = new Map();
}

onContractEvent(contractAddress, eventType, handler) {
const key = `${contractAddress}:${eventType}`;
if (!this.eventHandlers.has(key)) {
this.eventHandlers.set(key, []);
}
this.eventHandlers.get(key).push(handler);
}

async syncToLatest() {
try {
const latestBlock = await this.client.getBlockInfo();

if (latestBlock.blockNumber > this.lastSyncedBlock) {
console.log(`Syncing to block #${latestBlock.blockNumber}...`);

// Process transactions in the latest block
await this.processBlockTransactions(latestBlock);

this.lastSyncedBlock = latestBlock.blockNumber;

return {
syncedToBlock: latestBlock.blockNumber,
transactionsProcessed: latestBlock.transactionCount,
timestamp: latestBlock.datetime
};
}

return {
syncedToBlock: this.lastSyncedBlock,
message: 'Already up to date'
};
} catch (error) {
console.error('Sync failed:', error);
throw error;
}
}

async processBlockTransactions(blockInfo) {
for (const tx of blockInfo.transactions) {
if (this.isContractTransaction(tx)) {
await this.processContractTransaction(tx, blockInfo.blockNumber);
}
}
}

isContractTransaction(tx) {
if (!tx.raw_data?.contract?.[0]) return false;

const contract = tx.raw_data.contract[0];
const contractAddress = contract.parameter?.value?.contract_address;

return this.contractAddresses.includes(contractAddress);
}

async processContractTransaction(tx, blockNumber) {
const contract = tx.raw_data.contract[0];
const contractAddress = contract.parameter?.value?.contract_address;
const contractType = contract.type;

// Emit events for contract interactions
const eventKey = `${contractAddress}:${contractType}`;
const handlers = this.eventHandlers.get(eventKey) || [];

for (const handler of handlers) {
try {
await handler({
txId: tx.txID,
contractAddress,
contractType,
blockNumber,
transaction: tx
});
} catch (error) {
console.error(`Event handler error for ${eventKey}:`, error);
}
}
}

async startAutoSync(intervalSeconds = 3) {
console.log(`Starting auto-sync every ${intervalSeconds} seconds...`);

const syncInterval = setInterval(async () => {
try {
const result = await this.syncToLatest();
if (result.transactionsProcessed > 0) {
console.log(`Synced: Block #${result.syncedToBlock} (${result.transactionsProcessed} txs)`);
}
} catch (error) {
console.error('Auto-sync error:', error);
}
}, intervalSeconds * 1000);

return () => clearInterval(syncInterval);
}
}

Performance Tips

  1. Efficient Polling - Use 3-second intervals to match TRON's block time
  2. Cache Management - Cache recent block data to avoid redundant requests
  3. Event-Driven Updates - Use real-time monitoring instead of constant polling
  4. Batch Processing - Process multiple transactions efficiently
// Optimized block monitoring with caching
class OptimizedBlockMonitor {
constructor(apiKey, options = {}) {
this.client = new TronBlockClient(apiKey);
this.cache = new Map();
this.options = {
cacheSize: 100,
pollInterval: 3000,
...options
};
}

async getBlockWithCache(blockNumber = 'latest') {
if (blockNumber === 'latest') {
// Always fetch latest block
const block = await this.client.getBlockInfo();
this.addToCache(block.blockNumber, block);
return block;
}

// Check cache first
if (this.cache.has(blockNumber)) {
return this.cache.get(blockNumber);
}

// Fetch and cache
const block = await this.client.getBlockInfo();
this.addToCache(block.blockNumber, block);
return block;
}

addToCache(blockNumber, block) {
this.cache.set(blockNumber, block);

// Maintain cache size
if (this.cache.size > this.options.cacheSize) {
const oldestKey = Math.min(...this.cache.keys());
this.cache.delete(oldestKey);
}
}
}

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