web3.eth.getAccounts 不适用于 infura

Posted

技术标签:

【中文标题】web3.eth.getAccounts 不适用于 infura【英文标题】:web3.eth.getAccounts not working with infura 【发布时间】:2019-07-19 23:59:49 【问题描述】:

PS:我正在使用 web3 beta-37(因为每个版本都有自己的问题) 部署函数中 web3.eth.getAccounts 行下的任何内容都不起作用。 当我运行代码时,它什么也没有显示! 代码如下:

const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const interface , bytecode = require('./compile');

const provider = new HDWalletProvider(mnemonic,
'https://rinkeby.infura.io/v3/my_project_id');

const web3 = new Web3(provider);

const deploy = async() => 
    const accounts = await web3.eth.getAccounts();
    console.log('Attempting to deploy from account', accounts[0]);
    const result = await new web3.eth.Contract(JSON.parse(interface))
                             .deploy(data: bytecode, arguments: ['Hi There!'])
                             .send('from': accounts[0], 'gas': '1000000');

    console.log('Contract deployed to: ', result.options.address);
;
deploy();

另外,使用 ganache-cli 时在 mocha 中测试它会显示错误

const assert = require('assert');
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const bytecode , interface = require('../compile');

const provider = new HDWalletProvider(mnemonic,
'https://rinkeby.infura.io/v3/project_id');



let accounts;

beforeEach(async () => 
  //Get a list of all accounts
  accounts = await web3.eth.getAccounts();

);

describe('Inbox', () => 
  it('address', () => 
    assert.ok(accounts);
  )

以下是不同版本的结果: beta-46:无法读取未定义的属性映射() stackexchange 上的一个答案是使用 beta-36 来解决这个问题

beta-36 和 beta-37:getAccounts() 语句执行后没有任何内容,空白屏幕。

beta-26:core.addProviders 不是函数

【问题讨论】:

代码对我来说似乎很好。我不应该这么说,但您实际上在 Infura 链接中没有my_project_id,对吧?除此之外,它不起作用似乎很奇怪?你使用什么版本的web3?您能否验证提供程序是否设置正确(可能通过调试)? @nikosfotiadis on console.log(provider) 它向我展示了一个带有 10 个地址数组的大对象(一个地址)。所以我猜提供者设置正确,没有不使用 my_project_id。 web3 版本也是 beta-37。 您能分享您的compile.js 文件吗? Attempting to deploy from account 这一行是否记录了控制台? @IftifarTaz 很好,我确定 ....我已经在 mocha 中运行了测试...这件事与 ganache 完美配合...而且不...在const accounts = await web3.eth.getAccounts(); 获得控制台之后什么都没有记录 【参考方案1】:

我也遇到了同样的问题。

尝试从 infura url 中删除“/v3”部分:

const provider = new HDWalletProvider(mnemonic,
'https://rinkeby.infura.io/my_project_id');

希望这会有所帮助。

【讨论】:

它有效 :) 谢谢人!我无法告诉你我尝试了多少事情来让这件事发挥作用。我什至在 web3 Github 上发布了问题,我已经卡了 3 天了 XD 很高兴为您提供帮助!

以上是关于web3.eth.getAccounts 不适用于 infura的主要内容,如果未能解决你的问题,请参考以下文章

[Contract] web3.eth.getAccounts, web3.eth.getCoinbase 使用场景区别

让 accounts = web3.eth.getAccounts() 显示未定义和 app.vote(1, from: accounts[1] ) 显示错误

如何使用 1.2.x 版本从 web3 获取特定帐户?

获取 web3 元掩码中的注册资产

WEB3 |使用公共地址导入私钥

以太坊节点中的 web3(然后是属性)