Refactor api-promise/rx (#566)

* Use a generic abstract OnCall

* Add OnCall for Promise

* First run at fixing extrinsics

* Fix types

* Make submittable extrinsic work

* Move file

* Make derive work

* Fix types

* Only call metadata once

* Make tests pass

* Put event emitter in apirx

* Fix small bugs

* Fix tests

* Fix bug decorateStorage

* Make tests pass for tx

* Move rpc base to apirx

* Fix lint

* Fix small bugs

* Fix bug with isSubscription

* Fix codeclimate

* Revert

* Add tslint disable line

* Fix lint

* Skip e2e

* Typo

* Lint

* Re-add combinator back

* Add ._rx in Base

* Make extrinsics work

* Update derivex

* Fix bug lint

* Fix circular dep

* Fix bug e2e

* Remove useless check

* Add description comment

* Clean stuff

* Move assert to Base

* Bump version, update CHANGELOG

* Make _rx private

* Private emit
This commit is contained in:
Amaury Martiny
2019-01-16 15:42:59 +01:00
committed by Jaco Greeff
parent 38d2d06772
commit d07ed8ac38
49 changed files with 523 additions and 617 deletions
+4
View File
@@ -1,3 +1,7 @@
# 0.40.1
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
# 0.39.1
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "0.39.12"
"version": "0.40.0"
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "0.39.12",
"version": "0.40.0",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -31,8 +31,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/api": "^0.39.12",
"@polkadot/types": "^0.39.12",
"@polkadot/api": "^0.40.0",
"@polkadot/types": "^0.40.0",
"@types/memoizee": "^0.4.2",
"@types/rx": "^4.1.1",
"memoizee": "^0.4.14",
@@ -4,7 +4,7 @@
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { decodeAddress } from '@polkadot/keyring';
import { AccountId, AccountIndex } from '@polkadot/types/index';
@@ -14,7 +14,7 @@ import { drr } from '../util/drr';
export type IdAndIndex = [AccountId | undefined, AccountIndex | undefined];
export function accountIdAndIndex (api: ApiRx) {
export function accountIdAndIndex (api: ApiInterface$Rx) {
return (address: AccountId | AccountIndex | string | null | undefined)
: Observable<(AccountIndex | AccountId | undefined)[]> => {
try {
@@ -4,13 +4,13 @@
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId, AccountIndex } from '@polkadot/types/index';
import { accountIndexes, AccountIndexes } from './accountIndexes';
import { drr } from '../util/drr';
export function accountIdToIndex (api: ApiRx) {
export function accountIdToIndex (api: ApiInterface$Rx) {
return (accountId: AccountId | string): Observable<AccountIndex> =>
accountIndexes(api)()
.pipe(
@@ -4,14 +4,14 @@
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { ENUMSET_SIZE } from '@polkadot/types/AccountIndex';
import { Vector } from '@polkadot/types/codec';
import { AccountId, AccountIndex } from '@polkadot/types/index';
import { drr } from '../util/drr';
export function accountIndexToId (api: ApiRx) {
export function accountIndexToId (api: ApiInterface$Rx) {
return (accountIndex: AccountIndex | string): Observable<AccountId> => {
const _accountIndex = accountIndex instanceof AccountIndex
? accountIndex
@@ -5,7 +5,7 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { ENUMSET_SIZE } from '@polkadot/types/AccountIndex';
import { AccountId, AccountIndex } from '@polkadot/types/index';
@@ -13,7 +13,7 @@ import { drr } from '../util/drr';
export type AccountIndexes = { [index: string]: AccountIndex };
export function accountIndexes (api: ApiRx) {
export function accountIndexes (api: ApiInterface$Rx) {
return (): Observable<AccountIndexes> =>
(api.query.balances.nextEnumSet() as Observable<AccountIndex>)
.pipe(
+2 -2
View File
@@ -5,11 +5,11 @@
import BN from 'bn.js';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { drr } from '../util/drr';
export function fees (api: ApiRx) {
export function fees (api: ApiInterface$Rx) {
return () =>
combineLatest(
api.query.balances.creationFee(),
@@ -5,7 +5,7 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId, Balance } from '@polkadot/types/index';
import { DerivedBalances } from '../types';
@@ -13,7 +13,7 @@ import { drr } from '../util/drr';
import { votingBalance } from './votingBalance';
import { votingBalancesNominatorsFor } from './votingBalancesNominatorsFor';
export function validatingBalance (api: ApiRx) {
export function validatingBalance (api: ApiInterface$Rx) {
return (address: AccountId | string): Observable<DerivedBalances> =>
combineLatest(
votingBalance(api)(address),
@@ -4,14 +4,14 @@
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId } from '@polkadot/types/index';
import { DerivedBalancesMap } from '../types';
import { drr } from '../util/drr';
import { validatingBalance } from './validatingBalance';
export function validatingBalances (api: ApiRx) {
export function validatingBalances (api: ApiInterface$Rx) {
return (...params: Array<any>): Observable<DerivedBalancesMap> => {
const accountIds: Array<AccountId | string> = params.slice(0, params.length - 1);
@@ -4,7 +4,7 @@
import { combineLatest, of, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId, AccountIndex, Balance } from '@polkadot/types/index';
import { accountIdAndIndex } from './accountIdAndIndex';
@@ -13,7 +13,7 @@ import { drr } from '../util/drr';
const EMPTY_ACCOUNT = new AccountId(new Uint8Array(32));
export function votingBalance (api: ApiRx) {
export function votingBalance (api: ApiInterface$Rx) {
return (address: AccountIndex | AccountId | string): Observable<DerivedBalances> =>
accountIdAndIndex(api)(address).pipe(
switchMap(([accountId]) =>
@@ -3,14 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { combineLatest, Observable } from 'rxjs';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId, AccountIndex } from '@polkadot/types/index';
import { DerivedBalances } from '../types';
import { drr } from '../util/drr';
import { votingBalance } from './votingBalance';
export function votingBalances (api: ApiRx) {
export function votingBalances (api: ApiInterface$Rx) {
return (...params: Array<any>): Observable<Array<DerivedBalances>> => {
const addresses: Array<AccountIndex | AccountId | string> = params.slice(0, params.length - 1);
@@ -4,14 +4,14 @@
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId } from '@polkadot/types/index';
import { DerivedBalances } from '../types';
import { drr } from '../util/drr';
import { votingBalances } from './votingBalances';
export function votingBalancesNominatorsFor (api: ApiRx) {
export function votingBalancesNominatorsFor (api: ApiInterface$Rx) {
return (accountId: AccountId | string): Observable<Array<DerivedBalances>> =>
(api.query.staking.nominatorsFor(accountId) as Observable<Array<AccountId | undefined | null> | undefined>).pipe(
map((nominators) => nominators || []),
+3 -3
View File
@@ -4,7 +4,7 @@
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { BlockNumber, Header } from '@polkadot/types/index';
import { drr } from '../util/drr';
@@ -12,9 +12,9 @@ import { drr } from '../util/drr';
/**
* Get the latest block number.
*/
export function bestNumber (api: ApiRx) {
export function bestNumber (api: ApiInterface$Rx) {
return (): Observable<BlockNumber> =>
api.rpc.chain.subscribeNewHead()
(api.rpc.chain.subscribeNewHead() as Observable<Header>)
.pipe(
filter((header: Header) => header && !!header.blockNumber),
map(({ blockNumber }: Header) => blockNumber),
@@ -4,7 +4,7 @@
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { BlockNumber, Header } from '@polkadot/types/index';
import { drr } from '../util/drr';
@@ -12,9 +12,9 @@ import { drr } from '../util/drr';
/**
* Get the latest finalised block number.
*/
export function bestNumberFinalised (api: ApiRx) {
export function bestNumberFinalised (api: ApiInterface$Rx) {
return (): Observable<BlockNumber> =>
api.rpc.chain.subscribeFinalisedHeads()
(api.rpc.chain.subscribeFinalisedHeads() as Observable<Header>)
.pipe(
filter((header: Header) => header && !!header.blockNumber),
map(({ blockNumber }: Header) => blockNumber),
@@ -5,12 +5,12 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import { filter } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { ReferendumInfo } from '@polkadot/types/index';
import { drr } from '../util/drr';
export function referendumInfos (api: ApiRx) {
export function referendumInfos (api: ApiInterface$Rx) {
return (...params: Array<any>): Observable<Array<ReferendumInfo>> => {
const ids: Array<BN | number> = params.slice(0, params.length - 1);
@@ -5,7 +5,7 @@
import BN from 'bn.js';
import { combineLatest, Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { Vector } from '@polkadot/types/codec';
import { AccountId, Balance, Vote } from '@polkadot/types/index';
@@ -14,7 +14,7 @@ import { drr } from '../util/drr';
import { votes } from './votes';
import { votingBalances } from '../balances/votingBalances';
export function referendumVotesFor (api: ApiRx) {
export function referendumVotesFor (api: ApiInterface$Rx) {
return (referendumId: BN | number): Observable<Array<DerivedReferendumVote>> =>
(api.query.democracy.votersFor(referendumId) as Observable<Vector<AccountId>>).pipe(
switchMap((votersFor) =>
@@ -4,13 +4,13 @@
import { combineLatest, Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { ReferendumIndex, ReferendumInfo } from '@polkadot/types/index';
import { referendumInfos } from './referendumInfos';
import { drr } from '../util/drr';
export function referendums (api: ApiRx) {
export function referendums (api: ApiInterface$Rx) {
return (): Observable<Array<ReferendumInfo>> =>
(combineLatest(
api.query.democracy.nextTally(),
+2 -2
View File
@@ -4,12 +4,12 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { AccountId, Vote } from '@polkadot/types/index';
import { drr } from '../util/drr';
export function votes (api: ApiRx) {
export function votes (api: ApiInterface$Rx) {
return (referendumId: BN, ...accountIds: Array<AccountId>): Observable<Array<Vote>> =>
combineLatest(
accountIds.map(
+2 -1
View File
@@ -4,11 +4,12 @@
import { Observable } from 'rxjs';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import MockProvider from '@polkadot/rpc-provider/mock';
import { Derive } from './index';
const testFunction = (api: ApiRx) => {
const testFunction = (api: ApiInterface$Rx) => {
return <
Section extends keyof Derive,
Method extends keyof (typeof api.derive[Section])
+2 -2
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import * as balances from './balances';
import * as chain from './chain';
@@ -28,7 +28,7 @@ export interface Derive {
session: ReturnTypes<typeof session>;
}
export default function decorateDerive (api: ApiRx): Derive {
export default function decorateDerive (api: ApiInterface$Rx): Derive {
const derive = {} as Derive;
Object.keys(functions).forEach((sectionName: string) => {
+2 -2
View File
@@ -5,12 +5,12 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { BlockNumber } from '@polkadot/types/index';
import { drr } from '../util/drr';
export function eraLength (api: ApiRx) {
export function eraLength (api: ApiInterface$Rx) {
return (): Observable<BN> =>
(combineLatest(
api.query.session.sessionLength(),
@@ -5,13 +5,13 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { BlockNumber } from '@polkadot/types/index';
import { sessionProgress } from './sessionProgress';
import { drr } from '../util/drr';
export function eraProgress (api: ApiRx) {
export function eraProgress (api: ApiInterface$Rx) {
return (): Observable<BN> =>
(combineLatest(
sessionProgress(api)(),
@@ -5,13 +5,13 @@
import BN from 'bn.js';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { BlockNumber } from '@polkadot/types/index';
import { bestNumber } from '../chain';
import { drr } from '../util/drr';
export function sessionProgress (api: ApiRx) {
export function sessionProgress (api: ApiInterface$Rx) {
return (): Observable<BN> =>
combineLatest(
bestNumber(api)(),
+4 -4
View File
@@ -2,13 +2,13 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { cache } from './cache';
describe('cache', () => {
const f = cache((api: ApiRx) => (a: number, b: number) => [api, a, b]);
const api = {} as ApiRx;
const f = cache((api: ApiInterface$Rx) => (a: number, b: number) => [api, a, b]);
const api = {} as ApiInterface$Rx;
it('should hit cache when all arguments are the same', () => {
const first = f(api)(2, 3);
@@ -21,7 +21,7 @@ describe('cache', () => {
const first = f(api)(2, 3);
const second1 = f(api)(5, 3);
const second2 = f(api)(2, 5);
const second3 = f({} as ApiRx)(2, 3);
const second3 = f({} as ApiInterface$Rx)(2, 3);
expect(first).not.toBe(second1);
expect(first).not.toBe(second2);
+3 -3
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import memoizee from 'memoizee';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
/**
* Create memoization for a 2-currified function.
@@ -12,7 +12,7 @@ import ApiRx from '@polkadot/api/rx';
* @param map - The Map used to cache function returns.
* @example
* ```javascript
* const f = (api: ApiRx) => (b: number) => a * b;
* const f = (api: ApiInterface$Rx) => (b: number) => a * b;
* const cached = cache(f);
* f(api)(1, 2);
* f(api)(1); // Cache not hit
@@ -20,7 +20,7 @@ import ApiRx from '@polkadot/api/rx';
* f(api)(1, 2); // Cache hit
* ```
*/
export const cache = (fn: Function, map = new WeakMap()) => (api: ApiRx) => {
export const cache = (fn: Function, map = new WeakMap()) => (api: ApiInterface$Rx) => {
if (!map.has(api)) {
const innerFn = fn(api);
map.set(api, memoizee(innerFn));
+7 -5
View File
@@ -4,29 +4,31 @@
import BN from 'bn.js';
import ApiRx from '@polkadot/api/rx';
import { ApiInterface$Rx } from '@polkadot/api/types';
import { BlockNumber } from '@polkadot/types/index';
describe.skip('derive e2e', () => {
let api: ApiRx;
let api: ApiInterface$Rx;
beforeAll(() => {
jest.setTimeout(30000);
});
beforeEach(async () => {
beforeEach(async (done) => {
api = await ApiRx.create().toPromise();
done();
});
it('derive.chain.bestNumber', async (done) => {
api.derive.chain.bestNumber().subscribe((blockNumber: BlockNumber) => {
api.derive.chain.bestNumber().subscribe((blockNumber) => {
expect(blockNumber instanceof BlockNumber).toBe(true);
expect(blockNumber.gten(0)).toBe(true);
expect((blockNumber as BlockNumber).gten(0)).toBe(true);
done();
});
});
it('derive.session.sessionProgress', async (done) => {
api.derive.session.sessionProgress().subscribe((progress: BN) => {
api.derive.session.sessionProgress().subscribe((progress) => {
expect(progress instanceof BN).toBe(true);
done();
});
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "0.39.12",
"version": "0.40.0",
"description": "An RxJS wrapper around the Polkadot JS RPC",
"main": "index.js",
"keywords": [
@@ -30,12 +30,12 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/api-derive": "^0.39.12",
"@polkadot/extrinsics": "^0.39.12",
"@polkadot/rpc-provider": "^0.39.12",
"@polkadot/rpc-rx": "^0.39.12",
"@polkadot/storage": "^0.39.12",
"@polkadot/types": "^0.39.12",
"@polkadot/api-derive": "^0.40.0",
"@polkadot/extrinsics": "^0.40.0",
"@polkadot/rpc-provider": "^0.40.0",
"@polkadot/rpc-rx": "^0.40.0",
"@polkadot/storage": "^0.40.0",
"@polkadot/types": "^0.40.0",
"@types/rx": "^4.1.1",
"rxjs": "^6.3.3"
}
+208 -28
View File
@@ -3,18 +3,33 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { ApiBaseInterface, ApiInterface$Events, ApiOptions } from './types';
import { Storage } from '@polkadot/storage/types';
import {
ApiBaseInterface, ApiInterface$Rx, ApiInterface$Events, ApiOptions,
DecoratedRpc, DecoratedRpc$Section,
Derive, DeriveSection,
OnCallFunction,
QueryableModuleStorage, QueryableStorage, QueryableStorageFunction,
SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics
} from './types';
import EventEmitter from 'eventemitter3';
import Rpc from '@polkadot/rpc-core/index';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import decorateDerive, { Derive as DeriveInterface } from '@polkadot/api-derive/index';
import extrinsicsFromMeta from '@polkadot/extrinsics/fromMetadata';
import { Storage } from '@polkadot/storage/types';
import RpcBase from '@polkadot/rpc-core/index';
import RpcRx from '@polkadot/rpc-rx/index';
import storageFromMeta from '@polkadot/storage/fromMetadata';
import registry from '@polkadot/types/codec/typeRegistry';
import { Event, Hash, Metadata, Method, RuntimeVersion } from '@polkadot/types/index';
import { ModulesWithMethods } from '@polkadot/types/Method';
import { MethodFunction, ModulesWithMethods } from '@polkadot/types/Method';
import { StorageFunction } from '@polkadot/types/StorageKey';
import { Codec } from '@polkadot/types/types';
import { assert, isFunction, isObject, isUndefined, logger } from '@polkadot/util';
import SubmittableExtrinsic from './SubmittableExtrinsic';
type MetaDecoration = {
callIndex?: Uint8Array,
meta: any,
@@ -23,19 +38,34 @@ type MetaDecoration = {
toJSON: () => any
};
const l = logger('api');
const INIT_ERROR = `Api needs to be initialised before using, listen on 'ready'`;
export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S, E> {
const l = logger('api/decorator');
/**
* Put the `this.onCall` function of ApiRx here, because it is needed by
* `api._rx`.
*/
function rxOnCall (
method: OnCallFunction<Observable<Codec | undefined | null>>,
params: Array<any>,
_isSubscription?: boolean
): Observable<Codec | undefined | null> {
return method(...params);
}
export default abstract class ApiBase<OnCall> implements ApiBaseInterface<OnCall> {
private _eventemitter: EventEmitter;
protected _extrinsics?: E;
protected _genesisHash?: Hash;
protected _query?: S;
protected _rpc: R;
protected _rpcBase: Rpc;
protected _runtimeMetadata?: Metadata;
protected _runtimeVersion?: RuntimeVersion;
private _derive?: Derive<OnCall>;
private _extrinsics?: SubmittableExtrinsics<OnCall>;
private _genesisHash?: Hash;
private _query?: QueryableStorage<OnCall>;
private _rpc: DecoratedRpc<OnCall>;
protected _rpcBase: RpcBase; // FIXME These two could be merged
protected _rpcRx: RpcRx; // FIXME These two could be merged
private _runtimeMetadata?: Metadata;
private _runtimeVersion?: RuntimeVersion;
private _rx: Partial<ApiInterface$Rx> = {};
/**
* @description Create an instance of the class
@@ -61,8 +91,13 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
: provider as ApiOptions;
this._eventemitter = new EventEmitter();
this._rpcBase = new Rpc(options.provider);
this._rpc = this.decorateRpc(this._rpcBase);
this._rpcBase = new RpcBase(options.provider);
assert(this.hasSubscriptions, 'Api can only be used with a provider supporting subscriptions');
this._rpcRx = new RpcRx(options.provider);
this._rpc = this.decorateRpc(this._rpcRx, this.onCall);
this._rx.rpc = this.decorateRpc(this._rpcRx, rxOnCall);
if (options.types) {
registry.register(options.types);
@@ -105,6 +140,24 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
return this._runtimeVersion as RuntimeVersion;
}
/**
* @description Derived results that are injected into the API, allowing for combinations of various query results.
*
* @example
* <BR>
*
* ```javascript
* api.derive.chain.bestNumber((number) => {
* console.log('best number', number);
* });
* ```
*/
get derive (): Derive<OnCall> {
assert(!isUndefined(this._derive), INIT_ERROR);
return this._derive as Derive<OnCall>;
}
/**
* @description Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.
*
@@ -119,10 +172,10 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
* });
* ```
*/
get query (): S {
get query (): QueryableStorage<OnCall> {
assert(!isUndefined(this._query), INIT_ERROR);
return this._query as S;
return this._query as QueryableStorage<OnCall>;
}
/**
@@ -139,7 +192,7 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
* });
* ```
*/
get rpc (): R {
get rpc (): DecoratedRpc<OnCall> {
return this._rpc;
}
@@ -158,10 +211,10 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
* });
* ```
*/
get tx (): E {
get tx (): SubmittableExtrinsics<OnCall> {
assert(!isUndefined(this._extrinsics), INIT_ERROR);
return this._extrinsics as E;
return this._extrinsics as SubmittableExtrinsics<OnCall>;
}
/**
@@ -214,7 +267,7 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
return this;
}
protected emit (type: ApiInterface$Events, ...args: Array<any>): void {
private emit (type: ApiInterface$Events, ...args: Array<any>): void {
this._eventemitter.emit(type, ...args);
}
@@ -251,8 +304,14 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
const extrinsics = extrinsicsFromMeta(this.runtimeMetadata);
const storage = storageFromMeta(this.runtimeMetadata);
this._extrinsics = this.decorateExtrinsics(extrinsics);
this._query = this.decorateStorage(storage);
this._extrinsics = this.decorateExtrinsics(extrinsics, this.onCall);
this._query = this.decorateStorage(storage, this.onCall);
this._derive = this.decorateDerive(this._rx as ApiInterface$Rx, this.onCall);
this._rx.genesisHash = this._genesisHash;
this._rx.tx = this.decorateExtrinsics(extrinsics, rxOnCall);
this._rx.query = this.decorateStorage(storage, rxOnCall);
this._rx.derive = this.decorateDerive(this._rx as ApiInterface$Rx, rxOnCall);
Event.injectMetadata(this.runtimeMetadata);
Method.injectMethods(extrinsics);
@@ -265,7 +324,9 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
}
}
protected decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
protected abstract onCall (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean): OnCall;
private decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
output.meta = input.meta;
output.method = input.method;
output.section = input.section;
@@ -278,7 +339,126 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
return output;
}
protected abstract decorateRpc (rpc: Rpc): R;
protected abstract decorateExtrinsics (extrinsics: ModulesWithMethods): E;
protected abstract decorateStorage (storage: Storage): S;
private decorateRpc<T> (
rpc: RpcRx,
onCall: (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean) => T
): DecoratedRpc<T> {
return ['author', 'chain', 'state', 'system'].reduce((result, _sectionName) => {
const sectionName = _sectionName as keyof DecoratedRpc<T>;
result[sectionName] = Object.keys(rpc[sectionName]).reduce((section, methodName) => {
// FIXME Find a better way to know if a particular method is a subscription or not
const isSubscription = methodName.includes('subscribe');
const method = (...params: any[]) => onCall(rpc[sectionName][methodName], params, isSubscription);
section[methodName] = method;
return section;
}, {} as DecoratedRpc$Section<T>);
return result;
}, {} as DecoratedRpc<T>);
}
private decorateExtrinsics<T> (
extrinsics: ModulesWithMethods,
onCall: (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean) => T
): SubmittableExtrinsics<T> {
return Object.keys(extrinsics).reduce((result, sectionName) => {
const section = extrinsics[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[methodName] = this.decorateExtrinsicEntry(section[methodName], onCall);
return result;
}, {} as SubmittableModuleExtrinsics<T>);
return result;
}, {} as SubmittableExtrinsics<T>);
}
private decorateExtrinsicEntry<T> (
method: MethodFunction,
onCall: (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean) => T
): SubmittableExtrinsicFunction<T> {
const decorated: any = (...args: Array<any>): SubmittableExtrinsic<T> =>
new SubmittableExtrinsic(this._rx as ApiInterface$Rx, onCall, method(...args));
return this.decorateFunctionMeta(method, decorated) as SubmittableExtrinsicFunction<T>;
}
private decorateStorage<T> (
storage: Storage,
onCall: (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean) => T
): QueryableStorage<T> {
return Object.keys(storage).reduce((result, sectionName) => {
const section = storage[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[methodName] = this.decorateStorageEntry(section[methodName], onCall);
return result;
}, {} as QueryableModuleStorage<T>);
return result;
}, {} as QueryableStorage<T>);
}
private decorateStorageEntry<T> (
method: StorageFunction,
onCall: (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean) => T
): QueryableStorageFunction<T> {
const decorated: any = (...args: any): T => {
return onCall(
(...args: any) => this._rpcRx.state
.subscribeStorage([[method, args[0]]])
.pipe(
// errors can occur in the case of malformed methods + args
catchError(() => of([])),
// state_storage returns an array of values, since we have just subscribed to
// a single entry, we pull that from the array and return it as-is
map((result: Array<Codec | null | undefined> = []): Codec | null | undefined =>
result[0]
)
),
args
);
};
decorated.at = (hash: Hash, arg?: any): T =>
onCall(
arg => this._rpcRx.state
.getStorage([method, arg], hash)
.pipe(
// same as above (for single result), in the case of errors on creation, return `undefined`
catchError(() => of())
),
[arg]
);
return this.decorateFunctionMeta(method, decorated) as QueryableStorageFunction<T>;
}
private decorateDerive<T> (
apiRx: ApiInterface$Rx,
onCall: (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>, isSubscription?: boolean) => T
): Derive<T> {
const derive = decorateDerive(apiRx);
return Object.keys(derive).reduce((result, _sectionName) => {
const sectionName = _sectionName as keyof DeriveInterface;
result[sectionName] = Object.keys(derive[sectionName]).reduce((section, methodName) => {
const method = (...params: any[]) => onCall((derive[sectionName] as any)[methodName], params);
section[methodName] = method;
return section;
}, {} as DeriveSection<T>);
return result;
}, {} as Derive<T>);
}
}
+79
View File
@@ -0,0 +1,79 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeyringPair } from '@polkadot/keyring/types';
import { Extrinsic, ExtrinsicStatus, Index, Method, SignedBlock } from '@polkadot/types/index';
import { AnyNumber, AnyU8a } from '@polkadot/types/types';
import { ApiInterface$Rx, OnCallFunction, SubmittableSendResult } from './types';
import { Observable, of, combineLatest } from 'rxjs';
import { first, map, switchMap } from 'rxjs/operators';
import filterEvents from './util/filterEvents';
export default class SubmittableExtrinsic<OnCall> extends Extrinsic {
private _api: ApiInterface$Rx;
private _onCall: OnCallFunction<OnCall>;
constructor (api: ApiInterface$Rx, onCall: OnCallFunction<OnCall>, extrinsic: Extrinsic | Method) {
super(extrinsic);
this._api = api;
this._onCall = onCall;
}
private trackStatus (status: ExtrinsicStatus, statusCb?: (result: SubmittableSendResult) => any): Observable<SubmittableSendResult> {
if (status.type !== 'Finalised') {
return this._onCall(
() => of({
status,
type: status.type
}),
[statusCb]
) as unknown as Observable<SubmittableSendResult>;
}
const blockHash = status.asFinalised;
return this._onCall(
() => combineLatest(
this._api.rpc.chain.getBlock(blockHash),
this._api.query.system.events.at(blockHash)
).pipe(
map(([signedBlock, allEvents]) => ({
events: filterEvents(this.hash, signedBlock as SignedBlock, allEvents as any),
status,
type: status.type
}))
),
[statusCb]
) as unknown as Observable<SubmittableSendResult>;
}
send (statusCb?: (result: SubmittableSendResult) => any): Observable<SubmittableSendResult> {
return this._onCall(
(...args: any[]) => (this._api.rpc.author
.submitAndWatchExtrinsic(this) as Observable<ExtrinsicStatus>)
.pipe(switchMap((status) => this.trackStatus(status, statusCb))),
[statusCb]
) as unknown as Observable<SubmittableSendResult>;
}
sign (signerPair: KeyringPair, nonce: AnyNumber, blockHash?: AnyU8a): SubmittableExtrinsic<OnCall> {
super.sign(signerPair, nonce, blockHash || this._api.genesisHash);
return this;
}
signAndSend (signerPair: KeyringPair, statusCb: (result: SubmittableSendResult) => any): Observable<SubmittableSendResult> {
return this._api.query.system
.accountNonce(signerPair.address())
.pipe(
first(),
switchMap((nonce) =>
this.sign(signerPair, nonce as Index).send(statusCb)
)
);
}
}
@@ -1,47 +0,0 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import extrinsics from '@polkadot/extrinsics/static';
import Extrinsic from '@polkadot/types/Extrinsic';
import Method from '@polkadot/types/Method';
import SubmittableExtrinsic from './SubmittableExtrinsic';
describe('SubmittableExtrinsic', () => {
let api: any;
beforeEach(() => {
Method.injectMethods(extrinsics);
api = {
hasSubscriptions: true,
rpc: {
author: {
submitAndWatchExtrinsic: () => Promise.resolve('submitAndWatchExtrinsic'),
submitExtrinsic: () => Promise.resolve('submitExtrinsic')
}
}
};
});
it('send calls submitAndWatchExtrinsic with statusCb', async () => {
const result = await new SubmittableExtrinsic(
api,
new Extrinsic('0x010200ea51b75b00000000')
).send(() => {
// ignore
});
expect(result).toEqual('submitAndWatchExtrinsic');
});
it('send calls submitExtrinsic without statusCb', async () => {
const result = await new SubmittableExtrinsic(
api,
new Extrinsic('0x010200ea51b75b00000000')
).send();
expect(result).toEqual('submitExtrinsic');
});
});
@@ -1,67 +0,0 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeyringPair } from '@polkadot/keyring/types';
import { AnyNumber, AnyU8a } from '@polkadot/types/types';
import { SubmittableSendResult } from '../types';
import { ApiPromiseInterface, PromiseSubscription } from './types';
import { EventRecord, Extrinsic, ExtrinsicStatus, Hash, Index, Method, SignedBlock } from '@polkadot/types/index';
import { assert } from '@polkadot/util';
import filterEvents from '../util/filterEvents';
export default class SubmittableExtrinsic extends Extrinsic {
private _api: ApiPromiseInterface;
constructor (api: ApiPromiseInterface, extrinsic: Extrinsic | Method) {
super(extrinsic);
this._api = api;
}
private trackStatus (statusCb: (result: SubmittableSendResult) => any): (status: ExtrinsicStatus) => Promise<void> {
return async (status: ExtrinsicStatus): Promise<void> => {
let events: Array<any> | undefined = undefined;
if (status.type === 'Finalised') {
const blockHash = status.asFinalised;
const signedBlock: SignedBlock = await this._api.rpc.chain.getBlock(blockHash);
const allEvents: Array<EventRecord> = await this._api.query.system.events.at(blockHash) as any;
events = filterEvents(this.hash, signedBlock, allEvents);
}
statusCb({
events,
status,
type: status.type
});
};
}
send (statusCb?: (result: SubmittableSendResult) => any): Promise<Hash> | PromiseSubscription {
if (!statusCb || !this._api.hasSubscriptions) {
return this._api.rpc.author.submitExtrinsic(this);
}
return this._api.rpc.author.submitAndWatchExtrinsic(this, this.trackStatus(statusCb));
}
sign (signerPair: KeyringPair, nonce: AnyNumber, blockHash?: AnyU8a): SubmittableExtrinsic {
super.sign(signerPair, nonce, blockHash || this._api.genesisHash);
return this;
}
async signAndSend (signerPair: KeyringPair, statusCb: (result: SubmittableSendResult) => any): PromiseSubscription {
assert(this._api.hasSubscriptions, 'Api does not support subscriptions');
const signerNonce = await this._api.query.system.accountNonce(signerPair.address());
return this
.sign(signerPair, signerNonce as Index)
.send(statusCb) as PromiseSubscription;
}
}
+41 -125
View File
@@ -2,27 +2,19 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { RpcRxInterface$Method } from '@polkadot/rpc-rx/types';
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { ApiOptions } from '../types';
import { ApiPromiseInterface, DecoratedRpc, DecoratedRpc$Method, DecoratedRpc$Section, QueryableStorageFunction, QueryableModuleStorage, QueryableStorage, SubmittableExtrinsics, SubmittableModuleExtrinsics, SubmittableExtrinsicFunction, PromiseSubscription } from './types';
import { ApiPromiseInterface, OnCall, PromiseSubscription } from './types';
import { EMPTY } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import Rpc from '@polkadot/rpc-core/index';
import RpcRx from '@polkadot/rpc-rx/index';
import { Storage } from '@polkadot/storage/types';
import { Hash } from '@polkadot/types/index';
import { EMPTY, Observable } from 'rxjs';
import { catchError, first, tap } from 'rxjs/operators';
import { Codec } from '@polkadot/types/types';
import { MethodFunction, ModulesWithMethods } from '@polkadot/types/Method';
import { StorageFunction } from '@polkadot/types/StorageKey';
import { isFunction, logger, assert } from '@polkadot/util';
import { isFunction } from '@polkadot/util';
import ApiBase from '../Base';
import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator';
import SubmittableExtrinsic from './SubmittableExtrinsic';
const l = logger('api/promise');
type RxFn = (...params: Array<any>) => Observable<Codec | undefined | null>;
/**
* # @polkadot/api/promise
@@ -110,7 +102,7 @@ const l = logger('api/promise');
* });
* ```
*/
export default class ApiPromise extends ApiBase<DecoratedRpc, QueryableStorage, SubmittableExtrinsics> implements ApiPromiseInterface {
export default class ApiPromise extends ApiBase<OnCall> implements ApiPromiseInterface {
private _isReady: Promise<ApiPromise>;
/**
@@ -173,65 +165,6 @@ export default class ApiPromise extends ApiBase<DecoratedRpc, QueryableStorage,
return this._isReady;
}
protected decorateRpc (rpc: Rpc): DecoratedRpc {
const names = ['author', 'chain', 'state', 'system'] as Array<keyof DecoratedRpc>;
const rpcrx = new RpcRx(rpc);
return names.reduce((result, section) => {
result[section] = Object.keys(rpcrx[section]).reduce((fns, method) => {
fns[method] = this.decorateMethod(
rpcrx[section][method],
isFunction(rpc[section][method].unsubscribe)
);
return fns;
}, {} as DecoratedRpc$Section);
return result;
}, {} as DecoratedRpc);
}
protected decorateMethod (rxfn: RpcRxInterface$Method, isSubscription: boolean): DecoratedRpc$Method {
if (!isSubscription) {
return (...params: Array<any>): Promise<any> =>
rxfn(...params).toPromise();
}
return (..._params: Array<any>): PromiseSubscription => {
const cb = _params[_params.length - 1];
assert(isFunction(cb), 'Expected callback as last paramater for subscription');
return new Promise((resolve, reject) => {
let isCompleted = false;
const params = _params.slice(0, _params.length - 1);
const subscription = rxfn(...params)
.pipe(
// if we find an error (invalid params, etc), reject the promise
catchError((error) => {
if (!isCompleted) {
isCompleted = true;
reject(error);
}
// we don't want to continue, so empty observable it is
return EMPTY;
}),
// upon the first result, resolve the with the unsub function
tap(() => {
if (!isCompleted) {
isCompleted = true;
resolve(() => subscription.unsubscribe());
}
})
)
.subscribe(cb);
});
};
}
/**
* @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
* @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
@@ -260,63 +193,46 @@ export default class ApiPromise extends ApiBase<DecoratedRpc, QueryableStorage,
};
}
protected decorateExtrinsics (extrinsics: ModulesWithMethods): SubmittableExtrinsics {
return Object.keys(extrinsics).reduce((result, sectionName) => {
const section = extrinsics[sectionName];
protected onCall (method: RxFn, params: Array<any>, isSubscription?: boolean): OnCall {
if (!params || params.length === 0 || isSubscription === false) {
return method(...params).pipe(first()).toPromise();
}
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[methodName] = this.decorateExtrinsicEntry(section[methodName]);
const cb = params[params.length - 1];
const remainingParams = params.slice(0, - 1);
return result;
}, {} as SubmittableModuleExtrinsics);
if (!isFunction(cb)) {
return method(...params).pipe(first()).toPromise();
}
return result;
}, {} as SubmittableExtrinsics);
}
// FIXME TSLint shouts that type assertion is unnecessary, but tsc shouts
// when I remove it...
// tslint:disable-next-line
return new Promise((resolve, reject) => {
let isCompleted = false;
const subscription = method(...remainingParams)
.pipe(
// if we find an error (invalid params, etc), reject the promise
catchError((error) => {
if (!isCompleted) {
isCompleted = true;
private decorateExtrinsicEntry (method: MethodFunction): SubmittableExtrinsicFunction {
const decorated: any = (...args: Array<any>): SubmittableExtrinsic =>
new SubmittableExtrinsic(this, method(...args));
reject(error);
}
return this.decorateFunctionMeta(method, decorated) as SubmittableExtrinsicFunction;
}
// we don't want to continue, so empty observable it is
return EMPTY;
}),
// upon the first result, resolve the with the unsub function
tap(() => {
if (!isCompleted) {
isCompleted = true;
protected decorateStorage (storage: Storage): QueryableStorage {
return Object.keys(storage).reduce((result, sectionName) => {
const section = storage[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[methodName] = this.decorateStorageEntry(section[methodName]);
return result;
}, {} as QueryableModuleStorage);
return result;
}, {} as QueryableStorage);
}
private decorateStorageEntry (method: StorageFunction): QueryableStorageFunction {
const decorated: any = (...args: Array<any>): Promise<Codec | null | undefined> | PromiseSubscription => {
const cb = args[args.length - 1];
if (args.length === 0 || !isFunction(cb)) {
return this.rpc.state.getStorage([method, args[0]]);
} else if (!this.hasSubscriptions && isFunction(cb)) {
l.warn(`Storage subscription to ${method.section}.${method.name} ignored, provider does not support subscriptions`);
return this.rpc.state.getStorage([method, args.length === 1 ? undefined : args[0]]);
}
return this.rpc.state.subscribeStorage(
[[method, args.length === 1 ? undefined : args[0]]],
(result: Array<Codec | null | undefined> = []) =>
cb(result[0])
) as PromiseSubscription;
};
decorated.at = (hash: Hash, arg?: any): Promise<Codec | null | undefined> =>
this.rpc.state.getStorage([method, arg], hash) as Promise<Codec | null | undefined>;
return this.decorateFunctionMeta(method, decorated) as QueryableStorageFunction;
resolve(() => subscription.unsubscribe());
}
})
)
.subscribe(cb);
}) as PromiseSubscription;
}
}
+4 -51
View File
@@ -2,61 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Hash } from '@polkadot/types/index';
import { Codec } from '@polkadot/types/types';
import { MethodFunction } from '@polkadot/types/Method';
import { StorageFunction } from '@polkadot/types/StorageKey';
import { ApiBaseInterface } from '../types';
import SubmittableExtrinsic from './SubmittableExtrinsic';
import ApiBase from '../Base';
export type OnCall = Promise<Codec | null | undefined> | PromiseSubscription;
export type PromiseSubscription = Promise<() => any>;
export type DecoratedRpc$Method = (...params: Array<any>) => Promise<any> | PromiseSubscription;
export interface DecoratedRpc$Section {
[index: string]: DecoratedRpc$Method;
}
export interface DecoratedRpc {
author: DecoratedRpc$Section;
chain: DecoratedRpc$Section;
state: DecoratedRpc$Section;
system: DecoratedRpc$Section;
}
export interface QueryableStorageFunction$Subscribe {
(arg: any, cb: (value?: any | null) => any): PromiseSubscription;
(cb: (value?: any | null) => any): PromiseSubscription;
}
export interface QueryableStorageFunction extends StorageFunction {
(cb: (value?: any | null) => any): PromiseSubscription;
(arg: any, cb: (value?: any | null) => any): PromiseSubscription;
(arg?: any): Promise<Codec | null | undefined>;
at: (hash: Hash, arg?: any) => Promise<Codec | null | undefined>;
}
export interface QueryableModuleStorage {
[index: string]: QueryableStorageFunction;
}
export interface QueryableStorage {
[index: string]: QueryableModuleStorage;
}
export interface SubmittableExtrinsicFunction extends MethodFunction {
(...args: any[]): SubmittableExtrinsic;
}
export interface SubmittableModuleExtrinsics {
[index: string]: SubmittableExtrinsicFunction;
}
export interface SubmittableExtrinsics {
[index: string]: SubmittableModuleExtrinsics;
}
export interface ApiPromiseInterface extends ApiBaseInterface<DecoratedRpc, QueryableStorage, SubmittableExtrinsics> {
export interface ApiPromiseInterface extends ApiBase<OnCall> {
readonly isReady: Promise<ApiPromiseInterface>;
}
@@ -1,69 +0,0 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeyringPair } from '@polkadot/keyring/types';
import { AnyNumber, AnyU8a } from '@polkadot/types/types';
import { SubmittableSendResult } from '../types';
import { ApiRxInterface } from './types';
import { Observable, of, combineLatest } from 'rxjs';
import { first, map, switchMap } from 'rxjs/operators';
import { Extrinsic, ExtrinsicStatus, Index, Method } from '@polkadot/types/index';
import filterEvents from '../util/filterEvents';
export default class SubmittableExtrinsic extends Extrinsic {
private _api: ApiRxInterface;
constructor (api: ApiRxInterface, extrinsic: Extrinsic | Method) {
super(extrinsic);
this._api = api;
}
private trackStatus = (status: ExtrinsicStatus): Observable<SubmittableSendResult> => {
if (status.type !== 'Finalised') {
return of({
status,
type: status.type
});
}
const blockHash = status.asFinalised;
return combineLatest(
this._api.rpc.chain.getBlock(blockHash),
this._api.query.system.events.at(blockHash)
).pipe(
map(([signedBlock, allEvents]) => ({
events: filterEvents(this.hash, signedBlock, allEvents as any),
status,
type: status.type
}))
);
}
send (): Observable<SubmittableSendResult> {
return this._api.rpc.author
.submitAndWatchExtrinsic(this)
.pipe(switchMap(this.trackStatus));
}
sign (signerPair: KeyringPair, nonce: AnyNumber, blockHash?: AnyU8a): SubmittableExtrinsic {
super.sign(signerPair, nonce, blockHash || this._api.genesisHash);
return this;
}
signAndSend (signerPair: KeyringPair): Observable<SubmittableSendResult> {
return this._api.query.system
.accountNonce(signerPair.address())
.pipe(
first(),
switchMap((nonce) =>
this.sign(signerPair, nonce as Index).send()
)
);
}
}
+9 -89
View File
@@ -3,23 +3,13 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { ApiOptions } from '../types';
import { ApiRxInterface, QueryableStorageFunction, QueryableModuleStorage, QueryableStorage, SubmittableExtrinsics, SubmittableModuleExtrinsics, SubmittableExtrinsicFunction } from './types';
import { ApiRxInterface, OnCall } from './types';
import { ApiOptions, OnCallFunction } from '../types';
import { Observable, from, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import decorateDerive, { Derive } from '@polkadot/api-derive/index';
import Rpc from '@polkadot/rpc-core/index';
import RpcRx from '@polkadot/rpc-rx/index';
import { Storage } from '@polkadot/storage/types';
import { Hash } from '@polkadot/types/index';
import { Observable, from } from 'rxjs';
import { Codec } from '@polkadot/types/types';
import { MethodFunction, ModulesWithMethods } from '@polkadot/types/Method';
import { StorageFunction } from '@polkadot/types/StorageKey';
import { assert } from '@polkadot/util';
import ApiBase from '../Base';
import SubmittableExtrinsic from './SubmittableExtrinsic';
/**
* # @polkadot/api/rx
@@ -118,8 +108,7 @@ import SubmittableExtrinsic from './SubmittableExtrinsic';
* });
* ```
*/
export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableExtrinsics> implements ApiRxInterface {
protected _derive: Derive;
export default class ApiRx extends ApiBase<OnCall> implements ApiRxInterface {
private _isReady: Observable<ApiRx>;
/**
@@ -162,12 +151,9 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE
* });
* ```
*/
constructor (options?: ApiOptions | ProviderInterface) {
super(options);
constructor (provider?: ApiOptions | ProviderInterface) {
super(provider);
assert(this.hasSubscriptions, 'ApiRx can only be used with a provider supporting subscriptions');
this._derive = decorateDerive(this);
this._isReady = from(
// convinced you can observable from an event, however my mind groks this form better
new Promise((resolveReady) =>
@@ -178,15 +164,11 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE
);
}
get derive (): Derive {
return this._derive;
}
/**
* @description Observable that carries the connected state for the provider. Results in a boolean flag that is true/false based on the connectivity.
*/
get isConnected (): Observable<boolean> {
return this.rpc.isConnected();
return this._rpcRx.isConnected();
}
/**
@@ -196,69 +178,7 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE
return this._isReady;
}
protected decorateRpc (rpc: Rpc): RpcRx {
return new RpcRx(rpc);
}
protected decorateExtrinsics (extrinsics: ModulesWithMethods): SubmittableExtrinsics {
return Object.keys(extrinsics).reduce((result, sectionName) => {
const section = extrinsics[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[methodName] = this.decorateExtrinsicEntry(section[methodName]);
return result;
}, {} as SubmittableModuleExtrinsics);
return result;
}, {} as SubmittableExtrinsics);
}
private decorateExtrinsicEntry (method: MethodFunction): SubmittableExtrinsicFunction {
const decorated: any = (...args: Array<any>): SubmittableExtrinsic =>
new SubmittableExtrinsic(this, method(...args));
return this.decorateFunctionMeta(method, decorated) as SubmittableExtrinsicFunction;
}
protected decorateStorage (storage: Storage): QueryableStorage {
return Object.keys(storage).reduce((result, sectionName) => {
const section = storage[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[methodName] = this.decorateStorageEntry(section[methodName]);
return result;
}, {} as QueryableModuleStorage);
return result;
}, {} as QueryableStorage);
}
private decorateStorageEntry (method: StorageFunction): QueryableStorageFunction {
const decorated: any = (arg?: any): Observable<Codec | null | undefined> => {
return this.rpc.state
.subscribeStorage([[method, arg]])
.pipe(
// errors can occur in the case of malformed methods + args
catchError(() => of([])),
// state_storage returns an array of values, since we have just subscribed to
// a single entry, we pull that from the array and return it as-is
map((result: Array<Codec | null | undefined> = []): Codec | null | undefined =>
result[0]
)
);
};
decorated.at = (hash: Hash, arg?: any): Observable<Codec | null | undefined> =>
this.rpc.state
.getStorage([method, arg], hash)
.pipe(
// same as above (for single result), in the case of errors on creation, return `undefined`
catchError(() => of())
);
return this.decorateFunctionMeta(method, decorated) as QueryableStorageFunction;
protected onCall (method: OnCallFunction<Observable<Codec | undefined | null>>, params: Array<any>): OnCall {
return method(...params);
}
}
+4 -33
View File
@@ -2,43 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Hash } from '@polkadot/types/index';
import { Codec } from '@polkadot/types/types';
import { MethodFunction } from '@polkadot/types/Method';
import { StorageFunction } from '@polkadot/types/StorageKey';
import { ApiBaseInterface } from '../types';
import { Observable } from 'rxjs';
import RpcRx from '@polkadot/rpc-rx/index';
import { Codec } from '@polkadot/types/types';
import SubmittableExtrinsic from './SubmittableExtrinsic';
import ApiBase from '../Base';
export interface QueryableStorageFunction extends StorageFunction {
(arg?: any): Observable<Codec | null | undefined>;
at: (hash: Hash, arg?: any) => Observable<Codec | null | undefined>;
}
export type OnCall = Observable<Codec | null | undefined>;
export interface QueryableModuleStorage {
[index: string]: QueryableStorageFunction;
}
export interface QueryableStorage {
[index: string]: QueryableModuleStorage;
}
export interface SubmittableExtrinsicFunction extends MethodFunction {
(...args: any[]): SubmittableExtrinsic;
}
export interface SubmittableModuleExtrinsics {
[index: string]: SubmittableExtrinsicFunction;
}
export interface SubmittableExtrinsics {
[index: string]: SubmittableModuleExtrinsics;
}
export interface ApiRxInterface extends ApiBaseInterface<RpcRx, QueryableStorage, SubmittableExtrinsics> {
export interface ApiRxInterface extends ApiBase<OnCall> {
readonly isConnected: Observable<boolean>;
readonly isReady: Observable<ApiRxInterface>;
}
+78 -18
View File
@@ -2,24 +2,70 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { RpcRxInterface$Events } from '@polkadot/rpc-rx/types';
import { EventRecord, ExtrinsicStatus, Hash, Metadata, RuntimeVersion } from '@polkadot/types/index';
import { Constructor } from '@polkadot/types/types';
import { Codec, Constructor } from '@polkadot/types/types';
import { MethodFunction } from '@polkadot/types/Method';
import { StorageFunction } from '@polkadot/types/StorageKey';
export type ApiInterface$Events = RpcRxInterface$Events | 'ready';
import SubmittableExtrinsic from './SubmittableExtrinsic';
export interface ApiBaseInterface<R, S, E> {
readonly genesisHash: Hash;
readonly hasSubscriptions: boolean;
readonly runtimeMetadata: Metadata;
readonly runtimeVersion: RuntimeVersion;
readonly query: S;
readonly rpc: R;
readonly tx: E;
export type OnCallFunction<OnCall> = (...args: any[]) => OnCall;
on: (type: ApiInterface$Events, handler: (...args: Array<any>) => any) => this;
once: (type: ApiInterface$Events, handler: (...args: Array<any>) => any) => this;
export type DecoratedRpc$Method<OnCall> = (...params: Array<any>) => OnCall;
export interface DecoratedRpc$Section<OnCall> {
[index: string]: DecoratedRpc$Method<OnCall>;
}
export interface DecoratedRpc<OnCall> {
author: DecoratedRpc$Section<OnCall>;
chain: DecoratedRpc$Section<OnCall>;
state: DecoratedRpc$Section<OnCall>;
system: DecoratedRpc$Section<OnCall>;
}
export interface QueryableStorageFunction<OnCall> extends StorageFunction {
(arg?: any): OnCall;
at: (hash: Hash, arg?: any) => OnCall;
}
export interface QueryableModuleStorage<OnCall> {
[index: string]: QueryableStorageFunction<OnCall>;
}
export interface QueryableStorage<OnCall> {
[index: string]: QueryableModuleStorage<OnCall>;
}
export interface SubmittableExtrinsicFunction<OnCall> extends MethodFunction {
(...args: any[]): SubmittableExtrinsic<OnCall>;
}
export interface SubmittableModuleExtrinsics<OnCall> {
[index: string]: SubmittableExtrinsicFunction<OnCall>;
}
export interface SubmittableExtrinsics<OnCall> {
[index: string]: SubmittableModuleExtrinsics<OnCall>;
}
export type SubmittableSendResult = {
events?: Array<EventRecord>,
status: ExtrinsicStatus,
type: string
};
export type DeriveMethod<OnCall> = (...params: Array<any>) => OnCall;
export interface DeriveSection<OnCall> {
[index: string]: DeriveMethod<OnCall>;
}
export interface Derive<OnCall> {
[index: string]: DeriveSection<OnCall>;
}
export interface ApiOptions {
@@ -32,11 +78,25 @@ export interface ApiOptions {
* @description Additional types used by runtime modules. This is nessusary if the runtime modules
* uses types not available in the base Substrate runtime.
*/
types?: {[name: string]: Constructor};
types?: { [name: string]: Constructor };
}
export type SubmittableSendResult = {
events?: Array<EventRecord>,
status: ExtrinsicStatus,
type: string
};
export interface ApiInterface$Decorated<OnCall> {
genesisHash: Hash;
hasSubscriptions: boolean;
runtimeMetadata: Metadata;
runtimeVersion: RuntimeVersion;
derive: Derive<OnCall>;
query: QueryableStorage<OnCall>;
rpc: DecoratedRpc<OnCall>;
tx: SubmittableExtrinsics<OnCall>;
}
export type ApiInterface$Rx = ApiInterface$Decorated<Observable<Codec | null | undefined>>;
export type ApiInterface$Events = RpcRxInterface$Events | 'ready';
export interface ApiBaseInterface<OnCall> extends Readonly<ApiInterface$Decorated<OnCall>> {
on: (type: ApiInterface$Events, handler: (...args: Array<any>) => any) => this;
once: (type: ApiInterface$Events, handler: (...args: Array<any>) => any) => this;
}
@@ -12,10 +12,10 @@ const keyring = testingPairs();
describe.skip('e2e queries', () => {
let api;
beforeEach(async () => {
beforeEach(async (done) => {
api = await Api.create();
// console.error(api);
jest.setTimeout(30000);
done();
});
it('makes the runtime, rpc, state & extrinsics available', () => {
@@ -25,6 +25,7 @@ describe.skip('e2e queries', () => {
expect(api.rpc).toBeDefined();
expect(api.query).toBeDefined();
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
it('queries state for a balance', async () => {
+2 -2
View File
@@ -10,11 +10,11 @@ const keyring = testingPairs();
describe.skip('e2e transactions', () => {
let api;
let nonce;
beforeEach(async () => {
beforeEach(async (done) => {
api = await Api.create();
jest.setTimeout(30000);
done();
});
afterEach(() => {
+4 -3
View File
@@ -12,10 +12,10 @@ const keyring = testingPairs();
describe.skip('e2e queries', () => {
let api;
beforeEach(async () => {
beforeEach(async (done) => {
api = await Api.create().toPromise();
// console.error(api);
jest.setTimeout(30000);
done();
});
it('makes the runtime, rpc, state & extrinsics available', () => {
@@ -25,6 +25,7 @@ describe.skip('e2e queries', () => {
expect(api.rpc).toBeDefined();
expect(api.query).toBeDefined();
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
it('queries state for a balance', (done) => {
+2 -1
View File
@@ -12,9 +12,10 @@ const keyring = testingPairs();
describe.skip('e2e transactions', () => {
let api;
beforeEach(async () => {
beforeEach(async (done) => {
api = await Api.create().toPromise();
jest.setTimeout(30000);
done()
});
afterEach(() => {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-core",
"version": "0.39.12",
"version": "0.40.0",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"keywords": [
@@ -30,9 +30,9 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/jsonrpc": "^0.39.12",
"@polkadot/rpc-provider": "^0.39.12",
"@polkadot/types": "^0.39.12",
"@polkadot/jsonrpc": "^0.40.0",
"@polkadot/rpc-provider": "^0.40.0",
"@polkadot/types": "^0.40.0",
"@polkadot/util": "^0.33.34"
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-provider",
"version": "0.39.12",
"version": "0.40.0",
"description": "Transport providers for the API",
"main": "index.js",
"keywords": [
@@ -31,7 +31,7 @@
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/keyring": "^0.33.34",
"@polkadot/storage": "^0.39.12",
"@polkadot/storage": "^0.40.0",
"@polkadot/util": "^0.33.34",
"@polkadot/util-crypto": "^0.33.34",
"@types/nock": "^9.3.0",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-rx",
"version": "0.39.12",
"version": "0.40.0",
"description": "An RxJs wrapper around the Polkadot JS API",
"main": "index.js",
"keywords": [
@@ -30,8 +30,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-rx#readme",
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/rpc-core": "^0.39.12",
"@polkadot/rpc-provider": "^0.39.12",
"@polkadot/rpc-core": "^0.40.0",
"@polkadot/rpc-provider": "^0.40.0",
"@types/rx": "^4.1.1",
"rxjs": "^6.3.3"
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/extrinsics",
"version": "0.39.12",
"version": "0.40.0",
"main": "index.js",
"repository": "https://github.com/polkadot-js/api.git",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -11,7 +11,7 @@
"license": "Apache-2.0",
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/types": "^0.39.12",
"@polkadot/types": "^0.40.0",
"@polkadot/util": "^0.33.34"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/jsonrpc",
"version": "0.39.12",
"version": "0.40.0",
"description": "Method definitions for the Polkadot RPC layer",
"main": "index.js",
"engines": {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/storage",
"version": "0.39.12",
"version": "0.40.0",
"description": "Generic wrapper wrapper around state storage",
"main": "index.js",
"engines": {
@@ -31,7 +31,7 @@
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/keyring": "^0.33.34",
"@polkadot/types": "^0.39.12",
"@polkadot/types": "^0.40.0",
"@polkadot/util": "^0.33.34",
"@polkadot/util-crypto": "^0.33.34"
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types",
"version": "0.39.12",
"version": "0.40.0",
"description": "Implementation of the Parity codec",
"main": "index.js",
"keywords": [