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.
example:
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.newHead().subscribe((header) => {
console.log(`Chain is at #${header.blockNumber}`);
});
Subscribing to chain state -
import { ApiRx } from '@polkadot/api';
import WsProvider from '@polkadot/rpc-provider/ws';
import { combineLatest } from 'rxjs';
let last = 0;
// initialise via isReady & new with specific non-local endpoint
new ApiRx(new WsProvider('wss://example.com:9944'))
.isReady
.pipe(
switchMap((api) =>
combineLatest([
api.st.timestamp.blockPeriod(),
api.st.timestamp.now()
])
)
.subscribe(([blockPeriod, 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 ApiRx from '@polkadot/api/rx';
// get api via Promise
const api = await ApiRx.create().toPromise();
// retrieve nonce for the account
api.st.system
.accountNonce(keyring.alice.address())
.pipe(
// 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((hash) => {
console.log(`submitted with hash ${hash}`);
});
Hierarchy
ApiBase<RpcRx, QueryableStorage, SubmittableExtrinsics>
↳ ApiRx
Implements
ApiBaseInterface<RpcRx,QueryableStorage,SubmittableExtrinsics>ApiRxInterface
Constructors
constructor
⊕ new ApiRx(wsProvider?: WsProvider): ApiRx
Overrides ApiBase.constructor
Defined in rx/index.ts:130
example:
import Api from '@polkadot/api/rx';
new Api().isReady.subscribe((api) => {
api.rpc.newHead().subscribe((header) => {
console.log(`new block #${header.blockNumber.toNumber()}`);
});
});
Parameters:
| Param | Type | Description |
|---|---|---|
Optional wsProvider |
WsProvider |
An optional WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port |
Returns: ApiRx
Accessors
genesisHash
getgenesisHash(): Hash
Inherited from ApiBase.genesisHash
Defined in Base.ts:68
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
isConnected
getisConnected(): Observable<boolean>
Defined in rx/index.ts:163
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:170
description: Observable that returns the first time we are connected and loaded
Returns: Observable<ApiRx>
rpc
getrpc(): RpcRx
Defined in Base.ts:105
description: Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions.
example:
api.rpc.chain
.newHead()
.subscribe((header) => {
console.log('new header', header);
});
Returns: RpcRx
runtimeMetadata
getruntimeMetadata(): RuntimeMetadata
Inherited from ApiBase.runtimeMetadata
Defined in Base.ts:77
description: Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.
Returns: RuntimeMetadata
runtimeVersion
getruntimeVersion(): RuntimeVersion
Inherited from ApiBase.runtimeVersion
Defined in Base.ts:86
description: Contains the version information for the current runtime.
Returns: RuntimeVersion
st
getst(): QueryableStorage
Defined in Base.ts:122
description: Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.
example:
api.st.balances
.freeBalance(<accountId>)
.subscribe((balance) => {
console.log('new balance', balance);
});
Returns: QueryableStorage
tx
gettx(): SubmittableExtrinsics
Defined in Base.ts:143
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>)
.sign(<keyPair>, <accountNonce>, <blockHash (optional)>)
.send()
.subscribe((status) => {
console.log('tx status', status);
});
Returns: SubmittableExtrinsics
Methods
on
▸ on(type: ApiInterface$Events, handler: function): void
Defined in Base.ts:149
Parameters:
| Param | Type |
|---|---|
| type | ApiInterface$Events |
| handler | function |
Returns: void
<Static> create
▸ create(wsProvider?: WsProvider): Observable<ApiRx>
Defined in rx/index.ts:128
description: Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.
example:
import Api from '@polkadot/api/rx';
Api.create().subscribe((api) => {
api.st.timestamp.now.subscribe((timestamp) => {
console.log(`lastest block timestamp ${timestamp}`);
});
});
Parameters:
| Param | Type | Description |
|---|---|---|
Optional wsProvider |
WsProvider |
Optional WebSocket provider that is passed to the class contructor |
Returns: Observable<ApiRx>