web3.py function get_block tranactions is not in the current block

Question:

I want to synchronize all transactions with the database, so I use get_ Block method. The code is as follows:

    cur_block_num = web3.eth.get_block_number()
    if cur_block_num <= last_block_num:
        return
    res = web3.eth.get_block(cur_block_num, full_transactions=True)
    block_info = json.loads(web3.toJSON(res))
    block_info = convert_numeric_to_str(block_info)
    transactions = block_info.pop('transactions')
    db["block_info"].insert_one(block_info)

but When I get all the transactions in block 16498524, I eventually include the transactions in other blocks. Why is this, and sometimes it is normal? Is my method wrong? Have I got the transactions to be processed? Or is the node alchemy I use now returning the wrong value?

Asked By: zl zero

||

Answers:

Chain tips are unstable in Ethereum chains. Because you are dealing with the latest block, transactions may hop between different blocks as some blocks do not get included in the canonical blockchain.

You need to use a chain reorganisation-aware block reading to be able to read recent transactions and events. Some example here.

Answered By: Mikko Ohtamaa