* Bump util

* Adjust to fix build
This commit is contained in:
Jaco
2023-04-29 09:31:52 +03:00
committed by GitHub
parent 9c4554ddb3
commit 09222d9055
73 changed files with 441 additions and 429 deletions
+1 -1
View File
@@ -26,7 +26,7 @@
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-augment": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"tslib": "^2.5.0"
}
}
+1 -1
View File
@@ -23,7 +23,7 @@
"dependencies": {
"@polkadot/rpc-core": "10.4.2-6-x",
"@polkadot/types": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.0"
}
+3 -3
View File
@@ -25,13 +25,13 @@
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/types-create": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util-crypto": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/util-crypto": "^12.1.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.0"
},
"devDependencies": {
"@polkadot/api-augment": "10.4.2-6-x",
"@polkadot/keyring": "^12.0.1"
"@polkadot/keyring": "^12.1.1"
}
}
+2 -2
View File
@@ -27,8 +27,8 @@
"@polkadot/rpc-core": "10.4.2-6-x",
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util-crypto": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/util-crypto": "^12.1.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.0"
},
+1 -1
View File
@@ -55,7 +55,7 @@ export function _flags (instanceId: string, api: DeriveApi): () => Observable<Fl
map((values: Codec[]): FlagsIntermediate => {
let resultIndex = -1;
for (let i = 0; i < calls.length; i++) {
for (let i = 0, count = calls.length; i < count; i++) {
if (isFunction(calls[i])) {
results[i] = values[++resultIndex];
}
+1 -1
View File
@@ -119,7 +119,7 @@ function injectFunctions (instanceId: string, api: DeriveApi, derives: DeriveCus
)
));
for (let i = 0; i < names.length; i++) {
for (let i = 0, count = names.length; i < count; i++) {
const name = names[i];
isIncluded(name) &&
@@ -8,7 +8,7 @@ import type { ApprovalFlag } from '@polkadot/types/interfaces/elections';
export function approvalFlagsToBools (flags: Vec<ApprovalFlag> | ApprovalFlag[]): boolean[] {
const bools: boolean[] = [];
for (let i = 0; i < flags.length; i++) {
for (let i = 0, count = flags.length; i < count; i++) {
const str = flags[i].toString(2);
// read from lowest bit to highest
+3 -3
View File
@@ -24,7 +24,7 @@
"@polkadot/api-augment": "10.4.2-6-x",
"@polkadot/api-base": "10.4.2-6-x",
"@polkadot/api-derive": "10.4.2-6-x",
"@polkadot/keyring": "^12.0.1",
"@polkadot/keyring": "^12.1.1",
"@polkadot/rpc-augment": "10.4.2-6-x",
"@polkadot/rpc-core": "10.4.2-6-x",
"@polkadot/rpc-provider": "10.4.2-6-x",
@@ -33,8 +33,8 @@
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/types-create": "10.4.2-6-x",
"@polkadot/types-known": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util-crypto": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/util-crypto": "^12.1.1",
"eventemitter3": "^5.0.0",
"rxjs": "^7.8.1",
"tslib": "^2.5.0"
+15 -14
View File
@@ -322,7 +322,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// we try and create mappings to runtime names via a hash mapping)
const sectionMap: Record<string, boolean> = {};
for (let i = 0; i < methods.length; i++) {
for (let i = 0, count = methods.length; i < count; i++) {
const [section] = methods[i].split('_');
sectionMap[section] = true;
@@ -331,7 +331,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// convert the actual section names into an easy name lookup
const sections = Object.keys(sectionMap);
for (let i = 0; i < sections.length; i++) {
for (let i = 0, count = sections.length; i < count; i++) {
const nameA = stringUpperFirst(sections[i]);
const nameB = `${nameA}Api`;
@@ -347,8 +347,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const hasResults = exposed.length !== 0;
const allKnown = [...this._rpcCore.mapping.entries()];
const allKeys: string[] = [];
const count = allKnown.length;
for (let i = 0; i < allKnown.length; i++) {
for (let i = 0; i < count; i++) {
const [, { alias, endpoint, method, pubsub, section }] = allKnown[i];
allKeys.push(`${section}_${method}`);
@@ -378,7 +379,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// loop through all entries we have (populated in decorate) and filter as required
// only remove when we have results and method missing, or with no results if optional
for (let i = 0; i < allKnown.length; i++) {
for (let i = 0; i < count; i++) {
const [k, { method, section }] = allKnown[i];
if (hasResults && !exposed.includes(k) && k !== 'rpc_methods') {
@@ -411,7 +412,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return fn;
};
for (let s = 0; s < rpc.sections.length; s++) {
for (let s = 0, scount = rpc.sections.length; s < scount; s++) {
const section = rpc.sections[s];
if (!Object.prototype.hasOwnProperty.call(out, section)) {
@@ -420,7 +421,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const decorateInternal = (method: string) =>
decorateFn(section, method);
for (let m = 0; m < methods.length; m++) {
for (let m = 0, mcount = methods.length; m < mcount; m++) {
const method = methods[m];
// skip subscriptions where we have a non-subscribe interface
@@ -446,13 +447,13 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const entries = Object.entries(additional);
for (let j = 0; j < entries.length; j++) {
for (let j = 0, ecount = entries.length; j < ecount; j++) {
const [key, defs] = entries[j];
if (result[key]) {
// we have this one already, step through for new versions or
// new methods and add those as applicable
for (let k = 0; k < defs.length; k++) {
for (let k = 0, dcount = defs.length; k < dcount; k++) {
const def = defs[k];
const prev = result[key].find(({ version }) => def.version === version);
@@ -478,7 +479,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// options > chain/spec > built-in, apply in reverse order with
// methods overriding previous definitions (or interleave missing)
for (let i = 0; i < defValues.length; i++) {
for (let i = 0, count = defValues.length; i < count; i++) {
this._addRuntimeDef(result, defValues[i].runtime);
}
@@ -500,7 +501,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this.#runtimeLog[implName] = true;
for (let i = 0; i < sections.length; i++) {
for (let i = 0, scount = sections.length; i < scount; i++) {
const [_section, secs] = sections[i];
const sectionHash = blake2AsHex(_section, 64);
const rtApi = apis.find(([a]) => a.eq(sectionHash));
@@ -520,7 +521,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
named[section] = {};
}
for (let m = 0; m < methods.length; m++) {
for (let m = 0, mcount = methods.length; m < mcount; m++) {
const [_method, def] = methods[m];
const method = stringCamelCase(_method);
@@ -560,7 +561,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const modules = Object.keys(named);
for (let i = 0; i < modules.length; i++) {
for (let i = 0, count = modules.length; i < count; i++) {
lazyMethod(result, modules[i], lazySection);
}
@@ -645,7 +646,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const sections = Object.keys(tx);
for (let i = 0; i < sections.length; i++) {
for (let i = 0, count = sections.length; i < count; i++) {
lazyMethod(result, sections[i], lazySection);
}
@@ -676,7 +677,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const sections = Object.keys(query);
for (let i = 0; i < sections.length; i++) {
for (let i = 0, count = sections.length; i < count; i++) {
lazyMethod(result, sections[i], lazySection);
}
+2 -2
View File
@@ -265,11 +265,11 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
const sections = Object.keys(source.rpc);
const rpcs: string[] = [];
for (let s = 0; s < sections.length; s++) {
for (let s = 0, scount = sections.length; s < scount; s++) {
const section = sections[s];
const methods = Object.keys((source.rpc as unknown as Record<string, Record<string, unknown>>)[section]);
for (let m = 0; m < methods.length; m++) {
for (let m = 0, mcount = methods.length; m < mcount; m++) {
rpcs.push(`${section}_${methods[m]}`);
}
}
+2 -4
View File
@@ -13,7 +13,7 @@ import type { AddressOrPair, SignerOptions, SubmittableDryRunResult, Submittable
import { catchError, first, map, mergeMap, of, switchMap, tap } from 'rxjs';
import { isBn, isFunction, isNumber, isString, isU8a, objectSpread } from '@polkadot/util';
import { identity, isBn, isFunction, isNumber, isString, isU8a, objectSpread } from '@polkadot/util';
import { filterEvents, isKeyringPair } from '../util/index.js';
import { SubmittableResult } from './Result.js';
@@ -30,8 +30,6 @@ interface UpdateInfo {
updateId: number;
}
const identity = <T> (input: T): T => input;
function makeEraOptions (api: ApiInterfaceRx, registry: Registry, partialOptions: Partial<SignerOptions>, { header, mortalLength, nonce }: { header: Header | null; mortalLength: number; nonce: Index }): SignatureOptions {
if (!header) {
if (partialOptions.era && !partialOptions.blockHash) {
@@ -92,7 +90,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, blockHas
class Submittable extends ExtrinsicBase implements SubmittableExtrinsic<ApiType> {
readonly #ignoreStatusCb: boolean;
#transformResult: (input: ISubmittableResult) => ISubmittableResult = identity;
#transformResult = identity<ISubmittableResult>;
constructor (registry: Registry, extrinsic: Call | Extrinsic | Uint8Array | string) {
super(registry, extrinsic, { version: api.extrinsicType });
+3 -3
View File
@@ -53,12 +53,12 @@ function findMethodExcludes <T> (src: Sections<T>, dst: Sections<T>): string[] {
const dstSections = findSectionIncludes(Object.keys(dst), srcSections);
const excludes: string[] = [];
for (let s = 0; s < dstSections.length; s++) {
for (let s = 0, scount = dstSections.length; s < scount; s++) {
const section = dstSections[s];
const srcMethods = Object.keys(src[section]);
const dstMethods = Object.keys(dst[section]);
for (let d = 0; d < dstMethods.length; d++) {
for (let d = 0, mcount = dstMethods.length; d < mcount; d++) {
const method = dstMethods[d];
if (!srcMethods.includes(method)) {
@@ -95,7 +95,7 @@ export function augmentObject <T> (prefix: string | null, src: Sections<T>, dst:
const sections = Object.keys(src);
for (let i = 0; i < sections.length; i++) {
for (let i = 0, count = sections.length; i < count; i++) {
const section = sections[i];
const methods = src[section];
+1 -1
View File
@@ -35,7 +35,7 @@ export function decorateDeriveSections<ApiType extends ApiTypes> (decorateMethod
const result: AnyDerive = {};
const names = Object.keys(derives);
for (let i = 0; i < names.length; i++) {
for (let i = 0, count = names.length; i < count; i++) {
lazyDeriveSection(result, names[i], getKeys, creator);
}
+1 -1
View File
@@ -24,7 +24,7 @@
"@polkadot/rpc-core": "10.4.2-6-x",
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"tslib": "^2.5.0"
}
}
+2 -2
View File
@@ -24,12 +24,12 @@
"@polkadot/rpc-augment": "10.4.2-6-x",
"@polkadot/rpc-provider": "10.4.2-6-x",
"@polkadot/types": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.0"
},
"devDependencies": {
"@polkadot/keyring": "^12.0.1",
"@polkadot/keyring": "^12.1.1",
"@polkadot/rpc-augment": "10.4.2-6-x"
}
}
+14 -11
View File
@@ -170,12 +170,12 @@ export class RpcCore {
// add any extra user-defined sections
this.sections.push(...Object.keys(userRpc).filter((k) => !this.sections.includes(k)));
for (let s = 0; s < this.sections.length; s++) {
for (let s = 0, scount = this.sections.length; s < scount; s++) {
const section = this.sections[s];
const defs = objectSpread<Record<string, DefinitionRpc | DefinitionRpcSub>>({}, rpcDefinitions[section as 'babe'], userRpc[section]);
const methods = Object.keys(defs);
for (let m = 0; m < methods.length; m++) {
for (let m = 0, mcount = methods.length; m < mcount; m++) {
const method = methods[m];
const def = defs[method];
const jsonrpc = def.endpoint || `${section}_${method}`;
@@ -362,15 +362,16 @@ export class RpcCore {
}
private _formatParams (registry: Registry, blockHash: Uint8Array | string | null | undefined, def: DefinitionRpc, inputs: unknown[]): Codec[] {
const count = inputs.length;
const reqCount = def.params.filter(({ isOptional }) => !isOptional).length;
if (inputs.length < reqCount || inputs.length > def.params.length) {
throw new Error(`Expected ${def.params.length} parameters${reqCount === def.params.length ? '' : ` (${def.params.length - reqCount} optional)`}, ${inputs.length} found instead`);
if (count < reqCount || count > def.params.length) {
throw new Error(`Expected ${def.params.length} parameters${reqCount === def.params.length ? '' : ` (${def.params.length - reqCount} optional)`}, ${count} found instead`);
}
const params = new Array<Codec>(inputs.length);
const params = new Array<Codec>(count);
for (let i = 0; i < inputs.length; i++) {
for (let i = 0; i < count; i++) {
params[i] = registry.createTypeUnsafe(def.params[i].type, [inputs[i]], { blockHash });
}
@@ -390,9 +391,10 @@ export class RpcCore {
: registry.createType('StorageChangeSet', result);
} else if (rpc.type === 'Vec<StorageChangeSet>') {
const jsonSet = (result as StorageChangeSetJSON[]);
const mapped = new Array<[Hash, Codec[]]>(jsonSet.length);
const count = jsonSet.length;
const mapped = new Array<[Hash, Codec[]]>(count);
for (let i = 0; i < jsonSet.length; i++) {
for (let i = 0; i < count; i++) {
const { block, changes } = jsonSet[i];
mapped[i] = [
@@ -426,12 +428,13 @@ export class RpcCore {
private _formatStorageSet (registry: Registry, blockHash: string, keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] {
// For StorageChangeSet, the changes has the [key, value] mappings
const withCache = keys.length !== 1;
const values = new Array<Codec>(keys.length);
const count = keys.length;
const withCache = count !== 1;
const values = new Array<Codec>(count);
// multiple return values (via state.storage subscription), decode the
// values one at a time, all based on the supplied query types
for (let i = 0; i < keys.length; i++) {
for (let i = 0; i < count; i++) {
values[i] = this._formatStorageSetEntry(registry, blockHash, keys[i], changes, withCache, i);
}
+6 -6
View File
@@ -21,14 +21,14 @@
"version": "10.4.2-6-x",
"main": "index.js",
"dependencies": {
"@polkadot/keyring": "^12.0.1",
"@polkadot/keyring": "^12.1.1",
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-support": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util-crypto": "^12.0.1",
"@polkadot/x-fetch": "^12.0.1",
"@polkadot/x-global": "^12.0.1",
"@polkadot/x-ws": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/util-crypto": "^12.1.1",
"@polkadot/x-fetch": "^12.1.1",
"@polkadot/x-global": "^12.1.1",
"@polkadot/x-ws": "^12.1.1",
"eventemitter3": "^5.0.0",
"mock-socket": "^9.2.1",
"nock": "^13.3.1",
+2 -4
View File
@@ -3,7 +3,7 @@
import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types.js';
import { logger } from '@polkadot/util';
import { logger, noop } from '@polkadot/util';
import { fetch } from '@polkadot/x-fetch';
import { RpcCoder } from '../coder/index.js';
@@ -115,9 +115,7 @@ export class HttpProvider implements ProviderInterface {
public on (_type: ProviderInterfaceEmitted, _sub: ProviderInterfaceEmitCb): () => void {
l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
return (): void => {
// noop
};
return noop;
}
/**
+3 -2
View File
@@ -48,9 +48,10 @@ export class LRUCache {
entries (): [string, unknown][] {
const keys = this.keys();
const entries = new Array<[string, unknown]>(keys.length);
const count = keys.length;
const entries = new Array<[string, unknown]>(count);
for (let i = 0; i < keys.length; i++) {
for (let i = 0; i < count; i++) {
const key = keys[i];
entries[i] = [key, this.#data.get(key)];
+11 -5
View File
@@ -356,8 +356,12 @@ export class WsProvider implements ProviderInterface {
start: Date.now(),
subscription
};
this.#endpointStats.bytesSent += body.length;
this.#stats.total.bytesSent += body.length;
const bytesSent = body.length;
this.#endpointStats.bytesSent += bytesSent;
this.#stats.total.bytesSent += bytesSent;
this.#websocket.send(body);
} catch (error) {
this.#endpointStats.errors++;
@@ -480,8 +484,10 @@ export class WsProvider implements ProviderInterface {
#onSocketMessage = (message: MessageEvent<string>): void => {
l.debug(() => ['received', message.data]);
this.#endpointStats.bytesRecv += message.data.length;
this.#stats.total.bytesRecv += message.data.length;
const bytesRecv = message.data.length;
this.#endpointStats.bytesRecv += bytesRecv;
this.#stats.total.bytesRecv += bytesRecv;
const response = JSON.parse(message.data) as JsonRpcResponse;
@@ -602,7 +608,7 @@ export class WsProvider implements ProviderInterface {
const now = Date.now();
const ids = Object.keys(this.#handlers);
for (let i = 0; i < ids.length; i++) {
for (let i = 0, count = ids.length; i < count; i++) {
const handler = this.#handlers[ids[i]];
if ((now - handler.start) > this.#timeout) {
+3 -3
View File
@@ -37,9 +37,9 @@
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/types-create": "10.4.2-6-x",
"@polkadot/types-support": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util-crypto": "^12.0.1",
"@polkadot/x-ws": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/util-crypto": "^12.1.1",
"@polkadot/x-ws": "^12.1.1",
"handlebars": "^4.7.7",
"tslib": "^2.5.0",
"yargs": "^17.7.2"
+5 -4
View File
@@ -24,13 +24,13 @@ function getDefs (apis: Apis | null, defs: Record<string, Definitions>): Record<
const named: Record<string, Record<string, DefinitionCallNamed>> = {};
const all = Object.values(defs);
for (let j = 0; j < all.length; j++) {
for (let j = 0, jcount = all.length; j < jcount; j++) {
const set = all[j].runtime;
if (set) {
const sections = Object.entries(set);
for (let i = 0; i < sections.length; i++) {
for (let i = 0, scount = sections.length; i < scount; i++) {
const [_section, sec] = sections[i];
const sectionHash = blake2AsHex(_section, 64);
const api = apis && apis.find(([h]) => h === sectionHash);
@@ -40,15 +40,16 @@ function getDefs (apis: Apis | null, defs: Record<string, Definitions>): Record<
if (ver) {
const methods = Object.entries(ver.methods);
const mcount = methods.length;
if (methods.length) {
if (mcount) {
const section = stringCamelCase(_section);
if (!named[section]) {
named[section] = {};
}
for (let m = 0; m < methods.length; m++) {
for (let m = 0; m < mcount; m++) {
const [_method, def] = methods[m];
const method = stringCamelCase(_method);
+1 -1
View File
@@ -41,7 +41,7 @@ function splitAlternatives (type: string): string[] {
let level = 0;
// we assume that the string starts with '['
for (let i = 1; i < type.length; i++) {
for (let i = 1, count = type.length; i < count; i++) {
if (level === 0) {
switch (type[i]) {
case ']':
+1 -1
View File
@@ -23,7 +23,7 @@
"dependencies": {
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"tslib": "^2.5.0"
}
}
+3 -3
View File
@@ -21,14 +21,14 @@
"version": "10.4.2-6-x",
"main": "index.js",
"dependencies": {
"@polkadot/util": "^12.0.1",
"@polkadot/x-bigint": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/x-bigint": "^12.1.1",
"tslib": "^2.5.0"
},
"devDependencies": {
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-augment": "10.4.2-6-x",
"@polkadot/types-support": "10.4.2-6-x",
"@polkadot/util-crypto": "^12.0.1"
"@polkadot/util-crypto": "^12.1.1"
}
}
+21 -14
View File
@@ -42,9 +42,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
public get encodedLength (): number {
// We need to loop through all entries since they may have a variable length themselves,
// e.g. when a Vec or Compact is contained withing, it has a variable length based on data
let total = compactToU8a(this.length).length;
const count = this.length;
let total = compactToU8a(count).length;
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
total += this[i].encodedLength;
}
@@ -95,9 +96,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @description Internal per-item inspection of internal values
*/
public inspectInner (): Inspect[] {
const inner = new Array<Inspect>(this.length);
const count = this.length;
const inner = new Array<Inspect>(count);
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
inner[i] = this[i].inspect();
}
@@ -122,9 +124,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/
public toHuman (isExtended?: boolean): AnyJson {
const result = new Array<AnyJson>(this.length);
const count = this.length;
const result = new Array<AnyJson>(count);
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
result[i] = this[i] && this[i].toHuman(isExtended);
}
@@ -135,9 +138,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @description Converts the Object to JSON, typically used for RPC transfers
*/
public toJSON (): AnyJson {
const result = new Array<AnyJson>(this.length);
const count = this.length;
const result = new Array<AnyJson>(count);
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
// We actually log inside the U8a decoding and use JSON.stringify(...), which
// means that the Vec may be partially populated (same applies to toHuman, same check)
result[i] = this[i] && this[i].toJSON();
@@ -150,9 +154,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
const result = new Array<AnyJson>(this.length);
const count = this.length;
const result = new Array<AnyJson>(count);
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
result[i] = this[i] && this[i].toPrimitive();
}
@@ -168,9 +173,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @description Returns the string representation of the value
*/
public override toString (): string {
const result = new Array<string>(this.length);
const count = this.length;
const result = new Array<string>(count);
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
result[i] = this[i].toString();
}
@@ -195,9 +201,10 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
public toU8aInner (isBare?: boolean): Uint8Array[] {
const encoded = new Array<Uint8Array>(this.length);
const count = this.length;
const encoded = new Array<Uint8Array>(count);
for (let i = 0; i < this.length; i++) {
for (let i = 0; i < count; i++) {
encoded[i] = this[i].toU8a(isBare);
}
+2 -6
View File
@@ -5,14 +5,10 @@ import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { AnyJson, AnyNumber, CodecClass, DefinitionSetter, ICompact, Inspect, INumber, IU8a, Registry } from '../types/index.js';
import { compactFromU8a, compactFromU8aLim, compactToU8a, isU8a } from '@polkadot/util';
import { compactFromU8a, compactFromU8aLim, compactToU8a, identity, isU8a } from '@polkadot/util';
import { typeToConstructor } from '../utils/index.js';
function noopSetDefinition <T> (d: CodecClass<T>): CodecClass<T> {
return d;
}
function decodeCompact<T extends INumber> (registry: Registry, Type: CodecClass<T>, value: Compact<T> | AnyNumber): [T, number] {
if (isU8a(value)) {
const [decodedLength, bn] = (value[0] & 0b11) < 0b11
@@ -51,7 +47,7 @@ export class Compact<T extends INumber> implements ICompact<T> {
readonly #Type: CodecClass<T>;
readonly #raw: T;
constructor (registry: Registry, Type: CodecClass<T> | string, value: Compact<T> | AnyNumber = 0, { definition, setDefinition = noopSetDefinition }: DefinitionSetter<CodecClass<T>> = {}) {
constructor (registry: Registry, Type: CodecClass<T> | string, value: Compact<T> | AnyNumber = 0, { definition, setDefinition = identity }: DefinitionSetter<CodecClass<T>> = {}) {
this.registry = registry;
this.#Type = definition || setDefinition(typeToConstructor(registry, Type));
+9 -12
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { AnyJson, Codec, CodecClass, DefinitionSetter, IEnum, Inspect, IU8a, Registry } from '../types/index.js';
import { isHex, isNumber, isObject, isString, isU8a, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util';
import { identity, isHex, isNumber, isObject, isString, isU8a, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util';
import { mapToTypeMap, typesToMap } from '../utils/index.js';
import { Null } from './Null.js';
@@ -32,10 +32,6 @@ interface Decoded {
value: Codec;
}
function noopSetDefinition (d: Definition): Definition {
return d;
}
function isRustEnum (def: Record<string, string | CodecClass> | Record<string, number>): def is Record<string, string | CodecClass> {
const defValues = Object.values(def);
@@ -56,7 +52,7 @@ function extractDef (registry: Registry, _def: Record<string, string | CodecClas
let isIndexed: boolean;
if (Array.isArray(_def)) {
for (let i = 0; i < _def.length; i++) {
for (let i = 0, count = _def.length; i < count; i++) {
def[_def[i]] = { Type: Null, index: i };
}
@@ -65,7 +61,7 @@ function extractDef (registry: Registry, _def: Record<string, string | CodecClas
} else if (isRustEnum(_def)) {
const [Types, keys] = mapToTypeMap(registry, _def);
for (let i = 0; i < keys.length; i++) {
for (let i = 0, count = keys.length; i < count; i++) {
def[keys[i]] = { Type: Types[i], index: i };
}
@@ -74,7 +70,7 @@ function extractDef (registry: Registry, _def: Record<string, string | CodecClas
} else {
const entries = Object.entries(_def);
for (let i = 0; i < entries.length; i++) {
for (let i = 0, count = entries.length; i < count; i++) {
const [key, index] = entries[i];
def[key] = { Type: Null, index };
@@ -191,7 +187,7 @@ export class Enum implements IEnum {
readonly #isIndexed: boolean;
readonly #raw: Codec;
constructor (registry: Registry, Types: Record<string, string | CodecClass> | Record<string, number> | string[], value?: unknown, index?: number, { definition, setDefinition = noopSetDefinition }: DefinitionSetter<Definition> = {}) {
constructor (registry: Registry, Types: Record<string, string | CodecClass> | Record<string, number> | string[], value?: unknown, index?: number, { definition, setDefinition = identity }: DefinitionSetter<Definition> = {}) {
const { def, isBasic, isIndexed } = definition || setDefinition(extractDef(registry, Types));
// shortcut isU8a as used in SCALE decoding
@@ -224,10 +220,11 @@ export class Enum implements IEnum {
const keys = Array.isArray(Types)
? Types
: Object.keys(Types);
const asKeys = new Array<string>(keys.length);
const isKeys = new Array<string>(keys.length);
const count = keys.length;
const asKeys = new Array<string>(count);
const isKeys = new Array<string>(count);
for (let i = 0; i < keys.length; i++) {
for (let i = 0; i < count; i++) {
const name = stringPascalCase(keys[i]);
asKeys[i] = `as${name}`;
+2 -6
View File
@@ -4,15 +4,11 @@
import type { HexString } from '@polkadot/util/types';
import type { AnyJson, Codec, CodecClass, DefinitionSetter, Inspect, IOption, IU8a, Registry } from '../types/index.js';
import { isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
import { identity, isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
import { typeToConstructor } from '../utils/index.js';
import { Null } from './Null.js';
function noopSetDefinition <T extends Codec> (d: CodecClass<T>): CodecClass<T> {
return d;
}
class None extends Null {
/**
* @description Returns the base runtime type name for this instance
@@ -70,7 +66,7 @@ export class Option<T extends Codec> implements IOption<T> {
readonly #Type: CodecClass<T>;
readonly #raw: T;
constructor (registry: Registry, typeName: CodecClass<T> | string, value?: unknown, { definition, setDefinition = noopSetDefinition }: DefinitionSetter<CodecClass<T>> = {}) {
constructor (registry: Registry, typeName: CodecClass<T> | string, value?: unknown, { definition, setDefinition = identity }: DefinitionSetter<CodecClass<T>> = {}) {
const Type = definition || setDefinition(typeToConstructor(registry, typeName));
const decoded = isU8a(value) && value.length && !isCodec(value)
? value[0] === 0
+7 -11
View File
@@ -3,10 +3,10 @@
import type { AnyTupleValue, Codec, CodecClass, DefinitionSetter, Inspect, ITuple, Registry } from '../types/index.js';
import { isFunction, isHex, isString, isU8a, stringify, u8aConcatStrict, u8aToU8a } from '@polkadot/util';
import { identity, isFunction, isHex, isString, isU8a, stringify, u8aConcatStrict, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from '../abstract/Array.js';
import { decodeU8a, mapToTypeMap, typeToConstructor } from '../utils/index.js';
import { decodeU8a, mapToTypeMap, typesToConstructors, typeToConstructor } from '../utils/index.js';
type TupleType = (CodecClass | string);
@@ -16,16 +16,12 @@ type TupleTypes = TupleType[] | {
type Definition = [CodecClass[], string[]];
function noopSetDefinition (d: Definition): Definition {
return d;
}
/** @internal */
function decodeTuple (registry: Registry, result: Codec[], value: Exclude<AnyTupleValue, Uint8Array> | undefined, Classes: Definition): [Codec[], number] {
if (Array.isArray(value)) {
const Types = Classes[0];
for (let i = 0; i < Types.length; i++) {
for (let i = 0, count = Types.length; i < count; i++) {
try {
const entry = value?.[i];
@@ -43,7 +39,7 @@ function decodeTuple (registry: Registry, result: Codec[], value: Exclude<AnyTup
} else if (!value || !result.length) {
const Types = Classes[0];
for (let i = 0; i < Types.length; i++) {
for (let i = 0, count = Types.length; i < count; i++) {
result[i] = new Types[i](registry);
}
@@ -62,10 +58,10 @@ function decodeTuple (registry: Registry, result: Codec[], value: Exclude<AnyTup
export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
#Types: Definition;
constructor (registry: Registry, Types: TupleTypes | TupleType, value?: AnyTupleValue, { definition, setDefinition = noopSetDefinition }: DefinitionSetter<Definition> = {}) {
constructor (registry: Registry, Types: TupleTypes | TupleType, value?: AnyTupleValue, { definition, setDefinition = identity }: DefinitionSetter<Definition> = {}) {
const Classes = definition || setDefinition(
Array.isArray(Types)
? [Types.map((t) => typeToConstructor(registry, t)), []]
? [typesToConstructors(registry, Types), []]
: isFunction(Types) || isString(Types)
? [[typeToConstructor(registry, Types)], []]
: mapToTypeMap(registry, Types)
@@ -101,7 +97,7 @@ export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
public override get encodedLength (): number {
let total = 0;
for (let i = 0; i < this.length; i++) {
for (let i = 0, count = this.length; i < count; i++) {
total += this[i].encodedLength;
}
+3 -7
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Codec, CodecClass, DefinitionSetter, Registry } from '../types/index.js';
import { compactFromU8aLim, isHex, isU8a, logger, stringify, u8aToU8a } from '@polkadot/util';
import { compactFromU8aLim, identity, isHex, isU8a, logger, stringify, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from '../abstract/Array.js';
import { decodeU8aVec, typeToConstructor } from '../utils/index.js';
@@ -13,10 +13,6 @@ const MAX_LENGTH = 64 * 1024;
const l = logger('Vec');
function noopSetDefinition <T extends Codec> (d: CodecClass<T>): CodecClass<T> {
return d;
}
function decodeVecLength (value: Uint8Array | HexString | unknown[]): [Uint8Array | unknown[] | null, number, number] {
if (Array.isArray(value)) {
return [value, value.length, 0];
@@ -75,7 +71,7 @@ export function decodeVec<T extends Codec> (registry: Registry, result: T[], val
export class Vec<T extends Codec> extends AbstractArray<T> {
#Type: CodecClass<T>;
constructor (registry: Registry, Type: CodecClass<T> | string, value: Uint8Array | HexString | unknown[] = [], { definition, setDefinition = noopSetDefinition }: DefinitionSetter<CodecClass<T>> = {}) {
constructor (registry: Registry, Type: CodecClass<T> | string, value: Uint8Array | HexString | unknown[] = [], { definition, setDefinition = identity }: DefinitionSetter<CodecClass<T>> = {}) {
const [decodeFrom, length, startAt] = decodeVecLength(value);
super(registry, length);
@@ -119,7 +115,7 @@ export class Vec<T extends Codec> extends AbstractArray<T> {
? other
: new this.#Type(this.registry, other);
for (let i = 0; i < this.length; i++) {
for (let i = 0, count = this.length; i < count; i++) {
if (check.eq(this[i])) {
return i;
}
+3 -7
View File
@@ -4,16 +4,12 @@
import type { HexString } from '@polkadot/util/types';
import type { Codec, CodecClass, DefinitionSetter, Inspect, Registry } from '../types/index.js';
import { isU8a, u8aConcatStrict } from '@polkadot/util';
import { identity, isU8a, u8aConcatStrict } from '@polkadot/util';
import { AbstractArray } from '../abstract/Array.js';
import { decodeU8aVec, typeToConstructor } from '../utils/index.js';
import { decodeVec } from './Vec.js';
function noopSetDefinition <T extends Codec> (d: CodecClass<T>): CodecClass<T> {
return d;
}
/**
* @name VecFixed
* @description
@@ -22,7 +18,7 @@ function noopSetDefinition <T extends Codec> (d: CodecClass<T>): CodecClass<T> {
export class VecFixed<T extends Codec> extends AbstractArray<T> {
#Type: CodecClass<T>;
constructor (registry: Registry, Type: CodecClass<T> | string, length: number, value: Uint8Array | HexString | unknown[] = [] as unknown[], { definition, setDefinition = noopSetDefinition }: DefinitionSetter<CodecClass<T>> = {}) {
constructor (registry: Registry, Type: CodecClass<T> | string, length: number, value: Uint8Array | HexString | unknown[] = [] as unknown[], { definition, setDefinition = identity }: DefinitionSetter<CodecClass<T>> = {}) {
super(registry, length);
this.#Type = definition || setDefinition(typeToConstructor<T>(registry, Type));
@@ -61,7 +57,7 @@ export class VecFixed<T extends Codec> extends AbstractArray<T> {
public override get encodedLength (): number {
let total = 0;
for (let i = 0; i < this.length; i++) {
for (let i = 0, count = this.length; i < count; i++) {
total += this[i].encodedLength;
}
+3 -2
View File
@@ -87,9 +87,10 @@ export class BitVec extends Raw {
!!(v & 0b0000_0010),
!!(v & 0b0000_0001)
]);
const result = new Array<boolean>(8 * map.length);
const count = map.length;
const result = new Array<boolean>(8 * count);
for (let i = 0; i < map.length; i++) {
for (let i = 0; i < count; i++) {
const off = i * 8;
const v = map[i];
+1 -1
View File
@@ -26,7 +26,7 @@ function decodeMapFromU8a<K extends Codec, V extends Codec> (registry: Registry,
const [values, decodedLength] = decodeU8a(registry, new Array(types.length), u8a.subarray(offset), [types, []]);
for (let i = 0; i < values.length; i += 2) {
for (let i = 0, count = values.length; i < count; i += 2) {
output.set(values[i] as K, values[i + 1] as V);
}
+8 -6
View File
@@ -13,7 +13,7 @@ type SetValues = Record<string, number | BN>;
function encodeSet (setValues: SetValues, values: string[]): BN {
const encoded = new BN(0);
for (let i = 0; i < values.length; i++) {
for (let i = 0, count = values.length; i < count; i++) {
encoded.ior(bnToBn(setValues[values[i]] || 0));
}
@@ -22,9 +22,10 @@ function encodeSet (setValues: SetValues, values: string[]): BN {
/** @internal */
function decodeSetArray (setValues: SetValues, values: string[]): string[] {
const result = new Array<string>(values.length);
const count = values.length;
const result = new Array<string>(count);
for (let i = 0; i < values.length; i++) {
for (let i = 0; i < count; i++) {
const key = values[i];
if (isUndefined(setValues[key])) {
@@ -43,7 +44,7 @@ function decodeSetNumber (setValues: SetValues, _value: BN | number): string[] {
const keys = Object.keys(setValues);
const result: string[] = [];
for (let i = 0; i < keys.length; i++) {
for (let i = 0, count = keys.length; i < count; i++) {
const key = keys[i];
if (bn.and(bnToBn(setValues[key])).eq(bnToBn(setValues[key]))) {
@@ -113,9 +114,10 @@ export class CodecSet extends Set<string> implements ISet<string> {
return class extends CodecSet {
static {
const keys = Object.keys(values);
const isKeys = new Array<string>(keys.length);
const count = keys.length;
const isKeys = new Array<string>(count);
for (let i = 0; i < keys.length; i++) {
for (let i = 0; i < count; i++) {
isKeys[i] = `is${stringPascalCase(keys[i])}`;
}
+6 -5
View File
@@ -21,16 +21,17 @@ function decodeStructFromObject (registry: Registry, [Types, keys]: Definition,
let jsonObj: Record<string, unknown> | undefined;
const typeofArray = Array.isArray(value);
const typeofMap = value instanceof Map;
const count = keys.length;
if (!typeofArray && !typeofMap && !isObject(value)) {
throw new Error(`Struct: Cannot decode value ${stringify(value)} (typeof ${typeof value}), expected an input object, map or array`);
} else if (typeofArray && value.length !== keys.length) {
} else if (typeofArray && value.length !== count) {
throw new Error(`Struct: Unable to map ${stringify(value)} array to object with known keys ${keys.join(', ')}`);
}
const raw = new Array<[string, Codec]>(keys.length);
const raw = new Array<[string, Codec]>(count);
for (let i = 0; i < keys.length; i++) {
for (let i = 0; i < count; i++) {
const key = keys[i];
const jsonKey = jsonMap.get(key) || key;
const Type = Types[i];
@@ -50,7 +51,7 @@ function decodeStructFromObject (registry: Registry, [Types, keys]: Definition,
jsonObj = {};
for (let e = 0; e < entries.length; e++) {
for (let e = 0, ecount = entries.length; e < ecount; e++) {
jsonObj[stringCamelCase(entries[e][0])] = entries[e][1];
}
}
@@ -192,7 +193,7 @@ export class Struct<
const result: Record<string, string> = {};
const [Types, keys] = this.#Types;
for (let i = 0; i < keys.length; i++) {
for (let i = 0, count = keys.length; i < count; i++) {
result[keys[i]] = new Types[i](this.registry).toRawType();
}
+4 -3
View File
@@ -13,12 +13,13 @@ const PRE_PAD = 32;
function loop (count: number, inputs: unknown[][], exec: ExecFn): [number, unknown[]] {
const start = performance.now();
const results = new Array<unknown>(inputs.length);
const inputsCount = inputs.length;
const results = new Array<unknown>(inputsCount);
for (let i = 0; i < count; i++) {
const result = exec(...inputs[i % inputs.length]);
const result = exec(...inputs[i % inputsCount]);
if (i < inputs.length) {
if (i < inputsCount) {
results[i] = result;
}
}
@@ -64,6 +64,9 @@ export interface Registry {
createClassUnsafe <T extends Codec = Codec, K extends string = string> (type: K): CodecClass<T>;
createTypeUnsafe <T extends Codec = Codec, K extends string = string> (type: K, params: unknown[], options?: CodecCreateOptions): T;
// get is for Compat, overridden in derived classes
get (...params: never[]): any;
getClassName (clazz: CodecClass): string | undefined;
getOrThrow <T extends Codec = Codec, K extends string = string> (name: K, msg?: string): CodecClass<T>;
getOrUnknown <T extends Codec = Codec, K extends string = string> (name: K): CodecClass<T>;
@@ -5,7 +5,7 @@ import { isUndefined } from '@polkadot/util';
import { hasEq } from './util.js';
// NOTE These are used internally and when comparing objects, expects that
// NOTE These are used internally and when comparing objects, we expect that
// when the second is an Codec[] that the first has to be as well
export function compareArray (a: unknown[], b?: unknown): boolean {
if (Array.isArray(b)) {
+1 -1
View File
@@ -25,7 +25,7 @@ function compareMapArray (a: Map<unknown, unknown>, b: [unknown, unknown][]): bo
);
}
// NOTE These are used internally and when comparing objects, expects that
// NOTE These are used internally and when comparing objects, we expect that
// when the second is an Map<string, Codec> that the first has to be as well
export function compareMap (a: Map<unknown, unknown>, b?: unknown): boolean {
if (Array.isArray(b)) {
+1 -1
View File
@@ -8,7 +8,7 @@ function compareSetArray (a: Set<unknown>, b: any[]): boolean {
return (a.size === b.length) && !b.some((e) => !a.has(e));
}
// NOTE These are used internally and when comparing objects, expects that
// NOTE These are used internally and when comparing objects, we expect that
// when the second is an Set<string, Codec> that the first has to be as well
export function compareSet (a: Set<unknown>, b?: unknown): boolean {
if (Array.isArray(b)) {
+1 -2
View File
@@ -5,8 +5,7 @@ export { compareArray } from './compareArray.js';
export { compareMap } from './compareMap.js';
export { compareSet } from './compareSet.js';
export { decodeU8a, decodeU8aStruct, decodeU8aVec } from './decodeU8a.js';
export { mapToTypeMap } from './mapToTypeMap.js';
export { sanitize } from './sanitize.js';
export { sortAsc, sortMap, sortSet } from './sortValues.js';
export { mapToTypeMap, typesToConstructors, typeToConstructor } from './toConstructors.js';
export { typesToMap } from './typesToMap.js';
export { typeToConstructor } from './typeToConstructor.js';
@@ -1,22 +0,0 @@
// Copyright 2017-2023 @polkadot/types-codec authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { CodecClass, Registry } from '../types/index.js';
import { typeToConstructor } from './typeToConstructor.js';
/**
* @description takes an input map of the form `{ [string]: string | CodecClass }` and returns a map of `{ [string]: CodecClass }`
*/
export function mapToTypeMap (registry: Registry, input: Record<string, string | CodecClass>): [CodecClass[], string[]] {
const entries = Object.entries(input);
const count = entries.length;
const output: [CodecClass[], string[]] = [new Array<CodecClass>(count), new Array<string>(count)];
for (let i = 0; i < count; i++) {
output[1][i] = entries[i][0];
output[0][i] = typeToConstructor(registry, entries[i][1]);
}
return output;
}
+16 -16
View File
@@ -58,14 +58,14 @@ export function trim (): Mapper {
export function findClosing (value: string, start: number): number {
let depth = 0;
for (let index = start; index < value.length; index++) {
if (value[index] === '>') {
for (let i = start, count = value.length; i < count; i++) {
if (value[i] === '>') {
if (!depth) {
return index;
return i;
}
depth--;
} else if (value[index] === '<') {
} else if (value[i] === '<') {
depth++;
}
}
@@ -91,12 +91,12 @@ export function alias (src: string, dest: string, withChecks = true): Mapper {
export function cleanupCompact (): Mapper {
return (value: string): string => {
if (value.includes(' as HasCompact')) {
for (let index = 0; index < value.length; index++) {
if (value[index] === '<') {
const end = findClosing(value, index + 1) - 14;
for (let i = 0, count = value.length; i < count; i++) {
if (value[i] === '<') {
const end = findClosing(value, i + 1) - 14;
if (value.substring(end, end + 14) === ' as HasCompact') {
value = `Compact<${value.substring(index + 1, end)}>`;
value = `Compact<${value.substring(i + 1, end)}>`;
}
}
}
@@ -141,7 +141,7 @@ function replaceTagWith (value: string, matcher: string, replacer: (inner: strin
// remove the Bounded* or Weak* wrappers
export function removeExtensions (type: string, isSized: boolean): Mapper {
return (value: string): string => {
for (let i = 0; i < BOUNDED.length; i++) {
for (let i = 0, count = BOUNDED.length; i < count; i++) {
const tag = BOUNDED[i];
value = replaceTagWith(value, `${type}${tag}<`, (v: string): string => {
@@ -188,16 +188,16 @@ export function removeColons (): Mapper {
export function removeGenerics (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value[index] === '<') {
for (let i = 0, count = value.length; i < count; i++) {
if (value[i] === '<') {
// check against the allowed wrappers, be it Vec<..>, Option<...> ...
const box = ALLOWED_BOXES.find((box): boolean => {
const start = index - box.length;
const start = i - box.length;
return (
(
start >= 0 &&
value.substring(start, index) === box
value.substring(start, i) === box
) && (
// make sure it is stand-alone, i.e. don't catch ElectionResult<...> as Result<...>
start === 0 ||
@@ -208,9 +208,9 @@ export function removeGenerics (): Mapper {
// we have not found anything, unwrap generic innards
if (!box) {
const end = findClosing(value, index + 1);
const end = findClosing(value, i + 1);
value = `${value.substring(0, index)}${value.substring(end + 1)}`;
value = `${value.substring(0, i)}${value.substring(end + 1)}`;
}
}
}
@@ -280,7 +280,7 @@ export function sanitize (value: AnyString): string {
let result = startValue;
for (let i = 0; i < mappings.length; i++) {
for (let i = 0, count = mappings.length; i < count; i++) {
result = mappings[i](result);
}
+3 -8
View File
@@ -5,7 +5,7 @@ import type { BN } from '@polkadot/util';
import type { Enum } from '../base/Enum.js';
import type { Codec } from '../types/index.js';
import { bnToBn, isBigInt, isBn, isFunction, isNumber, stringify } from '@polkadot/util';
import { bnToBn, isBigInt, isBn, isCodec, isNumber, stringify } from '@polkadot/util';
type SortArg = Codec | Codec[] | number[] | BN | bigint | number | Uint8Array;
@@ -14,14 +14,9 @@ function isArrayLike (arg: SortArg): arg is Uint8Array | Codec[] | number[] {
return arg instanceof Uint8Array || Array.isArray(arg);
}
/** @internal **/
function isCodec (arg: SortArg): arg is Codec {
return isFunction(arg && (arg as Codec).toU8a);
}
/** @internal **/
function isEnum (arg: SortArg): arg is Enum {
return isCodec(arg) && isNumber((arg as Enum).index) && isCodec((arg as Enum).value);
return isCodec<Codec>(arg) && isNumber((arg as Enum).index) && isCodec((arg as Enum).value);
}
/** @internal */
@@ -60,7 +55,7 @@ export function sortAsc<V extends SortArg = Codec> (a: V, b: V): number {
return sortAsc(a.index, b.index) || sortAsc(a.value, b.value);
} else if (isArrayLike(a) && isArrayLike(b)) {
return sortArray(a, b);
} else if (isCodec(a) && isCodec(b)) {
} else if (isCodec<Codec>(a) && isCodec<Codec>(b)) {
// Text, Bool etc.
return sortAsc(a.toU8a(true), b.toU8a(true));
}
@@ -0,0 +1,46 @@
// Copyright 2017-2023 @polkadot/types-codec authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec, CodecClass, Registry } from '../types/index.js';
/**
* @internal
* From a type string or class, return the associated type class
*/
export function typeToConstructor <T extends Codec = Codec> (registry: Registry, type: string | CodecClass<T>): CodecClass<T> {
return typeof type === 'function'
? type
: registry.createClassUnsafe(type);
}
/**
* @internal
* Takes an input array of types and returns the associated classes for it
*/
export function typesToConstructors <T extends Codec = Codec> (registry: Registry, types: (string | CodecClass<T>)[]): CodecClass<T>[] {
const count = types.length;
const result = new Array<CodecClass<T>>(count);
for (let i = 0; i < count; i++) {
result[i] = typeToConstructor(registry, types[i]);
}
return result;
}
/**
* @internal
* Takes an input map of the form `{ [string]: string | CodecClass }` and returns a map of `{ [string]: CodecClass }`
*/
export function mapToTypeMap (registry: Registry, input: Record<string, string | CodecClass>): [CodecClass[], string[]] {
const entries = Object.entries(input);
const count = entries.length;
const output: [CodecClass[], string[]] = [new Array<CodecClass>(count), new Array<string>(count)];
for (let i = 0; i < count; i++) {
output[1][i] = entries[i][0];
output[0][i] = typeToConstructor(registry, entries[i][1]);
}
return output;
}
@@ -1,14 +0,0 @@
// Copyright 2017-2023 @polkadot/types-codec authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec, CodecClass, Registry } from '../types/index.js';
import { isString } from '@polkadot/util';
export function typeToConstructor <T extends Codec = Codec> (registry: Registry, type: string | CodecClass<T>): CodecClass<T> {
return (
isString(type)
? registry.createClassUnsafe(type)
: type
);
}
+1 -1
View File
@@ -6,7 +6,7 @@ import type { CodecClass, Registry } from '../types/index.js';
export function typesToMap (registry: Registry, [Types, keys]: [CodecClass[], string[]]): Record<string, string> {
const result: Record<string, string> = {};
for (let i = 0; i < keys.length; i++) {
for (let i = 0, count = keys.length; i < count; i++) {
result[keys[i]] = registry.getClassName(Types[i]) || new Types[i](registry).toRawType();
}
+1 -1
View File
@@ -22,7 +22,7 @@
"main": "index.js",
"dependencies": {
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"tslib": "^2.5.0"
},
"devDependencies": {
+1 -1
View File
@@ -39,7 +39,7 @@ function getTypeClassMap (value: TypeDef): Record<string, string> {
const subs = getSubDefArray(value);
const map: Record<string, string> = {};
for (let i = 0; i < subs.length; i++) {
for (let i = 0, count = subs.length; i < count; i++) {
map[subs[i].name as string] = getTypeDefType(subs[i]);
}
@@ -53,7 +53,7 @@ function encodeSubTypes (registry: Registry, sub: TypeDef[], asEnum?: boolean, e
const inner: Record<string, string> = objectSpread({}, extra);
for (let i = 0; i < sub.length; i++) {
for (let i = 0, count = sub.length; i < count; i++) {
const def = sub[i];
inner[def.name as string] = encodeTypeDef(registry, def);
+1 -1
View File
@@ -14,7 +14,7 @@ export function typeSplit (type: string): string[] {
// current start position
let start = 0;
for (let i = 0; i < type.length; i++) {
for (let i = 0, count = type.length; i < count; i++) {
switch (type[i]) {
// if we are not nested, add the type
case ',': {
+2 -2
View File
@@ -21,11 +21,11 @@
"version": "10.4.2-6-x",
"main": "index.js",
"dependencies": {
"@polkadot/networks": "^12.0.1",
"@polkadot/networks": "^12.1.1",
"@polkadot/types": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/types-create": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"tslib": "^2.5.0"
},
"devDependencies": {
+1 -1
View File
@@ -21,7 +21,7 @@
"version": "10.4.2-6-x",
"main": "index.js",
"dependencies": {
"@polkadot/util": "^12.0.1",
"@polkadot/util": "^12.1.1",
"tslib": "^2.5.0"
}
}
+4 -4
View File
@@ -21,17 +21,17 @@
"version": "10.4.2-6-x",
"main": "index.js",
"dependencies": {
"@polkadot/keyring": "^12.0.1",
"@polkadot/keyring": "^12.1.1",
"@polkadot/types-augment": "10.4.2-6-x",
"@polkadot/types-codec": "10.4.2-6-x",
"@polkadot/types-create": "10.4.2-6-x",
"@polkadot/util": "^12.0.1",
"@polkadot/util-crypto": "^12.0.1",
"@polkadot/util": "^12.1.1",
"@polkadot/util-crypto": "^12.1.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.0"
},
"devDependencies": {
"@polkadot/keyring": "^12.0.1",
"@polkadot/keyring": "^12.1.1",
"@polkadot/types-support": "10.4.2-6-x"
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ export function lazyVariants <T> (lookup: PortableRegistry, { type }: TypeHolder
const result: Record<string, T> = {};
const variants = lookup.getSiType(type).def.asVariant.variants;
for (let i = 0; i < variants.length; i++) {
for (let i = 0, count = variants.length; i < count; i++) {
lazyMethod(result, variants[i], creator, getName, i);
}
+15 -13
View File
@@ -35,9 +35,10 @@ function valueToString (v: { toString: () => string }): string {
}
function getFieldArgs (lookup: PortableRegistry, fields: SiField[]): string[] {
const args = new Array<string>(fields.length);
const count = fields.length;
const args = new Array<string>(count);
for (let i = 0; i < fields.length; i++) {
for (let i = 0; i < count; i++) {
args[i] = lookup.getTypeDef(fields[i].type).type;
}
@@ -47,7 +48,7 @@ function getFieldArgs (lookup: PortableRegistry, fields: SiField[]): string[] {
function clearRecord (record: Record<string, unknown>): void {
const keys = Object.keys(record);
for (let i = 0; i < keys.length; i++) {
for (let i = 0, count = keys.length; i < count; i++) {
delete record[keys[i]];
}
}
@@ -60,7 +61,7 @@ function getVariantStringIdx ({ index }: SiVariant): string {
function injectErrors (_: TypeRegistry, { lookup, pallets }: MetadataLatest, version: number, result: Record<string, Record<string, RegistryError>>): void {
clearRecord(result);
for (let i = 0; i < pallets.length; i++) {
for (let i = 0, count = pallets.length; i < count; i++) {
const { errors, index, name } = pallets[i];
if (errors.isSome) {
@@ -87,7 +88,7 @@ function injectEvents (registry: TypeRegistry, { lookup, pallets }: MetadataLate
clearRecord(result);
for (let i = 0; i < filtered.length; i++) {
for (let i = 0, count = filtered.length; i < count; i++) {
const { events, index, name } = filtered[i];
lazyMethod(result, version >= 12 ? index.toNumber() : i, () =>
@@ -111,7 +112,7 @@ function injectExtrinsics (registry: TypeRegistry, { lookup, pallets }: Metadata
clearRecord(result);
clearRecord(mapping);
for (let i = 0; i < filtered.length; i++) {
for (let i = 0, count = filtered.length; i < count; i++) {
const { calls, index, name } = filtered[i];
const sectionIndex = version >= 12 ? index.toNumber() : i;
const sectionName = stringCamelCase(name);
@@ -180,6 +181,7 @@ export class TypeRegistry implements Registry {
#userExtensions?: ExtDef | undefined;
readonly #knownDefaults: Record<string, CodecClass>;
readonly #knownDefaultsEntries: [string, CodecClass][];
readonly #knownDefinitions: Record<string, Definitions>;
readonly #metadataCalls: Record<string, Record<string, CallFunction>> = {};
readonly #metadataErrors: Record<string, Record<string, RegistryError>> = {};
@@ -190,11 +192,12 @@ export class TypeRegistry implements Registry {
constructor (createdAtHash?: Hash | Uint8Array | string) {
this.#knownDefaults = objectSpread({ Json, Metadata, PortableRegistry, Raw }, baseTypes);
this.#knownDefaultsEntries = Object.entries(this.#knownDefaults);
this.#knownDefinitions = definitions;
const allKnown = Object.values(this.#knownDefinitions);
for (let i = 0; i < allKnown.length; i++) {
for (let i = 0, count = allKnown.length; i < count; i++) {
this.register(allKnown[i].types as unknown as RegistryTypes);
}
@@ -393,7 +396,7 @@ export class TypeRegistry implements Registry {
// (previously this used to be a simple find & return)
const names: string[] = [];
for (const [name, Clazz] of Object.entries(this.#knownDefaults)) {
for (const [name, Clazz] of this.#knownDefaultsEntries) {
if (Type === Clazz) {
names.push(name);
}
@@ -405,11 +408,10 @@ export class TypeRegistry implements Registry {
}
}
// both sort and reverse are done in-place
names.sort().reverse();
return names.length
? names[0]
// both sort and reverse are done in-place
// ['U32', 'u32'] -> ['u32', 'U32']
? names.sort().reverse()[0]
: undefined;
}
@@ -485,7 +487,7 @@ export class TypeRegistry implements Registry {
#registerObject = (obj: RegistryTypes): void => {
const entries = Object.entries(obj);
for (let e = 0; e < entries.length; e++) {
for (let e = 0, count = entries.length; e < count; e++) {
const [name, type] = entries[e];
if (isFunction(type)) {
+1 -1
View File
@@ -88,7 +88,7 @@ abstract class ExtrinsicBase<A extends AnyTuple> extends AbstractBase<ExtrinsicV
// This is on the abstract class, ensuring that hasOwnProperty operates
// correctly, i.e. it needs to be on the base class exposing it
for (let i = 0; i < signKeys.length; i++) {
for (let i = 0, count = signKeys.length; i < count; i++) {
objectProperty(this, signKeys[i], getter);
}
}
@@ -116,7 +116,7 @@ export class GenericSignerPayload extends Struct implements ISignerPayload, Sign
const keys = Object.keys(this.#extraTypes);
// add any explicit overrides we may have
for (let i = 0; i < keys.length; i++) {
for (let i = 0, count = keys.length; i < count; i++) {
const key = keys[i];
const value = this.get(key) as Codec;
const isOption = value instanceof Option;
@@ -120,7 +120,7 @@ export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSig
protected _injectSignature (signer: Address, signature: ExtrinsicSignature, payload: GenericExtrinsicPayloadV4): IExtrinsicSignature {
// use the fields exposed to guide the getters
for (let i = 0; i < this.#signKeys.length; i++) {
for (let i = 0, count = this.#signKeys.length; i < count; i++) {
const k = this.#signKeys[i];
const v = payload.get(k);
+1 -1
View File
@@ -110,7 +110,7 @@ export class GenericEventData extends Tuple implements IEventData {
if (this.#names !== null) {
const json: Record<string, AnyJson> = {};
for (let i = 0; i < this.#names.length; i++) {
for (let i = 0, count = this.#names.length; i < count; i++) {
json[this.#names[i]] = this[i].toHuman(isExtended);
}
@@ -103,9 +103,10 @@ const PATH_RM_INDEX_1 = ['generic', 'misc', 'pallet', 'traits', 'types'];
/** @internal Converts a Text[] into string[] (used as part of definitions) */
function sanitizeDocs (docs: Text[]): string[] {
const result = new Array<string>(docs.length);
const count = docs.length;
const result = new Array<string>(count);
for (let i = 0; i < docs.length; i++) {
for (let i = 0; i < count; i++) {
result[i] = docs[i].toString();
}
@@ -114,9 +115,10 @@ function sanitizeDocs (docs: Text[]): string[] {
/** @internal Split a namespace with :: into individual parts */
function splitNamespace (values: string[]): string[][] {
const result = new Array<string[]>(values.length);
const count = values.length;
const result = new Array<string[]>(count);
for (let i = 0; i < values.length; i++) {
for (let i = 0; i < count; i++) {
result[i] = values[i].split('::');
}
@@ -237,7 +239,7 @@ function extractName (portable: PortableType[], lookupIndex: number, { type: { p
function nextDupeMatches (name: string, startAt: number, names: Extract[]): Extract[] {
const result = [names[startAt]];
for (let i = startAt + 1; i < names.length; i++) {
for (let i = startAt + 1, count = names.length; i < count; i++) {
const v = names[i];
if (v.name === name) {
@@ -331,11 +333,12 @@ function removeDupeNames (lookup: PortableRegistry, portable: PortableType[], na
}
// see if using the param type helps
const adjusted = new Array<ExtractBase>(allSame.length);
const sameCount = allSame.length;
const adjusted = new Array<ExtractBase>(sameCount);
// loop through all, specifically checking that index where the
// first param yields differences
for (let i = 0; i < allSame.length; i++) {
for (let i = 0; i < sameCount; i++) {
const { lookupIndex, name, params } = allSame[i];
const { def, path } = lookup.getSiType(params[paramIdx].type.unwrap());
@@ -364,7 +367,7 @@ function removeDupeNames (lookup: PortableRegistry, portable: PortableType[], na
// Last-ditch effort to use the full type path - ugly
// loop through all, specifically checking that index where the
// first param yields differences
for (let i = 0; i < allSame.length; i++) {
for (let i = 0; i < sameCount; i++) {
const { lookupIndex, name, params } = allSame[i];
const { def, path } = lookup.getSiType(params[paramIdx].type.unwrap());
const flat = extractNameFlat(portable, lookupIndex, params, path, true);
@@ -465,9 +468,8 @@ function extractAliases (params: Record<string, SiTypeParameter[]>, isContract?:
function extractTypeInfo (lookup: PortableRegistry, portable: PortableType[]): TypeInfo {
const nameInfo: Extract[] = [];
const types: Record<number, PortableType> = {};
const porCount = portable.length;
for (let i = 0; i < porCount; i++) {
for (let i = 0, count = portable.length; i < count; i++) {
const type = portable[i];
const lookupIndex = type.id.toNumber();
const extracted = extractName(portable, lookupIndex, portable[i]);
@@ -483,9 +485,8 @@ function extractTypeInfo (lookup: PortableRegistry, portable: PortableType[]): T
const names: Record<number, string> = {};
const params: Record<string, SiTypeParameter[]> = {};
const dedup = removeDupeNames(lookup, portable, nameInfo);
const dedupCount = dedup.length;
for (let i = 0; i < dedupCount; i++) {
for (let i = 0, count = dedup.length; i < count; i++) {
const { lookupIndex, name, params: p } = dedup[i];
names[lookupIndex] = name;
@@ -832,8 +833,9 @@ export class PortableRegistry extends Struct implements ILookup {
#extractFields (lookupIndex: number, fields: SiField[]): TypeDef {
let isStruct = true;
let isTuple = true;
const count = fields.length;
for (let f = 0; f < fields.length; f++) {
for (let f = 0; f < count; f++) {
const { name } = fields[f];
isStruct = isStruct && name.isSome;
@@ -844,12 +846,12 @@ export class PortableRegistry extends Struct implements ILookup {
throw new Error('Invalid fields type detected, expected either Tuple (all unnamed) or Struct (all named)');
}
if (fields.length === 0) {
if (count === 0) {
return {
info: TypeDefInfo.Null,
type: 'Null'
};
} else if (isTuple && fields.length === 1) {
} else if (isTuple && count === 1) {
const typeDef = this.#createSiDef(fields[0].type);
return objectSpread(
@@ -892,9 +894,10 @@ export class PortableRegistry extends Struct implements ILookup {
/** @internal Apply field aliassed (with no JS conflicts) */
#extractFieldsAlias (fields: SiField[]): [TypeDef[], Map<string, string>] {
const alias = new Map<string, string>();
const sub = new Array<TypeDef>(fields.length);
const count = fields.length;
const sub = new Array<TypeDef>(count);
for (let i = 0; i < fields.length; i++) {
for (let i = 0; i < count; i++) {
const { docs, name, type, typeName } = fields[i];
const typeDef = this.#createSiDef(type);
@@ -13,7 +13,7 @@ import { objectNameToCamel } from '../util.js';
export function decorateConstants (registry: Registry, { pallets }: MetadataLatest, _version: number): Constants {
const result: Constants = {};
for (let i = 0; i < pallets.length; i++) {
for (let i = 0, count = pallets.length; i < count; i++) {
const { constants, name } = pallets[i];
if (!constants.isEmpty) {
@@ -31,7 +31,7 @@ export function variantToMeta (lookup: PortableRegistry, variant: SiVariant): It
export function decorateErrors (registry: Registry, { lookup, pallets }: MetadataLatest, version: number): Errors {
const result: Errors = {};
for (let i = 0; i < pallets.length; i++) {
for (let i = 0, count = pallets.length; i < count; i++) {
const { errors, index, name } = pallets[i];
if (errors.isSome) {
@@ -21,7 +21,7 @@ export function decorateEvents (registry: Registry, { lookup, pallets }: Metadat
const result: Events = {};
const filtered = pallets.filter(filterEventsSome);
for (let i = 0; i < filtered.length; i++) {
for (let i = 0, count = filtered.length; i < count; i++) {
const { events, index, name } = filtered[i];
const sectionIndex = version >= 12 ? index.toNumber() : i;
@@ -20,14 +20,15 @@ export function filterCallsSome ({ calls }: PalletMetadataLatest): boolean {
export function createCallFunction (registry: Registry, lookup: PortableRegistry, variant: SiVariant, sectionName: string, sectionIndex: number): CallFunction {
const { fields, index } = variant;
const args = new Array<Record<string, unknown>>(fields.length);
const count = fields.length;
const args = new Array<Record<string, unknown>>(count);
for (let a = 0; a < fields.length; a++) {
const { name, type, typeName } = fields[a];
for (let i = 0; i < count; i++) {
const { name, type, typeName } = fields[i];
args[a] = objectSpread(
args[i] = objectSpread(
{
name: stringCamelCase(name.unwrapOr(`param${a}`)),
name: stringCamelCase(name.unwrapOr(`param${i}`)),
type: getSiName(lookup, type)
},
typeName.isSome
@@ -49,7 +50,7 @@ export function decorateExtrinsics (registry: Registry, { lookup, pallets }: Met
const result: Extrinsics = {};
const filtered = pallets.filter(filterCallsSome);
for (let i = 0; i < filtered.length; i++) {
for (let i = 0, count = filtered.length; i < count; i++) {
const { calls, index, name } = filtered[i];
const sectionName = stringCamelCase(name);
const sectionIndex = version >= 12 ? index.toNumber() : i;
@@ -62,9 +62,10 @@ function assertArgs ({ method, section }: CreateItemFn, { args, keys }: RawArgs)
/** @internal */
export function createKeyRawParts (registry: Registry, itemFn: CreateItemBase, { args, hashers, keys }: RawArgs): [Uint8Array[], Uint8Array[]] {
const extra = new Array<Uint8Array>(keys.length);
const count = keys.length;
const extra = new Array<Uint8Array>(count);
for (let i = 0; i < keys.length; i++) {
for (let i = 0; i < count; i++) {
extra[i] = getHasher(hashers[i])(
registry.createTypeUnsafe(registry.createLookupType(keys[i]), [args[i]]).toU8a()
);
@@ -12,7 +12,7 @@ export function getStorage (registry: Registry): Storage {
const storage: Record<string, StorageEntry> = {};
const entries = Object.entries(substrate);
for (let e = 0; e < entries.length; e++) {
for (let e = 0, count = entries.length; e < count; e++) {
storage[entries[e][0]] = entries[e][1](registry);
}
@@ -20,7 +20,7 @@ const VERSION_DOCS = { docs: 'Returns the current pallet version from storage',
export function decorateStorage (registry: Registry, { pallets }: MetadataLatest, _metaVersion: number): Storage {
const result: Storage = getStorage(registry);
for (let i = 0; i < pallets.length; i++) {
for (let i = 0, count = pallets.length; i < count; i++) {
const { name, storage } = pallets[i];
if (storage.isSome) {
@@ -5,7 +5,7 @@ type Types = string | Types[];
/** @internal */
export function flattenUniq (list: Types[], result: string[] = []): string[] {
for (let i = 0; i < list.length; i++) {
for (let i = 0, count = list.length; i < count; i++) {
const entry = list[i];
if (Array.isArray(entry)) {
+1 -1
View File
@@ -54,7 +54,7 @@ function compatType (specs: TypeSpec[], _type: Text | string): number {
}
function compatTypes (specs: TypeSpec[], ...types: (Text | string)[]): void {
for (let i = 0; i < types.length; i++) {
for (let i = 0, count = types.length; i < count; i++) {
compatType(specs, types[i]);
}
}
+3 -2
View File
@@ -85,9 +85,10 @@ function decodeStorageKey (value?: string | Uint8Array | StorageKey | StorageEnt
function decodeHashers <A extends AnyTuple> (registry: Registry, value: Uint8Array, hashers: [StorageHasher, SiLookupTypeId][]): A {
// the storage entry is xxhashAsU8a(prefix, 128) + xxhashAsU8a(method, 128), 256 bits total
let offset = 32;
const result = new Array<Codec>(hashers.length);
const count = hashers.length;
const result = new Array<Codec>(count);
for (let i = 0; i < hashers.length; i++) {
for (let i = 0; i < count; i++) {
const [hasher, type] = hashers[i];
const [hashLen, canDecode] = HASHER_MAP[hasher.type as 'Identity'];
const decoded = canDecode