@talismn/util 0.1.5 → 0.1.7

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 (39) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/{BigMath.d.ts → declarations/src/BigMath.d.ts} +0 -0
  3. package/dist/declarations/src/FunctionPropertyNames.d.ts +8 -0
  4. package/dist/{blake2Concat.d.ts → declarations/src/blake2Concat.d.ts} +0 -0
  5. package/dist/declarations/src/classNames.d.ts +3 -0
  6. package/dist/{decodeAnyAddress.d.ts → declarations/src/decodeAnyAddress.d.ts} +0 -0
  7. package/dist/{encodeAnyAddress.d.ts → declarations/src/encodeAnyAddress.d.ts} +0 -0
  8. package/dist/{formatDecimals.d.ts → declarations/src/formatDecimals.d.ts} +0 -0
  9. package/dist/{getBase64ImageUrl.d.ts → declarations/src/getBase64ImageUrl.d.ts} +0 -0
  10. package/dist/{hasOwnProperty.d.ts → declarations/src/hasOwnProperty.d.ts} +0 -0
  11. package/dist/{index.d.ts → declarations/src/index.d.ts} +2 -1
  12. package/dist/{isArrayOf.d.ts → declarations/src/isArrayOf.d.ts} +0 -0
  13. package/dist/{planckToTokens.d.ts → declarations/src/planckToTokens.d.ts} +0 -0
  14. package/dist/{sleep.d.ts → declarations/src/sleep.d.ts} +0 -0
  15. package/dist/{throwAfter.d.ts → declarations/src/throwAfter.d.ts} +0 -0
  16. package/dist/{tokensToPlanck.d.ts → declarations/src/tokensToPlanck.d.ts} +0 -0
  17. package/dist/{twox64Concat.d.ts → declarations/src/twox64Concat.d.ts} +0 -0
  18. package/dist/talismn-util.cjs.d.ts +1 -0
  19. package/dist/talismn-util.cjs.dev.js +176 -0
  20. package/dist/talismn-util.cjs.js +7 -0
  21. package/dist/talismn-util.cjs.prod.js +176 -0
  22. package/dist/talismn-util.esm.js +154 -0
  23. package/package.json +14 -13
  24. package/dist/BigMath.js +0 -34
  25. package/dist/FunctionPropertyNames.d.ts +0 -8
  26. package/dist/FunctionPropertyNames.js +0 -4
  27. package/dist/blake2Concat.js +0 -10
  28. package/dist/decodeAnyAddress.js +0 -19
  29. package/dist/encodeAnyAddress.js +0 -18
  30. package/dist/formatDecimals.js +0 -57
  31. package/dist/getBase64ImageUrl.js +0 -12
  32. package/dist/hasOwnProperty.js +0 -7
  33. package/dist/index.js +0 -30
  34. package/dist/isArrayOf.js +0 -9
  35. package/dist/planckToTokens.js +0 -16
  36. package/dist/sleep.js +0 -5
  37. package/dist/throwAfter.js +0 -5
  38. package/dist/tokensToPlanck.js +0 -16
  39. package/dist/twox64Concat.js +0 -10
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @talismn/util
2
2
 
3
+ ## 0.1.7
4
+
5
+ ### Patch Changes
6
+
7
+ - c651551c: build: move `@polkadot` dependencies to `peerDependencies`
8
+
9
+ ## 0.1.6
10
+
11
+ ### Patch Changes
12
+
13
+ - 8adc7f06: feat: switched build tool to preconstruct
14
+
3
15
  ## 0.1.5
4
16
 
5
17
  ### Patch Changes
@@ -0,0 +1,8 @@
1
+ export type FunctionPropertyNames<T> = {
2
+ [K in keyof T]: T[K] extends Function ? K : never;
3
+ }[keyof T];
4
+ export type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;
5
+ export type NonFunctionPropertyNames<T> = {
6
+ [K in keyof T]: T[K] extends Function ? never : K;
7
+ }[keyof T];
8
+ export type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
@@ -0,0 +1,3 @@
1
+ type ClassName = string | false | undefined | null;
2
+ export declare const classNames: (...args: ClassName[]) => string | undefined;
3
+ export {};
@@ -1,9 +1,10 @@
1
1
  export * from "./BigMath";
2
+ export * from "./FunctionPropertyNames";
2
3
  export * from "./blake2Concat";
4
+ export * from "./classNames";
3
5
  export * from "./decodeAnyAddress";
4
6
  export * from "./encodeAnyAddress";
5
7
  export * from "./formatDecimals";
6
- export * from "./FunctionPropertyNames";
7
8
  export * from "./getBase64ImageUrl";
8
9
  export * from "./hasOwnProperty";
9
10
  export * from "./isArrayOf";
File without changes
@@ -0,0 +1 @@
1
+ export * from "./declarations/src/index";
@@ -0,0 +1,176 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var util = require('@polkadot/util');
6
+ var utilCrypto = require('@polkadot/util-crypto');
7
+ var keyring = require('@polkadot/keyring');
8
+ var BigNumber = require('bignumber.js');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
+
12
+ var BigNumber__default = /*#__PURE__*/_interopDefault(BigNumber);
13
+
14
+ /**
15
+ * Javascript's `Math` library for `BigInt`.
16
+ * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
17
+ */
18
+ const BigMath = {
19
+ abs(x) {
20
+ return x < BigInt("0") ? -x : x;
21
+ },
22
+ sign(x) {
23
+ if (x === BigInt("0")) return BigInt("0");
24
+ return x < BigInt("0") ? BigInt("-1") : BigInt("1");
25
+ },
26
+ // TODO: Improve our babel/tsc config to let us use the `**` operator on bigint values.
27
+ // Error thrown: Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later. ts(2791)
28
+ // pow(base: bigint, exponent: bigint) {
29
+ // return base ** exponent
30
+ // },
31
+ min(value, ...values) {
32
+ for (const v of values) if (v < value) value = v;
33
+ return value;
34
+ },
35
+ max(value, ...values) {
36
+ for (const v of values) if (v > value) value = v;
37
+ return value;
38
+ }
39
+ };
40
+
41
+ const bitLength$1 = 128;
42
+ function blake2Concat(input) {
43
+ return util.u8aToHex(util.u8aConcat(utilCrypto.blake2AsU8a(input, bitLength$1), util.u8aToU8a(input)));
44
+ }
45
+
46
+ const classNames = (...args) => {
47
+ return args.filter(Boolean).join(" ") || undefined;
48
+ };
49
+
50
+ function decodeAnyAddress(encoded, ignoreChecksum, ss58Format) {
51
+ try {
52
+ return keyring.decodeAddress(encoded, ignoreChecksum, ss58Format);
53
+ } catch (error) {
54
+ if (typeof encoded !== "string") throw error;
55
+ if (!utilCrypto.isEthereumAddress(encoded)) throw error;
56
+ return util.hexToU8a(encoded.slice("0x".length));
57
+ }
58
+ }
59
+
60
+ function encodeAnyAddress(key, ss58Format) {
61
+ try {
62
+ return keyring.encodeAddress(key, ss58Format);
63
+ } catch (error) {
64
+ if (typeof key !== "string") throw error;
65
+ if (!utilCrypto.isEthereumAddress(key)) throw error;
66
+ return utilCrypto.ethereumEncode(key);
67
+ }
68
+ }
69
+
70
+ const MIN_DIGITS = 4; // less truncates more than what compact formating is
71
+ const MAX_DECIMALS_FORMAT = 12;
72
+
73
+ /**
74
+ * Custom decimal number formatting for Talisman
75
+ * note that the NumberFormat().format() call is the ressource heavy part, it's not worth trying to optimize other parts
76
+ * @param num input number
77
+ * @param digits number of significant digits to display
78
+ * @param locale locale used to format the number
79
+ * @param options formatting options
80
+ * @returns the formatted value
81
+ */
82
+ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US") => {
83
+ if (num === null || num === undefined) return "";
84
+ if (digits < MIN_DIGITS) digits = MIN_DIGITS;
85
+ const value = new BigNumber__default["default"](num);
86
+ // very small numbers should display "< 0.0001"
87
+ const minDisplayVal = 1 / Math.pow(10, digits);
88
+ if (value.gt(0) && value.lt(minDisplayVal)) return `< ${formatDecimals(minDisplayVal)}`;
89
+
90
+ // count digits
91
+ const flooredValue = value.integerValue();
92
+ const intDigits = flooredValue.isEqualTo(0) ? 0 : flooredValue.toString().length;
93
+
94
+ // we never want to display a rounded up value
95
+ // to prevent JS default rounding, we will remove/truncate insignificant digits ourselves before formatting
96
+ let truncatedValue = value;
97
+ //remove insignificant fraction digits
98
+ const excessFractionDigitsPow10 = new BigNumber__default["default"](10).pow(digits > intDigits ? digits - intDigits : 0);
99
+ truncatedValue = truncatedValue.multipliedBy(excessFractionDigitsPow10).integerValue().dividedBy(excessFractionDigitsPow10);
100
+
101
+ //remove insignificant integer digits
102
+ const excessIntegerDigits = new BigNumber__default["default"](intDigits > digits ? intDigits - digits : 0);
103
+ const excessIntegerDigitsPow10 = new BigNumber__default["default"](10).pow(excessIntegerDigits);
104
+ if (excessIntegerDigits.gt(0)) truncatedValue = truncatedValue.dividedBy(excessIntegerDigitsPow10).integerValue().multipliedBy(excessIntegerDigitsPow10);
105
+
106
+ // format
107
+
108
+ return Intl.NumberFormat(locale, {
109
+ //compact notation (K, M, B) if above 9999
110
+ notation: truncatedValue.gt(9999) ? "compact" : "standard",
111
+ maximumSignificantDigits: digits + (truncatedValue.lt(1) ? 1 : 0),
112
+ ...options
113
+ }).format(truncatedValue.toNumber());
114
+ };
115
+
116
+ const getBase64ImageUrl = base64 => {
117
+ const match = /^data:([^;]*?);base64,(.*?)$/.exec(base64);
118
+ if (!match) return null;
119
+ const buffer = Buffer.from(match[2], "base64");
120
+ const blob = new Blob([new Uint8Array(buffer, 0, buffer.length)], {
121
+ type: match[1]
122
+ });
123
+ return URL.createObjectURL(blob);
124
+ };
125
+
126
+ function hasOwnProperty(obj, prop) {
127
+ if (typeof obj !== "object") return false;
128
+ if (obj === null) return false;
129
+ return prop in obj;
130
+ }
131
+
132
+ function isArrayOf(array, func) {
133
+ if (array.length > 0 && array[0] instanceof func) return true;
134
+ return false;
135
+ }
136
+
137
+ function planckToTokens(planck, tokenDecimals) {
138
+ if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
139
+ const base = new BigNumber__default["default"](10);
140
+ const exponent = new BigNumber__default["default"](tokenDecimals).negated();
141
+ const multiplier = base.pow(exponent);
142
+ return new BigNumber__default["default"](planck).multipliedBy(multiplier).toString(10);
143
+ }
144
+
145
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
146
+
147
+ const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(reason), ms));
148
+
149
+ function tokensToPlanck(tokens, tokenDecimals) {
150
+ if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
151
+ const base = new BigNumber__default["default"](10);
152
+ const exponent = new BigNumber__default["default"](tokenDecimals);
153
+ const multiplier = base.pow(exponent);
154
+ return new BigNumber__default["default"](tokens).multipliedBy(multiplier).toString(10);
155
+ }
156
+
157
+ const bitLength = 64;
158
+ function twox64Concat(input) {
159
+ return util.u8aToHex(util.u8aConcat(utilCrypto.xxhashAsU8a(input, bitLength), util.u8aToU8a(input)));
160
+ }
161
+
162
+ exports.BigMath = BigMath;
163
+ exports.MAX_DECIMALS_FORMAT = MAX_DECIMALS_FORMAT;
164
+ exports.blake2Concat = blake2Concat;
165
+ exports.classNames = classNames;
166
+ exports.decodeAnyAddress = decodeAnyAddress;
167
+ exports.encodeAnyAddress = encodeAnyAddress;
168
+ exports.formatDecimals = formatDecimals;
169
+ exports.getBase64ImageUrl = getBase64ImageUrl;
170
+ exports.hasOwnProperty = hasOwnProperty;
171
+ exports.isArrayOf = isArrayOf;
172
+ exports.planckToTokens = planckToTokens;
173
+ exports.sleep = sleep;
174
+ exports.throwAfter = throwAfter;
175
+ exports.tokensToPlanck = tokensToPlanck;
176
+ exports.twox64Concat = twox64Concat;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./talismn-util.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./talismn-util.cjs.dev.js");
7
+ }
@@ -0,0 +1,176 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var util = require('@polkadot/util');
6
+ var utilCrypto = require('@polkadot/util-crypto');
7
+ var keyring = require('@polkadot/keyring');
8
+ var BigNumber = require('bignumber.js');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
+
12
+ var BigNumber__default = /*#__PURE__*/_interopDefault(BigNumber);
13
+
14
+ /**
15
+ * Javascript's `Math` library for `BigInt`.
16
+ * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
17
+ */
18
+ const BigMath = {
19
+ abs(x) {
20
+ return x < BigInt("0") ? -x : x;
21
+ },
22
+ sign(x) {
23
+ if (x === BigInt("0")) return BigInt("0");
24
+ return x < BigInt("0") ? BigInt("-1") : BigInt("1");
25
+ },
26
+ // TODO: Improve our babel/tsc config to let us use the `**` operator on bigint values.
27
+ // Error thrown: Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later. ts(2791)
28
+ // pow(base: bigint, exponent: bigint) {
29
+ // return base ** exponent
30
+ // },
31
+ min(value, ...values) {
32
+ for (const v of values) if (v < value) value = v;
33
+ return value;
34
+ },
35
+ max(value, ...values) {
36
+ for (const v of values) if (v > value) value = v;
37
+ return value;
38
+ }
39
+ };
40
+
41
+ const bitLength$1 = 128;
42
+ function blake2Concat(input) {
43
+ return util.u8aToHex(util.u8aConcat(utilCrypto.blake2AsU8a(input, bitLength$1), util.u8aToU8a(input)));
44
+ }
45
+
46
+ const classNames = (...args) => {
47
+ return args.filter(Boolean).join(" ") || undefined;
48
+ };
49
+
50
+ function decodeAnyAddress(encoded, ignoreChecksum, ss58Format) {
51
+ try {
52
+ return keyring.decodeAddress(encoded, ignoreChecksum, ss58Format);
53
+ } catch (error) {
54
+ if (typeof encoded !== "string") throw error;
55
+ if (!utilCrypto.isEthereumAddress(encoded)) throw error;
56
+ return util.hexToU8a(encoded.slice("0x".length));
57
+ }
58
+ }
59
+
60
+ function encodeAnyAddress(key, ss58Format) {
61
+ try {
62
+ return keyring.encodeAddress(key, ss58Format);
63
+ } catch (error) {
64
+ if (typeof key !== "string") throw error;
65
+ if (!utilCrypto.isEthereumAddress(key)) throw error;
66
+ return utilCrypto.ethereumEncode(key);
67
+ }
68
+ }
69
+
70
+ const MIN_DIGITS = 4; // less truncates more than what compact formating is
71
+ const MAX_DECIMALS_FORMAT = 12;
72
+
73
+ /**
74
+ * Custom decimal number formatting for Talisman
75
+ * note that the NumberFormat().format() call is the ressource heavy part, it's not worth trying to optimize other parts
76
+ * @param num input number
77
+ * @param digits number of significant digits to display
78
+ * @param locale locale used to format the number
79
+ * @param options formatting options
80
+ * @returns the formatted value
81
+ */
82
+ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US") => {
83
+ if (num === null || num === undefined) return "";
84
+ if (digits < MIN_DIGITS) digits = MIN_DIGITS;
85
+ const value = new BigNumber__default["default"](num);
86
+ // very small numbers should display "< 0.0001"
87
+ const minDisplayVal = 1 / Math.pow(10, digits);
88
+ if (value.gt(0) && value.lt(minDisplayVal)) return `< ${formatDecimals(minDisplayVal)}`;
89
+
90
+ // count digits
91
+ const flooredValue = value.integerValue();
92
+ const intDigits = flooredValue.isEqualTo(0) ? 0 : flooredValue.toString().length;
93
+
94
+ // we never want to display a rounded up value
95
+ // to prevent JS default rounding, we will remove/truncate insignificant digits ourselves before formatting
96
+ let truncatedValue = value;
97
+ //remove insignificant fraction digits
98
+ const excessFractionDigitsPow10 = new BigNumber__default["default"](10).pow(digits > intDigits ? digits - intDigits : 0);
99
+ truncatedValue = truncatedValue.multipliedBy(excessFractionDigitsPow10).integerValue().dividedBy(excessFractionDigitsPow10);
100
+
101
+ //remove insignificant integer digits
102
+ const excessIntegerDigits = new BigNumber__default["default"](intDigits > digits ? intDigits - digits : 0);
103
+ const excessIntegerDigitsPow10 = new BigNumber__default["default"](10).pow(excessIntegerDigits);
104
+ if (excessIntegerDigits.gt(0)) truncatedValue = truncatedValue.dividedBy(excessIntegerDigitsPow10).integerValue().multipliedBy(excessIntegerDigitsPow10);
105
+
106
+ // format
107
+
108
+ return Intl.NumberFormat(locale, {
109
+ //compact notation (K, M, B) if above 9999
110
+ notation: truncatedValue.gt(9999) ? "compact" : "standard",
111
+ maximumSignificantDigits: digits + (truncatedValue.lt(1) ? 1 : 0),
112
+ ...options
113
+ }).format(truncatedValue.toNumber());
114
+ };
115
+
116
+ const getBase64ImageUrl = base64 => {
117
+ const match = /^data:([^;]*?);base64,(.*?)$/.exec(base64);
118
+ if (!match) return null;
119
+ const buffer = Buffer.from(match[2], "base64");
120
+ const blob = new Blob([new Uint8Array(buffer, 0, buffer.length)], {
121
+ type: match[1]
122
+ });
123
+ return URL.createObjectURL(blob);
124
+ };
125
+
126
+ function hasOwnProperty(obj, prop) {
127
+ if (typeof obj !== "object") return false;
128
+ if (obj === null) return false;
129
+ return prop in obj;
130
+ }
131
+
132
+ function isArrayOf(array, func) {
133
+ if (array.length > 0 && array[0] instanceof func) return true;
134
+ return false;
135
+ }
136
+
137
+ function planckToTokens(planck, tokenDecimals) {
138
+ if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
139
+ const base = new BigNumber__default["default"](10);
140
+ const exponent = new BigNumber__default["default"](tokenDecimals).negated();
141
+ const multiplier = base.pow(exponent);
142
+ return new BigNumber__default["default"](planck).multipliedBy(multiplier).toString(10);
143
+ }
144
+
145
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
146
+
147
+ const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(reason), ms));
148
+
149
+ function tokensToPlanck(tokens, tokenDecimals) {
150
+ if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
151
+ const base = new BigNumber__default["default"](10);
152
+ const exponent = new BigNumber__default["default"](tokenDecimals);
153
+ const multiplier = base.pow(exponent);
154
+ return new BigNumber__default["default"](tokens).multipliedBy(multiplier).toString(10);
155
+ }
156
+
157
+ const bitLength = 64;
158
+ function twox64Concat(input) {
159
+ return util.u8aToHex(util.u8aConcat(utilCrypto.xxhashAsU8a(input, bitLength), util.u8aToU8a(input)));
160
+ }
161
+
162
+ exports.BigMath = BigMath;
163
+ exports.MAX_DECIMALS_FORMAT = MAX_DECIMALS_FORMAT;
164
+ exports.blake2Concat = blake2Concat;
165
+ exports.classNames = classNames;
166
+ exports.decodeAnyAddress = decodeAnyAddress;
167
+ exports.encodeAnyAddress = encodeAnyAddress;
168
+ exports.formatDecimals = formatDecimals;
169
+ exports.getBase64ImageUrl = getBase64ImageUrl;
170
+ exports.hasOwnProperty = hasOwnProperty;
171
+ exports.isArrayOf = isArrayOf;
172
+ exports.planckToTokens = planckToTokens;
173
+ exports.sleep = sleep;
174
+ exports.throwAfter = throwAfter;
175
+ exports.tokensToPlanck = tokensToPlanck;
176
+ exports.twox64Concat = twox64Concat;
@@ -0,0 +1,154 @@
1
+ import { u8aToHex, u8aConcat, u8aToU8a, hexToU8a } from '@polkadot/util';
2
+ import { blake2AsU8a, isEthereumAddress, ethereumEncode, xxhashAsU8a } from '@polkadot/util-crypto';
3
+ import { decodeAddress, encodeAddress } from '@polkadot/keyring';
4
+ import BigNumber from 'bignumber.js';
5
+
6
+ /**
7
+ * Javascript's `Math` library for `BigInt`.
8
+ * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
9
+ */
10
+ const BigMath = {
11
+ abs(x) {
12
+ return x < BigInt("0") ? -x : x;
13
+ },
14
+ sign(x) {
15
+ if (x === BigInt("0")) return BigInt("0");
16
+ return x < BigInt("0") ? BigInt("-1") : BigInt("1");
17
+ },
18
+ // TODO: Improve our babel/tsc config to let us use the `**` operator on bigint values.
19
+ // Error thrown: Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later. ts(2791)
20
+ // pow(base: bigint, exponent: bigint) {
21
+ // return base ** exponent
22
+ // },
23
+ min(value, ...values) {
24
+ for (const v of values) if (v < value) value = v;
25
+ return value;
26
+ },
27
+ max(value, ...values) {
28
+ for (const v of values) if (v > value) value = v;
29
+ return value;
30
+ }
31
+ };
32
+
33
+ const bitLength$1 = 128;
34
+ function blake2Concat(input) {
35
+ return u8aToHex(u8aConcat(blake2AsU8a(input, bitLength$1), u8aToU8a(input)));
36
+ }
37
+
38
+ const classNames = (...args) => {
39
+ return args.filter(Boolean).join(" ") || undefined;
40
+ };
41
+
42
+ function decodeAnyAddress(encoded, ignoreChecksum, ss58Format) {
43
+ try {
44
+ return decodeAddress(encoded, ignoreChecksum, ss58Format);
45
+ } catch (error) {
46
+ if (typeof encoded !== "string") throw error;
47
+ if (!isEthereumAddress(encoded)) throw error;
48
+ return hexToU8a(encoded.slice("0x".length));
49
+ }
50
+ }
51
+
52
+ function encodeAnyAddress(key, ss58Format) {
53
+ try {
54
+ return encodeAddress(key, ss58Format);
55
+ } catch (error) {
56
+ if (typeof key !== "string") throw error;
57
+ if (!isEthereumAddress(key)) throw error;
58
+ return ethereumEncode(key);
59
+ }
60
+ }
61
+
62
+ const MIN_DIGITS = 4; // less truncates more than what compact formating is
63
+ const MAX_DECIMALS_FORMAT = 12;
64
+
65
+ /**
66
+ * Custom decimal number formatting for Talisman
67
+ * note that the NumberFormat().format() call is the ressource heavy part, it's not worth trying to optimize other parts
68
+ * @param num input number
69
+ * @param digits number of significant digits to display
70
+ * @param locale locale used to format the number
71
+ * @param options formatting options
72
+ * @returns the formatted value
73
+ */
74
+ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US") => {
75
+ if (num === null || num === undefined) return "";
76
+ if (digits < MIN_DIGITS) digits = MIN_DIGITS;
77
+ const value = new BigNumber(num);
78
+ // very small numbers should display "< 0.0001"
79
+ const minDisplayVal = 1 / Math.pow(10, digits);
80
+ if (value.gt(0) && value.lt(minDisplayVal)) return `< ${formatDecimals(minDisplayVal)}`;
81
+
82
+ // count digits
83
+ const flooredValue = value.integerValue();
84
+ const intDigits = flooredValue.isEqualTo(0) ? 0 : flooredValue.toString().length;
85
+
86
+ // we never want to display a rounded up value
87
+ // to prevent JS default rounding, we will remove/truncate insignificant digits ourselves before formatting
88
+ let truncatedValue = value;
89
+ //remove insignificant fraction digits
90
+ const excessFractionDigitsPow10 = new BigNumber(10).pow(digits > intDigits ? digits - intDigits : 0);
91
+ truncatedValue = truncatedValue.multipliedBy(excessFractionDigitsPow10).integerValue().dividedBy(excessFractionDigitsPow10);
92
+
93
+ //remove insignificant integer digits
94
+ const excessIntegerDigits = new BigNumber(intDigits > digits ? intDigits - digits : 0);
95
+ const excessIntegerDigitsPow10 = new BigNumber(10).pow(excessIntegerDigits);
96
+ if (excessIntegerDigits.gt(0)) truncatedValue = truncatedValue.dividedBy(excessIntegerDigitsPow10).integerValue().multipliedBy(excessIntegerDigitsPow10);
97
+
98
+ // format
99
+
100
+ return Intl.NumberFormat(locale, {
101
+ //compact notation (K, M, B) if above 9999
102
+ notation: truncatedValue.gt(9999) ? "compact" : "standard",
103
+ maximumSignificantDigits: digits + (truncatedValue.lt(1) ? 1 : 0),
104
+ ...options
105
+ }).format(truncatedValue.toNumber());
106
+ };
107
+
108
+ const getBase64ImageUrl = base64 => {
109
+ const match = /^data:([^;]*?);base64,(.*?)$/.exec(base64);
110
+ if (!match) return null;
111
+ const buffer = Buffer.from(match[2], "base64");
112
+ const blob = new Blob([new Uint8Array(buffer, 0, buffer.length)], {
113
+ type: match[1]
114
+ });
115
+ return URL.createObjectURL(blob);
116
+ };
117
+
118
+ function hasOwnProperty(obj, prop) {
119
+ if (typeof obj !== "object") return false;
120
+ if (obj === null) return false;
121
+ return prop in obj;
122
+ }
123
+
124
+ function isArrayOf(array, func) {
125
+ if (array.length > 0 && array[0] instanceof func) return true;
126
+ return false;
127
+ }
128
+
129
+ function planckToTokens(planck, tokenDecimals) {
130
+ if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
131
+ const base = new BigNumber(10);
132
+ const exponent = new BigNumber(tokenDecimals).negated();
133
+ const multiplier = base.pow(exponent);
134
+ return new BigNumber(planck).multipliedBy(multiplier).toString(10);
135
+ }
136
+
137
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
138
+
139
+ const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(reason), ms));
140
+
141
+ function tokensToPlanck(tokens, tokenDecimals) {
142
+ if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
143
+ const base = new BigNumber(10);
144
+ const exponent = new BigNumber(tokenDecimals);
145
+ const multiplier = base.pow(exponent);
146
+ return new BigNumber(tokens).multipliedBy(multiplier).toString(10);
147
+ }
148
+
149
+ const bitLength = 64;
150
+ function twox64Concat(input) {
151
+ return u8aToHex(u8aConcat(xxhashAsU8a(input, bitLength), u8aToU8a(input)));
152
+ }
153
+
154
+ export { BigMath, MAX_DECIMALS_FORMAT, blake2Concat, classNames, decodeAnyAddress, encodeAnyAddress, formatDecimals, getBase64ImageUrl, hasOwnProperty, isArrayOf, planckToTokens, sleep, throwAfter, tokensToPlanck, twox64Concat };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talismn/util",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "author": "Talisman",
5
5
  "homepage": "https://talisman.xyz",
6
6
  "license": "UNLICENSED",
@@ -12,8 +12,8 @@
12
12
  "type": "git",
13
13
  "url": "https://github.com/talismansociety/talisman.git"
14
14
  },
15
- "main": "dist/index.js",
16
- "types": "dist/index.d.ts",
15
+ "main": "dist/talismn-util.cjs.js",
16
+ "module": "dist/talismn-util.esm.js",
17
17
  "files": [
18
18
  "/dist"
19
19
  ],
@@ -21,33 +21,34 @@
21
21
  "node": ">=14"
22
22
  },
23
23
  "scripts": {
24
- "dev": "tsc --watch --declarationMap",
25
- "build": "tsc --declarationMap",
26
- "build:packages:prod": "rm -rf dist && tsc",
27
- "prepack": "yarn build:packages:prod",
28
24
  "test": "jest",
29
25
  "lint": "eslint . --max-warnings 0",
30
26
  "clean": "rm -rf dist && rm -rf .turbo rm -rf node_modules"
31
27
  },
32
28
  "dependencies": {
33
- "@polkadot/keyring": "^10.1.7",
34
- "@polkadot/util": "^10.1.7",
35
- "@polkadot/util-crypto": "^10.1.7",
36
29
  "bignumber.js": "^9.1.0"
37
30
  },
38
31
  "devDependencies": {
39
- "@talismn/eslint-config": "^0.0.0",
40
- "@talismn/tsconfig": "^0.0.1",
32
+ "@polkadot/keyring": "^10.1.7",
33
+ "@polkadot/util": "^10.1.7",
34
+ "@polkadot/util-crypto": "^10.1.7",
35
+ "@talismn/eslint-config": "^0.0.1",
36
+ "@talismn/tsconfig": "^0.0.2",
41
37
  "@types/jest": "^27.5.1",
42
38
  "eslint": "^8.4.0",
43
39
  "jest": "^28.1.0",
44
40
  "ts-jest": "^28.0.2",
45
41
  "typescript": "^4.6.4"
46
42
  },
43
+ "peerDependencies": {
44
+ "@polkadot/keyring": "10.x",
45
+ "@polkadot/util": "10.x",
46
+ "@polkadot/util-crypto": "^10.x"
47
+ },
47
48
  "eslintConfig": {
48
49
  "root": true,
49
50
  "extends": [
50
- "@talismn/eslint-config"
51
+ "@talismn/eslint-config/base"
51
52
  ]
52
53
  }
53
54
  }
package/dist/BigMath.js DELETED
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BigMath = void 0;
4
- /**
5
- * Javascript's `Math` library for `BigInt`.
6
- * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
7
- */
8
- exports.BigMath = {
9
- abs(x) {
10
- return x < BigInt("0") ? -x : x;
11
- },
12
- sign(x) {
13
- if (x === BigInt("0"))
14
- return BigInt("0");
15
- return x < BigInt("0") ? BigInt("-1") : BigInt("1");
16
- },
17
- // TODO: Improve our babel/tsc config to let us use the `**` operator on bigint values.
18
- // Error thrown: Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later. ts(2791)
19
- // pow(base: bigint, exponent: bigint) {
20
- // return base ** exponent
21
- // },
22
- min(value, ...values) {
23
- for (const v of values)
24
- if (v < value)
25
- value = v;
26
- return value;
27
- },
28
- max(value, ...values) {
29
- for (const v of values)
30
- if (v > value)
31
- value = v;
32
- return value;
33
- },
34
- };
@@ -1,8 +0,0 @@
1
- export declare type FunctionPropertyNames<T> = {
2
- [K in keyof T]: T[K] extends Function ? K : never;
3
- }[keyof T];
4
- export declare type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;
5
- export declare type NonFunctionPropertyNames<T> = {
6
- [K in keyof T]: T[K] extends Function ? never : K;
7
- }[keyof T];
8
- export declare type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- /* eslint-disable @typescript-eslint/ban-types */
3
- // Some handy types from https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
4
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.blake2Concat = void 0;
4
- const util_1 = require("@polkadot/util");
5
- const util_crypto_1 = require("@polkadot/util-crypto");
6
- const bitLength = 128;
7
- function blake2Concat(input) {
8
- return (0, util_1.u8aToHex)((0, util_1.u8aConcat)((0, util_crypto_1.blake2AsU8a)(input, bitLength), (0, util_1.u8aToU8a)(input)));
9
- }
10
- exports.blake2Concat = blake2Concat;
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeAnyAddress = void 0;
4
- const keyring_1 = require("@polkadot/keyring");
5
- const util_1 = require("@polkadot/util");
6
- const util_crypto_1 = require("@polkadot/util-crypto");
7
- function decodeAnyAddress(encoded, ignoreChecksum, ss58Format) {
8
- try {
9
- return (0, keyring_1.decodeAddress)(encoded, ignoreChecksum, ss58Format);
10
- }
11
- catch (error) {
12
- if (typeof encoded !== "string")
13
- throw error;
14
- if (!(0, util_crypto_1.isEthereumAddress)(encoded))
15
- throw error;
16
- return (0, util_1.hexToU8a)(encoded.slice("0x".length));
17
- }
18
- }
19
- exports.decodeAnyAddress = decodeAnyAddress;
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.encodeAnyAddress = void 0;
4
- const keyring_1 = require("@polkadot/keyring");
5
- const util_crypto_1 = require("@polkadot/util-crypto");
6
- function encodeAnyAddress(key, ss58Format) {
7
- try {
8
- return (0, keyring_1.encodeAddress)(key, ss58Format);
9
- }
10
- catch (error) {
11
- if (typeof key !== "string")
12
- throw error;
13
- if (!(0, util_crypto_1.isEthereumAddress)(key))
14
- throw error;
15
- return (0, util_crypto_1.ethereumEncode)(key);
16
- }
17
- }
18
- exports.encodeAnyAddress = encodeAnyAddress;
@@ -1,57 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.formatDecimals = exports.MAX_DECIMALS_FORMAT = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const MIN_DIGITS = 4; // less truncates more than what compact formating is
9
- exports.MAX_DECIMALS_FORMAT = 12;
10
- /**
11
- * Custom decimal number formatting for Talisman
12
- * note that the NumberFormat().format() call is the ressource heavy part, it's not worth trying to optimize other parts
13
- * @param num input number
14
- * @param digits number of significant digits to display
15
- * @param locale locale used to format the number
16
- * @param options formatting options
17
- * @returns the formatted value
18
- */
19
- const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US") => {
20
- if (num === null || num === undefined)
21
- return "";
22
- if (digits < MIN_DIGITS)
23
- digits = MIN_DIGITS;
24
- const value = new bignumber_js_1.default(num);
25
- // very small numbers should display "< 0.0001"
26
- const minDisplayVal = 1 / Math.pow(10, digits);
27
- if (value.gt(0) && value.lt(minDisplayVal))
28
- return `< ${(0, exports.formatDecimals)(minDisplayVal)}`;
29
- // count digits
30
- const flooredValue = value.integerValue();
31
- const intDigits = flooredValue.isEqualTo(0) ? 0 : flooredValue.toString().length;
32
- // we never want to display a rounded up value
33
- // to prevent JS default rounding, we will remove/truncate insignificant digits ourselves before formatting
34
- let truncatedValue = value;
35
- //remove insignificant fraction digits
36
- const excessFractionDigitsPow10 = new bignumber_js_1.default(10).pow(digits > intDigits ? digits - intDigits : 0);
37
- truncatedValue = truncatedValue
38
- .multipliedBy(excessFractionDigitsPow10)
39
- .integerValue()
40
- .dividedBy(excessFractionDigitsPow10);
41
- //remove insignificant integer digits
42
- const excessIntegerDigits = new bignumber_js_1.default(intDigits > digits ? intDigits - digits : 0);
43
- const excessIntegerDigitsPow10 = new bignumber_js_1.default(10).pow(excessIntegerDigits);
44
- if (excessIntegerDigits.gt(0))
45
- truncatedValue = truncatedValue
46
- .dividedBy(excessIntegerDigitsPow10)
47
- .integerValue()
48
- .multipliedBy(excessIntegerDigitsPow10);
49
- // format
50
- return Intl.NumberFormat(locale, {
51
- //compact notation (K, M, B) if above 9999
52
- notation: truncatedValue.gt(9999) ? "compact" : "standard",
53
- maximumSignificantDigits: digits + (truncatedValue.lt(1) ? 1 : 0),
54
- ...options,
55
- }).format(truncatedValue.toNumber());
56
- };
57
- exports.formatDecimals = formatDecimals;
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getBase64ImageUrl = void 0;
4
- const getBase64ImageUrl = (base64) => {
5
- const match = /^data:([^;]*?);base64,(.*?)$/.exec(base64);
6
- if (!match)
7
- return null;
8
- const buffer = Buffer.from(match[2], "base64");
9
- const blob = new Blob([new Uint8Array(buffer, 0, buffer.length)], { type: match[1] });
10
- return URL.createObjectURL(blob);
11
- };
12
- exports.getBase64ImageUrl = getBase64ImageUrl;
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hasOwnProperty = void 0;
4
- function hasOwnProperty(obj, prop) {
5
- return prop in obj;
6
- }
7
- exports.hasOwnProperty = hasOwnProperty;
package/dist/index.js DELETED
@@ -1,30 +0,0 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./BigMath"), exports);
18
- __exportStar(require("./blake2Concat"), exports);
19
- __exportStar(require("./decodeAnyAddress"), exports);
20
- __exportStar(require("./encodeAnyAddress"), exports);
21
- __exportStar(require("./formatDecimals"), exports);
22
- __exportStar(require("./FunctionPropertyNames"), exports);
23
- __exportStar(require("./getBase64ImageUrl"), exports);
24
- __exportStar(require("./hasOwnProperty"), exports);
25
- __exportStar(require("./isArrayOf"), exports);
26
- __exportStar(require("./planckToTokens"), exports);
27
- __exportStar(require("./sleep"), exports);
28
- __exportStar(require("./throwAfter"), exports);
29
- __exportStar(require("./tokensToPlanck"), exports);
30
- __exportStar(require("./twox64Concat"), exports);
package/dist/isArrayOf.js DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isArrayOf = void 0;
4
- function isArrayOf(array, func) {
5
- if (array.length > 0 && array[0] instanceof func)
6
- return true;
7
- return false;
8
- }
9
- exports.isArrayOf = isArrayOf;
@@ -1,16 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.planckToTokens = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- function planckToTokens(planck, tokenDecimals) {
9
- if (typeof planck !== "string" || typeof tokenDecimals !== "number")
10
- return;
11
- const base = new bignumber_js_1.default(10);
12
- const exponent = new bignumber_js_1.default(tokenDecimals).negated();
13
- const multiplier = base.pow(exponent);
14
- return new bignumber_js_1.default(planck).multipliedBy(multiplier).toString(10);
15
- }
16
- exports.planckToTokens = planckToTokens;
package/dist/sleep.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sleep = void 0;
4
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5
- exports.sleep = sleep;
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.throwAfter = void 0;
4
- const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(reason), ms));
5
- exports.throwAfter = throwAfter;
@@ -1,16 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.tokensToPlanck = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- function tokensToPlanck(tokens, tokenDecimals) {
9
- if (typeof tokens !== "string" || typeof tokenDecimals !== "number")
10
- return;
11
- const base = new bignumber_js_1.default(10);
12
- const exponent = new bignumber_js_1.default(tokenDecimals);
13
- const multiplier = base.pow(exponent);
14
- return new bignumber_js_1.default(tokens).multipliedBy(multiplier).toString(10);
15
- }
16
- exports.tokensToPlanck = tokensToPlanck;
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.twox64Concat = void 0;
4
- const util_1 = require("@polkadot/util");
5
- const util_crypto_1 = require("@polkadot/util-crypto");
6
- const bitLength = 64;
7
- function twox64Concat(input) {
8
- return (0, util_1.u8aToHex)((0, util_1.u8aConcat)((0, util_crypto_1.xxhashAsU8a)(input, bitLength), (0, util_1.u8aToU8a)(input)));
9
- }
10
- exports.twox64Concat = twox64Concat;