All files / src/transactions/common utils.ts

95% Statements 19/20
50% Branches 2/4
100% Functions 5/5
93.75% Lines 15/16

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 48 49 50 51 52 5312x 12x 12x   12x 62x   12x 107x   12x 77x   12x 173x 173x                                                       12x     1x 1x          
import { bytesToHex, utf8ToBytes } from 'micro-stacks/common';
import { hashSha512_256 } from 'micro-stacks/crypto-sha';
import { ClarityValue, hexToCV } from 'micro-stacks/clarity';
 
export const leftPadHex = (hexString: string): string =>
  hexString.length % 2 == 0 ? hexString : `0${hexString}`;
 
export const leftPadHexToLength = (hexString: string, length: number): string =>
  hexString.padStart(length, '0');
 
export const rightPadHexToLength = (hexString: string, length: number): string =>
  hexString.padEnd(length, '0');
 
export const txidFromData = (data: Uint8Array): string => {
  const hash = hashSha512_256(data);
  return bytesToHex(hash);
};
 
/**
 * Read only function response object
 *
 * @param {Boolean} okay - the status of the response
 * @param {string} result - serialized hex clarity value
 */
 
export interface ReadOnlyFunctionSuccessResponse {
  okay: true;
  result: string;
}
 
export interface ReadOnlyFunctionErrorResponse {
  okay: false;
  cause: string;
}
 
export type ReadOnlyFunctionResponse =
  | ReadOnlyFunctionSuccessResponse
  | ReadOnlyFunctionErrorResponse;
 
/**
 * Converts the response of a read-only function call into its Clarity Value
 * @param response - {@link ReadOnlyFunctionResponse}
 */
export function parseReadOnlyResponse<T extends ClarityValue>(
  response: ReadOnlyFunctionResponse
): T {
  if (response.okay) {
    return hexToCV(response.result);
  } else E{
    throw new Error(response.cause);
  }
}