Production-ready, Farcaster client compatible and web application deployed on Base Network. Provides onchain asset management for NFT-based plants and lands with smart wallet support, autonomous agent actions via Coinbase CDP Spend Permissions, real-time chat infrastructure, and comprehensive reliability features.
- Platform: Dual-deployment architecture supporting Farcaster Mini App and standalone web application.
- Agent System: Coinbase CDP Smart Account implementation with Spend Permissions for delegated transaction execution and comprehensive permission validation.
- Blockchain Integration: Viem-based transaction layer with Uniswap V2-compatible swap routing on Base Network.
- Frontend Stack: React 19 with Next.js 15 App Router, Tailwind CSS 4, Radix UI primitives, WCAG 2.1 accessibility compliance.
- Authentication: Multi-provider wallet support (Privy embedded wallets, EOA, Farcaster embedded), Wagmi hooks, OnchainKit MiniKit integration, ERC-4337 smart wallet detection, optional paymaster sponsorship.
- Gamification Engine: Daily mission tracking, streak persistence, monthly leaderboard aggregation with admin reset capabilities.
- Communication Infrastructure: Redis-backed public chat with rate limiting and spam detection, OpenAI-powered AI assistant, Agent mode with tool-calling capabilities, administrative moderation interface.
- Security Architecture: Multi-endpoint RPC failover, Content Security Policy enforcement, CORS with origin validation, IP-based rate limiting with timing-attack mitigation, structured audit logging.
- Notification System: Farcaster Mini App push notifications via Neynar v2 API for transaction confirmations and time-sensitive alerts.
- Framework: Next.js 16, React 19.2
- UI: Tailwind CSS 4.1, Radix UI, Lucide React, custom pixel art icons
- Web3: Viem, Wagmi, Coinbase OnchainKit, Coinbase CDP SDK
- AI: Vercel AI SDK 4.3.19,
@ai-sdk/openai, optional Anthropic/Claude - Data: Redis/KV (Upstash compatible) for invites, chat, usage, audit logs, feedback, broadcasts
- Mini App:
@farcaster/miniapp-sdkwith manifest and notifications (Neynar v2 delivery) - Scheduler: Upstash QStash (HTTP cron) to trigger backend checks
- Analytics: Vercel Analytics, Vercel Speed Insights
- Authentication: Privy, Coinbase Wallet SDK
Key directories and files:
app/: Next.js routes (pages + API)app/.well-known/farcaster.json/route.ts: Farcaster Mini App manifest (icon/hero/splash, embeds, webhook, association)app/admin/*: Admin dashboard (invites, chat moderation, AI moderation, gamification)app/api/*: Server routes for chat, AI, agent, invites, staking, swap, notify, webhook, gamification, notifications cron/admin, feedback, broadcast
components/: UI, transactions, chat, tutorial, dialogs, loaders, theme, feedback, broadcasthooks/: UX and platform hooks (Farcaster, keyboard, countdown, auto‑connect)lib/: Core logic (contracts, env, AI, invites, gamification, redis, logger, wallet contexts)public/: Static assets (icons, fonts, ABIs, images)middleware.ts: Global CORS, CSP, and security headers
- Resilient Viem transport configuration with multi-endpoint RPC failover and exponential backoff retry logic.
- Contract interface abstractions in
lib/contracts.ts:PIXOTCHI_NFT_ADDRESS(ERC-721),PIXOTCHI_TOKEN_ADDRESS(SEED ERC-20),LEAF(ERC-20),STAKE(staking contract),UNISWAP_ROUTER_ADDRESS(AMM integration)
- Transaction helpers: NFT minting, token approvals, staking operations, marketplace item purchases, land/building management, token swaps, activity logging.
- Asset Transfer System: Bulk transfer capabilities for plants and lands with batch router integration for efficient multi-NFT transfers.
- Coinbase CDP Smart Account with ERC-7715 Spend Permission delegation for autonomous transaction execution.
- Supported operations: ZEST strain minting (strain ID 4, 10 SEED per NFT, maximum 5 NFTs per transaction).
- API surface
/api/agent/*:GET|POST /api/agent/wallet– Smart Account initialization and wallet bootstrapGET /api/agent/config– Agent configuration and operational parametersGET /api/agent/config/suggest-allowance– Permission allowance calculationGET /api/agent/permission/summary?address=0x..– Permission enumeration and statusPOST /api/agent/permission/validate– Pre-execution permission validationPOST /api/agent/mint– Atomic approve-mint-transfer transaction sequencePOST /api/agent/chat– LLM-driven tool-calling interface with estimation and confirmation flowPOST /api/agent/test-conversation– Integration testing endpoint
- Client implementation:
components/chat/AgentPermissionsPanel.tsxfor permission management interface.
- Invite code generation and validation with daily issuance caps, expiration enforcement, self-invite prevention, and user validation pipeline.
- Administrative interface for code lifecycle management, statistical analysis, bulk generation, cleanup operations, and audit trail persistence.
- Redis-backed message persistence with per-address rate limiting and duplicate message detection.
- Administrative moderation dashboard with message listing, selective/bulk deletion, and usage analytics.
- Multi-provider architecture (OpenAI/Anthropic) with runtime model selection, automatic retry with exponential backoff, request timeout enforcement, and usage/cost tracking.
- Conversation management with persistent history, automatic title generation, administrative list/fetch/delete operations, and aggregated usage metrics.
- Daily mission completion tracking with point attribution, consecutive day streak persistence, and monthly leaderboard aggregation.
- Administrative reset endpoints with granular scope (streaks/missions/all) and real-time leaderboard visualization dashboard.
- SEED token staking with approve-stake-claim workflow, marketplace order creation and fulfillment with dynamic price quotes, land building upgrades (LEAF cost), production acceleration (SEED cost), yield claiming, and quest progression.
- Manifest at
/.well-known/farcaster.jsonwith metadata, embed URL allowlist, and webhook configuration. OpenGraph andfc:miniapp/fc:framemetadata inapp/layout.tsx. - Push notification delivery via
/api/notifyendpoint; token lifecycle management via/api/webhookwith signature verification (Farcaster JSON signatures and HMAC fallback). Delivery orchestrated through Neynar v2 API. - Enhanced Context Handling: Comprehensive Farcaster context extraction with proper null/undefined handling, safe-area insets application, and platform detection.
- Interactive Tutorial System: Slideshow-based onboarding with step-by-step guidance for new users.
- Theme System: 8 customizable themes (light, dark, green, yellow, red, pink, blue, violet) with persistent user preferences.
- Mobile Optimization: Keyboard-aware UI, viewport height management, and touch-friendly navigation.
- Error Boundaries: Comprehensive error handling with graceful fallbacks and user-friendly error messages.
- Performance Optimizations: Code splitting, intelligent tab prefetching, and optimized asset loading.
- User Feedback Collection: In-app feedback submission with Farcaster context capture, wallet type detection, and 90-day data retention.
- Broadcast Message System: Admin-controlled in-app messaging with priority levels, expiration settings, and engagement tracking.
- Enhanced Chat Infrastructure: Multi-mode chat system (public, AI assistant, agent mode) with improved moderation tools.
- Tab-Based Navigation: 6 main tabs (Farm, Mint, Activity, Ranking, Swap, About) with intelligent prefetching and code splitting.
- Plant & Land Management: Comprehensive NFT management with shop items, garden accessories, building upgrades, and quest systems.
- Real-Time Status Bar: Global balance display (SEED, LEAF, ETH) with staking integration and transaction status.
- Wallet Profile System: Detailed wallet information display with Farcaster context, smart wallet status, and transaction history.
- Responsive Design: Mobile-first approach with keyboard awareness, viewport optimization, and touch-friendly interactions.
- Centralized RPC configuration in
lib/env-config.ts#getRpcConfig()with multi-endpoint fallback transport, automatic endpoint rotation, and exponential backoff on failures.
- Per-address rate limiting on public and AI chat endpoints with Redis-backed token buckets and duplicate message detection.
- Administrative endpoint protection: IP-based rate limiting (10 attempts per 15-minute window) with constant-time comparison (
crypto.timingSafeEqual) to prevent timing attacks.
- Dynamic CORS configuration in
middleware.tswith origin-specific policies for public APIs and strict admin endpoint allowlist. Global OPTIONS handler for preflight requests. - Content Security Policy with explicit host allowlisting for scripts, styles, connect sources, and frame ancestors. Additional security headers: X-Frame-Options, X-Content-Type-Options, Referrer-Policy.
- Redis client with JSON serialization safety, key namespace prefixing, and non-blocking connectivity validation.
- Structured logging infrastructure with request correlation IDs, administrative audit logs with Time-To-Live expiration, and rolling history retention.
- Notification dashboard aggregates delivery metrics, batch history, eligible user counts, and scheduled cron execution timestamps.
- Backend scheduled tasks use dedicated public Base RPC endpoints to isolate from application RPC pools.
All routes are under /api/*.
POST /api/invite/generate– Generate invite code with expiration and usage limitsPOST /api/invite/validate– Validate invite code without consumptionPOST /api/invite/use– Consume invite code and mark user as validatedGET|POST /api/invite/stats– Retrieve user statistics and invite historyPOST /api/invite/user-codes– List invite codes created by specific user- Admin (Bearer
ADMIN_INVITE_KEY, allowed origin):GET /api/invite/admin/stats– Global invite system statisticsGET /api/invite/admin/list– List all invite codes with filtersPOST /api/invite/admin/generate– Administrative bulk code generationPOST /api/invite/admin/cleanup– Cleanup expired or invalid codes
GET /api/chat/messages?limit=50– Retrieve recent public chat messagesPOST /api/chat/send– Send message to public chat with rate limiting- Admin:
GET /api/chat/admin/messages– List all messages with metadataDELETE /api/chat/admin/delete– Delete specific or all messages
GET /api/chat/ai/messages?address=0x..[&conversationId=..][&limit=50]– Retrieve conversation messages for addressPOST /api/chat/ai/send– Send message to AI assistant with context- Admin:
GET /api/chat/ai/admin/conversations?includeStats=true– List all conversations with usage statisticsGET /api/chat/ai/admin/messages?conversationId=..[&limit=100]– Retrieve messages from specific conversationDELETE /api/chat/ai/admin/conversations?conversationId=..– Delete conversation and associated messages
GET|POST /api/agent/wallet– Initialize or retrieve agent Smart Account walletGET /api/agent/config– Retrieve agent configuration and operational parametersGET /api/agent/config/suggest-allowance?mintsPerDay=10&strainId=4– Calculate suggested allowance for permission grantGET /api/agent/permission/summary?address=0x..– Enumerate all permissions granted to agent by addressPOST /api/agent/permission/validate– Validate permission allowance and time window constraintsPOST /api/agent/mint– Execute atomic approve-mint-transfer transaction sequencePOST /api/agent/chat– LLM-driven conversation interface with tool-calling (estimate, confirm, execute)POST /api/agent/test-conversation– End-to-end integration test for agent workflow
GET|POST /api/gamification/missions– Retrieve or update daily mission progressGET|POST /api/gamification/streak– Retrieve or update consecutive day streak- Admin (Bearer
ADMIN_INVITE_KEY, allowed origin):GET /api/gamification/leaderboards– Retrieve monthly leaderboard rankingsPOST /api/gamification/admin/reset– Reset user data (scope:streaks|missions|all)
GET /api/staking/balance?address=0x..– Retrieve staked SEED token balanceGET /api/staking/info?address=0x..– Retrieve staking position details and rewards
POST /api/swap– Execute token swap or retrieve quote ({ action: 'quote'|'execute', ethAmount, userAddress })
POST /api/notify– Send per-user Farcaster Mini App notification with type-specific metricsPOST /api/webhook– Process Farcaster Mini App webhook events (token add/remove) with signature verificationGET|POST /api/notifications/cron/plant-care– Scheduled task to check plant health and send batch alerts (invoked by QStash/Vercel Cron)- Admin:
GET /api/admin/notifications– Retrieve notification delivery statisticsDELETE /api/admin/notifications/reset?scope=all|fid|plant[&fid=..][&plantId=..]– Reset notification tracking data
POST /api/feedback/submit– Submit user feedback with context capture and validation- Admin:
GET /api/admin/feedback/list– Retrieve all feedback submissions with metadataPOST /api/admin/feedback/delete– Delete individual or all feedback entries
GET /api/broadcast/active– Retrieve active broadcast messages for displayPOST /api/broadcast/impression– Track message impression for analyticsPOST /api/broadcast/dismiss– Dismiss specific broadcast message- Admin:
GET /api/admin/broadcast– List all broadcast messages with statisticsPOST /api/admin/broadcast– Create new broadcast messagePUT /api/admin/broadcast– Update existing broadcast messageDELETE /api/admin/broadcast– Delete broadcast messagePOST /api/admin/broadcast/cleanup– Cleanup expired messages
GET /.well-known/farcaster.json– Serve Farcaster Mini App manifest (metadata, icons, webhooks)
Centralized in lib/env-config.ts and specific routes.
Prerequisites: Node.js 18+, npm or pnpm, Redis-compatible database (Upstash recommended).
npm installCreate .env.local with required variables:
- Base Network RPC endpoints
- Redis connection URL
ADMIN_INVITE_KEYfor administrative access- Optional: CDP credentials (
CDP_API_KEY_ID,CDP_API_KEY_SECRET,CDP_WALLET_SECRET) for Agent Mode - Optional: Privy credentials for embedded wallet support
npm run dev # Start Next.js development server with hot reload
npm run build # Generate production build with optimization
npm run start # Start production server (requires build)
npm run lint # Run ESLint static analysis- Path:
/admin/invite - Auth: Bearer key (
ADMIN_INVITE_KEY) with constant-time comparison, IP-based rate limiting (10 attempts/15min) - Enhanced Tabs: Overview, Codes, Users, Chat moderation, AI Chat moderation, Cleanup, Gamification (leaderboards + resets), RPC Status, Notifications, Feedback Management, Broadcast Messages
- Feedback Management: View, filter, and delete user feedback submissions with detailed context information and 90-day retention tracking.
- Broadcast System: Create, edit, and manage in-app broadcast messages with priority levels, expiration settings, and engagement analytics.
- Architecture: Request cancellation via AbortController, fail-closed rate limiting on Redis unavailability, structured error handling with detailed logging
- Configure environment variables:
- Server-side:
CDP_API_KEY_ID,CDP_API_KEY_SECRET,CDP_WALLET_SECRET - Client-side (optional):
NEXT_PUBLIC_CDP_CLIENT_API_KEYfor UI integration
- Server-side:
- Start application and navigate to Chat interface, enable Agent mode.
- Grant Spend Permission through the permission management panel, authorizing the agent's Smart Account to spend SEED tokens.
- Initiate minting request through natural language interface (e.g., "mint 1 ZEST").
- System provides cost estimation (10 SEED per NFT).
- Upon user confirmation, agent executes transaction sequence via
/api/agent/mintendpoint and transfers NFT to user wallet.
Troubleshooting endpoints:
GET /api/agent/permission/summary?address=0x..– Permission status verificationPOST /api/agent/permission/validate– Pre-execution validationPOST /api/agent/test-conversation– End-to-end integration test
- Strict CSP/security headers live in
proxy.ts(previously middleware.ts). If embedding new iframes/RPC domains, update CSP and CORS accordingly. - Prefer private Base RPCs with multiple endpoints for automatic failover.
- If using the paymaster, ensure
_PUBLIC_CDP_*are set; the app runs without it if omitted.
Licensed under the MIT License. See the LICENSE file at the project root for complete terms and conditions.
Built with ❤️ for the Pixotchi community