UNPKG

raiden-ts

Version:

Raiden Light Client Typescript/Javascript SDK

57 lines 2.56 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.jsonStringify = exports.jsonParse = exports.encode = void 0; const bignumber_1 = require("@ethersproject/bignumber"); const bytes_1 = require("@ethersproject/bytes"); const constants_1 = require("@ethersproject/constants"); const strings_1 = require("@ethersproject/strings"); const json_bigint_1 = __importDefault(require("json-bigint")); const error_1 = require("./error"); const types_1 = require("./types"); /** * Encode data to hex string of exactly length size (in bytes) * Throw if data can't be made to fit in length. * * @param data - May be of multiple types: * - number|BigNumber: Encoded in the big-endian byte-order and left-zero-padded to length * - string: Must be hex-encoded string of length bytes * - number[] Must be of exactly of length size (left/right-pad it before if needed) * @param length - The expected length of the hex string, in bytes * @returns HexString byte-array of length */ function encode(data, length) { let hex; if (typeof data === 'boolean') data = data ? constants_1.One : constants_1.Zero; else if (typeof data === 'number') data = bignumber_1.BigNumber.from(data); if (typeof data === 'string' && !(0, bytes_1.isHexString)(data)) data = (0, strings_1.toUtf8Bytes)(data); if ((0, bytes_1.isBytesLike)(data)) data = (0, bytes_1.hexlify)(data); if (types_1.BigNumberC.is(data)) { if (data.lt(0)) throw new error_1.RaidenError(error_1.ErrorCodes.DTA_NEGATIVE_NUMBER); if (data.gte(constants_1.Two.pow(length * 8))) throw new error_1.RaidenError(error_1.ErrorCodes.DTA_NUMBER_TOO_LARGE); hex = (0, bytes_1.hexZeroPad)((0, bytes_1.hexlify)(data), length); } else if (typeof data === 'string') { if ((0, bytes_1.hexDataLength)(data) !== length) throw new error_1.RaidenError(error_1.ErrorCodes.DTA_ARRAY_LENGTH_DIFFERENCE); hex = data; } else { throw new error_1.RaidenError(error_1.ErrorCodes.DTA_UNENCODABLE_DATA); } return hex; } exports.encode = encode; // storeAsString requires BigNumbers to be decoded by io-ts const JSONbigStr = (0, json_bigint_1.default)({ storeAsString: true }); exports.jsonParse = JSONbigStr.parse; exports.jsonStringify = JSONbigStr.stringify; //# sourceMappingURL=data.js.map