How to use @polkadot/rpc-provider - 10 common examples

To help you get started, we’ve selected a few @polkadot/rpc-provider 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 / deprecated-rpc / 06_craft_extrinsic / index.js View on Github external
const BN = require('bn.js');
const Rpc = require('@polkadot/rpc-core').default;
const WsProvider = require('@polkadot/rpc-provider/ws').default;
const extrinsics = require('@polkadot/extrinsics').default;
const encodeExtrinsic = require('@polkadot/extrinsics/codec/encode').default;
const encodeLength = require('@polkadot/extrinsics/codec/encode/length').default;
const Keyring = require('@polkadot/keyring').default;
const storage = require('@polkadot/storage').default;

const Encoder = new TextEncoder();
const keyring = new Keyring();
const provider = new WsProvider('ws://127.0.0.1:9944');
const api = new Rpc(provider);

async function getAccountIndex (address) {
  return api.state.getStorage([storage.system.public.accountIndexOf, address]);
}

async function transfer (keyRingFrom, addressTo, amount) {
  const accountIndex = await getAccountIndex(keyRingFrom.address());

  console.log(`Current accountIndex: ${accountIndex}`);

  // encode the call for signing
  const message = encodeExtrinsic(
    keyRingFrom.publicKey(),
    accountIndex,
    extrinsics.staking.public.transfer,
github polkadot-js / api / docs / examples / deprecated-rpc / 02_listen_to_blocks / index.js View on Github external
const Rpc = require('@polkadot/rpc-core').default;
const WsProvider = require('@polkadot/rpc-provider/ws').default;
const provider = new WsProvider('ws://127.0.0.1:9944');
const api = new Rpc(provider);

api.chain
  .newHead((error, header) => {
    if (error) {
      console.error('error:', error);
    }

    console.log(`best #${header.blockNumber.toString()}`);
  })
  .then((subscriptionId) => {
    console.log(`subscriptionId: ${subscriptionId}`);
    // id for the subscription, can unsubscribe via
    // api.chain.newHead.unsubscribe(subscriptionId);
  })
  .catch((error) => {
github paritytech / substrate-light-ui / packages / light-api / example / src / index.js View on Github external
import { LightApi } from '@polkadot/light-api';
import { WsProvider } from '@polkadot/rpc-provider';
import React from 'react';
import ReactDOM from 'react-dom';
import { switchMap } from 'rxjs/operators';

import App from './App';
import * as serviceWorker from './serviceWorker';
import './index.css';

ReactDOM.render(, document.getElementById('root'));

const lightApi = new LightApi(new WsProvider('ws://localhost:9944')).isReady;

lightApi
  .pipe(switchMap(api => api.light.newHead()))
  .subscribe(header => console.log('Now at ', header.get('number').toJSON()));

lightApi
  .pipe(switchMap(api => api.light.balanceOf('15jd4tmKwLf1mYWzmZxHeCpT38B2mx1GH6aDniXQxBjskkws')))
  .subscribe(b => console.log('Balance of Alice', b.toString()));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
github polkadot-js / apps / packages / react-api / src / WasmProviderLite.ts View on Github external
public constructor(client: any) {
    this._eventemitter = new EventEmitter();
    this.coder = new Coder();
    this.client = client;

    // Give subscribers time to subscribe
    setTimeout(() => {
      this._isConnected = true;
      this.emit('connected');
    });
  }
github polkadot-js / api / docs / examples / deprecated-rpc / 07_transfer_dots / index.js View on Github external
const BN = require('bn.js');
const Rpc = require('@polkadot/rpc-core').default;
const WsProvider = require('@polkadot/rpc-provider/ws').default;
const extrinsics = require('@polkadot/extrinsics').default;
const encodeExtrinsic = require('@polkadot/extrinsics/codec/encode/uncheckedLength').default;
const Keyring = require('@polkadot/keyring').default;
const storage = require('@polkadot/storage').default;

const Encoder = new TextEncoder();
const keyring = new Keyring();
const provider = new WsProvider('ws://127.0.0.1:9944');
const api = new Rpc(provider);

async function getAccountIndex (address) {
  return api.state.getStorage([storage.system.public.accountIndexOf, address]);
}

async function transfer (keyRingFrom, addressTo, amount) {
  const nextAccountIndex = await getAccountIndex(keyRingFrom.address());

  // encode the call for signing
  const encoded = encodeExtrinsic(
    keyRingFrom,
    nextAccountIndex,
    extrinsics.staking.public.transfer,
    [addressTo, amount]
  );
github polkadot-js / api / packages / api-derive / src / index.spec.ts View on Github external
describe('custom', (): void => {
    const api = new ApiRx({
      derives: {
        balances: {
          fees: (): any => (): Observable => from(['a', 'b'])
        },
        custom: {
          test: (): any => (): Observable => from([1, 2, 3])
        }
      },
      provider: new MockProvider(registry),
      registry
    });

    beforeAll((done): void => {
      api.isReady.subscribe((): void => done());
    });

    // override
    testFunction(api)('balances', 'fees', ['a', 'b']);

    // new
    testFunction(api)('custom' as any, 'test', [1, 2, 3]);

    // existing
    testFunction(api)('chain', 'bestNumber', []);
  });
github polkadot-js / client / packages / client-rpc / src / index.spec.js View on Github external
it.skip('starts and accepts requests, sending responses (WS)', () => {
    config.rpc.types = ['ws'];
    server = new Rpc(config, {}, handlers); // eslint-disable-line

    return new WsProvider('ws://localhost:9901')
      .send('echo', [1, 'ws', true])
      .then((result) => {
        expect(result).toEqual('echo: 1,ws,true');
      });
  });
github polkadot-js / api / docs / examples / deprecated-rpc / 01_simple_connect / index.js View on Github external
const Rpc = require('@polkadot/rpc-core').default;
const WsProvider = require('@polkadot/rpc-provider/ws').default;
const provider = new WsProvider('ws://127.0.0.1:9944');
const api = new Rpc(provider);

async function getChain () {
  return api.system.chain();
}

async function main () {
  const chain = await getChain();

  console.log('You are connected to chain:', chain);
}

main().finally(_ => process.exit());
github polkadot-js / api / docs / examples / deprecated-rpc / 03_listen_to_balance_change / index.js View on Github external
const BN = require('bn.js');
const Rpc = require('@polkadot/rpc-core').default;
const WsProvider = require('@polkadot/rpc-provider/ws').default;
const storage = require('@polkadot/storage').default;
const provider = new WsProvider('ws://127.0.0.1:9944');
const api = new Rpc(provider);

const Alice = '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ';

console.log('You may leave this example running and start example 06 or send DOTs to ' + Alice);

api.state
  .storage([[storage.staking.public.freeBalanceOf, Alice]], (_, values) => {
    console.log(`Balance of ${Alice}: ${new BN(values[0]).toString(10)} DOTs`);
  })
  .then((subscriptionId) => {
    console.log('Balance changes subscription id:', subscriptionId);
  });
github polkadot-js / api / packages / rpc-core / src / index.spec.ts View on Github external
it('allows for the definition of user RPCs', (): void => {
    const rpc = new Rpc(registry, new MockProvider(registry), {
      testing: [
        {
          name: 'foo',
          params: [{ name: 'bar', type: 'u32' }],
          type: 'Balance'
        }
      ]
    });

    expect(isFunction((rpc as any).testing.foo)).toBe(true);
    expect(rpc.sections.includes('testing')).toBe(true);
    expect(rpc.mapping.get('testing_foo')).toEqual({
      description: 'User defined',
      isDeprecated: false,
      isHidden: false,
      isOptional: false,

@polkadot/rpc-provider

Transport providers for the API

Apache-2.0
Latest version published 9 days ago

Package Health Score

90 / 100
Full package analysis

Similar packages