celo-poll/FARCASTER_REPLICATOR.md
2025-12-08 16:31:30 +03:00

306 lines
6.0 KiB
Markdown

# ๐Ÿ—„๏ธ Farcaster Postgres Replicator
## โœ… Use Existing Farcaster Data
Query the **Postgres Replicator** to access all Farcaster network data without creating new accounts.
---
## ๐ŸŽฏ What is the Replicator?
A Postgres database that mirrors all Farcaster Hub data:
- โœ… All registered FIDs
- โœ… All usernames (fnames & ENS)
- โœ… All casts (posts)
- โœ… All signers (account keys)
- โœ… All onchain events
**No registration needed - just query existing data!**
---
## ๐Ÿ“Š Database Tables
### fids
All registered Farcaster IDs
```sql
SELECT fid, registered_at, custody_address
FROM fids
WHERE fid = 1
```
### fnames
All usernames (fnames & ENS)
```sql
SELECT fid, username, type
FROM fnames
WHERE username = 'dwr'
AND deleted_at IS NULL
```
### casts
All posts/messages
```sql
SELECT text, timestamp, mentions
FROM casts
WHERE fid = 1
AND deleted_at IS NULL
ORDER BY timestamp DESC
```
### signers
All account keys
```sql
SELECT key, key_type, added_at
FROM signers
WHERE fid = 1
AND removed_at IS NULL
```
---
## ๐Ÿš€ Implementation
### Query Functions
```typescript
import { findUserByUsername, getUserProfile } from '@/lib/farcaster/replicator'
// Find user by username
const user = await findUserByUsername('@dwr')
// Returns: { fid: 3, username: 'dwr', type: 0 }
// Get full profile
const profile = await getUserProfile(3)
// Returns: { fid, username, registeredAt, custodyAddress }
// Search users
const results = await searchUsers('alice')
// Returns: [{ fid, username, type }, ...]
```
### API Endpoints
```bash
# Find by username
GET /api/farcaster/username?username=dwr
# Search users
GET /api/farcaster/username?search=alice
```
---
## ๐Ÿ’ก Use Cases in PollCelo
### 1. Username Lookup
```typescript
// User enters @username to challenge
const user = await findUserByUsername('@alice')
await createChallenge(myFid, user.fid)
```
### 2. Profile Display
```typescript
// Show user profile
const profile = await getUserProfile(fid)
<div>
<h2>@{profile.username}</h2>
<p>Joined: {profile.registeredAt}</p>
</div>
```
### 3. User Search
```typescript
// Search for users to follow
const results = await searchUsers('bob')
results.map(user => (
<UserCard fid={user.fid} username={user.username} />
))
```
### 4. Verify User Exists
```typescript
// Before creating vote
const exists = await userExists(fid)
if (!exists) {
return { error: 'Invalid FID' }
}
```
---
## ๐Ÿ”ง Setup
### 1. Use Same Database
The replicator uses your existing Postgres database:
```env
DATABASE_URL=postgresql://...
```
### 2. Query with Drizzle
```typescript
import { getDb } from '@/lib/db'
import { sql } from 'drizzle-orm'
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT * FROM fnames WHERE username = 'dwr'
`)
```
---
## ๐Ÿ“ˆ Performance
### Indexes
The replicator has built-in indexes:
- `fnames.username` - Fast username lookup
- `fnames.fid` - Fast FID lookup
- `casts.fid` - Fast user casts
- `signers.fid` - Fast signer lookup
### Caching
```typescript
// Cache username lookups
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 queryDatabase(username)
cache.set(username, { ...result, timestamp: Date.now() })
return result
}
```
---
## ๐ŸŽฏ Benefits
### vs Creating New Accounts
| Feature | New Accounts | Replicator |
|---------|--------------|------------|
| User Cost | $5 | $0 |
| Setup Time | 30s | 0s |
| Maintenance | High | Low |
| Data Access | Limited | Full |
### vs Fname Registry API
| Feature | API | Replicator |
|---------|-----|------------|
| Speed | Slow (HTTP) | Fast (SQL) |
| Queries | Limited | Unlimited |
| Rate Limits | Yes | No |
| Offline | No | Yes |
---
## ๐Ÿ” Advanced Queries
### Get User Activity
```sql
SELECT
c.text,
c.timestamp,
fn.username
FROM casts c
JOIN fnames fn ON c.fid = fn.fid
WHERE c.fid = 1
AND c.deleted_at IS NULL
ORDER BY c.timestamp DESC
LIMIT 10
```
### Find Active Users
```sql
SELECT
fn.fid,
fn.username,
COUNT(c.hash) as cast_count
FROM fnames fn
JOIN casts c ON fn.fid = c.fid
WHERE c.timestamp > NOW() - INTERVAL '7 days'
AND c.deleted_at IS NULL
GROUP BY fn.fid, fn.username
ORDER BY cast_count DESC
LIMIT 100
```
### Get User's Network
```sql
-- Users mentioned by FID 1
SELECT DISTINCT
fn.fid,
fn.username
FROM casts c
CROSS JOIN LATERAL unnest(c.mentions) AS mention_fid
JOIN fnames fn ON fn.fid = mention_fid
WHERE c.fid = 1
AND c.deleted_at IS NULL
```
---
## ๐Ÿ“Š Table Schema Reference
### fids
- `fid` (bigint) - Primary key
- `registered_at` (timestamp) - Registration date
- `custody_address` (bytea) - Owner address
- `recovery_address` (bytea) - Recovery address
### fnames
- `fid` (bigint) - User's FID
- `username` (text) - Username (fname or ENS)
- `type` (smallint) - 0=fname, 1=ENS
- `deleted_at` (timestamp) - Soft delete
### casts
- `fid` (bigint) - Author FID
- `hash` (bytea) - Cast hash
- `text` (text) - Cast content
- `timestamp` (timestamp) - Post time
- `mentions` (json) - Mentioned FIDs
- `embeds` (json) - Embedded URLs
- `deleted_at` (timestamp) - Soft delete
### signers
- `fid` (bigint) - Owner FID
- `key` (bytea) - Public key
- `key_type` (smallint) - Key type
- `added_at` (timestamp) - Added date
- `removed_at` (timestamp) - Removed date
- `requester_fid` (bigint) - App FID
---
## โœ… Production Checklist
- [x] Replicator queries implemented
- [x] Username lookup working
- [x] User search working
- [x] Profile queries working
- [ ] Caching implemented
- [ ] Indexes verified
- [ ] Performance tested
---
## ๐ŸŽ‰ Summary
**Use Replicator Instead of:**
- โŒ Creating new accounts ($5 per user)
- โŒ Fname Registry API (rate limited)
- โŒ Hub gRPC calls (complex)
**Benefits:**
- โœ… Free for users
- โœ… Fast SQL queries
- โœ… Full network data
- โœ… No rate limits
- โœ… Simple implementation
**PollCelo uses existing Farcaster accounts via replicator! ๐Ÿš€**