@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.subscribeNewHead((header) => {
console.log(`Chain is at #${header.blockNumber}`);
});
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)`);
});
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.accountNonce(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}`);
});
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Hierarchy
ApiBase<CodecResult, SubscriptionResult>
↳ ApiPromise
Implements
Constructors
constructor
⊕ new ApiPromise(options?: ApiOptions | ProviderInterface): ApiPromise
Overrides ApiBase.constructor
Defined in promise/Api.ts:127
description: Creates an instance of the ApiPromise class
example:
import Api from '@polkadot/api/promise';
new Api().isReady.then((api) => {
api.rpc.subscribeNewHead((header) => {
console.log(`new block #${header.blockNumber.toNumber()}`);
});
});
2
3
4
5
6
7
Parameters:
| Name | Type | Description |
|---|---|---|
Optional options | ApiOptions | ProviderInterface | Options to create an instance. This can be either ApiOptions or an [[WsProvider]]. |
Returns: ApiPromise
Accessors
derive
get derive(): Derive<CodecResult, SubscriptionResult>
Defined in Base.ts:196
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);
});
2
3
Returns: Derive<CodecResult, SubscriptionResult>
genesisHash
get genesisHash(): Hash
Inherited from ApiBase.genesisHash
Defined in Base.ts:132
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 ApiBase.hasSubscriptions
Defined in Base.ts:141
description: true when subscriptions are supported
Returns: boolean
isReady
get isReady(): Promise<ApiPromise>
Defined in promise/Api.ts:161
description: Promise that returns the first time we are connected and loaded
Returns: Promise<ApiPromise>
libraryInfo
get libraryInfo(): string
Inherited from ApiBase.libraryInfo
Defined in Base.ts:148
description: The library information name & version (from package.json)
Returns: string
query
get query(): QueryableStorage<CodecResult, SubscriptionResult>
Defined in Base.ts:216
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.accountNonce(<accountId>) (retrieving the associated nonce for an account), takes the AccountId as a parameter.
example:
api.query.balances.freeBalance(<accountId>, (balance) => {
console.log('new balance', balance);
});
2
3
Returns: QueryableStorage<CodecResult, SubscriptionResult>
rpc
get rpc(): DecoratedRpc<CodecResult, SubscriptionResult>
Defined in Base.ts:236
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 (usine known keys) and the submission of transactions.
example:
api.rpc.chain.subscribeNewHead((header) => {
console.log('new header', header);
});
2
3
Returns: DecoratedRpc<CodecResult, SubscriptionResult>
runtimeMetadata
get runtimeMetadata(): Metadata
Inherited from ApiBase.runtimeMetadata
Defined in Base.ts:155
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 ApiBase.runtimeVersion
Defined in Base.ts:164
description: Contains the version information for the current runtime.
Returns: RuntimeVersion
tx
get tx(): SubmittableExtrinsics<CodecResult, SubscriptionResult>
Defined in Base.ts:254
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.asFinalised.toHex());
});
2
3
4
5
Returns: SubmittableExtrinsics<CodecResult, SubscriptionResult>
type
get type(): ApiType
Defined in Base.ts:173
description: The type of this API instance, either 'rxjs' or 'promise'
Returns: ApiType
Methods
clone
▸ clone(): ApiPromise
Defined in promise/Api.ts:168
description: Returns a clone of this ApiPromise instance (new underlying provider connection)
Returns: ApiPromise
combineLatest
▸ combineLatest(fns: Array<CombinatorFunction | [CombinatorFunction, Array]>, callback: CombinatorCallback): SubscriptionResult
Defined in promise/Api.ts:195
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.subscribeNewHead,
[api.query.balances.freeBalance, address],
(cb) => api.query.system.accountNonce(address, cb)
], ([head, balance, nonce]) => {
console.log(`#${head.number}: You have ${balance} units, with ${nonce} transactions sent`);
});
2
3
4
5
6
7
8
9
10
Parameters:
| Name | Type | Description |
|---|---|---|
| fns | Array<CombinatorFunction | [CombinatorFunction, Array]> | An array of function to combine, each in the form of `(cb: (value: void)) => void` |
| callback | CombinatorCallback | A callback that will return an Array of all the values this combinator has been applied to |
Returns: SubscriptionResult
disconnect
▸ disconnect(): void
Implementation of ApiPromiseInterface.disconnect
Inherited from ApiBase.disconnect
Defined in Base.ts:263
description: Disconnect from the underlying provider, halting all comms
Returns: void
on
▸ on(type: ApiInterface$Events, handler: function): this
Defined in Base.ts:286
description: Attach an eventemitter handler to listen to a specific event
example:
api.on('connected', () => {
console.log('API has been connected to the endpoint');
});
api.on('disconnected', () => {
console.log('API has been disconnected from the endpoint');
});
2
3
4
5
6
7
Parameters:
| Name | Type | Description |
|---|---|---|
| type | ApiInterface$Events | 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. |
Returns: this
once
▸ once(type: ApiInterface$Events, handler: function): this
Defined in Base.ts:311
description: Attach an one-time eventemitter handler to listen to a specific event
example:
api.once('connected', () => {
console.log('API has been connected to the endpoint');
});
api.once('disconnected', () => {
console.log('API has been disconnected from the endpoint');
});
2
3
4
5
6
7
Parameters:
| Name | Type | Description |
|---|---|---|
| type | ApiInterface$Events | 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. |
Returns: this
registerTypes
▸ registerTypes(types?: RegistryTypes): void
Implementation of ApiPromiseInterface.registerTypes
Inherited from ApiBase.registerTypes
Defined in Base.ts:320
description: Register additional user-defined of chain-specific types in the type registry
Parameters:
| Name | Type |
|---|---|
Optional types | RegistryTypes |
Returns: void
setSigner
▸ setSigner(signer: Signer): void
Implementation of ApiPromiseInterface.setSigner
Inherited from ApiBase.setSigner
Defined in Base.ts:180
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
<Static> create
▸ create(options?: ApiOptions | ProviderInterface): Promise<ApiPromise>
Defined in promise/Api.ts:125
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}`);
});
2
3
4
5
6
7
Parameters:
| Name | Type | Default value | Description |
|---|---|---|---|
Default value options | ApiOptions | ProviderInterface | {} | options that is passed to the class contructor. Can be either ApiOptions or a provider (see the constructor arguments) |
Returns: Promise<ApiPromise>