To obtain a signer object from a named account address in a Hardhat project with the hardhat-deploy
plugin, you can use the ethers.getSigner
method, which is designed to work with the addresses of the accounts that Hardhat manages. Here's how you can do it:
// First, retrieve the named accounts using the hardhat-deploy plugin
const namedAccounts = await getNamedAccounts();
// Now, use ethers to get the signer for the 'deployer' named account
// namedAccounts.deployer returns the address for the deployer named account
const deployer = await ethers.getSigner(namedAccounts.deployer);
// You can now use the signer to interact with your contracts
await contract.connect(deployer).method();
In this example, namedAccounts.deployer
provides the address of the deployer account, and ethers.getSigner
returns the signer object associated with that address. This works because Hardhat knows the private keys of the named accounts for the Hardhat network environment. Remember that this approach is suitable for local development and testing purposes where Hardhat manages the private keys of the accounts.
For live networks or addresses not managed by Hardhat, you would need the private keys to create a new ethers.Wallet
instance connected to the appropriate provider, or in a hardhat local or forked node you can use hardhat_impersonateAccount to get the signer for an account you don't control to mock control on the hardhat node.
This can be generalized to all namedAccounts
as follows:
// In a shared utils file define the following
async function getNamedSigners() {
const namedAccounts = await getNamedAccounts();
const signers: {[name: string]: SignerWithAddress} = {};
for (const [name, address] of Object.entries(namedAccounts)) {
signers[name] = await ethers.getSigner(address);
}
return signers;
};
// strongly type your namedAccounts
export type ProjectSigners = {
owner: SignerWithAddress,
addr1: SignerWithAddress,
addr2: SignerWithAddress,
};
// the following function can be imported into any script to get strongly typed namedAccounts
export async function getProjectSigners(): Promise<ProjectSigners> {
return (await getNamedSigners()) as ProjectSigners
};
Now in your hardhat.config.ts
add the following:
type NamedAccounts = {
[K in keyof ProjectSigners]: number;
};
const namedAccounts: NamedAccounts = {
owner: 0,
addr1: 1,
addr2: 2,
};
const config: HardhatUserConfig = {
defaultNetwork: "hardhat",
namedAccounts,
/// ... rest of config
}