如何在Hardhat中测试智能合约时获得特定数量的签名者



我正在Hardhat中开发我的智能合约,并在RSK Testnet上进行测试。要创建签名者帐户,我正在使用助记符种子短语以及以下安全帽配置:​

require('@nomicfoundation/hardhat-toolbox');
const { mnemonic } = require('./.secret.json');
​
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: '0.8.16',
networks: {
hardhat: {},
rsktestnet: {
chainId: 31,
url: 'https://public-node.testnet.rsk.co/',
accounts: { // <-- here
mnemonic,
path: "m/44'/60'/0'/0",
},
},
},
// ...
};

​在我的测试中,我通常使用ethers.js辅助函数要在我的测试中获得一组签名者:​

const signers = await hre.ethers.getSigners();

​然而,此函数返回20个签名者钱包。有没有一种方法可以获得特定数量的钱包,如果我不想要这个默认金额?

您可以使用Wallet.fromMnemonic使用ethers.js中的函数来完成此操作。

在CCD_ 3内,或导入CCD_ 4变量的任何位置,您可以这样调用它:hre.ethers.Wallet.fromMnemonic(mnemonic, derivationPath?, wordList?)

此功能用于生成单个钱包。函数的第二个参数是BIP-32派生路径。由于您在配置中使用的是CCD_ 6,则默认情况下该函数将附加CCD_ 7,导致CCD_ 8生成第一钱包。

如果你想生成另一个,您可以指定m/44'/60'/0'/0/1(附带/1(。

为了生成特定数量的钱包,简单地在循环中执行以上操作,在每次迭代中更改派生路径中的最终索引。

例如,以下函数将获得10:

function getSigners(amount = 40) {
// getting seed phrase and derivation path from the hardhat config
const { mnemonic, path } = hre.network.config.accounts
return [...Array(amount).keys()].map((i) =>
hre.ethers.Wallet.fromMnemonic(mnemonic, `${path}/${i}`)
.connect(hre.ethers.provider),
)
}

最新更新