Remove onCall, use decorateMethod (#987)
* update signature of doublemap storage function * add test cases * update doublemap implementation * update implementation * remove duplicate test case * update test cases * Add hkt * Fix derive types * Make derive work * Fix some bugs * Fix some bugs * More stuff * Make some more stuff work * Fix types in derive * Fix all tests in derive * Change back ApiType * Remove vscode * Fix Submittables * Fix some errors * Fix some bugs * Change some stuff * Fix merge conflict * Fix types * Add console.log * Add console.log * Re-add decorateMethod * Fix tests * Skip e2e * Small fixes * Fix signAndSend * Fix typings in test * Fix lint * Add comments * One line * Remove useless * URI->ApiType * Indentation
This commit is contained in:
+140
-197
@@ -4,13 +4,10 @@
|
||||
|
||||
import { ProviderInterface } from '@polkadot/rpc-provider/types';
|
||||
import { Storage } from '@polkadot/storage/types';
|
||||
import { Codec, CodecArg, CodecCallback, RegistryTypes } from '@polkadot/types/types';
|
||||
import { RxResult } from './rx/types';
|
||||
import { AnyFunction, Codec, CodecArg, RegistryTypes } from '@polkadot/types/types';
|
||||
import {
|
||||
ApiBaseInterface, ApiInterface$Rx, ApiInterface$Events, ApiOptions, ApiType,
|
||||
DecoratedRpc, DecoratedRpc$Method, DecoratedRpc$Section,
|
||||
Derive, DeriveSection, HashResult, U64Result,
|
||||
OnCallDefinition, OnCallFunction,
|
||||
ApiInterface$Rx, ApiInterface$Events, ApiOptions, ApiTypes, DecorateMethodOptions,
|
||||
DecoratedRpc, DecoratedRpc$Section,
|
||||
QueryableModuleStorage, QueryableStorage, QueryableStorageFunction, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs,
|
||||
SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics, Signer
|
||||
} from './types';
|
||||
@@ -18,7 +15,7 @@ import {
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { BehaviorSubject, Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import decorateDerive, { Derive as DeriveInterface } from '@polkadot/api-derive';
|
||||
import decorateDerive from '@polkadot/api-derive';
|
||||
import extrinsicsFromMeta from '@polkadot/extrinsics/fromMetadata';
|
||||
import RpcBase from '@polkadot/rpc-core';
|
||||
import RpcRx from '@polkadot/rpc-rx';
|
||||
@@ -32,6 +29,7 @@ import { cryptoWaitReady } from '@polkadot/util-crypto';
|
||||
|
||||
import injectNodeCompat from './nodeCompat';
|
||||
import createSubmittable, { SubmittableExtrinsic } from './SubmittableExtrinsic';
|
||||
import { decorateSections } from './util/decorate';
|
||||
|
||||
type MetaDecoration = {
|
||||
callIndex?: Uint8Array,
|
||||
@@ -59,26 +57,26 @@ try {
|
||||
* Put the `this.onCall` function of ApiRx here, because it is needed by
|
||||
* `api._rx`.
|
||||
*/
|
||||
function rxOnCall (method: OnCallFunction<RxResult, RxResult>, params: Array<CodecArg> = [], _callback?: CodecCallback): RxResult {
|
||||
return method(...params);
|
||||
function rxDecorateMethod<Method extends AnyFunction> (method: Method): Method {
|
||||
return method;
|
||||
}
|
||||
|
||||
export default abstract class ApiBase<CodecResult, SubscriptionResult> implements ApiBaseInterface<CodecResult, SubscriptionResult> {
|
||||
private _derive?: Derive<CodecResult, SubscriptionResult>;
|
||||
export default abstract class ApiBase<ApiType> {
|
||||
private _derive?: ReturnType<ApiBase<ApiType>['decorateDerive']>;
|
||||
private _eventemitter: EventEmitter;
|
||||
private _extrinsics?: SubmittableExtrinsics<CodecResult, SubscriptionResult>;
|
||||
private _extrinsics?: SubmittableExtrinsics<ApiType>;
|
||||
private _genesisHash?: Hash;
|
||||
private _isReady: boolean = false;
|
||||
protected readonly _options: ApiOptions;
|
||||
private _query?: QueryableStorage<CodecResult, SubscriptionResult>;
|
||||
private _queryMulti: QueryableStorageMulti<CodecResult, SubscriptionResult>;
|
||||
private _rpc: DecoratedRpc<CodecResult, SubscriptionResult>;
|
||||
protected _rpcBase: RpcBase; // FIXME These two could be merged
|
||||
protected _rpcRx: RpcRx; // FIXME These two could be merged
|
||||
private _query?: QueryableStorage<ApiType>;
|
||||
private _queryMulti: QueryableStorageMulti<ApiType>;
|
||||
private _rpc: DecoratedRpc<ApiType>;
|
||||
protected _rpcBase: RpcBase; // FIXME These two could be merged https://github.com/polkadot-js/api/issues/642
|
||||
protected _rpcRx: RpcRx; // FIXME These two could be merged https://github.com/polkadot-js/api/issues/642
|
||||
private _runtimeMetadata?: Metadata;
|
||||
private _runtimeVersion?: RuntimeVersion;
|
||||
private _rx: Partial<ApiInterface$Rx> = {};
|
||||
private _type: ApiType;
|
||||
private _type: ApiTypes;
|
||||
|
||||
/**
|
||||
* @description Create an instance of the class
|
||||
@@ -98,7 +96,7 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
constructor (provider: ApiOptions | ProviderInterface = {}, type: ApiType) {
|
||||
constructor (provider: ApiOptions | ProviderInterface = {}, type: ApiTypes) {
|
||||
const options = isObject(provider) && isFunction((provider as ProviderInterface).send)
|
||||
? { provider } as ApiOptions
|
||||
: provider as ApiOptions;
|
||||
@@ -114,10 +112,10 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
assert(this.hasSubscriptions, 'Api can only be used with a provider supporting subscriptions');
|
||||
|
||||
this._rpcRx = new RpcRx(this._rpcBase._provider);
|
||||
this._rpc = this.decorateRpc(this._rpcRx, this.onCall) as any; // FIXME 3.4.1
|
||||
this._rx.rpc = this.decorateRpc(this._rpcRx, rxOnCall);
|
||||
this._queryMulti = this.decorateMulti(this.onCall) as any; // as above :(
|
||||
this._rx.queryMulti = this.decorateMulti(rxOnCall);
|
||||
this._rpc = this.decorateRpc(this._rpcRx, this.decorateMethod);
|
||||
this._rx.rpc = this.decorateRpc(this._rpcRx, rxDecorateMethod);
|
||||
this._queryMulti = this.decorateMulti(this.decorateMethod);
|
||||
this._rx.queryMulti = this.decorateMulti(rxDecorateMethod);
|
||||
this._rx.signer = options.signer;
|
||||
|
||||
// we only re-register the types (global) if this is not a cloned instance
|
||||
@@ -172,7 +170,7 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
/**
|
||||
* @description The type of this API instance, either 'rxjs' or 'promise'
|
||||
*/
|
||||
get type (): ApiType {
|
||||
get type (): ApiTypes {
|
||||
return this._type;
|
||||
}
|
||||
|
||||
@@ -195,10 +193,10 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get derive (): Derive<CodecResult, SubscriptionResult> {
|
||||
get derive (): ReturnType<ApiBase<ApiType>['decorateDerive']> {
|
||||
assert(!isUndefined(this._derive), INIT_ERROR);
|
||||
|
||||
return this._derive as Derive<CodecResult, SubscriptionResult>;
|
||||
return this._derive as ReturnType<ApiBase<ApiType>['decorateDerive']>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,10 +213,10 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get query (): QueryableStorage<CodecResult, SubscriptionResult> {
|
||||
get query (): QueryableStorage<ApiType> {
|
||||
assert(!isUndefined(this._query), INIT_ERROR);
|
||||
|
||||
return this._query as QueryableStorage<CodecResult, SubscriptionResult>;
|
||||
return this._query as QueryableStorage<ApiType>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -241,7 +239,7 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
get queryMulti (): QueryableStorageMulti<CodecResult, SubscriptionResult> {
|
||||
get queryMulti (): QueryableStorageMulti<ApiType> {
|
||||
return this._queryMulti;
|
||||
}
|
||||
|
||||
@@ -259,7 +257,7 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get rpc (): DecoratedRpc<CodecResult, SubscriptionResult> {
|
||||
get rpc (): DecoratedRpc<ApiType> {
|
||||
return this._rpc;
|
||||
}
|
||||
|
||||
@@ -277,10 +275,10 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get tx (): SubmittableExtrinsics<CodecResult, SubscriptionResult> {
|
||||
get tx (): SubmittableExtrinsics<ApiType> {
|
||||
assert(!isUndefined(this._extrinsics), INIT_ERROR);
|
||||
|
||||
return this._extrinsics as SubmittableExtrinsics<CodecResult, SubscriptionResult>;
|
||||
return this._extrinsics as SubmittableExtrinsics<ApiType>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -376,7 +374,23 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract onCall (method: OnCallFunction<RxResult, RxResult>, params?: Array<CodecArg>, callback?: CodecCallback, needsCallback?: boolean): CodecResult | SubscriptionResult;
|
||||
/**
|
||||
* This 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:
|
||||
* - For ApiRx, `decorateMethod` should just be identity, because the input
|
||||
* function is already an Observable
|
||||
* - For ApiPromise, `decorateMethod` 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 `deocrateMethod`.
|
||||
*/
|
||||
protected abstract decorateMethod (method: (...args: Array<any>) => Observable<any>, options?: DecorateMethodOptions): any;
|
||||
|
||||
private emit (type: ApiInterface$Events, ...args: Array<any>): void {
|
||||
this._eventemitter.emit(type, ...args);
|
||||
@@ -458,15 +472,14 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
const extrinsics = extrinsicsFromMeta(this.runtimeMetadata);
|
||||
const storage = storageFromMeta(this.runtimeMetadata);
|
||||
|
||||
this._extrinsics = this.decorateExtrinsics(extrinsics, this.onCall);
|
||||
this._query = this.decorateStorage(storage, this.onCall) as any; // FIXME 3.4.1
|
||||
this._derive = this.decorateDerive(this._rx as ApiInterface$Rx, this.onCall) as any; // FIXME 3.4.1
|
||||
this._extrinsics = this.decorateExtrinsics(extrinsics, this.decorateMethod);
|
||||
this._query = this.decorateStorage(storage, this.decorateMethod);
|
||||
|
||||
this._rx.genesisHash = this._genesisHash;
|
||||
this._rx.runtimeVersion = this._runtimeVersion;
|
||||
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);
|
||||
this._rx.tx = this.decorateExtrinsics(extrinsics, rxDecorateMethod);
|
||||
this._rx.query = this.decorateStorage(storage, rxDecorateMethod);
|
||||
this._derive = this.decorateDerive(this._rx as ApiInterface$Rx, this.decorateMethod);
|
||||
|
||||
// only inject if we are not a clone (global init)
|
||||
if (!this._options.source) {
|
||||
@@ -490,183 +503,137 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
return output;
|
||||
}
|
||||
|
||||
private decorateRpc<C, S> (rpc: RpcRx, onCall: OnCallDefinition<C, S>): DecoratedRpc<C, S> {
|
||||
private decorateRpc<ApiType> (rpc: RpcRx, decorateMethod: ApiBase<ApiType>['decorateMethod']): DecoratedRpc<ApiType> {
|
||||
return ['author', 'chain', 'state', 'system'].reduce((result, _sectionName) => {
|
||||
const sectionName = _sectionName as keyof DecoratedRpc<C, S>;
|
||||
const sectionName = _sectionName as keyof DecoratedRpc<ApiType>;
|
||||
|
||||
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 needsCallback = methodName.includes('subscribe');
|
||||
// These signatures are allowed and exposed here (bit or a stoopid way, but checked
|
||||
// RPCs and we have 3 max args, with subs max one arg... YMMV) -
|
||||
// (arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): CodecResult;
|
||||
// (arg1: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
// (callback: CodecCallback): SubscriptionResult;
|
||||
const method = ((...args: Array<any>): C | S => {
|
||||
let callback: CodecCallback | undefined;
|
||||
let params = args;
|
||||
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = args[args.length - 1];
|
||||
params = args.slice(0, args.length - 1);
|
||||
}
|
||||
|
||||
return onCall(rpc[sectionName][methodName], params, callback, needsCallback);
|
||||
}) as DecoratedRpc$Method<C, S>;
|
||||
|
||||
section[methodName] = method;
|
||||
const method = rpc[sectionName][methodName];
|
||||
section[methodName] = decorateMethod(method, { methodName });
|
||||
|
||||
return section;
|
||||
}, {} as DecoratedRpc$Section<C, S>);
|
||||
}, {} as DecoratedRpc$Section<ApiType>);
|
||||
|
||||
return result;
|
||||
}, {} as DecoratedRpc<C, S>);
|
||||
}, {} as DecoratedRpc<ApiType>);
|
||||
}
|
||||
|
||||
private decorateMulti<C, S> (onCall: OnCallDefinition<C, S>): QueryableStorageMulti<C, S> {
|
||||
return ((calls: QueryableStorageMultiArgs<C, S>, callback?: CodecCallback): S => {
|
||||
const mapped = calls.map((arg: QueryableStorageMultiArg<C, S>): [QueryableStorageFunction<CodecResult, SubscriptionResult>, ...Array<CodecArg>] =>
|
||||
// the input is a QueryableStorageFunction, convert to StorageFunction
|
||||
Array.isArray(arg)
|
||||
? [arg[0].creator, ...arg.slice(1)]
|
||||
: [arg.creator] as any
|
||||
);
|
||||
private decorateMulti<ApiType> (decorateMethod: ApiBase<ApiType>['decorateMethod']): QueryableStorageMulti<ApiType> {
|
||||
return decorateMethod(
|
||||
(calls: QueryableStorageMultiArgs<ApiType>) => {
|
||||
const mapped = calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageFunction<ApiType>, ...Array<CodecArg>] =>
|
||||
// the input is a QueryableStorageFunction, convert to StorageFunction
|
||||
Array.isArray(arg)
|
||||
? [arg[0].creator, ...arg.slice(1)]
|
||||
: [arg.creator] as any
|
||||
);
|
||||
|
||||
return onCall(
|
||||
() =>
|
||||
this._rpcRx.state
|
||||
.subscribeStorage(mapped)
|
||||
.pipe(map((results) => new VectorAny(...results))),
|
||||
[],
|
||||
callback
|
||||
) as S;
|
||||
}) as QueryableStorageMulti<C, S>;
|
||||
return this._rpcRx.state
|
||||
.subscribeStorage(mapped)
|
||||
.pipe(map((results) => new VectorAny(...results)));
|
||||
});
|
||||
}
|
||||
|
||||
private decorateExtrinsics<C, S> (extrinsics: ModulesWithMethods, onCall: OnCallDefinition<C, S>): SubmittableExtrinsics<C, S> {
|
||||
const creator = (value: Uint8Array | string): SubmittableExtrinsic<C, S> =>
|
||||
createSubmittable(this.type, this._rx as ApiInterface$Rx, onCall, value);
|
||||
private decorateExtrinsics<ApiType> (extrinsics: ModulesWithMethods, decorateMethod: ApiBase<ApiType>['decorateMethod']): SubmittableExtrinsics<ApiType> {
|
||||
const creator = (value: Uint8Array | string): SubmittableExtrinsic<ApiType> =>
|
||||
createSubmittable(this.type, this._rx as ApiInterface$Rx, decorateMethod, value);
|
||||
|
||||
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);
|
||||
result[methodName] = this.decorateExtrinsicEntry(section[methodName], decorateMethod);
|
||||
|
||||
return result;
|
||||
}, {} as SubmittableModuleExtrinsics<C, S>);
|
||||
}, {} as SubmittableModuleExtrinsics<ApiType>);
|
||||
|
||||
return result;
|
||||
}, creator as SubmittableExtrinsics<C, S>);
|
||||
}, creator as SubmittableExtrinsics<ApiType>);
|
||||
}
|
||||
|
||||
private decorateExtrinsicEntry<C, S> (method: MethodFunction, onCall: OnCallDefinition<C, S>): SubmittableExtrinsicFunction<C, S> {
|
||||
const decorated = (...params: Array<CodecArg>): SubmittableExtrinsic<C, S> =>
|
||||
createSubmittable(this.type, this._rx as ApiInterface$Rx, onCall, method(...params));
|
||||
private decorateExtrinsicEntry<ApiType> (method: MethodFunction, decorateMethod: ApiBase<ApiType>['decorateMethod']): SubmittableExtrinsicFunction<ApiType> {
|
||||
const decorated =
|
||||
(...params: Array<CodecArg>): SubmittableExtrinsic<ApiType> =>
|
||||
createSubmittable(this.type, this._rx as ApiInterface$Rx, decorateMethod, method(...params));
|
||||
|
||||
return this.decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<C, S>;
|
||||
return this.decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
|
||||
}
|
||||
|
||||
private decorateStorage<C, S> (storage: Storage, onCall: OnCallDefinition<C, S>): QueryableStorage<C, S> {
|
||||
private decorateStorage<ApiType> (storage: Storage, decorateMethod: ApiBase<ApiType>['decorateMethod']): QueryableStorage<ApiType> {
|
||||
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);
|
||||
result[methodName] = this.decorateStorageEntry(section[methodName], decorateMethod);
|
||||
|
||||
return result;
|
||||
}, {} as QueryableModuleStorage<C, S>);
|
||||
}, {} as QueryableModuleStorage<ApiType>);
|
||||
|
||||
return result;
|
||||
}, {} as QueryableStorage<C, S>);
|
||||
}, {} as QueryableStorage<ApiType>);
|
||||
}
|
||||
|
||||
private decorateStorageEntry<C, S> (creator: StorageFunction, onCall: OnCallDefinition<C, S>): QueryableStorageFunction<C, S> {
|
||||
// These signatures are allowed and exposed here -
|
||||
// (arg?: CodecArg): CodecResult;
|
||||
// (arg: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
// (callback: CodecCallback): SubscriptionResult;
|
||||
const decorated = ((...args: Array<any>): C | S => {
|
||||
let callback: CodecCallback | undefined;
|
||||
let params = args;
|
||||
private decorateStorageEntry<ApiType> (creator: StorageFunction, decorateMethod: ApiBase<ApiType>['decorateMethod']): QueryableStorageFunction<ApiType> {
|
||||
const decorated = creator.headKey
|
||||
? this.decorateStorageEntryLinked(creator, decorateMethod)
|
||||
: decorateMethod(
|
||||
(...args: Array<any>) => {
|
||||
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = args[args.length - 1];
|
||||
params = args.slice(0, args.length - 1);
|
||||
}
|
||||
|
||||
if (creator.headKey && params.length === 0) {
|
||||
return this.decorateStorageEntryLinked(creator, onCall, callback);
|
||||
}
|
||||
|
||||
return onCall(
|
||||
(...args: CodecArg[]) => this._rpcRx.state
|
||||
.subscribeStorage([
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, args]
|
||||
: [creator, ...args]])
|
||||
.pipe(
|
||||
// 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>): Codec =>
|
||||
result[0]
|
||||
)
|
||||
),
|
||||
params,
|
||||
callback
|
||||
);
|
||||
}) as QueryableStorageFunction<C, S>;
|
||||
return this._rpcRx.state
|
||||
.subscribeStorage([
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, args]
|
||||
: [creator, ...args]])
|
||||
.pipe(
|
||||
// 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>): Codec =>
|
||||
result[0]
|
||||
)
|
||||
);
|
||||
}, {
|
||||
methodName: creator.method
|
||||
});
|
||||
|
||||
decorated.creator = creator;
|
||||
|
||||
decorated.at = (hash: Hash | Uint8Array | string, arg1?: CodecArg, arg2?: CodecArg): C =>
|
||||
onCall(
|
||||
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcRx.state.getStorage(
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, [arg1, arg2]]
|
||||
: [creator, arg1],
|
||||
hash),
|
||||
[arg1, arg2]
|
||||
) as C;
|
||||
decorated.at = decorateMethod(
|
||||
(hash: Hash, arg1?: CodecArg, arg2?: CodecArg) => this._rpcRx.state.getStorage(
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, [arg1, arg2]]
|
||||
: [creator, arg1],
|
||||
hash)
|
||||
);
|
||||
|
||||
// FIXME The unknown cast is needed since the onCall result, `C | S` cannot
|
||||
// be converted from C to the actual result required
|
||||
decorated.hash = (arg1?: CodecArg, arg2?: CodecArg): HashResult<C, S> =>
|
||||
onCall(
|
||||
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcRx.state.getStorageHash(
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, [arg1, arg2]]
|
||||
: [creator, arg1]),
|
||||
[arg1, arg2]
|
||||
) as unknown as HashResult<C, S>;
|
||||
decorated.hash = decorateMethod(
|
||||
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcRx.state.getStorageHash(
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, [arg1, arg2]]
|
||||
: [creator, arg1])
|
||||
);
|
||||
|
||||
decorated.key = (arg1?: CodecArg, arg2?: CodecArg): string =>
|
||||
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
|
||||
|
||||
// When using double map storage function, user need to path double map key as an array
|
||||
decorated.multi = (args: Array<CodecArg[] | CodecArg>, callback?: CodecCallback): S =>
|
||||
onCall(
|
||||
() =>
|
||||
this._rpcRx.state
|
||||
.subscribeStorage(args.map((arg: CodecArg[] | CodecArg) => [creator, arg]))
|
||||
.pipe(map((results) => new VectorAny(...results))),
|
||||
[],
|
||||
callback
|
||||
) as unknown as S;
|
||||
decorated.multi = decorateMethod(
|
||||
(args: Array<CodecArg[] | CodecArg>) =>
|
||||
this._rpcRx.state
|
||||
.subscribeStorage(args.map((arg: CodecArg[] | CodecArg) => [creator, arg]))
|
||||
.pipe(map((results) => new VectorAny(...results)))
|
||||
);
|
||||
|
||||
decorated.size = (arg1?: CodecArg, arg2?: CodecArg): U64Result<C, S> =>
|
||||
onCall(
|
||||
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcRx.state.getStorageSize(
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, [arg1, arg2]]
|
||||
: [creator, arg1]),
|
||||
[arg1, arg2]
|
||||
) as unknown as U64Result<C, S>;
|
||||
decorated.size = decorateMethod(
|
||||
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcRx.state.getStorageSize(
|
||||
creator.meta.type.isDoubleMap
|
||||
? [creator, [arg1, arg2]]
|
||||
: [creator, arg1])
|
||||
);
|
||||
|
||||
return this.decorateFunctionMeta(creator, decorated) as QueryableStorageFunction<C, S>;
|
||||
return this.decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageFunction<ApiType>;
|
||||
}
|
||||
|
||||
private decorateStorageEntryLinked<C, S> (method: StorageFunction, onCall: OnCallDefinition<C, S>, callback: CodecCallback | undefined): C | S {
|
||||
private decorateStorageEntryLinked<ApiType> (method: StorageFunction, decorateMethod: ApiBase<ApiType>['decorateMethod']): ReturnType<ApiBase<ApiType>['decorateMethod']> {
|
||||
const result: Map<Codec, [Codec, Linkage<Codec>]> = new Map();
|
||||
let subject: BehaviorSubject<LinkageResult>;
|
||||
let head: Codec | null = null;
|
||||
@@ -735,47 +702,23 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
|
||||
|
||||
// this handles the case where the head changes effectively, i.e. a new entry
|
||||
// appears at the top of the list, the new getNext gets kicked off
|
||||
return onCall(
|
||||
(arg: CodecArg) => this._rpcRx.state
|
||||
.subscribeStorage([arg])
|
||||
return decorateMethod(
|
||||
() => this._rpcRx.state
|
||||
.subscribeStorage([method.headKey])
|
||||
.pipe(
|
||||
switchMap(([key]: Array<Codec>) => {
|
||||
head = key;
|
||||
|
||||
return getNext(key);
|
||||
})
|
||||
),
|
||||
[method.headKey],
|
||||
callback
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private decorateDerive<C, S> (apiRx: ApiInterface$Rx, onCall: OnCallDefinition<C, S>): Derive<C, S> {
|
||||
private decorateDerive (apiRx: ApiInterface$Rx, decorateMethod: ApiBase<ApiType>['decorateMethod']) {
|
||||
// Pull in derive from api-derive
|
||||
const derive = decorateDerive(apiRx, this._options.derives);
|
||||
|
||||
return Object.keys(derive).reduce((result, _sectionName) => {
|
||||
const sectionName = _sectionName as keyof DeriveInterface;
|
||||
|
||||
result[sectionName] = Object.keys(derive[sectionName]).reduce((section, methodName) => {
|
||||
// FIXME The callback extraction we do way too much - de-dupe
|
||||
const method = (...args: Array<any>): C | S => {
|
||||
let callback: CodecCallback | undefined;
|
||||
let params = args;
|
||||
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = args[args.length - 1];
|
||||
params = args.slice(0, args.length - 1);
|
||||
}
|
||||
|
||||
return onCall((derive[sectionName] as any)[methodName], params, callback, !!callback);
|
||||
};
|
||||
|
||||
section[methodName] = method as any; // CodecCallback or CodecArg form
|
||||
|
||||
return section;
|
||||
}, {} as DeriveSection<C, S>);
|
||||
|
||||
return result;
|
||||
}, {} as Derive<C, S>);
|
||||
return decorateSections<ApiType, typeof derive>(derive, decorateMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,24 +3,23 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Address, ExtrinsicStatus, EventRecord, getTypeRegistry, Hash, Index, Method, SignedBlock, Struct, Vector } from '@polkadot/types';
|
||||
import { Codec, CodecCallback, IExtrinsic, IKeyringPair, SignatureOptions } from '@polkadot/types/types';
|
||||
import { ApiInterface$Rx, ApiType, OnCallDefinition, Signer } from './types';
|
||||
import { Callback, Codec, IExtrinsic, IKeyringPair, SignatureOptions } from '@polkadot/types/types';
|
||||
import { ApiInterface$Rx, ApiTypes, Signer } from './types';
|
||||
|
||||
import { Observable, of, combineLatest } from 'rxjs';
|
||||
import { first, map, mergeMap, switchMap, tap } from 'rxjs/operators';
|
||||
import { assert, isBn, isFunction, isNumber, isUndefined } from '@polkadot/util';
|
||||
|
||||
import ApiBase from './Base';
|
||||
import filterEvents from './util/filterEvents';
|
||||
|
||||
type StatusCb = (result: SubmittableResult) => any;
|
||||
|
||||
type SumbitableResultResult<CodecResult, SubscriptionResult> =
|
||||
CodecResult extends Observable<any>
|
||||
type SumbitableResultResult<ApiType> =
|
||||
ApiType extends 'rxjs'
|
||||
? Observable<SubmittableResult>
|
||||
: Promise<Hash>;
|
||||
|
||||
type SumbitableResultSubscription<CodecResult, SubscriptionResult> =
|
||||
SubscriptionResult extends Observable<any>
|
||||
type SumbitableResultSubscription<ApiType> =
|
||||
ApiType extends 'rxjs'
|
||||
? Observable<SubmittableResult>
|
||||
: Promise<() => void>;
|
||||
|
||||
@@ -56,20 +55,26 @@ export class SubmittableResult extends Struct {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SubmittableExtrinsic<CodecResult, SubscriptionResult> extends IExtrinsic {
|
||||
send (): SumbitableResultResult<CodecResult, SubscriptionResult>;
|
||||
export interface SubmittableExtrinsic<ApiType> extends IExtrinsic {
|
||||
send (): SumbitableResultResult<ApiType>;
|
||||
|
||||
send (statusCb: (result: SubmittableResult) => any): SumbitableResultSubscription<CodecResult, SubscriptionResult>;
|
||||
send (statusCb: Callback<SubmittableResult>): SumbitableResultSubscription<ApiType>;
|
||||
|
||||
sign (account: IKeyringPair, _options: Partial<SignatureOptions>): this;
|
||||
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address, options?: Partial<Partial<SignatureOptions>>): SumbitableResultResult<CodecResult, SubscriptionResult>;
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address, options?: Partial<Partial<SignatureOptions>>): SumbitableResultResult<ApiType>;
|
||||
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address, statusCb: StatusCb): SumbitableResultSubscription<CodecResult, SubscriptionResult>;
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address, statusCb: Callback<SubmittableResult>): SumbitableResultSubscription<ApiType>;
|
||||
}
|
||||
|
||||
export default function createSubmittableExtrinsic<CodecResult, SubscriptionResult> (type: ApiType, api: ApiInterface$Rx, onCall: OnCallDefinition<CodecResult, SubscriptionResult>, extrinsic: Method | Uint8Array | string, trackingCb?: (result: SubmittableResult) => any): SubmittableExtrinsic<CodecResult, SubscriptionResult> {
|
||||
const _extrinsic = new (getTypeRegistry().getOrThrow('Extrinsic'))(extrinsic) as SubmittableExtrinsic<CodecResult, SubscriptionResult>;
|
||||
export default function createSubmittableExtrinsic<ApiType> (
|
||||
type: ApiTypes,
|
||||
api: ApiInterface$Rx,
|
||||
decorateMethod: ApiBase<ApiType>['decorateMethod'],
|
||||
extrinsic: Method | Uint8Array | string,
|
||||
trackingCb?: Callback<SubmittableResult>
|
||||
): SubmittableExtrinsic<ApiType> {
|
||||
const _extrinsic = new (getTypeRegistry().getOrThrow('Extrinsic'))(extrinsic) as SubmittableExtrinsic<ApiType>;
|
||||
const _noStatusCb = type === 'rxjs';
|
||||
|
||||
function updateSigner (updateId: number, status: Hash | SubmittableResult): void {
|
||||
@@ -142,21 +147,14 @@ export default function createSubmittableExtrinsic<CodecResult, SubscriptionResu
|
||||
_extrinsic,
|
||||
{
|
||||
send: {
|
||||
value: function (statusCb?: (result: SubmittableResult) => any): SumbitableResultResult<CodecResult, SubscriptionResult> | SumbitableResultSubscription<CodecResult, SubscriptionResult> {
|
||||
value: function (statusCb?: Callback<SubmittableResult>): SumbitableResultResult<ApiType> | SumbitableResultSubscription<ApiType> {
|
||||
const isSubscription = _noStatusCb || !!statusCb;
|
||||
|
||||
return onCall(
|
||||
() => isSubscription
|
||||
? subscribeObservable()
|
||||
: sendObservable(),
|
||||
[],
|
||||
statusCb as CodecCallback,
|
||||
isSubscription
|
||||
) as unknown as SumbitableResultSubscription<CodecResult, SubscriptionResult>;
|
||||
return decorateMethod(isSubscription ? subscribeObservable : sendObservable)(statusCb);
|
||||
}
|
||||
},
|
||||
sign: {
|
||||
value: function (account: IKeyringPair, _options: Partial<SignatureOptions>): SubmittableExtrinsic<CodecResult, SubscriptionResult> {
|
||||
value: function (account: IKeyringPair, _options: Partial<SignatureOptions>): SubmittableExtrinsic<ApiType> {
|
||||
// HACK here we actually override nonce if it was specified (backwards compat for
|
||||
// the previous signature - don't let userspace break, but allow then time to upgrade)
|
||||
const options: Partial<SignatureOptions> = isBn(_options) || isNumber(_options)
|
||||
@@ -169,7 +167,7 @@ export default function createSubmittableExtrinsic<CodecResult, SubscriptionResu
|
||||
}
|
||||
},
|
||||
signAndSend: {
|
||||
value: function (account: IKeyringPair | string | AccountId | Address, _options?: Partial<Partial<SignatureOptions>> | StatusCb, statusCb?: StatusCb): SumbitableResultResult<CodecResult, SubscriptionResult> | SumbitableResultSubscription<CodecResult, SubscriptionResult> {
|
||||
value: function (account: IKeyringPair | string | AccountId | Address, _options?: Partial<Partial<SignatureOptions>> | Callback<SubmittableResult>, statusCb?: Callback<SubmittableResult>): SumbitableResultResult<ApiType> | SumbitableResultSubscription<ApiType> {
|
||||
let options: Partial<Partial<SignatureOptions>> = {};
|
||||
|
||||
if (isFunction(_options)) {
|
||||
@@ -183,10 +181,10 @@ export default function createSubmittableExtrinsic<CodecResult, SubscriptionResu
|
||||
const address = isKeyringPair ? (account as IKeyringPair).address : account.toString();
|
||||
let updateId: number | undefined;
|
||||
|
||||
return onCall(
|
||||
return decorateMethod(
|
||||
() => ((
|
||||
isUndefined(options.nonce)
|
||||
? api.query.system.accountNonce(address) as Observable<Index>
|
||||
? api.query.system.accountNonce<Index>(address)
|
||||
: of(new Index(options.nonce))
|
||||
).pipe(
|
||||
first(),
|
||||
@@ -207,11 +205,8 @@ export default function createSubmittableExtrinsic<CodecResult, SubscriptionResu
|
||||
? subscribeObservable(updateId)
|
||||
: sendObservable(updateId) as any; // ???
|
||||
})
|
||||
) as Observable<Codec>),
|
||||
[],
|
||||
statusCb as CodecCallback,
|
||||
isSubscription
|
||||
) as unknown as SumbitableResultSubscription<CodecResult, SubscriptionResult>;
|
||||
) as Observable<Codec>)
|
||||
)(statusCb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,18 @@ export default async function test () {
|
||||
console.log('intentions:', intentions);
|
||||
});
|
||||
|
||||
await api.rpc.chain.subscribeNewHead<Header>((header) => {
|
||||
console.log('current blockNumber:', header.blockNumber);
|
||||
});
|
||||
|
||||
await api.rpc.chain.subscribeNewHead((header: Header) => {
|
||||
console.log('current blockNumber:', header.blockNumber);
|
||||
});
|
||||
|
||||
await api.derive.chain.subscribeNewHead((header) => {
|
||||
console.log('current author:', header.author);
|
||||
});
|
||||
|
||||
await api.derive.chain.subscribeNewHead((header: HeaderExtended) => {
|
||||
console.log('current author:', header.author);
|
||||
});
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface } from '@polkadot/rpc-provider/types';
|
||||
import { CodecArg, CodecCallback } from '@polkadot/types/types';
|
||||
import { RxResult } from '../rx/types';
|
||||
import { ApiOptions, OnCallFunction } from '../types';
|
||||
import { ApiPromiseInterface, CodecResult, SubscriptionResult } from './types';
|
||||
import { AnyFunction, Callback, Codec } from '@polkadot/types/types';
|
||||
import { ApiOptions, DecorateMethodOptions, ObsInnerType, StorageFunctionPromiseOverloads, UnsubscribePromise } from '../types';
|
||||
|
||||
import { EMPTY } from 'rxjs';
|
||||
import { catchError, first, tap } from 'rxjs/operators';
|
||||
@@ -100,7 +98,7 @@ import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export default class ApiPromise extends ApiBase<CodecResult, SubscriptionResult> implements ApiPromiseInterface {
|
||||
export default class ApiPromise extends ApiBase<'promise'> {
|
||||
private _isReadyPromise: Promise<ApiPromise>;
|
||||
|
||||
/**
|
||||
@@ -192,7 +190,7 @@ export default class ApiPromise extends ApiBase<CodecResult, SubscriptionResult>
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
async combineLatest (fns: Array<CombinatorFunction | [CombinatorFunction, ...Array<any>]>, callback: CombinatorCallback): SubscriptionResult {
|
||||
async combineLatest (fns: Array<CombinatorFunction | [CombinatorFunction, ...Array<any>]>, callback: CombinatorCallback): UnsubscribePromise {
|
||||
const combinator = new Combinator(fns, callback);
|
||||
|
||||
return (): void => {
|
||||
@@ -200,42 +198,55 @@ export default class ApiPromise extends ApiBase<CodecResult, SubscriptionResult>
|
||||
};
|
||||
}
|
||||
|
||||
protected onCall (method: OnCallFunction<RxResult, RxResult>, params: Array<CodecArg> = [], callback?: CodecCallback, needsCallback?: boolean): CodecResult | SubscriptionResult {
|
||||
// When we need a subscription, ensure that a valid callback is actually passed
|
||||
assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');
|
||||
protected decorateMethod<Method extends AnyFunction> (method: Method, options?: DecorateMethodOptions): StorageFunctionPromiseOverloads {
|
||||
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
|
||||
|
||||
if (!callback) {
|
||||
return method(...params).pipe(first()).toPromise();
|
||||
}
|
||||
return function (...args: any[]) {
|
||||
let callback: Callback<Codec> | undefined;
|
||||
let actualArgs = args.slice();
|
||||
|
||||
// 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(...params)
|
||||
.pipe(
|
||||
// if we find an error (invalid params, etc), reject the promise
|
||||
catchError((error) => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
// If the last arg is a function, we pop it, put it into callback.
|
||||
// actualArgs will then hold the actual arguments to be passed to `method`
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = actualArgs.pop();
|
||||
}
|
||||
|
||||
reject(error);
|
||||
}
|
||||
// When we need a subscription, ensure that a valid callback is actually passed
|
||||
assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');
|
||||
|
||||
// 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;
|
||||
if (!callback) {
|
||||
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
|
||||
}
|
||||
|
||||
resolve(() => subscription.unsubscribe());
|
||||
}
|
||||
})
|
||||
)
|
||||
.subscribe(callback);
|
||||
}) as SubscriptionResult;
|
||||
// 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(...actualArgs)
|
||||
.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(callback);
|
||||
}) as UnsubscribePromise;
|
||||
} as StorageFunctionPromiseOverloads;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +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 { SubscriptionResult } from './types';
|
||||
import { Callback } from '@polkadot/types/types';
|
||||
import { UnsubscribePromise } from '../types';
|
||||
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
export type CombinatorCallback = (value: Array<any>) => any;
|
||||
export type CombinatorCallback = Callback<Array<any>>;
|
||||
export type CombinatorFunction = {
|
||||
(cb: (value: any) => any): SubscriptionResult
|
||||
(cb: Callback<any>): UnsubscribePromise
|
||||
};
|
||||
|
||||
export default class Combinator {
|
||||
@@ -18,7 +19,7 @@ export default class Combinator {
|
||||
protected _fns: Array<CombinatorFunction> = [];
|
||||
protected _isActive: boolean = true;
|
||||
protected _results: Array<any> = [];
|
||||
protected _subscriptions: Array<SubscriptionResult> = [];
|
||||
protected _subscriptions: Array<UnsubscribePromise> = [];
|
||||
|
||||
constructor (fns: Array<CombinatorFunction | [CombinatorFunction, ...Array<any>]>, callback: CombinatorCallback) {
|
||||
this._callback = callback;
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { SubscriptionResult } from './types';
|
||||
import { UnsubscribePromise } from '../types';
|
||||
import Combinator from './Combinator';
|
||||
|
||||
describe('Combinator', () => {
|
||||
let fns: Array<(value: any) => void> = [];
|
||||
const storeFn = async (cb: (value: any) => void): SubscriptionResult => {
|
||||
const storeFn = async (cb: (value: any) => void): UnsubscribePromise => {
|
||||
fns.push(cb);
|
||||
|
||||
return () => undefined;
|
||||
|
||||
@@ -2,20 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { QueryableStorageFunction as QueryableStorageFunctionBase, SubmittableExtrinsicFunction as SubmittableExtrinsicFunctionBase } from '../types';
|
||||
|
||||
import ApiBase from '../Base';
|
||||
import { SubmittableExtrinsic as SubmittableExtrinsicBase } from '../SubmittableExtrinsic';
|
||||
|
||||
export type SubscriptionResult = Promise<() => any>;
|
||||
|
||||
export type CodecResult = Promise<Codec>;
|
||||
|
||||
export interface ApiPromiseInterface extends ApiBase<CodecResult, SubscriptionResult> {
|
||||
readonly isReady: Promise<ApiPromiseInterface>;
|
||||
}
|
||||
|
||||
export type QueryableStorageFunction = QueryableStorageFunctionBase<CodecResult, SubscriptionResult>;
|
||||
export type SubmittableExtrinsic = SubmittableExtrinsicBase<CodecResult, SubscriptionResult>;
|
||||
export type SubmittableExtrinsicFunction = SubmittableExtrinsicFunctionBase<CodecResult, SubscriptionResult>;
|
||||
export type QueryableStorageFunction = QueryableStorageFunctionBase<'promise'>;
|
||||
export type SubmittableExtrinsic = SubmittableExtrinsicBase<'promise'>;
|
||||
export type SubmittableExtrinsicFunction = SubmittableExtrinsicFunctionBase<'promise'>;
|
||||
|
||||
@@ -3,11 +3,10 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface } from '@polkadot/rpc-provider/types';
|
||||
import { CodecArg } from '@polkadot/types/types';
|
||||
import { ApiRxInterface, RxResult } from './types';
|
||||
import { ApiOptions, OnCallFunction } from '../types';
|
||||
import { AnyFunction } from '@polkadot/types/types';
|
||||
import { ApiOptions } from '../types';
|
||||
|
||||
import { Observable, from } from 'rxjs';
|
||||
import { from, Observable } from 'rxjs';
|
||||
|
||||
import ApiBase from '../Base';
|
||||
|
||||
@@ -111,7 +110,7 @@ import ApiBase from '../Base';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export default class ApiRx extends ApiBase<RxResult, RxResult> implements ApiRxInterface {
|
||||
export default class ApiRx extends ApiBase<'rxjs'> {
|
||||
private _isReadyRx: Observable<ApiRx>;
|
||||
|
||||
/**
|
||||
@@ -199,7 +198,7 @@ export default class ApiRx extends ApiBase<RxResult, RxResult> implements ApiRxI
|
||||
});
|
||||
}
|
||||
|
||||
protected onCall (method: OnCallFunction<RxResult, RxResult>, params: Array<CodecArg> = []): RxResult {
|
||||
return method(...params);
|
||||
protected decorateMethod<Method extends AnyFunction> (method: Method): Method {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +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 { Observable } from 'rxjs';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
|
||||
import ApiBase from '../Base';
|
||||
|
||||
export type RxResult = Observable<Codec>;
|
||||
|
||||
export interface ApiRxInterface extends ApiBase<RxResult, RxResult> {
|
||||
readonly isConnected: Observable<boolean>;
|
||||
readonly isReady: Observable<ApiRxInterface>;
|
||||
}
|
||||
+129
-109
@@ -6,130 +6,159 @@ import { Observable } from 'rxjs';
|
||||
import { DeriveCustom } from '@polkadot/api-derive';
|
||||
import { ProviderInterface } from '@polkadot/rpc-provider/types';
|
||||
import { RpcRxInterface$Events } from '@polkadot/rpc-rx/types';
|
||||
import { Hash, Metadata, RuntimeVersion, u64 as U64 } from '@polkadot/types';
|
||||
import { CodecArg, CodecCallback, IExtrinsic, RegistryTypes, SignatureOptions } from '@polkadot/types/types';
|
||||
import { Hash, RuntimeVersion, u64 as U64 } from '@polkadot/types';
|
||||
import { AnyFunction, Callback, Codec, CodecArg, IExtrinsic, RegistryTypes, SignatureOptions } from '@polkadot/types/types';
|
||||
import { MethodFunction } from '@polkadot/types/primitive/Method';
|
||||
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
|
||||
|
||||
import { RxResult } from './rx/types';
|
||||
import { SubmittableResult, SubmittableExtrinsic } from './SubmittableExtrinsic';
|
||||
import ApiBase from './Base';
|
||||
import { SubmittableResult, SubmittableExtrinsic } from './SubmittableExtrinsic';
|
||||
|
||||
export type OnCallDefinition<CodecResult, SubscriptionResult> = (method: OnCallFunction<RxResult, RxResult>, params?: Array<CodecArg>, callback?: CodecCallback, needsCallback?: boolean) => CodecResult | SubscriptionResult;
|
||||
// Prepend an element V onto the beginning of a tuple T.
|
||||
// Cons<1, [2,3,4]> is [1,2,3,4]
|
||||
type Cons<V, T extends any[]> = ((v: V, ...t: T) => void) extends ((...r: infer R) => void)
|
||||
? R
|
||||
: never;
|
||||
// Append an element V onto the end of a tuple T
|
||||
// Push<[1,2,3],4> is [1,2,3,4]
|
||||
// note that this DOES NOT PRESERVE optionality/readonly in tuples.
|
||||
// So unfortunately Push<[1, 2?, 3?], 4> is [1,2|undefined,3|undefined,4]
|
||||
type Push<T extends any[], V> = (Cons<any, Required<T>> extends infer R
|
||||
? { [K in keyof R]: K extends keyof T ? T[K] : V }
|
||||
: never) extends infer P
|
||||
? P extends any[] ? P : never
|
||||
: never;
|
||||
|
||||
export type OnCallFunction<CodecResult, SubscriptionResult> = (...params: Array<CodecArg>) => CodecResult | SubscriptionResult;
|
||||
// Returns the inner type of an Observable
|
||||
export type ObsInnerType<O extends Observable<any>> = O extends Observable<infer U> ? U : never;
|
||||
|
||||
// checked against max. params in jsonrpc, 1 for subs, 3 without
|
||||
export interface DecoratedRpc$Method<CodecResult, SubscriptionResult> {
|
||||
(callback: CodecCallback): SubscriptionResult;
|
||||
(arg1: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): CodecResult;
|
||||
export type UnsubscribePromise = Promise<() => void>;
|
||||
|
||||
// In the abstract `decorateMethod` in Base.ts, we can also pass in some meta-
|
||||
// information. This describes it.
|
||||
export type DecorateMethodOptions = {
|
||||
methodName?: string
|
||||
};
|
||||
|
||||
// Here are the return types of these parts of the api:
|
||||
// - api.query.*.*: no exact typings
|
||||
// - api.tx.*.*: SubmittableExtrinsic<ApiType>
|
||||
// - api.derive.*.*: MethodResult<ApiType, F>
|
||||
// - api.rpc.*.*: no exact typings (for now, FIXME: should be MethodResult<ApiType, F>, like in derive)
|
||||
|
||||
// These are the types that don't lose type information (used for api.derive.*)
|
||||
// Also use these for api.rpc.* https://github.com/polkadot-js/api/issues/1009
|
||||
export type RxResult<F extends AnyFunction> = (...args: Parameters<F>) => Observable<ObsInnerType<ReturnType<F>>>;
|
||||
export type PromiseResult<F extends AnyFunction> = {
|
||||
(...args: Parameters<F>): Promise<ObsInnerType<ReturnType<F>>>,
|
||||
(...args: Push<Parameters<F>, Callback<ObsInnerType<ReturnType<F>>>>): UnsubscribePromise
|
||||
};
|
||||
// FIXME The day TS has higher-kinded types, we can remove this hardcoded stuff
|
||||
export type MethodResult<ApiType, F extends AnyFunction> = ApiType extends 'rxjs'
|
||||
? RxResult<F>
|
||||
: PromiseResult<F>;
|
||||
|
||||
type DecoratedRpc$Method<ApiType> = ApiType extends 'rxjs'
|
||||
? {
|
||||
(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Observable<Codec>
|
||||
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Observable<T>
|
||||
}
|
||||
: {
|
||||
// These signatures are allowed and exposed here (bit or a stoopid way, but checked
|
||||
// RPCs and we have 3 max args, with subs max one arg... YMMV) -
|
||||
// (arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Promise<Codec>;
|
||||
// (arg1: CodecArg, callback: Callback<Codec>): UnsubscribePromise;
|
||||
// (callback: Callback<Codec>): UnsubscribePromise;
|
||||
(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Promise<Codec>;
|
||||
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Promise<T>;
|
||||
<T extends Codec>(callback: Callback<T>): UnsubscribePromise;
|
||||
<T extends Codec>(arg: CodecArg, callback: Callback<T>): UnsubscribePromise;
|
||||
};
|
||||
|
||||
// FIXME https://github.com/polkadot-js/api/issues/1009
|
||||
export interface DecoratedRpc$Section<ApiType> {
|
||||
[index: string]: DecoratedRpc$Method<ApiType>;
|
||||
}
|
||||
|
||||
export interface DecoratedRpc$Section<CodecResult, SubscriptionResult> {
|
||||
[index: string]: DecoratedRpc$Method<CodecResult, SubscriptionResult>;
|
||||
// FIXME https://github.com/polkadot-js/api/issues/1009
|
||||
export interface DecoratedRpc<ApiType> {
|
||||
author: DecoratedRpc$Section<ApiType>;
|
||||
chain: DecoratedRpc$Section<ApiType>;
|
||||
state: DecoratedRpc$Section<ApiType>;
|
||||
system: DecoratedRpc$Section<ApiType>;
|
||||
}
|
||||
|
||||
export interface DecoratedRpc<CodecResult, SubscriptionResult> {
|
||||
author: DecoratedRpc$Section<CodecResult, SubscriptionResult>;
|
||||
chain: DecoratedRpc$Section<CodecResult, SubscriptionResult>;
|
||||
state: DecoratedRpc$Section<CodecResult, SubscriptionResult>;
|
||||
system: DecoratedRpc$Section<CodecResult, SubscriptionResult>;
|
||||
}
|
||||
|
||||
export type HashResult<CodecResult, SubscriptionResult> =
|
||||
CodecResult extends Observable<any>
|
||||
? Observable<Hash>
|
||||
: Promise<Hash>;
|
||||
|
||||
export type U64Result<CodecResult, SubscriptionResult> =
|
||||
CodecResult extends Observable<any>
|
||||
? Observable<U64>
|
||||
: Promise<U64>;
|
||||
|
||||
export interface QueryableStorageFunctionBase<CodecResult, SubscriptionResult> extends StorageFunction {
|
||||
(arg1?: CodecArg, arg2?: CodecArg): CodecResult;
|
||||
at: (hash: Hash | Uint8Array | string, arg1?: CodecArg, arg2?: CodecArg) => CodecResult;
|
||||
interface StorageFunctionObservable {
|
||||
(arg1?: CodecArg, arg2?: CodecArg): Observable<Codec>;
|
||||
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg): Observable<T>;
|
||||
at: (hash: Hash | Uint8Array | string, arg1?: CodecArg, arg2?: CodecArg) => Observable<Codec>;
|
||||
creator: StorageFunction;
|
||||
hash: (arg1?: CodecArg, arg2?: CodecArg) => HashResult<CodecResult, SubscriptionResult>;
|
||||
hash: (arg1?: CodecArg, arg2?: CodecArg) => Observable<Hash>;
|
||||
key: (arg1?: CodecArg, arg2?: CodecArg) => string;
|
||||
multi: (args: Array<CodecArg[] | CodecArg>, callback?: CodecCallback) => SubscriptionResult;
|
||||
size: (arg1?: CodecArg, arg2?: CodecArg) => U64Result<CodecResult, SubscriptionResult>;
|
||||
multi: (args: Array<CodecArg[] | CodecArg>) => Observable<Codec>;
|
||||
size: (arg1?: CodecArg, arg2?: CodecArg) => Observable<U64>;
|
||||
}
|
||||
|
||||
interface QueryableStorageFunctionPromise<CodecResult, SubscriptionResult> extends QueryableStorageFunctionBase<CodecResult, SubscriptionResult> {
|
||||
(callback: CodecCallback): SubscriptionResult;
|
||||
(arg: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
(arg1: CodecArg, arg2: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
export interface StorageFunctionPromiseOverloads {
|
||||
(arg1?: CodecArg, arg2?: CodecArg): Promise<Codec>;
|
||||
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg): Promise<T>;
|
||||
<T extends Codec>(callback: Callback<T>): UnsubscribePromise;
|
||||
<T extends Codec>(arg: CodecArg, callback: Callback<T>): UnsubscribePromise;
|
||||
<T extends Codec>(arg1: CodecArg, arg2: CodecArg, callback: Callback<T>): UnsubscribePromise;
|
||||
}
|
||||
|
||||
export type QueryableStorageFunction<CodecResult, SubscriptionResult> =
|
||||
CodecResult extends Observable<any>
|
||||
? QueryableStorageFunctionBase<CodecResult, SubscriptionResult>
|
||||
: QueryableStorageFunctionPromise<CodecResult, SubscriptionResult>;
|
||||
|
||||
export interface QueryableModuleStorage<CodecResult, SubscriptionResult> {
|
||||
[index: string]: QueryableStorageFunction<CodecResult, SubscriptionResult>;
|
||||
interface StorageFunctionPromise extends StorageFunctionPromiseOverloads {
|
||||
at: (hash: Hash | Uint8Array | string, arg1?: CodecArg, arg2?: CodecArg) => Promise<Codec>;
|
||||
creator: StorageFunction;
|
||||
hash: (arg1?: CodecArg, arg2?: CodecArg) => Promise<Hash>;
|
||||
key: (arg1?: CodecArg, arg2?: CodecArg) => string;
|
||||
multi: <T extends Codec>(args: Array<CodecArg[] | CodecArg>, callback?: Callback<Array<T>>) => Promise<Array<T>>;
|
||||
size: (arg1?: CodecArg, arg2?: CodecArg) => Promise<U64>;
|
||||
}
|
||||
|
||||
export type QueryableStorageMultiArg<CodecResult, SubscriptionResult> =
|
||||
QueryableStorageFunction<CodecResult, SubscriptionResult> |
|
||||
[QueryableStorageFunction<CodecResult, SubscriptionResult>, ...Array<CodecArg>];
|
||||
export type QueryableStorageFunction<ApiType> =
|
||||
ApiType extends 'rxjs'
|
||||
? StorageFunctionObservable
|
||||
: StorageFunctionPromise;
|
||||
|
||||
export type QueryableStorageMultiArgs<CodecResult, SubscriptionResult> = Array<QueryableStorageMultiArg<CodecResult, SubscriptionResult>>;
|
||||
|
||||
export interface QueryableStorageMultiBase<CodecResult, SubscriptionResult> {
|
||||
(calls: QueryableStorageMultiArgs<CodecResult, SubscriptionResult>): SubscriptionResult;
|
||||
export interface QueryableModuleStorage<ApiType> {
|
||||
[index: string]: QueryableStorageFunction<ApiType>;
|
||||
}
|
||||
|
||||
export interface QueryableStorageMultiPromise<CodecResult, SubscriptionResult> {
|
||||
(calls: QueryableStorageMultiArgs<CodecResult, SubscriptionResult>, callback: CodecCallback): SubscriptionResult;
|
||||
export type QueryableStorageMultiArg<ApiType> =
|
||||
QueryableStorageFunction<ApiType> |
|
||||
[QueryableStorageFunction<ApiType>, ...Array<CodecArg>];
|
||||
|
||||
export type QueryableStorageMultiArgs<ApiType> = Array<QueryableStorageMultiArg<ApiType>>;
|
||||
|
||||
export interface QueryableStorageMultiBase<ApiType> {
|
||||
(calls: QueryableStorageMultiArgs<ApiType>): UnsubscribePromise;
|
||||
}
|
||||
|
||||
export type QueryableStorageMulti<CodecResult, SubscriptionResult> =
|
||||
CodecResult extends Observable<any>
|
||||
? QueryableStorageMultiBase<CodecResult, SubscriptionResult>
|
||||
: QueryableStorageMultiPromise<CodecResult, SubscriptionResult>;
|
||||
|
||||
export interface QueryableStorage<CodecResult, SubscriptionResult> {
|
||||
[index: string]: QueryableModuleStorage<CodecResult, SubscriptionResult>;
|
||||
export interface QueryableStorageMultiPromise<ApiType> {
|
||||
<T extends Codec>(calls: QueryableStorageMultiArgs<ApiType>, callback: Callback<Array<T>>): UnsubscribePromise;
|
||||
}
|
||||
|
||||
export interface SubmittableExtrinsicFunction<CodecResult, SubscriptionResult> extends MethodFunction {
|
||||
(...params: Array<CodecArg>): SubmittableExtrinsic<CodecResult, SubscriptionResult>;
|
||||
export type QueryableStorageMulti<ApiType> =
|
||||
ApiType extends 'rxjs'
|
||||
? QueryableStorageMultiBase<ApiType>
|
||||
: QueryableStorageMultiPromise<ApiType>;
|
||||
|
||||
export interface QueryableStorage<ApiType> {
|
||||
[index: string]: QueryableModuleStorage<ApiType>;
|
||||
}
|
||||
|
||||
export interface SubmittableModuleExtrinsics<CodecResult, SubscriptionResult> {
|
||||
[index: string]: SubmittableExtrinsicFunction<CodecResult, SubscriptionResult>;
|
||||
export interface SubmittableExtrinsicFunction<ApiType> extends MethodFunction {
|
||||
(...params: Array<CodecArg>): SubmittableExtrinsic<ApiType>;
|
||||
}
|
||||
|
||||
export interface SubmittableExtrinsics<CodecResult, SubscriptionResult> {
|
||||
(extrinsic: Uint8Array | string): SubmittableExtrinsic<CodecResult, SubscriptionResult>;
|
||||
[index: string]: SubmittableModuleExtrinsics<CodecResult, SubscriptionResult>;
|
||||
export interface SubmittableModuleExtrinsics<ApiType> {
|
||||
[index: string]: SubmittableExtrinsicFunction<ApiType>;
|
||||
}
|
||||
|
||||
export interface DeriveMethodBase<CodecResult, SubscriptionResult> {
|
||||
(...params: Array<CodecArg>): CodecResult;
|
||||
}
|
||||
|
||||
interface DeriveMethodPromise<CodecResult, SubscriptionResult> extends DeriveMethodBase<CodecResult, SubscriptionResult> {
|
||||
(callback: CodecCallback): SubscriptionResult;
|
||||
(arg0: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
(arg0: CodecArg, arg1: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
(arg0: CodecArg, arg1: CodecArg, arg2: CodecArg, callback: CodecCallback): SubscriptionResult;
|
||||
}
|
||||
|
||||
export type DeriveMethod<CodecResult, SubscriptionResult> =
|
||||
CodecResult extends Observable<any>
|
||||
? DeriveMethodBase<CodecResult, SubscriptionResult>
|
||||
: DeriveMethodPromise<CodecResult, SubscriptionResult>;
|
||||
|
||||
export interface DeriveSection<CodecResult, SubscriptionResult> {
|
||||
[index: string]: DeriveMethod<CodecResult, SubscriptionResult>;
|
||||
}
|
||||
|
||||
export interface Derive<CodecResult, SubscriptionResult> {
|
||||
[index: string]: DeriveSection<CodecResult, SubscriptionResult>;
|
||||
export interface SubmittableExtrinsics<ApiType> {
|
||||
(extrinsic: Uint8Array | string): SubmittableExtrinsic<ApiType>;
|
||||
[index: string]: SubmittableModuleExtrinsics<ApiType>;
|
||||
}
|
||||
|
||||
export interface ApiOptions {
|
||||
@@ -156,7 +185,7 @@ export interface ApiOptions {
|
||||
/**
|
||||
* @description The source object to use for runtime information (only used when cloning)
|
||||
*/
|
||||
source?: ApiBase<any, any>;
|
||||
source?: ApiBase<any>;
|
||||
/**
|
||||
* @description Additional types used by runtime modules. This is nessusary if the runtime modules
|
||||
* uses types not available in the base Substrate runtime.
|
||||
@@ -164,31 +193,22 @@ export interface ApiOptions {
|
||||
types?: RegistryTypes;
|
||||
}
|
||||
|
||||
export interface ApiInterface$Decorated<CodecResult, SubscriptionResult> {
|
||||
// A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic
|
||||
export interface ApiInterface$Rx {
|
||||
genesisHash: Hash;
|
||||
hasSubscriptions: boolean;
|
||||
runtimeMetadata: Metadata;
|
||||
runtimeVersion: RuntimeVersion;
|
||||
derive: Derive<CodecResult, SubscriptionResult>;
|
||||
query: QueryableStorage<CodecResult, SubscriptionResult>;
|
||||
queryMulti: QueryableStorageMulti<CodecResult, SubscriptionResult>;
|
||||
rpc: DecoratedRpc<CodecResult, SubscriptionResult>;
|
||||
tx: SubmittableExtrinsics<CodecResult, SubscriptionResult>;
|
||||
query: QueryableStorage<'rxjs'>;
|
||||
queryMulti: QueryableStorageMulti<'rxjs'>;
|
||||
rpc: DecoratedRpc<'rxjs'>;
|
||||
tx: SubmittableExtrinsics<'rxjs'>;
|
||||
signer?: Signer;
|
||||
}
|
||||
|
||||
export type ApiInterface$Rx = ApiInterface$Decorated<RxResult, RxResult>;
|
||||
|
||||
export type ApiInterface$Events = RpcRxInterface$Events | 'ready';
|
||||
|
||||
export type ApiType = 'promise' | 'rxjs';
|
||||
|
||||
export interface ApiBaseInterface<CodecResult, SubscriptionResult> extends Readonly<ApiInterface$Decorated<CodecResult, SubscriptionResult>> {
|
||||
readonly type: ApiType;
|
||||
|
||||
on: (type: ApiInterface$Events, handler: (...args: Array<any>) => any) => this;
|
||||
once: (type: ApiInterface$Events, handler: (...args: Array<any>) => any) => this;
|
||||
}
|
||||
export type ApiTypes = 'promise' | 'rxjs';
|
||||
|
||||
export type SignerOptions = SignatureOptions & {
|
||||
genesisHash: Hash
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// 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 { AnyFunction } from '@polkadot/types/types';
|
||||
import { MethodResult } from '../types';
|
||||
|
||||
// A technically unsafe version of Object.keys(obj) that assumes that
|
||||
// obj only has known properties of T
|
||||
function keys<T extends object> (obj: T) {
|
||||
return Object.keys(obj) as Array<keyof T>;
|
||||
}
|
||||
|
||||
function decorateMethods<ApiType, Section extends Record<keyof Section, (...args: Array<any>) => any>> (
|
||||
section: Section,
|
||||
decorateMethod: <Method extends AnyFunction>(method: Method) => MethodResult<ApiType, Method>
|
||||
) {
|
||||
return keys(section).reduce(
|
||||
<MethodName extends keyof Section>(
|
||||
acc: { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> },
|
||||
methodName: MethodName
|
||||
) => {
|
||||
const method = section[methodName];
|
||||
|
||||
acc[methodName] = decorateMethod(method) as any;
|
||||
|
||||
return acc;
|
||||
},
|
||||
{} as { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a section decorator which keeps all type information.
|
||||
*/
|
||||
export function decorateSections<ApiType, AllSections extends {
|
||||
[SectionName in keyof AllSections]: Record<keyof AllSections[SectionName], (...args: any[]) => any>
|
||||
}> (
|
||||
allSections: AllSections,
|
||||
decorateMethod: <Method extends AnyFunction>(method: Method) => MethodResult<ApiType, Method>
|
||||
) {
|
||||
return keys(allSections).reduce(
|
||||
<MethodName extends keyof AllSections>(
|
||||
acc: { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } },
|
||||
sectionName: MethodName
|
||||
) => {
|
||||
acc[sectionName] = decorateMethods(allSections[sectionName], decorateMethod);
|
||||
|
||||
return acc;
|
||||
},
|
||||
{} as { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } }
|
||||
);
|
||||
}
|
||||
@@ -84,7 +84,7 @@ describe.skip('alex queries', () => {
|
||||
});
|
||||
|
||||
it('subscribes to events', (done) => {
|
||||
api.query.system.events((events: Array<EventRecord>) => {
|
||||
return api.query.system.events((events: Vector<EventRecord>) => {
|
||||
expect(events).not.toHaveLength(0);
|
||||
done();
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import BN from 'bn.js';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import { LinkageResult } from '@polkadot/types/codec/Linkage';
|
||||
import { Balance, EventRecord, Header, Option, Vector } from '@polkadot/types';
|
||||
import { Balance, EventRecord, Header, Option, ValidatorPrefs, Vector } from '@polkadot/types';
|
||||
|
||||
import Api from './../../src/promise';
|
||||
|
||||
@@ -55,7 +55,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
|
||||
it('queries state for a balance', async () => {
|
||||
return (
|
||||
api.query.balances.freeBalance(keyring.alice.address, (balance) => {
|
||||
api.query.balances.freeBalance(keyring.alice.address, (balance: Balance) => {
|
||||
expect(balance).toBeInstanceOf(BN);
|
||||
expect(balance.isZero()).toBe(false);
|
||||
})
|
||||
@@ -64,7 +64,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
|
||||
it('subscribes to rpc', (done) => {
|
||||
return (
|
||||
api.rpc.chain.subscribeNewHead((header) => {
|
||||
api.rpc.chain.subscribeNewHead((header: Header) => {
|
||||
expect(header.blockNumber.isZero()).toBe(false);
|
||||
|
||||
done();
|
||||
@@ -74,7 +74,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
|
||||
it('subscribes to finalized', (done) => {
|
||||
return (
|
||||
api.rpc.chain.subscribeFinalizedHeads((header) => {
|
||||
api.rpc.chain.subscribeFinalizedHeads((header: Header) => {
|
||||
expect(header.blockNumber.isZero()).toBe(false);
|
||||
|
||||
done();
|
||||
@@ -104,7 +104,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
|
||||
it.skip('subscribes to queries (default)', (done) => {
|
||||
return (
|
||||
api.query.staking.validators(keyring.ferdie.address, (prefs) => {
|
||||
api.query.staking.validators(keyring.ferdie.address, (prefs: ValidatorPrefs) => {
|
||||
expect(prefs.unstakeThreshold.toNumber()).toBe(3);
|
||||
|
||||
done();
|
||||
@@ -114,7 +114,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
|
||||
it('subscribes to a linked map (staking.validators)', (done) => {
|
||||
return (
|
||||
api.query.staking.validators((prefs) => {
|
||||
api.query.staking.validators((prefs: LinkageResult) => {
|
||||
expect(prefs instanceof LinkageResult).toBe(true);
|
||||
|
||||
done();
|
||||
@@ -143,7 +143,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
[api.query.balances.freeBalance, keyring.bob.address],
|
||||
[api.query.balances.freeBalance, '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y'],
|
||||
[api.query.balances.freeBalance, keyring.ferdie.address]
|
||||
], (balances: Array<BN>) => {
|
||||
], (balances: Array<Balance>) => {
|
||||
expect(balances).toHaveLength(4);
|
||||
|
||||
done();
|
||||
@@ -213,7 +213,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
});
|
||||
|
||||
it('subscribes to query and get correct result', (done) => {
|
||||
return api.query.balances.existentialDeposit((existentialDeposit) => {
|
||||
return api.query.balances.existentialDeposit((existentialDeposit: Balance) => {
|
||||
expect(existentialDeposit.toNumber()).toEqual(EXISTENTIAL_DEPOSIT);
|
||||
done();
|
||||
});
|
||||
@@ -261,7 +261,7 @@ describe.skip('Promise e2e queries', () => {
|
||||
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
|
||||
const balance = await api.query.balances.freeBalance(keyring.alice.address);
|
||||
|
||||
return api.query.balances.freeBalance(keyring.alice.address, (balanceSubscribed) => {
|
||||
return api.query.balances.freeBalance(keyring.alice.address, (balanceSubscribed: Balance) => {
|
||||
expect(balanceSubscribed.isZero()).toBe(false);
|
||||
expect(balanceSubscribed.toString()).toEqual(balance.toString());
|
||||
done();
|
||||
|
||||
@@ -6,7 +6,7 @@ import Keyring from '@polkadot/keyring';
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import { randomAsHex } from '@polkadot/util-crypto';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { EventRecord, ExtrinsicEra, Hash, Index, SignedBlock } from '@polkadot/types';
|
||||
import { EventRecord, ExtrinsicEra, Hash, Header, Index, SignedBlock } from '@polkadot/types';
|
||||
|
||||
import SingleAccountSigner from '../util/SingleAccountSigner';
|
||||
import { SubmittableResult } from './../../src';
|
||||
@@ -190,7 +190,7 @@ describe.skip('Promise e2e transactions', () => {
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
|
||||
|
||||
return (
|
||||
api.rpc.chain.subscribeNewHead(async (header) => {
|
||||
api.rpc.chain.subscribeNewHead(async (header: Header) => {
|
||||
if (header.blockNumber.toNumber() === eraDeath - 1) {
|
||||
const hash = await ex.signAndSend(keyring.alice, { blockHash: eraHash, era: exERA, nonce } as any);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user