@polkadot/keyring#encodeAddress TypeScript Examples

The following examples show how to use @polkadot/keyring#encodeAddress. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: is-valid-polkadot-address.ts    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
isValidPolkadotAddress = (address: string): boolean => {
  try {
    encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address));

    return true;
  } catch {
    return false;
  }
}
Example #2
Source File: validate.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
isSS58Address = (address: string) => {
  try {
    encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address));

    return true;
  } catch (error) {
    return false;
  }
}
Example #3
Source File: index.ts    From polkadot-k8s with Apache License 2.0 4 votes vote down vote up
async function main() {
  const provider = new WsProvider(`ws://${process.env.NODE_ENDPOINT}:9944`);
  // Create our API
  const api = await ApiPromise.create({ provider });

  // Constuct the keying
  const keyring = new Keyring({ type: 'sr25519' });

  // Add the voteBot account to our keyring
  const voteBotKey = keyring.addFromUri(process.env.PROXY_ACCOUNT_MNEMONIC!);

  const stash_account: string = process.env.STASH_ACCOUNT_ADDRESS!;
  const stash_alias = process.env.STASH_ACCOUNT_ALIAS; //optional
  const vote_bot_alias = process.env.PROXY_ACCOUNT_ALIAS; //optional
  const chain = process.env.CHAIN;
  // https://wiki.polkadot.network/docs/build-ss58-registry
  const chain_ss58_prefix = (chain == "kusama") ? 2 : 0
  const voteBot_account = encodeAddress(voteBotKey.address, chain_ss58_prefix);
  const stash_account_address = encodeAddress(stash_account, chain_ss58_prefix);
  const voteBalance = (await api.query.system.account(stash_account_address)).data.free.toBigInt() - BigInt(100000000);
  const currentBlockNum = (await api.rpc.chain.getHeader()).number;

  // will send an alert when the referendum is this close to finishing, and
  // recommendation still hasn't been committed to the repo.
  const DEADLINE_WARNING_NUM_BLOCKS: BigInt = BigInt(15000);

  console.log("Polkadot Vote Bot by MIDL.dev");
  console.log("Copyright 2022 MIDLDEV OU");
  console.log("***");
  console.log(`Chain:                         ${chain}`);
  console.log(`Current block number:          ${currentBlockNum.toHuman()}`);
  console.log(`Stash account address:         ${stash_account}`);
  console.log(`Stash account alias:           ${stash_alias}`);
  console.log(`Voting proxy account address:  ${voteBot_account}`);
  console.log(`Voting proxy account alias:    ${vote_bot_alias}`);
  console.log(`Vote balance in nanodot:       ${voteBalance.toString()}`);
  console.log(`Node RPC endpoint in use:      ${process.env.NODE_ENDPOINT}`);
  let rawValVotes = await api.query.democracy.votingOf(stash_account);
  let valVotes = JSON.parse(JSON.stringify(rawValVotes));


  valVotes = valVotes["direct"]["votes"].map((v: any) => v[0]);
  console.log(`Validator ${stash_alias} already voted for referenda ${valVotes}.`);

  let refCount = await api.query.democracy.referendumCount();
  let i: number = refCount.toU8a()[0];
  var referenda: any = [];
  while (true) {
    i = i - 1;
    var rawR = await api.query.democracy.referendumInfoOf(i);
    let r = JSON.parse(JSON.stringify(rawR));

    if ("ongoing" in r) {
      r["number"] = i;
      console.log(`Current referenum ${i} found, ending at block ${r["ongoing"]["end"]}`);
      if (valVotes.includes(i)) {
        console.log(`But validator ${stash_alias} has already voted for referendum ${i}.`);
      } else {
        referenda.push(r);
      }
    } else {
      break;
    }
  }

  if (referenda.length == 0) {
    console.log("All up-to-date with voting, exiting.");
    process.exit(0);
  }

  // Load votes from external file
  const url = `https://raw.githubusercontent.com/${process.env.VOTE_REPO}/main/${chain}.yaml`;
  const getVotes = (url: string) => {
    return new Promise((resolve, reject) => {
      request.get(url, (error: any, response: any, body: any) => {
        if (!error && response.statusCode == 200) {
          return resolve(body);
        }
        return reject({
          message: "Invalid URL!",
          stack: error ? error.stack : null
        });
      });
    });
  }
  const votes = yaml.load(await getVotes(url));

  let r = referenda[referenda.length - 1];
  i = r["number"];
  if (!(i in votes)) {
    let blocksBeforeDeadline = BigInt(r["ongoing"]["end"]) - currentBlockNum.toBigInt();
    let errorMsg = `Recommendation for vote ${i} has not yet been committed to ${url}. Referendum ${i} will end in ${blocksBeforeDeadline} blocks, please commit a recommendation.`;
    if (blocksBeforeDeadline < DEADLINE_WARNING_NUM_BLOCKS) {
      await sendErrorToSlackAndExit(errorMsg);
    } else {
      console.error(errorMsg);
      console.log(`We will send an alert when we are less than ${DEADLINE_WARNING_NUM_BLOCKS} before the referendum end`);
      process.exit(0);
    }
  }
  console.log(`Voting ${votes[i]["vote"]} for referendum ${i}. Reason:`);
  console.log(votes[i]["reason"]);
  let isAye: boolean = (votes[i]["vote"] == "aye");

  let vote = {
    Standard: {
      vote: {
        aye: isAye,
        conviction: 'None',
      },
      balance: voteBalance,
    }
  };

  try {
    await api.tx.proxy.proxy(stash_account, "Governance", api.tx.democracy.vote(i, vote)).signAndSend(voteBotKey, (async (result) => {
      let status = result.status;
      let events = result.events;
      console.log('Transaction status:', result.status.type);

      if (status.isInBlock) {
        console.log('Included at block hash', result.status.asInBlock.toHex());

        events.forEach((event: any) => {
          console.log('\t', event.toString());
        });
      } else if (status.isFinalized) {
        console.log('Finalized block hash', status.asFinalized.toHex());
        if (result.dispatchError) {
          let slackMessage = `Vote extrinsic failed on-chain submission for validator ${stash_alias} from vote address ${vote_bot_alias} with error ${result.dispatchError}, check subscan, txhash ${status.asFinalized.toHex()}`;
          sendErrorToSlackAndExit(slackMessage)
        } else {
          console.log("extrinsic success in finalized block, exiting")
          process.exit(0);
        }
      } else if (status.isInvalid || status.isDropped) {
        let slackMessage = `Vote extrinsic failed for validator ${stash_alias}(${stash_account}) with error ${status}.`;
        sendErrorToSlackAndExit(slackMessage);
      } else if (status.isRetracted) {
        // fail the job but do not alert. It is likely the transaction will go through at next try.
        process.exit(1)
      }
    }));
  }
  catch (e: any) {
    const error_message: string = e.message;
    let slackMessage = `Vote extrinsic failed on - chain submission for validator ${stash_alias} from vote address ${vote_bot_alias} with error ${error_message}.`;
    sendErrorToSlackAndExit(slackMessage);
  }
}