|
| 1 | +import { type BytesLike, bytesToHex, hexToBytes } from '@metamask/utils'; |
| 2 | + |
| 3 | +import type { Hex } from './types'; |
| 4 | + |
| 5 | +/** |
| 6 | + * The possible return value types for encoding/decoding operations. |
| 7 | + */ |
| 8 | +export type ResultValue = 'hex' | 'bytes'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Utility type for function return types based on ResultValue. |
| 12 | + */ |
| 13 | +export type ResultType<TResultValue extends ResultValue> = |
| 14 | + TResultValue extends 'hex' ? Hex : Uint8Array; |
| 15 | + |
| 16 | +/** |
| 17 | + * Base options interface for operations that can return hex or bytes. |
| 18 | + */ |
| 19 | +export type EncodingOptions<TResultValue extends ResultValue> = { |
| 20 | + out: TResultValue; |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * Default options value with proper typing. Use this as your default parameter. |
| 25 | + */ |
| 26 | +export const defaultOptions = { out: 'hex' } as EncodingOptions<any>; |
| 27 | + |
| 28 | +/** |
| 29 | + * Prepares a result by converting between hex and bytes based on options. |
| 30 | + * @param result - The value to convert (either Uint8Array or Hex optionally prefixed with 0x). |
| 31 | + * @param options - The options specifying the desired output format. |
| 32 | + * @returns The converted value with proper type narrowing. |
| 33 | + */ |
| 34 | +export function prepareResult<TResultValue extends ResultValue>( |
| 35 | + result: Uint8Array | Hex | string, |
| 36 | + options: EncodingOptions<TResultValue>, |
| 37 | +): ResultType<TResultValue> { |
| 38 | + if (options.out === 'hex') { |
| 39 | + const hexValue = typeof result === 'string' ? result : bytesToHex(result); |
| 40 | + |
| 41 | + return hexValue.startsWith('0x') |
| 42 | + ? (hexValue as ResultType<TResultValue>) |
| 43 | + : (`0x${hexValue}` as ResultType<TResultValue>); |
| 44 | + } |
| 45 | + const bytesValue = result instanceof Uint8Array ? result : hexToBytes(result); |
| 46 | + return bytesValue as ResultType<TResultValue>; |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Converts a bytes-like value to a hex string. |
| 51 | + * @param bytesLike - The bytes-like value to convert. |
| 52 | + * @returns The hex string representation of the bytes-like value. |
| 53 | + */ |
| 54 | +export const bytesLikeToHex = (bytesLike: BytesLike) => { |
| 55 | + if (typeof bytesLike === 'string') { |
| 56 | + return bytesLike; |
| 57 | + } |
| 58 | + return bytesToHex(bytesLike); |
| 59 | +}; |
| 60 | + |
| 61 | +/** |
| 62 | + * Converts a bytes-like value to a Uint8Array. |
| 63 | + * @param bytesLike - The bytes-like value to convert. |
| 64 | + * @returns The Uint8Array representation of the bytes-like value. |
| 65 | + */ |
| 66 | +export const bytesLikeToBytes = (bytesLike: BytesLike) => { |
| 67 | + if (typeof bytesLike === 'string') { |
| 68 | + return hexToBytes(bytesLike); |
| 69 | + } |
| 70 | + return bytesLike; |
| 71 | +}; |
0 commit comments