@nervosnetwork/ckb-sdk-utils
Version:
Utils module of @nervosnetwork/ckb-sdk-core
59 lines • 2.54 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.bytesToHex = exports.toBigEndian = exports.hexToBytes = exports.toUint64Le = exports.toUint32Le = exports.toUint16Le = void 0;
const validators_js_1 = require("../validators.js");
const index_js_1 = require("../exceptions/index.js");
const toUint16Le = (uint16) => {
(0, validators_js_1.assertToBeHexStringOrBigint)(uint16);
const dv = new DataView(new ArrayBuffer(2));
dv.setUint16(0, Number(uint16), true);
return `0x${dv.getUint16(0, false).toString(16).padStart(4, '0')}`;
};
exports.toUint16Le = toUint16Le;
const toUint32Le = (uint32) => {
(0, validators_js_1.assertToBeHexStringOrBigint)(uint32);
const dv = new DataView(new ArrayBuffer(4));
dv.setUint32(0, Number(uint32), true);
return `0x${dv.getUint32(0, false).toString(16).padStart(8, '0')}`;
};
exports.toUint32Le = toUint32Le;
const toUint64Le = (uint64) => {
(0, validators_js_1.assertToBeHexStringOrBigint)(uint64);
const val = (typeof uint64 === 'bigint' ? uint64.toString(16) : uint64.slice(2)).padStart(16, '0');
const viewRight = (0, exports.toUint32Le)(`0x${val.slice(0, 8)}`).slice(2);
const viewLeft = (0, exports.toUint32Le)(`0x${val.slice(8)}`).slice(2);
return `0x${viewLeft}${viewRight}`;
};
exports.toUint64Le = toUint64Le;
const hexToBytes = (rawhex) => {
if (rawhex === '')
return new Uint8Array();
if (typeof rawhex === 'string' && !rawhex.startsWith('0x')) {
throw new index_js_1.HexStringWithout0xException(rawhex);
}
let hex = rawhex.toString(16).replace(/^0x/i, '');
hex = hex.length % 2 ? `0${hex}` : hex;
const bytes = [];
for (let c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return new Uint8Array(bytes);
};
exports.hexToBytes = hexToBytes;
const toBigEndian = (leHex) => {
(0, validators_js_1.assertToBeHexString)(leHex);
const bytes = (0, exports.hexToBytes)(leHex);
return `0x${bytes.reduceRight((pre, cur) => pre + cur.toString(16).padStart(2, '0'), '')}`;
};
exports.toBigEndian = toBigEndian;
const bytesToHex = (bytes) => `0x${[...bytes].map(b => b.toString(16).padStart(2, '0')).join('')}`;
exports.bytesToHex = bytesToHex;
exports.default = {
toUint16Le: exports.toUint16Le,
toUint32Le: exports.toUint32Le,
toUint64Le: exports.toUint64Le,
hexToBytes: exports.hexToBytes,
bytesToHex: exports.bytesToHex,
toBigEndian: exports.toBigEndian
};
//# sourceMappingURL=index.js.map
;