@ocap/util 1.27.15 → 1.28.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.
Files changed (54) hide show
  1. package/esm/bn.d.ts +8 -6
  2. package/esm/bn.js +11 -7
  3. package/esm/constant.d.ts +4 -1
  4. package/esm/constant.js +5 -1
  5. package/esm/create-sorted-list.d.ts +4 -1
  6. package/esm/create-sorted-list.js +8 -3
  7. package/esm/curve.d.ts +85 -55
  8. package/esm/curve.js +132 -127
  9. package/esm/error.d.ts +12 -9
  10. package/esm/error.js +24 -17
  11. package/esm/get-list-field.d.ts +4 -1
  12. package/esm/get-list-field.js +7 -2
  13. package/esm/get-related-addr.d.ts +4 -1
  14. package/esm/get-related-addr.js +5 -1
  15. package/esm/index.d.ts +47 -44
  16. package/esm/index.js +364 -469
  17. package/esm/lodash.d.ts +12 -0
  18. package/esm/md5.d.ts +4 -1
  19. package/esm/md5.js +7 -3
  20. package/esm/ready.d.ts +13 -9
  21. package/esm/ready.js +33 -36
  22. package/esm/retry.d.ts +16 -9
  23. package/esm/retry.js +26 -27
  24. package/esm/tsfixme.d.ts +3 -0
  25. package/esm/url.d.ts +16 -12
  26. package/esm/url.js +67 -92
  27. package/lib/_virtual/rolldown_runtime.js +29 -0
  28. package/lib/bn.d.ts +8 -6
  29. package/lib/bn.js +12 -12
  30. package/lib/constant.d.ts +4 -1
  31. package/lib/constant.js +6 -4
  32. package/lib/create-sorted-list.d.ts +4 -1
  33. package/lib/create-sorted-list.js +11 -10
  34. package/lib/curve.d.ts +84 -55
  35. package/lib/curve.js +139 -137
  36. package/lib/error.d.ts +12 -9
  37. package/lib/error.js +25 -21
  38. package/lib/get-list-field.d.ts +4 -1
  39. package/lib/get-list-field.js +9 -9
  40. package/lib/get-related-addr.d.ts +4 -1
  41. package/lib/get-related-addr.js +5 -4
  42. package/lib/index.d.ts +47 -44
  43. package/lib/index.js +386 -506
  44. package/lib/lodash.d.ts +12 -0
  45. package/lib/md5.d.ts +4 -1
  46. package/lib/md5.js +9 -10
  47. package/lib/ready.d.ts +13 -9
  48. package/lib/ready.js +34 -42
  49. package/lib/retry.d.ts +16 -9
  50. package/lib/retry.js +27 -30
  51. package/lib/tsfixme.d.ts +3 -0
  52. package/lib/url.d.ts +16 -12
  53. package/lib/url.js +69 -118
  54. package/package.json +23 -9
package/esm/index.js CHANGED
@@ -1,529 +1,424 @@
1
- import isBoolean from 'lodash/isBoolean';
2
- import isString from 'lodash/isString';
3
- import isNumber from 'lodash/isNumber';
4
- import isObject from 'lodash/isObject';
5
- import upperFirst from 'lodash/upperFirst';
6
- import camelCase from 'lodash/camelCase';
7
- import isNull from 'lodash/isNull';
8
- import rightPad from 'lodash/padEnd';
9
- import leftPad from 'lodash/padStart';
10
- import base58 from 'bs58';
11
- import base64 from 'base64-url';
12
- import * as utf8 from 'utf8';
13
- import { BN, BaseBN } from './bn';
14
- const DID_PREFIX = 'did:abt:';
1
+ import { BN } from "./bn.js";
2
+ import BaseBN from "bn.js";
3
+ import isBoolean from "lodash/isBoolean.js";
4
+ import isString from "lodash/isString.js";
5
+ import isNumber from "lodash/isNumber.js";
6
+ import isObject from "lodash/isObject.js";
7
+ import upperFirst from "lodash/upperFirst.js";
8
+ import camelCase from "lodash/camelCase.js";
9
+ import isNull from "lodash/isNull.js";
10
+ import rightPad from "lodash/padEnd.js";
11
+ import leftPad from "lodash/padStart.js";
12
+ import base58 from "bs58";
13
+ import base64 from "base64-url";
14
+ import * as utf8 from "utf8";
15
+
16
+ //#region src/index.ts
17
+ const DID_PREFIX = "did:abt:";
15
18
  const zero = new BN(0);
16
19
  const negative1 = new BN(-1);
17
20
  const base58btc = {
18
- encode: (v) => `z${base58.encode(v)}`,
19
- decode: (v) => base58.decode(v.slice(1)),
21
+ encode: (v) => `z${base58.encode(v)}`,
22
+ decode: (v) => base58.decode(v.slice(1))
20
23
  };
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
- export const isBase58btc = (data) => {
23
- if (typeof data !== 'string') {
24
- return false;
25
- }
26
- if (data[0] === 'z') {
27
- try {
28
- base58btc.decode(data);
29
- return true;
30
- }
31
- catch (err) {
32
- return false;
33
- }
34
- }
35
- return false;
24
+ const isBase58btc = (data) => {
25
+ if (typeof data !== "string") return false;
26
+ if (data[0] === "z") try {
27
+ base58btc.decode(data);
28
+ return true;
29
+ } catch (err) {
30
+ return false;
31
+ }
32
+ return false;
36
33
  };
37
- export { BN, leftPad, rightPad };
38
34
  /**
39
- * Returns a BN object, converts a number value to a BN
40
- * @param {string|number|BN} `arg` input a string number, hex string number, number, BigNumber or BN object
41
- * @return {BN} `output` BN object of the number
42
- * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number
43
- */
44
- export const numberToBN = (arg) => {
45
- if (typeof arg === 'string' || typeof arg === 'number') {
46
- let multiplier = new BN(1); // eslint-disable-line
47
- const formattedString = String(arg).toLowerCase().trim();
48
- const isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x';
49
- let stringArg = stripHexPrefix(formattedString); // eslint-disable-line
50
- if (stringArg.substr(0, 1) === '-') {
51
- stringArg = stripHexPrefix(stringArg.slice(1));
52
- multiplier = new BN(-1, 10);
53
- }
54
- stringArg = stringArg === '' ? '0' : stringArg;
55
- if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) ||
56
- stringArg.match(/^[a-fA-F]+$/) ||
57
- (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) {
58
- return new BN(stringArg, 16).mul(multiplier);
59
- }
60
- if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) {
61
- return new BN(stringArg, 10).mul(multiplier);
62
- }
63
- }
64
- if (isBN(arg)) {
65
- return new BN(arg.toString(10), 10);
66
- }
67
- 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.`);
35
+ * Returns a BN object, converts a number value to a BN
36
+ * @param {string|number|BN} `arg` input a string number, hex string number, number, BigNumber or BN object
37
+ * @return {BN} `output` BN object of the number
38
+ * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number
39
+ */
40
+ const numberToBN = (arg) => {
41
+ if (typeof arg === "string" || typeof arg === "number") {
42
+ let multiplier = new BN(1);
43
+ const formattedString = String(arg).toLowerCase().trim();
44
+ const isHexPrefixed$1 = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x";
45
+ let stringArg = stripHexPrefix(formattedString);
46
+ if (stringArg.substr(0, 1) === "-") {
47
+ stringArg = stripHexPrefix(stringArg.slice(1));
48
+ multiplier = new BN(-1, 10);
49
+ }
50
+ stringArg = stringArg === "" ? "0" : stringArg;
51
+ if (!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/) || stringArg.match(/^[a-fA-F]+$/) || isHexPrefixed$1 === true && stringArg.match(/^[0-9A-Fa-f]+$/)) return new BN(stringArg, 16).mul(multiplier);
52
+ if ((stringArg.match(/^-?[0-9]+$/) || stringArg === "") && isHexPrefixed$1 === false) return new BN(stringArg, 10).mul(multiplier);
53
+ }
54
+ if (isBN(arg)) return new BN(arg.toString(10), 10);
55
+ 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.`);
68
56
  };
69
57
  /**
70
- * Returns a `boolean` on whether or not the `string` starts with '0x'
71
- *
72
- * @public
73
- * @static
74
- * @param {String} str the string input value
75
- * @return {Boolean} a boolean if it is or is not hex prefixed
76
- * @throws if the str input is not a string
77
- */
78
- export const isHexPrefixed = (str) => {
79
- if (typeof str !== 'string') {
80
- throw new Error('[is-hex-prefixed] value must be type string');
81
- }
82
- return str.slice(0, 2).toLowerCase() === '0x';
58
+ * Returns a `boolean` on whether or not the `string` starts with '0x'
59
+ *
60
+ * @public
61
+ * @static
62
+ * @param {String} str the string input value
63
+ * @return {Boolean} a boolean if it is or is not hex prefixed
64
+ * @throws if the str input is not a string
65
+ */
66
+ const isHexPrefixed = (str) => {
67
+ if (typeof str !== "string") throw new Error("[is-hex-prefixed] value must be type string");
68
+ return str.slice(0, 2).toLowerCase() === "0x";
83
69
  };
84
70
  /**
85
- * Removes '0x' from a given `String` if present
86
- *
87
- * @public
88
- * @static
89
- */
90
- export const stripHexPrefix = (str) => {
91
- if (typeof str === 'string') {
92
- return isHexPrefixed(str) ? str.slice(2) : str;
93
- }
94
- return str;
71
+ * Removes '0x' from a given `String` if present
72
+ *
73
+ * @public
74
+ * @static
75
+ */
76
+ const stripHexPrefix = (str) => {
77
+ if (typeof str === "string") return isHexPrefixed(str) ? str.slice(2) : str;
78
+ return str;
95
79
  };
96
80
  /**
97
- * Returns true if object is BN, otherwise false
98
- *
99
- * @public
100
- * @static
101
- * @method isBN
102
- * @param {Object} object
103
- * @returns {Boolean}
104
- */
105
- export const isBN = (object) => object instanceof BN ||
106
- object instanceof BaseBN ||
107
- // constructor validation only work for node cause browser bundle will obfuscated code
108
- (object && object.constructor && object.constructor.name === 'BN');
81
+ * Returns true if object is BN, otherwise false
82
+ *
83
+ * @public
84
+ * @static
85
+ * @method isBN
86
+ * @param {Object} object
87
+ * @returns {Boolean}
88
+ */
89
+ const isBN = (object) => object instanceof BN || object instanceof BaseBN || object && object.constructor && object.constructor.name === "BN";
109
90
  /**
110
- * Returns true if object is BigNumber, otherwise false
111
- *
112
- * @public
113
- * @static
114
- * @method isBigNumber
115
- * @param {Object} object
116
- * @returns {Boolean}
117
- */
118
- export const isBigNumber = (object) => object && object.constructor && object.constructor.name === 'BigNumber';
91
+ * Returns true if object is BigNumber, otherwise false
92
+ *
93
+ * @public
94
+ * @static
95
+ * @method isBigNumber
96
+ * @param {Object} object
97
+ * @returns {Boolean}
98
+ */
99
+ const isBigNumber = (object) => object && object.constructor && object.constructor.name === "BigNumber";
119
100
  /**
120
- * Check if string is HEX, requires a 0x in front
121
- *
122
- * @public
123
- * @static
124
- * @method isHexStrict
125
- * @param {String} hex to be checked
126
- * @returns {Boolean}
127
- */
128
- export const isHexStrict = (hex) => (isString(hex) || isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex);
101
+ * Check if string is HEX, requires a 0x in front
102
+ *
103
+ * @public
104
+ * @static
105
+ * @method isHexStrict
106
+ * @param {String} hex to be checked
107
+ * @returns {Boolean}
108
+ */
109
+ const isHexStrict = (hex) => (isString(hex) || isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex);
129
110
  /**
130
- * Check if string is HEX
131
- *
132
- * @public
133
- * @static
134
- * @method isHex
135
- * @param {String} hex to be checked
136
- * @returns {Boolean}
137
- */
138
- export const isHex = (hex) => (isString(hex) || isNumber(hex)) && /^(-0x|0x|0X|-0X)?[0-9a-f]*$/i.test(hex);
111
+ * Check if string is HEX
112
+ *
113
+ * @public
114
+ * @static
115
+ * @method isHex
116
+ * @param {String} hex to be checked
117
+ * @returns {Boolean}
118
+ */
119
+ const isHex = (hex) => (isString(hex) || isNumber(hex)) && /^(-0x|0x|0X|-0X)?[0-9a-f]*$/i.test(hex);
139
120
  /**
140
- * Takes an input and transforms it into an BN
141
- *
142
- * @public
143
- * @static
144
- * @method toBN
145
- * @param {Number|String|BN} num, string, HEX string or BN
146
- * @returns {BN} BN
147
- */
148
- export const toBN = (num, base = 10) => {
149
- try {
150
- if (typeof num === 'number' && num > 0) {
151
- const numStr = Number(num).toLocaleString('fullwide', { useGrouping: false });
152
- return new BN(numStr, base);
153
- }
154
- return numberToBN(num);
155
- }
156
- catch (error) {
157
- throw new Error(`${error} Given value: "${num}"`);
158
- }
121
+ * Takes an input and transforms it into an BN
122
+ *
123
+ * @public
124
+ * @static
125
+ * @method toBN
126
+ * @param {Number|String|BN} num, string, HEX string or BN
127
+ * @returns {BN} BN
128
+ */
129
+ const toBN = (num, base = 10) => {
130
+ try {
131
+ if (typeof num === "number" && num > 0) return new BN(Number(num).toLocaleString("fullwide", { useGrouping: false }), base);
132
+ return numberToBN(num);
133
+ } catch (error) {
134
+ throw new Error(`${error} Given value: "${num}"`);
135
+ }
159
136
  };
160
137
  /**
161
- * Should be called to get hex representation (prefixed by 0x) of utf8 string
162
- *
163
- * @public
164
- * @static
165
- * @method utf8ToHex
166
- * @param {String} str
167
- * @returns {String} hex representation of input string
168
- */
169
- export const utf8ToHex = (str) => {
170
- str = utf8.encode(str);
171
- let hex = '';
172
- /* eslint-disable no-control-regex */
173
- // remove \u0000 padding from either side
174
- str = str.replace(/^(?:\u0000)*/, '');
175
- str = str.split('').reverse().join('');
176
- str = str.replace(/^(?:\u0000)*/, '');
177
- str = str.split('').reverse().join('');
178
- /* eslint-enable no-control-regex */
179
- for (let i = 0; i < str.length; i++) {
180
- const code = str.charCodeAt(i);
181
- const n = code.toString(16);
182
- hex += n.length < 2 ? `0${n}` : n;
183
- }
184
- return `0x${hex}`;
138
+ * Should be called to get hex representation (prefixed by 0x) of utf8 string
139
+ *
140
+ * @public
141
+ * @static
142
+ * @method utf8ToHex
143
+ * @param {String} str
144
+ * @returns {String} hex representation of input string
145
+ */
146
+ const utf8ToHex = (str) => {
147
+ str = utf8.encode(str);
148
+ let hex = "";
149
+ str = str.replace(/^(?:\u0000)*/, "");
150
+ str = str.split("").reverse().join("");
151
+ str = str.replace(/^(?:\u0000)*/, "");
152
+ str = str.split("").reverse().join("");
153
+ for (let i = 0; i < str.length; i++) {
154
+ const n = str.charCodeAt(i).toString(16);
155
+ hex += n.length < 2 ? `0${n}` : n;
156
+ }
157
+ return `0x${hex}`;
185
158
  };
186
159
  /**
187
- * Should be called to get utf8 from it's hex representation
188
- *
189
- * @public
190
- * @static
191
- * @method hexToUtf8
192
- * @param {String} hex
193
- * @returns {String} ascii string representation of hex value
194
- */
195
- export const hexToUtf8 = (hex) => {
196
- if (!isHexStrict(hex))
197
- throw new Error(`The parameter "${hex}" must be a valid HEX string.`);
198
- let str = '';
199
- let code = 0;
200
- hex = hex.replace(/^0x/i, '');
201
- // remove 00 padding from either side
202
- hex = hex.replace(/^(?:00)*/, '');
203
- hex = hex.split('').reverse().join('');
204
- hex = hex.replace(/^(?:00)*/, '');
205
- hex = hex.split('').reverse().join('');
206
- const l = hex.length;
207
- for (let i = 0; i < l; i += 2) {
208
- code = parseInt(hex.substr(i, 2), 16);
209
- // if (code !== 0) {
210
- str += String.fromCharCode(code);
211
- // }
212
- }
213
- return utf8.decode(str);
160
+ * Should be called to get utf8 from it's hex representation
161
+ *
162
+ * @public
163
+ * @static
164
+ * @method hexToUtf8
165
+ * @param {String} hex
166
+ * @returns {String} ascii string representation of hex value
167
+ */
168
+ const hexToUtf8 = (hex) => {
169
+ if (!isHexStrict(hex)) throw new Error(`The parameter "${hex}" must be a valid HEX string.`);
170
+ let str = "";
171
+ let code = 0;
172
+ hex = hex.replace(/^0x/i, "");
173
+ hex = hex.replace(/^(?:00)*/, "");
174
+ hex = hex.split("").reverse().join("");
175
+ hex = hex.replace(/^(?:00)*/, "");
176
+ hex = hex.split("").reverse().join("");
177
+ const l = hex.length;
178
+ for (let i = 0; i < l; i += 2) {
179
+ code = parseInt(hex.substr(i, 2), 16);
180
+ str += String.fromCharCode(code);
181
+ }
182
+ return utf8.decode(str);
214
183
  };
215
184
  /**
216
- * Converts value to number representation
217
- *
218
- * @public
219
- * @static
220
- * @method hexToNumber
221
- * @param {String|Number|BN} value
222
- * @returns {Number}
223
- */
224
- export const hexToNumber = (value) => {
225
- if (!value) {
226
- return 0;
227
- }
228
- return toBN(value).toNumber();
185
+ * Converts value to number representation
186
+ *
187
+ * @public
188
+ * @static
189
+ * @method hexToNumber
190
+ * @param {String|Number|BN} value
191
+ * @returns {Number}
192
+ */
193
+ const hexToNumber = (value) => {
194
+ if (!value) return 0;
195
+ return toBN(value).toNumber();
229
196
  };
230
197
  /**
231
- * Converts value to hex representation
232
- *
233
- * @public
234
- * @static
235
- * @method numberToHex
236
- * @param {String|Number|BN} value
237
- * @returns {String}
238
- */
239
- export const numberToHex = (value) => {
240
- if (isNull(value) || typeof value === 'undefined') {
241
- return value;
242
- }
243
- // eslint-disable-next-line no-restricted-globals
244
- if (!isFinite(value) && !isHex(value)) {
245
- throw new Error(`Given input "${value}" is not a number.`);
246
- }
247
- const num = toBN(value);
248
- const result = num.toString(16);
249
- return num.lt(new BN(0)) ? `-0x${result.substr(1)}` : `0x${result}`;
198
+ * Converts value to hex representation
199
+ *
200
+ * @public
201
+ * @static
202
+ * @method numberToHex
203
+ * @param {String|Number|BN} value
204
+ * @returns {String}
205
+ */
206
+ const numberToHex = (value) => {
207
+ if (isNull(value) || typeof value === "undefined") return value;
208
+ if (!isFinite(value) && !isHex(value)) throw new Error(`Given input "${value}" is not a number.`);
209
+ const num = toBN(value);
210
+ const result = num.toString(16);
211
+ return num.lt(new BN(0)) ? `-0x${result.substr(1)}` : `0x${result}`;
250
212
  };
251
213
  /**
252
- * Convert a byte array to a hex string
253
- * Note: Implementation from crypto-js
254
- *
255
- * @public
256
- * @static
257
- * @method bytesToHex
258
- * @param {Array} bytes
259
- * @returns {String} the hex string
260
- */
261
- export const bytesToHex = (bytes) => {
262
- const hex = [];
263
- for (let i = 0; i < bytes.length; i++) {
264
- hex.push((bytes[i] >>> 4).toString(16));
265
- hex.push((bytes[i] & 0xf).toString(16));
266
- }
267
- return `0x${hex.join('')}`;
214
+ * Convert a byte array to a hex string
215
+ * Note: Implementation from crypto-js
216
+ *
217
+ * @public
218
+ * @static
219
+ * @method bytesToHex
220
+ * @param {Array} bytes
221
+ * @returns {String} the hex string
222
+ */
223
+ const bytesToHex = (bytes) => {
224
+ const hex = [];
225
+ for (let i = 0; i < bytes.length; i++) {
226
+ hex.push((bytes[i] >>> 4).toString(16));
227
+ hex.push((bytes[i] & 15).toString(16));
228
+ }
229
+ return `0x${hex.join("")}`;
268
230
  };
269
231
  /**
270
- * Convert a hex string to a byte array
271
- * Note: Implementation from crypto-js
272
- *
273
- * @public
274
- * @static
275
- * @method hexToBytes
276
- * @param {String} hex
277
- * @returns {Array} the byte array
278
- */
279
- export const hexToBytes = (hex) => {
280
- hex = hex.toString(16);
281
- if (!isHex(hex)) {
282
- throw new Error(`Given value "${hex}" is not a valid hex string.`);
283
- }
284
- hex = hex.replace(/^0x/i, '');
285
- hex = hex.length % 2 ? `0${hex}` : hex;
286
- const bytes = [];
287
- for (let c = 0; c < hex.length; c += 2) {
288
- bytes.push(parseInt(hex.substr(c, 2), 16));
289
- }
290
- return bytes;
232
+ * Convert a hex string to a byte array
233
+ * Note: Implementation from crypto-js
234
+ *
235
+ * @public
236
+ * @static
237
+ * @method hexToBytes
238
+ * @param {String} hex
239
+ * @returns {Array} the byte array
240
+ */
241
+ const hexToBytes = (hex) => {
242
+ hex = hex.toString(16);
243
+ if (!isHex(hex)) throw new Error(`Given value "${hex}" is not a valid hex string.`);
244
+ hex = hex.replace(/^0x/i, "");
245
+ hex = hex.length % 2 ? `0${hex}` : hex;
246
+ const bytes = [];
247
+ for (let c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16));
248
+ return bytes;
291
249
  };
292
250
  /**
293
- * Auto converts any given value into it's hex representation.
294
- * And even stringify objects before.
295
- *
296
- * @public
297
- * @static
298
- * @method toHex
299
- * @param {String|Number|BN|Object|TypedArray|Buffer} value
300
- * @param {Boolean} returnType
301
- * @returns {String}
302
- */
303
- export const toHex = (value, returnType = false) => {
304
- if (isUint8Array(value) || Buffer.isBuffer(value)) {
305
- return returnType ? 'bytes' : bytesToHex(value);
306
- }
307
- if (isBase58btc(value)) {
308
- return returnType ? 'bytes' : bytesToHex(base58btc.decode(value));
309
- }
310
- if (isBoolean(value)) {
311
- // eslint-disable-next-line no-nested-ternary
312
- return returnType ? 'bool' : value ? '0x01' : '0x00';
313
- }
314
- if (isObject(value) && !isBigNumber(value) && !isBN(value)) {
315
- return returnType ? 'string' : utf8ToHex(JSON.stringify(value));
316
- }
317
- // if its a negative number, pass it through numberToHex
318
- if (typeof value === 'string') {
319
- if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) {
320
- return returnType ? 'int256' : numberToHex(value);
321
- }
322
- if (value.indexOf('0x') === 0 || value.indexOf('0X') === 0) {
323
- return returnType ? 'bytes' : value;
324
- }
325
- // TODO: some edge case may be not properly handled here
326
- return returnType ? 'string' : utf8ToHex(value);
327
- }
328
- // eslint-disable-next-line no-nested-ternary
329
- return returnType ? (+value < 0 ? 'int256' : 'uint256') : numberToHex(value);
251
+ * Auto converts any given value into it's hex representation.
252
+ * And even stringify objects before.
253
+ *
254
+ * @public
255
+ * @static
256
+ * @method toHex
257
+ * @param {String|Number|BN|Object|TypedArray|Buffer} value
258
+ * @param {Boolean} returnType
259
+ * @returns {String}
260
+ */
261
+ const toHex = (value, returnType = false) => {
262
+ if (isUint8Array(value) || Buffer.isBuffer(value)) return returnType ? "bytes" : bytesToHex(value);
263
+ if (isBase58btc(value)) return returnType ? "bytes" : bytesToHex(base58btc.decode(value));
264
+ if (isBoolean(value)) return returnType ? "bool" : value ? "0x01" : "0x00";
265
+ if (isObject(value) && !isBigNumber(value) && !isBN(value)) return returnType ? "string" : utf8ToHex(JSON.stringify(value));
266
+ if (typeof value === "string") {
267
+ if (value.indexOf("-0x") === 0 || value.indexOf("-0X") === 0) return returnType ? "int256" : numberToHex(value);
268
+ if (value.indexOf("0x") === 0 || value.indexOf("0X") === 0) return returnType ? "bytes" : value;
269
+ return returnType ? "string" : utf8ToHex(value);
270
+ }
271
+ return returnType ? +value < 0 ? "int256" : "uint256" : numberToHex(value);
330
272
  };
331
- export const numberToString = (arg) => {
332
- if (typeof arg === 'string') {
333
- if (!arg.match(/^-?[0-9.]+$/)) {
334
- throw new Error(`Invalid value '${arg}' while converting to string, should be a number matching (^-?[0-9.]+).`);
335
- }
336
- return arg;
337
- }
338
- if (typeof arg === 'number') {
339
- if (Number.isInteger(arg) && arg > 0) {
340
- return Number(arg).toLocaleString('fullwide', { useGrouping: false });
341
- }
342
- return String(arg);
343
- }
344
- if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) {
345
- if (arg.toPrecision) {
346
- return String(arg.toPrecision());
347
- }
348
- return arg.toString(10);
349
- }
350
- throw new Error(`while converting number to string, invalid number value '${arg}' type ${typeof arg}.`);
273
+ const numberToString = (arg) => {
274
+ if (typeof arg === "string") {
275
+ if (!arg.match(/^-?[0-9.]+$/)) throw new Error(`Invalid value '${arg}' while converting to string, should be a number matching (^-?[0-9.]+).`);
276
+ return arg;
277
+ }
278
+ if (typeof arg === "number") {
279
+ if (Number.isInteger(arg) && arg > 0) return Number(arg).toLocaleString("fullwide", { useGrouping: false });
280
+ return String(arg);
281
+ }
282
+ if (typeof arg === "object" && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) {
283
+ if (arg.toPrecision) return String(arg.toPrecision());
284
+ return arg.toString(10);
285
+ }
286
+ throw new Error(`while converting number to string, invalid number value '${arg}' type ${typeof arg}.`);
351
287
  };
352
288
  /**
353
- * Format a big number to human readable number, such as 1_0000_0000_0000_000 => 1 Token
354
- */
355
- export const fromUnitToToken = (input, decimal = 18, optionsInput = {}) => {
356
- let unit = toBN(input);
357
- const negative = unit.lt(zero);
358
- const base = toBN(`1${'0'.repeat(decimal)}`, 10);
359
- const baseLength = base.toString(10).length - 1 || 1;
360
- const options = optionsInput || {};
361
- if (negative) {
362
- unit = unit.mul(negative1);
363
- }
364
- let fraction = unit.mod(base).toString(10);
365
- while (fraction.length < baseLength) {
366
- fraction = `0${fraction}`;
367
- }
368
- if (!options.pad) {
369
- // eslint-disable-next-line prefer-destructuring
370
- fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
371
- }
372
- let whole = unit.div(base).toString(10);
373
- if (options.commify) {
374
- whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
375
- }
376
- let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;
377
- if (negative) {
378
- value = `-${value}`;
379
- }
380
- return value;
289
+ * Format a big number to human readable number, such as 1_0000_0000_0000_000 => 1 Token
290
+ */
291
+ const fromUnitToToken = (input, decimal = 18, optionsInput = {}) => {
292
+ let unit = toBN(input);
293
+ const negative = unit.lt(zero);
294
+ const base = toBN(`1${"0".repeat(decimal)}`, 10);
295
+ const baseLength = base.toString(10).length - 1 || 1;
296
+ const options = optionsInput || {};
297
+ if (negative) unit = unit.mul(negative1);
298
+ let fraction = unit.mod(base).toString(10);
299
+ while (fraction.length < baseLength) fraction = `0${fraction}`;
300
+ if (!options.pad) fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
301
+ let whole = unit.div(base).toString(10);
302
+ if (options.commify) whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
303
+ let value = `${whole}${fraction === "0" ? "" : `.${fraction}`}`;
304
+ if (negative) value = `-${value}`;
305
+ return value;
381
306
  };
382
307
  /**
383
- * Convert human readable token number to big number instance
384
- */
385
- export const fromTokenToUnit = (input, decimal = 18) => {
386
- let token = numberToString(input);
387
- const base = toBN(`1${'0'.repeat(decimal)}`, 10);
388
- const baseLength = base.toString(10).length - 1 || 1;
389
- // Is it negative?
390
- const negative = token.substring(0, 1) === '-';
391
- if (negative) {
392
- token = token.substring(1);
393
- }
394
- if (token === '.') {
395
- throw new Error(`error converting token ${input} to unit, invalid value`);
396
- }
397
- // Split it into a whole and fractional part
398
- const comps = token.split('.');
399
- if (comps.length > 2) {
400
- throw new Error(`error converting token ${input} to unit, too many decimal points`);
401
- }
402
- let whole = comps[0];
403
- let fraction = comps[1];
404
- if (!whole) {
405
- whole = '0';
406
- }
407
- if (!fraction) {
408
- fraction = '0';
409
- }
410
- if (fraction.length > baseLength) {
411
- throw new Error(`error converting token ${input} to unit, too many decimal places`);
412
- }
413
- while (fraction.length < baseLength) {
414
- fraction += '0';
415
- }
416
- whole = new BN(whole);
417
- fraction = new BN(fraction);
418
- let unit = whole.mul(base).add(fraction);
419
- if (negative) {
420
- unit = unit.mul(negative1);
421
- }
422
- return new BN(unit.toString(10), 10);
308
+ * Convert human readable token number to big number instance
309
+ */
310
+ const fromTokenToUnit = (input, decimal = 18) => {
311
+ let token = numberToString(input);
312
+ const base = toBN(`1${"0".repeat(decimal)}`, 10);
313
+ const baseLength = base.toString(10).length - 1 || 1;
314
+ const negative = token.substring(0, 1) === "-";
315
+ if (negative) token = token.substring(1);
316
+ if (token === ".") throw new Error(`error converting token ${input} to unit, invalid value`);
317
+ const comps = token.split(".");
318
+ if (comps.length > 2) throw new Error(`error converting token ${input} to unit, too many decimal points`);
319
+ let whole = comps[0];
320
+ let fraction = comps[1];
321
+ if (!whole) whole = "0";
322
+ if (!fraction) fraction = "0";
323
+ if (fraction.length > baseLength) throw new Error(`error converting token ${input} to unit, too many decimal places`);
324
+ while (fraction.length < baseLength) fraction += "0";
325
+ whole = new BN(whole);
326
+ fraction = new BN(fraction);
327
+ let unit = whole.mul(base).add(fraction);
328
+ if (negative) unit = unit.mul(negative1);
329
+ return new BN(unit.toString(10), 10);
423
330
  };
424
331
  /**
425
- * Validates if a value is an Uint8Array.
426
- */
427
- export function isUint8Array(value) {
428
- return Object.prototype.toString.call(value) === '[object Uint8Array]';
332
+ * Validates if a value is an Uint8Array.
333
+ */
334
+ function isUint8Array(value) {
335
+ return Object.prototype.toString.call(value) === "[object Uint8Array]";
429
336
  }
430
337
  /**
431
- * Generate a random UUID
432
- */
433
- export function UUID() {
434
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
435
- const r = (Math.random() * 16) | 0;
436
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
437
- return v.toString(16);
438
- });
338
+ * Generate a random UUID
339
+ */
340
+ function UUID() {
341
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
342
+ const r = Math.random() * 16 | 0;
343
+ return (c === "x" ? r : r & 3 | 8).toString(16);
344
+ });
439
345
  }
440
346
  /**
441
- * Check if a string is valid UUID
442
- */
443
- export function isUUID(str) {
444
- return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(str);
347
+ * Check if a string is valid UUID
348
+ */
349
+ function isUUID(str) {
350
+ return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(str);
445
351
  }
446
352
  /**
447
- * Convert input to Uint8Array on best effort, base64 node supported
448
- */
449
- export function toUint8Array(v) {
450
- let vb = null;
451
- if ([null, undefined, ''].includes(v)) {
452
- vb = new Uint8Array();
453
- }
454
- else if (Buffer.isBuffer(v)) {
455
- vb = new Uint8Array(v);
456
- }
457
- else if (isHexStrict(v)) {
458
- vb = new Uint8Array(hexToBytes(v));
459
- }
460
- else if (isUint8Array(v)) {
461
- vb = new Uint8Array(v);
462
- }
463
- else if (isBase58btc(v)) {
464
- vb = new Uint8Array(base58btc.decode(v));
465
- }
466
- else if (typeof v === 'string') {
467
- vb = new Uint8Array(hexToBytes(toHex(v)));
468
- }
469
- else {
470
- throw new Error(`Unsupported input type ${typeof v} detected for toBuffer, only Uint8Array/Buffer/Hex/Base58 are supported`);
471
- }
472
- return vb;
353
+ * Convert input to Uint8Array on best effort, base64 node supported
354
+ */
355
+ function toUint8Array(v) {
356
+ let vb = null;
357
+ if ([
358
+ null,
359
+ void 0,
360
+ ""
361
+ ].includes(v)) vb = new Uint8Array();
362
+ else if (Buffer.isBuffer(v)) vb = new Uint8Array(v);
363
+ else if (isHexStrict(v)) vb = new Uint8Array(hexToBytes(v));
364
+ else if (isUint8Array(v)) vb = new Uint8Array(v);
365
+ else if (isBase58btc(v)) vb = new Uint8Array(base58btc.decode(v));
366
+ else if (typeof v === "string") vb = new Uint8Array(hexToBytes(toHex(v)));
367
+ else throw new Error(`Unsupported input type ${typeof v} detected for toBuffer, only Uint8Array/Buffer/Hex/Base58 are supported`);
368
+ return vb;
473
369
  }
474
370
  /**
475
- * Convert input to Buffer on best effort, base64 not supported
476
- */
477
- export function toBuffer(v) {
478
- return Buffer.from(toUint8Array(v));
371
+ * Convert input to Buffer on best effort, base64 not supported
372
+ */
373
+ function toBuffer(v) {
374
+ return Buffer.from(toUint8Array(v));
479
375
  }
480
376
  /**
481
- * Convert input to base58btc format on best effort
482
- */
483
- export function toBase58(v) {
484
- const buf = base58btc.encode(toUint8Array(v));
485
- return Buffer.from(buf).toString('utf-8');
377
+ * Convert input to base58btc format on best effort
378
+ */
379
+ function toBase58(v) {
380
+ const buf = base58btc.encode(toUint8Array(v));
381
+ return Buffer.from(buf).toString("utf-8");
486
382
  }
487
383
  /**
488
- * Decode base58 string
489
- */
490
- export function fromBase58(v) {
491
- if (isBase58btc(v) === false) {
492
- throw new Error('fromBase58 expect strict base58 encoded string as input');
493
- }
494
- return Buffer.from(base58btc.decode(v));
384
+ * Decode base58 string
385
+ */
386
+ function fromBase58(v) {
387
+ if (isBase58btc(v) === false) throw new Error("fromBase58 expect strict base58 encoded string as input");
388
+ return Buffer.from(base58btc.decode(v));
495
389
  }
496
390
  /**
497
- * Convert input to base64 format
498
- */
499
- export function toBase64(v, escape = true) {
500
- const encoded = base64.encode(toBuffer(v));
501
- return escape ? base64.escape(encoded) : encoded;
391
+ * Convert input to base64 format
392
+ */
393
+ function toBase64(v, escape = true) {
394
+ const encoded = base64.encode(toBuffer(v));
395
+ return escape ? base64.escape(encoded) : encoded;
502
396
  }
503
397
  /**
504
- * Decode base64(base64_url) string to buffer
505
- */
506
- export function fromBase64(v) {
507
- if (typeof v !== 'string') {
508
- throw new Error('fromBase64 requires input to be a string');
509
- }
510
- return Buffer.from(base64.unescape(v), 'base64');
398
+ * Decode base64(base64_url) string to buffer
399
+ */
400
+ function fromBase64(v) {
401
+ if (typeof v !== "string") throw new Error("fromBase64 requires input to be a string");
402
+ return Buffer.from(base64.unescape(v), "base64");
511
403
  }
512
404
  /**
513
- * Convert did to address: remove `did:abt:` prefix
514
- */
515
- export function toAddress(did) {
516
- return did.replace(DID_PREFIX, '');
405
+ * Convert did to address: remove `did:abt:` prefix
406
+ */
407
+ function toAddress(did) {
408
+ return did.replace(DID_PREFIX, "");
517
409
  }
518
410
  /**
519
- * Convert address to did: prepend `did:abt:` prefix
520
- */
521
- export function toDid(address) {
522
- return `${DID_PREFIX}${toAddress(address)}`;
411
+ * Convert address to did: prepend `did:abt:` prefix
412
+ */
413
+ function toDid(address) {
414
+ return `${DID_PREFIX}${toAddress(address)}`;
523
415
  }
524
- export function isSameDid(a, b) {
525
- return toAddress(a).toLowerCase() === toAddress(b).toLowerCase();
416
+ function isSameDid(a, b) {
417
+ return toAddress(a).toLowerCase() === toAddress(b).toLowerCase();
526
418
  }
527
- export function formatTxType(type) {
528
- return upperFirst(camelCase(type));
419
+ function formatTxType(type) {
420
+ return upperFirst(camelCase(type));
529
421
  }
422
+
423
+ //#endregion
424
+ export { BN, UUID, bytesToHex, formatTxType, fromBase58, fromBase64, fromTokenToUnit, fromUnitToToken, hexToBytes, hexToNumber, hexToUtf8, isBN, isBase58btc, isBigNumber, isHex, isHexPrefixed, isHexStrict, isSameDid, isUUID, isUint8Array, leftPad, numberToBN, numberToHex, numberToString, rightPad, stripHexPrefix, toAddress, toBN, toBase58, toBase64, toBuffer, toDid, toHex, toUint8Array, utf8ToHex };