All files / src/clarity/clarity-value cv-to-true-value.ts

14.28% Statements 3/21
0% Branches 0/16
0% Functions 0/3
15% Lines 3/20

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 41 42 43 44 45 46 47 4821x 21x                 21x                                                                          
import { ClarityType } from '../common/constants';
import { principalToString } from '../types/principalCV';
import { ClarityValue } from './types';
 
/**
 * @param val - ClarityValue
 * @param strictJsonCompat If true then ints and uints are returned as JSON serializable numbers when
 * less than or equal to 53 bit length, otherwise string wrapped integers when larger than 53 bits.
 * If false, they are returned as js native `bigint`s which are _not_ JSON serializable.
 */
export function cvToTrueValue<T = unknown>(val: ClarityValue, strictJsonCompat = false): T {
  switch (val.type) {
    case ClarityType.BoolTrue:
      return true as unknown as T;
    case ClarityType.BoolFalse:
      return false as unknown as T;
    case ClarityType.Int:
    case ClarityType.UInt:
      Iif (strictJsonCompat) return val.value.toString() as unknown as T;
      return val.value as unknown as T;
    case ClarityType.Buffer:
      return val.buffer as unknown as T;
    case ClarityType.OptionalNone:
      return null as unknown as T;
    case ClarityType.OptionalSome:
      return cvToTrueValue(val.value, strictJsonCompat);
    case ClarityType.ResponseErr:
      return cvToTrueValue(val.value, strictJsonCompat);
    case ClarityType.ResponseOk:
      return cvToTrueValue(val.value, strictJsonCompat);
    case ClarityType.PrincipalStandard:
    case ClarityType.PrincipalContract:
      return principalToString(val) as unknown as T;
    case ClarityType.List:
      return val.list.map(v => cvToTrueValue<T>(v, strictJsonCompat)) as unknown as T;
    case ClarityType.Tuple:
      const result: { [key: string]: any } = {};
      Object.keys(val.data).forEach(key => {
        result[key] = cvToTrueValue<T>(val.data[key], strictJsonCompat);
      });
      return result as T;
    case ClarityType.StringASCII:
      return val.data as unknown as T;
    case ClarityType.StringUTF8:
      return val.data as unknown as T;
  }
}