Comparing coingecko with farcaster
coingecko
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
CoinGecko Solana API Development Guide
A comprehensive guide for integrating CoinGecko's on-chain API for Solana. Access real-time token prices, DEX pool data, OHLCV charts, trade history, and market analytics across 1,700+ decentralized exchanges.
Overview
CoinGecko's Solana API provides:
- Token Prices: Real-time prices by contract address (single or batch)
- Pool Data: Liquidity pool information, trending pools, top pools
- OHLCV Charts: Candlestick data for technical analysis
- Trade History: Recent trades for any pool
- DEX Discovery: List all DEXes operating on Solana
- Search: Find pools by token name, symbol, or address
- Megafilter: Advanced filtering across pools, tokens, and DEXes
Key Features
| Feature | Description |
|---|---|
| 250+ Networks | Multi-chain support including Solana |
| 1,700+ DEXes | Raydium, Orca, Jupiter, Meteora, Pump.fun, etc. |
| 15M+ Tokens | Comprehensive token coverage |
| Real-time Data | Updates every 10-30 seconds |
| Historical Data | OHLCV charts and trade history |
Quick Start
Get Your API Key
- Demo API (Free): Visit coingecko.com/en/api
- Pro API (Paid): Visit coingecko.com/en/api/pricing
Environment Setup
# .env file
COINGECKO_API_KEY=your_api_key_here
COINGECKO_API_TYPE=demo # or 'pro'
API Configuration
// Configuration for both Demo and Pro APIs
const CONFIG = {
demo: {
baseUrl: 'https://api.coingecko.com/api/v3/onchain',
headerKey: 'x-cg-demo-api-key',
rateLimit: 30, // calls per minute
},
pro: {
baseUrl: 'https://pro-api.coingecko.com/api/v3/onchain',
headerKey: 'x-cg-pro-api-key',
rateLimit: 500, // calls per minute (varies by plan)
},
};
const apiType = process.env.COINGECKO_API_TYPE || 'demo';
const apiKey = process.env.COINGECKO_API_KEY;
const BASE_URL = CONFIG[apiType].baseUrl;
const HEADER_KEY = CONFIG[apiType].headerKey;
// Solana network identifier
const NETWORK = 'solana';
Basic Token Price Fetch
async function getTokenPrice(tokenAddress: string): Promise<number | null> {
const url = `${BASE_URL}/simple/networks/${NETWORK}/token_price/${tokenAddress}`;
const response = await fetch(url, {
headers: {
[HEADER_KEY]: apiKey,
'Accept': 'application/json',
},
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
return data.data?.attributes?.token_prices?.[tokenAddress] ?? null;
}
// Usage
const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const price = await getTokenPrice(USDC);
console.log(`USDC Price: $${price}`);
API Endpoints Reference
Simple Token Price
Get token prices by contract address.
Endpoint: GET /simple/networks/{network}/token_price/{addresses}
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
network | string | Yes | Network ID (solana) |
addresses | string | Yes | Comma-separated token addresses (max 30 Demo, 100 Pro) |
include_market_cap | boolean | No | Include market cap data |
include_24hr_vol | boolean | No | Include 24h volume |
include_24hr_price_change | boolean | No | Include 24h price change % |
async function getTokenPrices(addresses: string[]): Promise<Record<string, TokenPriceData>> {
const addressList = addresses.join(',');
const url = `${BASE_URL}/simple/networks/${NETWORK}/token_price/${addressList}`;
const params = new URLSearchParams({
include_market_cap: 'true',
include_24hr_vol: 'true',
include_24hr_price_change: 'true',
});
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.attributes || {};
}
Token Data by Address
Get detailed token information.
Endpoint: GET /networks/{network}/tokens/{address}
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
network | string | Yes | Network ID |
address | string | Yes | Token contract address |
include | string | No | Include top_pools for liquidity data |
interface TokenData {
address: string;
name: string;
symbol: string;
decimals: number;
image_url: string;
price_usd: string;
fdv_usd: string;
market_cap_usd: string;
total_supply: string;
volume_usd: {
h24: string;
};
price_change_percentage: {
h24: string;
};
}
async function getTokenData(address: string): Promise<TokenData> {
const url = `${BASE_URL}/networks/${NETWORK}/tokens/${address}?include=top_pools`;
const response = await fetch(url, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.attributes;
}
Multi-Token Data
Batch fetch multiple tokens.
Endpoint: GET /networks/{network}/tokens/multi/{addresses}
async function getMultipleTokens(addresses: string[]): Promise<TokenData[]> {
const addressList = addresses.join(',');
const url = `${BASE_URL}/networks/${NETWORK}/tokens/multi/${addressList}`;
const response = await fetch(url, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => item.attributes) || [];
}
Pool Data by Address
Get detailed pool information.
Endpoint: GET /networks/{network}/pools/{address}
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
include | string | No | base_token, quote_token, dex |
include_volume_breakdown | boolean | No | Volume breakdown by timeframe |
interface PoolData {
address: string;
name: string;
pool_created_at: string;
base_token_price_usd: string;
quote_token_price_usd: string;
base_token_price_native_currency: string;
fdv_usd: string;
market_cap_usd: string;
reserve_in_usd: string;
price_change_percentage: {
m5: string;
h1: string;
h6: string;
h24: string;
};
transactions: {
m5: { buys: number; sells: number };
h1: { buys: number; sells: number };
h24: { buys: number; sells: number };
};
volume_usd: {
m5: string;
h1: string;
h6: string;
h24: string;
};
}
async function getPoolData(poolAddress: string): Promise<PoolData> {
const url = `${BASE_URL}/networks/${NETWORK}/pools/${poolAddress}`;
const params = new URLSearchParams({
include: 'base_token,quote_token,dex',
});
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.attributes;
}
Trending Pools
Get trending pools across all networks or filtered by network.
Endpoint: GET /networks/trending_pools
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
include | string | base_token | Attributes to include |
page | integer | 1 | Page number |
duration | string | 24h | 5m, 1h, 6h, 24h |
async function getTrendingPools(duration: '5m' | '1h' | '6h' | '24h' = '24h'): Promise<PoolData[]> {
const url = `${BASE_URL}/networks/trending_pools`;
const params = new URLSearchParams({
include: 'base_token,quote_token,dex,network',
duration,
page: '1',
});
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => item.attributes) || [];
}
// Filter for Solana pools
async function getSolanaTrendingPools(): Promise<PoolData[]> {
const allPools = await getTrendingPools();
return allPools.filter(pool => pool.network === 'solana');
}
Top Pools on Network
Get top pools by volume on Solana.
Endpoint: GET /networks/{network}/pools
async function getTopPools(page: number = 1): Promise<PoolData[]> {
const url = `${BASE_URL}/networks/${NETWORK}/pools`;
const params = new URLSearchParams({
include: 'base_token,quote_token,dex',
page: page.toString(),
});
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => item.attributes) || [];
}
Search Pools
Search for pools by token name, symbol, or address.
Endpoint: GET /search/pools
Parameters:
| Parameter | Type | Description |
|---|---|---|
query | string | Search term (name, symbol, address) |
network | string | Filter by network |
page | integer | Page number |
async function searchPools(query: string): Promise<PoolData[]> {
const url = `${BASE_URL}/search/pools`;
const params = new URLSearchParams({
query,
network: NETWORK,
include: 'base_token,quote_token,dex',
});
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => item.attributes) || [];
}
// Search for SOL pools
const solPools = await searchPools('SOL');
Pool OHLCV Chart
Get candlestick data for technical analysis.
Endpoint: GET /networks/{network}/pools/{pool_address}/ohlcv/{timeframe}
Timeframes: day, hour, minute
Parameters:
| Parameter | Type | Description |
|---|---|---|
aggregate | integer | Candle aggregation (1, 5, 15 for minute; 1, 4, 12 for hour) |
before_timestamp | integer | Unix timestamp for pagination |
limit | integer | Number of candles (max 1000) |
currency | string | usd or token |
interface OHLCVData {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
async function getPoolOHLCV(
poolAddress: string,
timeframe: 'day' | 'hour' | 'minute' = 'hour',
aggregate: number = 1,
limit: number = 100
): Promise<OHLCVData[]> {
const url = `${BASE_URL}/networks/${NETWORK}/pools/${poolAddress}/ohlcv/${timeframe}`;
const params = new URLSearchParams({
aggregate: aggregate.toString(),
limit: limit.toString(),
currency: 'usd',
});
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.attributes?.ohlcv_list?.map((candle: number[]) => ({
timestamp: candle[0],
open: candle[1],
high: candle[2],
low: candle[3],
close: candle[4],
volume: candle[5],
})) || [];
}
// Get hourly candles
const hourlyCandles = await getPoolOHLCV(poolAddress, 'hour', 1, 24);
// Get 5-minute candles
const fiveMinCandles = await getPoolOHLCV(poolAddress, 'minute', 5, 100);
Recent Trades
Get recent trades for a pool.
Endpoint: GET /networks/{network}/pools/{pool_address}/trades
interface TradeData {
block_number: number;
block_timestamp: string;
tx_hash: string;
tx_from_address: string;
from_token_amount: string;
to_token_amount: string;
price_from_in_currency_token: string;
price_to_in_currency_token: string;
price_from_in_usd: string;
price_to_in_usd: string;
kind: 'buy' | 'sell';
volume_in_usd: string;
}
async function getRecentTrades(poolAddress: string): Promise<TradeData[]> {
const url = `${BASE_URL}/networks/${NETWORK}/pools/${poolAddress}/trades`;
const response = await fetch(url, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => item.attributes) || [];
}
List DEXes on Solana
Get all decentralized exchanges on Solana.
Endpoint: GET /networks/{network}/dexes
interface DexData {
id: string;
name: string;
}
async function getSolanaDexes(): Promise<DexData[]> {
const url = `${BASE_URL}/networks/${NETWORK}/dexes`;
const response = await fetch(url, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => ({
id: item.id,
name: item.attributes.name,
})) || [];
}
Megafilter (Advanced)
Advanced filtering for pools across networks, DEXes, and tokens.
Endpoint: GET /pools/megafilter
Parameters:
| Parameter | Type | Description |
|---|---|---|
networks | string | Filter by network(s) |
dexes | string | Filter by DEX(es) |
sort | string | Sort order (e.g., pool_created_at_desc) |
min_reserve_in_usd | number | Minimum liquidity |
min_h24_volume_usd | number | Minimum 24h volume |
async function getMegafilterPools(options: {
dexes?: string[];
minLiquidity?: number;
minVolume?: number;
sort?: string;
}): Promise<PoolData[]> {
const url = `${BASE_URL}/pools/megafilter`;
const params = new URLSearchParams({
networks: NETWORK,
page: '1',
});
if (options.dexes) {
params.set('dexes', options.dexes.join(','));
}
if (options.minLiquidity) {
params.set('min_reserve_in_usd', options.minLiquidity.toString());
}
if (options.minVolume) {
params.set('min_h24_volume_usd', options.minVolume.toString());
}
if (options.sort) {
params.set('sort', options.sort);
}
const response = await fetch(`${url}?${params}`, {
headers: { [HEADER_KEY]: apiKey },
});
const data = await response.json();
return data.data?.map((item: any) => item.attributes) || [];
}
// Get newest Pump.fun pools
const pumpfunPools = await getMegafilterPools({
dexes: ['pump-fun'],
sort: 'pool_created_at_desc',
});
// Get high-volume Raydium pools
const raydiumPools = await getMegafilterPools({
dexes: ['raydium'],
minVolume: 100000,
minLiquidity: 50000,
});
Common Solana DEX Identifiers
| DEX | ID | Description |
|---|---|---|
| Raydium | raydium | Leading AMM on Solana |
| Orca | orca | User-friendly DEX |
| Jupiter | jupiter | Aggregator with pools |
| Meteora | meteora | Dynamic AMM |
| Pump.fun | pump-fun | Memecoin launchpad |
| OpenBook | openbook | Order book DEX |
| Lifinity | lifinity | Proactive market maker |
| Phoenix | phoenix | On-chain order book |
Common Token Addresses
| Token | Address |
|---|---|
| USDC | EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v |
| USDT | Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB |
| SOL (Wrapped) | So11111111111111111111111111111111111111112 |
| JUP | JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN |
| BONK | DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263 |
| WIF | EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm |
| PYTH | HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3 |
| RAY | 4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R |
| ORCA | orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE |
Rate Limits
| Plan | Calls/Minute | Max Addresses/Request |
|---|---|---|
| Demo (Free) | 30 | 30 |
| Analyst | 500 | 50 |
| Lite | 500 | 50 |
| Pro | 1,000 | 100 |
| Enterprise | Custom | Custom |
Rate Limit Handling
class RateLimiter {
private calls: number[] = [];
private maxCalls: number;
private windowMs: number = 60000; // 1 minute
constructor(maxCallsPerMinute: number) {
this.maxCalls = maxCallsPerMinute;
}
async waitForSlot(): Promise<void> {
const now = Date.now();
this.calls = this.calls.filter(t => now - t < this.windowMs);
if (this.calls.length >= this.maxCalls) {
const oldestCall = this.calls[0];
const waitTime = this.windowMs - (now - oldestCall);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
this.calls.push(Date.now());
}
}
// Usage
const rateLimiter = new RateLimiter(30); // Demo API
async function fetchWithRateLimit(url: string): Promise<any> {
await rateLimiter.waitForSlot();
const response = await fetch(url, {
headers: { [HEADER_KEY]: apiKey },
});
return response.json();
}
Error Handling
async function safeApiCall<T>(url: string): Promise<T | null> {
try {
const response = await fetch(url, {
headers: { [HEADER_KEY]: apiKey },
});
if (response.status === 401) {
throw new Error('Invalid API key');
}
if (response.status === 429) {
throw new Error('Rate limit exceeded - wait before retrying');
}
if (response.status === 404) {
console.warn('Resource not found');
return null;
}
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
} catch (error) {
console.error('CoinGecko API error:', error);
throw error;
}
}
Common Error Codes
| Code | Meaning | Solution |
|---|---|---|
| 401 | Invalid API key | Check your API key |
| 429 | Rate limit exceeded | Wait and retry, or upgrade plan |
| 404 | Resource not found | Check address/network ID |
| 500+ | Server error | Retry with exponential backoff |
Best Practices
Security
- Never commit API keys to git
- Use environment variables
- Rotate keys periodically
- Use separate keys for dev/prod
Performance
- Batch token requests when possible
- Cache frequently accessed data
- Use appropriate timeframes for OHLCV
- Implement request queuing for rate limits
Data Quality
- Verify market cap data (may be null if unverified)
- Check pool liquidity before trusting prices
- Use multiple timeframes for price analysis
- Monitor last trade timestamp for activity
Resources
Skill Structure
coingecko/
├── SKILL.md # This file
├── resources/
│ ├── api-reference.md # Complete API endpoint reference
│ ├── network-dex-ids.md # Solana network and DEX identifiers
│ └── token-addresses.md # Common Solana token addresses
├── examples/
│ ├── token-prices/
│ │ └── get-token-price.ts # Token price examples
│ ├── pools/
│ │ └── pool-data.ts # Pool data examples
│ ├── ohlcv/
│ │ └── ohlcv-charts.ts # OHLCV chart examples
│ ├── trades/
│ │ └── recent-trades.ts # Trade history examples
│ └── integration/
│ └── full-client.ts # Complete client example
├── templates/
│ └── coingecko-client.ts # Production-ready client template
└── docs/
└── troubleshooting.md # Common issues and solutions
farcaster
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
Farcaster
Farcaster is a sufficiently decentralized social protocol. Users register onchain identities (FIDs) on OP Mainnet and publish social data (casts, reactions, links) as offchain messages to Snapchain, a purpose-built message ordering layer. Neynar provides the primary API infrastructure and, since January 2026, owns the Farcaster protocol itself. Frames v2 (Mini Apps) enable full-screen interactive web applications embedded inside Farcaster clients like Warpcast.
What You Probably Got Wrong
-
Manifest
accountAssociationdomain MUST exactly match the FQDN where/.well-known/farcaster.jsonis hosted. A mismatch causes silent failure -- the Mini App will not load, no error is surfaced to the developer, and Warpcast simply shows nothing. The domain in the signature payload must be byte-identical to the hosting domain (no trailing slash, no protocol prefix, no port unless non-standard). -
Neynar webhooks MUST be verified via HMAC-SHA512 at write time. Check the
X-Neynar-Signatureheader against the raw request body. Never parse JSON before verification -- you must verify the raw bytes.
import crypto from "node:crypto";
import type { IncomingHttpHeaders } from "node:http";
function verifyNeynarWebhook(
rawBody: Buffer,
headers: IncomingHttpHeaders,
webhookSecret: string
): boolean {
const signature = headers["x-neynar-signature"];
if (typeof signature !== "string") return false;
const hmac = crypto.createHmac("sha512", webhookSecret);
hmac.update(rawBody);
const computedSignature = hmac.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(computedSignature, "hex")
);
}
-
Farcaster is NOT a blockchain. It is a social protocol with an onchain registry (OP Mainnet) for identity and key management, plus an offchain message layer (Snapchain) for social data. Casts, reactions, and follows are never posted to any blockchain.
-
FIDs are onchain but casts are NOT. Farcaster IDs (FIDs) live in the IdRegistry contract on OP Mainnet. Casts, reactions, and link messages are stored on Snapchain and are not onchain data.
-
Frames v2 is NOT Frames v1 -- completely different spec. Frames v1 used static OG images with action buttons and server-side rendering. Frames v2 (Mini Apps) are full-screen interactive web applications loaded in an iframe with SDK access to wallet, user context, and notifications. Do not mix the two APIs.
-
Neynar is NOT just an API provider. Neynar acquired Farcaster from Merkle Manufactory in January 2026. Neynar now owns and operates the protocol, the Snapchain infrastructure, and the primary API layer.
-
Frame images must be static. Frame preview images (OG images shown in feed) cannot contain JavaScript. They are rendered as static images by the client. Interactive behavior only works inside the launched Mini App.
-
@farcaster/frame-sdkand@farcaster/miniapp-sdkare converging. Both packages exist butframe-sdkis the current stable package for Frames v2. Check import paths -- functionality overlaps but the packages are not yet unified. -
Farcaster timestamps use a custom epoch. Timestamps are seconds since January 1, 2021 00:00:00 UTC (Farcaster epoch), not Unix epoch. To convert:
unixTimestamp = farcasterTimestamp + 1609459200. -
Cast text has a 1024 BYTE limit, not characters. UTF-8 multibyte characters (emoji, CJK, accented characters) consume 2-4 bytes each. A 1024-character cast with emoji will exceed the limit.
-
Warpcast aggressively caches OG/frame images. Changing content at the same URL will not update the preview in Warpcast feeds. Use cache-busting query parameters or new URLs when updating frame images.
Critical Context
Neynar acquired Farcaster from Merkle Manufactory in January 2026. This means:
- Neynar operates the protocol, Snapchain validators, and the Hub network
- The Neynar API is the canonical way to interact with Farcaster
- Warpcast remains the primary client, now under Neynar's umbrella
- The open-source protocol spec and hub software remain MIT-licensed
- Third-party hubs can still run, but Neynar controls the reference implementation
Protocol Architecture
Snapchain
Snapchain replaced the Hub network in April 2025 as Farcaster's offchain message ordering layer.
| Property | Detail |
|---|---|
| Consensus | Malachite BFT (Tendermint-derived) |
| Throughput | 10,000+ messages per second |
| Sharding | Account-level -- each FID's messages are ordered independently |
| Finality | Sub-second for message acceptance |
| Data model | Append-only log of signed messages per FID |
| Validator set | Operated by Neynar (post-acquisition) |
Messages on Snapchain are CRDTs (Conflict-free Replicated Data Types). Each message type has merge rules that ensure consistency across nodes without coordination:
- CastAdd conflicts with a later CastRemove for the same hash -- remove wins
- ReactionAdd conflicts with ReactionRemove for the same target -- last-write-wins by timestamp
- LinkAdd conflicts with LinkRemove -- last-write-wins by timestamp
Message Structure
Every Farcaster message is an Ed25519-signed protobuf:
MessageData {
type: MessageType // CAST_ADD, REACTION_ADD, LINK_ADD, etc.
fid: uint64 // Farcaster ID of the author
timestamp: uint32 // Farcaster epoch seconds
network: Network // MAINNET = 1
body: MessageBody // Type-specific payload
}
Message {
data: MessageData
hash: bytes // Blake3 hash of serialized MessageData
hash_scheme: BLAKE3
signature: bytes // Ed25519 signature over hash
signature_scheme: ED25519
signer: bytes // Public key of the signer (app key)
}
Onchain Registry (OP Mainnet)
Farcaster's onchain contracts manage identity, keys, and storage on OP Mainnet.
Last verified: March 2026
| Contract | Address | Purpose |
|---|---|---|
| IdRegistry | 0x00000000Fc6c5F01Fc30151999387Bb99A9f489b | Maps FIDs to custody addresses |
| KeyRegistry | 0x00000000Fc1237824fb747aBDE0FF18990E59b7e | Maps FIDs to Ed25519 app keys (signers) |
| StorageRegistry | 0x00000000FcCe7f938e7aE6D3c335bD6a1a7c593D | Manages storage units per FID |
| IdGateway | 0x00000000Fc25870C6eD6b6c7E41Fb078b7656f69 | Permissioned FID registration entry point |
| KeyGateway | 0x00000000fC56947c7E7183f8Ca4B62398CaaDF0B | Permissioned key addition entry point |
| Bundler | 0x00000000FC04c910A0b5feA33b03E0447ad0B0aA | Batches register + addKey + rent in one tx |
# Verify IdRegistry is deployed on OP Mainnet
cast code 0x00000000Fc6c5F01Fc30151999387Bb99A9f489b --rpc-url https://mainnet.optimism.io
# Look up custody address for an FID
cast call 0x00000000Fc6c5F01Fc30151999387Bb99A9f489b \
"custodyOf(uint256)(address)" 3 \
--rpc-url https://mainnet.optimism.io
Registration Flow
1. User calls IdGateway.register() or Bundler.register()
-> IdRegistry assigns next sequential FID to custody address
|
2. User (or Bundler) calls KeyGateway.add()
-> KeyRegistry maps FID to an Ed25519 public key (app key / signer)
|
3. User (or Bundler) calls StorageRegistry.rent()
-> Allocates storage units (each unit = 5,000 casts, 2,500 reactions, 2,500 links)
|
4. App key can now sign Farcaster messages on behalf of the FID
Farcaster IDs (FIDs)
Every Farcaster user has an FID -- a sequentially assigned uint256 stored in IdRegistry on OP Mainnet.
| Concept | Description |
|---|---|
| FID | The user's numeric identity, immutable once assigned |
| Custody address | The Ethereum address that owns the FID -- can transfer ownership |
| App key (signer) | Ed25519 key pair registered in KeyRegistry -- signs messages |
| Recovery address | Can initiate FID recovery if custody address is compromised |
An FID can have multiple app keys. Each app (Warpcast, third-party client) registers its own app key via KeyGateway. The custody address can revoke any app key by calling KeyRegistry.remove().
Neynar API v2
Neynar provides the primary API for reading and writing Farcaster data. Current SDK version: @neynar/nodejs-sdk v3.131.0.
Setup
npm install @neynar/nodejs-sdk
import { NeynarAPIClient, Configuration } from "@neynar/nodejs-sdk";
const config = new Configuration({
apiKey: process.env.NEYNAR_API_KEY,
});
const neynar = new NeynarAPIClient(config);
Fetch User by FID
const { users } = await neynar.fetchBulkUsers({ fids: [3] });
const user = users[0];
console.log(user.username, user.display_name, user.follower_count);
Publish a Cast
const response = await neynar.publishCast({
signerUuid: process.env.SIGNER_UUID,
text: "Hello from Neynar SDK",
});
console.log(response.cast.hash);
Fetch Feed
const feed = await neynar.fetchFeed({
feedType: "following",
fid: 3,
limit: 25,
});
for (const cast of feed.casts) {
console.log(`@${cast.author.username}: ${cast.text}`);
}
Search Users
const result = await neynar.searchUser({ q: "vitalik", limit: 5 });
for (const user of result.result.users) {
console.log(`FID ${user.fid}: @${user.username}`);
}
Fetch Cast by Hash
const { cast } = await neynar.lookupCastByHashOrWarpcastUrl({
identifier: "0xfe90f9de682273e05b201629ad2338bdcd89b6be",
type: "hash",
});
console.log(cast.text, cast.reactions.likes_count);
Webhook Configuration
Create webhooks in the Neynar dashboard or via API. Webhooks fire on cast creation, reaction events, follow events, and more.
import express from "express";
import crypto from "node:crypto";
const app = express();
// Raw body is required for signature verification
app.use("/webhook", express.raw({ type: "application/json" }));
app.post("/webhook", (req, res) => {
const rawBody = req.body as Buffer;
const signature = req.headers["x-neynar-signature"] as string;
if (!signature) {
res.status(401).json({ error: "Missing signature" });
return;
}
const hmac = crypto.createHmac("sha512", process.env.NEYNAR_WEBHOOK_SECRET!);
hmac.update(rawBody);
const computed = hmac.digest("hex");
const isValid = crypto.timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(computed, "hex")
);
if (!isValid) {
res.status(401).json({ error: "Invalid signature" });
return;
}
const event = JSON.parse(rawBody.toString("utf-8"));
console.log("Verified webhook event:", event.type);
res.status(200).json({ status: "ok" });
});
app.listen(3001, () => console.log("Webhook listener on :3001"));
Frames v2 / Mini Apps
Frames v2 are full-screen interactive web applications embedded inside Farcaster clients. They replaced the static image + button model of Frames v1 with a rich SDK-powered experience.
Manifest (/.well-known/farcaster.json)
Every Mini App must serve a manifest at /.well-known/farcaster.json on its domain:
{
"accountAssociation": {
"header": "eyJmaWQiOjM...",
"payload": "eyJkb21haW4iOiJleGFtcGxlLmNvbSJ9",
"signature": "abc123..."
},
"frame": {
"version": "1",
"name": "My Mini App",
"iconUrl": "https://example.com/icon.png",
"homeUrl": "https://example.com/app",
"splashImageUrl": "https://example.com/splash.png",
"splashBackgroundColor": "#1a1a2e",
"webhookUrl": "https://example.com/api/webhook"
}
}
The accountAssociation proves that the FID owner controls the domain. The payload decoded is {"domain":"example.com"} -- this domain MUST match the FQDN hosting the manifest file.
Meta Tags
Add these to your app's HTML <head> for Farcaster clients to discover the Mini App:
<meta name="fc:frame" content='{"version":"next","imageUrl":"https://example.com/og.png","button":{"title":"Launch App","action":{"type":"launch_frame","name":"My App","url":"https://example.com/app","splashImageUrl":"https://example.com/splash.png","splashBackgroundColor":"#1a1a2e"}}}' />
Frame SDK Setup
npm install @farcaster/frame-sdk
import sdk from "@farcaster/frame-sdk";
async function initMiniApp() {
const context = await sdk.context;
// context.user contains the viewing user's FID, username, pfpUrl
console.log(`User FID: ${context.user.fid}`);
console.log(`Username: ${context.user.username}`);
// Signal to the client that the app is ready to render
sdk.actions.ready();
}
initMiniApp();
SDK Actions
// Open an external URL in the client's browser
sdk.actions.openUrl("https://example.com");
// Close the Mini App
sdk.actions.close();
// Compose a cast with prefilled text
sdk.actions.composeCast({
text: "Check out this Mini App!",
embeds: ["https://example.com/app"],
});
// Add a Mini App to the user's favorites (prompts confirmation)
sdk.actions.addFrame();
Transaction Frames
Mini Apps can trigger onchain transactions through the embedded wallet provider. The SDK exposes an EIP-1193 provider that connects to the user's wallet in the Farcaster client.
Wallet Provider Setup
import sdk from "@farcaster/frame-sdk";
import { createWalletClient, custom, parseEther, type Address } from "viem";
import { base } from "viem/chains";
async function sendTransaction() {
const context = await sdk.context;
const provider = sdk.wallet.ethProvider;
const walletClient = createWalletClient({
chain: base,
transport: custom(provider),
});
const [address] = await walletClient.requestAddresses();
const hash = await walletClient.sendTransaction({
account: address,
to: "0xRecipient..." as Address,
value: parseEther("0.001"),
});
return hash;
}
With Wagmi Connector
For apps using wagmi, wrap the SDK's provider as a connector:
import sdk from "@farcaster/frame-sdk";
import { createConfig, http, useConnect, useSendTransaction } from "wagmi";
import { base } from "wagmi/chains";
import { farcasterFrame } from "@farcaster/frame-wagmi-connector";
const config = createConfig({
chains: [base],
transports: {
[base.id]: http(),
},
connectors: [farcasterFrame()],
});
// In your React component:
function MintButton() {
const { connect, connectors } = useConnect();
const { sendTransaction } = useSendTransaction();
async function handleMint() {
connect({ connector: connectors[0] });
sendTransaction({
to: "0xNFTContract..." as `0x${string}`,
data: "0x...", // mint function calldata
value: parseEther("0.01"),
});
}
return <button onClick={handleMint}>Mint</button>;
}
Warpcast Deep Links and Cast Intents
Cast Intent URL
Open Warpcast's compose screen with prefilled content:
https://warpcast.com/~/compose?text=Hello%20Farcaster&embeds[]=https://example.com
| Parameter | Description |
|---|---|
text | URL-encoded cast text |
embeds[] | Up to 2 embed URLs |
channelKey | Channel to post in (e.g., farcaster) |
Deep Links
# Open a user's profile
https://warpcast.com/<username>
# Open a specific cast
https://warpcast.com/<username>/<cast-hash>
# Open a channel
https://warpcast.com/~/channel/<channel-id>
# Open direct cast composer
https://warpcast.com/~/inbox/create/<fid>
Channels
Channels are topic-based feeds identified by a parent_url. A cast is posted to a channel by setting its parent_url to the channel's URL.
// Post a cast to the "ethereum" channel
const response = await neynar.publishCast({
signerUuid: process.env.SIGNER_UUID,
text: "Pectra upgrade is live!",
channelId: "ethereum",
});
Channel Lookup
const channel = await neynar.lookupChannel({ id: "farcaster" });
console.log(channel.channel.name, channel.channel.follower_count);
Channel Feed
const feed = await neynar.fetchFeed({
feedType: "filter",
filterType: "channel_id",
channelId: "ethereum",
limit: 25,
});
Neynar API Pricing
Current as of March 2026
| Plan | Monthly Credits | Price | Webhooks | Rate Limit |
|---|---|---|---|---|
| Free | 100K | $0 | 1 | 5 req/s |
| Starter | 1M | $49/mo | 5 | 20 req/s |
| Growth | 10M | $249/mo | 25 | 50 req/s |
| Scale | 60M | $899/mo | 100 | 200 req/s |
| Enterprise | Custom | Custom | Unlimited | Custom |
Credit costs vary by endpoint. Read operations (user lookup, feed) cost 1-5 credits. Write operations (publish cast, react) cost 10-50 credits. Webhook deliveries are free but count against webhook limits.
Hub / Snapchain Endpoints
Direct hub access for reading raw Farcaster data without the Neynar API abstraction.
| Provider | Endpoint | Auth |
|---|---|---|
| Neynar Hub API | hub-api.neynar.com | API key in x-api-key header |
| Self-hosted Hub | localhost:2283 | None (local) |
Hub HTTP API Examples
# Get casts by FID
curl -H "x-api-key: $NEYNAR_API_KEY" \
"https://hub-api.neynar.com/v1/castsByFid?fid=3&pageSize=10"
# Get user data (display name, bio, pfp)
curl -H "x-api-key: $NEYNAR_API_KEY" \
"https://hub-api.neynar.com/v1/userDataByFid?fid=3"
# Get reactions by FID
curl -H "x-api-key: $NEYNAR_API_KEY" \
"https://hub-api.neynar.com/v1/reactionsByFid?fid=3&reactionType=1"
Hub gRPC API
# Install hubble CLI
npm install -g @farcaster/hubble
# Query via gRPC
hubble --insecure -r hub-api.neynar.com:2283 getCastsByFid --fid 3
Farcaster Epoch Conversion
// Farcaster epoch: January 1, 2021 00:00:00 UTC
const FARCASTER_EPOCH = 1609459200;
function farcasterTimestampToUnix(farcasterTs: number): number {
return farcasterTs + FARCASTER_EPOCH;
}
function unixToFarcasterTimestamp(unixTs: number): number {
return unixTs - FARCASTER_EPOCH;
}
function farcasterTimestampToDate(farcasterTs: number): Date {
return new Date((farcasterTs + FARCASTER_EPOCH) * 1000);
}
Related Skills
- viem -- Used for onchain interactions with Farcaster registry contracts on OP Mainnet and for building transaction frames with the wallet provider
- wagmi -- React hooks for wallet connection in Mini Apps via the
@farcaster/frame-wagmi-connector - x402 -- Payment protocol that can be integrated with Farcaster Mini Apps for paywalled content