This commit is contained in:
lu7213 committed 2026-03-03 09:39:33 +08:00
1 parent 68a2b4f68c
commit 7cd697187c
308 files changed
+30454 -75

No files matched your search

@@ -0,0 +1,23 @@
package com.ruoyi.system.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import org.code.modules.plugins.PluginBeanFactory;
import org.code.modules.plugins.service.IPluginTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/system/test")
public class TestPluginController {
@Autowired
private PluginBeanFactory pluginBeanFactory;
@GetMapping(value = "/testPlugin")
public AjaxResult testPlugin() {
IPluginTest pluginTest = pluginBeanFactory.getBean("pluginDemo", "1.0.0", IPluginTest.class);
System.out.println(pluginTest.funcExec("dd"));
return AjaxResult.success(pluginTest.funcExec("dd"));
}
}
@@ -0,0 +1,168 @@
package com.ruoyi.system.controller;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.select.Ids;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.UsdtAggregationTask;
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
import com.ruoyi.system.service.IUsdtAggregationTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 归集任务Controller
*
* @author luqj
* @date 2026-01-01
*/
@RestController
@RequestMapping("/system/usdtTask")
public class UsdtAggregationTaskController extends BaseController {
@Autowired
private IUsdtAggregationTaskService usdtAggregationTaskService;
@PreAuthorize("@ss.hasPermi('system:usdtTask:getByIds')")
@PostMapping("/getByIds")
public AjaxResult getByIds(@RequestBody Ids ids) {
List<UsdtAggregationTaskPlus> list = usdtAggregationTaskService.getByIds(ids.getLongIds(), false, UsdtAggregationTaskPlus::getTaskName, UsdtAggregationTaskPlus::getId);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-getByIds')")
@PostMapping("/user/getByIds")
public AjaxResult userGetByIds(@RequestBody Ids ids) {
List<UsdtAggregationTaskPlus> list = usdtAggregationTaskService.getByIds(ids.getLongIds(), true, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getTaskName, UsdtAggregationTaskPlus::getId);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:select')")
@GetMapping("/select")
public AjaxResult select(String keyword) {
List<SelectItem> list = usdtAggregationTaskService.select(keyword, false);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-select')")
@GetMapping("/user/select")
public AjaxResult userSelect(String keyword) {
List<SelectItem> list = usdtAggregationTaskService.select(keyword, true);
return AjaxResult.success(list);
}
/**
* 查询归集任务列表
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:list')")
@GetMapping("/list")
public TableDataInfo list(UsdtAggregationTask usdtAggregationTask) {
startPage();
List<UsdtAggregationTask> list = usdtAggregationTaskService.selectUsdtAggregationTaskList(usdtAggregationTask, false);
return getDataTable(list);
}
/**
* 查询归集任务列表
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-list')")
@GetMapping("/user/list")
public TableDataInfo userList(UsdtAggregationTask usdtAggregationTask) {
startPage();
List<UsdtAggregationTask> list = usdtAggregationTaskService.selectUsdtAggregationTaskList(usdtAggregationTask, true);
return getDataTable(list);
}
/**
* 导出归集任务列表
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:export')")
@Log(title = "归集任务", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(UsdtAggregationTask usdtAggregationTask) {
List<UsdtAggregationTask> list = usdtAggregationTaskService.selectUsdtAggregationTaskList(usdtAggregationTask, false);
ExcelUtil<UsdtAggregationTask> util = new ExcelUtil<UsdtAggregationTask>(UsdtAggregationTask.class);
return util.exportExcel(list, "usdtTask");
}
/**
* 获取归集任务详细信息
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(usdtAggregationTaskService.selectUsdtAggregationTaskById(id, false));
}
/**
* 获取归集任务详细信息
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-query')")
@GetMapping(value = "/user/{id}")
public AjaxResult userGetInfo(@PathVariable("id") Long id) {
return AjaxResult.success(usdtAggregationTaskService.selectUsdtAggregationTaskById(id, true));
}
/**
* 新增归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:add')")
@Log(title = "归集任务", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.insertUsdtAggregationTask(usdtAggregationTask, false));
}
/**
* 新增归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-add')")
@Log(title = "归集任务", businessType = BusinessType.INSERT)
@PostMapping("/user")
public AjaxResult userAdd(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.insertUsdtAggregationTask(usdtAggregationTask, true));
}
/**
* 修改归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:edit')")
@Log(title = "归集任务", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.updateUsdtAggregationTask(usdtAggregationTask, false));
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-edit')")
@Log(title = "归集任务", businessType = BusinessType.UPDATE)
@PutMapping("/user")
public AjaxResult userEdit(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.updateUsdtAggregationTask(usdtAggregationTask, true));
}
/**
* 删除归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:remove')")
@Log(title = "归集任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(usdtAggregationTaskService.deleteUsdtAggregationTaskByIds(ids, false));
}
/**
* 删除归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-remove')")
@Log(title = "归集任务", businessType = BusinessType.DELETE)
@DeleteMapping("/user/{ids}")
public AjaxResult userRemove(@PathVariable Long[] ids) {
return toAjax(usdtAggregationTaskService.deleteUsdtAggregationTaskByIds(ids, true));
}
}
@@ -0,0 +1,170 @@
package com.ruoyi.system.controller;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.select.Ids;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.UsdtAggregationTaskItem;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
import com.ruoyi.system.service.IUsdtAggregationTaskItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 归集任务明细Controller
*
* @author luqj
* @date 2026-01-01
*/
@RestController
@RequestMapping("/system/usdtTaskItem")
public class UsdtAggregationTaskItemController extends BaseController
{
@Autowired
private IUsdtAggregationTaskItemService usdtAggregationTaskItemService;
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:getByIds')")
@PostMapping("/getByIds")
public AjaxResult getByIds(@RequestBody Ids ids)
{
List<UsdtAggregationTaskItemPlus> list = usdtAggregationTaskItemService.getByIds(ids.getLongIds(),false,UsdtAggregationTaskItemPlus::getRemark,UsdtAggregationTaskItemPlus::getId);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-getByIds')")
@PostMapping("/user/getByIds")
public AjaxResult userGetByIds(@RequestBody Ids ids)
{
List<UsdtAggregationTaskItemPlus> list = usdtAggregationTaskItemService.getByIds(ids.getLongIds(),true,UsdtAggregationTaskItemPlus::getUserId,UsdtAggregationTaskItemPlus::getRemark,UsdtAggregationTaskItemPlus::getId);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:select')")
@GetMapping("/select")
public AjaxResult select(String keyword)
{
List<SelectItem> list = usdtAggregationTaskItemService.select(keyword,false);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-select')")
@GetMapping("/user/select")
public AjaxResult userSelect(String keyword)
{
List<SelectItem> list = usdtAggregationTaskItemService.select(keyword,true);
return AjaxResult.success(list);
}
/**
* 查询归集任务明细列表
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:list')")
@GetMapping("/list")
public TableDataInfo list(UsdtAggregationTaskItem usdtAggregationTaskItem)
{
startPage();
List<UsdtAggregationTaskItem> list = usdtAggregationTaskItemService.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem,false);
return getDataTable(list);
}
/**
* 查询归集任务明细列表
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-list')")
@GetMapping("/user/list")
public TableDataInfo userList(UsdtAggregationTaskItem usdtAggregationTaskItem)
{
startPage();
List<UsdtAggregationTaskItem> list = usdtAggregationTaskItemService.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem,true);
return getDataTable(list);
}
/**
* 导出归集任务明细列表
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:export')")
@Log(title = "归集任务明细", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(UsdtAggregationTaskItem usdtAggregationTaskItem)
{
List<UsdtAggregationTaskItem> list = usdtAggregationTaskItemService.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem,false);
ExcelUtil<UsdtAggregationTaskItem> util = new ExcelUtil<UsdtAggregationTaskItem>(UsdtAggregationTaskItem.class);
return util.exportExcel(list, "usdtTaskItem");
}
/**
* 获取归集任务明细详细信息
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(usdtAggregationTaskItemService.selectUsdtAggregationTaskItemById(id,false));
}
/**
* 获取归集任务明细详细信息
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-query')")
@GetMapping(value = "/user/{id}")
public AjaxResult userGetInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(usdtAggregationTaskItemService.selectUsdtAggregationTaskItemById(id,true));
}
/**
* 新增归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:add')")
@Log(title = "归集任务明细", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.insertUsdtAggregationTaskItem(usdtAggregationTaskItem,false));
}
/**
* 新增归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-add')")
@Log(title = "归集任务明细", businessType = BusinessType.INSERT)
@PostMapping("/user")
public AjaxResult userAdd(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.insertUsdtAggregationTaskItem(usdtAggregationTaskItem,true));
}
/**
* 修改归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:edit')")
@Log(title = "归集任务明细", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.updateUsdtAggregationTaskItem(usdtAggregationTaskItem,false));
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-edit')")
@Log(title = "归集任务明细", businessType = BusinessType.UPDATE)
@PutMapping("/user")
public AjaxResult userEdit(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.updateUsdtAggregationTaskItem(usdtAggregationTaskItem,true));
}
/**
* 删除归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:remove')")
@Log(title = "归集任务明细", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(usdtAggregationTaskItemService.deleteUsdtAggregationTaskItemByIds(ids,false));
}
/**
* 删除归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-remove')")
@Log(title = "归集任务明细", businessType = BusinessType.DELETE)
@DeleteMapping("/user/{ids}")
public AjaxResult userRemove(@PathVariable Long[] ids)
{
return toAjax(usdtAggregationTaskItemService.deleteUsdtAggregationTaskItemByIds(ids,true));
}
}
@@ -1,6 +1,9 @@
package com.ruoyi.system.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -21,6 +24,7 @@ public class AppApiKeysPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 应用ID */
@Excel(name = "应用ID")
@@ -23,7 +23,8 @@ public class Apps extends BaseEntity
/** 用户 */
@Excel(name = "用户")
private Long userId;
@Excel(name = "归集地址")
private String distTokenAddress;
/** 名称 */
@Excel(name = "名称")
private String name;
@@ -90,7 +91,15 @@ public class Apps extends BaseEntity
this.status = status;
}
public Integer getStatus()
public String getDistTokenAddress() {
return distTokenAddress;
}
public void setDistTokenAddress(String distTokenAddress) {
this.distTokenAddress = distTokenAddress;
}
public Integer getStatus()
{
return status;
}
@@ -1,6 +1,9 @@
package com.ruoyi.system.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -21,6 +24,7 @@ public class AppsPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 用户 */
@Excel(name = "用户")
@@ -34,6 +38,9 @@ public class AppsPlus implements Serializable
/** 状态 */
@Excel(name = "状态")
private Integer status;
@Excel(name = "归集地址")
private String distTokenAddress;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
@@ -117,6 +124,14 @@ public class AppsPlus implements Serializable
return deletedAt;
}
public String getDistTokenAddress() {
return distTokenAddress;
}
public void setDistTokenAddress(String distTokenAddress) {
this.distTokenAddress = distTokenAddress;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
@@ -0,0 +1,197 @@
package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
/**
* 归集任务对象 usdt_aggregation_task
*
* @author luqj
* @date 2026-01-01
*/
public class UsdtAggregationTask extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
private Long id;
/** 任务名称 */
@Excel(name = "任务名称")
private String taskName;
/** 应用 */
@Excel(name = "应用")
private Long appId;
/** 用户 */
@Excel(name = "用户")
private Long userId;
/** 状态 */
@Excel(name = "状态")
private Integer status;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date createdAt;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date updatedAt;
/** 删除时间 */
private Date deletedAt;
/** 提现总金额 */
@Excel(name = "提现总金额")
private BigDecimal totalAmount;
/** 执行时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date exeTime;
/** 审核状态 */
@Excel(name = "审核状态")
private Integer verifyStatus;
/** 归集地址 */
@Excel(name = "归集地址")
private String distTokenAddress;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setTaskName(String taskName)
{
this.taskName = taskName;
}
public String getTaskName()
{
return taskName;
}
public void setAppId(Long appId)
{
this.appId = appId;
}
public Long getAppId()
{
return appId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getUserId()
{
return userId;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Integer getStatus()
{
return status;
}
public void setCreatedAt(Date createdAt)
{
this.createdAt = createdAt;
}
public Date getCreatedAt()
{
return createdAt;
}
public void setUpdatedAt(Date updatedAt)
{
this.updatedAt = updatedAt;
}
public Date getUpdatedAt()
{
return updatedAt;
}
public void setDeletedAt(Date deletedAt)
{
this.deletedAt = deletedAt;
}
public Date getDeletedAt()
{
return deletedAt;
}
public void setTotalAmount(BigDecimal totalAmount)
{
this.totalAmount = totalAmount;
}
public BigDecimal getTotalAmount()
{
return totalAmount;
}
public void setExeTime(Date exeTime)
{
this.exeTime = exeTime;
}
public Date getExeTime()
{
return exeTime;
}
public void setVerifyStatus(Integer verifyStatus)
{
this.verifyStatus = verifyStatus;
}
public Integer getVerifyStatus()
{
return verifyStatus;
}
public void setDistTokenAddress(String distTokenAddress)
{
this.distTokenAddress = distTokenAddress;
}
public String getDistTokenAddress()
{
return distTokenAddress;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("taskName", getTaskName())
.append("appId", getAppId())
.append("userId", getUserId())
.append("remark", getRemark())
.append("status", getStatus())
.append("createdAt", getCreatedAt())
.append("updatedAt", getUpdatedAt())
.append("deletedAt", getDeletedAt())
.append("totalAmount", getTotalAmount())
.append("exeTime", getExeTime())
.append("verifyStatus", getVerifyStatus())
.append("distTokenAddress", getDistTokenAddress())
.toString();
}
}
@@ -0,0 +1,182 @@
package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
/**
* 归集任务明细对象 usdt_aggregation_task_item
*
* @author luqj
* @date 2026-01-01
*/
public class UsdtAggregationTaskItem extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
private Long id;
/** 钱包地址 */
@Excel(name = "钱包地址")
private String tokenAddress;
/** 状态0 待执行 1 执行 2 执行失败 */
@Excel(name = "状态0 待执行 1 执行 2 执行失败")
private Integer status;
/** 金额 */
@Excel(name = "金额")
private BigDecimal opeAmount;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date createdAt;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date updatedAt;
/** 删除时间 */
private Date deletedAt;
/** 用户 */
@Excel(name = "用户")
private Long userId;
/** 应用 */
@Excel(name = "应用")
private Long appId;
/** 父任务 */
@Excel(name = "父任务")
private Long parentId;
/** 归集地址 */
@Excel(name = "归集地址")
private String distTokenAddress;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setTokenAddress(String tokenAddress)
{
this.tokenAddress = tokenAddress;
}
public String getTokenAddress()
{
return tokenAddress;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Integer getStatus()
{
return status;
}
public void setOpeAmount(BigDecimal opeAmount)
{
this.opeAmount = opeAmount;
}
public BigDecimal getOpeAmount()
{
return opeAmount;
}
public void setCreatedAt(Date createdAt)
{
this.createdAt = createdAt;
}
public Date getCreatedAt()
{
return createdAt;
}
public void setUpdatedAt(Date updatedAt)
{
this.updatedAt = updatedAt;
}
public Date getUpdatedAt()
{
return updatedAt;
}
public void setDeletedAt(Date deletedAt)
{
this.deletedAt = deletedAt;
}
public Date getDeletedAt()
{
return deletedAt;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getUserId()
{
return userId;
}
public void setAppId(Long appId)
{
this.appId = appId;
}
public Long getAppId()
{
return appId;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public Long getParentId()
{
return parentId;
}
public void setDistTokenAddress(String distTokenAddress)
{
this.distTokenAddress = distTokenAddress;
}
public String getDistTokenAddress()
{
return distTokenAddress;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("tokenAddress", getTokenAddress())
.append("status", getStatus())
.append("remark", getRemark())
.append("opeAmount", getOpeAmount())
.append("createdAt", getCreatedAt())
.append("updatedAt", getUpdatedAt())
.append("deletedAt", getDeletedAt())
.append("userId", getUserId())
.append("appId", getAppId())
.append("parentId", getParentId())
.append("distTokenAddress", getDistTokenAddress())
.toString();
}
}
@@ -0,0 +1,190 @@
package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* 归集任务明细对象 usdt_aggregation_task_item
*
* @author luqj
* @date 2026-01-01
*/
@TableName(value = "usdt_aggregation_task_item")
public class UsdtAggregationTaskItemPlus implements Serializable
{
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 钱包地址 */
@Excel(name = "钱包地址")
private String tokenAddress;
/** 状态0 待执行 1 执行 2 执行失败 */
@Excel(name = "状态0 待执行 1 执行 2 执行失败")
private Integer status;
/** 备注 */
@Excel(name = "备注")
private String remark;
/** 金额 */
@Excel(name = "金额")
private BigDecimal opeAmount;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date createdAt;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date updatedAt;
/** 删除时间 */
private Date deletedAt;
/** 用户 */
@Excel(name = "用户")
private Long userId;
/** 应用 */
@Excel(name = "应用")
private Long appId;
/** 父任务 */
@Excel(name = "父任务")
private Long parentId;
/** 归集地址 */
@Excel(name = "归集地址")
private String distTokenAddress;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setTokenAddress(String tokenAddress)
{
this.tokenAddress = tokenAddress;
}
public String getTokenAddress()
{
return tokenAddress;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Integer getStatus()
{
return status;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public String getRemark()
{
return remark;
}
public void setOpeAmount(BigDecimal opeAmount)
{
this.opeAmount = opeAmount;
}
public BigDecimal getOpeAmount()
{
return opeAmount;
}
public void setCreatedAt(Date createdAt)
{
this.createdAt = createdAt;
}
public Date getCreatedAt()
{
return createdAt;
}
public void setUpdatedAt(Date updatedAt)
{
this.updatedAt = updatedAt;
}
public Date getUpdatedAt()
{
return updatedAt;
}
public void setDeletedAt(Date deletedAt)
{
this.deletedAt = deletedAt;
}
public Date getDeletedAt()
{
return deletedAt;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getUserId()
{
return userId;
}
public void setAppId(Long appId)
{
this.appId = appId;
}
public Long getAppId()
{
return appId;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public Long getParentId()
{
return parentId;
}
public void setDistTokenAddress(String distTokenAddress)
{
this.distTokenAddress = distTokenAddress;
}
public String getDistTokenAddress()
{
return distTokenAddress;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("tokenAddress", getTokenAddress())
.append("status", getStatus())
.append("remark", getRemark())
.append("opeAmount", getOpeAmount())
.append("createdAt", getCreatedAt())
.append("updatedAt", getUpdatedAt())
.append("deletedAt", getDeletedAt())
.append("userId", getUserId())
.append("appId", getAppId())
.append("parentId", getParentId())
.append("distTokenAddress", getDistTokenAddress())
.toString();
}
}
@@ -0,0 +1,204 @@
package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* 归集任务对象 usdt_aggregation_task
*
* @author luqj
* @date 2026-01-01
*/
@TableName(value = "usdt_aggregation_task")
public class UsdtAggregationTaskPlus implements Serializable
{
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 任务名称 */
@Excel(name = "任务名称")
private String taskName;
/** 应用 */
@Excel(name = "应用")
private Long appId;
/** 用户 */
@Excel(name = "用户")
private Long userId;
/** 备注 */
@Excel(name = "备注")
private String remark;
/** 状态 */
@Excel(name = "状态")
private Integer status;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date createdAt;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date updatedAt;
/** 删除时间 */
private Date deletedAt;
/** 提现总金额 */
@Excel(name = "提现总金额")
private BigDecimal totalAmount;
/** 执行时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date exeTime;
/** 审核状态 */
@Excel(name = "审核状态")
private Integer verifyStatus;
/** 归集地址 */
@Excel(name = "归集地址")
private String distTokenAddress;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setTaskName(String taskName)
{
this.taskName = taskName;
}
public String getTaskName()
{
return taskName;
}
public void setAppId(Long appId)
{
this.appId = appId;
}
public Long getAppId()
{
return appId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getUserId()
{
return userId;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public String getRemark()
{
return remark;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Integer getStatus()
{
return status;
}
public void setCreatedAt(Date createdAt)
{
this.createdAt = createdAt;
}
public Date getCreatedAt()
{
return createdAt;
}
public void setUpdatedAt(Date updatedAt)
{
this.updatedAt = updatedAt;
}
public Date getUpdatedAt()
{
return updatedAt;
}
public void setDeletedAt(Date deletedAt)
{
this.deletedAt = deletedAt;
}
public Date getDeletedAt()
{
return deletedAt;
}
public void setTotalAmount(BigDecimal totalAmount)
{
this.totalAmount = totalAmount;
}
public BigDecimal getTotalAmount()
{
return totalAmount;
}
public void setExeTime(Date exeTime)
{
this.exeTime = exeTime;
}
public Date getExeTime()
{
return exeTime;
}
public void setVerifyStatus(Integer verifyStatus)
{
this.verifyStatus = verifyStatus;
}
public Integer getVerifyStatus()
{
return verifyStatus;
}
public void setDistTokenAddress(String distTokenAddress)
{
this.distTokenAddress = distTokenAddress;
}
public String getDistTokenAddress()
{
return distTokenAddress;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("taskName", getTaskName())
.append("appId", getAppId())
.append("userId", getUserId())
.append("remark", getRemark())
.append("status", getStatus())
.append("createdAt", getCreatedAt())
.append("updatedAt", getUpdatedAt())
.append("deletedAt", getDeletedAt())
.append("totalAmount", getTotalAmount())
.append("exeTime", getExeTime())
.append("verifyStatus", getVerifyStatus())
.append("distTokenAddress", getDistTokenAddress())
.toString();
}
}
@@ -2,6 +2,9 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -22,6 +25,7 @@ public class UsdtFundFlowPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 订单ID */
@Excel(name = "订单ID")
@@ -46,7 +50,7 @@ public class UsdtFundFlowPlus implements Serializable
@Excel(name = "操作金额")
private BigDecimal amount;
/** 操作类型 */
@Excel(name = "操作类型")
@Excel(name = "操作类型 操作类型 0 商户收入 1 平台抽佣 2 商户归集提现金额")
private Integer opType;
/** Token地址 */
@Excel(name = "Token地址")
@@ -2,6 +2,9 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -22,6 +25,7 @@ public class UsdtOrdersPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 订单号 */
@Excel(name = "订单号")
@@ -42,7 +46,7 @@ public class UsdtOrdersPlus implements Serializable
@Excel(name = "钱包地址")
private String token;
/** 状态 */
@Excel(name = "状态")
@Excel(name = "状态 状态1:等待支付,2:支付成功,3:已过期")
private Long status;
/** 异步地址 */
@Excel(name = "异步地址")
@@ -2,6 +2,9 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -22,6 +25,7 @@ public class UsdtUserSettlementConfigurationPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 用户id */
@Excel(name = "用户id")
@@ -1,6 +1,9 @@
package com.ruoyi.system.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -21,6 +24,7 @@ public class UserAuthPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键ID */
@TableId(type = IdType.INPUT)
private Long id;
/** 用户 */
@Excel(name = "用户")
@@ -1,5 +1,6 @@
package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
@@ -11,7 +12,7 @@ import java.io.Serializable;
* token管理对象 wallet_address
*
* @author luqj
* @date 2025-11-25
* @date 2025-12-30
*/
public class WalletAddress extends BaseEntity
{
@@ -50,6 +51,83 @@ public class WalletAddress extends BaseEntity
@Excel(name = "用户")
private Long userId;
/** 密钥 */
@Excel(name = "密钥")
private String tokenKey;
@Excel(name = "质押还剩能用的带宽")
private Long bandwidthStakedNum;
/** usdt余额 */
@Excel(name = "usdt余额")
private BigDecimal usdtBalance;
/** trx余额 */
@Excel(name = "trx余额")
private BigDecimal trxBalance;
/** 能量-可用 */
@Excel(name = "能量-可用")
private Long energyNum;
/** 带宽-可用 */
@Excel(name = "带宽-可用")
private Long bandwidthNum;
/** 可以提现usdt金额 */
@Excel(name = "可以提现usdt金额")
private BigDecimal withdrawUsdtBalance;
/** 代理给别人能量的trx数量 */
@Excel(name = "代理给别人能量的trx数量")
private Long delegatedEnergyTrxNum;
/** 代理给别人的能量 */
@Excel(name = "代理给别人的能量")
private BigDecimal delegatedEnergyValue;
/** 别人代理给我能量的trx数量 */
@Excel(name = "别人代理给我能量的trx数量")
private Long acquiredDelegatedEnergyTrxNum;
/** 别人代理给我的能量 */
@Excel(name = "别人代理给我的能量")
private BigDecimal acquiredDelegatedEnergyValue;
/** 代理给别人的带宽trx数量 */
@Excel(name = "代理给别人的带宽trx数量")
private Long delegatedBandwidthTrxNum;
/** 代理给别人的带宽 */
@Excel(name = "代理给别人的带宽")
private BigDecimal delegatedBandwidthValue;
/** 别人代理给我带宽的trx数量 */
@Excel(name = "别人代理给我带宽的trx数量")
private Long acquiredDelegatedBandwidthTrxNum;
/** 别人代理给我的带宽 */
@Excel(name = "别人代理给我的带宽")
private BigDecimal acquiredDelegatedBandwidthValue;
/** 质押的trx数量-不含代理 */
@Excel(name = "质押的trx数量-不含代理")
private Long stakedTrxNum;
/** 能量质押的trx数量-不含代理 */
@Excel(name = "能量质押的trx数量-不含代理")
private Long energyStakedTrxNum;
/** 带宽质押的trx数量-不含代理 */
@Excel(name = "带宽质押的trx数量-不含代理")
private Long bandwidthStakedTrxNum;
/** 可投票数 */
@Excel(name = "可投票数")
private Long voteNum;
/** 已经投票数量 */
@Excel(name = "已经投票数量")
private Long votedNum;
public void setId(Long id)
{
this.id = id;
@@ -64,7 +142,15 @@ public class WalletAddress extends BaseEntity
this.token = token;
}
public String getToken()
public Long getBandwidthStakedNum() {
return bandwidthStakedNum;
}
public void setBandwidthStakedNum(Long bandwidthStakedNum) {
this.bandwidthStakedNum = bandwidthStakedNum;
}
public String getToken()
{
return token;
}
@@ -122,6 +208,177 @@ public class WalletAddress extends BaseEntity
{
return userId;
}
public void setTokenKey(String key)
{
this.tokenKey = key;
}
public String getTokenKey()
{
return tokenKey;
}
public void setUsdtBalance(BigDecimal usdtBalance)
{
this.usdtBalance = usdtBalance;
}
public BigDecimal getUsdtBalance()
{
return usdtBalance;
}
public void setTrxBalance(BigDecimal trxBalance)
{
this.trxBalance = trxBalance;
}
public BigDecimal getTrxBalance()
{
return trxBalance;
}
public void setEnergyNum(Long energyNum)
{
this.energyNum = energyNum;
}
public Long getEnergyNum()
{
return energyNum;
}
public void setBandwidthNum(Long bandwidthNum)
{
this.bandwidthNum = bandwidthNum;
}
public Long getBandwidthNum()
{
return bandwidthNum;
}
public void setWithdrawUsdtBalance(BigDecimal withdrawUsdtBalance)
{
this.withdrawUsdtBalance = withdrawUsdtBalance;
}
public BigDecimal getWithdrawUsdtBalance()
{
return withdrawUsdtBalance;
}
public void setDelegatedEnergyTrxNum(Long delegatedEnergyTrxNum)
{
this.delegatedEnergyTrxNum = delegatedEnergyTrxNum;
}
public Long getDelegatedEnergyTrxNum()
{
return delegatedEnergyTrxNum;
}
public void setDelegatedEnergyValue(BigDecimal delegatedEnergyValue)
{
this.delegatedEnergyValue = delegatedEnergyValue;
}
public BigDecimal getDelegatedEnergyValue()
{
return delegatedEnergyValue;
}
public void setAcquiredDelegatedEnergyTrxNum(Long acquiredDelegatedEnergyTrxNum)
{
this.acquiredDelegatedEnergyTrxNum = acquiredDelegatedEnergyTrxNum;
}
public Long getAcquiredDelegatedEnergyTrxNum()
{
return acquiredDelegatedEnergyTrxNum;
}
public void setAcquiredDelegatedEnergyValue(BigDecimal acquiredDelegatedEnergyValue)
{
this.acquiredDelegatedEnergyValue = acquiredDelegatedEnergyValue;
}
public BigDecimal getAcquiredDelegatedEnergyValue()
{
return acquiredDelegatedEnergyValue;
}
public void setDelegatedBandwidthTrxNum(Long delegatedBandwidthTrxNum)
{
this.delegatedBandwidthTrxNum = delegatedBandwidthTrxNum;
}
public Long getDelegatedBandwidthTrxNum()
{
return delegatedBandwidthTrxNum;
}
public void setDelegatedBandwidthValue(BigDecimal delegatedBandwidthValue)
{
this.delegatedBandwidthValue = delegatedBandwidthValue;
}
public BigDecimal getDelegatedBandwidthValue()
{
return delegatedBandwidthValue;
}
public void setAcquiredDelegatedBandwidthTrxNum(Long acquiredDelegatedBandwidthTrxNum)
{
this.acquiredDelegatedBandwidthTrxNum = acquiredDelegatedBandwidthTrxNum;
}
public Long getAcquiredDelegatedBandwidthTrxNum()
{
return acquiredDelegatedBandwidthTrxNum;
}
public void setAcquiredDelegatedBandwidthValue(BigDecimal acquiredDelegatedBandwidthValue)
{
this.acquiredDelegatedBandwidthValue = acquiredDelegatedBandwidthValue;
}
public BigDecimal getAcquiredDelegatedBandwidthValue()
{
return acquiredDelegatedBandwidthValue;
}
public void setStakedTrxNum(Long stakedTrxNum)
{
this.stakedTrxNum = stakedTrxNum;
}
public Long getStakedTrxNum()
{
return stakedTrxNum;
}
public void setEnergyStakedTrxNum(Long energyStakedTrxNum)
{
this.energyStakedTrxNum = energyStakedTrxNum;
}
public Long getEnergyStakedTrxNum()
{
return energyStakedTrxNum;
}
public void setBandwidthStakedTrxNum(Long bandwidthStakedTrxNum)
{
this.bandwidthStakedTrxNum = bandwidthStakedTrxNum;
}
public Long getBandwidthStakedTrxNum()
{
return bandwidthStakedTrxNum;
}
public void setVoteNum(Long voteNum)
{
this.voteNum = voteNum;
}
public Long getVoteNum()
{
return voteNum;
}
public void setVotedNum(Long votedNum)
{
this.votedNum = votedNum;
}
public Long getVotedNum()
{
return votedNum;
}
@Override
public String toString() {
@@ -134,6 +391,25 @@ public class WalletAddress extends BaseEntity
.append("deletedAt", getDeletedAt())
.append("appId", getAppId())
.append("userId", getUserId())
.append("tokenKey", getTokenKey())
.append("usdtBalance", getUsdtBalance())
.append("trxBalance", getTrxBalance())
.append("energyNum", getEnergyNum())
.append("bandwidthNum", getBandwidthNum())
.append("withdrawUsdtBalance", getWithdrawUsdtBalance())
.append("delegatedEnergyTrxNum", getDelegatedEnergyTrxNum())
.append("delegatedEnergyValue", getDelegatedEnergyValue())
.append("acquiredDelegatedEnergyTrxNum", getAcquiredDelegatedEnergyTrxNum())
.append("acquiredDelegatedEnergyValue", getAcquiredDelegatedEnergyValue())
.append("delegatedBandwidthTrxNum", getDelegatedBandwidthTrxNum())
.append("delegatedBandwidthValue", getDelegatedBandwidthValue())
.append("acquiredDelegatedBandwidthTrxNum", getAcquiredDelegatedBandwidthTrxNum())
.append("acquiredDelegatedBandwidthValue", getAcquiredDelegatedBandwidthValue())
.append("stakedTrxNum", getStakedTrxNum())
.append("energyStakedTrxNum", getEnergyStakedTrxNum())
.append("bandwidthStakedTrxNum", getBandwidthStakedTrxNum())
.append("voteNum", getVoteNum())
.append("votedNum", getVotedNum())
.toString();
}
}
@@ -2,6 +2,9 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -14,7 +17,7 @@ import com.baomidou.mybatisplus.annotation.TableName;
* token管理对象 wallet_address
*
* @author luqj
* @date 2025-11-25
* @date 2025-12-30
*/
@TableName(value = "wallet_address")
public class WalletAddressPlus implements Serializable
@@ -22,6 +25,7 @@ public class WalletAddressPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(type = IdType.INPUT)
@Excel(name = "主键")
private Long id;
/** Token */
@@ -46,30 +50,66 @@ public class WalletAddressPlus implements Serializable
/** 用户 */
@Excel(name = "用户")
private Long userId;
/** 密钥 */
@Excel(name = "密钥")
private String tokenKey;
/** usdt余额 */
@Excel(name = "usdt余额")
private BigDecimal usdtBalance;
/** trx余额 */
@Excel(name = "trx余额")
private BigDecimal trxBalance;
public BigDecimal getTrxBalance() {
return trxBalance;
}
public void setTrxBalance(BigDecimal trxBalance) {
this.trxBalance = trxBalance;
}
public BigDecimal getUsdtBalance() {
return usdtBalance;
}
public void setUsdtBalance(BigDecimal usdtBalance) {
this.usdtBalance = usdtBalance;
}
public void setId(Long id)
/** 能量-可用 */
@Excel(name = "能量-可用")
private Long energyNum;
@Excel(name = "质押还剩能用的带宽")
private Long bandwidthStakedNum;
/** 带宽-可用 */
@Excel(name = "带宽-可用")
private Long bandwidthNum;
/** 可以提现usdt金额 */
@Excel(name = "可以提现usdt金额")
private BigDecimal withdrawUsdtBalance;
/** 代理给别人能量的trx数量 */
@Excel(name = "代理给别人能量的trx数量")
private Long delegatedEnergyTrxNum;
/** 代理给别人的能量 */
@Excel(name = "代理给别人的能量")
private BigDecimal delegatedEnergyValue;
/** 别人代理给我能量的trx数量 */
@Excel(name = "别人代理给我能量的trx数量")
private Long acquiredDelegatedEnergyTrxNum;
/** 别人代理给我的能量 */
@Excel(name = "别人代理给我的能量")
private BigDecimal acquiredDelegatedEnergyValue;
/** 代理给别人的带宽trx数量 */
@Excel(name = "代理给别人的带宽trx数量")
private Long delegatedBandwidthTrxNum;
/** 代理给别人的带宽 */
@Excel(name = "代理给别人的带宽")
private BigDecimal delegatedBandwidthValue;
/** 别人代理给我带宽的trx数量 */
@Excel(name = "别人代理给我带宽的trx数量")
private Long acquiredDelegatedBandwidthTrxNum;
/** 别人代理给我的带宽 */
@Excel(name = "别人代理给我的带宽")
private BigDecimal acquiredDelegatedBandwidthValue;
/** 质押的trx数量-不含代理 */
@Excel(name = "质押的trx数量-不含代理")
private Long stakedTrxNum;
/** 能量质押的trx数量-不含代理 */
@Excel(name = "能量质押的trx数量-不含代理")
private Long energyStakedTrxNum;
/** 带宽质押的trx数量-不含代理 */
@Excel(name = "带宽质押的trx数量-不含代理")
private Long bandwidthStakedTrxNum;
/** 可投票数 */
@Excel(name = "可投票数")
private Long voteNum;
/** 已经投票数量 */
@Excel(name = "已经投票数量")
private Long votedNum;
public void setId(Long id)
{
this.id = id;
}
@@ -101,7 +141,15 @@ public class WalletAddressPlus implements Serializable
this.createdAt = createdAt;
}
public Date getCreatedAt()
public Long getBandwidthStakedNum() {
return bandwidthStakedNum;
}
public void setBandwidthStakedNum(Long bandwidthStakedNum) {
this.bandwidthStakedNum = bandwidthStakedNum;
}
public Date getCreatedAt()
{
return createdAt;
}
@@ -141,6 +189,177 @@ public class WalletAddressPlus implements Serializable
{
return userId;
}
public void setTokenKey(String key)
{
this.tokenKey = key;
}
public String getTokenKey()
{
return tokenKey;
}
public void setUsdtBalance(BigDecimal usdtBalance)
{
this.usdtBalance = usdtBalance;
}
public BigDecimal getUsdtBalance()
{
return usdtBalance;
}
public void setTrxBalance(BigDecimal trxBalance)
{
this.trxBalance = trxBalance;
}
public BigDecimal getTrxBalance()
{
return trxBalance;
}
public void setEnergyNum(Long energyNum)
{
this.energyNum = energyNum;
}
public Long getEnergyNum()
{
return energyNum;
}
public void setBandwidthNum(Long bandwidthNum)
{
this.bandwidthNum = bandwidthNum;
}
public Long getBandwidthNum()
{
return bandwidthNum;
}
public void setWithdrawUsdtBalance(BigDecimal withdrawUsdtBalance)
{
this.withdrawUsdtBalance = withdrawUsdtBalance;
}
public BigDecimal getWithdrawUsdtBalance()
{
return withdrawUsdtBalance;
}
public void setDelegatedEnergyTrxNum(Long delegatedEnergyTrxNum)
{
this.delegatedEnergyTrxNum = delegatedEnergyTrxNum;
}
public Long getDelegatedEnergyTrxNum()
{
return delegatedEnergyTrxNum;
}
public void setDelegatedEnergyValue(BigDecimal delegatedEnergyValue)
{
this.delegatedEnergyValue = delegatedEnergyValue;
}
public BigDecimal getDelegatedEnergyValue()
{
return delegatedEnergyValue;
}
public void setAcquiredDelegatedEnergyTrxNum(Long acquiredDelegatedEnergyTrxNum)
{
this.acquiredDelegatedEnergyTrxNum = acquiredDelegatedEnergyTrxNum;
}
public Long getAcquiredDelegatedEnergyTrxNum()
{
return acquiredDelegatedEnergyTrxNum;
}
public void setAcquiredDelegatedEnergyValue(BigDecimal acquiredDelegatedEnergyValue)
{
this.acquiredDelegatedEnergyValue = acquiredDelegatedEnergyValue;
}
public BigDecimal getAcquiredDelegatedEnergyValue()
{
return acquiredDelegatedEnergyValue;
}
public void setDelegatedBandwidthTrxNum(Long delegatedBandwidthTrxNum)
{
this.delegatedBandwidthTrxNum = delegatedBandwidthTrxNum;
}
public Long getDelegatedBandwidthTrxNum()
{
return delegatedBandwidthTrxNum;
}
public void setDelegatedBandwidthValue(BigDecimal delegatedBandwidthValue)
{
this.delegatedBandwidthValue = delegatedBandwidthValue;
}
public BigDecimal getDelegatedBandwidthValue()
{
return delegatedBandwidthValue;
}
public void setAcquiredDelegatedBandwidthTrxNum(Long acquiredDelegatedBandwidthTrxNum)
{
this.acquiredDelegatedBandwidthTrxNum = acquiredDelegatedBandwidthTrxNum;
}
public Long getAcquiredDelegatedBandwidthTrxNum()
{
return acquiredDelegatedBandwidthTrxNum;
}
public void setAcquiredDelegatedBandwidthValue(BigDecimal acquiredDelegatedBandwidthValue)
{
this.acquiredDelegatedBandwidthValue = acquiredDelegatedBandwidthValue;
}
public BigDecimal getAcquiredDelegatedBandwidthValue()
{
return acquiredDelegatedBandwidthValue;
}
public void setStakedTrxNum(Long stakedTrxNum)
{
this.stakedTrxNum = stakedTrxNum;
}
public Long getStakedTrxNum()
{
return stakedTrxNum;
}
public void setEnergyStakedTrxNum(Long energyStakedTrxNum)
{
this.energyStakedTrxNum = energyStakedTrxNum;
}
public Long getEnergyStakedTrxNum()
{
return energyStakedTrxNum;
}
public void setBandwidthStakedTrxNum(Long bandwidthStakedTrxNum)
{
this.bandwidthStakedTrxNum = bandwidthStakedTrxNum;
}
public Long getBandwidthStakedTrxNum()
{
return bandwidthStakedTrxNum;
}
public void setVoteNum(Long voteNum)
{
this.voteNum = voteNum;
}
public Long getVoteNum()
{
return voteNum;
}
public void setVotedNum(Long votedNum)
{
this.votedNum = votedNum;
}
public Long getVotedNum()
{
return votedNum;
}
@Override
public String toString() {
@@ -153,6 +372,25 @@ public class WalletAddressPlus implements Serializable
.append("deletedAt", getDeletedAt())
.append("appId", getAppId())
.append("userId", getUserId())
.append("tokenKey", getTokenKey())
.append("usdtBalance", getUsdtBalance())
.append("trxBalance", getTrxBalance())
.append("energyNum", getEnergyNum())
.append("bandwidthNum", getBandwidthNum())
.append("withdrawUsdtBalance", getWithdrawUsdtBalance())
.append("delegatedEnergyTrxNum", getDelegatedEnergyTrxNum())
.append("delegatedEnergyValue", getDelegatedEnergyValue())
.append("acquiredDelegatedEnergyTrxNum", getAcquiredDelegatedEnergyTrxNum())
.append("acquiredDelegatedEnergyValue", getAcquiredDelegatedEnergyValue())
.append("delegatedBandwidthTrxNum", getDelegatedBandwidthTrxNum())
.append("delegatedBandwidthValue", getDelegatedBandwidthValue())
.append("acquiredDelegatedBandwidthTrxNum", getAcquiredDelegatedBandwidthTrxNum())
.append("acquiredDelegatedBandwidthValue", getAcquiredDelegatedBandwidthValue())
.append("stakedTrxNum", getStakedTrxNum())
.append("energyStakedTrxNum", getEnergyStakedTrxNum())
.append("bandwidthStakedTrxNum", getBandwidthStakedTrxNum())
.append("voteNum", getVoteNum())
.append("votedNum", getVotedNum())
.toString();
}
}
@@ -2,6 +2,9 @@ package com.ruoyi.system.domain;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@@ -22,6 +25,7 @@ public class Web3WalletPlus implements Serializable
private static final long serialVersionUID = 1L;
/** 用户 */
@TableId(type = IdType.INPUT)
private Long id;
/** usdt */
@Excel(name = "usdt")
@@ -0,0 +1,11 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.Map;
@Data
public class AccountResource {
@JsonProperty("frozen_balance_for_energy")
private Map<String, Object> frozenBalanceForEnergy;
}
@@ -0,0 +1,72 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Map;
@Data
public class Bandwidth {
@JsonProperty("energyRemaining")
private long energyRemaining;
@JsonProperty("energyLimit")
private long energyLimit;
@JsonProperty("totalEnergyLimit")
private long totalEnergyLimit;
@JsonProperty("totalEnergyWeight")
private long totalEnergyWeight;
@JsonProperty("energyUsed")
private long energyUsed;
@JsonProperty("netUsed")
private long netUsed;
@JsonProperty("netLimit")
private long netLimit;
@JsonProperty("netRemaining")
private long netRemaining;
@JsonProperty("freeNetLimit")
private long freeNetLimit;
@JsonProperty("freeNetUsed")
private long freeNetUsed;
@JsonProperty("freeNetRemaining")
private long freeNetRemaining;
@JsonProperty("totalNetLimit")
private long totalNetLimit;
@JsonProperty("totalNetWeight")
private long totalNetWeight;
@JsonProperty("netPercentage")
private BigDecimal netPercentage;
@JsonProperty("freeNetPercentage")
private BigDecimal freeNetPercentage;
@JsonProperty("energyPercentage")
private BigDecimal energyPercentage;
@JsonProperty("storageLimit")
private long storageLimit;
@JsonProperty("storageUsed")
private long storageUsed;
@JsonProperty("storageRemaining")
private long storageRemaining;
@JsonProperty("storagePercentage")
private BigDecimal storagePercentage;
@JsonProperty("assets")
private Map<String, Object> assets;
}
@@ -0,0 +1,24 @@
package com.ruoyi.system.domain.vo;
import com.ruoyi.common.annotation.Excel;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
public class EnergyAndBandwidthVo implements Serializable {
private BigDecimal delegateBandwidth;
private BigDecimal delegateEnergy;
private Long stakedTrxNum;
@Excel(name = "质押还剩能用的带宽")
private Long bandwidthStakedNum;
private BigDecimal bandwidth;
private BigDecimal energy;
private BigDecimal acquiredBandwidth;
private BigDecimal acquiredEnergy;
}
@@ -0,0 +1,15 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class Frozen {
@JsonProperty("total")
private long total;
@JsonProperty("balances")
private List<Object> balances;
}
@@ -0,0 +1,26 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class Permission {
@JsonProperty("id")
private int id;
@JsonProperty("type")
private String type;
@JsonProperty("permission_name")
private String permissionName;
@JsonProperty("threshold")
private int threshold;
@JsonProperty("operations")
private String operations;
@JsonProperty("keys")
private List<PermissionKey> keys;
}
@@ -0,0 +1,13 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class PermissionKey {
@JsonProperty("address")
private String address;
@JsonProperty("weight")
private int weight;
}
@@ -0,0 +1,20 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class Representative {
@JsonProperty("lastWithDrawTime")
private long lastWithDrawTime;
@JsonProperty("allowance")
private long allowance;
@JsonProperty("enabled")
private boolean enabled;
@JsonProperty("url")
private String url;
}
@@ -0,0 +1,47 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class TokenBalance {
@JsonProperty("tokenId")
private String tokenId;
@JsonProperty("tokenName")
private String tokenName;
@JsonProperty("tokenAbbr")
private String tokenAbbr;
@JsonProperty("tokenDecimal")
private int tokenDecimal;
@JsonProperty("tokenType")
private String tokenType;
@JsonProperty("balance")
private String balance;
@JsonProperty("amount")
private BigDecimal amount;
@JsonProperty("tokenPriceInTrx")
private BigDecimal tokenPriceInTrx;
@JsonProperty("vip")
private boolean vip;
@JsonProperty("tokenCanShow")
private int tokenCanShow;
@JsonProperty("tokenLogo")
private String tokenLogo;
@JsonProperty("transferCount")
private long transferCount;
@JsonProperty("nrOfTokenHolders")
private long nrOfTokenHolders;
}
@@ -0,0 +1,18 @@
package com.ruoyi.system.domain.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* TRON 钱包信息实体
*/
@Data
public class TronAccount implements Serializable {
private static final long serialVersionUID = 1L;
private List<TronAccountItem> items;
private String phrase;
}
@@ -0,0 +1,63 @@
package com.ruoyi.system.domain.vo;
import lombok.Data;
import java.io.Serializable;
/**
* TRON 钱包信息实体
*/
@Data
public class TronAccountItem implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Base58 地址(T 开头)
* 示例:TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW
*/
private String address;
private String pubKeyCompressed;
private String pubKeyUnCompressed;
/**
* 私钥(Hex)
* 示例:xxxx
*/
private String privateKey;
private String path;
/**
* Hex 地址(41 开头)
* 示例:41xxx
*/
private String hexAddress;
/**
* Base58 私钥
* 示例:xxx
*/
private String privateKeyBase58;
public TronAccountItem() {
}
public TronAccountItem(String address, String privateKey, String hexAddress, String privateKeyBase58) {
this.address = address;
this.privateKey = privateKey;
this.hexAddress = hexAddress;
this.privateKeyBase58 = privateKeyBase58;
}
@Override
public String toString() {
return "TronAccount{" +
"address='" + address + '\'' +
", hexAddress='" + hexAddress + '\'' +
'}';
}
}
@@ -0,0 +1,254 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class TronAccountResp {
@JsonProperty("totalFrozenV2")
private long totalFrozenV2;
@JsonProperty("transactions_out")
private int transactionsOut;
@JsonProperty("frozenForEnergyV2")
private long frozenForEnergyV2;
@JsonProperty("totalEnergy")
private long totalEnergy;
@JsonProperty("rewardNum")
private int rewardNum;
/**
* 我代理给别人的 2.0 带宽trx
*/
@JsonProperty("delegatedFrozenV2BalanceForBandwidth")
private long delegatedFrozenV2BalanceForBandwidth;
@JsonProperty("ownerPermission")
private Permission ownerPermission;
@JsonProperty("redTag")
private String redTag;
@JsonProperty("delegateFrozenForEnergy")
private long delegateFrozenForEnergy;
@JsonProperty("totalEnergyRemaining")
private long totalEnergyRemaining;
@JsonProperty("balance")
private long balance;
@JsonProperty("frozenForBandWidthV2")
private long frozenForBandWidthV2;
@JsonProperty("canWithdrawAmountV2")
private long canWithdrawAmountV2;
@JsonProperty("netRemainingCal")
private long netRemainingCal;
@JsonProperty("delegated")
private Map<String, Object> delegated;
@JsonProperty("transactions_in")
private int transactionsIn;
@JsonProperty("totalTransactionCount")
private int totalTransactionCount;
@JsonProperty("frozenForEnergyV2Value")
private long frozenForEnergyV2Value;
@JsonProperty("representative")
private Representative representative;
/**
* 别人代理给我 1.0 我获得的带宽值
*/
@JsonProperty("acquiredDelegatedFrozenBalanceForBandwidthValue")
private BigDecimal acquiredDelegatedFrozenBalanceForBandwidthValue;
@JsonProperty("announcement")
private String announcement;
@JsonProperty("allowExchange")
private List<Object> allowExchange;
@JsonProperty("accountType")
private int accountType;
@JsonProperty("totalFrozenBandwidthValue")
private long totalFrozenBandwidthValue;
@JsonProperty("frozen")
private Frozen frozen;
@JsonProperty("balanceStr")
private String balanceStr;
@JsonProperty("transactions")
private int transactions;
/**
*我代理給別人的2.0 trx
*/
@JsonProperty("delegatedFrozenV2BalanceForEnergy")
private long delegatedFrozenV2BalanceForEnergy;
@JsonProperty("totalFrozenEnergyV2Value")
private long totalFrozenEnergyV2Value;
@JsonProperty("name")
private String name;
@JsonProperty("totalFrozenEnergyValue")
private long totalFrozenEnergyValue;
@JsonProperty("frozenForEnergy")
private long frozenForEnergy;
@JsonProperty("energyCost")
private BigDecimal energyCost;
@JsonProperty("activePermissions")
private List<Permission> activePermissions;
/**
* 別人代理給我的 2.0 trx
*/
@JsonProperty("acquiredDelegatedFrozenV2BalanceForBandwidth")
private long acquiredDelegatedFrozenV2BalanceForBandwidth;
@JsonProperty("netCost")
private BigDecimal netCost;
/**
* 别人代理给我的 1.0 trx
*/
@JsonProperty("acquiredDelegateFrozenForBandWidth")
private long acquiredDelegateFrozenForBandWidth;
@JsonProperty("frozenForBandwidthValue")
private long frozenForBandwidthValue;
@JsonProperty("greyTag")
private String greyTag;
/**
* 我代理给别人的 2.0 能量值
*/
@JsonProperty("delegatedFrozenV2BalanceForEnergyValue")
private BigDecimal delegatedFrozenV2BalanceForEnergyValue;
@JsonProperty("withPriceTokens")
private List<TokenBalance> withPriceTokens;
/**
* 别人代理给我 我获得的 Stake 2.0 能量值
*/
@JsonProperty("acquiredDelegatedFrozenV2BalanceForEnergyValue")
private BigDecimal acquiredDelegatedFrozenV2BalanceForEnergyValue;
@JsonProperty("unfreezeV2")
private long unfreezeV2;
/**
* 我代理给别人的 2.0 带宽值
*/
@JsonProperty("delegatedFrozenV2BalanceForBandwidthValue")
private BigDecimal delegatedFrozenV2BalanceForBandwidthValue;
@JsonProperty("feedbackRisk")
private boolean feedbackRisk;
@JsonProperty("voteTotal")
private long voteTotal;
@JsonProperty("totalFrozen")
private long totalFrozen;
@JsonProperty("totalFrozenBandwidthV2Value")
private long totalFrozenBandwidthV2Value;
@JsonProperty("latest_operation_time")
private long latestOperationTime;
@JsonProperty("totalNetRemaining")
private long totalNetRemaining;
@JsonProperty("frozenForBandWidth")
private long frozenForBandWidth;
@JsonProperty("reward")
private int reward;
@JsonProperty("frozenForEnergyV2ValueSum")
private BigDecimal frozenForEnergyV2ValueSum;
@JsonProperty("addressTagLogo")
private String addressTagLogo;
@JsonProperty("address")
private String address;
@JsonProperty("frozen_supply")
private List<Object> frozenSupply;
@JsonProperty("bandwidth")
private Bandwidth bandwidth;
@JsonProperty("date_created")
private long dateCreated;
/**
* 别人代理给我 我获得的 Stake 2.0 Trx
*/
@JsonProperty("acquiredDelegatedFrozenV2BalanceForEnergy")
private long acquiredDelegatedFrozenV2BalanceForEnergy;
@JsonProperty("frozenForBandwidthV2Value")
private long frozenForBandwidthV2Value;
@JsonProperty("frozenForBandwidthV2ValueSum")
private BigDecimal frozenForBandwidthV2ValueSum;
@JsonProperty("accountResource")
private AccountResource accountResource;
@JsonProperty("totalNet")
private long totalNet;
@JsonProperty("blueTag")
private String blueTag;
/**
* 别人代理给我 我获得的 Stake 2.0 带宽值
*/
@JsonProperty("acquiredDelegatedFrozenV2BalanceForBandwidthValue")
private BigDecimal acquiredDelegatedFrozenV2BalanceForBandwidthValue;
@JsonProperty("witness")
private int witness;
@JsonProperty("frozenForEnergyValue")
private long frozenForEnergyValue;
@JsonProperty("freezing")
private long freezing;
/**
* 我代理给别人的带宽trx 1.0
*/
@JsonProperty("delegateFrozenForBandWidth")
private long delegateFrozenForBandWidth;
/**
* 别人代理给我 能量 我获得的 Stake 1.0 能量值
*/
@JsonProperty("acquiredDelegatedFrozenBalanceForEnergyValue")
private BigDecimal acquiredDelegatedFrozenBalanceForEnergyValue;
@JsonProperty("activated")
private boolean activated;
/**
* 别人代理给我的 1.0 能量trx
*/
@JsonProperty("acquiredDelegateFrozenForEnergy")
private long acquiredDelegateFrozenForEnergy;
}
@@ -0,0 +1,65 @@
package com.ruoyi.system.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import com.ruoyi.system.domain.UsdtAggregationTaskItem;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
/**
* 归集任务明细Mapper接口
*
* @author luqj
* @date 2026-01-01
*/
public interface UsdtAggregationTaskItemMapper extends BaseMapper<UsdtAggregationTaskItemPlus>
{
/**
* 查询归集任务明细
*
* @param id 归集任务明细ID
* @return 归集任务明细
*/
public UsdtAggregationTaskItem selectUsdtAggregationTaskItemById(Long id);
/**
* 查询归集任务明细列表
*
* @param usdtAggregationTaskItem 归集任务明细
* @return 归集任务明细集合
*/
public List<UsdtAggregationTaskItem> selectUsdtAggregationTaskItemList(UsdtAggregationTaskItem usdtAggregationTaskItem);
/**
* 新增归集任务明细
*
* @param usdtAggregationTaskItem 归集任务明细
* @return 结果
*/
public int insertUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem);
/**
* 修改归集任务明细
*
* @param usdtAggregationTaskItem 归集任务明细
* @return 结果
*/
public int updateUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem);
/**
* 删除归集任务明细
*
* @param id 归集任务明细ID
* @return 结果
*/
public int deleteUsdtAggregationTaskItemById(Long id);
/**
* 批量删除归集任务明细
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteUsdtAggregationTaskItemByIds(Long[] ids);
}
@@ -0,0 +1,65 @@
package com.ruoyi.system.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import com.ruoyi.system.domain.UsdtAggregationTask;
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
/**
* 归集任务Mapper接口
*
* @author luqj
* @date 2026-01-01
*/
public interface UsdtAggregationTaskMapper extends BaseMapper<UsdtAggregationTaskPlus>
{
/**
* 查询归集任务
*
* @param id 归集任务ID
* @return 归集任务
*/
public UsdtAggregationTask selectUsdtAggregationTaskById(Long id);
/**
* 查询归集任务列表
*
* @param usdtAggregationTask 归集任务
* @return 归集任务集合
*/
public List<UsdtAggregationTask> selectUsdtAggregationTaskList(UsdtAggregationTask usdtAggregationTask);
/**
* 新增归集任务
*
* @param usdtAggregationTask 归集任务
* @return 结果
*/
public int insertUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask);
/**
* 修改归集任务
*
* @param usdtAggregationTask 归集任务
* @return 结果
*/
public int updateUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask);
/**
* 删除归集任务
*
* @param id 归集任务ID
* @return 结果
*/
public int deleteUsdtAggregationTaskById(Long id);
/**
* 批量删除归集任务
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteUsdtAggregationTaskByIds(Long[] ids);
}
@@ -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);
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
@@ -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);
@@ -13,10 +13,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="createdAt" column="created_at" />
<result property="updatedAt" column="updated_at" />
<result property="deletedAt" column="deleted_at" />
<result property="distTokenAddress" column="dist_token_address" />
</resultMap>
<sql id="selectAppsVo">
select id, user_id, name, description, status, created_at, updated_at, deleted_at from apps
select id, user_id, name, dist_token_address,description, status, created_at, updated_at, deleted_at from apps
</sql>
<select id="selectAppsList" parameterType="Apps" resultMap="AppsResult">
@@ -29,6 +30,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null "> and created_at = #{createdAt}</if>
<if test="updatedAt != null "> and updated_at = #{updatedAt}</if>
<if test="deletedAt != null "> and deleted_at = #{deletedAt}</if>
<if test="distTokenAddress != null and distTokenAddress != ''"> and dist_token_address like concat('%', #{distTokenAddress}, '%')</if>
</where>
</select>
@@ -47,6 +49,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null">created_at,</if>
<if test="updatedAt != null">updated_at,</if>
<if test="deletedAt != null">deleted_at,</if>
<if test="distTokenAddress != null">dist_token_address,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userId != null">#{userId},</if>
@@ -56,6 +59,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null">#{createdAt},</if>
<if test="updatedAt != null">#{updatedAt},</if>
<if test="deletedAt != null">#{deletedAt},</if>
<if test="distTokenAddress != null">#{distTokenAddress},</if>
</trim>
</insert>
@@ -69,6 +73,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createdAt != null">created_at = #{createdAt},</if>
<if test="updatedAt != null">updated_at = #{updatedAt},</if>
<if test="deletedAt != null">deleted_at = #{deletedAt},</if>
<if test="distTokenAddress != null">dist_token_address = #{distTokenAddress},</if>
</trim>
where id = #{id}
</update>
@@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.UsdtAggregationTaskItemMapper">
<resultMap type="UsdtAggregationTaskItem" id="UsdtAggregationTaskItemResult">
<result property="id" column="id" />
<result property="tokenAddress" column="token_address" />
<result property="status" column="status" />
<result property="remark" column="remark" />
<result property="opeAmount" column="ope_amount" />
<result property="createdAt" column="created_at" />
<result property="updatedAt" column="updated_at" />
<result property="deletedAt" column="deleted_at" />
<result property="userId" column="user_id" />
<result property="appId" column="app_id" />
<result property="parentId" column="parent_id" />
<result property="distTokenAddress" column="dist_token_address" />
</resultMap>
<sql id="selectUsdtAggregationTaskItemVo">
select id, token_address, status, remark, ope_amount, created_at, updated_at, deleted_at, user_id, app_id, parent_id, dist_token_address from usdt_aggregation_task_item
</sql>
<select id="selectUsdtAggregationTaskItemList" parameterType="UsdtAggregationTaskItem" resultMap="UsdtAggregationTaskItemResult">
<include refid="selectUsdtAggregationTaskItemVo"/>
<where>
<if test="status != null "> and status = #{status}</if>
<if test="remark != null and remark != ''"> and remark like concat('%', #{remark}, '%')</if>
<if test="userId != null "> and user_id = #{userId}</if>
<if test="appId != null "> and app_id = #{appId}</if>
<if test="parentId != null "> and parent_id = #{parentId}</if>
</where>
</select>
<select id="selectUsdtAggregationTaskItemById" parameterType="Long" resultMap="UsdtAggregationTaskItemResult">
<include refid="selectUsdtAggregationTaskItemVo"/>
where id = #{id}
</select>
<insert id="insertUsdtAggregationTaskItem" parameterType="UsdtAggregationTaskItem" useGeneratedKeys="true" keyProperty="id">
insert into usdt_aggregation_task_item
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="tokenAddress != null">token_address,</if>
<if test="status != null">status,</if>
<if test="remark != null">remark,</if>
<if test="opeAmount != null">ope_amount,</if>
<if test="createdAt != null">created_at,</if>
<if test="updatedAt != null">updated_at,</if>
<if test="deletedAt != null">deleted_at,</if>
<if test="userId != null">user_id,</if>
<if test="appId != null">app_id,</if>
<if test="parentId != null">parent_id,</if>
<if test="distTokenAddress != null">dist_token_address,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="tokenAddress != null">#{tokenAddress},</if>
<if test="status != null">#{status},</if>
<if test="remark != null">#{remark},</if>
<if test="opeAmount != null">#{opeAmount},</if>
<if test="createdAt != null">#{createdAt},</if>
<if test="updatedAt != null">#{updatedAt},</if>
<if test="deletedAt != null">#{deletedAt},</if>
<if test="userId != null">#{userId},</if>
<if test="appId != null">#{appId},</if>
<if test="parentId != null">#{parentId},</if>
<if test="distTokenAddress != null">#{distTokenAddress},</if>
</trim>
</insert>
<update id="updateUsdtAggregationTaskItem" parameterType="UsdtAggregationTaskItem">
update usdt_aggregation_task_item
<trim prefix="SET" suffixOverrides=",">
<if test="tokenAddress != null">token_address = #{tokenAddress},</if>
<if test="status != null">status = #{status},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="opeAmount != null">ope_amount = #{opeAmount},</if>
<if test="createdAt != null">created_at = #{createdAt},</if>
<if test="updatedAt != null">updated_at = #{updatedAt},</if>
<if test="deletedAt != null">deleted_at = #{deletedAt},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="appId != null">app_id = #{appId},</if>
<if test="parentId != null">parent_id = #{parentId},</if>
<if test="distTokenAddress != null">dist_token_address = #{distTokenAddress},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteUsdtAggregationTaskItemById" parameterType="Long">
delete from usdt_aggregation_task_item where id = #{id}
</delete>
<delete id="deleteUsdtAggregationTaskItemByIds" parameterType="String">
delete from usdt_aggregation_task_item where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.UsdtAggregationTaskMapper">
<resultMap type="UsdtAggregationTask" id="UsdtAggregationTaskResult">
<result property="id" column="id" />
<result property="taskName" column="task_name" />
<result property="appId" column="app_id" />
<result property="userId" column="user_id" />
<result property="remark" column="remark" />
<result property="status" column="status" />
<result property="createdAt" column="created_at" />
<result property="updatedAt" column="updated_at" />
<result property="deletedAt" column="deleted_at" />
<result property="totalAmount" column="total_amount" />
<result property="exeTime" column="exe_time" />
<result property="verifyStatus" column="verify_status" />
<result property="distTokenAddress" column="dist_token_address" />
</resultMap>
<sql id="selectUsdtAggregationTaskVo">
select id, task_name, app_id, user_id, remark, status, created_at, updated_at, deleted_at, total_amount, exe_time, verify_status, dist_token_address from usdt_aggregation_task
</sql>
<select id="selectUsdtAggregationTaskList" parameterType="UsdtAggregationTask" resultMap="UsdtAggregationTaskResult">
<include refid="selectUsdtAggregationTaskVo"/>
<where>
<if test="taskName != null and taskName != ''"> and task_name like concat('%', #{taskName}, '%')</if>
<if test="appId != null "> and app_id = #{appId}</if>
<if test="userId != null "> and user_id = #{userId}</if>
<if test="status != null "> and status = #{status}</if>
<if test="verifyStatus != null "> and verify_status = #{verifyStatus}</if>
<if test="distTokenAddress != null and distTokenAddress != ''"> and dist_token_address like concat('%', #{distTokenAddress}, '%')</if>
</where>
</select>
<select id="selectUsdtAggregationTaskById" parameterType="Long" resultMap="UsdtAggregationTaskResult">
<include refid="selectUsdtAggregationTaskVo"/>
where id = #{id}
</select>
<insert id="insertUsdtAggregationTask" parameterType="UsdtAggregationTask" useGeneratedKeys="true" keyProperty="id">
insert into usdt_aggregation_task
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="taskName != null">task_name,</if>
<if test="appId != null">app_id,</if>
<if test="userId != null">user_id,</if>
<if test="remark != null">remark,</if>
<if test="status != null">status,</if>
<if test="createdAt != null">created_at,</if>
<if test="updatedAt != null">updated_at,</if>
<if test="deletedAt != null">deleted_at,</if>
<if test="totalAmount != null">total_amount,</if>
<if test="exeTime != null">exe_time,</if>
<if test="verifyStatus != null">verify_status,</if>
<if test="distTokenAddress != null">dist_token_address,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="taskName != null">#{taskName},</if>
<if test="appId != null">#{appId},</if>
<if test="userId != null">#{userId},</if>
<if test="remark != null">#{remark},</if>
<if test="status != null">#{status},</if>
<if test="createdAt != null">#{createdAt},</if>
<if test="updatedAt != null">#{updatedAt},</if>
<if test="deletedAt != null">#{deletedAt},</if>
<if test="totalAmount != null">#{totalAmount},</if>
<if test="exeTime != null">#{exeTime},</if>
<if test="verifyStatus != null">#{verifyStatus},</if>
<if test="distTokenAddress != null">#{distTokenAddress},</if>
</trim>
</insert>
<update id="updateUsdtAggregationTask" parameterType="UsdtAggregationTask">
update usdt_aggregation_task
<trim prefix="SET" suffixOverrides=",">
<if test="taskName != null">task_name = #{taskName},</if>
<if test="appId != null">app_id = #{appId},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="status != null">status = #{status},</if>
<if test="createdAt != null">created_at = #{createdAt},</if>
<if test="updatedAt != null">updated_at = #{updatedAt},</if>
<if test="deletedAt != null">deleted_at = #{deletedAt},</if>
<if test="totalAmount != null">total_amount = #{totalAmount},</if>
<if test="exeTime != null">exe_time = #{exeTime},</if>
<if test="verifyStatus != null">verify_status = #{verifyStatus},</if>
<if test="distTokenAddress != null">dist_token_address = #{distTokenAddress},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteUsdtAggregationTaskById" parameterType="Long">
delete from usdt_aggregation_task where id = #{id}
</delete>
<delete id="deleteUsdtAggregationTaskByIds" parameterType="String">
delete from usdt_aggregation_task where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
@@ -13,12 +13,30 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="deletedAt" column="deleted_at" />
<result property="appId" column="app_id" />
<result property="userId" column="user_id" />
<result property="tokenKey" column="token_key" />
<result property="usdtBalance" column="usdt_balance" />
<result property="trxBalance" column="trx_balance" />
<result property="energyNum" column="energy_num" />
<result property="bandwidthNum" column="bandwidth_num" />
<result property="withdrawUsdtBalance" column="withdraw_usdt_balance" />
<result property="delegatedEnergyTrxNum" column="delegated_energy_trx_num" />
<result property="delegatedEnergyValue" column="delegated_energy_value" />
<result property="acquiredDelegatedEnergyTrxNum" column="acquired_delegated_energy_trx_num" />
<result property="acquiredDelegatedEnergyValue" column="acquired_delegated_energy_value" />
<result property="delegatedBandwidthTrxNum" column="delegated_bandwidth_trx_num" />
<result property="delegatedBandwidthValue" column="delegated_bandwidth_value" />
<result property="acquiredDelegatedBandwidthTrxNum" column="acquired_delegated_bandwidth_trx_num" />
<result property="acquiredDelegatedBandwidthValue" column="acquired_delegated_bandwidth_value" />
<result property="stakedTrxNum" column="staked_trx_num" />
<result property="energyStakedTrxNum" column="energy_staked_trx_num" />
<result property="bandwidthStakedTrxNum" column="bandwidth_staked_trx_num" />
<result property="voteNum" column="vote_num" />
<result property="votedNum" column="voted_num" />
<result property="bandwidthStakedNum" column="bandwidth_staked_num" />
</resultMap>
<sql id="selectWalletAddressVo">
select id, token, status, created_at, updated_at, deleted_at, app_id, user_id,usdt_balance,trx_balance from wallet_address
select id, token, status, created_at, updated_at,bandwidth_staked_num, deleted_at, app_id, user_id, token_key, usdt_balance, trx_balance, energy_num, bandwidth_num, withdraw_usdt_balance, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num from wallet_address
</sql>
<select id="selectWalletAddressList" parameterType="WalletAddress" resultMap="WalletAddressResult">
@@ -26,11 +44,27 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<where>
<if test="token != null and token != ''"> and token = #{token}</if>
<if test="status != null "> and status = #{status}</if>
<if test="createdAt != null "> and created_at = #{createdAt}</if>
<if test="updatedAt != null "> and updated_at = #{updatedAt}</if>
<if test="deletedAt != null "> and deleted_at = #{deletedAt}</if>
<if test="appId != null "> and app_id = #{appId}</if>
<if test="userId != null "> and user_id = #{userId}</if>
<if test="tokenKey != null and tokenKey != ''"> and token_key = #{tokenKey}</if>
<if test="usdtBalance != null "> and usdt_balance = #{usdtBalance}</if>
<if test="trxBalance != null "> and trx_balance = #{trxBalance}</if>
<if test="energyNum != null "> and energy_num = #{energyNum}</if>
<if test="bandwidthNum != null "> and bandwidth_num = #{bandwidthNum}</if>
<if test="withdrawUsdtBalance != null "> and withdraw_usdt_balance = #{withdrawUsdtBalance}</if>
<if test="delegatedEnergyTrxNum != null "> and delegated_energy_trx_num = #{delegatedEnergyTrxNum}</if>
<if test="delegatedEnergyValue != null "> and delegated_energy_value = #{delegatedEnergyValue}</if>
<if test="acquiredDelegatedEnergyTrxNum != null "> and acquired_delegated_energy_trx_num = #{acquiredDelegatedEnergyTrxNum}</if>
<if test="acquiredDelegatedEnergyValue != null "> and acquired_delegated_energy_value = #{acquiredDelegatedEnergyValue}</if>
<if test="delegatedBandwidthTrxNum != null "> and delegated_bandwidth_trx_num = #{delegatedBandwidthTrxNum}</if>
<if test="delegatedBandwidthValue != null "> and delegated_bandwidth_value = #{delegatedBandwidthValue}</if>
<if test="acquiredDelegatedBandwidthTrxNum != null "> and acquired_delegated_bandwidth_trx_num = #{acquiredDelegatedBandwidthTrxNum}</if>
<if test="acquiredDelegatedBandwidthValue != null "> and acquired_delegated_bandwidth_value = #{acquiredDelegatedBandwidthValue}</if>
<if test="stakedTrxNum != null "> and staked_trx_num = #{stakedTrxNum}</if>
<if test="energyStakedTrxNum != null "> and energy_staked_trx_num = #{energyStakedTrxNum}</if>
<if test="bandwidthStakedTrxNum != null "> and bandwidth_staked_trx_num = #{bandwidthStakedTrxNum}</if>
<if test="voteNum != null "> and vote_num = #{voteNum}</if>
<if test="votedNum != null "> and voted_num = #{votedNum}</if>
</where>
</select>
@@ -49,8 +83,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="deletedAt != null">deleted_at,</if>
<if test="appId != null">app_id,</if>
<if test="userId != null">user_id,</if>
<if test="tokenKey != null">token_key,</if>
<if test="usdtBalance != null">usdt_balance,</if>
<if test="trxBalance != null">trx_balance,</if>
<if test="energyNum != null">energy_num,</if>
<if test="bandwidthNum != null">bandwidth_num,</if>
<if test="withdrawUsdtBalance != null">withdraw_usdt_balance,</if>
<if test="delegatedEnergyTrxNum != null">delegated_energy_trx_num,</if>
<if test="delegatedEnergyValue != null">delegated_energy_value,</if>
<if test="acquiredDelegatedEnergyTrxNum != null">acquired_delegated_energy_trx_num,</if>
<if test="acquiredDelegatedEnergyValue != null">acquired_delegated_energy_value,</if>
<if test="delegatedBandwidthTrxNum != null">delegated_bandwidth_trx_num,</if>
<if test="delegatedBandwidthValue != null">delegated_bandwidth_value,</if>
<if test="acquiredDelegatedBandwidthTrxNum != null">acquired_delegated_bandwidth_trx_num,</if>
<if test="acquiredDelegatedBandwidthValue != null">acquired_delegated_bandwidth_value,</if>
<if test="stakedTrxNum != null">staked_trx_num,</if>
<if test="energyStakedTrxNum != null">energy_staked_trx_num,</if>
<if test="bandwidthStakedTrxNum != null">bandwidth_staked_trx_num,</if>
<if test="voteNum != null">vote_num,</if>
<if test="votedNum != null">voted_num,</if>
<if test="bandwidthStakedNum != null">bandwidth_staked_num,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="token != null and token != ''">#{token},</if>
@@ -60,8 +112,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="deletedAt != null">#{deletedAt},</if>
<if test="appId != null">#{appId},</if>
<if test="userId != null">#{userId},</if>
<if test="tokenKey != null">#{tokenKey},</if>
<if test="usdtBalance != null">#{usdtBalance},</if>
<if test="trxBalance != null">#{trxBalance},</if>
<if test="energyNum != null">#{energyNum},</if>
<if test="bandwidthNum != null">#{bandwidthNum},</if>
<if test="withdrawUsdtBalance != null">#{withdrawUsdtBalance},</if>
<if test="delegatedEnergyTrxNum != null">#{delegatedEnergyTrxNum},</if>
<if test="delegatedEnergyValue != null">#{delegatedEnergyValue},</if>
<if test="acquiredDelegatedEnergyTrxNum != null">#{acquiredDelegatedEnergyTrxNum},</if>
<if test="acquiredDelegatedEnergyValue != null">#{acquiredDelegatedEnergyValue},</if>
<if test="delegatedBandwidthTrxNum != null">#{delegatedBandwidthTrxNum},</if>
<if test="delegatedBandwidthValue != null">#{delegatedBandwidthValue},</if>
<if test="acquiredDelegatedBandwidthTrxNum != null">#{acquiredDelegatedBandwidthTrxNum},</if>
<if test="acquiredDelegatedBandwidthValue != null">#{acquiredDelegatedBandwidthValue},</if>
<if test="stakedTrxNum != null">#{stakedTrxNum},</if>
<if test="energyStakedTrxNum != null">#{energyStakedTrxNum},</if>
<if test="bandwidthStakedTrxNum != null">#{bandwidthStakedTrxNum},</if>
<if test="voteNum != null">#{voteNum},</if>
<if test="votedNum != null">#{votedNum},</if>
<if test="bandwidthStakedNum != null">#{bandwidthStakedNum},</if>
</trim>
</insert>
@@ -75,8 +145,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="deletedAt != null">deleted_at = #{deletedAt},</if>
<if test="appId != null">app_id = #{appId},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="tokenKey != null">token_key = #{tokenKey},</if>
<if test="usdtBalance != null">usdt_balance = #{usdtBalance},</if>
<if test="trxBalance != null">trx_balance = #{trxBalance},</if>
<if test="energyNum != null">energy_num = #{energyNum},</if>
<if test="bandwidthNum != null">bandwidth_num = #{bandwidthNum},</if>
<if test="withdrawUsdtBalance != null">withdraw_usdt_balance = #{withdrawUsdtBalance},</if>
<if test="delegatedEnergyTrxNum != null">delegated_energy_trx_num = #{delegatedEnergyTrxNum},</if>
<if test="delegatedEnergyValue != null">delegated_energy_value = #{delegatedEnergyValue},</if>
<if test="acquiredDelegatedEnergyTrxNum != null">acquired_delegated_energy_trx_num = #{acquiredDelegatedEnergyTrxNum},</if>
<if test="acquiredDelegatedEnergyValue != null">acquired_delegated_energy_value = #{acquiredDelegatedEnergyValue},</if>
<if test="delegatedBandwidthTrxNum != null">delegated_bandwidth_trx_num = #{delegatedBandwidthTrxNum},</if>
<if test="delegatedBandwidthValue != null">delegated_bandwidth_value = #{delegatedBandwidthValue},</if>
<if test="acquiredDelegatedBandwidthTrxNum != null">acquired_delegated_bandwidth_trx_num = #{acquiredDelegatedBandwidthTrxNum},</if>
<if test="acquiredDelegatedBandwidthValue != null">acquired_delegated_bandwidth_value = #{acquiredDelegatedBandwidthValue},</if>
<if test="stakedTrxNum != null">staked_trx_num = #{stakedTrxNum},</if>
<if test="energyStakedTrxNum != null">energy_staked_trx_num = #{energyStakedTrxNum},</if>
<if test="bandwidthStakedTrxNum != null">bandwidth_staked_trx_num = #{bandwidthStakedTrxNum},</if>
<if test="voteNum != null">vote_num = #{voteNum},</if>
<if test="votedNum != null">voted_num = #{votedNum},</if>
<if test="bandwidthStakedNum != null">bandwidth_staked_num = #{bandwidthStakedNum},</if>
</trim>
where id = #{id}
</update>
@@ -29,6 +29,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="trxBalance != null "> and trx_balance = #{trxBalance}</if>
<if test="ethBalance != null "> and eth_balance = #{ethBalance}</if>
<if test="password != null and password != ''"> and password = #{password}</if>
<if test="id != null"> and id = #{id}</if>
</where>
</select>