首页 > 解决方案 > 尝试监控以太坊区块时获取“web3.eth.filter 不是功能”

问题描述

我正在尝试使用 web3 监视第 12 次确认。我使用以下代码:

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");
                }
            })
        }
    }
});

但是这会引发错误web3.eth.filter is not a function

标签: ethereumweb3web3js

解决方案


看来您正在使用 web3.js v1.0。v1中订阅新区块头信息的方式是web3.eth.subscribe('newBlockHeaders', callback);

有关更多信息,请参阅文档


推荐阅读