最近新學習了下區塊鏈這方面的知識,所學不多,給大家分享下,
# 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; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/623.html
標籤:區塊鏈
上一篇:返回列表