首页 > 解决方案 > 我怎样才能使这个 web3 python 脚本更快?

问题描述

我想制作一个 python 脚本(用于 BSC)来跟踪钱包中特定令牌的余额。我需要 python 脚本非常快。目前使用以下代码,脚本检测到进入钱包的令牌大约需要 6 秒。有没有更快、更有效的方法来做到这一点?(我添加了 sleep 函数来充当某种缓冲区。不知道这是否是个好主意?) 编辑:删除了 sleep 函数,但仍需要 6 秒。

from web3 import Web3
import json

bsc = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
print(web3.isConnected())

main_address = "wallet to be tracked"
contract_address = "token contract address"
abi = json.loads('the abi')

contract = web3.eth.contract(address=contract_address, abi = abi)

balanceOfToken = contract.functions.balanceOf(main_address).call()
print(web3.fromWei(balanceOfToken, 'ether'))

while(True):
    balanceOfToken = contract.functions.balanceOf(main_address).call()
    if(balanceOfToken > web3.fromWei(0.5, 'ether')):
        break
    
    time.sleep(1.1)
    x+=1
    print(f"Still looking {x}")
    continue

second_address = "the other wallet address"
main_key = "private key of first wallet"

nonce = web3.eth.getTransactionCount(main_address)

token_tx = contract.functions.transfer(second_address, balanceOfToken).buildTransaction({
    'chainId':56, 'gas': 90000, 'gasPrice': web3.toWei('5', 'gwei'), 'nonce':nonce
})

signed_tx = web3.eth.account.signTransaction(token_tx, main_key)
web3.eth.sendRawTransaction(signed_tx.rawTransaction)

print(contract.functions.balanceOf(my_address).call() + " " + contract.functions.name().call())

标签: pythonethereumweb3cryptocurrency

解决方案


回答你的问题的关键是:什么需要 6 秒?

  1. 从头到尾运行代码?

If I run the code on my laptop - using the same node - the code executes in 0.45-0.55s. So perhaps it is not the code itself, but your connection to the node that is slowing down calls or broadcasting the transaction? If so, maybe trying another node will speed up execution. See Binance's docs for alternatives or check a 3rd party provider.

Unlikely, but it could also be the lack of available processing power on your laptop (?)

  1. Starting the code until the transaction shows up in the block?

The code takes c. 0.5 to run. Add the 3s target block time on BSC and you are already at 3.5s, assuming there's space in the block (/your fee is sufficient to be included) and assuming it gets broadcasted and picked up immediately. I am unsure what the lower bound should be, but it will take a couple of seconds.

PS. As mentioned by – @Mikko Ohtamaa - Aug 17 '21 at 5:07 "Instead of polling, you can subscribe to all new blocks and filter out events in the block yourself. (..)" To do this, you can have a look at filtering in web3py.


推荐阅读