[Ethereum] How to connect a local Hardhat network to Metamask

hardhatmetamask

I have started a Hardhat network with default configuration using npx hardhat node. After running this command, I see Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/ and a list of 20 seed accounts along with their private keys.

Then, in Metamask, I've gone to "Custom RPC" network configuration, and entered the following:

Network Name: Hardhat

New RPC URL: http://localhost:8545

Chain ID: 31337

But when I try to apply the changes, I see this error: Could not fetch chain ID. Is your RPC URL correct?

If I enter http://localhost:8545 in my web browser, I see this JSON: {"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: Unexpected end of JSON input"}}

I am able to successfully run code that connects to the local Hardhat network and passes tests. I'm able to successfully run Hardhat tasks by using commands like npx hardhat TASKNAME --network localhost. I've tried using 127.0.0.1 instead of localhost in the Metamask config. I'm using WSL2 to run Bash and the Hardhat server.

Best Answer

The issue turned out to be caused by the browser I was using: Brave. It has some default ad blockers called "shields". These somehow prevented me from connecting the Metamask extension to my local network. In Brave settings for shields, I set "Trackers & ads blocking" to "disabled", and the issue was resolved.

Related Topic