【问题标题】:How to import ethereum account in web3 if I know address and private key?如果我知道地址和私钥,如何在 web3 中导入以太坊帐户?
【发布时间】:2019-04-20 06:57:31
【问题描述】:

我启动 ganache-gui 并看到很多帐户,它们有私钥和助记词。然后我用 nodejs 和 web3 1.x.x 连接到这个测试网,所以我的 wallet.length 是 0。我想通过助记词从 ganache 导入所有钱包,或者更好地使用私钥导入一个地址。我可以这样做吗?我尝试了web3.eth.accounts.privateKeyToAccount(privateKey);,但返回了新帐户。它是如何工作的? Metamask 可以通过 privateKey 做到这一点。

【问题讨论】:

  • 所以,如果我理解正确,您想在您的代码中访问您的 ganache 帐户..对吗?
  • 对。我还想知道如何导入任何知道其私钥的帐户,就像 metamask 一样。
  • 如果它符合您的目的,您是否也可以为答案投票?谢谢
  • 抱歉,声望不足以支持投票。我是那里的新用户。

标签: node.js web3js


【解决方案1】:

要访问 ganache 帐户,您必须执行以下操作:

    const ganache = require('ganache-cli');
    const Web3 = require('web3');

   //ganache client running on port 7545
    var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));

    const getAccounts = async () =>{

   //To get all accounts
    let accounts = await web3.eth.getAccounts();

    //To get accounts with private key
    let account = await web3.eth.accounts.privateKeyToAccount('0x'+privateKey);
    //privateKey is the key that you get from Ganache client
    }

    getAccounts();

【讨论】:

  • 私钥应始终以 0x 开头。
猜你喜欢
  • 2018-07-01
  • 2018-09-22
  • 2022-10-22
  • 2018-06-27
  • 2023-04-07
  • 1970-01-01
  • 2022-06-18
  • 1970-01-01
  • 2022-09-23
相关资源
最近更新 更多