Skip to content

Hardhat Console ethers not accessible #1284

@ottpeter

Description

@ottpeter

Hardhat Console: ethers not accessible after following documentation (Hardhat 3.x ESM)

Description

I followed the Hardhat setup documentation at https://docs.moonbeam.network/builders/ethereum/dev-env/hardhat/#__tabbed_2_3 but was unable to use ethers in the Hardhat console.

Problem

When running npx hardhat console --network moonbase and trying to use ethers, I got:

> const Box = await ethers.getContractFactory('Box');
Uncaught ReferenceError: ethers is not defined

Attempting to use require as suggested in some examples also failed:

> const hre = require("hardhat");
Uncaught Error: require is not supported in ES module scope

Root Cause

Hardhat 3.x requires ESM ("type": "module" in package.json), which breaks the traditional CommonJS patterns. Additionally, in Hardhat 3.x with ESM:

  1. Plugins must be explicitly imported and added to the plugins array in the config
  2. ethers is not automatically available globally in the console
  3. ethers is attached to the network connection object, not directly on hre
  4. require() doesn't work - ESM uses import() instead

Solution

1. Update package.json to include ESM:

{
  "type": "module",
  "dependencies": {
    "@nomicfoundation/hardhat-ethers": "^4.0.3",
    "hardhat": "^3.0.14"
  },
  "devDependencies": {
    "@nomicfoundation/hardhat-ignition-ethers": "^3.0.5",
    "@nomicfoundation/hardhat-keystore": "^3.0.3"
  }
}

2. Update hardhat.config.js to explicitly load plugins:

import { configVariable } from "hardhat/config";
import { default as hardhatEthers } from "@nomicfoundation/hardhat-ethers";
import { default as hardhatIgnitionEthers } from "@nomicfoundation/hardhat-ignition-ethers";
import { default as hardhatKeystore } from "@nomicfoundation/hardhat-keystore";

/** @type import('hardhat/config').HardhatUserConfig */
export default {
  plugins: [hardhatEthers, hardhatIgnitionEthers, hardhatKeystore],
  solidity: {
    compilers: [
      {
        version: "0.8.28",
        settings: {
          optimizer: {
            enabled: false,
          },
        },
      },
    ],
  },
  networks: {
    moonbase: {
      type: "http",
      chainType: "generic",
      chainId: 1287,
      url: "https://rpc.api.moonbase.moonbeam.network",
      accounts: process.env.MOONBASE_PRIVATE_KEY 
        ? [process.env.MOONBASE_PRIVATE_KEY]
        : [configVariable("MOONBASE_PRIVATE_KEY")],
    },
  },
};

Key change: Plugins must be imported as default exports and added to the plugins array.

3. Create a helper file load-ethers.js:

// Helper to load ethers in Hardhat console
// Usage in console:
// > const { ethers } = await import("./load-ethers.js");

import hre from "hardhat";

const connection = await hre.network.connect();
export const ethers = connection.ethers;

console.log("✅ Ethers loaded successfully! You can now use ethers.getSigners(), ethers.getContractFactory(), etc.");

4. Usage in console:

export MOONBASE_PRIVATE_KEY="your-private-key"
npx hardhat console --network moonbase

Then in the console:

> const { ethers } = await import("./load-ethers.js");
 Ethers loaded successfully!

> const [signer] = await ethers.getSigners();
> console.log("Address:", signer.address);

> const Box = await ethers.getContractFactory('Box');
> // ... rest of your code

Suggested Documentation Updates

  1. Add a section specifically for Hardhat 3.x ESM setup with the plugin configuration requirements
  2. Include the load-ethers.js helper or explain how to access ethers via hre.network.connect()
  3. Update console usage examples to show the import() syntax instead of require()
  4. Clarify that configVariable() (keystore) doesn't work in console - recommend using environment variables for console usage
  5. Add troubleshooting section for common ESM-related errors

Environment

  • Hardhat: 3.0.14
  • @nomicfoundation/hardhat-ethers: 4.0.3
  • Node.js: 22.x
  • OS: Linux

Complete Working Configuration Files

package.json

{
  "name": "hardhat",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@nomicfoundation/hardhat-ethers": "^4.0.3",
    "hardhat": "^3.0.14"
  },
  "type": "module",
  "devDependencies": {
    "@nomicfoundation/hardhat-ignition": "^3.0.5",
    "@nomicfoundation/hardhat-ignition-ethers": "^3.0.5",
    "@nomicfoundation/hardhat-keystore": "^3.0.3",
    "@nomicfoundation/hardhat-toolbox-mocha-ethers": "^3.0.1",
    "@types/chai": "^4.3.20",
    "@types/chai-as-promised": "^8.0.2",
    "@types/mocha": "^10.0.10",
    "@types/node": "^22.19.1",
    "chai": "^5.3.3",
    "ethers": "^6.15.0",
    "forge-std": "github:foundry-rs/forge-std#v1.9.4",
    "mocha": "^11.7.5",
    "typescript": "~5.8.0"
  }
}

hardhat.config.js

import { configVariable } from "hardhat/config";
import { default as hardhatEthers } from "@nomicfoundation/hardhat-ethers";
import { default as hardhatIgnitionEthers } from "@nomicfoundation/hardhat-ignition-ethers";
import { default as hardhatKeystore } from "@nomicfoundation/hardhat-keystore";

/** @type import('hardhat/config').HardhatUserConfig */
export default {
  plugins: [hardhatEthers, hardhatIgnitionEthers, hardhatKeystore],
  solidity: {
    compilers: [
      {
        version: "0.8.28",
        settings: {
          optimizer: {
            enabled: false,
          },
        },
      },
    ],
  },
  networks: {
    hardhatMainnet: {
      type: "edr-simulated",
      chainType: "l1",
    },
    hardhatOp: {
      type: "edr-simulated",
      chainType: "op",
    },
    sepolia: {
      type: "http",
      chainType: "l1",
      url: "wss://wss.api.moonbase.moonbeam.network",
      accounts: process.env.SEPOLIA_PRIVATE_KEY 
        ? [process.env.SEPOLIA_PRIVATE_KEY]
        : [configVariable("SEPOLIA_PRIVATE_KEY")],
    },
    moonbase: {
      type: "http",
      chainType: "generic",
      chainId: 1287,
      url: "https://rpc.api.moonbase.moonbeam.network",
      accounts: process.env.MOONBASE_PRIVATE_KEY 
        ? [process.env.MOONBASE_PRIVATE_KEY]
        : [configVariable("MOONBASE_PRIVATE_KEY")],
    },
  },
};

load-ethers.js

// Helper to load ethers in Hardhat console
// Usage in console:
// > const { ethers } = await import("./load-ethers.js");
// Then use ethers normally

import hre from "hardhat";

const connection = await hre.network.connect();
export const ethers = connection.ethers;

console.log("✅ Ethers loaded successfully! You can now use ethers.getSigners(), ethers.getContractFactory(), etc.");

tsconfig.json

{
  "compilerOptions": {
    "lib": ["es2023"],
    "module": "node16",
    "target": "es2022",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "moduleResolution": "node16",
    "outDir": "dist"
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions