@polkadot/api

  • Version 9.9.4
  • Published
  • 4.58 MB
  • 17 dependencies
  • Apache-2.0 license

Install

npm i @polkadot/api
yarn add @polkadot/api
pnpm add @polkadot/api

Overview

Promise and RxJS wrappers around the Polkadot JS RPC

Index

Variables

variable packageInfo

const packageInfo: { name: string; path: string; type: string; version: string };

    Functions

    function toPromiseMethod

    toPromiseMethod: <M extends DecorateFn<CodecReturnType<M>>>(
    method: M,
    options?: DecorateMethodOptions
    ) => StorageEntryPromiseOverloads;
    • Decorate method for ApiPromise, where the results are converted to the Promise equivalent

    function toRxMethod

    toRxMethod: <M extends DecorateFn<Codec>>(method: M) => M;

      Classes

      class ApiPromise

      class ApiPromise extends ApiBase<'promise'> {}
      • # @polkadot/api/promise

        ## Overview

        ApiPromise ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static .create(...). Subscription calls utilise (value) => {} callbacks to pass through the latest values.

        The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients.

        See Also

        • [[ApiRx]]

          ## Usage

          Making rpc calls -

          import ApiPromise from '@polkadot/api/promise';
          // initialise via static create
          const api = await ApiPromise.create();
          // make a subscription to the network head
          api.rpc.chain.subscribeNewHeads((header) => {
          console.log(`Chain is at #${header.number}`);
          });

          Subscribing to chain state -

          import { ApiPromise, WsProvider } from '@polkadot/api';
          // initialise a provider with a specific endpoint
          const provider = new WsProvider('wss://example.com:9944')
          // initialise via isReady & new with specific provider
          const api = await new ApiPromise({ provider }).isReady;
          // retrieve the block target time
          const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
          let last = 0;
          // subscribe to the current block timestamp, updates automatically (callback provided)
          api.query.timestamp.now((timestamp) => {
          const elapsed = last
          ? `, ${timestamp.toNumber() - last}s since last`
          : '';
          last = timestamp.toNumber();
          console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
          });

          Submitting a transaction -

          import ApiPromise from '@polkadot/api/promise';
          ApiPromise.create().then((api) => {
          const [nonce] = await api.query.system.account(keyring.alice.address);
          api.tx.balances
          // create transfer
          transfer(keyring.bob.address, 12345)
          // sign the transcation
          .sign(keyring.alice, { nonce })
          // send the transaction (optional status callback)
          .send((status) => {
          console.log(`current status ${status.type}`);
          })
          // retrieve the submitted extrinsic hash
          .then((hash) => {
          console.log(`submitted with hash ${hash}`);
          });
          });

      constructor

      constructor(options?: ApiOptions);
      • Creates an instance of the ApiPromise class

        Parameter options

        Options to create an instance. This can be either [[ApiOptions]] or an [[WsProvider]].

        Example 1

        import Api from '@polkadot/api/promise';
        new Api().isReady.then((api) => {
        api.rpc.subscribeNewHeads((header) => {
        console.log(`new block #${header.number.toNumber()}`);
        });
        });

      property isReady

      readonly isReady: Promise<ApiPromise>;
      • Promise that resolves the first time we are connected and loaded

      property isReadyOrError

      readonly isReadyOrError: Promise<ApiPromise>;
      • Promise that resolves if we can connect, or reject if there is an error

      method clone

      clone: () => ApiPromise;
      • Returns a clone of this ApiPromise instance (new underlying provider connection)

      method combineLatest

      combineLatest: <T extends any[] = any[]>(
      fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[],
      callback: Callback<T>
      ) => UnsubscribePromise;
      • Creates a combinator that can be used to combine the latest results from multiple subscriptions

        Parameter fns

        An array of function to combine, each in the form of (cb: (value: void)) => void

        Parameter callback

        A callback that will return an Array of all the values this combinator has been applied to

        Example 1

        const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
        // combines values from balance & nonce as it updates
        api.combineLatest([
        api.rpc.chain.subscribeNewHeads,
        (cb) => api.query.system.account(address, cb)
        ], ([head, [balance, nonce]]) => {
        console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
        });

      method create

      static create: (options?: ApiOptions) => Promise<ApiPromise>;
      • Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.

        Parameter options

        options that is passed to the class contructor. Can be either [[ApiOptions]] or a provider (see the constructor arguments)

        Example 1

        import Api from '@polkadot/api/promise';
        Api.create().then(async (api) => {
        const timestamp = await api.query.timestamp.now();
        console.log(`lastest block timestamp ${timestamp}`);
        });

      class ApiRx

      class ApiRx extends ApiBase<'rxjs'> {}
      • # @polkadot/api/rx

        ## Overview

        ApiRx

        ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static .create(...). In the same fashion and subscription-based methods return long-running Observables that update with the latest values.

        The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding .subscribe and .pipe on Observables will unlock full-scale use thereof.

        See Also

        • [[ApiPromise]]

          ## Usage

          Making rpc calls -

          import ApiRx from '@polkadot/api/rx';
          // initialize via Promise & static create
          const api = await ApiRx.create().toPromise();
          // make a call to retrieve the current network head
          api.rpc.chain.subscribeNewHeads().subscribe((header) => {
          console.log(`Chain is at #${header.number}`);
          });

          Subscribing to chain state -

          import { combineLatest, pairwise, switchMap } from 'rxjs';
          import { ApiRx, WsProvider } from '@polkadot/api';
          // initialize a provider with a specific endpoint
          const provider = new WsProvider('wss://example.com:9944')
          // initialize via isReady & new with specific provider
          new ApiRx({ provider })
          .isReady
          .pipe(
          switchMap((api) =>
          combineLatest([
          api.query.timestamp.blockPeriod(),
          api.query.timestamp.now().pipe(pairwise())
          ])
          )
          )
          .subscribe(([blockPeriod, timestamp]) => {
          const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber();
          console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`);
          });

          Submitting a transaction -

          import { first, switchMap } from 'rxjs';
          import ApiRx from '@polkadot/api/rx';
          // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
          import testingPairs from '@polkadot/keyring/testingPairs';
          const keyring = testingPairs();
          // get api via Promise
          const api = await ApiRx.create().toPromise();
          // retrieve nonce for the account
          api.query.system
          .account(keyring.alice.address)
          .pipe(
          first(),
          // pipe nonce into transfer
          switchMap(([nonce]) =>
          api.tx.balances
          // create transfer
          .transfer(keyring.bob.address, 12345)
          // sign the transaction
          .sign(keyring.alice, { nonce })
          // send the transaction
          .send()
          )
          )
          // subscribe to overall result
          .subscribe(({ status }) => {
          if (status.isInBlock) {
          console.log('Completed at block hash', status.asFinalized.toHex());
          }
          });

      constructor

      constructor(options?: ApiOptions);
      • Create an instance of the ApiRx class

        Parameter options

        Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]]

        Example 1

        import { switchMap } from 'rxjs';
        import Api from '@polkadot/api/rx';
        new Api().isReady
        .pipe(
        switchMap((api) =>
        api.rpc.chain.subscribeNewHeads()
        ))
        .subscribe((header) => {
        console.log(`new block #${header.number.toNumber()}`);
        });

      property isReady

      readonly isReady: Observable<ApiRx>;
      • Observable that returns the first time we are connected and loaded

      method clone

      clone: () => ApiRx;
      • Returns a clone of this ApiRx instance (new underlying provider connection)

      method create

      static create: (options?: ApiOptions) => Observable<ApiRx>;
      • Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.

        Parameter options

        options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]]

        Example 1

        import { switchMap } from 'rxjs';
        import Api from '@polkadot/api/rx';
        Api.create()
        .pipe(
        switchMap((api) =>
        api.rpc.chain.subscribeNewHeads()
        ))
        .subscribe((header) => {
        console.log(`new block #${header.number.toNumber()}`);
        });

      class SubmittableResult

      class SubmittableResult implements ISubmittableResult {}

        constructor

        constructor({
        dispatchError,
        dispatchInfo,
        events,
        internalError,
        status,
        txHash,
        txIndex,
        }: SubmittableResultValue);

          property dispatchError

          readonly dispatchError?: DispatchError;

            property dispatchInfo

            readonly dispatchInfo?: DispatchInfo;

              property events

              readonly events: EventRecord[];

                property internalError

                readonly internalError?: Error;

                  property isCompleted

                  readonly isCompleted: boolean;

                    property isError

                    readonly isError: boolean;

                      property isFinalized

                      readonly isFinalized: boolean;

                        property isInBlock

                        readonly isInBlock: boolean;

                          property isWarning

                          readonly isWarning: boolean;

                            property status

                            readonly status: ExtrinsicStatus;

                              property txHash

                              readonly txHash: Hash;

                                property txIndex

                                readonly txIndex?: number;

                                  method filterRecords

                                  filterRecords: (section: string, method: string | string[]) => EventRecord[];
                                  • Filters EventRecords for the specified method & section (there could be multiple)

                                  method findRecord

                                  findRecord: (
                                  section: string,
                                  method: string | string[]
                                  ) => EventRecord | undefined;
                                  • Finds an EventRecord for the specified method & section

                                  method toHuman

                                  toHuman: (isExtended?: boolean) => AnyJson;
                                  • Creates a human representation of the output

                                  Package Files (7)

                                  Dependencies (17)

                                  Dev Dependencies (0)

                                  No dev dependencies.

                                  Peer Dependencies (0)

                                  No peer dependencies.

                                  Badge

                                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@polkadot/api.

                                  • Markdown
                                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@polkadot/api)
                                  • HTML
                                    <a href="https://www.jsdocs.io/package/@polkadot/api"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>