@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
versionregistration). 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.jsfor 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/utilsPeer 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 formattingPredefinedToken—{ address: string; symbol: string; decimals: number }ChainPredefinedTokens—{ native, wrapped, stablecoins }ApiError— Error subclass withcode: number
Constants
SOLANA_TOKENS,ETHEREUM_TOKENS,BSC_TOKENS,ARBITRUM_TOKENS,OPTIMISM_TOKENS,AVALANCHE_TOKENS— Per-chain token registriesCHAIN_TOKENS—Partial<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",
); // trueDate formatting
import { formatAge } from "@liberfi.io/utils";
formatAge(120000); // "2m"
formatAge(120000, { minutesAgo: "{n} 分钟前" }); // "2 分钟前"Future Improvements
- Extract shared formatting logic in
number.tsto reduce DRY violations acrossformatAmount/formatAmountUSD/formatAmountUSDCompact. - Replace
anydefaults withunknowninfetch.tsgeneric type parameters. - Remove catch-rethrow antipattern in
fetch.tserror handling. - Move
version.tswindow side effect to opt-in registration or provider initialization. - Consolidate chain metadata (
chainSlugs,chainSlugAbbrs,chainColors) into a single structured registry. - Add grouping separators to
stringifyPercentfor large percentage values. - Extend
ApiErrorwith HTTP status code and response body fields.
