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

formatting.mddocs/

Formatting and Display

Utilities for formatting numbers, balances, dates, and other data for user display with internationalization support and SI unit handling.

Capabilities

Balance Formatting

Format cryptocurrency balances and token amounts with proper decimal handling and unit display.

/**
 * Formats balance values with SI units and proper decimal places
 * @param value - Balance value (BN, bigint, string, or number) 
 * @param options - Formatting options
 */
function formatBalance(value: BN | bigint | string | number, options?: FormatBalanceOptions): string;

interface FormatBalanceOptions {
  decimals?: number;        // Number of decimal places (default: 12)
  forceUnit?: string;       // Force specific unit (e.g., 'k', 'M', 'G')
  locale?: string;          // Locale for number formatting
  withSi?: boolean;         // Include SI unit suffix (default: true)
  withUnit?: boolean | string; // Include unit name (true for default, string for custom)
  withZero?: boolean;       // Show zero values (default: true)
}

Number Formatting

Format numbers with thousand separators and proper locale support.

/**
 * Formats numbers with thousand separators
 * @param value - Number to format (BN, bigint, string, or number)
 */
function formatNumber(value: BN | bigint | string | number): string;

/**
 * Formats decimal numbers with consistent decimal places
 * @param value - Decimal number to format
 * @param locale - Locale for formatting (optional)
 */
function formatDecimal(value: number, locale?: string): string;

Date and Time Formatting

Format dates and elapsed time for user display.

/**
 * Formats Date objects to strings
 * @param date - Date to format
 * @param fmt - Format string (optional)
 */
function formatDate(date: Date, fmt?: string): string;

/**
 * Formats elapsed time in human-readable format
 * @param now - Current time
 * @param value - Past time to compare against
 */
function formatElapsed(now: Date, value: Date): string;

Time Extraction

Convert milliseconds to structured time objects.

/**
 * Converts milliseconds to Time object with days, hours, minutes, seconds, milliseconds
 * @param milliseconds - Time in milliseconds
 */
function extractTime(milliseconds: number): Time;

interface Time {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  milliseconds: number;
}

SI Unit Utilities

Calculate and find appropriate SI (International System of Units) prefixes.

/**
 * Calculates appropriate SI unit for a given value
 * @param value - Value to calculate SI unit for
 * @param decimals - Number of decimal places (default: 12)
 */
function calcSi(value: string, decimals?: number): SiDef;

/**
 * Finds SI unit definition by power
 * @param power - Power of 10 (e.g., 3 for 'k', 6 for 'M')
 */
function findSi(power: number): SiDef;

interface SiDef {
  power: number;    // Power of 10
  text: string;     // Unit suffix (e.g., 'k', 'M', 'G')
  value: number;    // Multiplier value
}

Usage Examples

Balance Formatting:

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

// Format DOT balance (12 decimals)
const balance = new BN("1234567890123456"); // Raw balance in Planck (smallest unit)
const formatted = formatBalance(balance, { 
  decimals: 12, 
  withUnit: 'DOT' 
});
console.log(formatted); // "1.2346 DOT"

// Format with SI units
const largeBalance = new BN("1234567890123456789");
const withSi = formatBalance(largeBalance, { 
  decimals: 12,
  withSi: true,
  withUnit: 'DOT'
});
console.log(withSi); // "1.2346k DOT"

// Format without decimals for whole numbers
const wholeBalance = new BN("1000000000000"); // Exactly 1 DOT
const clean = formatBalance(wholeBalance, { 
  decimals: 12,
  withUnit: 'DOT'
});
console.log(clean); // "1 DOT"

// Custom locale formatting
const euroBalance = formatBalance(balance, {
  decimals: 12,
  locale: 'de-DE',
  withUnit: 'EUR'
});
console.log(euroBalance); // "1,2346 EUR" (German formatting)

Token Amount Display:

import { formatBalance, formatNumber, BN } from "@polkadot/util";

function displayTokenAmount(
  rawAmount: string | BN, 
  tokenSymbol: string, 
  decimals: number = 18
) {
  const amount = formatBalance(rawAmount, {
    decimals,
    withUnit: tokenSymbol,
    withSi: true
  });
  
  return amount;
}

// ERC-20 token with 18 decimals
const usdcAmount = "1500000000000000000000"; // 1500 USDC
console.log(displayTokenAmount(usdcAmount, "USDC", 6)); // "1.5k USDC"

// Display wallet balances
const walletBalances = [
  { symbol: "DOT", amount: "12345678901234567890", decimals: 12 },
  { symbol: "KSM", amount: "9876543210987654", decimals: 12 },
  { symbol: "USDT", amount: "50000000", decimals: 6 }
];

walletBalances.forEach(({ symbol, amount, decimals }) => {
  const display = displayTokenAmount(amount, symbol, decimals);
  console.log(`${symbol}: ${display}`);
});
// DOT: 12.3457k DOT
// KSM: 9.8765 KSM  
// USDT: 50 USDT

Number Formatting:

import { formatNumber, formatDecimal } from "@polkadot/util";

// Format large numbers with separators
const largeNumber = 1234567890;
console.log(formatNumber(largeNumber)); // "1,234,567,890"

// Format BigInt values
const hugeBigInt = BigInt("123456789012345678901234567890");
console.log(formatNumber(hugeBigInt)); // "123,456,789,012,345,678,901,234,567,890"

// Format decimal values
const decimal = 1234.56789;
console.log(formatDecimal(decimal)); // "1,234.57" (rounded to 2 decimals)
console.log(formatDecimal(decimal, 'fr-FR')); // "1 234,57" (French formatting)

// Display statistics
const stats = {
  totalUsers: 1247893,
  totalTransactions: 89654321,
  totalVolume: "98765432101234567890"
};

console.log(`Users: ${formatNumber(stats.totalUsers)}`);
console.log(`Transactions: ${formatNumber(stats.totalTransactions)}`);
console.log(`Volume: ${formatNumber(stats.totalVolume)}`);
// Users: 1,247,893
// Transactions: 89,654,321
// Volume: 98,765,432,101,234,567,890

Date and Time Formatting:

import { formatDate, formatElapsed, extractTime } from "@polkadot/util";

// Format current date
const now = new Date();
console.log(formatDate(now)); // "2023-12-07 14:30:15" (default format)

// Format with custom format (if supported)
console.log(formatDate(now, 'YYYY-MM-DD')); // "2023-12-07"

// Show elapsed time
const pastTime = new Date(Date.now() - 3600000); // 1 hour ago
console.log(formatElapsed(now, pastTime)); // "1 hour ago"

// Extract time components
const duration = 90061500; // 1 day, 1 hour, 1 minute, 1.5 seconds
const time = extractTime(duration);
console.log(time);
// {
//   days: 1,
//   hours: 1, 
//   minutes: 1,
//   seconds: 1,
//   milliseconds: 500
// }

// Format duration display
function formatDuration(ms: number): string {
  const time = extractTime(ms);
  const parts = [];
  
  if (time.days > 0) parts.push(`${time.days}d`);
  if (time.hours > 0) parts.push(`${time.hours}h`);
  if (time.minutes > 0) parts.push(`${time.minutes}m`);
  if (time.seconds > 0) parts.push(`${time.seconds}s`);
  
  return parts.join(' ') || '0s';
}

console.log(formatDuration(90061500)); // "1d 1h 1m 1s"
console.log(formatDuration(5000)); // "5s"

SI Unit Calculations:

import { calcSi, findSi, formatBalance } from "@polkadot/util";

// Calculate appropriate SI unit for large numbers
const largeValue = "1234567890123";
const si = calcSi(largeValue, 12);
console.log(si); // { power: 3, text: 'k', value: 1000 }

// Find SI unit by power
const megaUnit = findSi(6);
console.log(megaUnit); // { power: 6, text: 'M', value: 1000000 }

// Custom formatting with SI units
function formatWithCustomSi(value: string, decimals: number = 12): string {
  const si = calcSi(value, decimals);
  const divisor = Math.pow(10, decimals + si.power);
  const formatted = (parseFloat(value) / divisor).toFixed(4);
  
  return `${formatted}${si.text}`;
}

console.log(formatWithCustomSi("1234567890123456", 12)); // "1.2346k"
console.log(formatWithCustomSi("1234567890123456789", 12)); // "1.2346M"

Dashboard Display Components:

import { formatBalance, formatNumber, formatElapsed } from "@polkadot/util";

interface DashboardData {
  totalStaked: string;
  totalRewards: string;
  activeValidators: number;
  lastUpdate: Date;
  stakingApr: number;
}

function formatDashboard(data: DashboardData) {
  const now = new Date();
  
  return {
    totalStaked: formatBalance(data.totalStaked, { 
      decimals: 12, 
      withUnit: 'DOT',
      withSi: true 
    }),
    totalRewards: formatBalance(data.totalRewards, { 
      decimals: 12, 
      withUnit: 'DOT',
      withSi: true 
    }),
    activeValidators: formatNumber(data.activeValidators),
    lastUpdate: formatElapsed(now, data.lastUpdate),
    stakingApr: `${(data.stakingApr * 100).toFixed(2)}%`
  };
}

const dashboardData = {
  totalStaked: "1234567890123456789",
  totalRewards: "98765432109876543",
  activeValidators: 297,
  lastUpdate: new Date(Date.now() - 300000), // 5 minutes ago
  stakingApr: 0.1245
};

const formatted = formatDashboard(dashboardData);
console.log(formatted);
// {
//   totalStaked: "1.2346k DOT",
//   totalRewards: "98.7654 DOT", 
//   activeValidators: "297",
//   lastUpdate: "5 minutes ago",
//   stakingApr: "12.45%"
// }

Types

interface FormatBalanceOptions {
  decimals?: number;
  forceUnit?: string;
  locale?: string;
  withSi?: boolean;
  withUnit?: boolean | string;
  withZero?: boolean;
}

interface Time {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  milliseconds: number;
}

interface SiDef {
  power: number;
  text: string;
  value: number;
}

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