Hardhat JSON-RPC – Spin Up Local Fork Node at Specific Block

hardhathardhat-deployjavascriptnodejs

I can "spin up" a local fake blockchain in Terminal using

$ hardhat node

I can also make it fork the real mainnet using Alchemy, even pin it to a specific block N. Other local applications can then connect at http://localhost:8545 and interact with the forked local chain until I press Ctrl+C in that Terminal window and my local JSON-RPC node disappears. So far so good.

My question is: How do I combine this feature with deploying a contract?

How do I do BOTH:

  1. Spin up the forked chain at block N, so it is usable via port 8545 (launch an JSON-RPC server that runs until I stop it)
  2. And while my forked chain spins up, how do I deploy a test contract "into it" (probably will increase my block number from N to N + 1)?

What I have tried:

I have tried a deploy script. It seems that I can "spin up" the desired forked chain at block N momentarily, but at no time is it accessible via port 8545 to other applications.

Inside the script, I can deploy a contract with the usual deploy commands, and even interact with my contract.

What I really need though, is a "live" (accessible via port 8545 or 8546) forked chain with my brand new contract "in it", so another app (that is not launched via hardhat or hh commands) can interact with it.

Is this possible?

Best Answer

Just like it was said by Franco in the previous answer you can use the --network tag to deploy to the node you're running. For easy deployment, you can use the hardhat deploy plugin.

I would like to add that you make the app you're running locally accessible to other people by running ngrok for example. Since the node you're running is on localhost:8545, you could run ngrok http 8545 which will give you a url like https://XXXX-XXXX.ngrok.io
You can then share that link with other people (they can input it into their Metamask or you could use it in your web application. It's a great way of testing your app quickly from your localhost

Related Topic