111
This commit is contained in:
1 parent
68a2b4f68c
commit
7cd697187c
308 files changed
+30454
-75
No files matched your search
@@ -0,0 +1,258 @@
|
||||
package com.ruoyi.system.service;
|
||||
|
||||
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
|
||||
import com.ruoyi.system.domain.vo.TronAccount;
|
||||
import com.ruoyi.system.domain.vo.TronAccountItem;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.core.exceptions.IllegalException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public interface ITronService {
|
||||
Integer grpcPort();
|
||||
String grpcUrl();
|
||||
String type();
|
||||
ApiWrapper buildApiWrapper(String privateKey);
|
||||
|
||||
String contractAddress();
|
||||
|
||||
String tronscanApiUrl();
|
||||
|
||||
String tronscanApiKey();
|
||||
|
||||
String usdtTrans(ApiWrapper api,String fromAddress, String toAddress, String amount);
|
||||
|
||||
|
||||
String trxTrans(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount);
|
||||
/**
|
||||
* 不包含质押的数量
|
||||
* @param api
|
||||
* @param address
|
||||
* @return
|
||||
*/
|
||||
BigDecimal getTRxBalance(ApiWrapper api,String address);
|
||||
|
||||
BigDecimal getUsdtBalance(ApiWrapper api,String address);
|
||||
|
||||
/**
|
||||
* 所有的可用的 包括別人代理給你的值
|
||||
* @param ownerAddr
|
||||
* @return
|
||||
*/
|
||||
EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr);
|
||||
|
||||
/**
|
||||
* 別人代理給我的的能量和带宽值
|
||||
* @param ownerAddr
|
||||
* @return
|
||||
*/
|
||||
EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr);
|
||||
|
||||
/**
|
||||
* 一天后生效,一天内可以cancle
|
||||
* @param api
|
||||
* @param ownerAddr
|
||||
* @param balance
|
||||
* @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze |
|
||||
* | -------------- | ----- | ----------- | -------- | ----------- |
|
||||
* | BANDWIDTH | 0 | 带宽 | ✅ | ✅ |
|
||||
* | ENERGY | 1 | 能量 | ✅ | ✅ |
|
||||
* | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ |
|
||||
* | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ |
|
||||
* @return
|
||||
*/
|
||||
boolean unstakeTrxBalance(ApiWrapper api,String ownerAddr, BigDecimal balance, int resourceCode);
|
||||
|
||||
/**
|
||||
* 取消 unstakeTrxBalance
|
||||
* @param api
|
||||
* @param ownerAddr
|
||||
* @return
|
||||
*/
|
||||
boolean cancleUnstakeTrxBalance(ApiWrapper api,String ownerAddr);
|
||||
|
||||
/**
|
||||
* 質押trx-获取带宽或者能量
|
||||
* 调用会消耗能量或者带宽-不足是会消耗TRX-所以不能一次性质押TXT,最好要预留一个trx-1
|
||||
* @param api
|
||||
* @param ownerAddr
|
||||
* @param balance
|
||||
* @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze |
|
||||
* | -------------- | ----- | ----------- | -------- | ----------- |
|
||||
* | BANDWIDTH | 0 | 带宽 | ✅ | ✅ |
|
||||
* | ENERGY | 1 | 能量 | ✅ | ✅ |
|
||||
* | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ |
|
||||
* | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ |
|
||||
*/
|
||||
boolean stakeTrxBalance(ApiWrapper api,String ownerAddr, BigDecimal balance, int resourceCode);
|
||||
|
||||
/**
|
||||
* 获取质押trx的数量-不包含代理的
|
||||
* @param ownerAddr
|
||||
* @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze |
|
||||
* | -------------- | ----- | ----------- | -------- | ----------- |
|
||||
* | BANDWIDTH | 0 | 带宽 | ✅ | ✅ |
|
||||
* | ENERGY | 1 | 能量 | ✅ | ✅ |
|
||||
* | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ |
|
||||
* | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ |
|
||||
* @return
|
||||
*/
|
||||
BigDecimal stakedTrxBalance(ApiWrapper api,String ownerAddr, int resourceCode);
|
||||
|
||||
/**
|
||||
* 获取别人质押的trx的数量-代理的
|
||||
* @param ownerAddr
|
||||
* @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze |
|
||||
* | -------------- | ----- | ----------- | -------- | ----------- |
|
||||
* | BANDWIDTH | 0 | 带宽 | ✅ | ✅ |
|
||||
* | ENERGY | 1 | 能量 | ✅ | ✅ |
|
||||
* | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ |
|
||||
* | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ |
|
||||
* @return
|
||||
*/
|
||||
BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api,String ownerAddr, int resourceCode);
|
||||
|
||||
|
||||
/**
|
||||
* 我质押的trx的数量-代理的给别人的
|
||||
* @param ownerAddr
|
||||
* @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze |
|
||||
* | -------------- | ----- | ----------- | -------- | ----------- |
|
||||
* | BANDWIDTH | 0 | 带宽 | ✅ | ✅ |
|
||||
* | ENERGY | 1 | 能量 | ✅ | ✅ |
|
||||
* | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ |
|
||||
* | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ |
|
||||
* @return
|
||||
*/
|
||||
BigDecimal delegatedStakedTrxBalance(ApiWrapper api,String ownerAddr, int resourceCode);
|
||||
|
||||
/**
|
||||
* 取消质押账户金额 - 在unstakeTrxBalance操作后会有值
|
||||
* @param api
|
||||
* @param ownerAddr
|
||||
* @param resourceCode
|
||||
* @return
|
||||
*/
|
||||
BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode);
|
||||
|
||||
/**
|
||||
* 获取可投票的数量
|
||||
* @param ownerAddr
|
||||
* @return
|
||||
*/
|
||||
BigDecimal voteBalance(ApiWrapper api,String ownerAddr);
|
||||
|
||||
|
||||
/**
|
||||
* 已经投票的数量
|
||||
* @param ownerAddr
|
||||
* @return
|
||||
*/
|
||||
BigDecimal votedBalance(ApiWrapper api,String ownerAddr);
|
||||
|
||||
/**
|
||||
* 自动投票到top前size的地址上
|
||||
* @param api
|
||||
* @param ownerAddress
|
||||
* @param size
|
||||
* @return
|
||||
*/
|
||||
boolean autoVoteTop(ApiWrapper api,String ownerAddress,int size) throws IllegalException;
|
||||
|
||||
/**
|
||||
* 自动领取TRX奖励
|
||||
* @param api
|
||||
* @param ownerAddr
|
||||
* @throws IllegalException
|
||||
*/
|
||||
boolean autoGetReward(ApiWrapper api,String ownerAddr) throws IllegalException;
|
||||
|
||||
/**
|
||||
* 给某个sender 授权usdt 额度-是做覆盖操作
|
||||
* @param api ownerAddr的api
|
||||
* @param ownerAddr 账户所有者地址
|
||||
* @param sender - 被授权的钱包地址
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
Boolean approve(ApiWrapper api,String ownerAddr,String sender, BigDecimal amount);
|
||||
|
||||
|
||||
BigDecimal getAllowance(ApiWrapper api,String ownerAddress, String spenderAddress);
|
||||
/**
|
||||
* usdt 转账
|
||||
* @param api 被授权(approve)的账号生成的api
|
||||
* @param sender approve 被授权的钱包地址
|
||||
* @param fromAddress
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
Boolean usdtTransferFrom(ApiWrapper api,String sender,String fromAddress, String toAddress, BigDecimal amount);
|
||||
|
||||
/**
|
||||
* 创建钱包
|
||||
* @return
|
||||
*/
|
||||
TronAccountItem createTronAddress();
|
||||
|
||||
/**
|
||||
* 由助记词生成
|
||||
* @return
|
||||
*/
|
||||
TronAccount createTronWallet(Integer site);
|
||||
/**
|
||||
* 默认不使用
|
||||
* Estimate the energy required for the successful execution of smart contract transactions
|
||||
* This API is closed by default in tron node.
|
||||
* To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant
|
||||
* must be enabled in the node configuration file at the same time.
|
||||
* @param api
|
||||
* @param fromAddress
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
long estimateEnergy(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount);
|
||||
|
||||
/**
|
||||
* 默认消耗的energy
|
||||
* @return
|
||||
*/
|
||||
long defaultEstimateEnergy();
|
||||
|
||||
|
||||
long defaultEstimateBandwidth();
|
||||
/**
|
||||
* 获取transfer消耗的带宽
|
||||
* @param api
|
||||
* @param fromAddress
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
long estimateBandwidth(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount);
|
||||
|
||||
/**
|
||||
* 把质押的TRX 代理给其他账号获取 带宽或者能量
|
||||
* @param api
|
||||
* @param fromAddress
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @param resourceCode
|
||||
* @return
|
||||
*/
|
||||
String delegateResourceV2(ApiWrapper api,String fromAddress, String toAddress,BigDecimal amount ,int resourceCode);
|
||||
|
||||
|
||||
/**
|
||||
* 取消把质押的TRX 代理给其他账号
|
||||
* @param api
|
||||
* @param fromAddress
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @param resourceCode
|
||||
* @return
|
||||
*/
|
||||
String unDelegateResourceV2(ApiWrapper api,String fromAddress, String toAddress,BigDecimal amount ,int resourceCode);
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.ruoyi.system.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.ruoyi.common.select.SelectItem;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskItem;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
/**
|
||||
* 归集任务明细Service接口
|
||||
*
|
||||
* @author luqj
|
||||
* @date 2026-01-01
|
||||
*/
|
||||
public interface IUsdtAggregationTaskItemService extends IService<UsdtAggregationTaskItemPlus>
|
||||
{
|
||||
|
||||
List<SelectItem> select(String keyword,boolean isUser);
|
||||
/**
|
||||
* 查询归集任务明细
|
||||
*
|
||||
* @param id 归集任务明细ID
|
||||
* @return 归集任务明细
|
||||
*/
|
||||
public UsdtAggregationTaskItem selectUsdtAggregationTaskItemById(Long id,boolean isUser);
|
||||
|
||||
/**
|
||||
* 查询归集任务明细列表
|
||||
*
|
||||
* @param usdtAggregationTaskItem 归集任务明细
|
||||
* @return 归集任务明细集合
|
||||
*/
|
||||
public List<UsdtAggregationTaskItem> selectUsdtAggregationTaskItemList(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser);
|
||||
|
||||
/**
|
||||
* 新增归集任务明细
|
||||
*
|
||||
* @param usdtAggregationTaskItem 归集任务明细
|
||||
* @return 结果
|
||||
*/
|
||||
public int insertUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser);
|
||||
|
||||
/**
|
||||
* 修改归集任务明细
|
||||
*
|
||||
* @param usdtAggregationTaskItem 归集任务明细
|
||||
* @return 结果
|
||||
*/
|
||||
public int updateUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser);
|
||||
|
||||
/**
|
||||
* 批量删除归集任务明细
|
||||
*
|
||||
* @param ids 需要删除的归集任务明细ID
|
||||
* @return 结果
|
||||
*/
|
||||
public int deleteUsdtAggregationTaskItemByIds(Long[] ids,boolean isUser);
|
||||
|
||||
/**
|
||||
* 删除归集任务明细信息
|
||||
*
|
||||
* @param id 归集任务明细ID
|
||||
* @return 结果
|
||||
*/
|
||||
public int deleteUsdtAggregationTaskItemById(Long id,boolean isUser);
|
||||
|
||||
List<UsdtAggregationTaskItemPlus> getByIds(List<Long> ids,boolean isUser, SFunction<UsdtAggregationTaskItemPlus, ?>... columns);
|
||||
|
||||
UsdtAggregationTaskItemPlus getById(Long id, SFunction<UsdtAggregationTaskItemPlus, ?>... columns);
|
||||
|
||||
Map<Long, UsdtAggregationTaskItemPlus> getMapByIds(List<Long> ids, SFunction<UsdtAggregationTaskItemPlus, ?>... columns);
|
||||
|
||||
List<UsdtAggregationTaskItemPlus> getListByStatusAndParentId(Integer status,Long parentId);
|
||||
|
||||
List<UsdtAggregationTaskItemPlus> getByIds(List<Long> ids);
|
||||
|
||||
Map<Long, UsdtAggregationTaskItemPlus> getMapByIds(List<Long> ids);
|
||||
|
||||
/**
|
||||
* @param field sum 字段
|
||||
* @param where 条件
|
||||
* @param tClass 返回类型
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> T sum(String field, String where, Class<T> tClass);
|
||||
|
||||
Long count(String where);
|
||||
|
||||
<T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ruoyi.system.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.ruoyi.common.select.SelectItem;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTask;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
/**
|
||||
* 归集任务Service接口
|
||||
*
|
||||
* @author luqj
|
||||
* @date 2026-01-01
|
||||
*/
|
||||
public interface IUsdtAggregationTaskService extends IService<UsdtAggregationTaskPlus>
|
||||
{
|
||||
|
||||
List<SelectItem> select(String keyword,boolean isUser);
|
||||
|
||||
List<UsdtAggregationTaskPlus> getListByStatusAndLtExeTime(Integer status, Date gtExeTime);
|
||||
/**
|
||||
* 查询归集任务
|
||||
*
|
||||
* @param id 归集任务ID
|
||||
* @return 归集任务
|
||||
*/
|
||||
public UsdtAggregationTask selectUsdtAggregationTaskById(Long id,boolean isUser);
|
||||
|
||||
/**
|
||||
* 查询归集任务列表
|
||||
*
|
||||
* @param usdtAggregationTask 归集任务
|
||||
* @return 归集任务集合
|
||||
*/
|
||||
public List<UsdtAggregationTask> selectUsdtAggregationTaskList(UsdtAggregationTask usdtAggregationTask,boolean isUser);
|
||||
|
||||
/**
|
||||
* 新增归集任务
|
||||
*
|
||||
* @param usdtAggregationTask 归集任务
|
||||
* @return 结果
|
||||
*/
|
||||
public int insertUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask,boolean isUser);
|
||||
|
||||
/**
|
||||
* 修改归集任务
|
||||
*
|
||||
* @param usdtAggregationTask 归集任务
|
||||
* @return 结果
|
||||
*/
|
||||
public int updateUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask,boolean isUser);
|
||||
|
||||
/**
|
||||
* 批量删除归集任务
|
||||
*
|
||||
* @param ids 需要删除的归集任务ID
|
||||
* @return 结果
|
||||
*/
|
||||
public int deleteUsdtAggregationTaskByIds(Long[] ids,boolean isUser);
|
||||
|
||||
/**
|
||||
* 删除归集任务信息
|
||||
*
|
||||
* @param id 归集任务ID
|
||||
* @return 结果
|
||||
*/
|
||||
public int deleteUsdtAggregationTaskById(Long id,boolean isUser);
|
||||
|
||||
List<UsdtAggregationTaskPlus> getByIds(List<Long> ids,boolean isUser, SFunction<UsdtAggregationTaskPlus, ?>... columns);
|
||||
|
||||
UsdtAggregationTaskPlus getById(Long id, SFunction<UsdtAggregationTaskPlus, ?>... columns);
|
||||
|
||||
Map<Long, UsdtAggregationTaskPlus> getMapByIds(List<Long> ids, SFunction<UsdtAggregationTaskPlus, ?>... columns);
|
||||
|
||||
List<UsdtAggregationTaskPlus> getByIds(List<Long> ids);
|
||||
|
||||
Map<Long, UsdtAggregationTaskPlus> getMapByIds(List<Long> ids);
|
||||
|
||||
/**
|
||||
* @param field sum 字段
|
||||
* @param where 条件
|
||||
* @param tClass 返回类型
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> T sum(String field, String where, Class<T> tClass);
|
||||
|
||||
Long count(String where);
|
||||
|
||||
<T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
package com.ruoyi.system.service;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import com.ruoyi.system.domain.WalletAddress;
|
||||
@@ -15,6 +16,8 @@ import com.ruoyi.common.select.SelectItem;
|
||||
public interface IWalletAddressService extends IService<WalletAddressPlus>
|
||||
{
|
||||
|
||||
boolean updateTronInfo(WalletAddressPlus walletAddress);
|
||||
|
||||
List<SelectItem> select(String keyword,boolean isUser);
|
||||
/**
|
||||
* 查询token管理
|
||||
@@ -24,6 +27,10 @@ public interface IWalletAddressService extends IService<WalletAddressPlus>
|
||||
*/
|
||||
public WalletAddress selectWalletAddressById(Long id,boolean isUser);
|
||||
|
||||
|
||||
WalletAddressPlus getByTokenAndAppId(String token,Long appId, SFunction<WalletAddressPlus, ?>... columns);
|
||||
|
||||
List<WalletAddressPlus> getListByAppId(Long appId, SFunction<WalletAddressPlus, ?>... columns);
|
||||
/**
|
||||
* 查询token管理列表
|
||||
*
|
||||
@@ -70,6 +77,8 @@ public interface IWalletAddressService extends IService<WalletAddressPlus>
|
||||
|
||||
Map<Long, WalletAddressPlus> getMapByIds(List<Long> ids, SFunction<WalletAddressPlus, ?>... columns);
|
||||
|
||||
boolean updateWithdrawUsdtBalanceById(Long id, BigDecimal withdrawUsdtBalance);
|
||||
|
||||
List<WalletAddressPlus> getByIds(List<Long> ids);
|
||||
|
||||
Map<Long, WalletAddressPlus> getMapByIds(List<Long> ids);
|
||||
|
||||
@@ -0,0 +1,852 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
|
||||
import com.ruoyi.system.domain.vo.TronAccount;
|
||||
import com.ruoyi.system.domain.vo.TronAccountItem;
|
||||
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.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
import org.bitcoinj.crypto.MnemonicCode;
|
||||
import org.bitcoinj.wallet.DeterministicKeyChain;
|
||||
import org.bitcoinj.wallet.DeterministicSeed;
|
||||
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;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.common.utils.Base58;
|
||||
import org.tron.common.utils.ByteArray;
|
||||
import org.tron.protos.Protocol;
|
||||
import org.tron.trident.abi.FunctionEncoder;
|
||||
import org.tron.trident.abi.datatypes.Address;
|
||||
import org.tron.trident.abi.datatypes.Function;
|
||||
import org.tron.trident.abi.datatypes.generated.Uint256;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.core.NodeType;
|
||||
import org.tron.trident.core.contract.Contract;
|
||||
import org.tron.trident.core.contract.Trc20Contract;
|
||||
import org.tron.trident.core.exceptions.IllegalException;
|
||||
import org.tron.trident.proto.Chain;
|
||||
import org.tron.trident.proto.Common;
|
||||
import org.tron.trident.proto.Response;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
import org.tron.trident.utils.Convert;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
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 {
|
||||
// 能量和带宽限制
|
||||
public static final long FEE_LIMIT = 10_000_000L; // 10 TRX
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
private static final BigInteger BASE = BigInteger.valueOf(58);
|
||||
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
private RestTemplate restTemplate = new RestTemplate();
|
||||
@Override
|
||||
public Integer grpcPort() {
|
||||
return 50051;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String grpcUrl() {
|
||||
return "grpc.nile.trongrid.io";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String type() {
|
||||
return "nile";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper(String privateKey) {
|
||||
ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tronscanApiUrl() {
|
||||
return "https://nileapi.tronscan.org";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tronscanApiKey() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String usdtTrans(ApiWrapper api, String fromAddress, String toAddress, String amount) {
|
||||
try {
|
||||
// 获取合约地址信息
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, fromAddress, api);
|
||||
String transfer;
|
||||
// 获取转账账户的TRX余额
|
||||
BigInteger trc20Value = token.balanceOf(fromAddress);
|
||||
// 获取想要转账的数额
|
||||
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
|
||||
// 进行比较
|
||||
if (trc20Value.compareTo(sunAmountValue) >= 0) {
|
||||
// 设置最大矿工费用
|
||||
long feeLimit = Convert.toSun("2", Convert.Unit.TRX).longValue();
|
||||
//转账
|
||||
transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (transfer == null || transfer.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return transfer;
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getMessage(),ex);
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
Chain.Transaction signTransaction = api.signTransaction(transaction);
|
||||
// 计算交易所需要的宽带
|
||||
long byteSize = api.estimateBandwidth(signTransaction);
|
||||
// long byteSize = api.estimateEnergy(signTransaction);
|
||||
// 广播交易
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getTRxBalance(ApiWrapper api, String address) {
|
||||
Long balance = api.getAccountBalance(address);
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(balance).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getUsdtBalance(ApiWrapper api, String address) {
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, address, api);
|
||||
BigInteger balanceOf = token.balanceOf(address);
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(balanceOf).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr) {
|
||||
ManagedChannel channel = ManagedChannelBuilder
|
||||
// .forAddress("grpc.trongrid.io", 50051)
|
||||
.forAddress(this.grpcUrl(), this.grpcPort())
|
||||
.usePlaintext()
|
||||
.build();
|
||||
WalletGrpc.WalletBlockingStub stub =
|
||||
WalletGrpc.newBlockingStub(channel);
|
||||
byte[] address = Base58Check.base58ToBytes(ownerAddr);
|
||||
Protocol.Account account = Protocol.Account.newBuilder()
|
||||
.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();
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
|
||||
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
|
||||
channel.shutdown();
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("TRON-PRO-API-KEY", "your_api_key");
|
||||
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<Void> entity = new HttpEntity<>(headers);
|
||||
ResponseEntity<TronAccountResp> result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class);
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
if(null != result.getBody()){
|
||||
energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue());
|
||||
energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue());
|
||||
energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue());
|
||||
energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue());
|
||||
energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2());
|
||||
energyAndBandwidthVo.setBandwidthStakedNum(result.getBody().getBandwidth().getNetRemaining());
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
energyAndBandwidthVo.setStakedTrxNum(divide.longValue());
|
||||
}else{
|
||||
energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setStakedTrxNum(0L);
|
||||
}
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean unstakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.unfreezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.cancelAllUnfreezeV2(ownerAddr);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean stakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.freezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal stakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Response.Account.FreezeV2 frozenV2 : account.getFrozenV2List()) {
|
||||
if (frozenV2.getType().getNumber() == resourceCode) {
|
||||
totalStakedSun += frozenV2.getAmount();
|
||||
}
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr);
|
||||
List<ByteString> list = resourceAccountIndex.getFromAccountsList();
|
||||
BigDecimal result = new BigDecimal(0);
|
||||
for (ByteString byteString : list) {
|
||||
String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray());
|
||||
String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(address, ownerAddr);
|
||||
int count = delegatedResourceList.getDelegatedResourceCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i);
|
||||
String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray());
|
||||
String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress));
|
||||
String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray());
|
||||
String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress));
|
||||
if (resourceCode == 0) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
} else if (resourceCode == 1) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr);
|
||||
List<ByteString> list = resourceAccountIndex.getToAccountsList();
|
||||
BigDecimal result = new BigDecimal(0);
|
||||
for (ByteString byteString : list) {
|
||||
String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray());
|
||||
String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(ownerAddr,address);
|
||||
int count = delegatedResourceList.getDelegatedResourceCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i);
|
||||
String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray());
|
||||
String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress));
|
||||
String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray());
|
||||
String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress));
|
||||
if (resourceCode == 0) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
} else if (resourceCode == 1) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
public BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Response.Account.UnFreezeV2 frozenV2 : account.getUnfrozenV2List()) {
|
||||
if (frozenV2.getType().getNumber() == resourceCode) {
|
||||
totalStakedSun += frozenV2.getUnfreezeAmount();
|
||||
}
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
System.out.println(divide);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal voteBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalVotes = account.getFrozenV2List().stream()
|
||||
.mapToLong(Response.Account.FreezeV2::getAmount)
|
||||
.sum() / 1_000_000;
|
||||
return new BigDecimal(totalVotes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
Map<String, Long> currentVotes = account.getVotesList().stream()
|
||||
.collect(Collectors.toMap(
|
||||
v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()),
|
||||
Common.Vote::getVoteCount
|
||||
));
|
||||
Iterator<Map.Entry<String, Long>> iterator = currentVotes.entrySet().iterator();
|
||||
BigDecimal bigDecimal = new BigDecimal(0);
|
||||
while (iterator.hasNext()) {
|
||||
bigDecimal = bigDecimal.add(new BigDecimal(iterator.next().getValue()));
|
||||
}
|
||||
return bigDecimal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean autoVoteTop(ApiWrapper api, String ownerAddress, int size) throws IllegalException {
|
||||
// 1. 当前账户
|
||||
Response.Account account = api.getAccount(ownerAddress);
|
||||
long totalVotes = account.getFrozenV2List().stream()
|
||||
.mapToLong(Response.Account.FreezeV2::getAmount)
|
||||
.sum() / 1_000_000;
|
||||
if (totalVotes <= 0) {
|
||||
log.error("没有投票的vote");
|
||||
return false;
|
||||
}
|
||||
Map<String, Long> currentVotes = account.getVotesList().stream()
|
||||
.collect(Collectors.toMap(
|
||||
v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()),
|
||||
Common.Vote::getVoteCount
|
||||
));
|
||||
// 2. Top27 SR
|
||||
Response.WitnessList witnesses = api.listWitnesses();
|
||||
Set<String> top27 = witnesses.getWitnessesList().stream()
|
||||
.sorted(Comparator.comparingLong(w -> -w.getVoteCount()))
|
||||
.limit(size + 1)
|
||||
.map(w -> Base58Check.bytesToBase58(w.getAddress().toByteArray()))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// 3. 找出掉出 Top27 的 SR
|
||||
boolean needRevote = currentVotes.keySet().stream()
|
||||
.anyMatch(sr -> !top27.contains(sr));
|
||||
Iterator<String> iterator = currentVotes.keySet().iterator();
|
||||
org.tron.protos.Contract.VoteWitnessContract.Builder builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder()
|
||||
.setOwnerAddress(ApiWrapper.parseAddress(ownerAddress));
|
||||
boolean cancle = false;
|
||||
while (iterator.hasNext()) {
|
||||
String address = iterator.next();
|
||||
if (!top27.contains(address)) {
|
||||
builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(address))
|
||||
.setVoteCount(1));
|
||||
cancle = true;
|
||||
}
|
||||
}
|
||||
if (cancle) {
|
||||
org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build();
|
||||
Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract,
|
||||
Chain.Transaction.Contract.ContractType.VoteWitnessContract);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
}
|
||||
if (!needRevote) {
|
||||
log.info("All SRs still in Top27.");
|
||||
return true;
|
||||
}
|
||||
// 4. 总投票权
|
||||
List<String> backupSRs = new ArrayList<>();
|
||||
// 5. 构建新投票(平均投到备用 SR)
|
||||
backupSRs.addAll(top27.stream().sorted().collect(Collectors.toList()).subList(0, size));
|
||||
long perSRVotes = totalVotes / backupSRs.size();
|
||||
builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder()
|
||||
.setOwnerAddress(ApiWrapper.parseAddress(ownerAddress));
|
||||
for (String sr : backupSRs) {
|
||||
builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(sr)).setVoteCount(perSRVotes));
|
||||
}
|
||||
org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build();
|
||||
Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract,
|
||||
Chain.Transaction.Contract.ContractType.VoteWitnessContract);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean autoGetReward(ApiWrapper api, String ownerAddr) throws IllegalException {
|
||||
org.tron.trident.api.GrpcAPI.NumberMessage reward = api.getRewardInfo(ownerAddr, NodeType.FULL_NODE);
|
||||
log.info("Unclaimed reward: " + reward.getNum() / 1_000_000.0 + " TRX");
|
||||
Response.TransactionExtention tx = api.withdrawBalance(ownerAddr);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
Function function = new Function(
|
||||
"approve",
|
||||
Arrays.asList(
|
||||
new Address(spenderAddress),
|
||||
new Uint256(amountInSun)
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ownerAddr,
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
|
||||
function
|
||||
).setFeeLimit(FEE_LIMIT).build();
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
Response.TransactionReturn ret = api.blockingStub.broadcastTransaction(signedTxn);
|
||||
return ret.getResult();
|
||||
} catch (Exception e) {
|
||||
log.error("授权异常: " + e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getAllowance(ApiWrapper api, String ownerAddress, String spenderAddress) {
|
||||
// Trc20合约地址
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, ownerAddress, api);
|
||||
try {
|
||||
// 查询授权额度
|
||||
BigInteger allowance = token.allowance(ownerAddress, spenderAddress);
|
||||
|
||||
// 如果是USDT等6位小数代币
|
||||
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
|
||||
return new BigDecimal(allowanceInToken);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new BigDecimal(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 构建 transferFrom 函数
|
||||
Function function = new Function(
|
||||
"transferFrom",
|
||||
Arrays.asList(
|
||||
new Address(fromAddress), // 转出地址
|
||||
new Address(toAddress), // 接收地址
|
||||
new Uint256(amountInSun) // 转账金额
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
|
||||
|
||||
String encodedFunction = FunctionEncoder.encode(function);
|
||||
System.out.println("编码后的函数: " + encodedFunction);
|
||||
|
||||
// 触发智能合约调用
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
|
||||
function
|
||||
).setFeeLimit(FEE_LIMIT).build();
|
||||
// 签名交易
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
// 广播交易
|
||||
String ret = api.broadcastTransaction(signedTxn);
|
||||
log.info(ret);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("transferFrom 异常: " + e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TronAccountItem createTronAddress() {
|
||||
ECKey eCkey = new ECKey(random);
|
||||
String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes());
|
||||
byte[] addressBytes = eCkey.getAddress();
|
||||
String hexAddress = ByteArray.toHexString(addressBytes);
|
||||
TronAccountItem tronAccount = new TronAccountItem();
|
||||
tronAccount.setAddress(toViewAddress(hexAddress));
|
||||
tronAccount.setHexAddress(hexAddress);
|
||||
tronAccount.setPrivateKey(privateKey);
|
||||
//String privateKeyBase58 = org.spongycastle.util.encoders.Hex.e(base58Str);
|
||||
String privateKeyBase58 = encode58Check(eCkey.getPrivKeyBytes());
|
||||
tronAccount.setPrivateKeyBase58(privateKeyBase58);
|
||||
return tronAccount;
|
||||
}
|
||||
|
||||
private static byte[] keccak256(byte[] input) {
|
||||
Keccak.Digest256 digest = new Keccak.Digest256();
|
||||
return digest.digest(input);
|
||||
}
|
||||
|
||||
private String formatHDPath(HDPath path) {
|
||||
StringBuilder sb = new StringBuilder("m");
|
||||
for (ChildNumber cn : path) {
|
||||
sb.append("/");
|
||||
sb.append(cn.isHardened() ? cn.num() + "'" : cn.num());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String base58CheckEncode(byte[] input) throws NoSuchAlgorithmException {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash1 = digest.digest(input);
|
||||
byte[] hash2 = digest.digest(hash1);
|
||||
|
||||
byte[] checksum = Arrays.copyOfRange(hash2, 0, 4);
|
||||
|
||||
byte[] result = new byte[input.length + 4];
|
||||
System.arraycopy(input, 0, result, 0, input.length);
|
||||
System.arraycopy(checksum, 0, result, input.length, 4);
|
||||
|
||||
return encode(result);
|
||||
}
|
||||
|
||||
public String encode(byte[] input) {
|
||||
BigInteger bi = new BigInteger(1, input);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (bi.compareTo(BigInteger.ZERO) > 0) {
|
||||
BigInteger[] div = bi.divideAndRemainder(BASE);
|
||||
sb.append(ALPHABET[div[1].intValue()]);
|
||||
bi = div[0];
|
||||
}
|
||||
for (byte b : input) {
|
||||
if (b == 0) {
|
||||
sb.append(ALPHABET[0]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.reverse().toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TronAccount createTronWallet(Integer site) {
|
||||
TronAccount result = new TronAccount();
|
||||
// 1. 生成随机助记词(12个)
|
||||
SecureRandom random = new SecureRandom();
|
||||
byte[] entropy = new byte[16]; // 128-bit entropy
|
||||
random.nextBytes(entropy);
|
||||
List<String> mnemonicWords = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||
|
||||
// 可以使用助记词恢复公私钥和钱包地址
|
||||
/*String mnemonicStr = "elder trend clay accuse joke pizza extend holiday spread apple dress mercy";
|
||||
List<String> mnemonicWords = Arrays.stream(mnemonicStr.split(" ")).collect(Collectors.toList());*/
|
||||
|
||||
String mnemonic = String.join(" ", mnemonicWords);
|
||||
result.setPhrase(mnemonic);
|
||||
// 2. 创建 DeterministicSeed 和 KeyChain
|
||||
DeterministicSeed seed = DeterministicSeed.ofMnemonic(mnemonicWords, "");
|
||||
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
|
||||
|
||||
// 3. 使用 TRON 路径 m/44'/195'/0'/0/i
|
||||
HDPath basePath = HDPath.M().extend(
|
||||
new ChildNumber(44, true),
|
||||
new ChildNumber(195, true),
|
||||
new ChildNumber(0, true),
|
||||
ChildNumber.ZERO
|
||||
);
|
||||
|
||||
List<TronAccountItem> list = new ArrayList<>();
|
||||
for (int i = 0; i < site; i++) {
|
||||
HDPath path = basePath.extend(new ChildNumber(i, false));
|
||||
DeterministicKey key = keyChain.getKeyByPath(path, true);
|
||||
byte[] privateKey = key.getPrivKeyBytes();
|
||||
byte[] pubKeyCompressed = key.getPubKey(); // 压缩公钥(33字节)
|
||||
ECPoint pubKeyPoint = key.getPubKeyPoint();
|
||||
byte[] pubKeyUnCompressed = pubKeyPoint.getEncoded(false); // 非压缩公钥(65字节)
|
||||
byte[] pubKeyWithoutPrefix = Arrays.copyOfRange(pubKeyUnCompressed, 1, pubKeyUnCompressed.length);
|
||||
byte[] keccakHash = keccak256(pubKeyWithoutPrefix);
|
||||
byte[] addressBytes = new byte[21];
|
||||
addressBytes[0] = (byte) 0x41;
|
||||
System.arraycopy(keccakHash, 12, addressBytes, 1, 20);
|
||||
String base58Address = null;
|
||||
try {
|
||||
base58Address = base58CheckEncode(addressBytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
String pathStr = formatHDPath(path);
|
||||
TronAccountItem item = new TronAccountItem();
|
||||
item.setAddress(base58Address);
|
||||
item.setPrivateKey(Hex.toHexString(privateKey));
|
||||
item.setPubKeyCompressed(Hex.toHexString(pubKeyCompressed));
|
||||
item.setPubKeyUnCompressed(Hex.toHexString(pubKeyUnCompressed));
|
||||
item.setPath(pathStr);
|
||||
String hexAddress = ByteArray.toHexString(addressBytes);
|
||||
item.setHexAddress(hexAddress);
|
||||
String privateKeyBase58 = encode58Check(privateKey);
|
||||
item.setPrivateKeyBase58(privateKeyBase58);
|
||||
|
||||
list.add(item);
|
||||
}
|
||||
result.setItems(list);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the energy required for the successful execution of smart contract transactions
|
||||
* This API is closed by default in tron node.
|
||||
* To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant
|
||||
* must be enabled in the node configuration file at the same time.
|
||||
*
|
||||
* @param api
|
||||
* @param owner
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
@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();
|
||||
Function function = new Function(
|
||||
"transfer(address,uint256)",
|
||||
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
|
||||
);
|
||||
return estimate.getEnergyRequired();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long defaultEstimateEnergy() {
|
||||
return 20000L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long defaultEstimateBandwidth() {
|
||||
return 365;
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
Chain.Transaction signTransaction = api.signTransaction(transaction);
|
||||
// 计算交易所需要的宽带
|
||||
return api.estimateBandwidth(signTransaction);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@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();
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
}
|
||||
|
||||
@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();
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成T开头的地址
|
||||
*
|
||||
* @param hexAddress
|
||||
* @return
|
||||
*/
|
||||
private String toViewAddress(String hexAddress) {
|
||||
return encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 hash of the given bytes.
|
||||
*
|
||||
* @param input the bytes to hash
|
||||
* @return the hash (in big-endian order)
|
||||
*/
|
||||
public byte[] hash(boolean isSha256, byte[] input) throws NoSuchAlgorithmException {
|
||||
return hash(isSha256, input, 0, input.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 hash of the given byte range.
|
||||
*
|
||||
* @param input the array containing the bytes to hash
|
||||
* @param offset the offset within the array of the bytes to hash
|
||||
* @param length the number of bytes to hash
|
||||
* @return the hash (in big-endian order)
|
||||
*/
|
||||
public byte[] hash(boolean isSha256, byte[] input, int offset, int length) throws NoSuchAlgorithmException {
|
||||
if (isSha256) {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
digest.update(input, offset, length);
|
||||
return digest.digest();
|
||||
} else {
|
||||
SM3Digest digest = new SM3Digest();
|
||||
digest.update(input, offset, length);
|
||||
byte[] eHash = new byte[digest.getDigestSize()];
|
||||
digest.doFinal(eHash, 0);
|
||||
return eHash;
|
||||
}
|
||||
}
|
||||
|
||||
private String encode58Check(byte[] input) {
|
||||
try {
|
||||
byte[] hash0 = hash(true, input);
|
||||
byte[] hash1 = hash(true, hash0);
|
||||
byte[] inputCheck = new byte[input.length + 4];
|
||||
System.arraycopy(input, 0, inputCheck, 0, input.length);
|
||||
System.arraycopy(hash1, 0, inputCheck, input.length, 4);
|
||||
return Base58.encode(inputCheck);
|
||||
} catch (Throwable t) {
|
||||
log.error(String.format("data error:%s", Hex.toHexString(input)), t);
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,834 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
|
||||
import com.ruoyi.system.domain.vo.TronAccount;
|
||||
import com.ruoyi.system.domain.vo.TronAccountItem;
|
||||
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.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
import org.bitcoinj.crypto.MnemonicCode;
|
||||
import org.bitcoinj.wallet.DeterministicKeyChain;
|
||||
import org.bitcoinj.wallet.DeterministicSeed;
|
||||
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;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.common.utils.Base58;
|
||||
import org.tron.common.utils.ByteArray;
|
||||
import org.tron.protos.Protocol;
|
||||
import org.tron.trident.abi.FunctionEncoder;
|
||||
import org.tron.trident.abi.datatypes.Address;
|
||||
import org.tron.trident.abi.datatypes.Function;
|
||||
import org.tron.trident.abi.datatypes.generated.Uint256;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.core.NodeType;
|
||||
import org.tron.trident.core.contract.Contract;
|
||||
import org.tron.trident.core.contract.Trc20Contract;
|
||||
import org.tron.trident.core.exceptions.IllegalException;
|
||||
import org.tron.trident.proto.Chain;
|
||||
import org.tron.trident.proto.Common;
|
||||
import org.tron.trident.proto.Response;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
import org.tron.trident.utils.Convert;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
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 BigInteger BASE = BigInteger.valueOf(58);
|
||||
|
||||
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
private RestTemplate restTemplate = new RestTemplate();
|
||||
// 能量和带宽限制
|
||||
public static final long FEE_LIMIT = 10_000_000L; // 10 TRX
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
|
||||
@Override
|
||||
public Integer grpcPort() {
|
||||
return 50051;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String grpcUrl() {
|
||||
return "grpc.trongrid.io";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String type() {
|
||||
return "pro";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper(String privateKey) {
|
||||
return ApiWrapper.ofMainnet(privateKey, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
}
|
||||
|
||||
private static byte[] keccak256(byte[] input) {
|
||||
Keccak.Digest256 digest = new Keccak.Digest256();
|
||||
return digest.digest(input);
|
||||
}
|
||||
|
||||
private String formatHDPath(HDPath path) {
|
||||
StringBuilder sb = new StringBuilder("m");
|
||||
for (ChildNumber cn : path) {
|
||||
sb.append("/");
|
||||
sb.append(cn.isHardened() ? cn.num() + "'" : cn.num());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String base58CheckEncode(byte[] input) throws NoSuchAlgorithmException {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash1 = digest.digest(input);
|
||||
byte[] hash2 = digest.digest(hash1);
|
||||
|
||||
byte[] checksum = Arrays.copyOfRange(hash2, 0, 4);
|
||||
|
||||
byte[] result = new byte[input.length + 4];
|
||||
System.arraycopy(input, 0, result, 0, input.length);
|
||||
System.arraycopy(checksum, 0, result, input.length, 4);
|
||||
|
||||
return encode(result);
|
||||
}
|
||||
|
||||
public String encode(byte[] input) {
|
||||
BigInteger bi = new BigInteger(1, input);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (bi.compareTo(BigInteger.ZERO) > 0) {
|
||||
BigInteger[] div = bi.divideAndRemainder(BASE);
|
||||
sb.append(ALPHABET[div[1].intValue()]);
|
||||
bi = div[0];
|
||||
}
|
||||
for (byte b : input) {
|
||||
if (b == 0) {
|
||||
sb.append(ALPHABET[0]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.reverse().toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tronscanApiUrl() {
|
||||
return "https://api.tronscan.org";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tronscanApiKey() {
|
||||
return "47fae50b-b5e8-4d1b-8329-501a422a3169";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String usdtTrans(ApiWrapper api, String fromAddress, String toAddress, String amount) {
|
||||
try {
|
||||
// 获取合约地址信息
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, fromAddress, api);
|
||||
String transfer;
|
||||
// 获取转账账户的TRX余额
|
||||
BigInteger trc20Value = token.balanceOf(fromAddress);
|
||||
// 获取想要转账的数额
|
||||
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
|
||||
// 进行比较
|
||||
if (trc20Value.compareTo(sunAmountValue) >= 0) {
|
||||
// 设置最大矿工费用
|
||||
long feeLimit = Convert.toSun("2", Convert.Unit.TRX).longValue();
|
||||
//转账
|
||||
transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit);
|
||||
} else {
|
||||
return "error_error";
|
||||
}
|
||||
if (transfer == null || transfer.equals("")) {
|
||||
return "error_error";
|
||||
}
|
||||
return transfer;
|
||||
} catch (Exception ex) {
|
||||
String message = ex.getMessage();
|
||||
return "error_" + message;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
Chain.Transaction signTransaction = api.signTransaction(transaction);
|
||||
// 计算交易所需要的宽带
|
||||
long byteSize = api.estimateBandwidth(signTransaction);
|
||||
// long byteSize = api.estimateEnergy(signTransaction);
|
||||
// 广播交易
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getTRxBalance(ApiWrapper api, String address) {
|
||||
Long balance = api.getAccountBalance(address);
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(balance).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getUsdtBalance(ApiWrapper api, String address) {
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, address, api);
|
||||
BigInteger balanceOf = token.balanceOf(address);
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(balanceOf).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr) {
|
||||
ManagedChannel channel = ManagedChannelBuilder
|
||||
// .forAddress("grpc.trongrid.io", 50051)
|
||||
.forAddress(this.grpcUrl(), this.grpcPort())
|
||||
.usePlaintext()
|
||||
.build();
|
||||
WalletGrpc.WalletBlockingStub stub =
|
||||
WalletGrpc.newBlockingStub(channel);
|
||||
byte[] address = Base58Check.base58ToBytes(ownerAddr);
|
||||
Protocol.Account account = Protocol.Account.newBuilder()
|
||||
.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();
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
|
||||
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
@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();
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
}
|
||||
@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();
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
}
|
||||
@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("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<Void> entity = new HttpEntity<>(headers);
|
||||
ResponseEntity<TronAccountResp> result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class);
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
if(null != result.getBody()){
|
||||
energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue());
|
||||
energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue());
|
||||
energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue());
|
||||
energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue());
|
||||
energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2());
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
energyAndBandwidthVo.setStakedTrxNum(divide.longValue());
|
||||
}else{
|
||||
energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setStakedTrxNum(0L);
|
||||
}
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean unstakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.unfreezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
Map<String, Long> currentVotes = account.getVotesList().stream()
|
||||
.collect(Collectors.toMap(
|
||||
v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()),
|
||||
Common.Vote::getVoteCount
|
||||
));
|
||||
Iterator<Map.Entry<String, Long>> iterator = currentVotes.entrySet().iterator();
|
||||
BigDecimal bigDecimal = new BigDecimal(0);
|
||||
while (iterator.hasNext()) {
|
||||
bigDecimal = bigDecimal.add(new BigDecimal(iterator.next().getValue()));
|
||||
}
|
||||
return bigDecimal;
|
||||
}
|
||||
@Override
|
||||
public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr);
|
||||
List<ByteString> list = resourceAccountIndex.getToAccountsList();
|
||||
BigDecimal result = new BigDecimal(0);
|
||||
for (ByteString byteString : list) {
|
||||
String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray());
|
||||
String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(ownerAddr,address);
|
||||
int count = delegatedResourceList.getDelegatedResourceCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i);
|
||||
String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray());
|
||||
String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress));
|
||||
String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray());
|
||||
String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress));
|
||||
if (resourceCode == 0) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
} else if (resourceCode == 1) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr);
|
||||
List<ByteString> list = resourceAccountIndex.getFromAccountsList();
|
||||
BigDecimal result = new BigDecimal(0);
|
||||
for (ByteString byteString : list) {
|
||||
String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray());
|
||||
String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(address, ownerAddr);
|
||||
int count = delegatedResourceList.getDelegatedResourceCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i);
|
||||
String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray());
|
||||
String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress));
|
||||
String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray());
|
||||
String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress));
|
||||
if(resourceCode == 0){
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}else if(resourceCode == 1){
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}catch (Exception e){
|
||||
log.error(e.getMessage(),e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.cancelAllUnfreezeV2(ownerAddr);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean stakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.freezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal stakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Response.Account.FreezeV2 frozenV2 : account.getFrozenV2List()) {
|
||||
if (frozenV2.getType().getNumber() == resourceCode) {
|
||||
totalStakedSun += frozenV2.getAmount();
|
||||
}
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
public BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Response.Account.UnFreezeV2 frozenV2 : account.getUnfrozenV2List()) {
|
||||
if (frozenV2.getType().getNumber() == resourceCode) {
|
||||
totalStakedSun += frozenV2.getUnfreezeAmount();
|
||||
}
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
System.out.println(divide);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal voteBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Common.Vote vote : account.getVotesList()) {
|
||||
totalStakedSun += vote.getVoteCount();
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean autoVoteTop(ApiWrapper api, String ownerAddress, int size) throws IllegalException {
|
||||
// 1. 当前账户
|
||||
Response.Account account = api.getAccount(ownerAddress);
|
||||
long totalVotes = account.getFrozenV2List().stream()
|
||||
.mapToLong(Response.Account.FreezeV2::getAmount)
|
||||
.sum() / 1_000_000;
|
||||
if (totalVotes <= 0) {
|
||||
log.error("没有投票的vote");
|
||||
return false;
|
||||
}
|
||||
Map<String, Long> currentVotes = account.getVotesList().stream()
|
||||
.collect(Collectors.toMap(
|
||||
v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()),
|
||||
Common.Vote::getVoteCount
|
||||
));
|
||||
// 2. Top27 SR
|
||||
Response.WitnessList witnesses = api.listWitnesses();
|
||||
Set<String> top27 = witnesses.getWitnessesList().stream()
|
||||
.sorted(Comparator.comparingLong(w -> -w.getVoteCount()))
|
||||
.limit(size + 1)
|
||||
.map(w -> Base58Check.bytesToBase58(w.getAddress().toByteArray()))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// 3. 找出掉出 Top27 的 SR
|
||||
boolean needRevote = currentVotes.keySet().stream()
|
||||
.anyMatch(sr -> !top27.contains(sr));
|
||||
Iterator<String> iterator = currentVotes.keySet().iterator();
|
||||
org.tron.protos.Contract.VoteWitnessContract.Builder builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder()
|
||||
.setOwnerAddress(ApiWrapper.parseAddress(ownerAddress));
|
||||
boolean cancle = false;
|
||||
while (iterator.hasNext()) {
|
||||
String address = iterator.next();
|
||||
if (!top27.contains(address)) {
|
||||
builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(address))
|
||||
.setVoteCount(1));
|
||||
cancle = true;
|
||||
}
|
||||
}
|
||||
if (cancle) {
|
||||
org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build();
|
||||
Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract,
|
||||
Chain.Transaction.Contract.ContractType.VoteWitnessContract);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
}
|
||||
if (!needRevote) {
|
||||
log.info("All SRs still in Top27.");
|
||||
return true;
|
||||
}
|
||||
// 4. 总投票权
|
||||
List<String> backupSRs = new ArrayList<>();
|
||||
// 5. 构建新投票(平均投到备用 SR)
|
||||
backupSRs.addAll(top27.stream().sorted().collect(Collectors.toList()).subList(0, size));
|
||||
long perSRVotes = totalVotes / backupSRs.size();
|
||||
builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder()
|
||||
.setOwnerAddress(ApiWrapper.parseAddress(ownerAddress));
|
||||
for (String sr : backupSRs) {
|
||||
builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(sr)).setVoteCount(perSRVotes));
|
||||
}
|
||||
org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build();
|
||||
Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract,
|
||||
Chain.Transaction.Contract.ContractType.VoteWitnessContract);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean autoGetReward(ApiWrapper api, String ownerAddr) throws IllegalException {
|
||||
org.tron.trident.api.GrpcAPI.NumberMessage reward = api.getRewardInfo(ownerAddr, NodeType.FULL_NODE);
|
||||
log.info("Unclaimed reward: " + reward.getNum() / 1_000_000.0 + " TRX");
|
||||
Response.TransactionExtention tx = api.withdrawBalance(ownerAddr);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
Function function = new Function(
|
||||
"approve",
|
||||
Arrays.asList(
|
||||
new Address(spenderAddress),
|
||||
new Uint256(amountInSun)
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ownerAddr,
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
|
||||
function
|
||||
).setFeeLimit(FEE_LIMIT).build();
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
Response.TransactionReturn ret = api.blockingStub.broadcastTransaction(signedTxn);
|
||||
return ret.getResult();
|
||||
} catch (Exception e) {
|
||||
log.error("授权异常: " + e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getAllowance(ApiWrapper api, String ownerAddress, String spenderAddress) {
|
||||
// Trc20合约地址
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, ownerAddress, api);
|
||||
try {
|
||||
// 查询授权额度
|
||||
BigInteger allowance = token.allowance(ownerAddress, spenderAddress);
|
||||
|
||||
// 如果是USDT等6位小数代币
|
||||
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
|
||||
return new BigDecimal(allowanceInToken);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new BigDecimal(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 构建 transferFrom 函数
|
||||
Function function = new Function(
|
||||
"transferFrom",
|
||||
Arrays.asList(
|
||||
new Address(fromAddress), // 转出地址
|
||||
new Address(toAddress), // 接收地址
|
||||
new Uint256(amountInSun) // 转账金额
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
|
||||
|
||||
String encodedFunction = FunctionEncoder.encode(function);
|
||||
System.out.println("编码后的函数: " + encodedFunction);
|
||||
|
||||
// 触发智能合约调用
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
|
||||
function
|
||||
).setFeeLimit(FEE_LIMIT).build();
|
||||
// 签名交易
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
// 广播交易
|
||||
String ret = api.broadcastTransaction(signedTxn);
|
||||
log.info(ret);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("transferFrom 异常: " + e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TronAccountItem createTronAddress() {
|
||||
ECKey eCkey = new ECKey(random);
|
||||
String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes());
|
||||
byte[] addressBytes = eCkey.getAddress();
|
||||
String hexAddress = ByteArray.toHexString(addressBytes);
|
||||
TronAccountItem tronAccount = new TronAccountItem();
|
||||
tronAccount.setAddress(toViewAddress(hexAddress));
|
||||
tronAccount.setHexAddress(hexAddress);
|
||||
tronAccount.setPrivateKey(privateKey);
|
||||
//String privateKeyBase58 = org.spongycastle.util.encoders.Hex.e(base58Str);
|
||||
String privateKeyBase58 = encode58Check(eCkey.getPrivKeyBytes());
|
||||
tronAccount.setPrivateKeyBase58(privateKeyBase58);
|
||||
return tronAccount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TronAccount createTronWallet(Integer site) {
|
||||
TronAccount result = new TronAccount();
|
||||
// 1. 生成随机助记词(12个)
|
||||
SecureRandom random = new SecureRandom();
|
||||
byte[] entropy = new byte[16]; // 128-bit entropy
|
||||
random.nextBytes(entropy);
|
||||
List<String> mnemonicWords = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||
|
||||
// 可以使用助记词恢复公私钥和钱包地址
|
||||
/*String mnemonicStr = "elder trend clay accuse joke pizza extend holiday spread apple dress mercy";
|
||||
List<String> mnemonicWords = Arrays.stream(mnemonicStr.split(" ")).collect(Collectors.toList());*/
|
||||
|
||||
String mnemonic = String.join(" ", mnemonicWords);
|
||||
result.setPhrase(mnemonic);
|
||||
// 2. 创建 DeterministicSeed 和 KeyChain
|
||||
DeterministicSeed seed = DeterministicSeed.ofMnemonic(mnemonicWords, "");
|
||||
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
|
||||
|
||||
// 3. 使用 TRON 路径 m/44'/195'/0'/0/i
|
||||
HDPath basePath = HDPath.M().extend(
|
||||
new ChildNumber(44, true),
|
||||
new ChildNumber(195, true),
|
||||
new ChildNumber(0, true),
|
||||
ChildNumber.ZERO
|
||||
);
|
||||
|
||||
List<TronAccountItem> list = new ArrayList<>();
|
||||
for (int i = 0; i < site; i++) {
|
||||
HDPath path = basePath.extend(new ChildNumber(i, false));
|
||||
DeterministicKey key = keyChain.getKeyByPath(path, true);
|
||||
byte[] privateKey = key.getPrivKeyBytes();
|
||||
byte[] pubKeyCompressed = key.getPubKey(); // 压缩公钥(33字节)
|
||||
ECPoint pubKeyPoint = key.getPubKeyPoint();
|
||||
byte[] pubKeyUnCompressed = pubKeyPoint.getEncoded(false); // 非压缩公钥(65字节)
|
||||
byte[] pubKeyWithoutPrefix = Arrays.copyOfRange(pubKeyUnCompressed, 1, pubKeyUnCompressed.length);
|
||||
byte[] keccakHash = keccak256(pubKeyWithoutPrefix);
|
||||
byte[] addressBytes = new byte[21];
|
||||
addressBytes[0] = (byte) 0x41;
|
||||
System.arraycopy(keccakHash, 12, addressBytes, 1, 20);
|
||||
String base58Address = null;
|
||||
try {
|
||||
base58Address = base58CheckEncode(addressBytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
String pathStr = formatHDPath(path);
|
||||
TronAccountItem item = new TronAccountItem();
|
||||
item.setAddress(base58Address);
|
||||
item.setPrivateKey(Hex.toHexString(privateKey));
|
||||
item.setPubKeyCompressed(Hex.toHexString(pubKeyCompressed));
|
||||
item.setPubKeyUnCompressed(Hex.toHexString(pubKeyUnCompressed));
|
||||
item.setPath(pathStr);
|
||||
list.add(item);
|
||||
}
|
||||
result.setItems(list);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the energy required for the successful execution of smart contract transactions
|
||||
* This API is closed by default in tron node.
|
||||
* To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant
|
||||
* must be enabled in the node configuration file at the same time.
|
||||
*
|
||||
* @param api
|
||||
* @param owner
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
@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();
|
||||
Function function = new Function(
|
||||
"transfer(address,uint256)",
|
||||
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
|
||||
);
|
||||
return estimate.getEnergyRequired();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long defaultEstimateEnergy() {
|
||||
return 20000L;
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
Chain.Transaction signTransaction = api.signTransaction(transaction);
|
||||
// 计算交易所需要的宽带
|
||||
return api.estimateBandwidth(signTransaction);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成T开头的地址
|
||||
*
|
||||
* @param hexAddress
|
||||
* @return
|
||||
*/
|
||||
private String toViewAddress(String hexAddress) {
|
||||
return encode58Check(ByteArray.fromHexString(hexAddress));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 hash of the given bytes.
|
||||
*
|
||||
* @param input the bytes to hash
|
||||
* @return the hash (in big-endian order)
|
||||
*/
|
||||
public byte[] hash(boolean isSha256, byte[] input) throws NoSuchAlgorithmException {
|
||||
return hash(isSha256, input, 0, input.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 hash of the given byte range.
|
||||
*
|
||||
* @param input the array containing the bytes to hash
|
||||
* @param offset the offset within the array of the bytes to hash
|
||||
* @param length the number of bytes to hash
|
||||
* @return the hash (in big-endian order)
|
||||
*/
|
||||
public byte[] hash(boolean isSha256, byte[] input, int offset, int length) throws NoSuchAlgorithmException {
|
||||
if (isSha256) {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
digest.update(input, offset, length);
|
||||
return digest.digest();
|
||||
} else {
|
||||
SM3Digest digest = new SM3Digest();
|
||||
digest.update(input, offset, length);
|
||||
byte[] eHash = new byte[digest.getDigestSize()];
|
||||
digest.doFinal(eHash, 0);
|
||||
return eHash;
|
||||
}
|
||||
}
|
||||
|
||||
private String encode58Check(byte[] input) {
|
||||
try {
|
||||
byte[] hash0 = hash(true, input);
|
||||
byte[] hash1 = hash(true, hash0);
|
||||
byte[] inputCheck = new byte[input.length + 4];
|
||||
System.arraycopy(input, 0, inputCheck, 0, input.length);
|
||||
System.arraycopy(hash1, 0, inputCheck, input.length, 4);
|
||||
return Base58.encode(inputCheck);
|
||||
} catch (Throwable t) {
|
||||
log.error(String.format("data error:%s", Hex.toHexString(input)), t);
|
||||
}
|
||||
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,838 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.ruoyi.common.utils.http.HttpHelper;
|
||||
import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo;
|
||||
import com.ruoyi.system.domain.vo.TronAccount;
|
||||
import com.ruoyi.system.domain.vo.TronAccountItem;
|
||||
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.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
import org.bitcoinj.crypto.MnemonicCode;
|
||||
import org.bitcoinj.wallet.DeterministicKeyChain;
|
||||
import org.bitcoinj.wallet.DeterministicSeed;
|
||||
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;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.common.utils.Base58;
|
||||
import org.tron.common.utils.ByteArray;
|
||||
import org.tron.protos.Protocol;
|
||||
import org.tron.trident.abi.FunctionEncoder;
|
||||
import org.tron.trident.abi.datatypes.Address;
|
||||
import org.tron.trident.abi.datatypes.Function;
|
||||
import org.tron.trident.abi.datatypes.generated.Uint256;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.core.NodeType;
|
||||
import org.tron.trident.core.contract.Contract;
|
||||
import org.tron.trident.core.contract.Trc20Contract;
|
||||
import org.tron.trident.core.exceptions.IllegalException;
|
||||
import org.tron.trident.proto.Chain;
|
||||
import org.tron.trident.proto.Common;
|
||||
import org.tron.trident.proto.Response;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
import org.tron.trident.utils.Convert;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
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 {
|
||||
// 能量和带宽限制
|
||||
public static final long FEE_LIMIT = 10_000_000L; // 10 TRX
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
private static final BigInteger BASE = BigInteger.valueOf(58);
|
||||
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
private RestTemplate restTemplate = new RestTemplate();
|
||||
@Override
|
||||
public Integer grpcPort() {
|
||||
return 50051;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String grpcUrl() {
|
||||
return "grpc.shasta.trongrid.io";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String type() {
|
||||
return "shasta";
|
||||
}
|
||||
@Override
|
||||
public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
Map<String, Long> currentVotes = account.getVotesList().stream()
|
||||
.collect(Collectors.toMap(
|
||||
v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()),
|
||||
Common.Vote::getVoteCount
|
||||
));
|
||||
Iterator<Map.Entry<String, Long>> iterator = currentVotes.entrySet().iterator();
|
||||
BigDecimal bigDecimal = new BigDecimal(0);
|
||||
while (iterator.hasNext()) {
|
||||
bigDecimal = bigDecimal.add(new BigDecimal(iterator.next().getValue()));
|
||||
}
|
||||
return bigDecimal;
|
||||
}
|
||||
@Override
|
||||
public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr);
|
||||
List<ByteString> list = resourceAccountIndex.getToAccountsList();
|
||||
BigDecimal result = new BigDecimal(0);
|
||||
for (ByteString byteString : list) {
|
||||
String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray());
|
||||
String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(ownerAddr,address);
|
||||
int count = delegatedResourceList.getDelegatedResourceCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i);
|
||||
String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray());
|
||||
String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress));
|
||||
String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray());
|
||||
String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress));
|
||||
if (resourceCode == 0) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
} else if (resourceCode == 1) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
try {
|
||||
Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr);
|
||||
List<ByteString> list = resourceAccountIndex.getFromAccountsList();
|
||||
BigDecimal result = new BigDecimal(0);
|
||||
for (ByteString byteString : list) {
|
||||
String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray());
|
||||
String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress));
|
||||
Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(address, ownerAddr);
|
||||
int count = delegatedResourceList.getDelegatedResourceCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i);
|
||||
String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray());
|
||||
String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress));
|
||||
String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray());
|
||||
String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress));
|
||||
if(resourceCode == 0){
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}else if(resourceCode == 1){
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
result = result.add(divide);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}catch (Exception e){
|
||||
log.error(e.getMessage(),e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper(String privateKey) {
|
||||
ApiWrapper apiWrapper = ApiWrapper.ofShasta(privateKey);
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tronscanApiUrl() {
|
||||
return "https://shastapi.tronscan.org";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tronscanApiKey() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String usdtTrans(ApiWrapper api, String fromAddress, String toAddress, String amount) {
|
||||
try {
|
||||
// 获取合约地址信息
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, fromAddress, api);
|
||||
String transfer;
|
||||
// 获取转账账户的TRX余额
|
||||
BigInteger trc20Value = token.balanceOf(fromAddress);
|
||||
// 获取想要转账的数额
|
||||
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
|
||||
// 进行比较
|
||||
if (trc20Value.compareTo(sunAmountValue) >= 0) {
|
||||
// 设置最大矿工费用
|
||||
long feeLimit = Convert.toSun("2", Convert.Unit.TRX).longValue();
|
||||
//转账
|
||||
transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit);
|
||||
} else {
|
||||
return "error_error";
|
||||
}
|
||||
if (transfer == null || transfer.equals("")) {
|
||||
return "error_error";
|
||||
}
|
||||
return transfer;
|
||||
} catch (Exception ex) {
|
||||
String message = ex.getMessage();
|
||||
return "error_" + message;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
Chain.Transaction signTransaction = api.signTransaction(transaction);
|
||||
// 计算交易所需要的宽带
|
||||
long byteSize = api.estimateBandwidth(signTransaction);
|
||||
// long byteSize = api.estimateEnergy(signTransaction);
|
||||
// 广播交易
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getTRxBalance(ApiWrapper api, String address) {
|
||||
Long balance = api.getAccountBalance(address);
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(balance).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getUsdtBalance(ApiWrapper api, String address) {
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, address, api);
|
||||
BigInteger balanceOf = token.balanceOf(address);
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(balanceOf).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr) {
|
||||
ManagedChannel channel = ManagedChannelBuilder
|
||||
// .forAddress("grpc.trongrid.io", 50051)
|
||||
.forAddress(this.grpcUrl(), this.grpcPort())
|
||||
.usePlaintext()
|
||||
.build();
|
||||
WalletGrpc.WalletBlockingStub stub =
|
||||
WalletGrpc.newBlockingStub(channel);
|
||||
byte[] address = Base58Check.base58ToBytes(ownerAddr);
|
||||
Protocol.Account account = Protocol.Account.newBuilder()
|
||||
.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();
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
|
||||
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
@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();
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
}
|
||||
@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();
|
||||
Response.TransactionExtention transactionExtention = null;
|
||||
try {
|
||||
transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signTransaction = api.signTransaction(transactionExtention);
|
||||
String hashTx = api.broadcastTransaction(signTransaction);
|
||||
return hashTx;
|
||||
}
|
||||
@Override
|
||||
public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("TRON-PRO-API-KEY", "your_api_key");
|
||||
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<Void> entity = new HttpEntity<>(headers);
|
||||
ResponseEntity<TronAccountResp> result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class);
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
|
||||
if(null != result.getBody()){
|
||||
energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue());
|
||||
energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue());
|
||||
energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue());
|
||||
energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue());
|
||||
energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2());
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
energyAndBandwidthVo.setStakedTrxNum(divide.longValue());
|
||||
}else{
|
||||
energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0));
|
||||
energyAndBandwidthVo.setStakedTrxNum(0L);
|
||||
}
|
||||
return energyAndBandwidthVo;
|
||||
}
|
||||
@Override
|
||||
public long defaultEstimateBandwidth() {
|
||||
return 365;
|
||||
}
|
||||
@Override
|
||||
public boolean unstakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.unfreezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.cancelAllUnfreezeV2(ownerAddr);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean stakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) {
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
Response.TransactionExtention tx = null;
|
||||
try {
|
||||
tx = api.freezeBalanceV2(ownerAddr,
|
||||
balance.multiply(divisor).longValue(),
|
||||
resourceCode
|
||||
);
|
||||
} catch (IllegalException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal stakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Response.Account.FreezeV2 frozenV2 : account.getFrozenV2List()) {
|
||||
if (frozenV2.getType().getNumber() == resourceCode) {
|
||||
totalStakedSun += frozenV2.getAmount();
|
||||
}
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
public BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Response.Account.UnFreezeV2 frozenV2 : account.getUnfrozenV2List()) {
|
||||
if (frozenV2.getType().getNumber() == resourceCode) {
|
||||
totalStakedSun += frozenV2.getUnfreezeAmount();
|
||||
}
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
System.out.println(divide);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal voteBalance(ApiWrapper api, String ownerAddr) {
|
||||
Response.Account account = api.getAccount(ownerAddr);
|
||||
long totalStakedSun = 0;
|
||||
// ===== FrozenV2(当前主流质押方式)=====
|
||||
for (Common.Vote vote : account.getVotesList()) {
|
||||
totalStakedSun += vote.getVoteCount();
|
||||
}
|
||||
BigDecimal divisor = new BigDecimal("1000000");
|
||||
BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP);
|
||||
return divide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean autoVoteTop(ApiWrapper api, String ownerAddress, int size) throws IllegalException {
|
||||
// 1. 当前账户
|
||||
Response.Account account = api.getAccount(ownerAddress);
|
||||
long totalVotes = account.getFrozenV2List().stream()
|
||||
.mapToLong(Response.Account.FreezeV2::getAmount)
|
||||
.sum() / 1_000_000;
|
||||
if (totalVotes <= 0) {
|
||||
log.error("没有投票的vote");
|
||||
return false;
|
||||
}
|
||||
Map<String, Long> currentVotes = account.getVotesList().stream()
|
||||
.collect(Collectors.toMap(
|
||||
v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()),
|
||||
Common.Vote::getVoteCount
|
||||
));
|
||||
// 2. Top27 SR
|
||||
Response.WitnessList witnesses = api.listWitnesses();
|
||||
Set<String> top27 = witnesses.getWitnessesList().stream()
|
||||
.sorted(Comparator.comparingLong(w -> -w.getVoteCount()))
|
||||
.limit(size + 1)
|
||||
.map(w -> Base58Check.bytesToBase58(w.getAddress().toByteArray()))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// 3. 找出掉出 Top27 的 SR
|
||||
boolean needRevote = currentVotes.keySet().stream()
|
||||
.anyMatch(sr -> !top27.contains(sr));
|
||||
Iterator<String> iterator = currentVotes.keySet().iterator();
|
||||
org.tron.protos.Contract.VoteWitnessContract.Builder builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder()
|
||||
.setOwnerAddress(ApiWrapper.parseAddress(ownerAddress));
|
||||
boolean cancle = false;
|
||||
while (iterator.hasNext()) {
|
||||
String address = iterator.next();
|
||||
if (!top27.contains(address)) {
|
||||
builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(address))
|
||||
.setVoteCount(1));
|
||||
cancle = true;
|
||||
}
|
||||
}
|
||||
if (cancle) {
|
||||
org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build();
|
||||
Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract,
|
||||
Chain.Transaction.Contract.ContractType.VoteWitnessContract);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
}
|
||||
if (!needRevote) {
|
||||
log.info("All SRs still in Top27.");
|
||||
return true;
|
||||
}
|
||||
// 4. 总投票权
|
||||
List<String> backupSRs = new ArrayList<>();
|
||||
// 5. 构建新投票(平均投到备用 SR)
|
||||
backupSRs.addAll(top27.stream().sorted().collect(Collectors.toList()).subList(0, size));
|
||||
long perSRVotes = totalVotes / backupSRs.size();
|
||||
builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder()
|
||||
.setOwnerAddress(ApiWrapper.parseAddress(ownerAddress));
|
||||
for (String sr : backupSRs) {
|
||||
builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(sr)).setVoteCount(perSRVotes));
|
||||
}
|
||||
org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build();
|
||||
Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract,
|
||||
Chain.Transaction.Contract.ContractType.VoteWitnessContract);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean autoGetReward(ApiWrapper api, String ownerAddr) throws IllegalException {
|
||||
org.tron.trident.api.GrpcAPI.NumberMessage reward = api.getRewardInfo(ownerAddr, NodeType.FULL_NODE);
|
||||
log.info("Unclaimed reward: " + reward.getNum() / 1_000_000.0 + " TRX");
|
||||
Response.TransactionExtention tx = api.withdrawBalance(ownerAddr);
|
||||
Chain.Transaction signedTx = api.signTransaction(tx);
|
||||
api.broadcastTransaction(signedTx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) {
|
||||
try {
|
||||
BigInteger amountInSun =
|
||||
amount
|
||||
.multiply(BigDecimal.valueOf(1_000_000))
|
||||
.toBigInteger();
|
||||
Function function = new Function(
|
||||
"approve",
|
||||
Arrays.asList(
|
||||
new Address(spenderAddress),
|
||||
new Uint256(amountInSun)
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ownerAddr,
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
|
||||
function
|
||||
).setFeeLimit(FEE_LIMIT).build();
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
Response.TransactionReturn ret = api.blockingStub.broadcastTransaction(signedTxn);
|
||||
return ret.getResult();
|
||||
} catch (Exception e) {
|
||||
log.error("授权异常: " + e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigDecimal getAllowance(ApiWrapper api, String ownerAddress, String spenderAddress) {
|
||||
// Trc20合约地址
|
||||
Contract contract = api.getContract(contractAddress());
|
||||
Trc20Contract token = new Trc20Contract(contract, ownerAddress, api);
|
||||
try {
|
||||
// 查询授权额度
|
||||
BigInteger allowance = token.allowance(ownerAddress, spenderAddress);
|
||||
|
||||
// 如果是USDT等6位小数代币
|
||||
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
|
||||
return new BigDecimal(allowanceInToken);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new BigDecimal(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 构建 transferFrom 函数
|
||||
Function function = new Function(
|
||||
"transferFrom",
|
||||
Arrays.asList(
|
||||
new Address(fromAddress), // 转出地址
|
||||
new Address(toAddress), // 接收地址
|
||||
new Uint256(amountInSun) // 转账金额
|
||||
),
|
||||
Collections.emptyList()
|
||||
);
|
||||
|
||||
|
||||
String encodedFunction = FunctionEncoder.encode(function);
|
||||
System.out.println("编码后的函数: " + encodedFunction);
|
||||
|
||||
// 触发智能合约调用
|
||||
Chain.Transaction txnExtension = api.triggerCall(
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址
|
||||
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
|
||||
function
|
||||
).setFeeLimit(FEE_LIMIT).build();
|
||||
// 签名交易
|
||||
Chain.Transaction signedTxn = api.signTransaction(txnExtension);
|
||||
// 广播交易
|
||||
String ret = api.broadcastTransaction(signedTxn);
|
||||
log.info(ret);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("transferFrom 异常: " + e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TronAccountItem createTronAddress() {
|
||||
ECKey eCkey = new ECKey(random);
|
||||
String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes());
|
||||
byte[] addressBytes = eCkey.getAddress();
|
||||
String hexAddress = ByteArray.toHexString(addressBytes);
|
||||
TronAccountItem tronAccount = new TronAccountItem();
|
||||
tronAccount.setAddress(toViewAddress(hexAddress));
|
||||
tronAccount.setHexAddress(hexAddress);
|
||||
tronAccount.setPrivateKey(privateKey);
|
||||
//String privateKeyBase58 = org.spongycastle.util.encoders.Hex.e(base58Str);
|
||||
String privateKeyBase58 = encode58Check(eCkey.getPrivKeyBytes());
|
||||
tronAccount.setPrivateKeyBase58(privateKeyBase58);
|
||||
return tronAccount;
|
||||
}
|
||||
private static byte[] keccak256(byte[] input) {
|
||||
Keccak.Digest256 digest = new Keccak.Digest256();
|
||||
return digest.digest(input);
|
||||
}
|
||||
|
||||
private String formatHDPath(HDPath path) {
|
||||
StringBuilder sb = new StringBuilder("m");
|
||||
for (ChildNumber cn : path) {
|
||||
sb.append("/");
|
||||
sb.append(cn.isHardened() ? cn.num() + "'" : cn.num());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String base58CheckEncode(byte[] input) throws NoSuchAlgorithmException {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash1 = digest.digest(input);
|
||||
byte[] hash2 = digest.digest(hash1);
|
||||
|
||||
byte[] checksum = Arrays.copyOfRange(hash2, 0, 4);
|
||||
|
||||
byte[] result = new byte[input.length + 4];
|
||||
System.arraycopy(input, 0, result, 0, input.length);
|
||||
System.arraycopy(checksum, 0, result, input.length, 4);
|
||||
|
||||
return encode(result);
|
||||
}
|
||||
|
||||
public String encode(byte[] input) {
|
||||
BigInteger bi = new BigInteger(1, input);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (bi.compareTo(BigInteger.ZERO) > 0) {
|
||||
BigInteger[] div = bi.divideAndRemainder(BASE);
|
||||
sb.append(ALPHABET[div[1].intValue()]);
|
||||
bi = div[0];
|
||||
}
|
||||
for (byte b : input) {
|
||||
if (b == 0) {
|
||||
sb.append(ALPHABET[0]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.reverse().toString();
|
||||
}
|
||||
@Override
|
||||
public TronAccount createTronWallet(Integer site) {
|
||||
TronAccount result = new TronAccount();
|
||||
// 1. 生成随机助记词(12个)
|
||||
SecureRandom random = new SecureRandom();
|
||||
byte[] entropy = new byte[16]; // 128-bit entropy
|
||||
random.nextBytes(entropy);
|
||||
List<String> mnemonicWords = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||
|
||||
// 可以使用助记词恢复公私钥和钱包地址
|
||||
/*String mnemonicStr = "elder trend clay accuse joke pizza extend holiday spread apple dress mercy";
|
||||
List<String> mnemonicWords = Arrays.stream(mnemonicStr.split(" ")).collect(Collectors.toList());*/
|
||||
|
||||
String mnemonic = String.join(" ", mnemonicWords);
|
||||
result.setPhrase(mnemonic);
|
||||
// 2. 创建 DeterministicSeed 和 KeyChain
|
||||
DeterministicSeed seed = DeterministicSeed.ofMnemonic(mnemonicWords, "");
|
||||
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
|
||||
|
||||
// 3. 使用 TRON 路径 m/44'/195'/0'/0/i
|
||||
HDPath basePath = HDPath.M().extend(
|
||||
new ChildNumber(44, true),
|
||||
new ChildNumber(195, true),
|
||||
new ChildNumber(0, true),
|
||||
ChildNumber.ZERO
|
||||
);
|
||||
|
||||
List<TronAccountItem> list = new ArrayList<>();
|
||||
for (int i = 0; i < site; i++) {
|
||||
HDPath path = basePath.extend(new ChildNumber(i, false));
|
||||
DeterministicKey key = keyChain.getKeyByPath(path, true);
|
||||
byte[] privateKey = key.getPrivKeyBytes();
|
||||
byte[] pubKeyCompressed = key.getPubKey(); // 压缩公钥(33字节)
|
||||
ECPoint pubKeyPoint = key.getPubKeyPoint();
|
||||
byte[] pubKeyUnCompressed = pubKeyPoint.getEncoded(false); // 非压缩公钥(65字节)
|
||||
byte[] pubKeyWithoutPrefix = Arrays.copyOfRange(pubKeyUnCompressed, 1, pubKeyUnCompressed.length);
|
||||
byte[] keccakHash = keccak256(pubKeyWithoutPrefix);
|
||||
byte[] addressBytes = new byte[21];
|
||||
addressBytes[0] = (byte) 0x41;
|
||||
System.arraycopy(keccakHash, 12, addressBytes, 1, 20);
|
||||
String base58Address = null;
|
||||
try {
|
||||
base58Address = base58CheckEncode(addressBytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
String pathStr = formatHDPath(path);
|
||||
TronAccountItem item = new TronAccountItem();
|
||||
item.setAddress(base58Address);
|
||||
item.setPrivateKey(Hex.toHexString(privateKey));
|
||||
item.setPubKeyCompressed(Hex.toHexString(pubKeyCompressed));
|
||||
item.setPubKeyUnCompressed(Hex.toHexString(pubKeyUnCompressed));
|
||||
item.setPath(pathStr);
|
||||
String hexAddress = ByteArray.toHexString(addressBytes);
|
||||
item.setHexAddress(hexAddress);
|
||||
String privateKeyBase58 = encode58Check(privateKey);
|
||||
item.setPrivateKeyBase58(privateKeyBase58);
|
||||
|
||||
list.add(item);
|
||||
}
|
||||
result.setItems(list);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the energy required for the successful execution of smart contract transactions
|
||||
* This API is closed by default in tron node.
|
||||
* To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant
|
||||
* must be enabled in the node configuration file at the same time.
|
||||
* @param api
|
||||
* @param owner
|
||||
* @param toAddress
|
||||
* @param amount
|
||||
* @return
|
||||
*/
|
||||
@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();
|
||||
Function function = new Function(
|
||||
"transfer(address,uint256)",
|
||||
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
|
||||
);
|
||||
return estimate.getEnergyRequired();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long defaultEstimateEnergy() {
|
||||
return 20000L;
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
// 创建交易
|
||||
Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount);
|
||||
// 签名交易
|
||||
Chain.Transaction signTransaction = api.signTransaction(transaction);
|
||||
// 计算交易所需要的宽带
|
||||
return api.estimateBandwidth(signTransaction);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(),e);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成T开头的地址
|
||||
*
|
||||
* @param hexAddress
|
||||
* @return
|
||||
*/
|
||||
private String toViewAddress(String hexAddress) {
|
||||
return encode58Check(ByteArray.fromHexString(hexAddress));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 hash of the given bytes.
|
||||
*
|
||||
* @param input the bytes to hash
|
||||
* @return the hash (in big-endian order)
|
||||
*/
|
||||
public byte[] hash(boolean isSha256, byte[] input) throws NoSuchAlgorithmException {
|
||||
return hash(isSha256, input, 0, input.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 hash of the given byte range.
|
||||
*
|
||||
* @param input the array containing the bytes to hash
|
||||
* @param offset the offset within the array of the bytes to hash
|
||||
* @param length the number of bytes to hash
|
||||
* @return the hash (in big-endian order)
|
||||
*/
|
||||
public byte[] hash(boolean isSha256, byte[] input, int offset, int length) throws NoSuchAlgorithmException {
|
||||
if (isSha256) {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
digest.update(input, offset, length);
|
||||
return digest.digest();
|
||||
} else {
|
||||
SM3Digest digest = new SM3Digest();
|
||||
digest.update(input, offset, length);
|
||||
byte[] eHash = new byte[digest.getDigestSize()];
|
||||
digest.doFinal(eHash, 0);
|
||||
return eHash;
|
||||
}
|
||||
}
|
||||
|
||||
private String encode58Check(byte[] input) {
|
||||
try {
|
||||
byte[] hash0 = hash(true, input);
|
||||
byte[] hash1 = hash(true, hash0);
|
||||
byte[] inputCheck = new byte[input.length + 4];
|
||||
System.arraycopy(input, 0, inputCheck, 0, input.length);
|
||||
System.arraycopy(hash1, 0, inputCheck, input.length, 4);
|
||||
return Base58.encode(inputCheck);
|
||||
} catch (Throwable t) {
|
||||
log.error(String.format("data error:%s", Hex.toHexString(input)), t);
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
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.UsdtAggregationTaskItem;
|
||||
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
|
||||
import com.ruoyi.system.mapper.UsdtAggregationTaskItemMapper;
|
||||
import com.ruoyi.system.service.IUsdtAggregationTaskItemService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
/**
|
||||
* 归集任务明细Service业务层处理
|
||||
*
|
||||
* @author luqj
|
||||
* @date 2026-01-01
|
||||
*/
|
||||
@Service
|
||||
public class UsdtAggregationTaskItemServiceImpl extends ServiceImpl<UsdtAggregationTaskItemMapper, UsdtAggregationTaskItemPlus> implements IUsdtAggregationTaskItemService
|
||||
{
|
||||
@Autowired
|
||||
private UsdtAggregationTaskItemMapper usdtAggregationTaskItemMapper;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskItemPlus> getByIds(List<Long> ids ,boolean isUser, SFunction<UsdtAggregationTaskItemPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskItemPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
|
||||
.select(columns).in(UsdtAggregationTaskItemPlus::getId, ids);
|
||||
if(isUser){
|
||||
lambdaQueryWrapper.eq(UsdtAggregationTaskItemPlus::getUserId, SecurityUtils.getUserId());
|
||||
}
|
||||
List<UsdtAggregationTaskItemPlus> list = this.list(lambdaQueryWrapper);
|
||||
if(isUser){
|
||||
checkUserPlus(list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
private void checkUserPlus(List<UsdtAggregationTaskItemPlus> list) {
|
||||
for (UsdtAggregationTaskItemPlus item : list){
|
||||
if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
}
|
||||
private void checkUser(List<UsdtAggregationTaskItem> list) {
|
||||
for (UsdtAggregationTaskItem item : list){
|
||||
if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
}
|
||||
private void checkUser(UsdtAggregationTaskItemPlus item) {
|
||||
if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
private void checkUser(UsdtAggregationTaskItem item) {
|
||||
if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public List<SelectItem> select(String keyword,boolean isUser) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskItemPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
|
||||
.select(UsdtAggregationTaskItemPlus::getId,UsdtAggregationTaskItemPlus::getUserId, UsdtAggregationTaskItemPlus::getRemark)
|
||||
.like(UsdtAggregationTaskItemPlus::getRemark, keyword);
|
||||
if(isUser){
|
||||
lambdaQueryWrapper.eq(UsdtAggregationTaskItemPlus::getUserId, SecurityUtils.getUserId());
|
||||
}
|
||||
List<UsdtAggregationTaskItemPlus> list = this.list(lambdaQueryWrapper);
|
||||
if(isUser){
|
||||
checkUserPlus(list);
|
||||
}
|
||||
List<SelectItem> result =new ArrayList<>();
|
||||
for (UsdtAggregationTaskItemPlus item : list){
|
||||
SelectItem selectItem = new SelectItem();
|
||||
selectItem.setName(item.getRemark());
|
||||
selectItem.setId(item.getId());
|
||||
result.add(selectItem);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public UsdtAggregationTaskItemPlus getById(Long id, SFunction<UsdtAggregationTaskItemPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskItemPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
|
||||
.select(columns).eq(UsdtAggregationTaskItemPlus::getId, id);
|
||||
return baseMapper.selectOne(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, UsdtAggregationTaskItemPlus> getMapByIds(List<Long> ids, SFunction<UsdtAggregationTaskItemPlus, ?>... columns) {
|
||||
List<UsdtAggregationTaskItemPlus> list = this.getByIds(ids,false, columns);
|
||||
Map<Long, UsdtAggregationTaskItemPlus> map = new HashMap<>();
|
||||
for (UsdtAggregationTaskItemPlus item : list) {
|
||||
map.put(item.getId(), item);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskItemPlus> getListByStatusAndParentId(Integer status, Long parentId) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskItemPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
|
||||
.eq(UsdtAggregationTaskItemPlus::getStatus, status)
|
||||
.eq(UsdtAggregationTaskItemPlus::getParentId, parentId);
|
||||
return list(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, UsdtAggregationTaskItemPlus> getMapByIds(List<Long> ids) {
|
||||
List<UsdtAggregationTaskItemPlus> list = this.getByIds(ids);
|
||||
Map<Long, UsdtAggregationTaskItemPlus> map = new HashMap<>();
|
||||
for (UsdtAggregationTaskItemPlus item : list) {
|
||||
map.put(item.getId(), item);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskItemPlus> getByIds(List<Long> ids) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskItemPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>().in(UsdtAggregationTaskItemPlus::getId, ids);
|
||||
return this.list(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
public <T> T sum(String field, String where, Class<T> tClass) {
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append("select ");
|
||||
stringBuffer.append(" sum(" + field + ") as total ");
|
||||
stringBuffer.append(" from usdt_aggregation_task_item ");
|
||||
if (StringUtils.isNotBlank(where)) {
|
||||
stringBuffer.append(" where ");
|
||||
stringBuffer.append(where);
|
||||
}
|
||||
T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass);
|
||||
return result;
|
||||
}
|
||||
|
||||
public Long count(String where) {
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append("select ");
|
||||
stringBuffer.append(" count(1)");
|
||||
stringBuffer.append(" from ");
|
||||
stringBuffer.append(" usdt_aggregation_task_item ");
|
||||
if (StringUtils.isNotBlank(where)) {
|
||||
stringBuffer.append(" where ");
|
||||
stringBuffer.append(where);
|
||||
}
|
||||
Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class);
|
||||
return result;
|
||||
}
|
||||
|
||||
public <T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass) {
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append("select ");
|
||||
stringBuffer.append(select);
|
||||
stringBuffer.append(" from ");
|
||||
stringBuffer.append(" usdt_aggregation_task_item ");
|
||||
if (StringUtils.isNotBlank(where)) {
|
||||
stringBuffer.append(" where ");
|
||||
stringBuffer.append(where);
|
||||
}
|
||||
stringBuffer.append(" group by ");
|
||||
stringBuffer.append(groupby);
|
||||
List result = jdbcTemplate.queryForList(stringBuffer.toString());
|
||||
List<T> tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass);
|
||||
return tList;
|
||||
}
|
||||
/**
|
||||
* 查询归集任务明细
|
||||
*
|
||||
* @param id 归集任务明细ID
|
||||
* @return 归集任务明细
|
||||
*/
|
||||
@Override
|
||||
public UsdtAggregationTaskItem selectUsdtAggregationTaskItemById(Long id,boolean isUser)
|
||||
{
|
||||
UsdtAggregationTaskItem vo = usdtAggregationTaskItemMapper.selectUsdtAggregationTaskItemById(id);
|
||||
if(isUser){
|
||||
checkUser(vo);
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询归集任务明细列表
|
||||
*
|
||||
* @param usdtAggregationTaskItem 归集任务明细
|
||||
* @return 归集任务明细
|
||||
*/
|
||||
@Override
|
||||
public List<UsdtAggregationTaskItem> selectUsdtAggregationTaskItemList(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser)
|
||||
{
|
||||
if(usdtAggregationTaskItem == null){
|
||||
usdtAggregationTaskItem = new UsdtAggregationTaskItem();
|
||||
}
|
||||
if(isUser){
|
||||
usdtAggregationTaskItem.setUserId(SecurityUtils.getUserId());
|
||||
}
|
||||
List<UsdtAggregationTaskItem> list = usdtAggregationTaskItemMapper.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem);
|
||||
if(isUser){
|
||||
checkUser(list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增归集任务明细
|
||||
*
|
||||
* @param usdtAggregationTaskItem 归集任务明细
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int insertUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser)
|
||||
{
|
||||
usdtAggregationTaskItem.setCreatedAt(DateUtils.getNowDate());
|
||||
usdtAggregationTaskItem.setUpdatedAt(DateUtils.getNowDate());
|
||||
if(isUser){
|
||||
usdtAggregationTaskItem.setUserId(SecurityUtils.getUserId());
|
||||
}
|
||||
return usdtAggregationTaskItemMapper.insertUsdtAggregationTaskItem(usdtAggregationTaskItem);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改归集任务明细
|
||||
*
|
||||
* @param usdtAggregationTaskItem 归集任务明细
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int updateUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser)
|
||||
{
|
||||
usdtAggregationTaskItem.setUpdatedAt(DateUtils.getNowDate());
|
||||
if(isUser){
|
||||
checkUser(usdtAggregationTaskItem);
|
||||
}
|
||||
return usdtAggregationTaskItemMapper.updateUsdtAggregationTaskItem(usdtAggregationTaskItem);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除归集任务明细
|
||||
*
|
||||
* @param ids 需要删除的归集任务明细ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int deleteUsdtAggregationTaskItemByIds(Long[] ids,boolean isUser)
|
||||
{
|
||||
if(isUser){
|
||||
List<UsdtAggregationTaskItemPlus> list= getByIds(Arrays.asList(ids),false,UsdtAggregationTaskItemPlus::getUserId,UsdtAggregationTaskItemPlus::getId);
|
||||
checkUserPlus(list);
|
||||
}
|
||||
return usdtAggregationTaskItemMapper.deleteUsdtAggregationTaskItemByIds(ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除归集任务明细信息
|
||||
*
|
||||
* @param id 归集任务明细ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int deleteUsdtAggregationTaskItemById(Long id,boolean isUser)
|
||||
{
|
||||
if(isUser){
|
||||
UsdtAggregationTaskItemPlus vo = getById(id,UsdtAggregationTaskItemPlus::getUserId,UsdtAggregationTaskItemPlus::getId);
|
||||
checkUser(vo);
|
||||
}
|
||||
return usdtAggregationTaskItemMapper.deleteUsdtAggregationTaskItemById(id);
|
||||
}
|
||||
}
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
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.mapper.UsdtAggregationTaskMapper;
|
||||
import com.ruoyi.system.service.*;
|
||||
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.*;
|
||||
|
||||
/**
|
||||
* 归集任务Service业务层处理
|
||||
*
|
||||
* @author luqj
|
||||
* @date 2026-01-01
|
||||
*/
|
||||
@Service
|
||||
public class UsdtAggregationTaskServiceImpl extends ServiceImpl<UsdtAggregationTaskMapper, UsdtAggregationTaskPlus> implements IUsdtAggregationTaskService {
|
||||
@Autowired
|
||||
private UsdtAggregationTaskMapper usdtAggregationTaskMapper;
|
||||
@Autowired
|
||||
private ITronService tronService;
|
||||
@Autowired
|
||||
private IUsdtAggregationTaskItemService usdtAggregationTaskItemService;
|
||||
@Autowired
|
||||
private IAppsService appsService;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
@Autowired
|
||||
private IWeb3WalletService web3WalletService;
|
||||
@Autowired
|
||||
private IWalletAddressService walletAddressService;
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskPlus> getByIds(List<Long> ids, boolean isUser, SFunction<UsdtAggregationTaskPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskPlus>()
|
||||
.select(columns).in(UsdtAggregationTaskPlus::getId, ids);
|
||||
if (isUser) {
|
||||
lambdaQueryWrapper.eq(UsdtAggregationTaskPlus::getUserId, SecurityUtils.getUserId());
|
||||
}
|
||||
List<UsdtAggregationTaskPlus> list = this.list(lambdaQueryWrapper);
|
||||
if (isUser) {
|
||||
checkUserPlus(list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private void checkUserPlus(List<UsdtAggregationTaskPlus> list) {
|
||||
for (UsdtAggregationTaskPlus item : list) {
|
||||
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void checkUser(List<UsdtAggregationTask> list) {
|
||||
for (UsdtAggregationTask item : list) {
|
||||
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void checkUser(UsdtAggregationTaskPlus item) {
|
||||
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
|
||||
private void checkUser(UsdtAggregationTask item) {
|
||||
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
|
||||
throw new RuntimeException("无权限");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SelectItem> select(String keyword, boolean isUser) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskPlus>()
|
||||
.select(UsdtAggregationTaskPlus::getId, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getTaskName)
|
||||
.like(UsdtAggregationTaskPlus::getTaskName, keyword);
|
||||
if (isUser) {
|
||||
lambdaQueryWrapper.eq(UsdtAggregationTaskPlus::getUserId, SecurityUtils.getUserId());
|
||||
}
|
||||
List<UsdtAggregationTaskPlus> list = this.list(lambdaQueryWrapper);
|
||||
if (isUser) {
|
||||
checkUserPlus(list);
|
||||
}
|
||||
List<SelectItem> result = new ArrayList<>();
|
||||
for (UsdtAggregationTaskPlus item : list) {
|
||||
SelectItem selectItem = new SelectItem();
|
||||
selectItem.setName(item.getTaskName());
|
||||
selectItem.setId(item.getId());
|
||||
result.add(selectItem);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskPlus> getListByStatusAndLtExeTime(Integer status, Date gtExeTime) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskPlus>()
|
||||
.eq(UsdtAggregationTaskPlus::getStatus, status).lt(UsdtAggregationTaskPlus::getExeTime, gtExeTime);
|
||||
return list(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UsdtAggregationTaskPlus getById(Long id, SFunction<UsdtAggregationTaskPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskPlus>()
|
||||
.select(columns).eq(UsdtAggregationTaskPlus::getId, id);
|
||||
return baseMapper.selectOne(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, UsdtAggregationTaskPlus> getMapByIds(List<Long> ids, SFunction<UsdtAggregationTaskPlus, ?>... columns) {
|
||||
List<UsdtAggregationTaskPlus> list = this.getByIds(ids, false, columns);
|
||||
Map<Long, UsdtAggregationTaskPlus> map = new HashMap<>();
|
||||
for (UsdtAggregationTaskPlus item : list) {
|
||||
map.put(item.getId(), item);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, UsdtAggregationTaskPlus> getMapByIds(List<Long> ids) {
|
||||
List<UsdtAggregationTaskPlus> list = this.getByIds(ids);
|
||||
Map<Long, UsdtAggregationTaskPlus> map = new HashMap<>();
|
||||
for (UsdtAggregationTaskPlus item : list) {
|
||||
map.put(item.getId(), item);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UsdtAggregationTaskPlus> getByIds(List<Long> ids) {
|
||||
LambdaQueryWrapper<UsdtAggregationTaskPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskPlus>().in(UsdtAggregationTaskPlus::getId, ids);
|
||||
return this.list(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
public <T> T sum(String field, String where, Class<T> tClass) {
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append("select ");
|
||||
stringBuffer.append(" sum(" + field + ") as total ");
|
||||
stringBuffer.append(" from usdt_aggregation_task ");
|
||||
if (StringUtils.isNotBlank(where)) {
|
||||
stringBuffer.append(" where ");
|
||||
stringBuffer.append(where);
|
||||
}
|
||||
T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass);
|
||||
return result;
|
||||
}
|
||||
|
||||
public Long count(String where) {
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append("select ");
|
||||
stringBuffer.append(" count(1)");
|
||||
stringBuffer.append(" from ");
|
||||
stringBuffer.append(" usdt_aggregation_task ");
|
||||
if (StringUtils.isNotBlank(where)) {
|
||||
stringBuffer.append(" where ");
|
||||
stringBuffer.append(where);
|
||||
}
|
||||
Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class);
|
||||
return result;
|
||||
}
|
||||
|
||||
public <T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass) {
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append("select ");
|
||||
stringBuffer.append(select);
|
||||
stringBuffer.append(" from ");
|
||||
stringBuffer.append(" usdt_aggregation_task ");
|
||||
if (StringUtils.isNotBlank(where)) {
|
||||
stringBuffer.append(" where ");
|
||||
stringBuffer.append(where);
|
||||
}
|
||||
stringBuffer.append(" group by ");
|
||||
stringBuffer.append(groupby);
|
||||
List result = jdbcTemplate.queryForList(stringBuffer.toString());
|
||||
List<T> tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass);
|
||||
return tList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询归集任务
|
||||
*
|
||||
* @param id 归集任务ID
|
||||
* @return 归集任务
|
||||
*/
|
||||
@Override
|
||||
public UsdtAggregationTask selectUsdtAggregationTaskById(Long id, boolean isUser) {
|
||||
UsdtAggregationTask vo = usdtAggregationTaskMapper.selectUsdtAggregationTaskById(id);
|
||||
if (isUser) {
|
||||
checkUser(vo);
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询归集任务列表
|
||||
*
|
||||
* @param usdtAggregationTask 归集任务
|
||||
* @return 归集任务
|
||||
*/
|
||||
@Override
|
||||
public List<UsdtAggregationTask> selectUsdtAggregationTaskList(UsdtAggregationTask usdtAggregationTask, boolean isUser) {
|
||||
if (usdtAggregationTask == null) {
|
||||
usdtAggregationTask = new UsdtAggregationTask();
|
||||
}
|
||||
if (isUser) {
|
||||
usdtAggregationTask.setUserId(SecurityUtils.getUserId());
|
||||
}
|
||||
List<UsdtAggregationTask> list = usdtAggregationTaskMapper.selectUsdtAggregationTaskList(usdtAggregationTask);
|
||||
if (isUser) {
|
||||
checkUser(list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增归集任务
|
||||
*
|
||||
* @param usdtAggregationTask 归集任务
|
||||
* @return 结果
|
||||
*/
|
||||
@Transactional
|
||||
@Override
|
||||
public int insertUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask, boolean isUser) {
|
||||
usdtAggregationTask.setCreatedAt(DateUtils.getNowDate());
|
||||
usdtAggregationTask.setUpdatedAt(DateUtils.getNowDate());
|
||||
if (isUser) {
|
||||
usdtAggregationTask.setUserId(SecurityUtils.getUserId());
|
||||
if (usdtAggregationTask.getAppId() == null) {
|
||||
throw new RuntimeException("AppId为空");
|
||||
}
|
||||
AppsPlus apps = this.appsService.getById(usdtAggregationTask.getAppId());
|
||||
if (apps == null) {
|
||||
throw new RuntimeException("App为空");
|
||||
}
|
||||
if (SecurityUtils.getUserId() == null) {
|
||||
throw new RuntimeException("没有登入");
|
||||
}
|
||||
if (usdtAggregationTask.getExeTime() == null) {
|
||||
throw new RuntimeException("执行时间为空");
|
||||
}
|
||||
if (apps.getUserId().longValue() != SecurityUtils.getUserId()) {
|
||||
throw new RuntimeException("没有权限");
|
||||
}
|
||||
Web3WalletPlus web3WalletPlus = web3WalletService.getById(SecurityUtils.getUserId());
|
||||
if (web3WalletPlus.getUsdtBalance().subtract(usdtAggregationTask.getTotalAmount()).longValue() < 0) {
|
||||
throw new RuntimeException("超过账户金额");
|
||||
}
|
||||
if (usdtAggregationTask.getTaskName() == null) {
|
||||
throw new RuntimeException("任务名称为空");
|
||||
}
|
||||
if (usdtAggregationTask.getTotalAmount() == null || usdtAggregationTask.getTotalAmount().longValue() <= 0) {
|
||||
throw new RuntimeException("归集金额为空");
|
||||
}
|
||||
if (usdtAggregationTask.getExeTime() == null) {
|
||||
usdtAggregationTask.setExeTime(DateUtils.getNowDate());
|
||||
}
|
||||
usdtAggregationTask.setUserId(SecurityUtils.getUserId());
|
||||
usdtAggregationTask.setDistTokenAddress(apps.getDistTokenAddress());
|
||||
usdtAggregationTask.setVerifyStatus(1);
|
||||
usdtAggregationTask.setStatus(0);
|
||||
List<WalletAddressPlus> list = walletAddressService.getListByAppId(usdtAggregationTask.getAppId());
|
||||
list.sort(new Comparator<WalletAddressPlus>() {
|
||||
@Override
|
||||
public int compare(WalletAddressPlus p1, WalletAddressPlus p2) {
|
||||
return Double.compare(p2.getWithdrawUsdtBalance().doubleValue(), p1.getWithdrawUsdtBalance().doubleValue()); // 倒序排序
|
||||
}
|
||||
});
|
||||
String willTxAmount = this.sum("total_amount","status = 0 and verify_status=1 and user_id="+usdtAggregationTask.getUserId(),String.class);
|
||||
if(willTxAmount == null){
|
||||
willTxAmount ="0.00";
|
||||
}
|
||||
if(new BigDecimal(willTxAmount).add(usdtAggregationTask.getTotalAmount())
|
||||
.subtract(web3WalletPlus.getUsdtBalance()).doubleValue()>0){
|
||||
throw new RuntimeException("待提现金额超过账户金额");
|
||||
}
|
||||
LambdaQueryWrapper<UsdtAggregationTaskPlus> lambdaQueryWrapper = new LambdaQueryWrapper<UsdtAggregationTaskPlus>()
|
||||
.eq(UsdtAggregationTaskPlus::getAppId, usdtAggregationTask.getAppId())
|
||||
.eq(UsdtAggregationTaskPlus::getUserId,usdtAggregationTask.getUserId())
|
||||
.eq(UsdtAggregationTaskPlus::getStatus,0);
|
||||
if(count(lambdaQueryWrapper) > 0){
|
||||
throw new RuntimeException("存在正在提现的记录");
|
||||
}
|
||||
|
||||
this.usdtAggregationTaskMapper.insertUsdtAggregationTask(usdtAggregationTask);
|
||||
BigDecimal totalAmount = usdtAggregationTask.getTotalAmount();
|
||||
List<UsdtAggregationTaskItemPlus> usdtAggregationTaskItems = new ArrayList<>();
|
||||
BigDecimal hasTxItem = new BigDecimal(0);
|
||||
for (WalletAddressPlus item : list) {
|
||||
if (item.getWithdrawUsdtBalance() == null) {
|
||||
item.setWithdrawUsdtBalance(new BigDecimal(0));
|
||||
}
|
||||
UsdtAggregationTaskItemPlus usdtAggregationTaskItem = new UsdtAggregationTaskItemPlus();
|
||||
usdtAggregationTaskItem.setUserId(SecurityUtils.getUserId());
|
||||
usdtAggregationTaskItem.setAppId(usdtAggregationTask.getAppId());
|
||||
usdtAggregationTaskItem.setCreatedAt(new Date());
|
||||
usdtAggregationTaskItem.setUpdatedAt(new Date());
|
||||
usdtAggregationTaskItem.setStatus(0);
|
||||
usdtAggregationTaskItem.setDistTokenAddress(usdtAggregationTask.getDistTokenAddress());
|
||||
usdtAggregationTaskItem.setParentId(usdtAggregationTask.getId());
|
||||
usdtAggregationTaskItem.setTokenAddress(item.getToken());
|
||||
|
||||
if (item.getEnergyNum() < tronService.defaultEstimateEnergy()) {
|
||||
log.error(item.getToken()+"能量不足,需要手续费");
|
||||
continue;
|
||||
}
|
||||
long bandwidth = tronService.defaultEstimateBandwidth();
|
||||
if (bandwidth > item.getBandwidthNum()) {
|
||||
log.error(item.getToken()+"带宽不足需要手续费");
|
||||
continue;
|
||||
}
|
||||
if(bandwidth > item.getBandwidthStakedNum()
|
||||
&& bandwidth > (item.getBandwidthNum()-item.getBandwidthStakedNum())){
|
||||
log.error("代理|免费带宽不足需要手续费");
|
||||
continue;
|
||||
}
|
||||
|
||||
String tempAmount = usdtAggregationTaskItemService.sum("ope_amount","status = 0 and token_address ='"+item.getToken()+"'",String.class);
|
||||
if(tempAmount ==null){
|
||||
tempAmount = "0.00";
|
||||
}
|
||||
if (item.getWithdrawUsdtBalance().subtract(totalAmount).longValue() > 0) {
|
||||
usdtAggregationTaskItem.setOpeAmount(totalAmount);
|
||||
usdtAggregationTaskItems.add(usdtAggregationTaskItem);
|
||||
hasTxItem = hasTxItem.add(item.getWithdrawUsdtBalance().subtract(new BigDecimal(tempAmount))
|
||||
.subtract(totalAmount));
|
||||
totalAmount = new BigDecimal(0);
|
||||
break;
|
||||
} else {
|
||||
usdtAggregationTaskItem.setOpeAmount(item.getWithdrawUsdtBalance());
|
||||
totalAmount = totalAmount.subtract(item.getWithdrawUsdtBalance());
|
||||
usdtAggregationTaskItems.add(usdtAggregationTaskItem);
|
||||
hasTxItem = hasTxItem.add(item.getWithdrawUsdtBalance().subtract(new BigDecimal(tempAmount))
|
||||
.subtract(item.getWithdrawUsdtBalance()));
|
||||
}
|
||||
}
|
||||
if (hasTxItem.doubleValue() < 0) {
|
||||
throw new RuntimeException("app下的地址可提现金额不足,amount=" + hasTxItem.toString());
|
||||
}
|
||||
if (totalAmount.longValue() > 0) {
|
||||
throw new RuntimeException("app下的地址可提现金额不足,amount=" + totalAmount.toString());
|
||||
}
|
||||
if (!usdtAggregationTaskItems.isEmpty()) {
|
||||
this.usdtAggregationTaskItemService.saveBatch(usdtAggregationTaskItems);
|
||||
}else{
|
||||
throw new RuntimeException("没有可以免费提现的地址");
|
||||
}
|
||||
return 1;
|
||||
} else {
|
||||
return usdtAggregationTaskMapper.insertUsdtAggregationTask(usdtAggregationTask);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改归集任务
|
||||
*
|
||||
* @param usdtAggregationTask 归集任务
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int updateUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask, boolean isUser) {
|
||||
usdtAggregationTask.setUpdatedAt(DateUtils.getNowDate());
|
||||
if (isUser) {
|
||||
checkUser(usdtAggregationTask);
|
||||
}
|
||||
return usdtAggregationTaskMapper.updateUsdtAggregationTask(usdtAggregationTask);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除归集任务
|
||||
*
|
||||
* @param ids 需要删除的归集任务ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int deleteUsdtAggregationTaskByIds(Long[] ids, boolean isUser) {
|
||||
if (isUser) {
|
||||
List<UsdtAggregationTaskPlus> list = getByIds(Arrays.asList(ids), false, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getId);
|
||||
checkUserPlus(list);
|
||||
}
|
||||
return usdtAggregationTaskMapper.deleteUsdtAggregationTaskByIds(ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除归集任务信息
|
||||
*
|
||||
* @param id 归集任务ID
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public int deleteUsdtAggregationTaskById(Long id, boolean isUser) {
|
||||
if (isUser) {
|
||||
UsdtAggregationTaskPlus vo = getById(id, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getId);
|
||||
checkUser(vo);
|
||||
}
|
||||
return usdtAggregationTaskMapper.deleteUsdtAggregationTaskById(id);
|
||||
}
|
||||
}
|
||||
+81
-2
@@ -10,12 +10,16 @@ import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.system.domain.WalletAddress;
|
||||
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.IWalletAddressService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
@@ -30,7 +34,8 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
private WalletAddressMapper walletAddressMapper;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Autowired
|
||||
private ITronService tronService;
|
||||
@Override
|
||||
public List<WalletAddressPlus> getByIds(List<Long> ids, boolean isUser, SFunction<WalletAddressPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>()
|
||||
@@ -73,6 +78,54 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateTronInfo(WalletAddressPlus walletAddressPlus) {
|
||||
ApiWrapper api = tronService.buildApiWrapper(walletAddressPlus.getTokenKey());
|
||||
BigDecimal amout = tronService.getUsdtBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setUsdtBalance(amout);
|
||||
amout = tronService.getTRxBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setTrxBalance(amout);
|
||||
EnergyAndBandwidthVo energyAndBandwidthVo = tronService.energyAndBandwidth(walletAddressPlus.getToken());
|
||||
walletAddressPlus.setEnergyNum(energyAndBandwidthVo.getEnergy().longValue());
|
||||
walletAddressPlus.setBandwidthNum(energyAndBandwidthVo.getBandwidth().longValue());
|
||||
amout = tronService.votedBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setVotedNum(amout.longValue());
|
||||
amout = tronService.stakedTrxBalance(api,walletAddressPlus.getToken(),1);
|
||||
walletAddressPlus.setEnergyStakedTrxNum(amout.longValue());
|
||||
amout = tronService.stakedTrxBalance(api,walletAddressPlus.getToken(),0);
|
||||
walletAddressPlus.setBandwidthStakedTrxNum(amout.longValue());
|
||||
energyAndBandwidthVo = tronService.allDelegatedDnergyAndBandwidth(walletAddressPlus.getToken());
|
||||
walletAddressPlus.setAcquiredDelegatedBandwidthValue(energyAndBandwidthVo.getAcquiredBandwidth());
|
||||
walletAddressPlus.setAcquiredDelegatedEnergyValue(energyAndBandwidthVo.getAcquiredEnergy());
|
||||
walletAddressPlus.setDelegatedBandwidthValue(energyAndBandwidthVo.getDelegateBandwidth());
|
||||
walletAddressPlus.setDelegatedEnergyValue(energyAndBandwidthVo.getDelegateEnergy());
|
||||
|
||||
amout = tronService.delegatedStakedTrxBalance(api,walletAddressPlus.getToken(),1);
|
||||
walletAddressPlus.setDelegatedEnergyTrxNum(amout.longValue());
|
||||
amout = tronService.delegatedStakedTrxBalance(api,walletAddressPlus.getToken(),0);
|
||||
walletAddressPlus.setDelegatedBandwidthTrxNum(amout.longValue());
|
||||
|
||||
amout = tronService.acquiredDelegatedStakedTrxBalance(api,walletAddressPlus.getToken(),1);
|
||||
walletAddressPlus.setAcquiredDelegatedEnergyTrxNum(amout.longValue());
|
||||
amout = tronService.acquiredDelegatedStakedTrxBalance(api,walletAddressPlus.getToken(),0);
|
||||
walletAddressPlus.setAcquiredDelegatedBandwidthTrxNum(amout.longValue());
|
||||
|
||||
amout = tronService.voteBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setVoteNum(amout.longValue()+walletAddressPlus.getDelegatedBandwidthTrxNum()+ walletAddressPlus.getDelegatedEnergyTrxNum());
|
||||
|
||||
walletAddressPlus.setStakedTrxNum(walletAddressPlus.getVoteNum());
|
||||
|
||||
if(walletAddressPlus.getStakedTrxNum() != energyAndBandwidthVo.getStakedTrxNum().longValue()){
|
||||
log.error("please check stakedTrxNum is true");
|
||||
walletAddressPlus.setStakedTrxNum(energyAndBandwidthVo.getStakedTrxNum());
|
||||
walletAddressPlus.setVoteNum(walletAddressPlus.getStakedTrxNum());
|
||||
}
|
||||
walletAddressPlus.setUpdatedAt(new Date());
|
||||
updateById(walletAddressPlus);
|
||||
api.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SelectItem> select(String keyword, boolean isUser) {
|
||||
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>()
|
||||
@@ -101,6 +154,25 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
.select(columns).eq(WalletAddressPlus::getId, id);
|
||||
return baseMapper.selectOne(lambdaQueryWrapper);
|
||||
}
|
||||
@Override
|
||||
public WalletAddressPlus getByTokenAndAppId(String token,Long appId, SFunction<WalletAddressPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
|
||||
if(null != columns || columns.length > 0){
|
||||
lambdaQueryWrapper.select(columns);
|
||||
}
|
||||
lambdaQueryWrapper.eq(WalletAddressPlus::getToken, token).eq(WalletAddressPlus::getAppId, appId);
|
||||
return baseMapper.selectOne(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<WalletAddressPlus> getListByAppId(Long appId, SFunction<WalletAddressPlus, ?>... columns) {
|
||||
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
|
||||
if(null != columns || columns.length > 0){
|
||||
lambdaQueryWrapper.select(columns);
|
||||
}
|
||||
lambdaQueryWrapper.eq(WalletAddressPlus::getAppId, appId);
|
||||
return baseMapper.selectList(lambdaQueryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, WalletAddressPlus> getMapByIds(List<Long> ids, SFunction<WalletAddressPlus, ?>... columns) {
|
||||
@@ -111,7 +183,14 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateWithdrawUsdtBalanceById(Long id, BigDecimal withdrawUsdtBalance){
|
||||
WalletAddressPlus walletAddressPlus = new WalletAddressPlus();
|
||||
walletAddressPlus.setWithdrawUsdtBalance(withdrawUsdtBalance);
|
||||
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
|
||||
lambdaQueryWrapper.eq(WalletAddressPlus::getId, id);
|
||||
return this.update(walletAddressPlus,lambdaQueryWrapper);
|
||||
}
|
||||
@Override
|
||||
public Map<Long, WalletAddressPlus> getMapByIds(List<Long> ids) {
|
||||
List<WalletAddressPlus> list = this.getByIds(ids);
|
||||
|
||||
+17
-4
@@ -15,10 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 钱包管理Service业务层处理
|
||||
@@ -178,6 +176,21 @@ public class Web3WalletServiceImpl extends ServiceImpl<Web3WalletMapper, Web3Wal
|
||||
*/
|
||||
@Override
|
||||
public List<Web3Wallet> selectWeb3WalletList(Web3Wallet web3Wallet, boolean isUser) {
|
||||
if (isUser) {
|
||||
Web3WalletPlus myWallet = this.getById(SecurityUtils.getUserId());
|
||||
if(myWallet == null){
|
||||
myWallet = new Web3WalletPlus();
|
||||
myWallet.setId(SecurityUtils.getUserId());
|
||||
myWallet.setPassword(UUID.randomUUID().toString());
|
||||
myWallet.setEthBalance(new BigDecimal(0));
|
||||
myWallet.setTrxBalance(new BigDecimal(0));
|
||||
myWallet.setUsdtBalance(new BigDecimal(0));
|
||||
myWallet.setCreatedAt(new Date());
|
||||
myWallet.setUpdatedAt(new Date());
|
||||
this.save(myWallet);
|
||||
}
|
||||
web3Wallet.setId(SecurityUtils.getUserId());
|
||||
}
|
||||
List<Web3Wallet> list = web3WalletMapper.selectWeb3WalletList(web3Wallet);
|
||||
if (isUser) {
|
||||
checkUser(list);
|
||||
|
||||
Reference in new issue
Block a user