6.2 KiB
6.2 KiB
๐ Farcaster Username Lookup
โ Find Users by Username
Lookup Farcaster users by their fname (@username) or ENS name (username.eth).
๐ฏ Implementation
Core Function
import { findUserByUsername } from '@/lib/farcaster/username'
const user = await findUserByUsername('@alice')
// Returns: { fid: 123, username: 'alice' }
const ensUser = await findUserByUsername('alice.eth')
// Returns: { fid: 456, username: 'alice.eth' }
API Endpoint
# Single lookup
GET /api/farcaster/username?username=alice
Response:
{
"fid": 123,
"username": "alice"
}
# Bulk lookup
GET /api/farcaster/username?usernames=alice,bob,charlie
Response:
{
"users": [
{ "fid": 123, "username": "alice" },
{ "fid": 456, "username": "bob" }
]
}
๐ Username Types
Offchain ENS Names (Fnames)
Format: @username or username
Example: @alice, farcaster
Source: Fname Registry API
How it works:
// Query fname registry
const res = await fetch('https://fnames.farcaster.xyz/transfers/current?name=alice')
// Get latest transfer
const transfer = data.transfers[0]
const fid = transfer.to // Current owner FID
Onchain ENS Names
Format: username.eth
Example: alice.eth, vitalik.eth
Source: ENS + Fname Registry
Note: Some ENS names are also registered in fname registry
๐จ UI Component
UsernameSearch Component
import UsernameSearch from '@/components/UsernameSearch'
<UsernameSearch
onUserFound={(user) => {
console.log('Found:', user.fid, user.username)
}}
/>
Features:
- Search input with validation
- Loading states
- Error handling
- Result display
- Callback on success
๐ง Use Cases in PollCelo
1. Challenge a Friend
// User enters friend's username
const friend = await findUserByUsername('@bob')
// Create challenge
await createChallenge(myFid, friend.fid)
2. Follow Users
// Search for user to follow
const user = await findUserByUsername('@alice')
// Follow them
await followUser(user.fid)
3. Mention in Comments
// Parse @mentions
const mentions = extractMentions(comment) // ['@alice', '@bob']
// Lookup FIDs
const users = await bulkLookupUsernames(mentions)
// Notify mentioned users
users.forEach(user => notifyMention(user.fid))
4. Share with Friend
// User wants to share poll
const friend = await findUserByUsername('@charlie')
// Send notification
await sendShareNotification(friend.fid, pollId)
๐ Performance
Caching
// Cache results for 5 minutes
const cache = new Map<string, { fid: number; timestamp: number }>()
export async function findUserByUsername(username: string) {
const cached = cache.get(username)
if (cached && Date.now() - cached.timestamp < 300000) {
return cached
}
const result = await fetchFromRegistry(username)
cache.set(username, { ...result, timestamp: Date.now() })
return result
}
Bulk Lookups
// Efficient batch processing
const usernames = ['alice', 'bob', 'charlie']
const users = await bulkLookupUsernames(usernames)
// Single API call, multiple results
๐ Error Handling
User Not Found
const user = await findUserByUsername('@nonexistent')
// Returns: null
// In API
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
Invalid Username
// Handle edge cases
const username = cleanUsername(input)
.replace('@', '')
.toLowerCase()
.trim()
Rate Limiting
// Fname registry has rate limits
// Implement exponential backoff
async function fetchWithRetry(url: string, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fetch(url)
} catch (error) {
if (i === retries - 1) throw error
await sleep(1000 * Math.pow(2, i))
}
}
}
๐งช Testing
Test Cases
// Valid fname
const user1 = await findUserByUsername('@farcaster')
expect(user1?.fid).toBe(1)
// Valid ENS
const user2 = await findUserByUsername('vitalik.eth')
expect(user2).toBeTruthy()
// Invalid username
const user3 = await findUserByUsername('@nonexistent123456')
expect(user3).toBeNull()
// Bulk lookup
const users = await bulkLookupUsernames(['alice', 'bob'])
expect(users.length).toBeGreaterThan(0)
๐ Fname Registry API
Endpoint
GET https://fnames.farcaster.xyz/transfers/current?name={username}
Response
{
"transfers": [
{
"id": 1,
"timestamp": 1628882891,
"username": "farcaster",
"owner": "0x8773442740c17c9d0f0b87022c722f9a136206ed",
"from": 0,
"to": 1,
"user_signature": "0x...",
"server_signature": "0x..."
}
]
}
Fields
username: The fnameto: Current FID ownerfrom: Previous FID (0 for new registration)timestamp: Transfer time
๐ฏ Integration Examples
Challenge System
// app/challenges/page.tsx
import UsernameSearch from '@/components/UsernameSearch'
<UsernameSearch
onUserFound={async (user) => {
await createChallenge(user.fid)
router.push(`/challenges/${challengeId}`)
}}
/>
Follow System
// app/profile/[fid]/page.tsx
const handleFollow = async (username: string) => {
const user = await findUserByUsername(username)
if (user) {
await followUser(user.fid)
}
}
Mention System
// components/CommentInput.tsx
const handleMention = async (username: string) => {
const user = await findUserByUsername(username)
if (user) {
insertMention(`@${user.username}`, user.fid)
}
}
โ Production Checklist
- Fname lookup implemented
- ENS lookup supported
- Bulk lookup available
- API endpoint created
- UI component built
- Caching implemented
- Rate limiting added
- Error handling tested
๐ Summary
Implementation: โ Complete
Features:
- Fname lookup (@username)
- ENS lookup (username.eth)
- Bulk lookups
- API endpoint
- UI component
Use Cases:
- Challenge friends
- Follow users
- Mention in comments
- Share polls
Ready to find Farcaster users! ๐