I want to add some nice output in my hardhat scripts for showing what my configurations are during a test run. I run the script locally while changing configuration variables and I want the console output to reflect those config changes so that I can more easily track things.
For example, here is my hardhat.config.js:
require("@nomiclabs/hardhat-waffle"); require("dotenv").config(); /** * @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.4", networks: { rinkeby: { url: process.env.ALCHEMY_URL, // url: process.env.INFURA_URL, // url: process.env.QUICKNODE_URL, // url: process.env.MORALIS_URL, accounts: [process.env.PK] } } }; And here is my workflow:
- run the script with existing settings
thatguyintech@albert eth-call-analysis % npx hardhat run scripts/sample-script.js rpc url: localhost GasLimits contract deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3 - change the
urlconfig and re-run
thatguyintech@albert eth-call-analysis % npx hardhat run scripts/sample-script.js --network rinkeby rpc url: https://eth-rinkeby.alchemyapi.io/v2/<my api key> GasLimits contract deployed to: 0xeb8aeddb118b8141ea4e0e0e0d7e7ee685f214ac In order to get the above output, my sample-script.js looks like this:
const hre = require("hardhat"); async function main() { console.log("rpc url: ", process.env.ALCHEMY_URL) // I have to manually change this on each run. // We get the contract to deploy const GasLimits = await hre.ethers.getContractFactory("GasLimits"); const gasLimits = await GasLimits.deploy(); await gasLimits.deployed(); console.log("GasLimits contract deployed to:", gasLimits.address); } Is there a way to read the hardhat.config.js values at runtime so that I don't have to rely on dotenv and change my script manually on each run?
Specifically, is there a way to rewrite console.log("rpc url: ", process.env.ALCHEMY_URL) into something that can automatically update based on how I've set my hardhat.config.js? Maybe something like this: console.log("rpc url: ", hre.config.networks.url)?
Update: I do see in the hardhat runtime environment docs that there is an hre.config object I can use. However, I don't want to know about the original configuration, I want to know the network that is currently be used at runtime at the time that my script is invoked. Any tips for that?