UNPKG

@nervosnetwork/ckb-sdk-utils

Version:

Utils module of @nervosnetwork/ckb-sdk-core

50 lines 1.96 kB
import { assertToBeHexStringOrBigint, assertToBeHexString } from '../validators.js'; import { HexStringWithout0xException } from '../exceptions/index.js'; export const toUint16Le = (uint16) => { 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')}`; }; export const toUint32Le = (uint32) => { 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')}`; }; export const toUint64Le = (uint64) => { assertToBeHexStringOrBigint(uint64); const val = (typeof uint64 === 'bigint' ? uint64.toString(16) : uint64.slice(2)).padStart(16, '0'); const viewRight = toUint32Le(`0x${val.slice(0, 8)}`).slice(2); const viewLeft = toUint32Le(`0x${val.slice(8)}`).slice(2); return `0x${viewLeft}${viewRight}`; }; export const hexToBytes = (rawhex) => { if (rawhex === '') return new Uint8Array(); if (typeof rawhex === 'string' && !rawhex.startsWith('0x')) { throw new 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); }; export const toBigEndian = (leHex) => { assertToBeHexString(leHex); const bytes = hexToBytes(leHex); return `0x${bytes.reduceRight((pre, cur) => pre + cur.toString(16).padStart(2, '0'), '')}`; }; export const bytesToHex = (bytes) => `0x${[...bytes].map(b => b.toString(16).padStart(2, '0')).join('')}`; export default { toUint16Le, toUint32Le, toUint64Le, hexToBytes, bytesToHex, toBigEndian }; //# sourceMappingURL=index.js.map