How to fund a account with ETH on a local fork or local node in hardhat?

Expert

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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 require nomicfoundation/hardhat-toolbox, which is a set of tools and plugins useful for development.

  5. 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 the networks property to define a new network named hardhat that includes the forking 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;
});
  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 uses npx hardhat node to fork the mainnet, allowing you to interact with the pre-existing state and contracts of the Ethereum network. Replace yourAlchemyApiKey with your actual API key and optionally specify a block number to fork from.

  2. 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.

  3. 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 with npx 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;
});
  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);
  });