From 61076a2a666ff3eadf127a7912bf80b15b072c39 Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Fri, 8 Aug 2025 16:22:56 -0500 Subject: [PATCH 1/7] rename folder to miniapps --- .../base-app/build-with-minikit/debugging.mdx | 388 -------------- .../existing-app-integration.mdx | 477 ------------------ docs/base-app/build-with-minikit/overview.mdx | 446 ---------------- .../build-with-minikit/quickstart.mdx | 400 --------------- 4 files changed, 1711 deletions(-) delete mode 100644 docs/base-app/build-with-minikit/debugging.mdx delete mode 100644 docs/base-app/build-with-minikit/existing-app-integration.mdx delete mode 100644 docs/base-app/build-with-minikit/overview.mdx delete mode 100644 docs/base-app/build-with-minikit/quickstart.mdx diff --git a/docs/base-app/build-with-minikit/debugging.mdx b/docs/base-app/build-with-minikit/debugging.mdx deleted file mode 100644 index f3608b72e..000000000 --- a/docs/base-app/build-with-minikit/debugging.mdx +++ /dev/null @@ -1,388 +0,0 @@ ---- -title: Common Issues & Debugging -description: Frequent issues encountered during Mini App development and their solutions ---- - -## **Prerequisites & Setup Verification** - -Before debugging, ensure your Mini App has the foundational requirements in place. - -### **Required Files and Structure** - -Your Mini App must have these files in the correct locations: - -```html -your-domain.com/ -├── .well-known/ -│ └── farcaster.json # Required manifest file -├── your-app/ -│ ├── index.html # Your app entry point -│ └── ... # Your app files -``` - -### **Environment Setup Checklist** - -* Domain is accessible via HTTPS -* Manifest file exists at `/.well-known/farcaster.json` -* All image URLs are publicly accessible - -### **Basic Validation Steps** - -1. **Test manifest accessibility**: Visit `https://yourdomain.com/.well-known/farcaster.json` -2. **Validate JSON syntax**: Use [JSONLint](https://jsonlint.com/) to check your manifest -3. **Test app loading**: Ensure your app loads without console errors - - - -## **Quick Diagnostic Workflow** - - -**Is your app not appearing in search results?** → [Go to App Discovery & Indexing Issues](#1-app-discovery--indexing-issues) - -**Is your app not rendering as an embed when shared?** → [Go to Embed Rendering Issues](#3-embed-rendering-issues) - -**Are you having wallet connection problems?** → [Go to Wallet Connection Problems](#4-wallet-connection-problems) - -**Are you looking for testing tools ?** → [Go to Mobile Testing & Debugging](#6-mobile-testing--debugging) - -**Are changes not appearing after updates?** → [Go to Manifest Configuration Problems](#2-manifest-configuration-problems) - -**Does your app close unexpectedly during user interactions?** → [Go to Gesture Conflicts and App Dismissal Issues](#5-gesture-conflicts-and-app-dismissal-issues) - -## **Detailed Problem Solutions** - -## **1\. App Discovery & Indexing Issues** -**Problem**: Your Mini App doesn't appear in search results or app catalogs. - -**Root Cause**: Missing or incomplete manifest configuration. - -**Solution**: Ensure your manifest at `/.well-known/farcaster.json` includes all required fields: - - -```json -{ - "accountAssociation": { - "header": "eyJmaWQiOjkxNTIsInR5cGUiOiJjdXN0b2R5Iiwia2V5IjoiMHgwMmVmNzkwRGQ3OTkzQTM1ZkQ4NDdDMDUzRURkQUU5NDBEMDU1NTk2In0", - "payload": "eyJkb21haW4iOiJyZXdhcmRzLndhcnBjYXN0LmNvbSJ9", - "signature": "MHgxMGQwZGU4ZGYwZDUwZTdmMGIxN2YxMTU2NDI1MjRmZTY0MTUyZGU4ZGU1MWU0MThiYjU4ZjVmZmQxYjRjNDBiNGVlZTRhNDcwNmVmNjhlMzQ0ZGQ5MDBkYmQyMmNlMmVlZGY5ZGQ0N2JlNWRmNzMwYzUxNjE4OWVjZDJjY2Y0MDFj" - }, - "frame": { - "version": "1", - "name": "Example Mini App", - "iconUrl": "https://example.com/app.png", - "splashImageUrl": "https://example.com/logo.png", - "splashBackgroundColor": "#000000", - "homeUrl": "https://example.com", - "webhookUrl": "https://example.com/api/webhook", - "subtitle": "Example Mini App subtitle", - "description": "Example Mini App subtitle", - "screenshotUrls": [ - "https://example.com/screenshot1.png", - "https://example.com/screenshot2.png", - "https://example.com/screenshot3.png" - ], - "primaryCategory": "social", - "tags": [ - "example", - "mini app", - "coinbase wallet" - ], - "heroImageUrl": "https://example.com/og.png", - "tagline": "Example Mini App tagline", - "ogTitle": "Example Mini App", - "ogDescription": "Example Mini App description", - "ogImageUrl": "https://example.com/og.png" - } -} -``` - - In the Category section only the top 100 Mini Apps are shared. This is determined by activity such as user sharing. - - -**Critical Requirements**: - -* `primaryCategory` is required for searchability and category pages -* `accountAssociation` is required for verification - -**Reference**: [Complete manifest guide](https://docs.base.org/base-app/introduction/getting-started#manifest-file-configuration) - -### **App Indexing Requirements** - -**Problem**: Your app has a manifest but still doesn't appear in catalogs. - -**Solution**: Your Mini App must be shared in a post to be indexed. - -**Steps to Index Your App**: - -1. Complete your manifest setup -2. Share your Mini App URL in a post -3. Indexing can take up to 10 minutes -4. Verify appearance in app catalogs - -### **Caching Issues \- Changes Not Appearing** - -**Problem**: Updates to your manifest or app aren't showing up. - -**Why This Happens**: Farcaster clients cache manifest data for up to 24 hours for performance. - -**Solutions**: - -1. **Force Refresh**: Share your Mini App in a new cast to trigger cache refresh. This can take up to 10 minutes - - - -## **2\. Manifest Configuration Problems** - -### **Image Display Issues** - -**Problem**: App icons or images not displaying correctly. - -**Debug Steps**: - -1. Test image accessibility in incognito browser -2. Verify image format (PNG, JPG, WebP supported) -3. Check image dimensions (icons should be 200x200px minimum) -4. Ensure HTTPS URLs only - - -Manifest Embed Example - - - -## **3\. Embed Rendering Issues** - -### **Mini App Not Showing as Embed** - -**Problem**: Your Mini App URL doesn't render as a rich embed when shared. - -**Root Cause**: The embed configuration is not correct. - -**Solution**: Make sure the metadata in the head tag has the correct format in order to render correctly. In order for it to work properly for all clients please ensure you’re using the `name="fc:frame" meta tag.` - -```html - -``` - -**Debug Steps**: - -1. Test your URL in the [Mini App Embed Tool](https://farcaster.xyz/~/developers/mini-apps/embed) -2. Check meta tag is in `` section - -**Success Verification**: Your embed should show an image with a launch button when the URL is shared. - -## **4\. Wallet Connection Problems** - -### **Getting Connected Wallet** - -**Problem**: Unable to access user's wallet or connection status. - -### **Using MiniKit with OnchainKit (Recommended)** - -Minikit uses the Onchainkit wallet connect component that handles this behaviour of box for you without any additional set up. - -**Complete Setup**: - -```tsx -// 1. Install dependencies -// npm install @coinbase/onchainkit - -// 2. Set up your app with MiniKitProvider -import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; -import { base } from 'wagmi/chains'; - -function App() { - return ( - - - - ); -} - -// 3. Use wallet component -import { Wallet } from '@coinbase/onchainkit/wallet'; - -function YourAppContent() { - return ( -
- - {/* Your app content */} -
- ); -} -``` - -### **Using Wagmi Hooks Directly (Recommended)** - - -```tsx -import { useAccount } from 'wagmi'; - -function WalletInfo() { - const { address, isConnected } = useAccount(); - - if (!isConnected) { - return
Please connect your wallet
; - } - - return ( -
-
Status: Connected
-
Address: {address}
-
- ); -} -``` - -MiniKit includes wagmi providers by default \- don't add additional wagmi configuration. - - -**Error Handling**: - -```tsx -import { useAccount, useConnect } from 'wagmi'; - -function WalletConnection() { - const { address, isConnected } = useAccount(); - const { connect, connectors, error, isLoading } = useConnect(); - - if (error) { - return
Connection error: {error.message}
; - } - - if (isLoading) { - return
Connecting...
; - } - - if (!isConnected) { - return ( - - ); - } - - return
Connected: {address}
; -} -``` - -## **5\. Gesture Conflicts and App Dismissal Issues** - -**Problem**: App closes when users swipe, drag, or perform touch gestures. - -**Symptoms**: - -* Mini App closes when users swipe, drag, or perform touch gestures -* App dismisses during game interactions or custom navigation -* Users can't complete multi-step touch interactions - -**Root Cause**: Mini Apps run in modal containers where native gestures (swipes, taps outside the app area) automatically close the app. If your app uses similar gestures, they conflict with these native dismissal behaviors. - -**Solution**: Disable native gestures when calling `sdk.actions.ready()`: - -```ts -// Instead of this: -await sdk.actions.ready(); - -// Use this if your app has gesture conflicts: -await sdk.actions.ready({ disableNativeGestures: true }); -``` - -## **6\. Mobile Testing & Debugging** - -### **Using Eruda for Mobile Debug** - -**Problem**: Difficulty debugging Mini Apps on mobile devices. - -**Setup**: - -```html - - - -``` - - If you are testing specific enviornment behaviour - you can use clientFid :309857 - - -**How to Use**: - -1. Add the script to your app -2. Open your Mini App on mobile (cast the app in a DM to yourself) -3. Look for the Eruda debugging panel icon (usually bottom-right) -4. Access console, network, elements, and other debugging tools - -**Mobile Testing Workflow**: - -1. **Local Testing**: Use ngrok or similar to expose localhost -2. **Cast in DM**: Share your app URL in a DM to yourself -3. **Test Different Clients**: Test in Warpcast mobile and other Farcaster clients -4. **Check Different Devices**: Test on both iOS and Android if possible - - -Remove Eruda before production deployment. - - -## **Advanced Troubleshooting** - -### **AI-Assisted Debugging** - -**Using Coinbase Wallet Compatibility Validator**: - -The Coinbase Wallet team provides an AI-powered validation tool to check Mini App compatibility. - -**How to Use**: - -1. Use the validator prompt: [CBW MiniApp Validator](https://raw.githubusercontent.com/base/demos/refs/heads/master/minikit/mini-app-help/validate.txt) -2. In your preferred AI code editor (Cursor, etc.): - * Add the validator file to your project context - * Ask the AI: "Please validate my Mini App code using the CBW validator guidelines" -3. The AI will return a report of any unsupported actions or compatibility issues - -**What it Checks**: - -* Unsupported SDK methods -* Coinbase Wallet specific limitations - -## **Success Verification** - -### **Testing Checklist** - -Before deploying your Mini App, verify these items work correctly: - -**Basic Functionality**: - -- [ ] App loads without console errors -- [ ] All images display correctly -- [ ] Wallet connection works -- [ ] Core app functionality works as expected - -**Discovery & Sharing**: - -- [ ] Manifest file is accessible at `/.well-known/farcaster.json` -- [ ] App appears in embed when URL is shared -- [ ] App appears in search results (after posting) -- [ ] All required manifest fields are present - -## **Getting Additional Help** - -If you're still experiencing issues after following this guide: - -* [**Mini App Debug Tool**](https://farcaster.xyz/~/developers) \- Test your Mini App functionality -* [**Mini App Embed Tool**](https://farcaster.xyz/~/developers/mini-apps/embed) \- Preview how embeds will appear -* [**JSONLint**](https://jsonlint.com/) \- Validate JSON syntax -* [**Eruda**](https://github.com/liriliri/eruda) \- Mobile debugging console -* [Base Discord](https://discord.com/channels/1067165013397213286/1387875275756408883) \- \#minikit channel - - diff --git a/docs/base-app/build-with-minikit/existing-app-integration.mdx b/docs/base-app/build-with-minikit/existing-app-integration.mdx deleted file mode 100644 index 2d3317efc..000000000 --- a/docs/base-app/build-with-minikit/existing-app-integration.mdx +++ /dev/null @@ -1,477 +0,0 @@ ---- -title: Integrating MiniKit with Existing Applications -description: Guide for integrating MiniKit into an existing Next.js project with installation, provider setup, and environment configuration ---- - - -This guide helps developers integrate MiniKit into an existing Next.js project. It includes installation steps, provider setup and environment configuration. - - -This guide assumes you want to add MiniKit to an existing application. For new projects, use the [MiniKit CLI](/base-app/build-with-minikit/quickstart) for automatic setup. - - -## Prerequisites - -Before you begin, confirm the following: - - - -You are using a Next.js project with the `app/` directory structure (App Router). - - - -Your app is deployed and publicly accessible (e.g. via Vercel) with HTTPS enabled. - - - -You have an active Farcaster account for testing and access to your custody wallet. - - - -Sign up for a [Coinbase Developer Platform](https://portal.cdp.coinbase.com/) to retrieve your CDP API Key. - - - -## Integration Steps - - - -MiniKit is available as part of OnchainKit. - -```shell -npm install @coinbase/onchainkit -``` - - -Verify installation by checking that `@coinbase/onchainkit` appears in your `package.json`. - - - - -Create and use the `MiniKitProvider` to initialise SDK context for your application. - -**File: `providers/MiniKitProvider.tsx`** - -```jsx -'use client'; - -import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; -import { ReactNode } from 'react'; -import { base } from 'wagmi/chains'; - -export function MiniKitContextProvider({ children }: { children: ReactNode }) { - return ( - - {children} - - ); -} -``` - -Then wrap your app in `app/layout.tsx`: - -```jsx -import { MiniKitContextProvider } from '@/providers/MiniKitProvider'; - -export default function RootLayout({ children }: { children: React.ReactNode }) { - return ( - - - - {children} - - - - ); -} -``` - - -The provider automatically configures wagmi and react-query, and sets up connectors to use Farcaster when available. - - - - -Use the `useMiniKit` hook to access the frame context and trigger readiness. - -**File: `app/page.tsx`** - -```jsx -'use client'; - -import { useEffect, useState } from 'react'; -import { useMiniKit } from '@coinbase/onchainkit/minikit'; - -export default function HomePage() { - const { setFrameReady, isFrameReady } = useMiniKit(); - - // The setFrameReady() function is called when your mini-app is ready to be shown - useEffect(() => { - if (!isFrameReady) { - setFrameReady(); - } - }, [setFrameReady, isFrameReady]); - - return
Your app content goes here
; -} -``` - - -The `setFrameReady()` function removes the splash screen and shows your application. Only call this when your app is fully loaded and ready for user interaction. - -
- - -Add the required environment variables to your project and deployment platform. - - - -These variables are essential for your MiniKit app to function: - - -The name of your Mini App as it appears to users - - - -The deployed URL of your application (must be HTTPS) - - - -Your Coinbase Developer Platform API key - - - -Generated during manifest creation for account association - - - -Generated during manifest creation for account association - - - -Generated during manifest creation for account association - - - - -These variables enhance your app's appearance and metadata: - - -URL to your app's icon (recommended: 48x48px PNG) - - - -Brief subtitle shown in app listings - - - -Detailed description of your app's functionality - - - -URL to splash screen image shown during app loading - - - -Hex color code for splash screen background (e.g., "#000000") - - - -Primary category for app discovery (e.g., "social", "gaming", "utility") - - - -Hero image URL displayed in cast previews - - - -Short, compelling tagline for your app - - - -Open Graph title for social media sharing - - - -Open Graph description for social media sharing - - - -Open Graph image URL for social media previews - - - - - -Don't forget to include all referenced images in your `public/` folder and ensure they're accessible via HTTPS. - - - - -Use the OnchainKit CLI to generate account association credentials and update your environment variables. - -```shell -npx create-onchain --manifest -``` - - -**Important:** The wallet you connect must be your Farcaster custody wallet. You can import this wallet using the recovery phrase found in Farcaster under Settings → Advanced → Farcaster recovery phrase. - - -Follow these substeps: - -1. Connect your Farcaster custody wallet -2. Add your deployed Vercel URL -3. Sign the manifest to generate association credentials -4. The CLI will automatically update your local `.env` file - - -After running this command locally, remember to update your deployment platform's environment variables with the generated `FARCASTER_HEADER`, `FARCASTER_PAYLOAD`, and `FARCASTER_SIGNATURE` values. - - - - -The farcaster.json file contains metadata that allows clients to identify your Mini App and its capabilities. - -Create a route handler at `app/.well-known/farcaster.json/route.ts`: - -```typescript -function withValidProperties( - properties: Record, -) { - return Object.fromEntries( - Object.entries(properties).filter(([key, value]) => { - if (Array.isArray(value)) { - return value.length > 0; - } - return !!value; - }), - ); -} - -export async function GET() { - const URL = process.env.NEXT_PUBLIC_URL; - - return Response.json({ - accountAssociation: { - header: process.env.FARCASTER_HEADER, - payload: process.env.FARCASTER_PAYLOAD, - signature: process.env.FARCASTER_SIGNATURE, - }, - frame: withValidProperties({ - version: "1", - name: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, - subtitle: process.env.NEXT_PUBLIC_APP_SUBTITLE, - description: process.env.NEXT_PUBLIC_APP_DESCRIPTION, - screenshotUrls: [], - iconUrl: process.env.NEXT_PUBLIC_APP_ICON, - splashImageUrl: process.env.NEXT_PUBLIC_APP_SPLASH_IMAGE, - splashBackgroundColor: process.env.NEXT_PUBLIC_SPLASH_BACKGROUND_COLOR, - homeUrl: URL, - webhookUrl: `${URL}/api/webhook`, - primaryCategory: process.env.NEXT_PUBLIC_APP_PRIMARY_CATEGORY, - tags: [], - heroImageUrl: process.env.NEXT_PUBLIC_APP_HERO_IMAGE, - tagline: process.env.NEXT_PUBLIC_APP_TAGLINE, - ogTitle: process.env.NEXT_PUBLIC_APP_OG_TITLE, - ogDescription: process.env.NEXT_PUBLIC_APP_OG_DESCRIPTION, - ogImageUrl: process.env.NEXT_PUBLIC_APP_OG_IMAGE, - // use only while testing - "noindex": true - }), - }); -} -``` - - While testing your Mini App please add noIndex:true to your manifest - this is so the app is not indexed while in developement. - - - -Test this endpoint by visiting `https://yourdomain.com/.well-known/farcaster.json` to ensure it returns valid JSON. - - - - -Configure the metadata that clients use to render your Mini App in posts and generate preview cards. - -**File: `app/layout.tsx`** - -```typescript -import { Metadata } from 'next'; - -export async function generateMetadata(): Promise { - const URL = process.env.NEXT_PUBLIC_URL; - return { - title: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, - description: - "Generated by `create-onchain --mini`, a Next.js template for MiniKit", - other: { - "fc:frame": JSON.stringify({ - version: "next", - imageUrl: process.env.NEXT_PUBLIC_APP_HERO_IMAGE, - button: { - title: `Launch ${process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME}`, - action: { - type: "launch_frame", - name: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, - url: URL, - splashImageUrl: process.env.NEXT_PUBLIC_SPLASH_IMAGE, - splashBackgroundColor: - process.env.NEXT_PUBLIC_SPLASH_BACKGROUND_COLOR, - }, - }, - }), - }, - }; -} -``` - - -All image and API URLs used here must be publicly accessible via HTTPS. Test each URL in your browser before deploying. - - - - -Before sharing your Mini App, validate that everything is working correctly. - - - -Verify the following before going live: - -- ✅ App is deployed at a public HTTPS domain -- ✅ All environment variables are set on your deployment platform -- ✅ All referenced images are accessible in your `public/` folder -- ✅ The `.well-known/farcaster.json` endpoint returns valid JSON -- ✅ Your app loads without errors in a browser - - - - -Use these tools to test your configuration: - -**Manifest Validator:** -``` -https://farcaster.xyz/~/developers/mini-apps/manifest -``` - -This tool validates: -- Manifest can be loaded successfully -- Frame metadata is correctly formatted -- Button actions and preview images are functioning -- Account association is properly configured - -**Manual Testing:** -1. Visit your deployed URL directly in a browser -2. Check browser console for any errors -3. Verify the MiniKit context loads properly -4. Test frame readiness functionality - - - - -Once validation passes: - -1. **Create a cast** with your app's URL in Farcaster -2. **Verify the preview** displays your hero image and launch button -3. **Test the launch experience** by clicking the button -4. **Share with others** for feedback and testing - - -If your app doesn't render as an embed, double-check your manifest configuration and ensure all URLs are publicly accessible. - - - - - - -If you encounter issues, check our comprehensive debugging guide for common problems and solutions. - - -
- -## Understanding MiniKit Context - -### What `useMiniKit` Gives You - -The `useMiniKit()` hook provides access to everything your Mini App needs to understand the Farcaster session: - - -The Farcaster ID of the current user - - - -Whether the user has added your Mini App to their account - - - -Where the app was launched from (e.g., "cast", "launcher", "notification") - - - -Whether your app has called `setFrameReady()` and is ready to be shown - - - -Function to call when your app is fully loaded and ready for interaction - - -You can use this context to personalize the experience, trigger different flows, or track user behavior. - -## Available MiniKit Hooks - -MiniKit provides a comprehensive set of hooks designed to help you build rich, social experiences: - - - -Send in-app and push notifications to users who have added your frame - - - -Allow users to save your mini app to their Farcaster client for easy access - - - -Programmatically close the mini app frame when appropriate - - - -Open external URLs from within the frame context - - - -Configure and handle primary button interactions - - - -Navigate users to Farcaster profiles (their own or others) - - - -Handle Farcaster authentication and sign-in flows - - - - -Learn about all available MiniKit hooks, their parameters, and usage examples - - -## Next Steps - -Now that your Mini App is integrated and deployed: - - - -Share your Mini App URL in Farcaster and test all functionality with real users. - - - -Use analytics to understand how users interact with your app and identify areas for improvement. - - - -Consider adding notifications, authentication, or other MiniKit hooks to enhance the user experience. - - diff --git a/docs/base-app/build-with-minikit/overview.mdx b/docs/base-app/build-with-minikit/overview.mdx deleted file mode 100644 index 206fc7500..000000000 --- a/docs/base-app/build-with-minikit/overview.mdx +++ /dev/null @@ -1,446 +0,0 @@ ---- -title: Overview -description: Easiest way to build Mini Apps on Base ---- - - -MiniKit - - -MiniKit is easiest way to build Mini Apps on Base, allowing developers to easily build applications without needing to know the details of the SDK implementation. It integrates seamlessly with OnchainKit components and provides Coinbase Wallet-specific hooks. - -## Why MiniKit? - -MiniKit streamlines mini-app development by providing a comprehensive toolkit that makes complex Farcaster SDK interactions intuitive: - - - -Build apps with minimal knowledge of the Farcaster SDK - - - -Access Coinbase Wallet-specific hooks - - - -Use [OnchainKit](https://onchainkit.xyz/) components out of the box with MiniKit - - - -CLI tool for quick project scaffolding with webhooks and notifications - - - -## Use Cases - - - - - - - -And many more possibilities! - -## Quick Start - -The fastest way to get started with MiniKit is to use the CLI to bootstrap a new project: - -```bash -npx create-onchain --mini -``` - - -You can also follow our comprehensive Quick Start guide for detailed setup instructions - - -This command will: - - - -Set up a new project with both frontend and backend components - - - -Configure webhooks and notifications - - - -Set up account association generation - - - -Create a demo app showcasing onchain abilities using OnchainKit - - - -After running the command, follow the prompts to configure your project. - - -We recommend using [Vercel](https://vercel.com) to deploy your MiniKit app, as it integrates seamlessly with the upstash/redis backend required for webhooks, and notifications. The CLI will guide you through setting up the necessary environment variables for your Redis database. - - -## Provider - -The `MiniKitProvider` wraps your application and provides global access to the SDK's context. It handles initialization, events, and automatically applies client safeAreaInsets to ensure your app doesn't overlap parent application elements. - -```tsx -import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; - -function App({ children }) { - return ( - - {children} - - ); -} -``` - -### Props - -The `MiniKitProvider` accepts the following props: - - -React components to be wrapped by the provider - - - -Optional URL to override the default `/api/notification` proxy - - - -All props from `OnchainKitProvider` are also supported - - -The provider sets up wagmi and react-query providers automatically. It configures connectors to use the Farcaster connector if `sdk.context` is set, with a fallback to CoinbaseWallet. This allows the same application to run both as a Mini App and as a standalone application. - -## Hooks - -MiniKit provides several utility hooks that wrap the SDK functionality, making it easy to access different features. - -### useMiniKit - -This hook handles initialization of the application and provides access to the SDK context. - -```tsx -const { setFrameReady, isFrameReady, context, updateClientContext, notificationProxyUrl } = useMiniKit(); - -// Call setFrameReady() when your app is ready to be shown -useEffect(() => { - if (!isFrameReady) { - setFrameReady(); - } -}, [isFrameReady, setFrameReady]); -``` - -**Returns:** - - -Removes splash screen and shows the application - - - -Whether the app is ready to be shown - - - -The current frame context - - - -Update client context - - - -The notification proxy URL - - -### useAddFrame - -This hook adds a Mini App to the user's list of Mini Apps and returns notification details. - -```tsx -const addFrame = useAddFrame(); - -// Usage -const handleAddFrame = async () => { - const result = await addFrame(); - if (result) { - console.log('Frame added:', result.url, result.token); - } -}; -``` - -**Returns:** - - -Function that adds frame and returns notification details - - -### useNotification - -This hook allows sending notifications to users who have added your frame. It requires a token and URL, which are returned when a user adds your frame. - -```tsx -const sendNotification = useNotification(); - -// Usage -const handleSendNotification = () => { - sendNotification({ - title: 'New High Score!', - body: 'Congratulations on your new high score!' - }); -}; -``` - - -Notifications require a backend proxy to avoid CORS restrictions. The CLI automatically sets up this proxy at `/api/notification`, but you can override this in the `MiniKitProvider`. - - -### useOpenUrl - -This hook wraps `sdk.actions.openUrl` and falls back to `window.open` when outside a frame context. - -```tsx -const openUrl = useOpenUrl(); - -// Usage - -``` - -### useClose - -This hook wraps the `sdk.actions.close` functionality. - -```tsx -const close = useClose(); - -// Usage - -``` - -### useComposeCast - -The `useComposeCast` hook provides functionality to open the Farcaster compose interface with pre-filled content. - -```tsx -import { useComposeCast } from '@coinbase/onchainkit/minikit'; - -export default function ComposeCastButton() { - const { composeCast } = useComposeCast(); - - const handleCompose = () => { - composeCast({ - text: 'Just minted an awesome NFT using @coinbase OnchainKit! 🚀', - }); - }; - - const handleComposeWithEmbed = () => { - composeCast({ - text: 'Check out this amazing frame!', - embeds: ['https://your-frame-url.com'], - }); - }; - - return ( -
- - -
- ); -} -``` - -**Parameters:** -- `text: string` - The text content for the cast -- `embeds?: string[]` - Optional array of URLs to embed in the cast - -**Returns:** -- `composeCast: (params: ComposeCastParams) => void` - Function to open compose interface - -### useViewCast - -The `useViewCast` hook provides functionality to view a specific Farcaster cast by its hash. - -```tsx -import { useViewCast } from '@coinbase/onchainkit/minikit'; - -export default function ViewCastButton() { - const { viewCast } = useViewCast(); - - const handleViewCast = () => { - viewCast({ - hash: '0x32aed77ca61c92d253b98983f1e0fd20a8bd5745', - }); - }; - - const handleViewAnotherCast = () => { - viewCast({ - hash: '0x48f4d2c45e7b1a923d5c6f8e9a7b2c1d5e8f3a6b', - }); - }; - - return ( -
- - -
- ); -} -``` - -**Parameters:** -- `hash: string` - The hash of the cast to view - -**Returns:** -- `viewCast: (params: ViewCastParams) => void` - Function to view a specific cast - - -### usePrimaryButton - -This hook accepts primary button options and a callback which will be called on click. - -```tsx -usePrimaryButton( - { text: 'Submit Score' }, - () => { - // Handle button click - submitScore(); - } -); -``` - -### useViewProfile - -This hook wraps `sdk.actions.viewProfile`, accepting an FID but falling back to the client's FID. - -```tsx -const viewMyProfile = useViewProfile(); // Uses client's FID -const viewUserProfile = useViewProfile(123456); // Uses specified FID - -// Usage - - -``` - -### useAuthenticate - -This hook allows users to sign in with Farcaster. It wraps the SDK's signIn message, adding a default nonce and verification. - -```tsx -const { signIn } = useAuthenticate(); - -// Usage -const handleSignIn = async () => { - const result = await signIn({ - domain: 'your-domain.com', - siweUri: 'https://your-domain.com/login' - }); - - if (result) { - // Handle successful authentication - console.log('Authenticated:', result); - } -}; -``` - - -Authentication requires additional setup utilizing an auth framework like next/auth or manually integrating session storage and route/component authentication. - - -## CLI - -The MiniKit CLI is the easiest way to get started. It automatically creates a sample application that integrates different parts of the SDK and some OnchainKit components. - -```bash -npx create-onchain --mini -``` - -### Features - -The CLI creates an application with: - - - -Complete setup for adding Mini Apps, webhooks, and notifications using upstash/redis for data storage (compatible with Vercel). Requires users to sign up for an upstash/redis account and add their key and URL to the .env file. - - -The CLI creates both frontend and backend components to support adding Mini Apps, webhooks, and notifications. While a frontend-only option was considered, the ability to add Mini Apps and handle notifications requires backend support. If you don't need these features, you can easily remove the database and related routes after project creation. - - - - -Automatically generates valid account associations and configures the necessary environment variables. - - - -Sets up the required configuration file: - -```json -{ - "accountAssociation": { - "header": "eyJmaWQiOjgxODAyNiwidHlwZSI6ImN1c3RvZHkiLCJrZXkiOiIweDU4YjU1MTNjMzk5OTYzMjU0MjMzMmU0ZTJlRDAyOThFQzFmRjE4MzEifQ", - "payload": "eyJkb21haW4iOiI4MGI2LTI2MDAtMWYxOC0yNGM5LTYxMDUtNS0wLTQtNzA2Lm5ncm9rLWZyZWUuYXBwIn0", - "signature": "MHhmOGQ1YzQyMmU3ZTZlMWNhMzU1ZmNmN2ZjYzFmYjMyZWRhZmEyNWU1NjJiMzlhYzE4OWNlMmM5ODU3Y2JjZWViNzlkZTk2ZjhiNTc5NzZjMDM2NzM4Y2UwYjhhOGQxZmMyZDFhYzA2NTdiZTU5N2VhZjFhZDE1ODBmMGQyYjJhODFi" - }, - "frame": { - "version": "next", - "name": "MiniKit", - "iconUrl": "https://onchainkit.xyz/favicon/48x48.png?v4-19-24", - "splashImageUrl": "https://onchainkit.xyz/favicon/48x48.png?v4-19-24", - "splashBackgroundColor": "#000000", - "homeUrl": "https://your-domain.app/minikit" - } -} -``` - - - -Automatically sets up a proxy route at `/api/notification` used by the `useNotification` hook when sending notifications. - - - -Implements webhooks using the Farcaster key registry contract for verification. Allows applications to respond to events such as `FRAME_ADDED`. - - - -### Demo Application - -The CLI also creates a demo snake game application that showcases: - -- Buttons to add the frame and connect your wallet -- High score tracking with attestations using OnchainKit's `` component -- Score display using OnchainKit's `` components to resolve ENS names -- Notifications for high scores (rate limited to one every 30 seconds) - -## Next Steps - -Now that you have MiniKit set up, you can: - - - -Explore the demo application to understand how the hooks work - - - -Customize the application to fit your needs - - - -Deploy your application to a hosting provider like Vercel - - - -Enjoy building! diff --git a/docs/base-app/build-with-minikit/quickstart.mdx b/docs/base-app/build-with-minikit/quickstart.mdx deleted file mode 100644 index 2463ed189..000000000 --- a/docs/base-app/build-with-minikit/quickstart.mdx +++ /dev/null @@ -1,400 +0,0 @@ ---- -title: 'Quickstart' -description: 'Learn how to build mini apps on Base with MiniKit - from setup to deployment and advanced features' ---- - -This guide shows you how to get started with MiniKit, the easiest way to build mini apps on Base! It can also be used to update an existing standalone app to a mini app. We'll start by setting up the template project with the CLI tool and then explore both built-in and additional features of MiniKit. - -## Prerequisites - -Before you begin developing with MiniKit, you'll need: - -1. **Farcaster Account**: Create an account on [Farcaster](https://farcaster.xyz/) to test and deploy your Mini Apps. - -2. **Coinbase Developer Platform Account** (Optional): Sign up for a [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) account if you need CDP API key for additional functionalities. - -## What is a Mini App? - -A mini app is a lightweight web app that runs directly inside [Farcaster](https://docs.farcaster.xyz/developers/frames/v2/), without needing to open a browser or download anything. Built using familiar tools like Next.js and minikit, mini apps behave just like normal apps — but launch instantly from posts, making them feel native to the Farcaster experience. - -## Initial Setup - - - -```bash -npx create-onchain --mini -``` - - - -You can get a CDP API key by going to the [CDP Portal](https://www.coinbase.com/developer-platform) and navigating API Keys → Client API Key. - - - -You will be asked if you'd like to set up your manifest. You can skip the manifest setup step as we'll handle that separately once we know our project's URL. - - - -```bash Terminal -cd your-project-name -npm install -npm run dev -``` - - -These docs are LLM-friendly—reference [llms.txt](https://docs.base.org/base-app/build-with-minikit/llms.txt) in your code editor to streamline builds and prompt smarter. - - - - -## Testing Your Mini App - -To test your Mini App in Farcaster, you'll need a live URL. - -We recommend using [Vercel](https://vercel.com) to deploy your MiniKit app, as it integrates seamlessly with the upstash/redis backend required for stateful Mini Apps, webhooks, and notifications. - -Alternatively, you can use ngrok to tunnel your localhost to a live url. - - - - - -To successfully test your app, you'll need the paid version of ngrok. The free version has an approval screen which can break the frame manifest. Also the url for the free version will change every time requiring you to update the manifest each time you start a new ngrok tunnel. - - -1. Start your development server: - -```bash Terminal -npm run dev -``` - -2. Install and start ngrok to create a tunnel to your local server: - -```bash Terminal -# Install ngrok if you haven't already -npm install -g ngrok - -# Create a tunnel to your local server (assuming it's running on port 3000) -ngrok http 3000 -``` - -3. Copy the HTTPS URL provided by ngrok (e.g. `https://your-tunnel.ngrok.io`) - -4. Visit the [Farcaster Manifest Tool](https://farcaster.xyz/~/developers/mini-apps/manifest) - -5. Paste your ngrok URL into "Domain" and tap Submit - - - - -### Deploying to Vercel - - - -```bash -npm install -g vercel -``` - - - -```bash -vercel -``` - - - -You can use `vercel env add` to set these up via CLI: - -- NEXT_PUBLIC_CDP_CLIENT_API_KEY (from [CDP Portal](https://www.coinbase.com/developer-platform)) -- NEXT_PUBLIC_URL (deployed app URL) -- NEXT_PUBLIC_IMAGE_URL (optional) -- NEXT_PUBLIC_SPLASH_IMAGE_URL (optional) -- NEXT_PUBLIC_SPLASH_BACKGROUND_COLORs - - - -You can now test your mini app: - -1. Copy your deployed vercel URL -2. Visit the [Farcaster Manifest Tool](https://farcaster.xyz/~/developers/mini-apps/manifest) -3. Paste URL into "Domain" -4. Tap Submit - -## Exploring Built-in Features - -The template comes with several pre-implemented features. Let's explore where they are and how they work. - -### MiniKitProvider - -The `MiniKitProvider` is set up in your `providers.tsx` file. It wraps your application to handle initialization, events, and automatically applies client safeAreaInsets to ensure your app doesn't overlap parent application elements. - -```tsx app/providers.tsx -import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; - -export function Providers(props: { children: ReactNode }) { - return ( - - {props.children} - - ); -} -``` - -The MiniKitProvider also sets up your wagmi and react-query providers automatically, eliminating that initial setup work. - -### useMiniKit - -The `useMiniKit` hook is implemented in your main page component (`app/page.tsx`). It handles initialization of the frame and provides access to the SDK context. - -```tsx app/page.tsx -const { setFrameReady, isFrameReady, context } = useMiniKit(); - -// The setFrameReady() function is called when your mini-app is ready to be shown -useEffect(() => { - if (!isFrameReady) { - setFrameReady(); - } - }, [setFrameReady, isFrameReady]); -``` - -### Creating the Manifest - -The Frame Manifest is required in order for users to save the frame to their account. This means its also required to send notifications to the user. We initially skipped this step when setting up the app. Now that we know our vercel url, we can configure our manifest. - -To set up the manifest, run the following in your Terminal - -```bash Terminal -npx create-onchain --manifest -``` - -Enter `y` to proceed with the setup and your browser will open to the following page: - - -Manifest Setup - - - -The wallet that you connect must be your Farcaster custody wallet. You can import this wallet to your preferred wallet using the recovery phrase. You can find your recovery phrase in the Farcaster app under Settings → Advanced → Farcaster recovery phrase. - - -Once connected, add the vercel url and sign the manifest. This will automatically update your .env variables locally, but we'll need to update Vercel's .env variables. - -Create the following new .env variables in your vercel instance and paste the value you see in your local.env file: - - -Base64 encoded header from manifest generation - - - -Base64 encoded payload from manifest generation - - - -Signature from manifest generation - - -Now that the manifest is correctly set up, the Save Frame button in the template app should work. We'll explore that below. - - - While testing your Mini App please add noIndex:true to your manifest - this is so the app is not indexed while in developement. - - -### useAddFrame - -The `useAddFrame` hook is used to add your mini app to the user's list of mini apps. It's implemented in your main page component and displays a button in the top right allowing the user to add the mini app to their list. - -When a user adds the mini app, it returns a url and token, which is used for sending the user notifications. For this walkthrough we'll simply console.log those results to use them later when setting up notifications. - -```tsx app/page.tsx -const addFrame = useAddFrame() - -// Usage in a button click handler -const handleAddFrame = async () => { - const result = await addFrame() - if (result) { - console.log('Frame added:', result.url, result.token) - } -} -``` - - -In production, you'll want to save the url and token associated with each user in a persistent database so that you can send them notifications over time. - - -### useOpenUrl - -The `useOpenUrl` hook is used to open external URLs from within the frame. In the template, its used in the footer button which links to the MiniKit page. - -```tsx app/page.tsx -const openUrl = useOpenUrl() - -// Usage in a button click handler - - -// Then in the return function -
- -
-``` - -Now that we've reviewed the MiniKit template and the functionality already implemented, lets add some additional MiniKit features. - -## Additional MiniKit Features - -Now, let's implement additional hooks provided by the MiniKit library. We'll add these features one by one. - -### useClose - -First, let's add the ability to close the frame from within the interface: - -```tsx app/page.tsx -// Add useClose to the import list -import { useMinikit, useAddFrame, useOpenUrl, useClose } from '@coinbase/onchainkit/minikit' - -// Add the hook -const close = useClose() - -// Add the button in the header right after the `saveFrameButton` -
- {saveFrameButton} - -
-``` - - -If you reload the frame in the Farcaster dev tools preview, you'll now see the close button in the top right. - - -### usePrimaryButton - -The Primary Button is a button that always exists at the bottom of the frame. Its good for managing global state which is relevant throughout your mini app. - -For the template example, we'll use the Primary Button to Pause and Restart the game. The game state is managed within the `snake.tsx` component, and we can easily add the `usePrimaryButton` hook there since the MiniKit hooks are available throughout the app. - -```tsx app/components/snake.tsx -// add an import for usePrimaryButton -import {usePrimaryButton } from '@coinbase/onchainkit/minikit' - -// game state already exists, so we'll leverage that below. -usePrimaryButton( - {text: gameState == GameState.RUNNING ? 'PAUSE GAME' : 'START GAME'}, - () => { - setGameState(gameState == GameState.RUNNING ? GameState.PAUSED : GameState.RUNNING); - } -) -``` - - -You'll notice that adding the Primary button takes up space at the bottom of the frame, which causes the "BUILT ON BASE WITH MINIKIT" button to move upwards and overlap with the controls. -We can quickly fix that by changing the text to "BUILT WITH MINIKIT" and removing the `ml-4` style in the `className` of the ` -``` - -### useNotification - -One of the major benefits of mini apps is that you can send notifications to your users through their social app. - -Recall the token and url we saved in the [useAddFrame section](#useaddframe)? We'll use those now to send a user a notification. In this guide, we'll simply send a test notification unrelated to the game activity. - -```tsx app/page.tsx -//add useNotification to the import list -import {..., useNotification } from '@coinbase/onchainkit/minikit' - -// Add the hook -const sendNotification = useNotification() - -// Add the handler function -const handleSendNotification = async () => { - try { - await sendNotification({ - title: 'New High Score! 🎉', - body: 'Congratulations on achieving a new high score!' - }) - setTimeout(() => setNotificationSent(false), 30000) - } catch (error) { - console.error('Failed to send notification:', error) - } -} - -// Add the button in your UI -{context?.client.added && ( - -)} -``` - - -Notice that we first check if the user has added the frame to their list of mini apps before displaying the button. This is using the `context` object provided by `useMiniKit()`. If you don't see the button to send the notification, its likely because mini app hasn't been saved. - - -## Conclusion - -Congratulations, you've created your first mini app, set up the manifest, added key MiniKit hooks, and sent your users a notification! We're excited to see what you build with MiniKit! - - - -Learn more about MiniKit features and capabilities - - - -Design patterns for social mini apps - - From d7098b012c3e50d2b8011ffa3198c2d13e207675 Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Fri, 8 Aug 2025 16:23:29 -0500 Subject: [PATCH 2/7] renamed thinking social doc to grab user attention for viral apps --- docs/base-app/guides/thinking-social.mdx | 285 ----------------------- 1 file changed, 285 deletions(-) delete mode 100644 docs/base-app/guides/thinking-social.mdx diff --git a/docs/base-app/guides/thinking-social.mdx b/docs/base-app/guides/thinking-social.mdx deleted file mode 100644 index a2fe3f23c..000000000 --- a/docs/base-app/guides/thinking-social.mdx +++ /dev/null @@ -1,285 +0,0 @@ ---- -title: Thinking Social -description: Designing mini apps that people actually come back to ---- - - -**Designing mini apps that people actually come back to.** - -Most apps can launch. But few become part of someone's daily rhythm. -That's usually not a product problem. It's a people problem. - -Social mini apps live or die based on how they make people feel: seen, connected, curious or like they belong. That's not something you tack on — it's something you build in from the start. - -If you're designing for feed-based platforms (like Farcaster, Threads, or anything with posts, reactions, and reply chains), this guide will help you: - - - - - - - -## How to Use This Guide - -Welcome to your blueprint for designing social mini‑apps that people love to revisit. This guide is organized into distinct, actionable sections—each building on the last—to help you move from idea validation to deploying social features with purpose. - - - -Before writing a single line of code or sketching UI, use our four diagnostic questions to see if your concept naturally supports social behavior. Drop your one‑line idea into the supplied prompt to get clear insights on post frequency, social lift, content momentum, and emotional payoff. - - - -Analyze the responses. Identify which one or two social dimensions resonate most with your concept—whether it's habit formation, community spark, content growth, or emotional reward. The guide shows you how to validate and prioritize those dimensions before moving forward. - - - -See a worked example that demonstrates how to translate test results into a prototype feature. This mini case study will illustrate rapid iteration, metric considerations, and how to decide when you're ready to scale social elements. - - - -Dive into the heart of the guide—three social patterns designed to deepen engagement: - -- **Identity Playgrounds:** Customization and self‑expression -- **Co‑Creation Loops:** Collaboration and building on each other's posts -- **Long‑Term Rituals:** Scheduled, shared activities that foster habit and community - -Each pattern includes explanations, real‑world examples, and copy‑and‑paste prompts to spark your own brainstorming. - - - -Finish with a set of reflective questions and practical advice on measuring success. Use the closing prompts to refine your roadmap, plan experiments, and define key metrics for daily, weekly, and monthly engagement. - - - - -**Tips for Getting the Most Out of This Guide:** - -- **Iterate Quickly:** Treat prompts and patterns as hypotheses. Prototype fast, gather data, and refine. -- **Stay Human‑Centered:** At every stage, ask: "How will this make someone feel?" -- **Measure What Matters:** Define metrics for each dimension early—then use them to validate your choices. -- **Keep It Simple:** You don't need every pattern at once. Start with the one or two dimensions that align strongest with your concept. - - -## Pressure-test your idea - -Before you get into features or UI, take a step back. Ask whether your idea wants to be social — or if you're forcing it. These prompts are designed to give you structured, clear feedback if you drop them into a LLM or use them in your own reflection. - - -``` -Here's a one-line description of my app: [insert idea]. - -Evaluate it across these questions: - -1. Why would someone post here more than once? -2. Would the experience be better with another person involved? -3. What kind of content might naturally fill the feed over time? -4. What emotional reward might someone feel when they open it? - -Please be direct. If the idea lacks natural social behavior, suggest ways it could evolve. -``` - - -## Social Patterns - -### 1. Identity Playgrounds - -**The idea:** Give people ways to explore, express, or shape their identity within the app. - -**Why it works:** People don't just use feeds to consume — they use them to perform. Customization invites play, self-expression, and experimentation. - -**Where it shows up:** Discord roles, Reddit flair, Tumblr themes. - -**Use it for:** Differentiation, emotional investment, repeat posting. - - -``` -Given my app idea: [insert idea], explore 2 ways users might express or explore identity. - -For each, include: -– What the user customizes or signals -– How that shows up in the feed -– Why that might matter over time -``` - - -### 2. Co-Creation Loops - -**The idea:** Design behaviors that are better when shared — where users build on each other's contributions. - -**Why it works:** The strongest feeds don't just display content; they build momentum. If one person's post sparks another, you get a chain reaction. - -**Where it shows up:** Remix threads, collab playlists, group journaling. - -**Use it for:** Participation loops, content momentum, chain reactions. - - -``` -How could users in [insert app idea] create something together or build on each other's actions? -Return 3 co-creation flows that include: -– What kicks it off -– How others join in -– What the feed looks like after a few days -``` - - -### 3. Long-Term Rituals - -**The idea:** Introduce regular, shared behaviors that become a rhythm. - -**Why it works:** Rituals create predictability, belonging, and anticipation. They give users a reason to come back on a schedule. - -**Where it shows up:** Wordle scores, Monday memes, Friday drops, yearly Spotify Wrapped. - -**Use it for:** Habit loops, appointment-based engagement, social cohesion. - - -``` -Design 2 recurring rituals for [insert app idea]. - -For each, include: -– Frequency (daily, weekly, monthly) -– What users post -– What emotion or payoff they get -– How it could spread through the feed -``` - -## Interpreting your feedback - -After you get back raw answers to the four pressure‑test questions, look for the one or two dimensions that most naturally fit your idea. Nail those first, then decide if you need to shore up any others. - - - -Scan your AI responses for signs of strength in these four key areas: - - - -**Look for:** "Daily check‑ins create habit" or "Natural reason to post weekly" - - - -**Look for:** "Comments spark friendly competition" or "Better with others involved" - - - -**Look for:** "Automated reminders nudge new posts" or "Community‑driven growth" - - - -**Look for:** "Badges tap into achievement" or "Pride in sharing progress" - - - - -Focus on the dimensions where the AI feedback was most enthusiastic and specific. Vague responses usually indicate weak social potential. - - - - -For each dimension that scored well, confirm the feedback includes clear, actionable examples: - - - -**Strong signal:** At least 1 post per week feels natural to users - -**Examples to look for:** -- "Users would naturally share daily progress" -- "Weekly challenges create posting rhythm" -- "Status updates become habitual" - -**Red flag:** Forced or infrequent posting suggestions - - - -**Strong signal:** Others are meaningfully involved, not just passive viewers - -**Examples to look for:** -- "Friends can collaborate on projects" -- "Comments turn into conversations" -- "Peer reactions drive engagement" - -**Red flag:** Social features feel like an afterthought - - - -**Strong signal:** Community‑driven growth that builds over time - -**Examples to look for:** -- "Posts inspire similar content from others" -- "Trending topics emerge naturally" -- "User‑generated content feeds itself" - -**Red flag:** Content relies entirely on individual creators - - - -**Strong signal:** Opening the app delivers a felt reward - -**Examples to look for:** -- "Users feel proud sharing progress" -- "Achievements create satisfaction" -- "Community recognition feels meaningful" - -**Red flag:** Emotional benefits are unclear or generic - - - - - -Now that you've identified your strongest dimensions, here's how to proceed: - - - -**You're ready to build!** - -If your top 1–2 dimensions check out, skip straight to building social features around them. You don't need to perfect all four dimensions before starting. - - -Focus your energy on the social angles that truly resonate with your concept first. - - - - -**Iterate before building** - -If your dimensions are weak, spend time strengthening them before moving to development: - -- **Add a relational hook** (how do others get involved?) -- **Include a habit prompt** (what brings people back?) -- **Create emotional stakes** (why should users care?) - - -Don't force social features onto an inherently solo experience. Consider if your idea needs to evolve. - - - - -**Example Decision Flow:** - -You see strong **"Social lift"** ("Friends' reactions spark threads") and decent **"Emotional payoff"** ("Likes feel rewarding"). - -✅ **Decision:** Prototype a co‑posting feature focusing on these strengths - -⏳ **Later:** Explore "Content momentum" and "Repeat‑posting" patterns once core social features are solid - - -This focused approach prevents feature bloat and ensures you build social mechanics that actually work for your specific concept. - - - - -## Closing note - -The mini apps that thrive aren't the most complex — they're the ones that understand how people connect. - - -**Remember:** - -- Social features only work when they reflect real human behavior -- A feed isn't just content — it's a shared ritual -- True engagement comes from meaning over mechanics - - -As you build, ask: _Why would someone want to come back? Why would they share this with a friend?_ Those answers matter more than any feature list. - -The best apps don't just fill feeds. They create places people want to return to. -So — what will your app make people feel? From 135cd8cd7e91f290627df9d0baab8229a95f6907 Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Fri, 8 Aug 2025 16:24:28 -0500 Subject: [PATCH 3/7] change title --- .../base-app/introduction/getting-started.mdx | 137 ++++++++++-------- 1 file changed, 79 insertions(+), 58 deletions(-) diff --git a/docs/base-app/introduction/getting-started.mdx b/docs/base-app/introduction/getting-started.mdx index 95edf68ff..97724c898 100644 --- a/docs/base-app/introduction/getting-started.mdx +++ b/docs/base-app/introduction/getting-started.mdx @@ -1,10 +1,8 @@ --- -title: Getting Started with Mini Apps +title: What are Mini Apps? description: Overview and implementation guide for Mini Apps in Base App --- - - Mini Apps are lightweight web applications that run natively within clients like Base App. Users instantly access mini apps without downloads, benefit from seamless wallet interactions, and discover apps directly in the social feed. This benefits app developers by creating viral loops for user acquisition and engagement. ## What is a Mini App? @@ -16,12 +14,12 @@ A Mini App is composed of: Your current web app works as-is - -Simple wrapper component integration + + Simple wrapper component integration - -Single farcaster.json configuration file + + Single farcaster.json configuration file @@ -52,14 +50,15 @@ function App() { import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; function App() { - return ( - - {/* Existing components unchanged */} - {/* Existing components unchanged */} - - ); +return ( + + {/* Existing components unchanged */} + {/* Existing components unchanged */} + +); } -``` + +```` **Changes Required**: Two import lines and one wrapper component. All existing components remain unchanged. @@ -73,7 +72,8 @@ function App() { npx create-onchain --mini cd my-miniapp npm run dev -``` +```` + @@ -86,7 +86,8 @@ npm run dev -**Result**: Functional Mini App with wallet integration, transaction capabilities, and social features. + **Result**: Functional Mini App with wallet integration, transaction + capabilities, and social features. ## Pre-Solved Development Challenges @@ -143,8 +144,10 @@ Mini Apps require one configuration file located at `/.well-known/farcaster.json } } ``` + - While testing your Mini App, add "noindex": true to your manifest this prevents the app from being indexed during development. + While testing your Mini App, add "noindex": true to your manifest this + prevents the app from being indexed during development. ## Categories and Discovery @@ -156,24 +159,24 @@ Mini Apps require one configuration file located at `/.well-known/farcaster.json Gaming and entertainment applications - -Social networking and communication tools + + Social networking and communication tools - -DeFi, trading, and payment applications + + DeFi, trading, and payment applications - -Tools and productivity applications + + Tools and productivity applications - -Task management and organization tools + + Task management and organization tools - -Development utilities + + Development utilities @@ -204,12 +207,12 @@ You can use the [Farcaster manifest tool](https://farcaster.xyz/~/developers/min 200x200px PNG/JPG format - -200x200px PNG/JPG (displayed during app loading) + + 200x200px PNG/JPG (displayed during app loading) - -1200x628px PNG/JPG (for featured placement) + + 1200x628px PNG/JPG (for featured placement) @@ -226,17 +229,13 @@ The deployment process remains identical to standard web applications: `npm run build` (standard process) - -`public/.well-known/farcaster.json` - +`public/.well-known/farcaster.json` - -Use any hosting platform (Vercel, Netlify, custom servers) + + Use any hosting platform (Vercel, Netlify, custom servers) - -Functions as standard web application - +Functions as standard web application @@ -254,20 +253,23 @@ No special hosting, new infrastructure, or complex setup procedures required. No. Wrap your existing application in ``. Implementation complete. - -No. Mini Apps function in regular browsers. The same codebase works across all platforms. + + No. Mini Apps function in regular browsers. The same codebase works across all + platforms. - -No. Integration complexity is similar to Stripe implementation. + + No. Integration complexity is similar to Stripe implementation. - -Maintain current practices. You control data, backend systems, and privacy policies. + + Maintain current practices. You control data, backend systems, and privacy + policies. - -Minimal impact. MiniKit SDK is approximately 50KB. Application performance remains unchanged. + + Minimal impact. MiniKit SDK is approximately 50KB. Application performance + remains unchanged. @@ -282,28 +284,47 @@ Yes. The Farcaster SDK supports Vue, Angular, Svelte, and any web framework. View working implementation examples - -MiniKit documentation and overview + + MiniKit documentation and overview - -Comprehensive guide to Mini Apps + + Comprehensive guide to Mini Apps - -Debugging MiniKit and Mini Apps + + Debugging MiniKit and Mini Apps - -Validate and test your Mini App + + Validate and test your Mini App - -Farcaster Mini Apps SDK documentation + + Farcaster Mini Apps SDK documentation OnchainKit components and guides - From 256ccd18836f0be12e057680bcdefbb408d9e34a Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Fri, 8 Aug 2025 16:24:58 -0500 Subject: [PATCH 4/7] update navigation to include sections on miniapps and chat agents --- docs/docs.json | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/docs.json b/docs/docs.json index 1c84547e8..924a64ed4 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -173,9 +173,7 @@ "groups": [ { "group": "Introduction", - "pages": [ - "base-account/overview/what-is-base-account" - ] + "pages": ["base-account/overview/what-is-base-account"] }, { "group": "Quickstart", @@ -382,26 +380,29 @@ "group": "Introduction", "pages": [ "base-app/introduction/beta-faq", - "base-app/introduction/why-mini-apps", "base-app/introduction/getting-started", - "base-app/introduction/mini-apps" - + "base-app/introduction/why-mini-apps" ] }, { - "group": "Build with MiniKit", + "group": "MiniApps", "pages": [ - "base-app/build-with-minikit/overview", - "base-app/build-with-minikit/quickstart", - "base-app/build-with-minikit/existing-app-integration", - "base-app/build-with-minikit/debugging" + "base-app/miniapps/overview", + "base-app/miniapps/quickstart", + "base-app/miniapps/existing-app-integration", + "base-app/miniapps/thinking-social", + "base-app/miniapps/debugging" ] }, { - "group": "Guides", + "group": "Chat Agents", "pages": [ - "base-app/guides/thinking-social", - "base-app/guides/chat-agents" + "base-app/agents/why-agents", + "base-app/agents/getting-started", + "base-app/agents/content-types", + "base-app/agents/transaction-trays", + "base-app/agents/best-practices", + "base-app/agents/getting-featured" ] } ] @@ -2238,7 +2239,6 @@ "source": "/wallet-app/:slug*", "destination": "/base-app/:slug*" } - ], "integrations": { "ga4": { From 11eff8fe8826a0fd7004e22cf4de1aa82e263c29 Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Fri, 8 Aug 2025 16:25:34 -0500 Subject: [PATCH 5/7] create a new section on agents with smaller guides as subsections --- docs/base-app/agents/best-practices.mdx | 19 + docs/base-app/agents/chat-agents.mdx | 467 +++++++++++++++++++++ docs/base-app/agents/content-types.mdx | 183 ++++++++ docs/base-app/agents/getting-featured.mdx | 11 + docs/base-app/agents/getting-started.mdx | 227 ++++++++++ docs/base-app/agents/transaction-trays.mdx | 39 ++ docs/base-app/agents/why-agents.mdx | 19 + 7 files changed, 965 insertions(+) create mode 100644 docs/base-app/agents/best-practices.mdx create mode 100644 docs/base-app/agents/chat-agents.mdx create mode 100644 docs/base-app/agents/content-types.mdx create mode 100644 docs/base-app/agents/getting-featured.mdx create mode 100644 docs/base-app/agents/getting-started.mdx create mode 100644 docs/base-app/agents/transaction-trays.mdx create mode 100644 docs/base-app/agents/why-agents.mdx diff --git a/docs/base-app/agents/best-practices.mdx b/docs/base-app/agents/best-practices.mdx new file mode 100644 index 000000000..81034eb85 --- /dev/null +++ b/docs/base-app/agents/best-practices.mdx @@ -0,0 +1,19 @@ +--- +title: 'Chat Agent Best Practices' +description: 'Guidelines and recommendations for building effective chat agents' +sidebarTitle: 'Best Practices' +--- + +### Best practices + +1. Always validate content structures +2. Provide fallbacks for unsupported clients +3. Test across client versions +4. Limit message and metadata size +5. Follow [XIP-67](https://community.xmtp.org/t/xip-67-inline-actions/941) +6. Your agent should respond to both direct messages and group chat messages (if applicable). +7. For direct messages, it should automatically respond. +8. We recommend reacting to messages with an emoji (like 👀or ⌛) to indicate the message was received, while the response is processing. +9. For group chat messages, agents should only respond if they are mentioned with the "@" symbol and the agent's name. (example "@bankr"), OR if the user replies directly to a message from the agent (using the reply content type). + +For group chat messages, agents should only respond if they are mentioned with the "@" symbol and the agent's name. (example "@bankr"), OR if the user replies directly to a message from the agent (using the reply content type). diff --git a/docs/base-app/agents/chat-agents.mdx b/docs/base-app/agents/chat-agents.mdx new file mode 100644 index 000000000..36f185def --- /dev/null +++ b/docs/base-app/agents/chat-agents.mdx @@ -0,0 +1,467 @@ +--- +title: 'Chat Agents in Base App' +description: Learn how to build chat agents for Base App, using XMTP +sidebarTitle: 'Chat Agents' +--- + +This guide will cover how you can get started building messaging agents for Base App, using XMTP, a decentralized messaging protocol. Discover a fast, easy way to build and get distribution in Base App. + +- Why agents? +- Getting started with XMTP +- Getting featured in Base App + +## Why agents? + +Messaging is the largest use-case in the world, but it’s more than just conversations—it’s a secure, programmable channel for financial and social innovation. When combined with the onchain capabilities of Base App, builders have a new surface area to build 10X better messaging experiences not currently possible on legacy platforms like WhatsApp or Messenger. + +Real Examples: + +• Smart Payment Assistant: Text "split dinner $200 4 ways" and everyone gets paid instantly with sub-cent fees, no app switching or Venmo delays. + +• AI Trading Companion: Message "buy $100 ETH when it hits $3,000" and your agent executes trades 24/7 while you sleep. + +• Travel Planning Agent: "Book flight LAX to NYC under $300" and get instant booking with crypto payments, all in your group chat + +• Base App & XMTP are combining AI, crypto, and mini apps with secure messaging – to unlock use-cases never before possible. Secure group chats & DMs are the new surface area for developers. + +## Getting started + +This guide will walk you through creating, testing, and deploying your first XMTP messaging agent. By the end, you'll have a fully functional agent that can send and receive messages on the XMTP messaging network. + +**Prerequisites** +• Node.js (v20 or higher) +• Git +• A code editor +• Basic knowledge of JavaScript/TypeScript + +**Resources** + +- [Getting Started with XMTP (Video)](https://www.youtube.com/watch?v=djRLnWUvwIA) +- [Building Agents on XMTP](https://github.com/ephemeraHQ/xmtp-agent-examples) +- [Cursor Rules](https://github.com/ephemeraHQ/xmtp-agent-examples/blob/main/.cursor/rules/xmtp.md) +- [XMTP Documentation](https://docs.xmtp.org/) +- [Faucets](https://portal.cdp.coinbase.com/products/faucet) + +**STEP 1: SET UP YOUR DEVELOPMENT ENVIRONMENT** + +Clone the XMTP Agent Examples Repository: + +```bash +git clone https://github.com/ephemeraHQ/xmtp-agent-examples.git +cd xmtp-agent-examples +``` + +**STEP 2: INSTALL DEPENDENCIES** + +Install all required packages: + +```bash +npm install +``` + +**STEP 3: GENERATE KEYS FOR YOUR AGENT** + +Run the key generation script to create your agent's wallet: + +```bash +npm run gen:keys +``` + +This creates a .env file with: + +```bash +WALLET_KEY=0x... # Your agent's private key +ENCRYPTION_KEY=... # Encryption key for local database +XMTP_ENV=dev # Environment (local, dev, production) +``` + +**STEP 4: WRITE YOUR AGENT LOGIC** + +Create a basic agent that responds to messages: + +```javascript +// import the xmtp sdk +import { Client, type XmtpEnv, type Signer } from "@xmtp/node-sdk"; + +// encryption key, must be consistent across runs +const encryptionKey: Uint8Array = ...; +const signer: Signer = ...; +const env: XmtpEnv = "dev"; + +// create the client +const client = await Client.create(signer, {encryptionKey, env }); +// sync the client to get the latest messages +await client.conversations.sync(); + +// listen to all messages +const stream = await client.conversations.streamAllMessages(); +for await (const message of stream) { + // ignore messages from the agent + if (message?.senderInboxId === client.inboxId ) continue; + // get the conversation by id + const conversation = await client.conversations.getConversationById(message.conversationId); + // send a message from the agent + await conversation.send("gm"); +} +``` + +Then run your agent: + +```bash +npm run dev +``` + +### Getting the address of a user + +Each user has a unique inboxId for retrieving their associated addresses (identifiers). One inboxId can have multiple identifiers like passkeys or EVM wallet addresses. + +```tsx +const inboxState = await client.preferences.inboxStateFromInboxIds([ + message.senderInboxId, +]); +const addressFromInboxId = inboxState[0].identifiers[0].identifier; +``` + +You can also explore example implementations in the `/examples` folder, including: + +- [xmtp-gm](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-gm): A simple agent that replies to all text messages with "gm". +- [xmtp-gpt](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-gpt): An example using GPT API's to answer messages. +- [xmtp-nft-gated-group](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-nft-gated-group): Add members to a group based on an NFT +- [xmtp-coinbase-agentkit](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-coinbase-agentkit): Agent that uses a CDP for gassless USDC on base +- [xmtp-transactions](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-transactions): Use XMTP content types to send transactions +- [xmtp-smart-wallet](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-smart-wallet): Agent that uses a smart wallet to send messages + +**STEP 5: TEST YOUR AGENT** + +**Development Testing** + +1. Start your agent: + +```javascript +npm run dev +``` + +2. Test on [xmtp.chat:](https://xmtp.chat/conversations) + • Go to https://xmtp.chat + • Connect your personal wallet + • Switch to Dev environment in settings + • Start a new conversation with your agent's public address (from .env) + • Send a test message and verify the agent responds + +**Production Testing** + +1. Update environment: + +```javascript +XMTP_ENV = production; +``` + +2. Test on Base App: + • Open Base App mobile app + • Go to messaging + • Start conversation with your agent's address + • Verify functionality + +**STEP 6: GET A BASENAME FOR YOUR AGENT** + +Give your agent a human-readable name: + +**1. Import agent wallet to Base App extension:** +• Install Base App browser extension +• Import using your agent's private key + +**2. Purchase a basename:** +• Visit https://base.org/names +• Connect your agent's wallet +• Search and purchase your desired basename (e.g., myagent.base.eth) +• Set as primary name + +**3. Verify setup:** +• Your agent can now be reached via the basename instead of the long address +• Users can message myagent.base.eth instead of 0x123... + +**STEP 7: DEPLOY YOUR AGENT** + +**Option 1: Railway (Recommended)** + +• Visit https://railway.app +• Connect your GitHub repository +• Add environment variables in Railway dashboard: + \- XMTP_ENV=production + \- WALLET_KEY=your_agent_private_key + \- ENCRYPTION_KEY=your_agent_encryption_key +• Deploy and monitor logs + +**Option 2: Other Platforms** +Heroku, Vercel, or any Node.js hosting platform: +• Ensure your package.json has the correct start script +• Set environment variables in your hosting platform +• Deploy your repository + +**STEP 8: MONITOR AND MAINTAIN** + +**Best Practices** + +1. Logging: Add comprehensive logging to track agent activity +2. Error Handling: Implement try-catch blocks for network issues +3. Rate Limiting: Respect XMTP rate limits in your agent logic +4. Security: Never expose private keys; use environment variables + +**Monitoring** + +Add to your agent for basic monitoring: + +```javascript +const inboxState = await client.preferences.inboxState(); +const address = inboxState.identifiers[0].identifier; +const inboxId = client.inboxId; +const installationId = client.installationId; +const conversations = await client.conversations.list(); + +console.log(` +✓ XMTP Client: +• InboxId: ${inboxId} +• Address: ${address} +• Conversations: ${conversations.length} +• Installations: ${inboxState.installations.length} +• InstallationId: ${installationId} +• Network: ${process.env.XMTP_ENV}`); + +* console.log(\`Agent started. Address: ${xmtp.address}\`) +* console.log(\`Environment: ${process.env.XMTP\_ENV}\`) +* console.log(\`Listening for messages...\`) + +``` + +## Content types + +Base App supports various XMTP content types for rich messaging capabilities. This document outlines all supported content types, including custom types for Quick Actions and Intent. + +XMTP uses content types to define the structure and meaning of message types. + +We'll outline the standard and custom XMTP content types you can utilize in your agent. + +### XMTP Content Types + +**Text Messages** + +- Content Type: `xmtp.org/text:1.0` +- Purpose: Basic text messaging +- Usage: Default for plain text + +**Attachments** + +- Content Type: `xmtp.org/attachment:1.0` +- Purpose: File attachments (inline) +- Usage: Send files directly in messages + +**Remote Static Attachments** + +- Content Type: `xmtp.org/remoteStaticAttachment:1.0` +- Purpose: Remote file attachments via URLs +- Usage: Reduce message size + +**Reactions** + +- Content Type: `xmtp.org/reaction:1.0` +- Purpose: Emoji reactions +- Usage: React to messages with emojis +- Note: Does not trigger read receipts + +**Replies** + +- Content Type: `xmtp.org/reply:1.0` +- Purpose: Threaded conversations +- Usage: Reply to specific messages + +**Group Management** + +- Content Types: + - `xmtp.org/group_membership_change:1.0` + - `xmtp.org/group_updated:1.0` +- Purpose: Membership & group metadata updates +- Usage: Automatic system messages + +**Read Receipts** + +- Content Type: `xmtp.org/readReceipt:1.0` +- Purpose: Read confirmations +- Usage: Sent automatically + +**Transactions (Wallet Send Calls)** + +- Content Type: `xmtp.org/walletSendCalls:1.0` +- Purpose: Request wallet actions from users + +**Transaction Receipts** + +- Content Type: `xmtp.org/transactionReference:1.0` +- Purpose: Share blockchain transaction info + +### Base App Content Types + +There are content types developed by the Base App team for agents in Base App. Other XMTP clients may not support these content types. + +**Quick Actions (coinbase.com/actions:1.0)** + +Purpose: Present interactive buttons in a message + +Structure: + +```typescript +type ActionsContent = { + id: string; + description: string; + actions: Action[]; + expiresAt?: string; +}; + +type Action = { + id: string; + label: string; + imageUrl?: string; + style?: 'primary' | 'secondary' | 'danger'; + expiresAt?: string; +}; +``` + +Validation Rules: + +- `id`, `description` are required +- `actions` must be 1–10 items with unique IDs +- Style must be one of: `primary`, `secondary`, `danger` + +Fallback: + +``` +[Description] + +[1] [Action Label 1] +[2] [Action Label 2] +... +Reply with the number to select +``` + +Example: Payment Options + +```json +{ + "id": "payment_alice_123", + "description": "Choose amount to send to Alice", + "actions": [ + { "id": "send_10", "label": "Send $10", "style": "primary" }, + { "id": "send_20", "label": "Send $20", "style": "primary" }, + { "id": "custom_amount", "label": "Custom Amount", "style": "secondary" } + ], + "expiresAt": "2024-12-31T23:59:59Z" +} +``` + + +Manifest Embed Example + + + +**Intent (coinbase.com/intent:1.0)** + +Purpose: User expresses choice from Quick Actions + +Structure: + +```typescript +type IntentContent = { + id: string; + actionId: string; + metadata?: Record; +}; +``` + +Validation Rules: + +- `id`, `actionId` required +- Must match corresponding Actions +- `metadata` is optional, `<10KB` + +Fallback: + +``` +User selected action: [actionId] +``` + +Example: Intent Message + +```json +{ + id: 'payment_alice_123', + actionId: 'send_10', + metadata: { + timestamp: Date.now(), + actionLabel: 'Send $10' + } +} +``` + + + Analytics dashboard with charts + + +## Custom Transaction Trays + +If you would like to display agent information such as favicon and branded title, utilize the metadata property of wallet send calls data. + +#### **Example: Display agent information** + +```ts +// example of wallet send calls data shape{ + version: "1.0", + from: request.from as `0x${string}`, + chainId: this.networkConfig.chainId, + calls: [ + { + ... + metadata: { + description: "Transfer token", + ...other fields, + hostname: "tba.chat", + faviconUrl: "https://tba.chat/favicon", + title: "Your favorite Agent" + } + } + ] +} +``` + + + Transaction tray + + +You can send “GM” to **tbachat.base.eth** to get more details about message content types we support and get the firsthand experience on by interacting with our agent + +Our agent repo is found [here](https://github.com/siwan-cb/tba-chat-example-bot) + +### Best practices + +1. Always validate content structures +2. Provide fallbacks for unsupported clients +3. Test across client versions +4. Limit message and metadata size +5. Follow [XIP-67](https://community.xmtp.org/t/xip-67-inline-actions/941) +6. Your agent should respond to both direct messages and group chat messages (if applicable). +7. For direct messages, it should automatically respond. +8. We recommend reacting to messages with an emoji (like 👀or ⌛) to indicate the message was received, while the response is processing. +9. For group chat messages, agents should only respond if they are mentioned with the “@” symbol and the agent’s name. (example “@bankr”), OR if the user replies directly to a message from the agent (using the reply content type). + +For group chat messages, agents should only respond if they are mentioned with the "@" symbol and the agent's name. (example "@bankr"), OR if the user replies directly to a message from the agent (using the reply content type). + +## Getting featured + +Fill out the form [here](https://app.deform.cc/form/52b71db4-bfa2-4ef5-a954-76c66250bdd2/?page_number=0) to submit your agent for review. Note, agents often go through multiple rounds of feedback before they are ready to be featured. Once approved, your agent will be featured in Base App. You will hear back from us within 5 business days. + +Need help or have feature requests? Visit [https://community.xmtp.org/](https://community.xmtp.org/) diff --git a/docs/base-app/agents/content-types.mdx b/docs/base-app/agents/content-types.mdx new file mode 100644 index 000000000..d56dd49ab --- /dev/null +++ b/docs/base-app/agents/content-types.mdx @@ -0,0 +1,183 @@ +--- +title: 'Content Types for Chat Agents' +description: 'Learn about supported XMTP content types and how to use them in your chat agent' +sidebarTitle: 'Content Types' +--- + +## Content types + +Base App supports various XMTP content types for rich messaging capabilities. This document outlines all supported content types, including custom types for Quick Actions and Intent. + +XMTP uses content types to define the structure and meaning of message types. + +We'll outline the standard and custom XMTP content types you can utilize in your agent. + +### XMTP Content Types + +**Text Messages** + +- Content Type: `xmtp.org/text:1.0` +- Purpose: Basic text messaging +- Usage: Default for plain text + +**Attachments** + +- Content Type: `xmtp.org/attachment:1.0` +- Purpose: File attachments (inline) +- Usage: Send files directly in messages + +**Remote Static Attachments** + +- Content Type: `xmtp.org/remoteStaticAttachment:1.0` +- Purpose: Remote file attachments via URLs +- Usage: Reduce message size + +**Reactions** + +- Content Type: `xmtp.org/reaction:1.0` +- Purpose: Emoji reactions +- Usage: React to messages with emojis +- Note: Does not trigger read receipts + +**Replies** + +- Content Type: `xmtp.org/reply:1.0` +- Purpose: Threaded conversations +- Usage: Reply to specific messages + +**Group Management** + +- Content Types: + - `xmtp.org/group_membership_change:1.0` + - `xmtp.org/group_updated:1.0` +- Purpose: Membership & group metadata updates +- Usage: Automatic system messages + +**Read Receipts** + +- Content Type: `xmtp.org/readReceipt:1.0` +- Purpose: Read confirmations +- Usage: Sent automatically + +**Transactions (Wallet Send Calls)** + +- Content Type: `xmtp.org/walletSendCalls:1.0` +- Purpose: Request wallet actions from users + +**Transaction Receipts** + +- Content Type: `xmtp.org/transactionReference:1.0` +- Purpose: Share blockchain transaction info + +### Base App Content Types + +There are content types developed by the Base App team for agents in Base App. Other XMTP clients may not support these content types. + +**Quick Actions (coinbase.com/actions:1.0)** + +Purpose: Present interactive buttons in a message + +Structure: + +```typescript +type ActionsContent = { + id: string; + description: string; + actions: Action[]; + expiresAt?: string; +}; + +type Action = { + id: string; + label: string; + imageUrl?: string; + style?: 'primary' | 'secondary' | 'danger'; + expiresAt?: string; +}; +``` + +Validation Rules: + +- `id`, `description` are required +- `actions` must be 1–10 items with unique IDs +- Style must be one of: `primary`, `secondary`, `danger` + +Fallback: + +``` +[Description] + +[1] [Action Label 1] +[2] [Action Label 2] +... +Reply with the number to select +``` + +Example: Payment Options + +```json +{ + "id": "payment_alice_123", + "description": "Choose amount to send to Alice", + "actions": [ + { "id": "send_10", "label": "Send $10", "style": "primary" }, + { "id": "send_20", "label": "Send $20", "style": "primary" }, + { "id": "custom_amount", "label": "Custom Amount", "style": "secondary" } + ], + "expiresAt": "2024-12-31T23:59:59Z" +} +``` + + + Manifest Embed Example + + +**Intent (coinbase.com/intent:1.0)** + +Purpose: User expresses choice from Quick Actions + +Structure: + +```typescript +type IntentContent = { + id: string; + actionId: string; + metadata?: Record; +}; +``` + +Validation Rules: + +- `id`, `actionId` required +- Must match corresponding Actions +- `metadata` is optional, `<10KB` + +Fallback: + +``` +User selected action: [actionId] +``` + +Example: Intent Message + +```json +{ + id: 'payment_alice_123', + actionId: 'send_10', + metadata: { + timestamp: Date.now(), + actionLabel: 'Send $10' + } +} +``` + + + Analytics dashboard with charts + diff --git a/docs/base-app/agents/getting-featured.mdx b/docs/base-app/agents/getting-featured.mdx new file mode 100644 index 000000000..32f708754 --- /dev/null +++ b/docs/base-app/agents/getting-featured.mdx @@ -0,0 +1,11 @@ +--- +title: 'Getting Your Agent Featured' +description: 'Learn how to submit your chat agent for review and get featured in Base App' +sidebarTitle: 'Getting Featured' +--- + +## Getting featured + +Fill out the form [here](https://app.deform.cc/form/52b71db4-bfa2-4ef5-a954-76c66250bdd2/?page_number=0) to submit your agent for review. Note, agents often go through multiple rounds of feedback before they are ready to be featured. Once approved, your agent will be featured in Base App. You will hear back from us within 5 business days. + +Need help or have feature requests? Visit [https://community.xmtp.org/](https://community.xmtp.org/) diff --git a/docs/base-app/agents/getting-started.mdx b/docs/base-app/agents/getting-started.mdx new file mode 100644 index 000000000..50acfdfcd --- /dev/null +++ b/docs/base-app/agents/getting-started.mdx @@ -0,0 +1,227 @@ +--- +title: 'Getting Started with Chat Agents' +description: 'Step-by-step guide to creating, testing, and deploying your first XMTP messaging agent' +sidebarTitle: 'Getting Started' +--- + +This guide will walk you through creating, testing, and deploying your first XMTP messaging agent. By the end, you'll have a fully functional agent that can send and receive messages on the XMTP messaging network. + +## Prerequisites + +Before you begin, make sure you have: + +- Node.js (v20 or higher) +- Git +- A code editor +- Basic knowledge of JavaScript/TypeScript + +## Helpful Resources + +- [Getting Started with XMTP (Video)](https://www.youtube.com/watch?v=djRLnWUvwIA) +- [Building Agents on XMTP](https://github.com/ephemeraHQ/xmtp-agent-examples) +- [Cursor Rules](https://github.com/ephemeraHQ/xmtp-agent-examples/blob/main/.cursor/rules/xmtp.md) +- [XMTP Documentation](https://docs.xmtp.org/) +- [Faucets](https://portal.cdp.coinbase.com/products/faucet) + +## Development Guide + + + + Clone the XMTP Agent Examples Repository: + + ```bash + git clone https://github.com/ephemeraHQ/xmtp-agent-examples.git + cd xmtp-agent-examples + ``` + + + + + Install all required packages: + + ```bash + npm install + ``` + + + + + Run the key generation script to create your agent's wallet: + + ```bash + npm run gen:keys + ``` + + This creates a .env file with: + + ```bash + WALLET_KEY=0x... # Your agent's private key + ENCRYPTION_KEY=... # Encryption key for local database + XMTP_ENV=dev # Environment (local, dev, production) + ``` + + + + + Create a basic agent that responds to messages: + + ```javascript + // import the xmtp sdk + import { Client, type XmtpEnv, type Signer } from "@xmtp/node-sdk"; + + // encryption key, must be consistent across runs + const encryptionKey: Uint8Array = ...; + const signer: Signer = ...; + const env: XmtpEnv = "dev"; + + // create the client + const client = await Client.create(signer, {encryptionKey, env }); + // sync the client to get the latest messages + await client.conversations.sync(); + + // listen to all messages + const stream = await client.conversations.streamAllMessages(); + for await (const message of stream) { + // ignore messages from the agent + if (message?.senderInboxId === client.inboxId ) continue; + // get the conversation by id + const conversation = await client.conversations.getConversationById(message.conversationId); + // send a message from the agent + await conversation.send("gm"); + } + ``` + + Then run your agent: + + ```bash + npm run dev + ``` + + ### Getting the address of a user + + Each user has a unique inboxId for retrieving their associated addresses (identifiers). One inboxId can have multiple identifiers like passkeys or EVM wallet addresses. + + ```tsx + const inboxState = await client.preferences.inboxStateFromInboxIds([ + message.senderInboxId, + ]); + const addressFromInboxId = inboxState[0].identifiers[0].identifier; + ``` + + ### Example Implementations + + Explore these examples in the `/examples` folder: + + - [xmtp-gm](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-gm): A simple agent that replies to all text messages with "gm" + - [xmtp-gpt](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-gpt): An example using GPT API's to answer messages + - [xmtp-nft-gated-group](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-nft-gated-group): Add members to a group based on an NFT + - [xmtp-coinbase-agentkit](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-coinbase-agentkit): Agent that uses a CDP for gassless USDC on base + - [xmtp-transactions](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-transactions): Use XMTP content types to send transactions + - [xmtp-smart-wallet](https://github.com/ephemeraHQ/xmtp-agent-examples/tree/main/examples/xmtp-smart-wallet): Agent that uses a smart wallet to send messages + + + + + ### Development Testing + + 1. Start your agent: + ```javascript + npm run dev + ``` + + 2. Test on [xmtp.chat](https://xmtp.chat/conversations): + - Go to https://xmtp.chat + - Connect your personal wallet + - Switch to Dev environment in settings + - Start a new conversation with your agent's public address (from .env) + - Send a test message and verify the agent responds + + ### Production Testing + + 1. Update environment: + ```javascript + XMTP_ENV = production; + ``` + + 2. Test on Base App: + - Open Base App mobile app + - Go to messaging + - Start conversation with your agent's address + - Verify functionality + + + + + Give your agent a human-readable name: + + 1. **Import agent wallet to Base App extension:** + - Install Base App browser extension + - Import using your agent's private key + + 2. **Purchase a basename:** + - Visit https://base.org/names + - Connect your agent's wallet + - Search and purchase your desired basename (e.g., myagent.base.eth) + - Set as primary name + + 3. **Verify setup:** + - Your agent can now be reached via the basename instead of the long address + - Users can message myagent.base.eth instead of 0x123... + + + + + ### Option 1: Railway (Recommended) + + - Visit https://railway.app + - Connect your GitHub repository + - Add environment variables in Railway dashboard: + - XMTP_ENV=production + - WALLET_KEY=your_agent_private_key + - ENCRYPTION_KEY=your_agent_encryption_key + - Deploy and monitor logs + + ### Option 2: Other Platforms + + Heroku, Vercel, or any Node.js hosting platform: + - Ensure your package.json has the correct start script + - Set environment variables in your hosting platform + - Deploy your repository + + + + + ### Best Practices + + 1. Logging: Add comprehensive logging to track agent activity + 2. Error Handling: Implement try-catch blocks for network issues + 3. Rate Limiting: Respect XMTP rate limits in your agent logic + 4. Security: Never expose private keys; use environment variables + + ### Monitoring + + Add to your agent for basic monitoring: + + ```javascript + const inboxState = await client.preferences.inboxState(); + const address = inboxState.identifiers[0].identifier; + const inboxId = client.inboxId; + const installationId = client.installationId; + const conversations = await client.conversations.list(); + + console.log(` + ✓ XMTP Client: + • InboxId: ${inboxId} + • Address: ${address} + • Conversations: ${conversations.length} + • Installations: ${inboxState.installations.length} + • InstallationId: ${installationId} + • Network: ${process.env.XMTP_ENV}`); + + console.log(`Agent started. Address: ${xmtp.address}`) + console.log(`Environment: ${process.env.XMTP_ENV}`) + console.log(`Listening for messages...`) + ``` + + + diff --git a/docs/base-app/agents/transaction-trays.mdx b/docs/base-app/agents/transaction-trays.mdx new file mode 100644 index 000000000..24f9010ba --- /dev/null +++ b/docs/base-app/agents/transaction-trays.mdx @@ -0,0 +1,39 @@ +--- +title: 'Custom Transaction Trays' +description: 'Learn how to customize transaction trays with agent branding and information' +sidebarTitle: 'Transaction Trays' +--- + +## Custom Transaction Trays + +If you would like to display agent information such as favicon and branded title, utilize the metadata property of wallet send calls data. + +#### **Example: Display agent information** + +```ts +// example of wallet send calls data shape{ + version: "1.0", + from: request.from as `0x${string}`, + chainId: this.networkConfig.chainId, + calls: [ + { + ... + metadata: { + description: "Transfer token", + ...other fields, + hostname: "tba.chat", + faviconUrl: "https://tba.chat/favicon", + title: "Your favorite Agent" + } + } + ] +} +``` + + + Transaction tray + + +You can send "GM" to **tbachat.base.eth** to get more details about message content types we support and get the firsthand experience on by interacting with our agent + +Our agent repo is found [here](https://github.com/siwan-cb/tba-chat-example-bot) diff --git a/docs/base-app/agents/why-agents.mdx b/docs/base-app/agents/why-agents.mdx new file mode 100644 index 000000000..87d545e08 --- /dev/null +++ b/docs/base-app/agents/why-agents.mdx @@ -0,0 +1,19 @@ +--- +title: 'Why Build Chat Agents?' +description: 'Discover the power of messaging agents and their potential impact on Base App' +sidebarTitle: 'Why Agents?' +--- + +## Why agents? + +Messaging is the largest use-case in the world, but it's more than just conversations—it's a secure, programmable channel for financial and social innovation. When combined with the onchain capabilities of Base App, builders have a new surface area to build 10X better messaging experiences not currently possible on legacy platforms like WhatsApp or Messenger. + +Real Examples: + +• Smart Payment Assistant: Text "split dinner $200 4 ways" and everyone gets paid instantly with sub-cent fees, no app switching or Venmo delays. + +• AI Trading Companion: Message "buy $100 ETH when it hits $3,000" and your agent executes trades 24/7 while you sleep. + +• Travel Planning Agent: "Book flight LAX to NYC under $300" and get instant booking with crypto payments, all in your group chat + +• Base App & XMTP are combining AI, crypto, and mini apps with secure messaging – to unlock use-cases never before possible. Secure group chats & DMs are the new surface area for developers. From 276122040c26ca767ee53d658ac513b74d51e4a4 Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Fri, 8 Aug 2025 16:26:12 -0500 Subject: [PATCH 6/7] create miniapps section --- docs/base-app/miniapps/debugging.mdx | 388 ++++++++++++++ .../miniapps/existing-app-integration.mdx | 495 ++++++++++++++++++ docs/base-app/miniapps/overview.mdx | 464 ++++++++++++++++ docs/base-app/miniapps/quickstart.mdx | 415 +++++++++++++++ docs/base-app/miniapps/thinking-social.mdx | 294 +++++++++++ 5 files changed, 2056 insertions(+) create mode 100644 docs/base-app/miniapps/debugging.mdx create mode 100644 docs/base-app/miniapps/existing-app-integration.mdx create mode 100644 docs/base-app/miniapps/overview.mdx create mode 100644 docs/base-app/miniapps/quickstart.mdx create mode 100644 docs/base-app/miniapps/thinking-social.mdx diff --git a/docs/base-app/miniapps/debugging.mdx b/docs/base-app/miniapps/debugging.mdx new file mode 100644 index 000000000..f3608b72e --- /dev/null +++ b/docs/base-app/miniapps/debugging.mdx @@ -0,0 +1,388 @@ +--- +title: Common Issues & Debugging +description: Frequent issues encountered during Mini App development and their solutions +--- + +## **Prerequisites & Setup Verification** + +Before debugging, ensure your Mini App has the foundational requirements in place. + +### **Required Files and Structure** + +Your Mini App must have these files in the correct locations: + +```html +your-domain.com/ +├── .well-known/ +│ └── farcaster.json # Required manifest file +├── your-app/ +│ ├── index.html # Your app entry point +│ └── ... # Your app files +``` + +### **Environment Setup Checklist** + +* Domain is accessible via HTTPS +* Manifest file exists at `/.well-known/farcaster.json` +* All image URLs are publicly accessible + +### **Basic Validation Steps** + +1. **Test manifest accessibility**: Visit `https://yourdomain.com/.well-known/farcaster.json` +2. **Validate JSON syntax**: Use [JSONLint](https://jsonlint.com/) to check your manifest +3. **Test app loading**: Ensure your app loads without console errors + + + +## **Quick Diagnostic Workflow** + + +**Is your app not appearing in search results?** → [Go to App Discovery & Indexing Issues](#1-app-discovery--indexing-issues) + +**Is your app not rendering as an embed when shared?** → [Go to Embed Rendering Issues](#3-embed-rendering-issues) + +**Are you having wallet connection problems?** → [Go to Wallet Connection Problems](#4-wallet-connection-problems) + +**Are you looking for testing tools ?** → [Go to Mobile Testing & Debugging](#6-mobile-testing--debugging) + +**Are changes not appearing after updates?** → [Go to Manifest Configuration Problems](#2-manifest-configuration-problems) + +**Does your app close unexpectedly during user interactions?** → [Go to Gesture Conflicts and App Dismissal Issues](#5-gesture-conflicts-and-app-dismissal-issues) + +## **Detailed Problem Solutions** + +## **1\. App Discovery & Indexing Issues** +**Problem**: Your Mini App doesn't appear in search results or app catalogs. + +**Root Cause**: Missing or incomplete manifest configuration. + +**Solution**: Ensure your manifest at `/.well-known/farcaster.json` includes all required fields: + + +```json +{ + "accountAssociation": { + "header": "eyJmaWQiOjkxNTIsInR5cGUiOiJjdXN0b2R5Iiwia2V5IjoiMHgwMmVmNzkwRGQ3OTkzQTM1ZkQ4NDdDMDUzRURkQUU5NDBEMDU1NTk2In0", + "payload": "eyJkb21haW4iOiJyZXdhcmRzLndhcnBjYXN0LmNvbSJ9", + "signature": "MHgxMGQwZGU4ZGYwZDUwZTdmMGIxN2YxMTU2NDI1MjRmZTY0MTUyZGU4ZGU1MWU0MThiYjU4ZjVmZmQxYjRjNDBiNGVlZTRhNDcwNmVmNjhlMzQ0ZGQ5MDBkYmQyMmNlMmVlZGY5ZGQ0N2JlNWRmNzMwYzUxNjE4OWVjZDJjY2Y0MDFj" + }, + "frame": { + "version": "1", + "name": "Example Mini App", + "iconUrl": "https://example.com/app.png", + "splashImageUrl": "https://example.com/logo.png", + "splashBackgroundColor": "#000000", + "homeUrl": "https://example.com", + "webhookUrl": "https://example.com/api/webhook", + "subtitle": "Example Mini App subtitle", + "description": "Example Mini App subtitle", + "screenshotUrls": [ + "https://example.com/screenshot1.png", + "https://example.com/screenshot2.png", + "https://example.com/screenshot3.png" + ], + "primaryCategory": "social", + "tags": [ + "example", + "mini app", + "coinbase wallet" + ], + "heroImageUrl": "https://example.com/og.png", + "tagline": "Example Mini App tagline", + "ogTitle": "Example Mini App", + "ogDescription": "Example Mini App description", + "ogImageUrl": "https://example.com/og.png" + } +} +``` + + In the Category section only the top 100 Mini Apps are shared. This is determined by activity such as user sharing. + + +**Critical Requirements**: + +* `primaryCategory` is required for searchability and category pages +* `accountAssociation` is required for verification + +**Reference**: [Complete manifest guide](https://docs.base.org/base-app/introduction/getting-started#manifest-file-configuration) + +### **App Indexing Requirements** + +**Problem**: Your app has a manifest but still doesn't appear in catalogs. + +**Solution**: Your Mini App must be shared in a post to be indexed. + +**Steps to Index Your App**: + +1. Complete your manifest setup +2. Share your Mini App URL in a post +3. Indexing can take up to 10 minutes +4. Verify appearance in app catalogs + +### **Caching Issues \- Changes Not Appearing** + +**Problem**: Updates to your manifest or app aren't showing up. + +**Why This Happens**: Farcaster clients cache manifest data for up to 24 hours for performance. + +**Solutions**: + +1. **Force Refresh**: Share your Mini App in a new cast to trigger cache refresh. This can take up to 10 minutes + + + +## **2\. Manifest Configuration Problems** + +### **Image Display Issues** + +**Problem**: App icons or images not displaying correctly. + +**Debug Steps**: + +1. Test image accessibility in incognito browser +2. Verify image format (PNG, JPG, WebP supported) +3. Check image dimensions (icons should be 200x200px minimum) +4. Ensure HTTPS URLs only + + +Manifest Embed Example + + + +## **3\. Embed Rendering Issues** + +### **Mini App Not Showing as Embed** + +**Problem**: Your Mini App URL doesn't render as a rich embed when shared. + +**Root Cause**: The embed configuration is not correct. + +**Solution**: Make sure the metadata in the head tag has the correct format in order to render correctly. In order for it to work properly for all clients please ensure you’re using the `name="fc:frame" meta tag.` + +```html + +``` + +**Debug Steps**: + +1. Test your URL in the [Mini App Embed Tool](https://farcaster.xyz/~/developers/mini-apps/embed) +2. Check meta tag is in `` section + +**Success Verification**: Your embed should show an image with a launch button when the URL is shared. + +## **4\. Wallet Connection Problems** + +### **Getting Connected Wallet** + +**Problem**: Unable to access user's wallet or connection status. + +### **Using MiniKit with OnchainKit (Recommended)** + +Minikit uses the Onchainkit wallet connect component that handles this behaviour of box for you without any additional set up. + +**Complete Setup**: + +```tsx +// 1. Install dependencies +// npm install @coinbase/onchainkit + +// 2. Set up your app with MiniKitProvider +import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; +import { base } from 'wagmi/chains'; + +function App() { + return ( + + + + ); +} + +// 3. Use wallet component +import { Wallet } from '@coinbase/onchainkit/wallet'; + +function YourAppContent() { + return ( +
+ + {/* Your app content */} +
+ ); +} +``` + +### **Using Wagmi Hooks Directly (Recommended)** + + +```tsx +import { useAccount } from 'wagmi'; + +function WalletInfo() { + const { address, isConnected } = useAccount(); + + if (!isConnected) { + return
Please connect your wallet
; + } + + return ( +
+
Status: Connected
+
Address: {address}
+
+ ); +} +``` + +MiniKit includes wagmi providers by default \- don't add additional wagmi configuration. + + +**Error Handling**: + +```tsx +import { useAccount, useConnect } from 'wagmi'; + +function WalletConnection() { + const { address, isConnected } = useAccount(); + const { connect, connectors, error, isLoading } = useConnect(); + + if (error) { + return
Connection error: {error.message}
; + } + + if (isLoading) { + return
Connecting...
; + } + + if (!isConnected) { + return ( + + ); + } + + return
Connected: {address}
; +} +``` + +## **5\. Gesture Conflicts and App Dismissal Issues** + +**Problem**: App closes when users swipe, drag, or perform touch gestures. + +**Symptoms**: + +* Mini App closes when users swipe, drag, or perform touch gestures +* App dismisses during game interactions or custom navigation +* Users can't complete multi-step touch interactions + +**Root Cause**: Mini Apps run in modal containers where native gestures (swipes, taps outside the app area) automatically close the app. If your app uses similar gestures, they conflict with these native dismissal behaviors. + +**Solution**: Disable native gestures when calling `sdk.actions.ready()`: + +```ts +// Instead of this: +await sdk.actions.ready(); + +// Use this if your app has gesture conflicts: +await sdk.actions.ready({ disableNativeGestures: true }); +``` + +## **6\. Mobile Testing & Debugging** + +### **Using Eruda for Mobile Debug** + +**Problem**: Difficulty debugging Mini Apps on mobile devices. + +**Setup**: + +```html + + + +``` + + If you are testing specific enviornment behaviour - you can use clientFid :309857 + + +**How to Use**: + +1. Add the script to your app +2. Open your Mini App on mobile (cast the app in a DM to yourself) +3. Look for the Eruda debugging panel icon (usually bottom-right) +4. Access console, network, elements, and other debugging tools + +**Mobile Testing Workflow**: + +1. **Local Testing**: Use ngrok or similar to expose localhost +2. **Cast in DM**: Share your app URL in a DM to yourself +3. **Test Different Clients**: Test in Warpcast mobile and other Farcaster clients +4. **Check Different Devices**: Test on both iOS and Android if possible + + +Remove Eruda before production deployment. + + +## **Advanced Troubleshooting** + +### **AI-Assisted Debugging** + +**Using Coinbase Wallet Compatibility Validator**: + +The Coinbase Wallet team provides an AI-powered validation tool to check Mini App compatibility. + +**How to Use**: + +1. Use the validator prompt: [CBW MiniApp Validator](https://raw.githubusercontent.com/base/demos/refs/heads/master/minikit/mini-app-help/validate.txt) +2. In your preferred AI code editor (Cursor, etc.): + * Add the validator file to your project context + * Ask the AI: "Please validate my Mini App code using the CBW validator guidelines" +3. The AI will return a report of any unsupported actions or compatibility issues + +**What it Checks**: + +* Unsupported SDK methods +* Coinbase Wallet specific limitations + +## **Success Verification** + +### **Testing Checklist** + +Before deploying your Mini App, verify these items work correctly: + +**Basic Functionality**: + +- [ ] App loads without console errors +- [ ] All images display correctly +- [ ] Wallet connection works +- [ ] Core app functionality works as expected + +**Discovery & Sharing**: + +- [ ] Manifest file is accessible at `/.well-known/farcaster.json` +- [ ] App appears in embed when URL is shared +- [ ] App appears in search results (after posting) +- [ ] All required manifest fields are present + +## **Getting Additional Help** + +If you're still experiencing issues after following this guide: + +* [**Mini App Debug Tool**](https://farcaster.xyz/~/developers) \- Test your Mini App functionality +* [**Mini App Embed Tool**](https://farcaster.xyz/~/developers/mini-apps/embed) \- Preview how embeds will appear +* [**JSONLint**](https://jsonlint.com/) \- Validate JSON syntax +* [**Eruda**](https://github.com/liriliri/eruda) \- Mobile debugging console +* [Base Discord](https://discord.com/channels/1067165013397213286/1387875275756408883) \- \#minikit channel + + diff --git a/docs/base-app/miniapps/existing-app-integration.mdx b/docs/base-app/miniapps/existing-app-integration.mdx new file mode 100644 index 000000000..d1ff3c27c --- /dev/null +++ b/docs/base-app/miniapps/existing-app-integration.mdx @@ -0,0 +1,495 @@ +--- +title: 'Migrate an Existing App' +description: Guide for integrating MiniKit into an existing Next.js project with installation, provider setup, and environment configuration +--- + +This guide helps developers integrate MiniKit into an existing Next.js project. It includes installation steps, provider setup and environment configuration. + + + This guide assumes you want to add MiniKit to an existing application. For new + projects, use the [MiniKit CLI](/base-app/build-with-minikit/quickstart) for + automatic setup. + + +## Prerequisites + +Before you begin, confirm the following: + + + +You are using a Next.js project with the `app/` directory structure (App Router). + + + + Your app is deployed and publicly accessible (e.g. via Vercel) with HTTPS + enabled. + + + + You have an active Farcaster account for testing and access to your custody + wallet. + + + +Sign up for a [Coinbase Developer Platform](https://portal.cdp.coinbase.com/) to retrieve your CDP API Key. + + + +## Integration Steps + + + +MiniKit is available as part of OnchainKit. + +```shell +npm install @coinbase/onchainkit +``` + + +Verify installation by checking that `@coinbase/onchainkit` appears in your `package.json`. + + + + +Create and use the `MiniKitProvider` to initialise SDK context for your application. + +**File: `providers/MiniKitProvider.tsx`** + +```jsx +'use client'; + +import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; +import { ReactNode } from 'react'; +import { base } from 'wagmi/chains'; + +export function MiniKitContextProvider({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} +``` + +Then wrap your app in `app/layout.tsx`: + +```jsx +import { MiniKitContextProvider } from '@/providers/MiniKitProvider'; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode, +}) { + return ( + + + {children} + + + ); +} +``` + + +The provider automatically configures wagmi and react-query, and sets up connectors to use Farcaster when available. + + + + +Use the `useMiniKit` hook to access the frame context and trigger readiness. + +**File: `app/page.tsx`** + +```jsx +'use client'; + +import { useEffect, useState } from 'react'; +import { useMiniKit } from '@coinbase/onchainkit/minikit'; + +export default function HomePage() { + const { setFrameReady, isFrameReady } = useMiniKit(); + + // The setFrameReady() function is called when your mini-app is ready to be shown + useEffect(() => { + if (!isFrameReady) { + setFrameReady(); + } + }, [setFrameReady, isFrameReady]); + + return
Your app content goes here
; +} +``` + + +The `setFrameReady()` function removes the splash screen and shows your application. Only call this when your app is fully loaded and ready for user interaction. + +
+ + +Add the required environment variables to your project and deployment platform. + + + +These variables are essential for your MiniKit app to function: + + + The name of your Mini App as it appears to users + + + + The deployed URL of your application (must be HTTPS) + + + + Your Coinbase Developer Platform API key + + + + Generated during manifest creation for account association + + + + Generated during manifest creation for account association + + + +Generated during manifest creation for account association + + + + +These variables enhance your app's appearance and metadata: + + + URL to your app's icon (recommended: 48x48px PNG) + + + + Brief subtitle shown in app listings + + + + Detailed description of your app's functionality + + + + URL to splash screen image shown during app loading + + + + Hex color code for splash screen background (e.g., "#000000") + + + + Primary category for app discovery (e.g., "social", "gaming", "utility") + + + + Hero image URL displayed in cast previews + + + + Short, compelling tagline for your app + + + + Open Graph title for social media sharing + + + + Open Graph description for social media sharing + + + +Open Graph image URL for social media previews + + + + + +Don't forget to include all referenced images in your `public/` folder and ensure they're accessible via HTTPS. + + + + +Use the OnchainKit CLI to generate account association credentials and update your environment variables. + +```shell +npx create-onchain --manifest +``` + + + **Important:** The wallet you connect must be your Farcaster custody wallet. + You can import this wallet using the recovery phrase found in Farcaster under + Settings → Advanced → Farcaster recovery phrase. + + +Follow these substeps: + +1. Connect your Farcaster custody wallet +2. Add your deployed Vercel URL +3. Sign the manifest to generate association credentials +4. The CLI will automatically update your local `.env` file + + +After running this command locally, remember to update your deployment platform's environment variables with the generated `FARCASTER_HEADER`, `FARCASTER_PAYLOAD`, and `FARCASTER_SIGNATURE` values. + + + + +The farcaster.json file contains metadata that allows clients to identify your Mini App and its capabilities. + +Create a route handler at `app/.well-known/farcaster.json/route.ts`: + +```typescript +function withValidProperties( + properties: Record +) { + return Object.fromEntries( + Object.entries(properties).filter(([key, value]) => { + if (Array.isArray(value)) { + return value.length > 0; + } + return !!value; + }) + ); +} + +export async function GET() { + const URL = process.env.NEXT_PUBLIC_URL; + + return Response.json({ + accountAssociation: { + header: process.env.FARCASTER_HEADER, + payload: process.env.FARCASTER_PAYLOAD, + signature: process.env.FARCASTER_SIGNATURE, + }, + frame: withValidProperties({ + version: '1', + name: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, + subtitle: process.env.NEXT_PUBLIC_APP_SUBTITLE, + description: process.env.NEXT_PUBLIC_APP_DESCRIPTION, + screenshotUrls: [], + iconUrl: process.env.NEXT_PUBLIC_APP_ICON, + splashImageUrl: process.env.NEXT_PUBLIC_APP_SPLASH_IMAGE, + splashBackgroundColor: process.env.NEXT_PUBLIC_SPLASH_BACKGROUND_COLOR, + homeUrl: URL, + webhookUrl: `${URL}/api/webhook`, + primaryCategory: process.env.NEXT_PUBLIC_APP_PRIMARY_CATEGORY, + tags: [], + heroImageUrl: process.env.NEXT_PUBLIC_APP_HERO_IMAGE, + tagline: process.env.NEXT_PUBLIC_APP_TAGLINE, + ogTitle: process.env.NEXT_PUBLIC_APP_OG_TITLE, + ogDescription: process.env.NEXT_PUBLIC_APP_OG_DESCRIPTION, + ogImageUrl: process.env.NEXT_PUBLIC_APP_OG_IMAGE, + // use only while testing + noindex: true, + }), + }); +} +``` + + + While testing your Mini App please add noIndex:true to your manifest - this is + so the app is not indexed while in developement. + + + +Test this endpoint by visiting `https://yourdomain.com/.well-known/farcaster.json` to ensure it returns valid JSON. + + + + +Configure the metadata that clients use to render your Mini App in posts and generate preview cards. + +**File: `app/layout.tsx`** + +```typescript +import { Metadata } from 'next'; + +export async function generateMetadata(): Promise { + const URL = process.env.NEXT_PUBLIC_URL; + return { + title: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, + description: + 'Generated by `create-onchain --mini`, a Next.js template for MiniKit', + other: { + 'fc:frame': JSON.stringify({ + version: 'next', + imageUrl: process.env.NEXT_PUBLIC_APP_HERO_IMAGE, + button: { + title: `Launch ${process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME}`, + action: { + type: 'launch_frame', + name: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, + url: URL, + splashImageUrl: process.env.NEXT_PUBLIC_SPLASH_IMAGE, + splashBackgroundColor: + process.env.NEXT_PUBLIC_SPLASH_BACKGROUND_COLOR, + }, + }, + }), + }, + }; +} +``` + + +All image and API URLs used here must be publicly accessible via HTTPS. Test each URL in your browser before deploying. + + + + +Before sharing your Mini App, validate that everything is working correctly. + + + +Verify the following before going live: + +- ✅ App is deployed at a public HTTPS domain +- ✅ All environment variables are set on your deployment platform +- ✅ All referenced images are accessible in your `public/` folder +- ✅ The `.well-known/farcaster.json` endpoint returns valid JSON +- ✅ Your app loads without errors in a browser + + + + +Use these tools to test your configuration: + +**Manifest Validator:** + +``` +https://farcaster.xyz/~/developers/mini-apps/manifest +``` + +This tool validates: + +- Manifest can be loaded successfully +- Frame metadata is correctly formatted +- Button actions and preview images are functioning +- Account association is properly configured + +**Manual Testing:** + +1. Visit your deployed URL directly in a browser +2. Check browser console for any errors +3. Verify the MiniKit context loads properly +4. Test frame readiness functionality + + + + +Once validation passes: + +1. **Create a cast** with your app's URL in Farcaster +2. **Verify the preview** displays your hero image and launch button +3. **Test the launch experience** by clicking the button +4. **Share with others** for feedback and testing + + + If your app doesn't render as an embed, double-check your manifest + configuration and ensure all URLs are publicly accessible. + + + + + + +If you encounter issues, check our comprehensive debugging guide for common problems and solutions. + + +
+ +## Understanding MiniKit Context + +### What `useMiniKit` Gives You + +The `useMiniKit()` hook provides access to everything your Mini App needs to understand the Farcaster session: + + + The Farcaster ID of the current user + + + + Whether the user has added your Mini App to their account + + + + Where the app was launched from (e.g., "cast", "launcher", "notification") + + + + Whether your app has called `setFrameReady()` and is ready to be shown + + + + Function to call when your app is fully loaded and ready for interaction + + +You can use this context to personalize the experience, trigger different flows, or track user behavior. + +## Available MiniKit Hooks + +MiniKit provides a comprehensive set of hooks designed to help you build rich, social experiences: + + + +Send in-app and push notifications to users who have added your frame + + + + Allow users to save your mini app to their Farcaster client for easy access + + + + Programmatically close the mini app frame when appropriate + + + + Open external URLs from within the frame context + + + + Configure and handle primary button interactions + + + + Navigate users to Farcaster profiles (their own or others) + + + +Handle Farcaster authentication and sign-in flows + + + + + Learn about all available MiniKit hooks, their parameters, and usage examples + + +## Next Steps + +Now that your Mini App is integrated and deployed: + + + +Share your Mini App URL in Farcaster and test all functionality with real users. + + + + Use analytics to understand how users interact with your app and identify + areas for improvement. + + + +Consider adding notifications, authentication, or other MiniKit hooks to enhance the user experience. + + diff --git a/docs/base-app/miniapps/overview.mdx b/docs/base-app/miniapps/overview.mdx new file mode 100644 index 000000000..af9730991 --- /dev/null +++ b/docs/base-app/miniapps/overview.mdx @@ -0,0 +1,464 @@ +--- +title: MiniKit Overview +description: Easiest way to build Mini Apps on Base +--- + + + MiniKit + + +MiniKit is easiest way to build Mini Apps on Base, allowing developers to easily build applications without needing to know the details of the SDK implementation. It integrates seamlessly with OnchainKit components and provides Coinbase Wallet-specific hooks. + +## Why MiniKit? + +MiniKit streamlines mini-app development by providing a comprehensive toolkit that makes complex Farcaster SDK interactions intuitive: + + + +Build apps with minimal knowledge of the Farcaster SDK + + + + Access Coinbase Wallet-specific hooks + + + + Use [OnchainKit](https://onchainkit.xyz/) components out of the box with + MiniKit + + + +CLI tool for quick project scaffolding with webhooks and notifications + + + +## Use Cases + + + + + + + +And many more possibilities! + +## Quick Start + +The fastest way to get started with MiniKit is to use the CLI to bootstrap a new project: + +```bash +npx create-onchain --mini +``` + + + You can also follow our comprehensive Quick Start guide for detailed setup + instructions + + +This command will: + + + +Set up a new project with both frontend and backend components + + +Configure webhooks and notifications + +Set up account association generation + + +Create a demo app showcasing onchain abilities using OnchainKit + + + +After running the command, follow the prompts to configure your project. + + + We recommend using [Vercel](https://vercel.com) to deploy your MiniKit app, as + it integrates seamlessly with the upstash/redis backend required for webhooks, + and notifications. The CLI will guide you through setting up the necessary + environment variables for your Redis database. + + +## Provider + +The `MiniKitProvider` wraps your application and provides global access to the SDK's context. It handles initialization, events, and automatically applies client safeAreaInsets to ensure your app doesn't overlap parent application elements. + +```tsx +import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; + +function App({ children }) { + return ( + + {children} + + ); +} +``` + +### Props + +The `MiniKitProvider` accepts the following props: + + + React components to be wrapped by the provider + + + + Optional URL to override the default `/api/notification` proxy + + + + All props from `OnchainKitProvider` are also supported + + +The provider sets up wagmi and react-query providers automatically. It configures connectors to use the Farcaster connector if `sdk.context` is set, with a fallback to CoinbaseWallet. This allows the same application to run both as a Mini App and as a standalone application. + +## Hooks + +MiniKit provides several utility hooks that wrap the SDK functionality, making it easy to access different features. + +### useMiniKit + +This hook handles initialization of the application and provides access to the SDK context. + +```tsx +const { + setFrameReady, + isFrameReady, + context, + updateClientContext, + notificationProxyUrl, +} = useMiniKit(); + +// Call setFrameReady() when your app is ready to be shown +useEffect(() => { + if (!isFrameReady) { + setFrameReady(); + } +}, [isFrameReady, setFrameReady]); +``` + +**Returns:** + + + Removes splash screen and shows the application + + + + Whether the app is ready to be shown + + + + The current frame context + + + + Update client context + + + + The notification proxy URL + + +### useAddFrame + +This hook adds a Mini App to the user's list of Mini Apps and returns notification details. + +```tsx +const addFrame = useAddFrame(); + +// Usage +const handleAddFrame = async () => { + const result = await addFrame(); + if (result) { + console.log('Frame added:', result.url, result.token); + } +}; +``` + +**Returns:** + + + Function that adds frame and returns notification details + + +### useNotification + +This hook allows sending notifications to users who have added your frame. It requires a token and URL, which are returned when a user adds your frame. + +```tsx +const sendNotification = useNotification(); + +// Usage +const handleSendNotification = () => { + sendNotification({ + title: 'New High Score!', + body: 'Congratulations on your new high score!', + }); +}; +``` + + + Notifications require a backend proxy to avoid CORS restrictions. The CLI + automatically sets up this proxy at `/api/notification`, but you can override + this in the `MiniKitProvider`. + + +### useOpenUrl + +This hook wraps `sdk.actions.openUrl` and falls back to `window.open` when outside a frame context. + +```tsx +const openUrl = useOpenUrl(); + +// Usage +; +``` + +### useClose + +This hook wraps the `sdk.actions.close` functionality. + +```tsx +const close = useClose(); + +// Usage +; +``` + +### useComposeCast + +The `useComposeCast` hook provides functionality to open the Farcaster compose interface with pre-filled content. + +```tsx +import { useComposeCast } from '@coinbase/onchainkit/minikit'; + +export default function ComposeCastButton() { + const { composeCast } = useComposeCast(); + + const handleCompose = () => { + composeCast({ + text: 'Just minted an awesome NFT using @coinbase OnchainKit! 🚀', + }); + }; + + const handleComposeWithEmbed = () => { + composeCast({ + text: 'Check out this amazing frame!', + embeds: ['https://your-frame-url.com'], + }); + }; + + return ( +
+ + +
+ ); +} +``` + +**Parameters:** + +- `text: string` - The text content for the cast +- `embeds?: string[]` - Optional array of URLs to embed in the cast + +**Returns:** + +- `composeCast: (params: ComposeCastParams) => void` - Function to open compose interface + +### useViewCast + +The `useViewCast` hook provides functionality to view a specific Farcaster cast by its hash. + +```tsx +import { useViewCast } from '@coinbase/onchainkit/minikit'; + +export default function ViewCastButton() { + const { viewCast } = useViewCast(); + + const handleViewCast = () => { + viewCast({ + hash: '0x32aed77ca61c92d253b98983f1e0fd20a8bd5745', + }); + }; + + const handleViewAnotherCast = () => { + viewCast({ + hash: '0x48f4d2c45e7b1a923d5c6f8e9a7b2c1d5e8f3a6b', + }); + }; + + return ( +
+ + +
+ ); +} +``` + +**Parameters:** + +- `hash: string` - The hash of the cast to view + +**Returns:** + +- `viewCast: (params: ViewCastParams) => void` - Function to view a specific cast + +### usePrimaryButton + +This hook accepts primary button options and a callback which will be called on click. + +```tsx +usePrimaryButton({ text: 'Submit Score' }, () => { + // Handle button click + submitScore(); +}); +``` + +### useViewProfile + +This hook wraps `sdk.actions.viewProfile`, accepting an FID but falling back to the client's FID. + +```tsx +const viewMyProfile = useViewProfile(); // Uses client's FID +const viewUserProfile = useViewProfile(123456); // Uses specified FID + +// Usage + + +``` + +### useAuthenticate + +This hook allows users to sign in with Farcaster. It wraps the SDK's signIn message, adding a default nonce and verification. + +```tsx +const { signIn } = useAuthenticate(); + +// Usage +const handleSignIn = async () => { + const result = await signIn({ + domain: 'your-domain.com', + siweUri: 'https://your-domain.com/login', + }); + + if (result) { + // Handle successful authentication + console.log('Authenticated:', result); + } +}; +``` + + + Authentication requires additional setup utilizing an auth framework like + next/auth or manually integrating session storage and route/component + authentication. + + +## CLI + +The MiniKit CLI is the easiest way to get started. It automatically creates a sample application that integrates different parts of the SDK and some OnchainKit components. + +```bash +npx create-onchain --mini +``` + +### Features + +The CLI creates an application with: + + + +Complete setup for adding Mini Apps, webhooks, and notifications using upstash/redis for data storage (compatible with Vercel). Requires users to sign up for an upstash/redis account and add their key and URL to the .env file. + + +The CLI creates both frontend and backend components to support adding Mini Apps, webhooks, and notifications. While a frontend-only option was considered, the ability to add Mini Apps and handle notifications requires backend support. If you don't need these features, you can easily remove the database and related routes after project creation. + + + + + Automatically generates valid account associations and configures the + necessary environment variables. + + + +Sets up the required configuration file: + +```json +{ + "accountAssociation": { + "header": "eyJmaWQiOjgxODAyNiwidHlwZSI6ImN1c3RvZHkiLCJrZXkiOiIweDU4YjU1MTNjMzk5OTYzMjU0MjMzMmU0ZTJlRDAyOThFQzFmRjE4MzEifQ", + "payload": "eyJkb21haW4iOiI4MGI2LTI2MDAtMWYxOC0yNGM5LTYxMDUtNS0wLTQtNzA2Lm5ncm9rLWZyZWUuYXBwIn0", + "signature": "MHhmOGQ1YzQyMmU3ZTZlMWNhMzU1ZmNmN2ZjYzFmYjMyZWRhZmEyNWU1NjJiMzlhYzE4OWNlMmM5ODU3Y2JjZWViNzlkZTk2ZjhiNTc5NzZjMDM2NzM4Y2UwYjhhOGQxZmMyZDFhYzA2NTdiZTU5N2VhZjFhZDE1ODBmMGQyYjJhODFi" + }, + "frame": { + "version": "next", + "name": "MiniKit", + "iconUrl": "https://onchainkit.xyz/favicon/48x48.png?v4-19-24", + "splashImageUrl": "https://onchainkit.xyz/favicon/48x48.png?v4-19-24", + "splashBackgroundColor": "#000000", + "homeUrl": "https://your-domain.app/minikit" + } +} +``` + + + + + Automatically sets up a proxy route at `/api/notification` used by the + `useNotification` hook when sending notifications. + + + +Implements webhooks using the Farcaster key registry contract for verification. Allows applications to respond to events such as `FRAME_ADDED`. + + + +### Demo Application + +The CLI also creates a demo snake game application that showcases: + +- Buttons to add the frame and connect your wallet +- High score tracking with attestations using OnchainKit's `` component +- Score display using OnchainKit's `` components to resolve ENS names +- Notifications for high scores (rate limited to one every 30 seconds) + +## Next Steps + +Now that you have MiniKit set up, you can: + + + +Explore the demo application to understand how the hooks work + + + + Customize the application to fit your needs + + + +Deploy your application to a hosting provider like Vercel + + + +Enjoy building! diff --git a/docs/base-app/miniapps/quickstart.mdx b/docs/base-app/miniapps/quickstart.mdx new file mode 100644 index 000000000..597621e8c --- /dev/null +++ b/docs/base-app/miniapps/quickstart.mdx @@ -0,0 +1,415 @@ +--- +title: 'MiniKit Quickstart' +description: 'Learn how to build mini apps on Base with MiniKit - from setup to deployment and advanced features' +--- + +This guide shows you how to get started with MiniKit, the easiest way to build mini apps on Base! It can also be used to update an existing standalone app to a mini app. We'll start by setting up the template project with the CLI tool and then explore both built-in and additional features of MiniKit. + +## Prerequisites + +Before you begin developing with MiniKit, you'll need: + +1. **Farcaster Account**: Create an account on [Farcaster](https://farcaster.xyz/) to test and deploy your Mini Apps. + +2. **Coinbase Developer Platform Account** (Optional): Sign up for a [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) account if you need CDP API key for additional functionalities. + +## What is a Mini App? + +A mini app is a lightweight web app that runs directly inside [Farcaster](https://docs.farcaster.xyz/developers/frames/v2/), without needing to open a browser or download anything. Built using familiar tools like Next.js and minikit, mini apps behave just like normal apps — but launch instantly from posts, making them feel native to the Farcaster experience. + +## Initial Setup + + + +```bash +npx create-onchain --mini +``` + + + + You can get a CDP API key by going to the [CDP + Portal](https://www.coinbase.com/developer-platform) and navigating API Keys → + Client API Key. + + + + You will be asked if you'd like to set up your manifest. You can skip the + manifest setup step as we'll handle that separately once we know our project's + URL. + + + +```bash Terminal +cd your-project-name +npm install +npm run dev +``` + + +These docs are LLM-friendly—reference [llms.txt](https://docs.base.org/base-app/build-with-minikit/llms.txt) in your code editor to streamline builds and prompt smarter. + + + + +## Testing Your Mini App + +To test your Mini App in Farcaster, you'll need a live URL. + +We recommend using [Vercel](https://vercel.com) to deploy your MiniKit app, as it integrates seamlessly with the upstash/redis backend required for stateful Mini Apps, webhooks, and notifications. + +Alternatively, you can use ngrok to tunnel your localhost to a live url. + + + + + + To successfully test your app, you'll need the paid version of ngrok. The free + version has an approval screen which can break the frame manifest. Also the + url for the free version will change every time requiring you to update the + manifest each time you start a new ngrok tunnel. + + +1. Start your development server: + +```bash Terminal +npm run dev +``` + +2. Install and start ngrok to create a tunnel to your local server: + +```bash Terminal +# Install ngrok if you haven't already +npm install -g ngrok + +# Create a tunnel to your local server (assuming it's running on port 3000) +ngrok http 3000 +``` + +3. Copy the HTTPS URL provided by ngrok (e.g. `https://your-tunnel.ngrok.io`) + +4. Visit the [Farcaster Manifest Tool](https://farcaster.xyz/~/developers/mini-apps/manifest) + +5. Paste your ngrok URL into "Domain" and tap Submit + + + + +### Deploying to Vercel + + + +```bash +npm install -g vercel +``` + + +```bash vercel ``` + + +You can use `vercel env add` to set these up via CLI: + +- NEXT_PUBLIC_CDP_CLIENT_API_KEY (from [CDP Portal](https://www.coinbase.com/developer-platform)) +- NEXT_PUBLIC_URL (deployed app URL) +- NEXT_PUBLIC_IMAGE_URL (optional) +- NEXT_PUBLIC_SPLASH_IMAGE_URL (optional) +- NEXT_PUBLIC_SPLASH_BACKGROUND_COLORs + + + + +You can now test your mini app: + +1. Copy your deployed vercel URL +2. Visit the [Farcaster Manifest Tool](https://farcaster.xyz/~/developers/mini-apps/manifest) +3. Paste URL into "Domain" +4. Tap Submit + +## Exploring Built-in Features + +The template comes with several pre-implemented features. Let's explore where they are and how they work. + +### MiniKitProvider + +The `MiniKitProvider` is set up in your `providers.tsx` file. It wraps your application to handle initialization, events, and automatically applies client safeAreaInsets to ensure your app doesn't overlap parent application elements. + +```tsx app/providers.tsx +import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; + +export function Providers(props: { children: ReactNode }) { + return ( + + {props.children} + + ); +} +``` + +The MiniKitProvider also sets up your wagmi and react-query providers automatically, eliminating that initial setup work. + +### useMiniKit + +The `useMiniKit` hook is implemented in your main page component (`app/page.tsx`). It handles initialization of the frame and provides access to the SDK context. + +```tsx app/page.tsx +const { setFrameReady, isFrameReady, context } = useMiniKit(); + +// The setFrameReady() function is called when your mini-app is ready to be shown +useEffect(() => { + if (!isFrameReady) { + setFrameReady(); + } +}, [setFrameReady, isFrameReady]); +``` + +### Creating the Manifest + +The Frame Manifest is required in order for users to save the frame to their account. This means its also required to send notifications to the user. We initially skipped this step when setting up the app. Now that we know our vercel url, we can configure our manifest. + +To set up the manifest, run the following in your Terminal + +```bash Terminal +npx create-onchain --manifest +``` + +Enter `y` to proceed with the setup and your browser will open to the following page: + + + Manifest Setup + + + + The wallet that you connect must be your Farcaster custody wallet. You can + import this wallet to your preferred wallet using the recovery phrase. You can + find your recovery phrase in the Farcaster app under Settings → Advanced → + Farcaster recovery phrase. + + +Once connected, add the vercel url and sign the manifest. This will automatically update your .env variables locally, but we'll need to update Vercel's .env variables. + +Create the following new .env variables in your vercel instance and paste the value you see in your local.env file: + + + Base64 encoded header from manifest generation + + + + Base64 encoded payload from manifest generation + + + + Signature from manifest generation + + +Now that the manifest is correctly set up, the Save Frame button in the template app should work. We'll explore that below. + + + While testing your Mini App please add noIndex:true to your manifest - this is + so the app is not indexed while in developement. + + +### useAddFrame + +The `useAddFrame` hook is used to add your mini app to the user's list of mini apps. It's implemented in your main page component and displays a button in the top right allowing the user to add the mini app to their list. + +When a user adds the mini app, it returns a url and token, which is used for sending the user notifications. For this walkthrough we'll simply console.log those results to use them later when setting up notifications. + +```tsx app/page.tsx +const addFrame = useAddFrame(); + +// Usage in a button click handler +const handleAddFrame = async () => { + const result = await addFrame(); + if (result) { + console.log('Frame added:', result.url, result.token); + } +}; +``` + + + In production, you'll want to save the url and token associated with each user + in a persistent database so that you can send them notifications over time. + + +### useOpenUrl + +The `useOpenUrl` hook is used to open external URLs from within the frame. In the template, its used in the footer button which links to the MiniKit page. + +```tsx app/page.tsx +const openUrl = useOpenUrl() + +// Usage in a button click handler + + +// Then in the return function +
+ +
+``` + +Now that we've reviewed the MiniKit template and the functionality already implemented, lets add some additional MiniKit features. + +## Additional MiniKit Features + +Now, let's implement additional hooks provided by the MiniKit library. We'll add these features one by one. + +### useClose + +First, let's add the ability to close the frame from within the interface: + +```tsx app/page.tsx +// Add useClose to the import list +import { useMinikit, useAddFrame, useOpenUrl, useClose } from '@coinbase/onchainkit/minikit' + +// Add the hook +const close = useClose() + +// Add the button in the header right after the `saveFrameButton` +
+ {saveFrameButton} + +
+``` + + + If you reload the frame in the Farcaster dev tools preview, you'll now see the + close button in the top right. + + +### usePrimaryButton + +The Primary Button is a button that always exists at the bottom of the frame. Its good for managing global state which is relevant throughout your mini app. + +For the template example, we'll use the Primary Button to Pause and Restart the game. The game state is managed within the `snake.tsx` component, and we can easily add the `usePrimaryButton` hook there since the MiniKit hooks are available throughout the app. + +```tsx app/components/snake.tsx +// add an import for usePrimaryButton +import { usePrimaryButton } from '@coinbase/onchainkit/minikit'; + +// game state already exists, so we'll leverage that below. +usePrimaryButton( + { text: gameState == GameState.RUNNING ? 'PAUSE GAME' : 'START GAME' }, + () => { + setGameState( + gameState == GameState.RUNNING ? GameState.PAUSED : GameState.RUNNING + ); + } +); +``` + + +You'll notice that adding the Primary button takes up space at the bottom of the frame, which causes the "BUILT ON BASE WITH MINIKIT" button to move upwards and overlap with the controls. +We can quickly fix that by changing the text to "BUILT WITH MINIKIT" and removing the `ml-4` style in the `className` of the `; +``` + +### useNotification + +One of the major benefits of mini apps is that you can send notifications to your users through their social app. + +Recall the token and url we saved in the [useAddFrame section](#useaddframe)? We'll use those now to send a user a notification. In this guide, we'll simply send a test notification unrelated to the game activity. + +```tsx app/page.tsx +//add useNotification to the import list +import {..., useNotification } from '@coinbase/onchainkit/minikit' + +// Add the hook +const sendNotification = useNotification() + +// Add the handler function +const handleSendNotification = async () => { + try { + await sendNotification({ + title: 'New High Score! 🎉', + body: 'Congratulations on achieving a new high score!' + }) + setTimeout(() => setNotificationSent(false), 30000) + } catch (error) { + console.error('Failed to send notification:', error) + } +} + +// Add the button in your UI +{context?.client.added && ( + +)} +``` + + + Notice that we first check if the user has added the frame to their list of + mini apps before displaying the button. This is using the `context` object + provided by `useMiniKit()`. If you don't see the button to send the + notification, its likely because mini app hasn't been saved. + + +## Conclusion + +Congratulations, you've created your first mini app, set up the manifest, added key MiniKit hooks, and sent your users a notification! We're excited to see what you build with MiniKit! + + + +Learn more about MiniKit features and capabilities + + + +Design patterns for social mini apps + + diff --git a/docs/base-app/miniapps/thinking-social.mdx b/docs/base-app/miniapps/thinking-social.mdx new file mode 100644 index 000000000..d5cec4e85 --- /dev/null +++ b/docs/base-app/miniapps/thinking-social.mdx @@ -0,0 +1,294 @@ +--- +title: Build Viral Mini Apps +description: Designing mini apps that people actually come back to +--- + +**Designing mini apps that people actually come back to.** + +Most apps can launch. But few become part of someone's daily rhythm. +That's usually not a product problem. It's a people problem. + +Social mini apps live or die based on how they make people feel: seen, connected, curious or like they belong. That's not something you tack on — it's something you build in from the start. + +If you're designing for feed-based platforms (like Farcaster, Threads, or anything with posts, reactions, and reply chains), this guide will help you: + + + + + + + +## How to Use This Guide + +Welcome to your blueprint for designing social mini‑apps that people love to revisit. This guide is organized into distinct, actionable sections—each building on the last—to help you move from idea validation to deploying social features with purpose. + + + +Before writing a single line of code or sketching UI, use our four diagnostic questions to see if your concept naturally supports social behavior. Drop your one‑line idea into the supplied prompt to get clear insights on post frequency, social lift, content momentum, and emotional payoff. + + + + Analyze the responses. Identify which one or two social dimensions resonate + most with your concept—whether it's habit formation, community spark, content + growth, or emotional reward. The guide shows you how to validate and + prioritize those dimensions before moving forward. + + + + See a worked example that demonstrates how to translate test results into a + prototype feature. This mini case study will illustrate rapid iteration, + metric considerations, and how to decide when you're ready to scale social + elements. + + + +Dive into the heart of the guide—three social patterns designed to deepen engagement: + +- **Identity Playgrounds:** Customization and self‑expression +- **Co‑Creation Loops:** Collaboration and building on each other's posts +- **Long‑Term Rituals:** Scheduled, shared activities that foster habit and community + +Each pattern includes explanations, real‑world examples, and copy‑and‑paste prompts to spark your own brainstorming. + + + + +Finish with a set of reflective questions and practical advice on measuring success. Use the closing prompts to refine your roadmap, plan experiments, and define key metrics for daily, weekly, and monthly engagement. + + + + +**Tips for Getting the Most Out of This Guide:** + +- **Iterate Quickly:** Treat prompts and patterns as hypotheses. Prototype fast, gather data, and refine. +- **Stay Human‑Centered:** At every stage, ask: "How will this make someone feel?" +- **Measure What Matters:** Define metrics for each dimension early—then use them to validate your choices. +- **Keep It Simple:** You don't need every pattern at once. Start with the one or two dimensions that align strongest with your concept. + + +## Pressure-test your idea + +Before you get into features or UI, take a step back. Ask whether your idea wants to be social — or if you're forcing it. These prompts are designed to give you structured, clear feedback if you drop them into a LLM or use them in your own reflection. + +``` +Here's a one-line description of my app: [insert idea]. + +Evaluate it across these questions: + +1. Why would someone post here more than once? +2. Would the experience be better with another person involved? +3. What kind of content might naturally fill the feed over time? +4. What emotional reward might someone feel when they open it? + +Please be direct. If the idea lacks natural social behavior, suggest ways it could evolve. +``` + +## Social Patterns + +### 1. Identity Playgrounds + +**The idea:** Give people ways to explore, express, or shape their identity within the app. + +**Why it works:** People don't just use feeds to consume — they use them to perform. Customization invites play, self-expression, and experimentation. + +**Where it shows up:** Discord roles, Reddit flair, Tumblr themes. + +**Use it for:** Differentiation, emotional investment, repeat posting. + +``` +Given my app idea: [insert idea], explore 2 ways users might express or explore identity. + +For each, include: +– What the user customizes or signals +– How that shows up in the feed +– Why that might matter over time +``` + +### 2. Co-Creation Loops + +**The idea:** Design behaviors that are better when shared — where users build on each other's contributions. + +**Why it works:** The strongest feeds don't just display content; they build momentum. If one person's post sparks another, you get a chain reaction. + +**Where it shows up:** Remix threads, collab playlists, group journaling. + +**Use it for:** Participation loops, content momentum, chain reactions. + +``` +How could users in [insert app idea] create something together or build on each other's actions? +Return 3 co-creation flows that include: +– What kicks it off +– How others join in +– What the feed looks like after a few days +``` + +### 3. Long-Term Rituals + +**The idea:** Introduce regular, shared behaviors that become a rhythm. + +**Why it works:** Rituals create predictability, belonging, and anticipation. They give users a reason to come back on a schedule. + +**Where it shows up:** Wordle scores, Monday memes, Friday drops, yearly Spotify Wrapped. + +**Use it for:** Habit loops, appointment-based engagement, social cohesion. + +``` +Design 2 recurring rituals for [insert app idea]. + +For each, include: +– Frequency (daily, weekly, monthly) +– What users post +– What emotion or payoff they get +– How it could spread through the feed +``` + +## Interpreting your feedback + +After you get back raw answers to the four pressure‑test questions, look for the one or two dimensions that most naturally fit your idea. Nail those first, then decide if you need to shore up any others. + + + +Scan your AI responses for signs of strength in these four key areas: + + + +**Look for:** "Daily check‑ins create habit" or "Natural reason to post weekly" + + + + **Look for:** "Comments spark friendly competition" or "Better with others + involved" + + + + **Look for:** "Automated reminders nudge new posts" or "Community‑driven + growth" + + + +**Look for:** "Badges tap into achievement" or "Pride in sharing progress" + + + + +Focus on the dimensions where the AI feedback was most enthusiastic and specific. Vague responses usually indicate weak social potential. + + + + +For each dimension that scored well, confirm the feedback includes clear, actionable examples: + + + +**Strong signal:** At least 1 post per week feels natural to users + +**Examples to look for:** + +- "Users would naturally share daily progress" +- "Weekly challenges create posting rhythm" +- "Status updates become habitual" + +**Red flag:** Forced or infrequent posting suggestions + + + + +**Strong signal:** Others are meaningfully involved, not just passive viewers + +**Examples to look for:** + +- "Friends can collaborate on projects" +- "Comments turn into conversations" +- "Peer reactions drive engagement" + +**Red flag:** Social features feel like an afterthought + + + + +**Strong signal:** Community‑driven growth that builds over time + +**Examples to look for:** + +- "Posts inspire similar content from others" +- "Trending topics emerge naturally" +- "User‑generated content feeds itself" + +**Red flag:** Content relies entirely on individual creators + + + + +**Strong signal:** Opening the app delivers a felt reward + +**Examples to look for:** + +- "Users feel proud sharing progress" +- "Achievements create satisfaction" +- "Community recognition feels meaningful" + +**Red flag:** Emotional benefits are unclear or generic + + + + + + +Now that you've identified your strongest dimensions, here's how to proceed: + + + +**You're ready to build!** + +If your top 1–2 dimensions check out, skip straight to building social features around them. You don't need to perfect all four dimensions before starting. + + +Focus your energy on the social angles that truly resonate with your concept first. + + + + +**Iterate before building** + +If your dimensions are weak, spend time strengthening them before moving to development: + +- **Add a relational hook** (how do others get involved?) +- **Include a habit prompt** (what brings people back?) +- **Create emotional stakes** (why should users care?) + + +Don't force social features onto an inherently solo experience. Consider if your idea needs to evolve. + + + + +**Example Decision Flow:** + +You see strong **"Social lift"** ("Friends' reactions spark threads") and decent **"Emotional payoff"** ("Likes feel rewarding"). + +✅ **Decision:** Prototype a co‑posting feature focusing on these strengths + +⏳ **Later:** Explore "Content momentum" and "Repeat‑posting" patterns once core social features are solid + + +This focused approach prevents feature bloat and ensures you build social mechanics that actually work for your specific concept. + + + + +## Closing note + +The mini apps that thrive aren't the most complex — they're the ones that understand how people connect. + + +**Remember:** + +- Social features only work when they reflect real human behavior +- A feed isn't just content — it's a shared ritual +- True engagement comes from meaning over mechanics + + +As you build, ask: _Why would someone want to come back? Why would they share this with a friend?_ Those answers matter more than any feature list. + +The best apps don't just fill feeds. They create places people want to return to. +So — what will your app make people feel? From f253a30bde9cd66347a18b348d03cc0c9726d351 Mon Sep 17 00:00:00 2001 From: Patrick Hughes Date: Sat, 9 Aug 2025 21:01:38 -0500 Subject: [PATCH 7/7] fix closing tags --- docs/base-app/miniapps/thinking-social.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/base-app/miniapps/thinking-social.mdx b/docs/base-app/miniapps/thinking-social.mdx index d5cec4e85..2517c20a7 100644 --- a/docs/base-app/miniapps/thinking-social.mdx +++ b/docs/base-app/miniapps/thinking-social.mdx @@ -64,7 +64,8 @@ Finish with a set of reflective questions and practical advice on measuring succ - **Stay Human‑Centered:** At every stage, ask: "How will this make someone feel?" - **Measure What Matters:** Define metrics for each dimension early—then use them to validate your choices. - **Keep It Simple:** You don't need every pattern at once. Start with the one or two dimensions that align strongest with your concept. - + +
## Pressure-test your idea @@ -286,7 +287,8 @@ The mini apps that thrive aren't the most complex — they're the ones that unde - Social features only work when they reflect real human behavior - A feed isn't just content — it's a shared ritual - True engagement comes from meaning over mechanics - + + As you build, ask: _Why would someone want to come back? Why would they share this with a friend?_ Those answers matter more than any feature list.