CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-polkadot--util

A collection of useful utilities for @polkadot ecosystem with type checking, data conversion, and performance optimization functions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

big-numbers.mddocs/

Big Number Operations

Support for both native BigInt and BN.js big numbers with utility functions, constants, and conversion methods for high-precision arithmetic operations in blockchain applications.

Capabilities

BigInt Utilities

Native JavaScript BigInt operations with utility functions for common mathematical operations.

/**
 * Converts number to BigInt
 * @param value - Number, bigint, or string to convert
 */
function nToBigInt(value: number | bigint | string): bigint;

/**
 * Converts BigInt to hex string
 * @param value - BigInt to convert
 * @param bitLength - Expected bit length for padding
 */
function nToHex(value: bigint, bitLength?: number): HexString;

/**
 * Converts BigInt to Uint8Array
 * @param value - BigInt to convert
 * @param bitLength - Expected bit length in bits
 */
function nToU8a(value: bigint, bitLength?: number): Uint8Array;

/**
 * Returns maximum of BigInt values
 * @param values - BigInt values to compare
 */
function nMax(...values: bigint[]): bigint;

/**
 * Returns minimum of BigInt values
 * @param values - BigInt values to compare
 */
function nMin(...values: bigint[]): bigint;

/**
 * Calculates square root of BigInt value
 * @param value - BigInt to calculate square root of
 */
function nSqrt(value: bigint): bigint;

BigInt Constants

Pre-defined BigInt constants for common values to avoid repeated conversions.

const _0n: bigint;   // 0n
const _1n: bigint;   // 1n
const _2n: bigint;   // 2n
const _3n: bigint;   // 3n
const _4n: bigint;   // 4n
const _5n: bigint;   // 5n
const _6n: bigint;   // 6n
const _7n: bigint;   // 7n
const _8n: bigint;   // 8n
const _9n: bigint;   // 9n
const _10n: bigint;  // 10n
const _100n: bigint; // 100n
const _1000n: bigint; // 1000n
const _1Mn: bigint;   // 1,000,000n (million)
const _1Bn: bigint;   // 1,000,000,000n (billion)
const _1Qn: bigint;   // 1,000,000,000,000,000,000n (quintillion)
const _2pow53n: bigint; // MAX_SAFE_INTEGER as BigInt
const _sqrt2pow53n: bigint; // Math.sqrt(MAX_SAFE_INTEGER) as BigInt

BN.js Utilities

BN.js big number operations for compatibility with existing blockchain libraries.

/**
 * Converts value to BN (big number)
 * @param value - Value to convert (number, string, bigint, Uint8Array, BN)
 */
function bnToBn(value: BN | number | string | bigint | Uint8Array): BN;

/**
 * Creates BN from hex string
 * @param value - Hex string to convert
 */
function bnFromHex(value: string): BN;

/**
 * Converts BN to hex string
 * @param value - BN to convert
 * @param bitLength - Expected bit length for padding
 */
function bnToHex(value: BN, bitLength?: number): HexString;

/**
 * Converts BN to Uint8Array
 * @param value - BN to convert
 * @param options - Conversion options (endianness, sign)
 */
function bnToU8a(value: BN, options?: ToBnOptions): Uint8Array;

/**
 * Returns maximum of BN values
 * @param values - BN values to compare
 */
function bnMax(...values: BN[]): BN;

/**
 * Returns minimum of BN values
 * @param values - BN values to compare
 */
function bnMin(...values: BN[]): BN;

/**
 * Calculates square root of BN value
 * @param value - BN to calculate square root of
 */
function bnSqrt(value: BN): BN;

BN Class

The BN class provides comprehensive big number arithmetic operations.

class BN {
  /**
   * Creates a new BN instance
   * @param number - Number, string, number array, Uint8Array, Buffer, or BN
   * @param base - Base for parsing (default 10, or 'hex')
   * @param endian - Endianness for array inputs ('le' or 'be')
   */
  constructor(number: number | string | number[] | Uint8Array | Buffer | BN, base?: number | 'hex', endian?: 'le' | 'be');

  // Arithmetic operations
  add(b: BN): BN;
  sub(b: BN): BN;
  mul(b: BN): BN;
  div(b: BN): BN;
  mod(b: BN): BN;
  pow(b: BN): BN;
  sqrt(): BN;
  
  // Comparison operations
  eq(b: BN): boolean;
  lt(b: BN): boolean;
  lte(b: BN): boolean;
  gt(b: BN): boolean;
  gte(b: BN): boolean;
  cmp(b: BN): -1 | 0 | 1;
  
  // Bitwise operations
  and(b: BN): BN;
  or(b: BN): BN;
  xor(b: BN): BN;
  shln(b: number): BN;
  shrn(b: number): BN;
  
  // Conversion methods
  toString(base?: number | 'hex', length?: number): string;
  toNumber(): number;
  toArray(endian?: 'le' | 'be', length?: number): number[];
  toBuffer(endian?: 'le' | 'be', length?: number): Buffer;
  
  // Utility methods
  isZero(): boolean;
  isNeg(): boolean;
  clone(): BN;
  neg(): BN;
  abs(): BN;
}

BN Constants

Pre-defined BN constants for common values.

const BN_ZERO: BN;           // BN(0)
const BN_ONE: BN;            // BN(1)
const BN_TWO: BN;            // BN(2)
const BN_THREE: BN;          // BN(3)
const BN_FOUR: BN;           // BN(4)
const BN_FIVE: BN;           // BN(5)
const BN_SIX: BN;            // BN(6)
const BN_SEVEN: BN;          // BN(7)
const BN_EIGHT: BN;          // BN(8)
const BN_NINE: BN;           // BN(9)
const BN_TEN: BN;            // BN(10)
const BN_HUNDRED: BN;        // BN(100)
const BN_THOUSAND: BN;       // BN(1000)
const BN_MILLION: BN;        // BN(1000000)
const BN_BILLION: BN;        // BN(1000000000)
const BN_QUINTILL: BN;       // BN(1000000000000000000)
const BN_MAX_INTEGER: BN;    // BN(Number.MAX_SAFE_INTEGER)
const BN_SQRT_MAX_INTEGER: BN; // BN(Math.sqrt(Number.MAX_SAFE_INTEGER))

Usage Examples

BigInt Operations:

import { 
  nToBigInt, nToHex, nMax, nMin, nSqrt,
  _1Mn, _1Bn, _2pow53n 
} from "@polkadot/util";

// Convert to BigInt
const value = nToBigInt("123456789012345678901234567890");
console.log(value); // 123456789012345678901234567890n

// Mathematical operations
const max = nMax(_1Mn, _1Bn, value); // Returns largest value
const min = nMin(_1Mn, _1Bn, value); // Returns smallest value
const sqrt = nSqrt(_1Bn); // Square root of 1 billion

// Convert to hex
const hex = nToHex(value, 256); // Hex with 256-bit padding

// Use constants
const largeValue = _2pow53n * _1Mn; // Very large calculation

BN.js Operations:

import { 
  BN, bnToBn, bnFromHex, bnToHex, 
  BN_ZERO, BN_ONE, BN_MILLION 
} from "@polkadot/util";

// Create BN instances
const bn1 = bnToBn("1000000000000000000000"); // From string
const bn2 = bnFromHex("0x1000000000000000000"); // From hex
const bn3 = new BN(123456789); // Direct constructor

// Arithmetic operations
const sum = bn1.add(bn2);
const difference = bn1.sub(bn2);
const product = bn1.mul(BN_MILLION);
const quotient = bn1.div(BN_ONE);

// Comparisons
if (sum.gt(BN_ZERO)) {
  console.log("Sum is positive");
}

// Convert back to different formats
const hex = bnToHex(sum); // To hex string
const str = sum.toString(); // To decimal string
const num = sum.toNumber(); // To number (if within safe range)

Balance Calculations:

import { BN, bnToBn, BN_MILLION } from "@polkadot/util";

// Calculate token amounts (assuming 12 decimals)
const DECIMALS = new BN(10).pow(new BN(12));

function toTokens(amount: string | number): BN {
  return bnToBn(amount).mul(DECIMALS);
}

function fromTokens(amount: BN): string {
  return amount.div(DECIMALS).toString();
}

// Usage
const userBalance = toTokens("100.5"); // 100.5 tokens in smallest units
const fee = toTokens("0.01"); // 0.01 tokens as fee
const remaining = userBalance.sub(fee);

console.log(`Remaining: ${fromTokens(remaining)} tokens`);

Working with Both BigInt and BN:

import { nToBigInt, bnToBn, BN } from "@polkadot/util";

function convertBetweenTypes(value: string) {
  // As BigInt (native)
  const asBigInt = nToBigInt(value);
  
  // As BN (library)
  const asBN = bnToBn(value);
  
  // Convert BN to BigInt
  const bnToBigInt = BigInt(asBN.toString());
  
  // Convert BigInt to BN
  const bigIntToBN = new BN(asBigInt.toString());
  
  return { asBigInt, asBN, bnToBigInt, bigIntToBN };
}

Types

interface ToBnOptions {
  isLe?: boolean;      // Little-endian byte order
  isNegative?: boolean; // Handle as negative number
}

type HexString = `0x${string}`;

Install with Tessl CLI

npx tessl i tessl/npm-polkadot--util

docs

arrays.md

big-numbers.md

compact.md

data-conversion.md

formatting.md

index.md

objects.md

strings.md

system.md

type-checking.md

tile.json