How to use @polkadot/keyring - 10 common examples

To help you get started, we’ve selected a few @polkadot/keyring examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ChainSafe / gossamer / tests / polkadotjs_test / test_transaction.js View on Github external
async function main() {
    // Construct

    const wsProvider = new WsProvider('ws://127.0.0.1:8546');
    const api = await ApiPromise.create({ provider: wsProvider });

    // Simple transaction
    const keyring = new Keyring({type: 'sr25519' });
    const aliceKey = keyring.addFromUri('//Alice',  { name: 'Alice default' });
    console.log(`${aliceKey.meta.name}: has address ${aliceKey.address} with publicKey [${aliceKey.publicKey}]`);

    const ADDR_Bob = '0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22';

    const transfer = await api.tx.balances.transfer(ADDR_Bob, 12345)
        .signAndSend(aliceKey, {era: 0, blockHash: '0x64597c55a052d484d9ff357266be326f62573bb4fbdbb3cd49f219396fcebf78', blockNumber:0,  genesisHash: '0x64597c55a052d484d9ff357266be326f62573bb4fbdbb3cd49f219396fcebf78', nonce: 1, tip: 0, transactionVersion: 1});

    console.log(`hxHash ${transfer}`);

}
github paritytech / srml-contracts-waterfall / tests / contracts-rust.spec.ts View on Github external
import { u8aToHex } from "@polkadot/util";
import { randomAsU8a } from "@polkadot/util-crypto";
import { KeyringPair } from "@polkadot/keyring/types";
import { Option } from "@polkadot/types";
import { Address, ContractInfo, Hash } from "@polkadot/types/interfaces";

import { ALICE, CREATION_FEE, WSURL } from "./consts";
import {
  callContract,
  instantiate,
  getContractStorage,
  putCode
} from "./utils";

// This is a test account that is going to be created and funded each test.
const keyring = testKeyring({ type: "sr25519" });
const alicePair = keyring.getPair(ALICE);
let testAccount: KeyringPair;
let api: ApiPromise;

beforeAll((): void => {
  jest.setTimeout(30000);
});

beforeEach(
  async (done): Promise<() => void> => {
    api = await ApiPromise.create({ provider: new WsProvider(WSURL) });
    testAccount = keyring.addFromSeed(randomAsU8a(32));

    return api.tx.balances
      .transfer(testAccount.address, CREATION_FEE.muln(3))
      .signAndSend(alicePair, (result: SubmittableResult): void => {
github paritytech / srml-contracts-waterfall / tests / contracts-assemblyscript.spec.ts View on Github external
import { hexStripPrefix, hexToBn, u8aToHex, u8aToString } from "@polkadot/util";
import { randomAsU8a } from "@polkadot/util-crypto";
import { KeyringPair } from "@polkadot/keyring/types";
import { Address, ContractInfo, Balance, Hash } from "@polkadot/types/interfaces";
import BN from "bn.js";

import { ALICE, BOB, CREATION_FEE, WSURL } from "./consts";
import {
  callContract,
  instantiate,
  getContractStorage,
  putCode
} from "./utils";

// This is a test account that is going to be created and funded each test.
const keyring = testKeyring({ type: "sr25519" });
const bobPair = keyring.getPair(BOB);
const randomSeed = randomAsU8a(32);
let testAccount: KeyringPair;
let api: ApiPromise;

beforeAll((): void => {
  jest.setTimeout(30000);
});

beforeEach(
  async (done): Promise<() => void> => {
    api = await ApiPromise.create({ provider: new WsProvider(WSURL) });
    testAccount = keyring.addFromSeed(randomSeed);

    return api.tx.balances
      .transfer(testAccount.address, CREATION_FEE.muln(3))
github polkadot-js / api / packages / types / src / primitive / Extrinsic / v4 / Extrinsic.spec.ts View on Github external
// Copyright 2017-2019 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

import BN from 'bn.js';
import testingPairs from '@polkadot/keyring/testingPairs';
import Decorated from '@polkadot/metadata/Decorated';
import Metadata from '@polkadot/metadata/Metadata';
import metadataStatic from '@polkadot/metadata/Metadata/static';

import { TypeRegistry } from '../../../codec/create';
import Extrinsic from './Extrinsic';

const registry = new TypeRegistry();
const decorated = new Decorated(registry, metadataStatic);
const keyring = testingPairs({ type: 'ed25519' }, false);

// eslint-disable-next-line no-new
new Metadata(registry, metadataStatic);

describe('ExtrinsicV4', (): void => {
  it('constructs a sane Uint8Array (default)', (): void => {
    expect(
      new Extrinsic(registry).toU8a()
    ).toEqual(new Uint8Array([0, 0]));
  });

  it('creates a unsigned extrinsic', (): void => {
    expect(
      new Extrinsic(
        registry,
        decorated.tx.balances.transfer(keyring.bob.publicKey, 6969)
github polkadot-js / api / packages / metadata / src / Decorated / extrinsics / index.spec.ts View on Github external
// Copyright 2017-2019 @polkadot/metadata authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

import BN from 'bn.js';
import testingPairs from '@polkadot/keyring/testingPairs';
import { createType, Metadata, TypeRegistry } from '@polkadot/types';

import metadataStatic from '../../Metadata/static';
import fromMetadata from './fromMetadata';

const keyring = testingPairs({ type: 'ed25519' }, false);
const registry = new TypeRegistry();
const metadata = new Metadata(registry, metadataStatic);
const extrinsics = fromMetadata(registry, metadata);

describe('extrinsics', (): void => {
  it('encodes an actual transfer (actual data)', (): void => {
    expect(
      createType(registry, 'Extrinsic',
        extrinsics.balances.transfer(keyring.bob.publicKey, 6969)
      ).sign(keyring.alice, {
        blockHash: '0xec7afaf1cca720ce88c1d1b689d81f0583cc15a97d621cf046dd9abf605ef22f',
        genesisHash: '0xdcd1346701ca8396496e52aa2785b1748deb6db09551b72159dcb3e08991025b',
        nonce: 0,
        runtimeVersion: {
          apis: [],
          authoringVersion: new BN(123),
github polkadot-js / api / packages / metadata / src / Decorated / storage / fromMetadata / fromMetadata.spec.ts View on Github external
// Copyright 2017-2019 @polkadot/metadata authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

import testingPairs from '@polkadot/keyring/testingPairs';
import { TypeRegistry } from '@polkadot/types';
import { u8aToHex } from '@polkadot/util';

import rpcMetadata from '../../../Metadata/static';
import rpcMetadataV8 from '../../../Metadata/v8/static';
import Decorated from '../../Decorated';

const keyring = testingPairs({ type: 'ed25519' });

describe('fromMetadata', (): void => {
  describe('latest', (): void => {
    const registry = new TypeRegistry();
    const decorated = new Decorated(registry, rpcMetadata);

    it('should throw if the storage function expects an argument', (): void => {
      expect((): any => decorated.query.balances.freeBalance()).toThrowError(/requires one argument/);
    });

    it('should return a value if the storage function does not expect an argument', (): void => {
      expect((): any => decorated.query.timestamp.now()).not.toThrow();
    });

    it('should return the correct length-prefixed storage key', (): void => {
      expect(
github polkadot-js / api / packages / types / src / primitive / Extrinsic / v2 / Extrinsic.spec.ts View on Github external
// Copyright 2017-2019 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

import BN from 'bn.js';
import Decorated from '@polkadot/metadata/Decorated';
import Metadata from '@polkadot/metadata/Metadata';
import rpcMetadata from '@polkadot/metadata/Metadata/static';
import testingPairs from '@polkadot/keyring/testingPairs';

import { TypeRegistry } from '../../../codec';
import Extrinsic from './Extrinsic';

const registry = new TypeRegistry();
const decorated = new Decorated(registry, rpcMetadata);
const keyring = testingPairs({ type: 'ed25519' }, false);

// eslint-disable-next-line no-new
new Metadata(registry, rpcMetadata);

describe('ExtrinsicV2', (): void => {
  it('constructs a sane Uint8Array (default)', (): void => {
    expect(
      new Extrinsic(registry).toU8a()
    ).toEqual(new Uint8Array([0, 0]));
  });

  it('creates a unsigned extrinsic', (): void => {
    expect(
      new Extrinsic(
        registry,
        decorated.tx.balances.transfer(keyring.bob.publicKey, 6969)
github polkadot-js / api / docs / examples / rx / 06_make_transfer / index.js View on Github external
async function main () {
  // Instantiate the API
  const api = await ApiRx.create().toPromise();

  // Create an instance of the keyring
  const keyring = new Keyring({ type: 'sr25519' });

  // Add Alice to our keyring (with the known seed for the account)
  const alice = keyring.addFromUri('//Alice');

  // Create a extrinsic, transferring 12345 units to Bob.
  const subscription = api.tx.balances
    // create transfer
    .transfer(BOB, 12345)
    // Sign and send the transcation
    .signAndSend(alice)
    // Subscribe to the status updates of the transfer
    .subscribe(({ status }) => {
      if (status.isFinalized) {
        console.log(`Successful transfer of 12345 from Alice to Bob with hash ${status.asFinalized.toHex()}`);
        subscription.unsubscribe();
      } else {
github polkadot-js / api / docs / examples / promise / 06_make_transfer / index.js View on Github external
async function main () {
  // Instantiate the API
  const api = await ApiPromise.create();

  // Constuct the keying after the API (crypto has an async init)
  const keyring = new Keyring({ type: 'sr25519' });

  // Add Alice to our keyring with a hard-deived path (empty phrase, so uses dev)
  const alice = keyring.addFromUri('//Alice');

  // Create a extrinsic, transferring 12345 units to Bob
  const transfer = api.tx.balances.transfer(BOB, 12345);

  // Sign and send the transaction using our account
  const hash = await transfer.signAndSend(alice);

  console.log('Transfer sent with hash', hash.toHex());
}
github polkadot-js / api / docs / examples / deprecated-rpc / 04_generate_account / index.js View on Github external
const crypto = require('crypto');
const Keyring = require('@polkadot/keyring').default;
const u8aToHex = require('@polkadot/util/u8a/toHex').default;
const Encoder = new TextEncoder(); // always utf-8

// A fixed seed from an array
const SEED1 = new Uint8Array([
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
  22, 23, 24, 25, 26, 27, 28, 29, 30, 0, 0
]);

// A fixed seed from a 32 chars string
const SEED2 = Encoder.encode('correct horse battery and staple');

const keyring = new Keyring();
const pair1 = keyring.addFromSeed(SEED1);
const pair2 = keyring.addFromSeed(SEED2);

console.log('Deterministic addresses (same for each run):');
console.log(`Address 1\t ${pair1.address()}\t Seed: ${u8aToHex(SEED1)}`);
console.log(`Address 2\t ${pair2.address()}\t Seed: ${u8aToHex(SEED2)}`);

// A random seed
const SEED = new Uint8Array(32);

console.log('Random Addresses (random for each run):');

for (var i = 3; i < 13; i++) {
  Buffer.from(crypto.randomFillSync(SEED));
  const pair3 = keyring.addFromSeed(SEED);
  console.log(`Address ${i}\t ${pair3.address()}\t Seed: ${u8aToHex(SEED)}`);

@polkadot/keyring

Keyring management

Apache-2.0
Latest version published 1 month ago

Package Health Score

87 / 100
Full package analysis

Similar packages