web3j的基础用法-3ETH交易监听器

ETH的交易监听器

demo简单实现了4种

  1. 监听区块
  public Subscription subscribeBlock(final Action1<? super EthBlock> onNext) {
        if (this.web3j == null) return null;
        return this.web3j.blockObservable(true).subscribe(onNext);
    }

    public void unsubscribeBlock(Subscription subscription) {
        if (this.web3j == null) return;
        subscription.unsubscribe();
    }
  1. 监听所有交易
    /**
     * 监听新交易事件
     * 已经交易的事件
     **/
    public Subscription subscribeHasTrans(final Action1<? super Transaction> onNext) {
        if (this.web3j == null) return null;
        return web3j.transactionObservable().subscribe(onNext);
    }

    /**
     * 取消订阅信息
     **/
    public void unsubscribeHasTrans(Subscription subscription) {
        if (this.web3j == null) return;
        subscription.unsubscribe();
    }
  1. 监听待上链的交易
    /**
     * 监听待定交易
     */
    public Subscription subscribePendingTrans(final Action1<? super Transaction> onNext) {
        if (this.web3j == null) return null;
        return web3j.pendingTransactionObservable().subscribe(onNext);
    }

    /**
     * 取消订阅信息
     **/
    public void unsubscribePendingTrans(Subscription subscription) {
        if (this.web3j == null) return;
        subscription.unsubscribe();
    }

  1. 监听指定合约的交易事件(例如监控大户流转,实现跟单,抛售等后续逻辑)
   /**
     * 监听合约的交易事件
     * **/
    public Subscription subscribeContract(String contractAddress, final Action1<? super Log> onNext) {
        if (this.web3j == null) return null;

        // 要监听的合约事件 交易
        Event event = new Event("Transfer",

                Arrays.asList(
                        new TypeReference<Address>(true) {
                        },

                        new TypeReference<Address>(true) {
                        },

                        new TypeReference<Uint256>(false) {
                        }));
        EthFilter filter = new EthFilter(
                DefaultBlockParameterName.EARLIEST,
                DefaultBlockParameterName.LATEST,
                contractAddress);
        filter.addSingleTopic(EventEncoder.encode(event));
        return web3j.ethLogObservable(filter).subscribe(onNext);
    }
    
    public void subscribeContract(Subscription subscription){
        if (this.web3j == null) return;
        subscription.unsubscribe();
    }

web3j的基础用法-3ETH交易监听器_第1张图片

github 地址
https://github.com/jambestwick/we3jdemo

你可能感兴趣的:(以太坊,web3j,区块链,java,web3,以太坊,智能合约)