Some small complexity/readability improvements (#1309)

* Some small complexity/readability improvements

* Bump allowed returns to 5

* Revert override (as limiting as it seems)
This commit is contained in:
Jaco Greeff
2019-08-14 20:25:20 +02:00
committed by GitHub
parent c36173c0bb
commit 9954477de3
7 changed files with 132 additions and 110 deletions
+15 -15
View File
@@ -48,23 +48,23 @@ export default class Blueprint extends RxBase {
return this.apiContracts
.create(endowment, maxGas, this.codeHash, this.abi.deploy(...params))
.signAndSend(account)
.pipe(
map((result: SubmittableResult): BlueprintCreateResult => {
let contract: RxContract | undefined;
if (result.isFinalized) {
const record = result.findRecord('contract', 'Instantiated');
if (record) {
contract = new RxContract(this.api, this.abi, record.event.data[1] as Address);
}
}
return new BlueprintCreateResult(result, contract);
})
);
.pipe(map(this.createResult));
};
return { signAndSend };
}
private createResult = (result: SubmittableResult): BlueprintCreateResult => {
let contract: RxContract | undefined;
if (result.isFinalized) {
const record = result.findRecord('contract', 'Instantiated');
if (record) {
contract = new RxContract(this.api, this.abi, record.event.data[1] as Address);
}
}
return new BlueprintCreateResult(result, contract);
}
}
+15 -15
View File
@@ -61,23 +61,23 @@ export default class RxCode extends RxBase {
return this.apiContracts
.putCode(maxGas, compactAddLength(this.code))
.signAndSend(account)
.pipe(
map((result: ISubmittableResult): CodePutCodeResult => {
let blueprint: RxBlueprint | undefined;
if (result.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
blueprint = new RxBlueprint(this.api, this.abi, record.event.data[0] as Hash);
}
}
return new CodePutCodeResult(result, blueprint);
})
);
.pipe(map(this.createResult));
};
return { signAndSend };
}
private createResult = (result: ISubmittableResult): CodePutCodeResult => {
let blueprint: RxBlueprint | undefined;
if (result.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
blueprint = new RxBlueprint(this.api, this.abi, record.event.data[0] as Hash);
}
}
return new CodePutCodeResult(result, blueprint);
}
}
+26 -26
View File
@@ -148,26 +148,25 @@ export default class Rpc implements RpcInterface {
// a try/catch block). So we:
// - first do `of(1)` - won't throw
// - then do `map(()=>this.formatInputs)` - might throw, but inside Observable.
return of(1)
.pipe(
map((): Codec[] => this.formatInputs(method, values)),
switchMap((params): Observable<[Codec[], any]> =>
combineLatest([
of(params),
from(this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())))
])
),
map(([params, result]): any => this.formatOutput(method, params, result)),
catchError((error): any => {
const message = this.createErrorMessage(method, error);
return of(1).pipe(
map((): Codec[] => this.formatInputs(method, values)),
switchMap((params): Observable<[Codec[], any]> =>
combineLatest([
of(params),
from(this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())))
])
),
map(([params, result]): any => this.formatOutput(method, params, result)),
catchError((error): any => {
const message = this.createErrorMessage(method, error);
l.error(message);
l.error(message);
return throwError(new ExtError(message, (error as ExtError).code, undefined));
}),
publishReplay(1), // create a Replay(1)
refCount() // Unsubcribe WS when there are no more subscribers
);
return throwError(new ExtError(message, (error as ExtError).code, undefined));
}),
publishReplay(1), // create a Replay(1)
refCount() // Unsubcribe WS when there are no more subscribers
);
};
// We voluntarily don't cache the "one-shot" RPC calls. For example,
@@ -186,7 +185,6 @@ export default class Rpc implements RpcInterface {
return new Observable((observer: Observer<any>): VoidCallback => {
// Have at least an empty promise, as used in the unsubscribe
let subscriptionPromise: Promise<number | void> = Promise.resolve();
const errorHandler = (error: Error): void => {
const message = this.createErrorMessage(method, error);
@@ -235,11 +233,9 @@ export default class Rpc implements RpcInterface {
? this.provider.unsubscribe(subType, unsubName, subscriptionId)
: Promise.resolve(false)
)
.catch((error: Error): void => {
const message = this.createErrorMessage(method, error);
l.error(message);
});
.catch((error: Error): void =>
l.error(this.createErrorMessage(method, error))
);
};
}).pipe(
publishReplay(1),
@@ -319,7 +315,9 @@ export default class Rpc implements RpcInterface {
if (meta.modifier.isOptional) {
return new Option(
createClass(type),
isNull ? null : createTypeUnsafe(type, [base], true)
isNull
? null
: createTypeUnsafe(type, [base], true)
);
}
@@ -356,7 +354,9 @@ export default class Rpc implements RpcInterface {
if (meta.modifier.isOptional) {
return new Option(
createClass(type),
value.isNone ? null : createTypeUnsafe(type, [value.unwrap()], true)
value.isNone
? null
: createTypeUnsafe(type, [value.unwrap()], true)
);
}
+14 -10
View File
@@ -48,16 +48,7 @@ export default abstract class AbstractInt extends BN implements Codec {
if (isHex(value)) {
return hexToBn(value, { isLe: false, isNegative }).toString();
} else if (isU8a(value)) {
if (!value.length) {
return '0';
}
try {
// NOTE When passing u8a in (typically from decoded data), it is always Little Endian
return u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative }).toString();
} catch (error) {
throw new Error(`AbstractInt: failed on ${JSON.stringify(value)}:: ${error.message}`);
}
return AbstractInt.decodeAbstracIntU8a(value, bitLength, isNegative);
} else if (isString(value)) {
return new BN(value, 10).toString();
}
@@ -65,6 +56,19 @@ export default abstract class AbstractInt extends BN implements Codec {
return bnToBn(value).toString();
}
private static decodeAbstracIntU8a (value: Uint8Array, bitLength: UIntBitLength, isNegative: boolean): string {
if (!value.length) {
return '0';
}
try {
// NOTE When passing u8a in (typically from decoded data), it is always Little Endian
return u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative }).toString();
} catch (error) {
throw new Error(`AbstractInt: failed on ${JSON.stringify(value)}:: ${error.message}`);
}
}
/**
* @description The length of the value when encoded as a Uint8Array
*/
+17 -9
View File
@@ -32,19 +32,27 @@ export default class CodecSet extends Set<string> implements Codec {
if (isU8a(value)) {
return value.length === 0
? []
: CodecSet.decodeSet(setValues, value[0]);
: CodecSet.decodeSetNumber(setValues, value[0]);
} else if (value instanceof Set) {
return CodecSet.decodeSet(setValues, [...value.values()]);
return CodecSet.decodeSetArray(setValues, [...value.values()]);
} else if (Array.isArray(value)) {
return value.reduce((result, key): string[] => {
assert(!isUndefined(setValues[key]), `Set: Invalid key '${key}' passed to Set, allowed ${Object.keys(setValues).join(', ')}`);
result.push(key);
return result;
}, [] as string[]);
return CodecSet.decodeSetArray(setValues, value);
}
return CodecSet.decodeSetNumber(setValues, value);
}
private static decodeSetArray (setValues: SetValues, value: string[]): string[] {
return value.reduce((result, key): string[] => {
assert(!isUndefined(setValues[key]), `Set: Invalid key '${key}' passed to Set, allowed ${Object.keys(setValues).join(', ')}`);
result.push(key);
return result;
}, [] as string[]);
}
private static decodeSetNumber (setValues: SetValues, value: number): string[] {
const result = Object.keys(setValues).reduce((result, key): string[] => {
if ((value & setValues[key]) === setValues[key]) {
result.push(key);
@@ -33,14 +33,18 @@ export default class Address extends Base<AccountId | AccountIndex> {
public static decodeAddress (value: AnyAddress): AccountId | AccountIndex {
if (value instanceof AccountId || value instanceof AccountIndex) {
return value;
} else if (isBn(value) || isNumber(value)) {
return createType('AccountIndex', value);
} else if (value instanceof Address) {
return value.raw;
} else if (isBn(value) || isNumber(value)) {
return createType('AccountIndex', value);
} else if (Array.isArray(value) || isHex(value) || isU8a(value)) {
return Address.decodeU8a(u8aToU8a(value));
}
return Address.decodeString(value);
}
private static decodeString (value: string): AccountId | AccountIndex {
const decoded = decodeAddress(value);
return decoded.length === 32
+39 -33
View File
@@ -4,7 +4,7 @@
import { AnyU8a, ArgsDef, CallFunction, Codec, IMethod, ModulesWithCalls } from '../../types';
import { assert, isHex, isObject, isU8a, hexToU8a } from '@polkadot/util';
import { assert, isHex, isObject, isU8a, u8aToU8a } from '@polkadot/util';
import { getTypeDef, getTypeClass } from '../../codec/create';
import Struct from '../../codec/Struct';
@@ -70,44 +70,50 @@ export default class Call extends Struct implements IMethod {
* necessary.
*/
private static decodeCall (value: DecodedMethod | Uint8Array | string = new Uint8Array(), _meta?: FunctionMetadataV7): DecodedMethod {
if (isHex(value)) {
return Call.decodeCall(hexToU8a(value), _meta);
} else if (isU8a(value)) {
// The first 2 bytes are the callIndex
const callIndex = value.subarray(0, 2);
// Find metadata with callIndex
const meta = _meta || Call.findFunction(callIndex).meta;
return {
args: value.subarray(2),
argsDef: Call.getArgsDef(meta),
callIndex,
meta
};
if (isHex(value) || isU8a(value)) {
return Call.decodeCallViaU8a(u8aToU8a(value), _meta);
} else if (isObject(value) && value.callIndex && value.args) {
// destructure value, we only pass args/methodsIndex out
const { args, callIndex } = value;
// Get the correct lookupIndex
const lookupIndex = callIndex instanceof CallIndex
? callIndex.toU8a()
: callIndex;
// Find metadata with callIndex
const meta = _meta || Call.findFunction(lookupIndex).meta;
return {
args,
argsDef: Call.getArgsDef(meta),
meta,
callIndex
};
return Call.decodeCallViaObject(value, _meta);
}
throw new Error(`Call: Cannot decode value '${value}' of type ${typeof value}`);
}
private static decodeCallViaObject (value: DecodedMethod, _meta?: FunctionMetadataV7): DecodedMethod {
// destructure value, we only pass args/methodsIndex out
const { args, callIndex } = value;
// Get the correct lookupIndex
const lookupIndex = callIndex instanceof CallIndex
? callIndex.toU8a()
: callIndex;
// Find metadata with callIndex
const meta = _meta || Call.findFunction(lookupIndex).meta;
return {
args,
argsDef: Call.getArgsDef(meta),
meta,
callIndex
};
}
private static decodeCallViaU8a (value: Uint8Array, _meta?: FunctionMetadataV7): DecodedMethod {
// The first 2 bytes are the callIndex
const callIndex = value.subarray(0, 2);
// Find metadata with callIndex
const meta = _meta || Call.findFunction(callIndex).meta;
return {
args: value.subarray(2),
argsDef: Call.getArgsDef(meta),
callIndex,
meta
};
}
// If the extrinsic function has an argument of type `Origin`, we ignore it
public static filterOrigin (meta?: FunctionMetadataV7): FunctionArgumentMetadata[] {
// FIXME should be `arg.type !== Origin`, but doesn't work...