I'm trying to receive pending transactions from the eth mempool, for which I use a wss connection to the node.
The problem is that when normally receiving messages from the node, no errors occur and the cycle is not interrupted.
however, if I add transaction verification via web3, after a couple of minutes of the software running, an error occurs.
In websocket:
ERROR:root:An error occurred: object of type 'NoneType' has no len()
and in websockets:
Future exception was never retrieved
future: <Future finished exception=ConnectionClosedError(None, None, None)>
websockets.exceptions.ConnectionClosedError: no close frame received or sent
websocket code:
def on_message(ws, message):
timing = time.perf_counter()
try:
if 'eth_subscription' in message:
tx = json.loads(message)
try:
tx = web3.eth.get_transaction(tx['params']['result'])
print(tx)
except TransactionNotFound:
pass
#Thread(target=get_tx, args=(tx_hash,)).start()
except Exception as err:
print(err)
finally:
print(colored(str(time.perf_counter() - timing), 'magenta'))
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
def main():
try:
websocket.enableTrace(True, level='INFO')
ws = websocket.WebSocketApp("ws://localhost:7546", on_open=on_open, on_message=on_message, on_error=on_error,
on_close=on_close,)
subscribe_request = {
"id": 1,
"method": "eth_subscribe",
"params": [
"newPendingTransactions"
],
"jsonrpc": "2.0"
}
ws.run_forever(dispatcher=rel, reconnect=5, sslopt={"cert_reqs": ssl.CERT_NONE})
ws.send(json.dumps(subscribe_request))
rel.signal(2, rel.abort)
rel.dispatch()
except Exception as err:
logging.error(f"An error occurred: {err}")
if __name__ == '__main__':
main()
websockets code:
async def get_event():
async with websockets.connect(node_ws_url, ping_timeout=None) as ws:
await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}')
subscription_response = await ws.recv()
print(subscription_response)
while True:
try:
message = await asyncio.wait_for(ws.recv(), timeout=60)
#print("Received message:", message)
response = json.loads(message)
txHash = response['params']['result']
tx = web3.eth.get_transaction(txHash)
print(tx)
except TransactionNotFound:
pass
except websockets.exceptions.ConnectionClosed as e:
logging.error(f"Connection closed: {e}")
break
except Exception as e:
logging.error(f"An error occurred: {e}")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(get_event())