Blockchain 使用Infura提供程序时,web3.eth.getAccounts()返回空数组。为什么?

Blockchain 使用Infura提供程序时,web3.eth.getAccounts()返回空数组。为什么?,blockchain,ethereum,web3,web3js,Blockchain,Ethereum,Web3,Web3js,我试图使用infuraapi制作以太坊web应用程序。首先,我编译了一份solidity合同,然后在rinkeby网络上使用infura api进行部署。这是我的部署脚本,它似乎正在成功运行 const HDWalletProvider = require("truffle-hdwallet-provider"); const Web3 = require('Web3'); const compileFactory = require('./build/CampaignFactory.json'

我试图使用infuraapi制作以太坊web应用程序。首先,我编译了一份solidity合同,然后在rinkeby网络上使用infura api进行部署。这是我的部署脚本,它似乎正在成功运行

const HDWalletProvider = require("truffle-hdwallet-provider");
const Web3 = require('Web3');
const compileFactory = require('./build/CampaignFactory.json');

const provider = new HDWalletProvider(
    "MY_SECRET_MNEMONIC",
    "https://rinkeby.infura.io/v3/363ea9633bcb40bc8a857d908ee27094"
);
const web3 = new Web3(provider);
console.log("provider info: " + provider);
const deploy = async () => {
    const accounts = await web3.eth.getAccounts();
    console.log("account used: " + accounts[0]);
    result = await new web3.eth.Contract(JSON.parse(compileFactory.interface))
        .deploy({data: "0x"+compileFactory.bytecode})
        .send({from: accounts[0]});
    console.log("deployed to address: " + result.options.address);
};
deploy();
然后,我创建了另一个脚本web3.js,它使用Infura api创建了一个web3提供程序:

import  Web3 from 'web3';

let web3;

if (typeof window !== 'undefined' && typeof window.web3!=='undefined') {
    // we are in the browser and metamask is running.
    web3 = new Web3(window.web3.currentProvider);
    console.log("using metamask");
}
else {
    // we are in server OR user without metamask.
    const provider = new Web3.providers.HttpProvider(
        "https://rinkeby.infura.io/v3/363ea9633bcb40bc8a857d908ee27094"
    );
    web3 = new Web3(provider);
    console.log("using infura");
}

export default web3;
但当我在某处导入这个web3.js文件,然后尝试使用“web3”对象时,它会返回空的帐户数组。例如:

import web3 from '../../ethereum/web3';
...
const accounts = await web3.eth.getAccounts();
console.log("Account list: "+accounts); // returns empty array.

但理想情况下,它应该返回与我的助记符关联的帐户列表。有什么问题

一个简单的解决方案是在第二个脚本中使用
HDWalletProvider
,而不是
HttpProvider

你想对第二个脚本做什么?我怀疑第二个脚本是您希望使用DApp部署的,因此,包括助记符,有一个很好的方法可以将您所有的以太提供给第一个知道如何“查看源代码”的用户


如果是这样,在第一个脚本中,使用以下命令显示与助记符关联的地址:
provider.getAddresses()
,然后将这些地址硬编码到第二个脚本中,供以后使用。当然,您将无法在第二个脚本中签署任何事务,但至少您可以读取与这些地址相关联的数据。

Put
wait window.ethereum.enable()
before
web3.eth.getAccounts()

或者使用
requestAccounts()
而不是
getAccounts()


什么助记符?代码中没有任何内容使用助记符生成私钥。Infura不知道任何人的私钥,因此您需要有密钥客户端来签署事务。啊,我看到您的部署脚本确实使用了一个接受助记符的提供程序。但是你没有在失败的代码中使用它。你需要。我到底需要在哪里使用助记符?在第一个脚本中,我已经用过一次在区块链上部署合同。您能告诉我需要更正的确切位置和代码吗?每个交易都需要使用您的私钥签名。这包括部署契约的事务以及用于与契约交互的每个事务。你需要在任何你想使用私钥的地方使用相同种类的
HDWalletProvider
。你能详细说明一下吗?也许用某种代码来回答?谢谢。如果我想在客户端代码中初始化提供程序,我认为我们不应该使用助记符HDWallletProvider,因为这是一个秘密。这是真的吗?
await web3.eth.requestAccounts();