All files / src/clarity/clarity-value hex.ts

84.61% Statements 11/13
0% Branches 0/2
50% Functions 2/4
84.61% Lines 11/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4121x 21x 21x 21x 21x             21x 6x             21x 2x               21x                 21x      
import { bytesToHex } from 'micro-stacks/common';
import { serializeCV } from '../serialize';
import { deserializeCV } from '../deserialize';
import { cvToValue } from './cv-to-value';
import { cvToTrueValue } from './cv-to-true-value';
import type { ClarityValue } from './types';
 
/**
 * Converts a clarity value to a hex encoded string with `0x` prefix
 * @param {ClarityValue} cv  - the clarity value to convert
 */
export function cvToHex(cv: ClarityValue) {
  return `0x${bytesToHex(serializeCV(cv))}`;
}
 
/**
 * Converts a hex encoded string to a clarity value
 * @param {string} hex - the hex encoded string with or without `0x` prefix
 */
export function hexToCV<T extends ClarityValue>(hex: string) {
  return deserializeCV(hex) as T;
}
 
/**
 * Converts a hex encoded string to the javascript clarity value object {type: string; value: any}
 * @param {string} hex - the hex encoded string with or without `0x` prefix
 * @param {boolean} jsonCompat - enable to serialize bigints to strings
 */
export function hexToCvValue<T>(hex: string, jsonCompat = true) {
  return cvToValue(hexToCV(hex), jsonCompat) as T;
}
 
/**
 * Converts a hex encoded string to the pure javascript value
 * @param {string} hex - the hex encoded string with or without `0x` prefix
 * @param {boolean} jsonCompat - enable to serialize bigints to strings
 */
export function hexToValue<T>(hex: string, jsonCompat = true) {
  return cvToTrueValue(hexToCV(hex), jsonCompat) as T;
}