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}`);
});

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}`);
});
});

Hierarchy

  • ApiBase<"promise">
    • ApiPromise

Constructors

  • 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()}`);
    });
    });

    Parameters

    • Optional options: ApiOptions

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

    Returns ApiPromise

Properties

#private: any
#private: any
#private: any
#private: any
__phantom: BN
_call: QueryableCalls<"promise">
_consts: QueryableConsts<"promise">
_decorateMethod: DecorateMethod<"promise">

This is the one and only method concrete children classes need to implement. It's a higher-order function, which takes one argument method: Method extends (...args: any[]) => Observable<any> (and one optional options), and should return the user facing method. For example:

  • For ApiRx, decorateMethod should just be identity, because the input function is already an Observable
  • For ApiPromise, decorateMethod should return a function that takes all the parameters from method, adds an optional callback argument, and returns a Promise.

We could easily imagine other user-facing interfaces, which are simply implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon via decorateMethod.

_derive?: AllDerives<"promise">
_errors: DecoratedErrors<"promise">
_events: DecoratedEvents<"promise">
_extrinsicType: number
_extrinsics?: SubmittableExtrinsics<"promise">
_genesisHash?: Hash
_isConnected: BehaviorSubject<boolean>
_isReady: boolean
_options: ApiOptions
_query: QueryableStorage<"promise">
_queryMulti?: QueryableStorageMultiPromise<"promise">
_rpc?: DecoratedRpc<"promise", RpcInterface>
_rpcCore: RpcCore & RpcInterface
_runtimeChain?: Text
_runtimeMap: Record<`0x${string}`, string>
_runtimeMetadata?: Metadata
_runtimeVersion?: RuntimeVersion
_rx: ApiInterfaceRx
_rxDecorateMethod: (<Method>(method: Method) => Method)

Type declaration

    • <Method>(method: Method): Method
    • Put the this.onCall function of ApiRx here, because it is needed by api._rx.

      Type Parameters

      • Method extends AnyFunction

      Parameters

      • method: Method

      Returns Method

_type: ApiTypes

Accessors

  • get call(): QueryableCalls<ApiType>
  • Description

    Runtime call interfaces (currently untyped, only decorated via API options)

    Returns QueryableCalls<ApiType>

  • get consts(): QueryableConsts<ApiType>
  • 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())
    

    Returns QueryableConsts<ApiType>

  • get derive(): AllDerives<ApiType>
  • 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);
    });

    Returns AllDerives<ApiType>

  • get errors(): DecoratedErrors<ApiType>
  • Description

    Errors from metadata

    Returns DecoratedErrors<ApiType>

  • get events(): DecoratedEvents<ApiType>
  • Description

    Events from metadata

    Returns DecoratedEvents<ApiType>

  • get extrinsicVersion(): number
  • Description

    Returns the version of extrinsics in-use on this chain

    Returns number

  • get genesisHash(): Hash
  • 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

  • get hasSubscriptions(): boolean
  • Returns

    true if the API operates with subscriptions

    Returns boolean

  • get isConnected(): boolean
  • Description

    true is the underlying provider is connected

    Returns boolean

  • get isReady(): Promise<ApiPromise>
  • Description

    Promise that resolves the first time we are connected and loaded

    Returns Promise<ApiPromise>

  • get isReadyOrError(): Promise<ApiPromise>
  • Description

    Promise that resolves if we can connect, or reject if there is an error

    Returns Promise<ApiPromise>

  • get libraryInfo(): string
  • Description

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

    Returns string

  • get query(): QueryableStorage<ApiType>
  • 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);
    });

    Returns QueryableStorage<ApiType>

  • get queryMulti(): QueryableStorageMulti<ApiType>
  • 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();
    }
    );

    Returns QueryableStorageMulti<ApiType>

  • get registry(): Registry
  • Description

    Return the current used registry

    Returns Registry

  • get rpc(): DecoratedRpc<ApiType, RpcInterface>
  • 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);
    });

    Returns DecoratedRpc<ApiType, RpcInterface>

  • get runtimeChain(): Text
  • Description

    Contains the chain information for the current node.

    Returns Text

  • get runtimeMetadata(): Metadata
  • 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

  • get runtimeVersion(): RuntimeVersion
  • Description

    Contains the version information for the current runtime.

    Returns RuntimeVersion

  • get rx(): Pick<ApiInterfaceRx, "tx" | "query" | "rpc">
  • Description

    The underlying Rx API interface

    Returns Pick<ApiInterfaceRx, "tx" | "query" | "rpc">

  • get stats(): ProviderStats
  • Description

    Returns the underlying provider stats

    Returns ProviderStats

  • get supportMulti(): boolean
  • Returns

    true if the API decorate multi-key queries

    Returns boolean

  • get tx(): SubmittableExtrinsics<ApiType>
  • 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());
    });

    Returns SubmittableExtrinsics<ApiType>

  • get type(): ApiTypes
  • Description

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

    Returns ApiTypes

Methods

  • Parameters

    • result: DefinitionsCall
    • Optional additional: DefinitionsCall

    Returns void

  • Parameters

    • registry: VersionedRegistry<"promise">
    • fromEmpty: boolean
    • decoratedApi: ApiDecoration<"promise">
    • Optional blockHash: Uint8Array

    Returns FullDecoration<"promise">

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • registry: Registry
    • def: DefinitionCallNamed
    • stateCall: ((method: string, bytes: Uint8Array) => Observable<Codec>)
        • (method: string, bytes: Uint8Array): Observable<Codec>
        • Parameters

          • method: string
          • bytes: Uint8Array

          Returns Observable<Codec>

    • decorateMethod: DecorateMethod<ApiType>

    Returns AugmentedCall<ApiType>

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • __namedParameters: VersionedRegistry<ApiType>
    • decorateMethod: DecorateMethod<ApiType>
    • Optional blockHash: string | Uint8Array

    Returns QueryableCalls<ApiType>

  • Parameters

    • decorateMethod: DecorateMethod<"promise">

    Returns AllDerives<"promise">

  • Parameters

    • decorateMethod: DecorateMethod<"promise">

    Returns AllDerives<"rxjs">

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • __namedParameters: DecoratedMeta
    • decorateMethod: DecorateMethod<ApiType>

    Returns SubmittableExtrinsics<ApiType>

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • decorateMethod: DecorateMethod<ApiType>

    Returns QueryableStorageMulti<ApiType>

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • atApi: ApiDecoration<ApiType>
    • decorateMethod: DecorateMethod<ApiType>
    • blockHash: string | Uint8Array

    Returns QueryableStorageMulti<ApiType>

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • rpc: RpcCore & RpcInterface
    • decorateMethod: DecorateMethod<ApiType>
    • Optional input: Partial<DecoratedRpc<ApiType, RpcInterface>>

    Returns DecoratedRpc<ApiType, RpcInterface>

  • Type Parameters

    • ApiType extends ApiTypes

    Parameters

    • __namedParameters: DecoratedMeta
    • decorateMethod: DecorateMethod<ApiType>
    • Optional blockHash: Uint8Array

    Returns QueryableStorage<ApiType>

  • Parameters

    • registry: Registry
    • Optional blockHash: Uint8Array

    Returns ApiDecoration<"promise">

  • Parameters

    • methods: string[]
    • additional: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>

    Returns void

  • Parameters

    • exposed: string[]

    Returns void

  • Parameters

    • registry: Registry
    • specName: Text
    • Optional chain: string | Text

    Returns [string, DefinitionsCallEntry[]][]

  • Parameters

    • registry: VersionedRegistry<"promise">
    • Optional fromEmpty: boolean

    Returns void

  • Returns Promise<boolean>

  • Returns void

  • Description

    Returns a decorated API instance at a specific point in time

    Parameters

    • blockHash: string | Uint8Array
    • Optional knownVersion: RuntimeVersion

    Returns Promise<ApiDecoration<"promise">>

  • Description

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

    Returns ApiPromise

  • 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`);
    });

    Type Parameters

    • T extends any[] = any[]

    Parameters

    • 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

  • Description

    Connect from the underlying provider, halting all network traffic

    Returns Promise<void>

  • Description

    Creates an instance of a type as registered

    Type Parameters

    • T extends Codec = Codec

    • K extends string = string

    Parameters

    • type: K
    • Rest ...params: unknown[]

    Returns DetectCodec<T, K>

  • Description

    Disconnect from the underlying provider, halting all network traffic

    Returns Promise<void>

  • Parameters

    • type: ApiInterfaceEvents
    • Rest ...args: unknown[]

    Returns boolean

  • Description

    Finds the definition for a specific CallFunction based on the index supplied

    Parameters

    • callIndex: string | Uint8Array

    Returns CallFunction<AnyTuple, FunctionMetadataLatest>

  • Description

    Finds the definition for a specific RegistryError based on the index supplied

    Parameters

    • errorIndex: string | Uint8Array

    Returns RegistryError

  • Description

    Sets up a registry based on the block hash defined

    Parameters

    • blockHash: Uint8Array
    • Optional knownVersion: RuntimeVersion

    Returns Promise<VersionedRegistry<"promise">>

  • Deprecated

    backwards compatible endpoint for metadata injection, may be removed in the future (However, it is still useful for testing injection)

    Parameters

    • metadata: Metadata
    • Optional fromEmpty: boolean
    • Optional registry: Registry

    Returns void

  • 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);

    Parameters

    • type: ApiInterfaceEvents

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

    • handler: ((...args: any[]) => any)

      The callback to unregister.

        • (...args: any[]): any
        • Parameters

          • Rest ...args: any[]

          Returns any

    Returns ApiPromise

  • 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');
    });

    Parameters

    • type: ApiInterfaceEvents

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

    • handler: ((...args: any[]) => any)

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

        • (...args: any[]): any
        • Parameters

          • Rest ...args: any[]

          Returns any

    Returns ApiPromise

  • 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');
    });

    Parameters

    • type: ApiInterfaceEvents

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

    • handler: ((...args: any[]) => any)

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

        • (...args: any[]): any
        • Parameters

          • Rest ...args: any[]

          Returns any

    Returns ApiPromise

  • Description

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

    Parameters

    • Optional types: RegistryTypes

    Returns void

  • Description

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

    Parameters

    • signer: Signer

    Returns void

  • Description

    Signs a raw signer payload, string or Uint8Array

    Parameters

    • address: string | KeyringSigner
    • data: SignerPayloadRawBase
    • Optional __namedParameters: SignerRawOptions

    Returns Promise<string>

  • 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}`);
    });

    Parameters

    • Optional options: ApiOptions

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

    Returns Promise<ApiPromise>

Generated using TypeDoc