簡體   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