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,
EventCommitmentLevel.Confirmed,
],
},
{
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.
With useEdge: true, a subscription requesting both Processed and Confirmed opens two operations: Confirmed on the main API, and Processed on edge. Results share one sink and one unsubscribe function. Completion waits for both operations; a terminal error cancels both.
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
| Network |
ID |
| Ethereum |
1 |
| BNB |
56 |
| Polygon |
137 |
| Arbitrum |
42161 |
| Base |
8453 |
| Avalanche |
43114 |
| Solana |
1399811149 |
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.*)