Native State Persistence
The Hardhat Network does not persist state to disk by default. However, you can maintain a consistent environment across sessions using the --save-state and --load-state flags. These flags allow you to export the entire blockchain state—including deployed contracts, account balances, and chain data—into a JSON file.
Implementation Steps
- Save the current state: Start your node with the save flag to create a snapshot of the current memory state upon termination.
npx hardhat node --save-state
- Restore the state: On subsequent launches, use the load flag to initialize the node with the previously saved state.
npx hardhat node --load-state
By default, Hardhat uses a file named hardhat-state.json in the project root. If this file is present during a --load-state command, the node will replace its initial empty state with the data contained in the JSON file.
Alternative Approach: Scripted Initialization
If native state flags are unavailable (e.g., in legacy versions) or if you require a selective state rather than a full snapshot, the recommended approach is Idempotent Deployment Scripts. Instead of persisting the blockchain state, you persist the instructions to reach that state.
- Deployment Tracking: Save deployed contract addresses to a local JSON file (e.g.,
deployments.json).
- Setup Scripts: Create a TypeScript/JavaScript script that checks for existing addresses and only deploys missing contracts or resets specific account balances using
hardhat_setBalance.
- Execution: Run this setup script immediately after starting a fresh
npx hardhat node instance.
Technical Constraints and Assumptions
This resolution assumes you are using a modern version of Hardhat (v2.x) that supports state flags. Please note the following limitations:
- Version Sensitivity: State files are version-specific. A state saved in one Hardhat version may not be compatible with another.
- Account Keys: The state file captures blockchain data (balances, storage), but it does not persist the private keys of the default local accounts. These are regenerated based on the node's seed.
- Volatility: If the node process crashes unexpectedly, the
--save-state buffer may not flush to disk, potentially resulting in a corrupted or outdated JSON file.
Verification Method
To verify persistence is working: start the node with --save-state, deploy a contract, and exit. Restart with --load-state and use a script to call a view function on the previously deployed contract address. If the call returns the expected value without a redeployment, the state was successfully restored.
Diagnostic Detail: Are you using a custom hardhat.config.js network configuration for the local node, or are you relying on the default npx hardhat node CLI behavior?