Creates an instance of the ApiPromise class
import Api from '@polkadot/api/promise';
new Api().isReady.then((api) => {
api.rpc.subscribeNewHeads((header) => {
console.log(`new block #${header.number.toNumber()}`);
});
});
Optional
options: ApiOptionsOptions to create an instance. This can be either ApiOptions or an WsProvider.
Private
#privatePrivate
#privatePrivate
#privatePrivate
#privateProtected
__phantomProtected
_callProtected
_constsProtected
_decorateThis 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:
decorateMethod
should just be identity, because the input
function is already an ObservabledecorateMethod
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
.
Protected
Optional
_deriveProtected
_errorsProtected
_eventsProtected
_extrinsicProtected
Optional
_extrinsicsProtected
Optional
_genesisProtected
_isProtected
_isProtected
Readonly
_optionsProtected
_queryProtected
Optional
_queryProtected
Optional
_rpcProtected
_rpcProtected
Optional
_runtimeProtected
_runtimeProtected
Optional
_runtimeProtected
Optional
_runtimeProtected
_rxProtected
_rxPut the this.onCall
function of ApiRx here, because it is needed by
api._rx
.
Protected
_typeRuntime call interfaces (currently untyped, only decorated via API options)
Contains the parameter types (constants) of all modules.
The values are instances of the appropriate type and are accessible using section
.constantName
,
console.log(api.consts.democracy.enactmentPeriod.toString())
Derived results that are injected into the API, allowing for combinations of various query results.
api.derive.chain.bestNumber((number) => {
console.log('best number', number);
});
Errors from metadata
Events from metadata
Returns the version of extrinsics in-use on this chain
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.
true
if the API operates with subscriptions
true is the underlying provider is connected
Promise that resolves the first time we are connected and loaded
Promise that resolves if we can connect, or reject if there is an error
The library information name & version (from package.json)
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.
api.query.system.account(<accountId>, ([nonce, balance]) => {
console.log('new free balance', balance.free, 'new nonce', nonce);
});
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.
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();
}
);
Return the current used registry
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.
api.rpc.chain.subscribeNewHeads((header) => {
console.log('new header', header);
});
Contains the chain information for the current node.
Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.
Contains the version information for the current runtime.
The underlying Rx API interface
Returns the underlying provider stats
true
if the API decorate multi-key queries
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.
api.tx.balances
.transfer(<recipientId>, <balance>)
.signAndSend(<keyPair>, ({status}) => {
console.log('tx status', status.asFinalized.toHex());
});
The type of this API instance, either 'rxjs' or 'promise'
Protected
_addProtected
_createOptional
blockHash: Uint8ArrayProtected
_decorateProtected
_decorateOptional
blockHash: string | Uint8ArrayProtected
_decorateProtected
_decorateProtected
_decorateProtected
_decorateProtected
_decorateProtected
_decorateOptional
input: Partial<DecoratedRpc<ApiType, RpcInterface>>Protected
_decorateOptional
blockHash: Uint8ArrayProtected
_emptyProtected
_filterProtected
_filterProtected
_getProtected
_injectProtected
_loadProtected
_unsubscribeReturns a clone of this ApiPromise instance (new underlying provider connection)
Creates a combinator that can be used to combine the latest results from multiple subscriptions
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`);
});
An array of function to combine, each in the form of (cb: (value: void)) => void
A callback that will return an Array of all the values this combinator has been applied to
Protected
emitbackwards compatible endpoint for metadata injection, may be removed in the future (However, it is still useful for testing injection)
Optional
fromEmpty: booleanOptional
registry: RegistryRemove the given eventemitter handler
const handler = (): void => {
console.log('Connected !);
};
// Start listening
api.on('connected', handler);
// Stop listening
api.off('connected', handler);
The type of event the callback was attached to. Available events are connected
, disconnected
, ready
and error
The callback to unregister.
Rest
...args: any[]Attach an eventemitter handler to listen to a specific event
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');
});
The type of event to listen to. Available events are connected
, disconnected
, ready
and error
The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.
Rest
...args: any[]Attach an one-time eventemitter handler to listen to a specific event
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');
});
The type of event to listen to. Available events are connected
, disconnected
, ready
and error
The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.
Rest
...args: any[]Signs a raw signer payload, string or Uint8Array
Optional
__namedParameters: SignerRawOptionsStatic
createCreates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
import Api from '@polkadot/api/promise';
Api.create().then(async (api) => {
const timestamp = await api.query.timestamp.now();
console.log(`lastest block timestamp ${timestamp}`);
});
Optional
options: ApiOptionsoptions that is passed to the class contructor. Can be either ApiOptions or a provider (see the constructor arguments)
Generated using TypeDoc
@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 -
Subscribing to chain state -
Submitting a transaction -