Skip to content

Commit

Permalink
feat(core): add AssetName.toUTF8 util
Browse files Browse the repository at this point in the history
  • Loading branch information
mkazlauskas committed Sep 14, 2023
1 parent 9fc4722 commit 5f13b4f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
10 changes: 10 additions & 0 deletions packages/core/src/Cardano/types/Asset.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as Crypto from '@cardano-sdk/crypto';
import { AssetNameLabel } from '../../Asset';
import { HexBlob, InvalidStringError, OpaqueString, assertIsHexString, typedBech32 } from '@cardano-sdk/util';
import { TextDecoder } from 'web-encoding';

export type AssetId = OpaqueString<'AssetId'>;

Expand All @@ -18,6 +19,15 @@ export const AssetName = (value: string): AssetName => {
return value.toLowerCase() as unknown as AssetName;
};

const utf8Decoder = new TextDecoder('utf8', { fatal: true });
AssetName.toUTF8 = (assetName: AssetName) => {
try {
return utf8Decoder.decode(Buffer.from(assetName, 'hex'));
} catch (error) {
throw new InvalidStringError('Cannot convert AssetName to UTF8', error);
}
};

/**
* @param {string} value concatenated PolicyId and AssetName
* @throws InvalidStringError
Expand Down
11 changes: 10 additions & 1 deletion packages/core/test/Cardano/types/Asset.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AssetFingerprint, AssetId, AssetName, PolicyId } from '../../../src/Cardano';
import { Hash28ByteBase16 } from '@cardano-sdk/crypto';
import { assertIsHexString, typedBech32 } from '@cardano-sdk/util';
import { InvalidStringError, assertIsHexString, typedBech32 } from '@cardano-sdk/util';

jest.mock('@cardano-sdk/util', () => {
const actual = jest.requireActual('@cardano-sdk/util');
Expand Down Expand Up @@ -103,6 +103,15 @@ describe('Cardano/types/Asset', () => {
it('does not accept a hex string > 64 chars', () => {
expect(() => AssetName('0dbe461fb5f981c0d01615332b8666340eb1a692b3034f46bcb5f5e0dbe461abc')).toThrow();
});

describe('fromUTF8', () => {
it('decodes hex string (bytes) to utf8 string', () => {
expect(AssetName.toUTF8(AssetName('737472'))).toEqual('str');
});
it('throws InvalidStringError when it cannot be decoded to utf8', () => {
expect(() => AssetName.toUTF8(AssetName('e8'))).toThrowError(InvalidStringError);
});
});
});

describe('AssetFingerprint', () => {
Expand Down

0 comments on commit 5f13b4f

Please sign in to comment.