5

truffle(development)> web3.eth.accounts[0]

gives output as "undefined"

truffle(development)> web3.eth.accounts

instead of showing all accounts details gives the below output

Accounts {

currentProvider: [Getter/Setter],


_requestManager:

RequestManager {

 provider:

  HttpProvider {
    host: 'http://127.0.0.1:7545',

    httpAgent: [Agent],
    timeout: 0,

    headers: undefined,

    connected: true,

    send: [Function],

   ......blah...blah

but...

truffle(development)> web3.eth.getAccounts

is working. please help

  • 1
    If web3.eth.getAccounts is working, then why don't you simply use it??? As of web3.js v1, web3.eth.accounts is deprecated. – goodvibration Jan 27 at 8:23
  • I can use it but I am not able to choose any of the accounts specifically which I was able to do with 'web3.eth.accounts[0]" , please let me know the replacement for this? – Yash Shukla Jan 27 at 9:06
  • 1. You cannot use it, as it is undefined; you even specify it in your own question! 2. You've already found a replacement, and again - you even specify it in your own question! – goodvibration Jan 27 at 9:51
6

Use the code below to retrieve all the accounts

   var accounts = web3.eth.getAccounts();

Use this code to reference a single account

   var account0;
   web3.eth.getAccounts().then(function(result){
     account0 = result[0];
   })
5

from @goodvibration in the comments :

web3.eth.accounts is deprecated.

That is true. in the newer version of web3.js web3.eth.getAccounts returns a promise, so that is why doing :

var accounts = web3.eth.getAccounts();
accounts[0];

will return undefined.

TLDR : use this code instead (if it works, didn't test) :

var accounts =  await web3.eth.getAccounts();
accounts[0];
  • 1
    I'm getting: "TypeError: Cannot read property 'match' of undefined" – Rexcirus May 28 at 9:11
  • await is only valid in async function – btc4cash Aug 17 at 19:51
1

One line code: For displaying all accounts use:

web3.eth.getAccounts()

This works perfectly for displaying individual account addresses: You can get the address of the account required by changing the index referenced by the result array in the fall back function

web3.eth.getAccounts().then( function (result) { return result[0] });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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