如何在Hardhat测试中使用ethers.js生成带有ETH的任意钱包?
给Hardhat/Waffle中大量随机钱包分配ETH的最简高效方案
在本地Hardhat测试环境里,给数百个随机生成的钱包快速充ETH,有两种核心方案,我推荐优先用第二种,效率直接拉满:
方案1:用Hardhat默认测试账户批量转账(贴近真实链逻辑)
Hardhat启动本地节点时,默认会创建10个各持有10000 ETH的测试账户,你可以直接用这些账户给随机钱包批量转账。
代码示例:
const { ethers } = require("hardhat"); describe("Your Test Suite", function () { let testAccounts; const randomWallets = []; const NUM_WALLETS = 200; // 你需要的随机钱包数量 before(async function () { // 获取Hardhat默认测试账户 testAccounts = await ethers.getSigners(); // 批量生成随机钱包 for (let i = 0; i < NUM_WALLETS; i++) { randomWallets.push(ethers.Wallet.createRandom().connect(ethers.provider)); } // 用第一个测试账户给所有随机钱包转ETH const transferTasks = randomWallets.map(async (wallet) => { await testAccounts[0].sendTransaction({ to: wallet.address, value: ethers.utils.parseEther("1") // 每个钱包转1 ETH,按需调整 }); }); // 等待所有转账完成 await Promise.all(transferTasks); }); // 你的测试用例写在这里... });
注意事项:
- 如果需要更多ETH,可以在
hardhat.config.js里修改默认账户的初始余额:module.exports = { networks: { hardhat: { accounts: { count: 10, initialBalance: "1000000000000000000000000" // 每个账户1000000 ETH } } } }; - 缺点:转账需要发起交易并等待确认,数百个钱包的话速度会慢一些。
方案2:直接调用Hardhat节点API设置余额(最高效,本地链专属)
Hardhat本地节点提供了hardhat_setBalance RPC方法,可以直接修改任意地址的ETH余额,不需要发起交易,瞬间完成,完全适配大量钱包的场景。
代码示例:
const { ethers } = require("hardhat"); describe("Your Test Suite", function () { const randomWallets = []; const NUM_WALLETS = 200; const WALLET_BALANCE = ethers.utils.parseEther("10"); // 每个钱包设10 ETH before(async function () { // 批量生成随机钱包 for (let i = 0; i < NUM_WALLETS; i++) { randomWallets.push(ethers.Wallet.createRandom().connect(ethers.provider)); } // 批量设置余额:调用hardhat_setBalance const balanceTasks = randomWallets.map(async (wallet) => { await ethers.provider.send("hardhat_setBalance", [ wallet.address, WALLET_BALANCE.toHexString() // 余额需要转成十六进制字符串 ]); }); await Promise.all(balanceTasks); // 可选:验证第一个钱包的余额是否设置成功 const firstWalletBalance = await randomWallets[0].getBalance(); console.log("First wallet balance:", ethers.utils.formatEther(firstWalletBalance)); }); // 你的测试用例写在这里... });
为什么这是最优解?
- 速度极快:不需要处理交易签名、打包、确认,直接修改链上状态,几百个钱包几秒内就能搞定。
- 无ETH限制:不需要依赖测试账户的余额,想设多少就设多少。
- 代码更简洁:不用处理转账的错误场景(比如测试账户余额不足)。
总结
- 如果你的测试需要模拟真实链的转账逻辑(比如测试Gas费、交易失败场景),选方案1;
- 如果只需要让随机钱包有足够ETH发起交易/调用合约,方案2绝对是首选,效率最高,代码也更省心。
内容的提问来源于stack exchange,提问作者fullyallocated
相关产品推荐
相关产品推荐

