Search code examples
javascriptethereumweb3js

Getting "web3.eth.filter is not a function" while trying to monitor Ethereum blocks


I'm trying to monitor for the 12th confirmation using web3. I use the following code:

let filter = web3.eth.filter('latest',
filter.watch(function(error, result) {
    if (!error) {
        let confirmedBlock = web3.eth.getBlock(web3.eth.blockNumber - 11)
        if (confirmedBlock.transactions.length > 0) {
            confirmedBlock.transactions.forEach(function(txId) {
                let transaction = web3.eth.getTransaction(txId)
                if (transaction.to == account) {
                    // Do something useful.
                    console.log("12 confirmations received");
                }
            })
        }
    }
});

however this throws the error web3.eth.filter is not a function.


Solution

  • It appears you are using web3.js v1.0. The way to subscribe to new block header information in v1 is web3.eth.subscribe('newBlockHeaders', callback);

    For more information, see the docs.