JAVA使用 web3j 进行token转账

最近新学习了下区块链这方面的知识,所学不多,给大家分享下。

 

# 1. 关于web3j

web3j是一个高度模块化,反应性,类型安全的Java和Android库,用于与智能合约配合并与以太坊网络上的客户端(节点)集成。

 

# 2. 准备工作

  jdk版本1.8   

   引入maven

   

      <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>core</artifactId>
            <version>3.4.0</version>
      </dependency>

 

 

最新的web3j版本请参考 这里

 

# 3. 代码编写

 

 

首先你要创建一个web3j实例

 

Web3j web3j = Web3j.build(new HttpService("XXXXXXXX"))

 

 

 

 

然后是发起交易,这个工具类简单,只要传入入账、出账地址、私钥、以及合约地址就可以进行发起交易操作,最后的精度要判断不同的类型,传入不同的精度。

其中手续费很容易出现问题,要注意。

 

public static String tokenDeal(String from, String to, String value, String privateKey, String contractAddress,int decimal) {
         try {
             //转账的凭证,需要传入私钥
             Credentials credentials = Credentials.create(privateKey);
             //获取交易笔数
             BigInteger nonce;
             EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
             if (ethGetTransactionCount == null) {
                 return null;
             }
             nonce = ethGetTransactionCount.getTransactionCount();
        //手续费
             BigInteger gasPrice;
             EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
             if (ethGasPrice == null) {
                 return null;
             }
             gasPrice = ethGasPrice.getGasPrice();
             //注意手续费的设置,这块很容易遇到问题
             BigInteger gasLimit = BigInteger.valueOf(60000L);
             
             BigInteger val = new BigDecimal(value).multiply(new BigDecimal("10").pow(decimal)).toBigInteger();// 单位换算
             Function function = new Function(
                     "transfer",
                     Arrays.asList(new Address(to), new Uint256(val)),
                     Collections.singletonList(new TypeReference<Type>() {
                     }));
             //创建交易对象
             String encodedFunction = FunctionEncoder.encode(function);
             RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                     contractAddress, encodedFunction);
 
             //进行签名操作
             byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
             String hexValue = Numeric.toHexString(signMessage);
             //发起交易
             EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
             String hash = ethSendTransaction.getTransactionHash();
             if (hash != null) {
                 //执行业务
               return hash;
        }
         } catch (Exception ex){  
        //报错应进行错误处理
             ex.printStackTrace();
         }
             return null;
     }

 

posted @ 2020-05-08 14:20  shineAnthony  阅读(2302)  评论(0编辑  收藏  举报