Comparing aptos with farcaster

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/aptos/SKILL.md

Aptos Move L1 Development

Aptos is a Layer 1 blockchain built on Move, the language originally developed for Meta's Diem project. It achieves high throughput via Block-STM, a parallel execution engine that processes transactions optimistically and re-executes on conflicts. Smart contracts are called modules, and data is stored as resources at account addresses in a global storage model.

What You Probably Got Wrong

AI agents trained on Sui Move or Solidity make critical errors when generating Aptos Move code. Fix these first.

  • Aptos Move uses global storage, NOT Sui's object model — Resources are stored at addresses using move_to, move_from, borrow_global, and borrow_global_mut. There is no object::ObjectID or sui::object::UID. When you want to store data, you move_to<T>(signer, resource) to place it at the signer's address. To read it, you borrow_global<T>(address).

  • Resource accounts are NOT regular accounts — A resource account is a special account with no private key, controlled by its creating module. You create one with account::create_resource_account(origin, seed). The module publishes to the resource account's address. This is how protocols deploy immutable, admin-less contracts.

  • Token V1 is deprecated — use Token V2 (Digital Assets) — The aptos_token module (V1) is legacy. Use aptos_token_objects (V2), which uses the Move Object model. V2 tokens are stored as objects at their own addresses, not in a creator's TokenStore. Collections and tokens are first-class objects.

  • @aptos-labs/ts-sdk replaces the old aptos package — The npm package aptos is deprecated. Use @aptos-labs/ts-sdk. The entry point is new Aptos(new AptosConfig({ network: Network.MAINNET })). Do not import from aptos.

  • Coin standard is NOT ERC-20 — Aptos uses aptos_framework::coin with generics. A coin type is Coin<CoinType> where CoinType is a phantom type parameter defined by the deploying module. There is no approval/allowance pattern — coins are moved directly.

  • signer is not msg.sender — In Aptos Move, the signer is passed as a function parameter. A function must explicitly accept &signer to access the caller's address and perform operations on their account. Use signer::address_of(account) to get the address.

  • View functions are explicit — You must annotate functions with #[view] to make them callable off-chain without a transaction. They cannot modify state. They are called via the /view API endpoint, not through transaction submission.

  • u256 exists but u64 is standard for amounts — Unlike Solidity's uint256 default, Aptos uses u64 for coin amounts and most counters. u256 exists but is rarely used. APT has 8 decimals (not 18). 1 APT = 100,000,000 octas.

Chain Configuration

Mainnet

PropertyValue
Chain ID1
CurrencyAPT (8 decimals)
Block Time~100-300ms (sub-second)
Finality~900ms
Max Gas Unit2,000,000
Gas Unit PriceMin 100 octas
VMMove VM with Block-STM
ConsensusAptosBFT (DiemBFT v4)

RPC Endpoints

URLProviderNotes
https://fullnode.mainnet.aptoslabs.com/v1Aptos LabsDefault REST API
https://mainnet.aptoslabs.com/v1Aptos LabsAlternative
https://aptos-mainnet.nodereal.io/v1NodeRealRate-limited

Block Explorers

ExplorerURL
Aptos Explorerhttps://explorer.aptoslabs.com
Aptscanhttps://aptscan.ai

Testnet

PropertyValue
Chain ID2
RPChttps://fullnode.testnet.aptoslabs.com/v1
Faucethttps://faucet.testnet.aptoslabs.com
Explorerhttps://explorer.aptoslabs.com/?network=testnet

Devnet

PropertyValue
Chain IDvaries (resets frequently)
RPChttps://fullnode.devnet.aptoslabs.com/v1
Faucethttps://faucet.devnet.aptoslabs.com

Quick Start

Install Aptos CLI

# macOS
brew install aptos

# Linux / manual
curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3

# Verify
aptos --version

Create a New Move Project

# Initialize a new Move package
aptos move init --name my_module

# Project structure:
# my_module/
# ├── Move.toml
# └── sources/
#     └── my_module.move

Move.toml Configuration

[package]
name = "my_module"
version = "0.1.0"

[addresses]
my_addr = "_"

[dependencies]
AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework", rev = "mainnet" }
AptosTokenObjects = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-token-objects", rev = "mainnet" }

TypeScript SDK Setup

npm install @aptos-labs/ts-sdk
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({ network: Network.MAINNET });
const aptos = new Aptos(config);

Move Module Development

Module Structure

module my_addr::counter {
    use std::signer;

    struct Counter has key {
        value: u64,
    }

    /// Initialize a counter resource at the signer's address
    public entry fun initialize(account: &signer) {
        let counter = Counter { value: 0 };
        move_to(account, counter);
    }

    /// Increment the counter stored at the signer's address
    public entry fun increment(account: &signer) acquires Counter {
        let addr = signer::address_of(account);
        let counter = borrow_global_mut<Counter>(addr);
        counter.value = counter.value + 1;
    }

    /// Read the counter value at any address
    #[view]
    public fun get_count(addr: address): u64 acquires Counter {
        borrow_global<Counter>(addr).value
    }
}

Key Move Concepts

Global Storage Operations

// Store a resource at signer's address (signer must not already have one)
move_to<T>(signer, resource);

// Remove and return a resource from an address
let resource = move_from<T>(addr);

// Immutable reference to resource at address
let ref = borrow_global<T>(addr);

// Mutable reference to resource at address
let ref_mut = borrow_global_mut<T>(addr);

// Check if a resource exists at address
let exists = exists<T>(addr);

Abilities

// has copy — value can be copied
// has drop — value can be dropped (destroyed implicitly)
// has store — value can be stored inside another struct
// has key — value can be stored as a top-level resource in global storage

struct Coin has store {
    value: u64,
}

struct CoinStore has key {
    coin: Coin,
}

Access Control Pattern

module my_addr::admin {
    use std::signer;

    struct AdminConfig has key {
        admin: address,
    }

    const E_NOT_ADMIN: u64 = 1;
    const E_ALREADY_INITIALIZED: u64 = 2;

    public entry fun initialize(account: &signer) {
        let addr = signer::address_of(account);
        assert!(!exists<AdminConfig>(addr), E_ALREADY_INITIALIZED);
        move_to(account, AdminConfig { admin: addr });
    }

    public entry fun admin_only_action(account: &signer, config_addr: address) acquires AdminConfig {
        let config = borrow_global<AdminConfig>(config_addr);
        assert!(signer::address_of(account) == config.admin, E_NOT_ADMIN);
        // perform privileged action
    }
}

Events

module my_addr::events_example {
    use aptos_framework::event;

    #[event]
    struct TransferEvent has drop, store {
        from: address,
        to: address,
        amount: u64,
    }

    public entry fun transfer(from: &signer, to: address, amount: u64) {
        // ... transfer logic ...
        event::emit(TransferEvent {
            from: signer::address_of(from),
            to,
            amount,
        });
    }
}

Resource Accounts

module my_addr::resource_account_example {
    use std::signer;
    use aptos_framework::account;
    use aptos_framework::resource_account;

    struct ModuleData has key {
        resource_signer_cap: account::SignerCapability,
    }

    /// Called once during module publication to a resource account.
    /// The resource account's signer capability is stored for later use.
    fun init_module(resource_signer: &signer) {
        let resource_signer_cap = resource_account::retrieve_resource_account_cap(
            resource_signer,
            @source_addr
        );
        move_to(resource_signer, ModuleData {
            resource_signer_cap,
        });
    }

    /// Use the stored signer capability to act as the resource account
    public entry fun do_something(caller: &signer) acquires ModuleData {
        let module_data = borrow_global<ModuleData>(@my_addr);
        let resource_signer = account::create_signer_with_capability(
            &module_data.resource_signer_cap
        );
        // resource_signer can now sign transactions on behalf of the resource account
    }
}

Coin Standard

Creating a Custom Coin

module my_addr::my_coin {
    use std::signer;
    use std::string;
    use aptos_framework::coin;

    /// Phantom type marker for the coin — defines the coin type globally
    struct MyCoin {}

    struct CoinCapabilities has key {
        burn_cap: coin::BurnCapability<MyCoin>,
        freeze_cap: coin::FreezeCapability<MyCoin>,
        mint_cap: coin::MintCapability<MyCoin>,
    }

    const E_NOT_ADMIN: u64 = 1;

    public entry fun initialize(account: &signer) {
        let (burn_cap, freeze_cap, mint_cap) = coin::initialize<MyCoin>(
            account,
            string::utf8(b"My Coin"),
            string::utf8(b"MYC"),
            8, // decimals
            true, // monitor_supply
        );
        move_to(account, CoinCapabilities {
            burn_cap,
            freeze_cap,
            mint_cap,
        });
    }

    public entry fun mint(
        account: &signer,
        to: address,
        amount: u64,
    ) acquires CoinCapabilities {
        let addr = signer::address_of(account);
        let caps = borrow_global<CoinCapabilities>(addr);
        let coins = coin::mint(amount, &caps.mint_cap);
        coin::deposit(to, coins);
    }

    public entry fun burn(
        account: &signer,
        amount: u64,
    ) acquires CoinCapabilities {
        let addr = signer::address_of(account);
        let caps = borrow_global<CoinCapabilities>(addr);
        let coins = coin::withdraw<MyCoin>(account, amount);
        coin::burn(coins, &caps.burn_cap);
    }
}

Registering for a Coin

// Before receiving any coin type, an account must register for it
public entry fun register_coin<CoinType>(account: &signer) {
    coin::register<CoinType>(account);
}

Token V2 — Digital Assets

Creating a Collection and Token

module my_addr::nft {
    use std::signer;
    use std::string::{Self, String};
    use std::option;
    use aptos_token_objects::collection;
    use aptos_token_objects::token;

    struct TokenRefs has key {
        burn_ref: token::BurnRef,
        transfer_ref: option::Option<object::TransferRef>,
        mutator_ref: token::MutatorRef,
    }

    public entry fun create_collection(creator: &signer) {
        collection::create_unlimited_collection(
            creator,
            string::utf8(b"Collection description"),
            string::utf8(b"My Collection"),
            option::none(), // no royalty
            string::utf8(b"https://example.com/collection"),
        );
    }

    public entry fun mint_token(creator: &signer) {
        let constructor_ref = token::create_named_token(
            creator,
            string::utf8(b"My Collection"),
            string::utf8(b"Token description"),
            string::utf8(b"Token #1"),
            option::none(), // no royalty
            string::utf8(b"https://example.com/token/1"),
        );

        let token_signer = object::generate_signer(&constructor_ref);
        let burn_ref = token::generate_burn_ref(&constructor_ref);
        let mutator_ref = token::generate_mutator_ref(&constructor_ref);

        move_to(&token_signer, TokenRefs {
            burn_ref,
            transfer_ref: option::none(),
            mutator_ref,
        });
    }
}

TypeScript SDK (@aptos-labs/ts-sdk)

Client Initialization

import {
  Aptos,
  AptosConfig,
  Network,
  Account,
  Ed25519PrivateKey,
  AccountAddress,
} from "@aptos-labs/ts-sdk";

// Mainnet
const aptos = new Aptos(new AptosConfig({ network: Network.MAINNET }));

// Testnet
const aptosTestnet = new Aptos(new AptosConfig({ network: Network.TESTNET }));

// Custom node
const aptosCustom = new Aptos(
  new AptosConfig({
    fullnode: "https://my-node.example.com/v1",
    indexer: "https://my-indexer.example.com/v1/graphql",
  })
);

Account Management

// Generate a new account
const account = Account.generate();
console.log("Address:", account.accountAddress.toString());
console.log("Private key:", account.privateKey.toString());

// From existing private key
const privateKey = new Ed25519PrivateKey("0x...");
const existingAccount = Account.fromPrivateKey({ privateKey });

// Fund on testnet
const aptosTestnet = new Aptos(new AptosConfig({ network: Network.TESTNET }));
await aptosTestnet.fundAccount({
  accountAddress: account.accountAddress,
  amount: 100_000_000, // 1 APT = 100,000,000 octas
});

Transfer APT

async function transferAPT(
  aptos: Aptos,
  sender: Account,
  recipientAddress: string,
  amountOctas: number
): Promise<string> {
  const transaction = await aptos.transaction.build.simple({
    sender: sender.accountAddress,
    data: {
      function: "0x1::aptos_account::transfer",
      functionArguments: [AccountAddress.from(recipientAddress), amountOctas],
    },
  });

  const pendingTx = await aptos.signAndSubmitTransaction({
    signer: sender,
    transaction,
  });

  const committedTx = await aptos.waitForTransaction({
    transactionHash: pendingTx.hash,
  });

  return committedTx.hash;
}

View Functions

async function getBalance(aptos: Aptos, address: string): Promise<bigint> {
  const result = await aptos.view({
    payload: {
      function: "0x1::coin::balance",
      typeArguments: ["0x1::aptos_coin::AptosCoin"],
      functionArguments: [AccountAddress.from(address)],
    },
  });
  return BigInt(result[0] as string);
}

Read Account Resources

async function getCoinStore(aptos: Aptos, address: string) {
  return aptos.getAccountResource({
    accountAddress: AccountAddress.from(address),
    resourceType: "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
  });
}

Multi-Agent Transactions

// Multi-agent: multiple signers for one transaction
async function multiAgentTransfer(
  aptos: Aptos,
  sender: Account,
  secondSigner: Account
) {
  const transaction = await aptos.transaction.build.multiAgent({
    sender: sender.accountAddress,
    secondarySignerAddresses: [secondSigner.accountAddress],
    data: {
      function: "0xmodule::my_module::multi_signer_action",
      functionArguments: [],
    },
  });

  const senderAuth = aptos.transaction.sign({
    signer: sender,
    transaction,
  });

  const secondAuth = aptos.transaction.sign({
    signer: secondSigner,
    transaction,
  });

  const pendingTx = await aptos.transaction.submit.multiAgent({
    transaction,
    senderAuthenticator: senderAuth,
    additionalSignersAuthenticators: [secondAuth],
  });

  return aptos.waitForTransaction({ transactionHash: pendingTx.hash });
}

Gas Estimation

async function estimateGas(aptos: Aptos, sender: Account) {
  const transaction = await aptos.transaction.build.simple({
    sender: sender.accountAddress,
    data: {
      function: "0x1::aptos_account::transfer",
      functionArguments: [
        AccountAddress.from("0xrecipient"),
        100_000_000,
      ],
    },
  });

  // Simulate to get gas estimate
  const simulation = await aptos.transaction.simulate.simple({
    signerPublicKey: sender.publicKey,
    transaction,
  });

  const gasUsed = BigInt(simulation[0].gas_used);
  const gasUnitPrice = BigInt(simulation[0].gas_unit_price);
  const totalCost = gasUsed * gasUnitPrice;

  return { gasUsed, gasUnitPrice, totalCost };
}

Compile and Deploy

Compile Module

# Compile
aptos move compile --named-addresses my_addr=default

# Run tests
aptos move test --named-addresses my_addr=default

# Publish to testnet (requires funded account)
aptos move publish --named-addresses my_addr=default --profile testnet

CLI Account Setup

# Initialize a new profile (generates keypair, funds on devnet/testnet)
aptos init --profile testnet --network testnet

# Initialize with existing private key
aptos init --profile mainnet --private-key 0x... --network mainnet

# Check account balance
aptos account balance --profile testnet

See examples/deploy-module/ for full SDK deployment code.

Testing Move Modules

#[test_only]
module my_addr::counter_tests {
    use std::signer;
    use my_addr::counter;

    #[test(account = @0x1)]
    fun test_initialize(account: &signer) {
        counter::initialize(account);
        let addr = signer::address_of(account);
        assert!(counter::get_count(addr) == 0, 0);
    }

    #[test(account = @0x1)]
    fun test_increment(account: &signer) {
        counter::initialize(account);
        counter::increment(account);
        let addr = signer::address_of(account);
        assert!(counter::get_count(addr) == 1, 0);
    }

    #[test(account = @0x1)]
    #[expected_failure(abort_code = 0x60001, location = aptos_framework::account)]
    fun test_double_initialize(account: &signer) {
        counter::initialize(account);
        counter::initialize(account); // should fail: resource already exists
    }
}

Block-STM Parallel Execution

Aptos uses Block-STM for optimistic parallel execution. Transactions within a block execute concurrently. If two transactions conflict (read/write to the same resource), one is re-executed.

What This Means for Developers

  • Independent transactions run in parallel — Transactions touching different accounts or resources execute simultaneously.
  • Contention on hot resources serializes execution — If your contract uses a single global counter that every transaction increments, Block-STM will detect the conflict and serialize those transactions. Performance degrades to sequential.
  • Design for parallelism — Use per-user resources instead of global state when possible. Example: instead of a global TotalDeposits counter, track deposits per-user and aggregate off-chain.

Anti-Pattern: Global Hot Resource

// BAD: Every deposit transaction conflicts on the same resource
struct GlobalState has key {
    total_deposits: u64,
}

public entry fun deposit(account: &signer, amount: u64) acquires GlobalState {
    let state = borrow_global_mut<GlobalState>(@module_addr);
    state.total_deposits = state.total_deposits + amount;
    // every deposit serializes here
}

Pattern: Per-User State

// GOOD: Each user's deposit is independent — parallel-friendly
struct UserDeposit has key {
    amount: u64,
}

public entry fun deposit(account: &signer, amount: u64) acquires UserDeposit {
    let addr = signer::address_of(account);
    if (exists<UserDeposit>(addr)) {
        let deposit = borrow_global_mut<UserDeposit>(addr);
        deposit.amount = deposit.amount + amount;
    } else {
        move_to(account, UserDeposit { amount });
    };
}

Move Object Model

The Move Object model (used by Token V2) creates objects at deterministic addresses. Objects are distinct from resources stored at user addresses.

module my_addr::object_example {
    use aptos_framework::object::{Self, Object, ConstructorRef};
    use std::signer;

    struct MyObject has key {
        value: u64,
    }

    /// Create a named object at a deterministic address
    public entry fun create(creator: &signer) {
        let constructor_ref = object::create_named_object(
            creator,
            b"my_object_seed",
        );
        let object_signer = object::generate_signer(&constructor_ref);
        move_to(&object_signer, MyObject { value: 42 });
    }

    /// Transfer ownership of an object
    public entry fun transfer_object(
        owner: &signer,
        obj: Object<MyObject>,
        to: address,
    ) {
        object::transfer(owner, obj, to);
    }

    #[view]
    public fun get_value(obj: Object<MyObject>): u64 acquires MyObject {
        let obj_addr = object::object_address(&obj);
        borrow_global<MyObject>(obj_addr).value
    }
}

Common Patterns

Table Storage (Key-Value Map)

use aptos_std::table::{Self, Table};

struct Registry has key {
    entries: Table<address, u64>,
}

public entry fun add_entry(account: &signer, key: address, value: u64) acquires Registry {
    let registry = borrow_global_mut<Registry>(signer::address_of(account));
    table::upsert(&mut registry.entries, key, value);
}

#[view]
public fun get_entry(registry_addr: address, key: address): u64 acquires Registry {
    let registry = borrow_global<Registry>(registry_addr);
    *table::borrow(&registry.entries, key)
}

Timestamp

use aptos_framework::timestamp;

public fun is_expired(deadline: u64): bool {
    timestamp::now_seconds() > deadline
}

Indexer and GraphQL

Aptos provides a GraphQL indexer for querying historical data, events, and token ownership.

NetworkIndexer URL
Mainnethttps://indexer.mainnet.aptoslabs.com/v1/graphql
Testnethttps://indexer.testnet.aptoslabs.com/v1/graphql

Key tables: current_token_ownerships_v2 (NFT ownership), current_token_datas_v2 (token metadata), coin_activities (transfer history), account_transactions (transaction history).

See examples/read-resources/ for full GraphQL query patterns.

Reference Links

Last verified: 2025-12-01

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.