TRC20

1,974 阅读3分钟

因最近接手一个项目,涉及到波场和以太坊,自己学习了一下,以下为学习的记录。有不足之处,还请大家多多指教。话不多说,直接干。

波场需要准备的工具

1、TronLink: 需要准备两个tronLink的account,可在谷歌浏览器中进行插件搜索,加入组件到浏览器中,打开之后创建属于自己的account,通过此处nileex.io/join/getJoi…领取测试币。

2、所需的jar包 首先是TRC20的交互,TRC20的交互需要以下依赖包,org.tron.trident.abi,org.tron.trident.utils,org.tron.trident.core,大家可以通过此路径下载github.com/tronprotoco…下载后通过gradle进行打包。通过maven引入项目中使用即可。

相关的使用方法

1、生成tron的account地址及私钥

public static JSONObject getTrc20Address() {
        KeyPair keyPair = KeyPair.generate();
        JSONObject json = new JSONObject();
        json.put("privateKey", keyPair.toPrivateKey());
        json.put("address", keyPair.toBase58CheckAddress());
        return json;
    }

2、查询account的TRX的币数量

public static Long getTrxBalance(String addrss) {
        //此处私钥生成即可
       KeyPair keyPair = KeyPair.generate();
       //切换主网的话需要将此处改为ApiWrapper.ofMainnet(私钥"", "Api-Key")
       ApiWrapper wrapper = ApiWrapper.ofNile(keyPair.toPrivateKey());
       Long balance;
       try {
           balance = wrapper.getAccount(addrss).getBalance();
       } catch (Exception e) {
           balance = -1L;
       } finally {
           wrapper.close();
       }
       return balance;
   } 

注:此处返回的币数量单位为sun,可以使用Convert.fromSun(String.valueOf(balance), Convert.Unit.TRX)进行转换

3、查询USDT数量,使用USDT举例

public static BigInteger getBalance(String addrss, String contractAddress) {
 	//USDT测试网络合约地址为TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj
     KeyPair keyPair = KeyPair.generate();
     ApiWrapper wrapper = ApiWrapper.ofNile(keyPair.toPrivateKey());
     BigInteger balance;
     try {
         Contract contract = wrapper.getContract(contractAddress);
         Trc20Contract token = new Trc20Contract(contract, addrss, wrapper);
         balance = token.balanceOf(addrss);
         wrapper.close();
     } catch (Exception e) {
         log.info("查询代币数量失败:{}", e.getMessage());
         balance = BigInteger.ZERO;
     } finally {
         wrapper.close();
     }
     return balance;
 }

注:此处返回的数量为sun,可以使用Convert.fromSun(String.valueOf(balance), Convert.Unit.TRX)进行转换。

4、TRX转移

   
   public static String transferTrx(String privateKey, String fromAddress, String toAddress, Long amount) {
      log.info("从:" + fromAddress + "转移TRX" + amount + "到:" + toAddress);
      ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey);
      String ret = "";
      try {
          org.tron.trident.proto.Response.TransactionExtention transaction = apiWrapper.transfer(fromAddress, toAddress, amount);
          Chain.Transaction signedTxn = apiWrapper.signTransaction(transaction);
          ret = apiWrapper.broadcastTransaction(signedTxn);
          log.info("转移成功,哈希:" + JSONObject.toJSONString(ret));
      } catch (Exception e) {
          e.printStackTrace();
      } finally {
          apiWrapper.close();
      }
      return ret;
  }

注:此处的amount需要传入为sun单位的数值。返回的ID为区块链中的哈希值,可以通过此哈希值对此笔转移的详情进行查询

5、查询TRX转移详情

public static org.tron.trident.proto.Response.TransactionInfo getTransactionById(String transactionId) {
       KeyPair keyPair = KeyPair.generate();
       ApiWrapper wrapper = ApiWrapper.ofNile(keyPair.toPrivateKey());
       org.tron.trident.proto.Response.TransactionInfo info = null;
       try {
           info = wrapper.getTransactionInfoById(transactionId);
           if (ObjectUtil.isEmpty(info)) {
               info = wrapper.getTransactionInfoById(transactionId);
           }
           System.out.println("查询详情成功:\n" + info);
           System.out.println("解码ID:" + Hex.toHexString(info.getId().toByteArray()));
       } catch (Exception e) {
           return info;
       } finally {
           wrapper.close();
       }
       return info;
   }

注:公共接口返回的id为ByteString格式,转为Hex格式,返回的字段解释如下:

id:区块链ID(哈希值)

blockNumber:区块高度

blockTimeStamp:区块日期

contractResult:合约返回内容(因此处为TRX普通转移,未调用合约,因此为空)

net_usage:消耗的带宽

6、TRC20转移

public static String transferTrc(String fromAddress, String toAddress, String amount, String contractAddress, String privateKey) {
        ApiWrapper wrapper = ApiWrapper.ofNile(privateKey);
        String ret = "";
        try {
            //根据合约地址获取封装好的合约
            Contract contract = wrapper.getContract(contractAddress);
            //创建一个TRC20合约对象
            Trc20Contract token = new Trc20Contract(contract, fromAddress, wrapper);
            //获取想要转移的数量
            BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
            //设置最大手续费
            long maxTrx = Convert.toSun("17", Convert.Unit.TRX).longValue();
            ret = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", maxTrx);
            log.info("哈希:" + ret);
        } catch (Exception e) {
            log.info("转移失败:{}", e.getMessage());
        } finally {
            wrapper.close();
        }
        return ret;
    }

7、查询ERC20转移详情

查询ERC20转移详情使用方法和查询TRX转移详情一致,就不在此赘述,直接贴返回值

8、归集

因归集代码涉及到隐私,不在此公开代码,大概逻辑为将子account中的代币归集到统一的account中,感兴趣的朋友可以私信我。

以上为本项目中波场用到的一些代码,仅供大家交流学习,以太坊的在后期也会发布。