UNPKG

2.81 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.toType = exports.TypeOutput = exports.bnToRlp = exports.bnToUnpaddedBuffer = exports.bnToHex = void 0;
7const bn_js_1 = __importDefault(require("bn.js"));
8const internal_1 = require("./internal");
9const bytes_1 = require("./bytes");
10/**
11 * Convert BN to 0x-prefixed hex string.
12 */
13function bnToHex(value) {
14 return `0x${value.toString(16)}`;
15}
16exports.bnToHex = bnToHex;
17/**
18 * Convert value from BN to an unpadded Buffer
19 * (useful for RLP transport)
20 * @param value value to convert
21 */
22function bnToUnpaddedBuffer(value) {
23 // Using `bn.toArrayLike(Buffer)` instead of `bn.toBuffer()`
24 // for compatibility with browserify and similar tools
25 return (0, bytes_1.unpadBuffer)(value.toArrayLike(Buffer));
26}
27exports.bnToUnpaddedBuffer = bnToUnpaddedBuffer;
28/**
29 * Deprecated alias for {@link bnToUnpaddedBuffer}
30 * @deprecated
31 */
32function bnToRlp(value) {
33 return bnToUnpaddedBuffer(value);
34}
35exports.bnToRlp = bnToRlp;
36/**
37 * Type output options
38 */
39var TypeOutput;
40(function (TypeOutput) {
41 TypeOutput[TypeOutput["Number"] = 0] = "Number";
42 TypeOutput[TypeOutput["BN"] = 1] = "BN";
43 TypeOutput[TypeOutput["Buffer"] = 2] = "Buffer";
44 TypeOutput[TypeOutput["PrefixedHexString"] = 3] = "PrefixedHexString";
45})(TypeOutput = exports.TypeOutput || (exports.TypeOutput = {}));
46function toType(input, outputType) {
47 if (input === null) {
48 return null;
49 }
50 if (input === undefined) {
51 return undefined;
52 }
53 if (typeof input === 'string' && !(0, internal_1.isHexString)(input)) {
54 throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`);
55 }
56 else if (typeof input === 'number' && !Number.isSafeInteger(input)) {
57 throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)');
58 }
59 const output = (0, bytes_1.toBuffer)(input);
60 if (outputType === TypeOutput.Buffer) {
61 return output;
62 }
63 else if (outputType === TypeOutput.BN) {
64 return new bn_js_1.default(output);
65 }
66 else if (outputType === TypeOutput.Number) {
67 const bn = new bn_js_1.default(output);
68 const max = new bn_js_1.default(Number.MAX_SAFE_INTEGER.toString());
69 if (bn.gt(max)) {
70 throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)');
71 }
72 return bn.toNumber();
73 }
74 else {
75 // outputType === TypeOutput.PrefixedHexString
76 return `0x${output.toString('hex')}`;
77 }
78}
79exports.toType = toType;
80//# sourceMappingURL=types.js.map
\No newline at end of file