Polkadot JS APIGlobals"promise/Api"ApiPromise

# Class: ApiPromise

# @polkadot/api/promise

# Overview

name ApiPromise

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

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)`);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

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}`);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# Hierarchy

  • ApiBase‹"promise"›

    ApiPromise

# Index

# Constructors

# Properties

# Accessors

# Methods

# Constructors

# constructor

+ new ApiPromise(options?: ApiOptions): ApiPromise

Overrides void

Defined in api/src/promise/Api.ts:198

description Creates an instance of the ApiPromise class

example

import Api from '@polkadot/api/promise';

new Api().isReady.then((api) => {
  api.rpc.subscribeNewHeads((header) => {
    console.log(`new block #${header.number.toNumber()}`);
  });
});
1
2
3
4
5
6
7

Parameters:

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

Returns: ApiPromise

# 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<"promise">["_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<"promise">["_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


# isReady

get isReady(): Promise‹ApiPromise

Defined in api/src/promise/Api.ts:233

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

Returns: Promise‹ApiPromise


# 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‹"promise"›

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‹"promise"›


# queryMulti

get queryMulti(): QueryableStorageMulti‹"promise"›

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‹"promise"›


# rpc

get rpc(): DecoratedRpc‹"promise", 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‹"promise", 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‹"promise"›

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‹"promise"›


# 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(): ApiPromise

Defined in api/src/promise/Api.ts:240

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

Returns: ApiPromise


# combineLatest

combineLatest<T>(fns: CombinatorFunction | [CombinatorFunction, any][], callback: CombinatorCallback‹T›): UnsubscribePromise

Defined in api/src/promise/Api.ts:267

description Creates a combinator that can be used to combine the latest results from multiple subscriptions

example

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

Type parameters:

T: any[]

Parameters:

Name Type Description
fns CombinatorFunction | [CombinatorFunction, any][] An array of function to combine, each in the form of (cb: (value: void)) => void
callback CombinatorCallback‹T› A callback that will return an Array of all the values this combinator has been applied to

Returns: UnsubscribePromise


# 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): Promise‹ApiPromise

Defined in api/src/promise/Api.ts:196

description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.

example

import Api from '@polkadot/api/promise';

Api.create().then(async (api) => {
  const timestamp = await api.query.timestamp.now();

  console.log(`lastest block timestamp ${timestamp}`);
});
1
2
3
4
5
6
7

Parameters:

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

Returns: Promise‹ApiPromise