Skip to content

Commit

Permalink
feat(transactions): export cvToHex, hexToCV, parseReadOnlyResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
friedger committed Oct 8, 2020
1 parent 01f6e4e commit 1c0f0e3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
2 changes: 2 additions & 0 deletions packages/transactions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ export * from './types';
export * from './constants';
export * from './contract-abi';
export * from './signer';

export { cvToHex, parseReadOnlyResponse, hexToCV } from './utils';
26 changes: 21 additions & 5 deletions packages/transactions/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand All @@ -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 => {
Expand Down

0 comments on commit 1c0f0e3

Please sign in to comment.