UNPKG

@radixdlt/account

Version:

A JavaScript client library for interacting with the Radix Distributed Ledger.

85 lines 3.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Bech32 = exports.defaultEncoding = exports.Encoding = void 0; const bech32_1 = require("bech32"); const util_1 = require("@radixdlt/util"); const neverthrow_1 = require("neverthrow"); var Encoding; (function (Encoding) { Encoding["BECH32"] = "bech32"; Encoding["BECH32m"] = "bech32m"; })(Encoding = exports.Encoding || (exports.Encoding = {})); exports.defaultEncoding = Encoding.BECH32; const convertDataFromBech32 = (bech32Data) => { try { const data = bech32_1.bech32.fromWords(bech32Data); return (0, neverthrow_1.ok)(Buffer.from(data)); } catch (e) { const underlyingError = (0, util_1.msgFromError)(e); const errMsg = `Failed to converted bech32 data to Buffer, underlying error: '${underlyingError}'`; return (0, neverthrow_1.err)(new Error(errMsg)); } }; const convertDataToBech32 = (data) => { try { const bech32Data = bech32_1.bech32.toWords(data); return (0, neverthrow_1.ok)(Buffer.from(bech32Data)); } catch (e) { const underlyingError = (0, util_1.msgFromError)(e); const errMsg = `Failed to converted buffer to bech32 data, underlying error: '${underlyingError}'`; return (0, neverthrow_1.err)(new Error(errMsg)); } }; const __unsafeCreate = (input) => { const toString = () => input.bech32String; const equals = (other) => toString() === other.toString(); return { hrp: input.hrp, data: input.data, equals, toString }; }; const encode = (input) => { var _a; const { hrp, data, maxLength } = input; const encoding = (_a = input.encoding) !== null && _a !== void 0 ? _a : exports.defaultEncoding; const impl = encoding === Encoding.BECH32 ? bech32_1.bech32 : bech32_1.bech32m; try { // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access const bech32String = impl.encode(hrp, data, maxLength); return (0, neverthrow_1.ok)(__unsafeCreate({ bech32String: bech32String.toLowerCase(), hrp, data, })); } catch (e) { const errMsg = (0, util_1.msgFromError)(e); util_1.log.error(errMsg); return (0, neverthrow_1.err)(new Error(errMsg)); } }; const decode = (input) => { var _a; const { bechString, maxLength } = input; const encoding = (_a = input.encoding) !== null && _a !== void 0 ? _a : exports.defaultEncoding; const impl = encoding === Encoding.BECH32 ? bech32_1.bech32 : bech32_1.bech32m; try { const decoded = impl.decode(bechString, maxLength); return (0, neverthrow_1.ok)(__unsafeCreate({ bech32String: bechString, hrp: decoded.prefix, data: Buffer.from(decoded.words), })); } catch (e) { const errMsg = (0, util_1.msgFromError)(e); util_1.log.error(errMsg); return (0, neverthrow_1.err)(new Error(errMsg)); } }; exports.Bech32 = { convertDataToBech32, convertDataFromBech32, decode, encode, }; //# sourceMappingURL=bech32.js.map