I'm looking to get the ID of the chain/network I'm running a script on in hardhat. How can I get the names and IDs?
- 11,186
- 5
- 44
- 97
3 Answers
There are a few ways to get the network/chain name/id. We are going to assume you are in a script that you'd like to run, or a test. When running these, you must have a hardhat.config.ts or hardhat.config.js, and you must be running the script "in" hardhat. For example: npx hardhat run scripts/your_script_here.ts
import hre from 'hardhat'
const networkName = hre.network.name
const chainId = hre.network.config.chainId
This means, you'll need a hardhat.config that looks something like:
const config: HardhatUserConfig = {
defaultNetwork: 'hardhat',
networks: {
hardhat: {
chainId: 31337,
accounts: [process.env.PRIVATE_KEY!],
},
You could also create a file that has a mapping between your network/chain name and ID.
Alternatively, you could use hardhat-deploy with something like:
import { HardhatRuntimeEnvironment } from 'hardhat/types'
import { DeployFunction } from 'hardhat-deploy/types'
const deployScript: DeployFunction = async function (
hre: HardhatRuntimeEnvironment
) {
const { getChainId } = hre
const chainId = await getChainId()
Combined with a network mapping.
- 11,186
- 5
- 44
- 97
-
Hi, big fan thanks for ur videos :) could you please do a video or tutorial or blog article to explain the new gas system in ethereum and how to configure it correctly inside a transaction in hardhat or ethers. It was very simple before London fork.. now it is not :( – Majd TL Nov 05 '21 at 18:10
Another way to do it that works for me is
const { ethers } = require("hardhat");
const network = await ethers.getDefaultProvider().getNetwork();
console.log("Network name=", network.name);
console.log("Network chain id=", network.chainId);
As with the accepted answer, you must be running "in" Hardhat for this to work.
- 180
- 5
Add your network to networks section in hardhat config file:
networks: {
hardhat: {},
polygon: {
url: JSON_RPC_URL, // Alchemy/Infura/QuickNode,...
chainId: 137, // optional,
accounts: [YOUR_ACCOUNT_PRIVATE_KEY] // optional
}
}
then in your scripts to get chainId as hex string:
import { network } from 'hardhat';
const chainIdHex = await network.provider.send('eth_chainId');
- 21
- 2