mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-11 03:42:32 -05:00
Compare commits
65 Commits
lucas/begi
...
veganbeef/
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f0300fd7c | ||
|
|
e20a2a397d | ||
|
|
bef42eddd4 | ||
|
|
3a9f2cf8b8 | ||
|
|
4301252202 | ||
|
|
2b85800ba7 | ||
|
|
9f5d80fddd | ||
|
|
601f20bca3 | ||
|
|
e349724267 | ||
|
|
f97a697f88 | ||
|
|
4831308983 | ||
|
|
cfe51f067c | ||
|
|
8966dcee30 | ||
|
|
6a056cb30c | ||
|
|
7263cdef0e | ||
|
|
21ccdf3623 | ||
|
|
42152c3492 | ||
|
|
3bf80740c0 | ||
|
|
39437af6f0 | ||
|
|
7b87bc4dfa | ||
|
|
5420b8fca0 | ||
|
|
9cd07170b9 | ||
|
|
3e1acfce42 | ||
|
|
0b139f184d | ||
|
|
16a3e69a43 | ||
|
|
41973daea2 | ||
|
|
a39cb6a0da | ||
|
|
fab3ce9a10 | ||
|
|
b239f0553b | ||
|
|
7b754ba8fe | ||
|
|
d36a6920f5 | ||
|
|
6c5482bda4 | ||
|
|
5090a76fb4 | ||
|
|
0aaec3495a | ||
|
|
65496acc55 | ||
|
|
792beee05a | ||
|
|
55755bd91b | ||
|
|
d6791fe7c3 | ||
|
|
880b149300 | ||
|
|
7df556740d | ||
|
|
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 |
@@ -4,3 +4,8 @@ KV_REST_API_TOKEN=''
|
||||
KV_REST_API_URL=''
|
||||
NEXT_PUBLIC_URL='http://localhost:3000'
|
||||
NEXTAUTH_URL='http://localhost:3000'
|
||||
|
||||
NEXTAUTH_SECRET=""
|
||||
NEYNAR_API_KEY=""
|
||||
NEYNAR_CLIENT_ID=""
|
||||
USE_TUNNEL="false"
|
||||
|
||||
44
README.md
44
README.md
@@ -1,12 +1,16 @@
|
||||
# Farcaster Mini Apps (formerly Frames) Quickstart by Neynar 🪐
|
||||
# Farcaster Mini Apps (formerly Frames v2) Quickstart by Neynar 🪐
|
||||
|
||||
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.
|
||||
|
||||
|
||||
25
bin/index.js
25
bin/index.js
@@ -2,7 +2,30 @@
|
||||
|
||||
import { init } from './init.js';
|
||||
|
||||
init().catch((err) => {
|
||||
// Parse command line arguments
|
||||
const args = process.argv.slice(2);
|
||||
let projectName = null;
|
||||
let autoAcceptDefaults = false;
|
||||
|
||||
// Check for -y flag
|
||||
const yIndex = args.indexOf('-y');
|
||||
if (yIndex !== -1) {
|
||||
autoAcceptDefaults = true;
|
||||
args.splice(yIndex, 1); // Remove -y from args
|
||||
}
|
||||
|
||||
// If there's a remaining argument, it's the project name
|
||||
if (args.length > 0) {
|
||||
projectName = args[0];
|
||||
}
|
||||
|
||||
// If -y is used without project name, we still need to ask for project name
|
||||
if (autoAcceptDefaults && !projectName) {
|
||||
// We'll handle this case in the init function by asking only for project name
|
||||
autoAcceptDefaults = false;
|
||||
}
|
||||
|
||||
init(projectName, autoAcceptDefaults).catch((err) => {
|
||||
console.error('Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
456
bin/init.js
456
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 the Neynar Starter Kit${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,36 +60,8 @@ 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() {
|
||||
export async function init(projectName = null, autoAcceptDefaults = false) {
|
||||
printWelcomeMessage();
|
||||
|
||||
// Ask about Neynar usage
|
||||
@@ -98,50 +72,78 @@ export async function init() {
|
||||
let neynarAppLogoUrl = null;
|
||||
|
||||
while (useNeynar) {
|
||||
const neynarAnswers = await inquirer.prompt([
|
||||
{
|
||||
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?',
|
||||
default: true
|
||||
}
|
||||
]);
|
||||
let neynarAnswers;
|
||||
if (autoAcceptDefaults) {
|
||||
neynarAnswers = { useNeynar: true };
|
||||
} else {
|
||||
neynarAnswers = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useNeynar',
|
||||
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
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
if (!neynarAnswers.useNeynar) {
|
||||
useNeynar = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const neynarKeyAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'password',
|
||||
name: 'neynarApiKey',
|
||||
message: 'Enter your Neynar API key (or press enter to skip):',
|
||||
default: null
|
||||
}
|
||||
]);
|
||||
console.log('\n🪐 Find your Neynar API key at: https://dev.neynar.com/app\n');
|
||||
|
||||
let neynarKeyAnswer;
|
||||
if (autoAcceptDefaults) {
|
||||
neynarKeyAnswer = { neynarApiKey: null };
|
||||
} else {
|
||||
neynarKeyAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'password',
|
||||
name: 'neynarApiKey',
|
||||
message: 'Enter your Neynar API key (or press enter to skip):',
|
||||
default: null
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
if (neynarKeyAnswer.neynarApiKey) {
|
||||
neynarApiKey = neynarKeyAnswer.neynarApiKey;
|
||||
} else {
|
||||
const useDemoKey = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useDemo',
|
||||
message: 'Would you like to try the demo Neynar API key?',
|
||||
default: true
|
||||
}
|
||||
]);
|
||||
let useDemoKey;
|
||||
if (autoAcceptDefaults) {
|
||||
useDemoKey = { useDemo: true };
|
||||
} else {
|
||||
useDemoKey = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useDemo',
|
||||
message: 'Would you like to try the demo Neynar API key?',
|
||||
default: true
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
if (!neynarApiKey) {
|
||||
if (autoAcceptDefaults) {
|
||||
useNeynar = false;
|
||||
break;
|
||||
}
|
||||
console.log('\n⚠️ No valid API key provided. Would you like to try again?');
|
||||
const { retry } = await inquirer.prompt([
|
||||
{
|
||||
@@ -166,6 +168,10 @@ export async function init() {
|
||||
}
|
||||
|
||||
if (!neynarClientId) {
|
||||
if (autoAcceptDefaults) {
|
||||
useNeynar = false;
|
||||
break;
|
||||
}
|
||||
const { retry } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
@@ -185,67 +191,166 @@ export async function init() {
|
||||
break;
|
||||
}
|
||||
|
||||
const defaultFrameName = (neynarAppName && !neynarAppName.toLowerCase().includes('demo')) ? neynarAppName : undefined;
|
||||
const defaultMiniAppName = (neynarAppName && !neynarAppName.toLowerCase().includes('demo')) ? neynarAppName : undefined;
|
||||
|
||||
const answers = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'projectName',
|
||||
message: 'What is the name of your frame?',
|
||||
default: defaultFrameName,
|
||||
validate: (input) => {
|
||||
if (input.trim() === '') {
|
||||
return 'Project name cannot be empty';
|
||||
let answers;
|
||||
if (autoAcceptDefaults) {
|
||||
answers = {
|
||||
projectName: projectName || defaultMiniAppName || 'my-farcaster-mini-app',
|
||||
description: 'A Farcaster mini app created with Neynar',
|
||||
primaryCategory: null,
|
||||
tags: [],
|
||||
buttonText: 'Launch Mini App',
|
||||
useWallet: true,
|
||||
useTunnel: true,
|
||||
enableAnalytics: true
|
||||
};
|
||||
} else {
|
||||
// If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options
|
||||
const projectNamePrompt = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'projectName',
|
||||
message: 'What is the name of your mini app?',
|
||||
default: projectName || defaultMiniAppName,
|
||||
validate: (input) => {
|
||||
if (input.trim() === '') {
|
||||
return 'Project name cannot be empty';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'input',
|
||||
name: 'description',
|
||||
message: 'Give a one-line description of your frame (optional):',
|
||||
default: 'A Farcaster mini-app created with Neynar'
|
||||
},
|
||||
{
|
||||
type: 'input',
|
||||
name: 'buttonText',
|
||||
message: 'Enter the button text for your frame:',
|
||||
default: 'Launch Frame',
|
||||
validate: (input) => {
|
||||
if (input.trim() === '') {
|
||||
return 'Button text cannot be empty';
|
||||
]);
|
||||
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'description',
|
||||
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 mini app:',
|
||||
default: 'Launch Mini App',
|
||||
validate: (input) => {
|
||||
if (input.trim() === '') {
|
||||
return 'Button text cannot be empty';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]);
|
||||
]);
|
||||
|
||||
// Ask about localhost vs tunnel
|
||||
const hostingAnswer = await inquirer.prompt([
|
||||
{
|
||||
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
|
||||
}
|
||||
]);
|
||||
answers.useTunnel = hostingAnswer.useTunnel;
|
||||
// Merge project name from the first prompt
|
||||
answers.projectName = projectNamePrompt.projectName;
|
||||
|
||||
const projectName = answers.projectName;
|
||||
const projectDirName = projectName.replace(/\s+/g, '-').toLowerCase();
|
||||
// Ask about wallet and transaction tooling
|
||||
const walletAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useWallet',
|
||||
message: 'Would you like to include wallet and transaction tooling in your mini app?\n' +
|
||||
'This includes:\n' +
|
||||
'- EVM wallet connection\n' +
|
||||
'- Transaction signing\n' +
|
||||
'- Message signing\n' +
|
||||
'- Chain switching\n' +
|
||||
'- Solana support\n\n' +
|
||||
'Include wallet and transaction features?',
|
||||
default: true
|
||||
}
|
||||
]);
|
||||
answers.useWallet = walletAnswer.useWallet;
|
||||
|
||||
// Ask about localhost vs tunnel
|
||||
const hostingAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useTunnel',
|
||||
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 finalProjectName = answers.projectName;
|
||||
const projectDirName = finalProjectName.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.');
|
||||
@@ -268,7 +373,7 @@ export async function init() {
|
||||
const packageJsonPath = path.join(projectPath, 'package.json');
|
||||
let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
||||
|
||||
packageJson.name = projectName;
|
||||
packageJson.name = finalProjectName;
|
||||
packageJson.version = '0.1.0';
|
||||
delete packageJson.author;
|
||||
delete packageJson.keywords;
|
||||
@@ -281,13 +386,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.17 <1.0.0",
|
||||
"@neynar/react": "^1.2.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",
|
||||
@@ -295,10 +403,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 +416,22 @@ export async function init() {
|
||||
|
||||
packageJson.devDependencies = {
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^18",
|
||||
"@types/react-dom": "^18",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@vercel/sdk": "^1.9.0",
|
||||
"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));
|
||||
@@ -337,10 +446,93 @@ export async function init() {
|
||||
// Write it to .env.local
|
||||
fs.writeFileSync(envPath, envExampleContent);
|
||||
|
||||
// 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_BUTTON_TEXT="${answers.buttonText}"`);
|
||||
// Append remaining environment variables
|
||||
// Update constants.ts file with user-provided values
|
||||
console.log('\nUpdating constants.ts...');
|
||||
const constantsPath = path.join(projectPath, 'src', 'lib', 'constants.ts');
|
||||
if (fs.existsSync(constantsPath)) {
|
||||
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
|
||||
|
||||
// Helper function to escape single quotes in strings
|
||||
const escapeString = (str) => str.replace(/'/g, "\\'");
|
||||
|
||||
// Helper function to safely replace constants with validation
|
||||
const safeReplace = (content, pattern, replacement, constantName) => {
|
||||
const newContent = content.replace(pattern, replacement);
|
||||
if (newContent === content) {
|
||||
console.log(`⚠️ Warning: Could not update ${constantName} in constants.ts`);
|
||||
}
|
||||
return newContent;
|
||||
};
|
||||
|
||||
// Update APP_NAME
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const APP_NAME\s*=\s*['"`][^'"`]*['"`];/,
|
||||
`export const APP_NAME = '${escapeString(answers.projectName)}';`,
|
||||
'APP_NAME'
|
||||
);
|
||||
|
||||
// Update APP_DESCRIPTION
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const APP_DESCRIPTION\s*=\s*['"`][^'"`]*['"`];/,
|
||||
`export const APP_DESCRIPTION = '${escapeString(answers.description)}';`,
|
||||
'APP_DESCRIPTION'
|
||||
);
|
||||
|
||||
// Update APP_PRIMARY_CATEGORY
|
||||
if (answers.primaryCategory) {
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const APP_PRIMARY_CATEGORY\s*=\s*['"`][^'"`]*['"`];/,
|
||||
`export const APP_PRIMARY_CATEGORY = '${escapeString(answers.primaryCategory)}';`,
|
||||
'APP_PRIMARY_CATEGORY'
|
||||
);
|
||||
}
|
||||
|
||||
// Update APP_TAGS
|
||||
const tagsString = answers.tags.length > 0
|
||||
? `['${answers.tags.map(tag => escapeString(tag)).join("', '")}']`
|
||||
: "['neynar', 'starter-kit', 'demo']";
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const APP_TAGS\s*=\s*\[[^\]]*\];/,
|
||||
`export const APP_TAGS = ${tagsString};`,
|
||||
'APP_TAGS'
|
||||
);
|
||||
|
||||
// Update APP_BUTTON_TEXT
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const APP_BUTTON_TEXT\s*=\s*['"`][^'"`]*['"`];/,
|
||||
`export const APP_BUTTON_TEXT = '${escapeString(answers.buttonText)}';`,
|
||||
'APP_BUTTON_TEXT'
|
||||
);
|
||||
|
||||
// Update USE_WALLET
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const USE_WALLET\s*=\s*(true|false);/,
|
||||
`export const USE_WALLET = ${answers.useWallet};`,
|
||||
'USE_WALLET'
|
||||
);
|
||||
|
||||
// Update ANALYTICS_ENABLED
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
/export const ANALYTICS_ENABLED\s*=\s*(true|false);/,
|
||||
`export const ANALYTICS_ENABLED = ${answers.enableAnalytics};`,
|
||||
'ANALYTICS_ENABLED'
|
||||
);
|
||||
|
||||
fs.writeFileSync(constantsPath, constantsContent);
|
||||
console.log('✅ Updated constants.ts with user configuration');
|
||||
} else {
|
||||
console.log('⚠️ constants.ts not found, skipping constants update');
|
||||
}
|
||||
|
||||
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 +562,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...');
|
||||
@@ -387,7 +587,7 @@ export async function init() {
|
||||
execSync('git commit -m "initial commit from @neynar/create-farcaster-mini-app"', { cwd: projectPath });
|
||||
|
||||
// Calculate border length based on message length
|
||||
const message = `✨🪐 Successfully created frame ${projectName} with git and dependencies installed! 🪐✨`;
|
||||
const message = `✨🪐 Successfully created mini app ${finalProjectName} with git and dependencies installed! 🪐✨`;
|
||||
const borderLength = message.length;
|
||||
const borderStars = '✨'.repeat((borderLength / 2) + 1);
|
||||
|
||||
@@ -395,6 +595,6 @@ export async function init() {
|
||||
console.log(`${message}`);
|
||||
console.log(`${borderStars}`);
|
||||
console.log('\nTo run the app:');
|
||||
console.log(` cd ${projectName}`);
|
||||
console.log(` cd ${finalProjectName}`);
|
||||
console.log(' npm run dev\n');
|
||||
}
|
||||
|
||||
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>;
|
||||
10
package.json
10
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@neynar/create-farcaster-mini-app",
|
||||
"version": "1.2.11",
|
||||
"version": "1.5.0",
|
||||
"type": "module",
|
||||
"private": false,
|
||||
"access": "public",
|
||||
@@ -22,6 +22,9 @@
|
||||
"frame",
|
||||
"frames-v2",
|
||||
"farcaster-frames",
|
||||
"miniapps",
|
||||
"miniapp",
|
||||
"mini-apps",
|
||||
"mini-app",
|
||||
"neynar",
|
||||
"web3"
|
||||
@@ -29,9 +32,12 @@
|
||||
"scripts": {
|
||||
"dev": "node scripts/dev.js",
|
||||
"build": "node scripts/build.js",
|
||||
"build:raw": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"deploy:vercel": "node scripts/deploy.js"
|
||||
"deploy:vercel": "node scripts/deploy.js",
|
||||
"deploy:raw": "vercel --prod",
|
||||
"cleanup": "lsof -ti :3000 | xargs kill -9"
|
||||
},
|
||||
"bin": {
|
||||
"@neynar/create-farcaster-mini-app": "./bin/index.js"
|
||||
|
||||
@@ -20,13 +20,14 @@ 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',
|
||||
'x-api-key': apiKey
|
||||
'x-api-key': 'FARCASTER_V2_FRAMES_DEMO'
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -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_MINI_APP_TAGS?.split(',');
|
||||
|
||||
return {
|
||||
accountAssociation: {
|
||||
header: encodedHeader,
|
||||
@@ -168,14 +171,17 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
|
||||
},
|
||||
frame: {
|
||||
version: "1",
|
||||
name: process.env.NEXT_PUBLIC_FRAME_NAME,
|
||||
name: process.env.NEXT_PUBLIC_MINI_APP_NAME,
|
||||
iconUrl: `https://${domain}/icon.png`,
|
||||
homeUrl: `https://${domain}`,
|
||||
imageUrl: `https://${domain}/opengraph-image`,
|
||||
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT,
|
||||
imageUrl: `https://${domain}/api/opengraph-image`,
|
||||
buttonTitle: process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT,
|
||||
splashImageUrl: `https://${domain}/splash.png`,
|
||||
splashBackgroundColor: "#f7f7f7",
|
||||
webhookUrl,
|
||||
description: process.env.NEXT_PUBLIC_MINI_APP_DESCRIPTION,
|
||||
primaryCategory: process.env.NEXT_PUBLIC_MINI_APP_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):',
|
||||
default: process.env.NEXT_PUBLIC_FRAME_NAME,
|
||||
message: 'Enter the name for your mini app (e.g., My Cool Mini App):',
|
||||
default: process.env.NEXT_PUBLIC_MINI_APP_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_MINI_APP_BUTTON_TEXT || 'Launch Mini App',
|
||||
validate: (input) => {
|
||||
if (input.trim() === '') {
|
||||
return 'Button text cannot be empty';
|
||||
@@ -263,10 +269,17 @@ async function main() {
|
||||
}
|
||||
|
||||
// Try to get client ID from API
|
||||
const appInfo = await queryNeynarApp(neynarApiKey);
|
||||
if (appInfo) {
|
||||
neynarClientId = appInfo.app_uuid;
|
||||
console.log('✅ Fetched Neynar app client ID');
|
||||
if (!neynarClientId) {
|
||||
const appInfo = await queryNeynarApp(neynarApiKey);
|
||||
if (appInfo) {
|
||||
neynarClientId = appInfo.app_uuid;
|
||||
console.log('✅ Fetched Neynar app client ID');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// We have a client ID (either from .env or fetched from API), so we can break out of the loop
|
||||
if (neynarClientId) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -299,7 +312,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 +336,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 +344,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');
|
||||
@@ -342,10 +355,15 @@ async function main() {
|
||||
// Base URL
|
||||
`NEXT_PUBLIC_URL=https://${domain}`,
|
||||
|
||||
// Frame metadata
|
||||
`NEXT_PUBLIC_FRAME_NAME="${frameName}"`,
|
||||
`NEXT_PUBLIC_FRAME_DESCRIPTION="${process.env.NEXT_PUBLIC_FRAME_DESCRIPTION || ''}"`,
|
||||
`NEXT_PUBLIC_FRAME_BUTTON_TEXT="${buttonText}"`,
|
||||
// Mini app metadata
|
||||
`NEXT_PUBLIC_MINI_APP_NAME="${frameName}"`,
|
||||
`NEXT_PUBLIC_MINI_APP_DESCRIPTION="${process.env.NEXT_PUBLIC_MINI_APP_DESCRIPTION || ''}"`,
|
||||
`NEXT_PUBLIC_MINI_APP_PRIMARY_CATEGORY="${process.env.NEXT_PUBLIC_MINI_APP_PRIMARY_CATEGORY || ''}"`,
|
||||
`NEXT_PUBLIC_MINI_APP_TAGS="${process.env.NEXT_PUBLIC_MINI_APP_TAGS || ''}"`,
|
||||
`NEXT_PUBLIC_MINI_APP_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 ?
|
||||
@@ -355,13 +373,14 @@ async function main() {
|
||||
|
||||
// FID (if it exists in current env)
|
||||
...(process.env.FID ? [`FID="${process.env.FID}"`] : []),
|
||||
`NEXT_PUBLIC_USE_WALLET="${process.env.NEXT_PUBLIC_USE_WALLET || 'false'}"`,
|
||||
|
||||
// NextAuth configuration
|
||||
`NEXTAUTH_SECRET="${process.env.NEXTAUTH_SECRET || crypto.randomBytes(32).toString('hex')}"`,
|
||||
`NEXTAUTH_URL="https://${domain}"`,
|
||||
|
||||
// Frame manifest with signature
|
||||
`FRAME_METADATA=${JSON.stringify(metadata)}`,
|
||||
// Mini app manifest with signature
|
||||
`MINI_APP_METADATA=${JSON.stringify(metadata)}`,
|
||||
];
|
||||
|
||||
// Filter out empty values and join with newlines
|
||||
@@ -387,9 +406,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) {
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { fileURLToPath } from 'url';
|
||||
import inquirer from 'inquirer';
|
||||
import dotenv from 'dotenv';
|
||||
import crypto from 'crypto';
|
||||
import { mnemonicToAccount } from 'viem/accounts';
|
||||
import { Vercel } from '@vercel/sdk';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const projectRoot = path.join(__dirname, '..');
|
||||
|
||||
// Load environment variables in specific order
|
||||
// First load .env for main config
|
||||
dotenv.config({ path: '.env' });
|
||||
|
||||
async function validateSeedPhrase(seedPhrase) {
|
||||
try {
|
||||
// Try to create an account from the seed phrase
|
||||
const account = mnemonicToAccount(seedPhrase);
|
||||
return account.address;
|
||||
} 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_MINI_APP_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_MINI_APP_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_MINI_APP_BUTTON_TEXT,
|
||||
splashImageUrl: `https://${trimmedDomain}/splash.png`,
|
||||
splashBackgroundColor: "#f7f7f7",
|
||||
webhookUrl: webhookUrl?.trim(),
|
||||
description: process.env.NEXT_PUBLIC_MINI_APP_DESCRIPTION,
|
||||
primaryCategory: process.env.NEXT_PUBLIC_MINI_APP_PRIMARY_CATEGORY,
|
||||
tags,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -107,38 +113,35 @@ async function loadEnvLocal() {
|
||||
console.log('Loading values from .env.local...');
|
||||
const localEnv = dotenv.parse(fs.readFileSync('.env.local'));
|
||||
|
||||
// Define allowed variables to load from .env.local
|
||||
const allowedVars = [
|
||||
'SEED_PHRASE',
|
||||
'NEXT_PUBLIC_FRAME_NAME',
|
||||
'NEXT_PUBLIC_FRAME_DESCRIPTION',
|
||||
'NEXT_PUBLIC_FRAME_BUTTON_TEXT',
|
||||
'NEXT_PUBLIC_MINI_APP_NAME',
|
||||
'NEXT_PUBLIC_MINI_APP_DESCRIPTION',
|
||||
'NEXT_PUBLIC_MINI_APP_PRIMARY_CATEGORY',
|
||||
'NEXT_PUBLIC_MINI_APP_TAGS',
|
||||
'NEXT_PUBLIC_MINI_APP_BUTTON_TEXT',
|
||||
'NEXT_PUBLIC_ANALYTICS_ENABLED',
|
||||
'NEYNAR_API_KEY',
|
||||
'NEYNAR_CLIENT_ID'
|
||||
];
|
||||
|
||||
// Copy allowed values except SEED_PHRASE to .env
|
||||
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') + '\n' : '';
|
||||
let newEnvContent = envContent;
|
||||
|
||||
for (const [key, value] of Object.entries(localEnv)) {
|
||||
if (allowedVars.includes(key)) {
|
||||
// Update process.env
|
||||
process.env[key] = value;
|
||||
// Add to .env content if not already there (except for SEED_PHRASE)
|
||||
if (key !== 'SEED_PHRASE' && !envContent.includes(`${key}=`)) {
|
||||
newEnvContent += `${key}="${value}"\n`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write updated content to .env
|
||||
fs.writeFileSync('.env', newEnvContent);
|
||||
console.log('✅ Values from .env.local have been written to .env');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Error reading .env.local, which is fine
|
||||
console.log('Note: No .env.local file found');
|
||||
}
|
||||
}
|
||||
@@ -147,20 +150,19 @@ async function checkRequiredEnvVars() {
|
||||
console.log('\n📝 Checking environment variables...');
|
||||
console.log('Loading values from .env...');
|
||||
|
||||
// Load .env.local if user wants to
|
||||
await loadEnvLocal();
|
||||
|
||||
const requiredVars = [
|
||||
{
|
||||
name: 'NEXT_PUBLIC_FRAME_NAME',
|
||||
message: 'Enter the name for your frame (e.g., My Cool Frame):',
|
||||
default: process.env.NEXT_PUBLIC_FRAME_NAME,
|
||||
validate: input => input.trim() !== '' || 'Frame name cannot be empty'
|
||||
name: 'NEXT_PUBLIC_MINI_APP_NAME',
|
||||
message: 'Enter the name for your frame (e.g., My Cool Mini App):',
|
||||
default: process.env.NEXT_PUBLIC_MINI_APP_NAME,
|
||||
validate: input => input.trim() !== '' || 'Mini app name cannot be empty'
|
||||
},
|
||||
{
|
||||
name: 'NEXT_PUBLIC_FRAME_BUTTON_TEXT',
|
||||
name: 'NEXT_PUBLIC_MINI_APP_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_MINI_APP_BUTTON_TEXT ?? 'Launch Mini App',
|
||||
validate: input => input.trim() !== '' || 'Button text cannot be empty'
|
||||
}
|
||||
];
|
||||
@@ -179,15 +181,12 @@ async function checkRequiredEnvVars() {
|
||||
validate: varConfig.validate
|
||||
}
|
||||
]);
|
||||
// Write to both process.env and .env file
|
||||
|
||||
process.env[varConfig.name] = value;
|
||||
|
||||
// Read existing .env content
|
||||
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') : '';
|
||||
|
||||
// Check if the variable already exists in .env
|
||||
if (!envContent.includes(`${varConfig.name}=`)) {
|
||||
// Append the new variable to .env without extra newlines
|
||||
const newLine = envContent ? '\n' : '';
|
||||
fs.appendFileSync('.env', `${newLine}${varConfig.name}="${value.trim()}"`);
|
||||
}
|
||||
@@ -196,13 +195,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
|
||||
}
|
||||
]);
|
||||
@@ -220,7 +219,6 @@ async function checkRequiredEnvVars() {
|
||||
]);
|
||||
|
||||
if (storeSeedPhrase) {
|
||||
// Write to .env.local
|
||||
fs.appendFileSync('.env.local', `\nSEED_PHRASE="${seedPhrase}"`);
|
||||
console.log('✅ Seed phrase stored in .env.local');
|
||||
} else {
|
||||
@@ -244,7 +242,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 +254,43 @@ 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 getVercelToken() {
|
||||
try {
|
||||
// Try to get token from Vercel CLI config
|
||||
const configPath = path.join(os.homedir(), '.vercel', 'auth.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const authConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
||||
return authConfig.token;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not read Vercel token from config file');
|
||||
}
|
||||
|
||||
// Try environment variable
|
||||
if (process.env.VERCEL_TOKEN) {
|
||||
return process.env.VERCEL_TOKEN;
|
||||
}
|
||||
|
||||
// Try to extract from vercel whoami
|
||||
try {
|
||||
const whoamiOutput = execSync('vercel whoami', {
|
||||
encoding: 'utf8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
|
||||
// If we can get whoami, we're logged in, but we need the actual token
|
||||
// The token isn't directly exposed, so we'll need to use CLI for some operations
|
||||
console.log('✅ Verified Vercel CLI authentication');
|
||||
return null; // We'll fall back to CLI operations
|
||||
} catch (error) {
|
||||
throw new Error('Not logged in to Vercel CLI. Please run this script again to login.');
|
||||
}
|
||||
}
|
||||
|
||||
async function loginToVercel() {
|
||||
@@ -268,26 +305,16 @@ async function loginToVercel() {
|
||||
console.log('4. Return here once your Vercel account is created\n');
|
||||
console.log('\nNote: you may need to cancel this script with ctrl+c and run it again if creating a new vercel account');
|
||||
|
||||
// Start the login process
|
||||
const child = spawn('vercel', ['login'], {
|
||||
stdio: 'inherit'
|
||||
});
|
||||
|
||||
// Wait for the login process to complete
|
||||
await new Promise((resolve, reject) => {
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
// Don't reject here, as the process might exit with non-zero
|
||||
// during the browser auth flow
|
||||
resolve();
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
// After the browser flow completes, verify we're actually logged in
|
||||
// Keep checking for up to 5 minutes (increased timeout for new account setup)
|
||||
console.log('\n📱 Waiting for login to complete...');
|
||||
console.log('If you\'re creating a new account, please complete the Vercel account setup in your browser first.');
|
||||
|
||||
@@ -300,7 +327,6 @@ async function loginToVercel() {
|
||||
if (error.message.includes('Account not found')) {
|
||||
console.log('ℹ️ Waiting for Vercel account setup to complete...');
|
||||
}
|
||||
// Still not logged in, wait 2 seconds before trying again
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
}
|
||||
}
|
||||
@@ -312,9 +338,59 @@ async function loginToVercel() {
|
||||
return false;
|
||||
}
|
||||
|
||||
async function setVercelEnvVar(key, value, projectRoot) {
|
||||
async function setVercelEnvVarSDK(vercelClient, projectId, key, value) {
|
||||
try {
|
||||
// First try to remove the existing env var if it exists
|
||||
let processedValue;
|
||||
if (typeof value === 'object') {
|
||||
processedValue = JSON.stringify(value);
|
||||
} else {
|
||||
processedValue = value.toString();
|
||||
}
|
||||
|
||||
// Get existing environment variables
|
||||
const existingVars = await vercelClient.projects.getEnvironmentVariables({
|
||||
idOrName: projectId
|
||||
});
|
||||
|
||||
const existingVar = existingVars.envs?.find(env =>
|
||||
env.key === key && env.target?.includes('production')
|
||||
);
|
||||
|
||||
if (existingVar) {
|
||||
// Update existing variable
|
||||
await vercelClient.projects.editEnvironmentVariable({
|
||||
idOrName: projectId,
|
||||
id: existingVar.id,
|
||||
requestBody: {
|
||||
value: processedValue,
|
||||
target: ['production']
|
||||
}
|
||||
});
|
||||
console.log(`✅ Updated environment variable: ${key}`);
|
||||
} else {
|
||||
// Create new variable
|
||||
await vercelClient.projects.createEnvironmentVariable({
|
||||
idOrName: projectId,
|
||||
requestBody: {
|
||||
key: key,
|
||||
value: processedValue,
|
||||
type: 'encrypted',
|
||||
target: ['production']
|
||||
}
|
||||
});
|
||||
console.log(`✅ Created environment variable: ${key}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn(`⚠️ Warning: Failed to set environment variable ${key}:`, error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function setVercelEnvVarCLI(key, value, projectRoot) {
|
||||
try {
|
||||
// Remove existing env var
|
||||
try {
|
||||
execSync(`vercel env rm ${key} production -y`, {
|
||||
cwd: projectRoot,
|
||||
@@ -322,44 +398,82 @@ async function setVercelEnvVar(key, value, projectRoot) {
|
||||
env: process.env
|
||||
});
|
||||
} catch (error) {
|
||||
// Ignore errors from removal (var might not exist)
|
||||
// Ignore errors from removal
|
||||
}
|
||||
|
||||
// For complex objects like frameMetadata, use a temporary file approach
|
||||
|
||||
let processedValue;
|
||||
if (typeof value === 'object') {
|
||||
const tempFilePath = path.join(projectRoot, `${key}_temp.json`);
|
||||
// Write the value to a temporary file with proper JSON formatting
|
||||
fs.writeFileSync(tempFilePath, JSON.stringify(value));
|
||||
|
||||
// Use the file to add the environment variable
|
||||
execSync(`vercel env add ${key} production < "${tempFilePath}"`, {
|
||||
cwd: projectRoot,
|
||||
stdio: 'inherit',
|
||||
env: process.env
|
||||
});
|
||||
|
||||
// Clean up the temporary file
|
||||
fs.unlinkSync(tempFilePath);
|
||||
processedValue = JSON.stringify(value);
|
||||
} else {
|
||||
// For simple string values, use a different approach to avoid shell interpretation issues
|
||||
const tempFilePath = path.join(projectRoot, `${key}_temp.txt`);
|
||||
fs.writeFileSync(tempFilePath, value.toString());
|
||||
|
||||
execSync(`vercel env add ${key} production < "${tempFilePath}"`, {
|
||||
cwd: projectRoot,
|
||||
stdio: 'inherit',
|
||||
env: process.env
|
||||
});
|
||||
|
||||
fs.unlinkSync(tempFilePath);
|
||||
processedValue = value.toString();
|
||||
}
|
||||
|
||||
// Create temporary file
|
||||
const tempFilePath = path.join(projectRoot, `${key}_temp.txt`);
|
||||
fs.writeFileSync(tempFilePath, processedValue, 'utf8');
|
||||
|
||||
// Use appropriate command based on platform
|
||||
let command;
|
||||
if (process.platform === 'win32') {
|
||||
command = `type "${tempFilePath}" | vercel env add ${key} production`;
|
||||
} else {
|
||||
command = `cat "${tempFilePath}" | vercel env add ${key} production`;
|
||||
}
|
||||
|
||||
execSync(command, {
|
||||
cwd: projectRoot,
|
||||
stdio: 'pipe', // Changed from 'inherit' to avoid interactive prompts
|
||||
shell: true,
|
||||
env: process.env
|
||||
});
|
||||
|
||||
fs.unlinkSync(tempFilePath);
|
||||
console.log(`✅ Set environment variable: ${key}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const tempFilePath = path.join(projectRoot, `${key}_temp.txt`);
|
||||
if (fs.existsSync(tempFilePath)) {
|
||||
fs.unlinkSync(tempFilePath);
|
||||
}
|
||||
console.warn(`⚠️ Warning: Failed to set environment variable ${key}:`, error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function setEnvironmentVariables(vercelClient, projectId, envVars, projectRoot) {
|
||||
console.log('\n📝 Setting up environment variables...');
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const [key, value] of Object.entries(envVars)) {
|
||||
if (!value) continue;
|
||||
|
||||
let success = false;
|
||||
|
||||
// Try SDK approach first if we have a Vercel client
|
||||
if (vercelClient && projectId) {
|
||||
success = await setVercelEnvVarSDK(vercelClient, projectId, key, value);
|
||||
}
|
||||
|
||||
// Fallback to CLI approach
|
||||
if (!success) {
|
||||
success = await setVercelEnvVarCLI(key, value, projectRoot);
|
||||
}
|
||||
|
||||
results.push({ key, success });
|
||||
}
|
||||
|
||||
// Report results
|
||||
const failed = results.filter(r => !r.success);
|
||||
if (failed.length > 0) {
|
||||
console.warn(`\n⚠️ Failed to set ${failed.length} environment variables:`);
|
||||
failed.forEach(r => console.warn(` - ${r.key}`));
|
||||
console.warn('\nYou may need to set these manually in the Vercel dashboard.');
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async function deployToVercel(useGitHub = false) {
|
||||
try {
|
||||
console.log('\n🚀 Deploying to Vercel...');
|
||||
@@ -374,95 +488,113 @@ async function deployToVercel(useGitHub = false) {
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
// TODO: check if project already exists here
|
||||
|
||||
// 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
|
||||
// Load project info
|
||||
const projectJson = JSON.parse(fs.readFileSync('.vercel/project.json', 'utf8'));
|
||||
const projectId = projectJson.projectId;
|
||||
|
||||
// Get project details using project inspect
|
||||
console.log('\n🔍 Getting project details...');
|
||||
const inspectOutput = execSync(`vercel project inspect ${projectId} 2>&1`, {
|
||||
cwd: projectRoot,
|
||||
encoding: 'utf8'
|
||||
});
|
||||
// Get Vercel token and initialize SDK client
|
||||
let vercelClient = null;
|
||||
try {
|
||||
const token = await getVercelToken();
|
||||
if (token) {
|
||||
vercelClient = new Vercel({
|
||||
bearerToken: token
|
||||
});
|
||||
console.log('✅ Initialized Vercel SDK client');
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Could not initialize Vercel SDK, falling back to CLI operations');
|
||||
}
|
||||
|
||||
// Extract project name from inspect output
|
||||
let projectName;
|
||||
// Get project details
|
||||
console.log('\n🔍 Getting project details...');
|
||||
let domain;
|
||||
const nameMatch = inspectOutput.match(/Name\s+([^\n]+)/);
|
||||
if (nameMatch) {
|
||||
projectName = nameMatch[1].trim();
|
||||
domain = `${projectName}.vercel.app`;
|
||||
console.log('🌐 Using project name for domain:', domain);
|
||||
} else {
|
||||
// Try alternative format
|
||||
const altMatch = inspectOutput.match(/Found Project [^/]+\/([^\n]+)/);
|
||||
if (altMatch) {
|
||||
projectName = altMatch[1].trim();
|
||||
let projectName;
|
||||
|
||||
if (vercelClient) {
|
||||
try {
|
||||
const project = await vercelClient.projects.get({
|
||||
idOrName: projectId
|
||||
});
|
||||
projectName = project.name;
|
||||
domain = `${projectName}.vercel.app`;
|
||||
console.log('🌐 Using project name for domain:', domain);
|
||||
} else {
|
||||
throw new Error('Could not determine project name from inspection output');
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Could not get project details via SDK, using CLI fallback');
|
||||
}
|
||||
}
|
||||
|
||||
// Generate frame metadata if we have a seed phrase
|
||||
let frameMetadata;
|
||||
// Fallback to CLI method if SDK failed
|
||||
if (!domain) {
|
||||
const inspectOutput = execSync(`vercel project inspect ${projectId} 2>&1`, {
|
||||
cwd: projectRoot,
|
||||
encoding: 'utf8'
|
||||
});
|
||||
|
||||
const nameMatch = inspectOutput.match(/Name\s+([^\n]+)/);
|
||||
if (nameMatch) {
|
||||
projectName = nameMatch[1].trim();
|
||||
domain = `${projectName}.vercel.app`;
|
||||
console.log('🌐 Using project name for domain:', domain);
|
||||
} else {
|
||||
const altMatch = inspectOutput.match(/Found Project [^/]+\/([^\n]+)/);
|
||||
if (altMatch) {
|
||||
projectName = altMatch[1].trim();
|
||||
domain = `${projectName}.vercel.app`;
|
||||
console.log('🌐 Using project name for domain:', domain);
|
||||
} else {
|
||||
throw new Error('Could not determine project name from inspection output');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate mini app metadata if we have a seed phrase
|
||||
let miniAppMetadata;
|
||||
let fid;
|
||||
if (process.env.SEED_PHRASE) {
|
||||
console.log('\n🔨 Generating frame metadata...');
|
||||
console.log('\n🔨 Generating mini app metadata...');
|
||||
const accountAddress = await validateSeedPhrase(process.env.SEED_PHRASE);
|
||||
fid = await lookupFidByCustodyAddress(accountAddress, process.env.NEYNAR_API_KEY ?? 'FARCASTER_V2_FRAMES_DEMO');
|
||||
|
||||
// Determine webhook URL based on Neynar configuration
|
||||
const webhookUrl = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
||||
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
||||
: `https://${domain}/api/webhook`;
|
||||
|
||||
frameMetadata = await generateFarcasterMetadata(domain, fid, accountAddress, process.env.SEED_PHRASE, webhookUrl);
|
||||
console.log('✅ Frame metadata generated and signed');
|
||||
miniAppMetadata = await generateFarcasterMetadata(domain, fid, accountAddress, process.env.SEED_PHRASE, webhookUrl);
|
||||
console.log('✅ Mini app metadata generated and signed');
|
||||
}
|
||||
|
||||
// Prepare environment variables
|
||||
const nextAuthSecret = process.env.NEXTAUTH_SECRET || crypto.randomBytes(32).toString('hex');
|
||||
const vercelEnv = {
|
||||
// Required vars
|
||||
NEXTAUTH_SECRET: nextAuthSecret,
|
||||
AUTH_SECRET: nextAuthSecret, // Fallback for some NextAuth versions
|
||||
NEXTAUTH_URL: `https://${domain}`, // Add the deployment URL
|
||||
AUTH_SECRET: nextAuthSecret,
|
||||
NEXTAUTH_URL: `https://${domain}`,
|
||||
NEXT_PUBLIC_URL: `https://${domain}`,
|
||||
|
||||
// Optional vars that should be set if they exist
|
||||
...(process.env.NEYNAR_API_KEY && { NEYNAR_API_KEY: process.env.NEYNAR_API_KEY }),
|
||||
...(process.env.NEYNAR_CLIENT_ID && { NEYNAR_CLIENT_ID: process.env.NEYNAR_CLIENT_ID }),
|
||||
...(miniAppMetadata && { MINI_APP_METADATA: miniAppMetadata }),
|
||||
|
||||
// Frame metadata - don't stringify here
|
||||
...(frameMetadata && { FRAME_METADATA: frameMetadata }),
|
||||
|
||||
// Public vars
|
||||
...Object.fromEntries(
|
||||
Object.entries(process.env)
|
||||
.filter(([key]) => key.startsWith('NEXT_PUBLIC_'))
|
||||
)
|
||||
};
|
||||
|
||||
// Add or update env vars in Vercel project
|
||||
console.log('\n📝 Setting up environment variables...');
|
||||
for (const [key, value] of Object.entries(vercelEnv)) {
|
||||
if (value) {
|
||||
await setVercelEnvVar(key, value, projectRoot);
|
||||
}
|
||||
}
|
||||
// Set environment variables
|
||||
await setEnvironmentVariables(vercelClient, projectId, vercelEnv, projectRoot);
|
||||
|
||||
// Deploy the project
|
||||
if (useGitHub) {
|
||||
@@ -482,94 +614,58 @@ async function deployToVercel(useGitHub = false) {
|
||||
stdio: 'inherit',
|
||||
env: process.env
|
||||
});
|
||||
// Verify the actual domain after deployment
|
||||
|
||||
|
||||
// Verify actual domain after deployment
|
||||
console.log('\n🔍 Verifying deployment domain...');
|
||||
|
||||
// Create a temporary file path
|
||||
const tempOutputFile = path.join(projectRoot, 'vercel_output.txt');
|
||||
|
||||
try {
|
||||
// Redirect output to a file
|
||||
execSync(`vercel project ls > "${tempOutputFile}" 2>&1`, {
|
||||
cwd: projectRoot,
|
||||
shell: true
|
||||
});
|
||||
|
||||
// Read the output file
|
||||
const projectOutput = fs.readFileSync(tempOutputFile, 'utf8');
|
||||
|
||||
// Process the output
|
||||
const projectLines = projectOutput
|
||||
.split('\n')
|
||||
.filter(line => line.includes('https://'));
|
||||
|
||||
// Find the line containing our project name
|
||||
const currentProject = projectLines.find(line =>
|
||||
line.includes(projectName)
|
||||
);
|
||||
|
||||
if (currentProject) {
|
||||
// Extract the domain from the line
|
||||
const domainMatch = currentProject.match(/https:\/\/([^\s]+)/);
|
||||
if (domainMatch) {
|
||||
const actualDomain = domainMatch[1];
|
||||
if (actualDomain !== domain) {
|
||||
console.log(`⚠️ Actual domain (${actualDomain}) differs from assumed domain (${domain})`);
|
||||
console.log('🔄 Updating environment variables with correct domain...');
|
||||
|
||||
// Update domain-dependent environment variables
|
||||
const webhookUrl = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
||||
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
||||
: `https://${actualDomain}/api/webhook`;
|
||||
|
||||
if (frameMetadata) {
|
||||
frameMetadata = await generateFarcasterMetadata(actualDomain, fid, await validateSeedPhrase(process.env.SEED_PHRASE), process.env.SEED_PHRASE, webhookUrl);
|
||||
// Update FRAME_METADATA env var using the new function
|
||||
await setVercelEnvVar('FRAME_METADATA', frameMetadata, projectRoot);
|
||||
}
|
||||
|
||||
// Update NEXTAUTH_URL
|
||||
await setVercelEnvVar('NEXTAUTH_URL', `https://${actualDomain}`, projectRoot);
|
||||
|
||||
// Update NEXT_PUBLIC_URL
|
||||
await setVercelEnvVar('NEXT_PUBLIC_URL', `https://${actualDomain}`, projectRoot);
|
||||
|
||||
// Redeploy with updated environment variables
|
||||
console.log('\n📦 Redeploying with correct domain...');
|
||||
execSync('vercel deploy --prod', {
|
||||
cwd: projectRoot,
|
||||
stdio: 'inherit',
|
||||
env: process.env
|
||||
});
|
||||
|
||||
domain = actualDomain;
|
||||
}
|
||||
} else {
|
||||
console.warn('⚠️ Could not extract domain from project line');
|
||||
}
|
||||
} else {
|
||||
console.warn('⚠️ Could not find project in Vercel project list');
|
||||
}
|
||||
|
||||
// Clean up the temporary file
|
||||
fs.unlinkSync(tempOutputFile);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
|
||||
// Try to read the output file even if there was an error
|
||||
let actualDomain = domain;
|
||||
if (vercelClient) {
|
||||
try {
|
||||
if (fs.existsSync(tempOutputFile)) {
|
||||
const errorOutput = fs.readFileSync(tempOutputFile, 'utf8');
|
||||
console.log('Error output file contents:', errorOutput);
|
||||
fs.unlinkSync(tempOutputFile);
|
||||
const deployments = await vercelClient.deployments.list({
|
||||
projectId: projectId,
|
||||
limit: 1
|
||||
});
|
||||
|
||||
if (deployments.deployments?.[0]?.url) {
|
||||
actualDomain = deployments.deployments[0].url;
|
||||
console.log('🌐 Verified actual domain:', actualDomain);
|
||||
}
|
||||
} catch (readError) {
|
||||
console.error('Error reading output file:', readError);
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Could not verify domain via SDK, using assumed domain');
|
||||
}
|
||||
}
|
||||
|
||||
// Update environment variables if domain changed
|
||||
if (actualDomain !== domain) {
|
||||
console.log('🔄 Updating environment variables with correct domain...');
|
||||
|
||||
const webhookUrl = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
||||
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
||||
: `https://${actualDomain}/api/webhook`;
|
||||
|
||||
const updatedEnv = {
|
||||
NEXTAUTH_URL: `https://${actualDomain}`,
|
||||
NEXT_PUBLIC_URL: `https://${actualDomain}`
|
||||
};
|
||||
|
||||
if (miniAppMetadata) {
|
||||
const updatedMetadata = await generateFarcasterMetadata(actualDomain, fid, await validateSeedPhrase(process.env.SEED_PHRASE), process.env.SEED_PHRASE, webhookUrl);
|
||||
updatedEnv.MINI_APP_METADATA = updatedMetadata;
|
||||
}
|
||||
|
||||
await setEnvironmentVariables(vercelClient, projectId, updatedEnv, projectRoot);
|
||||
|
||||
console.log('\n📦 Redeploying with correct domain...');
|
||||
execSync('vercel deploy --prod', {
|
||||
cwd: projectRoot,
|
||||
stdio: 'inherit',
|
||||
env: process.env
|
||||
});
|
||||
|
||||
domain = actualDomain;
|
||||
}
|
||||
|
||||
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');
|
||||
|
||||
@@ -581,19 +677,28 @@ 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 (SDK Edition)');
|
||||
console.log('This script will deploy your mini app to Vercel using the Vercel SDK.');
|
||||
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('3. Configure environment variables in Vercel using SDK');
|
||||
console.log('4. Deploy and build your mini app\n');
|
||||
|
||||
// Check if @vercel/sdk is installed
|
||||
try {
|
||||
await import('@vercel/sdk');
|
||||
} catch (error) {
|
||||
console.log('📦 Installing @vercel/sdk...');
|
||||
execSync('npm install @vercel/sdk', {
|
||||
cwd: projectRoot,
|
||||
stdio: 'inherit'
|
||||
});
|
||||
console.log('✅ @vercel/sdk installed successfully');
|
||||
}
|
||||
|
||||
// Check for required environment variables
|
||||
await checkRequiredEnvVars();
|
||||
|
||||
// Check for git remote
|
||||
const remoteUrl = await getGitRemote();
|
||||
let useGitHub = false;
|
||||
|
||||
@@ -634,20 +739,16 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Check and install Vercel CLI if needed
|
||||
if (!await checkVercelCLI()) {
|
||||
console.log('Vercel CLI not found. Installing...');
|
||||
await installVercelCLI();
|
||||
}
|
||||
|
||||
// Login to Vercel
|
||||
console.log('pre login');
|
||||
if (!await loginToVercel()) {
|
||||
console.error('\n❌ Failed to log in to Vercel. Please try again.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Deploy to Vercel
|
||||
await deployToVercel(useGitHub);
|
||||
|
||||
} catch (error) {
|
||||
@@ -656,5 +757,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
main();
|
||||
@@ -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,15 +75,13 @@ 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);
|
||||
}
|
||||
|
||||
const useTunnel = process.env.USE_TUNNEL === 'true';
|
||||
let frameUrl;
|
||||
let miniAppUrl;
|
||||
|
||||
if (useTunnel) {
|
||||
// Start localtunnel and get URL
|
||||
@@ -95,49 +93,48 @@ async function startDev() {
|
||||
console.error('Error getting IP address:', error);
|
||||
}
|
||||
|
||||
frameUrl = tunnel.url;
|
||||
miniAppUrl = tunnel.url;
|
||||
console.log(`
|
||||
🌐 Local tunnel URL: ${tunnel.url}
|
||||
|
||||
💻 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';
|
||||
miniAppUrl = '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
|
||||
3. Enter this URL: ${frameUrl}
|
||||
4. Click "Preview" to test your frame (note that it may take ~5 seconds to load the first time)
|
||||
💻 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: ${miniAppUrl}
|
||||
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
|
||||
env: { ...process.env, NEXT_PUBLIC_URL: miniAppUrl, NEXTAUTH_URL: miniAppUrl },
|
||||
cwd: projectRoot,
|
||||
shell: process.platform === 'win32' // Add shell option for Windows
|
||||
});
|
||||
|
||||
// Handle cleanup
|
||||
|
||||
46
src/app/api/best-friends/route.ts
Normal file
46
src/app/api/best-friends/route.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const apiKey = process.env.NEYNAR_API_KEY;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const fid = searchParams.get('fid');
|
||||
|
||||
if (!apiKey) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!fid) {
|
||||
return NextResponse.json(
|
||||
{ error: 'FID parameter is required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://api.neynar.com/v2/farcaster/user/best_friends?fid=${fid}&limit=3`,
|
||||
{
|
||||
headers: {
|
||||
"x-api-key": apiKey,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Neynar API error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const { users } = await response.json() as { users: { user: { fid: number; username: string } }[] };
|
||||
|
||||
return NextResponse.json({ bestFriends: users });
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch best friends:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch best friends. Please check your Neynar API key and try again.' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
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-primary">
|
||||
{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,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { notificationDetailsSchema } from "@farcaster/frame-sdk";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { setUserNotificationDetails } from "~/lib/kv";
|
||||
import { sendFrameNotification } from "~/lib/notifs";
|
||||
import { sendNeynarFrameNotification } from "~/lib/neynar";
|
||||
import { sendMiniAppNotification } from "~/lib/notifs";
|
||||
import { sendNeynarMiniAppNotification } from "~/lib/neynar";
|
||||
|
||||
const requestSchema = z.object({
|
||||
fid: z.number(),
|
||||
@@ -34,7 +34,7 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Use appropriate notification function based on Neynar status
|
||||
const sendNotification = neynarEnabled ? sendNeynarFrameNotification : sendFrameNotification;
|
||||
const sendNotification = neynarEnabled ? sendNeynarMiniAppNotification : sendMiniAppNotification;
|
||||
const sendResult = await sendNotification({
|
||||
fid: Number(requestBody.data.fid),
|
||||
title: "Test notification",
|
||||
|
||||
39
src/app/api/users/route.ts
Normal file
39
src/app/api/users/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { NeynarAPIClient } from '@neynar/nodejs-sdk';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const apiKey = process.env.NEYNAR_API_KEY;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const fids = searchParams.get('fids');
|
||||
|
||||
if (!apiKey) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!fids) {
|
||||
return NextResponse.json(
|
||||
{ error: 'FIDs parameter is required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const neynar = new NeynarAPIClient({ apiKey });
|
||||
const fidsArray = fids.split(',').map(fid => parseInt(fid.trim()));
|
||||
|
||||
const { users } = await neynar.fetchBulkUsers({
|
||||
fids: fidsArray,
|
||||
});
|
||||
|
||||
return NextResponse.json({ users });
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch users:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch users. Please check your Neynar API key and try again.' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,12 @@ import {
|
||||
verifyAppKeyWithNeynar,
|
||||
} from "@farcaster/frame-node";
|
||||
import { NextRequest } from "next/server";
|
||||
import { APP_NAME } from "~/lib/constants";
|
||||
import {
|
||||
deleteUserNotificationDetails,
|
||||
setUserNotificationDetails,
|
||||
} from "~/lib/kv";
|
||||
import { sendFrameNotification } from "~/lib/notifs";
|
||||
import { sendMiniAppNotification } from "~/lib/notifs";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
// If Neynar is enabled, we don't need to handle webhooks here
|
||||
@@ -58,10 +59,10 @@ export async function POST(request: NextRequest) {
|
||||
case "frame_added":
|
||||
if (event.notificationDetails) {
|
||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||
await sendFrameNotification({
|
||||
await sendMiniAppNotification({
|
||||
fid,
|
||||
title: "Welcome to Frames v2",
|
||||
body: "Frame is now added to your client",
|
||||
title: `Welcome to ${APP_NAME}`,
|
||||
body: "Mini app is now added to your client",
|
||||
});
|
||||
} else {
|
||||
await deleteUserNotificationDetails(fid);
|
||||
@@ -74,9 +75,9 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
case "notifications_enabled":
|
||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||
await sendFrameNotification({
|
||||
await sendMiniAppNotification({
|
||||
fid,
|
||||
title: "Ding ding ding",
|
||||
title: `Welcome to ${APP_NAME}`,
|
||||
body: "Notifications are now enabled",
|
||||
});
|
||||
break;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
"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"), {
|
||||
const AppComponent = dynamic(() => import("~/components/App"), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
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} />;
|
||||
return <AppComponent title={title} />;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,25 @@
|
||||
/**
|
||||
* DESIGN SYSTEM - DO NOT EDIT UNLESS NECESSARY
|
||||
*
|
||||
* This file contains the centralized design system for the mini app.
|
||||
* These component classes establish the visual consistency across all components.
|
||||
*
|
||||
* ⚠️ AI SHOULD NOT NORMALLY EDIT THIS FILE ⚠️
|
||||
*
|
||||
* Instead of modifying these classes, AI should:
|
||||
* 1. Use existing component classes (e.g., .btn, .card, .input)
|
||||
* 2. Use Tailwind utilities for one-off styling
|
||||
* 3. Create new React components rather than new CSS classes
|
||||
* 4. Only edit this file for specific bug fixes or accessibility improvements
|
||||
*
|
||||
* When AI needs to style something:
|
||||
* ✅ Good: <button className="btn btn-primary">Click me</button>
|
||||
* ✅ Good: <div className="bg-primary text-white px-4 py-2 rounded">Custom</div>
|
||||
* ❌ Bad: Adding new CSS classes here for component-specific styling
|
||||
*
|
||||
* This design system is intentionally minimal to prevent bloat and maintain consistency.
|
||||
*/
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -34,3 +56,63 @@ body {
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
/* Global container styles for consistent layout */
|
||||
.container {
|
||||
@apply mx-auto max-w-md px-4;
|
||||
}
|
||||
|
||||
.container-wide {
|
||||
@apply mx-auto max-w-lg px-4;
|
||||
}
|
||||
|
||||
.container-narrow {
|
||||
@apply mx-auto max-w-sm px-4;
|
||||
}
|
||||
|
||||
/* Global card styles */
|
||||
.card {
|
||||
@apply bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm;
|
||||
}
|
||||
|
||||
.card-primary {
|
||||
@apply bg-primary/10 border-primary/20;
|
||||
}
|
||||
|
||||
/* Global button styles */
|
||||
.btn {
|
||||
@apply inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
@apply bg-primary text-white hover:bg-primary-dark focus:ring-primary;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply bg-secondary text-gray-900 hover:bg-gray-200 focus:ring-gray-500 dark:bg-secondary-dark dark:text-gray-100 dark:hover:bg-gray-600;
|
||||
}
|
||||
|
||||
.btn-outline {
|
||||
@apply border border-gray-300 bg-transparent hover:bg-gray-50 focus:ring-gray-500 dark:border-gray-600 dark:hover:bg-gray-800;
|
||||
}
|
||||
|
||||
/* Global input styles */
|
||||
.input {
|
||||
@apply block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 placeholder-gray-500 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder-gray-400;
|
||||
}
|
||||
|
||||
/* Global loading spinner */
|
||||
.spinner {
|
||||
@apply animate-spin rounded-full border-2 border-gray-300 border-t-primary;
|
||||
}
|
||||
|
||||
.spinner-primary {
|
||||
@apply animate-spin rounded-full border-2 border-white border-t-transparent;
|
||||
}
|
||||
|
||||
/* Global focus styles */
|
||||
.focus-ring {
|
||||
@apply focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 { getMiniAppEmbedMetadata } 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(getMiniAppEmbedMetadata()),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"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";
|
||||
import { ANALYTICS_ENABLED } from "~/lib/constants";
|
||||
|
||||
const WagmiProvider = dynamic(
|
||||
() => import("~/components/providers/WagmiProvider"),
|
||||
@@ -13,12 +15,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={ANALYTICS_ENABLED} backButtonEnabled={true}>
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
{children}
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</MiniAppProvider>
|
||||
</WagmiProvider>
|
||||
</SessionProvider>
|
||||
);
|
||||
|
||||
34
src/app/share/[fid]/page.tsx
Normal file
34
src/app/share/[fid]/page.tsx
Normal 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 { getMiniAppEmbedMetadata } 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(getMiniAppEmbedMetadata(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;
|
||||
}
|
||||
}
|
||||
|
||||
123
src/components/App.tsx
Normal file
123
src/components/App.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
import { Header } from "~/components/ui/Header";
|
||||
import { Footer } from "~/components/ui/Footer";
|
||||
import { HomeTab, ActionsTab, ContextTab, WalletTab } from "~/components/ui/tabs";
|
||||
import { USE_WALLET } from "~/lib/constants";
|
||||
import { useNeynarUser } from "../hooks/useNeynarUser";
|
||||
|
||||
// --- Types ---
|
||||
export enum Tab {
|
||||
Home = "home",
|
||||
Actions = "actions",
|
||||
Context = "context",
|
||||
Wallet = "wallet",
|
||||
}
|
||||
|
||||
export interface AppProps {
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* App component serves as the main container for the mini app interface.
|
||||
*
|
||||
* This component orchestrates the overall mini app experience by:
|
||||
* - Managing tab navigation and state
|
||||
* - Handling Farcaster mini app initialization
|
||||
* - Coordinating wallet and context state
|
||||
* - Providing error handling and loading states
|
||||
* - Rendering the appropriate tab content based on user selection
|
||||
*
|
||||
* The component integrates with the Neynar SDK for Farcaster functionality
|
||||
* and Wagmi for wallet management. It provides a complete mini app
|
||||
* experience with multiple tabs for different functionality areas.
|
||||
*
|
||||
* Features:
|
||||
* - Tab-based navigation (Home, Actions, Context, Wallet)
|
||||
* - Farcaster mini app integration
|
||||
* - Wallet connection management
|
||||
* - Error handling and display
|
||||
* - Loading states for async operations
|
||||
*
|
||||
* @param props - Component props
|
||||
* @param props.title - Optional title for the mini app (defaults to "Neynar Starter Kit")
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <App title="My Mini App" />
|
||||
* ```
|
||||
*/
|
||||
export default function App(
|
||||
{ title }: AppProps = { title: "Neynar Starter Kit" }
|
||||
) {
|
||||
// --- Hooks ---
|
||||
const {
|
||||
isSDKLoaded,
|
||||
context,
|
||||
setInitialTab,
|
||||
setActiveTab,
|
||||
currentTab,
|
||||
} = useMiniApp();
|
||||
|
||||
// --- Neynar user hook ---
|
||||
const { user: neynarUser } = useNeynarUser(context || undefined);
|
||||
|
||||
// --- Effects ---
|
||||
/**
|
||||
* Sets the initial tab to "home" when the SDK is loaded.
|
||||
*
|
||||
* This effect ensures that users start on the home tab when they first
|
||||
* load the mini app. It only runs when the SDK is fully loaded to
|
||||
* prevent errors during initialization.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (isSDKLoaded) {
|
||||
setInitialTab(Tab.Home);
|
||||
}
|
||||
}, [isSDKLoaded, setInitialTab]);
|
||||
|
||||
// --- Early Returns ---
|
||||
if (!isSDKLoaded) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen">
|
||||
<div className="text-center">
|
||||
<div className="spinner h-8 w-8 mx-auto mb-4"></div>
|
||||
<p>Loading SDK...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
paddingTop: context?.client.safeAreaInsets?.top ?? 0,
|
||||
paddingBottom: context?.client.safeAreaInsets?.bottom ?? 0,
|
||||
paddingLeft: context?.client.safeAreaInsets?.left ?? 0,
|
||||
paddingRight: context?.client.safeAreaInsets?.right ?? 0,
|
||||
}}
|
||||
>
|
||||
{/* Header should be full width */}
|
||||
<Header neynarUser={neynarUser} />
|
||||
|
||||
{/* Main content and footer should be centered */}
|
||||
<div className="container py-2 pb-20">
|
||||
{/* Main title */}
|
||||
<h1 className="text-2xl font-bold text-center mb-4">{title}</h1>
|
||||
|
||||
{/* Tab content rendering */}
|
||||
{currentTab === Tab.Home && <HomeTab />}
|
||||
{currentTab === Tab.Actions && <ActionsTab />}
|
||||
{currentTab === Tab.Context && <ContextTab />}
|
||||
{currentTab === Tab.Wallet && <WalletTab />}
|
||||
|
||||
{/* Footer with navigation */}
|
||||
<Footer activeTab={currentTab as Tab} setActiveTab={setActiveTab} showWallet={USE_WALLET} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,626 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { signIn, signOut, getCsrfToken } from "next-auth/react";
|
||||
import sdk, {
|
||||
SignIn as SignInCore,
|
||||
} from "@farcaster/frame-sdk";
|
||||
import {
|
||||
useAccount,
|
||||
useSendTransaction,
|
||||
useSignMessage,
|
||||
useSignTypedData,
|
||||
useWaitForTransactionReceipt,
|
||||
useDisconnect,
|
||||
useConnect,
|
||||
useSwitchChain,
|
||||
useChainId,
|
||||
} from "wagmi";
|
||||
|
||||
import { config } from "~/components/providers/WagmiProvider";
|
||||
import { Button } from "~/components/ui/Button";
|
||||
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 { Label } from "~/components/ui/label";
|
||||
import { useFrame } from "~/components/providers/FrameProvider";
|
||||
|
||||
export default function Demo(
|
||||
{ title }: { title?: string } = { title: "Frames v2 Demo" }
|
||||
) {
|
||||
const { isSDKLoaded, context, added, notificationDetails, lastEvent, addFrame, addFrameResult } = useFrame();
|
||||
const [isContextOpen, setIsContextOpen] = useState(false);
|
||||
const [txHash, setTxHash] = useState<string | null>(null);
|
||||
|
||||
const [sendNotificationResult, setSendNotificationResult] = useState("");
|
||||
|
||||
const { address, isConnected } = useAccount();
|
||||
const chainId = useChainId();
|
||||
|
||||
const {
|
||||
sendTransaction,
|
||||
error: sendTxError,
|
||||
isError: isSendTxError,
|
||||
isPending: isSendTxPending,
|
||||
} = useSendTransaction();
|
||||
|
||||
const { isLoading: isConfirming, isSuccess: isConfirmed } =
|
||||
useWaitForTransactionReceipt({
|
||||
hash: txHash as `0x${string}`,
|
||||
});
|
||||
|
||||
const {
|
||||
signTypedData,
|
||||
error: signTypedError,
|
||||
isError: isSignTypedError,
|
||||
isPending: isSignTypedPending,
|
||||
} = useSignTypedData();
|
||||
|
||||
const { disconnect } = useDisconnect();
|
||||
const { connect } = useConnect();
|
||||
|
||||
const {
|
||||
switchChain,
|
||||
error: switchChainError,
|
||||
isError: isSwitchChainError,
|
||||
isPending: isSwitchChainPending,
|
||||
} = useSwitchChain();
|
||||
|
||||
const nextChain = useMemo(() => {
|
||||
if (chainId === base.id) {
|
||||
return optimism;
|
||||
} else if (chainId === optimism.id) {
|
||||
return degen;
|
||||
} else if (chainId === degen.id) {
|
||||
return mainnet;
|
||||
} else if (chainId === mainnet.id) {
|
||||
return unichain;
|
||||
} else {
|
||||
return base;
|
||||
}
|
||||
}, [chainId]);
|
||||
|
||||
const handleSwitchChain = useCallback(() => {
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/send-notification", {
|
||||
method: "POST",
|
||||
mode: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
fid: context.user.fid,
|
||||
notificationDetails,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.status === 200) {
|
||||
setSendNotificationResult("Success");
|
||||
return;
|
||||
} else if (response.status === 429) {
|
||||
setSendNotificationResult("Rate limited");
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await response.text();
|
||||
setSendNotificationResult(`Error: ${data}`);
|
||||
} catch (error) {
|
||||
setSendNotificationResult(`Error: ${error}`);
|
||||
}
|
||||
}, [context, notificationDetails]);
|
||||
|
||||
const sendTx = useCallback(() => {
|
||||
sendTransaction(
|
||||
{
|
||||
// call yoink() on Yoink contract
|
||||
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
|
||||
data: "0x9846cd9efc000023c0",
|
||||
},
|
||||
{
|
||||
onSuccess: (hash) => {
|
||||
setTxHash(hash);
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [sendTransaction]);
|
||||
|
||||
const signTyped = useCallback(() => {
|
||||
signTypedData({
|
||||
domain: {
|
||||
name: "Frames v2 Demo",
|
||||
version: "1",
|
||||
chainId,
|
||||
},
|
||||
types: {
|
||||
Message: [{ name: "content", type: "string" }],
|
||||
},
|
||||
message: {
|
||||
content: "Hello from Frames v2!",
|
||||
},
|
||||
primaryType: "Message",
|
||||
});
|
||||
}, [chainId, signTypedData]);
|
||||
|
||||
const toggleContext = useCallback(() => {
|
||||
setIsContextOpen((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
if (!isSDKLoaded) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
paddingTop: context?.client.safeAreaInsets?.top ?? 0,
|
||||
paddingBottom: context?.client.safeAreaInsets?.bottom ?? 0,
|
||||
paddingLeft: context?.client.safeAreaInsets?.left ?? 0,
|
||||
paddingRight: context?.client.safeAreaInsets?.right ?? 0,
|
||||
}}
|
||||
>
|
||||
<div className="w-[300px] mx-auto py-2 px-2">
|
||||
<h1 className="text-2xl font-bold text-center mb-4">{title}</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<h2 className="font-2xl font-bold">Context</h2>
|
||||
<button
|
||||
onClick={toggleContext}
|
||||
className="flex items-center gap-2 transition-colors"
|
||||
>
|
||||
<span
|
||||
className={`transform transition-transform ${
|
||||
isContextOpen ? "rotate-90" : ""
|
||||
}`}
|
||||
>
|
||||
➤
|
||||
</span>
|
||||
Tap to expand
|
||||
</button>
|
||||
|
||||
{isContextOpen && (
|
||||
<div className="p-4 mt-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
||||
{JSON.stringify(context, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="font-2xl font-bold">Actions</h2>
|
||||
|
||||
<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.signIn
|
||||
</pre>
|
||||
</div>
|
||||
<SignIn />
|
||||
</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={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>
|
||||
</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.viewProfile
|
||||
</pre>
|
||||
</div>
|
||||
<ViewProfile />
|
||||
</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.close
|
||||
</pre>
|
||||
</div>
|
||||
<Button onClick={close}>Close Frame</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<h2 className="font-2xl font-bold">Last event</h2>
|
||||
|
||||
<div className="p-4 mt-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
||||
{lastEvent || "none"}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="font-2xl font-bold">Add to client & notifications</h2>
|
||||
|
||||
<div className="mt-2 mb-4 text-sm">
|
||||
Client fid {context?.client.clientFid},
|
||||
{added ? " frame added to client," : " frame not added to client,"}
|
||||
{notificationDetails
|
||||
? " notifications enabled"
|
||||
: " notifications disabled"}
|
||||
</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.addFrame
|
||||
</pre>
|
||||
</div>
|
||||
{addFrameResult && (
|
||||
<div className="mb-2 text-sm">
|
||||
Add frame result: {addFrameResult}
|
||||
</div>
|
||||
)}
|
||||
<Button onClick={addFrame} disabled={added}>
|
||||
Add frame to client
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{sendNotificationResult && (
|
||||
<div className="mb-2 text-sm">
|
||||
Send notification result: {sendNotificationResult}
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-4">
|
||||
<Button onClick={sendNotification} disabled={!notificationDetails}>
|
||||
Send notification
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="font-2xl font-bold">Wallet</h2>
|
||||
|
||||
{address && (
|
||||
<div className="my-2 text-xs">
|
||||
Address: <pre className="inline">{truncateAddress(address)}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{chainId && (
|
||||
<div className="my-2 text-xs">
|
||||
Chain ID: <pre className="inline">{chainId}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-4">
|
||||
<Button
|
||||
onClick={() =>
|
||||
isConnected
|
||||
? disconnect()
|
||||
: connect({ connector: config.connectors[0] })
|
||||
}
|
||||
>
|
||||
{isConnected ? "Disconnect" : "Connect"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<SignMessage />
|
||||
</div>
|
||||
|
||||
{isConnected && (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<SendEth />
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<Button
|
||||
onClick={sendTx}
|
||||
disabled={!isConnected || isSendTxPending}
|
||||
isLoading={isSendTxPending}
|
||||
>
|
||||
Send Transaction (contract)
|
||||
</Button>
|
||||
{isSendTxError && renderError(sendTxError)}
|
||||
{txHash && (
|
||||
<div className="mt-2 text-xs">
|
||||
<div>Hash: {truncateAddress(txHash)}</div>
|
||||
<div>
|
||||
Status:{" "}
|
||||
{isConfirming
|
||||
? "Confirming..."
|
||||
: isConfirmed
|
||||
? "Confirmed!"
|
||||
: "Pending"}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<Button
|
||||
onClick={signTyped}
|
||||
disabled={!isConnected || isSignTypedPending}
|
||||
isLoading={isSignTypedPending}
|
||||
>
|
||||
Sign Typed Data
|
||||
</Button>
|
||||
{isSignTypedError && renderError(signTypedError)}
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<Button
|
||||
onClick={handleSwitchChain}
|
||||
disabled={isSwitchChainPending}
|
||||
isLoading={isSwitchChainPending}
|
||||
>
|
||||
Switch to {nextChain.name}
|
||||
</Button>
|
||||
{isSwitchChainError && renderError(switchChainError)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SignMessage() {
|
||||
const { isConnected } = useAccount();
|
||||
const { connectAsync } = useConnect();
|
||||
const {
|
||||
signMessage,
|
||||
data: signature,
|
||||
error: signError,
|
||||
isError: isSignError,
|
||||
isPending: isSignPending,
|
||||
} = useSignMessage();
|
||||
|
||||
const handleSignMessage = useCallback(async () => {
|
||||
if (!isConnected) {
|
||||
await connectAsync({
|
||||
chainId: base.id,
|
||||
connector: config.connectors[0],
|
||||
});
|
||||
}
|
||||
|
||||
signMessage({ message: "Hello from Frames v2!" });
|
||||
}, [connectAsync, isConnected, signMessage]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={handleSignMessage}
|
||||
disabled={isSignPending}
|
||||
isLoading={isSignPending}
|
||||
>
|
||||
Sign Message
|
||||
</Button>
|
||||
{isSignError && renderError(signError)}
|
||||
{signature && (
|
||||
<div className="mt-2 text-xs">
|
||||
<div>Signature: {signature}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SendEth() {
|
||||
const { isConnected, chainId } = useAccount();
|
||||
const {
|
||||
sendTransaction,
|
||||
data,
|
||||
error: sendTxError,
|
||||
isError: isSendTxError,
|
||||
isPending: isSendTxPending,
|
||||
} = useSendTransaction();
|
||||
|
||||
const { isLoading: isConfirming, isSuccess: isConfirmed } =
|
||||
useWaitForTransactionReceipt({
|
||||
hash: data,
|
||||
});
|
||||
|
||||
const toAddr = useMemo(() => {
|
||||
// Protocol guild address
|
||||
return chainId === base.id
|
||||
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
|
||||
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
|
||||
}, [chainId]);
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
sendTransaction({
|
||||
to: toAddr,
|
||||
value: 1n,
|
||||
});
|
||||
}, [toAddr, sendTransaction]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
disabled={!isConnected || isSendTxPending}
|
||||
isLoading={isSendTxPending}
|
||||
>
|
||||
Send Transaction (eth)
|
||||
</Button>
|
||||
{isSendTxError && renderError(sendTxError)}
|
||||
{data && (
|
||||
<div className="mt-2 text-xs">
|
||||
<div>Hash: {truncateAddress(data)}</div>
|
||||
<div>
|
||||
Status:{" "}
|
||||
{isConfirming
|
||||
? "Confirming..."
|
||||
: isConfirmed
|
||||
? "Confirmed!"
|
||||
: "Pending"}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SignIn() {
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
const [signInResult, setSignInResult] = useState<SignInCore.SignInResult>();
|
||||
const [signInFailure, setSignInFailure] = useState<string>();
|
||||
const { data: session, status } = useSession();
|
||||
|
||||
const getNonce = useCallback(async () => {
|
||||
const nonce = await getCsrfToken();
|
||||
if (!nonce) throw new Error("Unable to generate nonce");
|
||||
return nonce;
|
||||
}, []);
|
||||
|
||||
const handleSignIn = useCallback(async () => {
|
||||
try {
|
||||
setSigningIn(true);
|
||||
setSignInFailure(undefined);
|
||||
const nonce = await getNonce();
|
||||
const result = await sdk.actions.signIn({ nonce });
|
||||
setSignInResult(result);
|
||||
|
||||
await signIn("credentials", {
|
||||
message: result.message,
|
||||
signature: result.signature,
|
||||
redirect: false,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof SignInCore.RejectedByUser) {
|
||||
setSignInFailure("Rejected by user");
|
||||
return;
|
||||
}
|
||||
|
||||
setSignInFailure("Unknown error");
|
||||
} finally {
|
||||
setSigningIn(false);
|
||||
}
|
||||
}, [getNonce]);
|
||||
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setSigningOut(true);
|
||||
await signOut({ redirect: false });
|
||||
setSignInResult(undefined);
|
||||
} finally {
|
||||
setSigningOut(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{status !== "authenticated" && (
|
||||
<Button onClick={handleSignIn} disabled={signingIn}>
|
||||
Sign In with Farcaster
|
||||
</Button>
|
||||
)}
|
||||
{status === "authenticated" && (
|
||||
<Button onClick={handleSignOut} disabled={signingOut}>
|
||||
Sign out
|
||||
</Button>
|
||||
)}
|
||||
{session && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">Session</div>
|
||||
<div className="whitespace-pre">
|
||||
{JSON.stringify(session, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{signInFailure && !signingIn && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre">{signInFailure}</div>
|
||||
</div>
|
||||
)}
|
||||
{signInResult && !signingIn && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre">
|
||||
{JSON.stringify(signInResult, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ViewProfile() {
|
||||
const [fid, setFid] = useState("3");
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<Label
|
||||
className="text-xs font-semibold text-gray-500 mb-1"
|
||||
htmlFor="view-profile-fid"
|
||||
>
|
||||
Fid
|
||||
</Label>
|
||||
<Input
|
||||
id="view-profile-fid"
|
||||
type="number"
|
||||
value={fid}
|
||||
className="mb-2"
|
||||
onChange={(e) => {
|
||||
setFid(e.target.value);
|
||||
}}
|
||||
step="1"
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
sdk.actions.viewProfile({ fid: parseInt(fid) });
|
||||
}}
|
||||
>
|
||||
View Profile
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const renderError = (error: Error | null) => {
|
||||
if (!error) return null;
|
||||
if (error instanceof BaseError) {
|
||||
const isUserRejection = error.walk(
|
||||
(e) => e instanceof UserRejectedRequestError
|
||||
);
|
||||
|
||||
if (isUserRejection) {
|
||||
return <div className="text-red-500 text-xs mt-1">Rejected by user.</div>;
|
||||
}
|
||||
}
|
||||
|
||||
return <div className="text-red-500 text-xs mt-1">{error.message}</div>;
|
||||
};
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,50 @@
|
||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
children: React.ReactNode;
|
||||
isLoading?: boolean;
|
||||
variant?: 'primary' | 'secondary' | 'outline';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
}
|
||||
|
||||
export function Button({ children, className = "", isLoading = false, ...props }: ButtonProps) {
|
||||
export function Button({
|
||||
children,
|
||||
className = "",
|
||||
isLoading = false,
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const baseClasses = "btn";
|
||||
|
||||
const variantClasses = {
|
||||
primary: "btn-primary",
|
||||
secondary: "btn-secondary",
|
||||
outline: "btn-outline"
|
||||
};
|
||||
|
||||
const sizeClasses = {
|
||||
sm: "px-3 py-1.5 text-xs",
|
||||
md: "px-4 py-2 text-sm",
|
||||
lg: "px-6 py-3 text-base"
|
||||
};
|
||||
|
||||
const fullWidthClasses = "w-full max-w-xs mx-auto block";
|
||||
|
||||
const combinedClasses = [
|
||||
baseClasses,
|
||||
variantClasses[variant],
|
||||
sizeClasses[size],
|
||||
fullWidthClasses,
|
||||
className
|
||||
].join(' ');
|
||||
|
||||
return (
|
||||
<button
|
||||
className={`w-full max-w-xs mx-auto block bg-[#7C65C1] text-white py-3 px-6 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-[#7C65C1] hover:bg-[#6952A3] ${className}`}
|
||||
className={combinedClasses}
|
||||
{...props}
|
||||
>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="animate-spin h-5 w-5 border-2 border-white border-t-transparent rounded-full" />
|
||||
<div className="spinner-primary h-5 w-5" />
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
|
||||
53
src/components/ui/Footer.tsx
Normal file
53
src/components/ui/Footer.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import React from "react";
|
||||
import { Tab } from "~/components/App";
|
||||
|
||||
interface FooterProps {
|
||||
activeTab: Tab;
|
||||
setActiveTab: (tab: Tab) => void;
|
||||
showWallet?: boolean;
|
||||
}
|
||||
|
||||
export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWallet = false }) => (
|
||||
<div className="fixed bottom-0 left-0 right-0 mx-4 mb-4 bg-gray-100 dark:bg-gray-800 border-[3px] border-double border-primary px-2 py-2 rounded-lg z-50">
|
||||
<div className="flex justify-around items-center h-14">
|
||||
<button
|
||||
onClick={() => setActiveTab(Tab.Home)}
|
||||
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||
activeTab === Tab.Home ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl">🏠</span>
|
||||
<span className="text-xs mt-1">Home</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab(Tab.Actions)}
|
||||
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||
activeTab === Tab.Actions ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl">⚡</span>
|
||||
<span className="text-xs mt-1">Actions</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab(Tab.Context)}
|
||||
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||
activeTab === Tab.Context ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl">📋</span>
|
||||
<span className="text-xs mt-1">Context</span>
|
||||
</button>
|
||||
{showWallet && (
|
||||
<button
|
||||
onClick={() => setActiveTab(Tab.Wallet)}
|
||||
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||
activeTab === Tab.Wallet ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl">👛</span>
|
||||
<span className="text-xs mt-1">Wallet</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
77
src/components/ui/Header.tsx
Normal file
77
src/components/ui/Header.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { APP_NAME } from "~/lib/constants";
|
||||
import sdk from "@farcaster/frame-sdk";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
|
||||
type HeaderProps = {
|
||||
neynarUser?: {
|
||||
fid: number;
|
||||
score: number;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export function Header({ neynarUser }: HeaderProps) {
|
||||
const { context } = useMiniApp();
|
||||
const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div
|
||||
className="mt-4 mb-4 mx-4 px-2 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-between border-[3px] border-double border-primary"
|
||||
>
|
||||
<div className="text-lg font-light">
|
||||
Welcome to {APP_NAME}!
|
||||
</div>
|
||||
{context?.user && (
|
||||
<div
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
setIsUserDropdownOpen(!isUserDropdownOpen);
|
||||
}}
|
||||
>
|
||||
{context.user.pfpUrl && (
|
||||
<img
|
||||
src={context.user.pfpUrl}
|
||||
alt="Profile"
|
||||
className="w-10 h-10 rounded-full border-2 border-primary"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{context?.user && (
|
||||
<>
|
||||
{isUserDropdownOpen && (
|
||||
<div className="absolute top-full right-0 z-50 w-fit mt-1 mx-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="p-3 space-y-2">
|
||||
<div className="text-right">
|
||||
<h3
|
||||
className="font-bold text-sm hover:underline cursor-pointer inline-block"
|
||||
onClick={() => sdk.actions.viewProfile({ fid: context.user.fid })}
|
||||
>
|
||||
{context.user.displayName || context.user.username}
|
||||
</h3>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400">
|
||||
@{context.user.username}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||
FID: {context.user.fid}
|
||||
</p>
|
||||
{neynarUser && (
|
||||
<>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||
Neynar Score: {neynarUser.score}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
118
src/components/ui/Share.tsx
Normal file
118
src/components/ui/Share.tsx
Normal file
@@ -0,0 +1,118 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState, useEffect } from 'react';
|
||||
import { Button } from './Button';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { type ComposeCast } from "@farcaster/frame-sdk";
|
||||
|
||||
interface EmbedConfig {
|
||||
path?: string;
|
||||
url?: string;
|
||||
imageUrl?: () => Promise<string>;
|
||||
}
|
||||
|
||||
interface CastConfig extends Omit<ComposeCast.Options, 'embeds'> {
|
||||
bestFriends?: boolean;
|
||||
embeds?: (string | EmbedConfig)[];
|
||||
}
|
||||
|
||||
interface ShareButtonProps {
|
||||
buttonText: string;
|
||||
cast: CastConfig;
|
||||
className?: string;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function ShareButton({ buttonText, cast, className = '', isLoading = false }: ShareButtonProps) {
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [bestFriends, setBestFriends] = useState<{ fid: number; username: string; }[] | null>(null);
|
||||
const [isLoadingBestFriends, setIsLoadingBestFriends] = useState(false);
|
||||
const { context, actions } = useMiniApp();
|
||||
|
||||
// Fetch best friends if needed
|
||||
useEffect(() => {
|
||||
if (cast.bestFriends && context?.user?.fid) {
|
||||
setIsLoadingBestFriends(true);
|
||||
fetch(`/api/best-friends?fid=${context.user.fid}`)
|
||||
.then(res => res.json())
|
||||
.then(data => setBestFriends(data.bestFriends))
|
||||
.catch(err => console.error('Failed to fetch best friends:', err))
|
||||
.finally(() => setIsLoadingBestFriends(false));
|
||||
}
|
||||
}, [cast.bestFriends, context?.user?.fid]);
|
||||
|
||||
const handleShare = useCallback(async () => {
|
||||
try {
|
||||
setIsProcessing(true);
|
||||
|
||||
let finalText = cast.text || '';
|
||||
|
||||
// Process best friends if enabled and data is loaded
|
||||
if (cast.bestFriends) {
|
||||
if (bestFriends) {
|
||||
// Replace @N with usernames, or remove if no matching friend
|
||||
finalText = finalText.replace(/@\d+/g, (match) => {
|
||||
const friendIndex = parseInt(match.slice(1)) - 1;
|
||||
const friend = bestFriends[friendIndex];
|
||||
if (friend) {
|
||||
return `@${friend.username}`;
|
||||
}
|
||||
return ''; // Remove @N if no matching friend
|
||||
});
|
||||
} else {
|
||||
// If bestFriends is not loaded but bestFriends is enabled, remove @N patterns
|
||||
finalText = finalText.replace(/@\d+/g, '');
|
||||
}
|
||||
}
|
||||
|
||||
// Process embeds
|
||||
const processedEmbeds = await Promise.all(
|
||||
(cast.embeds || []).map(async (embed) => {
|
||||
if (typeof embed === 'string') {
|
||||
return embed;
|
||||
}
|
||||
if (embed.path) {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_URL || window.location.origin;
|
||||
const url = new URL(`${baseUrl}${embed.path}`);
|
||||
|
||||
// Add UTM parameters
|
||||
url.searchParams.set('utm_source', `share-cast-${context?.user?.fid || 'unknown'}`);
|
||||
|
||||
// If custom image generator is provided, use it
|
||||
if (embed.imageUrl) {
|
||||
const imageUrl = await embed.imageUrl();
|
||||
url.searchParams.set('share_image_url', imageUrl);
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
return embed.url || '';
|
||||
})
|
||||
);
|
||||
|
||||
// Open cast composer with all supported intents
|
||||
await actions.composeCast({
|
||||
text: finalText,
|
||||
embeds: processedEmbeds as [string] | [string, string] | undefined,
|
||||
parent: cast.parent,
|
||||
channelKey: cast.channelKey,
|
||||
close: cast.close,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to share:', error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
}, [cast, bestFriends, context?.user?.fid, actions]);
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={handleShare}
|
||||
className={className}
|
||||
isLoading={isLoading || isProcessing}
|
||||
disabled={isLoadingBestFriends}
|
||||
>
|
||||
{buttonText}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
182
src/components/ui/tabs/ActionsTab.tsx
Normal file
182
src/components/ui/tabs/ActionsTab.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
import { ShareButton } from "../Share";
|
||||
import { Button } from "../Button";
|
||||
import { SignIn } from "../wallet/SignIn";
|
||||
import { type Haptics } from "@farcaster/frame-sdk";
|
||||
|
||||
/**
|
||||
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
|
||||
*
|
||||
* This component provides the main interaction interface for users to:
|
||||
* - Share the mini app with others
|
||||
* - Sign in with Farcaster
|
||||
* - Send notifications to their account
|
||||
* - Trigger haptic feedback
|
||||
* - Add the mini app to their client
|
||||
* - Copy share URLs
|
||||
*
|
||||
* The component uses the useMiniApp hook to access Farcaster context and actions.
|
||||
* All state is managed locally within this component.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <ActionsTab />
|
||||
* ```
|
||||
*/
|
||||
export function ActionsTab() {
|
||||
// --- Hooks ---
|
||||
const {
|
||||
actions,
|
||||
added,
|
||||
notificationDetails,
|
||||
haptics,
|
||||
context,
|
||||
} = useMiniApp();
|
||||
|
||||
// --- State ---
|
||||
const [notificationState, setNotificationState] = useState({
|
||||
sendStatus: "",
|
||||
shareUrlCopied: false,
|
||||
});
|
||||
const [selectedHapticIntensity, setSelectedHapticIntensity] = useState<Haptics.ImpactOccurredType>('medium');
|
||||
|
||||
// --- Handlers ---
|
||||
/**
|
||||
* Sends a notification to the current user's Farcaster account.
|
||||
*
|
||||
* This function makes a POST request to the /api/send-notification endpoint
|
||||
* with the user's FID and notification details. It handles different response
|
||||
* statuses including success (200), rate limiting (429), and errors.
|
||||
*
|
||||
* @returns Promise that resolves when the notification is sent or fails
|
||||
*/
|
||||
const sendFarcasterNotification = useCallback(async () => {
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: "" }));
|
||||
if (!notificationDetails || !context) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch("/api/send-notification", {
|
||||
method: "POST",
|
||||
mode: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
fid: context.user.fid,
|
||||
notificationDetails,
|
||||
}),
|
||||
});
|
||||
if (response.status === 200) {
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: "Success" }));
|
||||
return;
|
||||
} else if (response.status === 429) {
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: "Rate limited" }));
|
||||
return;
|
||||
}
|
||||
const responseText = await response.text();
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: `Error: ${responseText}` }));
|
||||
} catch (error) {
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: `Error: ${error}` }));
|
||||
}
|
||||
}, [context, notificationDetails]);
|
||||
|
||||
/**
|
||||
* Copies the share URL for the current user to the clipboard.
|
||||
*
|
||||
* This function generates a share URL using the user's FID and copies it
|
||||
* to the clipboard. It shows a temporary "Copied!" message for 2 seconds.
|
||||
*/
|
||||
const copyUserShareUrl = useCallback(async () => {
|
||||
if (context?.user?.fid) {
|
||||
const userShareUrl = `${process.env.NEXT_PUBLIC_URL}/share/${context.user.fid}`;
|
||||
await navigator.clipboard.writeText(userShareUrl);
|
||||
setNotificationState((prev) => ({ ...prev, shareUrlCopied: true }));
|
||||
setTimeout(() => setNotificationState((prev) => ({ ...prev, shareUrlCopied: false })), 2000);
|
||||
}
|
||||
}, [context?.user?.fid]);
|
||||
|
||||
/**
|
||||
* Triggers haptic feedback with the selected intensity.
|
||||
*
|
||||
* This function calls the haptics.impactOccurred method with the current
|
||||
* selectedHapticIntensity setting. It handles errors gracefully by logging them.
|
||||
*/
|
||||
const triggerHapticFeedback = useCallback(async () => {
|
||||
try {
|
||||
await haptics.impactOccurred(selectedHapticIntensity);
|
||||
} catch (error) {
|
||||
console.error('Haptic feedback failed:', error);
|
||||
}
|
||||
}, [haptics, selectedHapticIntensity]);
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
|
||||
{/* Share functionality */}
|
||||
<ShareButton
|
||||
buttonText="Share Mini App"
|
||||
cast={{
|
||||
text: "Check out this awesome frame @1 @2 @3! 🚀🪐",
|
||||
bestFriends: true,
|
||||
embeds: [`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`]
|
||||
}}
|
||||
className="w-full"
|
||||
/>
|
||||
|
||||
{/* Authentication */}
|
||||
<SignIn />
|
||||
|
||||
{/* Mini app actions */}
|
||||
<Button onClick={() => actions.openUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")} className="w-full">Open Link</Button>
|
||||
|
||||
<Button onClick={actions.addMiniApp} disabled={added} className="w-full">
|
||||
Add Mini App to Client
|
||||
</Button>
|
||||
|
||||
{/* Notification functionality */}
|
||||
{notificationState.sendStatus && (
|
||||
<div className="text-sm w-full">
|
||||
Send notification result: {notificationState.sendStatus}
|
||||
</div>
|
||||
)}
|
||||
<Button onClick={sendFarcasterNotification} disabled={!notificationDetails} className="w-full">
|
||||
Send notification
|
||||
</Button>
|
||||
|
||||
{/* Share URL copying */}
|
||||
<Button
|
||||
onClick={copyUserShareUrl}
|
||||
disabled={!context?.user?.fid}
|
||||
className="w-full"
|
||||
>
|
||||
{notificationState.shareUrlCopied ? "Copied!" : "Copy share URL"}
|
||||
</Button>
|
||||
|
||||
{/* Haptic feedback controls */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Haptic Intensity
|
||||
</label>
|
||||
<select
|
||||
value={selectedHapticIntensity}
|
||||
onChange={(e) => setSelectedHapticIntensity(e.target.value as Haptics.ImpactOccurredType)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
<option value={'light'}>Light</option>
|
||||
<option value={'medium'}>Medium</option>
|
||||
<option value={'heavy'}>Heavy</option>
|
||||
<option value={'soft'}>Soft</option>
|
||||
<option value={'rigid'}>Rigid</option>
|
||||
</select>
|
||||
<Button
|
||||
onClick={triggerHapticFeedback}
|
||||
className="w-full"
|
||||
>
|
||||
Trigger Haptic Feedback
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
35
src/components/ui/tabs/ContextTab.tsx
Normal file
35
src/components/ui/tabs/ContextTab.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
|
||||
/**
|
||||
* ContextTab component displays the current mini app context in JSON format.
|
||||
*
|
||||
* This component provides a developer-friendly view of the Farcaster mini app context,
|
||||
* including user information, client details, and other contextual data. It's useful
|
||||
* for debugging and understanding what data is available to the mini app.
|
||||
*
|
||||
* The context includes:
|
||||
* - User information (FID, username, display name, profile picture)
|
||||
* - Client information (safe area insets, platform details)
|
||||
* - Mini app configuration and state
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <ContextTab />
|
||||
* ```
|
||||
*/
|
||||
export function ContextTab() {
|
||||
const { context } = useMiniApp();
|
||||
|
||||
return (
|
||||
<div className="mx-6">
|
||||
<h2 className="text-lg font-semibold mb-2">Context</h2>
|
||||
<div className="p-4 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words w-full">
|
||||
{JSON.stringify(context, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
24
src/components/ui/tabs/HomeTab.tsx
Normal file
24
src/components/ui/tabs/HomeTab.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* HomeTab component displays the main landing content for the mini app.
|
||||
*
|
||||
* This is the default tab that users see when they first open the mini app.
|
||||
* It provides a simple welcome message and placeholder content that can be
|
||||
* customized for specific use cases.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <HomeTab />
|
||||
* ```
|
||||
*/
|
||||
export function HomeTab() {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-[calc(100vh-200px)] px-6">
|
||||
<div className="text-center w-full max-w-md mx-auto">
|
||||
<p className="text-lg mb-2">Put your content here!</p>
|
||||
<p className="text-sm text-gray-500">Powered by Neynar 🪐</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
347
src/components/ui/tabs/WalletTab.tsx
Normal file
347
src/components/ui/tabs/WalletTab.tsx
Normal file
@@ -0,0 +1,347 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState, useEffect } from "react";
|
||||
import { useAccount, useSendTransaction, useSignTypedData, useWaitForTransactionReceipt, useDisconnect, useConnect, useSwitchChain, useChainId } from "wagmi";
|
||||
import { useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
|
||||
import { base, degen, mainnet, optimism, unichain } from "wagmi/chains";
|
||||
import { Button } from "../Button";
|
||||
import { truncateAddress } from "../../../lib/truncateAddress";
|
||||
import { renderError } from "../../../lib/errorUtils";
|
||||
import { SignEvmMessage } from "../wallet/SignEvmMessage";
|
||||
import { SendEth } from "../wallet/SendEth";
|
||||
import { SignSolanaMessage } from "../wallet/SignSolanaMessage";
|
||||
import { SendSolana } from "../wallet/SendSolana";
|
||||
import { USE_WALLET, APP_NAME } from "../../../lib/constants";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
|
||||
/**
|
||||
* WalletTab component manages wallet-related UI for both EVM and Solana chains.
|
||||
*
|
||||
* This component provides a comprehensive wallet interface that supports:
|
||||
* - EVM wallet connections (Farcaster Frame, Coinbase Wallet, MetaMask)
|
||||
* - Solana wallet integration
|
||||
* - Message signing for both chains
|
||||
* - Transaction sending for both chains
|
||||
* - Chain switching for EVM chains
|
||||
* - Auto-connection in Farcaster clients
|
||||
*
|
||||
* The component automatically detects when running in a Farcaster client
|
||||
* and attempts to auto-connect using the Farcaster Frame connector.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <WalletTab />
|
||||
* ```
|
||||
*/
|
||||
|
||||
interface WalletStatusProps {
|
||||
address?: string;
|
||||
chainId?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the current wallet address and chain ID.
|
||||
*/
|
||||
function WalletStatus({ address, chainId }: WalletStatusProps) {
|
||||
return (
|
||||
<>
|
||||
{address && (
|
||||
<div className="text-xs w-full">
|
||||
Address: <pre className="inline w-full">{truncateAddress(address)}</pre>
|
||||
</div>
|
||||
)}
|
||||
{chainId && (
|
||||
<div className="text-xs w-full">
|
||||
Chain ID: <pre className="inline w-full">{chainId}</pre>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConnectionControlsProps {
|
||||
isConnected: boolean;
|
||||
context: any;
|
||||
connect: any;
|
||||
connectors: readonly any[];
|
||||
disconnect: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders wallet connection controls based on connection state and context.
|
||||
*/
|
||||
function ConnectionControls({
|
||||
isConnected,
|
||||
context,
|
||||
connect,
|
||||
connectors,
|
||||
disconnect,
|
||||
}: ConnectionControlsProps) {
|
||||
if (isConnected) {
|
||||
return (
|
||||
<Button onClick={() => disconnect()} className="w-full">
|
||||
Disconnect
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
if (context) {
|
||||
return (
|
||||
<div className="space-y-2 w-full">
|
||||
<Button onClick={() => connect({ connector: connectors[0] })} className="w-full">
|
||||
Connect (Auto)
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
console.log("Manual Farcaster connection attempt");
|
||||
console.log("Connectors:", connectors.map((c, i) => `${i}: ${c.name}`));
|
||||
connect({ connector: connectors[0] });
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
Connect Farcaster (Manual)
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3 w-full">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
export function WalletTab() {
|
||||
// --- State ---
|
||||
const [evmContractTransactionHash, setEvmContractTransactionHash] = useState<string | null>(null);
|
||||
|
||||
// --- Hooks ---
|
||||
const { context } = useMiniApp();
|
||||
const { address, isConnected } = useAccount();
|
||||
const chainId = useChainId();
|
||||
const solanaWallet = useSolanaWallet();
|
||||
const { publicKey: solanaPublicKey } = solanaWallet;
|
||||
|
||||
// --- Wagmi Hooks ---
|
||||
const {
|
||||
sendTransaction,
|
||||
error: evmTransactionError,
|
||||
isError: isEvmTransactionError,
|
||||
isPending: isEvmTransactionPending,
|
||||
} = useSendTransaction();
|
||||
|
||||
const { isLoading: isEvmTransactionConfirming, isSuccess: isEvmTransactionConfirmed } =
|
||||
useWaitForTransactionReceipt({
|
||||
hash: evmContractTransactionHash as `0x${string}`,
|
||||
});
|
||||
|
||||
const {
|
||||
signTypedData,
|
||||
error: evmSignTypedDataError,
|
||||
isError: isEvmSignTypedDataError,
|
||||
isPending: isEvmSignTypedDataPending,
|
||||
} = useSignTypedData();
|
||||
|
||||
const { disconnect } = useDisconnect();
|
||||
const { connect, connectors } = useConnect();
|
||||
|
||||
const {
|
||||
switchChain,
|
||||
error: chainSwitchError,
|
||||
isError: isChainSwitchError,
|
||||
isPending: isChainSwitchPending,
|
||||
} = useSwitchChain();
|
||||
|
||||
// --- Effects ---
|
||||
/**
|
||||
* Auto-connect when Farcaster context is available.
|
||||
*
|
||||
* This effect detects when the app is running in a Farcaster client
|
||||
* and automatically attempts to connect using the Farcaster Frame connector.
|
||||
* It includes comprehensive logging for debugging connection issues.
|
||||
*/
|
||||
useEffect(() => {
|
||||
// Check if we're in a Farcaster client environment
|
||||
const isInFarcasterClient = typeof window !== 'undefined' &&
|
||||
(window.location.href.includes('warpcast.com') ||
|
||||
window.location.href.includes('farcaster') ||
|
||||
window.ethereum?.isFarcaster ||
|
||||
context?.client);
|
||||
|
||||
if (context?.user?.fid && !isConnected && connectors.length > 0 && isInFarcasterClient) {
|
||||
console.log("Attempting auto-connection with Farcaster context...");
|
||||
console.log("- User FID:", context.user.fid);
|
||||
console.log("- Available connectors:", connectors.map((c, i) => `${i}: ${c.name}`));
|
||||
console.log("- Using connector:", connectors[0].name);
|
||||
console.log("- In Farcaster client:", isInFarcasterClient);
|
||||
|
||||
// Use the first connector (farcasterFrame) for auto-connection
|
||||
try {
|
||||
connect({ connector: connectors[0] });
|
||||
} catch (error) {
|
||||
console.error("Auto-connection failed:", error);
|
||||
}
|
||||
} else {
|
||||
console.log("Auto-connection conditions not met:");
|
||||
console.log("- Has context:", !!context?.user?.fid);
|
||||
console.log("- Is connected:", isConnected);
|
||||
console.log("- Has connectors:", connectors.length > 0);
|
||||
console.log("- In Farcaster client:", isInFarcasterClient);
|
||||
}
|
||||
}, [context?.user?.fid, isConnected, connectors, connect, context?.client]);
|
||||
|
||||
// --- Computed Values ---
|
||||
/**
|
||||
* Determines the next chain to switch to based on the current chain.
|
||||
* Cycles through: Base → Optimism → Degen → Mainnet → Unichain → Base
|
||||
*/
|
||||
const nextChain = useMemo(() => {
|
||||
if (chainId === base.id) {
|
||||
return optimism;
|
||||
} else if (chainId === optimism.id) {
|
||||
return degen;
|
||||
} else if (chainId === degen.id) {
|
||||
return mainnet;
|
||||
} else if (chainId === mainnet.id) {
|
||||
return unichain;
|
||||
} else {
|
||||
return base;
|
||||
}
|
||||
}, [chainId]);
|
||||
|
||||
// --- Handlers ---
|
||||
/**
|
||||
* Handles switching to the next chain in the rotation.
|
||||
* Uses the switchChain function from wagmi to change the active chain.
|
||||
*/
|
||||
const handleSwitchChain = useCallback(() => {
|
||||
switchChain({ chainId: nextChain.id });
|
||||
}, [switchChain, nextChain.id]);
|
||||
|
||||
/**
|
||||
* Sends a transaction to call the yoink() function on the Yoink contract.
|
||||
*
|
||||
* This function sends a transaction to a specific contract address with
|
||||
* the encoded function call data for the yoink() function.
|
||||
*/
|
||||
const sendEvmContractTransaction = useCallback(() => {
|
||||
sendTransaction(
|
||||
{
|
||||
// call yoink() on Yoink contract
|
||||
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
|
||||
data: "0x9846cd9efc000023c0",
|
||||
},
|
||||
{
|
||||
onSuccess: (hash) => {
|
||||
setEvmContractTransactionHash(hash);
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [sendTransaction]);
|
||||
|
||||
/**
|
||||
* Signs typed data using EIP-712 standard.
|
||||
*
|
||||
* This function creates a typed data structure with the app name, version,
|
||||
* and chain ID, then requests the user to sign it.
|
||||
*/
|
||||
const signTyped = useCallback(() => {
|
||||
signTypedData({
|
||||
domain: {
|
||||
name: APP_NAME,
|
||||
version: "1",
|
||||
chainId,
|
||||
},
|
||||
types: {
|
||||
Message: [{ name: "content", type: "string" }],
|
||||
},
|
||||
message: {
|
||||
content: `Hello from ${APP_NAME}!`,
|
||||
},
|
||||
primaryType: "Message",
|
||||
});
|
||||
}, [chainId, signTypedData]);
|
||||
|
||||
// --- Early Return ---
|
||||
if (!USE_WALLET) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
|
||||
{/* Wallet Information Display */}
|
||||
<WalletStatus address={address} chainId={chainId} />
|
||||
|
||||
{/* Connection Controls */}
|
||||
<ConnectionControls
|
||||
isConnected={isConnected}
|
||||
context={context}
|
||||
connect={connect}
|
||||
connectors={connectors}
|
||||
disconnect={disconnect}
|
||||
/>
|
||||
|
||||
{/* EVM Wallet Components */}
|
||||
<SignEvmMessage />
|
||||
|
||||
{isConnected && (
|
||||
<>
|
||||
<SendEth />
|
||||
<Button
|
||||
onClick={sendEvmContractTransaction}
|
||||
disabled={!isConnected || isEvmTransactionPending}
|
||||
isLoading={isEvmTransactionPending}
|
||||
className="w-full"
|
||||
>
|
||||
Send Transaction (contract)
|
||||
</Button>
|
||||
{isEvmTransactionError && renderError(evmTransactionError)}
|
||||
{evmContractTransactionHash && (
|
||||
<div className="text-xs w-full">
|
||||
<div>Hash: {truncateAddress(evmContractTransactionHash)}</div>
|
||||
<div>
|
||||
Status:{" "}
|
||||
{isEvmTransactionConfirming
|
||||
? "Confirming..."
|
||||
: isEvmTransactionConfirmed
|
||||
? "Confirmed!"
|
||||
: "Pending"}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={signTyped}
|
||||
disabled={!isConnected || isEvmSignTypedDataPending}
|
||||
isLoading={isEvmSignTypedDataPending}
|
||||
className="w-full"
|
||||
>
|
||||
Sign Typed Data
|
||||
</Button>
|
||||
{isEvmSignTypedDataError && renderError(evmSignTypedDataError)}
|
||||
<Button
|
||||
onClick={handleSwitchChain}
|
||||
disabled={isChainSwitchPending}
|
||||
isLoading={isChainSwitchPending}
|
||||
className="w-full"
|
||||
>
|
||||
Switch to {nextChain.name}
|
||||
</Button>
|
||||
{isChainSwitchError && renderError(chainSwitchError)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Solana Wallet Components */}
|
||||
{solanaPublicKey && (
|
||||
<>
|
||||
<SignSolanaMessage signMessage={solanaWallet.signMessage} />
|
||||
<SendSolana />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
src/components/ui/tabs/index.ts
Normal file
4
src/components/ui/tabs/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export { HomeTab } from './HomeTab';
|
||||
export { ActionsTab } from './ActionsTab';
|
||||
export { ContextTab } from './ContextTab';
|
||||
export { WalletTab } from './WalletTab';
|
||||
102
src/components/ui/wallet/SendEth.tsx
Normal file
102
src/components/ui/wallet/SendEth.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useAccount, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
|
||||
import { base } from "wagmi/chains";
|
||||
import { Button } from "../Button";
|
||||
import { truncateAddress } from "../../../lib/truncateAddress";
|
||||
import { renderError } from "../../../lib/errorUtils";
|
||||
|
||||
/**
|
||||
* SendEth component handles sending ETH transactions to protocol guild addresses.
|
||||
*
|
||||
* This component provides a simple interface for users to send small amounts
|
||||
* of ETH to protocol guild addresses. It automatically selects the appropriate
|
||||
* recipient address based on the current chain and displays transaction status.
|
||||
*
|
||||
* Features:
|
||||
* - Chain-specific recipient addresses
|
||||
* - Transaction status tracking
|
||||
* - Error handling and display
|
||||
* - Transaction hash display
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <SendEth />
|
||||
* ```
|
||||
*/
|
||||
export function SendEth() {
|
||||
// --- Hooks ---
|
||||
const { isConnected, chainId } = useAccount();
|
||||
const {
|
||||
sendTransaction,
|
||||
data: ethTransactionHash,
|
||||
error: ethTransactionError,
|
||||
isError: isEthTransactionError,
|
||||
isPending: isEthTransactionPending,
|
||||
} = useSendTransaction();
|
||||
|
||||
const { isLoading: isEthTransactionConfirming, isSuccess: isEthTransactionConfirmed } =
|
||||
useWaitForTransactionReceipt({
|
||||
hash: ethTransactionHash,
|
||||
});
|
||||
|
||||
// --- Computed Values ---
|
||||
/**
|
||||
* Determines the recipient address based on the current chain.
|
||||
*
|
||||
* Uses different protocol guild addresses for different chains:
|
||||
* - Base: 0x32e3C7fD24e175701A35c224f2238d18439C7dBC
|
||||
* - Other chains: 0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830
|
||||
*
|
||||
* @returns string - The recipient address for the current chain
|
||||
*/
|
||||
const protocolGuildRecipientAddress = useMemo(() => {
|
||||
// Protocol guild address
|
||||
return chainId === base.id
|
||||
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
|
||||
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
|
||||
}, [chainId]);
|
||||
|
||||
// --- Handlers ---
|
||||
/**
|
||||
* Handles sending the ETH transaction.
|
||||
*
|
||||
* This function sends a small amount of ETH (1 wei) to the protocol guild
|
||||
* address for the current chain. The transaction is sent using the wagmi
|
||||
* sendTransaction hook.
|
||||
*/
|
||||
const sendEthTransaction = useCallback(() => {
|
||||
sendTransaction({
|
||||
to: protocolGuildRecipientAddress,
|
||||
value: 1n,
|
||||
});
|
||||
}, [protocolGuildRecipientAddress, sendTransaction]);
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={sendEthTransaction}
|
||||
disabled={!isConnected || isEthTransactionPending}
|
||||
isLoading={isEthTransactionPending}
|
||||
>
|
||||
Send Transaction (eth)
|
||||
</Button>
|
||||
{isEthTransactionError && renderError(ethTransactionError)}
|
||||
{ethTransactionHash && (
|
||||
<div className="mt-2 text-xs">
|
||||
<div>Hash: {truncateAddress(ethTransactionHash)}</div>
|
||||
<div>
|
||||
Status:{" "}
|
||||
{isEthTransactionConfirming
|
||||
? "Confirming..."
|
||||
: isEthTransactionConfirmed
|
||||
? "Confirmed!"
|
||||
: "Pending"}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
111
src/components/ui/wallet/SendSolana.tsx
Normal file
111
src/components/ui/wallet/SendSolana.tsx
Normal file
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useConnection as useSolanaConnection, useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
|
||||
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
|
||||
import { Button } from "../Button";
|
||||
import { truncateAddress } from "../../../lib/truncateAddress";
|
||||
import { renderError } from "../../../lib/errorUtils";
|
||||
|
||||
/**
|
||||
* SendSolana component handles sending SOL transactions on Solana.
|
||||
*
|
||||
* This component provides a simple interface for users to send SOL transactions
|
||||
* using their connected Solana wallet. It includes transaction status tracking
|
||||
* and error handling.
|
||||
*
|
||||
* Features:
|
||||
* - SOL transaction sending
|
||||
* - Transaction status tracking
|
||||
* - Error handling and display
|
||||
* - Loading state management
|
||||
*
|
||||
* Note: This component is a placeholder implementation. In a real application,
|
||||
* you would integrate with a Solana wallet adapter and transaction library
|
||||
* like @solana/web3.js to handle actual transactions.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <SendSolana />
|
||||
* ```
|
||||
*/
|
||||
export function SendSolana() {
|
||||
const [solanaTransactionState, setSolanaTransactionState] = 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';
|
||||
|
||||
/**
|
||||
* Handles sending the Solana transaction
|
||||
*/
|
||||
const sendSolanaTransaction = useCallback(async () => {
|
||||
setSolanaTransactionState({ 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);
|
||||
setSolanaTransactionState({ status: 'success', signature });
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
setSolanaTransactionState({ status: 'error', error: e });
|
||||
} else {
|
||||
setSolanaTransactionState({ status: 'none' });
|
||||
}
|
||||
}
|
||||
}, [sendTransaction, publicKey, solanaConnection]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={sendSolanaTransaction}
|
||||
disabled={solanaTransactionState.status === 'pending'}
|
||||
isLoading={solanaTransactionState.status === 'pending'}
|
||||
className="mb-4"
|
||||
>
|
||||
Send Transaction (sol)
|
||||
</Button>
|
||||
{solanaTransactionState.status === 'error' && renderError(solanaTransactionState.error)}
|
||||
{solanaTransactionState.status === 'success' && (
|
||||
<div className="mt-2 text-xs">
|
||||
<div>Hash: {truncateAddress(solanaTransactionState.signature)}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
81
src/components/ui/wallet/SignEvmMessage.tsx
Normal file
81
src/components/ui/wallet/SignEvmMessage.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useAccount, useConnect, useSignMessage } from "wagmi";
|
||||
import { base } from "wagmi/chains";
|
||||
import { Button } from "../Button";
|
||||
import { config } from "../../providers/WagmiProvider";
|
||||
import { APP_NAME } from "../../../lib/constants";
|
||||
import { renderError } from "../../../lib/errorUtils";
|
||||
|
||||
/**
|
||||
* SignEvmMessage component handles signing messages on EVM-compatible chains.
|
||||
*
|
||||
* This component provides a simple interface for users to sign messages using
|
||||
* their connected EVM wallet. It automatically handles wallet connection if
|
||||
* the user is not already connected, and displays the signature result.
|
||||
*
|
||||
* Features:
|
||||
* - Automatic wallet connection if needed
|
||||
* - Message signing with app name
|
||||
* - Error handling and display
|
||||
* - Signature result display
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <SignEvmMessage />
|
||||
* ```
|
||||
*/
|
||||
export function SignEvmMessage() {
|
||||
// --- Hooks ---
|
||||
const { isConnected } = useAccount();
|
||||
const { connectAsync } = useConnect();
|
||||
const {
|
||||
signMessage,
|
||||
data: evmMessageSignature,
|
||||
error: evmSignMessageError,
|
||||
isError: isEvmSignMessageError,
|
||||
isPending: isEvmSignMessagePending,
|
||||
} = useSignMessage();
|
||||
|
||||
// --- Handlers ---
|
||||
/**
|
||||
* Handles the message signing process.
|
||||
*
|
||||
* This function first ensures the user is connected to an EVM wallet,
|
||||
* then requests them to sign a message containing the app name.
|
||||
* If the user is not connected, it automatically connects using the
|
||||
* Farcaster Frame connector.
|
||||
*
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const signEvmMessage = useCallback(async () => {
|
||||
if (!isConnected) {
|
||||
await connectAsync({
|
||||
chainId: base.id,
|
||||
connector: config.connectors[0],
|
||||
});
|
||||
}
|
||||
|
||||
signMessage({ message: `Hello from ${APP_NAME}!` });
|
||||
}, [connectAsync, isConnected, signMessage]);
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={signEvmMessage}
|
||||
disabled={isEvmSignMessagePending}
|
||||
isLoading={isEvmSignMessagePending}
|
||||
>
|
||||
Sign Message
|
||||
</Button>
|
||||
{isEvmSignMessageError && renderError(evmSignMessageError)}
|
||||
{evmMessageSignature && (
|
||||
<div className="mt-2 text-xs">
|
||||
<div>Signature: {evmMessageSignature}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
158
src/components/ui/wallet/SignIn.tsx
Normal file
158
src/components/ui/wallet/SignIn.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { signIn, signOut, getCsrfToken } from "next-auth/react";
|
||||
import sdk, { SignIn as SignInCore } from "@farcaster/frame-sdk";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { Button } from "../Button";
|
||||
|
||||
/**
|
||||
* SignIn component handles Farcaster authentication using Sign-In with Farcaster (SIWF).
|
||||
*
|
||||
* This component provides a complete authentication flow for Farcaster users:
|
||||
* - Generates nonces for secure authentication
|
||||
* - Handles the SIWF flow using the Farcaster SDK
|
||||
* - Manages NextAuth session state
|
||||
* - Provides sign-out functionality
|
||||
* - Displays authentication status and results
|
||||
*
|
||||
* The component integrates with both the Farcaster Frame SDK and NextAuth
|
||||
* to provide seamless authentication within mini apps.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <SignIn />
|
||||
* ```
|
||||
*/
|
||||
|
||||
interface AuthState {
|
||||
signingIn: boolean;
|
||||
signingOut: boolean;
|
||||
}
|
||||
|
||||
export function SignIn() {
|
||||
// --- State ---
|
||||
const [authState, setAuthState] = useState<AuthState>({
|
||||
signingIn: false,
|
||||
signingOut: false,
|
||||
});
|
||||
const [signInResult, setSignInResult] = useState<SignInCore.SignInResult>();
|
||||
const [signInFailure, setSignInFailure] = useState<string>();
|
||||
|
||||
// --- Hooks ---
|
||||
const { data: session, status } = useSession();
|
||||
|
||||
// --- Handlers ---
|
||||
/**
|
||||
* Generates a nonce for the sign-in process.
|
||||
*
|
||||
* This function retrieves a CSRF token from NextAuth to use as a nonce
|
||||
* for the SIWF authentication flow. The nonce ensures the authentication
|
||||
* request is fresh and prevents replay attacks.
|
||||
*
|
||||
* @returns Promise<string> - The generated nonce token
|
||||
* @throws Error if unable to generate nonce
|
||||
*/
|
||||
const getNonce = useCallback(async () => {
|
||||
const nonce = await getCsrfToken();
|
||||
if (!nonce) throw new Error("Unable to generate nonce");
|
||||
return nonce;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handles the sign-in process using Farcaster SDK.
|
||||
*
|
||||
* This function orchestrates the complete SIWF flow:
|
||||
* 1. Generates a nonce for security
|
||||
* 2. Calls the Farcaster SDK to initiate sign-in
|
||||
* 3. Submits the result to NextAuth for session management
|
||||
* 4. Handles various error conditions including user rejection
|
||||
*
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const handleSignIn = useCallback(async () => {
|
||||
try {
|
||||
setAuthState((prev) => ({ ...prev, signingIn: true }));
|
||||
setSignInFailure(undefined);
|
||||
const nonce = await getNonce();
|
||||
const result = await sdk.actions.signIn({ nonce });
|
||||
setSignInResult(result);
|
||||
await signIn("credentials", {
|
||||
message: result.message,
|
||||
signature: result.signature,
|
||||
redirect: false,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof SignInCore.RejectedByUser) {
|
||||
setSignInFailure("Rejected by user");
|
||||
return;
|
||||
}
|
||||
setSignInFailure("Unknown error");
|
||||
} finally {
|
||||
setAuthState((prev) => ({ ...prev, signingIn: false }));
|
||||
}
|
||||
}, [getNonce]);
|
||||
|
||||
/**
|
||||
* Handles the sign-out process.
|
||||
*
|
||||
* This function clears the NextAuth session and resets the local
|
||||
* sign-in result state to complete the sign-out flow.
|
||||
*
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setAuthState((prev) => ({ ...prev, signingOut: true }));
|
||||
await signOut({ redirect: false });
|
||||
setSignInResult(undefined);
|
||||
} finally {
|
||||
setAuthState((prev) => ({ ...prev, signingOut: false }));
|
||||
}
|
||||
}, []);
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<>
|
||||
{/* Authentication Buttons */}
|
||||
{status !== "authenticated" && (
|
||||
<Button onClick={handleSignIn} disabled={authState.signingIn}>
|
||||
Sign In with Farcaster
|
||||
</Button>
|
||||
)}
|
||||
{status === "authenticated" && (
|
||||
<Button onClick={handleSignOut} disabled={authState.signingOut}>
|
||||
Sign out
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Session Information */}
|
||||
{session && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">Session</div>
|
||||
<div className="whitespace-pre">
|
||||
{JSON.stringify(session, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Display */}
|
||||
{signInFailure && !authState.signingIn && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre">{signInFailure}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success Result Display */}
|
||||
{signInResult && !authState.signingIn && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre">
|
||||
{JSON.stringify(signInResult, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
87
src/components/ui/wallet/SignSolanaMessage.tsx
Normal file
87
src/components/ui/wallet/SignSolanaMessage.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { Button } from "../Button";
|
||||
import { renderError } from "../../../lib/errorUtils";
|
||||
|
||||
interface SignSolanaMessageProps {
|
||||
signMessage?: (message: Uint8Array) => Promise<Uint8Array>;
|
||||
}
|
||||
|
||||
/**
|
||||
* SignSolanaMessage component handles signing messages on Solana.
|
||||
*
|
||||
* This component provides a simple interface for users to sign messages using
|
||||
* their connected Solana wallet. It accepts a signMessage function as a prop
|
||||
* and handles the complete signing flow including error handling.
|
||||
*
|
||||
* Features:
|
||||
* - Message signing with Solana wallet
|
||||
* - Error handling and display
|
||||
* - Signature result display (base64 encoded)
|
||||
* - Loading state management
|
||||
*
|
||||
* @param props - Component props
|
||||
* @param props.signMessage - Function to sign messages with Solana wallet
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <SignSolanaMessage signMessage={solanaWallet.signMessage} />
|
||||
* ```
|
||||
*/
|
||||
export function SignSolanaMessage({ signMessage }: SignSolanaMessageProps) {
|
||||
// --- State ---
|
||||
const [signature, setSignature] = useState<string | undefined>();
|
||||
const [signError, setSignError] = useState<Error | undefined>();
|
||||
const [signPending, setSignPending] = useState(false);
|
||||
|
||||
// --- Handlers ---
|
||||
/**
|
||||
* Handles the Solana message signing process.
|
||||
*
|
||||
* This function encodes a message as UTF-8 bytes, signs it using the provided
|
||||
* signMessage function, and displays the base64-encoded signature result.
|
||||
* It includes comprehensive error handling and loading state management.
|
||||
*
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
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]);
|
||||
|
||||
// --- Render ---
|
||||
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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
5
src/components/ui/wallet/index.ts
Normal file
5
src/components/ui/wallet/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { SignIn } from './SignIn';
|
||||
export { SignEvmMessage } from './SignEvmMessage';
|
||||
export { SendEth } from './SendEth';
|
||||
export { SignSolanaMessage } from './SignSolanaMessage';
|
||||
export { SendSolana } from './SendSolana';
|
||||
38
src/hooks/useNeynarUser.ts
Normal file
38
src/hooks/useNeynarUser.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export interface NeynarUser {
|
||||
fid: number;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export function useNeynarUser(context?: { user?: { fid?: number } }) {
|
||||
const [user, setUser] = useState<NeynarUser | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!context?.user?.fid) {
|
||||
setUser(null);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
fetch(`/api/users?fids=${context.user.fid}`)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
if (data.users?.[0]) {
|
||||
setUser(data.users[0]);
|
||||
} else {
|
||||
setUser(null);
|
||||
}
|
||||
})
|
||||
.catch((err) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [context?.user?.fid]);
|
||||
|
||||
return { user, loading, error };
|
||||
}
|
||||
101
src/lib/constants.ts
Normal file
101
src/lib/constants.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Application constants and configuration values.
|
||||
*
|
||||
* This file contains all the configuration constants used throughout the mini app.
|
||||
* These values are either sourced from environment variables or hardcoded and provide
|
||||
* configuration for the app's appearance, behavior, and integration settings.
|
||||
*/
|
||||
|
||||
// --- App Configuration ---
|
||||
/**
|
||||
* The base URL of the application.
|
||||
* Used for generating absolute URLs for assets and API endpoints.
|
||||
*/
|
||||
export const APP_URL = process.env.NEXT_PUBLIC_URL!;
|
||||
|
||||
/**
|
||||
* The name of the mini app as displayed to users.
|
||||
* Used in titles, headers, and app store listings.
|
||||
*/
|
||||
export const APP_NAME = 'Starter Kit';
|
||||
|
||||
/**
|
||||
* A brief description of the mini app's functionality.
|
||||
* Used in app store listings and metadata.
|
||||
*/
|
||||
export const APP_DESCRIPTION = 'A demo of the Neynar Starter Kit';
|
||||
|
||||
/**
|
||||
* The primary category for the mini app.
|
||||
* Used for app store categorization and discovery.
|
||||
*/
|
||||
export const APP_PRIMARY_CATEGORY = 'developer-tools';
|
||||
|
||||
/**
|
||||
* Tags associated with the mini app.
|
||||
* Used for search and discovery in app stores.
|
||||
* Parsed from comma-separated environment variable.
|
||||
*/
|
||||
export const APP_TAGS = ['neynar', 'starter-kit', 'demo'];
|
||||
|
||||
// --- Asset URLs ---
|
||||
/**
|
||||
* URL for the app's icon image.
|
||||
* Used in app store listings and UI elements.
|
||||
*/
|
||||
export const APP_ICON_URL = `${APP_URL}/icon.png`;
|
||||
|
||||
/**
|
||||
* URL for the app's Open Graph image.
|
||||
* Used for social media sharing and previews.
|
||||
*/
|
||||
export const APP_OG_IMAGE_URL = `${APP_URL}/api/opengraph-image`;
|
||||
|
||||
/**
|
||||
* URL for the app's splash screen image.
|
||||
* Displayed during app loading.
|
||||
*/
|
||||
export const APP_SPLASH_URL = `${APP_URL}/splash.png`;
|
||||
|
||||
/**
|
||||
* Background color for the splash screen.
|
||||
* Used as fallback when splash image is loading.
|
||||
*/
|
||||
export const APP_SPLASH_BACKGROUND_COLOR = "#f7f7f7";
|
||||
|
||||
// --- UI Configuration ---
|
||||
/**
|
||||
* Text displayed on the main action button.
|
||||
* Used for the primary call-to-action in the mini app.
|
||||
*/
|
||||
export const APP_BUTTON_TEXT = 'Launch NSK';
|
||||
|
||||
// --- Integration Configuration ---
|
||||
/**
|
||||
* Webhook URL for receiving events from Neynar.
|
||||
*
|
||||
* If Neynar API key and client ID are configured, uses the official
|
||||
* Neynar webhook endpoint. Otherwise, falls back to a local webhook
|
||||
* endpoint for development and testing.
|
||||
*/
|
||||
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`;
|
||||
|
||||
/**
|
||||
* Flag to enable/disable wallet functionality.
|
||||
*
|
||||
* When true, wallet-related components and features are rendered.
|
||||
* When false, wallet functionality is completely hidden from the UI.
|
||||
* Useful for mini apps that don't require wallet integration.
|
||||
*/
|
||||
export const USE_WALLET = true;
|
||||
|
||||
/**
|
||||
* Flag to enable/disable analytics tracking.
|
||||
*
|
||||
* When true, usage analytics are collected and sent to Neynar.
|
||||
* When false, analytics collection is disabled.
|
||||
* Useful for privacy-conscious users or development environments.
|
||||
*/
|
||||
export const ANALYTICS_ENABLED = true;
|
||||
66
src/lib/errorUtils.tsx
Normal file
66
src/lib/errorUtils.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import { type ReactElement } from "react";
|
||||
import { BaseError, UserRejectedRequestError } from "viem";
|
||||
|
||||
/**
|
||||
* Renders an error object in a user-friendly format.
|
||||
*
|
||||
* This utility function takes an error object and renders it as a React element
|
||||
* with consistent styling. It handles different types of errors including:
|
||||
* - Error objects with message properties
|
||||
* - Objects with error properties
|
||||
* - String errors
|
||||
* - Unknown error types
|
||||
* - User rejection errors (special handling for wallet rejections)
|
||||
*
|
||||
* The rendered error is displayed in a gray container with monospace font
|
||||
* for better readability of technical error details. User rejections are
|
||||
* displayed with a simpler, more user-friendly message.
|
||||
*
|
||||
* @param error - The error object to render
|
||||
* @returns ReactElement - A styled error display component, or null if no error
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* {isError && renderError(error)}
|
||||
* ```
|
||||
*/
|
||||
export function renderError(error: unknown): ReactElement | null {
|
||||
// Handle null/undefined errors
|
||||
if (!error) return null;
|
||||
|
||||
// Special handling for user rejections in wallet operations
|
||||
if (error instanceof BaseError) {
|
||||
const isUserRejection = error.walk(
|
||||
(e) => e instanceof UserRejectedRequestError
|
||||
);
|
||||
|
||||
if (isUserRejection) {
|
||||
return (
|
||||
<div className="mt-2 p-2 text-xs bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||
<div className="font-semibold text-red-500 mb-1">User Rejection</div>
|
||||
<div>Transaction was rejected by user.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract error message from different error types
|
||||
let errorMessage: string;
|
||||
|
||||
if (error instanceof Error) {
|
||||
errorMessage = error.message;
|
||||
} else if (typeof error === 'object' && error !== null && 'error' in error) {
|
||||
errorMessage = String(error.error);
|
||||
} else if (typeof error === 'string') {
|
||||
errorMessage = error;
|
||||
} else {
|
||||
errorMessage = 'Unknown error occurred';
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-800 rounded-lg font-mono">
|
||||
<div className="font-semibold text-red-500 mb-1">Error</div>
|
||||
<div className="whitespace-pre-wrap break-words">{errorMessage}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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,7 +18,20 @@ export function getNeynarClient() {
|
||||
return neynarClient;
|
||||
}
|
||||
|
||||
type SendFrameNotificationResult =
|
||||
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 SendMiniAppNotificationResult =
|
||||
| {
|
||||
state: "error";
|
||||
error: unknown;
|
||||
@@ -26,7 +40,7 @@ type SendFrameNotificationResult =
|
||||
| { state: "rate_limit" }
|
||||
| { state: "success" };
|
||||
|
||||
export async function sendNeynarFrameNotification({
|
||||
export async function sendNeynarMiniAppNotification({
|
||||
fid,
|
||||
title,
|
||||
body,
|
||||
@@ -34,14 +48,14 @@ export async function sendNeynarFrameNotification({
|
||||
fid: number;
|
||||
title: string;
|
||||
body: string;
|
||||
}): Promise<SendFrameNotificationResult> {
|
||||
}): Promise<SendMiniAppNotificationResult> {
|
||||
try {
|
||||
const client = getNeynarClient();
|
||||
const targetFids = [fid];
|
||||
const notification = {
|
||||
title,
|
||||
body,
|
||||
target_url: process.env.NEXT_PUBLIC_URL!,
|
||||
target_url: APP_URL,
|
||||
};
|
||||
|
||||
const result = await client.publishFrameNotifications({
|
||||
|
||||
@@ -3,10 +3,9 @@ import {
|
||||
sendNotificationResponseSchema,
|
||||
} from "@farcaster/frame-sdk";
|
||||
import { getUserNotificationDetails } from "~/lib/kv";
|
||||
import { APP_URL } from "./constants";
|
||||
|
||||
const appUrl = process.env.NEXT_PUBLIC_URL || "";
|
||||
|
||||
type SendFrameNotificationResult =
|
||||
type SendMiniAppNotificationResult =
|
||||
| {
|
||||
state: "error";
|
||||
error: unknown;
|
||||
@@ -15,7 +14,7 @@ type SendFrameNotificationResult =
|
||||
| { state: "rate_limit" }
|
||||
| { state: "success" };
|
||||
|
||||
export async function sendFrameNotification({
|
||||
export async function sendMiniAppNotification({
|
||||
fid,
|
||||
title,
|
||||
body,
|
||||
@@ -23,7 +22,7 @@ export async function sendFrameNotification({
|
||||
fid: number;
|
||||
title: string;
|
||||
body: string;
|
||||
}): Promise<SendFrameNotificationResult> {
|
||||
}): Promise<SendMiniAppNotificationResult> {
|
||||
const notificationDetails = await getUserNotificationDetails(fid);
|
||||
if (!notificationDetails) {
|
||||
return { state: "no_token" };
|
||||
@@ -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 {
|
||||
interface MiniAppMetadata {
|
||||
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 MiniAppManifest {
|
||||
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: MiniAppMetadata;
|
||||
}
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
@@ -36,25 +43,45 @@ export function getSecretEnvVars() {
|
||||
return { seedPhrase, fid };
|
||||
}
|
||||
|
||||
export async function getFarcasterMetadata(): Promise<FrameMetadata> {
|
||||
// First check for FRAME_METADATA in .env and use that if it exists
|
||||
if (process.env.FRAME_METADATA) {
|
||||
export function getMiniAppEmbedMetadata(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<MiniAppManifest> {
|
||||
// First check for MINI_APP_METADATA in .env and use that if it exists
|
||||
if (process.env.MINI_APP_METADATA) {
|
||||
try {
|
||||
const metadata = JSON.parse(process.env.FRAME_METADATA);
|
||||
console.log('Using pre-signed frame metadata from environment');
|
||||
const metadata = JSON.parse(process.env.MINI_APP_METADATA);
|
||||
console.log('Using pre-signed mini app metadata from environment');
|
||||
return metadata;
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse FRAME_METADATA from environment:', error);
|
||||
console.warn('Failed to parse MINI_APP_METADATA from environment:', error);
|
||||
}
|
||||
}
|
||||
|
||||
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 ?? "Neynar Starter Kit",
|
||||
iconUrl: APP_ICON_URL,
|
||||
homeUrl: APP_URL,
|
||||
imageUrl: APP_OG_IMAGE_URL,
|
||||
buttonTitle: APP_BUTTON_TEXT ?? "Launch Mini App",
|
||||
splashImageUrl: APP_SPLASH_URL,
|
||||
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
|
||||
webhookUrl: APP_WEBHOOK_URL,
|
||||
description: APP_DESCRIPTION,
|
||||
primaryCategory: APP_PRIMARY_CATEGORY,
|
||||
tags: APP_TAGS,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
|
||||
/**
|
||||
* Tailwind CSS Configuration
|
||||
*
|
||||
* This configuration centralizes all theme colors for the mini app.
|
||||
* To change the app's color scheme, simply update the 'primary' color value below.
|
||||
*
|
||||
* Example theme changes:
|
||||
* - Blue theme: primary: "#3182CE"
|
||||
* - Green theme: primary: "#059669"
|
||||
* - Red theme: primary: "#DC2626"
|
||||
* - Orange theme: primary: "#EA580C"
|
||||
*/
|
||||
export default {
|
||||
darkMode: ["class"],
|
||||
darkMode: "media",
|
||||
content: [
|
||||
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
@@ -10,6 +22,16 @@ export default {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
// Main theme color - change this to update the entire app's color scheme
|
||||
primary: "#8b5cf6", // Main brand color
|
||||
"primary-light": "#a78bfa", // For hover states
|
||||
"primary-dark": "#7c3aed", // For active states
|
||||
|
||||
// Secondary colors for backgrounds and text
|
||||
secondary: "#f8fafc", // Light backgrounds
|
||||
"secondary-dark": "#334155", // Dark backgrounds
|
||||
|
||||
// Legacy CSS variables for backward compatibility
|
||||
background: 'var(--background)',
|
||||
foreground: 'var(--foreground)'
|
||||
},
|
||||
@@ -17,6 +39,20 @@ export default {
|
||||
lg: 'var(--radius)',
|
||||
md: 'calc(var(--radius) - 2px)',
|
||||
sm: 'calc(var(--radius) - 4px)'
|
||||
},
|
||||
// Custom spacing for consistent layout
|
||||
spacing: {
|
||||
'18': '4.5rem',
|
||||
'88': '22rem',
|
||||
},
|
||||
// Custom container sizes
|
||||
maxWidth: {
|
||||
'xs': '20rem',
|
||||
'sm': '24rem',
|
||||
'md': '28rem',
|
||||
'lg': '32rem',
|
||||
'xl': '36rem',
|
||||
'2xl': '42rem',
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user