package com.ruoyi.system.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.ruoyi.common.exception.CustomException; import com.ruoyi.system.domain.*; import com.ruoyi.system.mapper.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; import org.tron.trident.core.ApiWrapper; import org.tron.trident.proto.Response; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.UUID; /** 代付广播、链上确认和最终账务结算。 */ @Service public class PayoutProcessingService { /** 仅用于广播期间的并发占位,避免同一订单重复提交链上交易。 */ public static final int EXECUTING = 6; @Autowired private UsdtPayoutOrderMapper payoutMapper; @Autowired private UsdtConfigMapper configMapper; @Autowired private AppsMapper appsMapper; @Autowired private AppsBalanceLedgerMapper ledgerMapper; @Autowired private WalletSigningService signingService; @Autowired private TronServiceProvider tronProvider; @Autowired private TransactionTemplate transactionTemplate; /** 配置密码仅用于本次内存解锁,广播成功后订单进入待链上确认状态。 */ public String execute(Long id, String password) { if (payoutMapper.claimForExecution(id, PayoutOrderService.PENDING_EXECUTE, PayoutOrderService.EXECUTE_FAILED, EXECUTING) != 1) { throw new CustomException("仅待执行或执行失败的订单可以广播,请勿重复操作"); } try { UsdtPayoutOrder order = payoutMapper.selectById(id); UsdtConfigPlus config = config(); WalletAddressPlus mainWallet = new WalletAddressPlus(); mainWallet.setToken(config.getTokenAddress()); mainWallet.setTokenIndex("0"); String hash = signingService.execute(mainWallet, password, (tron, api, wallet) -> "USDT".equals(order.getCurrency()) ? tron.usdtTransWithBroadcastRetry(api, wallet.getToken(), order.getToAddress(), order.getAmount(), 3) : tron.trxTrans(api, wallet.getToken(), order.getToAddress(), order.getAmount())); transactionTemplate.execute(status -> { markBroadcasted(id, hash); return null; }); return hash; } catch (Exception exception) { transactionTemplate.execute(status -> { markFailed(id, safe(exception)); return null; }); throw exception instanceof CustomException ? (CustomException) exception : new CustomException("代付广播失败"); } } @Transactional(rollbackFor=Exception.class) public void markBroadcasted(Long id,String hash){UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(EXECUTING).equals(o.getStatus()))throw new CustomException("代付订单状态已变化");o.setStatus(PayoutOrderService.BROADCASTED);o.setBlockTransactionId(hash);o.setExecuteCount(n(o.getExecuteCount())+1);o.setExecutedAt(new Date());o.setExecuteError(null);o.setUpdatedAt(new Date());payoutMapper.updateById(o);} @Transactional(rollbackFor=Exception.class) public void markFailed(Long id,String error){UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(EXECUTING).equals(o.getStatus()))return;o.setStatus(PayoutOrderService.EXECUTE_FAILED);o.setExecuteCount(n(o.getExecuteCount())+1);o.setExecuteError(error);o.setUpdatedAt(new Date());payoutMapper.updateById(o);} /** 查询已广播交易,只有链上SUCCESS后才完成账务结算。 */ public void confirmPending(){List list=payoutMapper.selectList(new LambdaQueryWrapper().eq(UsdtPayoutOrder::getStatus,PayoutOrderService.BROADCASTED).isNotNull(UsdtPayoutOrder::getBlockTransactionId).isNull(UsdtPayoutOrder::getDeletedAt).last("limit 50"));if(list.isEmpty())return;ITronService tron=tronProvider.getCurrentService();ApiWrapper api=tron.buildApiWrapper();for(UsdtPayoutOrder o:list){try{Response.TransactionInfo info=api.getTransactionInfoById(o.getBlockTransactionId());if(info!=null&&!info.getId().isEmpty()){if(info.getResultValue()==0)settle(o.getId());else markChainFailed(o.getId(),"链上交易执行失败,resultValue="+info.getResultValue());}}catch(Exception ignored){}}} public void markChainFailed(Long id,String error){transactionTemplate.execute(status->{UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o!=null&&Integer.valueOf(PayoutOrderService.BROADCASTED).equals(o.getStatus())){o.setStatus(PayoutOrderService.EXECUTE_FAILED);o.setExecuteError(error);o.setUpdatedAt(new Date());payoutMapper.updateById(o);}return null;});} @Transactional(rollbackFor=Exception.class) public void settle(Long id){transactionTemplate.execute(status->{settleInternal(id);return null;});} private void settleInternal(Long id){UsdtPayoutOrder probe=payoutMapper.selectById(id);if(probe==null)return;Apps app=appsMapper.selectAppsByIdForUpdate(probe.getAppId());UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(PayoutOrderService.BROADCASTED).equals(o.getStatus()))return;Date now=new Date();BigDecimal ub=z(app.getUsdtBalance()),tb=z(app.getTrxBalance()),uf=z(app.getUsdtFrozenBalance()),tf=z(app.getTrxFrozenBalance());BigDecimal principalFrozenBefore="USDT".equals(o.getCurrency())?uf:tf;BigDecimal principalFrozenAfter=principalFrozenBefore.subtract(o.getAmount());if("USDT".equals(o.getCurrency()))uf=principalFrozenAfter;else tf=principalFrozenAfter;BigDecimal feeFrozenBefore=tf;BigDecimal feeFrozenAfter=feeFrozenBefore.subtract(o.getFeeAmount());tf=feeFrozenAfter;if(uf.signum()<0||tf.signum()<0)throw new CustomException("代付冻结余额异常");if(appsMapper.updatePayoutBalances(app.getId(),ub,tb,uf,tf,now)!=1)throw new CustomException("代付结算余额更新失败");post(o,"PAYOUT_SUCCESS",o.getCurrency(),o.getAmount(),"PAYOUT_PRINCIPAL:"+o.getId(),"USDT".equals(o.getCurrency())?ub:tb,principalFrozenBefore,principalFrozenAfter,now);if(o.getFeeAmount().signum()>0)post(o,"PAYOUT_FEE","TRX",o.getFeeAmount(),"PAYOUT_FEE:"+o.getId(),tb,feeFrozenBefore,feeFrozenAfter,now);o.setStatus(PayoutOrderService.COMPLETED);o.setConfirmedAt(now);o.setUpdatedAt(now);payoutMapper.updateById(o);} private void post(UsdtPayoutOrder o,String type,String currency,BigDecimal amount,String key,BigDecimal available,BigDecimal frozenBefore,BigDecimal frozenAfter,Date now){AppsBalanceLedger l=new AppsBalanceLedger();l.setTradeNo("PL"+UUID.randomUUID().toString().replace("-","").substring(0,24));l.setIdempotencyKey(key);l.setAppId(o.getAppId());l.setUserId(o.getUserId());l.setCurrency(currency);l.setBalanceType(2);l.setBusinessType(type);l.setDirection(2);l.setAmount(amount);l.setBalanceBefore(frozenBefore);l.setBalanceAfter(frozenAfter);l.setAvailableBefore(available);l.setAvailableAfter(available);l.setFrozenBefore(frozenBefore);l.setFrozenAfter(frozenAfter);l.setPayoutOrderId(o.getId());l.setMerchantOrderId(o.getOrderId());l.setTransactionId(o.getBlockTransactionId());l.setRemark("应用代付链上确认");l.setCreatedAt(now);ledgerMapper.insertSystemLedgerIgnoreDuplicate(l);} private UsdtConfigPlus config(){UsdtConfigPlus c=configMapper.selectOne(new LambdaQueryWrapper().orderByAsc(UsdtConfigPlus::getId).last("limit 1"));if(c==null||c.getTokenAddress()==null)throw new CustomException("主钱包配置不存在");return c;} private int n(Integer v){return v==null?0:v;}private BigDecimal z(BigDecimal v){return v==null?BigDecimal.ZERO:v;}private String safe(Exception e){String s=e.getMessage();return s==null?e.getClass().getSimpleName():s.substring(0,Math.min(1000,s.length()));} }