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.*; 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.*; /** * TRON HTTP 链上数据统一入口。 * *

同一网络可以配置多个兼容端点。单个端点出现 404、限流、服务端错误、 * 超时或响应结构异常时会自动尝试下一个端点,避免支付扫描依赖单一域名。

*/ @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> transactionEndpoints; private final Map> accountEndpoints; private final String apiKey; private String tronscanApiKey = "47fae50b-b5e8-4d1b-8329-501a422a3169"; /** * TronScan 与 TronGrid 是不同平台,凭证必须分别配置,禁止跨平台发送。 */ @Value("${tron.chain-data.tronscan-api-key:}") public void setTronscanApiKey(String key) { this.tronscanApiKey = key == null ? "" : key.trim(); } @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:719b2ba2-dedd-48ad-99a6-df1caa6f08ae}") String apiKey) { this(createRestTemplate(), endpointMap(mainnetTransactionEndpoints, nileTransactionEndpoints, shastaTransactionEndpoints), endpointMap(mainnetAccountEndpoints, nileAccountEndpoints, shastaAccountEndpoints), apiKey); } TronChainDataClient(RestTemplate restTemplate, Map> transactionEndpoints, Map> 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 endpoints = endpoints(transactionEndpoints, network); RuntimeException lastFailure = null; for (String endpoint : endpoints) { try { 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, scan ? tronscanApiKey : apiKey); if (Boolean.FALSE.equals(body.getBoolean("success"))) { throw new IllegalStateException("数据源明确返回查询失败"); } JSONArray data = scan ? normalizeTronscanTransfers(body, contractAddress) : 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, tronscanApiKey); if (!address.equals(json.getString("address"))) { throw new IllegalStateException("账户响应缺少匹配地址"); } 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 = serviceApiKey; if (StringUtils.hasText(effectiveApiKey)) { headers.set("TRON-PRO-API-KEY", effectiveApiKey); } ResponseEntity response = restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity(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); } } /** * 自定义代理地址可通过 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())); 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 endpoints(Map> source, String network) { List 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> endpointMap(String mainnet, String nile, String shasta) { Map> result = new LinkedHashMap<>(); result.put("mainnet", parseEndpoints(mainnet)); result.put("nile", parseEndpoints(nile)); result.put("shasta", parseEndpoints(shasta)); return result; } private static List parseEndpoints(String configured) { List 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; } }