@pezkuwi/util 14.0.1

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 (260) hide show
  1. package/README.md +17 -0
  2. package/package.json +49 -0
  3. package/src/array/chunk.spec.ts +29 -0
  4. package/src/array/chunk.ts +35 -0
  5. package/src/array/filter.spec.ts +20 -0
  6. package/src/array/filter.ts +24 -0
  7. package/src/array/flatten.spec.ts +33 -0
  8. package/src/array/flatten.ts +51 -0
  9. package/src/array/index.ts +14 -0
  10. package/src/array/range.spec.ts +29 -0
  11. package/src/array/range.ts +31 -0
  12. package/src/array/shuffle.spec.ts +39 -0
  13. package/src/array/shuffle.ts +27 -0
  14. package/src/array/unzip.spec.ts +14 -0
  15. package/src/array/unzip.ts +18 -0
  16. package/src/array/zip.spec.ts +26 -0
  17. package/src/array/zip.ts +17 -0
  18. package/src/assert.spec.ts +40 -0
  19. package/src/assert.ts +50 -0
  20. package/src/bi/consts.ts +112 -0
  21. package/src/bi/helpers.ts +23 -0
  22. package/src/bi/index.ts +16 -0
  23. package/src/bi/max.spec.ts +32 -0
  24. package/src/bi/min.spec.ts +26 -0
  25. package/src/bi/min.ts +16 -0
  26. package/src/bi/sqrt.spec.ts +59 -0
  27. package/src/bi/sqrt.ts +43 -0
  28. package/src/bi/toBigInt.spec.ts +69 -0
  29. package/src/bi/toBigInt.ts +33 -0
  30. package/src/bi/toHex.spec.ts +56 -0
  31. package/src/bi/toHex.ts +16 -0
  32. package/src/bi/toU8a.spec.ts +99 -0
  33. package/src/bi/toU8a.ts +72 -0
  34. package/src/bn/bn.ts +6 -0
  35. package/src/bn/consts.spec.ts +38 -0
  36. package/src/bn/consts.ts +112 -0
  37. package/src/bn/fromHex.spec.ts +15 -0
  38. package/src/bn/fromHex.ts +4 -0
  39. package/src/bn/index.ts +18 -0
  40. package/src/bn/max.spec.ts +32 -0
  41. package/src/bn/min.spec.ts +26 -0
  42. package/src/bn/min.ts +36 -0
  43. package/src/bn/sqrt.spec.ts +37 -0
  44. package/src/bn/sqrt.ts +50 -0
  45. package/src/bn/toBn.spec.ts +53 -0
  46. package/src/bn/toBn.ts +43 -0
  47. package/src/bn/toHex.spec.ts +50 -0
  48. package/src/bn/toHex.ts +27 -0
  49. package/src/bn/toU8a.spec.ts +60 -0
  50. package/src/bn/toU8a.ts +45 -0
  51. package/src/buffer/index.ts +8 -0
  52. package/src/buffer/toU8a.spec.ts +20 -0
  53. package/src/buffer/toU8a.ts +20 -0
  54. package/src/bundle.ts +35 -0
  55. package/src/compact/addLength.spec.ts +14 -0
  56. package/src/compact/addLength.ts +24 -0
  57. package/src/compact/defaults.ts +7 -0
  58. package/src/compact/fromU8a.spec.ts +84 -0
  59. package/src/compact/fromU8a.ts +109 -0
  60. package/src/compact/index.ts +28 -0
  61. package/src/compact/stripLength.spec.ts +17 -0
  62. package/src/compact/stripLength.ts +26 -0
  63. package/src/compact/toU8a.spec.ts +59 -0
  64. package/src/compact/toU8a.ts +53 -0
  65. package/src/compact/types.ts +4 -0
  66. package/src/detectPackage.spec.ts +110 -0
  67. package/src/detectPackage.ts +138 -0
  68. package/src/extractTime.spec.ts +21 -0
  69. package/src/extractTime.ts +71 -0
  70. package/src/float/index.ts +4 -0
  71. package/src/float/toU8a.spec.ts +52 -0
  72. package/src/float/toU8a.ts +30 -0
  73. package/src/format/formatBalance.spec.ts +296 -0
  74. package/src/format/formatBalance.ts +177 -0
  75. package/src/format/formatDate.spec.ts +17 -0
  76. package/src/format/formatDate.ts +22 -0
  77. package/src/format/formatDecimal.spec.ts +28 -0
  78. package/src/format/formatDecimal.ts +22 -0
  79. package/src/format/formatElapsed.spec.ts +44 -0
  80. package/src/format/formatElapsed.ts +35 -0
  81. package/src/format/formatNumber.spec.ts +60 -0
  82. package/src/format/formatNumber.ts +29 -0
  83. package/src/format/getSeparator.spec.ts +53 -0
  84. package/src/format/getSeparator.ts +15 -0
  85. package/src/format/index.ts +9 -0
  86. package/src/format/si.ts +52 -0
  87. package/src/has.spec.ts +12 -0
  88. package/src/has.ts +38 -0
  89. package/src/hex/addPrefix.spec.ts +32 -0
  90. package/src/hex/addPrefix.ts +26 -0
  91. package/src/hex/fixLength.spec.ts +38 -0
  92. package/src/hex/fixLength.ts +36 -0
  93. package/src/hex/hasPrefix.spec.ts +32 -0
  94. package/src/hex/hasPrefix.ts +24 -0
  95. package/src/hex/index.ts +16 -0
  96. package/src/hex/stripPrefix.spec.ts +44 -0
  97. package/src/hex/stripPrefix.ts +30 -0
  98. package/src/hex/toBigInt.spec.ts +74 -0
  99. package/src/hex/toBigInt.ts +19 -0
  100. package/src/hex/toBn.spec.ts +74 -0
  101. package/src/hex/toBn.ts +40 -0
  102. package/src/hex/toNumber.spec.ts +20 -0
  103. package/src/hex/toNumber.ts +24 -0
  104. package/src/hex/toString.spec.ts +20 -0
  105. package/src/hex/toString.ts +25 -0
  106. package/src/hex/toU8a.spec.ts +76 -0
  107. package/src/hex/toU8a.ts +68 -0
  108. package/src/hex/toU8aBuffer.spec.ts +38 -0
  109. package/src/hex/toU8aBuffer.ts +52 -0
  110. package/src/index.spec.ts +12 -0
  111. package/src/index.ts +6 -0
  112. package/src/is/array.spec.ts +20 -0
  113. package/src/is/array.ts +10 -0
  114. package/src/is/ascii.spec.ts +49 -0
  115. package/src/is/ascii.ts +52 -0
  116. package/src/is/bigInt.spec.ts +26 -0
  117. package/src/is/bigInt.ts +20 -0
  118. package/src/is/bn.spec.ts +21 -0
  119. package/src/is/bn.ts +23 -0
  120. package/src/is/boolean.spec.ts +26 -0
  121. package/src/is/boolean.ts +20 -0
  122. package/src/is/buffer.spec.ts +26 -0
  123. package/src/is/buffer.ts +28 -0
  124. package/src/is/childClass.spec.ts +36 -0
  125. package/src/is/childClass.ts +29 -0
  126. package/src/is/class.spec.ts +37 -0
  127. package/src/is/class.ts +12 -0
  128. package/src/is/codec.spec.ts +52 -0
  129. package/src/is/codec.ts +26 -0
  130. package/src/is/compact.spec.ts +27 -0
  131. package/src/is/compact.ts +19 -0
  132. package/src/is/error.spec.ts +20 -0
  133. package/src/is/error.ts +23 -0
  134. package/src/is/function.spec.ts +20 -0
  135. package/src/is/function.ts +23 -0
  136. package/src/is/helpers.ts +23 -0
  137. package/src/is/hex.spec.ts +77 -0
  138. package/src/is/hex.ts +36 -0
  139. package/src/is/index.ts +36 -0
  140. package/src/is/instanceOf.spec.ts +48 -0
  141. package/src/is/instanceOf.ts +24 -0
  142. package/src/is/ip.spec.ts +50 -0
  143. package/src/is/ip.ts +56 -0
  144. package/src/is/jsonObject.spec.ts +51 -0
  145. package/src/is/jsonObject.ts +45 -0
  146. package/src/is/null.spec.ts +20 -0
  147. package/src/is/null.ts +20 -0
  148. package/src/is/number.spec.ts +20 -0
  149. package/src/is/number.ts +20 -0
  150. package/src/is/object.spec.ts +32 -0
  151. package/src/is/object.ts +24 -0
  152. package/src/is/observable.spec.ts +26 -0
  153. package/src/is/observable.ts +22 -0
  154. package/src/is/promise.spec.ts +32 -0
  155. package/src/is/promise.ts +6 -0
  156. package/src/is/riscv.spec.ts +36 -0
  157. package/src/is/riscv.ts +27 -0
  158. package/src/is/string.spec.ts +32 -0
  159. package/src/is/string.ts +22 -0
  160. package/src/is/testChain.spec.ts +25 -0
  161. package/src/is/testChain.ts +12 -0
  162. package/src/is/toBigInt.spec.ts +22 -0
  163. package/src/is/toBigInt.ts +8 -0
  164. package/src/is/toBn.spec.ts +25 -0
  165. package/src/is/toBn.ts +8 -0
  166. package/src/is/u8a.spec.ts +42 -0
  167. package/src/is/u8a.ts +25 -0
  168. package/src/is/undefined.spec.ts +23 -0
  169. package/src/is/undefined.ts +21 -0
  170. package/src/is/utf8.spec.ts +42 -0
  171. package/src/is/utf8.ts +207 -0
  172. package/src/is/wasm.spec.ts +20 -0
  173. package/src/is/wasm.ts +17 -0
  174. package/src/lazy.spec.ts +71 -0
  175. package/src/lazy.ts +63 -0
  176. package/src/logger.spec.ts +188 -0
  177. package/src/logger.ts +160 -0
  178. package/src/memoize.spec.ts +79 -0
  179. package/src/memoize.ts +49 -0
  180. package/src/mod.ts +4 -0
  181. package/src/nextTick.ts +26 -0
  182. package/src/noop.ts +16 -0
  183. package/src/number/index.ts +9 -0
  184. package/src/number/toHex.spec.ts +44 -0
  185. package/src/number/toHex.ts +27 -0
  186. package/src/number/toU8a.spec.ts +50 -0
  187. package/src/number/toU8a.ts +25 -0
  188. package/src/object/clear.spec.ts +14 -0
  189. package/src/object/clear.ts +16 -0
  190. package/src/object/copy.spec.ts +17 -0
  191. package/src/object/copy.ts +12 -0
  192. package/src/object/entries.spec.ts +20 -0
  193. package/src/object/entries.ts +12 -0
  194. package/src/object/index.ts +10 -0
  195. package/src/object/keys.spec.ts +19 -0
  196. package/src/object/keys.ts +10 -0
  197. package/src/object/property.spec.ts +149 -0
  198. package/src/object/property.ts +39 -0
  199. package/src/object/spread.spec.ts +36 -0
  200. package/src/object/spread.ts +38 -0
  201. package/src/object/values.spec.ts +19 -0
  202. package/src/object/values.ts +10 -0
  203. package/src/packageDetect.ts +13 -0
  204. package/src/packageInfo.ts +6 -0
  205. package/src/promisify.spec.ts +50 -0
  206. package/src/promisify.ts +30 -0
  207. package/src/string/camelCase.spec.ts +119 -0
  208. package/src/string/camelCase.ts +79 -0
  209. package/src/string/index.ts +12 -0
  210. package/src/string/lowerFirst.spec.ts +41 -0
  211. package/src/string/lowerFirst.ts +46 -0
  212. package/src/string/pascalCase.spec.ts +26 -0
  213. package/src/string/shorten.spec.ts +38 -0
  214. package/src/string/shorten.ts +24 -0
  215. package/src/string/toHex.spec.ts +26 -0
  216. package/src/string/toHex.ts +27 -0
  217. package/src/string/toU8a.spec.ts +31 -0
  218. package/src/string/toU8a.ts +28 -0
  219. package/src/string/upperFirst.spec.ts +41 -0
  220. package/src/stringify.spec.ts +33 -0
  221. package/src/stringify.ts +20 -0
  222. package/src/test/index.ts +4 -0
  223. package/src/test/performance.ts +92 -0
  224. package/src/types.ts +100 -0
  225. package/src/u8a/cmp.spec.ts +62 -0
  226. package/src/u8a/cmp.ts +50 -0
  227. package/src/u8a/concat.spec.ts +42 -0
  228. package/src/u8a/concat.ts +60 -0
  229. package/src/u8a/concatBuffer.ts +34 -0
  230. package/src/u8a/empty.spec.ts +46 -0
  231. package/src/u8a/empty.ts +22 -0
  232. package/src/u8a/eq.spec.ts +113 -0
  233. package/src/u8a/eq.ts +46 -0
  234. package/src/u8a/fixLength.spec.ts +34 -0
  235. package/src/u8a/fixLength.ts +34 -0
  236. package/src/u8a/index.ts +22 -0
  237. package/src/u8a/sorted.spec.ts +20 -0
  238. package/src/u8a/sorted.ts +22 -0
  239. package/src/u8a/toBigInt.spec.ts +106 -0
  240. package/src/u8a/toBigInt.ts +100 -0
  241. package/src/u8a/toBn.spec.ts +106 -0
  242. package/src/u8a/toBn.ts +101 -0
  243. package/src/u8a/toBuffer.spec.ts +20 -0
  244. package/src/u8a/toBuffer.ts +28 -0
  245. package/src/u8a/toFloat.spec.ts +86 -0
  246. package/src/u8a/toFloat.ts +26 -0
  247. package/src/u8a/toHex.spec.ts +94 -0
  248. package/src/u8a/toHex.ts +68 -0
  249. package/src/u8a/toHexBuffer.spec.ts +63 -0
  250. package/src/u8a/toHexBuffer.ts +30 -0
  251. package/src/u8a/toNumber.spec.ts +47 -0
  252. package/src/u8a/toNumber.ts +80 -0
  253. package/src/u8a/toString.spec.ts +36 -0
  254. package/src/u8a/toString.ts +26 -0
  255. package/src/u8a/toU8a.spec.ts +63 -0
  256. package/src/u8a/toU8a.ts +46 -0
  257. package/src/u8a/wrap.spec.ts +139 -0
  258. package/src/u8a/wrap.ts +65 -0
  259. package/tsconfig.build.json +19 -0
  260. package/tsconfig.spec.json +17 -0
@@ -0,0 +1,138 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { xglobal } from '@pezkuwi/x-global';
5
+
6
+ import { isFunction } from './is/function.js';
7
+
8
+ type This = typeof globalThis;
9
+
10
+ interface VersionPath {
11
+ path: string;
12
+ type: string;
13
+ version: string;
14
+ }
15
+
16
+ interface PackageInfo extends VersionPath {
17
+ name: string;
18
+ }
19
+
20
+ interface PjsChecks extends This {
21
+ __polkadotjs: Record<string, VersionPath[]>;
22
+ }
23
+
24
+ type PjsGlobal = This & PjsChecks & Record<string, unknown>;
25
+ type FnString = () => string | undefined;
26
+
27
+ const DEDUPE = 'Either remove and explicitly install matching versions or dedupe using your package manager.\nThe following conflicting packages were found:';
28
+
29
+ export const POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG = 'POLKADOTJS_DISABLE_ESM_CJS_WARNING';
30
+
31
+ /** @internal */
32
+ function getEntry (name: string): VersionPath[] {
33
+ const _global = xglobal as PjsGlobal;
34
+
35
+ if (!_global.__polkadotjs) {
36
+ _global.__polkadotjs = {};
37
+ }
38
+
39
+ if (!_global.__polkadotjs[name]) {
40
+ _global.__polkadotjs[name] = [];
41
+ }
42
+
43
+ return _global.__polkadotjs[name];
44
+ }
45
+
46
+ /** @internal */
47
+ function formatDisplay <T extends { version: string }> (all: T[], fmt: (version: string, data: T) => string[]): string {
48
+ let max = 0;
49
+
50
+ for (let i = 0, count = all.length; i < count; i++) {
51
+ max = Math.max(max, all[i].version.length);
52
+ }
53
+
54
+ return all
55
+ .map((d) => `\t${fmt(d.version.padEnd(max), d).join('\t')}`)
56
+ .join('\n');
57
+ }
58
+
59
+ /** @internal */
60
+ function formatInfo (version: string, { name }: PackageInfo): string[] {
61
+ return [
62
+ version,
63
+ name
64
+ ];
65
+ }
66
+
67
+ /** @internal */
68
+ function formatVersion (version: string, { path, type }: VersionPath): string[] {
69
+ let extracted: string;
70
+
71
+ if (path && path.length >= 5) {
72
+ const nmIndex = path.indexOf('node_modules');
73
+
74
+ extracted = nmIndex === -1
75
+ ? path
76
+ : path.substring(nmIndex);
77
+ } else {
78
+ extracted = '<unknown>';
79
+ }
80
+
81
+ return [
82
+ `${`${type || ''}`.padStart(3)} ${version}`,
83
+ extracted
84
+ ];
85
+ }
86
+
87
+ /** @internal */
88
+ function getPath (infoPath?: string, pathOrFn?: FnString | string | false | null): string {
89
+ if (infoPath) {
90
+ return infoPath;
91
+ } else if (isFunction(pathOrFn)) {
92
+ try {
93
+ return pathOrFn() || '';
94
+ } catch {
95
+ return '';
96
+ }
97
+ }
98
+
99
+ return pathOrFn || '';
100
+ }
101
+
102
+ /** @internal */
103
+ function warn <T extends { version: string }> (pre: string, all: T[], fmt: (version: string, data: T) => string[]): void {
104
+ console.warn(`${pre}\n${DEDUPE}\n${formatDisplay(all, fmt)}`);
105
+ }
106
+
107
+ /**
108
+ * @name detectPackage
109
+ * @summary Checks that a specific package is only imported once
110
+ * @description A `@polkadot/*` version detection utility, checking for one occurrence of a package in addition to checking for dependency versions.
111
+ */
112
+ export function detectPackage ({ name, path, type, version }: PackageInfo, pathOrFn?: FnString | string | false | null, deps: PackageInfo[] = []): void {
113
+ if (!name.startsWith('@polkadot')) {
114
+ throw new Error(`Invalid package descriptor ${name}`);
115
+ }
116
+
117
+ const entry = getEntry(name);
118
+
119
+ entry.push({ path: getPath(path, pathOrFn), type, version });
120
+
121
+ // if we have more than one entry at DIFFERENT version types then warn. If there is
122
+ // more than one entry at the same version and ESM/CJS dual warnings are disabled,
123
+ // then do not display warnings
124
+ const entriesSameVersion = entry.every((e) => e.version === version);
125
+ const esmCjsWarningDisabled = xglobal.process?.env?.[POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG] === '1';
126
+ const multipleEntries = entry.length !== 1;
127
+ const disableWarnings = esmCjsWarningDisabled && entriesSameVersion;
128
+
129
+ if (multipleEntries && !disableWarnings) {
130
+ warn(`${name} has multiple versions, ensure that there is only one installed.`, entry, formatVersion);
131
+ } else {
132
+ const mismatches = deps.filter((d) => d && d.version !== version);
133
+
134
+ if (mismatches.length) {
135
+ warn(`${name} requires direct dependencies exactly matching version ${version}.`, mismatches, formatInfo);
136
+ }
137
+ }
138
+ }
@@ -0,0 +1,21 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /// <reference types="@polkadot/dev-test/globals.d.ts" />
5
+
6
+ import { extractTime } from './index.js';
7
+
8
+ describe('extractTime', (): void => {
9
+ const milliseconds = 1e9 + 123;
10
+
11
+ it('extracts time components correctly', (): void => {
12
+ expect(extractTime(milliseconds))
13
+ .toEqual({
14
+ days: 11,
15
+ hours: 13,
16
+ milliseconds: 123,
17
+ minutes: 46,
18
+ seconds: 40
19
+ });
20
+ });
21
+ });
@@ -0,0 +1,71 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Time } from './types.js';
5
+
6
+ const MIN_MS = 60 * 1000;
7
+ const HR_MS = MIN_MS * 60;
8
+ const DAY_MS = HR_MS * 24;
9
+ const ZERO: Time = { days: 0, hours: 0, milliseconds: 0, minutes: 0, seconds: 0 };
10
+
11
+ /** @internal */
12
+ function add (a: Partial<Time>, b: Time): Time {
13
+ return {
14
+ days: (a.days || 0) + b.days,
15
+ hours: (a.hours || 0) + b.hours,
16
+ milliseconds: (a.milliseconds || 0) + b.milliseconds,
17
+ minutes: (a.minutes || 0) + b.minutes,
18
+ seconds: (a.seconds || 0) + b.seconds
19
+ };
20
+ }
21
+
22
+ /** @internal */
23
+ function extractSecs (ms: number): Time {
24
+ const s = ms / 1000;
25
+
26
+ if (s < 60) {
27
+ const seconds = ~~s;
28
+
29
+ return add({ seconds }, extractTime(ms - (seconds * 1000)));
30
+ }
31
+
32
+ const m = s / 60;
33
+
34
+ if (m < 60) {
35
+ const minutes = ~~m;
36
+
37
+ return add({ minutes }, extractTime(ms - (minutes * MIN_MS)));
38
+ }
39
+
40
+ const h = m / 60;
41
+
42
+ if (h < 24) {
43
+ const hours = ~~h;
44
+
45
+ return add({ hours }, extractTime(ms - (hours * HR_MS)));
46
+ }
47
+
48
+ const days = ~~(h / 24);
49
+
50
+ return add({ days }, extractTime(ms - (days * DAY_MS)));
51
+ }
52
+
53
+ /**
54
+ * @name extractTime
55
+ * @summary Convert a quantity of seconds to Time array representing accumulated {days, minutes, hours, seconds, milliseconds}
56
+ * @example
57
+ * <BR>
58
+ *
59
+ * ```javascript
60
+ * import { extractTime } from '@pezkuwi/util';
61
+ *
62
+ * const { days, minutes, hours, seconds, milliseconds } = extractTime(6000); // 0, 0, 10, 0, 0
63
+ * ```
64
+ */
65
+ export function extractTime (milliseconds?: number): Time {
66
+ return !milliseconds
67
+ ? ZERO
68
+ : milliseconds < 1000
69
+ ? add({ milliseconds }, ZERO)
70
+ : extractSecs(milliseconds);
71
+ }
@@ -0,0 +1,4 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { floatToU8a } from './toU8a.js';
@@ -0,0 +1,52 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /// <reference types="@polkadot/dev-test/globals.d.ts" />
5
+
6
+ import { u8aToHex } from '../u8a/index.js';
7
+ import { floatToU8a } from './index.js';
8
+
9
+ class ExtNumber extends Number {
10
+ foo = 'bar';
11
+ }
12
+
13
+ class ExtString extends String {
14
+ foo = 'bar';
15
+ }
16
+
17
+ // NOTE Hex value outputs created via online conversion tool:
18
+ // https://www.h-schmidt.net/FloatConverter/IEEE754.html
19
+ // eslint-disable-next-line @typescript-eslint/ban-types
20
+ const TESTS: [isLe: boolean | undefined, bitLength: 32 | 64 | undefined, input: String | string | number | Number, output: string][] = [
21
+ [undefined, undefined, +0.0, '0x00000000'],
22
+ [undefined, undefined, -0.0, '0x00000080'],
23
+ [undefined, undefined, 123.456, '0x79e9f642'],
24
+ [undefined, undefined, '123.456', '0x79e9f642'],
25
+ [undefined, undefined, new ExtNumber(123.456), '0x79e9f642'],
26
+ [undefined, undefined, new ExtString(123.456), '0x79e9f642'],
27
+ [true, 32, new ExtString(123.456), '0x79e9f642'],
28
+ [true, undefined, Number.NaN, '0x0000c07f'],
29
+ [false, undefined, -0.0, '0x80000000'],
30
+ [undefined, 64, +0.0, '0x0000000000000000'],
31
+ [true, 64, -0.0, '0x0000000000000080'],
32
+ [false, 64, -0.0, '0x8000000000000000'],
33
+ [undefined, 64, Number.NaN, '0x000000000000f87f']
34
+ ];
35
+
36
+ describe('floatToU8a', (): void => {
37
+ it('throws on invalid bitLength', (): void => {
38
+ expect(
39
+ () => floatToU8a(123, { bitLength: 48 as 32 })
40
+ ).toThrow();
41
+ });
42
+
43
+ describe('conversion tests', (): void => {
44
+ TESTS.forEach(([isLe, bitLength, input, output], i): void => {
45
+ it(`#${i}: correctly encodes ${typeof input === 'number' ? input : input.toString()} (typeof=${typeof input})`, (): void => {
46
+ expect(
47
+ u8aToHex(floatToU8a(input, { bitLength, isLe }))
48
+ ).toEqual(output);
49
+ });
50
+ });
51
+ });
52
+ });
@@ -0,0 +1,30 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ interface Options {
5
+ bitLength?: 32 | 64;
6
+ isLe?: boolean;
7
+ }
8
+
9
+ /**
10
+ * @name floatToU8a
11
+ * @description Converts a float into a U8a representation (While we don't use BE in SCALE
12
+ * we still allow for either representation, although, as elsewhere, isLe is default)
13
+ */
14
+ // eslint-disable-next-line @typescript-eslint/ban-types
15
+ export function floatToU8a (value: String | string | number | Number = 0.0, { bitLength = 32, isLe = true }: Options = {}): Uint8Array {
16
+ if (bitLength !== 32 && bitLength !== 64) {
17
+ throw new Error('Invalid bitLength provided, expected 32 or 64');
18
+ }
19
+
20
+ const result = new Uint8Array(bitLength / 8);
21
+ const dv = new DataView(result.buffer, result.byteOffset);
22
+
23
+ if (bitLength === 32) {
24
+ dv.setFloat32(0, Number(value), isLe);
25
+ } else {
26
+ dv.setFloat64(0, Number(value), isLe);
27
+ }
28
+
29
+ return result;
30
+ }
@@ -0,0 +1,296 @@
1
+ // Copyright 2017-2025 @polkadot/util authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /// <reference types="@polkadot/dev-test/globals.d.ts" />
5
+
6
+ import { BN } from '../bn/index.js';
7
+ import { formatBalance } from './index.js';
8
+
9
+ const FMT_DEFAULTS = {
10
+ decimals: 0,
11
+ unit: 'Unit'
12
+ };
13
+
14
+ describe('formatBalance', (): void => {
15
+ const TESTVAL = new BN('123456789000');
16
+
17
+ // We mess around with the global setDefaults inside some tests,
18
+ // ensure we restore it to the defaults straight after each run
19
+ afterEach((): void => {
20
+ formatBalance.setDefaults(FMT_DEFAULTS);
21
+ });
22
+
23
+ it('returns options for dropdown', (): void => {
24
+ formatBalance.setDefaults({ decimals: 0, unit: 'TEST' });
25
+
26
+ expect(
27
+ formatBalance.getOptions()
28
+ ).toEqual([
29
+ { power: 0, text: 'TEST', value: '-' },
30
+ { power: 3, text: 'Kilo', value: 'k' },
31
+ { power: 6, text: 'Mill', value: 'M' },
32
+ { power: 9, text: 'Bill', value: 'B' },
33
+ { power: 12, text: 'Tril', value: 'T' },
34
+ { power: 15, text: 'Peta', value: 'P' },
35
+ { power: 18, text: 'Exa', value: 'E' },
36
+ { power: 21, text: 'Zeta', value: 'Z' },
37
+ { power: 24, text: 'Yotta', value: 'Y' }
38
+ ]);
39
+ });
40
+
41
+ it('can set defaults from array values', (): void => {
42
+ formatBalance.setDefaults({ decimals: [12, 24], unit: ['Multi', 'Unit'] });
43
+
44
+ expect(
45
+ formatBalance(TESTVAL)
46
+ ).toEqual('123.4567 mMulti');
47
+ });
48
+
49
+ describe('SI formatting', (): void => {
50
+ it('formats empty to 0', (): void => {
51
+ expect(formatBalance()).toEqual('0');
52
+ expect(formatBalance('0')).toEqual('0');
53
+ });
54
+
55
+ // this is after an issue/test from actual values with forceUnit
56
+ it('formats 1000 (BN) (decimals = 12, withAll, withZero = false)', (): void => {
57
+ expect(
58
+ formatBalance(new BN(1000), { decimals: 12, forceUnit: '-', withAll: true, withSi: false, withZero: true })
59
+ ).toEqual('0.000000001000');
60
+ });
61
+
62
+ it('formats 123,456,789,000 (decimals=15)', (): void => {
63
+ expect(
64
+ formatBalance(TESTVAL, { decimals: 15, withSi: true })
65
+ ).toEqual('123.4567 µUnit');
66
+ });
67
+
68
+ it('formats 123,456 (decimals=0)', (): void => {
69
+ expect(
70
+ formatBalance(123456, { decimals: 0, withSi: true })
71
+ ).toEqual('123.4560 kUnit');
72
+ });
73
+
74
+ it('formats BigInt numbers', (): void => {
75
+ expect(
76
+ formatBalance(123456789000n, { decimals: 15, withSi: true })
77
+ ).toEqual('123.4567 µUnit');
78
+ });
79
+
80
+ it('formats 123,456,789,000 (decimals=15, old style)', (): void => {
81
+ expect(
82
+ formatBalance(TESTVAL, { decimals: 15, withSi: true })
83
+ ).toEqual('123.4567 µUnit');
84
+ });
85
+
86
+ it('formats 123,456,789,000 (decimals=10, withAll=true)', (): void => {
87
+ expect(
88
+ formatBalance(TESTVAL, { decimals: 10, forceUnit: '-', withAll: true, withSi: true })
89
+ ).toEqual('12.3456789000 Unit');
90
+ });
91
+
92
+ it('formats 123,456,789,000 (decimals=10, withAll=true, withZero=false)', (): void => {
93
+ expect(
94
+ formatBalance(TESTVAL, { decimals: 10, forceUnit: '-', withAll: true, withSi: true, withZero: false })
95
+ ).toEqual('12.3456789 Unit');
96
+ });
97
+
98
+ it('formats 123,000,000,000 (decimals=9, withAll=true, withZero=false)', (): void => {
99
+ expect(
100
+ formatBalance('123000000000', { decimals: 9, forceUnit: '-', withAll: true, withSi: true, withZero: false })
101
+ ).toEqual('123 Unit');
102
+ });
103
+
104
+ it('formats 123,456,789,000 (decimals=15, Compact)', (): void => {
105
+ const compact = {
106
+ something: 'else',
107
+ toBn: (): BN => TESTVAL,
108
+ unwrap: (): BN => TESTVAL
109
+ };
110
+
111
+ expect(
112
+ formatBalance(compact, { decimals: 15, withSi: true })
113
+ ).toEqual('123.4567 µUnit');
114
+ });
115
+
116
+ it('formats 123,456,789,000 (decimals=12)', (): void => {
117
+ expect(
118
+ formatBalance(TESTVAL, { decimals: 12, withSi: true })
119
+ ).toEqual('123.4567 mUnit');
120
+ });
121
+
122
+ it('formats 123,456,789,000 (decimals=9)', (): void => {
123
+ expect(
124
+ formatBalance(TESTVAL, { decimals: 9, withSi: true })
125
+ ).toEqual('123.4567 Unit');
126
+ });
127
+
128
+ it('formats 123,456,789,000 (decimals=9, no unit)', (): void => {
129
+ expect(
130
+ formatBalance(TESTVAL, { decimals: 9, withSi: true, withUnit: false })
131
+ ).toEqual('123.4567');
132
+ });
133
+
134
+ it('formats 123,456,789,000 (decimals=9, unit given)', (): void => {
135
+ expect(
136
+ formatBalance(TESTVAL, { decimals: 9, withSi: true, withUnit: 'FOO' })
137
+ ).toEqual('123.4567 FOO');
138
+ });
139
+
140
+ it('formats 123,456,789,000 (decimals=12, no SI)', (): void => {
141
+ expect(
142
+ formatBalance(TESTVAL, { decimals: 12, withSi: false })
143
+ ).toEqual('123.4567');
144
+ });
145
+
146
+ it('formats 123,456,789,000 (decimals=12, full SI)', (): void => {
147
+ expect(
148
+ formatBalance(TESTVAL, { decimals: 12, withSiFull: true })
149
+ ).toEqual('123.4567 milli Unit');
150
+ });
151
+
152
+ it('formats 123,456,789,000 (decimals=12, full SI, no unit)', (): void => {
153
+ expect(
154
+ formatBalance(TESTVAL, { decimals: 12, withSiFull: true, withUnit: false })
155
+ ).toEqual('123.4567 milli');
156
+ });
157
+
158
+ it('formats 123,456,789,000 (decimals=9, full SI)', (): void => {
159
+ expect(
160
+ formatBalance(TESTVAL, { decimals: 9, withSiFull: true })
161
+ ).toEqual('123.4567 Unit');
162
+ });
163
+
164
+ it('formats 123,456,789,000 (decimals=6)', (): void => {
165
+ expect(
166
+ formatBalance(TESTVAL, { decimals: 6, withSi: true })
167
+ ).toEqual('123.4567 kUnit');
168
+ });
169
+
170
+ it('formats 123,456,789,000 (decimals=6, unit specified)', (): void => {
171
+ expect(
172
+ formatBalance(TESTVAL, { decimals: 6, withSi: true, withUnit: 'BAR' })
173
+ ).toEqual('123.4567 kBAR');
174
+ });
175
+
176
+ it('formats 123,456,789,000 (decimals=0, unit specified)', (): void => {
177
+ expect(
178
+ formatBalance(TESTVAL, { decimals: 0, withSi: true, withUnit: 'BAR' })
179
+ ).toEqual('123.4567 BBAR');
180
+ });
181
+
182
+ it('formats 123,456,789,000 * 10 (decimals=12)', (): void => {
183
+ expect(
184
+ formatBalance(TESTVAL.muln(10), { decimals: 12, withSi: true })
185
+ ).toEqual('1.2345 Unit');
186
+ });
187
+
188
+ it('formats 123,456,789,000 * 100 (decimals=12)', (): void => {
189
+ expect(
190
+ formatBalance(TESTVAL.muln(100), { decimals: 12, withSi: true })
191
+ ).toEqual('12.3456 Unit');
192
+ });
193
+
194
+ it('formats 123,456,789,000 * 1000 (decimals=12)', (): void => {
195
+ expect(
196
+ formatBalance(TESTVAL.muln(1000), { decimals: 12, withSi: true })
197
+ ).toEqual('123.4567 Unit');
198
+ });
199
+
200
+ it('formats -123,456,789,000 (decimals=15)', (): void => {
201
+ expect(
202
+ formatBalance(new BN('-123456789000'), { decimals: 15, withSi: true })
203
+ ).toEqual('-123.4567 µUnit');
204
+ });
205
+ });
206
+
207
+ describe('Forced formatting', (): void => {
208
+ it('formats 123,456,789,000 (decimals=12, forceUnit=base)', (): void => {
209
+ expect(
210
+ formatBalance(TESTVAL, { decimals: 12, forceUnit: '-' })
211
+ ).toEqual('0.1234 Unit');
212
+ });
213
+
214
+ it('formats 123,456,789,000 (decimals=9, forceUnit=base)', (): void => {
215
+ expect(
216
+ formatBalance(TESTVAL, { decimals: 9, forceUnit: '-' })
217
+ ).toEqual('123.4567 Unit');
218
+ });
219
+
220
+ it('formats 123,456,789,000 (decimals=7, forceUnit=base)', (): void => {
221
+ expect(
222
+ formatBalance(TESTVAL, { decimals: 7, forceUnit: '-' })
223
+ ).toEqual('12,345.6789 Unit');
224
+ });
225
+
226
+ it('formats 123,456,789,000 (decimals=15, forceUnit=micro)', (): void => {
227
+ expect(
228
+ formatBalance(TESTVAL, { decimals: 15, forceUnit: 'µ' })
229
+ ).toEqual('123.4567 µUnit');
230
+ });
231
+
232
+ it('formats 123,456 (decimals=0, locale=sl)', (): void => {
233
+ expect(
234
+ formatBalance(123456, { decimals: 0, locale: 'sl', withSi: true })
235
+ ).toEqual('123,4560 kUnit');
236
+ });
237
+
238
+ it('formats BigInt numbers (locale=sl)', (): void => {
239
+ expect(
240
+ formatBalance(123456789000n, { decimals: 15, locale: 'sl', withSi: true })
241
+ ).toEqual('123,4567 µUnit');
242
+ });
243
+
244
+ it('formats 123,456,789,000 (decimals=7, forceUnit=base locale=sl)', (): void => {
245
+ expect(
246
+ formatBalance(TESTVAL, { decimals: 7, forceUnit: '-', locale: 'sl' })
247
+ ).toEqual('12.345,6789 Unit');
248
+ });
249
+ });
250
+
251
+ describe('calcSi', (): void => {
252
+ it('exposes calcSi on formatBalance', (): void => {
253
+ expect(
254
+ formatBalance.calcSi('12345').value
255
+ ).toEqual('k');
256
+ });
257
+ });
258
+
259
+ describe('findSi', (): void => {
260
+ it('finds the SI value', (): void => {
261
+ expect(
262
+ formatBalance.findSi('k')
263
+ ).toEqual({ power: 3, text: 'Kilo', value: 'k' });
264
+ });
265
+
266
+ it('returns default on not found', (): void => {
267
+ expect(
268
+ formatBalance.findSi('blah')
269
+ ).toEqual({ power: 0, text: 'Unit', value: '-' });
270
+ });
271
+ });
272
+
273
+ describe('defaults', (): void => {
274
+ it('returns defaults', (): void => {
275
+ expect(
276
+ formatBalance.getDefaults()
277
+ ).toEqual(FMT_DEFAULTS);
278
+ });
279
+
280
+ it('formats 123,456,789,000 (defaultDecimals=12)', (): void => {
281
+ formatBalance.setDefaults({ decimals: 12 });
282
+
283
+ expect(
284
+ formatBalance(TESTVAL)
285
+ ).toEqual('123.4567 mUnit');
286
+ });
287
+
288
+ it('formats 123,456,789,000 (defaultUnit=TEST)', (): void => {
289
+ formatBalance.setDefaults({ decimals: 12, unit: 'TEST' });
290
+
291
+ expect(
292
+ formatBalance(TESTVAL)
293
+ ).toEqual('123.4567 mTEST');
294
+ });
295
+ });
296
+ });