Comparing chainlink with farcaster

chainlink

View full →

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/chainlink/SKILL.md

Chainlink

Chainlink provides decentralized oracle infrastructure: price feeds for DeFi pricing, VRF for provably fair randomness, Automation for scheduled/conditional on-chain execution, and CCIP for cross-chain messaging and token transfers.

What You Probably Got Wrong

  • latestRoundData() returns int256, not uint256 — Price can be negative (e.g., oil futures in 2020). Always check answer > 0 before casting.
  • Decimals vary per feed — ETH/USD has 8 decimals, ETH/BTC has 18 decimals, USDC/USD has 8. Always call decimals() or hardcode per known feed. Never assume 8.
  • VRF v2 is deprecated — use VRF v2.5 — VRF v2.5 supports both LINK and native payment, uses requestRandomWords() with a struct parameter, and has a different coordinator interface. Most LLM training data references VRF v2.
  • Staleness is not optional — A price feed can return a stale answer if the oracle network stops updating. You must check updatedAt against a heartbeat threshold. Feeds without staleness checks have caused protocol-draining exploits.
  • roundId can be zero on L2s — On Arbitrum/Optimism sequencer feeds, round semantics differ. Do not rely on roundId for ordering on L2 feeds.
  • CCIP is not Chainlink VRF — They are separate products. CCIP handles cross-chain messaging; VRF handles randomness. Different contracts, different billing.
  • Automation renamed from Keepers — The product is now called Chainlink Automation, not Keepers. The interface names changed: KeeperCompatibleInterface is now AutomationCompatibleInterface.

Price Feeds

AggregatorV3Interface

The core interface for reading Chainlink price data on-chain.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface internal immutable priceFeed;

    // ETH/USD heartbeat: 3600s on mainnet, 86400s on Arbitrum
    uint256 private constant STALENESS_THRESHOLD = 3600;

    constructor(address feedAddress) {
        priceFeed = AggregatorV3Interface(feedAddress);
    }

    function getLatestPrice() public view returns (int256 price, uint8 feedDecimals) {
        (
            uint80 roundId,
            int256 answer,
            /* uint256 startedAt */,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();

        if (answer <= 0) revert InvalidPrice();
        if (updatedAt == 0) revert RoundNotComplete();
        if (block.timestamp - updatedAt > STALENESS_THRESHOLD) revert StalePrice();
        if (answeredInRound < roundId) revert StaleRound();

        return (answer, priceFeed.decimals());
    }

    /// @notice Normalize a feed answer to 18 decimals
    function normalizeToWad(int256 answer, uint8 feedDecimals) public pure returns (uint256) {
        if (answer <= 0) revert InvalidPrice();
        if (feedDecimals <= 18) {
            return uint256(answer) * 10 ** (18 - feedDecimals);
        }
        return uint256(answer) / 10 ** (feedDecimals - 18);
    }

    error InvalidPrice();
    error RoundNotComplete();
    error StalePrice();
    error StaleRound();
}

Reading Price Feeds with TypeScript (viem)

import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";

const AGGREGATOR_V3_ABI = parseAbi([
  "function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)",
  "function decimals() external view returns (uint8)",
  "function description() external view returns (string)",
]);

// ETH/USD on Ethereum mainnet
const ETH_USD_FEED = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" as const;
const STALENESS_THRESHOLD = 3600n;

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

async function getPrice(feedAddress: `0x${string}`) {
  const [roundData, feedDecimals] = await Promise.all([
    client.readContract({
      address: feedAddress,
      abi: AGGREGATOR_V3_ABI,
      functionName: "latestRoundData",
    }),
    client.readContract({
      address: feedAddress,
      abi: AGGREGATOR_V3_ABI,
      functionName: "decimals",
    }),
  ]);

  const [roundId, answer, , updatedAt, answeredInRound] = roundData;

  if (answer <= 0n) throw new Error("Invalid price: non-positive");
  if (updatedAt === 0n) throw new Error("Round not complete");

  const now = BigInt(Math.floor(Date.now() / 1000));
  if (now - updatedAt > STALENESS_THRESHOLD) {
    throw new Error(`Stale price: ${now - updatedAt}s old`);
  }
  if (answeredInRound < roundId) {
    throw new Error("Stale round: answeredInRound < roundId");
  }

  // Normalize to 18 decimals
  const normalized =
    feedDecimals <= 18
      ? answer * 10n ** (18n - BigInt(feedDecimals))
      : answer / 10n ** (BigInt(feedDecimals) - 18n);

  return {
    raw: answer,
    decimals: feedDecimals,
    normalized,
    updatedAt,
  };
}

// Usage
const ethPrice = await getPrice(ETH_USD_FEED);
console.log(`ETH/USD: $${Number(ethPrice.raw) / 10 ** ethPrice.decimals}`);

L2 Sequencer Uptime Feed

On L2s, check the sequencer uptime feed before trusting price data. If the sequencer was recently restarted, prices may be stale while oracles catch up.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract L2PriceConsumer {
    AggregatorV3Interface internal immutable sequencerUptimeFeed;
    AggregatorV3Interface internal immutable priceFeed;

    // Grace period after sequencer comes back online
    uint256 private constant GRACE_PERIOD = 3600;

    constructor(address _sequencerFeed, address _priceFeed) {
        sequencerUptimeFeed = AggregatorV3Interface(_sequencerFeed);
        priceFeed = AggregatorV3Interface(_priceFeed);
    }

    function getPrice() external view returns (int256) {
        (, int256 sequencerAnswer, , uint256 sequencerUpdatedAt, ) =
            sequencerUptimeFeed.latestRoundData();

        // answer == 0 means sequencer is up, answer == 1 means down
        if (sequencerAnswer != 0) revert SequencerDown();
        if (block.timestamp - sequencerUpdatedAt < GRACE_PERIOD) revert GracePeriodNotOver();

        (, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
        if (price <= 0) revert InvalidPrice();
        if (block.timestamp - updatedAt > 86400) revert StalePrice();

        return price;
    }

    error SequencerDown();
    error GracePeriodNotOver();
    error InvalidPrice();
    error StalePrice();
}

VRF v2.5

Chainlink VRF v2.5 provides provably fair, verifiable randomness. It uses subscription-based billing and supports payment in LINK or native token.

Requesting Randomness

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";

contract RandomConsumer is VRFConsumerBaseV2Plus {
    uint256 public immutable subscriptionId;
    bytes32 public immutable keyHash;

    // 200k gas covers most callbacks; increase for complex logic
    uint32 private constant CALLBACK_GAS_LIMIT = 200_000;
    uint16 private constant REQUEST_CONFIRMATIONS = 3;
    uint32 private constant NUM_WORDS = 1;

    mapping(uint256 => address) public requestToSender;
    mapping(address => uint256) public results;

    event RandomnessRequested(uint256 indexed requestId, address indexed requester);
    event RandomnessFulfilled(uint256 indexed requestId, uint256 randomWord);

    constructor(
        uint256 _subscriptionId,
        address _vrfCoordinator,
        bytes32 _keyHash
    ) VRFConsumerBaseV2Plus(_vrfCoordinator) {
        subscriptionId = _subscriptionId;
        keyHash = _keyHash;
    }

    function requestRandom() external returns (uint256 requestId) {
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: keyHash,
                subId: subscriptionId,
                requestConfirmations: REQUEST_CONFIRMATIONS,
                callbackGasLimit: CALLBACK_GAS_LIMIT,
                numWords: NUM_WORDS,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    // false = pay with LINK, true = pay with native
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
                )
            })
        );

        requestToSender[requestId] = msg.sender;
        emit RandomnessRequested(requestId, msg.sender);
    }

    function fulfillRandomWords(
        uint256 requestId,
        uint256[] calldata randomWords
    ) internal override {
        address requester = requestToSender[requestId];
        results[requester] = randomWords[0];
        emit RandomnessFulfilled(requestId, randomWords[0]);
    }
}

VRF Subscription Management (TypeScript)

import { createWalletClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const VRF_COORDINATOR_ABI = parseAbi([
  "function createSubscription() external returns (uint256 subId)",
  "function addConsumer(uint256 subId, address consumer) external",
  "function removeConsumer(uint256 subId, address consumer) external",
  "function getSubscription(uint256 subId) external view returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address subOwner, address[] consumers)",
  "function fundSubscriptionWithNative(uint256 subId) external payable",
]);

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

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

// Ethereum mainnet VRF Coordinator v2.5
const VRF_COORDINATOR = "0xD7f86b4b8Cae7D942340FF628F82735b7a20893a" as const;

async function createSubscription() {
  const hash = await walletClient.writeContract({
    address: VRF_COORDINATOR,
    abi: VRF_COORDINATOR_ABI,
    functionName: "createSubscription",
  });
  console.log("Subscription created, tx:", hash);
  return hash;
}

async function addConsumer(subId: bigint, consumerAddress: `0x${string}`) {
  const hash = await walletClient.writeContract({
    address: VRF_COORDINATOR,
    abi: VRF_COORDINATOR_ABI,
    functionName: "addConsumer",
    args: [subId, consumerAddress],
  });
  console.log("Consumer added, tx:", hash);
  return hash;
}

Automation (Keepers)

Chainlink Automation executes on-chain functions when conditions are met. Your contract implements checkUpkeep (off-chain simulation) and performUpkeep (on-chain execution).

AutomationCompatible Contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol";

contract AutomatedCounter is AutomationCompatibleInterface {
    uint256 public counter;
    uint256 public lastTimestamp;
    uint256 public immutable interval;

    event CounterIncremented(uint256 indexed newValue, uint256 timestamp);

    constructor(uint256 _interval) {
        interval = _interval;
        lastTimestamp = block.timestamp;
    }

    /// @notice Called off-chain by Automation nodes to check if upkeep is needed
    /// @dev Must NOT modify state. Gas cost does not matter (simulated off-chain).
    function checkUpkeep(bytes calldata)
        external
        view
        override
        returns (bool upkeepNeeded, bytes memory performData)
    {
        upkeepNeeded = (block.timestamp - lastTimestamp) >= interval;
        performData = abi.encode(counter);
    }

    /// @notice Called on-chain when checkUpkeep returns true
    /// @dev Re-validate the condition — checkUpkeep result may be stale
    function performUpkeep(bytes calldata) external override {
        if ((block.timestamp - lastTimestamp) < interval) revert UpkeepNotNeeded();

        lastTimestamp = block.timestamp;
        counter += 1;
        emit CounterIncremented(counter, block.timestamp);
    }

    error UpkeepNotNeeded();
}

Log-Triggered Automation

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ILogAutomation, Log} from "@chainlink/contracts/src/v0.8/automation/interfaces/ILogAutomation.sol";

contract LogTriggeredUpkeep is ILogAutomation {
    event ActionPerformed(address indexed sender, uint256 amount);

    /// @notice Called when a matching log event is detected
    function checkLog(Log calldata log, bytes memory)
        external
        pure
        returns (bool upkeepNeeded, bytes memory performData)
    {
        upkeepNeeded = true;
        performData = log.data;
    }

    function performUpkeep(bytes calldata performData) external {
        (address sender, uint256 amount) = abi.decode(performData, (address, uint256));
        emit ActionPerformed(sender, amount);
    }
}

CCIP (Cross-Chain Interoperability Protocol)

CCIP enables sending arbitrary messages and tokens between supported chains.

Sending a Cross-Chain Message

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IRouterClient} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouterClient.sol";
import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract CCIPSender {
    IRouterClient public immutable router;
    IERC20 public immutable linkToken;

    event MessageSent(bytes32 indexed messageId, uint64 indexed destinationChain);

    constructor(address _router, address _link) {
        router = IRouterClient(_router);
        linkToken = IERC20(_link);
    }

    function sendMessage(
        uint64 destinationChainSelector,
        address receiver,
        bytes calldata data
    ) external returns (bytes32 messageId) {
        Client.EVM2AnyMessage memory message = Client.EVM2AnyMessage({
            receiver: abi.encode(receiver),
            data: data,
            tokenAmounts: new Client.EVMTokenAmount[](0),
            extraArgs: Client._argsToBytes(
                Client.EVMExtraArgsV2({gasLimit: 200_000, allowOutOfOrderExecution: true})
            ),
            feeToken: address(linkToken)
        });

        uint256 fees = router.getFee(destinationChainSelector, message);
        linkToken.approve(address(router), fees);

        messageId = router.ccipSend(destinationChainSelector, message);
        emit MessageSent(messageId, destinationChainSelector);
    }
}

Receiving a Cross-Chain Message

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {CCIPReceiver} from "@chainlink/contracts-ccip/src/v0.8/ccip/applications/CCIPReceiver.sol";
import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol";

contract CCIPReceiverExample is CCIPReceiver {
    // Allowlist source chains and senders to prevent unauthorized messages
    mapping(uint64 => mapping(address => bool)) public allowlistedSenders;
    address public owner;

    event MessageReceived(
        bytes32 indexed messageId,
        uint64 indexed sourceChainSelector,
        address sender,
        bytes data
    );

    constructor(address _router) CCIPReceiver(_router) {
        owner = msg.sender;
    }

    function allowlistSender(
        uint64 chainSelector,
        address sender,
        bool allowed
    ) external {
        if (msg.sender != owner) revert Unauthorized();
        allowlistedSenders[chainSelector][sender] = allowed;
    }

    function _ccipReceive(Client.Any2EVMMessage memory message) internal override {
        address sender = abi.decode(message.sender, (address));
        if (!allowlistedSenders[message.sourceChainSelector][sender]) {
            revert SenderNotAllowlisted();
        }

        emit MessageReceived(
            message.messageId,
            message.sourceChainSelector,
            sender,
            message.data
        );
    }

    error Unauthorized();
    error SenderNotAllowlisted();
}

Contract Addresses

Last verified: 2025-05-01

Price Feeds

PairEthereum MainnetArbitrum OneBase
ETH/USD0x5f4eC3Df9cbd43714FE2740f5E3616155c5b84190x639Fe6ab55C921f74e7fac1ee960C0B6293ba6120x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70
BTC/USD0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c0x6ce185860a4963106506C203335A2910413708e90x64c911996D3c6aC71f9b455B1E8E7M1BbDC942BAe
USDC/USD0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f60x50834F3163758fcC1Df9973b6e91f0F0F0434aD30x7e860098F58bBFC8648a4311b374B1D669a2bc6B
LINK/USD0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c0x86E53CF1B870786351Da77A57575e79CB55812CB0x17CAb8FE31cA45e4684E33E3D258F20E88B8fD8B

Sequencer Uptime Feeds

ChainAddress
Arbitrum0xFdB631F5EE196F0ed6FAa767959853A9F217697D
Base0xBCF85224fc0756B9Fa45aAb7d2257eC1673570EF
Optimism0x371EAD81c9102C9BF4874A9075FFFf170F2Ee389

VRF v2.5 Coordinators

ChainCoordinator
Ethereum0xD7f86b4b8Cae7D942340FF628F82735b7a20893a
Arbitrum0x3C0Ca683b403E37668AE3DC4FB62F4B29B6f7a3e
Base0xd5D517aBE5cF79B7e95eC98dB0f0277788aFF634

CCIP Routers

ChainRouterChain Selector
Ethereum0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D5009297550715157269
Arbitrum0x141fa059441E0ca23ce184B6A78bafD2A517DdE84949039107694359620
Base0x881e3A65B4d4a04dD529061dd0071cf975F58bCD15971525489660198786

LINK Token

ChainAddress
Ethereum0x514910771AF9Ca656af840dff83E8264EcF986CA
Arbitrum0xf97f4df75117a78c1A5a0DBb814Af92458539FB4
Base0x88Fb150BDc53A65fe94Dea0c9BA0a6dAf8C6e196

Error Handling

Error / SymptomCauseFix
answer <= 0 from price feedFeed returning invalid/negative priceCheck answer > 0 before using; revert or use fallback oracle
block.timestamp - updatedAt > thresholdOracle stopped updating (network congestion, feed deprecation)Implement staleness check with per-feed heartbeat threshold
answeredInRound < roundIdAnswer is from a previous roundReject stale round data
VRF callback revertscallbackGasLimit too low for your fulfillRandomWords logicIncrease callbackGasLimit; test gas usage on fork
VRF request pending indefinitelySubscription underfunded, consumer not added, or wrong keyHashFund subscription, verify consumer is registered, use correct key hash for your chain
Automation performUpkeep not firingcheckUpkeep returns false, upkeep underfunded, or gas price too highDebug checkUpkeep locally; fund upkeep; check min balance requirements
CCIP InsufficientFeeTokenAmountNot enough LINK approved for feesCall router.getFee() first, then approve that amount + buffer
CCIP message not deliveredDestination contract reverts, sender not allowlisted, or chain selector wrongCheck receiver contract, verify allowlist, confirm chain selectors from docs

Security Considerations

Price Feed Safety

  1. Always check staleness — Every latestRoundData() call must validate updatedAt against the feed's heartbeat. ETH/USD on mainnet has a 3600s heartbeat; on Arbitrum it is 86400s. Check Chainlink's feed page for per-feed heartbeats.

  2. Sanity-bound oracle prices — If a feed reports ETH at $0.01 or $1,000,000, something is wrong. Add upper and lower bounds based on reasonable price ranges and revert or pause if breached.

uint256 private constant MIN_ETH_PRICE = 100e8;       // $100
uint256 private constant MAX_ETH_PRICE = 100_000e8;    // $100,000

function getSafePrice(AggregatorV3Interface feed) internal view returns (uint256) {
    (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
    if (answer <= 0) revert InvalidPrice();
    if (block.timestamp - updatedAt > 3600) revert StalePrice();
    if (uint256(answer) < MIN_ETH_PRICE || uint256(answer) > MAX_ETH_PRICE) {
        revert PriceOutOfBounds();
    }
    return uint256(answer);
}
  1. L2 sequencer check — On Arbitrum, Base, and Optimism, always check the sequencer uptime feed. A sequencer outage means oracle updates are delayed; using stale prices during recovery has caused exploits.

  2. Decimal normalization — Never assume 8 decimals. Always call feed.decimals() or use known constants per feed. When combining two feeds (e.g., TOKEN/ETH and ETH/USD), handle decimals carefully to avoid overflow or truncation.

  3. Multi-oracle fallback — For critical DeFi protocols, use Chainlink as primary but have a fallback (e.g., Uniswap TWAP or Pyth) to prevent single oracle dependency from freezing your protocol.

VRF Safety

  • Never use block values (block.timestamp, block.prevrandao) as randomness — they are manipulable by validators.
  • Store the requestId -> user mapping before the callback. The callback is asynchronous and you need to know who requested it.
  • Set callbackGasLimit high enough for your logic but not excessively — you pay for unused gas.

Automation Safety

  • Always re-validate conditions in performUpkeep. The checkUpkeep result may be stale by the time performUpkeep executes on-chain.
  • checkUpkeep runs off-chain in simulation — it cannot modify state. Any state changes will be reverted.

CCIP Safety

  • Always allowlist source chains and sender addresses on your receiver contract. Without this, anyone on any supported chain can send messages to your contract.
  • Handle message failures gracefully. If _ccipReceive reverts, the message can be manually executed later, but your contract should not end up in an inconsistent state from partial execution.

Alternative Oracles

For use cases where Chainlink's push model isn't optimal, consider these alternatives:

Pyth Network (pyth-evm skill) — Pull oracle model where consumers fetch and submit price updates on-demand. Best for: sub-second price freshness (~400ms on Pythnet), confidence intervals (statistical uncertainty bounds), MEV-protected liquidations via Express Relay, and non-EVM chains (Solana, Sui, Aptos). Trade-off: consumers pay gas for price updates (~120-150K gas per feed).

When to use Chainlink vs Pyth:

  • Chainlink: Zero-cost reads (DON sponsors updates), broadest EVM feed coverage (1000+), VRF/CCIP/Automation ecosystem, well-established data quality
  • Pyth: Sub-second freshness, confidence intervals, historical price verification, MEV protection, 50+ EVM chains + non-EVM

See also: redstone skill for another pull oracle alternative.

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.