Web3 1.0.0-beta.27 – Equivalent of `web3.eth.accounts[x]`

nodejsweb3js

I have testrpc initialised:

testrpc -a 10

And have connected via http from a node command line using web3 version 1.0.0-beta.27:

var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');

I'd like to be able to access the 3rd of the accounts initialised in testrpc using web3. In version 0.x.x I'd use web3.eth.accounts[3]. In the beta it seems that the process will change (docs) to use a getAccounts function.

Here's what I've attempted with the console output – I can see the list of accounts but can't seem to access them – there's possibly something simple I'm missing?

> web3.eth.getAccounts(console.log)[3]
undefined
> null [ '0xEc9F5cEF462dc92C1A04758b93Bf940142dD9AB8',
  '0xF1EB9C3FCa1e8e43597eB9Ec9204b57811317483',
  '0xCf7127dAc175E7d0cB5AB989DDCBa993Af5CC257',
  '0xddAB30A0b405FDe916060dAb961A8939bcB0292c',
  '0x76721db21AA265453BD17FCE53637D5A621AD434',
  '0x8a2D213434034DbE47501DEC88Cf2c74eaF7cA78',
  '0xBa523A69318A831F7463C88CF2e96143e4643Ae1',
  '0xDE8f72ad2221f5dc188cC2c780E256Ce0f8e16A4',
  '0x9E10ec8A473a15b37D8EcdD65d3f9c4f04f5eD83',
  '0xedc486961d350d26F8Df6D9b5CD5451Dc4ebCAc5' ]


> web3.eth.getAccounts().then(console.log)[3]
undefined
> [ '0xEc9F5cEF462dc92C1A04758b93Bf940142dD9AB8',
  '0xF1EB9C3FCa1e8e43597eB9Ec9204b57811317483',
  '0xCf7127dAc175E7d0cB5AB989DDCBa993Af5CC257',
  '0xddAB30A0b405FDe916060dAb961A8939bcB0292c',
  '0x76721db21AA265453BD17FCE53637D5A621AD434',
  '0x8a2D213434034DbE47501DEC88Cf2c74eaF7cA78',
  '0xBa523A69318A831F7463C88CF2e96143e4643Ae1',
  '0xDE8f72ad2221f5dc188cC2c780E256Ce0f8e16A4',
  '0x9E10ec8A473a15b37D8EcdD65d3f9c4f04f5eD83',
  '0xedc486961d350d26F8Df6D9b5CD5451Dc4ebCAc5' ]

I've tried a few variants of the above – the output I'm aiming for is 'OxddAB...'

What command in web3 v1.0.0-beta.27 reproduces the behaviour of web.eth.accounts[3] in web3 v 0.x.x?

I'd like to understand the reason for the proposed change, in case anyone here knows or can provide a link…

Edit – Managed to do it like this:

var a=web3.eth.getAccounts(console.log)
a._rejectionHandler0[3]

but it seems clunky/incorrect – can anyone improve?

Best Answer

when you write web3.eth.getAccounts().then(console.log)[3] the result of the getAccounts() is being passed in to console.log which is a function. The [3] bit is then being tacked on to the end which is meaningless.

const get3rdAccount = async () => {
  const accounts = await web3.eth.getAccounts()
  return accounts[3]
}

will do what you need. (or you can also use the callback approach as outlined by @Marez if you prefer)

Related Topic