Python + getting pending transactions

Hi,

I’m having trouble getting pending txs using web3.py

when I type w3.eth.filter(‘pending’), I get “ValueError: {‘code’: -32601, ‘message’: ‘The method eth_newPendingTransactionFilter does not exist/is not available’}”

I have set project id and api key in env variables.
Can you help me?

Hi @redtaber - welcome to the Infura community!

Can you send over the block of code you’re working with? You can check out the web3py docs to get more information about the eth_newPendingTransactionFilter); it sounds like it may be an issue with how you’re using the w3.eth.filter('pending') and the method eth_newPendingTransactionFilter, but without seeing your code, it’s difficult to tell for sure.

The code fails on the filter creation. So I’m getting the error even with a basic code like this:

import os
from web3.auto.infura import w3

os.environ[‘WEB3_INFURA_PROJECT_ID’] = ‘…’
os.environ[‘WEB3_INFURA_API_KEY’] = ‘…’

def main():
eth_filter = w3.eth.filter(‘pending’) # this is the place where it fails
pending_txs = eth_filter.get_all_entries()

if name == ‘main’:
main()

Hi @redtaber - we don’t actually support the eth_newPendingTransactionFilter method.

So there is no way to get pending transactions using python?

You should be able to subscribe to our WSS and use the newPendingTransactions request param. This will return the hash for all transactions in the pending state. If you’d like more information, you can reference the docs here.

Is there an example of the python implementation of this code?

Hi @lowkeynicc, and welcome to the Infura community! We don’t currently have an example on hand for that specific method, but we are looking into translating some of our tutorials into other languages - we’ll keep this suggestion in mind! In the meantime, you can see a JS example of using the WebSocket connection in this blog post.

Thanks for the quick reply. Right now my code just hangs forever and never reaches the print(result) line. Any idea what I’m doing wrong? (can’t get lines to indent here, but that’s not the issue)

infura_url_ws = ‘wss://mainnet.infura.io/ws/v3/[infura-app-key]’
def on_open(ws):
print(“hey”)
params = {“jsonrpc”:“2.0”, “id”: 1, “method”: “eth_subscribe”, “params”: [“newPendingTransactions”]}
ws3.send(json.dumps(params))
result = ws.recv()
print(result)

def on_error(ws, error):
print(error)

def on_close(ws):
print(“### closed ###”)

def on_message(ws, message):
print(message)

ws = websocket.WebSocketApp(infura_url_ws, on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open

ws.run_forever()

Thanks for sharing your code! I found a python-centric tutorial on the WebSockets docs - check this out. It looks like you may be missing some imports at the top of your file and you may need to explicitly call websockets.connect to connect to the websocket itself.