First, I'm sort of new to hardhat testing. I'm testing on a forked network and want to try to impersonate an account with an ERC20 token. Here is my code:
import { ethers } from "hardhat";
import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";
import { assert } from "chai";
import myContractArtifact from "../artifacts/contracts/MyContract.sol/myContractArtifact.json";
describe("MyContract", function () {
async function deployContractAndSetVariables() {
const [owner] = await ethers.getSigners();
const impersonatedSigner = await ethers.getImpersonatedSigner(<addressOfImpersonatedAccount>);
const contract = await ethers.deployContract("MyContract", [<constructorArgs>]);
const myContract = await ethers.getContractAtFromArtifact(myContractArtifact, contract.target.toString(), impersonatedSigner);
return { myContract, owner, impersonatedSigner };
}
it("Should...", async function () {
const { myContract, owner } = await loadFixture(deployContractAndSetVariables);
// tests
});
});
I'm using a function I never see in examples - "ethers.getContractAtFromArtifact". Is this the best way to instantiate a contract using a impersonated signer?
I think ethers allows you to change Signer with myContract.connect(<newSigner>)
, but this creates Typescript errors. If you instantiate contract using standard method (new ethers.Contract(abi, address, <newSigner>)
), you require the ABI, which you cannot import from the artifacts folder in Typescript (instead, you need to copy the json to a .ts file and export, which is a road I don't want to go down).
So is "getContractAtFromArtifact" the best way? I just haven't seen it in any examples.