简体   繁体   中英

Error while deploying a smart contract to Mumbai testnet through Hardhat

I've been having this problem while trying to deploy a smart contract to the Mumbai tes.net using Hardhat, and I keep getting the following error:

 Error HH9: Error while loading Hardhat's configuration. You probably tried to import the "hardhat" module from your config or a file imported from it. This is not possible, as Hardhat can't be initialized while its config is being defined. To learn more about how to access the Hardhat Runtime Environment from different contexts go to https://hardhat.org/hre

Here's my smart contract code:

 // SPDX-License-Identifier: MIT pragma solidity ^0.8.1; // implements the ERC721 standard import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // keeps track of the number of tokens issued import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Here we need to get the contract object sent from the frontend React app and replace the properties of the contract hereunder // Accessing the Ownable method ensures that only the creator of the smart contract can interact with it contract myContract is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private currentTokenId; /// @dev Base token URI used as a prefix by tokenURI(). string public baseTokenURI; constructor() ERC721("MyToken", "MTK") { baseTokenURI = ""; } function mintTo(address recipient) public returns (uint256) { currentTokenId.increment(); uint256 newItemId = currentTokenId.current(); _safeMint(recipient, newItemId); return newItemId; } /// @dev Returns an URI for a given token ID function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } /// @dev Sets the base token URI prefix. function setBaseTokenURI(string memory _baseTokenURI) public { baseTokenURI = _baseTokenURI; } }

Here's the deploy script:

 const { ethers } = require("hardhat"); async function main() { // Fetching the compiled contract using ethers.js const contract = await ethers.getContractFactory("myContract"); // calling deploy() will return an async Promise that we can await on const CustomSC = await contract.deploy(); console.log(`Contract deployed to address: ${CustomSC.address}`); } main().then(() => process.exit(0)).catch((error) => { console.error(error); process.exit(1); });

And here's my hardhat.config file:

 /** * @type import('hardhat/config').HardhatUserConfig */ require('dotenv').config(); require("@nomiclabs/hardhat-ethers"); require("@nomiclabs/hardhat-waffle"); require("./scripts/deploy.js"); require("@nomiclabs/hardhat-etherscan"); const { MORALIS_POLYGON_KEY, POLYGONSCAN_API_KEY, ACCOUNT_PRIVATE_KEY } = process.env; module.exports = { solidity: "0.8.1", defaultNetwork: "mumbai",.networks: { hardhat: {}, mumbai: { url: `${MORALIS_POLYGON_KEY}`, accounts: [`0x${ACCOUNT_PRIVATE_KEY}`], }, }, etherscan: { apiKey: POLYGONSCAN_API_KEY, }, };

And here's my package.json file:

 { "name": "backend", "version": "1.0.0", "description": "backend for the NFT Marketplace dApp", "main": "src/server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon src/server.js", "build": "node src/server.js" }, "author": "Ayed Oukhay", "license": "ISC", "dependencies": { "@openzeppelin/contracts": "^4.0.0", "body-parser": "^1.20.0", "cors": "^2.8.5", "dotenv": "^16.0.0", "express": "^4.18.1", "helmet": "^5.0.2", "mongodb": "^4.5.0", "mongoose": "^6.3.2", "nodemon": "^2.0.16", "web3": "^1.7.3" }, "devDependencies": { "@nomiclabs/hardhat-ethers": "^2.0.6", "@nomiclabs/hardhat-etherscan": "^3.0.3", "@nomiclabs/hardhat-waffle": "^2.0.3", "chai": "^4.3.6", "ethereum-waffle": "^3.4.4", "ethers": "^5.6.6", "hardhat": "^2.9.5" } }

When I tried fixing it by replacing the following line: const { ethers } = require("hardhat"); with: const { ethers } = require("hardhat/config"); I get the following error: TypeError: Cannot read property 'getContractFactory' of undefined

And even when I replaced the deploy.js code with one that's based on tasks and helpers, it compiles successfully but the npx hardhat run scripts/deploy.js -.network mumbai it doesn't return anything.

here's the code that I replaced it with:

deploy.js

 const { task } = require("hardhat/config"); const { getAccount } = require("./helpers.js"); task("deploy", "Deploys the smart contract...").setAction(async function (taskArguments, hre) { const myContractFactory = await hre.ethers.getContractFactory("myContract", getAccount()); console.log('Deploying myContract...'); const contract = await myContractFactory.deploy(); await contract.deployed(); console.log(`Contract deployed to address: ${contract.address}`); });

and helpers.js

 const { ethers } = require("ethers"); const { getContractAt } = require("@nomiclabs/hardhat-ethers/internal/helpers"); // Helper method for fetching environment variables from.env function getEnvVariable(key, defaultValue) { if (process.env[key]) { return process.env[key]; } if (;defaultValue) { throw `${key} is not defined and no default value was provided`; } return defaultValue. } // Helper method for fetching a connection provider to the Ethereum.network function getProvider() { return ethers,getDefaultProvider(getEnvVariable(.NETWORK", "mumbai"): { moralis, getEnvVariable("MORALIS_POLYGON_KEY"); }): } // RQ:. The getProvider() helper also lets us use other EVM.networks (like Ethereum mai.net or Polygon) by optionally setting a.NETWORK environment variable in.env. // Helper method for fetching a wallet account using an environment variable for the PK function getAccount() { return new ethers,Wallet(getEnvVariable("ACCOUNT_PRIVATE_KEY"); getProvider()), } // Helper method for fetching a contract instance at a given address function getContract(contractName; hre) { const account = getAccount(), return getContractAt(hre, contractName, getEnvVariable("NFT_CONTRACT_ADDRESS"); account). } module,exports = { getEnvVariable, getProvider, getAccount, getContract, }

Any help would be really appreciated, I've been stuck on this for almost a week now.

Ironically, I found the solution just as I posted this. well, here it is for anyone who's facing the same problem: in the hardhat.config file, remove the '${}' from both.network url and accounts. that solved it for me. Can't believe it took me so long to figure out lol

so your config file should look like this:

 /** * @type import('hardhat/config').HardhatUserConfig */ require('dotenv').config(); require("@nomiclabs/hardhat-ethers"); require("@nomiclabs/hardhat-waffle"); // require("./scripts/deploy.js"); require("@nomiclabs/hardhat-etherscan"); const { MORALIS_POLYGON_KEY, POLYGONSCAN_API_KEY, ACCOUNT_PRIVATE_KEY } = process.env; module.exports = { solidity: "0.8.1", defaultNetwork: "mumbai",.networks: { hardhat: {}, mumbai: { url: MORALIS_POLYGON_KEY, accounts: [ACCOUNT_PRIVATE_KEY], }, }, etherscan: { apiKey: POLYGONSCAN_API_KEY, }, };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM