npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@liberfi.io/utils

v0.1.89

Published

Liberfi React SDK utils

Downloads

12,151

Readme

@liberfi.io/utils

Framework-agnostic utility library for the Liberfi React SDK monorepo. Provides number/currency formatting, chain metadata, HTTP helpers, date/time formatting, token registries, URL builders, and string utilities. Consumed by all UI and integration packages in the monorepo.

Design Philosophy

  • Pure functions — All exports are stateless, side-effect-free functions (except version registration). No React, no DOM.
  • Tiered precision formatting — Number formatters automatically select decimal places and abbreviation based on magnitude, matching financial UI conventions.
  • Single source of truth for chain data — Chain slugs, colors, icons, and address validation live here so UI packages don't duplicate chain logic.
  • Minimal dependencies — Only bignumber.js for precision math. Solana address validation uses a lightweight base58 regex. Common collection/timing utilities (throttle, debounce, etc.) are implemented in-house to avoid lodash overhead.

Installation

pnpm add @liberfi.io/utils

Peer dependencies: none (all dependencies are direct).

API Reference

Number Formatting

SafeBigNumber

A BigNumber subclass that never throws on construction. Invalid/undefined values fall back to 0.

new SafeBigNumber(value?: BigNumber.Value, base?: number)

isValidNumber(num: unknown): boolean

Returns true if num is a finite number, numeric string, or BigNumber/SafeBigNumber instance.

formatAmount(num, options?): string

Format a raw token/asset amount (no currency symbol). Precision auto-selects by magnitude.

formatAmount(num: BigNumber.Value, options?: FormatAmountOptions): string

| Option | Type | Default | Description | | -------------------- | --------- | ------- | ------------------------------- | | showPlusGtThanZero | boolean | false | Prefix positive values with "+" |

formatAmountUSD(num, options?): string

Format a USD amount with $ prefix. Standard precision tiers.

formatAmountUSDCompact(num, options?): string

Compact USD formatting — more aggressive rounding, suited for space-constrained UIs.

formatPriceUSD(num, options?): string

Format a token price with $ prefix. Supports high-precision and low-precision modes.

formatPriceUSD(num: BigNumber.Value, options?: FormatPriceOptions): string

| Option | Type | Default | Description | | --------------- | --------- | ------- | -------------------------------------- | | isHighPrecise | boolean | true | Use high-precision mode (4 dp vs 2 dp) |

formatPercent(num, options?): string

Format a ratio as percentage (0.3 = 30%).

formatPercent(num: BigNumber.Value, options?: FormatPercentOptions): string

| Option | Type | Default | Description | | -------------------- | --------- | ------- | ------------------------------- | | showPlusGtThanZero | boolean | false | Prefix positive values with "+" | | precision | number | 2 | Decimal precision override |

Chain Utilities

chainToNamespace(chain: Chain): ChainNamespace

Returns ChainNamespace.SOLANA or ChainNamespace.EVM for a given chain.

chainSlug(chainId: Chain): string | undefined

Returns the lowercase slug (e.g. "ethereum", "solana").

chainDisplayName(chainId: Chain): string

Returns a display-friendly name. Uses abbreviation if available (e.g. "ETH", "BSC"), otherwise title-cases the slug.

chainColor(chainId: Chain): string | undefined

Returns the brand hex color for a chain.

chainIcon(chain: Chain | string): string | undefined

Returns a llamao.fi icon URL for the chain.

chainIdBySlug(slug: string): Chain | undefined

Reverse lookup — resolves a slug or abbreviation to a Chain enum value. Case-insensitive.

isValidEvmAddress(value: string): boolean

Validates a 0x-prefixed 40-hex-character EVM address.

isValidSolanaAddress(value: string): boolean

Validates a Solana base58 address (32–44 character base58 string).

isValidWalletAddress(chain: Chain | string, addr: string): boolean

Dispatches to the correct validator based on the chain's namespace.

Date/Time Formatting

formatAgeInSeconds(age: number, options?): string

Formats elapsed time in seconds to a compact string ("just now", "45s", "2m", "3h", "5d", "1y").

formatAge(age: number, options?): string

Same as formatAgeInSeconds but accepts milliseconds.

interface FormatAgeOptions {
  justNow?: string;
  secondsAgo?: string; // use {n} placeholder
  minutesAgo?: string;
  hoursAgo?: string;
  daysAgo?: string;
  yearsAgo?: string;
}

HTTP Helpers

httpRequest<R>(url: string, options: RequestInit): Promise<R>

Core HTTP function. Throws ApiError for 400 responses, Error for other failures.

httpGet<R>(url, options?): Promise<R>

httpPost<R, P>(url, data, options?): Promise<R>

httpPut<R, P>(url, data, options?): Promise<R>

httpDelete<R>(url, options?): Promise<R>

httpMutate<R>(url, init): Promise<R>

URL Builders

txExplorerUrl(chainId: Chain, txHash: string): string | undefined

Returns a block explorer URL for a transaction hash.

accountExplorerUrl(chainId: Chain, account: string): string | undefined

Returns a block explorer URL for an account/address.

searchImageUrl(image: string): string

Google Lens reverse image search URL.

searchTwitterUrl(q: string): string

X/Twitter search URL.

twitterUserUrl(username: string): string

twitterTweetUrl(id: string): string

String Utilities

capitalize(str: string): string

Capitalizes the first letter, lowercases the rest.

truncateAddress(address: string, start?: number, end?: number): string

Truncates a string with ... in the middle. Defaults: start=6, end=4.

Symbol Formatting

formatSymbol(symbol: string, formatString?: string): string

Formats a trading pair symbol ("PERP_BTC_USDT") using a template string with type, base, quote placeholders. Default format: "base-type".

Token Protocols

parseTokenProtocolFamily(chain: Chain, protocolFamily: string): TokenProtocol | undefined

Parses a protocol family string to a known TokenProtocol (Solana only).

formatTokenProtocolName(protocol: TokenProtocol): string

Formats a protocol slug to display name (e.g. "pump-amm""Pump Amm").

Token Registry

getNativeToken(chain: Chain): PredefinedToken | undefined

getWrappedToken(chain: Chain): PredefinedToken | undefined

getStablecoins(chain: Chain): Record<string, PredefinedToken> | undefined

getCommonTokenAddresses(chain: Chain): string[]

getCommonTokenSymbolsMap(chain: Chain): Record<string, string>

Types

  • FormatAmountOptions{ showPlusGtThanZero: boolean }
  • FormatPriceOptions{ isHighPrecise: boolean }
  • FormatPercentOptions{ showPlusGtThanZero?: boolean; precision?: number }
  • FormatAgeOptions — i18n label overrides for age formatting
  • PredefinedToken{ address: string; symbol: string; decimals: number }
  • ChainPredefinedTokens{ native, wrapped, stablecoins }
  • ApiError — Error subclass with code: number

Constants

  • SOLANA_TOKENS, ETHEREUM_TOKENS, BSC_TOKENS, ARBITRUM_TOKENS, OPTIMISM_TOKENS, AVALANCHE_TOKENS — Per-chain token registries
  • CHAIN_TOKENSPartial<Record<Chain, ChainPredefinedTokens>>
  • version — Package version string

Collection & Timing Utilities

Lightweight, zero-dependency replacements for common lodash functions.

| Function | Signature | Description | | ---------------- | ------------------------------------------ | ------------------------------------------ | | throttle | (fn, wait) => fn | Throttle with leading + trailing execution | | debounce | (fn, wait) => fn | Trailing-edge debounce | | uniqBy | (array, iteratee) => T[] | Deduplicate by key or accessor | | intersectionBy | (a, b, iteratee) => T[] | Items in a whose key exists in b | | keyBy | (array, iteratee) => Record<string, T> | Index array into object by key | | groupBy | (array, iteratee) => Record<string, T[]> | Group array items by key | | mapKeys | (obj, iteratee) => Record<string, T> | Transform object keys | | mapValues | (obj, iteratee) => Record<string, R> | Transform object values |

Usage Examples

Number formatting

import {
  formatAmount,
  formatAmountUSD,
  formatPriceUSD,
  formatPercent,
} from "@liberfi.io/utils";

formatAmount(1_500_000); // "1.5M"
formatAmountUSD(42.678); // "$42.67"
formatPriceUSD(0.0000382); // "$0.0₄382"
formatPercent(0.3); // "30%"
formatPercent(-0.05, { showPlusGtThanZero: true }); // "-5%"

Chain utilities

import { Chain } from "@liberfi.io/types";
import {
  chainDisplayName,
  chainIcon,
  isValidWalletAddress,
} from "@liberfi.io/utils";

chainDisplayName(Chain.ETHEREUM); // "ETH"
chainIcon(Chain.SOLANA); // "https://icons.llamao.fi/icons/chains/rsz_solana.jpg"
isValidWalletAddress(
  Chain.ETHEREUM,
  "0x1234567890abcdef1234567890abcdef12345678",
); // true

Date formatting

import { formatAge } from "@liberfi.io/utils";

formatAge(120000); // "2m"
formatAge(120000, { minutesAgo: "{n} 分钟前" }); // "2 分钟前"

Future Improvements

  • Extract shared formatting logic in number.ts to reduce DRY violations across formatAmount / formatAmountUSD / formatAmountUSDCompact.
  • Replace any defaults with unknown in fetch.ts generic type parameters.
  • Remove catch-rethrow antipattern in fetch.ts error handling.
  • Move version.ts window side effect to opt-in registration or provider initialization.
  • Consolidate chain metadata (chainSlugs, chainSlugAbbrs, chainColors) into a single structured registry.
  • Add grouping separators to stringifyPercent for large percentage values.
  • Extend ApiError with HTTP status code and response body fields.