From 1c0f0e3f31f0849f02762c7422d1f7c22aebe22b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Friedger=20M=C3=BCffke?= Date: Thu, 8 Oct 2020 23:26:40 +0200 Subject: [PATCH] feat(transactions): export cvToHex, hexToCV, parseReadOnlyResponse --- packages/transactions/src/index.ts | 2 ++ packages/transactions/src/utils.ts | 26 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/transactions/src/index.ts b/packages/transactions/src/index.ts index ea7adb94c..69f71b32b 100644 --- a/packages/transactions/src/index.ts +++ b/packages/transactions/src/index.ts @@ -29,3 +29,5 @@ export * from './types'; export * from './constants'; export * from './contract-abi'; export * from './signer'; + +export { cvToHex, parseReadOnlyResponse, hexToCV } from './utils'; diff --git a/packages/transactions/src/utils.ts b/packages/transactions/src/utils.ts index dea8454cf..1248164d5 100644 --- a/packages/transactions/src/utils.ts +++ b/packages/transactions/src/utils.ts @@ -160,12 +160,24 @@ export async function fetchPrivate(input: RequestInfo, init?: RequestInit): Prom const fetchResult = await fetch(input, fetchOpts); return fetchResult; } - +/** + * 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) { const serialized = serializeCV(cv); return `0x${serialized.toString('hex')}`; } +/** + * Converts a hex encoded string to a clarity value + * @param {string} hex - the hex encoded string with or without `0x` prefix + */ +export function hexToCV(hex: string) { + const hexWithoutPrefix = hex.startsWith('0x') ? hex.slice(2) : hex; + const bufferCV = Buffer.from(hexWithoutPrefix, 'hex'); + return deserializeCV(bufferCV); +} /** * Read only function response object * @@ -178,10 +190,14 @@ export interface ReadOnlyFunctionResponse { result: string; } -export const parseReadOnlyResponse = ({ result }: ReadOnlyFunctionResponse): ClarityValue => { - const hex = result.slice(2); - const bufferCV = Buffer.from(hex, 'hex'); - return deserializeCV(bufferCV); +/** + * Converts the response of a read-only function call into its Clarity Value + * @param param + */ +export const parseReadOnlyResponse = ({ + result +}: ReadOnlyFunctionResponse): ClarityValue => { + return hexToCV(result); }; export const validateStacksAddress = (stacksAddress: string): boolean => {