How to listen to multipal events in python

Viewed 247

I wanted to ask something My Code:

token_CA = 'Binance Chain Wallet Address'
​
contract = web3.eth.contract(address=web3.toChecksumAddress(token_CA), abi=token_abi)
​
def handle_event(event):
    result = json.loads(Web3.toJSON(event))
    print(result)
​
async def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
            await asyncio.sleep(poll_interval)
​
def main():
    event_filter = contract.events.Transfer.createFilter(fromBlock='latest')
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(
            asyncio.gather(
                log_loop(event_filter, 2)
            )
        )
    finally:
        loop.close()
​
if __name__ == '__main__':
    main()

Suppose, I have a Binance chain address in the database & I wanted to listen to all of their events by events I mean like when someone transfer BNB Or Something

Currently, In My Code, The Address Is Fixed With Contract Variable & I Can Listen To Only One Address At A Time, I Have To Change token_CA Variable And Restart The Script For Listening To Other Wallet Events.

But The Thing I Want Is That When I Add New Wallet In The Database It Automatically start listening to that new address or something & I can listen to events of all the wallet addresses. Is there do it, I just wanted to listen to all the addresses in my database & I Also want if I add a new wallet address to my database the script autostart listening to that one

1 Answers

I have figured out how to do this.

I have to change event filter

event_filter = web3.eth.filter({
    "address": [#all address which I want to track],
    "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
})

Now I can track multiple addresses

Related