1

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.

  1. The code seems to skip over certain blocks, missing the transactions from that wallet in those blocks.
  2. 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.

1 Answer 1

1

It seems that your code is trying to check for new transactions in the current block every 5 seconds. However, this approach has several problems:

Your code may miss transactions if they are not included in the current block, or if the current block is not the latest block. Your code may produce duplicate results if it checks the same block multiple times. Your code is using up a lot of API requests, which may lead to rate limiting or even temporary blocking of your IP address. To solve these problems, you can use the eth_subscribe function provided by the Web3.js library to subscribe to new transactions for a specific wallet address. This function allows you to set up a persistent connection to the Ethereum network, and receive notifications whenever a new transaction is confirmed for a specific wallet address.

Here's an example of how you can use eth_subscribe to check for new transactions for a specific wallet address:

   from web3 import Web3

# Set up a connection to the Ethereum network
web3 = Web3(Web3.HTTPProvider(infura_url))

# Check if the connection is successful
if web3.isConnected():
    print("Successfully connected to Infura HTTP provider")
else:
    print("Error connecting to Infura HTTP provider")

# Define the wallet address that you want to check for new transactions
wallet_address = '0x0000000000000000000000000000000000000000'

# Subscribe to new transactions for the wallet address
subscription = web3.eth.subscribe('newPendingTransactions', lambda x: print(x))

# Keep the connection open indefinitely
while True:
    pass

This code will set up a persistent connection to the Ethereum network and print the transaction hash whenever a new transaction is confirmed for the specified wallet address.

Note: To unsubscribe from the subscription, you can call the unsubscribe method on the subscription object.

3
  • Hello, thanks for your reply. I tried this code but I keep getting the following error in my terminal. Traceback (most recent call last): File "c:/Users/..../Subscription.py", line 18, in <module> subscription = web3.eth.subscribe('newPendingTransactions', lambda x: print(x)) AttributeError: 'Eth' object has no attribute 'subscribe' How do I fix this? I tried pip web3 --upgrade but this did not fix the issue.
    – JaspeR
    Dec 18, 2022 at 14:48
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 21, 2022 at 12:24
  • @JaspeR web3.eth.subscribe is not part of web3py (but do exists in web3js - web3js.readthedocs.io/en/v1.2.11/web3-eth-subscribe.html), see ethereum.stackexchange.com/questions/103925/… Dec 21, 2022 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.