Introduction
This guide is inspired by a GitHub contributor's code, which has been optimized and improved for broader accessibility. If you are the original author and wish to be credited, please contact us for attribution.
Implementation Overview
Tron blockchain offers specialized HTTP APIs to monitor block events, parse transaction data, and track fund flows (e.g., TRX/USDT transfers). Key steps include:
- Fetch Latest Block: Retrieve the latest block number and cache it in Redis.
- Scheduled Task: A 10-second cron job compares cached and live block numbers.
Data Processing: For each new block:
- Fetch transactions via API.
- Parse and process data (e.g., identify USDT/TRX transfers).
- Update Redis cache with the latest block number.
Prerequisites
- API Key: Sign up at TronGrid for a free key (500K daily calls). Paid tiers are available for higher demands.
Dependencies: Add these libraries to your project:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.33</version> </dependency>
Code Implementation
Main Task Class
package com.app.web.task;
import com.app.web.trx.TrxEventDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Slf4j
@Component
public class Web3Task {
@Resource
private TrxEventDataService trxEventDataService;
@Scheduled(initialDelay = 20_000, fixedDelay = 10_000)
public void exec() {
String contractUsdt = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"; // USDT contract
String url = "https://api.trongrid.io";
String apiKey = "YOUR_API_KEY"; // Replace with your key
trxEventDataService.exec(contractUsdt, url, apiKey);
}
}Transaction Data Service
package com.app.web.trx;
import com.alibaba.fastjson.*;
import org.springframework.stereotype.Service;
import java.net.*;
import java.nio.charset.StandardCharsets;
@Service
public class TrxEventDataService {
private static final String REDIS_BLOCK_NUM = "REDIS_BLOCK_NUM";
public void exec(String contractUsdt, String url, String apiKey) {
ScanBlock scan = new ScanBlock();
scan.set_api_key(apiKey);
scan.set_uri(url);
String latestBlock = scan.GetNowBlockNum();
String cachedBlock = RedisUtil.get(REDIS_BLOCK_NUM) != null ?
RedisUtil.get(REDIS_BLOCK_NUM) : latestBlock;
for (int i = Integer.parseInt(cachedBlock) + 1;
i < Integer.parseInt(latestBlock); i++) {
String blockData = sendPost(url + "/walletsolidity/getblockbynum",
"{\"num\":" + i + "}", apiKey);
JSONObject json = JSON.parseObject(blockData);
if (json.containsKey("transactions")) {
String transfers = AnalysisOt.getTransferEvent(
json.getJSONArray("transactions").toJSONString(),
String.valueOf(i));
processTransferData(transfers, contractUsdt);
}
RedisUtil.set(REDIS_BLOCK_NUM, String.valueOf(i));
Thread.sleep(1000); // Rate limiting
}
}
private void processTransferData(String data, String contractUsdt) {
JSONArray transfers = JSON.parseArray(data);
transfers.forEach(transfer -> {
JSONObject t = (JSONObject) transfer;
if ("SUCCESS".equals(t.getString("contractRet"))) {
String logMsg = t.getString("type").equals("TriggerSmartContract") ?
"USDT Transfer: " + t.getString("from_address") + " → " +
t.getString("to_address") + " → " + t.getString("amount") :
"TRX Transfer: " + t.getString("from_address") + " → " +
t.getString("to_address") + " → " + t.getString("amount");
System.out.println(logMsg);
}
});
}
public String sendPost(String url, String json, String apiKey) {
// HTTP POST logic (see original code)
return response.toString();
}
}Key Tools & Utilities
AnalysisOt Class
- Function: Parses transaction data into readable formats.
Methods:
hexToBase58Check(): Converts hex addresses to Base58.getTransferEvent(): Extracts transfer details from raw transactions.
ScanBlock Class
- Purpose: Interfaces with TronGrid API to fetch blocks.
Critical Methods:
GetNowBlockNum(): Retrieves the latest block number.GetBlockAllData(): Fetches full block data.
👉 Explore TronGrid API Documentation
FAQs
Q1: How do I avoid API rate limits?
A: Space requests 1+ seconds apart and use a valid API key.
Q2: Why are some blocks empty?
A: Blocks may take seconds to finalize. Retry after a 30-second delay.
Q3: Can I monitor multiple tokens?
A: Yes! Add more contract addresses to the contractUsdt array.
Notes
- Performance: Use
System.gc()sparingly to manage memory. - JAR Dependency: Download the scanner JAR here.
- Contributions: Feedback welcome! Optimize this for your needs.
### Key SEO Elements:
- **Keywords**: Tron, TRX, USDT, blockchain monitoring, API integration.
- **Structure**: Hierarchical headings (`##`, `###`) for readability.
- **Anchor Text**: Contextual links (e.g., TronGrid API).