更快地检索块的总eth事务值

2024-09-29 20:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个简单的while{}来返回块的总事务值,但是,根据块上的事务数,有时可能需要将近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)

Tags: tofromgetvaluecountblocklistweb3
2条回答

您需要在本地运行自己的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调用以获取每个事务

相关问题 更多 >

    热门问题