如何在打字稿任务中使用hardhat.ethers?

Max*_*ina 1 typescript ethers.js hardhat

以下代码找不到“ethers”

import { HardhatUserConfig, task } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";

task('read',async () => {
    const contract = ethers.getContractFactory('AwesomeContract');
    // ...
})

const config: HardhatUserConfig = {
  solidity: "0.8.15",
};

export default config;
Run Code Online (Sandbox Code Playgroud)

开发者当然不能这样做:

import { ethers } from 'hardhat';
Run Code Online (Sandbox Code Playgroud)

因为它抛出HH9

是否可以在打字稿任务中使用hardhat.ethers?

小智 6

在运行任务之前,Harhat 会将 Hardhad 运行时环境注入全局范围,因此您需要ethers从中获取。

检查文档示例

task(
  "hello",
  "Prints 'Hello, World!'",
  async function (taskArguments, hre, runSuper) {
    console.log("Hello, World!");
  }
);
Run Code Online (Sandbox Code Playgroud)

还有另一个更真实的例子:

hardhat.config.ts

import { HardhatUserConfig, task } from "hardhat/config"

import { updateItem } from "./scripts"

task("updateItem", "Update a listed NFT price")
  .addParam("id", "token ID")
  .addParam("price", "token new listing price")
  .setAction(async (args, hre) => {
    const tokenId = Number(args.id)
    const newPrice = String(args.price)
    await updateItem(hre, tokenId, newPrice)
  })

...
Run Code Online (Sandbox Code Playgroud)

updateItem.ts

import { HardhatRuntimeEnvironment } from "hardhat/types"
import { NFTMarketplace } from "../typechain"

async function updateItem(hre: HardhatRuntimeEnvironment, tokenId: number, newPrice: string) {
  const nftMarketplace = (await hre.ethers.getContract("NFTMarketplace")) as NFTMarketplace
  ...
}

export default updateItem
Run Code Online (Sandbox Code Playgroud)