@codex-data/sdk

中文文档
2.6.3发布于 2026/11/10MITTypeScriptESM + CJS构建来源已验证近 30 天下载 20.6万

The Codex SDK for JavaScript/Typescript. It provides generated types and convenient ways to access the graphql api.

原始使用文档
文档目录28 节
  1. Installation
  2. Quick Start
  3. Get Token Prices
  4. Get OHLCV Chart Data
  5. Discover and Filter Tokens
  6. Get Wallet Balances
  7. Get Token Holders
  8. Get Token Trade History
  9. Stream Real-Time Prices
  10. Stream Real-Time OHLCV Bars
  11. Stream Live Trades
  12. Edge Subscriptions
  13. Custom Queries: Request Only the Fields You Need
  14. Option 1: sdk.send() — quick, zero setup
  15. Option 2: GraphQL Code Generator — exact types and autocomp…
  16. Common Network IDs
  17. ID Format Convention
  18. All Available Methods
  19. Queries ( sdk.queries.* )
  20. Subscriptions ( sdk.subscriptions.* ) — paid plan required
  21. Mutations ( sdk.mutations.* )
  22. Configuration
  23. Examples
  24. Contributing
  25. Releasing
  26. Upgrading to v2
  27. Links
  28. License

Codex SDK

The TypeScript SDK for the Codex API — real-time blockchain data, token prices, OHLCV charts, wallet balances, and holder analytics for 60M+ tokens across 80+ networks including Ethereum, Solana, Base, Arbitrum, BNB, and Polygon.

Codex is a GraphQL API used by teams like Coinbase, TradingView, Uniswap, Rainbow, FOMO, Farcaster, and hundreds of others.

Installation

npm install @codex-data/sdk
yarn add @codex-data/sdk
pnpm add @codex-data/sdk

Quick Start

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const networks = await sdk.queries.getNetworks({});
console.log(networks.getNetworks); // [{ id: 1, name: "ethereum" }, { id: 1399811149, name: "solana" }, ...]

Tip: The built-in sdk.queries.* methods request every available field. They're great for exploring the API, but for production we recommend writing a custom query that selects only the fields you need.

Get Token Prices

Get the current USD price of any token. Supports up to 25 tokens per request. Prices are liquidity-weighted across all valid pools.

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const prices = await sdk.queries.getTokenPrices({
  inputs: [
    {
      address: "So11111111111111111111111111111111111111112",
      networkId: 1399811149,
    }, // SOL
    { address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", networkId: 1 }, // WETH
  ],
});

prices.getTokenPrices?.forEach((price) => {
  console.log(`${price?.address}: $${price?.priceUsd}`);
});

To get a historical price, pass a timestamp:

const historicalPrice = await sdk.queries.getTokenPrices({
  inputs: [
    {
      address: "So11111111111111111111111111111111111111112",
      networkId: 1399811149,
      timestamp: 1704067200, // Unix timestamp
    },
  ],
});

Get OHLCV Chart Data

Get candlestick data for any token or trading pair. Supports resolutions from 1-second to 7-day.

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const bars = await sdk.queries.getBars({
  symbol: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2:1", // WETH on Ethereum
  from: 1704067200,
  to: 1704153600,
  resolution: "60", // 1-hour candles
  removeEmptyBars: true,
});

bars.getBars?.o?.forEach((open, i) => {
  console.log({
    open,
    high: bars.getBars?.h?.[i],
    low: bars.getBars?.l?.[i],
    close: bars.getBars?.c?.[i],
    volume: bars.getBars?.volume?.[i],
    timestamp: bars.getBars?.t?.[i],
  });
});

Available resolutions: 1S, 5S, 15S, 30S, 1, 5, 15, 30, 60, 240, 720, 1D, 7D

Discover and Filter Tokens

Search and filter tokens by price, volume, market cap, liquidity, holder count, trading activity, and more.

import {
  Codex,
  TokenRankingAttribute,
  RankingDirection,
} from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const result = await sdk.queries.filterTokens({
  filters: {
    network: [1], // Ethereum
    liquidity: { gte: "100000" }, // $100k+ liquidity
    marketCap: { gte: "1000000" }, // $1M+ market cap
    txnCount24: { gte: "500" }, // 500+ transactions in 24h
  },
  rankings: [
    {
      attribute: TokenRankingAttribute.TrendingScore24,
      direction: RankingDirection.Desc,
    },
  ],
  limit: 20,
});

result.filterTokens?.results?.forEach((token) => {
  console.log(
    `${token?.token?.name} (${token?.token?.symbol}): $${token?.priceUSD}`,
  );
});

Get Wallet Balances

Get all token balances for a wallet address with USD values.

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const balances = await sdk.queries.balances({
  input: {
    walletAddress: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", // vitalik.eth
    networks: [1],
    includeNative: true,
    removeScams: true,
    limit: 50,
  },
});

balances.balances?.items?.forEach((item) => {
  console.log(
    `${item?.token?.symbol}: ${item?.shiftedBalance} ($${item?.balanceUsd})`,
  );
});

Get Token Holders

Get the list of wallets holding a specific token, sorted by balance.

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const holders = await sdk.queries.holders({
  input: {
    tokenId: "So11111111111111111111111111111111111111112:1399811149", // SOL
    limit: 50,
  },
});

console.log(`Total holders: ${holders.holders?.count}`);
console.log(`Top 10 hold: ${holders.holders?.top10HoldersPercent}%`);

holders.holders?.items?.forEach((holder) => {
  console.log(
    `${holder?.address}: ${holder?.shiftedBalance} ($${holder?.balanceUsd})`,
  );
});

Get Token Trade History

Get buy, sell, mint, and burn events for any token or pair.

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const events = await sdk.queries.getTokenEvents({
  query: {
    address: "So11111111111111111111111111111111111111112",
    networkId: 1399811149,
    eventDisplayType: ["Buy", "Sell"],
  },
  limit: 25,
});

events.getTokenEvents?.items?.forEach((event) => {
  console.log(
    `${event?.eventDisplayType} by ${event?.maker} — $${event?.token0SwapValueUsd}`,
  );
});

Stream Real-Time Prices

Note: WebSocket subscriptions require a paid plan.

Subscribe to live price updates via WebSocket. Fires on every on-chain swap.

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const unsubscribe = sdk.subscriptions.onPriceUpdated(
  {
    address: "So11111111111111111111111111111111111111112",
    networkId: 1399811149,
  },
  {
    next: (result) => {
      console.log("Price:", result.data?.onPriceUpdated?.priceUsd);
    },
    error: (err) => console.error(err),
    complete: () => console.log("Stream ended"),
  },
);

// Call unsubscribe() to clean up

Stream Real-Time OHLCV Bars

Note: WebSocket subscriptions require a paid plan.

Get live candlestick updates across all resolutions simultaneously.

import { Codex, QuoteToken } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const unsubscribe = sdk.subscriptions.onBarsUpdated(
  {
    pairId: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640:1", // USDC/WETH on Ethereum
    quoteToken: QuoteToken.Token1,
  },
  {
    next: (result) => {
      const bar = result.data?.onBarsUpdated;
      const oneMin = bar?.aggregates?.r1?.usd;
      console.log(
        `1min candle — O: ${oneMin?.o} H: ${oneMin?.h} L: ${oneMin?.l} C: ${oneMin?.c}`,
      );
    },
    error: (err) => console.error(err),
    complete: () => console.log("Stream ended"),
  },
);

Stream Live Trades

Note: WebSocket subscriptions require a paid plan.

Watch buy/sell events as they happen on any trading pair.

import { Codex, QuoteToken } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const unsubscribe = sdk.subscriptions.onEventsCreated(
  {
    id: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640:1",
    quoteToken: QuoteToken.Token0,
  },
  {
    next: (result) => {
      result.data?.onEventsCreated?.events?.forEach((event) => {
        console.log(
          `${event?.eventDisplayType} by ${event?.maker} — $${event?.token0SwapValueUsd}`,
        );
      });
    },
    error: (err) => console.error(err),
    complete: () => console.log("Stream ended"),
  },
);

Edge Subscriptions

Pass { useEdge: true } as the third argument to a generated subscription method (or the fourth argument to sdk.subscribe) to use a regional edge node. Solana (1399811149) routes to wss://fra.edge.codex.io/graphql; Robinhood Chain (4663) and BNB (56) route to wss://iad.edge.codex.io/graphql in us-east-1. Connections are created on demand and reused per endpoint.

import { Codex, EventCommitmentLevel } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const unsubscribe = sdk.subscriptions.onTokenEventsCreated(
  {
    input: { tokenAddress: "0x...", networkId: 56 },
    commitmentLevel: [EventCommitmentLevel.Processed],
  },
  {
    next: (result) => console.log(result.data),
    error: (err) => console.error(err),
    complete: () => console.log("Stream ended"),
  },
  { useEdge: true },
);

Edge supports onEventsCreated, onTokenEventsCreated, onBarsUpdated, and onTokenBarsUpdated. The commitment levels must include Processed, and onBarsUpdated requires an explicit quoteToken. Each subscription must target one supported chain. Subscriptions without useEdge use the main endpoint.

The lightweight withEdge helper from @codex-data/sdk/edge uses the same routing. For a standalone Robinhood or BNB connection, pass url: ROBINHOOD_EDGE_URL or url: BNB_EDGE_URL to createEdgeClient, importing them from @codex-data/sdk/edge. The SDK's apiEdgeUrl and the helper's edgeUrl override routing for all chains.

Custom Queries: Request Only the Fields You Need

The built-in sdk.queries.* methods select every available field, so the recipes above are the most expensive way to call each endpoint. Writing your own query means you get smaller, faster responses.

There are two ways to do it:

Option 1: sdk.send() — quick, zero setup

Write the query yourself and describe the result type inline:

import { Codex } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const result = await sdk.send<{
  getNetworks: Array<{ id: number; name: string }>;
}>(
  `query GetNetworks {
    getNetworks { id name }
  }`,
  {},
);

console.log("Networks:", result.getNetworks);

Instead of writing types by hand, you can reuse the SDK's exported query types with DeepPartial, which makes every field optional:

import { Codex, DeepPartial, FilterTokensQuery } from "@codex-data/sdk";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const result = await sdk.send<DeepPartial<FilterTokensQuery>>(
  `query FilterTokens($limit: Int) {
    filterTokens(limit: $limit) {
      results {
        priceUSD
        volume24
        token { name symbol }
      }
    }
  }`,
  { limit: 10 },
);

Option 2: GraphQL Code Generator — exact types and autocomplete

For production codebases we recommend generating types from your own queries. The SDK ships its schema at @codex-data/sdk/schema.graphql, so codegen runs offline against the exact schema version you have installed.

Install the codegen tooling:

npm install -D @graphql-codegen/cli @graphql-codegen/client-preset

Add a codegen.ts to your project root:

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "./node_modules/@codex-data/sdk/schema.graphql",
  documents: "src/**/*.ts",
  generates: {
    "src/gql/": {
      preset: "client",
      presetConfig: { fragmentMasking: false },
    },
  },
};

export default config;

Run graphql-codegen, then write queries with the generated graphql() helper and pass them to sdk.query(). The result type is inferred from exactly the fields you selected:

import { Codex } from "@codex-data/sdk";
import { graphql } from "./gql";

const sdk = new Codex(process.env.CODEX_API_KEY!);

const trendingTokens = graphql(`
  query TrendingTokens($limit: Int) {
    filterTokens(limit: $limit) {
      results {
        priceUSD
        volume24
        token {
          name
          symbol
        }
      }
    }
  }
`);

const result = await sdk.query(trendingTokens, { limit: 10 });
// result.filterTokens.results[0].priceUSD — fully typed, only what you asked for

See the codegen example for a complete working project.

Common Network IDs

NetworkID
Ethereum1
BNB56
Polygon137
Arbitrum42161
Base8453
Avalanche43114
Solana1399811149

Use sdk.queries.getNetworks({}) for the full list of 80+ supported networks.

ID Format Convention

IDs in the Codex API follow the pattern address:networkId:

  • Token ID: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2:1 (WETH on Ethereum)
  • Pair ID: 0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640:1 (USDC/WETH on Ethereum)
  • Wallet ID: 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045:1

All Available Methods

Queries (sdk.queries.*)

MethodDescription
filterTokensSearch and filter tokens by price, volume, market cap, liquidity
getTokenPricesGet current or historical USD prices for up to 25 tokens
getBarsGet OHLCV candlestick data for a trading pair
holdersGet token holder list sorted by balance (paid)
filterPairsSearch and filter trading pairs
balancesGet wallet token balances with USD values (paid)
getTokenEventsGet buy/sell/mint/burn trade events
pairMetadataGet trading pair stats and metadata
tokenGet metadata for a single token
listPairsWithMetadataForTokenList pairs with full metadata
getTokenEventsForMakerGet trade events for a specific wallet
getDetailedPairStatsGet detailed bucketed stats for a pair
listPairsForTokenList all trading pairs for a token
tokenTopTradersGet top traders for a token
tokensGet metadata for multiple tokens
top10HoldersPercentGet percentage held by top 10 wallets
getDetailedPairsStatsGet detailed stats for multiple pairs
filterTokenWalletsGet per-wallet trading stats (profit/loss, buy/sell counts) (paid)
liquidityMetadataGet liquidity pool metadata (paid)
tokenSparklinesGet sparkline price data for tokens
filterWalletsFilter wallets by trading statistics (paid)
detailedWalletStatsGet comprehensive wallet analytics (paid)
getExchangesGet DEX information
getNetworksList all 80+ supported networks
getTokenBarsGet OHLCV data for a token across all pairs
chartUrlsGet pre-rendered chart image URLs (paid)
walletChartGet wallet portfolio chart data (paid)
filterExchangesFilter decentralized exchanges
liquidityLocksGet liquidity lock information (paid)
getNetworkConfigsGet network configuration details
getNetworkStatsGet network-level statistics
getNetworkStatusGet network sync status
tokenLifecycleEventsGet token creation and migration events
blocksGet block data by number or timestamp

Subscriptions (sdk.subscriptions.*) — paid plan required

MethodDescription
onPairMetadataUpdatedLive pair stat updates
onLaunchpadTokenEventBatchBatched launchpad events
onBarsUpdatedReal-time OHLCV bars for a trading pair
onPriceUpdatedReal-time price for a single token
onHoldersUpdatedLive holder count and balance changes
onDetailedStatsUpdatedLive detailed stats updates
onDetailedTokenStatsUpdatedLive detailed token stats aggregated across pools
onEventsCreatedLive buy/sell events for a pair
onPricesUpdatedReal-time prices for multiple tokens
onUnconfirmedEventsCreatedUnconfirmed (mempool) trade events
onTokenEventsCreatedLive events across all pools for a token
onLaunchpadTokenEventIndividual launchpad events (Pump.fun, etc.)
onTokenBarsUpdatedReal-time OHLCV bars for a token
onLatestPairUpdatedNew trading pair creation events
onUnconfirmedBarsUpdatedUnconfirmed bar updates
onEventsCreatedByMakerLive events for a specific wallet
onBalanceUpdatedLive wallet balance updates
onTokenLifecycleEventsCreatedToken lifecycle events
onLatestTokensNew token creation events
onNftEventsCreatedNFT trade events

Mutations (sdk.mutations.*)

MethodDescription
createWebhooksCreate webhook alerts (paid)
deleteWebhooksDelete webhook alerts (paid)
backfillWalletAggregatesTrigger wallet data backfill (paid)
createApiTokensCreate short-lived API tokens for client-side use (paid)
deleteApiTokenDelete an API token (paid)
refreshBalancesRefresh wallet balances

Configuration

import { Codex } from "@codex-data/sdk";

const sdk = new Codex("YOUR_API_KEY", {
  apiUrl: "https://graph.codex.io/graphql", // default
  apiRealtimeUrl: "wss://graph.codex.io/graphql", // default
  ws: true, // enable WebSocket (default: true)
});

// Update config at runtime
sdk.updateConfig({ ws: false });

// Clean up WebSocket connection
sdk.dispose();

Examples

See the examples directory for full working projects:

  • Simple — Basic queries, filtering, and subscriptions
  • Codegen — Using GraphQL Code Generator for fully typed custom queries
  • Next.js — Full-stack web application

Contributing

We welcome contributions! Please feel free to submit a Pull Request.

pnpm install    # Install dependencies
pnpm run build  # Build the SDK
pnpm run test   # Run tests
pnpm run lint   # Lint the codebase

Releasing

On a branch, make your changes then:

  • pnpm run build
  • change package.json version accordingly
  • merge to main
  • create a github release with the same tag as the version in package.json

Upgrading to v2

See UPGRADING.md for migration instructions from v1 to v2.

License

MIT

版本与发布记录

@codex-data/sdk 共发布 121 个版本,首次发布于 2024/08/28;过去 12 个月发布了 74 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.6.3latest2026/11/10今天
2.6.22026/11/10今天
2.5.242026/11/10今天
2.5.212026/11/073 天前
2.5.182026/11/055 天前
2.5.152026/11/037 天前

关于 @codex-data/sdk 的常见问题

@codex-data/sdk 是什么?

The Codex SDK for JavaScript/Typescript. It provides generated types and convenient ways to access the graphql api.

如何安装 @codex-data/sdk?

在项目目录运行 npm install @codex-data/sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:graphql(^16.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@codex-data/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@codex-data/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@codex-data/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=17.5.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@codex-data/sdk 可以商用吗?

@codex-data/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@codex-data/sdk 的下载量有多少?

根据 npm 官方下载统计,@codex-data/sdk 在 2026/10/10 – 2026/11/08 这 30 天内被下载 206,276 次,日均约 6,876 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@codex-data/sdk 还在维护吗?

最新版本 2.6.3 发布于 2026/11/10(今天);至今共发布 121 个版本,其中过去 12 个月发布了 74 个;首次发布于 2024/08/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。