Docs
Docs
Home
Getting Started
Agent Tooling
CLI
Supported Chains
Acala
Aptos
Arbitrum
Arc
Asset Hub
Astar
Avalanche
Base
Berachain
Bifrost
Binance Smart Chain
Bittensor
Blast
Boba Network
Bridge Hub
Celo
Centrifuge
Chiliz
Cronos
Enjin
Ethereum
Etherlink
Flow EVM Gateway
Gnosis
Hydration
Hyperliquid
Immutable
Ink
IoTeX
Kusama
Linea
LISK
Manta Atlantic
Manta Pacific
Mantle
MegaETH
Monad
Movement
Neuroweb
opBNB
Optimism
Plasma
Polkadot
Polygon
Pulsechain
Robinhood
Ronin
Scroll
Sonic
Starknet
Taiko
Tempo
Sui
TRON
Unichain
Viction
World Chain
XDC Network
XX Network
Zetachain
zkSync Era
Zora
Supported ChainsTRONTRON HTTP API

wallet/getnowblock - Get Current TRON Block

Get the latest block information from TRON network including block number, transactions, and timestamp via Dwellir's lightning-fast RPC endpoints.

TRON RPC endpoint: endpoint URLs, plans and pricing.

Real-Time Block Data

Dwellir's TRON endpoints deliver the latest block information in under 20ms with 99.99% 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
JSON-RPC request
// No request body needed for this method

Implementation Examples

Response Examples

Latest Block Response

JSON
{
  "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

JSON
{
  "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

JavaScript
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

JavaScript
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

JavaScript
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

JavaScript
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
JavaScript
// 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.

wallet/gettransactioninfobyid

Get detailed TRON transaction information including receipt, logs, and energy/bandwidth usage via Dwellir's high-performance RPC endpoint.

wallet/getblockbynum

Get TRON block information by height number including transactions and block header via Dwellir's optimized RPC endpoint.

On this page

When to Use This MethodImplementation ExamplesResponse ExamplesLatest Block ResponseEmpty Block ResponseCommon Use Cases1. Real-Time Block Explorer2. Transaction Confirmation Tracker3. Network Health Monitor4. DApp Synchronization ServicePerformance Tips