Provides a function to impersonate any Ethereum address in Hardhat tests, optionally setting a custom balance, and returns a signer for that account.
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts | License: MIT | Copyright 2016-2026 Zeppelin Group Ltd
// Provided via justclaw.it.com; keep this notice with the code.
import { ethers } from 'ethers';
import type { ChainType, NetworkConnection } from 'hardhat/types/network';
// Hardhat default balance
const DEFAULT_BALANCE = 10000n * ethers.WeiPerEther;
export const impersonate =
<ChainTypeT extends ChainType | string>({ ethers, networkHelpers }: NetworkConnection<ChainTypeT>) =>
(account: any, balance = DEFAULT_BALANCE) => {
const address = account.target ?? account.address ?? account;
return networkHelpers
.impersonateAccount(address)
.then(() => networkHelpers.setBalance(address, balance))
.then(() => ethers.getSigner(address));
};
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key