Handle Text is same way as Bytes (isPedantic mode) (#3521)

* Handle Text is same was as Bytes (isPedantic mode)

* Length on input

* tests

* raw decoding test
This commit is contained in:
Jaco
2021-05-13 07:10:44 +02:00
committed by GitHub
parent cd5c306b22
commit 2611fc5e1a
2 changed files with 30 additions and 2 deletions
@@ -122,6 +122,26 @@ describe('createType', (): void => {
).toEqual(new Uint8Array([0x00, 0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67]));
});
describe('isPedantic', (): void => {
it('correctly decodes Bytes', (): void => {
expect(
createTypeUnsafe(registry, 'Bytes', ['0x12345678'], { isPedantic: true })
).toBeDefined();
});
it('correctly decodes Bytes (prefixed)', (): void => {
expect(
createTypeUnsafe(registry, 'Bytes', [new Uint8Array([4 << 2, 1, 2, 3, 4])], { isPedantic: true })
).toBeDefined();
});
it('correctly decodes Text', (): void => {
expect(
createTypeUnsafe(registry, 'Text', ['0x2070726f7669646572'], { isPedantic: true })
).toBeDefined();
});
});
describe('instanceof', (): void => {
it('instanceof should work (primitive type)', (): void => {
const value = registry.createType('Balance', 1234);
+10 -2
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Bytes } from '../primitive/Bytes';
import type { Codec, Constructor, InterfaceTypes, Registry } from '../types';
import type { FromReg } from './types';
@@ -19,8 +20,15 @@ interface CreateOptions {
function checkInstance<T extends Codec = Codec, K extends string = string> (value: Uint8Array, created: FromReg<T, K>): void {
const u8a = created.toU8a();
const rawType = created.toRawType();
const isEqual = rawType === 'Bytes'
? value.length === u8a.length
// for length-prefixed byte types, just check the length, else the full encoding
const isEqual = ['Bytes', 'Text'].includes(rawType)
? [
// input was via hex, we don't have a prefix
(created as Bytes).length,
// input was raw bytes, we do have a prefix
u8a.length
].includes(value.length)
: u8aEq(value, u8a);
assert(isEqual, () => `${rawType}:: Decoded input doesn't match input, received ${u8aToHex(value, 512)} (${value.length} bytes), created ${u8aToHex(u8a, 512)} (${u8a.length} bytes)`);