0
# @polkadot/util
1
2
@polkadot/util is a comprehensive TypeScript utility library providing essential functions for the Polkadot ecosystem. It offers type-safe utilities for data conversion, type checking, numeric operations, array manipulation, string processing, and cryptographic helpers designed to reduce boilerplate code in blockchain applications.
3
4
## Package Information
5
6
- **Package Name**: @polkadot/util
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @polkadot/util` or `yarn add @polkadot/util`
10
11
## Core Imports
12
13
```typescript
14
import {
15
isHex, isU8a, isString,
16
hexToU8a, u8aToHex,
17
BN, bnToBn,
18
arrayChunk, objectSpread
19
} from "@polkadot/util";
20
```
21
22
For CommonJS:
23
24
```javascript
25
const {
26
isHex, isU8a, isString,
27
hexToU8a, u8aToHex,
28
BN, bnToBn,
29
arrayChunk, objectSpread
30
} = require("@polkadot/util");
31
```
32
33
## Basic Usage
34
35
```typescript
36
import { isHex, hexToU8a, u8aToHex, BN, formatBalance } from "@polkadot/util";
37
38
// Type checking
39
if (isHex("0x1234abcd")) {
40
console.log("Valid hex string");
41
}
42
43
// Data conversion
44
const bytes = hexToU8a("0x48656c6c6f"); // Convert hex to Uint8Array
45
const hex = u8aToHex(bytes); // Convert back to hex
46
47
// Big number operations
48
const balance = new BN("1000000000000"); // 1 trillion in smallest units
49
const formatted = formatBalance(balance, { decimals: 12, withUnit: 'DOT' });
50
51
console.log(formatted); // "1.0000 DOT"
52
```
53
54
## Architecture
55
56
@polkadot/util is organized into focused modules, each providing specialized functionality:
57
58
- **Type System**: Comprehensive type checking utilities (`is*` functions) for runtime validation
59
- **Data Conversion**: Bi-directional conversion between hex strings, Uint8Arrays, numbers, and BigInts
60
- **Big Number Support**: Both native BigInt and BN.js support with utility functions and constants
61
- **Array Operations**: Functional utilities for array manipulation (chunk, flatten, zip, etc.)
62
- **String Processing**: Case conversion, formatting, and encoding utilities
63
- **Object Utilities**: Property manipulation and object transformation helpers
64
- **System Detection**: Environment capability detection for cross-platform compatibility
65
- **Performance Optimization**: Memoization, lazy evaluation, and efficient data structures
66
67
## Capabilities
68
69
### Type Checking Utilities
70
71
Comprehensive runtime type validation with 28 utility functions for checking data types and formats in JavaScript/TypeScript applications.
72
73
```typescript { .api }
74
function isHex(value: unknown, bitLength?: number, ignoreLength?: boolean): value is HexString;
75
function isU8a(value: unknown): value is Uint8Array;
76
function isString(value: unknown): value is string;
77
function isBn(value: unknown): value is BN;
78
function isNumber(value: unknown): value is number;
79
```
80
81
[Type Checking](./type-checking.md)
82
83
### Data Conversion
84
85
Bi-directional conversion utilities for transforming data between different formats commonly used in blockchain applications.
86
87
```typescript { .api }
88
function hexToU8a(value?: string | null, bitLength?: number): Uint8Array;
89
function u8aToHex(value?: Uint8Array | null, bitLength?: number, isPrefixed?: boolean): HexString;
90
function stringToU8a(value: string): Uint8Array;
91
function u8aToString(value: Uint8Array): string;
92
```
93
94
[Data Conversion](./data-conversion.md)
95
96
### Big Number Operations
97
98
Support for both native BigInt and BN.js big numbers with utility functions, constants, and conversion methods for high-precision arithmetic.
99
100
```typescript { .api }
101
// BigInt utilities
102
function nToBigInt(value: number | bigint | string): bigint;
103
function nToHex(value: bigint, bitLength?: number): HexString;
104
105
// BN.js utilities
106
function bnToBn(value: BN | number | string | bigint | Uint8Array): BN;
107
function bnToHex(value: BN, bitLength?: number): HexString;
108
109
class BN {
110
constructor(number: number | string | number[] | Uint8Array | Buffer | BN, base?: number | 'hex', endian?: 'le' | 'be');
111
}
112
```
113
114
[Big Number Operations](./big-numbers.md)
115
116
### Array Utilities
117
118
Functional array manipulation utilities for common operations like chunking, flattening, and data transformation.
119
120
```typescript { .api }
121
function arrayChunk<T>(array: T[], size: number): T[][];
122
function arrayFlatten<T>(array: (T | T[])[]): T[];
123
function arrayRange(size: number, startAt?: number): number[];
124
function arrayZip<T>(...arrays: T[][]): T[][];
125
```
126
127
[Array Utilities](./arrays.md)
128
129
### String Processing
130
131
String manipulation utilities including case conversion, formatting, and encoding/decoding operations.
132
133
```typescript { .api }
134
function stringCamelCase(value: string): string;
135
function stringPascalCase(value: string): string;
136
function stringShorten(value: string, prefixLength?: number, suffixLength?: number): string;
137
function stringToHex(value: string): HexString;
138
```
139
140
[String Processing](./strings.md)
141
142
### Object Utilities
143
144
Object manipulation helpers for property access, copying, and transformation operations.
145
146
```typescript { .api }
147
function objectSpread<T, S>(dest: T, ...sources: S[]): T & S;
148
function objectCopy<T>(source: T): T;
149
function objectKeys<T>(value: T): (keyof T)[];
150
function objectEntries<T>(value: T): [keyof T, T[keyof T]][];
151
```
152
153
[Object Utilities](./objects.md)
154
155
### Formatting and Display
156
157
Utilities for formatting numbers, balances, dates, and other data for user display with internationalization support.
158
159
```typescript { .api }
160
function formatBalance(value: BN | bigint | string | number, options?: FormatBalanceOptions): string;
161
function formatNumber(value: BN | bigint | string | number): string;
162
function formatDate(date: Date, fmt?: string): string;
163
164
interface FormatBalanceOptions {
165
decimals?: number;
166
forceUnit?: string;
167
locale?: string;
168
withSi?: boolean;
169
withUnit?: boolean | string;
170
withZero?: boolean;
171
}
172
```
173
174
[Formatting](./formatting.md)
175
176
### Compact Encoding
177
178
SCALE (Simple Concatenated Aggregate Little-Endian) compact encoding and decoding utilities for efficient data serialization.
179
180
```typescript { .api }
181
function compactToU8a(value: BN | bigint | number | string): Uint8Array;
182
function compactFromU8a(input: Uint8Array): [BN, number];
183
function compactAddLength(input: Uint8Array): Uint8Array;
184
function compactStripLength(input: Uint8Array): [Uint8Array, number];
185
```
186
187
[Compact Encoding](./compact.md)
188
189
### System and Environment
190
191
Environment detection utilities and system-level helpers for cross-platform compatibility and feature detection.
192
193
```typescript { .api }
194
const hasBigInt: boolean;
195
const hasBuffer: boolean;
196
const hasWasm: boolean;
197
198
function detectPackage(packageInfo: PackageInfo, path?: string, deps?: PackageInfo[]): void;
199
```
200
201
[System Utilities](./system.md)
202
203
## Types
204
205
```typescript { .api }
206
type HexString = `0x${string}`;
207
type U8aLike = number[] | Uint8Array | string;
208
type AnyString = string | String;
209
210
interface Logger {
211
debug: (...values: unknown[]) => void;
212
error: (...values: unknown[]) => void;
213
log: (...values: unknown[]) => void;
214
warn: (...values: unknown[]) => void;
215
}
216
217
interface Time {
218
days: number;
219
hours: number;
220
minutes: number;
221
seconds: number;
222
milliseconds: number;
223
}
224
225
interface ToBn {
226
toBn(): BN;
227
}
228
229
interface ToBigInt {
230
toBigInt(): bigint;
231
}
232
```