当前位置:   article > 正文

Web3j使用教程(2)_conflux.web3j

conflux.web3j

3.加入智能合约

首先安装solc(用于编译智能合约)和web3j命令行工具(用于打包智能合约)

npm install -g solc

web3j安装地址: Releases · web3j/web3j · GitHub,选择对应操作系统

首先准备一个智能合约 Owner.sol,建议先在remix上测试一下Remix - Ethereum IDE

  1. //SPDX-License-Identifier:UNLICENSED
  2. pragma solidity >=0.7.0 <0.9.0;
  3. contract Qwner {
  4. address private owner;
  5. event OwnerSet(address oldAddress,address newAddress);
  6. modifier isOwner(){
  7. require (msg.sender==owner,"Caller is not owner!");
  8. _;
  9. }
  10. constructor (){
  11. owner = msg.sender;
  12. emit OwnerSet( address(0) , owner);
  13. }
  14. function changeOwner (address newOwner) public isOwner {
  15. emit OwnerSet(owner, newOwner);
  16. owner = newOwner;
  17. }
  18. function getOwner()public view returns (address) {
  19. return owner;
  20. }
  21. }

先编译  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文件

 接着就是代码,包括部署智能合约,调用智能合约的函数:

  1. package com.example;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.math.BigInteger;
  5. import java.util.List;
  6. import org.web3j.crypto.Credentials;
  7. import org.web3j.protocol.Web3j;
  8. import org.web3j.protocol.core.methods.response.TransactionReceipt;
  9. import org.web3j.protocol.http.HttpService;
  10. import org.web3j.tx.gas.ContractGasProvider;
  11. import org.web3j.tx.gas.DefaultGasProvider;
  12. class Cpp{
  13. public static void main(String[] args) {
  14. try {
  15. Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:8545"));
  16. //创建钱包
  17. Credentials defaulCredential = Credentials.create(App.privateKey1);
  18. BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
  19. //这个类的作用是你能够根据你不同函数名称灵活的选择不同的GasPrice和GasLimit
  20. ContractGasProvider myGasProvider = new DefaultGasProvider(){
  21. @Override
  22. public BigInteger getGasPrice(String contractFunc ) {
  23. return gasPrice;
  24. }
  25. @Override
  26. public BigInteger getGasLimit(String contractFunc ){
  27. return BigInteger.valueOf(6721975);
  28. }
  29. };
  30. //部署合约,并打印合约地址
  31. Owner myContract = Owner.deploy(web3j, defaulCredential, myGasProvider).send();
  32. System.out.println("deploy contract: "+myContract.isValid());
  33. System.out.println("contract adddress: "+myContract.getContractAddress());
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
  39. public class App
  40. {
  41. static Web3j web3j = null;
  42. //ganache上的accounts[0]和accounts[1]的私钥
  43. static String privateKey1 = "0x64685c9589ef1e937e8009eba589059d4b7b10bb44a6efc6eeb436c7f47ab85c";
  44. static String privateKey2 = "0xae7d780682ee82c5301152bec4ddb51ada56944135d211130a582f33c52d7c1d";
  45. //硬编码,填入合约部署后输出的合约地址
  46. static String contractAddress = "0x30a856cd0aaf589b99152331ae4bc1193ed32570";
  47. public static void main(String[] args )
  48. {
  49. try {
  50. web3j = Web3j.build(new HttpService("http://127.0.0.1:8545"));
  51. String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();
  52. System.out.println("clientVersion : "+clientVersion);
  53. List<String> accounts = web3j.ethAccounts().send().getAccounts();
  54. System.out.println("accounts"+accounts);
  55. //连个私钥accounts[0]和accounts[1]
  56. Credentials defaulCredential = Credentials.create(privateKey1);
  57. Credentials secondCredentials = Credentials.create(privateKey2);
  58. BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
  59. ContractGasProvider myGasProvider = new DefaultGasProvider(){
  60. @Override
  61. public BigInteger getGasPrice(String contractFunc ) {
  62. return gasPrice;
  63. }
  64. @Override
  65. public BigInteger getGasLimit(String contractFunc ){
  66. return BigInteger.valueOf(6721975);
  67. }
  68. };
  69. BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
  70. String command;
  71. //根据地址获取合约实例,注意这两个合约实例不同之处在于他们的用户不同,第一个合约对应accounts[0],第二给合约对应accounts[1]
  72. Owner myContract = Owner.load(contractAddress, web3j,defaulCredential , myGasProvider);
  73. Owner secondContract = Owner.load(contractAddress, web3j,secondCredentials , myGasProvider);
  74. //判断合约是否合法,这一步也很重要
  75. if(myContract.isValid()==false||secondContract.isValid()==false) {
  76. throw new Exception("load contract error");
  77. }
  78. System.out.println("load contract: "+myContract.isValid()+" "+secondContract.isValid());
  79. System.out.println("contract adddress: "+myContract.getContractAddress()+" "+secondContract.getContractAddress());
  80. boolean exit = false;
  81. TransactionReceipt receipt;
  82. while (exit == false) {
  83. System.out.println("please input command :");
  84. command = br.readLine();
  85. switch (command){
  86. case "set":{
  87. //accounts[0]把Owner设成accounts[1],accounts[1]再设成accounts[0],如此循环
  88. if( myContract.getOwner().send().equals( accounts.get(0) ) ){
  89. receipt = myContract.changeOwner(accounts.get(1)).send();
  90. }
  91. else {
  92. receipt = secondContract.changeOwner(accounts.get(0)).send();
  93. }
  94. System.out.println(receipt);
  95. System.out.println("now owner is ");
  96. System.out.println(myContract.getOwner().send());
  97. break;
  98. }
  99. case "get":{
  100. System.out.println("now owner is ");
  101. System.out.println(myContract.getOwner().send());
  102. break;
  103. }
  104. case "exit": {
  105. System.out.println("you type exit");
  106. exit = true;
  107. break;
  108. }
  109. default :{
  110. System.out.println("wrong command input again");
  111. break;
  112. }
  113. }
  114. }
  115. } catch (Exception e) {
  116. System.err.println(e);
  117. }
  118. }
  119. }

部署合约(Cpp中main函数输出)

加载合约并调用合约函数 (App中main函数输出)

4.事件监听 

还能监听区块链事件,主要有三种:监听区块,监听交易,监听合约事件

  1. package com.example;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.math.BigInteger;
  5. import org.web3j.crypto.Credentials;
  6. import org.web3j.protocol.Web3j;
  7. import org.web3j.protocol.core.DefaultBlockParameterName;
  8. import org.web3j.protocol.http.HttpService;
  9. import org.web3j.tx.gas.ContractGasProvider;
  10. import org.web3j.tx.gas.DefaultGasProvider;
  11. import io.reactivex.disposables.CompositeDisposable;
  12. import io.reactivex.disposables.Disposable;
  13. public class App
  14. {
  15. static Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:8545"));
  16. static String privateKey = "0x36308cc80ca2e632b0fb90d8acbe316d4c23f782f03131d4406a0026ed5de9e7";
  17. static String contractAddress = "0x30a856cd0aaf589b99152331ae4bc1193ed32570";
  18. static DefaultBlockParameterName earliest = DefaultBlockParameterName.EARLIEST;
  19. static DefaultBlockParameterName latest = DefaultBlockParameterName.LATEST;
  20. public static void main( String[] args )
  21. {
  22. try {
  23. String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();
  24. System.out.println(clientVersion);
  25. Credentials defaulCredential = Credentials.create(privateKey);
  26. BigInteger gasLimit = BigInteger.valueOf(6721975);
  27. BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
  28. ContractGasProvider simplProvider = new DefaultGasProvider(){
  29. @Override
  30. public BigInteger getGasPrice(String contractFunc ) {
  31. return gasPrice;
  32. }
  33. @Override
  34. public BigInteger getGasLimit(String contractFunc ){
  35. return gasLimit;
  36. }
  37. };
  38. Owner mycontract = Owner.load(contractAddress, web3j, defaulCredential, simplProvider);
  39. if(mycontract.isValid()==false){
  40. throw new Exception("load error");
  41. }
  42. System.out.println("load contract: "+mycontract.isValid());
  43. //使用CompositeDisposable
  44. CompositeDisposable disposableSet = new CompositeDisposable();
  45. //监听区块
  46. Disposable blockSubscription =web3j.blockFlowable(false).subscribe( block -> {
  47. System.out.println("new block: "+block.getBlock().getHash());
  48. } );
  49. //监听交易
  50. Disposable txsubcription = web3j.transactionFlowable().subscribe( tx -> {
  51. System.out.println("new tx: from "+tx.getFrom()+ "; to "+tx.getTo());
  52. } );
  53. //监听合约的OwnerSet事件
  54. Disposable ownersetSubscription = mycontract.ownerSetEventFlowable(latest, latest).subscribe(res -> {
  55. System.out.println(res.log);
  56. System.out.println("owner chage: old "+res.oldAddress+" new "+res.newAddress);
  57. });
  58. disposableSet.add(blockSubscription);
  59. disposableSet.add(txsubcription);
  60. disposableSet.add(ownersetSubscription);
  61. System.out.println(disposableSet);
  62. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  63. String command =null;
  64. while(true){
  65. System.out.println("input command: ");
  66. command = br.readLine();
  67. if(command.equals("stop")){
  68. disposableSet.dispose();
  69. System.out.println(disposableSet);
  70. break;
  71. } else {
  72. continue;
  73. }
  74. }
  75. } catch (Exception e) {
  76. System.err.println(e);
  77. }
  78. }
  79. }

控制台输出: 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/419534
推荐阅读
  

闽ICP备14008679号