npm package: @liberfi.io/types
Description: Liberfi React SDK types
Latest version: 0.1.151

# @liberfi.io/types

Pure TypeScript type-definition package with zero runtime dependencies. 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** — contains only TypeScript types and enums; adds no weight to the consumer's bundle beyond what is used.
- **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 & {})` provide autocompletion for known values while remaining extensible for future additions.
- **Interface-based abstraction** — `IClient` and `ISubscribeClient` define the API surface abstractly, enabling different implementations (production client, mocks, stubs) without coupling consumers to a concrete class.

## Installation

```bash
pnpm add @liberfi.io/types
```

No peer dependencies required.

## 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, etc.). |
| `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.                                                          |

### Domain Interfaces — Activity

| Type            | Description                                                                                                            |
| --------------- | ---------------------------------------------------------------------------------------------------------------------- | -------- |
| `Activity`      | On-chain activity record (trade, liquidity, red packet). Contains `from`/`to` tokens, dex info, status, and timestamp. |
| `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 (in USD and native).                               |
| `PortfolioPnl`        | Per-token PnL details: buy/sell volumes, avg prices, realized/unrealized profit.                   |
| `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`).                       |

### 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`): same time/block filters plus `type` (ActivityType).                             |

### API Contract — Swap & Transaction

| Type            | Description                                                                   |
| --------------- | ----------------------------------------------------------------------------- |
| `SwapParams`    | Swap request: chain, addresses, mode, amount, slippage, fees, anti-MEV flag.  |
| `SwapRoute`     | Swap response: serialized unsigned transaction + route plans.                 |
| `SwapRoutePlan` | Single route plan step: protocol name, input/output tokens and amounts, fees. |
| `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:

```typescript
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>;
  sendTx(params: SendTxParams): Promise<SendTxResult>;
  checkTxSuccess(chain, txHash, timeout?): Promise<boolean>;
  getWalletPortfolios(chain, address, options?): Promise<WalletPortfolios>;
  getWalletPnl(chain, address, resolution?): 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:

```typescript
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`

```typescript
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` field.                                                                                |
| `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`   | 50+ string literals + `(string & {})`                                 | Sortable / filterable token field identifiers.     |

### Constants

| Name                     | Type                    | Description                                     |
| ------------------------ | ----------------------- | ----------------------------------------------- |
| `SOLANA_TOKEN_PROTOCOLS` | `SolanaTokenProtocol[]` | Array of all `SolanaTokenProtocol` enum values. |
| `version`                | `string`                | Current package version.                        |

### Namespace

| Name  | Description                                                                                                  |
| ----- | ------------------------------------------------------------------------------------------------------------ |
| `API` | Re-exports all types from `./api` as a single namespace for backward-compatible access (e.g. `API.IClient`). |

## Usage Examples

### Import domain types

```typescript
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

```typescript
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

```typescript
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

```typescript
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();
}
```

## Future Improvements

- Deduplicate `version.ts` global side effect across packages into a shared utility.
- Extract `HolderTagBreakdown` sub-type from `TokenMarketData` to reduce repeated field triples.
- Generate `TokenFieldOption` via template literal types instead of maintaining 50+ manual entries.
- Complete `TokenSecurity` interface (currently has a `TODO` for additional security checks).
- Consider auto-generating the `Chain` enum from a canonical chain registry.
- Document or mitigate the `version.ts` multi-instance overwrite concern in SSR environments.