I want to get validator address list from nominator address using PolkadotJS/api.
How can I get?
Substrate and Polkadot Stack Exchange is a question and answer site for developers building blockchains with the Substrate SDK. It only takes a minute to sign up.
Sign up to join this communityBelow 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:
wss%3A%2F%2Frpc.polkadot.io
with the WS endpoints for RPC connections of the chain they are using to nominate onALICE
address with an address that is actively nominatingconst 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:
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'
wss://rpc.polkadot.io
with the WS endpoint for RPC connections of the chain they are using to nominate oncat <<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