1

I want to get validator address list from nominator address using PolkadotJS/api.

How can I get?

1 Answer 1

1

Below are a couple of options of how to use the following Substrate storage query api.query.staking.nominators(AccountId32):Option<PalletStakingNominations> from the Polkadot.js API docs here to get the list of validators that have been nominated by a given nominator stash address.

Option 1:

  • Go to https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc.polkadot.io#/js
  • Note: Replace wss%3A%2F%2Frpc.polkadot.io with the WS endpoints for RPC connections of the chain they are using to nominate on
  • Paste the code snippet below, replacing the ALICE address with an address that is actively nominating
  • Click the play icon
  • View the output in the terminal on the right that will list the validators they have nominated.
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const validators = await api.query.staking.nominators(ALICE);
if (validators.toJSON() && validators.toJSON().hasOwnProperty("targets")) {
  console.log(`stash account ${ALICE} has nominated the following validators\n\n`,
    JSON.stringify(validators.toJSON()["targets"], null, 2));
} else {
  console.log(`stash account ${ALICE} has not nominated any validators`);
}

Option 2:

  • Alternatively install Node.js and create a program:
mkdir nominated-validators-for-account
cd nominated-validators-for-account
yarn init
touch index.js
yarn add @polkadot/api
npm pkg set 'scripts.start'='node index.js'
npm pkg set 'type'='module'
  • Paste the following code in your terminal to add it to index.js
    • Note: Replace wss://rpc.polkadot.io with the WS endpoint for RPC connections of the chain they are using to nominate on
cat <<EOT >> index.js

import { ApiPromise, WsProvider } from '@polkadot/api';

const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';

async function main () {
  const wsProvider = new WsProvider('wss://rpc.polkadot.io');
  const api = await ApiPromise.create({ provider: wsProvider });
  const validators = await api.query.staking.nominators(ALICE);
  if (validators.toJSON() && validators.toJSON().hasOwnProperty("targets")) {
    console.log(`ALICE account ${ALICE} has nominated the following validators\n\n`,
      JSON.stringify(validators.toJSON()["targets"], null, 2));
  } else {
    console.log(`ALICE account ${ALICE} has not nominated any validators`);
  }
}

main().catch(console.error).finally(() => process.exit());

EOT

Run the program and view the output:

yarn start

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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