More small readability enhancements (#1296)

* More small readability enhancements

* Pacify CC on manual checks
This commit is contained in:
Jaco Greeff
2019-08-11 22:44:02 +02:00
committed by GitHub
parent a12a776392
commit 5ee2caf00e
8 changed files with 91 additions and 87 deletions
@@ -26,7 +26,6 @@ import { HeaderAndValidators } from './subscribeNewHead';
*/
export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
return (hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
// tslint:disable-next-line
(combineLatest([
api.rpc.chain.getHeader(hash),
api.query.session
@@ -40,7 +39,6 @@ export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) =>
// where rpc.chain.getHeader throws, we will land here - it can happen that
// we supplied an invalid hash. (Due to defaults, storeage will have an
// empty value, so only the RPC is affected). So return undefined
// tslint:disable-next-line
of() as Observable<undefined>
),
drr()
+14 -12
View File
@@ -12,6 +12,19 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { DerivedElectionsInfo } from '../types';
import { drr } from '../util/drr';
function query (api: ApiInterfaceRx): Observable<[[AccountId, BlockNumber][], AccountId[], BN, BN, SetIndex, BlockNumber, VoteIndex, SetIndex]> {
return api.queryMulti([
api.query.elections.members,
api.query.elections.candidates,
api.query.elections.candidateCount,
api.query.elections.desiredSeats,
api.query.elections.nextVoterSet,
api.query.elections.termDuration,
api.query.elections.voteCount,
api.query.elections.voterCount
]) as any;
}
/**
* @name info
* @returns An object containing the combined results of the storage queries for
@@ -27,18 +40,7 @@ import { drr } from '../util/drr';
*/
export function info (api: ApiInterfaceRx): () => Observable<DerivedElectionsInfo> {
return (): Observable<DerivedElectionsInfo> => {
return (
api.queryMulti([
api.query.elections.members,
api.query.elections.candidates,
api.query.elections.candidateCount,
api.query.elections.desiredSeats,
api.query.elections.nextVoterSet,
api.query.elections.termDuration,
api.query.elections.voteCount,
api.query.elections.voterCount
]) as any as Observable<[[AccountId, BlockNumber][], AccountId[], BN, BN, SetIndex, BlockNumber, VoteIndex, SetIndex]>
).pipe(
return query(api).pipe(
map(([members, candidates, candidateCount, desiredSeats, nextVoterSet, termDuration, voteCount, voterCount]): DerivedElectionsInfo => ({
members: members.reduce(
(record: Record<string, BlockNumber>, [accountId, blockNumber]): Record<string, BlockNumber> => {
+49 -36
View File
@@ -9,16 +9,31 @@ import { Balance, Header, Index } from '@polkadot/types/interfaces';
import { ApiPromise } from '@polkadot/api';
import { HeaderExtended } from '@polkadot/api-derive';
import { ConstantCodec } from '@polkadot/api-metadata/consts/types';
import testKeyring from '@polkadot/keyring/testingPairs';
import testKeyring, { TestKeyringMap } from '@polkadot/keyring/testingPairs';
import { IExtrinsic, IMethod } from '@polkadot/types/types';
import createType, { createTypeUnsafe } from '@polkadot/types/codec/createType';
import { SubmittableResult } from './';
export default async function test (): Promise<void> {
const api = await ApiPromise.create();
const keyring = testKeyring();
async function consts (api: ApiPromise): Promise<void> {
// constants has actual value & metadata
console.log(
api.consts.balances.creationFee.toHex(),
(api.consts.balances.creationFee as ConstantCodec).meta.documentation.map((s): string => s.toString()).join('')
);
}
async function derive (api: ApiPromise): Promise<void> {
await api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
console.log('current author:', header.author);
});
await api.query.staking.intentions((intentions): void => {
console.log('intentions:', intentions);
});
}
async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
const intentions = await api.query.staking.intentions();
console.log('intentions:', intentions);
@@ -31,35 +46,32 @@ export default async function test (): Promise<void> {
multiUnsub();
});
}
// rpc section
async function rpc (api: ApiPromise): Promise<void> {
await api.rpc.chain.subscribeNewHead((header: Header): void => {
console.log('current blockNumber:', header.number);
console.log('current header:', header);
});
await api.rpc.state.subscribeStorage<[Balance]>(['my_balance_key'], ([balance]): void => {
console.log('current balance:', balance.toString());
});
}
// derives
await api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
console.log('current author:', header.author);
});
function types (): void {
// check correct types with `createType`
const balance = createType('Balance', 2);
const gas = createType('Gas', 2);
const compact = createType('Compact<u32>', 2);
// const random = createType('RandomType', 2); // This one should deliberately show a TS error
await api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
console.log('current author:', header.author);
});
const gasUnsafe = createTypeUnsafe('Gas', [2]);
const overriddenUnsafe = createTypeUnsafe<Header>('Gas', [2]);
await api.query.staking.intentions((intentions): void => {
console.log('intentions:', intentions);
});
// constants has actual value & metadata
console.log(
api.consts.balances.creationFee.toHex(),
(api.consts.balances.creationFee as ConstantCodec).meta.documentation.map((s): string => s.toString()).join('')
);
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
}
async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
const transfer = api.tx.balances.transfer(keyring.bob.address, 12345);
console.log('transfer as Call', transfer as IMethod);
@@ -77,12 +89,10 @@ export default async function test (): Promise<void> {
).toHex();
// just with the callback
const unsub = await api.tx.balances
await api.tx.balances
.transfer(keyring.bob.address, 12345)
.signAndSend(keyring.alice, ({ status }: SubmittableResult): void => {
console.log('transfer status:', status.type);
unsub();
});
// with options and the callback
@@ -94,15 +104,18 @@ export default async function test (): Promise<void> {
unsub2();
});
// check correct types with `createType`
const balance = createType('Balance', 2);
const gas = createType('Gas', 2);
const compact = createType('Compact<u32>', 2);
// const random = createType('RandomType', 2); // This one should deliberately show a TS error
const gasUnsafe = createTypeUnsafe('Gas', [2]);
const overriddenUnsafe = createTypeUnsafe<Header>('Gas', [2]);
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
}
async function main (): Promise<void> {
const api = await ApiPromise.create();
const keyring = testKeyring();
consts(api);
derive(api);
query(api, keyring);
rpc(api);
types();
tx(api, keyring);
}
main().catch(console.error);
-3
View File
@@ -217,9 +217,6 @@ export default class ApiPromise extends ApiBase<'promise'> {
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
}
// FIXME TSLint shouts that type assertion is unnecessary, but tsc shouts
// when I remove it...
// tslint:disable-next-line
return new Promise((resolve, reject): void => {
let isCompleted = false;
const subscription = method(...actualArgs)
@@ -2,7 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// tslint:disable-next-line
if (typeof fetch === 'undefined') {
require('isomorphic-fetch');
}
-1
View File
@@ -2,7 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// tslint:disable-next-line
if (typeof WebSocket === 'undefined') {
// @ts-ignore
global.WebSocket = require('websocket').w3cwebsocket;
@@ -8,34 +8,34 @@ import { getTypeDef } from '../../codec/createType';
import flattenUniq from './flattenUniq';
import { getTypeRegistry } from '../../codec';
function extractTypes (types: string[]): any[] {
return types.map((type): any => {
const decoded = getTypeDef(type);
switch (decoded.info) {
case TypeDefInfo.Plain:
return decoded.type;
case TypeDefInfo.Compact:
case TypeDefInfo.Option:
case TypeDefInfo.Vec:
return extractTypes([(decoded.sub as TypeDef).type]);
case TypeDefInfo.VecFixed:
return extractTypes([(decoded.ext as TypeDefExtVecFixed).type]);
case TypeDefInfo.Tuple:
return extractTypes(
(decoded.sub as TypeDef[]).map((sub): string => sub.type)
);
default:
throw new Error(`Uhandled: Unnable to create and validate type from ${type}`);
}
});
}
export default function validateTypes (types: string[], throwError: boolean): void {
const extractTypes = (types: string[]): any[] => {
return types.map((type): any => {
const decoded = getTypeDef(type);
switch (decoded.info) {
case TypeDefInfo.Plain:
return decoded.type;
case TypeDefInfo.Compact:
case TypeDefInfo.Option:
case TypeDefInfo.Vec:
return extractTypes([(decoded.sub as TypeDef).type]);
case TypeDefInfo.VecFixed:
return extractTypes([(decoded.ext as TypeDefExtVecFixed).type]);
case TypeDefInfo.Tuple:
return extractTypes(
(decoded.sub as TypeDef[]).map((sub): string => sub.type)
);
default:
throw new Error(`Uhandled: Unnable to create and validate type from ${type}`);
}
});
};
const typeRegistry = getTypeRegistry();
const missing = flattenUniq(extractTypes(types)).filter((type): boolean =>
!typeRegistry.hasType(type)
+1 -5
View File
@@ -25,11 +25,7 @@ type FromReg<T extends Codec, K extends string> = K extends InterfaceTypes ? Int
// safely split a string on ', ' while taking care of any nested occurences
export function typeSplit (type: string): string[] {
let cDepth = 0; // compact/doublemap/linkedmap/option/vector depth
let fDepth = 0; // vector (fixed) depth
let sDepth = 0; // struct depth
let tDepth = 0; // tuple depth
let start = 0;
let [cDepth, fDepth, sDepth, tDepth, start] = [0, 0, 0, 0, 0];
const result = [];
for (let index = 0; index < type.length; index++) {