Comparing curve with farcaster

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/curve/SKILL.md

Curve Finance

Curve is the dominant AMM for pegged-asset swaps (stablecoins, wrapped tokens, LSTs). Its StableSwap invariant concentrates liquidity around peg, delivering 10-100x lower slippage than constant-product AMMs for like-kind assets. CryptoSwap (Tricrypto) extends this to volatile pairs. The protocol also issues crvUSD, a stablecoin backed by LLAMMA — a soft-liquidation mechanism that gradually converts collateral instead of instant liquidation. CRV emissions are directed to liquidity gauges via vote-escrowed CRV (veCRV).

All Curve pool contracts are written in Vyper. ABI encoding is identical to Solidity — viem works without modification.

What You Probably Got Wrong

Curve is one of the most commonly mis-integrated protocols. Each pool type has different interfaces, and token ordering is deployment-specific.

  • Curve pools have DIFFERENT ABIs per pool type — StableSwap (2-pool, 3-pool), CryptoSwap, Tricrypto, Meta pools, and Factory pools all have different function signatures. There is NO universal pool ABI. Always read the specific pool's ABI from Etherscan or the Curve docs.
  • Token indices are pool-specific and NOT sorted — The order depends on deployment, not address sorting. Always call coins(i) to verify which token is at which index. Getting this wrong swaps the wrong token.
  • exchange() uses token indices, not addresses — You pass i (sell token index) and j (buy token index), not token addresses. Passing the wrong index silently swaps the wrong token pair.
  • get_dy() returns the estimated output BEFORE fees — The actual received amount is slightly less. Use get_dy() for quoting but apply slippage tolerance on top.
  • add_liquidity() amounts array length varies per pool — 2 for 2-pool, 3 for 3-pool, 4 for 4-pool. Passing the wrong array length causes a revert with no useful error message.
  • exchange() vs exchange_underlying() — Plain pools use exchange(). Meta pools use exchange_underlying() to swap between the meta-asset and the underlying basepool tokens. Calling the wrong function reverts.
  • crvUSD uses LLAMMA (soft liquidation), NOT traditional liquidation — Positions are gradually converted between collateral and crvUSD as price moves through bands. There is no instant liquidation threshold. Health approaching 0 means bands are fully converted.
  • Gauge voting requires veCRV (vote-escrowed CRV) — Lock CRV for 1-4 years to get voting power. Voting power decays linearly. You cannot transfer or sell veCRV.
  • remove_liquidity_one_coin() has high slippage for large withdrawals from imbalanced pools — The StableSwap invariant penalizes imbalanced withdrawals. Always simulate first.
  • Virtual price only goes up (monotonic)get_virtual_price() returns the LP token value in underlying. It increases from fees and never decreases. Useful for pricing LP positions but NOT for detecting exploits (it was manipulated in some reentrancy attacks on Vyper <0.3.1 pools).

Quick Start

Installation

npm install viem

Client Setup

import { createPublicClient, createWalletClient, http, type Address } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";

const publicClient = createPublicClient({
  chain: mainnet,
  transport: http(process.env.RPC_URL),
});

const account = privateKeyToAccount(
  process.env.PRIVATE_KEY as `0x${string}`
);

const walletClient = createWalletClient({
  account,
  chain: mainnet,
  transport: http(process.env.RPC_URL),
});

Swap USDC to USDT on 3pool

const THREE_POOL = "0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7" as const;

// 3pool indices: 0 = DAI, 1 = USDC, 2 = USDT
// Always verify with coins(i) before swapping
const threePoolAbi = [
  {
    name: "exchange",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "i", type: "int128" },
      { name: "j", type: "int128" },
      { name: "dx", type: "uint256" },
      { name: "min_dy", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "get_dy",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "i", type: "int128" },
      { name: "j", type: "int128" },
      { name: "dx", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "coins",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "i", type: "uint256" }],
    outputs: [{ name: "", type: "address" }],
  },
] as const;

const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" as const;
const USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7" as const;

const amountIn = 10_000_000000n; // 10,000 USDC (6 decimals)

// Verify token indices
const coin1 = await publicClient.readContract({
  address: THREE_POOL,
  abi: threePoolAbi,
  functionName: "coins",
  args: [1n],
});
if (coin1.toLowerCase() !== USDC.toLowerCase()) {
  throw new Error(`Expected USDC at index 1, got ${coin1}`);
}

// Quote expected output
const expectedOut = await publicClient.readContract({
  address: THREE_POOL,
  abi: threePoolAbi,
  functionName: "get_dy",
  args: [1n, 2n, amountIn], // i=1 (USDC) -> j=2 (USDT)
});

// 0.1% slippage tolerance (stableswap pools have tight spreads)
const minDy = (expectedOut * 999n) / 1000n;

// Approve 3pool to spend USDC
const erc20Abi = [
  {
    name: "approve",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "spender", type: "address" },
      { name: "amount", type: "uint256" },
    ],
    outputs: [{ name: "", type: "bool" }],
  },
] as const;

const { request: approveRequest } = await publicClient.simulateContract({
  address: USDC,
  abi: erc20Abi,
  functionName: "approve",
  args: [THREE_POOL, amountIn],
  account: account.address,
});
const approveHash = await walletClient.writeContract(approveRequest);
await publicClient.waitForTransactionReceipt({ hash: approveHash });

// Execute swap
const { request } = await publicClient.simulateContract({
  address: THREE_POOL,
  abi: threePoolAbi,
  functionName: "exchange",
  args: [1n, 2n, amountIn, minDy],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Swap reverted");

Pool Types

StableSwap Pools (Pegged Assets)

The original Curve pool type. Optimized for assets that trade near 1:1 (stablecoins, wrapped tokens). Uses the StableSwap invariant which blends constant-sum and constant-product formulas, controlled by the amplification parameter A.

PoolAddressCoinsIndices
3pool0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7DAI, USDC, USDT0, 1, 2
stETH/ETH0xDC24316b9AE028F1497c275EB9192a3Ea0f67022ETH, stETH0, 1
frxETH/ETH0xa1F8A6807c402E4A15ef4EBa36528A3FED24E577ETH, frxETH0, 1

Key parameters:

  • A (amplification) — Higher A means tighter peg. 3pool uses A=2000. Ranges from 1 (constant product) to ~5000.
  • Fee — Typically 0.01%-0.04% for stableswap pools. Read via fee() (returns value in 1e10 precision, so 4000000 = 0.04%).

CryptoSwap Pools (Volatile Pairs)

Two-token pools for non-pegged assets using the CryptoSwap invariant. Internally re-pegs around the current price, providing concentrated liquidity that auto-rebalances.

PoolAddressCoins
tricrypto20xD51a44d3FaE010294C616388b506AcdA1bfAAE46USDT, WBTC, WETH

Meta Pools

Pools that pair a single token against an existing basepool's LP token. For example, FRAX/3CRV pairs FRAX against the 3pool LP token, giving FRAX access to DAI/USDC/USDT liquidity.

// Meta pool: exchange_underlying() swaps between the meta-asset
// and any token in the basepool
const metaPoolAbi = [
  {
    name: "exchange_underlying",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "i", type: "int128" },
      { name: "j", type: "int128" },
      { name: "dx", type: "uint256" },
      { name: "min_dy", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// LUSD/3CRV meta pool
// Underlying indices: 0 = LUSD, 1 = DAI, 2 = USDC, 3 = USDT
// exchange_underlying(0, 2, amount, minOut) swaps LUSD -> USDC

Factory Pools

User-deployed pools created through the Curve Factory. They follow the same interface as their pool type (StableSwap or CryptoSwap) but are created permissionlessly.

const CURVE_FACTORY = "0xB9fC157394Af804a3578134A6585C0dc9cc990d4" as const;

const factoryAbi = [
  {
    name: "pool_count",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "pool_list",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "i", type: "uint256" }],
    outputs: [{ name: "", type: "address" }],
  },
] as const;

const poolCount = await publicClient.readContract({
  address: CURVE_FACTORY,
  abi: factoryAbi,
  functionName: "pool_count",
});

Swapping

Basic Exchange (StableSwap)

All StableSwap pools use exchange(i, j, dx, min_dy) where i and j are token indices.

// Older pools (like 3pool) use int128 for indices
const stableSwapExchangeAbi = [
  {
    name: "exchange",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "i", type: "int128" },
      { name: "j", type: "int128" },
      { name: "dx", type: "uint256" },
      { name: "min_dy", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Newer factory pools may use uint256 for indices
const factoryExchangeAbi = [
  {
    name: "exchange",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "i", type: "uint256" },
      { name: "j", type: "uint256" },
      { name: "dx", type: "uint256" },
      { name: "min_dy", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

Exchange with ETH

ETH pools (stETH/ETH, frxETH/ETH) accept native ETH via msg.value. Pass ETH as value, not as an ERC-20 approval.

const STETH_POOL = "0xDC24316b9AE028F1497c275EB9192a3Ea0f67022" as const;

// stETH/ETH pool: 0 = ETH, 1 = stETH
const ethPoolExchangeAbi = [
  {
    name: "exchange",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "i", type: "int128" },
      { name: "j", type: "int128" },
      { name: "dx", type: "uint256" },
      { name: "min_dy", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

const ethAmount = 1_000_000_000_000_000_000n; // 1 ETH

const expectedSteth = await publicClient.readContract({
  address: STETH_POOL,
  abi: threePoolAbi, // get_dy has same signature
  functionName: "get_dy",
  args: [0n, 1n, ethAmount],
});

const minSteth = (expectedSteth * 999n) / 1000n;

const { request } = await publicClient.simulateContract({
  address: STETH_POOL,
  abi: ethPoolExchangeAbi,
  functionName: "exchange",
  args: [0n, 1n, ethAmount, minSteth],
  value: ethAmount, // send ETH with the call
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Swap reverted");

Curve Router

For optimal routing across multiple pools, use the Curve Router. It finds the best path automatically.

const CURVE_ROUTER = "0xF0d4c12A5768D806021F80a262B4d39d26C58b8D" as const;

const routerAbi = [
  {
    name: "exchange",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "_route", type: "address[11]" },
      { name: "_swap_params", type: "uint256[5][5]" },
      { name: "_amount", type: "uint256" },
      { name: "_min_dy", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "get_dy",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "_route", type: "address[11]" },
      { name: "_swap_params", type: "uint256[5][5]" },
      { name: "_amount", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Route encoding: alternating [token, pool, token, pool, ..., token]
// padded with zero addresses to length 11
// swap_params[i] = [i, j, swap_type, pool_type, n_coins]
// swap_type: 1 = exchange, 2 = exchange_underlying, 3 = exchange on underlying
// pool_type: 1 = stableswap, 2 = cryptoswap, 3 = tricrypto

Liquidity

Add Liquidity (Balanced)

Provide all tokens proportionally to minimize slippage.

const addLiquidityAbi = [
  {
    name: "add_liquidity",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "amounts", type: "uint256[3]" },
      { name: "min_mint_amount", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "calc_token_amount",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "amounts", type: "uint256[3]" },
      { name: "is_deposit", type: "bool" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Deposit 1000 of each stablecoin into 3pool
const amounts: readonly [bigint, bigint, bigint] = [
  1000_000000000000000000n, // 1000 DAI  (18 decimals)
  1000_000000n,             // 1000 USDC (6 decimals)
  1000_000000n,             // 1000 USDT (6 decimals)
];

// Estimate LP tokens received
const expectedLp = await publicClient.readContract({
  address: THREE_POOL,
  abi: addLiquidityAbi,
  functionName: "calc_token_amount",
  args: [amounts, true],
});

// 0.5% slippage on LP token mint
const minMintAmount = (expectedLp * 995n) / 1000n;

// Approve all three tokens to the pool
// (omitted for brevity — same pattern as swap approval)

const { request } = await publicClient.simulateContract({
  address: THREE_POOL,
  abi: addLiquidityAbi,
  functionName: "add_liquidity",
  args: [amounts, minMintAmount],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Add liquidity reverted");

Add Liquidity (Single-Sided)

Deposit only one token. The pool rebalances internally, charging a small imbalance fee.

// Deposit 5000 USDC only into 3pool
const singleSidedAmounts: readonly [bigint, bigint, bigint] = [
  0n,           // 0 DAI
  5000_000000n, // 5000 USDC
  0n,           // 0 USDT
];

const expectedLp = await publicClient.readContract({
  address: THREE_POOL,
  abi: addLiquidityAbi,
  functionName: "calc_token_amount",
  args: [singleSidedAmounts, true],
});

// Wider slippage for single-sided (imbalance fee applies)
const minMintAmount = (expectedLp * 990n) / 1000n;

const { request } = await publicClient.simulateContract({
  address: THREE_POOL,
  abi: addLiquidityAbi,
  functionName: "add_liquidity",
  args: [singleSidedAmounts, minMintAmount],
  account: account.address,
});

Remove Liquidity (Proportional)

Withdraw all tokens proportionally — no slippage from imbalance.

const removeLiquidityAbi = [
  {
    name: "remove_liquidity",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "_amount", type: "uint256" },
      { name: "min_amounts", type: "uint256[3]" },
    ],
    outputs: [{ name: "", type: "uint256[3]" }],
  },
] as const;

const lpAmount = 3000_000000000000000000n; // 3000 LP tokens

const { request } = await publicClient.simulateContract({
  address: THREE_POOL,
  abi: removeLiquidityAbi,
  functionName: "remove_liquidity",
  args: [lpAmount, [0n, 0n, 0n]], // SET MIN AMOUNTS IN PRODUCTION
  account: account.address,
});

Remove Liquidity (Single Coin)

Withdraw everything as a single token. Higher slippage for large amounts or imbalanced pools.

const removeOneCoinAbi = [
  {
    name: "remove_liquidity_one_coin",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "_token_amount", type: "uint256" },
      { name: "i", type: "int128" },
      { name: "_min_amount", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "calc_withdraw_one_coin",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "_token_amount", type: "uint256" },
      { name: "i", type: "int128" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

const lpToWithdraw = 1000_000000000000000000n; // 1000 LP tokens

// Estimate how much USDC we get
const expectedUsdc = await publicClient.readContract({
  address: THREE_POOL,
  abi: removeOneCoinAbi,
  functionName: "calc_withdraw_one_coin",
  args: [lpToWithdraw, 1n], // index 1 = USDC
});

const minUsdc = (expectedUsdc * 995n) / 1000n;

const { request } = await publicClient.simulateContract({
  address: THREE_POOL,
  abi: removeOneCoinAbi,
  functionName: "remove_liquidity_one_coin",
  args: [lpToWithdraw, 1n, minUsdc],
  account: account.address,
});

Remove Liquidity (Imbalanced)

Withdraw specific amounts of each token.

const removeImbalanceAbi = [
  {
    name: "remove_liquidity_imbalance",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "amounts", type: "uint256[3]" },
      { name: "max_burn_amount", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Withdraw exactly 500 DAI and 500 USDC, no USDT
const withdrawAmounts: readonly [bigint, bigint, bigint] = [
  500_000000000000000000n, // 500 DAI
  500_000000n,             // 500 USDC
  0n,                      // 0 USDT
];

// Estimate LP tokens burned
const estimatedBurn = await publicClient.readContract({
  address: THREE_POOL,
  abi: addLiquidityAbi,
  functionName: "calc_token_amount",
  args: [withdrawAmounts, false], // false = withdrawal
});

// Allow 1% more LP burn than estimated
const maxBurnAmount = (estimatedBurn * 1010n) / 1000n;

const { request } = await publicClient.simulateContract({
  address: THREE_POOL,
  abi: removeImbalanceAbi,
  functionName: "remove_liquidity_imbalance",
  args: [withdrawAmounts, maxBurnAmount],
  account: account.address,
});

crvUSD (LLAMMA)

crvUSD is Curve's stablecoin. Loans are backed by collateral deposited into LLAMMA (Lending-Liquidating AMM Algorithm). Instead of instant liquidation at a threshold, LLAMMA gradually converts collateral to crvUSD as the collateral price drops through user-defined bands. If the price recovers, it converts back.

Create a crvUSD Loan

// crvUSD Controller for WETH collateral
const CRVUSD_WETH_CONTROLLER = "0xA920De414eA4Ab66b97dA1bFE9e6EcA7d4219635" as const;

const controllerAbi = [
  {
    name: "create_loan",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "collateral", type: "uint256" },
      { name: "debt", type: "uint256" },
      { name: "N", type: "uint256" },
    ],
    outputs: [],
  },
  {
    name: "max_borrowable",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "collateral", type: "uint256" },
      { name: "N", type: "uint256" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "health",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "user", type: "address" },
    ],
    outputs: [{ name: "", type: "int256" }],
  },
  {
    name: "user_state",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "user", type: "address" },
    ],
    outputs: [
      { name: "collateral", type: "uint256" },
      { name: "stablecoin", type: "uint256" },
      { name: "debt", type: "uint256" },
      { name: "N", type: "uint256" },
    ],
  },
] as const;

const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" as const;
const collateralAmount = 10_000000000000000000n; // 10 WETH

// N = number of bands (4-50). More bands = wider liquidation range = safer but lower LTV
const numBands = 10n;

// Check max borrowable amount
const maxDebt = await publicClient.readContract({
  address: CRVUSD_WETH_CONTROLLER,
  abi: controllerAbi,
  functionName: "max_borrowable",
  args: [collateralAmount, numBands],
});

// Borrow 80% of max for safety margin
const debtAmount = (maxDebt * 80n) / 100n;

// Approve WETH to controller
const { request: approveReq } = await publicClient.simulateContract({
  address: WETH,
  abi: erc20Abi,
  functionName: "approve",
  args: [CRVUSD_WETH_CONTROLLER, collateralAmount],
  account: account.address,
});
await walletClient.writeContract(approveReq);

// Create loan
const { request } = await publicClient.simulateContract({
  address: CRVUSD_WETH_CONTROLLER,
  abi: controllerAbi,
  functionName: "create_loan",
  args: [collateralAmount, debtAmount, numBands],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Loan creation reverted");

Monitor Loan Health

// Health > 0 means position is safe
// Health approaching 0 means bands are being converted (soft liquidation)
// Health < 0 means position can be hard-liquidated
const health = await publicClient.readContract({
  address: CRVUSD_WETH_CONTROLLER,
  abi: controllerAbi,
  functionName: "health",
  args: [account.address],
});

// Health is returned in 1e18 precision
// health = 100e18 means 100% above liquidation
const healthPercent = Number(health) / 1e18;

if (healthPercent < 10) {
  console.warn(`Low health: ${healthPercent.toFixed(2)}% — consider repaying or adding collateral`);
}

// Read full user state
const [collateral, stablecoin, debt, bands] = await publicClient.readContract({
  address: CRVUSD_WETH_CONTROLLER,
  abi: controllerAbi,
  functionName: "user_state",
  args: [account.address],
});

Repay crvUSD Loan

const repayAbi = [
  {
    name: "repay",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "_d_debt", type: "uint256" },
    ],
    outputs: [],
  },
] as const;

const CRVUSD = "0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E" as const;

const repayAmount = 5000_000000000000000000n; // repay 5000 crvUSD

// Approve crvUSD to controller
const { request: approveReq } = await publicClient.simulateContract({
  address: CRVUSD,
  abi: erc20Abi,
  functionName: "approve",
  args: [CRVUSD_WETH_CONTROLLER, repayAmount],
  account: account.address,
});
await walletClient.writeContract(approveReq);

const { request } = await publicClient.simulateContract({
  address: CRVUSD_WETH_CONTROLLER,
  abi: repayAbi,
  functionName: "repay",
  args: [repayAmount],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Repay reverted");

Gauge System

Curve directs CRV emissions to liquidity providers via gauges. Deposit your LP tokens into a gauge to earn CRV rewards. Boost your rewards up to 2.5x by holding veCRV.

Deposit LP Tokens into Gauge

// 3pool gauge
const THREE_POOL_GAUGE = "0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A" as const;
const THREE_POOL_LP = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490" as const;

const gaugeAbi = [
  {
    name: "deposit",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [{ name: "_value", type: "uint256" }],
    outputs: [],
  },
  {
    name: "withdraw",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [{ name: "_value", type: "uint256" }],
    outputs: [],
  },
  {
    name: "claimable_tokens",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [{ name: "addr", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

const lpAmount = 1000_000000000000000000n; // 1000 LP tokens

// Approve gauge to spend LP tokens
const { request: approveReq } = await publicClient.simulateContract({
  address: THREE_POOL_LP,
  abi: erc20Abi,
  functionName: "approve",
  args: [THREE_POOL_GAUGE, lpAmount],
  account: account.address,
});
await walletClient.writeContract(approveReq);

// Deposit into gauge
const { request } = await publicClient.simulateContract({
  address: THREE_POOL_GAUGE,
  abi: gaugeAbi,
  functionName: "deposit",
  args: [lpAmount],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Gauge deposit reverted");

Claim CRV Rewards

const MINTER = "0xd061D61a4d941c39E5453435B6345Dc261C2fcE0" as const;

const minterAbi = [
  {
    name: "mint",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [{ name: "gauge_addr", type: "address" }],
    outputs: [],
  },
] as const;

// Check claimable amount
const claimable = await publicClient.simulateContract({
  address: THREE_POOL_GAUGE,
  abi: gaugeAbi,
  functionName: "claimable_tokens",
  args: [account.address],
});

// Mint (claim) CRV rewards
const { request } = await publicClient.simulateContract({
  address: MINTER,
  abi: minterAbi,
  functionName: "mint",
  args: [THREE_POOL_GAUGE],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("CRV claim reverted");

Gauge Voting

Lock CRV for veCRV

Lock CRV tokens to receive vote-escrowed CRV (veCRV). Longer lock = more voting power. Lock duration: 1 week to 4 years. Voting power decays linearly toward the unlock date.

const CRV = "0xD533a949740bb3306d119CC777fa900bA034cd52" as const;
const VECRV = "0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2" as const;

const veCrvAbi = [
  {
    name: "create_lock",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "_value", type: "uint256" },
      { name: "_unlock_time", type: "uint256" },
    ],
    outputs: [],
  },
  {
    name: "increase_amount",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [{ name: "_value", type: "uint256" }],
    outputs: [],
  },
  {
    name: "increase_unlock_time",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [{ name: "_unlock_time", type: "uint256" }],
    outputs: [],
  },
  {
    name: "withdraw",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [],
    outputs: [],
  },
] as const;

const lockAmount = 10000_000000000000000000n; // 10,000 CRV

// Lock for 4 years (max voting power)
// unlock_time must be rounded down to the nearest week (Thursday 00:00 UTC)
const WEEK = 7n * 24n * 60n * 60n;
const FOUR_YEARS = 4n * 365n * 24n * 60n * 60n;
const now = BigInt(Math.floor(Date.now() / 1000));
const unlockTime = ((now + FOUR_YEARS) / WEEK) * WEEK;

// Approve CRV to veCRV
const { request: approveReq } = await publicClient.simulateContract({
  address: CRV,
  abi: erc20Abi,
  functionName: "approve",
  args: [VECRV, lockAmount],
  account: account.address,
});
await walletClient.writeContract(approveReq);

// Create lock
const { request } = await publicClient.simulateContract({
  address: VECRV,
  abi: veCrvAbi,
  functionName: "create_lock",
  args: [lockAmount, unlockTime],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("veCRV lock reverted");

Vote on Gauge Weights

Direct CRV emissions to specific gauges. Votes persist until changed. Each veCRV holder gets 10,000 vote points (100%) to allocate across gauges.

const GAUGE_CONTROLLER = "0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB" as const;

const gaugeControllerAbi = [
  {
    name: "vote_for_gauge_weights",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "_gauge_addr", type: "address" },
      { name: "_user_weight", type: "uint256" },
    ],
    outputs: [],
  },
  {
    name: "gauge_relative_weight",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "addr", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "vote_user_power",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "user", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Allocate 50% of voting power to 3pool gauge
// Weight is in basis points: 5000 = 50%
const { request } = await publicClient.simulateContract({
  address: GAUGE_CONTROLLER,
  abi: gaugeControllerAbi,
  functionName: "vote_for_gauge_weights",
  args: [THREE_POOL_GAUGE, 5000n],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Gauge vote reverted");

Check Voting Power Usage

// Returns total weight used out of 10000 (100%)
const usedPower = await publicClient.readContract({
  address: GAUGE_CONTROLLER,
  abi: gaugeControllerAbi,
  functionName: "vote_user_power",
  args: [account.address],
});

const remainingBps = 10000n - usedPower;

Pool Discovery

MetaRegistry

The MetaRegistry aggregates all pool registries (main, factory, crypto factory) into a single interface.

const META_REGISTRY = "0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC" as const;

const metaRegistryAbi = [
  {
    name: "find_pool_for_coins",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "_from", type: "address" },
      { name: "_to", type: "address" },
    ],
    outputs: [{ name: "", type: "address" }],
  },
  {
    name: "find_pools_for_coins",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "_from", type: "address" },
      { name: "_to", type: "address" },
    ],
    outputs: [{ name: "", type: "address[]" }],
  },
  {
    name: "get_coins",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "_pool", type: "address" }],
    outputs: [{ name: "", type: "address[8]" }],
  },
  {
    name: "get_balances",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "_pool", type: "address" }],
    outputs: [{ name: "", type: "uint256[8]" }],
  },
] as const;

// Find the best pool for USDC -> USDT
const pool = await publicClient.readContract({
  address: META_REGISTRY,
  abi: metaRegistryAbi,
  functionName: "find_pool_for_coins",
  args: [USDC, USDT],
});

// Find ALL pools for a pair
const pools = await publicClient.readContract({
  address: META_REGISTRY,
  abi: metaRegistryAbi,
  functionName: "find_pools_for_coins",
  args: [USDC, USDT],
});

Reading Pool State

Virtual Price

Virtual price represents the LP token value in terms of the underlying asset. It only increases over time from trading fees.

const poolStateAbi = [
  {
    name: "get_virtual_price",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "balances",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "i", type: "uint256" }],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "A",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "fee",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Virtual price is 1e18 precision
const virtualPrice = await publicClient.readContract({
  address: THREE_POOL,
  abi: poolStateAbi,
  functionName: "get_virtual_price",
});

// LP token value in USD (assuming underlying = $1)
const lpValueUsd = Number(virtualPrice) / 1e18;

// Pool balances per coin index
const [daiBalance, usdcBalance, usdtBalance] = await Promise.all([
  publicClient.readContract({ address: THREE_POOL, abi: poolStateAbi, functionName: "balances", args: [0n] }),
  publicClient.readContract({ address: THREE_POOL, abi: poolStateAbi, functionName: "balances", args: [1n] }),
  publicClient.readContract({ address: THREE_POOL, abi: poolStateAbi, functionName: "balances", args: [2n] }),
]);

// Amplification parameter
const amplification = await publicClient.readContract({
  address: THREE_POOL,
  abi: poolStateAbi,
  functionName: "A",
});

// Fee in 1e10 precision (4000000 = 0.04%)
const poolFee = await publicClient.readContract({
  address: THREE_POOL,
  abi: poolStateAbi,
  functionName: "fee",
});
const feePercent = Number(poolFee) / 1e10 * 100;

Contract Addresses

Last verified: February 2026

See resources/contract-addresses.md for the full address table.

ContractEthereum
3pool0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7
stETH/ETH0xDC24316b9AE028F1497c275EB9192a3Ea0f67022
Tricrypto20xD51a44d3FaE010294C616388b506AcdA1bfAAE46
CRV Token0xD533a949740bb3306d119CC777fa900bA034cd52
veCRV0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2
Curve Router0xF0d4c12A5768D806021F80a262B4d39d26C58b8D
MetaRegistry0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC
crvUSD0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E

Error Handling

ErrorCauseFix
Exchange resulted in fewer coins than expectedOutput below min_dyIncrease slippage tolerance or re-quote
Exceeds allowancePool not approved to spend tokenCall approve() with sufficient amount
Insufficient fundsBalance below swap amountCheck balanceOf before calling exchange
Empty revert (Vyper)Wrong function signature or invalid indexVerify ABI matches pool type, check coin indices
dev: exceeds allowanceVyper dev error for allowance checkApprove token to the correct pool address
Lock expiredTrying to increase amount on expired veCRV lockWithdraw first, then create new lock
Withdraw old tokens firstCreating veCRV lock when one already existsCall withdraw() on expired lock first

Security

Slippage Protection

Never set min_dy to 0 in production. Always quote with get_dy() first.

const expectedOut = await publicClient.readContract({
  address: poolAddress,
  abi: threePoolAbi,
  functionName: "get_dy",
  args: [i, j, amountIn],
});

// For stableswap: 10-50 bps is reasonable
const minDy = (expectedOut * 9990n) / 10000n; // 10 bps

// For cryptoswap/volatile: 50-200 bps
const minDyCrypto = (expectedOut * 9950n) / 10000n; // 50 bps

USDT Approval Reset

USDT requires setting allowance to 0 before setting a new non-zero value.

async function approveUsdt(spender: Address, amount: bigint): Promise<void> {
  const currentAllowance = await publicClient.readContract({
    address: USDT,
    abi: erc20Abi,
    functionName: "allowance",
    args: [account.address, spender],
  });

  if (currentAllowance > 0n && currentAllowance < amount) {
    const { request: resetReq } = await publicClient.simulateContract({
      address: USDT,
      abi: erc20Abi,
      functionName: "approve",
      args: [spender, 0n],
      account: account.address,
    });
    const resetHash = await walletClient.writeContract(resetReq);
    await publicClient.waitForTransactionReceipt({ hash: resetHash });
  }

  const { request } = await publicClient.simulateContract({
    address: USDT,
    abi: erc20Abi,
    functionName: "approve",
    args: [spender, amount],
    account: account.address,
  });
  const hash = await walletClient.writeContract(request);
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
  if (receipt.status !== "success") throw new Error("USDT approval failed");
}

Front-Running Mitigation

  • Use tight min_dy on every swap (quote + slippage)
  • Use Flashbots Protect RPC for mainnet transactions
  • Large liquidity operations should use proportional add/remove to minimize extractable value
  • For large single-sided deposits, split into multiple smaller transactions

References

farcaster

View full →

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/farcaster/SKILL.md

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 accountAssociation domain MUST exactly match the FQDN where /.well-known/farcaster.json is 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-Signature header 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-sdk and @farcaster/miniapp-sdk are converging. Both packages exist but frame-sdk is 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.

PropertyDetail
ConsensusMalachite BFT (Tendermint-derived)
Throughput10,000+ messages per second
ShardingAccount-level -- each FID's messages are ordered independently
FinalitySub-second for message acceptance
Data modelAppend-only log of signed messages per FID
Validator setOperated 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

ContractAddressPurpose
IdRegistry0x00000000Fc6c5F01Fc30151999387Bb99A9f489bMaps FIDs to custody addresses
KeyRegistry0x00000000Fc1237824fb747aBDE0FF18990E59b7eMaps FIDs to Ed25519 app keys (signers)
StorageRegistry0x00000000FcCe7f938e7aE6D3c335bD6a1a7c593DManages storage units per FID
IdGateway0x00000000Fc25870C6eD6b6c7E41Fb078b7656f69Permissioned FID registration entry point
KeyGateway0x00000000fC56947c7E7183f8Ca4B62398CaaDF0BPermissioned key addition entry point
Bundler0x00000000FC04c910A0b5feA33b03E0447ad0B0aABatches 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.

ConceptDescription
FIDThe user's numeric identity, immutable once assigned
Custody addressThe Ethereum address that owns the FID -- can transfer ownership
App key (signer)Ed25519 key pair registered in KeyRegistry -- signs messages
Recovery addressCan 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
ParameterDescription
textURL-encoded cast text
embeds[]Up to 2 embed URLs
channelKeyChannel 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

PlanMonthly CreditsPriceWebhooksRate Limit
Free100K$015 req/s
Starter1M$49/mo520 req/s
Growth10M$249/mo2550 req/s
Scale60M$899/mo100200 req/s
EnterpriseCustomCustomUnlimitedCustom

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.

ProviderEndpointAuth
Neynar Hub APIhub-api.neynar.comAPI key in x-api-key header
Self-hosted Hublocalhost:2283None (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

References

AI Skill Finder

Ask me what skills you need

What are you building?

Tell me what you're working on and I'll find the best agent skills for you.