Polkadot JS APIGlobals"rx/Api"ApiRx

# Class: ApiRx

# @polkadot/api/rx

# Overview

name ApiRx

description ApiRx is a powerfull 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 ApiPromise

# Usage

Making rpc calls -

import ApiRx from '@polkadot/api/rx';

// initialise 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}`);
});
1
2
3
4
5
6
7
8
9

Subscribing to chain state -

import { combineLatest } from 'rxjs';
import { pairwise, switchMap } from 'rxjs/operators';
import { ApiRx, 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
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)`);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Submitting a transaction -

import { first, switchMap } from 'rxjs/operators';
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 transcation
         .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());
    }
  });
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
31
32

# Hierarchy

  • ApiBase‹"rxjs"›

    ApiRx

# Index

# Constructors

# Properties

# Accessors

# Methods

# Constructors

# constructor

+ new ApiRx(options?: ApiOptions): ApiRx

Overrides void

Defined in api/src/rx/Api.ts:141

description Create an instance of the ApiRx class

example

import { switchMap } from 'rxjs/operators';
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()}`);
  });
1
2
3
4
5
6
7
8
9
10
11

Parameters:

Name Type Description
options? ApiOptions Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]]

Returns: ApiRx

# Properties

# Readonly registry

registry: Registry

Inherited from Decorate.registry

Defined in api/src/base/Decorate.ts:48

# Accessors

# consts

get consts(): Constants

Inherited from ApiPromise.consts

Defined in api/src/base/index.ts:80

description Contains the parameter types (constants) of all modules.

The values are instances of the appropriate type and are accessible using section.constantName,

example

console.log(api.consts.democracy.enactmentPeriod.toString())
1

Returns: Constants


# derive

get derive(): ReturnType‹ApiBase<"rxjs">["_decorateDerive"]›

Inherited from ApiPromise.derive

Defined in api/src/base/index.ts:96

description Derived results that are injected into the API, allowing for combinations of various query results.

example

api.derive.chain.bestNumber((number) => {
  console.log('best number', number);
});
1
2
3

Returns: ReturnType‹ApiBase<"rxjs">["_decorateDerive"]›


# extrinsicVersion

get extrinsicVersion(): number

Inherited from ApiPromise.extrinsicVersion

Defined in api/src/base/index.ts:103

description Returns the version of extrinsics in-use on this chain

Returns: number


# genesisHash

get genesisHash(): Hash

Inherited from ApiPromise.genesisHash

Defined in api/src/base/index.ts:110

description Contains the genesis Hash of the attached chain. Apart from being useful to determine the actual chain, it can also be used to sign immortal transactions.

Returns: Hash


# hasSubscriptions

get hasSubscriptions(): boolean

Inherited from ApiPromise.hasSubscriptions

Overrides Decorate.hasSubscriptions

Defined in api/src/base/index.ts:117

description true when subscriptions are supported

Returns: boolean


# isConnected

get isConnected(): Observable‹boolean›

Defined in api/src/rx/Api.ts:179

description Observable that carries the connected state for the provider. Results in a boolean flag that is true/false based on the connectivity.

Returns: Observable‹boolean›


# isReady

get isReady(): Observable‹ApiRx

Defined in api/src/rx/Api.ts:186

description Observable that returns the first time we are connected and loaded

Returns: Observable‹ApiRx


# libraryInfo

get libraryInfo(): string

Inherited from ApiPromise.libraryInfo

Defined in api/src/base/index.ts:124

description The library information name & version (from package.json)

Returns: string


# query

get query(): QueryableStorage‹"rxjs"›

Inherited from ApiPromise.query

Defined in api/src/base/index.ts:142

description Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.

All calls inside the namespace, is denoted by section.method and may take an optional query parameter. As an example, api.query.timestamp.now() (current block timestamp) does not take parameters, while api.query.system.account(<accountId>) (retrieving the associated nonce & balances for an account), takes the AccountId as a parameter.

example

api.query.system.account(<accountId>, ([nonce, balance]) => {
  console.log('new free balance', balance.free, 'new nonce', nonce);
});
1
2
3

Returns: QueryableStorage‹"rxjs"›


# queryMulti

get queryMulti(): QueryableStorageMulti‹"rxjs"›

Inherited from ApiPromise.queryMulti

Defined in api/src/base/index.ts:168

description Allows for the querying of multiple storage entries and the combination thereof into a single result. This is a very optimal way to make multiple queries since it only makes a single connection to the node and retrieves the data over one subscription.

example

const unsub = await api.queryMulti(
  [
    // you can include the storage without any parameters
    api.query.balances.totalIssuance,
    // or you can pass parameters to the storage query
    [api.query.system.account, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']
  ],
  ([existential, [, { free }]]) => {
    console.log(`You have ${free.sub(existential)} more than the existential deposit`);

    unsub();
  }
);
1
2
3
4
5
6
7
8
9
10
11
12
13

Returns: QueryableStorageMulti‹"rxjs"›


# rpc

get rpc(): DecoratedRpc‹"rxjs", RpcInterface

Inherited from ApiPromise.rpc

Defined in api/src/base/index.ts:186

description Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions. Unlike the dynamic api.query and api.tx sections, these methods are fixed (although extensible with node upgrades) and not determined by the runtime.

RPC endpoints available here allow for the query of chain, node and system information, in addition to providing interfaces for the raw queries of state (using known keys) and the submission of transactions.

example

api.rpc.chain.subscribeNewHeads((header) => {
  console.log('new header', header);
});
1
2
3

Returns: DecoratedRpc‹"rxjs", RpcInterface


# runtimeMetadata

get runtimeMetadata(): Metadata

Inherited from ApiPromise.runtimeMetadata

Defined in api/src/base/index.ts:193

description Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.

Returns: Metadata


# runtimeVersion

get runtimeVersion(): RuntimeVersion

Inherited from ApiPromise.runtimeVersion

Defined in api/src/base/index.ts:200

description Contains the version information for the current runtime.

Returns: RuntimeVersion


# rx

get rx(): Pick‹ApiInterfaceRx, "tx" | "rpc"›

Inherited from ApiPromise.rx

Defined in api/src/base/index.ts:207

description The underlying Rx API interface

Returns: Pick‹ApiInterfaceRx, "tx" | "rpc"›


# tx

get tx(): SubmittableExtrinsics‹"rxjs"›

Inherited from ApiPromise.tx

Defined in api/src/base/index.ts:232

description Contains all the extrinsic modules and their subsequent methods in the API. It allows for the construction of transactions and the submission thereof. These are attached dynamically from the runtime metadata.

example

api.tx.balances
  .transfer(<recipientId>, <balance>)
  .signAndSend(<keyPair>, ({status}) => {
    console.log('tx status', status.asFinalized.toHex());
  });
1
2
3
4
5

Returns: SubmittableExtrinsics‹"rxjs"›


# type

get type(): ApiTypes

Inherited from ApiPromise.type

Defined in api/src/base/index.ts:214

description The type of this API instance, either 'rxjs' or 'promise'

Returns: ApiTypes

# Methods

# clone

clone(): ApiRx

Defined in api/src/rx/Api.ts:193

description Returns a clone of this ApiRx instance (new underlying provider connection)

Returns: ApiRx


# createType

createType<K>(type: K, ...params: any[]): InterfaceTypes[K]

Inherited from Decorate.createType

Defined in api/src/base/Decorate.ts:148

description Creates an instance of a type as registered

Type parameters:

K: keyof InterfaceTypes

Parameters:

Name Type
type K
...params any[]

Returns: InterfaceTypes[K]


# disconnect

disconnect(): void

Inherited from ApiPromise.disconnect

Defined in api/src/base/index.ts:239

description Disconnect from the underlying provider, halting all network traffic

Returns: void


# findCall

findCall(callIndex: Uint8Array | string): CallFunction

Inherited from ApiPromise.findCall

Defined in api/src/base/index.ts:246

description Finds the definition for a specific [[CallFunction]] based on the index supplied

Parameters:

Name Type
callIndex Uint8Array | string

Returns: CallFunction


# findError

findError(errorIndex: Uint8Array | string): RegistryError

Inherited from ApiPromise.findError

Defined in api/src/base/index.ts:253

description Finds the definition for a specific [[RegistryError]] based on the index supplied

Parameters:

Name Type
errorIndex Uint8Array | string

Returns: RegistryError


# injectMetadata

injectMetadata(metadata: Metadata, fromEmpty?: undefined | false | true): void

Inherited from Decorate.injectMetadata

Defined in api/src/base/Decorate.ts:166

Parameters:

Name Type
metadata Metadata
fromEmpty? undefined | false | true

Returns: void


# off

off(type: ApiInterfaceEvents, handler: function): this

Inherited from Events.off

Defined in api/src/base/Events.ts:62

description Remove the given eventemitter handler

example

const handler = (): void => {
 console.log('Connected !);
};

// Start listening
api.on('connected', handler);

// Stop listening
api.off('connected', handler);
1
2
3
4
5
6
7
8
9

Parameters:

type: ApiInterfaceEvents

The type of event the callback was attached to. Available events are connected, disconnected, ready and error

handler: function

The callback to unregister.

▸ (...args: any[]): any

Parameters:

Name Type
...args any[]

Returns: this


# on

on(type: ApiInterfaceEvents, handler: function): this

Inherited from Events.on

Defined in api/src/base/Events.ts:35

description Attach an eventemitter handler to listen to a specific event

example

api.on('connected', (): void => {
  console.log('API has been connected to the endpoint');
});

api.on('disconnected', (): void => {
  console.log('API has been disconnected from the endpoint');
});
1
2
3
4
5
6
7

Parameters:

type: ApiInterfaceEvents

The type of event to listen to. Available events are connected, disconnected, ready and error

handler: function

The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.

▸ (...args: any[]): any

Parameters:

Name Type
...args any[]

Returns: this


# once

once(type: ApiInterfaceEvents, handler: function): this

Inherited from Events.once

Defined in api/src/base/Events.ts:87

description Attach an one-time eventemitter handler to listen to a specific event

example

api.once('connected', (): void => {
  console.log('API has been connected to the endpoint');
});

api.once('disconnected', (): void => {
  console.log('API has been disconnected from the endpoint');
});
1
2
3
4
5
6
7

Parameters:

type: ApiInterfaceEvents

The type of event to listen to. Available events are connected, disconnected, ready and error

handler: function

The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.

▸ (...args: any[]): any

Parameters:

Name Type
...args any[]

Returns: this


# registerTypes

registerTypes(types?: RegistryTypes): void

Inherited from Decorate.registerTypes

Defined in api/src/base/Decorate.ts:155

description Register additional user-defined of chain-specific types in the type registry

Parameters:

Name Type
types? RegistryTypes

Returns: void


# setSigner

setSigner(signer: Signer): void

Inherited from ApiPromise.setSigner

Defined in api/src/base/index.ts:260

description Set an external signer which will be used to sign extrinsic when account passed in is not KeyringPair

Parameters:

Name Type
signer Signer

Returns: void


# sign

sign(address: KeyringSigner | string, data: SignerPayloadRawBase, __namedParameters: object): Promise‹string›

Inherited from ApiPromise.sign

Defined in api/src/base/index.ts:267

description Signs a raw signer payload, string or Uint8Array

Parameters:

address: KeyringSigner | string

data: SignerPayloadRawBase

Default value __namedParameters: object= {}

Name Type
signer undefined | Signer

Returns: Promise‹string›


# Static create

create(options?: ApiOptions): Observable‹ApiRx

Defined in api/src/rx/Api.ts:139

description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.

example

import { switchMap } from 'rxjs/operators';
import Api from '@polkadot/api/rx';

Api.create()
  .pipe(
    switchMap((api) =>
      api.rpc.chain.subscribeNewHeads()
  ))
  .subscribe((header) => {
    console.log(`new block #${header.number.toNumber()}`);
  });
1
2
3
4
5
6
7
8
9
10
11

Parameters:

Name Type Description
options? ApiOptions options that is passed to the class contructor. Can be either [[ApiOptions]] or [[WsProvider]]

Returns: Observable‹ApiRx