Adjust type asserts (#4952)
This commit is contained in:
@@ -9,7 +9,7 @@ import type { CallFunction, CodecHasher, Definitions, DetectCodec, RegisteredTyp
|
||||
|
||||
import { DoNotConstruct, Json, Raw } from '@polkadot/types-codec';
|
||||
import { constructTypeClass, createClassUnsafe, createTypeUnsafe } from '@polkadot/types-create';
|
||||
import { assert, assertReturn, BN_ZERO, formatBalance, isFunction, isNumber, isString, isU8a, lazyMethod, logger, objectSpread, stringCamelCase, stringify } from '@polkadot/util';
|
||||
import { assertReturn, BN_ZERO, formatBalance, isFunction, isNumber, isString, isU8a, lazyMethod, logger, objectSpread, stringCamelCase, stringify } from '@polkadot/util';
|
||||
import { blake2AsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { expandExtensionTypes, fallbackExtensions, findUnknownExtensions } from '../extrinsic/signedExtensions';
|
||||
@@ -410,7 +410,9 @@ export class TypeRegistry implements Registry {
|
||||
public getOrThrow <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (name: K, msg?: string): CodecClass<R> {
|
||||
const Clazz = this.get<T, K>(name);
|
||||
|
||||
assert(Clazz, msg || `type ${name} not found`);
|
||||
if (!Clazz) {
|
||||
throw new Error(msg || `type ${name} not found`);
|
||||
}
|
||||
|
||||
return Clazz as unknown as CodecClass<R>;
|
||||
}
|
||||
@@ -454,8 +456,11 @@ export class TypeRegistry implements Registry {
|
||||
if (isFunction(arg1)) {
|
||||
this.#classes.set(arg1.name, arg1);
|
||||
} else if (isString(arg1)) {
|
||||
assert(isFunction(arg2), () => `Expected class definition passed to '${arg1}' registration`);
|
||||
assert(arg1 !== arg2.toString(), () => `Unable to register circular ${arg1} === ${arg1}`);
|
||||
if (!isFunction(arg2)) {
|
||||
throw new Error(`Expected class definition passed to '${arg1}' registration`);
|
||||
} else if (arg1 === arg2.toString()) {
|
||||
throw new Error(`Unable to register circular ${arg1} === ${arg1}`);
|
||||
}
|
||||
|
||||
this.#classes.set(arg1, arg2);
|
||||
} else {
|
||||
@@ -477,7 +482,9 @@ export class TypeRegistry implements Registry {
|
||||
? type
|
||||
: stringify(type);
|
||||
|
||||
assert(name !== def, () => `Unable to register circular ${name} === ${def}`);
|
||||
if (name === def) {
|
||||
throw new Error(`Unable to register circular ${name} === ${def}`);
|
||||
}
|
||||
|
||||
// we already have this type, remove the classes registered for it
|
||||
if (this.#classes.has(name)) {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
import type { AnyNumber, Registry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { U32 } from '@polkadot/types-codec';
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding
|
||||
|
||||
@@ -12,8 +11,8 @@ export class MagicNumber extends U32 {
|
||||
constructor (registry: Registry, value?: AnyNumber) {
|
||||
super(registry, value);
|
||||
|
||||
if (!this.isEmpty) {
|
||||
assert(this.eq(MAGIC_NUMBER), () => `MagicNumber mismatch: expected ${registry.createTypeUnsafe('u32', [MAGIC_NUMBER]).toHex()}, found ${this.toHex()}`);
|
||||
if (!this.isEmpty && !this.eq(MAGIC_NUMBER)) {
|
||||
throw new Error(`MagicNumber mismatch: expected ${registry.createTypeUnsafe('u32', [MAGIC_NUMBER]).toHex()}, found ${this.toHex()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11,
|
||||
import type { Registry } from '../types';
|
||||
|
||||
import { Struct } from '@polkadot/types-codec';
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { toV10 } from './v9/toV10';
|
||||
import { toV11 } from './v10/toV11';
|
||||
@@ -44,7 +43,9 @@ export class MetadataVersioned extends Struct {
|
||||
}
|
||||
|
||||
#assertVersion = (version: number): boolean => {
|
||||
assert(this.version <= version, () => `Cannot convert metadata from version ${this.version} to ${version}`);
|
||||
if (this.version > version) {
|
||||
throw new Error(`Cannot convert metadata from version ${this.version} to ${version}`);
|
||||
}
|
||||
|
||||
return this.version === version;
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDefArray, SiTypeDef
|
||||
|
||||
import { sanitize, Struct, u32 } from '@polkadot/types-codec';
|
||||
import { getTypeDef, TypeDefInfo, withTypeString } from '@polkadot/types-create';
|
||||
import { assert, assertUnreachable, isNumber, isString, logger, objectSpread, stringCamelCase, stringify, stringPascalCase } from '@polkadot/util';
|
||||
import { assertUnreachable, isNumber, isString, logger, objectSpread, stringCamelCase, stringify, stringPascalCase } from '@polkadot/util';
|
||||
|
||||
const l = logger('PortableRegistry');
|
||||
|
||||
@@ -540,7 +540,9 @@ export class PortableRegistry extends Struct implements ILookup {
|
||||
// ensure that we have actually initialized it correctly
|
||||
const found = (this.#types || this.types)[this.#getLookupId(lookupId)];
|
||||
|
||||
assert(found, () => `PortableRegistry: Unable to find type with lookupId ${lookupId.toString()}`);
|
||||
if (!found) {
|
||||
throw new Error(`PortableRegistry: Unable to find type with lookupId ${lookupId.toString()}`);
|
||||
}
|
||||
|
||||
return found.type;
|
||||
}
|
||||
@@ -626,7 +628,9 @@ export class PortableRegistry extends Struct implements ILookup {
|
||||
|
||||
#getLookupId (lookupId: SiLookupTypeId | string | number): number {
|
||||
if (isString(lookupId)) {
|
||||
assert(this.registry.isLookupType(lookupId), () => `PortableRegistry: Expected a lookup string type, found ${lookupId}`);
|
||||
if (!this.registry.isLookupType(lookupId)) {
|
||||
throw new Error(`PortableRegistry: Expected a lookup string type, found ${lookupId}`);
|
||||
}
|
||||
|
||||
return parseInt(lookupId.replace('Lookup', ''), 10);
|
||||
} else if (isNumber(lookupId)) {
|
||||
@@ -665,12 +669,16 @@ export class PortableRegistry extends Struct implements ILookup {
|
||||
return objectSpread({ docs: sanitizeDocs(type.docs), namespace }, typeDef);
|
||||
}
|
||||
|
||||
#extractArray (_: number, { len: length, type }: SiTypeDefArray): TypeDef {
|
||||
assert(!length || length.toNumber() <= 256, 'Only support for [Type; <length>], where length <= 256');
|
||||
#extractArray (_: number, { len, type }: SiTypeDefArray): TypeDef {
|
||||
const length = len.toNumber();
|
||||
|
||||
if (length > 2048) {
|
||||
throw new Error('Only support for [Type; <length>], where length <= 2048');
|
||||
}
|
||||
|
||||
return withTypeString(this.registry, {
|
||||
info: TypeDefInfo.VecFixed,
|
||||
length: length.toNumber(),
|
||||
length,
|
||||
sub: this.#createSiDef(type)
|
||||
});
|
||||
}
|
||||
@@ -687,8 +695,11 @@ export class PortableRegistry extends Struct implements ILookup {
|
||||
// NOTE: Currently the BitVec type is one-way only, i.e. we only use it to decode, not
|
||||
// re-encode stuff. As such we ignore the msb/lsb identifier given by bitOrderType, or rather
|
||||
// we don't pass it though at all (all displays in LSB)
|
||||
assert(BITVEC_NS.includes(bitOrder.namespace || ''), () => `Unexpected bitOrder found as ${bitOrder.namespace || '<unknown>'}`);
|
||||
assert(bitStore.info === TypeDefInfo.Plain && bitStore.type === 'u8', () => `Only u8 bitStore is currently supported, found ${bitStore.type}`);
|
||||
if (!BITVEC_NS.includes(bitOrder.namespace || '')) {
|
||||
throw new Error(`Unexpected bitOrder found as ${bitOrder.namespace || '<unknown>'}`);
|
||||
} else if (bitStore.info !== TypeDefInfo.Plain || bitStore.type !== 'u8') {
|
||||
throw new Error(`Only u8 bitStore is currently supported, found ${bitStore.type}`);
|
||||
}
|
||||
|
||||
return {
|
||||
info: TypeDefInfo.Plain,
|
||||
@@ -741,7 +752,9 @@ export class PortableRegistry extends Struct implements ILookup {
|
||||
}
|
||||
|
||||
#extractCompositeSet (_: number, params: SiTypeParameter[], fields: SiField[]): TypeDef {
|
||||
assert(params.length === 1 && fields.length === 1, 'Set handling expects param/field as single entries');
|
||||
if (params.length !== 1 || fields.length !== 1) {
|
||||
throw new Error('Set handling expects param/field as single entries');
|
||||
}
|
||||
|
||||
return withTypeString(this.registry, {
|
||||
info: TypeDefInfo.Set,
|
||||
@@ -767,7 +780,9 @@ export class PortableRegistry extends Struct implements ILookup {
|
||||
isTuple = isTuple && name.isNone;
|
||||
}
|
||||
|
||||
assert(isTuple || isStruct, 'Invalid fields type detected, expected either Tuple (all unnamed) or Struct (all named)');
|
||||
if (!isTuple && !isStruct) {
|
||||
throw new Error('Invalid fields type detected, expected either Tuple (all unnamed) or Struct (all named)');
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
return {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { AnyJson, AnyTuple, Registry } from '@polkadot/types-codec/types';
|
||||
import type { Call, FunctionMetadataLatest } from '../../../interfaces';
|
||||
import type { CallFunction, IMethod } from '../../../types';
|
||||
|
||||
import { assert, stringCamelCase } from '@polkadot/util';
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
function isTx <A extends AnyTuple> (tx: IMethod<AnyTuple>, callIndex: Uint8Array): tx is IMethod<A> {
|
||||
return tx.callIndex[0] === callIndex[0] && tx.callIndex[1] === callIndex[1];
|
||||
@@ -17,7 +17,9 @@ export function createUnchecked (registry: Registry, section: string, callIndex:
|
||||
const funcName = stringCamelCase(callMetadata.name);
|
||||
|
||||
const extrinsicFn = (...args: unknown[]): Call => {
|
||||
assert(expectedArgs.length === args.length, () => `Extrinsic ${section}.${funcName} expects ${expectedArgs.length} arguments, got ${args.length}.`);
|
||||
if (expectedArgs.length !== args.length) {
|
||||
throw new Error(`Extrinsic ${section}.${funcName} expects ${expectedArgs.length} arguments, got ${args.length}.`);
|
||||
}
|
||||
|
||||
return registry.createTypeUnsafe('Call', [{ args, callIndex }, callMetadata]);
|
||||
};
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
import type { Registry } from '@polkadot/types-codec/types';
|
||||
import type { DecoratedMeta } from './types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { Metadata } from '../Metadata';
|
||||
import { decorateConstants } from './constants';
|
||||
import { decorateErrors } from './errors';
|
||||
@@ -17,7 +15,9 @@ import { decorateStorage } from './storage';
|
||||
* Expands the metadata by decoration into consts, query and tx sections
|
||||
*/
|
||||
export function expandMetadata (registry: Registry, metadata: Metadata): DecoratedMeta {
|
||||
assert(metadata instanceof Metadata, 'You need to pass a valid Metadata instance to Decorated');
|
||||
if (!(metadata instanceof Metadata)) {
|
||||
throw new Error('You need to pass a valid Metadata instance to Decorated');
|
||||
}
|
||||
|
||||
const latest = metadata.asLatest;
|
||||
const version = metadata.version;
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { StorageEntry, StorageEntryIterator } from '../../../primitive/type
|
||||
import type { Registry } from '../../../types';
|
||||
|
||||
import { Raw } from '@polkadot/types-codec';
|
||||
import { assert, compactAddLength, compactStripLength, isUndefined, objectSpread, stringCamelCase, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
import { compactAddLength, compactStripLength, isUndefined, objectSpread, stringCamelCase, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
import { xxhashAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { StorageKey } from '../../../primitive';
|
||||
@@ -48,9 +48,11 @@ export const NO_RAW_ARGS: RawArgs = {
|
||||
|
||||
/** @internal */
|
||||
function assertArgs ({ method, section }: CreateItemFn, { args, keys }: RawArgs): void {
|
||||
assert(Array.isArray(args), () => `Call to ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs ${keys.length} arguments`);
|
||||
|
||||
assert(args.filter(filterDefined).length === keys.length, () => `Call to ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs ${keys.length} arguments, found [${args.join(', ')}]`);
|
||||
if (!Array.isArray(args)) {
|
||||
throw new Error(`Call to ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs ${keys.length} arguments`);
|
||||
} else if (args.filter(filterDefined).length !== keys.length) {
|
||||
throw new Error(`Call to ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs ${keys.length} arguments, found [${args.join(', ')}]`);
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -217,13 +219,9 @@ function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn:
|
||||
const { meta: { type }, method, section } = itemFn;
|
||||
|
||||
storageFn.iterKey = extendHeadMeta(registry, itemFn, storageFn, (...args: unknown[]): Raw => {
|
||||
assert(
|
||||
(
|
||||
(args.length === 0) ||
|
||||
(type.isMap && args.length < type.asMap.hashers.length)
|
||||
),
|
||||
() => `Iteration ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs arguments to be at least one less than the full arguments, found [${args.join(', ')}]`
|
||||
);
|
||||
if (args.length && (type.isPlain || (args.length > type.asMap.hashers.length))) {
|
||||
throw new Error(`Iteration ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs arguments to be at least one less than the full arguments, found [${args.join(', ')}]`);
|
||||
}
|
||||
|
||||
if (args.length) {
|
||||
if (type.isMap) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { Check } from './types';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { assert, hexToU8a, stringCamelCase, stringify, u8aToHex } from '@polkadot/util';
|
||||
import { hexToU8a, stringCamelCase, stringify, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { TypeRegistry } from '../../create';
|
||||
import { unwrapStorageSi, unwrapStorageType } from '../../primitive/StorageKey';
|
||||
@@ -107,7 +107,9 @@ export function defaultValues (registry: Registry, { data, fails = [] }: Check,
|
||||
if (withFallbackCheck) {
|
||||
const [hexType, hexOrig] = [u8aToHex(instance.toU8a()), u8aToHex(fallback.toU8a(true))];
|
||||
|
||||
assert(hexType === hexOrig, () => `Fallback does not match (${((hexOrig.length - 2) / 2) - ((hexType.length - 2) / 2)} bytes missing): ${hexType} !== ${hexOrig}`);
|
||||
if (hexType !== hexOrig) {
|
||||
throw new Error(`Fallback does not match (${((hexOrig.length - 2) / 2) - ((hexType.length - 2) / 2)} bytes missing): ${hexType} !== ${hexOrig}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const message = `${location}:: ${(error as Error).message}`;
|
||||
|
||||
Reference in New Issue
Block a user