javascript - web3.eth.accounts 返回一个函数

标签 javascript ethereum solidity web3js

我正在关注tutorial here that uses testrpc with 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})

最佳答案

该教程是在 web3.js v1 发布之前编写的。 API 在 v1 中发生了显着变化,包括 eth.accounts。您可以固定到旧版本的 web3.js,例如 0.19.0,或者在新的 v1 docs 中找到等效的方法。 .

与新 API 中的许多其他调用一样,检索帐户现在是异步完成的。因此,您可以通过回调或使用 Promise 来调用它。将帐户列表打印到控制台如下所示:

web3.eth.getAccounts(console.log);
// or
web3.eth.getAccounts().then(console.log);

来自web3.eth.getAccounts v1 documentation

因此,专门重写您在最后引用的部分:

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...
})

关于javascript - web3.eth.accounts 返回一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144735/

相关文章:

ruby-on-rails - 您可以使用 Webpacker 直接在 Rails 6 应用程序中使用 Web3.js 吗?

ethereum - 限制 geth API RPC 方法的部分内容

ethereum - 您如何在Solidity中比较字符串?

JavaScript 处理程序

javascript - Cassette Add Individual Javascript Script Link Reference 内联

以太坊彩票智能合约满足以下条件

ethereum - 为什么我的以太坊交易花费比我预期多 21000 Gas?

javascript - Safari 中简单同位素示例的问题

javascript - 尝试找出如何使用 Knockout 中选择的值更新隐藏输入

node.js - 是什么导致 web3js 测试代码中出现 MaxListenersExceededWarning 警告