繁体   English   中英

通过 Hardhat 将智能合约部署到孟买 tes.net 时出错

[英]Error while deploying a smart contract to Mumbai testnet through Hardhat

我在尝试使用 Hardhat 将智能合约部署到孟买 tes.net 时遇到了这个问题,并且不断收到以下错误:

 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

这是我的智能合约代码:

 // 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; } }

这是部署脚本:

 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); });

这是我的 hardhat.config 文件:

 /** * @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, }, };

这是我的 package.json 文件:

 { "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" } }

当我尝试通过替换以下行来修复它时:const { ethers } = require("hardhat"); 与: const { ethers } = require("hardhat/config"); 我收到以下错误:TypeError: Cannot read property 'getContractFactory' of undefined

即使我将 deploy.js 代码替换为基于任务和助手的代码,它也能成功编译,但 npx hardhat run scripts/deploy.js -.network mumbai 它不会返回任何内容。

这是我替换它的代码:

部署.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}`); });

和 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, }

任何帮助将不胜感激,我已经坚持了将近一个星期了。

具有讽刺意味的是,我在发布这篇文章时就找到了解决方案。 好吧,这是给遇到同样问题的人的:在 hardhat.config 文件中,从 both.network url 和 accounts 中删除“${}”。 那为我解决了。 不敢相信我花了这么长时间才弄明白哈哈

所以你的配置文件应该是这样的:

 /** * @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, }, };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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