Search code examples
typescriptethers.jshardhat

How can I use hardhat.ethers inside a typescript task?


Following code can't find '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;

Of course the developer can't do this:

import { ethers } from 'hardhat';

because it throws HH9.

Is it possible to use hardhat.ethers inside typescript tasks?


Solution

  • Before running a task, Hardhat injects the Hardhad Runtime Environment into the global scope, so you need to get ethers from it.

    Check the documentation example:

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

    And another more real example:

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

    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