1

I'm using ethers.js to handle functions and listen events on ethereum for both mainnet and sepolia. I'm also using Alchemy as RPC provider.

I have created a service:

import { Injectable } from "@nestjs/common";
import { ethers } from "ethers";
import { LoggerService } from "src/logger/logger.service";
@Injectable()
export class RpcService {
 private readonly RPC_URL:any = process.env.ETH_RPC_WS_URL!;
 public provider:any;
 constructor(
 private readonly logger: LoggerService,
 ) {
 this.initializeProvider();
 }
 private initializeProvider() {
 this.provider = new ethers.WebSocketProvider(this.RPC_URL);
 // Keep the connection alive
 this.provider.websocket.on("open", () => {
 this.logger.log("RPC provider websocket connected");
 console.log("####################")
 console.log("----------- RPC provider websocket connected -----------");
 console.log("####################")
 setInterval(() => {
 this.provider.websocket.send("ping");
 }, 30000); // Send a ping every 30 seconds
 });
 // Reconnect on error or close
 this.provider.websocket.on("close", () => {
 this.logger.error("RPC provider websocket closed. Attempting to reconnect...");
 this.initializeProvider();
 });
 this.provider.websocket.on("error", (error:any) => {
 this.logger.error("RPC provider websocket error:", error);
 this.initializeProvider();
 });
 }
 
}

As you see I'm listening close and error messages on RPC websocket. I'm also sending "ping" message on every 30 seconds.

Sometimes I get error and shutdown messages from Alchemy. There is no problem with this. Because in these cases the websocket connection is reestablished anyway. However, sometimes the connection goes without receiving any message and the service I wrote above cannot listen to events and cannot call functions.

I don't think it is an error caused by Alchemy. Because I do not get an error when the same service is running simultaneously in my local.

I am not sure, but I think the ping message is not configured correctly. Also, I think ethersjs does not check if the connection is stable. When I restart the application, the error disappears completely.

At this point, how can I send the ping message to Alchemy properly and test the connection?

asked Apr 1, 2025 at 9:19
1
  • Why arent you checking the response from the ping? You're just sending it but if it fails you probably wanna do something Commented Apr 1, 2025 at 17:46

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.