您现在的位置是:首页 >学无止境 >【web3j】java通过web3j监听并解析合约中的事件(event/emit)网站首页学无止境

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

猫墨* 2023-05-14 00:00:02
简介【web3j】java通过web3j监听并解析合约中的事件(event/emit)

① 查询链上数据用的rpc(本示例是binance的,测试网可以使用:https://data-seed-prebsc-2-s2.binance.org:8545)

② 自己还要有一个测试链上部署好的合约,合约中要有一个方法emit了事件。

③ java依赖

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.9.7</version>
</dependency>
<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>codegen</artifactId>
    <version>4.9.7</version>
</dependency>

一、通过自己合约的abi和bin生成一个java文件,abi和bin可以在remix的compiler模块中获取,代码如下这一步懒得做的可以跳过,在第二步传合约地址的时候,直接传一个字符串也行。这里就是顺手存一下这个方法,其实实际使用也是直接传的字符串,具体可以看页面最下方的”三、“

    /**
     * 通过合约abi和bin获得java文件
     */
    public void getJavaFileBySolidity(){
        // 生成的java类名,同ABI文件同名,自动首字母大写
        String packageName = "";
        String outDirPath = "/Users/maomo/Desktop/";
        String binDirPath = "/Users/maomo/Desktop/xxxbin.txt";
        String abiDirPath = "/Users/maomo/Desktop/xxxabi.txt";
        String[] arr = Arrays.asList(
                "-b", binDirPath,
                "-a", abiDirPath,
                "-p", packageName,
                "-o", outDirPath
        ).toArray(new String[0]);
        SolidityFunctionWrapperGenerator.main(arr);
    }

二、通过web3j查询事件,通过eventethFilter增加过滤条件

    public void testSub() {
        Web3j web3j = Web3j.build(new HttpService("https://data-seed-prebsc-2-s2.binance.org:8545"));
        //第一步生成的合约实体
        Contract contract;
        Disposable subscribe = null;
        try {
            Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
            String clientVersion = web3ClientVersion.getWeb3ClientVersion();
            log.info("wen3j subscribe --clientVersion-- :{} ", clientVersion);
            //设置谁调用合约
            TransactionManager transactionManager = new ClientTransactionManager(web3j, "这里可以输入自己的钱包地址");
            //加载智能合约(此处可以跳过,下面穿合约地址的地方 直接传字符串)
            contract = Contract.load("你要监听的合约地址", web3j, transactionManager, ManagedTransaction.GAS_PRICE, org.web3j.tx.Contract.GAS_LIMIT);
            //设置过滤条件 这个示例是监听最新的1000个块
            BigInteger blockNumber = web3j.ethBlockNumber().send().getBlockNumber()
                                        .subtract(new BigInteger("1000"));
            EthFilter ethFilter = new EthFilter(DefaultBlockParameter.valueOf(blockNumber),DefaultBlockParameterName.LATEST, contract.getContractAddress());
            //监听哪个事件,合约中的event写了几个参数,这里就写几个,类型对应好
            Event event = new Event("startEvent",
                    Arrays.<TypeReference<?>>asList(
                            new TypeReference<Address>(true) {},
                            new TypeReference<Address>(true) {},
                            new TypeReference<Uint256>(true) {},
                            new TypeReference<Uint256>(false) {},
                            new TypeReference<Uint256>(false) {},
                            new TypeReference<Uint256>(false) {}));
            ethFilter.addSingleTopic(EventEncoder.encode(event));
            subscribe = web3j.ethLogFlowable(ethFilter).subscribe(tx -> {
                int newBlock = tx.getBlockNumber().intValue();
                log.info("wen3j subscribe --newBlock-- :{} ", newBlock);
                log.info("wen3j subscribe --tx-- :{} ", tx);
                EventValues eventValues = staticExtractEventParameters(event, tx);
                //定义接收参数(本示例使用的事件返回了6个,具体按自己合约来)
                String address1 = "";String address2 = "";int uint1 = 0;
                int uint2 = 0;int uint3 = 0;int uint4 = 0;
                List<Type> indexedValues = eventValues.getIndexedValues();
                if (ObjectUtils.isNotEmpty(indexedValues) && indexedValues.size() == 3) {
                    Type type1 = indexedValues.get(0);
                    address1 = type1.getValue().toString();
                    Type type2 = indexedValues.get(1);
                    address2 = type2.getValue().toString();
                    Type type3 = indexedValues.get(2);
                    uint1 = Integer.parseInt(type3.getValue().toString());
                }
                List<Type> nonIndexedValues = eventValues.getNonIndexedValues();
                if (ObjectUtils.isNotEmpty(nonIndexedValues) && nonIndexedValues.size() == 3) {
                    Type type1 = nonIndexedValues.get(0);
                    uint2 = Integer.parseInt(type1.getValue().toString());
                    Type type2 = nonIndexedValues.get(1);
                    uint3 = Integer.parseInt(type2.getValue().toString());
                    Type type3 = nonIndexedValues.get(2);
                    uint4 = Integer.parseInt(type3.getValue().toString());
                }
                log.info("address1:{};address2:{};uint1:{};uint2:{};uint3:{};uint4:{}",address1, address2, uint1, uint2, uint3, uint4);
            });
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭监听
            if(ObjectUtils.isNotEmpty(subscribe) && !subscribe.isDisposed()){
                subscribe.dispose();
            }
        }
    }
    /**
     * 解析log返回的data
     * @param event 合约中定义的事件
     * @param log 监听到的log
     * @return 解析后的数据
     */
    public EventValues staticExtractEventParameters(Event event, Log log) {
        final List<String> topics = log.getTopics();
        String encodedEventSignature = EventEncoder.encode(event);
        if (topics == null || topics.size() == 0 || !topics.get(0).equals(encodedEventSignature)) {
            return null;
        }
        List<Type> indexedValues = new ArrayList<>();
        List<Type> nonIndexedValues = FunctionReturnDecoder.decode(
                log.getData(), event.getNonIndexedParameters());
        List<TypeReference<Type>> indexedParameters = event.getIndexedParameters();
        for (int i = 0; i < indexedParameters.size(); i++) {
            Type value = FunctionReturnDecoder.decodeIndexedValue(
                    topics.get(i + 1), indexedParameters.get(i));
            indexedValues.add(value);
        }
        return new EventValues(indexedValues, nonIndexedValues);
    }

三、为了方便以后复制粘贴(不是),最下面再传一个不生成合约的版本

    public void testSub() {
        Web3j web3j = Web3j.build(new HttpService("https://data-seed-prebsc-2-s2.binance.org:8545"));
        //第一步生成的合约实体
        Contract contract;
        Disposable subscribe = null;
        try {
            Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
            String clientVersion = web3ClientVersion.getWeb3ClientVersion();
            log.info("wen3j subscribe --clientVersion-- :{} ", clientVersion);
            //设置过滤条件 这个示例是监听最新的1000个块
            BigInteger blockNumber = web3j.ethBlockNumber().send().getBlockNumber()
                                        .subtract(new BigInteger("1000"));
            EthFilter ethFilter = new EthFilter(DefaultBlockParameter.valueOf(blockNumber),DefaultBlockParameterName.LATEST, "输入合约地址");
            //监听哪个事件,合约中的event写了几个参数,这里就写几个,类型对应好
            Event event = new Event("startEvent",
                    Arrays.<TypeReference<?>>asList(
                            new TypeReference<Address>(true) {},
                            new TypeReference<Address>(true) {},
                            new TypeReference<Uint256>(true) {},
                            new TypeReference<Uint256>(false) {},
                            new TypeReference<Uint256>(false) {},
                            new TypeReference<Uint256>(false) {}));
            ethFilter.addSingleTopic(EventEncoder.encode(event));
            subscribe = web3j.ethLogFlowable(ethFilter).subscribe(tx -> {
                int newBlock = tx.getBlockNumber().intValue();
                log.info("wen3j subscribe --newBlock-- :{} ", newBlock);
                log.info("wen3j subscribe --tx-- :{} ", tx);
                EventValues eventValues = staticExtractEventParameters(event, tx);
                //定义接收参数(本示例使用的事件返回了6个,具体按自己合约来)
                String address1 = "";String address2 = "";int uint1 = 0;
                int uint2 = 0;int uint3 = 0;int uint4 = 0;
                List<Type> indexedValues = eventValues.getIndexedValues();
                if (ObjectUtils.isNotEmpty(indexedValues) && indexedValues.size() == 3) {
                    Type type1 = indexedValues.get(0);
                    address1 = type1.getValue().toString();
                    Type type2 = indexedValues.get(1);
                    address2 = type2.getValue().toString();
                    Type type3 = indexedValues.get(2);
                    uint1 = Integer.parseInt(type3.getValue().toString());
                }
                List<Type> nonIndexedValues = eventValues.getNonIndexedValues();
                if (ObjectUtils.isNotEmpty(nonIndexedValues) && nonIndexedValues.size() == 3) {
                    Type type1 = nonIndexedValues.get(0);
                    uint2 = Integer.parseInt(type1.getValue().toString());
                    Type type2 = nonIndexedValues.get(1);
                    uint3 = Integer.parseInt(type2.getValue().toString());
                    Type type3 = nonIndexedValues.get(2);
                    uint4 = Integer.parseInt(type3.getValue().toString());
                }
                log.info("address1:{};address2:{};uint1:{};uint2:{};uint3:{};uint4:{}",address1, address2, uint1, uint2, uint3, uint4);
            });
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭监听
            if(ObjectUtils.isNotEmpty(subscribe) && !subscribe.isDisposed()){
                subscribe.dispose();
            }
        }
    }

=========================分割线=========================

还有一种把web3j.ethLogFlowable(ethFilter).subscribe换成查询的方法,做个记录

把这段代码

subscribe = web3j.ethLogFlowable(ethFilter).subscribe(tx -> {

    //逻辑...
}

换成

List<EthLog.LogResult> resp = web3j.ethGetLogs(ethFilter).send().getLogs();
    for (EthLog.LogResult logItem : resp) {
                EthLog.LogObject tx = ObjectUtils.isNotEmpty(logItem.get()) ? (EthLog.LogObject) logItem.get() : null;
                if(ObjectUtils.isEmpty(tx)){
                    return false;
                }

    //逻辑...

    }

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。