多域名兼容链上获取数据

This commit is contained in:
lu7213 committed 2026-10-16 11:27:52 -04:00
1 parent 2601bc898a
commit 0d0642d312
4 files changed
+119 -5

No files matched your search

@@ -47,6 +47,13 @@ public class TronChainDataClient {
private final Map<String, List<String>> transactionEndpoints;
private final Map<String, List<String>> accountEndpoints;
private final String apiKey;
private String tronscanApiKey = "";
/** TronScan 与 TronGrid 是不同平台,凭证必须分别配置,禁止跨平台发送。 */
@Value("${tron.chain-data.tronscan-api-key:}")
public void setTronscanApiKey(String key) {
this.tronscanApiKey = key == null ? "" : key.trim();
}
@Autowired
public TronChainDataClient(
@@ -82,17 +89,27 @@ public class TronChainDataClient {
RuntimeException lastFailure = null;
for (String endpoint : endpoints) {
try {
URI uri = UriComponentsBuilder.fromHttpUrl(endpoint)
boolean scan = isTronscan(endpoint);
String base = endpoint.replaceFirst("^(tronscan|trongrid)\\|", "");
URI uri = scan ? UriComponentsBuilder.fromHttpUrl(base)
.path("/api/token_trc20/transfers")
.queryParam("relatedAddress", address)
.queryParam("contract_address", contractAddress)
.queryParam("start", 0).queryParam("limit", Math.min(limit, 50))
.queryParam("sort", "-timestamp").queryParam("confirm", true)
.build().encode().toUri()
: UriComponentsBuilder.fromHttpUrl(base)
.pathSegment("v1", "accounts", address, "transactions", "trc20")
.queryParam("limit", limit)
.queryParam("only_confirmed", true)
.queryParam("contract_address", contractAddress)
.build().encode().toUri();
JSONObject body = requestJson(uri, serviceApiKey);
JSONObject body = requestJson(uri, scan ? tronscanApiKey : apiKey);
if (Boolean.FALSE.equals(body.getBoolean("success"))) {
throw new IllegalStateException("数据源明确返回查询失败");
}
JSONArray data = body.getJSONArray("data");
JSONArray data = scan ? normalizeTronscanTransfers(body, contractAddress)
: body.getJSONArray("data");
if (data == null) {
throw new IllegalStateException("响应缺少 data 数组");
}
@@ -124,7 +141,10 @@ public class TronChainDataClient {
.path("/api/accountv2")
.queryParam("address", address)
.build().encode().toUri();
JSONObject json = requestJson(uri, serviceApiKey);
JSONObject json = requestJson(uri, tronscanApiKey);
if (!address.equals(json.getString("address"))) {
throw new IllegalStateException("账户响应缺少匹配地址");
}
TronAccountResp account = json.toJavaObject(TronAccountResp.class);
return toDelegatedResourceSummary(account);
} catch (RuntimeException ex) {
@@ -143,7 +163,7 @@ public class TronChainDataClient {
private JSONObject requestJson(URI uri, String serviceApiKey) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
String effectiveApiKey = StringUtils.hasText(apiKey) ? apiKey : serviceApiKey;
String effectiveApiKey = serviceApiKey;
if (StringUtils.hasText(effectiveApiKey)) {
headers.set("TRON-PRO-API-KEY", effectiveApiKey);
}
@@ -163,6 +183,45 @@ public class TronChainDataClient {
}
}
/** 自定义代理地址可通过 tronscan|URL 显式指定协议,普通历史配置按域名识别。 */
private boolean isTronscan(String endpoint) {
if (endpoint.startsWith("tronscan|")) return true;
if (endpoint.startsWith("trongrid|")) return false;
String host = URI.create(endpoint).getHost();
return host != null && (host.endsWith(".tronscan.org")
|| host.endsWith(".tronscanapi.com"));
}
/** 只接受已确认、执行成功且合约匹配的转账,金额保留原始最小单位字符串。 */
private JSONArray normalizeTronscanTransfers(JSONObject body, String contract) {
JSONArray transfers = body.getJSONArray("token_transfers");
if (transfers == null) throw new IllegalStateException("响应缺少 token_transfers 数组");
JSONArray result = new JSONArray();
for (int i = 0; i < transfers.size(); i++) {
JSONObject transfer = transfers.getJSONObject(i);
if (transfer == null || !Boolean.TRUE.equals(transfer.getBoolean("confirmed"))
|| !"SUCCESS".equals(transfer.getString("contractRet"))) continue;
JSONObject token = transfer.getJSONObject("tokenInfo");
String tokenAddress = transfer.getString("contract_address");
if (tokenAddress == null && token != null) tokenAddress = token.getString("tokenId");
if (!contract.equals(tokenAddress)) continue;
if (token != null && token.getInteger("tokenDecimal") != null
&& token.getIntValue("tokenDecimal") != 6) continue;
JSONObject tx = new JSONObject();
tx.put("to", transfer.getString("to_address"));
tx.put("from", transfer.getString("from_address"));
tx.put("block_timestamp", transfer.getLong("block_ts"));
tx.put("transaction_id", transfer.getString("transaction_id"));
tx.put("value", transfer.getString("quant"));
if (tx.getString("value") == null || tx.getLong("block_timestamp") == null
|| tx.getString("transaction_id") == null) {
throw new IllegalStateException("转账响应字段不完整");
}
result.add(tx);
}
return result;
}
private EnergyAndBandwidthVo toDelegatedResourceSummary(TronAccountResp account) {
EnergyAndBandwidthVo result = emptyDelegatedResourceSummary();
result.setAcquiredEnergy(zeroIfNull(account.getAcquiredDelegatedFrozenV2BalanceForEnergyValue()));