0

This question already has an answer here:

Ganache (v1.2.3) provides a list of 10 accounts.

They can be easily selected by selecting web3.eth.getAccounts();.

However web3.eth.accounts[0] returns undefined as shown below. Not sure how to select just one account here.

enter image description here

marked as duplicate by goodvibration, Ismael, Richard Horrocks, Briomkez, flygoing Feb 4 at 15:28

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

The new version of Truffle v5 uses web3 v1.0 which has web3.eth.accounts as a module.

The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data.

Another change in web3 v1 is that most functions are async and return a promise. To obtain a value you can await for it.

truffle(develop)> (await web3.eth.getAccounts())[0]
'0x5f461C987879517f04a5Ae88A5B26CB6E9DB63bc'
truffle(develop)> addr=(await web3.eth.getAccounts())[0]
undefined
truffle(develop)> addr
'0x5f461C987879517f04a5Ae88A5B26CB6E9DB63bc'
truffle(develop)> 
  • 1
    The code above worked as described. – monkrus Feb 4 at 21:05
2

If it's Web3 1.x, it's a promise. Try:

> var accounts;
> web3.eth.getAccounts().then(function(response) { accounts = response; console.log(accounts[0]; });

Hope it helps.

  • If it's Web3 0.x then web3.eth.accounts[0] should actually work as is. – goodvibration Feb 4 at 5:25
  • @RobHitchensB9lab I`m getting a "TypeError: Cannot read property '0' of undefined". – monkrus Feb 4 at 18:12
  • Corrected a typo in line 2 accounts. – Rob Hitchens B9lab Feb 4 at 18:16
  • Corrected, still getting a "TypeError: Cannot read property '0' of null" – monkrus Feb 4 at 20:59
  • Hmmm ... try that. Edited. – Rob Hitchens B9lab Feb 4 at 21:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.