41 lines
1.5 KiB
TypeScript
41 lines
1.5 KiB
TypeScript
import { bigIntToVmNumber, utf8ToBin } from '@bitauth/libauth';
|
|
import { CashAssemblyNumberNotSafeIntegerError, CashAssemblyUnsupportedValueTypeError } from './errors.ts';
|
|
|
|
/**
|
|
* Converts a value into bytes representation.
|
|
*
|
|
* @param {unknown} value - Value to encode, should be one of: Uint8Array, bigint, boolean, string, or a safe integer number.
|
|
* @param {string} valueIdentifier - Identifier used in error messages.
|
|
* @returns {Uint8Array} Bytes representation of the value.
|
|
* @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number is not a safe integer.
|
|
* @throws {@link CashAssemblyUnsupportedValueTypeError} When the value type cannot be resolved.
|
|
*/
|
|
export const convertValueToBytes = (value: unknown, valueIdentifier: string): Uint8Array => {
|
|
if (value instanceof Uint8Array) {
|
|
return value;
|
|
}
|
|
|
|
if (typeof value === 'bigint') {
|
|
return bigIntToVmNumber(value);
|
|
}
|
|
|
|
if (typeof value === 'boolean') {
|
|
// The BCH VM treats an empty byte array as false and any nonempty byte array as true.
|
|
return new Uint8Array(value ? [ 1 ] : []);
|
|
}
|
|
|
|
if (typeof value === 'string') {
|
|
return utf8ToBin(value);
|
|
}
|
|
|
|
if (typeof value === 'number') {
|
|
if (Number.isSafeInteger(value) === true) {
|
|
return bigIntToVmNumber(BigInt(value));
|
|
}
|
|
|
|
throw new CashAssemblyNumberNotSafeIntegerError(valueIdentifier, value);
|
|
}
|
|
|
|
throw new CashAssemblyUnsupportedValueTypeError(valueIdentifier, typeof value);
|
|
};
|