About monitor a ETH address

Hi,
I use this code for monitor a ETH address
code from: Web3.py: How to Monitor ETH Transfers to an Address
but even I delete “time.sleep(5)”, it is too slow to search a block, It takes more than 30 seconds to search a block, but Ethereum average block time is at a current level of 12s, so blocks will definitely be missed, how can I solve this problem?

def watch():
while True:
block = web3.eth.get_block(‘latest’)
print("Searching in block " + str(block.number))

    if block and block.transactions: 
        for transaction in block.transactions: 
            tx_hash = transaction.hex() # the hashes are stored in a hexBytes format
            tx = web3.eth.get_transaction(tx_hash)
            if tx.to != None:
                if tx.to == account:
                    print("Transaction found in block {} :".format(block.number))
                    print({
                        "hash": tx_hash,
                        "from": tx["from"],
                        "value": web3.fromWei(tx["value"], 'ether')
                        })
    time.sleep(5)

watch()

1 Like

Hi @welsn,

Thank you for bringing this up! After rechecking the script, it appears that it takes roughly 0.17 seconds per transaction (on my machine). This would mean that for any block that exceeds 70 transactions it encounters, the script would fail to keep up with the 12s average block time. I likely failed to notice this since I was testing on Ropsten, with much lower block sizes - I will add a disclaimer to the support tip.

My two suggestions are:

  • either use a local variable to store the latest checked block number and increment it as you go, then ask the blockchain for that specific next block, or:
  • use websockets to subscribe to pending transactions, as seen in this article.

I hope at least one of the above solutions suits your needs.