diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index d194e38..310b471 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -133,6 +133,10 @@ payment: apps-private-key-encryption-key: ${APP_PRIVATE_KEY_ENCRYPTION_KEY:} # 1 USDT 对应的业务货币金额;订单实际支付 USDT = amount / 此汇率,向下保留 2 位。 usdt-exchange-rate: ${USDT_EXCHANGE_RATE:1} + +# 钱包链上操作资源预算配置。 +tron: + operation-resource-redundancy-percent: ${TRON_OPERATION_RESOURCE_REDUNDANCY_PERCENT:20} # MyBatis配置 mybatis: diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java index 651a694..55038be 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java @@ -17,6 +17,7 @@ import com.ruoyi.system.service.IWalletAddressService; import com.ruoyi.system.service.IUsdtProxyToOtherService; import com.ruoyi.system.service.IUsdtOtherToProxyService; import com.ruoyi.system.service.WalletSigningService; +import com.ruoyi.system.service.WalletOperationEstimateService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; @@ -42,6 +43,8 @@ public class WalletAddressController extends BaseController { @Autowired private WalletSigningService walletSigningService; @Autowired + private WalletOperationEstimateService walletOperationEstimateService; + @Autowired private IUsdtProxyToOtherService usdtProxyToOtherService; @Autowired private IUsdtOtherToProxyService usdtOtherToProxyService; @@ -100,6 +103,16 @@ public class WalletAddressController extends BaseController { return AjaxResult.success(result); } + /** 计算操作所需能量、带宽、安全冗余及预计燃烧的 TRX。 */ + @PreAuthorize("@ss.hasPermi('system:address:query') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/{type}/estimate") + public AjaxResult estimate(@PathVariable("type") String type, + @RequestBody WalletOperationRequest request) { + WalletAddressPlus wallet = requireWallet(request); + validateOperation(type, request); + return AjaxResult.success(walletOperationEstimateService.estimate(type, wallet, request)); + } + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") @PostMapping("/operations/transfer-trx") public AjaxResult transferTrx(@RequestBody WalletOperationRequest request) { @@ -107,7 +120,7 @@ public class WalletAddressController extends BaseController { validateAmount(request); validateTarget(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("trx", wallet, request, (tron, api, current) -> tron.trxTrans(api, current.getToken(), request.getToAddress().trim(), request.getAmount())); } @@ -118,7 +131,7 @@ public class WalletAddressController extends BaseController { validateAmount(request); validateTarget(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("usdt", wallet, request, (tron, api, current) -> tron.usdtTrans(api, current.getToken(), request.getToAddress().trim(), request.getAmount().toPlainString())); } @@ -130,7 +143,7 @@ public class WalletAddressController extends BaseController { validateAmount(request); validateResource(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("stake", wallet, request, (tron, api, current) -> tron.stakeTrxBalance(api, current.getToken(), request.getAmount(), request.getResourceCode())); } @@ -141,7 +154,7 @@ public class WalletAddressController extends BaseController { validateAmount(request); validateResource(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("unstake", wallet, request, (tron, api, current) -> tron.unstakeTrxBalance(api, current.getToken(), request.getAmount(), request.getResourceCode())); } @@ -153,7 +166,7 @@ public class WalletAddressController extends BaseController { validateTarget(request); validateResource(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("delegate", wallet, request, (tron, api, current) -> tron.delegateResourceV2(api, current.getToken(), request.getToAddress().trim(), request.getAmount(), request.getResourceCode())); } @@ -166,7 +179,7 @@ public class WalletAddressController extends BaseController { validateTarget(request); validateResource(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("undelegate", wallet, request, (tron, api, current) -> tron.unDelegateResourceV2(api, current.getToken(), request.getToAddress().trim(), request.getAmount(), request.getResourceCode())); } @@ -176,13 +189,17 @@ public class WalletAddressController extends BaseController { public AjaxResult cancelUnstake(@RequestBody WalletOperationRequest request) { final WalletAddressPlus wallet = requireWallet(request); if (isPreview(request)) return previewSuccess(); - return signedResult(wallet, request, (tron, api, current) -> + return signedResult("cancel-unstake", wallet, request, (tron, api, current) -> tron.cancleUnstakeTrxBalance(api, current.getToken())); } - private AjaxResult signedResult(WalletAddressPlus wallet, WalletOperationRequest request, + private AjaxResult signedResult(String operationType, WalletAddressPlus wallet, + WalletOperationRequest request, WalletSigningService.SignedOperation operation) { try { + if (Boolean.TRUE.equals(request.getResourceOnly())) { + walletOperationEstimateService.requireNoBurn(operationType, wallet, request); + } Object result = walletSigningService.execute(wallet, request.getConfigurationPassword(), operation); return AjaxResult.success(result); } finally { @@ -224,6 +241,22 @@ public class WalletAddressController extends BaseController { } } + private void validateOperation(String type, WalletOperationRequest request) { + if ("trx".equals(type) || "usdt".equals(type)) { + validateAmount(request); + validateTarget(request); + } else if ("stake".equals(type) || "unstake".equals(type)) { + validateAmount(request); + validateResource(request); + } else if ("delegate".equals(type) || "undelegate".equals(type)) { + validateAmount(request); + validateTarget(request); + validateResource(request); + } else if (!"cancel-unstake".equals(type)) { + throw new com.ruoyi.common.exception.CustomException("不支持的钱包操作"); + } + } + private boolean isPreview(WalletOperationRequest request) { return !Boolean.TRUE.equals(request.getBroadcast()); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java index 589cd58..af6d594 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java @@ -10,6 +10,8 @@ public class WalletOperationRequest { private BigDecimal amount; private Integer resourceCode; private Boolean broadcast; + /** 为 true 时资源不足立即拒绝,禁止通过燃烧 TRX 补足资源。 */ + private Boolean resourceOnly; /** 配置密码仅用于本次请求解锁助记词,禁止持久化或输出日志。 */ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private String configurationPassword; @@ -24,6 +26,8 @@ public class WalletOperationRequest { public void setResourceCode(Integer resourceCode) { this.resourceCode = resourceCode; } public Boolean getBroadcast() { return broadcast; } public void setBroadcast(Boolean broadcast) { this.broadcast = broadcast; } + public Boolean getResourceOnly() { return resourceOnly; } + public void setResourceOnly(Boolean resourceOnly) { this.resourceOnly = resourceOnly; } public String getConfigurationPassword() { return configurationPassword; } public void setConfigurationPassword(String configurationPassword) { this.configurationPassword = configurationPassword; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletResourceEstimateVo.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletResourceEstimateVo.java new file mode 100644 index 0000000..ddf97c0 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletResourceEstimateVo.java @@ -0,0 +1,50 @@ +package com.ruoyi.system.domain.vo; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** 钱包链上操作资源估算结果。 */ +public class WalletResourceEstimateVo implements Serializable { + private static final long serialVersionUID = 1L; + + private long estimatedEnergy; + private long estimatedBandwidth; + private long safeEnergy; + private long safeBandwidth; + private long availableEnergy; + private long availableBandwidth; + private long energyGap; + private long bandwidthGap; + private int redundancyPercent; + private long energyFeeSun; + private long bandwidthFeeSun; + private BigDecimal estimatedBurnTrx; + private boolean burnRequired; + + public long getEstimatedEnergy() { return estimatedEnergy; } + public void setEstimatedEnergy(long estimatedEnergy) { this.estimatedEnergy = estimatedEnergy; } + public long getEstimatedBandwidth() { return estimatedBandwidth; } + public void setEstimatedBandwidth(long estimatedBandwidth) { this.estimatedBandwidth = estimatedBandwidth; } + public long getSafeEnergy() { return safeEnergy; } + public void setSafeEnergy(long safeEnergy) { this.safeEnergy = safeEnergy; } + public long getSafeBandwidth() { return safeBandwidth; } + public void setSafeBandwidth(long safeBandwidth) { this.safeBandwidth = safeBandwidth; } + public long getAvailableEnergy() { return availableEnergy; } + public void setAvailableEnergy(long availableEnergy) { this.availableEnergy = availableEnergy; } + public long getAvailableBandwidth() { return availableBandwidth; } + public void setAvailableBandwidth(long availableBandwidth) { this.availableBandwidth = availableBandwidth; } + public long getEnergyGap() { return energyGap; } + public void setEnergyGap(long energyGap) { this.energyGap = energyGap; } + public long getBandwidthGap() { return bandwidthGap; } + public void setBandwidthGap(long bandwidthGap) { this.bandwidthGap = bandwidthGap; } + public int getRedundancyPercent() { return redundancyPercent; } + public void setRedundancyPercent(int redundancyPercent) { this.redundancyPercent = redundancyPercent; } + public long getEnergyFeeSun() { return energyFeeSun; } + public void setEnergyFeeSun(long energyFeeSun) { this.energyFeeSun = energyFeeSun; } + public long getBandwidthFeeSun() { return bandwidthFeeSun; } + public void setBandwidthFeeSun(long bandwidthFeeSun) { this.bandwidthFeeSun = bandwidthFeeSun; } + public BigDecimal getEstimatedBurnTrx() { return estimatedBurnTrx; } + public void setEstimatedBurnTrx(BigDecimal estimatedBurnTrx) { this.estimatedBurnTrx = estimatedBurnTrx; } + public boolean isBurnRequired() { return burnRequired; } + public void setBurnRequired(boolean burnRequired) { this.burnRequired = burnRequired; } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOperationEstimateService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOperationEstimateService.java new file mode 100644 index 0000000..a25a4ba --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOperationEstimateService.java @@ -0,0 +1,128 @@ +package com.ruoyi.system.service; + +import com.ruoyi.common.exception.CustomException; +import com.ruoyi.system.domain.WalletAddressPlus; +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; +import com.ruoyi.system.domain.vo.WalletOperationRequest; +import com.ruoyi.system.domain.vo.WalletResourceEstimateVo; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.tron.trident.core.ApiWrapper; +import org.tron.trident.proto.Response; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** 计算链上操作资源预算,并为免燃烧广播提供服务端强制校验。 */ +@Service +public class WalletOperationEstimateService { + private static final long DEFAULT_ENERGY_FEE_SUN = 420L; + private static final long DEFAULT_BANDWIDTH_FEE_SUN = 1000L; + private static final long CONSERVATIVE_USDT_ENERGY = 100000L; + + private final TronServiceProvider tronServiceProvider; + + @Value("${tron.operation-resource-redundancy-percent:20}") + private int redundancyPercent; + + public WalletOperationEstimateService(TronServiceProvider tronServiceProvider) { + this.tronServiceProvider = tronServiceProvider; + } + + public WalletResourceEstimateVo estimate(String operationType, WalletAddressPlus wallet, + WalletOperationRequest request) { + ITronService tron = tronServiceProvider.getCurrentService(); + ApiWrapper api = tron.buildApiWrapper(); + try { + long energy = estimateEnergy(operationType, tron, api, wallet, request); + long bandwidth = estimateBandwidth(operationType, tron, api, wallet, request); + EnergyAndBandwidthVo current = tron.energyAndBandwidth(wallet.getToken()); + long availableEnergy = current.getEnergy() == null ? 0L : Math.max(0L, current.getEnergy().longValue()); + long availableBandwidth = current.getBandwidth() == null ? 0L + : Math.max(0L, current.getBandwidth().longValue()); + int safePercent = Math.max(0, redundancyPercent); + long safeEnergy = addRedundancy(energy, safePercent); + long safeBandwidth = addRedundancy(bandwidth, safePercent); + long energyGap = Math.max(0L, safeEnergy - availableEnergy); + long bandwidthGap = Math.max(0L, safeBandwidth - availableBandwidth); + long[] fees = readResourceFees(api); + + WalletResourceEstimateVo result = new WalletResourceEstimateVo(); + result.setEstimatedEnergy(energy); + result.setEstimatedBandwidth(bandwidth); + result.setSafeEnergy(safeEnergy); + result.setSafeBandwidth(safeBandwidth); + result.setAvailableEnergy(availableEnergy); + result.setAvailableBandwidth(availableBandwidth); + result.setEnergyGap(energyGap); + result.setBandwidthGap(bandwidthGap); + result.setRedundancyPercent(safePercent); + result.setEnergyFeeSun(fees[0]); + result.setBandwidthFeeSun(fees[1]); + BigDecimal burnSun = BigDecimal.valueOf(energyGap).multiply(BigDecimal.valueOf(fees[0])) + .add(BigDecimal.valueOf(bandwidthGap).multiply(BigDecimal.valueOf(fees[1]))); + result.setEstimatedBurnTrx(burnSun.movePointLeft(6).setScale(6, RoundingMode.UP)); + result.setBurnRequired(energyGap > 0L || bandwidthGap > 0L); + return result; + } finally { + api.close(); + } + } + + public void requireNoBurn(String operationType, WalletAddressPlus wallet, + WalletOperationRequest request) { + WalletResourceEstimateVo estimate = estimate(operationType, wallet, request); + if (estimate.isBurnRequired()) { + throw new CustomException("当前资源不足:缺少能量 " + estimate.getEnergyGap() + + "、带宽 " + estimate.getBandwidthGap() + + ",免消耗TRX模式已拒绝广播"); + } + } + + private long estimateEnergy(String operationType, ITronService tron, ApiWrapper api, + WalletAddressPlus wallet, WalletOperationRequest request) { + if (!"usdt".equals(operationType)) { + return 0L; + } + try { + return Math.max(0L, tron.estimateEnergy(api, wallet.getToken(), + request.getToAddress().trim(), request.getAmount())); + } catch (RuntimeException ex) { + // 公共节点可能关闭 estimateEnergy;回退值必须足够保守,随后仍会叠加配置冗余。 + return Math.max(CONSERVATIVE_USDT_ENERGY, tron.defaultEstimateEnergy()); + } + } + + private long estimateBandwidth(String operationType, ITronService tron, ApiWrapper api, + WalletAddressPlus wallet, WalletOperationRequest request) { + if ("trx".equals(operationType)) { + long estimated = tron.estimateBandwidth(api, wallet.getToken(), + request.getToAddress().trim(), request.getAmount()); + return estimated > 0L ? estimated : tron.defaultEstimateBandwidth(); + } + return tron.defaultEstimateBandwidth(); + } + + private long addRedundancy(long value, int percent) { + return BigDecimal.valueOf(value).multiply(BigDecimal.valueOf(100L + percent)) + .divide(BigDecimal.valueOf(100L), 0, RoundingMode.UP).longValue(); + } + + private long[] readResourceFees(ApiWrapper api) { + long energyFee = DEFAULT_ENERGY_FEE_SUN; + long bandwidthFee = DEFAULT_BANDWIDTH_FEE_SUN; + try { + for (Response.ChainParameters.ChainParameter parameter + : api.getChainParameters().getChainParameterList()) { + if ("getEnergyFee".equals(parameter.getKey())) { + energyFee = parameter.getValue(); + } else if ("getTransactionFee".equals(parameter.getKey())) { + bandwidthFee = parameter.getValue(); + } + } + } catch (Exception ignored) { + // 节点暂时不可用时使用协议常见费率,仅用于提示;免燃烧判断仍基于资源缺口。 + } + return new long[]{energyFee, bandwidthFee}; + } +}