我在此处遵循一个教程,该教程将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})
该教程是在Web3.js V1出来之前编写的。API在V1中发生了很大变化,包括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...
})
如果web3.eth.accounts
未显示预期结果然后,按照这两个简单的步骤(在松露控制台内)
-
web3.eth.getAccounts().then(function(acc){ accounts = acc })
-
accounts
那是...如果您想要特定的帐户,则accounts[0/1/2...9]