This commit is contained in:
lu7213 committed 2026-09-27 19:18:44 -04:00
1 parent 0df6716cc3
commit 009955d560
25 files changed
+415 -61

No files matched your search

@@ -88,6 +88,9 @@ spring:
max-file-size: 10MB
# 设置总上传的文件大小
max-request-size: 20MB
# 支付接口 JSON 请求体限制由 Tomcat 层控制,避免异常大请求占用内存
http:
max-request-size: 64KB
# 服务模块
devtools:
restart:
@@ -3,6 +3,8 @@ package com.ruoyi.common.core.controller;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
@@ -133,6 +135,9 @@ public class BaseController
return AjaxResult.error(message);
}
protected Long getUserId(){
return SecurityUtils.getLoginUser().getUser().getUserId();
}
/**
* 页面跳转
*/
@@ -0,0 +1,61 @@
package com.ruoyi.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.AppApiKeysPlus;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.IAppApiKeysService;
import com.ruoyi.system.service.IUsdtOrdersService;
import com.ruoyi.system.service.PaymentSignatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.net.URI;
/** 对外支付 API,统一使用 JSON 和签名校验。 */
@RestController
@RequestMapping("/api/v1/order")
public class PaymentApiController {
@Autowired private IAppApiKeysService keys;
@Autowired private IUsdtOrdersService orders;
@Autowired private StringRedisTemplate redis;
@PostMapping("/create-transaction")
public AjaxResult create(@RequestBody Map<String, Object> body) {
String signature = String.valueOf(body.get("signature"));
Long appId = parseLong(body.get("app_id"));
AppApiKeysPlus key = activeKey(appId);
if (key == null || !PaymentSignatureService.sign(body, key.getApiSecret()).equalsIgnoreCase(signature)) return AjaxResult.error("签名无效");
String orderId = String.valueOf(body.get("order_id"));
if (orderId.length() == 0 || orderId.length() > 32 || body.get("amount") == null || body.get("wallet_user_name") == null) return AjaxResult.error("缺少必要参数");
if (!validUrl(body.get("notify_url")) || (body.get("redirect_url") != null && !validUrl(body.get("redirect_url")))) return AjaxResult.error("回调地址无效");
UsdtOrdersPlus order = new UsdtOrdersPlus();
order.setTradeId(UUID.randomUUID().toString().replace("-", "")); order.setOrderId(orderId);
order.setToken(String.valueOf(body.get("payment_address")));
order.setAmount(new BigDecimal(String.valueOf(body.get("amount")))); order.setActualAmount(order.getAmount());
String lockKey = "payment:slot:" + appId + ":" + order.getToken() + ":" + order.getActualAmount().toPlainString();
if (!Boolean.TRUE.equals(redis.opsForValue().setIfAbsent(lockKey, order.getTradeId(), 30, TimeUnit.MINUTES))) return AjaxResult.error("该金额已有待支付订单");
order.setStatus(1L); order.setCallbackConfirm(2L); order.setAppId(appId); order.setUserId(key.getUserId());
order.setNotifyUrl(String.valueOf(body.get("notify_url"))); order.setRedirectUrl(body.get("redirect_url") == null ? null : String.valueOf(body.get("redirect_url")));
orders.save(order);
Map<String, Object> result = new HashMap<String, Object>(); result.put("order_id", orderId); result.put("trade_id", order.getTradeId()); result.put("payment_amount", order.getActualAmount()); result.put("payment_address", order.getToken());
return AjaxResult.success(result);
}
@PostMapping("/query")
public AjaxResult query(@RequestBody Map<String, Object> body) {
Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId); String signature = String.valueOf(body.get("signature"));
if (key == null || !PaymentSignatureService.sign(body, key.getApiSecret()).equalsIgnoreCase(signature)) return AjaxResult.error("签名无效");
UsdtOrdersPlus order = orders.getOne(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id"))));
if (order == null) return AjaxResult.error("订单不存在");
Map<String, Object> result = new HashMap<String, Object>(); result.put("order_id", order.getOrderId()); result.put("trade_id", order.getTradeId()); result.put("status", order.getStatus()); result.put("transaction_id", order.getBlockTransactionId()); return AjaxResult.success(result);
}
private AppApiKeysPlus activeKey(Long appId) { return appId == null ? null : keys.getOne(new LambdaQueryWrapper<AppApiKeysPlus>().eq(AppApiKeysPlus::getAppId, appId).eq(AppApiKeysPlus::getStatus, 1)); }
private Long parseLong(Object value) { try { return value == null ? null : Long.valueOf(String.valueOf(value)); } catch (Exception ex) { return null; } }
private boolean validUrl(Object value) { try { if (value == null) return false; URI uri = new URI(String.valueOf(value)); return ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme())) && uri.getHost() != null; } catch (Exception ex) { return false; } }
}
@@ -7,8 +7,10 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
@RequestMapping("/system/test")
public class TestPluginController {
@Autowired
@@ -17,7 +19,8 @@ public class TestPluginController {
@GetMapping(value = "/testPlugin")
public AjaxResult testPlugin() {
IPluginTest pluginTest = pluginBeanFactory.getBean("pluginDemo", "1.0.0", IPluginTest.class);
System.out.println(pluginTest.funcExec("dd"));
return AjaxResult.success(pluginTest.funcExec("dd"));
String result = pluginTest.funcExec("dd");
log.debug("plugin test completed, resultLength={}", result == null ? 0 : result.length());
return AjaxResult.success(result);
}
}
@@ -28,6 +28,18 @@ import java.util.List;
public class UsdtAggregationTaskController extends BaseController {
@Autowired
private IUsdtAggregationTaskService usdtAggregationTaskService;
/** 触发归集任务;实际明细执行由后台任务处理,避免阻塞 HTTP 请求。 */
@PreAuthorize("@ss.hasPermi('system:usdtTask:execute')")
@PostMapping("/{id}/execute")
public AjaxResult execute(@PathVariable("id") Long id) {
UsdtAggregationTask task = usdtAggregationTaskService.selectUsdtAggregationTaskById(id, false);
if (task == null) return AjaxResult.error("任务不存在");
if (task.getStatus() != null && task.getStatus() == 1) return AjaxResult.error("任务正在执行");
task.setStatus(1);
task.setExeTime(new java.util.Date());
usdtAggregationTaskService.updateUsdtAggregationTask(task, false);
return AjaxResult.success("任务已进入执行队列");
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:getByIds')")
@PostMapping("/getByIds")
@@ -8,6 +8,7 @@ import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.select.Ids;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.WalletAddress;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.service.IWalletAddressService;
@@ -16,6 +17,13 @@ import org.springframework.security.access.prepost.PreAuthorize;
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.domain.vo.WalletOperationRequest;
/**
* token管理Controller
@@ -28,6 +36,77 @@ import java.util.List;
public class WalletAddressController extends BaseController {
@Autowired
private IWalletAddressService walletAddressService;
@Autowired
private ITronService tronService;
/** 查询链上账户快照。私钥只从服务端读取,响应永远不包含 tokenKey。 */
@PreAuthorize("@ss.hasPermi('system:address:query')")
@GetMapping("/{id}/chain")
public AjaxResult chain(@PathVariable("id") Long id) {
WalletAddressPlus wallet = walletAddressService.getById(id);
if (wallet == null) {
return AjaxResult.error("钱包不存在");
}
if (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId())) {
return AjaxResult.error("无权访问该钱包");
}
if (wallet.getTokenKey() == null || wallet.getTokenKey().trim().isEmpty()) {
return AjaxResult.error("钱包未配置受控私钥");
}
ApiWrapper api = null;
try {
api = tronService.buildApiWrapper(wallet.getTokenKey());
wallet.setTrxBalance(tronService.getTRxBalance(api, wallet.getToken()));
wallet.setUsdtBalance(tronService.getUsdtBalance(api, wallet.getToken()));
com.ruoyi.system.domain.vo.EnergyAndBandwidthVo resource = tronService.energyAndBandwidth(wallet.getToken());
wallet.setEnergyNum(resource.getEnergy().max(BigDecimal.ZERO).longValue());
wallet.setBandwidthNum(resource.getBandwidth().max(BigDecimal.ZERO).longValue());
wallet.setTokenKey(null);
return AjaxResult.success(wallet);
} catch (Exception ex) {
return AjaxResult.error("链上查询失败,请稍后重试");
} finally {
if (api != null) api.close();
}
}
@PreAuthorize("@ss.hasPermi('system:address:operate')")
@PostMapping("/operate/{type}")
public AjaxResult operate(@PathVariable("type") String type, @RequestBody WalletOperationRequest request) {
if (request == null || request.getWalletId() == null) return AjaxResult.error("钱包不能为空");
WalletAddressPlus wallet = walletAddressService.getById(request.getWalletId());
if (wallet == null || (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId()))) return AjaxResult.error("无权访问该钱包");
if (wallet.getTokenKey() == null || wallet.getTokenKey().trim().isEmpty()) return AjaxResult.error("钱包未配置受控私钥");
try {
String derived = Base58Check.bytesToBase58(ECKey.fromPrivate(new BigInteger(wallet.getTokenKey().trim(), 16)).getAddress());
if (!derived.equals(wallet.getToken())) return AjaxResult.error("钱包私钥与地址不匹配");
} catch (Exception ex) { return AjaxResult.error("钱包私钥格式无效"); }
if (type == null || !type.matches("(?i)trx|usdt|stake|unstake|delegate|undelegate|cancel-unstake")) return AjaxResult.error("不支持的操作类型");
if (!"cancel-unstake".equalsIgnoreCase(type) && (request.getAmount() == null || request.getAmount().signum() <= 0)) return AjaxResult.error("金额必须大于 0");
if (("trx".equalsIgnoreCase(type) || "usdt".equalsIgnoreCase(type) || "delegate".equalsIgnoreCase(type) || "undelegate".equalsIgnoreCase(type)) && (request.getToAddress() == null || request.getToAddress().trim().isEmpty())) return AjaxResult.error("目标地址不能为空");
if (!Boolean.TRUE.equals(request.getBroadcast())) return AjaxResult.success("预演模式:已通过参数校验,未广播交易");
ApiWrapper api = null;
try {
api = tronService.buildApiWrapper(wallet.getTokenKey());
String tx;
BigDecimal amount = request.getAmount();
if ("trx".equalsIgnoreCase(type)) tx = tronService.trxTrans(api, wallet.getToken(), request.getToAddress(), amount);
else if ("usdt".equalsIgnoreCase(type)) tx = tronService.usdtTrans(api, wallet.getToken(), request.getToAddress(), amount.toPlainString());
else if ("stake".equalsIgnoreCase(type)) tx = String.valueOf(tronService.stakeTrxBalance(api, wallet.getToken(), amount, resource(request)));
else if ("unstake".equalsIgnoreCase(type)) tx = String.valueOf(tronService.unstakeTrxBalance(api, wallet.getToken(), amount, resource(request)));
else if ("delegate".equalsIgnoreCase(type)) tx = tronService.delegateResourceV2(api, wallet.getToken(), request.getToAddress(), amount, resource(request));
else if ("undelegate".equalsIgnoreCase(type)) tx = tronService.unDelegateResourceV2(api, wallet.getToken(), request.getToAddress(), amount, resource(request));
else if ("cancel-unstake".equalsIgnoreCase(type)) tx = String.valueOf(tronService.cancleUnstakeTrxBalance(api, wallet.getToken()));
else return AjaxResult.error("不支持的操作类型");
return AjaxResult.success(tx);
} catch (Exception ex) {
return AjaxResult.error("链上操作失败,请检查余额、资源和地址");
} finally { if (api != null) api.close(); }
}
private int resource(WalletOperationRequest request) {
return request.getResourceCode() == null ? 1 : request.getResourceCode();
}
@PreAuthorize("@ss.hasPermi('system:address:getByIds')" )
@PostMapping("/getByIds" )
@@ -2,6 +2,7 @@ package com.ruoyi.system.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
@@ -5,6 +5,7 @@ import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
@@ -50,10 +50,6 @@ public class UsdtAggregationTask extends BaseEntity
/** 删除时间 */
private Date deletedAt;
/** 提现总金额 */
@Excel(name = "提现总金额")
private BigDecimal totalAmount;
/** 执行时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd")
@@ -139,15 +135,6 @@ public class UsdtAggregationTask extends BaseEntity
{
return deletedAt;
}
public void setTotalAmount(BigDecimal totalAmount)
{
this.totalAmount = totalAmount;
}
public BigDecimal getTotalAmount()
{
return totalAmount;
}
public void setExeTime(Date exeTime)
{
this.exeTime = exeTime;
@@ -188,7 +175,6 @@ public class UsdtAggregationTask extends BaseEntity
.append("createdAt", getCreatedAt())
.append("updatedAt", getUpdatedAt())
.append("deletedAt", getDeletedAt())
.append("totalAmount", getTotalAmount())
.append("exeTime", getExeTime())
.append("verifyStatus", getVerifyStatus())
.append("distTokenAddress", getDistTokenAddress())
@@ -52,9 +52,6 @@ public class UsdtAggregationTaskPlus implements Serializable
private Date updatedAt;
/** 删除时间 */
private Date deletedAt;
/** 提现总金额 */
@Excel(name = "提现总金额")
private BigDecimal totalAmount;
/** 执行时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd")
@@ -146,15 +143,6 @@ public class UsdtAggregationTaskPlus implements Serializable
{
return deletedAt;
}
public void setTotalAmount(BigDecimal totalAmount)
{
this.totalAmount = totalAmount;
}
public BigDecimal getTotalAmount()
{
return totalAmount;
}
public void setExeTime(Date exeTime)
{
this.exeTime = exeTime;
@@ -195,7 +183,6 @@ public class UsdtAggregationTaskPlus implements Serializable
.append("createdAt", getCreatedAt())
.append("updatedAt", getUpdatedAt())
.append("deletedAt", getDeletedAt())
.append("totalAmount", getTotalAmount())
.append("exeTime", getExeTime())
.append("verifyStatus", getVerifyStatus())
.append("distTokenAddress", getDistTokenAddress())
@@ -3,6 +3,7 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
@@ -61,6 +62,7 @@ public class WalletAddress extends BaseEntity
private String tokenIndex;
@Excel(name = "token key")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String tokenKey;
/** usdt余额 */
@@ -3,6 +3,7 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
@@ -112,6 +113,7 @@ public class WalletAddressPlus implements Serializable
private Long votedNum;
@Excel(name = "token key")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String tokenKey;
/** 质押还剩能用的带宽 */
@@ -1,6 +1,7 @@
package com.ruoyi.system.domain.vo;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
@@ -27,6 +28,7 @@ public class TronAccountItem implements Serializable {
* 私钥(Hex)
* 示例:xxxx
*/
@JsonIgnore
private String privateKey;
private String path;
@@ -41,6 +43,7 @@ public class TronAccountItem implements Serializable {
* Base58 私钥
* 示例:xxx
*/
@JsonIgnore
private String privateKeyBase58;
public TronAccountItem() {
@@ -0,0 +1,23 @@
package com.ruoyi.system.domain.vo;
import java.math.BigDecimal;
/** 管理端钱包操作请求;私钥不允许从请求传入。 */
public class WalletOperationRequest {
private Long walletId;
private String toAddress;
private BigDecimal amount;
private Integer resourceCode;
private Boolean broadcast;
public Long getWalletId() { return walletId; }
public void setWalletId(Long walletId) { this.walletId = walletId; }
public String getToAddress() { return toAddress; }
public void setToAddress(String toAddress) { this.toAddress = toAddress; }
public BigDecimal getAmount() { return amount; }
public void setAmount(BigDecimal amount) { this.amount = amount; }
public Integer getResourceCode() { return resourceCode; }
public void setResourceCode(Integer resourceCode) { this.resourceCode = resourceCode; }
public Boolean getBroadcast() { return broadcast; }
public void setBroadcast(Boolean broadcast) { this.broadcast = broadcast; }
}
@@ -0,0 +1,27 @@
package com.ruoyi.system.service;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;
/** 支付 API 签名:按键排序拼接非空参数后追加 secret,MD5 小写。 */
public final class PaymentSignatureService {
private PaymentSignatureService() { }
public static String sign(Map<String, ?> values, String secret) {
TreeMap<String, Object> sorted = new TreeMap<String, Object>(values);
StringBuilder text = new StringBuilder();
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
if (entry.getValue() != null && !"".equals(String.valueOf(entry.getValue())) && !"signature".equals(entry.getKey())) {
if (text.length() > 0) text.append('&');
text.append(entry.getKey()).append('=').append(entry.getValue());
}
}
text.append(secret);
try {
byte[] digest = MessageDigest.getInstance("MD5").digest(text.toString().getBytes("UTF-8"));
StringBuilder result = new StringBuilder();
for (byte b : digest) result.append(String.format("%02x", b & 0xff));
return result.toString();
} catch (Exception ex) { throw new IllegalStateException("MD5 unavailable", ex); }
}
}
@@ -0,0 +1,39 @@
package com.ruoyi.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.IUsdtOrdersService;
import com.ruoyi.system.service.IAppApiKeysService;
import com.ruoyi.system.service.PaymentSignatureService;
import com.ruoyi.system.domain.AppApiKeysPlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
/** 回调只在对方响应正文严格为 ok 时确认,失败保留未确认状态并重试。 */
@Component
public class PaymentCallbackWorker {
@Autowired private IUsdtOrdersService orders;
@Autowired private IAppApiKeysService keys;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
public void dispatch() {
for (UsdtOrdersPlus order : orders.list(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getStatus, 2).eq(UsdtOrdersPlus::getCallbackConfirm, 2).lt(UsdtOrdersPlus::getCallbackNum, 10))) {
try {
if (order.getNotifyUrl() == null || order.getNotifyUrl().trim().isEmpty()) continue;
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
String body = "{\"order_id\":\"" + order.getOrderId() + "\",\"trade_id\":\"" + order.getTradeId() + "\",\"status\":" + order.getStatus() + ",\"transaction_id\":\"" + (order.getBlockTransactionId() == null ? "" : order.getBlockTransactionId()) + "\"}";
AppApiKeysPlus key = keys.getOne(new LambdaQueryWrapper<AppApiKeysPlus>().eq(AppApiKeysPlus::getAppId, order.getAppId()).eq(AppApiKeysPlus::getStatus, 1));
java.util.Map<String, Object> signatureValues = new java.util.HashMap<String, Object>(); signatureValues.put("order_id", order.getOrderId()); signatureValues.put("trade_id", order.getTradeId()); signatureValues.put("status", order.getStatus()); signatureValues.put("transaction_id", order.getBlockTransactionId());
headers.set("X-Payment-Signature", key == null ? "" : PaymentSignatureService.sign(signatureValues, key.getApiSecret()));
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(), new HttpEntity<String>(body, headers), String.class);
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
if (response.getStatusCode().is2xxSuccessful() && "ok".equalsIgnoreCase(response.getBody() == null ? "" : response.getBody().trim())) order.setCallbackConfirm(1L);
order.setUpdatedAt(new Date()); orders.updateById(order);
} catch (Exception ignored) { }
}
}
}
@@ -0,0 +1,28 @@
package com.ruoyi.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.IUsdtOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/** 支付订单生命周期任务:先处理过期订单,链上入账由独立扫描器补充。 */
@Component
public class PaymentOrderMonitor {
@Autowired private IUsdtOrdersService orders;
@Scheduled(fixedDelay = 30000L)
public void expireOrders() {
LambdaQueryWrapper<UsdtOrdersPlus> query = new LambdaQueryWrapper<UsdtOrdersPlus>()
.eq(UsdtOrdersPlus::getStatus, 1)
.isNotNull(UsdtOrdersPlus::getCreatedAt)
.lt(UsdtOrdersPlus::getCreatedAt, new Date(System.currentTimeMillis() - 30 * 60 * 1000L));
for (UsdtOrdersPlus order : orders.list(query)) {
order.setStatus(3L);
order.setUpdatedAt(new Date());
orders.updateById(order);
}
}
}
@@ -109,7 +109,9 @@ public class TronNileServiceImpl implements ITronService {
// 获取转账账户的TRX余额
BigInteger trc20Value = token.balanceOf(fromAddress);
// 获取想要转账的数额
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
// USDT uses six decimal places but is not TRX; convert the business amount directly.
BigInteger sunAmountValue = amount == null ? BigInteger.ZERO
: new BigDecimal(amount).movePointRight(6).toBigIntegerExact();
// 进行比较
if (trc20Value.compareTo(sunAmountValue) >= 0) {
// 设置最大矿工费用
@@ -145,7 +147,7 @@ public class TronNileServiceImpl implements ITronService {
String hashTx = api.broadcastTransaction(signTransaction);
return hashTx;
} catch (Exception e) {
e.printStackTrace();
log.error("TRX transfer failed", e);
}
return "";
}
@@ -182,11 +184,9 @@ public class TronNileServiceImpl implements ITronService {
.setAddress(ByteString.copyFrom(address))
.build();
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
long bandwidth =
(res.getFreeNetLimit() - res.getFreeNetUsed()) +
(res.getNetLimit() - res.getNetUsed());
long energy =
res.getEnergyLimit() - res.getEnergyUsed();
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));
@@ -513,7 +513,7 @@ public class TronNileServiceImpl implements ITronService {
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
return new BigDecimal(allowanceInToken);
} catch (Exception e) {
e.printStackTrace();
log.error("TRON operation failed", e);
}
return new BigDecimal(0);
}
@@ -0,0 +1,45 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
/** 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。 */
@Component
public class TronPaymentScanner {
@Autowired private IUsdtOrdersService orders;
@Autowired private ITronService tron;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
public void scan() {
for (UsdtOrdersPlus order : orders.list(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getStatus, 1))) {
if (order.getToken() == null || order.getActualAmount() == null) continue;
try {
String url = tron.tronscanApiUrl() + "/v1/accounts/" + order.getToken() + "/transactions/trc20?limit=200&only_confirmed=true&contract_address=" + tron.contractAddress();
JSONObject root = JSON.parseObject(http.getForObject(url, String.class)); JSONArray data = root == null ? null : root.getJSONArray("data");
if (data == null) continue;
for (int i = 0; i < data.size(); i++) {
JSONObject tx = data.getJSONObject(i);
if (!order.getToken().equals(tx.getString("to"))) continue;
BigDecimal value = new BigDecimal(tx.getString("value")).movePointLeft(6).setScale(6, RoundingMode.DOWN);
if (value.compareTo(order.getActualAmount().setScale(6, RoundingMode.DOWN)) != 0) continue;
String hash = tx.getString("transaction_id"); if (hash == null || hash.trim().isEmpty()) continue;
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0) continue;
order.setBlockTransactionId(hash); order.setStatus(2L); order.setUpdatedAt(new Date()); orders.updateById(order); break;
}
} catch (Exception ignored) { }
}
}
}
@@ -156,7 +156,8 @@ public class TronProServiceImpl implements ITronService {
// 获取转账账户的TRX余额
BigInteger trc20Value = token.balanceOf(fromAddress);
// 获取想要转账的数额
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
BigInteger sunAmountValue = amount == null ? BigInteger.ZERO
: new BigDecimal(amount).movePointRight(6).toBigIntegerExact();
// 进行比较
if (trc20Value.compareTo(sunAmountValue) >= 0) {
// 设置最大矿工费用
@@ -192,7 +193,7 @@ public class TronProServiceImpl implements ITronService {
String hashTx = api.broadcastTransaction(signTransaction);
return hashTx;
} catch (Exception e) {
e.printStackTrace();
log.error("TRX transfer failed", e);
}
return "";
}
@@ -229,11 +230,9 @@ public class TronProServiceImpl implements ITronService {
.setAddress(ByteString.copyFrom(address))
.build();
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
long bandwidth =
(res.getFreeNetLimit() - res.getFreeNetUsed()) +
(res.getNetLimit() - res.getNetUsed());
long energy =
res.getEnergyLimit() - res.getEnergyUsed();
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));
@@ -591,7 +590,7 @@ public class TronProServiceImpl implements ITronService {
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
return new BigDecimal(allowanceInToken);
} catch (Exception e) {
e.printStackTrace();
log.error("TRON operation failed", e);
}
return new BigDecimal(0);
}
@@ -192,7 +192,8 @@ public class TronShastaServiceImpl implements ITronService {
// 获取转账账户的TRX余额
BigInteger trc20Value = token.balanceOf(fromAddress);
// 获取想要转账的数额
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
BigInteger sunAmountValue = amount == null ? BigInteger.ZERO
: new BigDecimal(amount).movePointRight(6).toBigIntegerExact();
// 进行比较
if (trc20Value.compareTo(sunAmountValue) >= 0) {
// 设置最大矿工费用
@@ -228,7 +229,7 @@ public class TronShastaServiceImpl implements ITronService {
String hashTx = api.broadcastTransaction(signTransaction);
return hashTx;
} catch (Exception e) {
e.printStackTrace();
log.error("TRX transfer failed", e);
}
return "";
}
@@ -265,11 +266,9 @@ public class TronShastaServiceImpl implements ITronService {
.setAddress(ByteString.copyFrom(address))
.build();
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
long bandwidth =
(res.getFreeNetLimit() - res.getFreeNetUsed()) +
(res.getNetLimit() - res.getNetUsed());
long energy =
res.getEnergyLimit() - res.getEnergyUsed();
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));
@@ -544,7 +543,7 @@ public class TronShastaServiceImpl implements ITronService {
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
return new BigDecimal(allowanceInToken);
} catch (Exception e) {
e.printStackTrace();
log.error("TRON operation failed", e);
}
return new BigDecimal(0);
}
@@ -0,0 +1,53 @@
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());
if (wallet == null || wallet.getTokenKey() == null) { fail(item, "来源钱包不存在或未配置私钥"); failed = true; continue; }
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(wallet.getTokenKey()); 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); }
}
@@ -157,7 +157,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
@Override
public WalletAddressPlus getByTokenAndAppId(String token,Long appId, SFunction<WalletAddressPlus, ?>... columns) {
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
if(null != columns || columns.length > 0){
if(columns != null && columns.length > 0){
lambdaQueryWrapper.select(columns);
}
lambdaQueryWrapper.eq(WalletAddressPlus::getToken, token).eq(WalletAddressPlus::getAppId, appId);
@@ -167,7 +167,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
@Override
public List<WalletAddressPlus> getListByAppId(Long appId, SFunction<WalletAddressPlus, ?>... columns) {
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
if(null != columns || columns.length > 0){
if(columns != null && columns.length > 0){
lambdaQueryWrapper.select(columns);
}
lambdaQueryWrapper.eq(WalletAddressPlus::getAppId, appId);
@@ -17,7 +17,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<sql id="selectAppsVo">
select id, user_id, name, dist_token_address,description, status, created_at, updated_at, deleted_at from apps
select id, user_id, name, dist_token_address, description, status, created_at, updated_at, deleted_at from apps
</sql>
<select id="selectAppsList" parameterType="Apps" resultMap="AppsResult">
@@ -14,14 +14,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="createdAt" column="created_at" />
<result property="updatedAt" column="updated_at" />
<result property="deletedAt" column="deleted_at" />
<result property="totalAmount" column="total_amount" />
<result property="exeTime" column="exe_time" />
<result property="verifyStatus" column="verify_status" />
<result property="distTokenAddress" column="dist_token_address" />
</resultMap>
<sql id="selectUsdtAggregationTaskVo">
select id, task_name, app_id, user_id, remark, status, created_at, updated_at, deleted_at, total_amount, exe_time, verify_status, dist_token_address from usdt_aggregation_task
select id, task_name, app_id, user_id, remark, status, created_at, updated_at, deleted_at, exe_time, verify_status, dist_token_address from usdt_aggregation_task
</sql>
<select id="selectUsdtAggregationTaskList" parameterType="UsdtAggregationTask" resultMap="UsdtAggregationTaskResult">
@@ -52,7 +51,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null">created_at,</if>
<if test="updatedAt != null">updated_at,</if>
<if test="deletedAt != null">deleted_at,</if>
<if test="totalAmount != null">total_amount,</if>
<if test="exeTime != null">exe_time,</if>
<if test="verifyStatus != null">verify_status,</if>
<if test="distTokenAddress != null">dist_token_address,</if>
@@ -66,7 +64,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null">#{createdAt},</if>
<if test="updatedAt != null">#{updatedAt},</if>
<if test="deletedAt != null">#{deletedAt},</if>
<if test="totalAmount != null">#{totalAmount},</if>
<if test="exeTime != null">#{exeTime},</if>
<if test="verifyStatus != null">#{verifyStatus},</if>
<if test="distTokenAddress != null">#{distTokenAddress},</if>
@@ -84,7 +81,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null">created_at = #{createdAt},</if>
<if test="updatedAt != null">updated_at = #{updatedAt},</if>
<if test="deletedAt != null">deleted_at = #{deletedAt},</if>
<if test="totalAmount != null">total_amount = #{totalAmount},</if>
<if test="exeTime != null">exe_time = #{exeTime},</if>
<if test="verifyStatus != null">verify_status = #{verifyStatus},</if>
<if test="distTokenAddress != null">dist_token_address = #{distTokenAddress},</if>