web3.eth.getBlock(i) is an asynchronous function, you should either use a callback or async / await. Because you are not waiting for the result, you get undefined simply because there is no result (yet).
Here is a version using the callback :
function checkTransactionCount(startBlockNumber, endBlockNumber) {
console.log(
"Searching for non-zero transaction counts between blocks " +
startBlockNumber +
" and " +
endBlockNumber
);
for (var i = startBlockNumber; i <= endBlockNumber; i++) {
web3.eth.getBlock(i, (err, block) => {
if (err == null && block != null) {
if (block.transactions != null && block.transactions.length != 0) {
console.log(
"\n\nBlock #" + i + " has " + block.transactions + " transactions"
);
}
}
});
}
}
Or as stated above, you could use async / await like so :
async function checkTransactionCount(startBlockNumber, endBlockNumber) {
console.log(
"Searching for non-zero transaction counts between blocks " +
startBlockNumber +
" and " +
endBlockNumber
);
for (var i = startBlockNumber; i <= endBlockNumber; i++) {
let block = await web3.eth.getBlock(i);
if (block != null) {
if (block.transactions != null && block.transactions.length != 0) {
console.log(
"\n\nBlock #" + i + " has " + block.transactions + " transactions"
);
}
}
}
}
EDIT : Here is an example using async / await returning an array with the transactions hash that are present between startBlockNumber and endBlockNumber :
const Web3 = require("Web3");
const ENDPOINT = "https://mainnet.infura.io/v3/YOUR_PROJECT_ID";
let web3 = new Web3(ENDPOINT);
async function checkTransactionCount(startBlockNumber, endBlockNumber) {
transactions = [];
for (var i = startBlockNumber; i <= endBlockNumber; i++) {
let block = await web3.eth.getBlock(i);
if (block != null) {
if (block.transactions != null && block.transactions.length != 0) {
transactions = transactions.concat(block.transactions);
}
}
}
return transactions;
}
async function main() {
console.log(
"Searching for non-zero transaction counts between blocks 2000000 and 2000010"
);
let transactions = await checkTransactionCount(2000000, 2000010);
console.log(transactions.length + " transactions found");
console.log(transactions);
}
main();
checkTransactionCountreturn an array of transactions, it should be called like in my example :let transactions = await checkTransactionCount(2000000, 2000010);where you can change the start and end block of course. – hroussille Mar 30 '22 at 07:36blocksdata = { console.log( "Searching for non-zero transaction counts between blocks 2000000 and 2000010" ); let transactions = await checkTransactionCount(startBlockNumber, endBlockNumber); console.log(transactions.length + " transactions found"); console.log(transactions); return transactions; }– DataDope Apr 01 '22 at 14:05checkTransactionCountfunction, but don't bother with that, it was just for the example. – hroussille Apr 01 '22 at 14:41