I am trying to make a piece of code that scans a wallet for new transactions. When a new transaction is detected my code should print the transaction hash.
I looked online and saw stuff about the subscription attribute. When trying to use this in my code I receive an error saying that that attribute does not exist. I have tried the filter attribute as well but this also gave me problems. Now I made a code that does work mostly but still struggles with a few problems. Below is a list of the problems I would like to find solutions for. I am also not sure if my code is the most optimal way to do the task.
- The code seems to skip over certain blocks, missing the transactions from that wallet in those blocks.
- This code has about 400 API requests (Using Infura) per minute, I would like to lower that number (Under 100 would be best) without missing transactions.
Below you can find my code.
web3 = Web3(Web3.HTTPProvider(infura_url))
if web3.isConnected():
print("Successfully connected to Infura HTTP provider")
else:
print("Error connecting to Infura HTTP provider")
def check_tx_history():
# Get the current block number
block_number = web3.eth.blockNumber
# Get the block object for the current block
block = web3.eth.getBlock(block_number)
# Iterate over the transactions in the block
for transaction in block['transactions']:
# Get the transaction object
tx = web3.eth.getTransaction(transaction)
# Check if the transaction is from or to the specified account
if tx['from'] == account or tx['to'] == account:
# Get the transaction hash
tx_hash = tx['hash'].hex()
# Print a message depending on whether the transaction is incoming or outgoing
if tx['to'] == account:
print("Incoming transaction found:", tx_hash)
else:
print("Outgoing transaction found:", tx_hash)
# Keep checking the transaction history indefinitely
while True:
check_tx_history()
time.sleep(5)
I would like to know if it's possible to fix any of the above problems or if I should change anything in my code in general.