更快地检索区块的总 ETH 交易价值

Retrieving total eth transaction value of block faster

我已经写了一个简单的 while loop 到 return 一个区块的总交易价值,但是,有时可能需要将近 30 秒,具体取决于交易数量街区。

因此,我向社区寻求帮助,以更快的方式检索上述信息。

下面是我的脚本,感谢大家花时间阅读 - 我对区块链还很陌生:

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)

您需要在本地运行您自己的JSON-RPC 节点。 See example here.

除非您每月向他们支付数百美元,否则任何第三方节点提供商都会给您慢车道。

eth_getBlockByNumber 方法接收一个布尔值作为最新参数,指定您是否需要完整的交易对象列表:

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.

所以在你的代码中你可以做类似的事情:

# 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

并避免进行 RPC 调用来获取每笔交易。