mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-11 11:52:35 -05:00
Compare commits
39 Commits
lucas/begi
...
arthur/ney
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41973daea2 | ||
|
|
a39cb6a0da | ||
|
|
fab3ce9a10 | ||
|
|
b239f0553b | ||
|
|
7b754ba8fe | ||
|
|
d36a6920f5 | ||
|
|
6c5482bda4 | ||
|
|
5090a76fb4 | ||
|
|
0aaec3495a | ||
|
|
65496acc55 | ||
|
|
792beee05a | ||
|
|
55755bd91b | ||
|
|
d6791fe7c3 | ||
|
|
880b149300 | ||
|
|
7f10d4e8c0 | ||
|
|
9f748076db | ||
|
|
a352e8d5ec | ||
|
|
f2d2e26a4a | ||
|
|
3fcd2f6e52 | ||
|
|
3c9d845f44 | ||
|
|
d38bce50c5 | ||
|
|
f350aaa897 | ||
|
|
5fe54a80da | ||
|
|
08091fc206 | ||
|
|
681f287c20 | ||
|
|
f3f8924fa9 | ||
|
|
eda896e478 | ||
|
|
d8c53ceab7 | ||
|
|
5f0fd8876a | ||
|
|
40e40543cd | ||
|
|
eba6b89593 | ||
|
|
a5000b7e71 | ||
|
|
46058db54f | ||
|
|
19788e2ade | ||
|
|
1baea5d793 | ||
|
|
18b36f9603 | ||
|
|
9b5cc10b4c | ||
|
|
6c35293e80 | ||
|
|
b3e419b1f6 |
42
README.md
42
README.md
@@ -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.
|
||||
|
||||
|
||||
156
bin/init.js
156
bin/init.js
@@ -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: '🪐 Neynar is an API that makes it easy to build on Farcaster.\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,10 +244,10 @@ 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;
|
||||
@@ -237,15 +256,26 @@ export async function init() {
|
||||
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 +311,15 @@ 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",
|
||||
"@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",
|
||||
@@ -314,6 +346,7 @@ export async function init() {
|
||||
"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"
|
||||
@@ -340,7 +373,10 @@ 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, `\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 +406,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
2
index.d.ts
vendored
@@ -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>;
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@neynar/create-farcaster-mini-app",
|
||||
"version": "1.2.11",
|
||||
"version": "1.2.28",
|
||||
"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"
|
||||
|
||||
@@ -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,6 +351,8 @@ 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}"`,
|
||||
|
||||
// Neynar configuration (if it exists in current env)
|
||||
@@ -387,9 +395,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) {
|
||||
|
||||
@@ -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,6 +118,8 @@ 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',
|
||||
'NEYNAR_API_KEY',
|
||||
'NEYNAR_CLIENT_ID'
|
||||
@@ -153,14 +161,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 +204,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 +252,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 +264,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 +392,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 +584,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 +597,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();
|
||||
|
||||
@@ -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
|
||||
|
||||
30
src/app/api/opengraph-image/route.tsx
Normal file
30
src/app/api/opengraph-image/route.tsx
Normal 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,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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} />;
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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()),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import dynamic from "next/dynamic";
|
||||
import type { Session } from "next-auth"
|
||||
import { SessionProvider } from "next-auth/react"
|
||||
import { FrameProvider } from "~/components/providers/FrameProvider";
|
||||
import { SafeFarcasterSolanaProvider } from "~/components/providers/SafeFarcasterSolanaProvider";
|
||||
|
||||
const WagmiProvider = dynamic(
|
||||
() => import("~/components/providers/WagmiProvider"),
|
||||
@@ -13,11 +14,14 @@ 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}
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
{children}
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</FrameProvider>
|
||||
</WagmiProvider>
|
||||
</SessionProvider>
|
||||
|
||||
30
src/app/share/[fid]/page.tsx
Normal file
30
src/app/share/[fid]/page.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { 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: { fid: string } }): Promise<Metadata> {
|
||||
const fid = params.fid;
|
||||
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("/");
|
||||
}
|
||||
14
src/auth.ts
14
src/auth.ts
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
@@ -26,18 +31,34 @@ import { BaseError, UserRejectedRequestError } from "viem";
|
||||
import { useSession } from "next-auth/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 } = useFrame();
|
||||
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 +80,7 @@ export default function Demo(
|
||||
} = useSignTypedData();
|
||||
|
||||
const { disconnect } = useDisconnect();
|
||||
const { connect } = useConnect();
|
||||
const { connect, connectors } = useConnect();
|
||||
|
||||
const {
|
||||
switchChain,
|
||||
@@ -86,18 +107,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 +234,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 +303,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 +337,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 +426,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 +786,7 @@ function ViewProfile() {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const renderError = (error: Error | null) => {
|
||||
if (!error) return null;
|
||||
if (error instanceof BaseError) {
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import sdk, { type Context, type FrameNotificationDetails, AddFrame } from "@farcaster/frame-sdk";
|
||||
import sdk, { type Context, type FrameNotificationDetails, AddMiniApp } from "@farcaster/frame-sdk";
|
||||
import { createStore } from "mipd";
|
||||
import React from "react";
|
||||
|
||||
interface FrameContextType {
|
||||
isSDKLoaded: boolean;
|
||||
context: Context.FrameContext | undefined;
|
||||
openUrl: (url: string) => Promise<void>;
|
||||
close: () => Promise<void>;
|
||||
added: boolean;
|
||||
notificationDetails: FrameNotificationDetails | null;
|
||||
lastEvent: string;
|
||||
addFrame: () => Promise<void>;
|
||||
addFrameResult: string;
|
||||
}
|
||||
|
||||
const FrameContext = React.createContext<FrameContextType | undefined>(undefined);
|
||||
@@ -20,10 +27,26 @@ export function useFrame() {
|
||||
const [lastEvent, setLastEvent] = useState("");
|
||||
const [addFrameResult, setAddFrameResult] = useState("");
|
||||
|
||||
// SDK actions only work in mini app clients, so this pattern supports browser actions as well
|
||||
const openUrl = useCallback(async (url: string) => {
|
||||
if (context) {
|
||||
await sdk.actions.openUrl(url);
|
||||
} else {
|
||||
window.open(url, '_blank');
|
||||
}
|
||||
}, [context]);
|
||||
|
||||
const close = useCallback(async () => {
|
||||
if (context) {
|
||||
await sdk.actions.close();
|
||||
} else {
|
||||
window.close();
|
||||
}
|
||||
}, [context]);
|
||||
|
||||
const addFrame = useCallback(async () => {
|
||||
try {
|
||||
setNotificationDetails(null);
|
||||
|
||||
const result = await sdk.actions.addFrame();
|
||||
|
||||
if (result.notificationDetails) {
|
||||
@@ -35,15 +58,11 @@ export function useFrame() {
|
||||
: "Added, got no notification details"
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof AddFrame.RejectedByUser) {
|
||||
if (error instanceof AddMiniApp.RejectedByUser || error instanceof AddMiniApp.InvalidDomainManifest) {
|
||||
setAddFrameResult(`Not added: ${error.message}`);
|
||||
}else {
|
||||
setAddFrameResult(`Error: ${error}`);
|
||||
}
|
||||
|
||||
if (error instanceof AddFrame.InvalidDomainManifest) {
|
||||
setAddFrameResult(`Not added: ${error.message}`);
|
||||
}
|
||||
|
||||
setAddFrameResult(`Error: ${error}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -111,18 +130,28 @@ export function useFrame() {
|
||||
}
|
||||
}, [isSDKLoaded]);
|
||||
|
||||
return { isSDKLoaded, context, added, notificationDetails, lastEvent, addFrame, addFrameResult };
|
||||
return {
|
||||
isSDKLoaded,
|
||||
context,
|
||||
added,
|
||||
notificationDetails,
|
||||
lastEvent,
|
||||
addFrame,
|
||||
addFrameResult,
|
||||
openUrl,
|
||||
close,
|
||||
};
|
||||
}
|
||||
|
||||
export function FrameProvider({ children }: { children: React.ReactNode }) {
|
||||
const { isSDKLoaded, context } = useFrame();
|
||||
const frameContext = useFrame();
|
||||
|
||||
if (!isSDKLoaded) {
|
||||
if (!frameContext.isSDKLoaded) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<FrameContext.Provider value={{ isSDKLoaded, context }}>
|
||||
<FrameContext.Provider value={frameContext}>
|
||||
{children}
|
||||
</FrameContext.Provider>
|
||||
);
|
||||
|
||||
86
src/components/providers/SafeFarcasterSolanaProvider.tsx
Normal file
86
src/components/providers/SafeFarcasterSolanaProvider.tsx
Normal 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;
|
||||
}
|
||||
@@ -2,6 +2,44 @@ import { createConfig, http, WagmiProvider } from "wagmi";
|
||||
import { base, degen, mainnet, optimism, unichain } 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],
|
||||
@@ -12,15 +50,38 @@ export const config = createConfig({
|
||||
[degen.id]: http(),
|
||||
[unichain.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
13
src/lib/constants.ts
Normal 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`;
|
||||
@@ -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(
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user