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