Comparing ens with farcaster
ens
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
ENS (Ethereum Name Service)
ENS maps human-readable names (alice.eth) to Ethereum addresses, content hashes, and arbitrary metadata. It is the identity layer for Ethereum — used for wallets, dApps, and onchain profiles. The architecture separates the registry (who owns a name) from resolvers (what data a name points to).
What You Probably Got Wrong
- ENS uses
namehash, not plain strings -- The registry and resolvers never see "alice.eth" as a string. Names are normalized (UTS-46), then hashed with the recursivenamehashalgorithm (EIP-137). If you pass a raw string to a contract call, it will not work. viem handles this automatically in its ENS actions but you must usenamehash()andlabelhash()for direct contract calls. - Registry vs Resolver vs Registrar -- three different contracts -- The Registry tracks name ownership and which resolver to use. The Resolver stores records (address, text, contenthash). The Registrar handles
.ethname registration and renewal. Confusing these is the most common ENS integration bug. .ethregistrar uses commit-reveal, not a single transaction -- Registration requires two transactions separated by at least 60 seconds: firstcommit(secret), wait, thenregister(name, owner, duration, secret, ...). This prevents frontrunning. Skipping the wait or reusing a secret will revert.- Reverse resolution is opt-in -- An address only has a "primary name" if the owner explicitly set it via the Reverse Registrar. Do not assume every address has a reverse record. Always handle
nullreturns fromgetEnsName(). - Name Wrapper changes ownership semantics -- Since 2023, ENS names can be "wrapped" as ERC-1155 tokens via the Name Wrapper contract. Wrapped names have fuses that permanently restrict operations (cannot unwrap, cannot set resolver, etc.). Check
isWrappedbefore assuming standard ownership patterns. - CCIP-Read (ERC-3668) enables offchain resolution -- Resolvers can return an
OffchainLookuperror that instructs the client to fetch data from an offchain gateway and verify it onchain. This powers offchain subdomains, L2 resolution, and gasless record updates. viem handles CCIP-Read automatically. - Wildcard resolution (ENSIP-10) is real -- Resolvers can implement
resolve(bytes name, bytes data)to handle any subdomain dynamically, even ones not explicitly registered. This is how services like cb.id and lens.xyz work. - ENS names expire --
.ethnames require annual renewal. Expired names enter a 90-day grace period, then a 21-day premium auction, then become available. Do not cache resolution results indefinitely. normalize()before any ENS operation -- Names must be UTS-46 normalized before hashing. "Alice.ETH" and "alice.eth" produce different hashes. viem normalizes automatically, but if you build raw calldata you must normalize first using@adraffy/ens-normalize.
Quick Start
Installation
npm install viem
viem has built-in ENS support -- no additional packages needed for resolution.
Forward Resolution (Name to Address)
import { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const address = await client.getEnsAddress({
name: "vitalik.eth",
});
// "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
Reverse Resolution (Address to Name)
const name = await client.getEnsName({
address: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
});
// "vitalik.eth" (or null if no primary name set)
Get Avatar
const avatar = await client.getEnsAvatar({
name: "vitalik.eth",
});
// HTTPS URL to avatar image, or null
Name Resolution
Forward Resolution with Coin Types
ENS can store addresses for any blockchain, not just Ethereum. Each chain has a SLIP-44 coin type.
const ethAddress = await client.getEnsAddress({
name: "vitalik.eth",
});
// BTC address (coin type 0)
const btcAddress = await client.getEnsAddress({
name: "vitalik.eth",
coinType: 0,
});
// Solana address (coin type 501)
const solAddress = await client.getEnsAddress({
name: "vitalik.eth",
coinType: 501,
});
Text Records
ENS text records store arbitrary key-value metadata. Standard keys are defined in ENSIP-5.
const twitter = await client.getEnsText({
name: "vitalik.eth",
key: "com.twitter",
});
const github = await client.getEnsText({
name: "vitalik.eth",
key: "com.github",
});
const email = await client.getEnsText({
name: "vitalik.eth",
key: "email",
});
const url = await client.getEnsText({
name: "vitalik.eth",
key: "url",
});
const description = await client.getEnsText({
name: "vitalik.eth",
key: "description",
});
// Avatar is also a text record (ENSIP-12 supports NFT references)
const avatarRecord = await client.getEnsText({
name: "vitalik.eth",
key: "avatar",
});
// Can be HTTPS URL, IPFS URI, or NFT reference like
// "eip155:1/erc721:0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d/1234"
Standard Text Record Keys
| Key | Description |
|---|---|
email | Email address |
url | Website URL |
avatar | Avatar image (HTTPS, IPFS, or NFT reference) |
description | Short bio |
display | Display name (may differ from ENS name) |
com.twitter | Twitter/X handle |
com.github | GitHub username |
com.discord | Discord username |
org.telegram | Telegram handle |
notice | Contract notice text |
keywords | Comma-separated keywords |
header | Profile header/banner image |
Content Hash
import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
import { namehash } from "viem/ens";
const client = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const RESOLVER_ABI = parseAbi([
"function contenthash(bytes32 node) view returns (bytes)",
]);
const node = namehash("vitalik.eth");
// First get the resolver address
const resolverAddress = await client.getEnsResolver({
name: "vitalik.eth",
});
const contenthash = await client.readContract({
address: resolverAddress,
abi: RESOLVER_ABI,
functionName: "contenthash",
args: [node],
});
// Encoded content hash (IPFS, Swarm, Arweave, etc.)
Batch Resolution with Multicall
import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
import { namehash } from "viem/ens";
const client = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const RESOLVER_ABI = parseAbi([
"function addr(bytes32 node) view returns (address)",
"function text(bytes32 node, string key) view returns (string)",
]);
const node = namehash("vitalik.eth");
const resolverAddress = await client.getEnsResolver({
name: "vitalik.eth",
});
const results = await client.multicall({
contracts: [
{
address: resolverAddress,
abi: RESOLVER_ABI,
functionName: "addr",
args: [node],
},
{
address: resolverAddress,
abi: RESOLVER_ABI,
functionName: "text",
args: [node, "com.twitter"],
},
{
address: resolverAddress,
abi: RESOLVER_ABI,
functionName: "text",
args: [node, "com.github"],
},
{
address: resolverAddress,
abi: RESOLVER_ABI,
functionName: "text",
args: [node, "url"],
},
],
});
const [addr, twitter, github, url] = results.map((r) => r.result);
Registration
Commit-Reveal Process
ENS .eth registration uses a two-step commit-reveal to prevent frontrunning. You must wait at least 60 seconds between commit and register.
import {
createPublicClient,
createWalletClient,
http,
parseAbi,
encodePacked,
keccak256,
parseEther,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";
const ETH_REGISTRAR_CONTROLLER =
"0x253553366Da8546fC250F225fe3d25d0C782303b" as const;
const CONTROLLER_ABI = parseAbi([
"function rentPrice(string name, uint256 duration) view returns (tuple(uint256 base, uint256 premium))",
"function available(string name) view returns (bool)",
"function makeCommitment(string name, address owner, uint256 duration, bytes32 secret, address resolver, bytes[] data, bool reverseRecord, uint16 ownerControlledFuses) pure returns (bytes32)",
"function commit(bytes32 commitment) external",
"function register(string name, address owner, uint256 duration, bytes32 secret, address resolver, bytes[] data, bool reverseRecord, uint16 ownerControlledFuses) payable",
]);
const PUBLIC_RESOLVER = "0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63" as const;
const account = privateKeyToAccount(
process.env.PRIVATE_KEY as `0x${string}`
);
const client = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const walletClient = createWalletClient({
account,
chain: mainnet,
transport: http(process.env.RPC_URL),
});
async function registerName(label: string, durationSeconds: bigint) {
// 1. Check availability
const isAvailable = await client.readContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI,
functionName: "available",
args: [label],
});
if (!isAvailable) throw new Error(`${label}.eth is not available`);
// 2. Get price
const rentPrice = await client.readContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI,
functionName: "rentPrice",
args: [label, durationSeconds],
});
// Add 10% buffer for price fluctuation during commit-reveal wait
const totalPrice =
((rentPrice.base + rentPrice.premium) * 110n) / 100n;
// 3. Generate secret (random 32 bytes)
const secret = keccak256(
encodePacked(["address", "uint256"], [account.address, BigInt(Date.now())])
);
// 4. Create commitment
const commitment = await client.readContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI,
functionName: "makeCommitment",
args: [
label,
account.address,
durationSeconds,
secret,
PUBLIC_RESOLVER,
[], // data (encoded resolver calls to set records at registration)
true, // reverseRecord (set as primary name)
0, // ownerControlledFuses (0 = no fuses)
],
});
// 5. Submit commitment
const commitHash = await walletClient.writeContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI,
functionName: "commit",
args: [commitment],
});
await client.waitForTransactionReceipt({ hash: commitHash });
console.log("Commitment submitted. Waiting 60 seconds...");
// 6. Wait at least 60 seconds (minCommitmentAge)
await new Promise((resolve) => setTimeout(resolve, 65_000));
// 7. Register
const registerHash = await walletClient.writeContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI,
functionName: "register",
args: [
label,
account.address,
durationSeconds,
secret,
PUBLIC_RESOLVER,
[],
true,
0,
],
value: totalPrice,
});
const receipt = await client.waitForTransactionReceipt({
hash: registerHash,
});
if (receipt.status !== "success") {
throw new Error("Registration transaction reverted");
}
console.log(`Registered ${label}.eth for ${durationSeconds / 31536000n} year(s)`);
return receipt;
}
// Register for 1 year (365 days in seconds)
await registerName("myname", 31536000n);
Renewal
const CONTROLLER_ABI_RENEW = parseAbi([
"function rentPrice(string name, uint256 duration) view returns (tuple(uint256 base, uint256 premium))",
"function renew(string name, uint256 duration) payable",
]);
async function renewName(label: string, durationSeconds: bigint) {
const rentPrice = await client.readContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI_RENEW,
functionName: "rentPrice",
args: [label, durationSeconds],
});
// 5% buffer for price changes
const totalPrice = ((rentPrice.base + rentPrice.premium) * 105n) / 100n;
const hash = await walletClient.writeContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI_RENEW,
functionName: "renew",
args: [label, durationSeconds],
value: totalPrice,
});
const receipt = await client.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("Renewal transaction reverted");
}
console.log(`Renewed ${label}.eth for ${durationSeconds / 31536000n} year(s)`);
return receipt;
}
Check Price Before Registering
async function getRegistrationCost(
label: string,
durationSeconds: bigint
): Promise<{ base: bigint; premium: bigint; total: bigint }> {
const rentPrice = await client.readContract({
address: ETH_REGISTRAR_CONTROLLER,
abi: CONTROLLER_ABI,
functionName: "rentPrice",
args: [label, durationSeconds],
});
return {
base: rentPrice.base,
premium: rentPrice.premium,
total: rentPrice.base + rentPrice.premium,
};
}
Working with Resolvers
Setting Text Records
import {
createPublicClient,
createWalletClient,
http,
parseAbi,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";
import { namehash } from "viem/ens";
const PUBLIC_RESOLVER = "0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63" as const;
const RESOLVER_ABI = parseAbi([
"function setText(bytes32 node, string key, string value) external",
"function setAddr(bytes32 node, address addr) external",
"function setAddr(bytes32 node, uint256 coinType, bytes value) external",
"function setContenthash(bytes32 node, bytes hash) external",
"function multicall(bytes[] data) external returns (bytes[])",
]);
const account = privateKeyToAccount(
process.env.PRIVATE_KEY as `0x${string}`
);
const client = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const walletClient = createWalletClient({
account,
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const node = namehash("myname.eth");
// Set a single text record
const hash = await walletClient.writeContract({
address: PUBLIC_RESOLVER,
abi: RESOLVER_ABI,
functionName: "setText",
args: [node, "com.twitter", "myhandle"],
});
await client.waitForTransactionReceipt({ hash });
Batch Update Records with Multicall
Setting multiple records in a single transaction using the resolver's built-in multicall.
import { encodeFunctionData } from "viem";
const node = namehash("myname.eth");
const calls = [
encodeFunctionData({
abi: RESOLVER_ABI,
functionName: "setText",
args: [node, "com.twitter", "myhandle"],
}),
encodeFunctionData({
abi: RESOLVER_ABI,
functionName: "setText",
args: [node, "com.github", "mygithub"],
}),
encodeFunctionData({
abi: RESOLVER_ABI,
functionName: "setText",
args: [node, "url", "https://mysite.com"],
}),
encodeFunctionData({
abi: RESOLVER_ABI,
functionName: "setText",
args: [node, "email", "me@mysite.com"],
}),
encodeFunctionData({
abi: RESOLVER_ABI,
functionName: "setText",
args: [node, "avatar", "https://mysite.com/avatar.png"],
}),
];
const hash = await walletClient.writeContract({
address: PUBLIC_RESOLVER,
abi: RESOLVER_ABI,
functionName: "multicall",
args: [calls],
});
const receipt = await client.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("Multicall record update reverted");
}
Setting the Primary Name (Reverse Record)
const REVERSE_REGISTRAR = "0xa58E81fe9b61B5c3fE2AFD33CF304c454AbFc7Cb" as const;
const REVERSE_ABI = parseAbi([
"function setName(string name) external returns (bytes32)",
]);
const hash = await walletClient.writeContract({
address: REVERSE_REGISTRAR,
abi: REVERSE_ABI,
functionName: "setName",
args: ["myname.eth"],
});
await client.waitForTransactionReceipt({ hash });
Subdomains
Creating an Onchain Subdomain
import { parseAbi } from "viem";
import { namehash, labelhash } from "viem/ens";
const ENS_REGISTRY = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e" as const;
const REGISTRY_ABI = parseAbi([
"function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external",
"function owner(bytes32 node) view returns (address)",
"function resolver(bytes32 node) view returns (address)",
]);
const parentNode = namehash("myname.eth");
const subLabel = labelhash("sub");
const hash = await walletClient.writeContract({
address: ENS_REGISTRY,
abi: REGISTRY_ABI,
functionName: "setSubnodeRecord",
args: [
parentNode,
subLabel,
account.address, // owner of sub.myname.eth
PUBLIC_RESOLVER, // resolver
0n, // TTL
],
});
await client.waitForTransactionReceipt({ hash });
// sub.myname.eth now exists and points to PUBLIC_RESOLVER
Offchain Subdomains (CCIP-Read / ERC-3668)
Offchain subdomains let you issue unlimited subdomains without gas costs. The resolver responds with an OffchainLookup error that directs the client to a gateway URL. The gateway returns signed data that is verified onchain.
This is how services like cb.id (Coinbase), uni.eth (Uniswap), and lens.xyz work.
For offchain resolution, viem handles CCIP-Read transparently -- no client-side changes needed:
// Resolving an offchain subdomain works identically to onchain names
const address = await client.getEnsAddress({
name: "myuser.cb.id",
});
// viem automatically:
// 1. Calls resolver.resolve(...)
// 2. Catches OffchainLookup revert
// 3. Fetches from the gateway URL
// 4. Calls resolver with the gateway proof
// 5. Returns the verified address
const avatar = await client.getEnsAvatar({
name: "myuser.cb.id",
});
To build your own offchain resolver, implement ERC-3668:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IExtendedResolver} from "@ensdomains/ens-contracts/contracts/resolvers/profiles/IExtendedResolver.sol";
/// @notice Offchain resolver that delegates lookups to a gateway
/// @dev Implements ERC-3668 (CCIP-Read) and ENSIP-10 (wildcard resolution)
contract OffchainResolver is IExtendedResolver {
string public url;
address public signer;
error OffchainLookup(
address sender,
string[] urls,
bytes callData,
bytes4 callbackFunction,
bytes extraData
);
constructor(string memory _url, address _signer) {
url = _url;
signer = _signer;
}
/// @notice ENSIP-10 wildcard resolve entry point
function resolve(
bytes calldata name,
bytes calldata data
) external view returns (bytes memory) {
string[] memory urls = new string[](1);
urls[0] = url;
revert OffchainLookup(
address(this),
urls,
data,
this.resolveWithProof.selector,
abi.encode(name, data)
);
}
/// @notice Callback that verifies the gateway signature
function resolveWithProof(
bytes calldata response,
bytes calldata extraData
) external view returns (bytes memory) {
// Verify signature from gateway matches expected signer
// Return decoded result
// Implementation depends on your signing scheme
}
}
Contract Addresses
Ethereum Mainnet. Last verified: 2025-03-01.
| Contract | Address | Purpose |
|---|---|---|
| ENS Registry | 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e | Core registry -- maps names to owners and resolvers |
| Public Resolver | 0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63 | Default resolver for address, text, contenthash, and ABI records |
| ETH Registrar Controller | 0x253553366Da8546fC250F225fe3d25d0C782303b | Handles .eth name registration and renewal (commit-reveal) |
| Name Wrapper | 0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401 | Wraps names as ERC-1155 tokens with permission fuses |
| Reverse Registrar | 0xa58E81fe9b61B5c3fE2AFD33CF304c454AbFc7Cb | Manages reverse records (address-to-name mapping) |
| Base Registrar (NFT) | 0x57f1887a8BF19b14fC0dF6Fd9B2acc9Af147eA85 | ERC-721 NFT for .eth second-level names |
| Universal Resolver | 0xce01f8eee7E30F8E3BfC1C22bCBc01faBc8680E4 | Batch resolution with CCIP-Read support |
Address Constants for TypeScript
const ENS_ADDRESSES = {
registry: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
publicResolver: "0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63",
ethRegistrarController: "0x253553366Da8546fC250F225fe3d25d0C782303b",
nameWrapper: "0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401",
reverseRegistrar: "0xa58E81fe9b61B5c3fE2AFD33CF304c454AbFc7Cb",
baseRegistrar: "0x57f1887a8BF19b14fC0dF6Fd9B2acc9Af147eA85",
universalResolver: "0xce01f8eee7E30F8E3BfC1C22bCBc01faBc8680E4",
} as const satisfies Record<string, `0x${string}`>;
Sepolia Testnet
Last verified: 2025-03-01.
| Contract | Address |
|---|---|
| ENS Registry | 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e |
| Public Resolver | 0x8FADE66B79cC9f707aB26799354482EB93a5B7dD |
| ETH Registrar Controller | 0xFED6a969AaA60E4961FCD3EBF1A2e8913DeBe6c7 |
| Name Wrapper | 0x0635513f179D50A207757E05759CbD106d7dFcE8 |
| Reverse Registrar | 0xA0a1AbcDAe1a2a4A2EF8e9113Ff0e02DD81DC0C6 |
Error Handling
Common Resolution Errors
async function safeResolve(name: string) {
try {
const address = await client.getEnsAddress({ name });
if (!address) {
console.log(`${name} has no address record set`);
return null;
}
return address;
} catch (error) {
if (error instanceof Error) {
// Name does not exist or is malformed
if (error.message.includes("Could not find resolver")) {
console.log(`${name} is not registered or has no resolver`);
return null;
}
// CCIP-Read gateway failure
if (error.message.includes("OffchainLookup")) {
console.log(`Offchain resolution failed for ${name}`);
return null;
}
}
throw error;
}
}
Common Registration Errors
| Error | Cause | Fix |
|---|---|---|
CommitmentTooNew | Called register() less than 60s after commit() | Wait at least 60 seconds between commit and register |
CommitmentTooOld | Commitment expired (older than 24 hours) | Submit a new commitment |
NameNotAvailable | Name is registered or in grace period | Check available() first |
DurationTooShort | Duration under minimum (28 days) | Use at least 2419200 seconds |
InsufficientValue | Sent less ETH than rentPrice() requires | Add a 5-10% buffer to rentPrice() result |
Unauthorised | Caller is not the name owner | Verify ownership via registry before writing records |
Validating ENS Names
import { normalize } from "viem/ens";
function isValidEnsName(name: string): boolean {
try {
normalize(name);
return true;
} catch {
return false;
}
}
// normalize() throws on invalid names
// Valid: "alice.eth", "sub.alice.eth", "alice.xyz"
// Invalid: names with zero-width characters, confusable Unicode, etc.
Key Constants
| Constant | Value | Notes |
|---|---|---|
| Min commitment age | 60 seconds | Wait between commit and register |
| Max commitment age | 86400 seconds (24h) | Commitment expires after this |
| Min registration duration | 2419200 seconds (28 days) | Shortest allowed registration |
| Grace period | 90 days | After expiry, owner can still renew |
| Premium auction | 21 days | After grace period, decaying price auction |
Namehash of eth | 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae | Used as parent node for .eth names |
References
- ENS Documentation -- official docs covering architecture, resolution, registration, and CCIP-Read
- EIP-137: ENS -- core ENS specification (registry, namehash, resolvers)
- EIP-181: Reverse Resolution -- reverse registrar and addr.reverse namespace
- EIP-2304: Multichain Address Resolution -- SLIP-44 coin type support in resolvers
- ERC-3668: CCIP-Read -- offchain data retrieval standard
- ENSIP-5: Text Records -- standardized text record keys
- ENSIP-10: Wildcard Resolution -- dynamic subdomain resolution
- ENSIP-12: Avatar Text Records -- NFT and IPFS avatar specification
- ENS Deployments -- official contract addresses per network
- viem ENS Actions -- built-in ENS resolution in viem
- @adraffy/ens-normalize -- reference UTS-46 normalization library used by viem
farcaster
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
Farcaster
Farcaster is a sufficiently decentralized social protocol. Users register onchain identities (FIDs) on OP Mainnet and publish social data (casts, reactions, links) as offchain messages to Snapchain, a purpose-built message ordering layer. Neynar provides the primary API infrastructure and, since January 2026, owns the Farcaster protocol itself. Frames v2 (Mini Apps) enable full-screen interactive web applications embedded inside Farcaster clients like Warpcast.
What You Probably Got Wrong
-
Manifest
accountAssociationdomain MUST exactly match the FQDN where/.well-known/farcaster.jsonis hosted. A mismatch causes silent failure -- the Mini App will not load, no error is surfaced to the developer, and Warpcast simply shows nothing. The domain in the signature payload must be byte-identical to the hosting domain (no trailing slash, no protocol prefix, no port unless non-standard). -
Neynar webhooks MUST be verified via HMAC-SHA512 at write time. Check the
X-Neynar-Signatureheader against the raw request body. Never parse JSON before verification -- you must verify the raw bytes.
import crypto from "node:crypto";
import type { IncomingHttpHeaders } from "node:http";
function verifyNeynarWebhook(
rawBody: Buffer,
headers: IncomingHttpHeaders,
webhookSecret: string
): boolean {
const signature = headers["x-neynar-signature"];
if (typeof signature !== "string") return false;
const hmac = crypto.createHmac("sha512", webhookSecret);
hmac.update(rawBody);
const computedSignature = hmac.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(computedSignature, "hex")
);
}
-
Farcaster is NOT a blockchain. It is a social protocol with an onchain registry (OP Mainnet) for identity and key management, plus an offchain message layer (Snapchain) for social data. Casts, reactions, and follows are never posted to any blockchain.
-
FIDs are onchain but casts are NOT. Farcaster IDs (FIDs) live in the IdRegistry contract on OP Mainnet. Casts, reactions, and link messages are stored on Snapchain and are not onchain data.
-
Frames v2 is NOT Frames v1 -- completely different spec. Frames v1 used static OG images with action buttons and server-side rendering. Frames v2 (Mini Apps) are full-screen interactive web applications loaded in an iframe with SDK access to wallet, user context, and notifications. Do not mix the two APIs.
-
Neynar is NOT just an API provider. Neynar acquired Farcaster from Merkle Manufactory in January 2026. Neynar now owns and operates the protocol, the Snapchain infrastructure, and the primary API layer.
-
Frame images must be static. Frame preview images (OG images shown in feed) cannot contain JavaScript. They are rendered as static images by the client. Interactive behavior only works inside the launched Mini App.
-
@farcaster/frame-sdkand@farcaster/miniapp-sdkare converging. Both packages exist butframe-sdkis the current stable package for Frames v2. Check import paths -- functionality overlaps but the packages are not yet unified. -
Farcaster timestamps use a custom epoch. Timestamps are seconds since January 1, 2021 00:00:00 UTC (Farcaster epoch), not Unix epoch. To convert:
unixTimestamp = farcasterTimestamp + 1609459200. -
Cast text has a 1024 BYTE limit, not characters. UTF-8 multibyte characters (emoji, CJK, accented characters) consume 2-4 bytes each. A 1024-character cast with emoji will exceed the limit.
-
Warpcast aggressively caches OG/frame images. Changing content at the same URL will not update the preview in Warpcast feeds. Use cache-busting query parameters or new URLs when updating frame images.
Critical Context
Neynar acquired Farcaster from Merkle Manufactory in January 2026. This means:
- Neynar operates the protocol, Snapchain validators, and the Hub network
- The Neynar API is the canonical way to interact with Farcaster
- Warpcast remains the primary client, now under Neynar's umbrella
- The open-source protocol spec and hub software remain MIT-licensed
- Third-party hubs can still run, but Neynar controls the reference implementation
Protocol Architecture
Snapchain
Snapchain replaced the Hub network in April 2025 as Farcaster's offchain message ordering layer.
| Property | Detail |
|---|---|
| Consensus | Malachite BFT (Tendermint-derived) |
| Throughput | 10,000+ messages per second |
| Sharding | Account-level -- each FID's messages are ordered independently |
| Finality | Sub-second for message acceptance |
| Data model | Append-only log of signed messages per FID |
| Validator set | Operated by Neynar (post-acquisition) |
Messages on Snapchain are CRDTs (Conflict-free Replicated Data Types). Each message type has merge rules that ensure consistency across nodes without coordination:
- CastAdd conflicts with a later CastRemove for the same hash -- remove wins
- ReactionAdd conflicts with ReactionRemove for the same target -- last-write-wins by timestamp
- LinkAdd conflicts with LinkRemove -- last-write-wins by timestamp
Message Structure
Every Farcaster message is an Ed25519-signed protobuf:
MessageData {
type: MessageType // CAST_ADD, REACTION_ADD, LINK_ADD, etc.
fid: uint64 // Farcaster ID of the author
timestamp: uint32 // Farcaster epoch seconds
network: Network // MAINNET = 1
body: MessageBody // Type-specific payload
}
Message {
data: MessageData
hash: bytes // Blake3 hash of serialized MessageData
hash_scheme: BLAKE3
signature: bytes // Ed25519 signature over hash
signature_scheme: ED25519
signer: bytes // Public key of the signer (app key)
}
Onchain Registry (OP Mainnet)
Farcaster's onchain contracts manage identity, keys, and storage on OP Mainnet.
Last verified: March 2026
| Contract | Address | Purpose |
|---|---|---|
| IdRegistry | 0x00000000Fc6c5F01Fc30151999387Bb99A9f489b | Maps FIDs to custody addresses |
| KeyRegistry | 0x00000000Fc1237824fb747aBDE0FF18990E59b7e | Maps FIDs to Ed25519 app keys (signers) |
| StorageRegistry | 0x00000000FcCe7f938e7aE6D3c335bD6a1a7c593D | Manages storage units per FID |
| IdGateway | 0x00000000Fc25870C6eD6b6c7E41Fb078b7656f69 | Permissioned FID registration entry point |
| KeyGateway | 0x00000000fC56947c7E7183f8Ca4B62398CaaDF0B | Permissioned key addition entry point |
| Bundler | 0x00000000FC04c910A0b5feA33b03E0447ad0B0aA | Batches register + addKey + rent in one tx |
# Verify IdRegistry is deployed on OP Mainnet
cast code 0x00000000Fc6c5F01Fc30151999387Bb99A9f489b --rpc-url https://mainnet.optimism.io
# Look up custody address for an FID
cast call 0x00000000Fc6c5F01Fc30151999387Bb99A9f489b \
"custodyOf(uint256)(address)" 3 \
--rpc-url https://mainnet.optimism.io
Registration Flow
1. User calls IdGateway.register() or Bundler.register()
-> IdRegistry assigns next sequential FID to custody address
|
2. User (or Bundler) calls KeyGateway.add()
-> KeyRegistry maps FID to an Ed25519 public key (app key / signer)
|
3. User (or Bundler) calls StorageRegistry.rent()
-> Allocates storage units (each unit = 5,000 casts, 2,500 reactions, 2,500 links)
|
4. App key can now sign Farcaster messages on behalf of the FID
Farcaster IDs (FIDs)
Every Farcaster user has an FID -- a sequentially assigned uint256 stored in IdRegistry on OP Mainnet.
| Concept | Description |
|---|---|
| FID | The user's numeric identity, immutable once assigned |
| Custody address | The Ethereum address that owns the FID -- can transfer ownership |
| App key (signer) | Ed25519 key pair registered in KeyRegistry -- signs messages |
| Recovery address | Can initiate FID recovery if custody address is compromised |
An FID can have multiple app keys. Each app (Warpcast, third-party client) registers its own app key via KeyGateway. The custody address can revoke any app key by calling KeyRegistry.remove().
Neynar API v2
Neynar provides the primary API for reading and writing Farcaster data. Current SDK version: @neynar/nodejs-sdk v3.131.0.
Setup
npm install @neynar/nodejs-sdk
import { NeynarAPIClient, Configuration } from "@neynar/nodejs-sdk";
const config = new Configuration({
apiKey: process.env.NEYNAR_API_KEY,
});
const neynar = new NeynarAPIClient(config);
Fetch User by FID
const { users } = await neynar.fetchBulkUsers({ fids: [3] });
const user = users[0];
console.log(user.username, user.display_name, user.follower_count);
Publish a Cast
const response = await neynar.publishCast({
signerUuid: process.env.SIGNER_UUID,
text: "Hello from Neynar SDK",
});
console.log(response.cast.hash);
Fetch Feed
const feed = await neynar.fetchFeed({
feedType: "following",
fid: 3,
limit: 25,
});
for (const cast of feed.casts) {
console.log(`@${cast.author.username}: ${cast.text}`);
}
Search Users
const result = await neynar.searchUser({ q: "vitalik", limit: 5 });
for (const user of result.result.users) {
console.log(`FID ${user.fid}: @${user.username}`);
}
Fetch Cast by Hash
const { cast } = await neynar.lookupCastByHashOrWarpcastUrl({
identifier: "0xfe90f9de682273e05b201629ad2338bdcd89b6be",
type: "hash",
});
console.log(cast.text, cast.reactions.likes_count);
Webhook Configuration
Create webhooks in the Neynar dashboard or via API. Webhooks fire on cast creation, reaction events, follow events, and more.
import express from "express";
import crypto from "node:crypto";
const app = express();
// Raw body is required for signature verification
app.use("/webhook", express.raw({ type: "application/json" }));
app.post("/webhook", (req, res) => {
const rawBody = req.body as Buffer;
const signature = req.headers["x-neynar-signature"] as string;
if (!signature) {
res.status(401).json({ error: "Missing signature" });
return;
}
const hmac = crypto.createHmac("sha512", process.env.NEYNAR_WEBHOOK_SECRET!);
hmac.update(rawBody);
const computed = hmac.digest("hex");
const isValid = crypto.timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(computed, "hex")
);
if (!isValid) {
res.status(401).json({ error: "Invalid signature" });
return;
}
const event = JSON.parse(rawBody.toString("utf-8"));
console.log("Verified webhook event:", event.type);
res.status(200).json({ status: "ok" });
});
app.listen(3001, () => console.log("Webhook listener on :3001"));
Frames v2 / Mini Apps
Frames v2 are full-screen interactive web applications embedded inside Farcaster clients. They replaced the static image + button model of Frames v1 with a rich SDK-powered experience.
Manifest (/.well-known/farcaster.json)
Every Mini App must serve a manifest at /.well-known/farcaster.json on its domain:
{
"accountAssociation": {
"header": "eyJmaWQiOjM...",
"payload": "eyJkb21haW4iOiJleGFtcGxlLmNvbSJ9",
"signature": "abc123..."
},
"frame": {
"version": "1",
"name": "My Mini App",
"iconUrl": "https://example.com/icon.png",
"homeUrl": "https://example.com/app",
"splashImageUrl": "https://example.com/splash.png",
"splashBackgroundColor": "#1a1a2e",
"webhookUrl": "https://example.com/api/webhook"
}
}
The accountAssociation proves that the FID owner controls the domain. The payload decoded is {"domain":"example.com"} -- this domain MUST match the FQDN hosting the manifest file.
Meta Tags
Add these to your app's HTML <head> for Farcaster clients to discover the Mini App:
<meta name="fc:frame" content='{"version":"next","imageUrl":"https://example.com/og.png","button":{"title":"Launch App","action":{"type":"launch_frame","name":"My App","url":"https://example.com/app","splashImageUrl":"https://example.com/splash.png","splashBackgroundColor":"#1a1a2e"}}}' />
Frame SDK Setup
npm install @farcaster/frame-sdk
import sdk from "@farcaster/frame-sdk";
async function initMiniApp() {
const context = await sdk.context;
// context.user contains the viewing user's FID, username, pfpUrl
console.log(`User FID: ${context.user.fid}`);
console.log(`Username: ${context.user.username}`);
// Signal to the client that the app is ready to render
sdk.actions.ready();
}
initMiniApp();
SDK Actions
// Open an external URL in the client's browser
sdk.actions.openUrl("https://example.com");
// Close the Mini App
sdk.actions.close();
// Compose a cast with prefilled text
sdk.actions.composeCast({
text: "Check out this Mini App!",
embeds: ["https://example.com/app"],
});
// Add a Mini App to the user's favorites (prompts confirmation)
sdk.actions.addFrame();
Transaction Frames
Mini Apps can trigger onchain transactions through the embedded wallet provider. The SDK exposes an EIP-1193 provider that connects to the user's wallet in the Farcaster client.
Wallet Provider Setup
import sdk from "@farcaster/frame-sdk";
import { createWalletClient, custom, parseEther, type Address } from "viem";
import { base } from "viem/chains";
async function sendTransaction() {
const context = await sdk.context;
const provider = sdk.wallet.ethProvider;
const walletClient = createWalletClient({
chain: base,
transport: custom(provider),
});
const [address] = await walletClient.requestAddresses();
const hash = await walletClient.sendTransaction({
account: address,
to: "0xRecipient..." as Address,
value: parseEther("0.001"),
});
return hash;
}
With Wagmi Connector
For apps using wagmi, wrap the SDK's provider as a connector:
import sdk from "@farcaster/frame-sdk";
import { createConfig, http, useConnect, useSendTransaction } from "wagmi";
import { base } from "wagmi/chains";
import { farcasterFrame } from "@farcaster/frame-wagmi-connector";
const config = createConfig({
chains: [base],
transports: {
[base.id]: http(),
},
connectors: [farcasterFrame()],
});
// In your React component:
function MintButton() {
const { connect, connectors } = useConnect();
const { sendTransaction } = useSendTransaction();
async function handleMint() {
connect({ connector: connectors[0] });
sendTransaction({
to: "0xNFTContract..." as `0x${string}`,
data: "0x...", // mint function calldata
value: parseEther("0.01"),
});
}
return <button onClick={handleMint}>Mint</button>;
}
Warpcast Deep Links and Cast Intents
Cast Intent URL
Open Warpcast's compose screen with prefilled content:
https://warpcast.com/~/compose?text=Hello%20Farcaster&embeds[]=https://example.com
| Parameter | Description |
|---|---|
text | URL-encoded cast text |
embeds[] | Up to 2 embed URLs |
channelKey | Channel to post in (e.g., farcaster) |
Deep Links
# Open a user's profile
https://warpcast.com/<username>
# Open a specific cast
https://warpcast.com/<username>/<cast-hash>
# Open a channel
https://warpcast.com/~/channel/<channel-id>
# Open direct cast composer
https://warpcast.com/~/inbox/create/<fid>
Channels
Channels are topic-based feeds identified by a parent_url. A cast is posted to a channel by setting its parent_url to the channel's URL.
// Post a cast to the "ethereum" channel
const response = await neynar.publishCast({
signerUuid: process.env.SIGNER_UUID,
text: "Pectra upgrade is live!",
channelId: "ethereum",
});
Channel Lookup
const channel = await neynar.lookupChannel({ id: "farcaster" });
console.log(channel.channel.name, channel.channel.follower_count);
Channel Feed
const feed = await neynar.fetchFeed({
feedType: "filter",
filterType: "channel_id",
channelId: "ethereum",
limit: 25,
});
Neynar API Pricing
Current as of March 2026
| Plan | Monthly Credits | Price | Webhooks | Rate Limit |
|---|---|---|---|---|
| Free | 100K | $0 | 1 | 5 req/s |
| Starter | 1M | $49/mo | 5 | 20 req/s |
| Growth | 10M | $249/mo | 25 | 50 req/s |
| Scale | 60M | $899/mo | 100 | 200 req/s |
| Enterprise | Custom | Custom | Unlimited | Custom |
Credit costs vary by endpoint. Read operations (user lookup, feed) cost 1-5 credits. Write operations (publish cast, react) cost 10-50 credits. Webhook deliveries are free but count against webhook limits.
Hub / Snapchain Endpoints
Direct hub access for reading raw Farcaster data without the Neynar API abstraction.
| Provider | Endpoint | Auth |
|---|---|---|
| Neynar Hub API | hub-api.neynar.com | API key in x-api-key header |
| Self-hosted Hub | localhost:2283 | None (local) |
Hub HTTP API Examples
# Get casts by FID
curl -H "x-api-key: $NEYNAR_API_KEY" \
"https://hub-api.neynar.com/v1/castsByFid?fid=3&pageSize=10"
# Get user data (display name, bio, pfp)
curl -H "x-api-key: $NEYNAR_API_KEY" \
"https://hub-api.neynar.com/v1/userDataByFid?fid=3"
# Get reactions by FID
curl -H "x-api-key: $NEYNAR_API_KEY" \
"https://hub-api.neynar.com/v1/reactionsByFid?fid=3&reactionType=1"
Hub gRPC API
# Install hubble CLI
npm install -g @farcaster/hubble
# Query via gRPC
hubble --insecure -r hub-api.neynar.com:2283 getCastsByFid --fid 3
Farcaster Epoch Conversion
// Farcaster epoch: January 1, 2021 00:00:00 UTC
const FARCASTER_EPOCH = 1609459200;
function farcasterTimestampToUnix(farcasterTs: number): number {
return farcasterTs + FARCASTER_EPOCH;
}
function unixToFarcasterTimestamp(unixTs: number): number {
return unixTs - FARCASTER_EPOCH;
}
function farcasterTimestampToDate(farcasterTs: number): Date {
return new Date((farcasterTs + FARCASTER_EPOCH) * 1000);
}
Related Skills
- viem -- Used for onchain interactions with Farcaster registry contracts on OP Mainnet and for building transaction frames with the wallet provider
- wagmi -- React hooks for wallet connection in Mini Apps via the
@farcaster/frame-wagmi-connector - x402 -- Payment protocol that can be integrated with Farcaster Mini Apps for paywalled content