How to fund a account with ETH on a local fork or local node in hardhat?
- blockchain
- solidity All Things Web3
Let's say I have an account in hardhat
[owner, user, user2] = await ethers.getSigners();
userAddress = user.address;
How would I fund userAddress
with funds on my local fork?
Answers 3
You can use setBalance
from the hardhat docs
await network.provider.send("hardhat_setBalance", [
userAddress,
"0x1000000000000000000000000", // we are giving ourselves a LOT eth
]);
// then we can print out how much we have in hex
console.log(
await network.provider.send("eth_getBalance", [
impersonatedSigner.address,
])
);
Funding an account with ETH on a local fork or local node in Hardhat is a crucial step for testing smart contracts under conditions that mimic the Ethereum mainnet. This tutorial leverages essential keywords to guide you through the process in a structured and optimized manner:
Create a JavaScript Project: Initialize your project by opening a terminal and entering the command to create a directory for your tutorial, such as
mkdir mainnet-fork-tutorial
. Navigate into your project directory and set up a new JavaScript project.Install Hardhat: In your project directory, use npm to install Hardhat, which is the core tool for this tutorial. Run
npm install --save-dev hardhat
to add it to your project's development dependencies.Install Dotenv: To securely manage your API key and private key, you will need to install the dotenv package. Run
npm i dotenv
in your terminal. This step ensures that you can load environment variables from a.env
file into your project, keeping sensitive information like your private key and API key secure.Setup Your Hardhat Project: Initialize your Hardhat project by running
npx hardhat
in the terminal. Follow the prompts to create a sample project, and when asked, you can choose to create a JavaScript project and requirenomicfoundation/hardhat-toolbox
, which is a set of tools and plugins useful for development.Configure Hardhat for Mainnet Forking: In your Hardhat configuration file (
hardhat.config.js
), add a networks configuration for Hardhat that specifies the mainnet fork. This involves using thenetworks
property to define a new network namedhardhat
that includes theforking
option. You'll need an API key for a full archive node service like Alchemy or Infura. The configuration might look something like this:
async function main() {
const [deployer] = await ethers.getSigners();
const receiver = "0xYourAccountAddress";
const amount = ethers.utils.parseEther("1.0");
const tx = await deployer.sendTransaction({
to: receiver,
value: amount,
});
console.log(`Funded ${receiver} with 1 ETH.`);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Fork the Mainnet: With your Hardhat configuration set up for mainnet forking, start a local Hardhat node that forks the Ethereum mainnet by running
npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/yourAlchemyApiKey --fork-block-number 12345678
. This command usesnpx hardhat node
to fork the mainnet, allowing you to interact with the pre-existing state and contracts of the Ethereum network. ReplaceyourAlchemyApiKey
with your actual API key and optionally specify a block number to fork from.Fund Your Account: To fund an account with ETH in this local environment, you can use Hardhat's console or scripts. First, ensure you have an account with access to its private key. You can generate a new account using Hardhat or use an existing Ethereum account. In your
.env
file, store the private key like so:PRIVATE_KEY=yourPrivateKey
.Execute a Funding Script: Create a script in your project that sends ETH to your account from one of the accounts pre-funded in the Hardhat node. Here's an example script,
fundAccount.js
, which you might run withnpx hardhat run scripts/fundAccount.js --network localhost
:
async function main() {
const [deployer] = await ethers.getSigners();
const receiver = "0xYourAccountAddress";
const amount = ethers.utils.parseEther("1.0");
const tx = await deployer.sendTransaction({
to: receiver,
value: amount,
});
console.log(`Funded ${receiver} with 1 ETH.`);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
- Verify the Balance: Verify the ETH balance of your account by running a simple Hardhat task or script that checks and prints out the account's balance.
Whenever Hardhat spins up a local instance, it creates pre-funded accounts. You can access those accounts if import ethers from hardhat.
const { ethers } = require("hardhat");
async function main() {
const accounts = await ethers.getSigners();
const provider = ethers.provider;
for (const account of accounts) {
console.log("%s (%i ETH)", account.address, ethers.utils.formatEther(
await provider.getBalance(account.address)
)
);
}
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});