Skip to content

Instantly share code, notes, and snippets.

@ydm
Last active December 8, 2024 12:40
Show Gist options
  • Save ydm/69d110c87ffdb66bc5dab5a0bf5948f1 to your computer and use it in GitHub Desktop.
Save ydm/69d110c87ffdb66bc5dab5a0bf5948f1 to your computer and use it in GitHub Desktop.
// ethers.js v5
import { ethers, network } from "hardhat";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
async function impersonate(
who: string,
f: (signer: SignerWithAddress) => Promise<void>
): Promise<void> {
await network.provider.request({
method: "hardhat_impersonateAccount",
params: [who],
});
const signer = await ethers.getSigner(who);
try {
await f(signer);
} finally {
network.provider.request({
method: "hardhat_stopImpersonatingAccount",
params: [who],
});
}
}
@ydm
Copy link
Author

ydm commented Sep 8, 2023

// ethers.js v6

import ethers from "ethers";
import hre, { network } from "hardhat";

async function impersonate<T>(
    who: string,
    f: (signer: ethers.Signer) => Promise<T>
): Promise<T | undefined> {
    if (hre.network.name === "hardhat") {
        const norm: string = hre.ethers.getAddress(who);
        await network.provider.request({
            method: "hardhat_impersonateAccount",
            params: [norm],
        });
        const signer = await hre.ethers.getSigner(who);
        try {
            return await f(signer);
        } finally {
            network.provider.request({
                method: "hardhat_stopImpersonatingAccount",
                params: [norm],
            });
        }
    }
}

@ydm
Copy link
Author

ydm commented Dec 30, 2023

// JavaScript

const { ethers, network } = require('hardhat');

async function impersonate(who, f) {
  await network.provider.request({
    method: 'hardhat_impersonateAccount',
    params: [who],
  });
  const signer = await ethers.getSigner(who);
  try {
    await f(signer);
  } finally {
    network.provider.request({
      method: 'hardhat_stopImpersonatingAccount',
      params: [who],
    });
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment