UNPKG

@nervosnetwork/ckb-sdk-utils

Version:

Utils module of @nervosnetwork/ckb-sdk-core

67 lines 2.96 kB
import { hexToBytes, bytesToHex, toUint32Le } from '../convertors/index.js'; export const offsetSize = 4; export const fullLengthSize = 4; export const getOffsets = (elmLengths) => { const headerLength = fullLengthSize + offsetSize * elmLengths.length; const offsets = [headerLength]; elmLengths.forEach((_, idx) => { if (idx) { offsets.push(offsets[offsets.length - 1] + elmLengths[idx - 1]); } }); return offsets; }; export const serializeArray = (array) => { if (typeof array !== 'string' && !Array.isArray(array)) { throw new TypeError('The array to be serialized should by type of string or bytes'); } const bytes = typeof array === 'string' ? hexToBytes(array) : array; return bytesToHex(bytes); }; export const serializeStruct = (struct) => { let res = ''; struct.forEach(value => { res += serializeArray(value).slice(2); }); return `0x${res}`; }; export const serializeFixVec = (fixVec) => { if (typeof fixVec !== 'string' && !Array.isArray(fixVec)) { throw new TypeError('The fixed vector to be serialized should be a string or an array of bytes'); } const vec = typeof fixVec === 'string' ? [...hexToBytes(fixVec)].map(b => `0x${b.toString(16)}`) : fixVec; const serializedItemVec = vec.map(item => serializeArray(item).slice(2)); const header = toUint32Le(`0x${serializedItemVec.length.toString(16)}`).slice(2); return `0x${header}${serializedItemVec.join('')}`; }; export const serializeDynVec = (dynVec) => { if (!Array.isArray(dynVec)) { throw new TypeError('The dynamic vector to be serialized should be an array of bytes'); } const serializedItemVec = dynVec.map(item => serializeArray(item).slice(2)); const body = serializedItemVec.join(''); let offsets = ''; if (serializedItemVec.length) { offsets = getOffsets(serializedItemVec.map(item => item.length / 2)) .map(offset => toUint32Le(`0x${offset.toString(16)}`).slice(2)) .join(''); } const headerLength = fullLengthSize + offsetSize * serializedItemVec.length; const fullLength = toUint32Le(`0x${(headerLength + body.length / 2).toString(16)}`).slice(2); return `0x${fullLength}${offsets}${body}`; }; export const serializeTable = (table) => { const bodyElms = []; table.forEach(value => { bodyElms.push(serializeArray(value).slice(2)); }); const body = bodyElms.join(''); const headerLength = fullLengthSize + offsetSize * table.size; const fullLength = toUint32Le(`0x${(headerLength + body.length / 2).toString(16)}`).slice(2); const offsets = getOffsets(bodyElms.map(arg => arg.length / 2)) .map(offset => toUint32Le(`0x${offset.toString(16)}`).slice(2)) .join(''); return `0x${fullLength}${offsets}${body}`; }; export const serializeOption = (innerItem) => (!innerItem ? '0x' : innerItem); //# sourceMappingURL=basic.js.map