Web3j使用教程(2)

这篇具有很好参考价值的文章主要介绍了Web3j使用教程(2)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

3.加入智能合约

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

npm install -g solc

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

Web3j使用教程(2)

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

//SPDX-License-Identifier:UNLICENSED

pragma 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

Web3j使用教程(2)

 然后打包成把合约打包成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文件

Web3j使用教程(2)

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

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和GasLimit
            ContractGasProvider  myGasProvider = new DefaultGasProvider(){
                @Override
                public BigInteger getGasPrice(String contractFunc ) {
                    return gasPrice;
                }
                @Override
                public 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(){
                @Override
                public BigInteger getGasPrice(String contractFunc ) {
                    return gasPrice;
                }
                @Override
                public 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函数输出)

Web3j使用教程(2)

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

Web3j使用教程(2)

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(){
                @Override
                public BigInteger getGasPrice(String contractFunc ) {
                    return gasPrice;
                }
                @Override
                public 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());

            //使用CompositeDisposable
            CompositeDisposable 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)

 文章来源地址https://www.toymoban.com/news/detail-423158.html

到了这里,关于Web3j使用教程(2)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【web3j】java通过web3j监听并解析合约中的事件(event/emit)

    ① 查询链上数据用的rpc(本示例是binance的,测试网可以使用:https://data-seed-prebsc-2-s2.binance.org:8545) ② 自己还要有一个测试链上部署好的合约,合约中要有一个方法emit了事件。 ③ java依赖 一、 通过自己合约的abi和bin生成一个java文件,abi和bin可以在remix的compiler模块中获取,

    2024年02月09日
    浏览(25)
  • Web3j使用教程(2)

    首先安装solc(用于编译智能合约)和web3j命令行工具(用于打包智能合约) npm install -g solc web3j安装地址: Releases · web3j/web3j · GitHub,选择对应操作系统 首先准备一个智能合约 Owner.sol,建议先在remix上测试一下Remix - Ethereum IDE 先编译  solcjs Owner.sol --bin --abi --optimize -o . 然后

    2023年04月24日
    浏览(31)
  • web3j的基础用法-6合约的监听器事件Event和过滤器EthFilter,以及NullPointed,调用失败导致的bug解决

    本篇以Uniswap为例(https://uniswap.org/) 合约地址 :0x1f9840a85d5af5bf1d1762f925bdaddc4201f984 (Uni) 监听合约Tranfer事件 调用代码 核心代码实现在这里 之前实验全量区块,导致请求多次失败,是由于个人RPC节点的请求和数据有限,为了测试出结果,从13763721L block到当前,结果毫秒级返

    2024年02月11日
    浏览(18)
  • java web3j4.8.4版本的使用记录

    最近公司做NFT市场开发,特记录一下自己在使用web3j组件测试调用区块链合约的时使用的方法和踩过的坑,便于自己以后查看。 主要用到工具有4个 idea,谷歌浏览,小狐狸钱包(metamask)插件,remix在线智能合约平台 1.1、java项目  在pom.xml中添加引用仓库地址,添加web3j的引入 1.2、

    2023年04月14日
    浏览(22)
  • 【WEB3】如何使用Web3J库开发应用连接到以太坊区块链网络

    ​ Web3j 是一个与以太坊智能合约交互并与以太坊节点集成的 Java 库。它是高度模块化、类型安全和反应式的,专为以太坊上的 Java 和 Android 开发而构建。Web3j 消除了编写自定义集成代码以连接到以太坊区块链网络的开销。 通过 HTTP 和 IPC 实现完整的 Ethereum JSON-RPC客户端 API,

    2024年02月02日
    浏览(32)
  • Java Web3j nonce 获取

    Web3j 获取 nonce 的参考代码 获取一个 address nonce 值的时候,其中有一个参数为 DefaultBlockParameter,上面代码中采用的是 DefaultBlockParameterName 类,它有 3 个值,分别为 EARLIEST ( \\\"earliest\\\" ) LATEST ( \\\"latest\\\" ) PENDING ( \\\"pending\\\" ) earliest:创世区块 latest:最新区块 (区块链的头号区块) pending:

    2024年02月14日
    浏览(39)
  • java通过web3j获取ETH交易明细

        我们在项目里面如果想要得到用户的ETH交易明细怎么做呢?有两种方式:    1、直接获取ETH最新块的交易明细。    2、通过块获取用户的交易明细。 废话不多说,直接贴代码看了          下面是项目的相关依赖:

    2024年02月05日
    浏览(26)
  • Web3j 5.0版本的签名与验签

    2024年02月13日
    浏览(26)
  • web3j的基础用法-3ETH交易监听器

    demo简单实现了4种 监听区块 监听所有交易 监听待上链的交易 监听指定合约的交易事件(例如监控大户流转,实现跟单,抛售等后续逻辑) github 地址 https://github.com/jambestwick/we3jdemo

    2024年02月11日
    浏览(29)
  • Web3j 继承StaticStruct的类所有属性必须为Public <DynamicArray<StaticStruct>>

    Web3j 继承StaticStruct的类所有属性必须为Public,属性的顺序和数量必须和solidity 里面的struct 属性相同,否则属性少了或者多了的时候会出现错位 Web3j 继承StaticStruct的类所有属性不能为private,因为web3j 是通过长度去截取返回值解析成对应的属性进行赋值的。要获取一个list对象时

    2024年02月09日
    浏览(20)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包