获取链上信息兼容
This commit is contained in:
1 parent
ceb8807273
commit
2601bc898a
8 files changed
+412
-103
No files matched your search
@@ -0,0 +1,253 @@
|
||||
package com.ruoyi.system.service;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
|
||||
import com.ruoyi.system.domain.vo.TronAccountResp;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* TRON HTTP 链上数据统一入口。
|
||||
*
|
||||
* <p>同一网络可以配置多个兼容端点。单个端点出现 404、限流、服务端错误、
|
||||
* 超时或响应结构异常时会自动尝试下一个端点,避免支付扫描依赖单一域名。</p>
|
||||
*/
|
||||
@Component
|
||||
public class TronChainDataClient {
|
||||
private static final Logger log = LoggerFactory.getLogger(TronChainDataClient.class);
|
||||
private static final int HTTP_TIMEOUT_MILLIS = 60_000;
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final Map<String, List<String>> transactionEndpoints;
|
||||
private final Map<String, List<String>> accountEndpoints;
|
||||
private final String apiKey;
|
||||
|
||||
@Autowired
|
||||
public TronChainDataClient(
|
||||
@Value("${tron.chain-data.mainnet.transaction-endpoints:https://api.trongrid.io,https://apilist.tronscanapi.com,https://api.tronscan.org}") String mainnetTransactionEndpoints,
|
||||
@Value("${tron.chain-data.mainnet.account-endpoints:https://apilist.tronscanapi.com,https://api.tronscan.org}") String mainnetAccountEndpoints,
|
||||
@Value("${tron.chain-data.nile.transaction-endpoints:https://nile.trongrid.io,https://nileapi.tronscan.org}") String nileTransactionEndpoints,
|
||||
@Value("${tron.chain-data.nile.account-endpoints:https://nileapi.tronscan.org}") String nileAccountEndpoints,
|
||||
@Value("${tron.chain-data.shasta.transaction-endpoints:https://api.shasta.trongrid.io,https://shastapi.tronscan.org}") String shastaTransactionEndpoints,
|
||||
@Value("${tron.chain-data.shasta.account-endpoints:https://shastapi.tronscan.org}") String shastaAccountEndpoints,
|
||||
@Value("${tron.chain-data.api-key:}") String apiKey) {
|
||||
this(createRestTemplate(), endpointMap(mainnetTransactionEndpoints, nileTransactionEndpoints,
|
||||
shastaTransactionEndpoints),
|
||||
endpointMap(mainnetAccountEndpoints, nileAccountEndpoints, shastaAccountEndpoints), apiKey);
|
||||
}
|
||||
|
||||
TronChainDataClient(RestTemplate restTemplate, Map<String, List<String>> transactionEndpoints,
|
||||
Map<String, List<String>> accountEndpoints, String apiKey) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.transactionEndpoints = transactionEndpoints;
|
||||
this.accountEndpoints = accountEndpoints;
|
||||
this.apiKey = apiKey == null ? "" : apiKey.trim();
|
||||
}
|
||||
|
||||
/** 查询已确认的 TRC20 交易,返回结构与 TronGrid v1 的 data 数组保持一致。 */
|
||||
public JSONArray queryConfirmedTrc20Transactions(ITronService tronService, String address, int limit) {
|
||||
return queryConfirmedTrc20Transactions(tronService.type(), address,
|
||||
tronService.contractAddress(), tronService.tronscanApiKey(), limit);
|
||||
}
|
||||
|
||||
JSONArray queryConfirmedTrc20Transactions(String network, String address, String contractAddress,
|
||||
String serviceApiKey, int limit) {
|
||||
List<String> endpoints = endpoints(transactionEndpoints, network);
|
||||
RuntimeException lastFailure = null;
|
||||
for (String endpoint : endpoints) {
|
||||
try {
|
||||
URI uri = UriComponentsBuilder.fromHttpUrl(endpoint)
|
||||
.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);
|
||||
if (Boolean.FALSE.equals(body.getBoolean("success"))) {
|
||||
throw new IllegalStateException("数据源明确返回查询失败");
|
||||
}
|
||||
JSONArray data = body.getJSONArray("data");
|
||||
if (data == null) {
|
||||
throw new IllegalStateException("响应缺少 data 数组");
|
||||
}
|
||||
return data;
|
||||
} catch (RuntimeException ex) {
|
||||
lastFailure = ex;
|
||||
warnUnavailable(endpoint, network, "TRC20交易", ex);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("所有 TRON HTTP 数据源均无法查询 TRC20 交易,网络="
|
||||
+ network, lastFailure);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询 TronScan 账户聚合数据。全部端点不可用时返回安全的零值,调用方仍可继续
|
||||
* 使用 Trident/gRPC 查询余额、质押本金和代理关系明细。
|
||||
*/
|
||||
public EnergyAndBandwidthVo queryDelegatedResourceSummary(ITronService tronService,
|
||||
String address) {
|
||||
return queryDelegatedResourceSummary(tronService.type(), address,
|
||||
tronService.tronscanApiKey());
|
||||
}
|
||||
|
||||
EnergyAndBandwidthVo queryDelegatedResourceSummary(String network, String address,
|
||||
String serviceApiKey) {
|
||||
for (String endpoint : endpoints(accountEndpoints, network)) {
|
||||
try {
|
||||
URI uri = UriComponentsBuilder.fromHttpUrl(endpoint)
|
||||
.path("/api/accountv2")
|
||||
.queryParam("address", address)
|
||||
.build().encode().toUri();
|
||||
JSONObject json = requestJson(uri, serviceApiKey);
|
||||
TronAccountResp account = json.toJavaObject(TronAccountResp.class);
|
||||
return toDelegatedResourceSummary(account);
|
||||
} catch (RuntimeException ex) {
|
||||
warnUnavailable(endpoint, network, "账户代理汇总", ex);
|
||||
}
|
||||
}
|
||||
log.warn("所有 TRON 账户聚合数据源均不可用,代理资源值暂按0返回,网络={}", network);
|
||||
return emptyDelegatedResourceSummary();
|
||||
}
|
||||
|
||||
/** 提供给 Trident 主网客户端使用,配置值禁止写入日志。 */
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
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;
|
||||
if (StringUtils.hasText(effectiveApiKey)) {
|
||||
headers.set("TRON-PRO-API-KEY", effectiveApiKey);
|
||||
}
|
||||
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,
|
||||
new HttpEntity<Void>(headers), String.class);
|
||||
if (!response.getStatusCode().is2xxSuccessful() || !StringUtils.hasText(response.getBody())) {
|
||||
throw new IllegalStateException("HTTP响应无有效数据,状态=" + response.getStatusCodeValue());
|
||||
}
|
||||
try {
|
||||
JSONObject json = JSON.parseObject(response.getBody());
|
||||
if (json == null) {
|
||||
throw new IllegalStateException("JSON响应为空");
|
||||
}
|
||||
return json;
|
||||
} catch (RuntimeException ex) {
|
||||
throw new IllegalStateException("JSON响应格式错误", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private EnergyAndBandwidthVo toDelegatedResourceSummary(TronAccountResp account) {
|
||||
EnergyAndBandwidthVo result = emptyDelegatedResourceSummary();
|
||||
result.setAcquiredEnergy(zeroIfNull(account.getAcquiredDelegatedFrozenV2BalanceForEnergyValue()));
|
||||
result.setAcquiredBandwidth(zeroIfNull(account.getAcquiredDelegatedFrozenV2BalanceForBandwidthValue()));
|
||||
result.setDelegateEnergy(zeroIfNull(account.getDelegatedFrozenV2BalanceForEnergyValue()));
|
||||
result.setDelegateBandwidth(zeroIfNull(account.getDelegatedFrozenV2BalanceForBandwidthValue()));
|
||||
result.setStakedTrxNum(BigDecimal.valueOf(account.getTotalFrozenV2())
|
||||
.movePointLeft(6).setScale(0, RoundingMode.DOWN).longValue());
|
||||
if (account.getBandwidth() != null) {
|
||||
result.setBandwidthStakedNum(account.getBandwidth().getNetRemaining());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private EnergyAndBandwidthVo emptyDelegatedResourceSummary() {
|
||||
EnergyAndBandwidthVo result = new EnergyAndBandwidthVo();
|
||||
result.setDelegateBandwidth(BigDecimal.ZERO);
|
||||
result.setDelegateEnergy(BigDecimal.ZERO);
|
||||
result.setAcquiredBandwidth(BigDecimal.ZERO);
|
||||
result.setAcquiredEnergy(BigDecimal.ZERO);
|
||||
result.setStakedTrxNum(0L);
|
||||
return result;
|
||||
}
|
||||
|
||||
private BigDecimal zeroIfNull(BigDecimal value) {
|
||||
return value == null ? BigDecimal.ZERO : value;
|
||||
}
|
||||
|
||||
private void warnUnavailable(String endpoint, String network, String operation, RuntimeException ex) {
|
||||
String host;
|
||||
try {
|
||||
host = URI.create(endpoint).getHost();
|
||||
} catch (RuntimeException ignored) {
|
||||
host = "invalid-endpoint";
|
||||
}
|
||||
String reason = ex instanceof RestClientException ? ex.getClass().getSimpleName() : ex.getMessage();
|
||||
log.warn("TRON数据源不可用,准备切换备用源,操作={},网络={},主机={},原因={}",
|
||||
operation, network, host, reason);
|
||||
}
|
||||
|
||||
private List<String> endpoints(Map<String, List<String>> source, String network) {
|
||||
List<String> result = source.get(normalizeNetwork(network));
|
||||
if (result == null || result.isEmpty()) {
|
||||
throw new IllegalStateException("未配置 TRON HTTP 数据源,网络=" + network);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static RestTemplate createRestTemplate() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(HTTP_TIMEOUT_MILLIS);
|
||||
factory.setReadTimeout(HTTP_TIMEOUT_MILLIS);
|
||||
return new RestTemplate(factory);
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> endpointMap(String mainnet, String nile, String shasta) {
|
||||
Map<String, List<String>> result = new LinkedHashMap<>();
|
||||
result.put("mainnet", parseEndpoints(mainnet));
|
||||
result.put("nile", parseEndpoints(nile));
|
||||
result.put("shasta", parseEndpoints(shasta));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<String> parseEndpoints(String configured) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (configured == null) {
|
||||
return result;
|
||||
}
|
||||
for (String endpoint : Arrays.asList(configured.split(","))) {
|
||||
String normalized = endpoint.trim();
|
||||
while (normalized.endsWith("/")) {
|
||||
normalized = normalized.substring(0, normalized.length() - 1);
|
||||
}
|
||||
if (StringUtils.hasText(normalized) && !result.contains(normalized)) {
|
||||
result.add(normalized);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String normalizeNetwork(String network) {
|
||||
if (network == null) {
|
||||
return "";
|
||||
}
|
||||
String normalized = network.trim().toLowerCase(Locale.ROOT);
|
||||
return "pro".equals(normalized) ? "mainnet" : normalized;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user