WTFAcademy / WTF-Ethers

我最近在重新学ethers.js,巩固一下细节,也写一个“WTF Ethers.js极简入门”,供小白们使用,每周更新1-3讲。Now supports English! 官网: https://wtf.academy
https://wtf.academy
Other
3.03k stars 489 forks source link

在14批量生成钱包章节中 base地址问题 #134

Closed yaoji-cell closed 4 months ago

yaoji-cell commented 7 months ago
const numWallet = 20
// 派生路径:m / purpose' / coin_type' / account' / change / address_index
// 我们只需要切换最后一位address_index,就可以从hdNode派生出新钱包
let basePath = "m/44'/60'/0'/0";
let wallets = [];
for (let i = 0; i < numWallet; i++) {
    let hdNodeNew = hdNode.derivePath(basePath + "/" + i);
    let walletNew = new ethers.Wallet(hdNodeNew.privateKey);
    console.log(`第${i+1}个钱包地址: ${walletNew.address}`)
    wallets.push(walletNew);
}

这里提示一下报错,路径找了很久都是这个路径

TypeError: cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth 5 (argument="path", value="m/44'/60'/0'/0/0", code=INVALID_ARGUMENT, version=6.11.1)
    at makeError (d:\code\mev-bot\node_modules\ethers\lib.commonjs\utils\errors.js:122:21)
    at assert (d:\code\mev-bot\node_modules\ethers\lib.commonjs\utils\errors.js:149:15)
    at assertArgument (d:\code\mev-bot\node_modules\ethers\lib.commonjs\utils\errors.js:161:5)
    at derivePath (d:\code\mev-bot\node_modules\ethers\lib.commonjs\wallet\hdwallet.js:68:39)
    at HDNodeWallet.derivePath (d:\code\mev-bot\node_modules\ethers\lib.commonjs\wallet\hdwallet.js:253:16)
    at main (d:\code\mev-bot\练习操作\批量钱包.js:20:32)
    at Object.<anonymous> (d:\code\mev-bot\练习操作\批量钱包.js:44:1)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32) {
  code: 'INVALID_ARGUMENT',
  argument: 'path',
  value: "m/44'/60'/0'/0/0",
  shortMessage: 'cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth 5'
}

但是在 ethers v6版本 derivePath函数中写了这样一个判断

    if (components[0] === "m") {
        assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${ node.depth }`, "path", path);
        components.shift();
    }

请问这是为什么呢,我是新手刚开始学习,不太懂这个

Sean329 commented 6 months ago

等这个PR merge了之后再看教程新的代码,会解决你的疑问。 https://github.com/WTFAcademy/WTF-Ethers/pull/141