以太坊-web3j監聽合約事件沒有回調?

    以太坊-web3j監聽合約事件不工做(web3j listen contract events not working),始終沒有回調。html

測試方式:

  1. web3j官方文檔說明Infura不支持過濾器,Note: filters are not supported on Infura,文檔地址https://docs.web3j.io/filters.html
  2. 使用testRPC/ganache/或者truffle develop,依然不起做用

代碼:

EthFilter filter = new EthFilter(
                DefaultBlockParameterName.EARLIEST,
                DefaultBlockParameterName.LATEST,
                contractAddress);
        Event event = new Event("Transfer",
                Arrays.asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}),
                Arrays.asList(new TypeReference<Uint256>() {})
        );

        String topicData = EventEncoder.encode(event);
        filter.addSingleTopic(topicData);

        web3j.ethLogObservable(filter).subscribe(log -> {

            System.out.println(log.getBlockNumber());
            System.out.println(log.getTransactionHash());
            List<String> topics = log.getTopics();
            for (String topic : topics) {
                System.out.println("topic:" + topic);
            }
            EventValues eventValues = Contract.staticExtractEventParameters(event, log);
            String from = (String) eventValues.getIndexedValues().get(0).getValue();
            String to = (String) eventValues.getIndexedValues().get(1).getValue();
            BigInteger value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();
            System.out.println("form:" + from);
            System.out.println("to:" + to);
            System.out.println("value:" + value);
        });

    通過屢次測試發現,上面兩張方式都把監聽合約閹割掉了,必須本身在本地運行一個geth客戶端纔有用。緣由是監聽通常使用websocket作長鏈接,去掉監聽是爲了節省資源。java

    通常推薦web3j開發環境,搭建一個公用的geth測試節點,而後開發的時候鏈接使用。部署合約能夠使用 truffle console --network xxx(xxx是你配置的網絡),我的喜歡的一種方式,固然你也能夠使用geth控制檯部署。web

相關文章
相關標籤/搜索