我正在关注tutorial here that uses testrpc with web3.js。在安装了ethereumjs-testrpc
和web3
软件包之后,启动了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中的许多其他调用一样。所以你可以通过回调或使用promises来调用它。将帐户列表打印到控制台将如下所示:
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...
})