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. 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 - diff --git a/docs/base-app/build-with-minikit/debugging.mdx b/docs/base-app/miniapps/debugging.mdx similarity index 100% rename from docs/base-app/build-with-minikit/debugging.mdx rename to docs/base-app/miniapps/debugging.mdx diff --git a/docs/base-app/build-with-minikit/existing-app-integration.mdx b/docs/base-app/miniapps/existing-app-integration.mdx similarity index 68% rename from docs/base-app/build-with-minikit/existing-app-integration.mdx rename to docs/base-app/miniapps/existing-app-integration.mdx index 2d3317efc..d1ff3c27c 100644 --- a/docs/base-app/build-with-minikit/existing-app-integration.mdx +++ b/docs/base-app/miniapps/existing-app-integration.mdx @@ -1,13 +1,14 @@ --- -title: Integrating MiniKit with Existing Applications +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. + 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 @@ -19,12 +20,14 @@ 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. + + 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. + + You have an active Farcaster account for testing and access to your custody + wallet. @@ -76,13 +79,15 @@ Then wrap your app in `app/layout.tsx`: ```jsx import { MiniKitContextProvider } from '@/providers/MiniKitProvider'; -export default function RootLayout({ children }: { children: React.ReactNode }) { +export default function RootLayout({ + children, +}: { + children: React.ReactNode, +}) { return ( - + - - {children} - + {children} ); @@ -131,24 +136,24 @@ 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 name of your Mini App as it appears to users - -The deployed URL of your application (must be HTTPS) + + The deployed URL of your application (must be HTTPS) - -Your Coinbase Developer Platform API key + + 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 + + Generated during manifest creation for account association @@ -159,44 +164,44 @@ 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) + + URL to your app's icon (recommended: 48x48px PNG) - -Brief subtitle shown in app listings + + Brief subtitle shown in app listings - -Detailed description of your app's functionality + + Detailed description of your app's functionality - -URL to splash screen image shown during app loading + + URL to splash screen image shown during app loading - -Hex color code for splash screen background (e.g., "#000000") + + Hex color code for splash screen background (e.g., "#000000") - -Primary category for app discovery (e.g., "social", "gaming", "utility") + + Primary category for app discovery (e.g., "social", "gaming", "utility") - -Hero image URL displayed in cast previews + + Hero image URL displayed in cast previews - -Short, compelling tagline for your app + + Short, compelling tagline for your app - -Open Graph title for social media sharing + + Open Graph title for social media sharing - -Open Graph description for social media sharing + + Open Graph description for social media sharing @@ -218,7 +223,9 @@ 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. + **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: @@ -240,7 +247,7 @@ Create a route handler at `app/.well-known/farcaster.json/route.ts`: ```typescript function withValidProperties( - properties: Record, + properties: Record ) { return Object.fromEntries( Object.entries(properties).filter(([key, value]) => { @@ -248,7 +255,7 @@ function withValidProperties( return value.length > 0; } return !!value; - }), + }) ); } @@ -262,7 +269,7 @@ export async function GET() { signature: process.env.FARCASTER_SIGNATURE, }, frame: withValidProperties({ - version: "1", + version: '1', name: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, subtitle: process.env.NEXT_PUBLIC_APP_SUBTITLE, description: process.env.NEXT_PUBLIC_APP_DESCRIPTION, @@ -279,14 +286,16 @@ export async function GET() { 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 + // 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. + While testing your Mini App please add noIndex:true to your manifest - this is + so the app is not indexed while in developement. @@ -307,15 +316,15 @@ export async function generateMetadata(): Promise { return { title: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, description: - "Generated by `create-onchain --mini`, a Next.js template for MiniKit", + 'Generated by `create-onchain --mini`, a Next.js template for MiniKit', other: { - "fc:frame": JSON.stringify({ - version: "next", + '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", + type: 'launch_frame', name: process.env.NEXT_PUBLIC_ONCHAINKIT_PROJECT_NAME, url: URL, splashImageUrl: process.env.NEXT_PUBLIC_SPLASH_IMAGE, @@ -353,17 +362,20 @@ Verify the following before going live: 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 +- 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 @@ -380,7 +392,8 @@ Once validation passes: 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 your app doesn't render as an embed, double-check your manifest + configuration and ensure all URLs are publicly accessible. @@ -398,24 +411,24 @@ If you encounter issues, check our comprehensive debugging guide for common prob The `useMiniKit()` hook provides access to everything your Mini App needs to understand the Farcaster session: - -The Farcaster ID of the current user + + The Farcaster ID of the current user - -Whether the user has added your Mini App to their account + + Whether the user has added your Mini App to their account - -Where the app was launched from (e.g., "cast", "launcher", "notification") + + Where the app was launched from (e.g., "cast", "launcher", "notification") - -Whether your app has called `setFrameReady()` and is ready to be shown + + 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 + + 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. @@ -429,24 +442,24 @@ MiniKit provides a comprehensive set of hooks designed to help you build rich, s 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 + + Allow users to save your mini app to their Farcaster client for easy access - -Programmatically close the mini app frame when appropriate + + Programmatically close the mini app frame when appropriate - -Open external URLs from within the frame context + + Open external URLs from within the frame context - -Configure and handle primary button interactions + + Configure and handle primary button interactions - -Navigate users to Farcaster profiles (their own or others) + + Navigate users to Farcaster profiles (their own or others) @@ -454,8 +467,12 @@ Handle Farcaster authentication and sign-in flows - -Learn about all available MiniKit hooks, their parameters, and usage examples + + Learn about all available MiniKit hooks, their parameters, and usage examples ## Next Steps @@ -467,8 +484,9 @@ 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. + + Use analytics to understand how users interact with your app and identify + areas for improvement. diff --git a/docs/base-app/build-with-minikit/overview.mdx b/docs/base-app/miniapps/overview.mdx similarity index 71% rename from docs/base-app/build-with-minikit/overview.mdx rename to docs/base-app/miniapps/overview.mdx index 206fc7500..af9730991 100644 --- a/docs/base-app/build-with-minikit/overview.mdx +++ b/docs/base-app/miniapps/overview.mdx @@ -1,12 +1,10 @@ --- -title: Overview +title: MiniKit Overview description: Easiest way to build Mini Apps on Base --- -MiniKit + 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. @@ -20,12 +18,13 @@ MiniKit streamlines mini-app development by providing a comprehensive toolkit th Build apps with minimal knowledge of the Farcaster SDK - -Access Coinbase Wallet-specific hooks + + Access Coinbase Wallet-specific hooks - -Use [OnchainKit](https://onchainkit.xyz/) components out of the box with MiniKit + + Use [OnchainKit](https://onchainkit.xyz/) components out of the box with + MiniKit @@ -36,9 +35,9 @@ CLI tool for quick project scaffolding with webhooks and notifications ## Use Cases - - - + + + And many more possibilities! @@ -51,8 +50,13 @@ The fastest way to get started with MiniKit is to use the CLI to bootstrap a new npx create-onchain --mini ``` - -You can also follow our comprehensive Quick Start guide for detailed setup instructions + + You can also follow our comprehensive Quick Start guide for detailed setup + instructions This command will: @@ -62,13 +66,9 @@ This command will: Set up a new project with both frontend and backend components - -Configure webhooks and notifications - +Configure webhooks and notifications - -Set up account association generation - +Set up account association generation Create a demo app showcasing onchain abilities using OnchainKit @@ -78,7 +78,10 @@ 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. + 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 @@ -91,8 +94,8 @@ import { MiniKitProvider } from '@coinbase/onchainkit/minikit'; function App({ children }) { return ( {children} @@ -104,16 +107,20 @@ function App({ children }) { The `MiniKitProvider` accepts the following props: - -React components to be wrapped by the provider + + React components to be wrapped by the provider - -Optional URL to override the default `/api/notification` proxy + + Optional URL to override the default `/api/notification` proxy - -All props from `OnchainKitProvider` are also supported + + 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. @@ -127,7 +134,13 @@ MiniKit provides several utility hooks that wrap the SDK functionality, making i This hook handles initialization of the application and provides access to the SDK context. ```tsx -const { setFrameReady, isFrameReady, context, updateClientContext, notificationProxyUrl } = useMiniKit(); +const { + setFrameReady, + isFrameReady, + context, + updateClientContext, + notificationProxyUrl, +} = useMiniKit(); // Call setFrameReady() when your app is ready to be shown useEffect(() => { @@ -139,24 +152,27 @@ useEffect(() => { **Returns:** - -Removes splash screen and shows the application + + Removes splash screen and shows the application - -Whether the app is ready to be shown + + Whether the app is ready to be shown - -The current frame context + + The current frame context - -Update client context + + Update client context - -The notification proxy URL + + The notification proxy URL ### useAddFrame @@ -177,8 +193,11 @@ const handleAddFrame = async () => { **Returns:** - -Function that adds frame and returns notification details + + Function that adds frame and returns notification details ### useNotification @@ -192,13 +211,15 @@ const sendNotification = useNotification(); const handleSendNotification = () => { sendNotification({ title: 'New High Score!', - body: 'Congratulations on your 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`. + 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 @@ -209,7 +230,7 @@ This hook wraps `sdk.actions.openUrl` and falls back to `window.open` when outsi const openUrl = useOpenUrl(); // Usage - +; ``` ### useClose @@ -220,7 +241,7 @@ This hook wraps the `sdk.actions.close` functionality. const close = useClose(); // Usage - +; ``` ### useComposeCast @@ -248,22 +269,20 @@ export default function ComposeCastButton() { 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 @@ -290,36 +309,30 @@ export default function ViewCastButton() { return (
- - + +
); } ``` **Parameters:** + - `hash: string` - The hash of the cast to view **Returns:** -- `viewCast: (params: ViewCastParams) => void` - Function to view a specific cast +- `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(); - } -); +usePrimaryButton({ text: 'Submit Score' }, () => { + // Handle button click + submitScore(); +}); ``` ### useViewProfile @@ -346,7 +359,7 @@ const { signIn } = useAuthenticate(); const handleSignIn = async () => { const result = await signIn({ domain: 'your-domain.com', - siweUri: 'https://your-domain.com/login' + siweUri: 'https://your-domain.com/login', }); if (result) { @@ -357,7 +370,9 @@ const handleSignIn = async () => { ``` -Authentication requires additional setup utilizing an auth framework like next/auth or manually integrating session storage and route/component authentication. + Authentication requires additional setup utilizing an auth framework like + next/auth or manually integrating session storage and route/component + authentication. ## CLI @@ -381,8 +396,9 @@ The CLI creates both frontend and backend components to support adding Mini Apps - -Automatically generates valid account associations and configures the necessary environment variables. + + Automatically generates valid account associations and configures the + necessary environment variables. @@ -405,10 +421,12 @@ Sets up the required configuration file: } } ``` + - -Automatically sets up a proxy route at `/api/notification` used by the `useNotification` hook when sending notifications. + + Automatically sets up a proxy route at `/api/notification` used by the + `useNotification` hook when sending notifications. @@ -434,8 +452,8 @@ 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 + + Customize the application to fit your needs diff --git a/docs/base-app/build-with-minikit/quickstart.mdx b/docs/base-app/miniapps/quickstart.mdx similarity index 80% rename from docs/base-app/build-with-minikit/quickstart.mdx rename to docs/base-app/miniapps/quickstart.mdx index 2463ed189..597621e8c 100644 --- a/docs/base-app/build-with-minikit/quickstart.mdx +++ b/docs/base-app/miniapps/quickstart.mdx @@ -1,5 +1,5 @@ --- -title: 'Quickstart' +title: 'MiniKit Quickstart' description: 'Learn how to build mini apps on Base with MiniKit - from setup to deployment and advanced features' --- @@ -26,12 +26,16 @@ 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 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. + + 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. @@ -59,7 +63,10 @@ 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. + 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: @@ -96,11 +103,7 @@ npm install -g vercel ``` - -```bash -vercel -``` - +```bash vercel ``` You can use `vercel env add` to set these up via CLI: @@ -110,6 +113,7 @@ You can use `vercel env add` to set these up via CLI: - NEXT_PUBLIC_IMAGE_URL (optional) - NEXT_PUBLIC_SPLASH_IMAGE_URL (optional) - NEXT_PUBLIC_SPLASH_BACKGROUND_COLORs + @@ -162,10 +166,10 @@ 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]); + if (!isFrameReady) { + setFrameReady(); + } +}, [setFrameReady, isFrameReady]); ``` ### Creating the Manifest @@ -181,37 +185,41 @@ npx create-onchain --manifest Enter `y` to proceed with the setup and your browser will open to the following page: -Manifest Setup + 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. + 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 header from manifest generation - -Base64 encoded payload from manifest generation + + Base64 encoded payload from manifest generation - -Signature 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. + While testing your Mini App please add noIndex:true to your manifest - this is + so the app is not indexed while in developement. ### useAddFrame @@ -221,19 +229,20 @@ The `useAddFrame` hook is used to add your mini app to the user's list of mini a 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() +const addFrame = useAddFrame(); // Usage in a button click handler const handleAddFrame = async () => { - const result = await addFrame() + const result = await addFrame(); if (result) { - console.log('Frame added:', result.url, result.token) + 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. + 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 @@ -291,7 +300,8 @@ const close = useClose() ``` -If you reload the frame in the Farcaster dev tools preview, you'll now see the close button in the top right. + If you reload the frame in the Farcaster dev tools preview, you'll now see the + close button in the top right. ### usePrimaryButton @@ -302,15 +312,17 @@ For the template example, we'll use the Primary Button to Pause and Restart the ```tsx app/components/snake.tsx // add an import for usePrimaryButton -import {usePrimaryButton } from '@coinbase/onchainkit/minikit' +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'}, + { text: gameState == GameState.RUNNING ? 'PAUSE GAME' : 'START GAME' }, () => { - setGameState(gameState == GameState.RUNNING ? GameState.PAUSED : GameState.RUNNING); + setGameState( + gameState == GameState.RUNNING ? GameState.PAUSED : GameState.RUNNING + ); } -) +); ``` @@ -323,24 +335,24 @@ We can quickly fix that by changing the text to "BUILT WITH MINIKIT" and removin Now, let's add profile viewing capability. The useViewProfile hook allows you to define what profile to use by defining the user's FID, which is great for social applications. If you don't define an FID, it defaults to the client FID. ```tsx app/page.tsx -import { useViewProfile } from '@coinbase/onchainkit/minikit' +import { useViewProfile } from '@coinbase/onchainkit/minikit'; // Add the hook -const viewProfile = useViewProfile() +const viewProfile = useViewProfile(); // Add the handler function const handleViewProfile = () => { - viewProfile() -} + viewProfile(); +}; // Add the button in your UI in the header after the close button +; ``` ### useNotification @@ -382,7 +394,10 @@ const handleSendNotification = async () => { ``` -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. + 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 diff --git a/docs/base-app/guides/thinking-social.mdx b/docs/base-app/miniapps/thinking-social.mdx similarity index 89% rename from docs/base-app/guides/thinking-social.mdx rename to docs/base-app/miniapps/thinking-social.mdx index a2fe3f23c..2517c20a7 100644 --- a/docs/base-app/guides/thinking-social.mdx +++ b/docs/base-app/miniapps/thinking-social.mdx @@ -1,9 +1,8 @@ --- -title: Thinking Social +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. @@ -14,9 +13,9 @@ Social mini apps live or die based on how they make people feel: seen, connected 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 @@ -28,12 +27,18 @@ Welcome to your blueprint for designing social mini‑apps that people love to r 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. + + 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. + + 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. @@ -44,6 +49,7 @@ Dive into the heart of the guide—three social patterns designed to deepen enga - **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. + @@ -58,13 +64,13 @@ 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 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]. @@ -78,7 +84,6 @@ Evaluate it across these questions: Please be direct. If the idea lacks natural social behavior, suggest ways it could evolve. ``` - ## Social Patterns ### 1. Identity Playgrounds @@ -91,7 +96,6 @@ Please be direct. If the idea lacks natural social behavior, suggest ways it cou **Use it for:** Differentiation, emotional investment, repeat posting. - ``` Given my app idea: [insert idea], explore 2 ways users might express or explore identity. @@ -101,7 +105,6 @@ For each, include: – 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. @@ -112,7 +115,6 @@ For each, include: **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: @@ -121,7 +123,6 @@ Return 3 co-creation flows that include: – What the feed looks like after a few days ``` - ### 3. Long-Term Rituals **The idea:** Introduce regular, shared behaviors that become a rhythm. @@ -132,7 +133,6 @@ Return 3 co-creation flows that include: **Use it for:** Habit loops, appointment-based engagement, social cohesion. - ``` Design 2 recurring rituals for [insert app idea]. @@ -156,12 +156,14 @@ 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:** "Comments spark friendly competition" or "Better with others + involved" - -**Look for:** "Automated reminders nudge new posts" or "Community‑driven growth" + + **Look for:** "Automated reminders nudge new posts" or "Community‑driven + growth" @@ -182,44 +184,52 @@ For each dimension that scored well, confirm the feedback includes clear, action **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 + @@ -229,7 +239,7 @@ Now that you've identified your strongest dimensions, here's how to proceed: -**You're ready to build!** +**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. @@ -277,6 +287,7 @@ 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. diff --git a/docs/docs.json b/docs/docs.json index 69736640b..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,28 +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/search-and-discovery", - "base-app/guides/thinking-social", - "base-app/guides/sharing-your-miniapp", - "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" ] } ] @@ -2240,7 +2239,6 @@ "source": "/wallet-app/:slug*", "destination": "/base-app/:slug*" } - ], "integrations": { "ga4": {