@polkadot/keyring#Keyring TypeScript Examples

The following examples show how to use @polkadot/keyring#Keyring. 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: account.ts    From metamask-snap-polkadot with Apache License 2.0 6 votes vote down vote up
/**
 * Returns KeyringPair if one is saved in wallet state, creates new one otherwise
 * @param wallet
 */
export async function getKeyPair(wallet: Wallet): Promise<KeyringPair> {
  // get app key and wait for api to be ready
  const [appKey] = await Promise.all([wallet.getAppKey(), cryptoWaitReady()]);
  // generate keys
  const seed = appKey.substr(0, 32);
  const keyring = new Keyring({ss58Format: getConfiguration(wallet).addressPrefix});
  return keyring.addFromSeed(stringToU8a(seed));
}
Example #2
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
createPolkadotAccountFromSeed = async (
  key: string,
): Promise<{ account: DotAccount; stashKey: any }> => {
  console.log(`Creating new Polkadot Account from Seed: ${key}`);
  const seed = key.padEnd(32, " ");
  const keyring: Keyring = new Keyring({ type: "ed25519", ss58Format: 2 });
  const stashKey = keyring.addFromSeed(stringToU8a(seed));
  const account = await fetchAccount(stashKey.address);
  console.log("Account Result:");
  console.log(account);
  return { account, stashKey };
}
Example #3
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _initKey = (): void =>{
      this.logger.debug(`init registrar with index ${this.registrarIndex} ...`)
      const keyring = new Keyring({ type: 'sr25519' });
      const keyJson = JSON.parse(fs.readFileSync(this.registrarWalletFilePath, { encoding: 'utf-8' })) as KeyringPair$Json;
      const passwordContent = fs.readFileSync(this.registrarPasswordFilePath, { encoding: 'utf-8' });
      this.registrarAccount = keyring.addFromJson(keyJson)
      this.registrarAccount.decodePkcs8(passwordContent)

      this.logger.debug(`read account with address: ${keyring.pairs[0].toJson().address}`)
      this.logger.debug(`is locked: ${this.registrarAccount.isLocked}`)

      if(this.registrarAccount.isLocked){
        this.logger.error(`problem unlocking the wallet, exiting ...`)
        process.exit(1)
      }
    }
Example #4
Source File: script.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
async function main () {
  

  const scriptArg = process.argv[2]
  const script = scripts[scriptArg]

  if (!scriptArg || !script) {
    console.error('Please specify valid script name.')
    console.error('Available scripts:', Object.keys(scripts))
    return
  }

  const provider = new WsProvider('ws://127.0.0.1:9944')
  // const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org')

  const api = await ApiPromise.create({ provider, types: joyTypes })

  // We don't pass a custom signer to the api so we must use a keyPair
  // when calling signAndSend on transactions
  const keyring = new Keyring()

  // Optional last argument is a SURI for account to use for signing transactions
  const suri = process.argv[3]
  if (suri) {
    keyring.addFromUri(suri, undefined, 'sr25519')
  }

  // Add development well known keys to keyring
  if ((await api.rpc.system.chain()).toString() === 'Development') {
    keyring.addFromUri('//Alice', undefined, 'sr25519')
    keyring.addFromUri('//Bob', undefined, 'sr25519')
  }

  try {
    await script({ api, types, util, hashing, keyring, joy })
  } catch (err) {
    console.error(err)
  }

  api.disconnect();
}
Example #5
Source File: signers.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function aliceSigner (): KeyringPair {
  const keyring = new Keyring({ type: 'sr25519' });

  return keyring.addFromUri('//Alice');
}
Example #6
Source File: signers.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function bobSigner (): KeyringPair {
  const keyring = new Keyring({ type: 'sr25519' });

  return keyring.addFromUri('//Bob');
}
Example #7
Source File: signers.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function charlieSigner (): KeyringPair {
  const keyring = new Keyring({ type: 'sr25519' });

  return keyring.addFromUri('//Charlie');
}
Example #8
Source File: signers.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function daveSigner (): KeyringPair {
  const keyring = new Keyring({ type: 'sr25519' });

  return keyring.addFromUri('//Dave');
}
Example #9
Source File: signers.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function eveSigner (): KeyringPair {
  const keyring = new Keyring({ type: 'sr25519' });

  return keyring.addFromUri('//Eve');
}
Example #10
Source File: signers.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function ferdieSigner (): KeyringPair {
  const keyring = new Keyring({ type: 'sr25519' });

  return keyring.addFromUri('//Ferdie');
}
Example #11
Source File: account.ts    From sdk with Apache License 2.0 5 votes vote down vote up
keyring = new Keyring({ ss58Format: 0, type: "sr25519" })
Example #12
Source File: keyring.ts    From sdk with Apache License 2.0 5 votes vote down vote up
keyring = new Keyring({ ss58Format: 0, type: "sr25519" })
Example #13
Source File: index.ts    From sdk with Apache License 2.0 5 votes vote down vote up
async function signPayload(api: ApiPromise, { payload }, password: string) {
  const { method, params } = payload;
  const address = params[0];
  const keyPair = ((window as any).keyring as Keyring).getPair(address);
  try {
    if (!keyPair.isLocked) {
      keyPair.lock();
    }
    keyPair.decodePkcs8(password);

    if (method == "signExtrinsic") {
      const txInfo = params[1];
      const { header, mortalLength, nonce } = (await api.derive.tx.signingInfo(address)) as any;
      const tx = api.tx[txInfo.module][txInfo.call](...txInfo.params);

      const signerPayload = api.registry.createType("SignerPayload", {
        address,
        blockHash: header.hash,
        blockNumber: header ? header.number : 0,
        era: api.registry.createType("ExtrinsicEra", {
          current: header.number,
          period: mortalLength,
        }),
        genesisHash: api.genesisHash,
        method: tx.method,
        nonce,
        signedExtensions: ["CheckNonce"],
        tip: txInfo.tip,
        runtimeVersion: {
          specVersion: api.runtimeVersion.specVersion,
          transactionVersion: api.runtimeVersion.transactionVersion,
        },
        version: api.extrinsicVersion,
      });
      const payload = signerPayload.toPayload();
      const txPayload = api.registry.createType("ExtrinsicPayload", payload, {
        version: payload.version,
      });
      const signed = txPayload.sign(keyPair);
      return signed;
    }
    if (method == "signBytes") {
      const msg = params[1];
      const isDataHex = isHex(msg);
      return {
        signature: u8aToHex(keyPair.sign(isDataHex ? hexToU8a(msg) : stringToU8a(msg))),
      };
    }
  } catch (err) {
    (window as any).send({ error: err.message });
  }

  return {};
}
Example #14
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);
  }
}