UNPKG

@exodus/ethereumjs-util

Version:
79 lines 2.79 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.toType = exports.TypeOutput = exports.bnToRlp = exports.bnToUnpaddedBuffer = exports.bnToHex = void 0; const bn_js_1 = __importDefault(require("bn.js")); const ethjs_util_1 = require("ethjs-util"); const bytes_1 = require("./bytes"); /** * Convert BN to 0x-prefixed hex string. */ function bnToHex(value) { return `0x${value.toString(16)}`; } exports.bnToHex = bnToHex; /** * Convert value from BN to an unpadded Buffer * (useful for RLP transport) * @param value value to convert */ function bnToUnpaddedBuffer(value) { // Using `bn.toArrayLike(Buffer)` instead of `bn.toBuffer()` // for compatibility with browserify and similar tools return bytes_1.unpadBuffer(value.toArrayLike(Buffer)); } exports.bnToUnpaddedBuffer = bnToUnpaddedBuffer; /** * Deprecated alias for {@link bnToUnpaddedBuffer} * @deprecated */ function bnToRlp(value) { return bnToUnpaddedBuffer(value); } exports.bnToRlp = bnToRlp; /** * Type output options */ var TypeOutput; (function (TypeOutput) { TypeOutput[TypeOutput["Number"] = 0] = "Number"; TypeOutput[TypeOutput["BN"] = 1] = "BN"; TypeOutput[TypeOutput["Buffer"] = 2] = "Buffer"; TypeOutput[TypeOutput["PrefixedHexString"] = 3] = "PrefixedHexString"; })(TypeOutput = exports.TypeOutput || (exports.TypeOutput = {})); /** * Convert an input to a specified type * @param input value to convert * @param outputType type to output */ function toType(input, outputType) { if (typeof input === 'string' && !ethjs_util_1.isHexString(input)) { throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`); } else if (typeof input === 'number' && !Number.isSafeInteger(input)) { throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'); } input = bytes_1.toBuffer(input); if (outputType === TypeOutput.Buffer) { return input; } else if (outputType === TypeOutput.BN) { return new bn_js_1.default(input); } else if (outputType === TypeOutput.Number) { const bn = new bn_js_1.default(input); const max = new bn_js_1.default(Number.MAX_SAFE_INTEGER.toString()); if (bn.gt(max)) { throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)'); } return bn.toNumber(); } else { // outputType === TypeOutput.PrefixedHexString return `0x${input.toString('hex')}`; } } exports.toType = toType; //# sourceMappingURL=types.js.map