使用hardhat编写脚本时,遇到TypeError: ethers.getContract is not a function的解决方法

使用hardhat编写脚本时,遇到TypeError: ethers.getContract is not a function的解决方法

在使用 hardhat 编写部署或测试脚本在本地部署时,如果是多个合约相互调用,每次修改合约地址是非常麻烦的一件事情。hardhat 团队提供了ethers.getContract 方法,可以直接通过合约名称获取合约实例。

例如:

 const mshkNftContract = await ethers.getContract("MSHK721NFT1")

第一次运行脚本时,如果遇到如下错误,是因为未引用到正确的包。

$ npx hardhat run script/ERC721/03-mint-and-list-item.js --network localhost
TypeError: ethers.getContract is not a function
    at mintAndList (/hardhat/script/ERC721/03-mint-and-list-item.js:17:49)

运行下面的命令,可以进行修复:

$ yarn add -D @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers
yarn add v1.22.19
warning package.json: No license field
warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.
warning hardhat-project: No license field
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning " > @nomiclabs/hardhat-waffle@2.0.3" has incorrect peer dependency "@nomiclabs/hardhat-ethers@^2.0.0".
warning " > @openzeppelin/hardhat-upgrades@1.19.0" has incorrect peer dependency "@nomiclabs/hardhat-ethers@^2.0.0".
warning "hardhat-deploy > zksync-web3@0.4.0" has incorrect peer dependency "ethers@~5.5.0".
[4/4] 🔨  Building fresh packages...
warning hardhat-project: No license field
success Saved 0 new dependencies.
✨  Done in 3.42s.

再次运行测试脚本,可以看到能够成功运行,并且输出正确的信息:

$ npx hardhat run script/ERC721/03-mint-and-list-item.js --network localhost
Minting NFT for 0x70997970C51812dc3A010C7d01b50e0d17dc79C8
Approving Marketplace as operator of NFT...
Listing NFT...
NFT Listed with token ID:  0
NFT with ID 0 minted and listed by owner 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 with identity OWNER.

发表回复

您的电子邮箱地址不会被公开。