多域名兼容链上获取数据
This commit is contained in:
1 parent
2601bc898a
commit
0d0642d312
4 files changed
+119
-5
No files matched your search
@@ -0,0 +1,26 @@
|
||||
# TRON HTTP 数据源配置
|
||||
|
||||
TronGrid 和 TronScan 使用独立 API Key,即使请求头名称相同也不能混用。
|
||||
|
||||
```sh
|
||||
export TRON_GRID_API_KEY='你的TronGrid密钥'
|
||||
export TRONSCAN_API_KEY='你的TronScan密钥'
|
||||
```
|
||||
|
||||
重启后端生效。原有 `tron.chain-data.api-key` 仍仅代表 TronGrid,
|
||||
新增 `tron.chain-data.tronscan-api-key` 代表 TronScan。
|
||||
|
||||
交易查询按现有端点列表顺序切换,TronGrid 使用
|
||||
`/v1/accounts/{address}/transactions/trc20`,TronScan 使用
|
||||
`/api/token_trc20/transfers`,映射为统一的地址、毫秒时间、交易哈希和原始最小单位金额。
|
||||
TronScan 仅接受 `confirmed=true`、`contractRet=SUCCESS` 且合约匹配的记录。
|
||||
单次 TronScan 查询最多50条,当前实现不提供历史全量分页,适用于现有近期待支付订单扫描。
|
||||
|
||||
自定义代理地址可使用 `tronscan|https://proxy.example` 或
|
||||
`trongrid|https://proxy.example` 显式指定交易接口类型;未指定时按域名识别,其他域名默认为TronGrid。
|
||||
账户端点列表仅配置兼容 `/api/accountv2` 的 TronScan 服务。
|
||||
账户汇总使用 TronScan Key,Trident RPC 使用 TronGrid Key。
|
||||
|
||||
连接和读取超时各60秒,全部交易源失败时保留订单待支付状态,下一轮继续查询。
|
||||
账户汇总全部失败时沿用现有零值降级;不代表链上真实资源为0。
|
||||
未使用真实生产凭证进行端到端验证,需部署环境验证两平台权限及配额。
|
||||
@@ -140,6 +140,8 @@ tron:
|
||||
chain-data:
|
||||
# 多个端点按顺序尝试,使用英文逗号分隔。生产环境建议通过对应环境变量覆盖。
|
||||
api-key: ${TRON_GRID_API_KEY:}
|
||||
# TronScan 独立申请的 API Key,不能填写 TronGrid 的 Key。
|
||||
tronscan-api-key: ${TRONSCAN_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}
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -76,6 +76,33 @@ public class TronChainDataClientTest {
|
||||
assertEquals(Long.valueOf(0L), summary.getStakedTrxNum());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldAdaptTronscanAndKeepCredentialsSeparate() {
|
||||
final String[] keys = new String[2];
|
||||
server.createContext("/grid/v1/accounts/TAddress/transactions/trc20", exchange -> {
|
||||
keys[0] = exchange.getRequestHeaders().getFirst("TRON-PRO-API-KEY");
|
||||
new FixedResponseHandler(429, "{}").handle(exchange);
|
||||
});
|
||||
server.createContext("/scan/api/token_trc20/transfers", exchange -> {
|
||||
keys[1] = exchange.getRequestHeaders().getFirst("TRON-PRO-API-KEY");
|
||||
new FixedResponseHandler(200, "{\"token_transfers\":["
|
||||
+ "{\"confirmed\":true,\"contractRet\":\"SUCCESS\",\"contract_address\":\"TContract\","
|
||||
+ "\"to_address\":\"TAddress\",\"block_ts\":123456,\"transaction_id\":\"hash\",\"quant\":\"1230000\"},"
|
||||
+ "{\"confirmed\":false,\"contractRet\":\"SUCCESS\"}]}").handle(exchange);
|
||||
});
|
||||
Map<String, List<String>> endpoints = new LinkedHashMap<>();
|
||||
endpoints.put("mainnet", Arrays.asList(baseUrl + "/grid", "tronscan|" + baseUrl + "/scan"));
|
||||
TronChainDataClient client = new TronChainDataClient(new RestTemplate(), endpoints,
|
||||
endpoints, "grid-key");
|
||||
client.setTronscanApiKey("scan-key");
|
||||
JSONArray data = client.queryConfirmedTrc20Transactions("mainnet", "TAddress", "TContract", "", 200);
|
||||
assertEquals(1, data.size());
|
||||
assertEquals("1230000", data.getJSONObject(0).getString("value"));
|
||||
assertEquals("TAddress", data.getJSONObject(0).getString("to"));
|
||||
assertEquals("grid-key", keys[0]);
|
||||
assertEquals("scan-key", keys[1]);
|
||||
}
|
||||
|
||||
private TronChainDataClient client(List<String> transactions, List<String> accounts) {
|
||||
Map<String, List<String>> transactionEndpoints = new LinkedHashMap<>();
|
||||
Map<String, List<String>> accountEndpoints = new LinkedHashMap<>();
|
||||
|
||||
Reference in new issue
Block a user