Python Web3 - Event Listener

Hello

I will try my luck here. I am trying to create a Web3 Event Listener for a specific Smart Contract using Python.

I have developed some code, which works as intended. I need this code to be executed if a certain event occurs on the blockchain according to a specific smart contract.

Therefore I need to develop a Web3 Event Listener for a specific smart contract using Python. As an example, I wish to know once a transaction occurs on this smart contract, which I have tried to represent below.

I establish connection to the BSC Mainnet using the moralis HTTP speedy node. I verify the connection, and that yields: “True”.

I wish to listen for events conducted for the token “FLOKI” on the BEP20 Network. More specifically, I wish to listen for this event, that is “Approval” - found here:

https://bscscan.com/tx/0xc9a79e9507c22356574fee191e895099921141bc9ad5d38fcd02f8ab609592e2#eventlog

Python Code Used:


`
import json
import time
from web3 import Web3
from web3.middleware import geth_poa_middleware

node_provider = “https://speedy-nodes-nyc.moralis.io/afasfadsf/bsc/mainnet” # Moralis Web3

web3 = Web3(Web3.HTTPProvider(node_provider))
print("Web3 Connection Established: ",web3.isConnected())

ca_floki = web3.toChecksumAddress(‘0xfb5B838b6cfEEdC2873aB27866079AC55363D37E’)

abi_floki = json.loads(’[{“anonymous”:false,“inputs”:[{“indexed”:true,“internalType”:“address”,“name”:“owner”,“type”:“address”},{“indexed”:true,“internalType”:“address”,“name”:“spender”,“type”:“address”},{“indexed”:false,“internalType”:“uint256”,“name”:“value”,“type”:“uint256”}],“name”:“Approval”,“type”:“event”}]’)

contract = web3.eth.contract(address=ca_floki, abi=abi_floki)

while True:
event_filter = contract.events.Approval.createFilter(fromBlock=‘latest’, address=ca_floki)
print(event_filter)
time.sleep(2)

`


In doing so, running the code, yields several random-looking addresses, however, which are not addresses. Output: Web3Python_EventListener

I expect to retrieve the address, that was approved, but instead I am given invalid addresses?

The contract ABI code is found here:

https://bscscan.com/address/0xfb5b838b6cfeedc2873ab27866079ac55363d37e#code

it should be much easier if you try to use event sync functionality in a Moralis Server: https://docs.moralis.io/moralis-server/automatic-transaction-sync/smart-contract-events#sync-and-watch-contract-events

you can also do it from code: https://docs.moralis.io/moralis-server/automatic-transaction-sync/smart-contract-events#sync-and-watch-contract-events

and you can connect directly to mongo db from python: How to do database backups?

Yes, thanks. I have seen this, but I wish to do it within the python script. I wish only to use the node provider from Moralis, not their internal applications

I appreciate your answer however :slight_smile:

can you put a number instead of ‘latest’? do you get any error?

Yields somewhat same (but different) type of outputs