I'm making a simple program to track transactions in and out of an address, I have a function that gets the latest block and then I run it consecutively.

When I run the function sometimes the block I try to read is null, and some other times when I encounter a block full of transactions, the function takes more time to execute and I end up skipping a block.

How can I be sure the block number I'm checking is always <= of the latest block?

Is there any risk that I might scan an uncle block instead?

Here is my code:

const Web3 = require('web3')
const PROJECT_ID = 'myprojectid'

// Connect to the node
const web3 = new Web3( Web3.givenProvider || `wss://mainnet.infura.io/ws/v3/${PROJECT_ID}`)
const eth = web3.eth

async function listenToBlocks(addressToWatch){
    // Get the latest block and the transactions 
    lastBlock = await eth.getBlock('latest','true')
   //Do stuff with the transactions here

const addressToWatch = 'myaddress'

const callback = async () => {
        eth.getBlockNumber().then(result => console.log(`Searching block: ${result}`))
        await listenToBlocks(network,addressToWatch)


In a proof of work blockchain like Ethereum it is always possible for chain reorganization. The longer you wait the less likely a block will change.

It is very common for user wallets to use 12 blocks for transaction confirmation.

Exchanges often have longer waits, ie something like 24 or more.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.