[Ethereum] How to list ALL Ethereum addresses with a positive balance

mappingweb3js

Using web3 I can query the balance of any fixed account with web3.eth.getBalance. Assuming I have the entire blockchain downloaded, how can I recover the list of all addresses that have a positive balance at this moment?

Best Answer

simple:

  1. get all the blocks
  2. from each block get all the transactions
  3. filter all the transactions with a value > 0
  4. record the list of all the to addresses
  5. filter out duplicates
  6. filter out addresses with balance 0

    const Web3 = require('web3')
    
    const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/<InfuraToken>'))
    
    let blockNum = 0
    
    let run = async () => {
      let addresses = {}
    
      while (true) {
        let blck = blockNum++
        let block = await web3.eth.getBlock(blck)
        if (!block)
          break
    
        console.log('block', blck, 'transactions', block.transactions.length)
        for(let i = 0; i < block.transactions.length; i++) {
          let tx = await web3.eth.getTransaction(block.transactions[i])
          if (parseInt(tx.value) > 0) {
            addresses[tx.to] = true
          }
        }
      }
    
      let positiveAddresses = []
      for (address in addresses) {
        try {
          let balance = await web3.eth.getBalance(address)
          if (balance > 0) {
            positiveAddresses.push(address)
          }
        } catch (err) {
          console.log(err)
        }
      }
      console.log(positiveAddresses)
    }
    
    run()
    

let this script run for a week or two and you'll have your result. The script requires the 1.0 version of web3 npm i web3 should do the trick. No other dependencies.

to run this simply use node scriptName.js

improvements may include finding out which addresses are contracts with eth.getCode. You could also write the result to disk instead of doing it all in memory.

Related Topic