@ledgerhq/coin-stacks
Version:
Ledger Stacks Coin integration
86 lines • 3.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.processMemoCV = exports.bufferMemoToString = exports.hexMemoToString = exports.memoToBufferCV = void 0;
const logs_1 = require("@ledgerhq/logs");
const transactions_1 = require("@stacks/transactions");
/**
* Converts a memo string to a buffer Clarity Value for sending in transactions
*
* @param memo - The memo to convert
* @returns Clarity Value representing the memo (some(buffer) or none)
*/
const memoToBufferCV = (memo) => {
if (memo === undefined || memo === null || memo === "") {
return (0, transactions_1.noneCV)();
}
return (0, transactions_1.someCV)((0, transactions_1.bufferCV)(Buffer.from(String(memo))));
};
exports.memoToBufferCV = memoToBufferCV;
/**
* Converts a hex string (from memo) to a readable string
*
* @param memoHex - Hex string representation of memo
* @returns Readable string or empty string if conversion fails
*/
const hexMemoToString = (memoHex) => {
if (memoHex?.substring(0, 2) === "0x") {
try {
// eslint-disable-next-line no-control-regex
return Buffer.from(memoHex.substring(2), "hex").toString().replaceAll("\x00", "");
}
catch (e) {
(0, logs_1.log)("error", "Failed to convert hex memo to string", e);
}
}
return "";
};
exports.hexMemoToString = hexMemoToString;
/**
* Converts a Clarity Value memo to readable string
* Used when processing incoming transactions
*
* @param memoJson - The memo Clarity Value from a transaction
* @returns Readable string or undefined if conversion fails
*/
const bufferMemoToString = (memoJson) => {
// If memo is a buffer type, try to convert to string if it contains valid printable chars
if (memoJson?.type?.startsWith("(buff ") &&
typeof memoJson?.value === "string" &&
memoJson.value.startsWith("0x")) {
try {
const buffer = Buffer.from(memoJson.value.substring(2), "hex");
const str = buffer.toString();
// Check if string contains only printable characters
if (/^[\x20-\x7E]*$/.test(str)) {
return str;
}
}
catch (e) {
// Keep original memo value if conversion fails
(0, logs_1.log)("error", "Failed to convert memo buffer to string", e);
}
}
return undefined;
};
exports.bufferMemoToString = bufferMemoToString;
/**
* Processes a memo CV hex string from a transaction
*
* @param memoHex - Hex string of serialized Clarity Value memo
* @returns Readable string or undefined if conversion fails
*/
const processMemoCV = (memoHex) => {
if (!memoHex)
return undefined;
try {
const deserialized = (0, transactions_1.deserializeCV)(memoHex);
const memoJson = (0, transactions_1.cvToJSON)(deserialized).value;
return (0, exports.bufferMemoToString)(memoJson);
}
catch (e) {
(0, logs_1.log)("error", "Failed to process memo CV", e);
return undefined;
}
};
exports.processMemoCV = processMemoCV;
//# sourceMappingURL=memoUtils.js.map