Compare commits

..

48 Commits

Author SHA1 Message Date
veganbeef
3bf80740c0 fix: update neynar/react version number 2025-06-04 12:46:08 -07:00
veganbeef
39437af6f0 feat: add celo 2025-06-02 19:55:44 -07:00
veganbeef
7b87bc4dfa fix: remove amplitude lib (moved to react package) 2025-05-30 16:49:45 -07:00
veganbeef
5420b8fca0 feat: update to use MiniAppProvider 2025-05-30 16:35:31 -07:00
grin
9cd07170b9 Merge pull request #6 from neynarxyz/grin/fix-share-page
fix share page
2025-05-30 16:42:32 -04:00
grin
3e1acfce42 fix share page 2025-05-27 14:23:26 -04:00
veganbeef
0b139f184d v1.3.0 2025-05-22 15:37:47 -07:00
Lucas Myers
16a3e69a43 Merge pull request #5 from neynarxyz/arthur/neyn-5412-add-solana-support-to-mini-app-template
feat: add solana support to mini app template [NEYN-5412]
2025-05-22 16:35:57 -06:00
Quazia
41973daea2 refactor: SignMessage -> SignEvmMessage
addresses comment from @veganbeef
2025-05-22 18:27:40 -04:00
Quazia
a39cb6a0da refactor: named imports vs default
addresses comment from @veganbeef
2025-05-22 18:20:06 -04:00
Quazia
fab3ce9a10 chore: cleanup provider imports
addresses comment from @veganbeef
2025-05-22 18:18:09 -04:00
Quazia
b239f0553b chore: alphabetize deps
addresses comment from @veganbeef
2025-05-22 18:17:32 -04:00
Quazia
7b754ba8fe chore: tweak mini app stylization
Addresses comment from @veganbeef
2025-05-22 18:14:58 -04:00
Quazia
d36a6920f5 chore: cleanup test app 2025-05-22 17:45:18 -04:00
Quazia
6c5482bda4 feat: update app provider 2025-05-22 17:41:21 -04:00
Quazia
5090a76fb4 chore: hyphenate mini-app
Addresses nit from copilot
2025-05-22 17:33:01 -04:00
Quazia
0aaec3495a refactor: text encoder over buffer
Addresses comment from copilot
2025-05-22 17:30:01 -04:00
Quazia
65496acc55 chore: cleanup test project 2025-05-22 17:21:28 -04:00
Quazia
792beee05a refactor: cleanup send sol transaction; add comments 2025-05-22 17:19:09 -04:00
Quazia
55755bd91b feat: solana send transaction
Still needs cleanup but functional
2025-05-22 17:06:55 -04:00
Quazia
d6791fe7c3 chore: update local development readme section 2025-05-22 15:58:55 -04:00
Quazia
880b149300 feat: add guards for when provider is not valid or present 2025-05-22 15:51:51 -04:00
veganbeef
7df556740d feat: add optional amplitude tracking 2025-05-22 12:17:49 -07:00
Quazia
7f10d4e8c0 feat: providers working
Still need to flesh out real demo components and handle the case where there isn't a solana provider injected
2025-05-22 14:24:47 -04:00
Quazia
9f748076db feat: add solana deps to init.js 2025-05-22 12:19:29 -04:00
Quazia
a352e8d5ec chore: add local development section 2025-05-22 12:18:04 -04:00
Quazia
f2d2e26a4a chore: update readme 2025-05-22 11:58:07 -04:00
veganbeef
3fcd2f6e52 fix: update AddFrame type to AddMiniApp 2025-05-16 16:32:12 -07:00
veganbeef
3c9d845f44 add starter kit query param 2025-05-16 16:25:08 -07:00
veganbeef
d38bce50c5 fix: default to skip primary category 2025-05-09 16:57:22 -07:00
veganbeef
f350aaa897 feat: add primary category and tags 2025-05-09 16:41:53 -07:00
veganbeef
5fe54a80da feat: copy share url button and frames to mini app in cli text 2025-05-09 14:08:06 -07:00
veganbeef
08091fc206 fix: dynamic share page 2025-05-09 11:54:39 -07:00
veganbeef
681f287c20 feat: neynar data in opengraph share image 2025-05-09 10:55:22 -07:00
veganbeef
f3f8924fa9 fix: windows compatibility 2025-05-08 10:49:31 -07:00
veganbeef
eda896e478 feat: add support for coinbase wallet with auto connect and metamask 2025-05-08 10:47:59 -07:00
lucas-neynar
d8c53ceab7 feat: update to use coinbaseWallet and metaMask connectors 2025-05-05 15:54:34 -07:00
lucas-neynar
5f0fd8876a refactor: move env vars to constants file 2025-05-05 15:52:38 -07:00
lucas-neynar
40e40543cd fix: update custody address lookup to use free api 2025-04-29 13:10:27 -07:00
lucas-neynar
eba6b89593 version bump 2025-04-22 15:04:08 -07:00
lucas-neynar
a5000b7e71 Merge pull request #2 from megabyte0x/patch-1
Change farcaster packages version to `latest`
2025-04-22 15:02:35 -07:00
megabyte
46058db54f fix: remove latest as the version 2025-04-14 23:19:37 +05:30
lucas-neynar
19788e2ade fix: formatting 2025-04-11 16:53:06 -07:00
lucas-neynar
1baea5d793 fix: script formatting 2025-04-11 16:43:31 -07:00
lucas-neynar
18b36f9603 feat: update init script text about demo API key and tunnel 2025-04-11 16:40:55 -07:00
megabyte
9b5cc10b4c Update init.js 2025-04-11 14:38:25 +05:30
lucas-neynar
6c35293e80 feat: add more logging for error debugging 2025-04-10 10:59:17 -07:00
lucas-neynar
b3e419b1f6 Merge pull request #1 from neynarxyz/lucas/beginner-friendly-script
feat: remove seed phrase from init script
2025-04-10 10:58:44 -07:00
24 changed files with 812 additions and 387 deletions

View File

@@ -4,9 +4,13 @@ A Farcaster Mini Apps quickstart npx script.
This is a [NextJS](https://nextjs.org/) + TypeScript + React app.
## Guide
Check out [this Neynar docs page](https://docs.neynar.com/docs/create-farcaster-miniapp-in-60s) for a simple guide on how to create a Farcaster Mini App in less than 60 seconds!
## Getting Started
To create a new frames project, run:
To create a new mini app project, run:
```{bash}
npx @neynar/create-farcaster-mini-app@latest
```
@@ -37,3 +41,39 @@ npm run build
```
The above command will generate a `.env` file based on the `.env.local` file and user input. Be sure to configure those environment variables on your hosting platform.
## Developing Script Locally
This section is only for working on the script and template. If you simply want to create a mini app and _use_ the template, this section is not for you.
### Recommended: Using `npm link` for Local Development
To iterate on the CLI and test changes in a generated app without publishing to npm:
1. In your installer/template repo (this repo), run:
```bash
npm link
```
This makes your local version globally available as a symlinked package.
1. Now, when you run:
```bash
npx @neynar/create-farcaster-mini-app
```
...it will use your local changes (including any edits to `init.js` or other files) instead of the published npm version.
### Alternative: Running the Script Directly
You can also run the script directly for quick iteration:
```bash
node ./bin/index.js
```
However, this does not fully replicate the npx install flow and may not catch all issues that would occur in a real user environment.
### Environment Variables and Scripts
If you update environment variable handling, remember to replicate any changes in the `dev`, `build`, and `deploy` scripts as needed. The `build` and `deploy` scripts may need further updates and are less critical for most development workflows.

View File

@@ -6,7 +6,7 @@ import { dirname } from 'path';
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import { mnemonicToAccount } from 'viem/accounts';
import crypto from 'crypto';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -16,24 +16,26 @@ const SCRIPT_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'pa
// ANSI color codes
const purple = '\x1b[35m';
const yellow = '\x1b[33m';
const blue = '\x1b[34m';
const reset = '\x1b[0m';
const dim = '\x1b[2m';
const bright = '\x1b[1m';
const italic = '\x1b[3m';
function printWelcomeMessage() {
console.log(`
${purple}╔═══════════════════════════════════════════════════╗${reset}
${purple}║ ║${reset}
${purple}${reset} ${bright}Welcome to Frames v2 Quickstart by Neynar${reset} ${purple}${reset}
${purple}${reset} ${dim}The fastest way to build Farcaster Frames${reset} ${purple}${reset}
${purple}${reset} ${bright}Welcome to Mini Apps Quickstart by Neynar${reset} ${purple}${reset}
${purple}${reset} ${dim}the quickest way to build Farcaster mini apps${reset} ${purple}${reset}
${purple}║ ║${reset}
${purple}╚═══════════════════════════════════════════════════╝${reset}
${blue}Version:${reset} ${SCRIPT_VERSION}
${blue}Repository:${reset} ${dim}${REPO_URL}${reset}
Let's create your Frame! 🚀
Let's create your mini app! 🚀
`);
}
@@ -43,7 +45,7 @@ async function queryNeynarApp(apiKey) {
}
try {
const response = await fetch(
`https://api.neynar.com/portal/app_by_api_key`,
`https://api.neynar.com/portal/app_by_api_key?starter_kit=true`,
{
headers: {
'x-api-key': apiKey
@@ -58,34 +60,6 @@ async function queryNeynarApp(apiKey) {
}
}
async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
if (!apiKey) {
throw new Error('Neynar API key is required');
}
const lowerCasedCustodyAddress = custodyAddress.toLowerCase();
const response = await fetch(
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
{
headers: {
'accept': 'application/json',
'x-api-key': apiKey
}
}
);
if (!response.ok) {
throw new Error(`Failed to lookup FID: ${response.statusText}`);
}
const data = await response.json();
if (!data[lowerCasedCustodyAddress]?.length && !data[lowerCasedCustodyAddress][0].custody_address) {
throw new Error('No FID found for this custody address');
}
return data[lowerCasedCustodyAddress][0].fid;
}
// Export the main CLI function for programmatic use
export async function init() {
printWelcomeMessage();
@@ -102,7 +76,14 @@ export async function init() {
{
type: 'confirm',
name: 'useNeynar',
message: '🪐 Neynar is an API that makes it easy to build on Farcaster.\n\nBenefits of using Neynar in your frame:\n- Pre-configured webhook handling (no setup required)\n- Automatic frame analytics in your dev portal\n- Send manual notifications from dev.neynar.com\n- Built-in rate limiting and error handling\n\nWould you like to use Neynar in your frame?',
message: `🪐 ${purple}${bright}${italic}Neynar is an API that makes it easy to build on Farcaster.${reset}\n\n` +
'Benefits of using Neynar in your mini app:\n' +
'- Pre-configured webhook handling (no setup required)\n' +
'- Automatic mini app analytics in your dev portal\n' +
'- Send manual notifications from dev.neynar.com\n' +
'- Built-in rate limiting and error handling\n\n' +
`${purple}${bright}${italic}A demo API key is included if you would like to try out Neynar before signing up!${reset}\n\n` +
'Would you like to use Neynar in your mini app?',
default: true
}
]);
@@ -136,7 +117,7 @@ export async function init() {
if (useDemoKey.useDemo) {
console.warn('\n⚠ Note: the demo key is for development purposes only and is aggressively rate limited.');
console.log('For production, please sign up for a Neynar account at https://neynar.com/ and configure the API key in your .env or .env.local file with NEYNAR_API_KEY.');
console.log('Neynar now has a free tier! See https://neynar.com/#pricing for details.');
console.log(`\n${purple}${bright}${italic}Neynar now has a free tier! See https://neynar.com/#pricing for details.\n${reset}`);
neynarApiKey = 'FARCASTER_V2_FRAMES_DEMO';
}
}
@@ -191,7 +172,7 @@ export async function init() {
{
type: 'input',
name: 'projectName',
message: 'What is the name of your frame?',
message: 'What is the name of your mini app?',
default: defaultFrameName,
validate: (input) => {
if (input.trim() === '') {
@@ -203,14 +184,52 @@ export async function init() {
{
type: 'input',
name: 'description',
message: 'Give a one-line description of your frame (optional):',
default: 'A Farcaster mini-app created with Neynar'
message: 'Give a one-line description of your mini app (optional):',
default: 'A Farcaster mini app created with Neynar'
},
{
type: 'list',
name: 'primaryCategory',
message: 'It is strongly recommended to choose a primary category and tags to help users discover your mini app.\n\nSelect a primary category:',
choices: [
new inquirer.Separator(),
{ name: 'Skip (not recommended)', value: null },
new inquirer.Separator(),
{ name: 'Games', value: 'games' },
{ name: 'Social', value: 'social' },
{ name: 'Finance', value: 'finance' },
{ name: 'Utility', value: 'utility' },
{ name: 'Productivity', value: 'productivity' },
{ name: 'Health & Fitness', value: 'health-fitness' },
{ name: 'News & Media', value: 'news-media' },
{ name: 'Music', value: 'music' },
{ name: 'Shopping', value: 'shopping' },
{ name: 'Education', value: 'education' },
{ name: 'Developer Tools', value: 'developer-tools' },
{ name: 'Entertainment', value: 'entertainment' },
{ name: 'Art & Creativity', value: 'art-creativity' }
],
default: null
},
{
type: 'input',
name: 'tags',
message: 'Enter tags for your mini app (separate with spaces or commas, optional):',
default: '',
filter: (input) => {
if (!input.trim()) return [];
// Split by both spaces and commas, trim whitespace, and filter out empty strings
return input
.split(/[,\s]+/)
.map(tag => tag.trim())
.filter(tag => tag.length > 0);
}
},
{
type: 'input',
name: 'buttonText',
message: 'Enter the button text for your frame:',
default: 'Launch Frame',
message: 'Enter the button text for your mini app:',
default: 'Launch Mini App',
validate: (input) => {
if (input.trim() === '') {
return 'Button text cannot be empty';
@@ -225,27 +244,49 @@ export async function init() {
{
type: 'confirm',
name: 'useTunnel',
message: 'Would you like to test on mobile, or through a desktop browser?\n' +
'Mobile testing requires setting up a tunnel to serve your app from localhost to the broader internet.\n' +
'Configure mobile testing?',
default: false
message: 'Would you like to test on mobile and/or test the app with Warpcast developer tools?\n' +
`⚠️ ${yellow}${italic}Both mobile testing and the Warpcast debugger require setting up a tunnel to serve your app from localhost to the broader internet.\n${reset}` +
'Configure a tunnel for mobile testing and/or Warpcast developer tools?',
default: true
}
]);
answers.useTunnel = hostingAnswer.useTunnel;
// Ask about analytics opt-out
const analyticsAnswer = await inquirer.prompt([
{
type: 'confirm',
name: 'enableAnalytics',
message: 'Would you like to help improve Neynar products by sharing usage data from your mini app?',
default: true
}
]);
answers.enableAnalytics = analyticsAnswer.enableAnalytics;
const projectName = answers.projectName;
const projectDirName = projectName.replace(/\s+/g, '-').toLowerCase();
const projectPath = path.join(process.cwd(), projectDirName);
console.log(`\nCreating a new Frames v2 app in ${projectPath}`);
console.log(`\nCreating a new mini app in ${projectPath}`);
// Clone the repository
try {
console.log(`\nCloning repository from ${REPO_URL}...`);
// Use separate commands for better cross-platform compatibility
execSync(`git clone ${REPO_URL} "${projectPath}"`, { stdio: 'inherit' });
execSync('git fetch origin main', { cwd: projectPath, stdio: 'inherit' });
execSync('git reset --hard origin/main', { cwd: projectPath, stdio: 'inherit' });
execSync(`git clone ${REPO_URL} "${projectPath}"`, {
stdio: 'inherit',
shell: process.platform === 'win32'
});
execSync('git fetch origin main', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
});
execSync('git reset --hard origin/main', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
});
} catch (error) {
console.error('\n❌ Error: Failed to create project directory.');
console.error('Please make sure you have write permissions and try again.');
@@ -281,13 +322,16 @@ export async function init() {
// Add dependencies
packageJson.dependencies = {
"@farcaster/auth-client": "^0.3.0",
"@farcaster/auth-kit": "^0.6.0",
"@farcaster/frame-core": "^0.0.29",
"@farcaster/frame-node": "^0.0.18",
"@farcaster/frame-sdk": "^0.0.31",
"@farcaster/frame-wagmi-connector": "^0.0.19",
"@farcaster/auth-client": ">=0.3.0 <1.0.0",
"@farcaster/auth-kit": ">=0.6.0 <1.0.0",
"@farcaster/frame-core": ">=0.0.29 <1.0.0",
"@farcaster/frame-node": ">=0.0.18 <1.0.0",
"@farcaster/frame-sdk": ">=0.0.31 <1.0.0",
"@farcaster/frame-wagmi-connector": ">=0.0.19 <1.0.0",
"@farcaster/mini-app-solana": "^0.0.5",
"@neynar/react": "^1.2.2",
"@radix-ui/react-label": "^2.1.1",
"@solana/wallet-adapter-react": "^0.15.38",
"@tanstack/react-query": "^5.61.0",
"@upstash/redis": "^1.34.3",
"class-variance-authority": "^0.7.1",
@@ -295,10 +339,10 @@ export async function init() {
"dotenv": "^16.4.7",
"lucide-react": "^0.469.0",
"mipd": "^0.0.7",
"next": "15.0.3",
"next": "^15",
"next-auth": "^4.24.11",
"react": "^18",
"react-dom": "^18",
"react": "^19",
"react-dom": "^19",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
"viem": "^2.23.6",
@@ -308,21 +352,21 @@ export async function init() {
packageJson.devDependencies = {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react": "^19",
"@types/react-dom": "^19",
"crypto": "^1.0.1",
"eslint": "^8",
"eslint-config-next": "15.0.3",
"localtunnel": "^2.0.2",
"pino-pretty": "^13.0.0",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
};
// Add Neynar dependencies if selected
// Add Neynar SDK if selected
if (useNeynar) {
packageJson.dependencies['@neynar/nodejs-sdk'] = '^2.19.0';
packageJson.dependencies['@neynar/react'] = '^0.9.7';
}
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
@@ -340,7 +384,12 @@ export async function init() {
// Append all remaining environment variables
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_NAME="${answers.projectName}"`);
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_DESCRIPTION="${answers.description}"`);
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_PRIMARY_CATEGORY="${answers.primaryCategory}"`);
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_TAGS="${answers.tags.join(',')}"`);
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_BUTTON_TEXT="${answers.buttonText}"`);
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_ANALYTICS_ENABLED="${answers.enableAnalytics}"`);
fs.appendFileSync(envPath, `\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`);
if (useNeynar && neynarApiKey && neynarClientId) {
fs.appendFileSync(envPath, `\nNEYNAR_API_KEY="${neynarApiKey}"`);
fs.appendFileSync(envPath, `\nNEYNAR_CLIENT_ID="${neynarClientId}"`);
@@ -370,8 +419,16 @@ export async function init() {
// Install dependencies
console.log('\nInstalling dependencies...');
execSync('npm cache clean --force', { cwd: projectPath, stdio: 'inherit' });
execSync('npm install', { cwd: projectPath, stdio: 'inherit' });
execSync('npm cache clean --force', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
});
execSync('npm install', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
});
// Remove the bin directory
console.log('\nRemoving bin directory...');

2
index.d.ts vendored
View File

@@ -1,5 +1,5 @@
/**
* Initialize a new Farcaster mini-app project
* Initialize a new Farcaster mini app project
* @returns Promise<void>
*/
export function init(): Promise<void>;

View File

@@ -1,6 +1,6 @@
{
"name": "@neynar/create-farcaster-mini-app",
"version": "1.2.11",
"version": "1.3.1",
"type": "module",
"private": false,
"access": "public",
@@ -22,6 +22,9 @@
"frame",
"frames-v2",
"farcaster-frames",
"miniapps",
"miniapp",
"mini-apps",
"mini-app",
"neynar",
"web3"
@@ -31,7 +34,8 @@
"build": "node scripts/build.js",
"start": "next start",
"lint": "next lint",
"deploy:vercel": "node scripts/deploy.js"
"deploy:vercel": "node scripts/deploy.js",
"cleanup": "lsof -ti :3000 | xargs kill -9"
},
"bin": {
"@neynar/create-farcaster-mini-app": "./bin/index.js"

View File

@@ -20,9 +20,10 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
if (!apiKey) {
throw new Error('Neynar API key is required');
}
const lowerCasedCustodyAddress = custodyAddress.toLowerCase();
const response = await fetch(
`https://api.neynar.com/v2/farcaster/user/custody-address?custody_address=${custodyAddress}`,
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
{
headers: {
'accept': 'application/json',
@@ -36,11 +37,11 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
}
const data = await response.json();
if (!data.user?.fid) {
if (!data[lowerCasedCustodyAddress]?.length || !data[lowerCasedCustodyAddress][0].custody_address) {
throw new Error('No FID found for this custody address');
}
return data.user.fid;
return data[lowerCasedCustodyAddress][0].fid;
}
async function loadEnvLocal() {
@@ -160,6 +161,8 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
});
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
const tags = process.env.NEXT_PUBLIC_FRAME_TAGS?.split(',');
return {
accountAssociation: {
header: encodedHeader,
@@ -171,11 +174,14 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
name: process.env.NEXT_PUBLIC_FRAME_NAME,
iconUrl: `https://${domain}/icon.png`,
homeUrl: `https://${domain}`,
imageUrl: `https://${domain}/opengraph-image`,
imageUrl: `https://${domain}/api/opengraph-image`,
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT,
splashImageUrl: `https://${domain}/splash.png`,
splashBackgroundColor: "#f7f7f7",
webhookUrl,
description: process.env.NEXT_PUBLIC_FRAME_DESCRIPTION,
primaryCategory: process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY,
tags,
},
};
}
@@ -193,7 +199,7 @@ async function main() {
{
type: 'input',
name: 'domain',
message: 'Enter the domain where your frame will be deployed (e.g., example.com):',
message: 'Enter the domain where your mini app will be deployed (e.g., example.com):',
validate: async (input) => {
try {
await validateDomain(input);
@@ -210,11 +216,11 @@ async function main() {
{
type: 'input',
name: 'frameName',
message: 'Enter the name for your frame (e.g., My Cool Frame):',
message: 'Enter the name for your mini app (e.g., My Cool Mini App):',
default: process.env.NEXT_PUBLIC_FRAME_NAME,
validate: (input) => {
if (input.trim() === '') {
return 'Frame name cannot be empty';
return 'Mini app name cannot be empty';
}
return true;
}
@@ -226,8 +232,8 @@ async function main() {
{
type: 'input',
name: 'buttonText',
message: 'Enter the text for your frame button:',
default: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT || 'Launch Frame',
message: 'Enter the text for your mini app button:',
default: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT || 'Launch Mini App',
validate: (input) => {
if (input.trim() === '') {
return 'Button text cannot be empty';
@@ -299,7 +305,7 @@ async function main() {
type: 'password',
name: 'seedPhrase',
message: 'Your farcaster custody account seed phrase is required to create a signature proving this app was created by you.\n' +
`⚠️ ${yellow}${italic}seed phrase is only used to sign the frame manifest, then discarded${reset} ⚠️\n` +
`⚠️ ${yellow}${italic}seed phrase is only used to sign the mini app manifest, then discarded${reset} ⚠️\n` +
'Seed phrase:',
validate: async (input) => {
try {
@@ -323,7 +329,7 @@ async function main() {
const fid = await lookupFidByCustodyAddress(accountAddress, neynarApiKey ?? 'FARCASTER_V2_FRAMES_DEMO');
// Generate and sign manifest
console.log('\n🔨 Generating frame manifest...');
console.log('\n🔨 Generating mini app manifest...');
// Determine webhook URL based on environment variables
const webhookUrl = neynarApiKey && neynarClientId
@@ -331,7 +337,7 @@ async function main() {
: `${domain}/api/webhook`;
const metadata = await generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase, webhookUrl);
console.log('\n✅ Frame manifest generated' + (seedPhrase ? ' and signed' : ''));
console.log('\n✅ Mini app manifest generated' + (seedPhrase ? ' and signed' : ''));
// Read existing .env file or create new one
const envPath = path.join(projectRoot, '.env');
@@ -345,8 +351,13 @@ async function main() {
// Frame metadata
`NEXT_PUBLIC_FRAME_NAME="${frameName}"`,
`NEXT_PUBLIC_FRAME_DESCRIPTION="${process.env.NEXT_PUBLIC_FRAME_DESCRIPTION || ''}"`,
`NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY="${process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY || ''}"`,
`NEXT_PUBLIC_FRAME_TAGS="${process.env.NEXT_PUBLIC_FRAME_TAGS || ''}"`,
`NEXT_PUBLIC_FRAME_BUTTON_TEXT="${buttonText}"`,
// Analytics
`NEXT_PUBLIC_ANALYTICS_ENABLED="${process.env.NEXT_PUBLIC_ANALYTICS_ENABLED || 'false'}"`,
// Neynar configuration (if it exists in current env)
...(process.env.NEYNAR_API_KEY ?
[`NEYNAR_API_KEY="${process.env.NEYNAR_API_KEY}"`] : []),
@@ -387,9 +398,14 @@ async function main() {
// Run next build
console.log('\nBuilding Next.js application...');
execSync('next build', { cwd: projectRoot, stdio: 'inherit' });
const nextBin = path.normalize(path.join(projectRoot, 'node_modules', '.bin', 'next'));
execSync(`"${nextBin}" build`, {
cwd: projectRoot,
stdio: 'inherit',
shell: process.platform === 'win32'
});
console.log('\n✨ Build complete! Your frame is ready for deployment. 🪐');
console.log('\n✨ Build complete! Your mini app is ready for deployment. 🪐');
console.log('📝 Make sure to configure the environment variables from .env in your hosting provider');
} catch (error) {

View File

@@ -28,9 +28,10 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
if (!apiKey) {
throw new Error('Neynar API key is required');
}
const lowerCasedCustodyAddress = custodyAddress.toLowerCase();
const response = await fetch(
`https://api.neynar.com/v2/farcaster/user/custody-address?custody_address=${custodyAddress}`,
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
{
headers: {
'accept': 'application/json',
@@ -44,11 +45,11 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
}
const data = await response.json();
if (!data.user?.fid) {
if (!data[lowerCasedCustodyAddress]?.length || !data[lowerCasedCustodyAddress][0].custody_address) {
throw new Error('No FID found for this custody address');
}
return data.user.fid;
return data[lowerCasedCustodyAddress][0].fid;
}
async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase, webhookUrl) {
@@ -71,6 +72,8 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
});
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
const tags = process.env.NEXT_PUBLIC_FRAME_TAGS?.split(',');
return {
accountAssociation: {
header: encodedHeader,
@@ -79,14 +82,17 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
},
frame: {
version: "1",
name: process.env.NEXT_PUBLIC_FRAME_NAME?.trim(),
name: process.env.NEXT_PUBLIC_FRAME_NAME,
iconUrl: `https://${trimmedDomain}/icon.png`,
homeUrl: `https://${trimmedDomain}`,
imageUrl: `https://${trimmedDomain}/opengraph-image`,
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT?.trim(),
imageUrl: `https://${trimmedDomain}/api/opengraph-image`,
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT,
splashImageUrl: `https://${trimmedDomain}/splash.png`,
splashBackgroundColor: "#f7f7f7",
webhookUrl: webhookUrl?.trim(),
description: process.env.NEXT_PUBLIC_FRAME_DESCRIPTION,
primaryCategory: process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY,
tags,
},
};
}
@@ -112,7 +118,10 @@ async function loadEnvLocal() {
'SEED_PHRASE',
'NEXT_PUBLIC_FRAME_NAME',
'NEXT_PUBLIC_FRAME_DESCRIPTION',
'NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY',
'NEXT_PUBLIC_FRAME_TAGS',
'NEXT_PUBLIC_FRAME_BUTTON_TEXT',
'NEXT_PUBLIC_ANALYTICS_ENABLED',
'NEYNAR_API_KEY',
'NEYNAR_CLIENT_ID'
];
@@ -153,14 +162,14 @@ async function checkRequiredEnvVars() {
const requiredVars = [
{
name: 'NEXT_PUBLIC_FRAME_NAME',
message: 'Enter the name for your frame (e.g., My Cool Frame):',
message: 'Enter the name for your frame (e.g., My Cool Mini App):',
default: process.env.NEXT_PUBLIC_FRAME_NAME,
validate: input => input.trim() !== '' || 'Frame name cannot be empty'
validate: input => input.trim() !== '' || 'Mini app name cannot be empty'
},
{
name: 'NEXT_PUBLIC_FRAME_BUTTON_TEXT',
message: 'Enter the text for your frame button:',
default: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT ?? 'Launch Frame',
default: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT ?? 'Launch Mini App',
validate: input => input.trim() !== '' || 'Button text cannot be empty'
}
];
@@ -196,13 +205,13 @@ async function checkRequiredEnvVars() {
// Check for seed phrase
if (!process.env.SEED_PHRASE) {
console.log('\n🔑 Frame Manifest Signing');
console.log('A signed manifest helps users trust your frame.');
console.log('\n🔑 Mini App Manifest Signing');
console.log('A signed manifest helps users trust your mini app.');
const { seedPhrase } = await inquirer.prompt([
{
type: 'password',
name: 'seedPhrase',
message: 'Enter your Farcaster custody account seed phrase to sign the frame manifest\n(optional -- leave blank to create an unsigned frame)\n\nSeed phrase:',
message: 'Enter your Farcaster custody account seed phrase to sign the mini app manifest\n(optional -- leave blank to create an unsigned mini app)\n\nSeed phrase:',
default: null
}
]);
@@ -244,7 +253,10 @@ async function getGitRemote() {
async function checkVercelCLI() {
try {
execSync('vercel --version', { stdio: 'ignore' });
execSync('vercel --version', {
stdio: 'ignore',
shell: process.platform === 'win32'
});
return true;
} catch (error) {
return false;
@@ -253,7 +265,10 @@ async function checkVercelCLI() {
async function installVercelCLI() {
console.log('Installing Vercel CLI...');
execSync('npm install -g vercel', { stdio: 'inherit' });
execSync('npm install -g vercel', {
stdio: 'inherit',
shell: process.platform === 'win32'
});
}
async function loginToVercel() {
@@ -378,11 +393,12 @@ async function deployToVercel(useGitHub = false) {
// Set up Vercel project
console.log('\n📦 Setting up Vercel project...');
console.log(' An initial deployment is required to get an assigned domain that can be used in the frame manifest\n');
console.log(' An initial deployment is required to get an assigned domain that can be used in the mini app manifest\n');
console.log('\n⚠ Note: choosing a longer, more unique project name will help avoid conflicts with other existing domains\n');
execSync('vercel', {
cwd: projectRoot,
stdio: 'inherit'
stdio: 'inherit',
shell: process.platform === 'win32'
});
// Load project info from .vercel/project.json
@@ -569,7 +585,7 @@ async function deployToVercel(useGitHub = false) {
}
}
console.log('\n✨ Deployment complete! Your frame is now live at:');
console.log('\n✨ Deployment complete! Your mini app is now live at:');
console.log(`🌐 https://${domain}`);
console.log('\n📝 You can manage your project at https://vercel.com/dashboard');
@@ -582,13 +598,13 @@ async function deployToVercel(useGitHub = false) {
async function main() {
try {
// Print welcome message
console.log('🚀 Vercel Frame Deployment');
console.log('This script will deploy your frame to Vercel.');
console.log('🚀 Vercel Mini App Deployment');
console.log('This script will deploy your mini app to Vercel.');
console.log('\nThe script will:');
console.log('1. Check for required environment variables');
console.log('2. Set up a Vercel project (new or existing)');
console.log('3. Configure environment variables in Vercel');
console.log('4. Deploy and build your frame (Vercel will run the build automatically)\n');
console.log('4. Deploy and build your mini app (Vercel will run the build automatically)\n');
// Check for required environment variables
await checkRequiredEnvVars();

View File

@@ -9,7 +9,7 @@ import { fileURLToPath } from 'url';
dotenv.config({ path: '.env.local' });
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.join(__dirname, '..');
const projectRoot = path.resolve(path.normalize(path.join(__dirname, '..')));
let tunnel;
let nextDev;
@@ -75,9 +75,7 @@ async function startDev() {
? '1. Run: netstat -ano | findstr :3000\n' +
'2. Note the PID (Process ID) from the output\n' +
'3. Run: taskkill /PID <PID> /F\n'
: '1. On macOS/Linux, run: lsof -i :3000\n' +
'2. Note the PID (Process ID) from the output\n' +
'3. Run: kill -9 <PID>\n') +
: `On macOS/Linux, run:\nnpm run cleanup\n`) +
'\nThen try running this command again.');
process.exit(1);
}
@@ -102,42 +100,41 @@ async function startDev() {
💻 To test on desktop:
1. Open the localtunnel URL in your browser: ${tunnel.url}
2. Enter your IP address in the password field${ip ? `: ${ip}` : ''} (note that this IP may be incorrect if you are using a VPN)
3. Click "Click to Submit" -- your frame should now load in the browser
4. Navigate to the Warpcast Frame Developer Tools: https://warpcast.com/~/developers/frames
5. Enter your frame URL: ${tunnel.url}
6. Click "Preview" to launch your frame within Warpcast (note that it may take ~10 seconds to load)
3. Click "Click to Submit" -- your mini app should now load in the browser
4. Navigate to the Warpcast Mini App Developer Tools: https://warpcast.com/~/developers
5. Enter your mini app URL: ${tunnel.url}
6. Click "Preview" to launch your mini app within Warpcast (note that it may take ~10 seconds to load)
❗️ You will not be able to load your frame in Warpcast until ❗️
❗️ You will not be able to load your mini app in Warpcast until ❗️
❗️ you submit your IP address in the localtunnel password field ❗️
📱 To test in Warpcast mobile app:
1. Open Warpcast on your phone
2. Go to Settings > Developer > Frames
2. Go to Settings > Developer > Mini Apps
4. Enter this URL: ${tunnel.url}
5. Click "Preview" (note that it may take ~10 seconds to load)
`);
} else {
frameUrl = 'http://localhost:3000';
console.log(`
💻 To test your frame:
1. Open the Warpcast Frame Developer Tools: https://warpcast.com/~/developers/frames
2. Scroll down to the "Preview Frame" tool
💻 To test your mini app:
1. Open the Warpcast Mini App Developer Tools: https://warpcast.com/~/developers
2. Scroll down to the "Preview Mini App" tool
3. Enter this URL: ${frameUrl}
4. Click "Preview" to test your frame (note that it may take ~5 seconds to load the first time)
4. Click "Preview" to test your mini app (note that it may take ~5 seconds to load the first time)
`);
}
// Start next dev with appropriate configuration
const nextBin = process.platform === 'win32'
? path.join(projectRoot, 'node_modules', '.bin', 'next.cmd')
: path.join(projectRoot, 'node_modules', '.bin', 'next');
const nextBin = path.normalize(path.join(projectRoot, 'node_modules', '.bin', 'next'));
nextDev = spawn(nextBin, ['dev'], {
stdio: 'inherit',
env: { ...process.env, NEXT_PUBLIC_URL: frameUrl, NEXTAUTH_URL: frameUrl },
cwd: projectRoot
cwd: projectRoot,
shell: process.platform === 'win32' // Add shell option for Windows
});
// Handle cleanup

View File

@@ -0,0 +1,30 @@
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
import { getNeynarUser } from "~/lib/neynar";
export const dynamic = 'force-dynamic';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const fid = searchParams.get('fid');
const user = fid ? await getNeynarUser(Number(fid)) : null;
return new ImageResponse(
(
<div tw="flex h-full w-full flex-col justify-center items-center relative bg-purple-600">
{user?.pfp_url && (
<div tw="flex w-96 h-96 rounded-full overflow-hidden mb-8 border-8 border-white">
<img src={user.pfp_url} alt="Profile" tw="w-full h-full object-cover" />
</div>
)}
<h1 tw="text-8xl text-white">{user?.display_name ? `Hello from ${user.display_name ?? user.username}!` : 'Hello!'}</h1>
<p tw="text-5xl mt-4 text-white opacity-80">Powered by Neynar 🪐</p>
</div>
),
{
width: 1200,
height: 800,
}
);
}

View File

@@ -1,7 +1,7 @@
"use client";
import dynamic from "next/dynamic";
import { APP_NAME } from "~/lib/constants";
// note: dynamic import is required for components that use the Frame SDK
const Demo = dynamic(() => import("~/components/Demo"), {
@@ -9,7 +9,7 @@ const Demo = dynamic(() => import("~/components/Demo"), {
});
export default function App(
{ title }: { title?: string } = { title: process.env.NEXT_PUBLIC_FRAME_NAME || "Frames v2 Demo" }
{ title }: { title?: string } = { title: APP_NAME }
) {
return <Demo title={title} />;
}

View File

@@ -3,10 +3,11 @@ import type { Metadata } from "next";
import { getSession } from "~/auth"
import "~/app/globals.css";
import { Providers } from "~/app/providers";
import { APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
export const metadata: Metadata = {
title: process.env.NEXT_PUBLIC_FRAME_NAME || "Frames v2 Demo",
description: process.env.NEXT_PUBLIC_FRAME_DESCRIPTION || "A Farcaster Frames v2 demo app",
title: APP_NAME,
description: APP_DESCRIPTION,
};
export default async function RootLayout({

View File

@@ -1,23 +0,0 @@
import { ImageResponse } from "next/og";
export const alt = process.env.NEXT_PUBLIC_FRAME_NAME || "Frames V2 Demo";
export const size = {
width: 600,
height: 400,
};
export const contentType = "image/png";
// dynamically generated OG image for frame preview
export default async function Image() {
return new ImageResponse(
(
<div tw="h-full w-full flex flex-col justify-center items-center relative bg-white">
<h1 tw="text-6xl">{alt}</h1>
</div>
),
{
...size,
}
);
}

View File

@@ -1,40 +1,20 @@
import { Metadata } from "next";
import App from "./app";
const appUrl = process.env.NEXT_PUBLIC_URL;
// frame preview metadata
const appName = process.env.NEXT_PUBLIC_FRAME_NAME;
const splashImageUrl = `${appUrl}/splash.png`;
const iconUrl = `${appUrl}/icon.png`;
const framePreviewMetadata = {
version: "next",
imageUrl: `${appUrl}/opengraph-image`,
button: {
title: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT,
action: {
type: "launch_frame",
name: appName,
url: appUrl,
splashImageUrl,
iconUrl,
splashBackgroundColor: "#f7f7f7",
},
},
};
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from "~/lib/constants";
import { getFrameEmbedMetadata } from "~/lib/utils";
export const revalidate = 300;
export async function generateMetadata(): Promise<Metadata> {
return {
title: appName,
title: APP_NAME,
openGraph: {
title: appName,
description: process.env.NEXT_PUBLIC_FRAME_DESCRIPTION,
title: APP_NAME,
description: APP_DESCRIPTION,
images: [APP_OG_IMAGE_URL],
},
other: {
"fc:frame": JSON.stringify(framePreviewMetadata),
"fc:frame": JSON.stringify(getFrameEmbedMetadata()),
},
};
}

View File

@@ -1,9 +1,10 @@
"use client";
import dynamic from "next/dynamic";
import type { Session } from "next-auth"
import { SessionProvider } from "next-auth/react"
import { FrameProvider } from "~/components/providers/FrameProvider";
import type { Session } from "next-auth";
import { SessionProvider } from "next-auth/react";
import { MiniAppProvider } from "@neynar/react";
import { SafeFarcasterSolanaProvider } from "~/components/providers/SafeFarcasterSolanaProvider";
const WagmiProvider = dynamic(
() => import("~/components/providers/WagmiProvider"),
@@ -13,12 +14,15 @@ const WagmiProvider = dynamic(
);
export function Providers({ session, children }: { session: Session | null, children: React.ReactNode }) {
const solanaEndpoint = process.env.SOLANA_RPC_ENDPOINT || "https://solana-rpc.publicnode.com";
return (
<SessionProvider session={session}>
<WagmiProvider>
<FrameProvider>
{children}
</FrameProvider>
<MiniAppProvider analyticsEnabled={true}>
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
{children}
</SafeFarcasterSolanaProvider>
</MiniAppProvider>
</WagmiProvider>
</SessionProvider>
);

View File

@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { APP_URL, APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
import { getFrameEmbedMetadata } from "~/lib/utils";
export const revalidate = 300;
// This is an example of how to generate a dynamically generated share page based on fid:
// Sharing this route e.g. exmaple.com/share/123 will generate a share page for fid 123,
// with the image dynamically generated by the opengraph-image API route.
export async function generateMetadata({
params,
}: {
params: Promise<{ fid: string }>;
}): Promise<Metadata> {
const { fid } = await params;
const imageUrl = `${APP_URL}/api/opengraph-image?fid=${fid}`;
return {
title: `${APP_NAME} - Share`,
openGraph: {
title: APP_NAME,
description: APP_DESCRIPTION,
images: [imageUrl],
},
other: {
"fc:frame": JSON.stringify(getFrameEmbedMetadata(imageUrl)),
},
};
}
export default function SharePage() {
// redirect to home page
redirect("/");
}

View File

@@ -58,6 +58,11 @@ export const authOptions: AuthOptions = {
},
async authorize(credentials, req) {
const csrfToken = req?.body?.csrfToken;
if (!csrfToken) {
console.error('CSRF token is missing from request');
return null;
}
const appClient = createAppClient({
ethereum: viemConnector(),
});
@@ -120,4 +125,11 @@ export const authOptions: AuthOptions = {
}
}
export const getSession = () => getServerSession(authOptions)
export const getSession = async () => {
try {
return await getServerSession(authOptions);
} catch (error) {
console.error('Error getting server session:', error);
return null;
}
}

View File

@@ -1,6 +1,6 @@
"use client";
import { useCallback, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Input } from "../components/ui/input";
import { signIn, signOut, getCsrfToken } from "next-auth/react";
import sdk, {
@@ -17,6 +17,11 @@ import {
useSwitchChain,
useChainId,
} from "wagmi";
import {
useConnection as useSolanaConnection,
useWallet as useSolanaWallet,
} from '@solana/wallet-adapter-react';
import { useHasSolanaProvider } from "./providers/SafeFarcasterSolanaProvider";
import { config } from "~/components/providers/WagmiProvider";
import { Button } from "~/components/ui/Button";
@@ -24,20 +29,46 @@ import { truncateAddress } from "~/lib/truncateAddress";
import { base, degen, mainnet, optimism, unichain } from "wagmi/chains";
import { BaseError, UserRejectedRequestError } from "viem";
import { useSession } from "next-auth/react";
import { useMiniApp } from "@neynar/react";
import { Label } from "~/components/ui/label";
import { useFrame } from "~/components/providers/FrameProvider";
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
export default function Demo(
{ title }: { title?: string } = { title: "Frames v2 Demo" }
) {
const { isSDKLoaded, context, added, notificationDetails, lastEvent, addFrame, addFrameResult } = useFrame();
const {
isSDKLoaded,
context,
added,
notificationDetails,
lastEvent,
addFrame,
addFrameResult,
openUrl,
close,
} = useMiniApp();
const [isContextOpen, setIsContextOpen] = useState(false);
const [txHash, setTxHash] = useState<string | null>(null);
const [sendNotificationResult, setSendNotificationResult] = useState("");
const [copied, setCopied] = useState(false);
const { address, isConnected } = useAccount();
const chainId = useChainId();
const hasSolanaProvider = useHasSolanaProvider();
let solanaWallet, solanaPublicKey, solanaSignMessage, solanaAddress;
if (hasSolanaProvider) {
solanaWallet = useSolanaWallet();
({ publicKey: solanaPublicKey, signMessage: solanaSignMessage } = solanaWallet);
solanaAddress = solanaPublicKey?.toBase58();
}
useEffect(() => {
console.log("isSDKLoaded", isSDKLoaded);
console.log("context", context);
console.log("address", address);
console.log("isConnected", isConnected);
console.log("chainId", chainId);
}, [context, address, isConnected, chainId, isSDKLoaded]);
const {
sendTransaction,
@@ -59,7 +90,7 @@ export default function Demo(
} = useSignTypedData();
const { disconnect } = useDisconnect();
const { connect } = useConnect();
const { connect, connectors } = useConnect();
const {
switchChain,
@@ -86,18 +117,6 @@ export default function Demo(
switchChain({ chainId: nextChain.id });
}, [switchChain, nextChain.id]);
const openUrl = useCallback(() => {
sdk.actions.openUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
}, []);
const openWarpcastUrl = useCallback(() => {
sdk.actions.openUrl("https://warpcast.com/~/compose");
}, []);
const close = useCallback(() => {
sdk.actions.close();
}, []);
const sendNotification = useCallback(async () => {
setSendNotificationResult("");
if (!notificationDetails || !context) {
@@ -225,16 +244,7 @@ export default function Demo(
sdk.actions.openUrl
</pre>
</div>
<Button onClick={openUrl}>Open Link</Button>
</div>
<div className="mb-4">
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
sdk.actions.openUrl
</pre>
</div>
<Button onClick={openWarpcastUrl}>Open Warpcast Link</Button>
<Button onClick={() => openUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")}>Open Link</Button>
</div>
<div className="mb-4">
@@ -303,6 +313,22 @@ export default function Demo(
Send notification
</Button>
</div>
<div className="mb-4">
<Button
onClick={async () => {
if (context?.user?.fid) {
const shareUrl = `${process.env.NEXT_PUBLIC_URL}/share/${context.user.fid}`;
await navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
}}
disabled={!context?.user?.fid}
>
{copied ? "Copied!" : "Copy share URL"}
</Button>
</div>
</div>
<div>
@@ -321,19 +347,42 @@ export default function Demo(
)}
<div className="mb-4">
<Button
onClick={() =>
isConnected
? disconnect()
: connect({ connector: config.connectors[0] })
}
>
{isConnected ? "Disconnect" : "Connect"}
</Button>
{isConnected ? (
<Button
onClick={() => disconnect()}
className="w-full"
>
Disconnect
</Button>
) : context ? (
/* if context is not null, mini app is running in frame client */
<Button
onClick={() => connect({ connector: connectors[0] })}
className="w-full"
>
Connect
</Button>
) : (
/* if context is null, mini app is running in browser */
<div className="space-y-2">
<Button
onClick={() => connect({ connector: connectors[1] })}
className="w-full"
>
Connect Coinbase Wallet
</Button>
<Button
onClick={() => connect({ connector: connectors[2] })}
className="w-full"
>
Connect MetaMask
</Button>
</div>
)}
</div>
<div className="mb-4">
<SignMessage />
<SignEvmMessage />
</div>
{isConnected && (
@@ -387,12 +436,150 @@ export default function Demo(
</>
)}
</div>
{solanaAddress && (
<div>
<h2 className="font-2xl font-bold">Solana</h2>
<div className="my-2 text-xs">
Address: <pre className="inline">{truncateAddress(solanaAddress)}</pre>
</div>
<SignSolanaMessage signMessage={solanaSignMessage} />
<div className="mb-4">
<SendSolana />
</div>
</div>
)}
</div>
</div>
);
}
function SignMessage() {
// Solana functions inspired by farcaster demo
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx
function SignSolanaMessage({ signMessage }: { signMessage?: (message: Uint8Array) => Promise<Uint8Array> }) {
const [signature, setSignature] = useState<string | undefined>();
const [signError, setSignError] = useState<Error | undefined>();
const [signPending, setSignPending] = useState(false);
const handleSignMessage = useCallback(async () => {
setSignPending(true);
try {
if (!signMessage) {
throw new Error('no Solana signMessage');
}
const input = new TextEncoder().encode("Hello from Solana!");
const signatureBytes = await signMessage(input);
const signature = btoa(String.fromCharCode(...signatureBytes));
setSignature(signature);
setSignError(undefined);
} catch (e) {
if (e instanceof Error) {
setSignError(e);
}
} finally {
setSignPending(false);
}
}, [signMessage]);
return (
<>
<Button
onClick={handleSignMessage}
disabled={signPending}
isLoading={signPending}
className="mb-4"
>
Sign Message
</Button>
{signError && renderError(signError)}
{signature && (
<div className="mt-2 text-xs">
<div>Signature: {signature}</div>
</div>
)}
</>
);
}
function SendSolana() {
const [state, setState] = useState<
| { status: 'none' }
| { status: 'pending' }
| { status: 'error'; error: Error }
| { status: 'success'; signature: string }
>({ status: 'none' });
const { connection: solanaConnection } = useSolanaConnection();
const { sendTransaction, publicKey } = useSolanaWallet();
// This should be replaced but including it from the original demo
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx#L718
const ashoatsPhantomSolanaWallet = 'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
const handleSend = useCallback(async () => {
setState({ status: 'pending' });
try {
if (!publicKey) {
throw new Error('no Solana publicKey');
}
const { blockhash } = await solanaConnection.getLatestBlockhash();
if (!blockhash) {
throw new Error('failed to fetch latest Solana blockhash');
}
const fromPubkeyStr = publicKey.toBase58();
const toPubkeyStr = ashoatsPhantomSolanaWallet;
const transaction = new Transaction();
transaction.add(
SystemProgram.transfer({
fromPubkey: new PublicKey(fromPubkeyStr),
toPubkey: new PublicKey(toPubkeyStr),
lamports: 0n,
}),
);
transaction.recentBlockhash = blockhash;
transaction.feePayer = new PublicKey(fromPubkeyStr);
const simulation = await solanaConnection.simulateTransaction(transaction);
if (simulation.value.err) {
// Gather logs and error details for debugging
const logs = simulation.value.logs?.join('\n') ?? 'No logs';
const errDetail = JSON.stringify(simulation.value.err);
throw new Error(`Simulation failed: ${errDetail}\nLogs:\n${logs}`);
}
const signature = await sendTransaction(transaction, solanaConnection);
setState({ status: 'success', signature });
} catch (e) {
if (e instanceof Error) {
setState({ status: 'error', error: e });
} else {
setState({ status: 'none' });
}
}
}, [sendTransaction, publicKey, solanaConnection]);
return (
<>
<Button
onClick={handleSend}
disabled={state.status === 'pending'}
isLoading={state.status === 'pending'}
className="mb-4"
>
Send Transaction (sol)
</Button>
{state.status === 'error' && renderError(state.error)}
{state.status === 'success' && (
<div className="mt-2 text-xs">
<div>Hash: {truncateAddress(state.signature)}</div>
</div>
)}
</>
);
}
function SignEvmMessage() {
const { isConnected } = useAccount();
const { connectAsync } = useConnect();
const {
@@ -609,6 +796,7 @@ function ViewProfile() {
</>
);
}
const renderError = (error: Error | null) => {
if (!error) return null;
if (error instanceof BaseError) {

View File

@@ -1,129 +0,0 @@
"use client";
import { useEffect, useState, useCallback } from "react";
import sdk, { type Context, type FrameNotificationDetails, AddFrame } from "@farcaster/frame-sdk";
import { createStore } from "mipd";
import React from "react";
interface FrameContextType {
isSDKLoaded: boolean;
context: Context.FrameContext | undefined;
}
const FrameContext = React.createContext<FrameContextType | undefined>(undefined);
export function useFrame() {
const [isSDKLoaded, setIsSDKLoaded] = useState(false);
const [context, setContext] = useState<Context.FrameContext>();
const [added, setAdded] = useState(false);
const [notificationDetails, setNotificationDetails] = useState<FrameNotificationDetails | null>(null);
const [lastEvent, setLastEvent] = useState("");
const [addFrameResult, setAddFrameResult] = useState("");
const addFrame = useCallback(async () => {
try {
setNotificationDetails(null);
const result = await sdk.actions.addFrame();
if (result.notificationDetails) {
setNotificationDetails(result.notificationDetails);
}
setAddFrameResult(
result.notificationDetails
? `Added, got notificaton token ${result.notificationDetails.token} and url ${result.notificationDetails.url}`
: "Added, got no notification details"
);
} catch (error) {
if (error instanceof AddFrame.RejectedByUser) {
setAddFrameResult(`Not added: ${error.message}`);
}
if (error instanceof AddFrame.InvalidDomainManifest) {
setAddFrameResult(`Not added: ${error.message}`);
}
setAddFrameResult(`Error: ${error}`);
}
}, []);
useEffect(() => {
const load = async () => {
const context = await sdk.context;
setContext(context);
setIsSDKLoaded(true);
// Set up event listeners
sdk.on("frameAdded", ({ notificationDetails }) => {
console.log("Frame added", notificationDetails);
setAdded(true);
setNotificationDetails(notificationDetails ?? null);
setLastEvent("Frame added");
});
sdk.on("frameAddRejected", ({ reason }) => {
console.log("Frame add rejected", reason);
setAdded(false);
setLastEvent(`Frame add rejected: ${reason}`);
});
sdk.on("frameRemoved", () => {
console.log("Frame removed");
setAdded(false);
setLastEvent("Frame removed");
});
sdk.on("notificationsEnabled", ({ notificationDetails }) => {
console.log("Notifications enabled", notificationDetails);
setNotificationDetails(notificationDetails ?? null);
setLastEvent("Notifications enabled");
});
sdk.on("notificationsDisabled", () => {
console.log("Notifications disabled");
setNotificationDetails(null);
setLastEvent("Notifications disabled");
});
sdk.on("primaryButtonClicked", () => {
console.log("Primary button clicked");
setLastEvent("Primary button clicked");
});
// Call ready action
console.log("Calling ready");
sdk.actions.ready({});
// Set up MIPD Store
const store = createStore();
store.subscribe((providerDetails) => {
console.log("PROVIDER DETAILS", providerDetails);
});
};
if (sdk && !isSDKLoaded) {
console.log("Calling load");
setIsSDKLoaded(true);
load();
return () => {
sdk.removeAllListeners();
};
}
}, [isSDKLoaded]);
return { isSDKLoaded, context, added, notificationDetails, lastEvent, addFrame, addFrameResult };
}
export function FrameProvider({ children }: { children: React.ReactNode }) {
const { isSDKLoaded, context } = useFrame();
if (!isSDKLoaded) {
return <div>Loading...</div>;
}
return (
<FrameContext.Provider value={{ isSDKLoaded, context }}>
{children}
</FrameContext.Provider>
);
}

View File

@@ -0,0 +1,86 @@
import React, { createContext, useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { sdk } from '@farcaster/frame-sdk';
const FarcasterSolanaProvider = dynamic(
() => import('@farcaster/mini-app-solana').then(mod => mod.FarcasterSolanaProvider),
{ ssr: false }
);
type SafeFarcasterSolanaProviderProps = {
endpoint: string;
children: React.ReactNode;
};
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({ hasSolanaProvider: false });
export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcasterSolanaProviderProps) {
const isClient = typeof window !== "undefined";
const [hasSolanaProvider, setHasSolanaProvider] = useState<boolean>(false);
const [checked, setChecked] = useState<boolean>(false);
useEffect(() => {
if (!isClient) return;
let cancelled = false;
(async () => {
try {
const provider = await sdk.wallet.getSolanaProvider();
if (!cancelled) {
setHasSolanaProvider(!!provider);
}
} catch {
if (!cancelled) {
setHasSolanaProvider(false);
}
} finally {
if (!cancelled) {
setChecked(true);
}
}
})();
return () => {
cancelled = true;
};
}, [isClient]);
useEffect(() => {
let errorShown = false;
const origError = console.error;
console.error = (...args) => {
if (
typeof args[0] === "string" &&
args[0].includes("WalletConnectionError: could not get Solana provider")
) {
if (!errorShown) {
origError(...args);
errorShown = true;
}
return;
}
origError(...args);
};
return () => {
console.error = origError;
};
}, []);
if (!isClient || !checked) {
return null;
}
return (
<SolanaProviderContext.Provider value={{ hasSolanaProvider }}>
{hasSolanaProvider ? (
<FarcasterSolanaProvider endpoint={endpoint}>
{children}
</FarcasterSolanaProvider>
) : (
<>{children}</>
)}
</SolanaProviderContext.Provider>
);
}
export function useHasSolanaProvider() {
return React.useContext(SolanaProviderContext).hasSolanaProvider;
}

View File

@@ -1,26 +1,88 @@
import { createConfig, http, WagmiProvider } from "wagmi";
import { base, degen, mainnet, optimism, unichain } from "wagmi/chains";
import { base, degen, mainnet, optimism, unichain, celo } from "wagmi/chains";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { farcasterFrame } from "@farcaster/frame-wagmi-connector";
import { coinbaseWallet, metaMask } from 'wagmi/connectors';
import { APP_NAME, APP_ICON_URL, APP_URL } from "~/lib/constants";
import { useEffect, useState } from "react";
import { useConnect, useAccount } from "wagmi";
import React from "react";
// Custom hook for Coinbase Wallet detection and auto-connection
function useCoinbaseWalletAutoConnect() {
const [isCoinbaseWallet, setIsCoinbaseWallet] = useState(false);
const { connect, connectors } = useConnect();
const { isConnected } = useAccount();
useEffect(() => {
// Check if we're running in Coinbase Wallet
const checkCoinbaseWallet = () => {
const isInCoinbaseWallet = window.ethereum?.isCoinbaseWallet ||
window.ethereum?.isCoinbaseWalletExtension ||
window.ethereum?.isCoinbaseWalletBrowser;
setIsCoinbaseWallet(!!isInCoinbaseWallet);
};
checkCoinbaseWallet();
window.addEventListener('ethereum#initialized', checkCoinbaseWallet);
return () => {
window.removeEventListener('ethereum#initialized', checkCoinbaseWallet);
};
}, []);
useEffect(() => {
// Auto-connect if in Coinbase Wallet and not already connected
if (isCoinbaseWallet && !isConnected) {
connect({ connector: connectors[1] }); // Coinbase Wallet connector
}
}, [isCoinbaseWallet, isConnected, connect, connectors]);
return isCoinbaseWallet;
}
export const config = createConfig({
chains: [base, optimism, mainnet, degen, unichain],
chains: [base, optimism, mainnet, degen, unichain, celo],
transports: {
[base.id]: http(),
[optimism.id]: http(),
[mainnet.id]: http(),
[degen.id]: http(),
[unichain.id]: http(),
[celo.id]: http(),
},
connectors: [farcasterFrame()],
connectors: [
farcasterFrame(),
coinbaseWallet({
appName: APP_NAME,
appLogoUrl: APP_ICON_URL,
preference: 'all',
}),
metaMask({
dappMetadata: {
name: APP_NAME,
url: APP_URL,
},
}),
],
});
const queryClient = new QueryClient();
// Wrapper component that provides Coinbase Wallet auto-connection
function CoinbaseWalletAutoConnect({ children }: { children: React.ReactNode }) {
useCoinbaseWalletAutoConnect();
return <>{children}</>;
}
export default function Provider({ children }: { children: React.ReactNode }) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
<QueryClientProvider client={queryClient}>
<CoinbaseWalletAutoConnect>
{children}
</CoinbaseWalletAutoConnect>
</QueryClientProvider>
</WagmiProvider>
);
}

13
src/lib/constants.ts Normal file
View File

@@ -0,0 +1,13 @@
export const APP_URL = process.env.NEXT_PUBLIC_URL!;
export const APP_NAME = process.env.NEXT_PUBLIC_FRAME_NAME;
export const APP_DESCRIPTION = process.env.NEXT_PUBLIC_FRAME_DESCRIPTION;
export const APP_PRIMARY_CATEGORY = process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY;
export const APP_TAGS = process.env.NEXT_PUBLIC_FRAME_TAGS?.split(',');
export const APP_ICON_URL = `${APP_URL}/icon.png`;
export const APP_OG_IMAGE_URL = `${APP_URL}/api/opengraph-image`;
export const APP_SPLASH_URL = `${APP_URL}/splash.png`;
export const APP_SPLASH_BACKGROUND_COLOR = "#f7f7f7";
export const APP_BUTTON_TEXT = process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT;
export const APP_WEBHOOK_URL = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
: `${APP_URL}/api/webhook`;

View File

@@ -1,5 +1,6 @@
import { FrameNotificationDetails } from "@farcaster/frame-sdk";
import { Redis } from "@upstash/redis";
import { APP_NAME } from "./constants";
// In-memory fallback storage
const localStore = new Map<string, FrameNotificationDetails>();
@@ -12,7 +13,7 @@ const redis = useRedis ? new Redis({
}) : null;
function getUserNotificationDetailsKey(fid: number): string {
return `${process.env.NEXT_PUBLIC_FRAME_NAME}:user:${fid}`;
return `${APP_NAME}:user:${fid}`;
}
export async function getUserNotificationDetails(

View File

@@ -1,4 +1,5 @@
import { NeynarAPIClient, Configuration } from '@neynar/nodejs-sdk';
import { NeynarAPIClient, Configuration, WebhookUserCreated } from '@neynar/nodejs-sdk';
import { APP_URL } from './constants';
let neynarClient: NeynarAPIClient | null = null;
@@ -17,6 +18,19 @@ export function getNeynarClient() {
return neynarClient;
}
type User = WebhookUserCreated['data'];
export async function getNeynarUser(fid: number): Promise<User | null> {
try {
const client = getNeynarClient();
const usersResponse = await client.fetchBulkUsers({ fids: [fid] });
return usersResponse.users[0];
} catch (error) {
console.error('Error getting Neynar user:', error);
return null;
}
}
type SendFrameNotificationResult =
| {
state: "error";
@@ -41,7 +55,7 @@ export async function sendNeynarFrameNotification({
const notification = {
title,
body,
target_url: process.env.NEXT_PUBLIC_URL!,
target_url: APP_URL,
};
const result = await client.publishFrameNotifications({

View File

@@ -3,8 +3,7 @@ import {
sendNotificationResponseSchema,
} from "@farcaster/frame-sdk";
import { getUserNotificationDetails } from "~/lib/kv";
const appUrl = process.env.NEXT_PUBLIC_URL || "";
import { APP_URL } from "./constants";
type SendFrameNotificationResult =
| {
@@ -38,7 +37,7 @@ export async function sendFrameNotification({
notificationId: crypto.randomUUID(),
title,
body,
targetUrl: appUrl,
targetUrl: APP_URL,
tokens: [notificationDetails.token],
} satisfies SendNotificationRequest),
});

View File

@@ -1,24 +1,31 @@
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { mnemonicToAccount } from 'viem/accounts';
import { APP_BUTTON_TEXT, APP_DESCRIPTION, APP_ICON_URL, APP_NAME, APP_OG_IMAGE_URL, APP_PRIMARY_CATEGORY, APP_SPLASH_BACKGROUND_COLOR, APP_TAGS, APP_URL, APP_WEBHOOK_URL } from './constants';
import { APP_SPLASH_URL } from './constants';
interface FrameMetadata {
version: string;
name: string;
iconUrl: string;
homeUrl: string;
imageUrl?: string;
buttonTitle?: string;
splashImageUrl?: string;
splashBackgroundColor?: string;
webhookUrl?: string;
description?: string;
primaryCategory?: string;
tags?: string[];
};
interface FrameManifest {
accountAssociation?: {
header: string;
payload: string;
signature: string;
};
frame: {
version: string;
name: string;
iconUrl: string;
homeUrl: string;
imageUrl: string;
buttonTitle: string;
splashImageUrl: string;
splashBackgroundColor: string;
webhookUrl: string;
};
frame: FrameMetadata;
}
export function cn(...inputs: ClassValue[]) {
@@ -36,7 +43,28 @@ export function getSecretEnvVars() {
return { seedPhrase, fid };
}
export async function getFarcasterMetadata(): Promise<FrameMetadata> {
export function getFrameEmbedMetadata(ogImageUrl?: string) {
return {
version: "next",
imageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
button: {
title: APP_BUTTON_TEXT,
action: {
type: "launch_frame",
name: APP_NAME,
url: APP_URL,
splashImageUrl: APP_SPLASH_URL,
iconUrl: APP_ICON_URL,
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
description: APP_DESCRIPTION,
primaryCategory: APP_PRIMARY_CATEGORY,
tags: APP_TAGS,
},
},
};
}
export async function getFarcasterMetadata(): Promise<FrameManifest> {
// First check for FRAME_METADATA in .env and use that if it exists
if (process.env.FRAME_METADATA) {
try {
@@ -48,13 +76,12 @@ export async function getFarcasterMetadata(): Promise<FrameMetadata> {
}
}
const appUrl = process.env.NEXT_PUBLIC_URL;
if (!appUrl) {
if (!APP_URL) {
throw new Error('NEXT_PUBLIC_URL not configured');
}
// Get the domain from the URL (without https:// prefix)
const domain = new URL(appUrl).hostname;
const domain = new URL(APP_URL).hostname;
console.log('Using domain for manifest:', domain);
const secretEnvVars = getSecretEnvVars();
@@ -92,25 +119,21 @@ export async function getFarcasterMetadata(): Promise<FrameMetadata> {
};
}
// Determine webhook URL based on whether Neynar is enabled
const neynarApiKey = process.env.NEYNAR_API_KEY;
const neynarClientId = process.env.NEYNAR_CLIENT_ID;
const webhookUrl = neynarApiKey && neynarClientId
? `https://api.neynar.com/f/app/${neynarClientId}/event`
: `${appUrl}/api/webhook`;
return {
accountAssociation,
frame: {
version: "1",
name: process.env.NEXT_PUBLIC_FRAME_NAME || "Frames v2 Demo",
iconUrl: `${appUrl}/icon.png`,
homeUrl: appUrl,
imageUrl: `${appUrl}/opengraph-image`,
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT || "Launch Frame",
splashImageUrl: `${appUrl}/splash.png`,
splashBackgroundColor: "#f7f7f7",
webhookUrl,
name: APP_NAME ?? "Frames v2 Demo",
iconUrl: APP_ICON_URL,
homeUrl: APP_URL,
imageUrl: APP_OG_IMAGE_URL,
buttonTitle: APP_BUTTON_TEXT ?? "Launch Frame",
splashImageUrl: APP_SPLASH_URL,
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
webhookUrl: APP_WEBHOOK_URL,
description: APP_DESCRIPTION,
primaryCategory: APP_PRIMARY_CATEGORY,
tags: APP_TAGS,
},
};
}