All private prefixed with _ (#2157)

* All private prefixed with _

* Fix test
This commit is contained in:
Jaco Greeff
2020-04-11 22:21:55 +02:00
committed by GitHub
parent b58d772156
commit a833dccdaf
24 changed files with 254 additions and 257 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
- Cleanups to derives for democracy & staking to be more performant
- Add Centrifuge base types to `@polkadot/types-known`
- Adjust with all the latest substrate master types
- Internally all protected methods/variables are now indicated with `_` (Aligning with the `protected` indicators in the TS definitions)
- Internally all private/protected methods/variables are now indicated with `_` (Aligning with the `private/protected` indicators in the TS definitions)
# 1.9.1 Apr 1, 2020
+2 -2
View File
@@ -18,10 +18,10 @@ export default class ContractAbi extends ContractRegistry implements InterfaceAb
constructor (registry: Registry, abi: ContractABIPre) {
super(registry, abi);
[this.abi, this.constructors, this.messages] = this.decodeAbi(abi);
[this.abi, this.constructors, this.messages] = this._decodeAbi(abi);
}
private decodeAbi (abiPre: ContractABIPre): [ContractABI, ContractABIFn[], AbiMessages] {
private _decodeAbi (abiPre: ContractABIPre): [ContractABI, ContractABIFn[], AbiMessages] {
this.validateAbi(abiPre);
const abi = this.convertAbi(abiPre);
+21 -21
View File
@@ -116,7 +116,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
this.typeDefs[typeIndex - 1] = this.typeDefFromMetaType(this.typeAt(typeIndex), typeIndex);
}
private typeDefIdFields ({ id }: MetaType): Pick<TypeDef, never> {
private _typeDefIdFields ({ id }: MetaType): Pick<TypeDef, never> {
const { 'custom.name': nameIndex, 'custom.namespace': namespaceIndices, 'custom.params': paramsIndices } = id as MetaTypeIdCustom;
if (!nameIndex) {
@@ -136,33 +136,33 @@ export default class MetaRegistry extends MetadataRegistryLookup {
};
}
private typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick<TypeDef, never> {
private _typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick<TypeDef, never> {
let typeDef;
switch (detectedType(metaType)) {
case MetaTypeInfo.BuiltinPlain:
typeDef = this.typeDefForBuiltinPlain(metaType.id as string);
typeDef = this._typeDefForBuiltinPlain(metaType.id as string);
break;
case MetaTypeInfo.BuiltinTuple:
typeDef = this.typeDefForBuiltinTuple(metaType.id as TypeIndex[]);
typeDef = this._typeDefForBuiltinTuple(metaType.id as TypeIndex[]);
break;
case MetaTypeInfo.BuiltinVec:
typeDef = this.typeDefForBuiltinVec(metaType.id as MetaTypeIdVec, typeIndex);
typeDef = this._typeDefForBuiltinVec(metaType.id as MetaTypeIdVec, typeIndex);
break;
case MetaTypeInfo.BuiltinVecFixed:
typeDef = this.typeDefForBuiltinVecFixed(metaType.id as MetaTypeIdVecFixed, typeIndex);
typeDef = this._typeDefForBuiltinVecFixed(metaType.id as MetaTypeIdVecFixed, typeIndex);
break;
case MetaTypeInfo.Enum:
typeDef = this.typeDefForEnum(metaType.def as MetaTypeDefEnum, metaType.id as MetaTypeIdCustom, typeIndex);
typeDef = this._typeDefForEnum(metaType.def as MetaTypeDefEnum, metaType.id as MetaTypeIdCustom, typeIndex);
break;
case MetaTypeInfo.ClikeEnum:
typeDef = this.typeDefForClikeEnum(metaType.def as MetaTypeDefClikeEnum);
typeDef = this._typeDefForClikeEnum(metaType.def as MetaTypeDefClikeEnum);
break;
case MetaTypeInfo.Struct:
typeDef = this.typeDefForStruct(metaType.def as MetaTypeDefStruct);
break;
case MetaTypeInfo.TupleStruct:
typeDef = this.typeDefForTupleStruct(metaType.def as MetaTypeDefTupleStruct);
typeDef = this._typeDefForTupleStruct(metaType.def as MetaTypeDefTupleStruct);
break;
case MetaTypeInfo.Null:
default:
@@ -176,8 +176,8 @@ export default class MetaRegistry extends MetadataRegistryLookup {
return withTypeString({
info: TypeDefInfo.Null,
type: '',
...this.typeDefDefFields(metaType, typeIndex),
...this.typeDefIdFields(metaType)
...this._typeDefDefFields(metaType, typeIndex),
...this._typeDefIdFields(metaType)
}) as TypeDef;
}
@@ -189,7 +189,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
return this.typeDefAt(typeIndex);
}
private typeDefForEnumVariant (variant: MetaTypeDefEnumVariant): Pick<TypeDef, any> {
private _typeDefForEnumVariant (variant: MetaTypeDefEnumVariant): Pick<TypeDef, any> {
const { 'unit_variant.name': unitNameIndex } = variant as MetaTypeDefEnumVariantUnit;
if (unitNameIndex) {
@@ -203,7 +203,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
const { 'tuple_struct_variant.name': tupleStructVariantNameIndex } = variant as MetaTypeDefEnumVariantTupleStruct;
if (tupleStructVariantNameIndex) {
return this.typeDefForTupleStruct(variant as MetaTypeDefEnumVariantTupleStruct);
return this._typeDefForTupleStruct(variant as MetaTypeDefEnumVariantTupleStruct);
}
const { 'struct_variant.name': structVariantNameIndex } = variant as MetaTypeDefEnumVariantStruct;
@@ -218,14 +218,14 @@ export default class MetaRegistry extends MetadataRegistryLookup {
};
}
private typeDefForBuiltinPlain (id: string): Pick<TypeDef, never> {
private _typeDefForBuiltinPlain (id: string): Pick<TypeDef, never> {
return {
info: TypeDefInfo.Plain,
type: id
};
}
private typeDefForBuiltinTuple (id: TypeIndex[]): Pick<TypeDef, never> {
private _typeDefForBuiltinTuple (id: TypeIndex[]): Pick<TypeDef, never> {
const sub = id.map((tupleTypeIndex: number): TypeDef => this.typeDefFromMetaTypeAt(tupleTypeIndex));
return {
@@ -234,7 +234,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
};
}
private typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick<TypeDef, never> {
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick<TypeDef, never> {
const { 'slice.type': vecTypeIndex } = id;
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
@@ -250,7 +250,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
};
}
private typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick<TypeDef, never> {
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick<TypeDef, never> {
const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id;
assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256');
@@ -268,7 +268,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
};
}
private typeDefForEnum (def: MetaTypeDefEnum, id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
private _typeDefForEnum (def: MetaTypeDefEnum, id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
const name = id && this._stringAt(id['custom.name']);
switch (name) {
@@ -279,7 +279,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
return this.typeDefForResult(id, typeIndex);
default: {
const sub = def['enum.variants'].map((variant) => this.typeDefForEnumVariant(variant));
const sub = def['enum.variants'].map((variant) => this._typeDefForEnumVariant(variant));
return {
info: TypeDefInfo.Enum,
@@ -289,7 +289,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
}
}
private typeDefForClikeEnum (def: MetaTypeDefClikeEnum): Pick<TypeDef, never> {
private _typeDefForClikeEnum (def: MetaTypeDefClikeEnum): Pick<TypeDef, never> {
return {
info: TypeDefInfo.Enum,
sub: def['clike_enum.variants'].map(({ discriminant, name: nameIndex }): TypeDef => ({
@@ -336,7 +336,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
});
}
private typeDefForTupleStruct (def: MetaTypeDefTupleStruct | MetaTypeDefEnumVariantTupleStruct): Pick<TypeDef, any> {
private _typeDefForTupleStruct (def: MetaTypeDefTupleStruct | MetaTypeDefEnumVariantTupleStruct): Pick<TypeDef, any> {
const tupleStructTypes = (def as MetaTypeDefTupleStruct)['tuple_struct.types'] || (def as MetaTypeDefEnumVariantTupleStruct)['tuple_struct_variant.types'];
const tupleStructNameIndex = (def as MetaTypeDefEnumVariantTupleStruct)['tuple_struct_variant.name'];
+2 -2
View File
@@ -52,13 +52,13 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
return this._apiContracts
.create(endowment, maxGas, this.codeHash, this.abi.constructors[constructorIndex](...params))
.signAndSend(account)
.pipe(map(this.createResult));
.pipe(map(this._createResult));
}
)
};
}
private createResult = (result: SubmittableResult): BlueprintCreateResult<ApiType> => {
private _createResult = (result: SubmittableResult): BlueprintCreateResult<ApiType> => {
let contract: Contract<ApiType> | undefined;
if (result.isInBlock) {
+2 -2
View File
@@ -51,12 +51,12 @@ export default class Code<ApiType extends ApiTypes> extends BaseWithTx<ApiType>
this._apiContracts
.putCode(maxGas, compactAddLength(this.code))
.signAndSend(account)
.pipe(map(this.createResult))
.pipe(map(this._createResult))
)
};
}
private createResult = (result: ISubmittableResult): CodePutCodeResult<ApiType> => {
private _createResult = (result: ISubmittableResult): CodePutCodeResult<ApiType> => {
let blueprint: Blueprint<ApiType> | undefined;
if (result.isInBlock) {
+8 -8
View File
@@ -33,6 +33,12 @@ export type ContractCallResult<CallType extends ContractCallTypes> = CallType ex
export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpcCall<ApiType> {
public readonly address: Address;
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, address: string | AccountId | Address) {
super(api, abi, decorateMethod);
this.address = this.registry.createType('Address', address);
}
public call (as: 'rpc', message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, 'rpc'>;
public call (as: 'tx', message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, 'tx'>;
public call<CallType extends ContractCallTypes> (as: CallType, message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, CallType> {
@@ -51,7 +57,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
value
})
).pipe(map((result: ContractExecResult): ContractCallOutcome =>
this.createOutcome(result, this.registry.createType('AccountId', account), def, params)
this._createOutcome(result, this.registry.createType('AccountId', account), def, params)
))
: (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'tx'> =>
this._apiContracts
@@ -61,7 +67,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
};
}
private createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: any[]): ContractCallOutcome {
private _createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: any[]): ContractCallOutcome {
let output: Codec | null = null;
if (result.isSuccess) {
@@ -82,10 +88,4 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
time: Date.now()
};
}
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, address: string | AccountId | Address) {
super(api, abi, decorateMethod);
this.address = this.registry.createType('Address', address);
}
}
@@ -22,10 +22,10 @@ export default class HeaderExtended extends _Header {
constructor (registry: Registry, header?: Header, sessionValidators?: AccountId[]) {
super(registry, header);
this.#author = this.extractAuthor(sessionValidators);
this.#author = this._extractAuthor(sessionValidators);
}
private extractAuthor (sessionValidators: AccountId[] = []): AccountId | undefined {
private _extractAuthor (sessionValidators: AccountId[] = []): AccountId | undefined {
const [pitem] = this.digest.logsWith('PreRuntime');
// extract from the substrate 2.0 PreRuntime digest
+12 -12
View File
@@ -184,7 +184,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
augmentObject('', decoratedMeta.consts, this._rx.consts, fromEmpty);
}
private decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
private _decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
output.meta = input.meta;
output.method = input.method;
output.section = input.section;
@@ -300,7 +300,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
creator(method(...params));
return this.decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
return this._decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
}
protected _decorateStorage<ApiType extends ApiTypes> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
@@ -321,7 +321,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// FIXME We probably want to be able to query the full list with non-subs as well
const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue
? this.decorateStorageLinked(creator, decorateMethod)
? this._decorateStorageLinked(creator, decorateMethod)
: decorateMethod((...args: any[]): Observable<Codec> => (
this.hasSubscriptions
? this._rpcCore.state
@@ -348,7 +348,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
u8aToHex(creator.keyPrefix);
decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> =>
this.decorateStorageRange(decorated, [arg1, arg2], range));
this._decorateStorageRange(decorated, [arg1, arg2], range));
decorated.size = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<u64> =>
this._rpcCore.state.getStorageSize(getArgs(arg1, arg2)));
@@ -357,11 +357,11 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) {
decorated.entries = decorateMethod(
memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> =>
this.retrieveMapEntries(creator, doubleMapArg)));
this._retrieveMapEntries(creator, doubleMapArg)));
decorated.keys = decorateMethod(
memo((doubleMapArg?: Arg): Observable<StorageKey[]> =>
this.retrieveMapKeys(creator, doubleMapArg)));
this._retrieveMapKeys(creator, doubleMapArg)));
}
// only support multi where subs are available
@@ -372,10 +372,10 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg])));
}
return this.decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
return this._decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
private decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
const outputType = unwrapStorageType(decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
return this._rpcCore.state
@@ -388,7 +388,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
));
}
private decorateStorageLinked<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
private _decorateStorageLinked<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
const result: Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null> = new Map();
let subject: BehaviorSubject<LinkageResult>;
let head: Codec | null = null;
@@ -460,7 +460,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
);
}
private retrieveMapKeys ({ iterKey, meta }: StorageEntry, arg?: Arg): Observable<StorageKey[]> {
private _retrieveMapKeys ({ iterKey, meta }: StorageEntry, arg?: Arg): Observable<StorageKey[]> {
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
const headKey = this.createType('Raw', u8aConcat(
@@ -493,10 +493,10 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
);
}
private retrieveMapEntries (entry: StorageEntry, arg?: Arg): Observable<[StorageKey, Codec][]> {
private _retrieveMapEntries (entry: StorageEntry, arg?: Arg): Observable<[StorageKey, Codec][]> {
const outputType = unwrapStorageType(entry.meta.type, entry.meta.modifier.isOptional);
return this.retrieveMapKeys(entry, arg).pipe(
return this._retrieveMapKeys(entry, arg).pipe(
switchMap((keys): Observable<[StorageKey[], Option<Raw>[][]]> =>
combineLatest([
of(keys),
+8 -8
View File
@@ -89,14 +89,14 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// only load from on-chain if we are not a clone (default path), alternatively
// just use the values from the source instance provided
this._runtimeMetadata = this._options.source?._isReady
? await this.metaFromSource(this._options.source)
: await this.metaFromChain(metadata);
? await this._metaFromSource(this._options.source)
: await this._metaFromChain(metadata);
return this.initFromMeta(this._runtimeMetadata);
return this._initFromMeta(this._runtimeMetadata);
}
// eslint-disable-next-line @typescript-eslint/require-await
private async metaFromSource (source: ApiBase<any>): Promise<Metadata> {
private async _metaFromSource (source: ApiBase<any>): Promise<Metadata> {
this._extrinsicType = source.extrinsicVersion;
this._runtimeVersion = source.runtimeVersion;
this._genesisHash = source.genesisHash;
@@ -118,7 +118,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
}
// subscribe to metadata updates, inject the types on changes
private subscribeUpdates (): void {
private _subscribeUpdates (): void {
if (this.#updateSub) {
return;
}
@@ -148,7 +148,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
).subscribe();
}
private async metaFromChain (optMetadata: Record<string, string>): Promise<Metadata> {
private async _metaFromChain (optMetadata: Record<string, string>): Promise<Metadata> {
const [runtimeVersion, chain, chainProps] = await Promise.all([
this._rpcCore.state.getRuntimeVersion().toPromise(),
this._rpcCore.system.chain().toPromise(),
@@ -162,7 +162,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// do the setup for the specific chain
this.registry.setChainProperties(chainProps);
this.registerTypes(getSpecTypes(this.registry, chain, runtimeVersion.specName, runtimeVersion.specVersion));
this.subscribeUpdates();
this._subscribeUpdates();
// filter the RPC methods (this does an rpc-methods call)
await this._filterRpc();
@@ -179,7 +179,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
return metadata;
}
private async initFromMeta (metadata: Metadata): Promise<boolean> {
private async _initFromMeta (metadata: Metadata): Promise<boolean> {
// inject types based on metadata, if applicable
this.registerTypes(getMetadataTypes(this.registry, metadata.version));
+12 -12
View File
@@ -11,49 +11,49 @@ import { hexToU8a, u8aToHex } from '@polkadot/util';
let id = 0;
export class SingleAccountSigner implements Signer {
private keyringPair: KeyringPair;
readonly #keyringPair: KeyringPair;
private registry: Registry;
readonly #registry: Registry;
private signDelay: number;
readonly #signDelay: number;
constructor (registry: Registry, keyringPair: KeyringPair, signDelay = 0) {
this.keyringPair = keyringPair;
this.registry = registry;
this.signDelay = signDelay;
this.#keyringPair = keyringPair;
this.#registry = registry;
this.#signDelay = signDelay;
}
public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
if (payload.address !== this.keyringPair.address) {
if (payload.address !== this.#keyringPair.address) {
throw new Error('does not have the keyringPair');
}
return new Promise((resolve): void => {
setTimeout((): void => {
const signed = this.registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.keyringPair);
const signed = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.#keyringPair);
resolve({
id: ++id,
...signed
});
}, this.signDelay);
}, this.#signDelay);
});
}
public async signRaw ({ address, data }: SignerPayloadRaw): Promise<SignerResult> {
if (address !== this.keyringPair.address) {
if (address !== this.#keyringPair.address) {
throw new Error('does not have the keyringPair');
}
return new Promise((resolve): void => {
setTimeout((): void => {
const signature = u8aToHex(this.keyringPair.sign(hexToU8a(data)));
const signature = u8aToHex(this.#keyringPair.sign(hexToU8a(data)));
resolve({
id: ++id,
signature
});
}, this.signDelay);
}, this.#signDelay);
});
}
}
@@ -44,18 +44,18 @@ export default class MetadataVersioned extends Struct {
registry.setMetadata(this);
}
private assertVersion (version: number): boolean {
private _assertVersion (version: number): boolean {
assert(this.version <= version, `Cannot convert metadata from v${this.version} to v${version}`);
return this.version === version;
}
private getVersion<T extends MetaMapped, F extends MetaMapped> (version: MetaVersions, fromPrev: (registry: Registry, input: F) => T): T {
private _getVersion<T extends MetaMapped, F extends MetaMapped> (version: MetaVersions, fromPrev: (registry: Registry, input: F) => T): T {
const asCurr = `asV${version}` as MetaAsX;
const asPrev = `asV${version - 1}` as MetaAsX;
if (this.assertVersion(version)) {
return this.metadata[asCurr] as T;
if (this._assertVersion(version)) {
return this._metadata[asCurr] as T;
}
if (!this.#converted.has(version)) {
@@ -79,86 +79,86 @@ export default class MetadataVersioned extends Struct {
* @description Returns the wrapped metadata as a V0 object
*/
public get asV0 (): MetadataV0 {
this.assertVersion(0);
this._assertVersion(0);
return this.metadata.asV0;
return this._metadata.asV0;
}
/**
* @description Returns the wrapped values as a V1 object
*/
public get asV1 (): MetadataV1 {
return this.getVersion(1, v0ToV1);
return this._getVersion(1, v0ToV1);
}
/**
* @description Returns the wrapped values as a V2 object
*/
public get asV2 (): MetadataV2 {
return this.getVersion(2, v1ToV2);
return this._getVersion(2, v1ToV2);
}
/**
* @description Returns the wrapped values as a V3 object
*/
public get asV3 (): MetadataV3 {
return this.getVersion(3, v2ToV3);
return this._getVersion(3, v2ToV3);
}
/**
* @description Returns the wrapped values as a V4 object
*/
public get asV4 (): MetadataV4 {
return this.getVersion(4, v3ToV4);
return this._getVersion(4, v3ToV4);
}
/**
* @description Returns the wrapped values as a V5 object
*/
public get asV5 (): MetadataV5 {
return this.getVersion(5, v4ToV5);
return this._getVersion(5, v4ToV5);
}
/**
* @description Returns the wrapped values as a V6 object
*/
public get asV6 (): MetadataV6 {
return this.getVersion(6, v5ToV6);
return this._getVersion(6, v5ToV6);
}
/**
* @description Returns the wrapped values as a V7 object
*/
public get asV7 (): MetadataV7 {
return this.getVersion(7, v6ToV7);
return this._getVersion(7, v6ToV7);
}
/**
* @description Returns the wrapped values as a V8 object
*/
public get asV8 (): MetadataV8 {
return this.getVersion(8, v7ToV8);
return this._getVersion(8, v7ToV8);
}
/**
* @description Returns the wrapped values as a V9 object
*/
public get asV9 (): MetadataV9 {
return this.getVersion(9, v8ToV9);
return this._getVersion(9, v8ToV9);
}
/**
* @description Returns the wrapped values as a V10 object
*/
public get asV10 (): MetadataV10 {
return this.getVersion(10, v9ToV10);
return this._getVersion(10, v9ToV10);
}
/**
* @description Returns the wrapped values as a V10 object
*/
public get asV11 (): MetadataV11 {
return this.getVersion(11, v10ToV11);
return this._getVersion(11, v10ToV11);
}
/**
@@ -166,7 +166,7 @@ export default class MetadataVersioned extends Struct {
*/
public get asLatest (): MetadataLatest {
// This is non-existent & latest - applied here to do the module-specific type conversions
return this.getVersion(12, v11ToLatest);
return this._getVersion(12, v11ToLatest);
}
/**
@@ -179,7 +179,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description the metadata wrapped
*/
private get metadata (): MetadataAll {
private get _metadata (): MetadataAll {
return this.get('metadata') as MetadataAll;
}
@@ -187,7 +187,7 @@ export default class MetadataVersioned extends Struct {
* @description the metadata version this structure represents
*/
public get version (): number {
return this.metadata.index;
return this._metadata.index;
}
public getUniqTypes (throwError: boolean): string[] {
+30 -30
View File
@@ -111,7 +111,7 @@ export default class Rpc implements RpcInterface {
this.registry = registry;
this.provider = provider;
this.createInterfaces(userRpc);
this._createInterfaces(userRpc);
}
/**
@@ -121,7 +121,7 @@ export default class Rpc implements RpcInterface {
this.provider.disconnect();
}
private createInterfaces<Section extends keyof RpcInterface> (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
private _createInterfaces<Section extends keyof RpcInterface> (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
const sectionNames = Object.keys(jsonrpc);
// these are the base keys (i.e. part of jsonrpc)
@@ -133,13 +133,13 @@ export default class Rpc implements RpcInterface {
// decorate the sections with base and user methods
this.sections.forEach((sectionName): void => {
(this as any)[sectionName as Section] = {
...this.createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}),
...this.createInterface(sectionName, userRpc[sectionName] || {})
...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}),
...this._createInterface(sectionName, userRpc[sectionName] || {})
};
});
}
private createInterface<Section extends keyof RpcInterface> (section: string, methods: Record<string, DefinitionRpc | DefinitionRpcSub>): RpcInterface[Section] {
private _createInterface<Section extends keyof RpcInterface> (section: string, methods: Record<string, DefinitionRpc | DefinitionRpcSub>): RpcInterface[Section] {
return Object
.keys(methods)
.reduce((exposed, method): RpcInterface[Section] => {
@@ -155,14 +155,14 @@ export default class Rpc implements RpcInterface {
// Not doing so, because it makes this class a little bit less readable,
// and leaving it as-is doesn't harm much
(exposed as any)[method] = isSubscription
? this.createMethodSubscribe(section, method, def as DefinitionRpcSub)
: this.createMethodSend(section, method, def);
? this._createMethodSubscribe(section, method, def as DefinitionRpcSub)
: this._createMethodSend(section, method, def);
return exposed;
}, {} as RpcInterface[Section]);
}
private createMethodWithRaw (creator: (isRaw: boolean) => (...values: any[]) => Observable<any>): RpcInterfaceMethod {
private _createMethodWithRaw (creator: (isRaw: boolean) => (...values: any[]) => Observable<any>): RpcInterfaceMethod {
const call = creator(false) as Partial<RpcInterfaceMethod>;
call.raw = creator(true);
@@ -170,7 +170,7 @@ export default class Rpc implements RpcInterface {
return call as RpcInterfaceMethod;
}
private createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod {
private _createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod {
const rpcName = `${section}_${method}`;
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
@@ -181,7 +181,7 @@ export default class Rpc implements RpcInterface {
// - first do `of(1)` - won't throw
// - then do `map(()=>this.formatInputs)` - might throw, but inside Observable.
return of(1).pipe(
map(() => this.formatInputs(def, values)),
map(() => this._formatInputs(def, values)),
switchMap((params): Observable<[Codec[], any]> =>
combineLatest([
of(params),
@@ -191,7 +191,7 @@ export default class Rpc implements RpcInterface {
map(([params, result]) =>
isRaw
? this.registry.createType('Raw', result)
: this.formatOutput(method, def, params, result)
: this._formatOutput(method, def, params, result)
),
catchError((error): any => {
logErrorMessage(method, def, error);
@@ -206,11 +206,11 @@ export default class Rpc implements RpcInterface {
// We voluntarily don't cache the "one-shot" RPC calls. For example,
// `getStorage('123')` returns the current value, but this value can change
// over time, so we wouldn't want to cache the Observable.
return this.createMethodWithRaw(creator);
return this._createMethodWithRaw(creator);
}
// create a subscriptor, it subscribes once and resolves with the id as subscribe
private createSubscriber ({ paramsJson, subName, subType, update }: { subType: string; subName: string; paramsJson: AnyJson[]; update: ProviderInterfaceCallback }, errorHandler: (error: Error) => void): Promise<number> {
private _createSubscriber ({ paramsJson, subName, subType, update }: { subType: string; subName: string; paramsJson: AnyJson[]; update: ProviderInterfaceCallback }, errorHandler: (error: Error) => void): Promise<number> {
return new Promise((resolve, reject): void => {
this.provider
.subscribe(subType, subName, paramsJson, update)
@@ -222,7 +222,7 @@ export default class Rpc implements RpcInterface {
});
}
private createMethodSubscribe (section: string, method: string, def: DefinitionRpcSub): RpcInterfaceMethod {
private _createMethodSubscribe (section: string, method: string, def: DefinitionRpcSub): RpcInterfaceMethod {
const [updateType, subMethod, unsubMethod] = def.pubsub;
const subName = `${section}_${subMethod}`;
const unsubName = `${section}_${unsubMethod}`;
@@ -240,7 +240,7 @@ export default class Rpc implements RpcInterface {
};
try {
const params = this.formatInputs(def, values);
const params = this._formatInputs(def, values);
const paramsJson = params.map((param): AnyJson => param.toJSON());
const update = (error?: Error | null, result?: any): void => {
@@ -254,14 +254,14 @@ export default class Rpc implements RpcInterface {
observer.next(
isRaw
? this.registry.createType('Raw', result)
: this.formatOutput(method, def, params, result)
: this._formatOutput(method, def, params, result)
);
} catch (error) {
observer.error(error);
}
};
subscriptionPromise = this.createSubscriber({ paramsJson, subName, subType, update }, errorHandler);
subscriptionPromise = this._createSubscriber({ paramsJson, subName, subType, update }, errorHandler);
} catch (error) {
errorHandler(error);
}
@@ -292,7 +292,7 @@ export default class Rpc implements RpcInterface {
}).pipe(drr());
};
const memoized = memoizee(this.createMethodWithRaw(creator), {
const memoized = memoizee(this._createMethodWithRaw(creator), {
// Dynamic length for argument
length: false,
// Normalize args so that different args that should be cached
@@ -305,7 +305,7 @@ export default class Rpc implements RpcInterface {
return memoized;
}
private formatInputs (def: DefinitionRpc, inputs: any[]): Codec[] {
private _formatInputs (def: DefinitionRpc, inputs: any[]): Codec[] {
const reqArgCount = def.params.filter(({ isOptional }): boolean => !isOptional).length;
const optText = reqArgCount === def.params.length
? ''
@@ -318,29 +318,29 @@ export default class Rpc implements RpcInterface {
);
}
private treatAsHex (key: StorageKey): boolean {
private _treatAsHex (key: StorageKey): boolean {
// :code is problematic - it does not have the length attached, which is
// unlike all other storage entries where it is indeed properly encoded
return ['0x3a636f6465'].includes(key.toHex());
}
private formatOutput (method: string, rpc: DefinitionRpc, params: Codec[], result?: any): Codec | Codec[] {
private _formatOutput (method: string, rpc: DefinitionRpc, params: Codec[], result?: any): Codec | Codec[] {
if (rpc.type === 'StorageData') {
const key = params[0] as StorageKey;
try {
return this.formatStorageData(key, result);
return this._formatStorageData(key, result);
} catch (error) {
console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message);
throw error;
}
} else if (rpc.type === 'StorageChangeSet') {
return this.formatStorageSet(params[0] as Vec<StorageKey>, result.changes);
return this._formatStorageSet(params[0] as Vec<StorageKey>, result.changes);
} else if (rpc.type === 'Vec<StorageChangeSet>') {
const mapped = result.map(({ block, changes }: { block: string; changes: [string, string | null][] }): [Hash, Codec[]] => [
this.registry.createType('Hash', block),
this.formatStorageSet(params[0] as Vec<StorageKey>, changes)
this._formatStorageSet(params[0] as Vec<StorageKey>, changes)
]);
// we only query at a specific block, not a range - flatten
@@ -352,7 +352,7 @@ export default class Rpc implements RpcInterface {
return createTypeUnsafe(this.registry, rpc.type, [result]);
}
private formatStorageData (key: StorageKey, value: string | null): Codec {
private _formatStorageData (key: StorageKey, value: string | null): Codec {
// single return value (via state.getStorage), decode the value based on the
// outputType that we have specified. Fallback to Raw on nothing
const type = key.outputType || 'Raw';
@@ -363,7 +363,7 @@ export default class Rpc implements RpcInterface {
// data will be correctly encoded (incl. numbers, excl. :code)
const input = isEmpty
? null
: this.treatAsHex(key)
: this._treatAsHex(key)
? value
: u8aToU8a(value);
@@ -386,7 +386,7 @@ export default class Rpc implements RpcInterface {
], true);
}
private formatStorageSet (keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] {
private _formatStorageSet (keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] {
// For StorageChangeSet, the changes has the [key, value] mappings
const withCache = keys.length !== 1;
@@ -396,7 +396,7 @@ export default class Rpc implements RpcInterface {
// - null - The storage key is empty
return keys.reduce((results: Codec[], key: StorageKey): Codec[] => {
try {
results.push(this.formatStorageSetEntry(key, changes, withCache));
results.push(this._formatStorageSetEntry(key, changes, withCache));
} catch (error) {
console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message);
@@ -407,7 +407,7 @@ export default class Rpc implements RpcInterface {
}, []);
}
private formatStorageSetEntry (key: StorageKey, changes: [string, string | null][], witCache: boolean): Codec {
private _formatStorageSetEntry (key: StorageKey, changes: [string, string | null][], witCache: boolean): Codec {
// Fallback to Raw (i.e. just the encoding) if we don't have a specific type
const type = key.outputType || 'Raw';
const hexKey = key.toHex();
@@ -422,7 +422,7 @@ export default class Rpc implements RpcInterface {
? (witCache && this.#storageCache.get(hexKey)) || null
: found[1];
const isEmpty = isNull(value);
const input = isEmpty || this.treatAsHex(key)
const input = isEmpty || this._treatAsHex(key)
? value
: u8aToU8a(value);
+2 -2
View File
@@ -41,7 +41,7 @@ describe('methodSend', (): void => {
it('checks for mismatched parameters', (done): void => {
// private method
const method = (rpc as any).createMethodSend('test', 'bleh', methods.bleh);
const method = (rpc as any)._createMethodSend('test', 'bleh', methods.bleh);
method(1).subscribe(
(): void => undefined,
@@ -53,7 +53,7 @@ describe('methodSend', (): void => {
it('calls the provider with the correct parameters', (done): void => {
// private method
const method = (rpc as any).createMethodSend('test', 'blah', methods.blah);
const method = (rpc as any)._createMethodSend('test', 'blah', methods.blah);
// Args are length-prefixed, because it's a Bytes
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe((): void => {
+3 -3
View File
@@ -32,12 +32,12 @@ export default class RpcCoder {
assert(isNumber(response.id) || (isSubscription && isNumber(response.params.subscription)), 'Invalid id field in decoded object');
this.checkError(response.error);
this._checkError(response.error);
assert(!isUndefined(response.result) || isSubscription, 'No result found in JsonRpc response');
if (isSubscription) {
this.checkError(response.params.error);
this._checkError(response.params.error);
return response.params.result;
}
@@ -64,7 +64,7 @@ export default class RpcCoder {
return this.#id;
}
private checkError (error?: JsonRpcResponseBaseError): void {
private _checkError (error?: JsonRpcResponseBaseError): void {
if (error) {
const { code, data, message } = error;
+31 -31
View File
@@ -15,6 +15,36 @@ export type UIntBitLength = 8 | 16 | 32 | 64 | 128 | 256;
export const DEFAULT_UINT_BITS = 64;
/** @internal */
function 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}`);
}
}
/** @internal */
function decodeAbstracInt (value: AnyNumber, bitLength: UIntBitLength, isNegative: boolean): string {
// This function returns a string, which will be passed in the BN
// constructor. It would be ideal to actually return a BN, but there's a
// bug: https://github.com/indutny/bn.js/issues/206.
if (isHex(value, -1, true)) {
return hexToBn(value, { isLe: false, isNegative }).toString();
} else if (isU8a(value)) {
return decodeAbstracIntU8a(value, bitLength, isNegative);
} else if (isString(value)) {
return new BN(value.toString(), 10).toString();
}
return bnToBn(value).toString();
}
/**
* @name AbstractInt
* @ignore
@@ -32,7 +62,7 @@ export default abstract class AbstractInt extends BN implements Codec {
readonly #isSigned: boolean;
protected constructor (registry: Registry, isSigned: boolean, value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson = true) {
super(AbstractInt.decodeAbstracInt(value, bitLength, isSigned));
super(decodeAbstracInt(value, bitLength, isSigned));
this.registry = registry;
this.#bitLength = bitLength;
@@ -42,36 +72,6 @@ export default abstract class AbstractInt extends BN implements Codec {
assert(super.bitLength() <= bitLength, `${this.toRawType()}: Input too large. Found input with ${super.bitLength()} bits, expected ${bitLength}`);
}
/** @internal */
public static decodeAbstracInt (value: AnyNumber, bitLength: UIntBitLength, isNegative: boolean): string {
// This function returns a string, which will be passed in the BN
// constructor. It would be ideal to actually return a BN, but there's a
// bug: https://github.com/indutny/bn.js/issues/206.
if (isHex(value, -1, true)) {
return hexToBn(value, { isLe: false, isNegative }).toString();
} else if (isU8a(value)) {
return AbstractInt.decodeAbstracIntU8a(value, bitLength, isNegative);
} else if (isString(value)) {
return new BN(value.toString(), 10).toString();
}
return bnToBn(value).toString();
}
/** @internal */
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
*/
+6 -6
View File
@@ -12,6 +12,11 @@ import Raw from './Raw';
import { compareMap } from './utils';
/** @internal */
function decodeJson (value?: { [index: string]: any } | null): [string, any][] {
return Object.entries(value || {});
}
/**
* @name Json
* @description
@@ -24,7 +29,7 @@ export default class StructAny extends Map<string, any> implements Codec {
public readonly registry: Registry;
constructor (registry: Registry, value?: { [index: string]: any } | null) {
const decoded = StructAny.decodeJson(value);
const decoded = decodeJson(value);
super(decoded);
@@ -44,11 +49,6 @@ export default class StructAny extends Map<string, any> implements Codec {
});
}
/** @internal */
private static decodeJson (value?: { [index: string]: any } | null): [string, any][] {
return Object.entries(value || {});
}
/**
* @description Always 0, never encodes as a Uint8Array
*/
+24 -24
View File
@@ -17,6 +17,29 @@ type TupleTypes = (Constructor | keyof InterfaceTypes)[] | {
[index: string]: Constructor | keyof InterfaceTypes;
};
/** @internal */
function decodeTuple (registry: Registry, _Types: TupleConstructors, value: AnyU8a | string | (AnyU8a | AnyNumber | AnyString | undefined | null)[]): Codec[] {
if (isU8a(value)) {
return decodeU8a(registry, value, _Types);
} else if (isHex(value)) {
return decodeTuple(registry, _Types, hexToU8a(value));
}
const Types: Constructor[] = Array.isArray(_Types)
? _Types
: Object.values(_Types);
return Types.map((Type, index): Codec => {
try {
if (value?.[index] instanceof Type) return value[index] as any;
return new Type(registry, value?.[index]);
} catch (error) {
throw new Error(`Tuple: failed on ${index}:: ${error.message}`);
}
});
}
/**
* @name Tuple
* @description
@@ -31,34 +54,11 @@ export default class Tuple extends AbstractArray<Codec> {
? Types.map((type): Constructor => typeToConstructor(registry, type))
: mapToTypeMap(registry, Types);
super(registry, ...Tuple.decodeTuple(registry, Clazzes, value));
super(registry, ...decodeTuple(registry, Clazzes, value));
this._Types = Clazzes;
}
/** @internal */
private static decodeTuple (registry: Registry, _Types: TupleConstructors, value: AnyU8a | string | (AnyU8a | AnyNumber | AnyString | undefined | null)[]): Codec[] {
if (isU8a(value)) {
return decodeU8a(registry, value, _Types);
} else if (isHex(value)) {
return Tuple.decodeTuple(registry, _Types, hexToU8a(value));
}
const Types: Constructor[] = Array.isArray(_Types)
? _Types
: Object.values(_Types);
return Types.map((Type, index): Codec => {
try {
if (value?.[index] instanceof Type) return value[index] as any;
return new Type(registry, value?.[index]);
} catch (error) {
throw new Error(`Tuple: failed on ${index}:: ${error.message}`);
}
});
}
public static with (Types: TupleTypes): Constructor<Tuple> {
return class extends Tuple {
constructor (registry: Registry, value?: any) {
+23 -23
View File
@@ -13,6 +13,28 @@ import Raw from './Raw';
// as a result of the Polkadot claims module. (Technically we don't need the 520 in here)
export type BitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 512 | 520 | 1024 | 2048;
/** @internal */
function decodeU8aFixed (value: AnyU8a, bitLength: BitLength): AnyU8a {
if (Array.isArray(value) || isString(value)) {
return decodeU8aFixed(u8aToU8a(value), bitLength);
}
// ensure that we have an actual u8a with the full length as specified by
// the bitLength input (padded with zeros as required)
const byteLength = bitLength / 8;
const sub = value.subarray(0, byteLength);
if (sub.length === byteLength) {
return sub;
}
const u8a = new Uint8Array(byteLength);
u8a.set(sub, 0);
return u8a;
}
/**
* @name U8aFixed
* @description
@@ -21,29 +43,7 @@ export type BitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 512 | 520 | 1024 |
*/
export default class U8aFixed extends Raw {
constructor (registry: Registry, value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) {
super(registry, U8aFixed.decodeU8aFixed(value, bitLength));
}
/** @internal */
private static decodeU8aFixed (value: AnyU8a, bitLength: BitLength): AnyU8a {
if (Array.isArray(value) || isString(value)) {
return U8aFixed.decodeU8aFixed(u8aToU8a(value), bitLength);
}
// ensure that we have an actual u8a with the full length as specified by
// the bitLength input (padded with zeros as required)
const byteLength = bitLength / 8;
const sub = value.subarray(0, byteLength);
if (sub.length === byteLength) {
return sub;
}
const u8a = new Uint8Array(byteLength);
u8a.set(sub, 0);
return u8a;
super(registry, decodeU8aFixed(value, bitLength));
}
public static with (bitLength: BitLength, typeName?: string): Constructor<U8aFixed> {
+2 -2
View File
@@ -270,11 +270,11 @@ export class TypeRegistry implements Registry {
this.#classes.set(arg1, arg2);
} else {
this.registerObject(arg1);
this._registerObject(arg1);
}
}
private registerObject (obj: RegistryTypes): void {
private _registerObject (obj: RegistryTypes): void {
Object.entries(obj).forEach(([name, type]): void => {
if (isFunction(type)) {
// This _looks_ a bit funny, but `typeof Clazz === 'function'
+9 -9
View File
@@ -173,11 +173,11 @@ abstract class ExtrinsicBase extends Base<ExtrinsicVx | ExtrinsicUnknown> {
*/
export default class Extrinsic extends ExtrinsicBase implements IExtrinsic {
constructor (registry: Registry, value: Extrinsic | ExtrinsicValue | AnyU8a | Call | undefined, { version }: CreateOptions = {}) {
super(registry, Extrinsic.decodeExtrinsic(registry, value, version));
super(registry, Extrinsic._decodeExtrinsic(registry, value, version));
}
/** @internal */
private static newFromValue (registry: Registry, value: any, version: number): ExtrinsicVx | ExtrinsicUnknown {
private static _newFromValue (registry: Registry, value: any, version: number): ExtrinsicVx | ExtrinsicUnknown {
if (value instanceof Extrinsic) {
return value._raw;
}
@@ -191,20 +191,20 @@ export default class Extrinsic extends ExtrinsicBase implements IExtrinsic {
}
/** @internal */
public static decodeExtrinsic (registry: Registry, value: Extrinsic | ExtrinsicValue | AnyU8a | Call | undefined, version: number = DEFAULT_VERSION): ExtrinsicVx | ExtrinsicUnknown {
private static _decodeExtrinsic (registry: Registry, value: Extrinsic | ExtrinsicValue | AnyU8a | Call | undefined, version: number = DEFAULT_VERSION): ExtrinsicVx | ExtrinsicUnknown {
if (isU8a(value) || Array.isArray(value) || isHex(value)) {
return Extrinsic.decodeU8a(registry, u8aToU8a(value), version);
return Extrinsic._decodeU8a(registry, u8aToU8a(value), version);
} else if (value instanceof registry.createClass('Call')) {
return Extrinsic.newFromValue(registry, { method: value }, version);
return Extrinsic._newFromValue(registry, { method: value }, version);
}
return Extrinsic.newFromValue(registry, value, version);
return Extrinsic._newFromValue(registry, value, version);
}
/** @internal */
private static decodeU8a (registry: Registry, value: Uint8Array, version: number): ExtrinsicVx | ExtrinsicUnknown {
private static _decodeU8a (registry: Registry, value: Uint8Array, version: number): ExtrinsicVx | ExtrinsicUnknown {
if (!value.length) {
return Extrinsic.newFromValue(registry, new Uint8Array(), version);
return Extrinsic._newFromValue(registry, new Uint8Array(), version);
}
const [offset, length] = Compact.decodeU8a(value);
@@ -214,7 +214,7 @@ export default class Extrinsic extends ExtrinsicBase implements IExtrinsic {
const data = value.subarray(offset, total);
return Extrinsic.newFromValue(registry, data.subarray(1), data[0]);
return Extrinsic._newFromValue(registry, data.subarray(1), data[0]);
}
/**
+24 -27
View File
@@ -28,6 +28,17 @@ interface ImmortalEnumDef {
ImmortalEra: string;
}
function getTrailingZeros (period: number): number {
const binary = period.toString(2);
let index = 0;
while (binary[binary.length - 1 - index] === '0') {
index++;
}
return index;
}
/**
* @name ImmortalEra
* @description
@@ -52,19 +63,19 @@ export class MortalEra extends Tuple {
super(registry, {
period: U64,
phase: U64
}, MortalEra.decodeMortalEra(registry, value));
}, MortalEra._decodeMortalEra(registry, value));
}
/** @internal */
private static decodeMortalEra (registry: Registry, value?: MortalMethod | Uint8Array | number[] | string): MortalEraValue {
private static _decodeMortalEra (registry: Registry, value?: MortalMethod | Uint8Array | number[] | string): MortalEraValue {
if (isHex(value)) {
return MortalEra.decodeMortalU8a(registry, hexToU8a(value));
return MortalEra._decodeMortalU8a(registry, hexToU8a(value));
} else if (Array.isArray(value)) {
return MortalEra.decodeMortalU8a(registry, new Uint8Array(value));
return MortalEra._decodeMortalU8a(registry, new Uint8Array(value));
} else if (isU8a(value)) {
return MortalEra.decodeMortalU8a(registry, value);
return MortalEra._decodeMortalU8a(registry, value);
} else if (isObject(value)) {
return MortalEra.decodeMortalObject(registry, value);
return MortalEra._decodeMortalObject(registry, value);
} else if (!value) {
return [new U64(registry), new U64(registry)];
}
@@ -73,7 +84,7 @@ export class MortalEra extends Tuple {
}
/** @internal */
private static decodeMortalObject (registry: Registry, value: MortalMethod): MortalEraValue {
private static _decodeMortalObject (registry: Registry, value: MortalMethod): MortalEraValue {
const { current, period } = value;
let calPeriod = Math.pow(2, Math.ceil(Math.log2(period)));
@@ -87,7 +98,7 @@ export class MortalEra extends Tuple {
}
/** @internal */
private static decodeMortalU8a (registry: Registry, value: Uint8Array): MortalEraValue {
private static _decodeMortalU8a (registry: Registry, value: Uint8Array): MortalEraValue {
if (value.length === 0) {
return [new U64(registry), new U64(registry)];
}
@@ -157,7 +168,7 @@ export class MortalEra extends Tuple {
const period = this.period.toNumber();
const phase = this.phase.toNumber();
const quantizeFactor = Math.max(period >> 12, 1);
const trailingZeros = this.getTrailingZeros(period);
const trailingZeros = getTrailingZeros(period);
const encoded = Math.min(15, Math.max(1, trailingZeros - 1)) + (((phase / quantizeFactor) << 4));
const first = encoded >> 8;
const second = encoded & 0xff;
@@ -184,20 +195,6 @@ export class MortalEra extends Tuple {
// FIXME No toNumber() here
return this.birth(current) + this.period.toNumber();
}
/**
* @description convert the number to binary and get the trailing zero's.
*/
private getTrailingZeros (period: number): number {
const binary = period.toString(2);
let index = 0;
while (binary[binary.length - 1 - index] === '0') {
index++;
}
return index;
}
}
/**
@@ -210,16 +207,16 @@ export default class ExtrinsicEra extends Enum implements IExtrinsicEra {
super(registry, {
ImmortalEra,
MortalEra
}, ExtrinsicEra.decodeExtrinsicEra(value));
}, ExtrinsicEra._decodeExtrinsicEra(value));
}
/** @internal */
// eslint-disable-next-line @typescript-eslint/ban-types
private static decodeExtrinsicEra (value: IExtrinsicEra | MortalMethod | MortalEnumDef | ImmortalEnumDef | Uint8Array | string = new Uint8Array()): Uint8Array | Object | undefined {
private static _decodeExtrinsicEra (value: IExtrinsicEra | MortalMethod | MortalEnumDef | ImmortalEnumDef | Uint8Array | string = new Uint8Array()): Uint8Array | Object | undefined {
if (value instanceof ExtrinsicEra) {
return ExtrinsicEra.decodeExtrinsicEra(value.toU8a());
return ExtrinsicEra._decodeExtrinsicEra(value.toU8a());
} else if (isHex(value)) {
return ExtrinsicEra.decodeExtrinsicEra(hexToU8a(value));
return ExtrinsicEra._decodeExtrinsicEra(hexToU8a(value));
} else if (!value || isU8a(value)) {
return (!value?.length || value[0] === 0)
? new Uint8Array([0])
@@ -99,7 +99,7 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
return this.registry.createType('Compact<Balance>', 0);
}
private injectSignature (signer: Address, signature: Signature, { era, nonce }: ExtrinsicPayloadV1): IExtrinsicSignature {
private _injectSignature (signer: Address, signature: Signature, { era, nonce }: ExtrinsicPayloadV1): IExtrinsicSignature {
this.set('era', era);
this.set('nonce', nonce);
this.set('signer', signer);
@@ -112,7 +112,7 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
* @description Adds a raw signature
*/
public addSignature (signer: Address | Uint8Array | string, signature: Uint8Array | string, payload: ExtrinsicPayloadValue | Uint8Array | string): IExtrinsicSignature {
return this.injectSignature(
return this._injectSignature(
this.registry.createType('Address', signer),
this.registry.createType('Signature', signature),
new ExtrinsicPayloadV1(this.registry, payload)
@@ -142,7 +142,7 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
const payload = this.createPayload(method, options);
const signature = this.registry.createType('Signature', payload.sign(account));
return this.injectSignature(signer, signature, payload);
return this._injectSignature(signer, signature, payload);
}
/**
@@ -153,7 +153,7 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
const payload = this.createPayload(method, options);
const signature = this.registry.createType('Signature', new Uint8Array(64).fill(0x42));
return this.injectSignature(signer, signature, payload);
return this._injectSignature(signer, signature, payload);
}
/**
+2 -2
View File
@@ -50,11 +50,11 @@ function decodeU8a (registry: Registry, value: Uint8Array): AccountId | AccountI
*/
export default class Address extends Base<AccountId | AccountIndex> {
constructor (registry: Registry, value: AnyAddress = new Uint8Array()) {
super(registry, Address.decodeAddress(registry, value));
super(registry, Address._decodeAddress(registry, value));
}
/** @internal */
private static decodeAddress (registry: Registry, value: AnyAddress): AccountId | AccountIndex {
private static _decodeAddress (registry: Registry, value: AnyAddress): AccountId | AccountIndex {
if (value instanceof AccountId || value instanceof AccountIndex) {
return value;
} else if (value instanceof Address) {
@@ -57,7 +57,7 @@ export default class ConsensusEngineId extends U32 {
return this.eq(CID_GRPA);
}
private getAuraAuthor (bytes: Bytes, sessionValidators: AccountId[]): AccountId {
private _getAuraAuthor (bytes: Bytes, sessionValidators: AccountId[]): AccountId {
return sessionValidators[
this.registry.createType('RawAuraPreDigest', bytes.toU8a(true))
.slotNumber
@@ -66,7 +66,7 @@ export default class ConsensusEngineId extends U32 {
];
}
private getBabeAuthor (bytes: Bytes, sessionValidators: AccountId[]): AccountId {
private _getBabeAuthor (bytes: Bytes, sessionValidators: AccountId[]): AccountId {
const digest = this.registry.createType('RawBabePreDigestCompat', bytes.toU8a(true));
return sessionValidators[
@@ -80,9 +80,9 @@ export default class ConsensusEngineId extends U32 {
public extractAuthor (bytes: Bytes, sessionValidators: AccountId[]): AccountId | undefined {
if (sessionValidators?.length) {
if (this.isAura) {
return this.getAuraAuthor(bytes, sessionValidators);
return this._getAuraAuthor(bytes, sessionValidators);
} else if (this.isBabe) {
return this.getBabeAuthor(bytes, sessionValidators);
return this._getBabeAuthor(bytes, sessionValidators);
}
}