Cleanup encodedLength calculations (#3441)

* Cleanup encodedLength calculations

* Remove array santize

* Test adjustments
This commit is contained in:
Jaco
2021-04-26 12:33:16 +02:00
committed by GitHub
parent 5c03359f32
commit 4afa345a7d
10 changed files with 50 additions and 42 deletions
+23 -7
View File
@@ -31,7 +31,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
#registries: VersionedRegistry[] = [];
#updateSub?: Subscription;
#updateSub?: Subscription | null = null;
constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
super(options, type, decorateMethod);
@@ -156,10 +156,10 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// on re-connection to the same chain, we don't want to re-do everything from chain again
if (this._isReady) {
return true;
} else if (this.#updateSub) {
this.#updateSub.unsubscribe();
}
this._unsubscribeUpdates();
// only load from on-chain if we are not a clone (default path), alternatively
// just use the values from the source instance provided
[this._genesisHash, this._runtimeMetadata] = this._options.source?._isReady
@@ -302,6 +302,25 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
return true;
}
private _unsubscribeHealth (): void {
if (this.#healthTimer) {
clearInterval(this.#healthTimer);
this.#healthTimer = null;
}
}
private _unsubscribeUpdates (): void {
if (this.#updateSub) {
this.#updateSub.unsubscribe();
this.#updateSub = null;
}
}
protected _unsubscribe (): void {
this._unsubscribeHealth();
this._unsubscribeUpdates();
}
#onProviderConnect = async (): Promise<void> => {
this.emit('connected');
this._isConnected.next(true);
@@ -337,10 +356,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this.emit('disconnected');
this._isConnected.next(false);
if (this.#healthTimer) {
clearInterval(this.#healthTimer);
this.#healthTimer = null;
}
this._unsubscribeHealth();
};
#onProviderError = (error: Error): void => {
+2
View File
@@ -50,6 +50,8 @@ export abstract class ApiBase<ApiType extends ApiTypes> extends Getters<ApiType>
* @description Disconnect from the underlying provider, halting all network traffic
*/
public disconnect (): Promise<void> {
this._unsubscribe();
return this._rpcCore.disconnect();
}
+1 -3
View File
@@ -165,9 +165,7 @@ export class ApiRx extends ApiBase<'rxjs'> {
this.#isReadyRx = from<Promise<ApiRx>>(
// You can create an observable from an event, however my mind groks this form better
new Promise((resolve): void => {
super.on('ready', (): void => {
resolve(this);
});
super.on('ready', () => resolve(this));
})
);
}
+2 -2
View File
@@ -3,7 +3,7 @@
import type { Registry } from '@polkadot/types/types';
import { isString, u8aConcat, u8aToU8a } from '@polkadot/util';
import { isString, u8aToU8a } from '@polkadot/util';
import { MetadataVersioned } from './MetadataVersioned';
@@ -11,7 +11,7 @@ import { MetadataVersioned } from './MetadataVersioned';
const VERSION_IDX = 4;
// magic + lowest supported version
const EMPTY_METADATA = u8aConcat(new Uint8Array([0x6d, 0x65, 0x74, 0x61, 9]));
const EMPTY_METADATA = new Uint8Array([0x6d, 0x65, 0x74, 0x61, 9]);
const EMPTY_U8A = new Uint8Array();
function sanitizeInput (_value: Uint8Array | string = EMPTY_U8A): Uint8Array {
+1 -3
View File
@@ -30,9 +30,7 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @description The length of the value when encoded as a Uint8Array
*/
public get encodedLength (): number {
return this.reduce((total, raw): number => {
return total + raw.encodedLength;
}, compactToU8a(this.length).length);
return this.reduce((total, entry) => total + entry.encodedLength, compactToU8a(this.length).length);
}
/**
+1 -5
View File
@@ -74,11 +74,7 @@ export class Tuple extends AbstractArray<Codec> {
* @description The length of the value when encoded as a Uint8Array
*/
public get encodedLength (): number {
return this.reduce((length: number, entry: Codec): number => {
length += entry.encodedLength;
return length;
}, 0);
return this.reduce((total, entry) => total + entry.encodedLength, 0);
}
/**
+1 -1
View File
@@ -63,7 +63,7 @@ export class VecFixed<T extends Codec> extends AbstractArray<T> {
* @description The length of the value when encoded as a Uint8Array
*/
public get encodedLength (): number {
return this.toU8a().length;
return this.reduce((total, entry) => total + entry.encodedLength, 0);
}
public toU8a (): Uint8Array {
+2 -2
View File
@@ -5,7 +5,7 @@ import { alias, removeColons } from './sanitize';
describe('sanitize', (): void => {
describe('alias', (): void => {
const exec = alias(['String'], 'Text');
const exec = alias('String', 'Text');
it('replaces all occurrences for types', (): void => {
expect(exec('(String,Address,MasterString,String)')).toEqual(
@@ -27,7 +27,7 @@ describe('sanitize', (): void => {
});
it('handles emdedded Vec/Tuples', (): void => {
const ann = alias(['Announcement'], 'ProxyAnnouncement');
const ann = alias('Announcement', 'ProxyAnnouncement');
expect(ann('(Vec<Announcement>,BalanceOf)')).toEqual(
'(Vec<ProxyAnnouncement>,BalanceOf)'
+16 -18
View File
@@ -12,8 +12,8 @@ const BOX_PRECEDING = ['<', '(', '[', '"', ',', ' ']; // start of vec, tuple, fi
const mappings: Mapper[] = [
// alias <T::InherentOfflineReport as InherentOfflineReport>::Inherent -> InherentOfflineReport
alias(['<T::InherentOfflineReport as InherentOfflineReport>::Inherent'], 'InherentOfflineReport', false),
alias(['VecDeque<'], 'Vec<', false),
alias('<T::InherentOfflineReport as InherentOfflineReport>::Inherent', 'InherentOfflineReport', false),
alias('VecDeque<', 'Vec<', false),
// <T::Balance as HasCompact>
cleanupCompact(),
// Change BoundedVec<Type, Size> to Vec<Type>
@@ -27,16 +27,17 @@ const mappings: Mapper[] = [
// remove generics, `MisbehaviorReport<Hash, BlockNumber>` -> `MisbehaviorReport`
removeGenerics(),
// alias String -> Text (compat with jsonrpc methods)
alias(['String'], 'Text'),
alias('String', 'Text'),
// alias Vec<u8> -> Bytes
alias(['Vec<u8>', '&\\[u8\\]'], 'Bytes'),
alias('Vec<u8>', 'Bytes'),
alias('&\\[u8\\]', 'Bytes'),
// alias RawAddress -> Address
alias(['RawAddress'], 'Address'),
alias('RawAddress', 'Address'),
// lookups, mapped to Address/AccountId as appropriate in runtime
alias(['Lookup::Source'], 'LookupSource'),
alias(['Lookup::Target'], 'LookupTarget'),
alias('Lookup::Source', 'LookupSource'),
alias('Lookup::Target', 'LookupTarget'),
// HACK duplication between contracts & primitives, however contracts prefixed with exec
alias(['exec::StorageKey'], 'ContractStorageKey'),
alias('exec::StorageKey', 'ContractStorageKey'),
// flattens tuples with one value, `(AccountId)` -> `AccountId`
flattenSingleTuple(),
// converts ::Type to Type, <T as Trait<I>>::Proposal -> Proposal
@@ -62,17 +63,14 @@ export function findClosing (value: string, start: number): number {
throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`);
}
export function alias (src: string[], dest: string, withChecks = true): Mapper {
export function alias (src: string, dest: string, withChecks = true): Mapper {
return (value: string): string =>
src.reduce((value, src): string =>
value
.replace(
new RegExp(`(^${src}|${BOX_PRECEDING.map((box) => `\\${box}${src}`).join('|')})`, 'g'),
(src): string =>
withChecks && BOX_PRECEDING.includes(src[0])
? `${src[0]}${dest}`
: dest
), value
value.replace(
new RegExp(`(^${src}|${BOX_PRECEDING.map((box) => `\\${box}${src}`).join('|')})`, 'g'),
(src): string =>
withChecks && BOX_PRECEDING.includes(src[0])
? `${src[0]}${dest}`
: dest
);
}
+1 -1
View File
@@ -28,7 +28,7 @@ function decodeText (value?: null | Text | string | AnyU8a | { toString: () => s
const [offset, length] = compactFromU8a(value);
const total = offset + length.toNumber();
assert(length.lten(MAX_LENGTH), () => `Text length ${length.toString()} exceeds ${MAX_LENGTH}`);
assert(length.lten(MAX_LENGTH), () => `Text: length ${length.toString()} exceeds ${MAX_LENGTH}`);
assert(total <= value.length, () => `Text: required length less than remainder, expected at least ${total}, found ${value.length}`);
return u8aToString(value.subarray(offset, total));