I have a basic node express application. It connects to my locally running hardhat network via ethers & websocket. The connection seems to work, since I can query the blockchain succesfully (for instance await ethers.getBlockNumber()
returns the correct block number).
However, my event listeners do not seem to work. The callbacks are never triggered.
Code example: I'm using a loader function when I initialize the express app. When it is executed, I connect to the websocket provider. Then I successfully print the current block number to the console. Then I register an event listener on the "block" event (taken from the documentation). However, the listener never fires.
I'm connecting to the hardhat network, which is configured to produce a new block every five seconds (I can see that this is the case in the hardhat console). I would expect the listener to be fired every five seconds, always when a new block is mined.
What am I missing?
import { ethers } from "ethers";
export default async ({ expressApp }) => {
const provider = new ethers.providers.WebSocketProvider(
"ws://localhost:8545"
);
console.log(await provider.getBlockNumber());
provider.on("block", () => console.log("new block"));
expressLoader({ app: expressApp });
};
EDIT:
If I use the JsonRpcProvider
instead of WebSocketProvider
and the following url http://localhost:8545
the callbacks are fired. What do I need to do to achieve the same behavior with websocket?