How to use the @polkadot/api.ApiPromise.create function in @polkadot/api

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 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 / promise / 07_make_transfer_with_allowed_block_permissions_only / index.js View on Github external
async function main () {
  // Instantiate the API
  const api = await ApiPromise.create(); // default provider

  // 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-derived path (empty phrase, so uses dev)
  const alice = keyring.addFromUri('//Alice');

  // Get nonce for account
  const nonce = await api.query.system.accountNonce(alice.address);

  // Get current block
  const signedBlock = await api.rpc.chain.getBlock();

  // Get current block height and hash
  const currentHeight = signedBlock.block.header.number;
  const blockHash = signedBlock.block.header.hash;
github paritytech / srml-contracts-waterfall / tests / contracts-rust.spec.ts View on Github external
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 => {
        if (
          result.status.isFinalized &&
          result.findRecord("system", "ExtrinsicSuccess")
        ) {
          console.log("New test account has been created.");
          done();
        }
      });
  }
);
github vue-polkadot / vue-ui / packages / vue-api / src / Api.ts View on Github external
private async createApi(
    apiUrl: string = 'wss://poc3-rpc.polkadot.io/'
  ): Promise {
    const provider = new WsProvider(apiUrl);
    return await ApiPromise.create({provider});
  }
}
github polkadot-js / tools / packages / monitor-rpc / src / monitor.ts View on Github external
async function main (): Promise {
  const app = new Koa();

  app.use(koaRoute.all('/', httpStatus));
  app.listen(port);

  const provider = new WsProvider(ws);
  const api = await ApiPromise.create({ provider });

  await api.rpc.chain.subscribeNewHeads(updateCurrent);

  setInterval(checkDelay, 1000);
}

@polkadot/api

Promise and RxJS wrappers around the Polkadot JS RPC

Apache-2.0
Latest version published 11 days ago

Package Health Score

90 / 100
Full package analysis

Similar packages