'Web3 JS How to get transactions from the block

Basically I am running these commands:

var blocknumber = await web3.eth.getBlockNumber();
var transaction = await web3.eth.getTransactionFromBlock(blocknumber, 0)
console.log(transaction)

But transaction never gets any output, regardless of the iterator. Block number is fetched properly, I can also get the block via web3.eth.getBlock(blocknumber), but the transactions cannot be fetched for some reason.

How can I debug this?



Solution 1:[1]

Here is the code you want friend:

async function GetTransactions(){
    latestBlock=await web3.eth.getBlockNumber()
    Block =await web3.eth.getBlock(latestBlock)

    Block.transactions.forEach(async(transactionAddress) => {
        let t=await web3.eth.getTransaction(transactionAddress)
        console.log(t)
    })
}
GetTransactions()

This will give Transactions of the Latest Block.

Also, Instade of latestBlock, you can pass any Block Number to get its all transactions details. A Block have ~10 Transactions Addressess, and by web3.eth.getTransaction(transactionAddress) you can get that transactions details.

Ref: https://web3js.readthedocs.io/en/v1.7.3/web3-eth.html

Solution 2:[2]

Seems the provider simply does not allow this method.

Error: Invalid JSON RPC response: "\n403 Forbidden

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aakash4dev
Solution 2 Mircea Golgu