@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.subscribeNewHead().subscribe((header) => {
console.log(`Chain is at #${header.blockNumber}`);
});
Subscribing to chain state -
import { combineLatest } from 'rxjs';
import { pairwise, switchMap } from 'rxjs/operators';
import { ApiRx } from '@polkadot/api';
import { WsProvider } from '@polkadot/rpc-provider';
// 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)`);
});
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
.accountNonce(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, type }) => {
if (type === 'Finalised') {
console.log('Completed at block hash', status.asFinalised.toHex());
}
});
Hierarchy
↳ ApiRx
Implements
Constructors
constructor
⊕ new ApiRx(provider?: ApiOptions | ProviderInterface): ApiRx
Overrides ApiBase.constructor
Defined in rx/index.ts:142
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.subscribeNewHead()
))
.subscribe((header) => {
console.log(`new block #${header.blockNumber.toNumber()}`);
});
Parameters:
| Name | Type | |
|---|---|---|
Optional provider |
ApiOptions | ProviderInterface |
Returns: ApiRx
Accessors
derive
getderive(): Derive<RxResult, RxResult>
Defined in Base.ts:179
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: Derive<RxResult, RxResult>
genesisHash
getgenesisHash(): Hash
Inherited from ApiBase.genesisHash
Defined in Base.ts:122
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
gethasSubscriptions(): boolean
Inherited from ApiBase.hasSubscriptions
Defined in Base.ts:131
description: true when subscriptions are supported
Returns: boolean
isConnected
getisConnected(): Observable<boolean>
Defined in rx/index.ts:182
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
getisReady(): Observable<ApiRx>
Defined in rx/index.ts:189
description: Observable that returns the first time we are connected and loaded
Returns: Observable<ApiRx>
query
getquery(): QueryableStorage<RxResult, RxResult>
Defined in Base.ts:199
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);
});
Returns: QueryableStorage<RxResult, RxResult>
rpc
getrpc(): DecoratedRpc<RxResult, RxResult>
Defined in Base.ts:219
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);
});
Returns: DecoratedRpc<RxResult, RxResult>
runtimeMetadata
getruntimeMetadata(): Metadata
Inherited from ApiBase.runtimeMetadata
Defined in Base.ts:138
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
getruntimeVersion(): RuntimeVersion
Inherited from ApiBase.runtimeVersion
Defined in Base.ts:147
description: Contains the version information for the current runtime.
Returns: RuntimeVersion
tx
gettx(): SubmittableExtrinsics<RxResult, RxResult>
Defined in Base.ts:237
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());
});
Returns: SubmittableExtrinsics<RxResult, RxResult>
type
gettype(): ApiType
Defined in Base.ts:156
description: The type of this API instance, either 'rxjs' or 'promise'
Returns: ApiType
Methods
clone
▸ clone(): ApiRx
Defined in rx/index.ts:196
description: Returns a clone of this ApiRx instance (new underlying provider connection)
Returns: ApiRx
disconnect
▸ disconnect(): void
Implementation of ApiRxInterface.disconnect
Inherited from ApiBase.disconnect
Defined in Base.ts:246
description: Disconnect from the underlying provider, halting all comms
Returns: void
on
▸ on(type: ApiInterface$Events, handler: function): this
Defined in Base.ts:269
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');
});
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:294
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');
});
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 ApiRxInterface.registerTypes
Inherited from ApiBase.registerTypes
Defined in Base.ts:303
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 ApiRxInterface.setSigner
Inherited from ApiBase.setSigner
Defined in Base.ts:163
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): Observable<ApiRx>
Defined in rx/index.ts:140
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.subscribeNewHead()
))
.subscribe((header) => {
console.log(`new block #${header.blockNumber.toNumber()}`);
});
Parameters:
| Name | Type | Description | |
|---|---|---|---|
Optional options |
ApiOptions | ProviderInterface |
options that is passed to the class contructor. Can be either ApiOptions or [[WsProvider]] |
Returns: Observable<ApiRx>