Make derive types work, and a bit more readable (#1430)

* Fix typings for derive

* Fix typings

* Spacing
This commit is contained in:
Amaury Martiny
2019-10-01 14:30:53 +02:00
committed by GitHub
parent bddb48f452
commit fadb1ffdd8
11 changed files with 70 additions and 65 deletions
+1 -1
View File
@@ -53,7 +53,7 @@ export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes>
});
return result;
}, {} as unknown as AccountIndexes)),
}, {} as AccountIndexes)),
drr()
);
};
+1 -1
View File
@@ -53,7 +53,7 @@ function calcBalances ([accountId = createType('AccountId'), bestNumber = create
reservedBalance,
vestedBalance,
votingBalance: freeBalance.add(reservedBalance)
} as unknown as DerivedBalances;
} as DerivedBalances;
}
/**
+1 -1
View File
@@ -62,7 +62,7 @@ export function fees (api: ApiInterfaceRx): () => Observable<DerivedFees> {
transactionBaseFee,
transactionByteFee,
transferFee
} as unknown as DerivedFees)),
})),
drr()
);
};
+2 -2
View File
@@ -6,11 +6,11 @@ import { Observable, from } from 'rxjs';
import ApiRx from '@polkadot/api/rx/Api';
import MockProvider from '@polkadot/rpc-provider/mock';
import { Derive } from '.';
import { ExactDerive } from '.';
const testFunction = (api: ApiRx): any => {
return <
Section extends keyof Derive,
Section extends keyof ExactDerive,
Method extends keyof (typeof api.derive[Section])
>(section: Section, method: Method, inputs: any[]): void => {
describe(`derive.${section}.${method}`, (): void => {
+12 -13
View File
@@ -19,14 +19,13 @@ import * as staking from './staking';
export * from './type';
export type ReturnTypes<Section> = {
type DeriveSection<Section> = {
[Method in keyof Section]: Section[Method] extends AnyFunction
? ReturnType<Section[Method]> // ReturnType<Section[Method]> will be the inner function, i.e. without (api) argument
: never;
};
export type DeriveSections<AllSections> = {
[Section in keyof AllSections]: ReturnTypes<AllSections[Section]>
type DeriveAllSections<AllSections> = {
[Section in keyof AllSections]: DeriveSection<AllSections[Section]>
};
export type DeriveCustom = Record<string, Record<string, (api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
@@ -35,15 +34,15 @@ export type DeriveCustom = Record<string, Record<string, (api: ApiInterfaceRx) =
* Returns an object that will inject `api` into all the functions inside
* `allSections`, and keep the object architecture of `allSections`.
*/
function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSections): DeriveSections<AllSections> {
function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
return Object
.keys(allSections)
.reduce((deriveAcc, sectionName): DeriveSections<AllSections> => {
.reduce((deriveAcc, sectionName): DeriveAllSections<AllSections> => {
const section = allSections[sectionName as keyof AllSections];
deriveAcc[sectionName as keyof AllSections] = Object
.keys(section)
.reduce((sectionAcc, _methodName): ReturnTypes<typeof section> => {
.reduce((sectionAcc, _methodName): DeriveSection<typeof section> => {
const methodName = _methodName as keyof typeof section;
// Not sure what to do here, casting as any. Though the final types are good
const method = (section[methodName] as any)(api);
@@ -51,18 +50,18 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
(sectionAcc as any)[methodName] = method;
return sectionAcc;
}, {} as unknown as ReturnTypes<typeof section>);
}, {} as DeriveSection<typeof section>);
return deriveAcc;
}, {} as unknown as DeriveSections<AllSections>);
}, {} as DeriveAllSections<AllSections>);
}
export const derive = { accounts, balances, chain, contracts, democracy, elections, imOnline, session, staking };
export type Derive = typeof derive;
export type ExactDerive = DeriveAllSections<typeof derive>;
// FIXME I have no idea how to get this done
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}) {
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
// For now we just drop the custom derive typings
export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
return {
...injectFunctions(api, derive),
...injectFunctions(api, custom)
+24 -24
View File
@@ -4,18 +4,20 @@
import { RpcMethod } from '@polkadot/jsonrpc/types';
import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
// Unfortunately we cannot import individual interfaces here, because the
// return type of `decorateDerive` needs to have all interfaces. See
// https://github.com/polkadot-js/api/issues/1425 for more info.
import * as t from '@polkadot/types/interfaces';
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ModulesWithCalls } from '@polkadot/types/types';
import { SubmittableExtrinsic } from '../submittable/types';
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import {
ApiInterfaceRx, ApiOptions, ApiTypes,
DecorateMethod, DecoratedRpc, DecoratedRpcSection,
QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg,
SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics
} from '../types';
import BN from 'bn.js';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import decorateDerive from '@polkadot/api-derive';
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
import { Constants } from '@polkadot/api-metadata/consts/types';
import { Storage } from '@polkadot/api-metadata/storage/types';
import jsonrpc from '@polkadot/jsonrpc';
@@ -28,7 +30,7 @@ import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
import { compactStripLength, u8aToHex } from '@polkadot/util';
import { createSubmittable } from '../submittable';
import { decorateSections } from '../util/decorate';
import { decorateSections, DeriveAllSections } from '../util/decorate';
import Events from './Events';
interface MetaDecoration {
@@ -51,7 +53,7 @@ export default abstract class Decorate<ApiType> extends Events {
protected _extrinsicType: number = EXTRINSIC_DEFAULT_VERSION;
protected _genesisHash?: t.Hash;
protected _genesisHash?: Hash;
protected _isConnected: BehaviorSubject<boolean>;
@@ -71,7 +73,7 @@ export default abstract class Decorate<ApiType> extends Events {
protected _runtimeMetadata?: Metadata;
protected _runtimeVersion?: t.RuntimeVersion;
protected _runtimeVersion?: RuntimeVersion;
protected _rx: Partial<ApiInterfaceRx> = {};
@@ -93,7 +95,7 @@ export default abstract class Decorate<ApiType> extends Events {
* implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon
* via `deocrateMethod`.
*/
protected decorateMethod: DecorateMethod;
protected decorateMethod: DecorateMethod<ApiType>;
/**
* @description Create an instance of the class
@@ -113,7 +115,7 @@ export default abstract class Decorate<ApiType> extends Events {
* });
* ```
*/
public constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod) {
public constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
super();
const thisProvider = options.source
@@ -173,7 +175,7 @@ export default abstract class Decorate<ApiType> extends Events {
});
}
protected decorateRpc<ApiType> (rpc: RpcCore, decorateMethod: Decorate<ApiType>['decorateMethod']): DecoratedRpc<ApiType, RpcInterface> {
protected decorateRpc<ApiType> (rpc: RpcCore, decorateMethod: DecorateMethod<ApiType>): DecoratedRpc<ApiType, RpcInterface> {
return Object.keys(jsonrpc).reduce((out, _sectionName): DecoratedRpc<ApiType, RpcInterface> => {
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
@@ -191,7 +193,7 @@ export default abstract class Decorate<ApiType> extends Events {
}, {} as unknown as DecoratedRpc<ApiType, RpcInterface>);
}
protected decorateMulti<ApiType> (decorateMethod: Decorate<ApiType>['decorateMethod']): QueryableStorageMulti<ApiType> {
protected decorateMulti<ApiType> (decorateMethod: DecorateMethod<ApiType>): QueryableStorageMulti<ApiType> {
return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
this._rpcCore.state.subscribeStorage(
calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] =>
@@ -201,7 +203,7 @@ export default abstract class Decorate<ApiType> extends Events {
: [arg.creator] as any)));
}
protected decorateExtrinsics<ApiType> (extrinsics: ModulesWithCalls, decorateMethod: Decorate<ApiType>['decorateMethod']): SubmittableExtrinsics<ApiType> {
protected decorateExtrinsics<ApiType> (extrinsics: ModulesWithCalls, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
const creator = createSubmittable(this._type, this._rx as ApiInterfaceRx, decorateMethod);
return Object.entries(extrinsics).reduce((out, [name, section]): SubmittableExtrinsics<ApiType> => {
@@ -215,14 +217,14 @@ export default abstract class Decorate<ApiType> extends Events {
}, creator as unknown as SubmittableExtrinsics<ApiType>);
}
private decorateExtrinsicEntry<ApiType> (method: CallFunction, creator: (value: t.Call | Uint8Array | string) => SubmittableExtrinsic<ApiType>): SubmittableExtrinsicFunction<ApiType> {
private decorateExtrinsicEntry<ApiType> (method: CallFunction, creator: (value: Call | Uint8Array | string) => SubmittableExtrinsic<ApiType>): SubmittableExtrinsicFunction<ApiType> {
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
creator(method(...params));
return this.decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
}
protected decorateStorage<ApiType> (storage: Storage, decorateMethod: Decorate<ApiType>['decorateMethod']): QueryableStorage<ApiType> {
protected decorateStorage<ApiType> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
return Object.entries(storage).reduce((out, [name, section]): QueryableStorage<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): QueryableModuleStorage<ApiType> => {
out[name] = this.decorateStorageEntry(method, decorateMethod);
@@ -234,7 +236,7 @@ export default abstract class Decorate<ApiType> extends Events {
}, {} as unknown as QueryableStorage<ApiType>);
}
private decorateStorageEntry<ApiType> (creator: StorageEntry, decorateMethod: Decorate<ApiType>['decorateMethod']): QueryableStorageEntry<ApiType> {
private decorateStorageEntry<ApiType> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
const getArgs = (...args: any[]): any[] => creator.meta.type.isDoubleMap
? [creator, args]
@@ -252,10 +254,10 @@ export default abstract class Decorate<ApiType> extends Events {
decorated.creator = creator;
decorated.at = decorateMethod((hash: t.Hash, arg1?: Arg, arg2?: Arg): Observable<Codec> =>
decorated.at = decorateMethod((hash: Hash, arg1?: Arg, arg2?: Arg): Observable<Codec> =>
this._rpcCore.state.getStorage(getArgs(arg1, arg2), hash));
decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<t.Hash> =>
decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<Hash> =>
this._rpcCore.state.getStorageHash(getArgs(arg1, arg2)));
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
@@ -272,7 +274,7 @@ export default abstract class Decorate<ApiType> extends Events {
return this.decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
private decorateStorageEntryLinked<ApiType> (creator: StorageEntry, decorateMethod: Decorate<ApiType>['decorateMethod']): ReturnType<Decorate<ApiType>['decorateMethod']> {
private decorateStorageEntryLinked<ApiType> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
const result: Map<Codec, [Codec, Linkage<Codec>]> = new Map();
let subject: BehaviorSubject<LinkageResult>;
let head: Codec | null = null;
@@ -340,13 +342,11 @@ export default abstract class Decorate<ApiType> extends Events {
);
}
// FIXME Any better ideas? `any` doesn't work, needs a return but TS infers
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
protected decorateDerive (apiRx: ApiInterfaceRx, decorateMethod: Decorate<ApiType>['decorateMethod']) {
protected decorateDerive (apiRx: ApiInterfaceRx, decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<ApiType, ExactDerive> {
// Pull in derive from api-derive
const derive = decorateDerive(apiRx, this._options.derives);
return decorateSections<ApiType, typeof derive>(derive, decorateMethod);
return decorateSections<ApiType, ExactDerive>(derive, decorateMethod);
}
/**
+1 -1
View File
@@ -56,7 +56,7 @@ const l = logger('api/decorator');
export default abstract class Init<ApiType> extends Decorate<ApiType> {
private _healthTimer: NodeJS.Timeout | null = null;
public constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod) {
public constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
super(options, type, decorateMethod);
assert(this._rpcCore.provider.hasSubscriptions, 'Api can only be used with a provider supporting subscriptions');
+2 -2
View File
@@ -26,7 +26,7 @@ try {
pkgJson = { name: '@polkadot/api', version: '-' };
}
function assertResult <T> (value: T | undefined): T {
function assertResult<T> (value: T | undefined): T {
assert(!isUndefined(value), 'Api needs to be initialised before using, listen on \'ready\'');
return value as T;
@@ -51,7 +51,7 @@ export default abstract class ApiBase<ApiType> extends Init<ApiType> {
* });
* ```
*/
public constructor (options: ApiOptions = {}, type: ApiTypes, decorateMethod: DecorateMethod) {
public constructor (options: ApiOptions = {}, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
super(options, type, decorateMethod);
}
+1 -1
View File
@@ -28,7 +28,7 @@ async function derive (api: ApiPromise): Promise<void> {
console.log('current author:', header.author);
});
const fees = api.derive.balances.fees();
const fees = await api.derive.balances.fees();
console.log('fees', fees);
}
+1 -1
View File
@@ -50,7 +50,7 @@ export interface DecorateMethodOptions {
methodName?: string;
}
export type DecorateMethod = (method: (...args: any[]) => Observable<any>, options?: DecorateMethodOptions) => any;
export type DecorateMethod<ApiType> = <Method extends (...args: any[]) => Observable<any>>(method: Method, options?: DecorateMethodOptions) => any;
// Here are the return types of these parts of the api:
// - api.query.*.*: no exact typings
+24 -18
View File
@@ -3,7 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { AnyFunction } from '@polkadot/types/types';
import { MethodResult } from '../types';
import { DecorateMethod, MethodResult } from '../types';
// Most generic typings for `api.derive.*.*`
type AnyDerive = Record<string, Record<string, AnyFunction>>;
// Exact typings for a particular section `api.derive.section.*`
type DeriveSection<ApiType, Section extends Record<string, AnyFunction>> = { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> };
// Exact typings for all sections `api.derive.*.*`
export type DeriveAllSections<ApiType, AllSections extends AnyDerive> = { [SectionName in keyof AllSections]: DeriveSection<ApiType, AllSections[SectionName]> };
// A technically unsafe version of Object.keys(obj) that assumes that
// obj only has known properties of T
@@ -11,45 +18,44 @@ function keys<T extends object> (obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[];
}
// FIXME the return value typings here is horrible and not DRY
function decorateMethods<ApiType, Section extends Record<keyof Section, (...args: any[]) => any>> (
/**
* This is a methods decorator which keeps all type information.
*/
function decorateMethods<ApiType, Section extends Record<string, AnyFunction>> (
section: Section,
decorateMethod: <Method extends AnyFunction>(method: Method) => MethodResult<ApiType, Method>
): { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> } {
decorateMethod: DecorateMethod<ApiType>
): DeriveSection<ApiType, Section> {
return keys(section).reduce(
<MethodName extends keyof Section>(
acc: { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> },
acc: DeriveSection<ApiType, Section>,
methodName: MethodName
): { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> } => {
): DeriveSection<ApiType, Section> => {
const method = section[methodName];
acc[methodName] = decorateMethod(method) as any;
acc[methodName] = decorateMethod(method);
return acc;
},
{} as unknown as { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> }
{} as DeriveSection<ApiType, Section>
);
}
/**
* This is a section decorator which keeps all type information.
*/
// FIXME the return value typings here is horrible and not DRY
export function decorateSections<ApiType, AllSections extends {
[SectionName in keyof AllSections]: Record<keyof AllSections[SectionName], (...args: any[]) => any>
}> (
export function decorateSections<ApiType, AllSections extends AnyDerive> (
allSections: AllSections,
decorateMethod: <Method extends AnyFunction>(method: Method) => MethodResult<ApiType, Method>
): { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } } {
decorateMethod: DecorateMethod<ApiType>
): DeriveAllSections<ApiType, AllSections> {
return keys(allSections).reduce(
<MethodName extends keyof AllSections>(
acc: { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } },
acc: DeriveAllSections<ApiType, AllSections>,
sectionName: MethodName
): { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } } => {
): DeriveAllSections<ApiType, AllSections> => {
acc[sectionName] = decorateMethods(allSections[sectionName], decorateMethod);
return acc;
},
{} as unknown as { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } }
{} as DeriveAllSections<ApiType, AllSections>
);
}