How to generate arbitrary wallet seeded with eth in hardhat tests using ethers.js?
Hardhat allows to seed a custom amount of prefunded addresses using the accounts
.count
config option of the built-in hardhat
network.
Example:
module.exports = {
networks: {
hardhat: {
accounts: {
count: 1000
}
}
}
}
Docs: https://hardhat.org/hardhat-network/reference/#config
The new ethers.Wallet.createRandom()
function only creates an account from a random private key in the context of the JS application, but it doesn't communicate with the provider (Hardhat in your case).
I think you'll probably want to use the hardhat network method hardhat_setBalance, the docs use an example like this:
await network.provider.send("hardhat_setBalance", [
"<ACCOUNT ADDRESS>",
"0x1000", # 4096 wei
]);
I'm not developing in javascript though, but I've been doing something similar in python using web3.py and eth-account with code like this:
from web3 import Web3
from eth_account import Account
chain = Web3(HTTPProvider("http://127.0.0.1:8545"))
acct = Account.create('<RANDOM VALUE>')
address = Web3.toChecksumAddress(acct.address)
print(chain.eth.get_balance(address)) # 0 wei
# add a balance of eth tokens to the address
chain.provider.make_request("hardhat_setBalance", [address, "0x1000"])
print(chain.eth.get_balance(address)) # 4096 wei