How to use @polkadot/api - 10 common examples

To help you get started, we’ve selected a few @polkadot/api 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 polkadot-js / api / docs / examples / promise / 02_listen_to_blocks / index.js View on Github external
async function main () {
  // Here we don't pass the (optional) provider, connecting directly to the default
  // node/port, i.e. `ws://127.0.0.1:9944`. Await for the isReady promise to ensure
  // the API has connected to the node and completed the initialisation process
  const api = await ApiPromise.create();

  // We only display a couple, then unsubscribe
  let count = 0;

  // Subscribe to the new headers on-chain. The callback is fired when new headers
  // are found, the call itself returns a promise with a subscription that can be
  // used to unsubscribe from the newHead subscription
  const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => {
    console.log(`Chain is at block: #${header.number}`);

    if (++count === 256) {
      unsubscribe();
      process.exit(0);
    }
  });
}
github polkadot-js / api / docs / examples / promise / 09_transfer_events / index.js View on Github external
async function main () {
  // Create the API and wait until ready
  const api = await ApiPromise.create();

  // Create an instance of our testing keyring
  // If you're using ES6 module imports instead of require, just change this line to:
  // const keyring = testKeyring();
  const keyring = testKeyring.default();

  // Get the nonce for the admin key
  const nonce = await api.query.system.accountNonce(ALICE);

  // Find the actual keypair in the keyring
  const alicePair = keyring.getPair(ALICE);

  // Create a new random recipient
  const recipient = keyring.addFromSeed(randomAsU8a(32)).address;

  console.log('Sending', AMOUNT, 'from', alicePair.address, 'to', recipient, 'with nonce', nonce.toString());
github polkadot-js / api / docs / examples / promise / 03_listen_to_balance_change / index.js View on Github external
async function main () {
  // Create an await for the API
  const api = await ApiPromise.create();

  // Retrieve the initial balance. Since the call has no callback, it is simply a promise
  // that resolves to the current on-chain value
  let previous = await api.query.balances.freeBalance(Alice);

  console.log(`${Alice} has a balance of ${previous}`);
  console.log(`You may leave this example running and start example 06 or transfer any value to ${Alice}`);

  // Here we subscribe to any balance changes and update the on-screen value
  api.query.balances.freeBalance(Alice, (current) => {
    // Calculate the delta
    const change = current.sub(previous);

    // Only display positive value changes (Since we are pulling `previous` above already,
    // the initial balance change will also be zero)
    if (!change.isZero()) {
github polkadot-js / api / docs / examples / promise / 04_unsubscribe / index.js View on Github external
async function main () {
  // Create a new instance of the api
  const api = await ApiPromise.create();

  // Subscribe to chain updates and log the current block number on update.
  const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => {
    console.log(`Chain is at block: #${header.number}`);
  });

  // In this example we're calling the unsubscribe() function that is being
  // returned by the api call function after 20s.
  setTimeout(() => {
    unsubscribe();
    console.log('Unsubscribed');
  }, 20000);
}
github polkadot-js / api / docs / examples / promise / 05_read_storage / index.js View on Github external
async function main () {
  // Create our API with a default connection to the local node
  const api = await ApiPromise.create();

  // Make our basic chain state/storage queries, all in one go
  const [accountNonce, now, validators] = await Promise.all([
    api.query.system.accountNonce(ALICE),
    api.query.timestamp.now(),
    api.query.session.validators()
  ]);

  console.log(`accountNonce(${ALICE}) ${accountNonce}`);
  console.log(`last block timestamp ${now.toNumber()}`);

  if (validators && validators.length > 0) {
    // Retrieve the balances for all validators
    const validatorBalances = await Promise.all(
      validators.map(authorityId =>
        api.query.balances.freeBalance(authorityId)
github polkadot-js / api / docs / examples / rx / 08_system_events / index.js View on Github external
async function main () {
  // Create our API with a default connection to the local node
  ApiRx.create()
    .pipe(
      switchMap((api) =>
        // subscribe to system events via storage
        api.query.system.events()
      )
    )
    // Then we're subscribing to the emitted results
    .subscribe((events) => {
      console.log(`\nReceived ${events.length} events:`);
      // loop through the Vec
      events.forEach((record) => {
      // extract the phase, event and the event types
        const { event, phase } = record;
        const types = event.typeDef;

        // show what we are busy with
github polkadot-js / api / docs / examples / rx / 09_transfer_events / index.js View on Github external
async function main () {
  // Create our API with a connection to the node
  const api = await ApiRx.create().toPromise();

  // Create an instance of our testign keyring
  // If you're using ES6 module imports instead of require, just change this line to:
  // const keyring = testKeyring();
  const keyring = testKeyring.default();

  // Find the actual keypair in the keyring
  const alicePair = keyring.getPair(ALICE);

  // Create a new random recipient
  const recipient = keyring.addFromSeed(randomAsU8a(32)).address;

  console.log('Sending', AMOUNT, 'from', alicePair.address, 'to', recipient);

  // Get the nonce for the admin key
  // Create a extrinsic, transferring 12345 units to Bob.
github polkadot-js / api / docs / examples / rx / 10_upgrade_chain / index.js View on Github external
async function main () {
  // Initialise the provider to connect to the local node
  const provider = new WsProvider('ws://127.0.0.1:9944');

  // Create the API and wait until ready (optional provider passed through)
  const api = await ApiRx.create({ provider }).toPromise();

  // Retrieve the upgrade key from the chain state
  // TODO It seems like this promise doesn't resolve
  const adminId = await api.query.sudo.key().toPromise();

  // Find the actual keypair in the keyring (if this is an changed value, the key
  // needs to be added to the keyring before - this assumes we have defaults, i.e.
  // Alice as the key - and this already exists on the test keyring)
  const keyring = testKeyring.default();
  const adminPair = keyring.getPair(adminId.toString());

  // Retrieve the runtime to upgrade to
  const code = fs.readFileSync('./test.wasm').toString('hex');
  const proposal = api.tx.consensus.setCode(`0x${code}`);

  console.log(`Upgrading chain runtime from ${adminId}`);
github polkadot-js / api / docs / examples / rx / 03_listen_to_balance_change / index.js View on Github external
async function main () {
  // Create an await for the API
  const api = await ApiRx.create().toPromise();

  // Here we subscribe to any balance changes and update the on-screen value.
  // We're using RxJs pairwise() operator to get the previous and current values as an array.
  api.query.balances.freeBalance(Alice)
    .pipe(
      // since pairwise only starts emitting values on the second emission, we prepend an
      // initial value with the startWith() operator to be able to also receive the first value
      startWith('first'),
      pairwise()
    )
    .subscribe((balance) => {
      if (balance[0] === 'first') {
        // Now we know that if the previous value emitted as balance[0] is `first`,
        // then balance[1] is the initial value of Alice account.
        console.log(`Alice ${Alice} has a balance of ${balance[1]}`);
        console.log('You may leave this example running and start the "Make a transfer" example or transfer any value to Alice address');

@polkadot/api

Promise and RxJS wrappers around the Polkadot JS RPC

Apache-2.0
Latest version published 10 days ago

Package Health Score

92 / 100
Full package analysis

Similar packages