优化代码
This commit is contained in:
1 parent
ed738d3da6
commit
4048428169
14 files changed
+351
-279
No files matched your search
@@ -7,6 +7,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.ruoyi.system.domain.UsdtOrdersPlus;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import com.ruoyi.system.service.IUsdtOrdersService;
|
||||
import com.ruoyi.system.service.TronServiceProvider;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -21,14 +24,23 @@ import java.util.Date;
|
||||
*/
|
||||
@Component
|
||||
public class TronPaymentTask {
|
||||
private static final Logger log = LoggerFactory.getLogger(TronPaymentTask.class);
|
||||
|
||||
@Autowired
|
||||
private IUsdtOrdersService orders;
|
||||
@Autowired
|
||||
private ITronService tron;
|
||||
private TronServiceProvider tronServiceProvider;
|
||||
private final RestTemplate http = new RestTemplate();
|
||||
|
||||
@Scheduled(fixedDelay = 30000L)
|
||||
public void scan() {
|
||||
ITronService tron;
|
||||
try {
|
||||
tron = tronServiceProvider.getCurrentService();
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("无法读取 TRON 全局网络配置,跳过本轮支付扫描:{}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
for (UsdtOrdersPlus order : orders.list(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getStatus, 1))) {
|
||||
if (order.getToken() == null || order.getActualAmount() == null) continue;
|
||||
try {
|
||||
@@ -51,8 +63,11 @@ public class TronPaymentTask {
|
||||
orders.updateById(order);
|
||||
break;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
} catch (Exception e) {
|
||||
// 单笔订单查询失败不能中断其他订单,日志中禁止输出凭证和钱包私钥。
|
||||
log.warn("查询 TRON 支付交易失败,订单ID={},网络={}", order.getId(), tron.type());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.ruoyi.task;
|
||||
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
|
||||
import com.ruoyi.system.domain.WalletAddressPlus;
|
||||
import com.ruoyi.system.service.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 后台逐地址执行归集任务;每个明细独立失败并继续后续地址。
|
||||
*/
|
||||
@Component
|
||||
@EnableScheduling
|
||||
public class UsdtAggregationExecutorTask {
|
||||
private static final Logger log = LoggerFactory.getLogger(UsdtAggregationExecutorTask.class);
|
||||
@Autowired
|
||||
private IUsdtAggregationTaskService taskService;
|
||||
@Autowired
|
||||
private IUsdtAggregationTaskItemService itemService;
|
||||
@Autowired
|
||||
private IWalletAddressService walletService;
|
||||
@Autowired
|
||||
private TronServiceProvider tronServiceProvider;
|
||||
|
||||
@Scheduled(fixedDelay = 30000L)
|
||||
public void executePending() {
|
||||
ITronService tronService;
|
||||
try {
|
||||
tronService = tronServiceProvider.getCurrentService();
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("无法读取 TRON 全局网络配置,跳过本轮归集任务:{}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
List<UsdtAggregationTaskPlus> tasks = taskService.getListByStatusAndLtExeTime(1, new java.util.Date(System.currentTimeMillis() + 1));
|
||||
for (UsdtAggregationTaskPlus task : tasks) executeTask(task, tronService);
|
||||
}
|
||||
|
||||
private void executeTask(UsdtAggregationTaskPlus task, ITronService tronService) {
|
||||
List<UsdtAggregationTaskItemPlus> items = itemService.getListByStatusAndParentId(0, task.getId());
|
||||
boolean failed = false;
|
||||
for (UsdtAggregationTaskItemPlus item : items) {
|
||||
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
|
||||
String tx = null;
|
||||
Exception last = null;
|
||||
for (int attempt = 0; attempt < 4 && tx == null; attempt++) {
|
||||
org.tron.trident.core.ApiWrapper api = null;
|
||||
try {
|
||||
api = tronService.buildApiWrapper();
|
||||
tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString());
|
||||
} catch (Exception ex) {
|
||||
last = ex;
|
||||
} finally {
|
||||
if (api != null) api.close();
|
||||
}
|
||||
}
|
||||
if (tx == null || tx.trim().isEmpty()) {
|
||||
fail(item, "重试耗尽:" + (last == null ? "交易失败" : last.getMessage()));
|
||||
failed = true;
|
||||
} else {
|
||||
item.setStatus(1L);
|
||||
item.setRemark("交易哈希:" + tx);
|
||||
itemService.updateById(item);
|
||||
}
|
||||
}
|
||||
task.setStatus(failed ? 3 : 2);
|
||||
taskService.updateById(task);
|
||||
}
|
||||
|
||||
private void fail(UsdtAggregationTaskItemPlus item, String reason) {
|
||||
item.setStatus(2L);
|
||||
item.setRemark(reason);
|
||||
itemService.updateById(item);
|
||||
}
|
||||
}
|
||||
@@ -57,10 +57,6 @@ logging:
|
||||
level:
|
||||
com.ruoyi: debug
|
||||
org.springframework: warn
|
||||
|
||||
tron:
|
||||
env:
|
||||
type: nile
|
||||
# Spring配置
|
||||
spring:
|
||||
resources:
|
||||
|
||||
@@ -19,10 +19,8 @@ import org.springframework.web.bind.annotation.*;
|
||||
import java.util.List;
|
||||
import java.math.BigDecimal;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
import java.math.BigInteger;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import com.ruoyi.system.service.TronServiceProvider;
|
||||
import com.ruoyi.system.domain.vo.WalletOperationRequest;
|
||||
|
||||
/**
|
||||
@@ -37,7 +35,7 @@ public class WalletAddressController extends BaseController {
|
||||
@Autowired
|
||||
private IWalletAddressService walletAddressService;
|
||||
@Autowired
|
||||
private ITronService tronService;
|
||||
private TronServiceProvider tronServiceProvider;
|
||||
|
||||
/** 查询链上账户快照。私钥只从服务端读取,响应永远不包含 tokenKey。 */
|
||||
@PreAuthorize("@ss.hasPermi('system:address:query')")
|
||||
@@ -52,6 +50,7 @@ public class WalletAddressController extends BaseController {
|
||||
}
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
ITronService tronService = tronServiceProvider.getCurrentService();
|
||||
api = tronService.buildApiWrapper();
|
||||
wallet.setTrxBalance(tronService.getTRxBalance(api, wallet.getToken()));
|
||||
wallet.setUsdtBalance(tronService.getUsdtBalance(api, wallet.getToken()));
|
||||
@@ -78,6 +77,7 @@ public class WalletAddressController extends BaseController {
|
||||
if (!Boolean.TRUE.equals(request.getBroadcast())) return AjaxResult.success("预演模式:已通过参数校验,未广播交易");
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
ITronService tronService = tronServiceProvider.getCurrentService();
|
||||
api = tronService.buildApiWrapper();
|
||||
String tx;
|
||||
BigDecimal amount = request.getAmount();
|
||||
|
||||
@@ -12,8 +12,10 @@ public interface ITronService {
|
||||
Integer grpcPort();
|
||||
String grpcUrl();
|
||||
String type();
|
||||
/** 创建带私钥的客户端,仅用于确实需要签名的交易操作。 */
|
||||
ApiWrapper buildApiWrapper(String privateKey);
|
||||
|
||||
/** 创建只读客户端;禁止用于转账、质押、代理、投票等签名操作。 */
|
||||
ApiWrapper buildApiWrapper();
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ruoyi.system.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import com.ruoyi.system.domain.UsdtConfigPlus;
|
||||
import com.ruoyi.system.mapper.UsdtConfigMapper;
|
||||
import com.ruoyi.system.service.impl.TronNileServiceImpl;
|
||||
import com.ruoyi.system.service.impl.TronProServiceImpl;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 根据数据库全局配置提供当前 TRON 网络服务。
|
||||
* <p>
|
||||
* 无需重启即可切换到 Nile 测试网或主网。
|
||||
*/
|
||||
@Service
|
||||
public class TronServiceProvider {
|
||||
private static final int NETWORK_NILE = 0;
|
||||
private static final int NETWORK_MAINNET = 1;
|
||||
|
||||
@Autowired
|
||||
private UsdtConfigMapper usdtConfigMapper;
|
||||
|
||||
private final ITronService nileService = new TronNileServiceImpl();
|
||||
private final ITronService mainnetService = new TronProServiceImpl();
|
||||
|
||||
/**
|
||||
* 查询唯一全局配置,并返回配置网络对应的服务实现。
|
||||
*/
|
||||
public ITronService getCurrentService() {
|
||||
UsdtConfigPlus config = usdtConfigMapper.selectOne(new LambdaQueryWrapper<UsdtConfigPlus>()
|
||||
.select(UsdtConfigPlus::getId, UsdtConfigPlus::getTronNetType)
|
||||
.orderByAsc(UsdtConfigPlus::getId).last("limit 1"));
|
||||
if (config == null || config.getTronNetType() == null) {
|
||||
throw new CustomException("未配置 TRON 全局网络");
|
||||
}
|
||||
int networkType = config.getTronNetType().intValue();
|
||||
if (networkType == NETWORK_NILE) return nileService;
|
||||
if (networkType == NETWORK_MAINNET) return mainnetService;
|
||||
throw new CustomException("TRON 全局网络类型非法:" + networkType);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import com.ruoyi.system.domain.vo.TronAccountResp;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.ManagedChannelBuilder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
@@ -53,10 +54,8 @@ import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@ConditionalOnProperty(prefix = "tron.env", name = "type", havingValue = "nile")
|
||||
@Service
|
||||
public class TronNileServiceImpl implements ITronService {
|
||||
private static final Logger log = LoggerFactory.getLogger(TronNileServiceImpl.class);
|
||||
// 能量和带宽限制
|
||||
public static final long FEE_LIMIT = 10_000_000L; // 10 TRX
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
@@ -130,7 +129,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
if (transfer == null || transfer.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return transfer;
|
||||
return TronServiceSupport.requireTransactionHash(transfer);
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getMessage(),ex);
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
@@ -141,7 +140,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
public String trxTrans(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
@@ -150,8 +149,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
long byteSize = api.estimateBandwidth(signTransaction);
|
||||
// long byteSize = api.estimateEnergy(signTransaction);
|
||||
// 广播交易
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
} catch (Exception e) {
|
||||
log.error("TRX transfer failed", e);
|
||||
}
|
||||
@@ -183,27 +181,28 @@ public class TronNileServiceImpl implements ITronService {
|
||||
.forAddress(this.grpcUrl(), this.grpcPort())
|
||||
.usePlaintext()
|
||||
.build();
|
||||
WalletGrpc.WalletBlockingStub stub =
|
||||
WalletGrpc.newBlockingStub(channel);
|
||||
try {
|
||||
WalletGrpc.WalletBlockingStub stub = WalletGrpc.newBlockingStub(channel);
|
||||
byte[] address = Base58Check.base58ToBytes(ownerAddr);
|
||||
Protocol.Account account = Protocol.Account.newBuilder()
|
||||
.setAddress(ByteString.copyFrom(address))
|
||||
.build();
|
||||
.setAddress(ByteString.copyFrom(address)).build();
|
||||
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
|
||||
long bandwidth = Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())
|
||||
+ Math.max(0L, res.getNetLimit() - res.getNetUsed());
|
||||
long energy = Math.max(0L, res.getEnergyLimit() - res.getEnergyUsed());
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
|
||||
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
|
||||
EnergyAndBandwidthVo result = new EnergyAndBandwidthVo();
|
||||
result.setBandwidth(BigDecimal.valueOf(bandwidth));
|
||||
result.setEnergy(BigDecimal.valueOf(energy));
|
||||
return result;
|
||||
} finally {
|
||||
channel.shutdown();
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("TRON-PRO-API-KEY", "your_api_key");
|
||||
if (!tronscanApiKey().isEmpty()) headers.set("TRON-PRO-API-KEY", tronscanApiKey());
|
||||
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<Void> entity = new HttpEntity<>(headers);
|
||||
@@ -235,14 +234,14 @@ public class TronNileServiceImpl implements ITronService {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.unfreezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
TronServiceSupport.toSun(balance, "balance"),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -255,7 +254,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -265,14 +264,14 @@ public class TronNileServiceImpl implements ITronService {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.freezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
TronServiceSupport.toSun(balance, "balance"),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -370,7 +369,6 @@ public class TronNileServiceImpl implements ITronService {
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
System.out.println(divide);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@@ -480,10 +478,8 @@ public class TronNileServiceImpl implements ITronService {
|
||||
@Override
|
||||
public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
BigInteger amountInSun = BigInteger.valueOf(
|
||||
TronServiceSupport.toSun(amount, "amount"));
|
||||
Function function = new Function(
|
||||
"approve",
|
||||
Arrays.asList(
|
||||
@@ -516,8 +512,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
BigInteger allowance = token.allowance(ownerAddress, spenderAddress);
|
||||
|
||||
// 如果是USDT等6位小数代币
|
||||
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
|
||||
return new BigDecimal(allowanceInToken);
|
||||
return new BigDecimal(allowance).movePointLeft(6);
|
||||
} catch (Exception e) {
|
||||
log.error("TRON operation failed", e);
|
||||
}
|
||||
@@ -528,10 +523,8 @@ public class TronNileServiceImpl implements ITronService {
|
||||
public Boolean usdtTransferFrom(ApiWrapper api, String sender, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
// 转换金额为 USDT 最小单位 (6位小数)
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
BigInteger amountInSun = BigInteger.valueOf(
|
||||
TronServiceSupport.toSun(amount, "amount"));
|
||||
// 构建 transferFrom 函数
|
||||
Function function = new Function(
|
||||
"transferFrom",
|
||||
@@ -544,9 +537,6 @@ public class TronNileServiceImpl implements ITronService {
|
||||
);
|
||||
|
||||
|
||||
String encodedFunction = FunctionEncoder.encode(function);
|
||||
System.out.println("编码后的函数: " + encodedFunction);
|
||||
|
||||
// 触发智能合约调用
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址
|
||||
@@ -556,8 +546,8 @@ public class TronNileServiceImpl implements ITronService {
|
||||
// 签名交易
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
// 广播交易
|
||||
String ret = api.broadcastTransaction(signedTxn);
|
||||
log.info(ret);
|
||||
String ret = TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTxn));
|
||||
log.info("USDT transferFrom broadcast successfully, transactionHash={}", ret);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("transferFrom 异常: " + e.getMessage(), e);
|
||||
@@ -706,19 +696,17 @@ public class TronNileServiceImpl implements ITronService {
|
||||
@Override
|
||||
public long estimateEnergy(ApiWrapper api, String owner, String toAddress, BigDecimal amount) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Function function = new Function(
|
||||
"transfer(address,uint256)",
|
||||
"transfer",
|
||||
Arrays.asList(
|
||||
new Address(toAddress), // 接收地址
|
||||
new Uint256(rechangeAmount) // 转账金额
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
String callData = FunctionEncoder.encode(function);
|
||||
|
||||
Response.EstimateEnergyMessage estimate = api.estimateEnergy(
|
||||
owner, callData, callData, 0, 0, null
|
||||
owner, contractAddress(), function
|
||||
);
|
||||
return estimate.getEnergyRequired();
|
||||
}
|
||||
@@ -737,7 +725,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
public long estimateBandwidth(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
@@ -753,7 +741,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
@Override
|
||||
public String delegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400);
|
||||
@@ -761,14 +749,13 @@ public class TronNileServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String unDelegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress);
|
||||
@@ -776,8 +763,7 @@ public class TronNileServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -836,23 +822,4 @@ public class TronNileServiceImpl implements ITronService {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ITronService tronService = new TronNileServiceImpl();
|
||||
// tronService.energyAndBandwidth("TULphDUxnr4VBrKJr4C6YVetses1PSx8B4");
|
||||
ApiWrapper api = tronService.buildApiWrapper("34d200bcf5693a7ffc000edbb85fe0a7f84e7c87d894ef8638f516c07994a989");
|
||||
tronService.delegateResourceV2(api,"TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW","TULphDUxnr4VBrKJr4C6YVetses1PSx8B4",new BigDecimal("20"),0);
|
||||
// BigDecimal balance = tronService.getUsdtBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW");
|
||||
// System.out.println(balance);
|
||||
// balance = tronService.getTRxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW");
|
||||
// System.out.println(balance);
|
||||
// tronService.energyAndBandwidth("TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW");
|
||||
// System.out.println(tronService.stakedTrxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW", 0));
|
||||
// System.out.println(tronService.stakedTrxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW", 1));
|
||||
// System.out.println(tronService.delegatedStakedTrxBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4", 1));
|
||||
// System.out.println(tronService.delegatedStakedTrxBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4", 0));
|
||||
//// tronService.trxTrans(api,"TULphDUxnr4VBrKJr4C6YVetses1PSx8B4","TXTJKCikqtLZHK7moDdmxdaTNWbjdCM1H9",new BigDecimal(200));
|
||||
//// TronAccount tronAccount = tronService.createTronWallet(2);
|
||||
//// System.out.println(JSONObject.toJSONString(tronAccount));
|
||||
// tronService.allDelegatedDnergyAndBandwidth("TULphDUxnr4VBrKJr4C6YVetses1PSx8B4");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import com.ruoyi.system.domain.vo.TronAccountResp;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.ManagedChannelBuilder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
@@ -19,9 +20,7 @@ import org.bouncycastle.crypto.digests.SM3Digest;
|
||||
import org.bouncycastle.jcajce.provider.digest.Keccak;
|
||||
import org.bouncycastle.math.ec.ECPoint;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.tron.api.GrpcAPI;
|
||||
import org.tron.api.WalletGrpc;
|
||||
@@ -53,10 +52,8 @@ import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@ConditionalOnProperty(prefix = "tron.env", name = "type", havingValue = "pro")
|
||||
@Service
|
||||
public class TronProServiceImpl implements ITronService {
|
||||
private static final Logger log = LoggerFactory.getLogger(TronProServiceImpl.class);
|
||||
private static final BigInteger BASE = BigInteger.valueOf(58);
|
||||
|
||||
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
@@ -82,12 +79,14 @@ public class TronProServiceImpl implements ITronService {
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper(String privateKey) {
|
||||
return ApiWrapper.ofMainnet(privateKey, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
return ApiWrapper.ofMainnet(privateKey,
|
||||
TronServiceSupport.requiredEnvironment("TRON_PRO_API_KEY"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
return ApiWrapper.ofMainnet(null, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
return ApiWrapper.ofMainnet(null,
|
||||
TronServiceSupport.requiredEnvironment("TRON_PRO_API_KEY"));
|
||||
}
|
||||
|
||||
private static byte[] keccak256(byte[] input) {
|
||||
@@ -170,15 +169,11 @@ public class TronProServiceImpl implements ITronService {
|
||||
//转账
|
||||
transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit);
|
||||
} else {
|
||||
return "error_error";
|
||||
throw new IllegalStateException("USDT 余额不足");
|
||||
}
|
||||
if (transfer == null || transfer.equals("")) {
|
||||
return "error_error";
|
||||
}
|
||||
return transfer;
|
||||
return TronServiceSupport.requireTransactionHash(transfer);
|
||||
} catch (Exception ex) {
|
||||
String message = ex.getMessage();
|
||||
return "error_" + message;
|
||||
throw new IllegalStateException("USDT 转账失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +181,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
public String trxTrans(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
@@ -195,8 +190,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
long byteSize = api.estimateBandwidth(signTransaction);
|
||||
// long byteSize = api.estimateEnergy(signTransaction);
|
||||
// 广播交易
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
} catch (Exception e) {
|
||||
log.error("TRX transfer failed", e);
|
||||
}
|
||||
@@ -228,25 +222,28 @@ public class TronProServiceImpl implements ITronService {
|
||||
.forAddress(this.grpcUrl(), this.grpcPort())
|
||||
.usePlaintext()
|
||||
.build();
|
||||
WalletGrpc.WalletBlockingStub stub =
|
||||
WalletGrpc.newBlockingStub(channel);
|
||||
try {
|
||||
WalletGrpc.WalletBlockingStub stub = WalletGrpc.newBlockingStub(channel);
|
||||
byte[] address = Base58Check.base58ToBytes(ownerAddr);
|
||||
Protocol.Account account = Protocol.Account.newBuilder()
|
||||
.setAddress(ByteString.copyFrom(address))
|
||||
.build();
|
||||
.setAddress(ByteString.copyFrom(address)).build();
|
||||
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
|
||||
long bandwidth = Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())
|
||||
+ Math.max(0L, res.getNetLimit() - res.getNetUsed());
|
||||
long energy = Math.max(0L, res.getEnergyLimit() - res.getEnergyUsed());
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
|
||||
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
|
||||
return energyAndBandwidthVo;
|
||||
EnergyAndBandwidthVo result = new EnergyAndBandwidthVo();
|
||||
result.setBandwidth(BigDecimal.valueOf(bandwidth));
|
||||
result.setEnergy(BigDecimal.valueOf(energy));
|
||||
return result;
|
||||
} finally {
|
||||
channel.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String unDelegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.undelegateResource(fromAddress, rechangeAmount, resourceCode, toAddress);
|
||||
@@ -254,13 +251,13 @@ public class TronProServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String delegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.delegateResourceV2(fromAddress, rechangeAmount, resourceCode, toAddress, true, 86400);
|
||||
@@ -268,17 +265,18 @@ public class TronProServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
}
|
||||
|
||||
@Override
|
||||
public long defaultEstimateBandwidth() {
|
||||
return 365;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("TRON-PRO-API-KEY", "your_api_key");
|
||||
headers.set("TRON-PRO-API-KEY", tronscanApiKey());
|
||||
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<Void> entity = new HttpEntity<>(headers);
|
||||
@@ -309,16 +307,17 @@ public class TronProServiceImpl implements ITronService {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.unfreezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
TronServiceSupport.toSun(balance, "balance"),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
@@ -334,6 +333,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
}
|
||||
return bigDecimal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
@@ -368,6 +368,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
@@ -402,6 +403,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.TransactionExtention tx = null;
|
||||
@@ -411,7 +413,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -421,14 +423,14 @@ public class TronProServiceImpl implements ITronService {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.freezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
TronServiceSupport.toSun(balance, "balance"),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -458,7 +460,6 @@ public class TronProServiceImpl implements ITronService {
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
System.out.println(divide);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@@ -556,10 +557,8 @@ public class TronProServiceImpl implements ITronService {
|
||||
@Override
|
||||
public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
BigInteger amountInSun = BigInteger.valueOf(
|
||||
TronServiceSupport.toSun(amount, "amount"));
|
||||
Function function = new Function(
|
||||
"approve",
|
||||
Arrays.asList(
|
||||
@@ -592,8 +591,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
BigInteger allowance = token.allowance(ownerAddress, spenderAddress);
|
||||
|
||||
// 如果是USDT等6位小数代币
|
||||
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
|
||||
return new BigDecimal(allowanceInToken);
|
||||
return new BigDecimal(allowance).movePointLeft(6);
|
||||
} catch (Exception e) {
|
||||
log.error("TRON operation failed", e);
|
||||
}
|
||||
@@ -604,10 +602,8 @@ public class TronProServiceImpl implements ITronService {
|
||||
public Boolean usdtTransferFrom(ApiWrapper api, String sender, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
// 转换金额为 USDT 最小单位 (6位小数)
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
BigInteger amountInSun = BigInteger.valueOf(
|
||||
TronServiceSupport.toSun(amount, "amount"));
|
||||
// 构建 transferFrom 函数
|
||||
Function function = new Function(
|
||||
"transferFrom",
|
||||
@@ -620,9 +616,6 @@ public class TronProServiceImpl implements ITronService {
|
||||
);
|
||||
|
||||
|
||||
String encodedFunction = FunctionEncoder.encode(function);
|
||||
System.out.println("编码后的函数: " + encodedFunction);
|
||||
|
||||
// 触发智能合约调用
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址
|
||||
@@ -632,8 +625,8 @@ public class TronProServiceImpl implements ITronService {
|
||||
// 签名交易
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
// 广播交易
|
||||
String ret = api.broadcastTransaction(signedTxn);
|
||||
log.info(ret);
|
||||
String ret = TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTxn));
|
||||
log.info("USDT transferFrom broadcast successfully, transactionHash={}", ret);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("transferFrom 异常: " + e.getMessage(), e);
|
||||
@@ -731,19 +724,17 @@ public class TronProServiceImpl implements ITronService {
|
||||
@Override
|
||||
public long estimateEnergy(ApiWrapper api, String owner, String toAddress, BigDecimal amount) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Function function = new Function(
|
||||
"transfer(address,uint256)",
|
||||
"transfer",
|
||||
Arrays.asList(
|
||||
new Address(toAddress), // 接收地址
|
||||
new Uint256(rechangeAmount) // 转账金额
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
String callData = FunctionEncoder.encode(function);
|
||||
|
||||
Response.EstimateEnergyMessage estimate = api.estimateEnergy(
|
||||
owner, callData, callData, 0, 0, null
|
||||
owner, contractAddress(), function
|
||||
);
|
||||
return estimate.getEnergyRequired();
|
||||
}
|
||||
@@ -757,7 +748,7 @@ public class TronProServiceImpl implements ITronService {
|
||||
public long estimateBandwidth(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
@@ -826,13 +817,4 @@ public class TronProServiceImpl implements ITronService {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ITronService tronService = new TronProServiceImpl();
|
||||
tronService.energyAndBandwidth("TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW");
|
||||
ApiWrapper api = tronService.buildApiWrapper("34d200bcf5693a7ffc000edbb85fe0a7f84e7c87d894ef8638f516c07994a989");
|
||||
BigDecimal balance = tronService.getUsdtBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW");
|
||||
System.out.println(balance);
|
||||
balance = tronService.getTRxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW");
|
||||
System.out.println(balance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** TRON 服务实现共用的金额和广播结果校验。 */
|
||||
final class TronServiceSupport {
|
||||
private static final BigDecimal SUN_FACTOR = new BigDecimal("1000000");
|
||||
|
||||
private TronServiceSupport() { }
|
||||
|
||||
static long toSun(BigDecimal amount, String fieldName) {
|
||||
if (amount == null || amount.signum() <= 0) {
|
||||
throw new IllegalArgumentException(fieldName + " 必须大于 0");
|
||||
}
|
||||
try {
|
||||
return amount.multiply(SUN_FACTOR).longValueExact();
|
||||
} catch (ArithmeticException e) {
|
||||
throw new IllegalArgumentException(fieldName + " 最多支持 6 位小数且不能超出范围", e);
|
||||
}
|
||||
}
|
||||
|
||||
static String requireTransactionHash(String transactionHash) {
|
||||
if (transactionHash == null || transactionHash.trim().isEmpty()
|
||||
|| transactionHash.startsWith("error")) {
|
||||
throw new IllegalStateException("TRON 交易广播失败");
|
||||
}
|
||||
return transactionHash;
|
||||
}
|
||||
|
||||
static String requiredEnvironment(String name) {
|
||||
String value = System.getenv(name);
|
||||
if (value == null || value.trim().isEmpty()) {
|
||||
throw new IllegalStateException("缺少环境变量 " + name);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
+39
-66
@@ -9,7 +9,8 @@ import com.ruoyi.system.domain.vo.TronAccountResp;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.ManagedChannelBuilder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
@@ -54,10 +55,10 @@ import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@ConditionalOnProperty(prefix = "tron.env", name = "type", havingValue = "shasta")
|
||||
@Service
|
||||
public class TronShastaServiceImpl implements ITronService {
|
||||
private static final Logger log = LoggerFactory.getLogger(TronShastaServiceImpl.class);
|
||||
// 能量和带宽限制
|
||||
public static final long FEE_LIMIT = 10_000_000L; // 10 TRX
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
@@ -207,15 +208,11 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
//转账
|
||||
transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit);
|
||||
} else {
|
||||
return "error_error";
|
||||
throw new IllegalStateException("USDT 余额不足");
|
||||
}
|
||||
if (transfer == null || transfer.equals("")) {
|
||||
return "error_error";
|
||||
}
|
||||
return transfer;
|
||||
return TronServiceSupport.requireTransactionHash(transfer);
|
||||
} catch (Exception ex) {
|
||||
String message = ex.getMessage();
|
||||
return "error_" + message;
|
||||
throw new IllegalStateException("USDT 转账失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,7 +220,7 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
public String trxTrans(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
@@ -232,8 +229,7 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
long byteSize = api.estimateBandwidth(signTransaction);
|
||||
// long byteSize = api.estimateEnergy(signTransaction);
|
||||
// 广播交易
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
} catch (Exception e) {
|
||||
log.error("TRX transfer failed", e);
|
||||
}
|
||||
@@ -265,25 +261,27 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
.forAddress(this.grpcUrl(), this.grpcPort())
|
||||
.usePlaintext()
|
||||
.build();
|
||||
WalletGrpc.WalletBlockingStub stub =
|
||||
WalletGrpc.newBlockingStub(channel);
|
||||
try {
|
||||
WalletGrpc.WalletBlockingStub stub = WalletGrpc.newBlockingStub(channel);
|
||||
byte[] address = Base58Check.base58ToBytes(ownerAddr);
|
||||
Protocol.Account account = Protocol.Account.newBuilder()
|
||||
.setAddress(ByteString.copyFrom(address))
|
||||
.build();
|
||||
.setAddress(ByteString.copyFrom(address)).build();
|
||||
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
|
||||
long bandwidth = Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())
|
||||
+ Math.max(0L, res.getNetLimit() - res.getNetUsed());
|
||||
long energy = Math.max(0L, res.getEnergyLimit() - res.getEnergyUsed());
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
|
||||
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
|
||||
return energyAndBandwidthVo;
|
||||
EnergyAndBandwidthVo result = new EnergyAndBandwidthVo();
|
||||
result.setBandwidth(BigDecimal.valueOf(bandwidth));
|
||||
result.setEnergy(BigDecimal.valueOf(energy));
|
||||
return result;
|
||||
} finally {
|
||||
channel.shutdown();
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String delegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400);
|
||||
@@ -291,13 +289,12 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
}
|
||||
@Override
|
||||
public String unDelegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress);
|
||||
@@ -305,13 +302,12 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
return TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signTransaction));
|
||||
}
|
||||
@Override
|
||||
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("TRON-PRO-API-KEY", "your_api_key");
|
||||
if (!tronscanApiKey().isEmpty()) headers.set("TRON-PRO-API-KEY", tronscanApiKey());
|
||||
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<Void> entity = new HttpEntity<>(headers);
|
||||
@@ -345,14 +341,14 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.unfreezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
TronServiceSupport.toSun(balance, "balance"),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -365,7 +361,7 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -375,14 +371,14 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.freezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
TronServiceSupport.toSun(balance, "balance"),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTx));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -412,7 +408,6 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
System.out.println(divide);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@@ -510,10 +505,8 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
@Override
|
||||
public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
BigInteger amountInSun = BigInteger.valueOf(
|
||||
TronServiceSupport.toSun(amount, "amount"));
|
||||
Function function = new Function(
|
||||
"approve",
|
||||
Arrays.asList(
|
||||
@@ -546,8 +539,7 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
BigInteger allowance = token.allowance(ownerAddress, spenderAddress);
|
||||
|
||||
// 如果是USDT等6位小数代币
|
||||
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
|
||||
return new BigDecimal(allowanceInToken);
|
||||
return new BigDecimal(allowance).movePointLeft(6);
|
||||
} catch (Exception e) {
|
||||
log.error("TRON operation failed", e);
|
||||
}
|
||||
@@ -558,10 +550,8 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
public Boolean usdtTransferFrom(ApiWrapper api, String sender, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
// 转换金额为 USDT 最小单位 (6位小数)
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
BigInteger amountInSun = BigInteger.valueOf(
|
||||
TronServiceSupport.toSun(amount, "amount"));
|
||||
// 构建 transferFrom 函数
|
||||
Function function = new Function(
|
||||
"transferFrom",
|
||||
@@ -574,9 +564,6 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
);
|
||||
|
||||
|
||||
String encodedFunction = FunctionEncoder.encode(function);
|
||||
System.out.println("编码后的函数: " + encodedFunction);
|
||||
|
||||
// 触发智能合约调用
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址
|
||||
@@ -586,8 +573,8 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
// 签名交易
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
// 广播交易
|
||||
String ret = api.broadcastTransaction(signedTxn);
|
||||
log.info(ret);
|
||||
String ret = TronServiceSupport.requireTransactionHash(api.broadcastTransaction(signedTxn));
|
||||
log.info("USDT transferFrom broadcast successfully, transactionHash={}", ret);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("transferFrom 异常: " + e.getMessage(), e);
|
||||
@@ -733,19 +720,17 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
@Override
|
||||
public long estimateEnergy(ApiWrapper api, String owner, String toAddress, BigDecimal amount) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
Function function = new Function(
|
||||
"transfer(address,uint256)",
|
||||
"transfer",
|
||||
Arrays.asList(
|
||||
new Address(toAddress), // 接收地址
|
||||
new Uint256(rechangeAmount) // 转账金额
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
String callData = FunctionEncoder.encode(function);
|
||||
|
||||
Response.EstimateEnergyMessage estimate = api.estimateEnergy(
|
||||
owner, callData, callData, 0, 0, null
|
||||
owner, contractAddress(), function
|
||||
);
|
||||
return estimate.getEnergyRequired();
|
||||
}
|
||||
@@ -759,7 +744,7 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
public long estimateBandwidth(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue();
|
||||
long rechangeAmount = TronServiceSupport.toSun(amount, "amount");
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
@@ -828,16 +813,4 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ITronService tronService = new TronShastaServiceImpl();
|
||||
tronService.energyAndBandwidth("TULphDUxnr4VBrKJr4C6YVetses1PSx8B4");
|
||||
ApiWrapper api = tronService.buildApiWrapper("7a1b41106df333ec8eb53fed529a957b57478a919d39b3d961a02753a95de506");
|
||||
BigDecimal balance = tronService.getUsdtBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4");
|
||||
System.out.println(balance);
|
||||
balance = tronService.getTRxBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4");
|
||||
System.out.println(balance);
|
||||
tronService.trxTrans(api,"TULphDUxnr4VBrKJr4C6YVetses1PSx8B4","TXTJKCikqtLZHK7moDdmxdaTNWbjdCM1H9",new BigDecimal(200));
|
||||
// TronAccount tronAccount = tronService.createTronWallet(2);
|
||||
// System.out.println(JSONObject.toJSONString(tronAccount));
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.ruoyi.system.domain.UsdtAggregationTask;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskItem;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
|
||||
import com.ruoyi.system.domain.WalletAddressPlus;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import com.ruoyi.system.service.IUsdtAggregationTaskItemService;
|
||||
import com.ruoyi.system.service.IUsdtAggregationTaskService;
|
||||
import com.ruoyi.system.service.IWalletAddressService;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import java.util.List;
|
||||
|
||||
/** 后台逐地址执行归集任务;每个明细独立失败并继续后续地址。 */
|
||||
@Component
|
||||
@EnableScheduling
|
||||
public class UsdtAggregationExecutor {
|
||||
@Autowired private IUsdtAggregationTaskService taskService;
|
||||
@Autowired private IUsdtAggregationTaskItemService itemService;
|
||||
@Autowired private IWalletAddressService walletService;
|
||||
@Autowired private ITronService tronService;
|
||||
|
||||
@Scheduled(fixedDelay = 30000L)
|
||||
public void executePending() {
|
||||
List<UsdtAggregationTaskPlus> tasks = taskService.getListByStatusAndLtExeTime(1, new java.util.Date(System.currentTimeMillis() + 1));
|
||||
for (UsdtAggregationTaskPlus task : tasks) executeTask(task);
|
||||
}
|
||||
|
||||
private void executeTask(UsdtAggregationTaskPlus task) {
|
||||
List<UsdtAggregationTaskItemPlus> items = itemService.getListByStatusAndParentId(0, task.getId());
|
||||
boolean failed = false;
|
||||
for (UsdtAggregationTaskItemPlus item : items) {
|
||||
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
|
||||
String tx = null;
|
||||
Exception last = null;
|
||||
for (int attempt = 0; attempt < 4 && tx == null; attempt++) {
|
||||
org.tron.trident.core.ApiWrapper api = null;
|
||||
try { api = tronService.buildApiWrapper(); tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString()); }
|
||||
catch (Exception ex) { last = ex; }
|
||||
finally { if (api != null) api.close(); }
|
||||
}
|
||||
if (tx == null || tx.trim().isEmpty()) { fail(item, "重试耗尽:" + (last == null ? "交易失败" : last.getMessage())); failed = true; }
|
||||
else { item.setStatus(1L); item.setRemark("交易哈希:" + tx); itemService.updateById(item); }
|
||||
}
|
||||
task.setStatus(failed ? 3 : 2); taskService.updateById(task);
|
||||
}
|
||||
private void fail(UsdtAggregationTaskItemPlus item, String reason) { item.setStatus(2L); item.setRemark(reason); itemService.updateById(item); }
|
||||
}
|
||||
+3
-12
@@ -8,16 +8,15 @@ import com.ruoyi.common.select.SelectItem;
|
||||
import com.ruoyi.common.utils.DateUtils;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.system.domain.*;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTask;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
|
||||
import com.ruoyi.system.mapper.UsdtAggregationTaskMapper;
|
||||
import com.ruoyi.system.service.*;
|
||||
import com.ruoyi.system.service.IUsdtAggregationTaskService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
@@ -31,15 +30,7 @@ public class UsdtAggregationTaskServiceImpl extends ServiceImpl<UsdtAggregationT
|
||||
@Autowired
|
||||
private UsdtAggregationTaskMapper usdtAggregationTaskMapper;
|
||||
@Autowired
|
||||
private ITronService tronService;
|
||||
@Autowired
|
||||
private IUsdtAggregationTaskItemService usdtAggregationTaskItemService;
|
||||
@Autowired
|
||||
private IAppsService appsService;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
@Autowired
|
||||
private IWalletAddressService walletAddressService;
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskPlus> getByIds(List<Long> ids, boolean isUser, SFunction<UsdtAggregationTaskPlus, ?>... columns) {
|
||||
|
||||
+3
-1
@@ -13,6 +13,7 @@ import com.ruoyi.system.domain.WalletAddressPlus;
|
||||
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
|
||||
import com.ruoyi.system.mapper.WalletAddressMapper;
|
||||
import com.ruoyi.system.service.ITronService;
|
||||
import com.ruoyi.system.service.TronServiceProvider;
|
||||
import com.ruoyi.system.service.IWalletAddressService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
@@ -35,7 +36,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
@Autowired
|
||||
private ITronService tronService;
|
||||
private TronServiceProvider tronServiceProvider;
|
||||
@Override
|
||||
public List<WalletAddressPlus> getByIds(List<Long> ids, boolean isUser, SFunction<WalletAddressPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>()
|
||||
@@ -80,6 +81,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
|
||||
@Override
|
||||
public boolean updateTronInfo(WalletAddressPlus walletAddressPlus) {
|
||||
ITronService tronService = tronServiceProvider.getCurrentService();
|
||||
ApiWrapper api = tronService.buildApiWrapper();
|
||||
BigDecimal amout = tronService.getUsdtBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setUsdtBalance(amout);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** TRON 金额最小单位和广播结果校验测试。 */
|
||||
public class TronServiceSupportTest {
|
||||
@Test
|
||||
public void shouldConvertSixDecimalAmountExactly() {
|
||||
Assert.assertEquals(1234567L,
|
||||
TronServiceSupport.toSun(new BigDecimal("1.234567"), "amount"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void shouldRejectAmountWithMoreThanSixDecimals() {
|
||||
TronServiceSupport.toSun(new BigDecimal("1.0000001"), "amount");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void shouldRejectNonPositiveAmount() {
|
||||
TronServiceSupport.toSun(BigDecimal.ZERO, "amount");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void shouldRejectErrorTextAsTransactionHash() {
|
||||
TronServiceSupport.requireTransactionHash("error_insufficient balance");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnValidTransactionHash() {
|
||||
Assert.assertEquals("abc123", TronServiceSupport.requireTransactionHash("abc123"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user