airgap-coin-lib
Version:
The airgap-coin-lib is a protocol agnostic library to prepare, sign and broadcast cryptocurrency transactions.
71 lines • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var padStart_1 = require("./padStart");
var HEX_PREFIX = '0x';
var HEX_REGEX = new RegExp("^(" + HEX_PREFIX + ")?[0-9a-fA-F]*$");
function hasPrefix(value) {
return value.startsWith(HEX_PREFIX);
}
function addHexPrefix(raw) {
return hasPrefix(raw) ? raw : HEX_PREFIX + raw;
}
exports.addHexPrefix = addHexPrefix;
function stripHexPrefix(hex) {
return hasPrefix(hex) ? hex.substring(2) : hex;
}
exports.stripHexPrefix = stripHexPrefix;
function isHex(value) {
return HEX_REGEX.test(value);
}
exports.isHex = isHex;
function toHexBuffer(value) {
return Buffer.from(toHexStringRaw(value), 'hex');
}
exports.toHexBuffer = toHexBuffer;
function toHexStringRaw(value, bitLength) {
if (bitLength === void 0) { bitLength = 8; }
var nibbleLength = Math.ceil(bitLength / 4);
var hexString = value.toString(16);
var targetLength = hexString.length >= nibbleLength ? hexString.length : nibbleLength;
targetLength = targetLength % 2 == 0 ? targetLength : targetLength + 1;
return padStart_1.padStart(value.toString(16), targetLength, '0');
}
exports.toHexStringRaw = toHexStringRaw;
function toHexString(value, bitLength) {
if (bitLength === void 0) { bitLength = 8; }
return addHexPrefix(toHexStringRaw(value, bitLength));
}
exports.toHexString = toHexString;
function hexToBytes(hex) {
if (typeof hex === 'string' && isHex(hex)) {
return Buffer.from(stripHexPrefix(hex), 'hex');
}
else if (!(typeof hex === 'string')) {
return Buffer.from(hex);
}
else {
return Buffer.from([0]);
}
}
exports.hexToBytes = hexToBytes;
function bytesToHex(bytes, config) {
var _a;
var hex;
if (typeof bytes === 'string') {
hex = bytes;
}
else {
var buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
hex = buffer.toString('hex');
}
return ((_a = config) === null || _a === void 0 ? void 0 : _a.withPrefix) ? addHexPrefix(hex) : hex;
}
exports.bytesToHex = bytesToHex;
function changeEndianness(hex) {
var _hex = stripHexPrefix(hex);
_hex = _hex.length % 2 != 0 ? '0' + _hex : _hex;
var bytes = _hex.match(/.{2}/g) || [];
return bytes.reverse().join('');
}
exports.changeEndianness = changeEndianness;
//# sourceMappingURL=hex.js.map