波場錢包 TRC20 充值 提現 解析資料 等功能 重點程式碼公佈

2020-10-15 15:00:15

前提

  1. 匯入springboot 工程
  2. 匯入wallet-cli 到maven中

properties 設定資訊

server.port=8080
#密匙
trc20.privateKey=xxxxx
#trx地址
trc20.trxAddress=xxxx
#合約地址 幣種
trc20.symbol=LIUJH#TW2VVpjBCZVEAGVrTHftjGPFMHLLWSEV4z
#幣種 位數
trc20.wei=TRX#6,LIUJH#18
# http 地址
trc20.http=xxxx
# solidity 地址
trc20.walletSolidityHttp=xxx
#錢包消費最大區塊深度
tron_block_deep=100
#初始高度
tron_block=10000
# 手續費 1trx
trc20.fee=1000000


# Redis資料庫索引(預設為0)
spring.redis.database=0
# Redis伺服器地址
spring.redis.host=000000
# Redis伺服器連線埠
spring.redis.port=6379
# Redis伺服器連線密碼(預設為空)
spring.redis.password=00000
# 連線池最大連線數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=20
# 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1
# 連線池中的最大空閒連線
spring.redis.jedis.pool.max-idle=10
# 連線池中的最小空閒連線
spring.redis.jedis.pool.min-idle=0
# 連線超時時間(毫秒)
spring.redis.timeout=1000

Service類各種介面主要程式碼

   package com.tron.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.Any;
import com.tron.demo.util.TransformUtil;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;
import org.tron.api.GrpcAPI;
import org.tron.common.crypto.SignInterface;
import org.tron.common.crypto.SignUtils;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.Utils;
import org.tron.protos.Protocol;
import org.tron.protos.contract.BalanceContract;
import org.tron.protos.contract.SmartContractOuterClass;
import org.tron.walletserver.WalletApi;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * @Auther: little liu
 * @Date: 2020/09/03/16:06
 * @Description:
 */
@Service
public class TRC20Service {

    private static String privateKey;

    private static String trxAddress;

    private static String http;

    private static String walletSolidityHttp;

    private static String privateHttp;

    private static Long blockNum;

    private static Long blockDeep;

    private static Long fee;

    private static Map<String, String> symbolMap;

    private static Map<String, String> contractMap;

    private static Map<String, Integer> weiMap;

    private BigInteger currentBlock = BigInteger.ZERO;

    @Autowired
    private Environment environment;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostConstruct
    public void initService() {
        privateKey = environment.getProperty("trc20.privateKey");
        trxAddress = environment.getProperty("trc20.trxAddress");
        String symbol = environment.getProperty("trc20.symbol");
        String wei = environment.getProperty("trc20.wei");
        http = environment.getProperty("trc20.http");
        walletSolidityHttp = environment.getProperty("trc20.walletSolidityHttp");
        blockDeep = Long.valueOf(Objects.requireNonNull(environment.getProperty("tron_block_deep")));

        String tronBlock = stringRedisTemplate.opsForValue().get("tron_block");
        if (StringUtils.isEmpty(tronBlock)) {
            stringRedisTemplate.opsForValue().set("tron_block", Objects.requireNonNull(environment.getProperty("tron_block")));
        }

        fee = Long.valueOf(Objects.requireNonNull(environment.getProperty("trc20.fee")));

        String[] symbols = symbol.split(",");

        symbolMap = new HashMap<>();
        contractMap = new HashMap<>();

        for (String s : symbols) {
            symbolMap.put(s.split("#")[0], s.split("#")[1]);
            contractMap.put(s.split("#")[1], s.split("#")[0]);
        }

        String[] weis = wei.split(",");
        weiMap = new HashMap<>();
        for (String s : weis) {
            weiMap.put(s.split("#")[0], Integer.valueOf(s.split("#")[1]));

        }
    }


    /**
     * 建立使用者錢包地址
     **/
    public static String createAddress() {
//        String url = http + "/wallet/generateaddress";
        SignInterface sign = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true);
        byte[] priKey = sign.getPrivateKey();
        byte[] address = sign.getAddress();
        String priKeyStr = Hex.encodeHexString(priKey);
        String base58check = WalletApi.encode58Check(address);
        String hexString = ByteArray.toHexString(address);
        JSONObject jsonAddress = new JSONObject();
        jsonAddress.put("address", base58check);
        jsonAddress.put("hexAddress", hexString);
        jsonAddress.put("privateKey", priKeyStr);
        return jsonAddress.toJSONString();
    }

    /**
     * 啟用地址
     *
     * @param address
     * @return
     */
    public static String createAccount(String address) {
        String url = http + "/wallet/createaccount";
        Map<String, Object> map = new HashMap<>();
        map.put("owner_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(trxAddress)));
        map.put("account_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(address)));
        String param = JSON.toJSONString(map);
        return signAndBroadcast(postForEntity(url, param).getBody(), privateKey);
    }


    /**
     * 獲取TRX地址餘額
     *
     * @param address
     * @return
     */
    public static String getAccount(String address) {
        String url = http + "/wallet/getaccount";
        Map<String, Object> map = new HashMap<>();
        map.put("address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(address)));
        String param = JSON.toJSONString(map);
        return postForEntity(url, param).getBody();
    }

    /**
     * 獲取合約地址餘額
     *
     * @param symbol  幣種
     * @param address 地址
     * @return
     */
    public static String getTrc20Account(String symbol, String address) {
        String url = http + "/wallet/triggerconstantcontract";
        Map<String, Object> map = new HashMap<>();
        address = TransformUtil.addZeroForNum(ByteArray.toHexString(WalletApi.decodeFromBase58Check(address)), 64);
        map.put("contract_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(symbolMap.get(symbol))));
        map.put("function_selector", "balanceOf(address)");
        map.put("parameter", address);
        map.put("owner_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(trxAddress)));
        String param = JSON.toJSONString(map);
        return postForEntity(url, param).getBody();
    }

    /**
     * trc20 轉賬
     *
     * @param symbol    代幣名稱
     * @param toAddress 地址
     * @param amount    數量
     * @return
     */
    public static String trc20Transaction(String symbol, String toAddress, BigDecimal amount) {
        //發起交易
        String url = http + "/wallet/triggersmartcontract";

        Map<String, Object> map = new HashMap<>();

        String to_address = ByteArray.toHexString(WalletApi.decodeFromBase58Check(toAddress));
        to_address = TransformUtil.addZeroForNum(to_address, 64);
        amount = amount.multiply(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get(symbol))));
        String uint256 = TransformUtil.addZeroForNum(amount.toBigInteger().toString(16), 64);

        map.put("owner_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(trxAddress)));
        map.put("contract_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(symbolMap.get(symbol))));
        map.put("function_selector", "transfer(address,uint256)");
        map.put("parameter", to_address + uint256);
        map.put("call_value", 0);
        map.put("fee_limit", fee);

        String param = JSON.toJSONString(map);

        ResponseEntity<String> stringResponseEntity = postForEntity(url, param);

        return signAndBroadcast(JSON.parseObject(stringResponseEntity.getBody()).getString("transaction"), privateKey);
    }

   

    /**
     * trc20 彙集專用介面
     *
     * @param symbol      幣種
     * @param fromAddress 地址
     * @param privateKey  私鑰
     * @param toAddress   地址
     * @param amount      數量
     * @return
     */
    private static String trc20Transaction(String symbol, String fromAddress, String privateKey, String toAddress, BigDecimal amount) {
        //發起交易
        String url = http + "/wallet/triggersmartcontract";

        Map<String, Object> map = new HashMap<>();

        String to_address = ByteArray.toHexString(WalletApi.decodeFromBase58Check(toAddress));
        to_address = TransformUtil.addZeroForNum(to_address, 64);
        amount = amount.multiply(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get(symbol))));
        String uint256 = TransformUtil.addZeroForNum(amount.toBigInteger().toString(16), 64);

        map.put("owner_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(fromAddress)));
        map.put("contract_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(symbolMap.get(symbol))));
        map.put("function_selector", "transfer(address,uint256)");
        map.put("parameter", to_address + uint256);
        map.put("call_value", 0);
        map.put("fee_limit", fee);

        String param = JSON.toJSONString(map);

        ResponseEntity<String> stringResponseEntity = postForEntity(url, param);

        //簽名
        url = http + "/wallet/gettransactionsign";
        map = new HashMap<>();
        map.put("transaction", JSON.parseObject(stringResponseEntity.getBody()).get("transaction"));
        map.put("privateKey", privateKey);
        param = JSON.toJSONString(map);
        stringResponseEntity = postForEntity(url, param);

        //廣播
        url = http + "/wallet/broadcasttransaction";
        stringResponseEntity = postForEntity(url, stringResponseEntity.getBody());

        return stringResponseEntity.getBody();
    }

   

    /**
     * 簽名廣播
     *
     * @param transaction 交易物件
     * @return
     */
    private static String signAndBroadcast(String transaction, String privateKey) {

        //簽名
        String url = http + "/wallet/gettransactionsign";
        Map<String, Object> map = new HashMap<>();
        map.put("transaction", transaction);
        map.put("privateKey", privateKey);
        String param = JSON.toJSONString(map);
        ResponseEntity<String> stringResponseEntity = postForEntity(url, param);

        //廣播
        url = http + "/wallet/broadcasttransaction";
        stringResponseEntity = postForEntity(url, stringResponseEntity.getBody());


        return stringResponseEntity.getBody();
    }


    /**
     * trx 轉賬
     *
     * @param toAddress 地址
     * @param amount    數量
     */
    public static String trxTransaction(String toAddress, BigDecimal amount) {
        String url = http + "/wallet/easytransferbyprivate";
        Map<String, Object> map = new HashMap<>();
        map.put("privateKey", privateKey);
        map.put("toAddress", ByteArray.toHexString(WalletApi.decodeFromBase58Check(toAddress)));
        amount = amount.multiply(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get("TRX"))));
        map.put("amount", amount.toBigInteger());
        String param = JSON.toJSONString(map);
        return postForEntity(url, param).getBody();
    }

    /**
     * 建立 transaction 物件
     *
     * @param toAddress 地址
     * @param amount    數量
     * @return
     */
    public static String transaction(String toAddress, BigDecimal amount) {
        String url = http + "/wallet/createtransaction";
        Map<String, Object> map = new HashMap<>();
        map.put("owner_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(trxAddress)));
        map.put("to_address", ByteArray.toHexString(WalletApi.decodeFromBase58Check(toAddress)));
        amount = amount.multiply(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get("TRX"))));
        map.put("amount", amount.toBigInteger());
        String param = JSON.toJSONString(map);
        return signAndBroadcast(postForEntity(url, param).getBody(), privateKey);
    }


    /**
     * https://cn.developers.tron.network/docs/%E4%BA%A4%E6%98%9311#%E4%BA%A4%E6%98%93%E7%A1%AE%E8%AE%A4%E6%96%B9%E6%B3%95
     * 按交易雜湊查詢交易
     *
     * @param txId 交易id
     * @return
     */
    public static String getTransactionById(String txId) {
        String url = walletSolidityHttp + "/walletsolidity/gettransactionbyid";
        Map<String, Object> map = new HashMap<>();
        map.put("value", txId);
        String param = JSON.toJSONString(map);
        return postForEntity(url, param).getBody();
    }

    /**
     * 查詢交易的 Info 資訊, 包括交易的 fee 資訊, 所在區塊, 虛擬機器器 log 等.
     *
     * @param txId 交易id
     * @return
     */
    public static String getTransactionInfoById(String txId) {
        String url = http + "/wallet/gettransactioninfobyid";
        Map<String, Object> map = new HashMap<>();
        map.put("value", txId);
        String param = JSON.toJSONString(map);
        return postForEntity(url, param).getBody();
    }

    /**
     * 獲取特定區塊的所有交易 Info 資訊
     *
     * @param num 區塊
     * @return
     */
    public static String getTransactionInfoByBlockNum(BigInteger num) {
        String url = http + "/wallet/gettransactioninfobyblocknum";
        Map<String, Object> map = new HashMap<>();
        map.put("num", num);
        String param = JSON.toJSONString(map);
        return postForEntity(url, param).getBody();
    }


    /**
     * 查詢最新區塊
     *
     * @return
     */
    public static String getNowBlock() {
        String url = http + "/wallet/getnowblock";
        return getForEntity(url);
    }


    /**
     * 執行 post 請求
     *
     * @param url   url
     * @param param 請求引數
     * @return
     */
    private static ResponseEntity<String> postForEntity(String url, String param) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> request = new HttpEntity<>(param, headers);
        ResponseEntity<String> result = restTemplate.postForEntity(url, request, String.class);
//        System.out.println("url:" + url + ",param:" + param + ",result:" + result.getBody());
        return result;
    }

    /**
     * 執行 get 請求
     *
     * @param url url
     * @return
     */
    private static String getForEntity(String url) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
//        System.out.println("url:" + url + ",result:" + result.getBody());
        return result.getBody();
    }

    public void monitorCoinListener() {

        //獲取所有使用者充值地址
        List<String> addressList = new ArrayList<>();
        addressList.add("xxxx");

        /*Long block = Long.valueOf(Objects.requireNonNull(stringRedisTemplate.opsForValue().get("tron_block")));
        if (currentBlock.longValue() > block) {
            // rpcTransactionInfo(addressList, Long.valueOf(tron_block));
            httpTransactionInfo(addressList, block);
            System.out.println(currentBlock + "===========tron_block=======" + block);
            stringRedisTemplate.opsForValue().set("tron_block", new BigInteger(block.toString()).add(BigInteger.ONE).toString());
        }*/

        int end = currentBlock.intValue();
        for (int i = end; i > 0; i--) {
            if (end - i > blockDeep) {
                break;
            }
            //Wallet rpc 請求
//            rpcTransactionInfo(addressList, (long) i);
            // http 請求
            httpTransactionInfo(addressList, (long) i);
        }
    }

    /**
     * 根據 txId 查詢交易是否成功
     *
     * @param txId 交易id
     * @return
     */
    private boolean transactionStatus(String txId) {
        JSONObject parseObject = JSON.parseObject(getTransactionById(txId));
        if (StringUtils.isEmpty(parseObject.toJSONString())) {
            return false;
        }
        String contractRet = parseObject.getJSONArray("ret").getJSONObject(0).getString("contractRet");
        return "SUCCESS".equals(contractRet);
    }


    private void httpTransactionInfo(List<String> addressList, Long num) {
        String transactionInfoByBlockNum = getTransactionInfoByBlockNum(BigInteger.valueOf(num));
        JSONArray parseArray = JSON.parseArray(transactionInfoByBlockNum);
        if (parseArray.size() > 0) {
            parseArray.forEach(e -> {
                try {
                    String txId = JSON.parseObject(e.toString()).getString("id");
                    //判斷 資料庫 txId 有 就不用往下繼續了

                    JSONObject parseObject = JSON.parseObject(getTransactionById(txId));
                    String contractRet = parseObject.getJSONArray("ret").getJSONObject(0).getString("contractRet");
                    //交易成功
                    if ("SUCCESS".equals(contractRet)) {
                        String type = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getString("type");
                        if ("TriggerSmartContract".equals(type)) {
                            //合約地址轉賬
                            triggerSmartContract(addressList, txId, parseObject);

                        } else if ("TransferContract".equals(type)) {
                            //trx 轉賬
                            transferContract(parseObject);
                        }
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            });
        }
    }


    private void rpcTransactionInfo(List<String> addressList, Long num) {
        try {
            Optional<GrpcAPI.TransactionInfoList> optional = WalletApi.getTransactionInfoByBlockNum(num);
            if (!optional.isPresent()) {
                return;
            }

            List<Protocol.TransactionInfo> transactionInfoList = optional.get().getTransactionInfoList();
            for (Protocol.TransactionInfo transactionInfo : transactionInfoList) {
                String txId = ByteArray.toHexString(transactionInfo.getId().toByteArray());
                //判斷 資料庫 txId 有 就不用往下繼續了

                Optional<Protocol.Transaction> transaction = WalletApi.getTransactionById(txId);
                if (!transaction.isPresent()) {
                    continue;
                }

                List<Protocol.Transaction.Result> retList = transaction.get().getRetList();
                Protocol.Transaction.Result.contractResult contractRet = retList.get(0).getContractRet();
                if (!Protocol.Transaction.Result.contractResult.SUCCESS.name().equals(contractRet.name())) {
                    continue;
                }

                Protocol.Transaction.Contract.ContractType type = transaction.get().getRawData().getContract(0).getType();
                Any contractParameter = transaction.get().getRawData().getContract(0).getParameter();

                if (Protocol.Transaction.Contract.ContractType.TriggerSmartContract.name().equals(type.name())) {
                    // trc20 充值

                    SmartContractOuterClass.TriggerSmartContract deployContract = contractParameter
                            .unpack(SmartContractOuterClass.TriggerSmartContract.class);

                    String owner_address = WalletApi.encode58Check(ByteArray.fromHexString(ByteArray.toHexString(deployContract.getOwnerAddress().toByteArray())));
                    String contract_address = WalletApi.encode58Check(ByteArray.fromHexString(ByteArray.toHexString(deployContract.getContractAddress().toByteArray())));

                    String dataStr = ByteArray.toHexString(deployContract.getData().toByteArray()).substring(8);
                    List<String> strList = TransformUtil.getStrList(dataStr, 64);
                    if (strList.size() != 2) {
                        continue;
                    }

                    String to_address = TransformUtil.delZeroForNum(strList.get(0));
                    if (!to_address.startsWith("41")) {
                        to_address = "41" + to_address;
                    }

                    to_address = WalletApi.encode58Check(ByteArray.fromHexString(to_address));

                    String amountStr = TransformUtil.delZeroForNum(strList.get(1));
                    if (amountStr.length() > 0) {
                        amountStr = new BigInteger(amountStr, 16).toString(10);
                    }

                    BigDecimal amount = BigDecimal.ZERO;
                    //相匹配的合約地址
                    if (!contractMap.containsKey(contract_address)) {
                        continue;
                    }
                    //合約幣種
                    String symbol = contractMap.get(contract_address);
                    if (StringUtils.isNotEmpty(amountStr)) {
                        amount = new BigDecimal(amountStr).divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get(symbol))));
                    }
                    for (String address : addressList) {
                        if (address.equals(to_address)) {
                            System.out.println("===to_address:" + to_address + "===amount:" + amount);
                        }
                    }

                } else if (Protocol.Transaction.Contract.ContractType.TransferContract.name().equals(type.name())) {
                    // trx 充值
                    BalanceContract.TransferContract deployContract = contractParameter
                            .unpack(BalanceContract.TransferContract.class);
                    String owner_address = WalletApi.encode58Check(ByteArray.fromHexString(ByteArray.toHexString(deployContract.getOwnerAddress().toByteArray())));
                    String to_address = WalletApi.encode58Check(ByteArray.fromHexString(ByteArray.toHexString(deployContract.getToAddress().toByteArray())));
                    BigDecimal amount = new BigDecimal(deployContract.getAmount());
                    amount = amount.divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get("TRX"))));

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void transferContract(JSONObject parseObject) {
        //數量
        BigDecimal amount = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getBigDecimal("amount");

        //呼叫者地址
        String owner_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("owner_address");
        owner_address = WalletApi.encode58Check(ByteArray.fromHexString(owner_address));

        //轉入地址
        String to_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("to_address");
        to_address = WalletApi.encode58Check(ByteArray.fromHexString(to_address));

        amount = amount.divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get("TRX"))));


    }

    private void triggerSmartContract(List<String> addressList, String txId, JSONObject parseObject) {
        //方法引數
        String data = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("data");
        // 呼叫者地址
        String owner_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("owner_address");
        owner_address = WalletApi.encode58Check(ByteArray.fromHexString(owner_address));
        // 合約地址
        String contract_address = parseObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0).getJSONObject("parameter").getJSONObject("value").getString("contract_address");
        contract_address = WalletApi.encode58Check(ByteArray.fromHexString(contract_address));

        String dataStr = data.substring(8);
        List<String> strList = TransformUtil.getStrList(dataStr, 64);

        if (strList.size() != 2) {
            return;
        }

        String to_address = TransformUtil.delZeroForNum(strList.get(0));
        if (!to_address.startsWith("41")) {
            to_address = "41" + to_address;
        }

        to_address = WalletApi.encode58Check(ByteArray.fromHexString(to_address));

        String amountStr = TransformUtil.delZeroForNum(strList.get(1));

        if (amountStr.length() > 0) {
            amountStr = new BigInteger(amountStr, 16).toString(10);
        }

        BigDecimal amount = BigDecimal.ZERO;
        //相匹配的合約地址
        if (!contractMap.containsKey(contract_address)) {
            return;
        }

        //幣種
        String symbol = contractMap.get(contract_address);
        if (StringUtils.isNotEmpty(amountStr)) {
            amount = new BigDecimal(amountStr).divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get(symbol))));
        }

        for (String address : addressList) {
            if (address.equals(to_address)) {
                System.out.println("===to_address:" + to_address + "===amount:" + amount);
            }

        }

    }


    /**
     * 快取最新深度
     */
    public void blockDeepListener() {
        try {
            //當前區塊高度
            currentBlock = JSON.parseObject(getNowBlock()).getJSONObject("block_header").getJSONObject("raw_data").getBigInteger("number");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    public void collectionTrc20Listener() {
        try {
            //獲取需要彙集使用者地址
            Map<String, String> addressMap = new HashMap<>();
            addressMap.put("xxx", "xxxx");
            //彙集到的地址
            String toAddress = "xxx";
            String fromAddress = null;
            String privateKey = null;

            for (String symbol : symbolMap.keySet()) {
                for (String key : addressMap.keySet()) {
                    fromAddress = key;
                    privateKey = addressMap.get(key);
                    String trc20Account = getTrc20Account(symbol, fromAddress);
                    JSONObject jsonObject = JSON.parseObject(trc20Account);
                    String constant_result = jsonObject.getString("constant_result");

                    if (StringUtils.isEmpty(constant_result)) {
                        continue;
                    }

                    List<String> strings = JSON.parseArray(constant_result.toString(), String.class);

                    String data = strings.get(0).replaceAll("^(0+)", "");
                    if (data.length() == 0) {
                        continue;
                    }

                    String amountStr = new BigInteger(data, 16).toString();
                    BigDecimal amount = new BigDecimal(amountStr).divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get(symbol))));

                    if (amount.compareTo(BigDecimal.ONE) < 0) {
                        continue;
                    }

                    String account = getAccount(fromAddress);
                    String accountBalance = JSON.parseObject(account).getString("balance");
                    BigDecimal balance = BigDecimal.ZERO;

                    if (StringUtils.isNotEmpty(accountBalance)) {
                        balance = new BigDecimal(accountBalance).divide(new BigDecimal(1 + TransformUtil.getSeqNumByLong(0L, weiMap.get("TRX"))));
                    }

                    if (balance.compareTo(new BigDecimal("0.5")) < 0) {
                        // 充值手續費
                        String transaction = transaction(fromAddress, new BigDecimal("0.5"));
                        continue;
                    }

                    // 彙集 轉賬
                    String transaction = trc20Transaction(symbol, fromAddress, privateKey, toAddress, amount);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

工具類

package com.tron.demo.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: little liu
 * @Date: 2020/09/03/16:03
 * @Description:
 */
public class TransformUtil {


    /**
     * 長度不夠前面補0
     *
     * @param str
     * @param strLength
     * @return
     */
    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左補0
                // sb.append(str).append("0");//右補0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

    public static String delZeroForNum(String str) {
       return str.replaceAll("^(0+)", "");
    }

    public static String getSeqNumByLong(Long l, int bitCount) {
        return String.format("%0" + bitCount + "d", l);
    }


    /**
     * 字串轉換為16進位制字串
     *
     * @param s
     * @return
     */
    public static String stringToHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    /**
     * 16進位制字串轉換為字串
     *
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 16進位製表示的字串轉換為位元組陣列
     *
     * @param s 16進位製表示的字串
     * @return byte[] 位元組陣列
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 兩位一組,表示一個位元組,把這樣表示的16進位制字串,還原成一個位元組
            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return b;
    }

    /**
     * byte陣列轉16進位制字串
     *
     * @param bArray
     * @return
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * @param: [hex]
     * @return: int
     * @description: 按位元計算,位值乘權重
     */
    public static int hexToDecimal(String hex) {
        int outcome = 0;
        for (int i = 0; i < hex.length(); i++) {
            char hexChar = hex.charAt(i);
            outcome = outcome * 16 + charToDecimal(hexChar);
        }
        return outcome;
    }

    /**
     * @param: [c]
     * @return: int
     * @description:將字元轉化為數位
     */
    public static int charToDecimal(char c) {
        if (c >= 'A' && c <= 'F')
            return 10 + c - 'A';
        else
            return c - '0';
    }




    /**
     * 把原始字串分割成指定長度的字串列表
     *
     * @param inputString
     *            原始字串
     * @param length
     *            指定長度
     * @return
     */
    public static List<String> getStrList(String inputString, int length) {
        int size = inputString.length() / length;
        if (inputString.length() % length != 0) {
            size += 1;
        }
        return getStrList(inputString, length, size);
    }

    /**
     * 把原始字串分割成指定長度的字串列表
     *
     * @param inputString
     *            原始字串
     * @param length
     *            指定長度
     * @param size
     *            指定列表大小
     * @return
     */
    public static List<String> getStrList(String inputString, int length,
                                          int size) {
        List<String> list = new ArrayList<String>();
        for (int index = 0; index < size; index++) {
            String childStr = substring(inputString, index * length,
                    (index + 1) * length);
            list.add(childStr);
        }
        return list;
    }

    /**
     * 分割字串,如果開始位置大於字串長度,返回空
     *
     * @param str
     *            原始字串
     * @param f
     *            開始位置
     * @param t
     *            結束位置
     * @return
     */
    public static String substring(String str, int f, int t) {
        if (f > str.length())
            return null;
        if (t > str.length()) {
            return str.substring(f, str.length());
        } else {
            return str.substring(f, t);
        }
    }

}

參考檔案
https://github.com/tronprotocol 官方github
https://cn.developers.tron.network/ 官方對接檔案
有什麼不對的地方歡迎留言我也好改進 謝謝
關於充值監控有更好的方法也歡迎指導一下小編 謝謝