2

I'm looking to query all Polkadot accounts and so I can sort them by balance. which javascript api should I use? I'm not just looking for accounts with identities. I'm looking for all accounts thank you very much

jhon alino
  • 85
  • 1
  • 9

1 Answers1

8

Using Polkadot JS: https://polkadot.js.org/docs/

To query all acccounts you need to look at all the entries of system.account

let users = substrate.query.system.account.entries();

Then to look at the total balance of a particular user you need to look at their data.free and add that to their data.reserved.

Here is how you will get the data for the first user:

let account_id = util_crypto.encodeAddress(users[0][0].slice(-32));
let free_balance = users[0][1].data.free.toNumber();
let reserved_balance = users[0][1].data.reserved.toNumber();

From there, you should be able to figure out how to sort the list and create the output you want.

EDIT:

Here is a full script for others:

var { ApiPromise, WsProvider } = require('@polkadot/api');
var { encodeAddress } = require('@polkadot/util-crypto')

async function main() {
    // Substrate node we are connected to and listening to remarks
    const provider = new WsProvider('ws://localhost:9944');
    const api = await ApiPromise.create({ provider });

    // Get general information about the node we are connected to
    const [chain, nodeName, nodeVersion] = await Promise.all([
        api.rpc.system.chain(),
        api.rpc.system.name(),
        api.rpc.system.version()
    ]);
    console.log(
        `You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`
    );

    // Adjust how many accounts to query at once.
    let limit = 50;
    let result = [];
    let last_key = "";

    while (true) {
        let query = await api.query.system.account.entriesPaged({ args: [], pageSize: limit, startKey: last_key });

        if (query.length == 0) {
            break
        }

        for (const user of query) {
            let account_id = encodeAddress(user[0].slice(-32));
            let free_balance = user[1].data.free.toString();
            let reserved_balance = user[1].data.reserved.toString();
            result.push({ account_id, free_balance, reserved_balance });
            last_key = user[0];
        }
    }

    console.log(result)
}
Shawn Tabrizi
  • 12,206
  • 1
  • 38
  • 69