3

In hardhat I'd like to get the privateKey from a signer, the privateKeys are initialised in the hardhat.config networks.network.accounts.

import { ethers } from "hardhat";
import { Signer } from "ethers";

const accounts = await ethers.getSigners();
const account0: Signer = accounts[0];

I don't see any attribute/method on the Signer instance to get the privateKey.

2 Answers 2

4

You can get the private keys from the network config (localhost, mainnet, etc):

import { config } from "hardhat";

console.log('Accounts from config:', config.networks.mainnet.accounts);

In case you want to get the private keys for hardhat accounts:

const accounts = config.networks.hardhat.accounts;
const index = 0; // first wallet, increment for next wallets
const wallet1 = ethers.Wallet.fromMnemonic(accounts.mnemonic, accounts.path + `/${index}`);

const privateKey1 = wallet1.privateKey
...

Here is an example, how I use this:

https://github.com/0xweb-org/dequanto/blob/8bab2114875b055f5f6ea361951d0d7083f3259c/src/hardhat/HardhatProvider.ts#L41

3
  • Thanks for this, however the default hardhat accounts i.e. config.networks.hardhat.accounts is an HD Wallet config, is there a simple way to get all the private keys from that config? { initialIndex: 0, count: 20, path: "m/44'/60'/0'/0", passphrase: '', mnemonic: 'test test test test test test test test test test test junk', accountsBalance: '10000000000000000000000' }
    – MShakeG
    Commented Oct 12, 2022 at 21:38
  • See the updated answer. This was smth you want?
    – tenbits
    Commented Oct 12, 2022 at 21:53
  • 1
    Yeah, that's exactly it, though I got the private keys by simple starting the hardhat node which logs all the private keys for all 20 accounts.
    – MShakeG
    Commented Oct 14, 2022 at 20:59
0

Well, think on connecting ether.js with some wallet. The private key wouldn’t be passed to the library because than it could be stolen. The library issues a request to the wallet to sign the transaction.

So the private key isn’t stored inside Signer.

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.