Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

hardhat

БесплатноБез исполняемых скриптовНе проверен

Hardhat 3 is a development environment for Ethereum smart contracts: it compiles Solidity, runs tests on a built-in simulated chain, deploys with Ignition and…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Hardhat

Overview

Hardhat 3 (current: 3.21) is an ESM-only TypeScript toolchain for Solidity. It compiles contracts, runs an in-process simulated chain (EDR), tests in TypeScript (Mocha + ethers, or the Node test runner + viem) and in Solidity, deploys with Hardhat Ignition, and verifies on Etherscan, Blockscout and Sourcify. Hardhat 3 differs from 2 in ways that break old snippets: no hardhat-toolbox, no global ethers import, no etherscan config key, network.create() instead of implicit networks. Hardhat 2 (hardhat@hh2) is end of life; a 2.x project keeps working until migrated.

Instructions

Step 1: Set up a project

Needs Node.js 22.13 or later. The init command is interactive (it needs a terminal):

mkdir token-sale && cd token-sale
npm init -y
npm install --save-dev hardhat
npx hardhat --init        # pick a template: mocha-ethers, node-test-runner-viem or minimal

The mocha-ethers template installs @nomicfoundation/hardhat-toolbox-mocha-ethers plus ethers, mocha and chai, and sets "type": "module" in package.json. Keep that: Hardhat 3 does not load CommonJS configs. Add contract libraries with npm install @openzeppelin/contracts.

Step 2: Write a contract and tests

// contracts/MyToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}

In Hardhat 3 the connection is created in the test file with network.create(); ethers and networkHelpers come from that connection, not from import { ethers } from "hardhat".

// test/MyToken.ts
import { expect } from "chai";
import { network } from "hardhat";

const { ethers, networkHelpers } = await network.create();

describe("MyToken", function () {
  async function deployFixture() {
    const [owner, user1, user2] = await ethers.getSigners();
    const token = await ethers.deployContract("MyToken", [ethers.parseEther("1000000")]);
    return { token, owner, user1, user2 };
  }

  it("assigns the total supply to the deployer", async function () {
    const { token, owner } = await networkHelpers.loadFixture(deployFixture);
    expect(await token.balanceOf(owner.address)).to.equal(await token.totalSupply());
  });

  it("transfers tokens", async function () {
    const { token, user1 } = await networkHelpers.loadFixture(deployFixture);
    const amount = ethers.parseEther("100");
    await expect(token.transfer(user1.address, amount)).to.changeTokenBalance(ethers, token, user1, amount);
  });

  it("reverts when the sender has no balance", async function () {
    const { token, user1, user2 } = await networkHelpers.loadFixture(deployFixture);
    await expect(token.connect(user1).transfer(user2.address, 1n))
      .to.be.revertedWithCustomError(token, "ERC20InsufficientBalance");
  });
});

Solidity tests (*.t.sol files using forge-std) also run under npx hardhat test; npx hardhat test mocha and npx hardhat test solidity run one kind.

Step 3: Configure networks and secrets

configVariable("NAME") is read lazily from an environment variable or the encrypted keystore, so the config never holds a secret.

// hardhat.config.ts
import hardhatToolboxMochaEthersPlugin from "@nomicfoundation/hardhat-toolbox-mocha-ethers";
import { configVariable, defineConfig } from "hardhat/config";

export default defineConfig({
  plugins: [hardhatToolboxMochaEthersPlugin],
  solidity: { version: "0.8.34" },
  networks: {
    mainnetFork: {
      type: "edr-simulated",
      chainType: "l1",
      forking: { url: configVariable("MAINNET_RPC_URL"), blockNumber: 21000000 },
    },
    sepolia: {
      type: "http",
      chainType: "l1",
      url: configVariable("SEPOLIA_RPC_URL"),
      accounts: [configVariable("SEPOLIA_PRIVATE_KEY")],
    },
  },
  verify: { etherscan: { apiKey: configVariable("ETHERSCAN_API_KEY") } },
});

Store values in the keystore instead of a .env file: npx hardhat keystore set SEPOLIA_PRIVATE_KEY prompts for the value (keystore list, get, delete, change-password also exist; --dev targets a separate development keystore for throwaway keys). Every network must have a type: edr-simulated for local or forked, http for a remote RPC. Use a funded throwaway testnet key, never a mainnet key.

Step 4: Build, test, deploy, verify

npx hardhat build                            # compile (replaces `hardhat compile`)
npx hardhat test                             # all tests
npx hardhat test --gas-stats                 # per-function gas table
npx hardhat test --coverage                  # line and statement coverage
npx hardhat test --network mainnetFork       # run tests on the fork

Deploy with an Ignition module instead of a script:

// ignition/modules/MyToken.ts
import { b
Полный SKILL.md на GitHub

Установить hardhat в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл hardhat?

Hardhat 3 is a development environment for Ethereum smart contracts: it compiles Solidity, runs tests on a built-in simulated chain, deploys with Ignition and verifies on block explorers. Use when a user asks to set up a Solidity project, test or deploy smart contracts, fork mainnet, or check gas and coverage.

Как установить скилл hardhat?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл hardhat запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить hardhat с