Search code examples
pythonblockchainethereumweb3pyether

Retrieving total eth transaction value of block faster


I have written a simple while loop to return the total transaction value of a block, however, it can sometimes take almost 30 seconds depending on the number of transactions on the block.

Therefore I am looking to the community for help with a much faster way of retrieving said info.

Below is my script and I thank you all for taking the time to read - I am very new to blockchain:

from web3 import Web3
import pandas as pd
    
    
w3 = Web3(Web3.HTTPProvider(config.INFURA_URL)

block_hegiht = 13179360
block = w3.eth.get_block(block_height)
block_tranasctions = (block['transactions'])  
transLen = len(block['transactions'])
        
count = transLen
transValue_eth_list = []
        
while count >0:
            
    count = count - 1
    transId = w3.eth.get_transaction_by_block(block_height,count)
    transValue_wei = transId['value'] # get transaction value in wei
    transValue_eth = w3.fromWei(transValue_wei, 'ether') # convert transaction value from wei to eth
    transValue_eth = pd.to_numeric(transValue_eth) # convert from hex decimal to numeric

    if transValue_eth > 0: # where value of transaction is greater than 0.00 eth

        transValue_eth_list.append(transValue_eth) # append eth transaction value to list
    
block_transValue_eth = sum(transValue_eth_list) # sum of all transactions in block
print(block_transValue_eth)

Solution

  • The eth_getBlockByNumber method receive as the latest parameter a boolean specifying if you want the full transaction object list or not:

    1 - QUANTITY|TAG - integer of a block number, or the string "earliest", "latest" or "pending", as in the default block parameter.
    2 - Boolean - If true it returns the full transaction objects, if false only the hashes of the transactions.
    

    So in your code you can do something like that:

    # I'm not sure about the python code, this is just a sample
    block = w3.eth.get_block(block_height, true)
    block_transValue_eth = 0
    for tx in block['transactions']:
        block_transValue_eth += tx.value
    print block_transValue_eth
    

    And avoid doing an RPC call to get each transaction.