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;
     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM