0

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.

1 Answer 1

0

You’ve to deploy the contract using the corresponding contract factory instance, that you can fetch using getContractFactory. Then, you can use .connect on the deployed contract instance, like:

const myContract_Factory = await ethers.getContractFactory("MyContract");
const myContract = await myContract_Factory.deploy([<constructorArgs>]);
await myContract.connect(impersonatedSigner).contractFunction([<functionArgs>]);

For better understanding, you can refer to this example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.