@liberfi.io/types
v0.4.44
Published
Liberfi React SDK types
Readme
@liberfi.io/types
Pure TypeScript type-definition package with zero runtime dependencies;
the package itself ships only types plus a few derived enum constants
(Chain, ChainNamespace, SolanaTokenProtocol, SwapMode,
SOLANA_TOKEN_PROTOCOLS). Serves as the single source of truth for
domain types and API contract interfaces across the entire LiberFi React
SDK monorepo. Consumed by @liberfi.io/client, @liberfi.io/react, and
all UI packages.
Design Philosophy
- Zero runtime dependencies — no third-party packages at runtime; consumers pay only for the enums / constants they actually import.
- Domain vs API contract layering — domain models (
Token,Activity,Chain,Portfolio, etc.) are cleanly separated from API contract interfaces (IClient,ISubscribeClient), with one-directional imports from domain → API. - Open literal types — patterns like
TokenProtocol = SolanaTokenProtocol | (string & {})andSwapDex = "jupiter" | "kyberswap" | (string & {})give autocomplete for known values while remaining extensible for future additions. - Interface-based abstraction —
IClientandISubscribeClientdefine the API surface abstractly, enabling different implementations (production client, mocks, stubs) without coupling consumers to a concrete class. - Single tag vocabulary — wallet classification across token-holding,
activity, and portfolio contexts is unified into a single
WalletTagtype rather than three structurally identical aliases.
Installation
pnpm add @liberfi.io/typesNo peer dependencies required.
Sub-path Exports
The package exposes two entry points:
| Entry point | Purpose |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| @liberfi.io/types | Default — every type re-exported flat (domain + API contract). |
| @liberfi.io/types/api | API contract subset only (IClient, ISubscribeClient, swap / transaction / option types, subscription payloads, cursor pagination). |
Use the sub-path entry when you want to address API contract types as a group (e.g. while mocking the client layer):
import * as API from "@liberfi.io/types/api";
const mockClient: API.IClient = {
/* ... */
};
const params: API.SwapParams = {
/* ... */
};For everyday usage, prefer flat named imports from the package root.
API Reference
Enums
| Enum | Description |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Chain | ~190 blockchain chain IDs (e.g. Chain.ETHEREUM, Chain.SOLANA, Chain.BASE). Values are numeric string identifiers. |
| ChainNamespace | Chain family namespace — EVM or SOL. |
| SolanaTokenProtocol | Known Solana launch protocols (e.g. PUMP, RAYDIUM, METEORA, ORCA). |
| SwapMode | Swap direction — EXACT_IN or EXACT_OUT. |
Domain Interfaces — Token
| Type | Description |
| ------------------------ | ------------------------------------------------------------------------------------------------------------ |
| Token | Core token model with metadata, stats, market data, liquidity, security, and social links. |
| TokenCreator | Token creator info: address, share percentage, verification status. |
| TokenLaunchedFrom | Launch platform details: program address and protocol family. |
| TokenMigratedTo | Migration target: program address, protocol family, pool address, timestamp. |
| TokenSocialMedias | Social media URLs (twitter, telegram, website, discord, github, etc.). |
| TokenStats | Per-resolution (1m–24h) trading statistics container. |
| TokenStatsByResolution | Single-resolution stats: buys, sells, traders, volumes, OHLC prices, price change. |
| TokenMarketData | Market data: supply, market cap, price, TVL, holder breakdowns by tag (bluechip, KOL, sniper, pro, insider). |
| TokenLiquidity | Liquidity pool info: pool/pair address, protocol, TVL. |
| TokenSecurity | Security flags: transfer fee, freezable, closable, transferable. |
| TokenCandle | OHLCV candlestick data point with resolution and timestamp. |
| TokenHolder | Single holder: address, amount, USD value, holding ratio. Phase 3: tags, lastActiveAt, startHoldingAt. |
Domain Interfaces — Activity
| Type | Description |
| --------------- | ----------------------------------------------------------------------------------------- |
| Activity | On-chain activity record (trade, liquidity, red packet). Phase 3: gasFee, traderTags. |
| ActivityToken | Token within an activity: address, symbol, amount, USD values. |
| ActivityDex | DEX where the activity occurred: name, image, protocol family, program address. |
| Trade | Narrowed subset of Activity with type: "buy" \| "sell". |
Domain Interfaces — Wallet & Portfolio
| Type | Description |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Portfolio | Wallet's token holding: price, amount, decimals. Phase 3: isActive, avgCostUsd, lastActiveAt, walletTokenTags. |
| PortfolioPnl | Per-token PnL details: buy/sell volumes, avg prices, realized/unrealized profit. Phase 3: isClosed, firstBuyAt, lastSellAt. |
| WalletPnl | Wallet-level PnL summary: win rate, total trades, profit breakdown. |
| WalletPortfolioPnls | Paginated portfolio PnL list with wallet-level summary (extends WalletPnl + CursorPagination). |
| WalletPortfolios | Paginated wallet portfolios with total balance (extends CursorPagination). |
Tag
| Type | Description |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| WalletTag | Single classification tag vocabulary used across token-holding (Token.holders[i].tags), activity (Activity.traderTags), and portfolio (Portfolio.walletTokenTags) contexts. Known values: kol, smart, sniper, dev, bundle, bluechip. Open union via (string & {}). |
API Contract — Pagination
| Type | Description |
| ------------------- | ---------------------------------------------------------------------------------------- |
| CursorPagination | Shared cursor-based pagination fields: startCursor, endCursor, hasPrev, hasNext. |
| CursorList<T> | Generic paginated result: data: T[] + CursorPagination. |
| CursorListOptions | Query options: cursor, limit, direction. |
API Contract — Query Options
| Type | Description |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GetTokenCandlesOptions | Candle query options: after, before (Date), limit. |
| GetTokenListOptions | Token list options: sortBy, sortDirection, filters, keywords, excludeKeywords. |
| SearchTokensOptions | Search options (extends CursorListOptions): chains, keyword, filters, sortBy, sortDirection. |
| SearchTokenCursorList | Search result (extends CursorList<Token>): adds total count and extra metadata. |
| TokenFilterOption | Filter descriptor: field (TokenFieldOption), operator (eq / gt / between / in / …), value. |
| GetTradesOptions | Trade query options (extends CursorListOptions): before, after, beforeBlockHeight, afterBlockHeight, type, poolAddress. |
| GetActivitiesOptions | Activity query options (extends CursorListOptions): time/block filters plus type, and (Phase 3) sortBy (timestamp / totalUsd). |
| GetTokenHoldersOptions | Token holder query options (extends CursorListOptions): Phase 3 sortBy (amount / usd / ratio / lastActiveAt). |
| GetWalletPortfolioPnlsOptions | Wallet PnL detail query options (extends CursorListOptions): Phase 3 resolution (WalletPnlResolution, required), positionState (open / closed / all), sortBy (pnl / totalUsd / winRate). |
| WalletPnlResolution | Allowed resolution values for wallet PnL queries: 7d / 30d / 90d. |
API Contract — Swap & Transaction
| Type | Description |
| ----------------------- | ----------------------------------------------------------------------------------------------------------- |
| SwapDex | Aggregator id: "jupiter" \| "kyberswap" \| (string & {}). |
| SwapParams | Swap request: chain, addresses, mode, amount, slippage, fees, anti-MEV flag. |
| SwapRoute | Swap response: serialized unsigned transaction, route plans, and optional Solana blockhash expiry metadata. |
| SwapRoutePlan | Single route plan step: protocol name, input/output tokens and amounts, fees. |
| LatestBlockParams | Latest block request: target chain. |
| BlockchainLatestBlock | Latest block response: blockhash and lastValidBlockHeight. |
| SendTxParams | Send transaction request: chain, signed serialized transaction, extras. |
| SendTxResult | Send transaction response: txHash + extras. |
API Contract — Client Interfaces
IClient
REST API client interface. Key methods:
interface IClient {
getToken(chain: Chain, address: string): Promise<Token>;
getTokens(chain: Chain, addresses: string[]): Promise<Token[]>;
getTokenCandles(chain, address, resolution, options?): Promise<TokenCandle[]>;
getTokenSecurity(chain, address): Promise<TokenSecurity>;
getTokenStats(chain, address): Promise<TokenStats>;
getTokenHolders(chain, address, options?): Promise<CursorList<TokenHolder>>;
getTokenMarketData(chain, address): Promise<TokenMarketData>;
getNewTokens(chain, options?): Promise<Token[]>;
getFinalStretchTokens(chain, options?): Promise<Token[]>;
getMigratedTokens(chain, options?): Promise<Token[]>;
getTrendingTokens(chain, resolution, options?): Promise<Token[]>;
getStockTokens(chain, options?): Promise<Token[]>;
searchTokens(options?): Promise<SearchTokenCursorList>;
swapRoute(params: SwapParams): Promise<SwapRoute>;
getLatestBlock(params: LatestBlockParams): Promise<BlockchainLatestBlock>;
sendTx(params: SendTxParams): Promise<SendTxResult>;
checkTxSuccess(chain, txHash, timeout?): Promise<boolean>;
getWalletPortfolios(chain, address, options?): Promise<WalletPortfolios>;
getWalletPnl(
chain,
address,
resolution?: WalletPnlResolution,
): Promise<WalletPnl>;
getWalletPortfolioPnls(
chain,
address,
options?,
): Promise<WalletPortfolioPnls>;
getWalletPortfoliosByTokens(
chain,
address,
tokenAddresses,
): Promise<Portfolio[]>;
getWalletPortfolioPnlsByTokens(
chain,
address,
tokenAddresses,
): Promise<PortfolioPnl[]>;
getWalletTrades(chain, address, options?): Promise<CursorList<Trade>>;
getTokenTrades(chain, address, options?): Promise<CursorList<Trade>>;
getWalletActivities(chain, address, options?): Promise<CursorList<Activity>>;
getTokenActivities(chain, address, options?): Promise<CursorList<Activity>>;
getPresignedUploadUrl(): Promise<string>;
}ISubscribeClient
WebSocket subscription interface for real-time updates:
interface ISubscribeClient {
subscribeToken(chain, address, callback): ISubscription;
subscribeTokenCandles(chain, address, resolution, callback): ISubscription;
subscribeWalletPnl(chain, address, callback): ISubscription;
subscribeWalletPortfolios(chain, address, callback): ISubscription;
subscribeWalletPortfolioPnls(chain, address, callback): ISubscription;
subscribeWalletTrades(chain, address, callback): ISubscription;
subscribeTokenTrades(chain, address, callback): ISubscription;
subscribeWalletActivities(chain, address, callback): ISubscription;
subscribeTokenActivities(chain, address, callback): ISubscription;
subscribeNewTokens(chain, callback): ISubscription;
subscribeTrendingTokens(chain, callback): ISubscription;
subscribeMigratedTokens(chain, callback): ISubscription;
subscribeFinalStretchTokens(chain, callback): ISubscription;
subscribeStockTokens(chain, callback): ISubscription;
}ISubscription
interface ISubscription {
unsubscribe(): void;
}Subscription Data Types
| Type | Description |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| TokenSubscribed | Incremental token update — chain + address required, all other Token fields optional (undefined = not included in this push). |
| WalletPnlSubscribed | WalletPnl extended with optional resolution: WalletPnlResolution. |
| PortfolioSubscribed | Lightweight portfolio update: chain, wallet address, token address, price, amount. |
| PortfolioPnlSubscribed | Partial PortfolioPnl keyed by walletAddress + tokenAddress. |
Type Aliases
| Type | Definition | Description |
| -------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| TokenProtocol | SolanaTokenProtocol \| (string & {}) | Open union for token launch protocols. |
| ActivityType | "buy" \| "sell" \| "liquidity_initialize" \| "liquidity_add" \| ... | All known on-chain activity types. |
| TokenResolution | "1s" \| "15s" \| "30s" \| "1m" \| ... \| "24h" | Candlestick / stats time resolution. |
| TrendingResolution | Extract<TokenResolution, "1m" \| "5m" \| "1h" \| "4h" \| "24h"> | Subset of resolutions supported by trending lists. |
| TokenFieldOption | Template literal: ${TimeBasedMetric}${Capitalize<Timeframe>} ∪ standalone fields ∪ (string & {}) | Sortable / filterable token field identifiers, generated programmatically. |
Constants
| Name | Type | Description |
| ------------------------ | ----------------------- | ----------------------------------------------- |
| SOLANA_TOKEN_PROTOCOLS | SolanaTokenProtocol[] | Array of all SolanaTokenProtocol enum values. |
Usage Examples
Import domain types
import { Chain, Token, Activity } from "@liberfi.io/types";
function formatToken(token: Token): string {
return `${token.symbol} on chain ${token.chain}`;
}Type-safe API client implementation
import {
IClient,
Chain,
Token,
CursorList,
TokenHolder,
} from "@liberfi.io/types";
class MyClient implements IClient {
async getToken(chain: Chain, address: string): Promise<Token> {
const res = await fetch(`/api/tokens/${chain}/${address}`);
return res.json();
}
// ... implement remaining methods
}Filter tokens with TokenFilterOption
import type { TokenFilterOption, GetTokenListOptions } from "@liberfi.io/types";
const options: GetTokenListOptions = {
sortBy: "volumes24h",
sortDirection: "desc",
filters: [
{ field: "marketCap", operator: "gte", value: "100000" },
{ field: "holders", operator: "gte", value: "50" },
],
};Subscribe to real-time updates
import type {
ISubscribeClient,
Chain,
TokenSubscribed,
} from "@liberfi.io/types";
function watchToken(client: ISubscribeClient, chain: Chain, address: string) {
const sub = client.subscribeToken(
chain,
address,
(updates: TokenSubscribed[]) => {
for (const update of updates) {
if (update.marketData?.priceInUsd) {
console.log(`Price: $${update.marketData.priceInUsd}`);
}
}
},
);
return () => sub.unsubscribe();
}Group API contract types under a namespace alias
import * as API from "@liberfi.io/types/api";
function makeMockClient(): API.IClient {
return {
/* ... */
} as API.IClient;
}
function buildSwap(params: API.SwapParams): Promise<API.SwapRoute> {
/* ... */
}Future Improvements
- Complete the
TokenSecurityinterface (additional security checks pending upstream backend support). - Consider auto-generating the
Chainenum from a canonical chain registry to keep the ~190 entries authoritative. - Evaluate further splitting
TokenintoTokenCore+TokenStats+TokenMarketDataif downstream consumers commonly need only a subset.
