【问题标题】:Retrieving total eth transaction value of block faster更快地检索区块的总 eth 交易价值
【发布时间】:2021-09-10 05:42:28
【问题描述】:

我写了一个简单的whileloop 来返回一个区块的总交易价值,但是,根据区块上的交易数量,有时可能需要将近 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)

【问题讨论】:

标签: python blockchain ethereum web3py ether


【解决方案1】:

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 调用来获取每个事务。

【讨论】:

  • 通过最小的更改使其成为pythonic,这很有效。用 248 笔交易在区块上进行测试,你的方法比我的快 6 倍。谢谢
【解决方案2】:

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

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

【讨论】:

  • 运行我自己的节点不是我希望采用的方法
  • 您将获得 100 倍的加速。
猜你喜欢
  • 2021-10-08
  • 2021-11-23
  • 2018-02-16
  • 2022-11-04
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多