@ocap/util 1.16.15 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,48 +1,65 @@
1
- /* eslint-disable max-len */
2
- /* eslint-disable no-bitwise */
3
- /* eslint-disable implicit-arrow-linebreak */
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.formatTxType = exports.toDid = exports.toAddress = exports.fromBase64 = exports.toBase64 = exports.fromBase58 = exports.toBase58 = exports.toBuffer = exports.toUint8Array = exports.isUUID = exports.UUID = exports.isUint8Array = exports.fromTokenToUnit = exports.fromUnitToToken = exports.numberToString = exports.toHex = exports.hexToBytes = exports.bytesToHex = exports.numberToHex = exports.hexToNumber = exports.hexToUtf8 = exports.utf8ToHex = exports.toBN = exports.isHex = exports.isHexStrict = exports.isBigNumber = exports.isBN = exports.stripHexPrefix = exports.isHexPrefixed = exports.numberToBN = exports.rightPad = exports.leftPad = exports.BN = void 0;
30
+ /* eslint-disable @typescript-eslint/no-use-before-define */
4
31
  /* eslint-disable no-param-reassign */
5
- /**
6
- * @fileOverview Contains utility functions to help developers manipulate blockchain related encoding/decoding/formatting
7
- * @module @ocap/util
8
- * @example
9
- * yarn add @ocap/util
10
- *
11
- * const Util = require('@ocap/util');
12
- * console.log(Util.fromTokenToUnit(100)); // 100_0000_0000_0000_0000
13
- * console.log(Util.fromUnitToToken('1000000000000000000')); // 100
14
- * console.log(Util.isStrictHex('0x123abc')); // true
15
- */
16
- const isBoolean = require('lodash/isBoolean');
17
- const isString = require('lodash/isString');
18
- const isNumber = require('lodash/isNumber');
19
- const isObject = require('lodash/isObject');
20
- const upperFirst = require('lodash/upperFirst');
21
- const camelCase = require('lodash/camelCase');
22
- const isNull = require('lodash/isNull');
23
- const rightPad = require('lodash/padEnd');
24
- const leftPad = require('lodash/padStart');
25
- const base58 = require('bs58');
26
- const utf8 = require('utf8');
27
- const base64 = require('base64-url');
28
- const BN = require('bn.js');
29
-
32
+ /* eslint-disable no-bitwise */
33
+ const isBoolean_1 = __importDefault(require("lodash/isBoolean"));
34
+ const isString_1 = __importDefault(require("lodash/isString"));
35
+ const isNumber_1 = __importDefault(require("lodash/isNumber"));
36
+ const isObject_1 = __importDefault(require("lodash/isObject"));
37
+ const upperFirst_1 = __importDefault(require("lodash/upperFirst"));
38
+ const camelCase_1 = __importDefault(require("lodash/camelCase"));
39
+ const isNull_1 = __importDefault(require("lodash/isNull"));
40
+ const padEnd_1 = __importDefault(require("lodash/padEnd"));
41
+ exports.rightPad = padEnd_1.default;
42
+ const padStart_1 = __importDefault(require("lodash/padStart"));
43
+ exports.leftPad = padStart_1.default;
44
+ const bs58_1 = __importDefault(require("bs58"));
45
+ const base64_url_1 = __importDefault(require("base64-url"));
46
+ const bn_js_1 = __importDefault(require("bn.js"));
47
+ exports.BN = bn_js_1.default;
48
+ const utf8 = __importStar(require("utf8"));
30
49
  const DID_PREFIX = 'did:abt:';
31
- const zero = new BN(0);
32
- const negative1 = new BN(-1);
33
-
50
+ const zero = new bn_js_1.default(0);
51
+ const negative1 = new bn_js_1.default(-1);
34
52
  const base58btc = {
35
- encode: (v) => `z${base58.encode(v)}`,
36
- decode: (v) => base58.decode(v.slice(1)),
53
+ encode: (v) => `z${bs58_1.default.encode(v)}`,
54
+ decode: (v) => bs58_1.default.decode(v.slice(1)),
37
55
  };
56
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
57
  const isBase58btc = (data) => {
39
- if (typeof data !== 'string') {
40
- return false;
41
- }
42
-
43
- return data[0] === 'z';
58
+ if (typeof data !== 'string') {
59
+ return false;
60
+ }
61
+ return data[0] === 'z';
44
62
  };
45
-
46
63
  /**
47
64
  * Returns a BN object, converts a number value to a BN
48
65
  * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object
@@ -50,41 +67,31 @@ const isBase58btc = (data) => {
50
67
  * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number
51
68
  */
52
69
  const numberToBN = (arg) => {
53
- if (typeof arg === 'string' || typeof arg === 'number') {
54
- let multiplier = new BN(1); // eslint-disable-line
55
- const formattedString = String(arg).toLowerCase().trim();
56
- const isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x';
57
- let stringArg = stripHexPrefix(formattedString); // eslint-disable-line
58
- if (stringArg.substr(0, 1) === '-') {
59
- stringArg = stripHexPrefix(stringArg.slice(1));
60
- multiplier = new BN(-1, 10);
61
- }
62
- stringArg = stringArg === '' ? '0' : stringArg;
63
-
64
- if (
65
- (!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) ||
66
- stringArg.match(/^[a-fA-F]+$/) ||
67
- (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))
68
- ) {
69
- return new BN(stringArg, 16).mul(multiplier);
70
- }
71
-
72
- if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) {
73
- return new BN(stringArg, 10).mul(multiplier);
74
- }
75
- } else if (typeof arg === 'object' && arg.toString && !arg.pop && !arg.push) {
76
- if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) {
77
- return new BN(arg.toString(10), 10);
78
- }
79
- }
80
-
81
- throw new Error(
82
- `[number-to-bn] while converting number ${JSON.stringify(
83
- arg
84
- )} to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.`
85
- );
70
+ if (typeof arg === 'string' || typeof arg === 'number') {
71
+ let multiplier = new bn_js_1.default(1); // eslint-disable-line
72
+ const formattedString = String(arg).toLowerCase().trim();
73
+ const isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x';
74
+ let stringArg = (0, exports.stripHexPrefix)(formattedString); // eslint-disable-line
75
+ if (stringArg.substr(0, 1) === '-') {
76
+ stringArg = (0, exports.stripHexPrefix)(stringArg.slice(1));
77
+ multiplier = new bn_js_1.default(-1, 10);
78
+ }
79
+ stringArg = stringArg === '' ? '0' : stringArg;
80
+ if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) ||
81
+ stringArg.match(/^[a-fA-F]+$/) ||
82
+ (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) {
83
+ return new bn_js_1.default(stringArg, 16).mul(multiplier);
84
+ }
85
+ if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) {
86
+ return new bn_js_1.default(stringArg, 10).mul(multiplier);
87
+ }
88
+ }
89
+ if ((0, exports.isBN)(arg)) {
90
+ return new bn_js_1.default(arg.toString(10), 10);
91
+ }
92
+ throw new Error(`[number-to-bn] while converting number ${JSON.stringify(arg)} to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.`);
86
93
  };
87
-
94
+ exports.numberToBN = numberToBN;
88
95
  /**
89
96
  * Returns a `boolean` on whether or not the `string` starts with '0x'
90
97
  *
@@ -95,13 +102,12 @@ const numberToBN = (arg) => {
95
102
  * @throws if the str input is not a string
96
103
  */
97
104
  const isHexPrefixed = (str) => {
98
- if (typeof str !== 'string') {
99
- throw new Error('[is-hex-prefixed] value must be type string');
100
- }
101
-
102
- return str.slice(0, 2).toLowerCase() === '0x';
105
+ if (typeof str !== 'string') {
106
+ throw new Error('[is-hex-prefixed] value must be type string');
107
+ }
108
+ return str.slice(0, 2).toLowerCase() === '0x';
103
109
  };
104
-
110
+ exports.isHexPrefixed = isHexPrefixed;
105
111
  /**
106
112
  * Removes '0x' from a given `String` if present
107
113
  *
@@ -111,13 +117,12 @@ const isHexPrefixed = (str) => {
111
117
  * @return {String|Optional} a string by pass if necessary
112
118
  */
113
119
  const stripHexPrefix = (str) => {
114
- if (typeof str !== 'string') {
115
- return str;
116
- }
117
-
118
- return isHexPrefixed(str) ? str.slice(2) : str;
120
+ if (typeof str !== 'string') {
121
+ return str;
122
+ }
123
+ return (0, exports.isHexPrefixed)(str) ? str.slice(2) : str;
119
124
  };
120
-
125
+ exports.stripHexPrefix = stripHexPrefix;
121
126
  /**
122
127
  * Returns true if object is BN, otherwise false
123
128
  *
@@ -127,8 +132,8 @@ const stripHexPrefix = (str) => {
127
132
  * @param {Object} object
128
133
  * @returns {Boolean}
129
134
  */
130
- const isBN = (object) => object instanceof BN || (object && object.constructor && object.constructor.name === 'BN');
131
-
135
+ const isBN = (object) => object instanceof bn_js_1.default || (object && object.constructor && object.constructor.name === 'BN');
136
+ exports.isBN = isBN;
132
137
  /**
133
138
  * Returns true if object is BigNumber, otherwise false
134
139
  *
@@ -139,7 +144,7 @@ const isBN = (object) => object instanceof BN || (object && object.constructor &
139
144
  * @returns {Boolean}
140
145
  */
141
146
  const isBigNumber = (object) => object && object.constructor && object.constructor.name === 'BigNumber';
142
-
147
+ exports.isBigNumber = isBigNumber;
143
148
  /**
144
149
  * Check if string is HEX, requires a 0x in front
145
150
  *
@@ -149,8 +154,8 @@ const isBigNumber = (object) => object && object.constructor && object.construct
149
154
  * @param {String} hex to be checked
150
155
  * @returns {Boolean}
151
156
  */
152
- const isHexStrict = (hex) => (isString(hex) || isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex);
153
-
157
+ const isHexStrict = (hex) => ((0, isString_1.default)(hex) || (0, isNumber_1.default)(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex);
158
+ exports.isHexStrict = isHexStrict;
154
159
  /**
155
160
  * Check if string is HEX
156
161
  *
@@ -160,29 +165,30 @@ const isHexStrict = (hex) => (isString(hex) || isNumber(hex)) && /^(-)?0x[0-9a-f
160
165
  * @param {String} hex to be checked
161
166
  * @returns {Boolean}
162
167
  */
163
- const isHex = (hex) => (isString(hex) || isNumber(hex)) && /^(-0x|0x|0X|-0X)?[0-9a-f]*$/i.test(hex);
164
-
168
+ const isHex = (hex) => ((0, isString_1.default)(hex) || (0, isNumber_1.default)(hex)) && /^(-0x|0x|0X|-0X)?[0-9a-f]*$/i.test(hex);
169
+ exports.isHex = isHex;
165
170
  /**
166
171
  * Takes an input and transforms it into an BN
167
172
  *
168
173
  * @public
169
174
  * @static
170
175
  * @method toBN
171
- * @param {Number|String|BN} number, string, HEX string or BN
176
+ * @param {Number|String|BN} num, string, HEX string or BN
172
177
  * @returns {BN} BN
173
178
  */
174
- const toBN = (number) => {
175
- try {
176
- if (typeof number === 'number' && number > 0) {
177
- const numStr = Number(number).toLocaleString('fullwide', { useGrouping: false });
178
- return new BN(numStr, 10);
179
- }
180
- return numberToBN(number);
181
- } catch (error) {
182
- throw new Error(`${error} Given value: "${number}"`);
183
- }
179
+ const toBN = (num, base = 10) => {
180
+ try {
181
+ if (typeof num === 'number' && num > 0) {
182
+ const numStr = Number(num).toLocaleString('fullwide', { useGrouping: false });
183
+ return new bn_js_1.default(numStr, base);
184
+ }
185
+ return (0, exports.numberToBN)(num);
186
+ }
187
+ catch (error) {
188
+ throw new Error(`${error} Given value: "${num}"`);
189
+ }
184
190
  };
185
-
191
+ exports.toBN = toBN;
186
192
  /**
187
193
  * Should be called to get hex representation (prefixed by 0x) of utf8 string
188
194
  *
@@ -193,28 +199,23 @@ const toBN = (number) => {
193
199
  * @returns {String} hex representation of input string
194
200
  */
195
201
  const utf8ToHex = (str) => {
196
- str = utf8.encode(str);
197
- let hex = '';
198
-
199
- /* eslint-disable no-control-regex */
200
- // remove \u0000 padding from either side
201
- str = str.replace(/^(?:\u0000)*/, '');
202
- str = str.split('').reverse().join('');
203
- str = str.replace(/^(?:\u0000)*/, '');
204
- str = str.split('').reverse().join('');
205
- /* eslint-enable no-control-regex */
206
-
207
- for (let i = 0; i < str.length; i++) {
208
- const code = str.charCodeAt(i);
209
- // if (code !== 0) {
210
- const n = code.toString(16);
211
- hex += n.length < 2 ? `0${n}` : n;
212
- // }
213
- }
214
-
215
- return `0x${hex}`;
202
+ str = utf8.encode(str);
203
+ let hex = '';
204
+ /* eslint-disable no-control-regex */
205
+ // remove \u0000 padding from either side
206
+ str = str.replace(/^(?:\u0000)*/, '');
207
+ str = str.split('').reverse().join('');
208
+ str = str.replace(/^(?:\u0000)*/, '');
209
+ str = str.split('').reverse().join('');
210
+ /* eslint-enable no-control-regex */
211
+ for (let i = 0; i < str.length; i++) {
212
+ const code = str.charCodeAt(i);
213
+ const n = code.toString(16);
214
+ hex += n.length < 2 ? `0${n}` : n;
215
+ }
216
+ return `0x${hex}`;
216
217
  };
217
-
218
+ exports.utf8ToHex = utf8ToHex;
218
219
  /**
219
220
  * Should be called to get utf8 from it's hex representation
220
221
  *
@@ -225,30 +226,26 @@ const utf8ToHex = (str) => {
225
226
  * @returns {String} ascii string representation of hex value
226
227
  */
227
228
  const hexToUtf8 = (hex) => {
228
- if (!isHexStrict(hex)) throw new Error(`The parameter "${hex}" must be a valid HEX string.`);
229
-
230
- let str = '';
231
- let code = 0;
232
- hex = hex.replace(/^0x/i, '');
233
-
234
- // remove 00 padding from either side
235
- hex = hex.replace(/^(?:00)*/, '');
236
- hex = hex.split('').reverse().join('');
237
- hex = hex.replace(/^(?:00)*/, '');
238
- hex = hex.split('').reverse().join('');
239
-
240
- const l = hex.length;
241
-
242
- for (let i = 0; i < l; i += 2) {
243
- code = parseInt(hex.substr(i, 2), 16);
244
- // if (code !== 0) {
245
- str += String.fromCharCode(code);
246
- // }
247
- }
248
-
249
- return utf8.decode(str);
229
+ if (!(0, exports.isHexStrict)(hex))
230
+ throw new Error(`The parameter "${hex}" must be a valid HEX string.`);
231
+ let str = '';
232
+ let code = 0;
233
+ hex = hex.replace(/^0x/i, '');
234
+ // remove 00 padding from either side
235
+ hex = hex.replace(/^(?:00)*/, '');
236
+ hex = hex.split('').reverse().join('');
237
+ hex = hex.replace(/^(?:00)*/, '');
238
+ hex = hex.split('').reverse().join('');
239
+ const l = hex.length;
240
+ for (let i = 0; i < l; i += 2) {
241
+ code = parseInt(hex.substr(i, 2), 16);
242
+ // if (code !== 0) {
243
+ str += String.fromCharCode(code);
244
+ // }
245
+ }
246
+ return utf8.decode(str);
250
247
  };
251
-
248
+ exports.hexToUtf8 = hexToUtf8;
252
249
  /**
253
250
  * Converts value to number representation
254
251
  *
@@ -259,13 +256,12 @@ const hexToUtf8 = (hex) => {
259
256
  * @returns {Number}
260
257
  */
261
258
  const hexToNumber = (value) => {
262
- if (!value) {
263
- return value;
264
- }
265
-
266
- return toBN(value).toNumber();
259
+ if (!value) {
260
+ return value;
261
+ }
262
+ return (0, exports.toBN)(value).toNumber();
267
263
  };
268
-
264
+ exports.hexToNumber = hexToNumber;
269
265
  /**
270
266
  * Converts value to hex representation
271
267
  *
@@ -276,21 +272,18 @@ const hexToNumber = (value) => {
276
272
  * @returns {String}
277
273
  */
278
274
  const numberToHex = (value) => {
279
- if (isNull(value) || typeof value === 'undefined') {
280
- return value;
281
- }
282
-
283
- // eslint-disable-next-line no-restricted-globals
284
- if (!isFinite(value) && !isHex(value)) {
285
- throw new Error(`Given input "${value}" is not a number.`);
286
- }
287
-
288
- const number = toBN(value);
289
- const result = number.toString(16);
290
-
291
- return number.lt(new BN(0)) ? `-0x${result.substr(1)}` : `0x${result}`;
275
+ if ((0, isNull_1.default)(value) || typeof value === 'undefined') {
276
+ return value;
277
+ }
278
+ // eslint-disable-next-line no-restricted-globals
279
+ if (!isFinite(value) && !(0, exports.isHex)(value)) {
280
+ throw new Error(`Given input "${value}" is not a number.`);
281
+ }
282
+ const num = (0, exports.toBN)(value);
283
+ const result = num.toString(16);
284
+ return num.lt(new bn_js_1.default(0)) ? `-0x${result.substr(1)}` : `0x${result}`;
292
285
  };
293
-
286
+ exports.numberToHex = numberToHex;
294
287
  /**
295
288
  * Convert a byte array to a hex string
296
289
  * Note: Implementation from crypto-js
@@ -302,16 +295,14 @@ const numberToHex = (value) => {
302
295
  * @returns {String} the hex string
303
296
  */
304
297
  const bytesToHex = (bytes) => {
305
- const hex = [];
306
-
307
- for (let i = 0; i < bytes.length; i++) {
308
- hex.push((bytes[i] >>> 4).toString(16));
309
- hex.push((bytes[i] & 0xf).toString(16));
310
- }
311
-
312
- return `0x${hex.join('')}`;
298
+ const hex = [];
299
+ for (let i = 0; i < bytes.length; i++) {
300
+ hex.push((bytes[i] >>> 4).toString(16));
301
+ hex.push((bytes[i] & 0xf).toString(16));
302
+ }
303
+ return `0x${hex.join('')}`;
313
304
  };
314
-
305
+ exports.bytesToHex = bytesToHex;
315
306
  /**
316
307
  * Convert a hex string to a byte array
317
308
  * Note: Implementation from crypto-js
@@ -323,23 +314,19 @@ const bytesToHex = (bytes) => {
323
314
  * @returns {Array} the byte array
324
315
  */
325
316
  const hexToBytes = (hex) => {
326
- hex = hex.toString(16);
327
-
328
- if (!isHex(hex)) {
329
- throw new Error(`Given value "${hex}" is not a valid hex string.`);
330
- }
331
-
332
- hex = hex.replace(/^0x/i, '');
333
- hex = hex.length % 2 ? `0${hex}` : hex;
334
-
335
- const bytes = [];
336
- for (let c = 0; c < hex.length; c += 2) {
337
- bytes.push(parseInt(hex.substr(c, 2), 16));
338
- }
339
-
340
- return bytes;
317
+ hex = hex.toString(16);
318
+ if (!(0, exports.isHex)(hex)) {
319
+ throw new Error(`Given value "${hex}" is not a valid hex string.`);
320
+ }
321
+ hex = hex.replace(/^0x/i, '');
322
+ hex = hex.length % 2 ? `0${hex}` : hex;
323
+ const bytes = [];
324
+ for (let c = 0; c < hex.length; c += 2) {
325
+ bytes.push(parseInt(hex.substr(c, 2), 16));
326
+ }
327
+ return bytes;
341
328
  };
342
-
329
+ exports.hexToBytes = hexToBytes;
343
330
  /**
344
331
  * Auto converts any given value into it's hex representation.
345
332
  * And even stringify objects before.
@@ -351,66 +338,57 @@ const hexToBytes = (hex) => {
351
338
  * @param {Boolean} returnType
352
339
  * @returns {String}
353
340
  */
354
- const toHex = (value, returnType) => {
355
- if (isUint8Array(value) || Buffer.isBuffer(value)) {
356
- return returnType ? 'bytes' : bytesToHex(value);
357
- }
358
-
359
- if (isBase58btc(value)) {
360
- return returnType ? 'bytes' : bytesToHex(base58btc.decode(value));
361
- }
362
-
363
- if (isBoolean(value)) {
341
+ const toHex = (value, returnType = false) => {
342
+ if (isUint8Array(value) || Buffer.isBuffer(value)) {
343
+ return returnType ? 'bytes' : (0, exports.bytesToHex)(value);
344
+ }
345
+ if (isBase58btc(value)) {
346
+ return returnType ? 'bytes' : (0, exports.bytesToHex)(base58btc.decode(value));
347
+ }
348
+ if ((0, isBoolean_1.default)(value)) {
349
+ // eslint-disable-next-line no-nested-ternary
350
+ return returnType ? 'bool' : value ? '0x01' : '0x00';
351
+ }
352
+ if ((0, isObject_1.default)(value) && !(0, exports.isBigNumber)(value) && !(0, exports.isBN)(value)) {
353
+ return returnType ? 'string' : (0, exports.utf8ToHex)(JSON.stringify(value));
354
+ }
355
+ // if its a negative number, pass it through numberToHex
356
+ if ((0, isString_1.default)(value)) {
357
+ if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) {
358
+ return returnType ? 'int256' : (0, exports.numberToHex)(value);
359
+ }
360
+ if (value.indexOf('0x') === 0 || value.indexOf('0X') === 0) {
361
+ return returnType ? 'bytes' : value;
362
+ }
363
+ // TODO: some edge case may be not properly handled here
364
+ return returnType ? 'string' : (0, exports.utf8ToHex)(value);
365
+ }
364
366
  // eslint-disable-next-line no-nested-ternary
365
- return returnType ? 'bool' : value ? '0x01' : '0x00';
366
- }
367
-
368
- if (isObject(value) && !isBigNumber(value) && !isBN(value)) {
369
- return returnType ? 'string' : utf8ToHex(JSON.stringify(value));
370
- }
371
-
372
- // if its a negative number, pass it through numberToHex
373
- if (isString(value)) {
374
- if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) {
375
- return returnType ? 'int256' : numberToHex(value);
376
- }
377
- if (value.indexOf('0x') === 0 || value.indexOf('0X') === 0) {
378
- return returnType ? 'bytes' : value;
379
- }
380
-
381
- // TODO: some edge case may be not properly handled here
382
- return returnType ? 'string' : utf8ToHex(value);
383
- }
384
-
385
- // eslint-disable-next-line no-nested-ternary
386
- return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value);
367
+ return returnType ? (value < 0 ? 'int256' : 'uint256') : (0, exports.numberToHex)(value);
387
368
  };
388
-
369
+ exports.toHex = toHex;
389
370
  const numberToString = (arg) => {
390
- if (typeof arg === 'string') {
391
- if (!arg.match(/^-?[0-9.]+$/)) {
392
- throw new Error(`Invalid value '${arg}' while converting to string, should be a number matching (^-?[0-9.]+).`);
393
- }
394
- return arg;
395
- }
396
- if (typeof arg === 'number') {
397
- if (typeof number === 'number' && arg > 0) {
398
- return Number(arg).toLocaleString('fullwide', { useGrouping: false });
399
- }
400
-
401
- return String(arg);
402
- }
403
-
404
- if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) {
405
- if (arg.toPrecision) {
406
- return String(arg.toPrecision());
407
- }
408
- return arg.toString(10);
409
- }
410
-
411
- throw new Error(`while converting number to string, invalid number value '${arg}' type ${typeof arg}.`);
371
+ if (typeof arg === 'string') {
372
+ if (!arg.match(/^-?[0-9.]+$/)) {
373
+ throw new Error(`Invalid value '${arg}' while converting to string, should be a number matching (^-?[0-9.]+).`);
374
+ }
375
+ return arg;
376
+ }
377
+ if (typeof arg === 'number') {
378
+ if (Number.isInteger(arg) && arg > 0) {
379
+ return Number(arg).toLocaleString('fullwide', { useGrouping: false });
380
+ }
381
+ return String(arg);
382
+ }
383
+ if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) {
384
+ if (arg.toPrecision) {
385
+ return String(arg.toPrecision());
386
+ }
387
+ return arg.toString(10);
388
+ }
389
+ throw new Error(`while converting number to string, invalid number value '${arg}' type ${typeof arg}.`);
412
390
  };
413
-
391
+ exports.numberToString = numberToString;
414
392
  /**
415
393
  * Format a big number to human readable number, such as 1_0000_0000_0000_000 => 1 Token
416
394
  *
@@ -422,40 +400,34 @@ const numberToString = (arg) => {
422
400
  * @param {object} [optionsInput=undefined]
423
401
  * @returns {string}
424
402
  */
425
- const fromUnitToToken = (input, decimal = 18, optionsInput) => {
426
- let unit = toBN(input);
427
- const negative = unit.lt(zero);
428
- const base = toBN(`1${'0'.repeat(decimal)}`, 10);
429
- const baseLength = base.toString(10).length - 1 || 1;
430
- const options = optionsInput || {};
431
-
432
- if (negative) {
433
- unit = unit.mul(negative1);
434
- }
435
-
436
- let fraction = unit.mod(base).toString(10);
437
- while (fraction.length < baseLength) {
438
- fraction = `0${fraction}`;
439
- }
440
-
441
- if (!options.pad) {
442
- // eslint-disable-next-line prefer-destructuring
443
- fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
444
- }
445
-
446
- let whole = unit.div(base).toString(10);
447
- if (options.commify) {
448
- whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
449
- }
450
-
451
- let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;
452
- if (negative) {
453
- value = `-${value}`;
454
- }
455
-
456
- return value;
403
+ const fromUnitToToken = (input, decimal = 18, optionsInput = {}) => {
404
+ let unit = (0, exports.toBN)(input);
405
+ const negative = unit.lt(zero);
406
+ const base = (0, exports.toBN)(`1${'0'.repeat(decimal)}`, 10);
407
+ const baseLength = base.toString(10).length - 1 || 1;
408
+ const options = optionsInput || {};
409
+ if (negative) {
410
+ unit = unit.mul(negative1);
411
+ }
412
+ let fraction = unit.mod(base).toString(10);
413
+ while (fraction.length < baseLength) {
414
+ fraction = `0${fraction}`;
415
+ }
416
+ if (!options.pad) {
417
+ // eslint-disable-next-line prefer-destructuring
418
+ fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
419
+ }
420
+ let whole = unit.div(base).toString(10);
421
+ if (options.commify) {
422
+ whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
423
+ }
424
+ let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;
425
+ if (negative) {
426
+ value = `-${value}`;
427
+ }
428
+ return value;
457
429
  };
458
-
430
+ exports.fromUnitToToken = fromUnitToToken;
459
431
  /**
460
432
  * Convert human readable token number to big number instance
461
433
  *
@@ -466,54 +438,45 @@ const fromUnitToToken = (input, decimal = 18, optionsInput) => {
466
438
  * @returns {BN}
467
439
  */
468
440
  const fromTokenToUnit = (input, decimal = 18) => {
469
- let token = numberToString(input);
470
- const base = toBN(`1${'0'.repeat(decimal)}`, 10);
471
- const baseLength = base.toString(10).length - 1 || 1;
472
-
473
- // Is it negative?
474
- const negative = token.substring(0, 1) === '-';
475
- if (negative) {
476
- token = token.substring(1);
477
- }
478
-
479
- if (token === '.') {
480
- throw new Error(`error converting token ${input} to unit, invalid value`);
481
- }
482
-
483
- // Split it into a whole and fractional part
484
- const comps = token.split('.');
485
- if (comps.length > 2) {
486
- throw new Error(`error converting token ${input} to unit, too many decimal points`);
487
- }
488
-
489
- let whole = comps[0];
490
- let fraction = comps[1];
491
-
492
- if (!whole) {
493
- whole = '0';
494
- }
495
- if (!fraction) {
496
- fraction = '0';
497
- }
498
- if (fraction.length > baseLength) {
499
- throw new Error(`error converting token ${input} to unit, too many decimal places`);
500
- }
501
-
502
- while (fraction.length < baseLength) {
503
- fraction += '0';
504
- }
505
-
506
- whole = new BN(whole);
507
- fraction = new BN(fraction);
508
- let unit = whole.mul(base).add(fraction);
509
-
510
- if (negative) {
511
- unit = unit.mul(negative1);
512
- }
513
-
514
- return new BN(unit.toString(10), 10);
441
+ let token = (0, exports.numberToString)(input);
442
+ const base = (0, exports.toBN)(`1${'0'.repeat(decimal)}`, 10);
443
+ const baseLength = base.toString(10).length - 1 || 1;
444
+ // Is it negative?
445
+ const negative = token.substring(0, 1) === '-';
446
+ if (negative) {
447
+ token = token.substring(1);
448
+ }
449
+ if (token === '.') {
450
+ throw new Error(`error converting token ${input} to unit, invalid value`);
451
+ }
452
+ // Split it into a whole and fractional part
453
+ const comps = token.split('.');
454
+ if (comps.length > 2) {
455
+ throw new Error(`error converting token ${input} to unit, too many decimal points`);
456
+ }
457
+ let whole = comps[0];
458
+ let fraction = comps[1];
459
+ if (!whole) {
460
+ whole = '0';
461
+ }
462
+ if (!fraction) {
463
+ fraction = '0';
464
+ }
465
+ if (fraction.length > baseLength) {
466
+ throw new Error(`error converting token ${input} to unit, too many decimal places`);
467
+ }
468
+ while (fraction.length < baseLength) {
469
+ fraction += '0';
470
+ }
471
+ whole = new bn_js_1.default(whole);
472
+ fraction = new bn_js_1.default(fraction);
473
+ let unit = whole.mul(base).add(fraction);
474
+ if (negative) {
475
+ unit = unit.mul(negative1);
476
+ }
477
+ return new bn_js_1.default(unit.toString(10), 10);
515
478
  };
516
-
479
+ exports.fromTokenToUnit = fromTokenToUnit;
517
480
  /**
518
481
  * Validates if a value is an Uint8Array.
519
482
  *
@@ -523,9 +486,9 @@ const fromTokenToUnit = (input, decimal = 18) => {
523
486
  * @returns {Boolean} boolean indicating if a value is an Uint8Array
524
487
  */
525
488
  function isUint8Array(value) {
526
- return Object.prototype.toString.call(value) === '[object Uint8Array]';
489
+ return Object.prototype.toString.call(value) === '[object Uint8Array]';
527
490
  }
528
-
491
+ exports.isUint8Array = isUint8Array;
529
492
  /**
530
493
  * Generate a random UUID
531
494
  *
@@ -534,13 +497,13 @@ function isUint8Array(value) {
534
497
  * @returns {string} Generated uuid
535
498
  */
536
499
  function UUID() {
537
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
538
- const r = (Math.random() * 16) | 0;
539
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
540
- return v.toString(16);
541
- });
500
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
501
+ const r = (Math.random() * 16) | 0;
502
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
503
+ return v.toString(16);
504
+ });
542
505
  }
543
-
506
+ exports.UUID = UUID;
544
507
  /**
545
508
  * Check if a string is valid UUID
546
509
  *
@@ -550,9 +513,9 @@ function UUID() {
550
513
  * @returns {boolean}
551
514
  */
552
515
  function isUUID(str) {
553
- return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(str);
516
+ return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(str);
554
517
  }
555
-
518
+ exports.isUUID = isUUID;
556
519
  /**
557
520
  * Convert input to Uint8Array on best effort, base64 node supported
558
521
  *
@@ -563,28 +526,31 @@ function isUUID(str) {
563
526
  * @throws {Error}
564
527
  */
565
528
  function toUint8Array(v) {
566
- let vb = null;
567
- if ([null, undefined, ''].includes(v)) {
568
- vb = new Uint8Array();
569
- } else if (Buffer.isBuffer(v)) {
570
- vb = new Uint8Array(v);
571
- } else if (isHexStrict(v)) {
572
- vb = new Uint8Array(hexToBytes(v));
573
- } else if (isUint8Array(v)) {
574
- vb = new Uint8Array(v);
575
- } else if (isBase58btc(v)) {
576
- vb = new Uint8Array(base58btc.decode(v));
577
- } else if (typeof v === 'string') {
578
- vb = new Uint8Array(hexToBytes(toHex(v)));
579
- } else {
580
- throw new Error(
581
- `Unsupported input type ${typeof v} detected for toBuffer, only Uint8Array/Buffer/Hex/Base58 are supported`
582
- );
583
- }
584
-
585
- return vb;
529
+ let vb = null;
530
+ if ([null, undefined, ''].includes(v)) {
531
+ vb = new Uint8Array();
532
+ }
533
+ else if (Buffer.isBuffer(v)) {
534
+ vb = new Uint8Array(v);
535
+ }
536
+ else if ((0, exports.isHexStrict)(v)) {
537
+ vb = new Uint8Array((0, exports.hexToBytes)(v));
538
+ }
539
+ else if (isUint8Array(v)) {
540
+ vb = new Uint8Array(v);
541
+ }
542
+ else if (isBase58btc(v)) {
543
+ vb = new Uint8Array(base58btc.decode(v));
544
+ }
545
+ else if (typeof v === 'string') {
546
+ vb = new Uint8Array((0, exports.hexToBytes)((0, exports.toHex)(v)));
547
+ }
548
+ else {
549
+ throw new Error(`Unsupported input type ${typeof v} detected for toBuffer, only Uint8Array/Buffer/Hex/Base58 are supported`);
550
+ }
551
+ return vb;
586
552
  }
587
-
553
+ exports.toUint8Array = toUint8Array;
588
554
  /**
589
555
  * Convert input to Buffer on best effort, base64 not supported
590
556
  *
@@ -595,9 +561,9 @@ function toUint8Array(v) {
595
561
  * @throws {Error}
596
562
  */
597
563
  function toBuffer(v) {
598
- return Buffer.from(toUint8Array(v));
564
+ return Buffer.from(toUint8Array(v));
599
565
  }
600
-
566
+ exports.toBuffer = toBuffer;
601
567
  /**
602
568
  * Convert input to base58btc format on best effort
603
569
  *
@@ -608,10 +574,10 @@ function toBuffer(v) {
608
574
  * @throws {Error}
609
575
  */
610
576
  function toBase58(v) {
611
- const buf = base58btc.encode(toUint8Array(v));
612
- return Buffer.from(buf).toString('utf-8');
577
+ const buf = base58btc.encode(toUint8Array(v));
578
+ return Buffer.from(buf).toString('utf-8');
613
579
  }
614
-
580
+ exports.toBase58 = toBase58;
615
581
  /**
616
582
  * Decode base58 string
617
583
  *
@@ -621,13 +587,12 @@ function toBase58(v) {
621
587
  * @returns {buffer}
622
588
  */
623
589
  function fromBase58(v) {
624
- if (isBase58btc(v) === false) {
625
- throw new Error('fromBase58 expect strict base58 encoded string as input');
626
- }
627
-
628
- return Buffer.from(base58btc.decode(v));
590
+ if (isBase58btc(v) === false) {
591
+ throw new Error('fromBase58 expect strict base58 encoded string as input');
592
+ }
593
+ return Buffer.from(base58btc.decode(v));
629
594
  }
630
-
595
+ exports.fromBase58 = fromBase58;
631
596
  /**
632
597
  * Convert input to base64 format
633
598
  *
@@ -639,10 +604,11 @@ function fromBase58(v) {
639
604
  * @throws {Error}
640
605
  */
641
606
  function toBase64(v, escape = true) {
642
- const encoded = base64.encode(toBuffer(v));
643
- return escape ? base64.escape(encoded) : encoded;
607
+ // FIXME: 这个是正确的?
608
+ const encoded = base64_url_1.default.encode(toBuffer(v));
609
+ return escape ? base64_url_1.default.escape(encoded) : encoded;
644
610
  }
645
-
611
+ exports.toBase64 = toBase64;
646
612
  /**
647
613
  * Decode base64(base64_url) string to buffer
648
614
  *
@@ -652,12 +618,12 @@ function toBase64(v, escape = true) {
652
618
  * @returns {buffer}
653
619
  */
654
620
  function fromBase64(v) {
655
- if (typeof v !== 'string') {
656
- throw new Error('fromBase64 requires input to be a string');
657
- }
658
- return Buffer.from(base64.unescape(v), 'base64');
621
+ if (typeof v !== 'string') {
622
+ throw new Error('fromBase64 requires input to be a string');
623
+ }
624
+ return Buffer.from(base64_url_1.default.unescape(v), 'base64');
659
625
  }
660
-
626
+ exports.fromBase64 = fromBase64;
661
627
  /**
662
628
  * Convert did to address: remove `did:abt:` prefix
663
629
  *
@@ -667,9 +633,9 @@ function fromBase64(v) {
667
633
  * @returns {string}
668
634
  */
669
635
  function toAddress(did) {
670
- return did.replace(DID_PREFIX, '');
636
+ return did.replace(DID_PREFIX, '');
671
637
  }
672
-
638
+ exports.toAddress = toAddress;
673
639
  /**
674
640
  * Convert address to did: prepend `did:abt:` prefix
675
641
  *
@@ -679,42 +645,8 @@ function toAddress(did) {
679
645
  * @returns {string}
680
646
  */
681
647
  function toDid(address) {
682
- return `${DID_PREFIX}${toAddress(address)}`;
648
+ return `${DID_PREFIX}${toAddress(address)}`;
683
649
  }
684
-
685
- const formatTxType = (type) => upperFirst(camelCase(type));
686
-
687
- module.exports = {
688
- BN,
689
- isBN,
690
- isBigNumber,
691
- isHexPrefixed,
692
- stripHexPrefix,
693
- utf8ToHex,
694
- hexToUtf8,
695
- numberToHex,
696
- hexToNumber,
697
- isHex,
698
- isHexStrict,
699
- isUint8Array,
700
- hexToBytes,
701
- bytesToHex,
702
- toHex,
703
- numberToString,
704
- fromUnitToToken,
705
- fromTokenToUnit,
706
- toBN,
707
- toUint8Array,
708
- toBuffer,
709
- toBase58,
710
- fromBase58,
711
- toBase64,
712
- fromBase64,
713
- UUID,
714
- isUUID,
715
- toDid,
716
- toAddress,
717
- formatTxType,
718
- leftPad,
719
- rightPad,
720
- };
650
+ exports.toDid = toDid;
651
+ const formatTxType = (type) => (0, upperFirst_1.default)((0, camelCase_1.default)(type));
652
+ exports.formatTxType = formatTxType;