Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@solarity/hardhat-migrate

dl-solarity1.2kMIT3.1.1TypeScript support: included

The simplest way to deploy smart contracts

ethereum, solidity, smart-contracts, hardhat, hardhat-plugin, etherscan, distributedlab, solarity

readme

npm hardhat

Hardhat migrate

The simplest way to deploy smart contracts.

What

This plugin helps you deploy and verify the source code for your Solidity contracts via migrations.

With sleek UX that doesn't require writing "deployment wrappers", users can:

  • Specify custom smart contract deployment rules and configuration via @ethers.
  • Verify smart contracts source code through seamless integration with @nomicfoundation/hardhat-verify.
  • Leverage "migration recovery mode" that syncs up deployment from the last failed transaction.
  • Observe real-time status and logging of executing transactions.
  • Check out the generation of deployment reports in Markdown (.md) or JSON (.json) format.
  • Simplify Solidity libraries usage via auto-linking mechanics.
  • Support multiple wallet types, including Cast Wallet and Trezor hardware wallet.
  • And much more.

Installation

npm install --save-dev @solarity/hardhat-migrate

Add the following statement to your hardhat.config.js:

require("@solarity/hardhat-migrate");
require("@nomicfoundation/hardhat-ethers");
require("@nomicfoundation/hardhat-verify"); // If you want to verify contracts

Or, if you are using TypeScript, add this to your hardhat.config.ts:

import "@solarity/hardhat-migrate";
import "@nomicfoundation/hardhat-ethers";
import "@typechain/hardhat"; // For typization of Ethers
import "@nomicfoundation/hardhat-verify"; // If you want to verify contracts

[!NOTE] The @nomicfoundation/hardhat-ethers import is obligatory as it is used to determine the deployment account.

Usage

You may add the following migrate config to your hardhat.config file:

module.exports = {
  migrate: {
    filter: {
      from: -1,
      to: -1,
      only: -1,
      skip: -1,
    },
    verification: {
      verify: false,
      verificationDelay: 5000,
      verifyParallel: 1,
      verifyAttempts: 3,
    },
    paths: {
      pathToMigrations: "./deploy",
      namespace: "",
    },
    execution: {
      force: false,
      continue: false,
      wait: 1,
      transactionStatusCheckInterval: 2000,
      withoutCLIReporting: false,
    },
    castWallet: {
      passwordFile: "/path/to/password",
      keystore: "/path/to/keystore",
      account: "account-name",
    },
    trezorWallet: {
      enabled: false,
      mnemonicIndex: 0,
    },
  },
};

Where:

  • filter
    • from - The migration number from which the migration will be applied.
    • to - The migration number up to which the migration will be applied.
    • only - The number of the migration that will be applied. Overrides from and to parameters.
    • skip- The number of migration to skip. Overrides only parameter.
  • verification
    • verify - The flag indicating whether the contracts have to be verified after all migrations.
    • verificationDelay - The delay in milliseconds between the deployment and verification of the contract.
    • verifyParallel - The size of the batch for verification.
    • verifyAttempts - The number of attempts to verify the contract.
  • paths
    • pathToMigrations - The path to the folder with the specified migrations.
    • namespace - The path to the subfolder where the migration should be run.
    • reportPath - The path to directory where the migration report should be saved (./cache by default).
    • reportFormat - The format of the migration report (md or json). Defaults to md for Markdown format.
  • execution
    • force - The flag indicating whether the contracts compilation is forced.
    • continue - The flag indicating whether the deployment should restore the state from the previous deployment.
    • wait - The number of block confirmations to wait for after the transaction is mined.
    • transactionStatusCheckInterval - The interval in milliseconds between transaction status checks.
    • withoutCLIReporting - The flag indicating whether the CLI reporting should be disabled.
  • castWallet
    • passwordFile - File path to the keystore password.
    • keystore - Use a keystore file or directory. Cannot be used with account.
    • account - The name of the cast wallet account. Cannot be used with keystore.
  • trezorWallet
    • enabled - The flag indicating whether to use the Trezor hardware wallet for signing transactions.
    • mnemonicIndex - The mnemonic index for Trezor wallet.

Tasks

  • migrate task, which allows you to deploy and automatically verify contracts.
  • migrate:verify task, which helps you verify already deployed contracts.

To view the available options, run the help command:

npx hardhat help migrate

[!WARNING] If you are willing to verify smart contracts source code, make sure to specify the correct config for the @nomicfoundation/hardhat-verify plugin.

Migration naming

It is mandatory to follow this naming convention for migration files:

X_migration_name.migration.[js|ts]

  • Where X is an ordinal number indicating the order in which the migration will be applied.
  • migration_name is simply the name of the migration.

Example

After importing the necessary dependencies to the hardhat.config, create the file 1_token.migration.ts in the deploy directory.

Then run:

npx hardhat migrate --network <the network of choice>

This command will run the migration script and execute all the specified actions, producing the following live deployment log:

Migration Script Deployment Output Migration Report
// file location: ./deploy/1_token.migration.ts

import { ethers } from "ethers";

import { Deployer, Reporter } from "@solarity/hardhat-migrate";

import { ERC20Mock__factory } from "../generated-types/ethers";

export = async (deployer: Deployer) => {
  // deploy the token via `Deployer` object
  const token = await deployer.deploy(
    ERC20Mock__factory, // contract to deploy
    ["Example Token", "ET", 18] // constructor params
  );

  const recipient = "0x1E3953B6ee74461169A3E346060AE27bD0B5bF2B";
  const amount = ethers.parseEther("1000");

  // call `mint` function on the token
  await token.mint(recipient, amount);

  // log the token address via `Reporter` object
  await Reporter.reportContractsMD(
    ["Example Token", await token.getAddress()]
  );
};
Migration files:
> 1_token.migration.ts

> Network:             sepolia
> Network id:          11155111

Starting migration...

Running 1_token.migration.ts...

Deploying ERC20Mock
> explorer: 0xc35dd9e9600f102cf3b414f1341560870021b3824ace4bedbd59e2216bd89a49
> contractAddress: 0xc596A6e2f1558c7e030272d2A2E37E53050E2D63
> blockNumber: 7844739
> blockTimestamp: 1741263816
> account: 0xf41ceE234219D6cc3d90A6996dC3276aD378cfCF
> value: 0.0 ETH
> balance: 0.117945868841929599 ETH
> gasUsed: 571635
> gasPrice: 96.422889727 GWei
> fee: 0.055118698569093645 ETH

Transaction: ERC20Mock.mint(address,uint256)(2 arguments)
> explorer: 0x508a289795cb8e3e1265dfd8f528efc206146a62deba4f9a80a2fa19d6a6ec8e
> blockNumber: 7844740
> blockTimestamp: 1741263828
> account: 0xf41ceE234219D6cc3d90A6996dC3276aD378cfCF
> value: 0.0 ETH
> balance: 0.111637670105208768 ETH
> gasUsed: 68433
> gasPrice: 92.180654607 GWei
> fee: 0.006308198736720831 ETH

| Contract      | Address                                    |
| ------------- | ------------------------------------------ |
| Example Token | 0xc596A6e2f1558c7e030272d2A2E37E53050E2D63 |

> Total transactions:  2
> Final cost:          0.061426897305814476 ETH

Migration Report 2025-03-14T16:01:26.567Z.md

General Information

Migration Files

  • 1_token.migration.ts

Networks

Detailed Migration Files

1_token.migration.ts

Stats

Total Contracts Total Transactions Gas Used Average Gas Price Fee Payed Native Currency Sent
1 1 640068 94.301772167 GWei 0.061426897305814476 ETH 0.0 ETH

Total Cost:

0.061426897305814476 ETH

All Data

Name Address
contracts/mock/tokens/ERC20Mock.sol:ERC20Mock 0xc596A6e2f1558c7e030272d2A2E37E53050E2D63
ERC20Mock.mint(address,uint256)(2 arguments) 0x508a289795cb8e3e1265dfd8f528efc206146a62deba4f9a80a2fa19d6a6ec8e

The detailed migration report with all information about transactions is automatically saved in the ./cache folder in either Markdown (.md) or JSON (.json) format based on the reportFormat configuration.

Documentation

For more detailed information, please refer to the following documentation:

Known limitations

  • Adding, removing, moving, or renaming contracts in your Hardhat project or reorganizing the directory structure after deployment may alter the resulting bytecode in some Solidity compiler versions. See this Solidity issue for further information.
  • This plugin does not function properly with native Ethers factory methods, such as factory.attach(). Instead, use deployer.deployed().

changelog

Changelog

3.1.1

  • Fixed verification reporting with Blockscout explorers
    • Reporter now reads blockscout.customChains in addition to etherscan.customChains and prefers Blockscout entries when both exist for the same chain
  • Fixed implementation contract verification when using a custom contract name

Version 3.0.3 - 3.1.0

  • Accounted for the gasPrice and gasMultiplier in the network config
  • Added an ability to pass constructorCalldata when deploying proxy
  • Bump @nomicfoundation/hardhat-verify version

Version 3.0.2

  • Added an ability to specify custom path for reporting
  • Refactored ReporterStorage to separate contracts and transactions data structures

Version 3.0.1

  • Added BaseInstance type for better TypeChain interfaces support

Version 3.0.0

Breaking changes

  • Removed Truffle support.
  • Removed import of @nomicfoundation/hardhat-verify from the index.ts.
    • Please refer to the Installation section in the README for the updated installation instructions.
    • The motivation is to avoid conflicts with @nomicfoundation/hardhat-toolbox when using both plugins.
  • Removed the default conversion of the bigint to string for the JSON.stringify function.
  • Updated the MigrateConfig layout. Now similar by logic parameter are grouped together.

New features

  • Added an ability to specify namespaces for deployment scripts.

Now instead of having all deployment scripts in the deploy folder, tou can separate those into subfolders like below.

deploy
├── l1-deployment
│   ├── 1_core.migration.ts
│   └── 2_setup.migration.ts
└── l2-testnet
    ├── 1_prepare.migration.ts
    └── 2_deploy.migration.ts

And when running the migration, you can specify the namespace like this:

npx hardhat migrate --namespace l1-deployment
  • Added an ability to disable address shortening in the reporter with following syntax: PublicReporter.disableShortenAddress().reportContractsMD

  • Added file reporting throughout the migration process

    • During the migration the relevant report will be generated and stored in the cache folder.
  • Added an ability to link proxy to the implementation contract

    • The linking is decided based on the presence of the IMPLEMENTATION_SLOT in the contract
  • Added helper function to the Deployer for the proxy deployment: deployERC1967Proxy and deployTransparentUpgradeableProxy

  • Added integration with cast and trezor wallets.

Version 2.1.11

  • Added a caching mechanism to reduce the number of requests to the RPC provider.
  • Removed handling of network errors due to the high instability of the current implementation of the network handler.
  • Updated packages and replaced require with await import to load migration files.
  • Updated the version of the eslint package to the latest one.
  • Added the reportContractsMD function to the public reporter.
  • Fixed a bug where migration files were missing when running the migration command from outside the project root.

Version 2.1.10

  • Added an ability to change signer during the migration

Version 2.1.9

  • Updated dependencies
  • Fixed a bug when the cache was not saved if the cache directory did not exist
  • Exported TransactionStorage, VerificationStorage, and ArtifactStorage for convenience

Version 2.1.8

  • Fixed a bug where remote chain metadata overwrote the local one.

Version 2.1.7

  • Fixed a visual bug that sometimes total cost was displayed incorrectly.

Version 2.1.6

  • Fixed a bug when the default signer was used instead of the actual signer.

Version 2.1.5

  • Fixed behaviour of connect method in Ethers Adapter.

Version 2.1.4

  • Deleted pinst package.

Version 2.1.3

  • Added the verificationDelay parameter, which defines the time in milliseconds that must pass before the verification process starts.
  • Added health check for the explorer links before the verification process starts
  • Added BigInt.prototype.toJSON to the BigInt type to fix the issue with the BigInt type in the JSON.stringify function.

Version 2.1.2

  • Updated the ethers version to 6.1.1 to address issue: 4583.

Version 2.1.1

  • Fixed a bug related to the shallow copying and mutation of arguments within the getMethodString function.
  • Added ability to retrieve the class name from the contract instance.

Version 2.1.0

  • Updated packages to their latest versions (updated @nomicfoundation/hardhat-verify to version 2.0.4).
  • Added a save function to the Deployer class to enable saving the contract to storage without deploying it.

Version 2.0.1

  • Fixed a bug where an instance of a storage object overwrote the state of another object in the file.
  • Changed the way of naming for Truffle transactions to txName.

Version 2.0.0

  • Removed redundant Hardhat Runtime Extensions.
  • Removed Verifier from Migrator class.
  • Revised the test infrastructure and architecture.
  • Fixed bugs related to the recovery of contract names.
  • Fixed a bug related to contract recovery when a custom name is used.
  • Migrated test fixture projects to TypeScript, updating configurations and scripts. Created new fixture contracts for testing and deleted auto-generated files.
  • Added TransactionFieldsToSave as a return value to the sendNative function
  • Added handling of the custom chains specified in the Hardhat config
  • Refactored the architecture and made it consistent
  • Used spinner instead of console.log for network errors

Version 2.0.0-alpha.22

  • Enforce the overwriting in ArtifactStorage in the case of bytecodeHash as a key

Version 2.0.0-alpha.21

  • Fix a bug related to parsing the same bytecode for two different contracts

Version 2.0.0-alpha.20

  • Remove redundant initializers in a verifier task

Version 2.0.0-alpha.19

  • Handle the potentially undefined tx.customData.txName field

Version 2.0.0-alpha.18

  • Handle the partially linked Bytecode in the Truffle Adapter.

Version 2.0.0-alpha.17

  • Separated the logic of the Reporter and moved transaction-related functions to the TransactionRunner class.
  • Added the ability to specify a name for each transaction, essentially enabling the same transaction to be distinguishable. Also fixed a few bugs related to migration storage.
  • Added a Network Manager to handle network errors and implemented logic for reconnection. Also updated the Reporter to support these changes properly.

Version 2.0.0-alpha.16

  • Fixed a bug when txs could not be sent with overrides
  • Eliminate a collision warning during recovery

Version 2.0.0-alpha.15

  • Added ethers to dependencies

Version 2.0.0-alpha.12

  • Added ability to accept Overrides as second parameter to the deploy function.

Version 2.0.0-alpha.11

  • Initially, the fully qualified name is used to retrieve a contract from the Transaction Storage.
  • If the fully qualified name is absent, the recovery process falls back to using the ContractFieldsToSave derived from the contract.
  • Should the name be located, the ContractFieldsToSave is disregarded and is not used as a key within the Transaction Storage.

Version 2.0.0-alpha.2

  • Library linking fully relies on the hardhat artifacts.

Version 2.0.0-alpha.1

This release represents a major update to our plugin. We have completely rebuilt the core logic from scratch, now using ethersV6. Additionally, we have conducted a comprehensive code walkthrough, addressing and resolving bugs, as well as introducing new features.

Breaking changes

  • Removed the logger from migrations. Logging functionality is now fully integrated within the plugin.
  • Restructured the arguments passed to the deploy function.
  • Transitioned to using the hardhat-verify plugin for contract verification.

Deployer

  • Added support for EthersV5, EthersV6, and TruffleV5 through Adapters.
  • Introduced types support for EthersV5 and EthersV6 only, including constructor arguments validation.
  • Implemented a library linking during contract deployment.
  • Enhanced reporting during contract deployment.
  • Enabled recoverability of contract deployments.
  • Improved error reporting during contract deployment.
  • Added special user storage between deployments.

Verifier

  • Utilized the hardhat-verify plugin for contract verification.
  • Added three types of verification: "immediately," "at-the-end," and "none."
  • Introduced Verification processor and Verification Storage to enable verification of all deployed contracts at the end of the migration.
  • Implemented verification error handling.
  • Utilized Reporter to override the default 'hardhat-verify' logging.

New tools

Reporter

Centralizes all console logging.

Storage

A module that stores necessary data for the migration process in a JSON file. The default path is the artifacts/build-info folder.

...