diff --git a/CHANGELOG.md b/CHANGELOG.md index 705c8b4c10cd..276d55a8605c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Contributed: Changes: - Extract metadata v14 `BTreeSet` types into correct type +- Assert to ensure that `[u8; ]` has exact sizes (non-u8a inputs) - Adjust `tx.paymentInfo` signing process - Add Kusama 9190 upgrade block - Add Westend 9200 upgrade block diff --git a/packages/types-codec/src/extended/U8aFixed.spec.ts b/packages/types-codec/src/extended/U8aFixed.spec.ts index 0aaa662b9608..b448af13ff11 100644 --- a/packages/types-codec/src/extended/U8aFixed.spec.ts +++ b/packages/types-codec/src/extended/U8aFixed.spec.ts @@ -35,13 +35,43 @@ describe('U8aFixed', (): void => { new Uint8Array([0x02, 0x03, 0x00, 0x00]) ); }); + + it('constructs when passed Uint8Array is >= length', (): void => { + expect( + new (U8aFixed.with(32))(registry, new Uint8Array([0x00, 0x01, 0x02, 0x03])).toU8a() + ).toEqual( + new Uint8Array([0x00, 0x01, 0x02, 0x03]) + ); + expect( + new (U8aFixed.with(32))(registry, new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05])).toU8a() + ).toEqual( + new Uint8Array([0x00, 0x01, 0x02, 0x03]) + ); + }); + + it('constructs when passed string is === length', (): void => { + expect( + new (U8aFixed.with(32))(registry, '1234').toU8a() + ).toEqual( + new Uint8Array([49, 50, 51, 52]) + ); + }); + + it('fails construction when passed string is > length', (): void => { + expect( + () => new (U8aFixed.with(32))(registry, '0x000102030405').toU8a() + ).toThrow(/Expected input with 4 bytes/); + expect( + () => new (U8aFixed.with(256))(registry, '1363HWTPzDrzAQ6ChFiMU6mP4b6jmQid2ae55JQcKtZnpLGv') + ).toThrow(/Expected input with 32 bytes/); + }); }); describe('utils', (): void => { let u8a: U8aFixed; beforeEach((): void => { - u8a = new U8aFixed(registry, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 32); + u8a = new U8aFixed(registry, [1, 2, 3, 4], 32); }); it('limits the length', (): void => { diff --git a/packages/types-codec/src/extended/U8aFixed.ts b/packages/types-codec/src/extended/U8aFixed.ts index c592169e7caa..5248b004b27f 100644 --- a/packages/types-codec/src/extended/U8aFixed.ts +++ b/packages/types-codec/src/extended/U8aFixed.ts @@ -3,7 +3,7 @@ import type { AnyU8a, CodecClass, Registry, U8aBitLength } from '../types'; -import { assert, u8aToU8a } from '@polkadot/util'; +import { assert, isU8a, u8aToU8a } from '@polkadot/util'; import { Raw } from '../native/Raw'; @@ -16,7 +16,7 @@ function decodeU8aFixed (value: AnyU8a, bitLength: U8aBitLength): [AnyU8a, numbe return [new Uint8Array(byteLength), 0]; } - assert(u8a.length >= byteLength, () => `Expected at least ${byteLength} bytes (${bitLength} bits), found ${u8a.length} bytes`); + assert(isU8a(value) ? u8a.length >= byteLength : u8a.length === byteLength, () => `Expected input with ${byteLength} bytes (${bitLength} bits), found ${u8a.length} bytes`); return [u8a.subarray(0, byteLength), byteLength]; }