diff --git a/packages/types/src/primitive/Text.spec.ts b/packages/types/src/primitive/Text.spec.ts index 14b0e5512d..e0f4b2cef6 100644 --- a/packages/types/src/primitive/Text.spec.ts +++ b/packages/types/src/primitive/Text.spec.ts @@ -8,9 +8,9 @@ import Text from './Text'; describe('Text', () => { describe('decode', () => { - const testDecode = (type: string, input: string | Uint8Array | { toString: () => string }, expected: string) => + const testDecode = (type: string, input: string | Uint8Array | { toString: () => string }, expected: string, toFn: 'toString' | 'toHex' = 'toString') => it(`can decode from ${type}`, () => { - expect(new Text(input).toString()).toBe(expected); + expect(new Text(input)[toFn]()).toBe(expected); }); testDecode('string', 'foo', 'foo'); @@ -18,6 +18,7 @@ describe('Text', () => { testDecode('Uint8Array', Uint8Array.from([12, 102, 111, 111]), 'foo'); testDecode('U8a', new U8a(Uint8Array.from([12, 102, 111, 111])), 'foo'); testDecode('object with `toString()`', { toString (): string { return 'foo'; } }, 'foo'); + testDecode('hex input value', new Text('0x12345678'), '0x12345678', 'toHex'); }); describe('encode', () => { @@ -26,7 +27,7 @@ describe('Text', () => { expect(new Text('foo')[to]()).toEqual(expected); }); - testEncode('toHex', '0x0c666f6f'); + testEncode('toHex', '0x666f6f'); testEncode('toString', 'foo'); testEncode('toU8a', Uint8Array.from([12, 102, 111, 111])); }); diff --git a/packages/types/src/primitive/Text.ts b/packages/types/src/primitive/Text.ts index 87bff8f122..e0295f2246 100644 --- a/packages/types/src/primitive/Text.ts +++ b/packages/types/src/primitive/Text.ts @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { assert, isString, stringToU8a, u8aToString, u8aToHex } from '@polkadot/util'; +import { assert, hexToU8a, isHex, isString, stringToU8a, u8aToString, u8aToHex } from '@polkadot/util'; import { AnyU8a, Codec } from '../types'; import Compact from '../codec/Compact'; @@ -28,8 +28,8 @@ export default class Text extends String implements Codec { } private static decodeText (value: Text | string | AnyU8a | { toString: () => string }): string { - if (isString(value)) { - return value.toString(); + if (isHex(value)) { + return u8aToString(hexToU8a(value.toString())); } else if (value instanceof Uint8Array) { if (!value.length) { return ''; @@ -81,7 +81,9 @@ export default class Text extends String implements Codec { * @description Returns a hex string representation of the value */ toHex (): string { - return u8aToHex(this.toU8a()); + // like with Vec, when we are encoding to hex, we don't actually add + // the length prefix (it is already implied by the actual string length) + return u8aToHex(this.toU8a(true)); } /**