R0i*_*ixy 3 python blockchain smartcontracts web3py
如何跟踪 bsc 网络中钱包列表的代币交易?
我考虑使用websocket和过滤功能。我认为可以使用作为topics过滤器参数的一部分,并仅反映发送Transfer至/来自监视地址的事件,以便我的应用程序不必处理不必要的数据。
但我做错了,不知道如何正确地将钱包列表(或至少只有一个钱包)作为我的过滤函数的参数。怎么做?
我在从Transfer事件获取数据时遇到问题,因为我不知道如何解码HexBytes类型。我看到了 web3.js 的功能,但没有看到 web3.py 的功能。
address_list = ['0x67fdE6D04a82689a59E5188f9B572CBeF53D4763', '...', '...']
web3 = Web3(Web3.WebsocketProvider('wss://bsc.getblock.io/mainnet/?api_key=your_api_key'))
web3_filter = web3.eth.filter({'topics': address_list})
while True:
for event in web3_filter.get_new_entries():
print(web3.toJSON(web3.eth.wait_for_transaction_receipt(event).logs))
Run Code Online (Sandbox Code Playgroud)
最后我找到了解决方案。起初,我使用 node.js 编写了相同的代码,因为 web3.js 让我更容易理解它的实际工作原理。它有更好的方法命名、更好的文档等
回到 web.py:
为了获取Transfer事件签名,我使用了这段代码transferEventSignature = web3.toHex(Web3.sha3(text='Transfer(address,address,uint256)'))
对于编码/解码,您可以使用eth_abi库
from web3 import Web3
from eth_abi import encode_abi, decode_abi
from hexbytes import HexBytes
encoded_wallet = (web3.toHex(encode_abi(['address'], [wallet])) # encoding
web3 = Web3(Web3.WebsocketProvider('wss://speedy-nodes-nyc.moralis.io/api-key/bsc/mainnet/ws'))
event_filter = web3.eth.filter({'topics': [transferEventSignature, None, encoded_wallet]}) # setting up a filter with correct parametrs
while True:
for event in event_filter.get_new_entries():
decoded_address = decode_abi(['address'], HexBytes(event.topics[2])) # decoding wallet
value = decode_abi(['uint256'], HexBytes(event.data)) # decoding event.data
tokenContractAddress = event.address
contractInstance = web3.eth.contract(address=tokenContractAddress, abi=jsonAbi) # jsonAbi is standart erc-20 token abi
# I used simplified JSON abi that is only able to read decimals, name and symbol
name = contractInstance.functions.name().call()
decimals = contractInstance.functions.decimals().call()
symbol = contractInstance.functions.symbol().call()
# getting any token information
# doing some useful stuff
Run Code Online (Sandbox Code Playgroud)
GetBlock.io 为我工作,但有时会与网络不同步。我通过这项服务取得了更好的成功: https: //moralis.io/
我希望有人会觉得这很有用。
| 归档时间: |
|
| 查看次数: |
10823 次 |
| 最近记录: |