获取链上信息兼容

This commit is contained in:
lu7213 committed 2026-10-16 10:19:14 -04:00
1 parent ceb8807273
commit 2601bc898a
8 files changed
+412 -103

No files matched your search

@@ -1,6 +1,5 @@
package com.ruoyi.task; package com.ruoyi.task;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@@ -8,13 +7,13 @@ import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.ITronService; import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.IUsdtOrdersService; import com.ruoyi.system.service.IUsdtOrdersService;
import com.ruoyi.system.service.TronServiceProvider; import com.ruoyi.system.service.TronServiceProvider;
import com.ruoyi.system.service.TronChainDataClient;
import com.ruoyi.system.service.WalletLedgerPostingService; import com.ruoyi.system.service.WalletLedgerPostingService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
@@ -36,7 +35,8 @@ public class TronPaymentTask {
private TronServiceProvider tronServiceProvider; private TronServiceProvider tronServiceProvider;
@Autowired @Autowired
private WalletLedgerPostingService ledgerPostingService; private WalletLedgerPostingService ledgerPostingService;
private final RestTemplate http = new RestTemplate(); @Autowired
private TronChainDataClient chainDataClient;
@Scheduled(fixedDelay = 10000L) @Scheduled(fixedDelay = 10000L)
public void scan() { public void scan() {
@@ -53,10 +53,8 @@ public class TronPaymentTask {
.or().eq(UsdtOrdersPlus::getBlockTransactionId, "")))) { .or().eq(UsdtOrdersPlus::getBlockTransactionId, "")))) {
if (order.getToken() == null || order.getActualAmount() == null) continue; if (order.getToken() == null || order.getActualAmount() == null) continue;
try { try {
String url = tron.tronscanApiUrl() + "/v1/accounts/" + order.getToken() + "/transactions/trc20?limit=200&only_confirmed=true&contract_address=" + tron.contractAddress(); JSONArray data = chainDataClient.queryConfirmedTrc20Transactions(
JSONObject root = JSON.parseObject(http.getForObject(url, String.class)); tron, order.getToken(), 200);
JSONArray data = root == null ? null : root.getJSONArray("data");
if (data == null) continue;
for (int i = 0; i < data.size(); i++) { for (int i = 0; i < data.size(); i++) {
JSONObject tx = data.getJSONObject(i); JSONObject tx = data.getJSONObject(i);
if (!order.getToken().equals(tx.getString("to"))) continue; if (!order.getToken().equals(tx.getString("to"))) continue;
@@ -137,6 +137,18 @@ payment:
# 钱包链上操作资源预算配置。 # 钱包链上操作资源预算配置。
tron: tron:
operation-resource-redundancy-percent: ${TRON_OPERATION_RESOURCE_REDUNDANCY_PERCENT:20} operation-resource-redundancy-percent: ${TRON_OPERATION_RESOURCE_REDUNDANCY_PERCENT:20}
chain-data:
# 多个端点按顺序尝试,使用英文逗号分隔。生产环境建议通过对应环境变量覆盖。
api-key: ${TRON_GRID_API_KEY:}
mainnet:
transaction-endpoints: ${TRON_MAINNET_TRANSACTION_ENDPOINTS:https://api.trongrid.io,https://apilist.tronscanapi.com,https://api.tronscan.org}
account-endpoints: ${TRON_MAINNET_ACCOUNT_ENDPOINTS:https://apilist.tronscanapi.com,https://api.tronscan.org}
nile:
transaction-endpoints: ${TRON_NILE_TRANSACTION_ENDPOINTS:https://nile.trongrid.io,https://nileapi.tronscan.org}
account-endpoints: ${TRON_NILE_ACCOUNT_ENDPOINTS:https://nileapi.tronscan.org}
shasta:
transaction-endpoints: ${TRON_SHASTA_TRANSACTION_ENDPOINTS:https://api.shasta.trongrid.io,https://shastapi.tronscan.org}
account-endpoints: ${TRON_SHASTA_ACCOUNT_ENDPOINTS:https://shastapi.tronscan.org}
# MyBatis配置 # MyBatis配置
mybatis: mybatis:
@@ -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;
}
}
@@ -6,7 +6,6 @@ import com.ruoyi.system.domain.UsdtConfigPlus;
import com.ruoyi.system.mapper.UsdtConfigMapper; import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.impl.TronNileServiceImpl; import com.ruoyi.system.service.impl.TronNileServiceImpl;
import com.ruoyi.system.service.impl.TronProServiceImpl; import com.ruoyi.system.service.impl.TronProServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
@@ -19,11 +18,16 @@ public class TronServiceProvider {
private static final int NETWORK_NILE = 0; private static final int NETWORK_NILE = 0;
private static final int NETWORK_MAINNET = 1; private static final int NETWORK_MAINNET = 1;
@Autowired private final UsdtConfigMapper usdtConfigMapper;
private UsdtConfigMapper usdtConfigMapper; private final ITronService nileService;
private final ITronService mainnetService;
private final ITronService nileService = new TronNileServiceImpl(); public TronServiceProvider(UsdtConfigMapper usdtConfigMapper,
private final ITronService mainnetService = new TronProServiceImpl(); TronChainDataClient chainDataClient) {
this.usdtConfigMapper = usdtConfigMapper;
this.nileService = new TronNileServiceImpl(chainDataClient);
this.mainnetService = new TronProServiceImpl(chainDataClient);
}
/** /**
* 查询唯一全局配置,并返回配置网络对应的服务实现。 * 查询唯一全局配置,并返回配置网络对应的服务实现。
@@ -4,8 +4,8 @@ import com.google.protobuf.ByteString;
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
import com.ruoyi.system.domain.vo.TronAccount; import com.ruoyi.system.domain.vo.TronAccount;
import com.ruoyi.system.domain.vo.TronAccountItem; import com.ruoyi.system.domain.vo.TronAccountItem;
import com.ruoyi.system.domain.vo.TronAccountResp;
import com.ruoyi.system.service.ITronService; import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.TronChainDataClient;
import io.grpc.ManagedChannel; import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder; import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -21,9 +21,7 @@ import org.bouncycastle.jcajce.provider.digest.Keccak;
import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.Hex;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.*;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI;
import org.tron.api.WalletGrpc; import org.tron.api.WalletGrpc;
import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey;
@@ -62,7 +60,11 @@ public class TronNileServiceImpl implements ITronService {
private static SecureRandom random = new SecureRandom(); private static SecureRandom random = new SecureRandom();
private static final BigInteger BASE = BigInteger.valueOf(58); private static final BigInteger BASE = BigInteger.valueOf(58);
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private RestTemplate restTemplate = new RestTemplate(); private final TronChainDataClient chainDataClient;
public TronNileServiceImpl(TronChainDataClient chainDataClient) {
this.chainDataClient = chainDataClient;
}
@Override @Override
public Integer grpcPort() { public Integer grpcPort() {
return 50051; return 50051;
@@ -101,12 +103,13 @@ public class TronNileServiceImpl implements ITronService {
@Override @Override
public String tronscanApiUrl() { public String tronscanApiUrl() {
return "https://nileapi.tronscan.org"; return "https://nile.trongrid.io";
// return "https://nile.trongrid.io";
} }
@Override @Override
public String tronscanApiKey() { public String tronscanApiKey() {
return ""; return chainDataClient.getApiKey();
} }
@Override @Override
@@ -212,31 +215,7 @@ public class TronNileServiceImpl implements ITronService {
@Override @Override
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) { public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
HttpHeaders headers = new HttpHeaders(); return chainDataClient.queryDelegatedResourceSummary(this, ownerAddr);
if (!tronscanApiKey().isEmpty()) headers.set("TRON-PRO-API-KEY", tronscanApiKey());
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<Void> entity = new HttpEntity<>(headers);
ResponseEntity<TronAccountResp> result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class);
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
if(null != result.getBody()){
energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue());
energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue());
energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue());
energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue());
energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2());
energyAndBandwidthVo.setBandwidthStakedNum(result.getBody().getBandwidth().getNetRemaining());
BigDecimal divisor = new BigDecimal("1000000");
BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP);
energyAndBandwidthVo.setStakedTrxNum(divide.longValue());
}else{
energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0));
energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0));
energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0));
energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0));
energyAndBandwidthVo.setStakedTrxNum(0L);
}
return energyAndBandwidthVo;
} }
@Override @Override
@@ -4,8 +4,8 @@ import com.google.protobuf.ByteString;
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
import com.ruoyi.system.domain.vo.TronAccount; import com.ruoyi.system.domain.vo.TronAccount;
import com.ruoyi.system.domain.vo.TronAccountItem; import com.ruoyi.system.domain.vo.TronAccountItem;
import com.ruoyi.system.domain.vo.TronAccountResp;
import com.ruoyi.system.service.ITronService; import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.TronChainDataClient;
import io.grpc.ManagedChannel; import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder; import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -20,8 +20,6 @@ import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jcajce.provider.digest.Keccak; import org.bouncycastle.jcajce.provider.digest.Keccak;
import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.Hex;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI;
import org.tron.api.WalletGrpc; import org.tron.api.WalletGrpc;
import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey;
@@ -58,11 +56,15 @@ public class TronProServiceImpl implements ITronService {
private static final BigInteger BASE = BigInteger.valueOf(58); private static final BigInteger BASE = BigInteger.valueOf(58);
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private RestTemplate restTemplate = new RestTemplate(); private final TronChainDataClient chainDataClient;
// 能量和带宽限制 // 能量和带宽限制
public static final long FEE_LIMIT = 10_000_000L; // 10 TRX public static final long FEE_LIMIT = 10_000_000L; // 10 TRX
private static SecureRandom random = new SecureRandom(); private static SecureRandom random = new SecureRandom();
public TronProServiceImpl(TronChainDataClient chainDataClient) {
this.chainDataClient = chainDataClient;
}
@Override @Override
public Integer grpcPort() { public Integer grpcPort() {
return 50051; return 50051;
@@ -148,12 +150,12 @@ public class TronProServiceImpl implements ITronService {
@Override @Override
public String tronscanApiUrl() { public String tronscanApiUrl() {
return "https://api.tronscan.org"; return "https://api.trongrid.io";
} }
@Override @Override
public String tronscanApiKey() { public String tronscanApiKey() {
return "47fae50b-b5e8-4d1b-8329-501a422a3169"; return chainDataClient.getApiKey();
} }
@Override @Override
@@ -287,30 +289,7 @@ public class TronProServiceImpl implements ITronService {
@Override @Override
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) { public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
HttpHeaders headers = new HttpHeaders(); return chainDataClient.queryDelegatedResourceSummary(this, ownerAddr);
headers.set("TRON-PRO-API-KEY", tronscanApiKey());
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<Void> entity = new HttpEntity<>(headers);
ResponseEntity<TronAccountResp> result = restTemplate.exchange(tronscanApiUrl() + "/api/accountv2?address=" + ownerAddr, HttpMethod.GET, entity, TronAccountResp.class);
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
if (null != result.getBody()) {
energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue());
energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue());
energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue());
energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue());
energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2());
BigDecimal divisor = new BigDecimal("1000000");
BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP);
energyAndBandwidthVo.setStakedTrxNum(divide.longValue());
} else {
energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0));
energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0));
energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0));
energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0));
energyAndBandwidthVo.setStakedTrxNum(0L);
}
return energyAndBandwidthVo;
} }
@Override @Override
@@ -5,8 +5,8 @@ import com.ruoyi.common.utils.http.HttpHelper;
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
import com.ruoyi.system.domain.vo.TronAccount; import com.ruoyi.system.domain.vo.TronAccount;
import com.ruoyi.system.domain.vo.TronAccountItem; import com.ruoyi.system.domain.vo.TronAccountItem;
import com.ruoyi.system.domain.vo.TronAccountResp;
import com.ruoyi.system.service.ITronService; import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.TronChainDataClient;
import io.grpc.ManagedChannel; import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder; import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -22,9 +22,7 @@ import org.bouncycastle.jcajce.provider.digest.Keccak;
import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.Hex;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.*;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI;
import org.tron.api.WalletGrpc; import org.tron.api.WalletGrpc;
import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey;
@@ -64,7 +62,11 @@ public class TronShastaServiceImpl implements ITronService {
private static SecureRandom random = new SecureRandom(); private static SecureRandom random = new SecureRandom();
private static final BigInteger BASE = BigInteger.valueOf(58); private static final BigInteger BASE = BigInteger.valueOf(58);
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private RestTemplate restTemplate = new RestTemplate(); private final TronChainDataClient chainDataClient;
public TronShastaServiceImpl(TronChainDataClient chainDataClient) {
this.chainDataClient = chainDataClient;
}
@Override @Override
public Integer grpcPort() { public Integer grpcPort() {
return 50051; return 50051;
@@ -181,12 +183,12 @@ public class TronShastaServiceImpl implements ITronService {
@Override @Override
public String tronscanApiUrl() { public String tronscanApiUrl() {
return "https://shastapi.tronscan.org"; return "https://api.shasta.trongrid.io";
} }
@Override @Override
public String tronscanApiKey() { public String tronscanApiKey() {
return ""; return chainDataClient.getApiKey();
} }
@Override @Override
@@ -312,30 +314,7 @@ public class TronShastaServiceImpl implements ITronService {
} }
@Override @Override
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) { public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
HttpHeaders headers = new HttpHeaders(); return chainDataClient.queryDelegatedResourceSummary(this, ownerAddr);
if (!tronscanApiKey().isEmpty()) headers.set("TRON-PRO-API-KEY", tronscanApiKey());
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<Void> entity = new HttpEntity<>(headers);
ResponseEntity<TronAccountResp> result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class);
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
if(null != result.getBody()){
energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue());
energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue());
energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue());
energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue());
energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2());
BigDecimal divisor = new BigDecimal("1000000");
BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP);
energyAndBandwidthVo.setStakedTrxNum(divide.longValue());
}else{
energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0));
energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0));
energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0));
energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0));
energyAndBandwidthVo.setStakedTrxNum(0L);
}
return energyAndBandwidthVo;
} }
@Override @Override
public long defaultEstimateBandwidth() { public long defaultEstimateBandwidth() {
@@ -0,0 +1,105 @@
package com.ruoyi.system.service;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class TronChainDataClientTest {
private HttpServer server;
private String baseUrl;
@Before
public void setUp() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.start();
baseUrl = "http://127.0.0.1:" + server.getAddress().getPort();
}
@After
public void tearDown() {
if (server != null) {
server.stop(0);
}
}
@Test
public void shouldFallbackWhenEndpointReturns404OrMalformedBody() {
server.createContext("/missing/v1/accounts/TAddress/transactions/trc20",
new FixedResponseHandler(404, "not found"));
server.createContext("/malformed/v1/accounts/TAddress/transactions/trc20",
new FixedResponseHandler(200, "{\"success\":true}"));
server.createContext("/healthy/v1/accounts/TAddress/transactions/trc20",
new FixedResponseHandler(200, "{\"data\":[{\"transaction_id\":\"tx-1\"}]}"));
TronChainDataClient client = client(
Arrays.asList(baseUrl + "/missing", baseUrl + "/malformed", baseUrl + "/healthy"),
Collections.singletonList(baseUrl + "/missing"));
JSONArray transactions = client.queryConfirmedTrc20Transactions(
"mainnet", "TAddress", "TContract", "", 200);
assertEquals(1, transactions.size());
assertEquals("tx-1", transactions.getJSONObject(0).getString("transaction_id"));
}
@Test
public void shouldReturnSafeZeroSummaryWhenAllAccountEndpointsFail() {
server.createContext("/missing/api/accountv2", new FixedResponseHandler(404, "not found"));
TronChainDataClient client = client(Collections.singletonList(baseUrl + "/missing"),
Collections.singletonList(baseUrl + "/missing"));
EnergyAndBandwidthVo summary = client.queryDelegatedResourceSummary(
"mainnet", "TAddress", "");
assertEquals(0, summary.getDelegateEnergy().signum());
assertEquals(0, summary.getDelegateBandwidth().signum());
assertEquals(0, summary.getAcquiredEnergy().signum());
assertEquals(0, summary.getAcquiredBandwidth().signum());
assertEquals(Long.valueOf(0L), summary.getStakedTrxNum());
}
private TronChainDataClient client(List<String> transactions, List<String> accounts) {
Map<String, List<String>> transactionEndpoints = new LinkedHashMap<>();
Map<String, List<String>> accountEndpoints = new LinkedHashMap<>();
transactionEndpoints.put("mainnet", transactions);
accountEndpoints.put("mainnet", accounts);
return new TronChainDataClient(new RestTemplate(), transactionEndpoints, accountEndpoints, "");
}
private static class FixedResponseHandler implements HttpHandler {
private final int status;
private final byte[] body;
FixedResponseHandler(int status, String body) {
this.status = status;
this.body = body.getBytes(StandardCharsets.UTF_8);
}
@Override
public void handle(HttpExchange exchange) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json;charset=UTF-8");
exchange.sendResponseHeaders(status, body.length);
try (OutputStream output = exchange.getResponseBody()) {
output.write(body);
}
}
}
}