Web3j使用教程(2)
生活随笔
收集整理的這篇文章主要介紹了
Web3j使用教程(2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
3.加入智能合約
首先安裝solc(用于編譯智能合約)和web3j命令行工具(用于打包智能合約)
npm install -g solc
web3j安裝地址:?Releases · web3j/web3j · GitHub,選擇對應操作系統
首先準備一個智能合約 Owner.sol,建議先在remix上測試一下Remix - Ethereum IDE
//SPDX-License-Identifier:UNLICENSEDpragma solidity >=0.7.0 <0.9.0;contract Qwner {address private owner;event OwnerSet(address oldAddress,address newAddress);modifier isOwner(){require (msg.sender==owner,"Caller is not owner!");_;}constructor (){owner = msg.sender;emit OwnerSet( address(0) , owner);}function changeOwner (address newOwner) public isOwner {emit OwnerSet(owner, newOwner);owner = newOwner;}function getOwner()public view returns (address) {return owner;}}先編譯? solcjs Owner.sol --bin --abi --optimize -o .\ 然后你可以看到當前文件夾下生成了兩個文件,.abi和.bin,這名字有點反人類,最好改成Owner.abi和Owner.bin
?然后打包成把合約打包成Java文件使用如下命令,其中-p是指定包名
web3j ?generate solidity -a src\main\Owner.abi -b src\main\Owner.bin -o src\main\java\?-p com.example
執行完上述命令后可以看到src\main\java\com\example下多了一個Owner.java文件
?接著就是代碼,包括部署智能合約,調用智能合約的函數:
package com.example;import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.List; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.protocol.http.HttpService; import org.web3j.tx.gas.ContractGasProvider; import org.web3j.tx.gas.DefaultGasProvider;class Cpp{public static void main(String[] args) {try {Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:8545"));//創建錢包Credentials defaulCredential = Credentials.create(App.privateKey1);BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();//這個類的作用是你能夠根據你不同函數名稱靈活的選擇不同的GasPrice和GasLimitContractGasProvider myGasProvider = new DefaultGasProvider(){@Overridepublic BigInteger getGasPrice(String contractFunc ) {return gasPrice;}@Overridepublic BigInteger getGasLimit(String contractFunc ){return BigInteger.valueOf(6721975);}}; //部署合約,并打印合約地址Owner myContract = Owner.deploy(web3j, defaulCredential, myGasProvider).send();System.out.println("deploy contract: "+myContract.isValid());System.out.println("contract adddress: "+myContract.getContractAddress());} catch (Exception e) {e.printStackTrace();}} } public class App {static Web3j web3j = null;//ganache上的accounts[0]和accounts[1]的私鑰static String privateKey1 = "0x64685c9589ef1e937e8009eba589059d4b7b10bb44a6efc6eeb436c7f47ab85c";static String privateKey2 = "0xae7d780682ee82c5301152bec4ddb51ada56944135d211130a582f33c52d7c1d";//硬編碼,填入合約部署后輸出的合約地址static String contractAddress = "0x30a856cd0aaf589b99152331ae4bc1193ed32570";public static void main(String[] args ){try {web3j = Web3j.build(new HttpService("http://127.0.0.1:8545"));String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();System.out.println("clientVersion : "+clientVersion);List<String> accounts = web3j.ethAccounts().send().getAccounts(); System.out.println("accounts"+accounts);//連個私鑰accounts[0]和accounts[1]Credentials defaulCredential = Credentials.create(privateKey1);Credentials secondCredentials = Credentials.create(privateKey2);BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();ContractGasProvider myGasProvider = new DefaultGasProvider(){@Overridepublic BigInteger getGasPrice(String contractFunc ) {return gasPrice;}@Overridepublic BigInteger getGasLimit(String contractFunc ){return BigInteger.valueOf(6721975);}};BufferedReader br = new BufferedReader( new InputStreamReader(System.in));String command;//根據地址獲取合約實例,注意這兩個合約實例不同之處在于他們的用戶不同,第一個合約對應accounts[0],第二給合約對應accounts[1]Owner myContract = Owner.load(contractAddress, web3j,defaulCredential , myGasProvider);Owner secondContract = Owner.load(contractAddress, web3j,secondCredentials , myGasProvider);//判斷合約是否合法,這一步也很重要if(myContract.isValid()==false||secondContract.isValid()==false) {throw new Exception("load contract error");}System.out.println("load contract: "+myContract.isValid()+" "+secondContract.isValid());System.out.println("contract adddress: "+myContract.getContractAddress()+" "+secondContract.getContractAddress());boolean exit = false;TransactionReceipt receipt;while (exit == false) {System.out.println("please input command :");command = br.readLine();switch (command){case "set":{//accounts[0]把Owner設成accounts[1],accounts[1]再設成accounts[0],如此循環if( myContract.getOwner().send().equals( accounts.get(0) ) ){receipt = myContract.changeOwner(accounts.get(1)).send(); }else {receipt = secondContract.changeOwner(accounts.get(0)).send(); }System.out.println(receipt);System.out.println("now owner is ");System.out.println(myContract.getOwner().send());break;}case "get":{System.out.println("now owner is ");System.out.println(myContract.getOwner().send());break;}case "exit": {System.out.println("you type exit");exit = true;break;}default :{System.out.println("wrong command input again");break;}}} } catch (Exception e) {System.err.println(e);}} }部署合約(Cpp中main函數輸出)
加載合約并調用合約函數 (App中main函數輸出)
4.事件監聽?
還能監聽區塊鏈事件,主要有三種:監聽區塊,監聽交易,監聽合約事件
package com.example;import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger;import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.http.HttpService; import org.web3j.tx.gas.ContractGasProvider; import org.web3j.tx.gas.DefaultGasProvider;import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable;public class App {static Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:8545"));static String privateKey = "0x36308cc80ca2e632b0fb90d8acbe316d4c23f782f03131d4406a0026ed5de9e7";static String contractAddress = "0x30a856cd0aaf589b99152331ae4bc1193ed32570";static DefaultBlockParameterName earliest = DefaultBlockParameterName.EARLIEST;static DefaultBlockParameterName latest = DefaultBlockParameterName.LATEST;public static void main( String[] args ){try {String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();System.out.println(clientVersion);Credentials defaulCredential = Credentials.create(privateKey);BigInteger gasLimit = BigInteger.valueOf(6721975);BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();ContractGasProvider simplProvider = new DefaultGasProvider(){@Overridepublic BigInteger getGasPrice(String contractFunc ) {return gasPrice;}@Overridepublic BigInteger getGasLimit(String contractFunc ){return gasLimit;}};Owner mycontract = Owner.load(contractAddress, web3j, defaulCredential, simplProvider);if(mycontract.isValid()==false){throw new Exception("load error");}System.out.println("load contract: "+mycontract.isValid());//使用CompositeDisposableCompositeDisposable disposableSet = new CompositeDisposable();//監聽區塊Disposable blockSubscription =web3j.blockFlowable(false).subscribe( block -> {System.out.println("new block: "+block.getBlock().getHash());} );//監聽交易Disposable txsubcription = web3j.transactionFlowable().subscribe( tx -> {System.out.println("new tx: from "+tx.getFrom()+ "; to "+tx.getTo());} );//監聽合約的OwnerSet事件Disposable ownersetSubscription = mycontract.ownerSetEventFlowable(latest, latest).subscribe(res -> {System.out.println(res.log);System.out.println("owner chage: old "+res.oldAddress+" new "+res.newAddress);});disposableSet.add(blockSubscription);disposableSet.add(txsubcription);disposableSet.add(ownersetSubscription);System.out.println(disposableSet);BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String command =null;while(true){System.out.println("input command: ");command = br.readLine();if(command.equals("stop")){disposableSet.dispose();System.out.println(disposableSet);break;} else {continue;}}} catch (Exception e) {System.err.println(e);}} }控制臺輸出:?
?
總結
以上是生活随笔為你收集整理的Web3j使用教程(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机专业指南 专 平时作业,《计算机专
- 下一篇: 第11节:唤醒心灵的巨人