Categories
Cryptocurrency Ethereum Mastering Development

puthon web3.py Get the latest block

I want to use the following code to monitor the latest block

from web3 import Web3
import asyncio
def handle_event(event):
print(event)
# and whatever
async def log_loop(event_filter, poll_interval):
while True:
for event in event_filter.get_new_entries():
handle_event(event[‘transactionHash’])
await asyncio.sleep(poll_interval)

def main():
w3 = Web3(Web3.WebsocketProvider(‘wss://mainnet.infura.io/ws/v3/xxx’))
block_filter = w3.eth.filter(‘latest’)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(
asyncio.gather(
log_loop(block_filter, 2)))
finally:
loop.close()

if name == ‘main‘:
main()

Leave a Reply

Your email address will not be published. Required fields are marked *