web3.eth.accounts 返回了一个函数

3
我是一名有用的助手,可以为您翻译文本。

我正在遵循这里的教程,使用testrpc和web3.js。安装了ethereumjs-testrpc和web3js包之后,启动testrpc,它提供了10个可用帐户及其私钥。

web3版本为1.0.0-beta.18,ethereumjs-testrpc版本为4.1.1。

运行以下代码时

Web3 = require('web3');
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.accounts

我得到了与教程中显示的10个帐户不同的输出结果。出了什么问题?
Accounts {
  currentProvider: [Getter/Setter],
  _requestManager:
   RequestManager {
     provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
     providers:
      { WebsocketProvider: [Function: WebsocketProvider],
        HttpProvider: [Function: HttpProvider],
        IpcProvider: [Function: IpcProvider] },
     subscriptions: {} },
  givenProvider: null,
  providers:
   { WebsocketProvider: [Function: WebsocketProvider],
     HttpProvider: [Function: HttpProvider],
     IpcProvider: [Function: IpcProvider] },
  _provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
  setProvider: [Function],
  _ethereumCall:
   { getId:
      { [Function: send]
        method: [Object],
        request: [Function: bound ],
        call: 'net_version' },
     getGasPrice:
      { [Function: send]
        method: [Object],
        request: [Function: bound ],
        call: 'eth_gasPrice' },
     getTransactionCount:
      { [Function: send]
        method: [Object],
        request: [Function: bound ],
        call: 'eth_getTransactionCount' } },
  wallet:
   Wallet {
     length: 0,
     _accounts: [Circular],
     defaultKeyName: 'web3js_wallet' } }

在教程的后面,当部署合约时需要使用web3.eth.accounts

deployedContract = VotingContract.new(['Rama','Nick','Jose'],
    {data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
2个回答

7
那篇教程是在web3.js v1发布之前写的。在v1中,API发生了显著变化,包括`eth.accounts`。您可以将其固定在旧版本的web3.js上,如`0.19.0`,或者在新的v1文档中找到等效的方法。
现在,检索帐户是异步完成的,就像新API中的许多其他调用一样。因此,您可以使用回调或承诺来调用它。将帐户列表打印到控制台的代码如下:
web3.eth.getAccounts(console.log);
// or
web3.eth.getAccounts().then(console.log);

来自web3.eth.getAccounts v1文档

具体地,重写您在结尾引用的部分:

web3.eth.getAccounts()
.then(function (accounts) {
  return VotingContract.new(['Rama','Nick','Jose'],
    {data: byteCode, from: accounts[0], gas: 4700000});
})
.then(function (deployedContract) {
  // whatever you want to do with deployedContract...
})

谢谢,我也很难找到如何更新这段代码 deployedContract = VotingContract.new(['Rama','Nick','Jose'], {data: byteCode, from: web3.eth.accounts[0], gas: 4700000}),因为 web3.eth.getAccounts() 现在使用 Promises。 - Nyxynyx
好的,已经在答案中添加了一个部分。 - carver

0
如果web3.eth.accounts未显示预期结果,则按以下两个简单步骤操作(在Truffle控制台内):
  1. web3.eth.getAccounts().then(function(acc){ accounts = acc })

  2. accounts

这就是全部... 如果您想要特定的帐户,则使用accounts [0/1/2...9]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接