@polkadot/util

  • Version 9.2.1
  • Published
  • 493 kB
  • 8 dependencies
  • Apache-2.0 license

Install

npm i @polkadot/util
yarn add @polkadot/util
pnpm add @polkadot/util

Overview

A collection of useful utilities for @polkadot

Index

Variables

Functions

Variables

variable BN_BILLION

const BN_BILLION: BN;
  • BN_BILLION BN constant for 1,000,000,000.

variable BN_EIGHT

const BN_EIGHT: BN;
  • BN_EIGHT BN constant for 8.

variable BN_FIVE

const BN_FIVE: BN;
  • BN_FIVE BN constant for 5.

variable BN_FOUR

const BN_FOUR: BN;
  • BN_FOUR BN constant for 4.

variable BN_HUNDRED

const BN_HUNDRED: BN;
  • BN_HUNDRED BN constant for 100.

variable BN_MAX_INTEGER

const BN_MAX_INTEGER: BN;
  • BN_MAX_INTEGER BN constant for MAX_SAFE_INTEGER

variable BN_MILLION

const BN_MILLION: BN;
  • BN_MILLION BN constant for 1,000,000.

variable BN_NINE

const BN_NINE: BN;
  • BN_NINE BN constant for 9.

variable BN_ONE

const BN_ONE: BN;
  • BN_ONE BN constant for 1.

variable BN_QUINTILL

const BN_QUINTILL: BN;
  • BN_QUINTILL BN constant for 1,000,000,000,000,000,000.

variable BN_SEVEN

const BN_SEVEN: BN;
  • BN_SEVEN BN constant for 7.

variable BN_SIX

const BN_SIX: BN;
  • BN_SIX BN constant for 6.

variable BN_TEN

const BN_TEN: BN;
  • BN_TEN BN constant for 10.

variable BN_THOUSAND

const BN_THOUSAND: BN;
  • BN_THOUSAND BN constant for 1,000.

variable BN_THREE

const BN_THREE: BN;
  • BN_THREE BN constant for 3.

variable BN_TWO

const BN_TWO: BN;
  • BN_TWO BN constant for 2.

variable BN_ZERO

const BN_ZERO: BN;
  • BN_ZERO BN constant for 0.

variable formatBalance

const formatBalance: BalanceFormatter;

    variable hasBigInt

    const hasBigInt: boolean;

      variable hasBuffer

      const hasBuffer: boolean;

        variable hasCjs

        const hasCjs: boolean;

          variable hasDirname

          const hasDirname: boolean;

            variable hasEsm

            const hasEsm: boolean;

              variable hasProcess

              const hasProcess: boolean;

                variable hasWasm

                const hasWasm: boolean;

                  variable packageInfo

                  const packageInfo: { name: string; path: string; type: string; version: string };

                    variable U8A_WRAP_ETHEREUM

                    const U8A_WRAP_ETHEREUM: Uint8Array;

                      variable U8A_WRAP_POSTFIX

                      const U8A_WRAP_POSTFIX: Uint8Array;

                        variable U8A_WRAP_PREFIX

                        const U8A_WRAP_PREFIX: Uint8Array;

                          Functions

                          function arrayChunk

                          arrayChunk: <T>(array: T[], chunkSize: number) => T[][];
                          • arrayChunk Split T[] into T[][] based on the defind size Returns a set ao arrays based on the chunksize

                            Example 1

                            import { arrayChunk } from '@polkadot/util';
                            arrayChunk([1, 2, 3, 4, 5]); // [[1, 2], [3, 4], [5]]

                          function arrayFilter

                          arrayFilter: <T = any>(array: T[], allowNulls?: boolean) => T[];
                          • arrayFilter Filters undefined and (optionally) null values from an array Returns a new array with all undefined values removed. Optionally, when allowNulls = false, it removes the null values as well

                            Example 1

                            import { arrayFilter } from '@polkadot/util';
                            arrayFilter([0, void 0, true, null, false, '']); // [0, true, null, false, '']
                            arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, '']

                          function arrayFlatten

                          arrayFlatten: <T>(arrays: T[][]) => T[];
                          • arrayFlatten Merge T[][] into T[] Returns a new array with all arrays merged into one

                            Example 1

                            import { arrayFlatten } from '@polkadot/util';
                            arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]

                          function arrayRange

                          arrayRange: (size: number, startAt?: number) => number[];
                          • arrayRange Returns a range of numbers ith the size and the specified offset Returns a new array of numbers with the specific size. Optionally, when startAt, is provided, it generates the range to start at a specific value.

                            Example 1

                            import { arrayRange } from '@polkadot/util';
                            arrayRange(5); // [0, 1, 2, 3, 4]
                            arrayRange(3, 5); // [5, 6, 7]

                          function arrayShuffle

                          arrayShuffle: <T>(input: T[]) => T[];

                            function arrayZip

                            arrayZip: <K, V>(keys: K[], values: V[]) => [K, V][];

                              function assert

                              assert: (condition: unknown, message: string | MessageFn) => asserts condition;
                              • assert Checks for a valid test, if not Error is thrown. Checks that test is a truthy value. If value is falsy (null, undefined, false, ...), it throws an Error with the supplied message. When test passes, true is returned.

                                Example 1

                                const { assert } from '@polkadot/util';
                                assert(true, 'True should be true'); // passes
                                assert(false, 'False should not be true'); // Error thrown
                                assert(false, () => 'message'); // Error with 'message'

                              function assertReturn

                              assertReturn: <T>(value: T | undefined | null, message: string | MessageFn) => T;
                              • assertReturn Returns when the value is not undefined/null, otherwise throws assertion error

                              function assertUnreachable

                              assertUnreachable: (x: never) => never;
                              • assertUnreachable An assertion helper that ensures all codepaths are followed

                              function bnFromHex

                              bnFromHex: {
                              (value?: string | null, options?: ToBnOptions): BN;
                              (value?: string, options?: boolean): BN;
                              };
                              • hexToBn Creates a BN.js object from a hex string. null inputs returns a BN(0) result. Hex input values return the actual value converted to a BN. Anything that is not a hex string (including the 0x prefix) throws an error.

                                Parameter _value

                                The value to convert

                                Parameter _options

                                Options to pass while converting

                                Parameter

                                _options.isLe Convert using Little Endian

                                Parameter

                                _options.isNegative Convert using two's complement

                                Example 1

                                import { hexToBn } from '@polkadot/util';
                                hexToBn('0x123480001f'); // => BN(0x123480001f)
                              • Deprecated

                                Use hexToBn (value?: string | null, options?: ToBnOptions)

                              function bnMax

                              bnMax: (...items: BN[]) => BN;
                              • bnMax Finds and returns the highest value in an array of BNs.

                                Example 1

                                import BN from 'bn.js';
                                import { bnMax } from '@polkadot/util';
                                bnMax([new BN(1), new BN(3), new BN(2)]).toString(); // => '3'

                              function bnMin

                              bnMin: (...items: BN[]) => BN;
                              • bnMin Finds and returns the smallest value in an array of BNs.

                                Example 1

                                import BN from 'bn.js';
                                import { bnMin } from '@polkadot/util';
                                bnMin([new BN(1), new BN(3), new BN(2)]).toString(); // => '1'

                              function bnSqrt

                              bnSqrt: <ExtToBn extends ToBn>(
                              value: ExtToBn | BN | bigint | string | number | null
                              ) => BN;
                              • bnSqrt Calculates the integer square root of a BN

                                Example 1

                                import BN from 'bn.js';
                                import { bnSqrt } from '@polkadot/util';
                                bnSqrt(new BN(16)).toString(); // => '4'

                              function bnToBn

                              bnToBn: <ExtToBn extends ToBn | ToBigInt>(
                              value?: HexString | ExtToBn | BN | bigint | string | number | null
                              ) => BN;
                              • bnToBn Creates a BN value from a BN, bigint, string (base 10 or hex) or number input. null inputs returns a 0x0 result, BN values returns the value, numbers returns a BN representation.

                                Example 1

                                import BN from 'bn.js';
                                import { bnToBn } from '@polkadot/util';
                                bnToBn(0x1234); // => BN(0x1234)
                                bnToBn(new BN(0x1234)); // => BN(0x1234)

                              function bnToHex

                              bnToHex: {
                              <ExtToBn extends ToBn>(
                              value?: ExtToBn | BN | bigint | number | null,
                              options?: NumberOptions
                              ): HexString;
                              <ExtToBn extends ToBn>(
                              value?: any,
                              bitLength?: number,
                              isLe?: boolean
                              ): `0x${string}`;
                              };
                              • bnToHex Creates a hex value from a BN.js bignumber object. null inputs returns a 0x result, BN values return the actual value as a 0x prefixed hex value. Anything that is not a BN object throws an error. With bitLength set, it fixes the number to the specified length.

                                Example 1

                                import BN from 'bn.js';
                                import { bnToHex } from '@polkadot/util';
                                bnToHex(new BN(0x123456)); // => '0x123456'
                              • Deprecated

                                Use bnToHex (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions)

                              function bnToU8a

                              bnToU8a: {
                              <ExtToBn extends ToBn>(
                              value?: ExtToBn | BN | bigint | number | null,
                              options?: NumberOptions
                              ): Uint8Array;
                              <ExtToBn extends ToBn>(
                              value?: any,
                              bitLength?: number,
                              isLe?: boolean
                              ): Uint8Array;
                              };
                              • bnToU8a Creates a Uint8Array object from a BN. null/undefined/NaN inputs returns an empty Uint8Array result. BN input values return the actual bytes value converted to a Uint8Array. Optionally convert using little-endian format if isLE is set.

                                Example 1

                                import { bnToU8a } from '@polkadot/util';
                                bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
                              • Deprecated

                                Use bnToU8a(value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions)

                              function bufferToU8a

                              bufferToU8a: (buffer?: Buffer | number[] | null) => Uint8Array;
                              • bufferToU8a Creates a Uint8Array value from a Buffer object. null inputs returns an empty result, Buffer values return the actual value as a Uint8Array. Anything that is not a Buffer object throws an error.

                                Example 1

                                import { bufferToU8a } from '@polkadot/util';
                                bufferToU8a(Buffer.from([1, 2, 3]));

                              function calcSi

                              calcSi: (text: string, decimals: number, forceUnit?: string) => SiDef;

                                function compactAddLength

                                compactAddLength: (input: Uint8Array) => Uint8Array;
                                • compactAddLength Adds a length prefix to the input value

                                  Example 1

                                  import { compactAddLength } from '@polkadot/util';
                                  console.log(compactAddLength(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))); // Uint8Array([4 << 2, 0xde, 0xad, 0xbe, 0xef])

                                function compactFromU8a

                                compactFromU8a: (input: U8aLike) => [number, BN];
                                • compactFromU8a Retrives the offset and encoded length from a compact-prefixed value

                                  Example 1

                                  import { compactFromU8a } from '@polkadot/util';
                                  const [offset, length] = compactFromU8a(new Uint8Array([254, 255, 3, 0]));
                                  console.log('value offset=', offset, 'length=', length); // 4, 0xffff

                                function compactStripLength

                                compactStripLength: (input: Uint8Array) => [number, Uint8Array];
                                • compactStripLength Removes the length prefix, returning both the total length (including the value + compact encoding) and the decoded value with the correct length

                                  Example 1

                                  import { compactStripLength } from '@polkadot/util';
                                  console.log(compactStripLength(new Uint8Array([2 << 2, 0xde, 0xad]))); // [2, Uint8Array[0xde, 0xad]]

                                function compactToU8a

                                compactToU8a: (value: BN | bigint | number) => Uint8Array;
                                • compactToU8a Encodes a number into a compact representation

                                  Example 1

                                  import { compactToU8a } from '@polkadot/util';
                                  console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111])

                                function detectPackage

                                detectPackage: (
                                { name, path, type, version }: PackageJson,
                                pathOrFn?: FnString | string | false | null,
                                deps?: PackageJson[]
                                ) => void;
                                • detectPackage Checks that a specific package is only imported once A @polkadot/* version detection utility, checking for one occurence of a package in addition to checking for ddependency versions.

                                function extractTime

                                extractTime: (milliseconds?: number) => Time;
                                • extractTime Convert a quantity of seconds to Time array representing accumulated {days, minutes, hours, seconds, milliseconds}

                                  Example 1

                                  import { extractTime } from '@polkadot/util';
                                  const { days, minutes, hours, seconds, milliseconds } = extractTime(6000); // 0, 0, 10, 0, 0

                                function findSi

                                findSi: (type: string) => SiDef;

                                  function formatDate

                                  formatDate: (date: Date) => string;

                                    function formatDecimal

                                    formatDecimal: (value: string) => string;

                                      function formatElapsed

                                      formatElapsed: <ExtToBn extends ToBn>(
                                      now?: Date | null,
                                      value?: bigint | BN | ExtToBn | Date | number | null
                                      ) => string;

                                        function formatNumber

                                        formatNumber: <ExtToBn extends ToBn>(
                                        value?: ExtToBn | BN | bigint | number | null
                                        ) => string;

                                          function hexAddPrefix

                                          hexAddPrefix: (value?: string | null) => HexString;
                                          • hexAddPrefix Adds the 0x prefix to string values. Returns a 0x prefixed string from the input value. If the input is already prefixed, it is returned unchanged.

                                            Example 1

                                            import { hexAddPrefix } from '@polkadot/util';
                                            console.log('With prefix', hexAddPrefix('0a0b12')); // => 0x0a0b12

                                          function hexFixLength

                                          hexFixLength: (
                                          value: string,
                                          bitLength?: number,
                                          withPadding?: boolean
                                          ) => HexString;
                                          • hexFixLength Shifts a hex string to a specific bitLength Returns a 0x prefixed string with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. Input values with less bits are returned as-is by default. When withPadding is set, shorter values are padded with 0.

                                            Example 1

                                            import { hexFixLength } from '@polkadot/util';
                                            console.log('fixed', hexFixLength('0x12', 16)); // => 0x12
                                            console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012
                                            console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12

                                          function hexHasPrefix

                                          hexHasPrefix: (value?: string | null) => value is `0x${string}`;
                                          • hexHasPrefix Tests for the existence of a 0x prefix. Checks for a valid hex input value and if the start matched 0x

                                            Example 1

                                            import { hexHasPrefix } from '@polkadot/util';
                                            console.log('has prefix', hexHasPrefix('0x1234')); // => true

                                          function hexStripPrefix

                                          hexStripPrefix: (value?: string | null) => string;
                                          • hexStripPrefix Strips any leading 0x prefix. Tests for the existence of a 0x prefix, and returns the value without the prefix. Un-prefixed values are returned as-is.

                                            Example 1

                                            import { hexStripPrefix } from '@polkadot/util';
                                            console.log('stripped', hexStripPrefix('0x1234')); // => 1234

                                          function hexToBigInt

                                          hexToBigInt: (value?: string | null, options?: ToBnOptions) => bigint;
                                          • hexToBigInt Creates a BigInt instance object from a hex string.

                                          function hexToBn

                                          hexToBn: {
                                          (value?: string | null, options?: ToBnOptions): BN;
                                          (value?: string, options?: boolean): BN;
                                          };
                                          • hexToBn Creates a BN.js object from a hex string. null inputs returns a BN(0) result. Hex input values return the actual value converted to a BN. Anything that is not a hex string (including the 0x prefix) throws an error.

                                            Parameter _value

                                            The value to convert

                                            Parameter _options

                                            Options to pass while converting

                                            Parameter

                                            _options.isLe Convert using Little Endian

                                            Parameter

                                            _options.isNegative Convert using two's complement

                                            Example 1

                                            import { hexToBn } from '@polkadot/util';
                                            hexToBn('0x123480001f'); // => BN(0x123480001f)
                                          • Deprecated

                                            Use hexToBn (value?: string | null, options?: ToBnOptions)

                                          function hexToNumber

                                          hexToNumber: (value?: string | null) => number;
                                          • hexToNumber Creates a Number value from a Buffer object. null inputs returns an NaN result, hex values return the actual value as a Number.

                                            Example 1

                                            import { hexToNumber } from '@polkadot/util';
                                            hexToNumber('0x1234'); // => 0x1234

                                          function hexToString

                                          hexToString: (_value?: string | null) => string;
                                          • hexToU8a Creates a Uint8Array object from a hex string. Hex input values return the actual bytes value converted to a string. Anything that is not a hex string (including the 0x prefix) throws an error.

                                            Example 1

                                            import { hexToString } from '@polkadot/util';
                                            hexToU8a('0x68656c6c6f'); // hello

                                          function hexToU8a

                                          hexToU8a: (_value?: HexString | string | null, bitLength?: number) => Uint8Array;
                                          • hexToU8a Creates a Uint8Array object from a hex string. null inputs returns an empty Uint8Array result. Hex input values return the actual bytes value converted to a Uint8Array. Anything that is not a hex string (including the 0x prefix) throws an error.

                                            Example 1

                                            import { hexToU8a } from '@polkadot/util';
                                            hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
                                            hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])

                                          function isArray

                                          isArray: <T>(value?: unknown) => value is T[];
                                          • isArray Tests for a Array instance.

                                          function isAscii

                                          isAscii: (value?: U8aLike | null) => boolean;
                                          • isAscii Tests if the input is printable ASCII Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters

                                          function isBigInt

                                          isBigInt: (value: unknown) => value is bigint;
                                          • isBigInt Tests for a BigInt object instance. Checks to see if the input object is an instance of BigInt

                                            Example 1

                                            import { isBigInt } from '@polkadot/util';
                                            console.log('isBigInt', isBigInt(123_456n)); // => true

                                          function isBn

                                          isBn: (value: unknown) => value is BN;
                                          • isBn Tests for a BN object instance. Checks to see if the input object is an instance of BN (bn.js).

                                            Example 1

                                            import BN from 'bn.js';
                                            import { isBn } from '@polkadot/util';
                                            console.log('isBn', isBn(new BN(1))); // => true

                                          function isBoolean

                                          isBoolean: (value: unknown) => value is boolean;
                                          • isBoolean Tests for a boolean value. Checks to see if the input value is a JavaScript boolean.

                                            Example 1

                                            import { isBoolean } from '@polkadot/util';
                                            isBoolean(false); // => true

                                          function isBuffer

                                          isBuffer: (value: unknown) => value is Buffer;
                                          • isBuffer Tests for a Buffer object instance. Checks to see if the input object is an instance of Buffer.

                                            Example 1

                                            import { isBuffer } from '@polkadot/util';
                                            console.log('isBuffer', isBuffer(Buffer.from([]))); // => true

                                          function isChildClass

                                          isChildClass: <P extends Constructor<any>>(
                                          Parent: P,
                                          Child?: Constructor | null | unknown
                                          ) => Child is P;
                                          • isChildClass Tests if the child extends the parent Class Checks to see if the child Class extends the parent Class

                                            Example 1

                                            import { isChildClass } from '@polkadot/util';
                                            console.log('isChildClass', isChildClass(BN, BN); // => true
                                            console.log('isChildClass', isChildClass(BN, Uint8Array); // => false

                                          function isCodec

                                          isCodec: <T extends Codec = Codec>(value?: unknown) => value is T;

                                            function isCompact

                                            isCompact: <T>(value?: unknown) => value is Compact<T>;
                                            • isCompact Tests for SCALE-Compact-like object instance.

                                            function isError

                                            isError: (value: unknown) => value is Error;
                                            • isError Tests for a Error object instance. Checks to see if the input object is an instance of Error.

                                              Example 1

                                              import { isError } from '@polkadot/util';
                                              console.log('isError', isError(new Error('message'))); // => true

                                            function isFunction

                                            isFunction: (value: unknown) => value is Function;
                                            • isFunction Tests for a function. Checks to see if the input value is a JavaScript function.

                                              Example 1

                                              import { isFunction } from '@polkadot/util';
                                              isFunction(() => false); // => true

                                            function isHex

                                            isHex: (
                                            value: unknown,
                                            bitLength?: number,
                                            ignoreLength?: boolean
                                            ) => value is `0x${string}`;
                                            • isHex Tests for a hex string. Checks to see if the input value is a 0x prefixed hex string. Optionally (bitLength !== -1) checks to see if the bitLength is correct.

                                              Example 1

                                              import { isHex } from '@polkadot/util';
                                              isHex('0x1234'); // => true
                                              isHex('0x1234', 8); // => false

                                            function isInstanceOf

                                            isInstanceOf: (value: unknown, clazz: Function) => boolean;
                                            • isInstanceOf Tests for a instance of a class. Checks to see if the input value is an instance of the test class.

                                              Example 1

                                              import { isInstanceOf } from '@polkadot/util';
                                              console.log('isInstanceOf', isInstanceOf(new Array(0), Array)); // => true

                                            function isIp

                                            isIp: (value: string, type?: IpTypes) => boolean;
                                            • isIp Tests if the value is a valid IP address Checks to see if the value is a valid IP address. Optionally check for either v4/v6

                                              Example 1

                                              import { isIp } from '@polkadot/util';
                                              isIp('192.168.0.1')); // => true
                                              isIp('1:2:3:4:5:6:7:8'); // => true
                                              isIp('192.168.0.1', 'v6')); // => false
                                              isIp('1:2:3:4:5:6:7:8', 'v4'); // => false

                                            function isJsonObject

                                            isJsonObject: (value: unknown) => value is ObjectIndexed;
                                            • isJsonObject Tests for a valid JSON object. Checks to see if the input value is a valid JSON object. It returns false if the input is JSON parsable, but not an Javascript object.

                                              Example 1

                                              import { isJsonObject } from '@polkadot/util';
                                              isJsonObject({}); // => true
                                              isJsonObject({
                                              "Test": "1234",
                                              "NestedTest": {
                                              "Test": "5678"
                                              }
                                              }); // => true
                                              isJsonObject(1234); // JSON parsable, but not an object => false
                                              isJsonObject(null); // JSON parsable, but not an object => false
                                              isJsonObject('not an object'); // => false

                                            function isNull

                                            isNull: (value?: unknown) => value is null;
                                            • isNull Tests for a null values. Checks to see if the input value is null.

                                              Example 1

                                              import { isNull } from '@polkadot/util';
                                              console.log('isNull', isNull(null)); // => true

                                            function isNumber

                                            isNumber: (value: unknown) => value is number;
                                            • isNumber Tests for a JavaScript number. Checks to see if the input value is a valid number.

                                              Example 1

                                              import { isNumber } from '@polkadot/util';
                                              console.log('isNumber', isNumber(1234)); // => true

                                            function isObject

                                            isObject: <T extends ObjectIndexed = ObjectIndexed>(
                                            value?: unknown
                                            ) => value is T;
                                            • isObject Tests for an object. Checks to see if the input value is a JavaScript object.

                                              Example 1

                                              import { isObject } from '@polkadot/util';
                                              isObject({}); // => true
                                              isObject('something'); // => false

                                            function isObservable

                                            isObservable: (value?: unknown) => value is Observable;
                                            • isBObservable Tests for a Observable object instance. Checks to see if the input object is an instance of BN (bn.js).

                                              Example 1

                                              import { isObservable } from '@polkadot/util';
                                              console.log('isObservable', isObservable(...));

                                            function isPromise

                                            isPromise: (value?: unknown) => value is Promise<unknown>;

                                              function isString

                                              isString: (value: unknown) => value is AnyString;
                                              • isString Tests for a string. Checks to see if the input value is a JavaScript string.

                                                Example 1

                                                import { isString } from '@polkadot/util';
                                                console.log('isString', isString('test')); // => true

                                              function isTestChain

                                              isTestChain: (chain?: string | null) => boolean;

                                                function isToBigInt

                                                isToBigInt: (value?: unknown) => value is ToBigInt;

                                                  function isToBn

                                                  isToBn: (value?: unknown) => value is ToBn;

                                                    function isU8a

                                                    isU8a: (value?: unknown) => value is Uint8Array;
                                                    • isU8a Tests for a Uint8Array object instance. Checks to see if the input object is an instance of Uint8Array.

                                                      Example 1

                                                      import { isUint8Array } from '@polkadot/util';
                                                      console.log('isU8a', isU8a([])); // => false

                                                    function isUndefined

                                                    isUndefined: (value?: unknown) => value is undefined;
                                                    • isUndefined Tests for a undefined values. Checks to see if the input value is undefined.

                                                      Example 1

                                                      import { isUndefined } from '@polkadot/util';
                                                      console.log('isUndefined', isUndefined(void(0))); // => true

                                                    function isUtf8

                                                    isUtf8: (
                                                    value?: HexString | number[] | Buffer | Uint8Array | string | null
                                                    ) => boolean;
                                                    • isUtf8 Tests if the input is valid Utf8 Checks to see if the input string or Uint8Array is valid Utf8

                                                    function isWasm

                                                    isWasm: (value?: unknown) => value is Uint8Array;
                                                    • isWasm Tests if the input has a WASM header Checks to see if the input Uint8Array contains a valid WASM header

                                                    function lazyMethod

                                                    lazyMethod: <T, K>(
                                                    result: Record<string, T> | AnyFn,
                                                    item: K,
                                                    creator: (d: K) => T,
                                                    getName?: (d: K) => string
                                                    ) => void;

                                                      function lazyMethods

                                                      lazyMethods: <T, K>(
                                                      result: Record<string, T>,
                                                      items: K[],
                                                      creator: (v: K) => T,
                                                      getName?: (m: K) => string
                                                      ) => Record<string, T>;

                                                        function logger

                                                        logger: (_type: string) => Logger;
                                                        • Logger Creates a consistent log interface for messages Returns a Logger that has .log, .error, .warn and .debug (controlled with environment DEBUG=typeA,typeB) methods. Logging is done with a consistent prefix (type of logger, date) followed by the actual message using the underlying console.

                                                          Example 1

                                                          import { logger } from '@polkadot';
                                                          const l = logger('test');

                                                        function loggerFormat

                                                        loggerFormat: (value: unknown) => unknown;

                                                          function memoize

                                                          memoize: <T, F extends (...args: any[]) => T>(
                                                          fn: F,
                                                          { getInstanceId }?: Options
                                                          ) => Memoized<F>;

                                                            function nMax

                                                            nMax: (...items: bigint[]) => bigint;
                                                            • nMax Finds and returns the highest value in an array of bigint.

                                                            function nMin

                                                            nMin: (...items: bigint[]) => bigint;
                                                            • nMin Finds and returns the lowest value in an array of bigint.

                                                            function nSqrt

                                                            nSqrt: <ExtToBn extends ToBn | ToBigInt>(
                                                            value: ExtToBn | BN | bigint | string | number | null
                                                            ) => bigint;
                                                            • nSqrt Calculates the integer square root of a bigint

                                                            function nToBigInt

                                                            nToBigInt: <ExtToBn extends ToBn | ToBigInt>(
                                                            value?: HexString | ExtToBn | BN | bigint | string | number | null
                                                            ) => bigint;
                                                            • nToBigInt Creates a bigInt value from a BN, bigint, string (base 10 or hex) or number input.

                                                            function nToHex

                                                            nToHex: <ExtToBn extends ToBn | ToBigInt>(
                                                            value?: ExtToBn | BN | bigint | number | null,
                                                            options?: NumberOptions
                                                            ) => HexString;
                                                            • nToHex Creates a hex value from a bigint object.

                                                            function nToU8a

                                                            nToU8a: <ExtToBn extends ToBn | ToBigInt>(
                                                            value?: ExtToBn | BN | bigint | number | null,
                                                            options?: NumberOptions
                                                            ) => Uint8Array;
                                                            • nToU8a Creates a Uint8Array object from a bigint.

                                                            function numberToHex

                                                            numberToHex: (value?: number | null, bitLength?: number) => HexString;
                                                            • numberToHex Creates a hex value from a number. null/undefined/NaN inputs returns an empty 0x result. number input values return the actual bytes value converted to a hex. With bitLength set, it converts the number to the equivalent size.

                                                              Example 1

                                                              import { numberToHex } from '@polkadot/util';
                                                              numberToHex(0x1234); // => '0x1234'
                                                              numberToHex(0x1234, 32); // => 0x00001234

                                                            function numberToU8a

                                                            numberToU8a: (value?: number | null, bitLength?: number) => Uint8Array;
                                                            • numberToU8a Creates a Uint8Array object from a number. null/undefined/NaN inputs returns an empty Uint8Array result. number input values return the actual bytes value converted to a Uint8Array. With bitLength, it converts the value to the equivalent size.

                                                              Example 1

                                                              import { numberToU8a } from '@polkadot/util';
                                                              numberToU8a(0x1234); // => [0x12, 0x34]

                                                            function objectClear

                                                            objectClear: <T>(value: Record<string, T>) => Record<string, T>;
                                                            • objectClear Removes all the keys from the input object

                                                            function objectCopy

                                                            objectCopy: <T extends object>(source: T) => T;
                                                            • objectCopy Creates a shallow clone of the input object

                                                            function objectEntries

                                                            objectEntries: <T extends object>(obj: T) => Entries<T>;
                                                            • objectEntries A version of Object.entries that is typed for TS

                                                            function objectKeys

                                                            objectKeys: <T extends object, K extends Extract<keyof T, string>>(
                                                            value: T
                                                            ) => K[];
                                                            • objectKeys A version of Object.keys that is typed for TS

                                                            function objectProperties

                                                            objectProperties: (
                                                            that: object,
                                                            keys: string[],
                                                            getter: (k: string, i: number) => unknown
                                                            ) => void;
                                                            • objectProperties Assign get properties on the input object

                                                            function objectProperty

                                                            objectProperty: (
                                                            that: object,
                                                            key: string,
                                                            getter: (k: string) => unknown
                                                            ) => void;
                                                            • objectProperty Assign a get property on the input object

                                                            function objectSpread

                                                            objectSpread: <T extends object>(
                                                            dest: object,
                                                            ...sources: (object | undefined | null)[]
                                                            ) => T;
                                                            • objectSpread Concats all sources into the destination

                                                            function objectValues

                                                            objectValues: <T extends object>(obj: T) => T[keyof T][];
                                                            • objectValues A version of Object.values that is typed for TS

                                                            function promisify

                                                            promisify: <R = any>(
                                                            self: unknown,
                                                            fn: (...params: any) => any,
                                                            ...params: any[]
                                                            ) => Promise<R>;
                                                            • promisify Wraps an async callback into a Promise Wraps the supplied async function fn that has a standard JS callback (error: Error, result: any) into a Promise, passing the supplied parameters. When error is set, the Promise is rejected, else the Promise resolves with the result value.

                                                              Example 1

                                                              const { promisify } from '@polkadot/util';
                                                              await promisify(null, ((a, cb) => cb(null, a), true); // resolves with `true`
                                                              await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!`

                                                            function stringCamelCase

                                                            stringCamelCase: (value: AnyString) => string;
                                                            • stringCamelCase Convert a dash/dot/underscore/space separated Ascii string/String to camelCase

                                                            function stringify

                                                            stringify: (value: unknown, space?: string | number) => string;
                                                            • stringify Performs a JSON.stringify, with BigInt handling A wrapper for JSON.stringify that handles BigInt values transparently, converting them to string. No differences from the native JSON.stringify function otherwise.

                                                            function stringLowerFirst

                                                            stringLowerFirst: (value?: AnyString | null | undefined) => string;
                                                            • stringLowerFirst Lowercase the first letter of a string Lowercase the first letter of a string

                                                              Example 1

                                                              import { stringLowerFirst } from '@polkadot/util';
                                                              stringLowerFirst('ABC'); // => 'aBC'

                                                            function stringPascalCase

                                                            stringPascalCase: (value: AnyString) => string;
                                                            • stringPascalCase Convert a dash/dot/underscore/space separated Ascii string/String to PascalCase

                                                            function stringShorten

                                                            stringShorten: (value: AnyString, prefixLength?: number) => string;
                                                            • stringShorten Returns a string with maximum length Checks the string against the prefixLength, if longer than double this, shortens it by placing .. in the middle of it

                                                              Example 1

                                                              import { stringShorten } from '@polkadot/util';
                                                              stringShorten('1234567890', 2); // => 12..90

                                                            function stringToHex

                                                            stringToHex: (value?: AnyString) => HexString;
                                                            • stringToHex Creates a hex string from a utf-8 string String input values return the actual encoded hex value.

                                                              Example 1

                                                              import { stringToHex } from '@polkadot/util';
                                                              stringToU8a('hello'); // 0x68656c6c6f

                                                            function stringToU8a

                                                            stringToU8a: (value?: AnyString) => Uint8Array;
                                                            • stringToU8a Creates a Uint8Array object from a utf-8 string. String input values return the actual encoded UInt8Array. null or undefined values returns an empty encoded array.

                                                              Example 1

                                                              import { stringToU8a } from '@polkadot/util';
                                                              stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f]

                                                            function stringUpperFirst

                                                            stringUpperFirst: (value?: AnyString | null | undefined) => string;
                                                            • stringUpperFirst Uppercase the first letter of a string Lowercase the first letter of a string

                                                              Example 1

                                                              import { stringUpperFirst } from '@polkadot/util';
                                                              stringUpperFirst('abc'); // => 'Abc'

                                                            function u8aCmp

                                                            u8aCmp: (
                                                            a: HexString | Uint8Array | string,
                                                            b: HexString | Uint8Array | string
                                                            ) => number;
                                                            • u8aCmp Compares two Uint8Arrays for sorting. For UInt8Array (or hex string) input values returning -1, 0 or +1

                                                              Example 1

                                                              import { u8aCmp } from '@polkadot/util';
                                                              u8aCmp(new Uint8Array([0x67, 0x65]), new Uint8Array([0x68, 0x65])); // -1
                                                              u8aCmp(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // 0
                                                              u8aCmp(new Uint8Array([0x69, 0x65]), new Uint8Array([0x68, 0x65])); // +1

                                                            function u8aConcat

                                                            u8aConcat: (...list: U8aLike[]) => Uint8Array;
                                                            • u8aConcat Creates a concatenated Uint8Array from the inputs. Concatenates the input arrays into a single UInt8Array.

                                                              Example 1

                                                              import { { u8aConcat } from '@polkadot/util';
                                                              u8aConcat(
                                                              new Uint8Array([1, 2, 3]),
                                                              new Uint8Array([4, 5, 6])
                                                              ); // [1, 2, 3, 4, 5, 6]

                                                            function u8aEmpty

                                                            u8aEmpty: (value: Uint8Array) => boolean;
                                                            • u8aEmpty Tests for a Uint8Array for emptyness Checks to see if the input Uint8Array has zero length or contains all 0 values.

                                                            function u8aEq

                                                            u8aEq: (
                                                            a: HexString | Uint8Array | string,
                                                            b: HexString | Uint8Array | string
                                                            ) => boolean;
                                                            • u8aEq Compares two Uint8Arrays for equality. For UInt8Array (or hex string) input values true if there is a match.

                                                              Example 1

                                                              import { u8aEq } from '@polkadot/util';
                                                              u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true

                                                            function u8aFixLength

                                                            u8aFixLength: (
                                                            value: Uint8Array,
                                                            bitLength?: number,
                                                            atStart?: boolean
                                                            ) => Uint8Array;
                                                            • u8aFixLength Shifts a Uint8Array to a specific bitLength Returns a uint8Array with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length.

                                                              Example 1

                                                              import { u8aFixLength } from '@polkadot/util';
                                                              u8aFixLength('0x12') // => 0x12
                                                              u8aFixLength('0x12', 16) // => 0x0012
                                                              u8aFixLength('0x1234', 8) // => 0x12

                                                            function u8aIsWrapped

                                                            u8aIsWrapped: (u8a: Uint8Array, withEthereum: boolean) => boolean;

                                                              function u8aSorted

                                                              u8aSorted: (u8as: Uint8Array[]) => Uint8Array[];
                                                              • u8aSorted Sorts an array of Uint8Arrays For input UInt8Array[] return the sorted result

                                                                Example 1

                                                                import { u8aSorted} from '@polkadot/util';
                                                                u8aSorted([new Uint8Array([0x69]), new Uint8Array([0x68])]); // [0x68, 0x69]

                                                              function u8aToBigInt

                                                              u8aToBigInt: (value: Uint8Array, options?: ToBnOptions) => bigint;
                                                              • u8aToBigInt Creates a BigInt from a Uint8Array object.

                                                              function u8aToBn

                                                              u8aToBn: {
                                                              (value: Uint8Array, options?: ToBnOptions): BN;
                                                              (value: Uint8Array, options?: boolean): BN;
                                                              };
                                                              • u8aToBn Creates a BN from a Uint8Array object. UInt8Array input values return the actual BN. null or undefined values returns an 0x0 value.

                                                                Parameter value

                                                                The value to convert

                                                                Parameter options

                                                                Options to pass while converting

                                                                Parameter

                                                                options.isLe Convert using Little Endian (default)

                                                                Parameter

                                                                options.isNegative Convert using two's complement

                                                                Example 1

                                                                import { u8aToBn } from '@polkadot/util';
                                                                u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
                                                              • Deprecated

                                                                Use u8aToBn(value: Uint8Array, options?: ToBnOptions)

                                                              function u8aToBuffer

                                                              u8aToBuffer: (value?: Uint8Array | null) => Buffer;
                                                              • u8aToBuffer Creates a Buffer object from a hex string. null inputs returns an empty Buffer result. UInt8Array input values return the actual bytes value converted to a Buffer. Anything that is not a UInt8Array throws an error.

                                                                Example 1

                                                                import { u8aToBuffer } from '@polkadot/util';
                                                                console.log('Buffer', u8aToBuffer('0x123480001f'));

                                                              function u8aToHex

                                                              u8aToHex: (
                                                              value?: Uint8Array | null,
                                                              bitLength?: number,
                                                              isPrefixed?: boolean
                                                              ) => HexString;
                                                              • u8aToHex Creates a hex string from a Uint8Array object. UInt8Array input values return the actual hex string. null or undefined values returns an 0x string.

                                                                Example 1

                                                                import { u8aToHex } from '@polkadot/util';
                                                                u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f

                                                              function u8aToString

                                                              u8aToString: (value?: Uint8Array | null) => string;
                                                              • u8aToString Creates a utf-8 string from a Uint8Array object. UInt8Array input values return the actual decoded utf-8 string. null or undefined values returns an empty string.

                                                                Example 1

                                                                import { u8aToString } from '@polkadot/util';
                                                                u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello

                                                              function u8aToU8a

                                                              u8aToU8a: (value?: U8aLike | null) => Uint8Array;
                                                              • u8aToU8a Creates a Uint8Array value from a Uint8Array, Buffer, string or hex input. null or undefined inputs returns a [] result, Uint8Array values returns the value, hex strings returns a Uint8Array representation.

                                                                Example 1

                                                                import { u8aToU8a } from '@polkadot/util';
                                                                u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34])
                                                                u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34])

                                                              function u8aUnwrapBytes

                                                              u8aUnwrapBytes: (bytes: U8aLike) => Uint8Array;

                                                                function u8aWrapBytes

                                                                u8aWrapBytes: (bytes: U8aLike) => Uint8Array;

                                                                  Package Files (103)

                                                                  Dependencies (8)

                                                                  Dev Dependencies (0)

                                                                  No dev dependencies.

                                                                  Peer Dependencies (0)

                                                                  No peer dependencies.

                                                                  Badge

                                                                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@polkadot/util.

                                                                  • Markdown
                                                                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@polkadot/util)
                                                                  • HTML
                                                                    <a href="https://www.jsdocs.io/package/@polkadot/util"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>