formatting

This commit is contained in:
Shreyaschorge 2025-07-07 14:10:47 +05:30
parent f42a5f8d33
commit 193dffe03a
No known key found for this signature in database
64 changed files with 6398 additions and 985 deletions

29
.editorconfig Normal file
View File

@ -0,0 +1,29 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
# Matches multiple files with brace expansion notation
[*.{js,jsx,ts,tsx,json,css,scss,md,mdx,yml,yaml}]
indent_style = space
indent_size = 2
# Tab indentation (no size specified)
[Makefile]
indent_style = tab
# Matches the exact files
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2
# Markdown files
[*.md]
trim_trailing_whitespace = false

92
.eslintignore Normal file
View File

@ -0,0 +1,92 @@
# Dependencies
node_modules/
.pnp/
.pnp.*
# Build outputs
.next/
out/
build/
dist/
# Environment files
.env*
!.env.example
# Generated files
next-env.d.ts
*.tsbuildinfo
# Package manager lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
# Vercel
.vercel/
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Editor files
.vscode/
.idea/
*.swp
*.swo
*~
# Git
.git/
# Temporary files
tmp/
temp/
# Coverage
coverage/
.nyc_output
# Cache directories
.cache/
.parcel-cache/
.eslintcache
# Storybook build outputs
storybook-static
# Database
*.db
*.sqlite
# Documentation
docs/
# Auto-generated files
*.d.ts
!src/**/*.d.ts
!types/**/*.d.ts
# Test coverage
*.lcov
# Compiled binary addons
build/Release
# Yarn
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz

View File

@ -1,3 +1,75 @@
{
"extends": ["next/core-web-vitals", "next/typescript"]
"root": true,
"env": {
"browser": true,
"es2022": true,
"node": true
},
"extends": [
"eslint:recommended",
"@typescript-eslint/recommended",
"next/core-web-vitals",
"next/typescript",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
},
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
"prettier/prettier": "error",
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
],
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/prefer-const": "error",
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/require-await": "error",
"react/display-name": "off",
"react/prop-types": "off",
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off",
"no-console": ["warn", { "allow": ["warn", "error"] }],
"prefer-const": "error",
"no-var": "error",
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 0 }],
"no-trailing-spaces": "error",
"eol-last": "error",
"comma-dangle": ["error", "es5"],
"semi": ["error", "always"],
"quotes": ["error", "single", { "avoidEscape": true }]
},
"overrides": [
{
"files": ["*.js", "*.jsx"],
"rules": {
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/require-await": "off"
}
},
{
"files": ["*.config.js", "*.config.ts", "next.config.*"],
"rules": {
"@typescript-eslint/no-var-requires": "off"
}
}
]
}

22
.gitignore vendored
View File

@ -39,3 +39,25 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
# IDE and editor files
.vscode/settings.json
.idea/
*.swp
*.swo
*~
# Linting and formatting cache
.eslintcache
.prettierignore.bak
# OS generated files
Thumbs.db
# Package manager files
.pnpm-debug.log*
.yarn-integrity
# Temporary files
tmp/
temp/

4
.lintstagedrc Normal file
View File

@ -0,0 +1,4 @@
{
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{json,css,scss,md,mdx,yml,yaml}": ["prettier --write"]
}

204
.prettierignore Normal file
View File

@ -0,0 +1,204 @@
# Dependencies
node_modules/
.pnp/
.pnp.*
# Build outputs
.next/
out/
build/
dist/
# Environment files
.env*
!.env.example
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
lerna-debug.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# nyc test coverage
.nyc_output
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# parcel-bundler cache
.cache
.parcel-cache
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# Generated files
next-env.d.ts
# Package manager lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
# Vercel
.vercel/
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Temporary files
tmp/
temp/
# Database
*.db
*.sqlite
# Compiled binary addons
build/Release
# Documentation
docs/
# Git
.git/
.gitignore
# Editor files
*.swp
*.swo
*~
# Changelog
CHANGELOG.md
# Auto-generated documentation
api-docs/
# Dependency directories
node_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Storybook build outputs
.out
.storybook-out
# Temporary folders
tmp/
temp/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Vercel
.vercel
# Package manager lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
# Git
.git/

17
.prettierrc Normal file
View File

@ -0,0 +1,17 @@
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "avoid",
"endOfLine": "lf",
"quoteProps": "as-needed",
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"embeddedLanguageFormatting": "auto",
"singleAttributePerLine": false
}

13
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,13 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"bradlc.vscode-tailwindcss",
"ms-vscode.vscode-typescript-next",
"editorconfig.editorconfig",
"christian-kohler.path-intellisense",
"ms-vscode.vscode-json",
"formulahendry.auto-rename-tag",
"christian-kohler.npm-intellisense"
]
}

226
FORMATTING.md Normal file
View File

@ -0,0 +1,226 @@
# Formatting and Code Style Guide
This project uses a comprehensive set of tools to ensure consistent code formatting and quality across the entire codebase.
## Tools Configured
### 🎨 **Prettier** - Code Formatter
- Automatically formats JavaScript, TypeScript, CSS, JSON, and Markdown files
- Configuration: `.prettierrc`
- Ignore patterns: `.prettierignore`
### 🔍 **ESLint** - Linter and Code Quality
- Enforces code quality rules and catches potential bugs
- Configuration: `.eslintrc.json`
- Ignore patterns: `.eslintignore`
### ⚙️ **EditorConfig** - Cross-Editor Consistency
- Ensures consistent indentation and line endings across different editors
- Configuration: `.editorconfig`
### 🔧 **VS Code Settings**
- Pre-configured workspace settings for optimal development experience
- Configuration: `.vscode/settings.json`
- Recommended extensions: `.vscode/extensions.json`
## Quick Start
### Installation
When you create a new project using this template, all formatting tools are already configured. Simply run:
```bash
npm install
```
### Available Scripts
#### Formatting
```bash
npm run format # Format all files with Prettier
npm run format:check # Check if files are properly formatted
npm run format:fix # Format files and fix ESLint issues
```
#### Linting
```bash
npm run lint # Run ESLint
npm run lint:fix # Run ESLint and auto-fix issues
npm run lint:check # Run ESLint with zero warnings tolerance
```
#### Type Checking
```bash
npm run type-check # Run TypeScript compiler without emitting files
```
#### Combined Checks
```bash
npm run check # Run type-check, lint:check, and format:check
```
## Editor Setup
### VS Code (Recommended)
1. Install recommended extensions when prompted
2. Formatting and linting will work automatically on save
3. Key extensions:
- **Prettier**: Code formatter
- **ESLint**: Linting and error detection
- **EditorConfig**: Consistent editor settings
### Other Editors
- **WebStorm/IntelliJ**: Built-in support for Prettier and ESLint
- **Vim/Neovim**: Use appropriate plugins for Prettier and ESLint
- **Emacs**: Configure with prettier-js and flycheck-eslint
## Configuration Details
### Prettier Configuration (`.prettierrc`)
```json
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "avoid",
"endOfLine": "lf"
}
```
### Key ESLint Rules
- TypeScript and React best practices
- Prettier integration (no conflicts)
- Async/await safety rules
- Import organization
- Console warnings (allows warn/error)
### EditorConfig Settings
- 2-space indentation for most files
- LF line endings
- UTF-8 encoding
- Trim trailing whitespace
- Insert final newline
## Git Hooks (Optional)
You can set up pre-commit hooks using `husky` and `lint-staged`:
```bash
npm install --save-dev husky lint-staged
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"
```
The project includes a `.lintstagedrc` configuration that will:
- Run ESLint and Prettier on staged JS/TS files
- Run Prettier on staged JSON, CSS, and Markdown files
## Team Guidelines
### Before Committing
1. Run `npm run check` to ensure code quality
2. Fix any linting errors or formatting issues
3. Commit your changes
### Pull Request Requirements
- All checks must pass
- Code must be properly formatted
- No ESLint warnings or errors
- TypeScript compilation must succeed
### Customization
If you need to modify the formatting rules:
1. **Prettier**: Edit `.prettierrc`
2. **ESLint**: Edit `.eslintrc.json`
3. **EditorConfig**: Edit `.editorconfig`
Remember to discuss any changes with your team first!
## Troubleshooting
### Common Issues
#### "Prettier and ESLint conflict"
- This shouldn't happen as we use `eslint-config-prettier`
- If it does, check that Prettier rules come last in ESLint extends
#### "Format on save not working"
- Ensure Prettier extension is installed and enabled
- Check VS Code settings for `editor.formatOnSave: true`
- Verify the file type is in ESLint validation array
#### "TypeScript errors in JavaScript files"
- Check file extension (.js vs .ts)
- Verify ESLint overrides for JavaScript files
#### "Formatting different in CI vs local"
- Ensure same Node.js version
- Check line ending settings (LF vs CRLF)
- Verify Prettier version consistency
### Getting Help
- Check the documentation for [Prettier](https://prettier.io/)
- Check the documentation for [ESLint](https://eslint.org/)
- Review [Next.js ESLint configuration](https://nextjs.org/docs/basic-features/eslint)
## Best Practices
### File Organization
- Keep configuration files in project root
- Use meaningful names for custom ESLint rules
- Group related imports together
### Code Style
- Use meaningful variable names
- Prefer `const` over `let` when possible
- Use template literals for string interpolation
- Keep functions small and focused
- Add JSDoc comments for complex functions
### React Specific
- Use functional components with hooks
- Prefer explicit prop types (TypeScript interfaces)
- Use meaningful component names
- Keep components focused on single responsibility
### TypeScript
- Enable strict mode
- Use proper types instead of `any`
- Leverage type inference where appropriate
- Use proper generic constraints
---
_This formatting guide is automatically included with every new project created from this template._

View File

@ -11,24 +11,51 @@ Check out [this Neynar docs page](https://docs.neynar.com/docs/create-farcaster-
## Getting Started
To create a new mini app project, run:
```{bash}
npx @neynar/create-farcaster-mini-app@latest
```
To run the project:
```{bash}
cd <PROJECT_NAME>
npm run dev
```
## Code Formatting & Linting
This template includes comprehensive formatting and linting tools to ensure consistent code quality:
- **Prettier**: Automatic code formatting
- **ESLint**: Code linting with Next.js and TypeScript support
- **EditorConfig**: Cross-editor consistency
### Available Scripts
```bash
npm run format # Format all files with Prettier
npm run format:check # Check if files are properly formatted
npm run lint # Run ESLint
npm run lint:fix # Fix ESLint issues automatically
npm run type-check # Run TypeScript type checking
npm run check # Run all checks (types, lint, format)
```
See [FORMATTING.md](./FORMATTING.md) for detailed configuration and setup information.
### Importing the CLI
To invoke the CLI directly in JavaScript, add the npm package to your project and use the following import statement:
```{javascript}
import { init } from '@neynar/create-farcaster-mini-app';
```
## Deploying to Vercel
For projects that have made minimal changes to the quickstart template, deploy to vercel by running:
```{bash}
npm run deploy:vercel
```
@ -36,6 +63,7 @@ npm run deploy:vercel
## Building for Production
To create a production build, run:
```{bash}
npm run build
```
@ -51,11 +79,12 @@ This section is only for working on the script and template. If you simply want
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.
This makes your local version globally available as a symlinked package.
1. Now, when you run:
```bash
@ -76,4 +105,3 @@ However, this does not fully replicate the npx install flow and may not catch al
### Environment Variables and Scripts
If you update environment variable handling, remember to replicate any changes in the `dev`, `build`, and `deploy` scripts as needed. The `build` and `deploy` scripts may need further updates and are less critical for most development workflows.

View File

@ -25,7 +25,7 @@ if (autoAcceptDefaults && !projectName) {
autoAcceptDefaults = false;
}
init(projectName, autoAcceptDefaults).catch((err) => {
init(projectName, autoAcceptDefaults).catch(err => {
console.error('Error:', err);
process.exit(1);
});

View File

@ -1,18 +1,19 @@
#!/usr/bin/env node
import inquirer from 'inquirer';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import fs from 'fs';
import inquirer from 'inquirer';
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const REPO_URL = 'https://github.com/neynarxyz/create-farcaster-mini-app.git';
const SCRIPT_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8')).version;
const SCRIPT_VERSION = JSON.parse(
fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8')
).version;
// ANSI color codes
const purple = '\x1b[35m';
@ -48,8 +49,8 @@ async function queryNeynarApp(apiKey) {
`https://api.neynar.com/portal/app_by_api_key?starter_kit=true`,
{
headers: {
'x-api-key': apiKey
}
'x-api-key': apiKey,
},
}
);
const data = await response.json();
@ -80,16 +81,17 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
{
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
}
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,
},
]);
}
@ -98,7 +100,9 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
break;
}
console.log('\n🪐 Find your Neynar API key at: https://dev.neynar.com/app\n');
console.log(
'\n🪐 Find your Neynar API key at: https://dev.neynar.com/app\n'
);
let neynarKeyAnswer;
if (autoAcceptDefaults) {
@ -109,8 +113,8 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
type: 'password',
name: 'neynarApiKey',
message: 'Enter your Neynar API key (or press enter to skip):',
default: null
}
default: null,
},
]);
}
@ -126,15 +130,21 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
type: 'confirm',
name: 'useDemo',
message: 'Would you like to try the demo Neynar API key?',
default: true
}
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(`\n${purple}${bright}${italic}Neynar now has a free tier! See https://neynar.com/#pricing for details.\n${reset}`);
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(
`\n${purple}${bright}${italic}Neynar now has a free tier! See https://neynar.com/#pricing for details.\n${reset}`
);
neynarApiKey = 'FARCASTER_V2_FRAMES_DEMO';
}
}
@ -144,14 +154,16 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
useNeynar = false;
break;
}
console.log('\n⚠ No valid API key provided. Would you like to try again?');
console.log(
'\n⚠ No valid API key provided. Would you like to try again?'
);
const { retry } = await inquirer.prompt([
{
type: 'confirm',
name: 'retry',
message: 'Try configuring Neynar again?',
default: true
}
default: true,
},
]);
if (!retry) {
useNeynar = false;
@ -176,9 +188,10 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
{
type: 'confirm',
name: 'retry',
message: '⚠️ Could not find a client ID for this API key. Would you like to try configuring Neynar again?',
default: true
}
message:
'⚠️ Could not find a client ID for this API key. Would you like to try configuring Neynar again?',
default: true,
},
]);
if (!retry) {
useNeynar = false;
@ -191,7 +204,10 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
break;
}
const defaultMiniAppName = (neynarAppName && !neynarAppName.toLowerCase().includes('demo')) ? neynarAppName : undefined;
const defaultMiniAppName =
neynarAppName && !neynarAppName.toLowerCase().includes('demo')
? neynarAppName
: undefined;
let answers;
if (autoAcceptDefaults) {
@ -203,7 +219,7 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
buttonText: 'Launch Mini App',
useWallet: true,
useTunnel: true,
enableAnalytics: true
enableAnalytics: true,
};
} else {
// If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options
@ -213,13 +229,13 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
name: 'projectName',
message: 'What is the name of your mini app?',
default: projectName || defaultMiniAppName,
validate: (input) => {
validate: input => {
if (input.trim() === '') {
return 'Project name cannot be empty';
}
return true;
}
}
},
},
]);
answers = await inquirer.prompt([
@ -227,12 +243,13 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
type: 'input',
name: 'description',
message: 'Give a one-line description of your mini app (optional):',
default: 'A Farcaster mini app created with Neynar'
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:',
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 },
@ -249,36 +266,37 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
{ name: 'Education', value: 'education' },
{ name: 'Developer Tools', value: 'developer-tools' },
{ name: 'Entertainment', value: 'entertainment' },
{ name: 'Art & Creativity', value: 'art-creativity' }
{ name: 'Art & Creativity', value: 'art-creativity' },
],
default: null
default: null,
},
{
type: 'input',
name: 'tags',
message: 'Enter tags for your mini app (separate with spaces or commas, optional):',
message:
'Enter tags for your mini app (separate with spaces or commas, optional):',
default: '',
filter: (input) => {
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) => {
validate: input => {
if (input.trim() === '') {
return 'Button text cannot be empty';
}
return true;
}
}
},
},
]);
// Merge project name from the first prompt
@ -289,7 +307,8 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
{
type: 'confirm',
name: 'useWallet',
message: 'Would you like to include wallet and transaction tooling in your mini app?\n' +
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' +
@ -297,8 +316,8 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
'- Chain switching\n' +
'- Solana support\n\n' +
'Include wallet and transaction features?',
default: true
}
default: true,
},
]);
answers.useWallet = walletAnswer.useWallet;
@ -307,11 +326,12 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
{
type: 'confirm',
name: 'useTunnel',
message: 'Would you like to test on mobile and/or test the app with Warpcast developer tools?\n' +
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
}
default: true,
},
]);
answers.useTunnel = hostingAnswer.useTunnel;
@ -320,9 +340,10 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
{
type: 'confirm',
name: 'enableAnalytics',
message: 'Would you like to help improve Neynar products by sharing usage data from your mini app?',
default: true
}
message:
'Would you like to help improve Neynar products by sharing usage data from your mini app?',
default: true,
},
]);
answers.enableAnalytics = analyticsAnswer.enableAnalytics;
}
@ -339,17 +360,17 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
// Use separate commands for better cross-platform compatibility
execSync(`git clone ${REPO_URL} "${projectPath}"`, {
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
execSync('git fetch origin main', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
execSync('git reset --hard origin/main', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
} catch (error) {
console.error('\n❌ Error: Failed to create project directory.');
@ -386,47 +407,52 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
// Add dependencies
packageJson.dependencies = {
"@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",
"clsx": "^2.1.1",
"dotenv": "^16.4.7",
"lucide-react": "^0.469.0",
"mipd": "^0.0.7",
"next": "^15",
"next-auth": "^4.24.11",
"react": "^19",
"react-dom": "^19",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
"viem": "^2.23.6",
"wagmi": "^2.14.12",
"zod": "^3.24.2"
'@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',
clsx: '^2.1.1',
dotenv: '^16.4.7',
'lucide-react': '^0.469.0',
mipd: '^0.0.7',
next: '^15',
'next-auth': '^4.24.11',
react: '^19',
'react-dom': '^19',
'tailwind-merge': '^2.6.0',
'tailwindcss-animate': '^1.0.7',
viem: '^2.23.6',
wagmi: '^2.14.12',
zod: '^3.24.2',
};
packageJson.devDependencies = {
"@types/node": "^20",
"@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"
'@types/node': '^20',
'@types/react': '^19',
'@types/react-dom': '^19',
'@typescript-eslint/eslint-plugin': '^8.0.0',
'@typescript-eslint/parser': '^8.0.0',
'@vercel/sdk': '^1.9.0',
crypto: '^1.0.1',
eslint: '^8.57.0',
'eslint-config-next': '15.0.3',
'eslint-config-prettier': '^9.1.0',
'eslint-plugin-prettier': '^5.2.1',
localtunnel: '^2.0.2',
'pino-pretty': '^13.0.0',
postcss: '^8',
prettier: '^3.3.3',
tailwindcss: '^3.4.1',
typescript: '^5',
};
// Add Neynar SDK if selected
@ -434,6 +460,15 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
packageJson.dependencies['@neynar/nodejs-sdk'] = '^2.19.0';
}
// Update scripts with formatting and linting
packageJson.scripts = {
...packageJson.scripts,
'lint:fix': 'next lint --fix',
format: 'prettier --write .',
'format:check': 'prettier --check .',
'type-check': 'tsc --noEmit',
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
// Handle .env file
@ -454,15 +489,19 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
// Helper function to escape single quotes in strings
const escapeString = (str) => str.replace(/'/g, "\\'");
const escapeString = str => str.replace(/'/g, "\\'");
// Helper function to safely replace constants with validation
const safeReplace = (content, pattern, replacement, constantName) => {
const match = content.match(pattern);
if (!match) {
console.log(`⚠️ Warning: Could not update ${constantName} in constants.ts. Pattern not found.`);
console.log(
`⚠️ Warning: Could not update ${constantName} in constants.ts. Pattern not found.`
);
console.log(`Pattern: ${pattern}`);
console.log(`Expected to match in: ${content.split('\n').find(line => line.includes(constantName)) || 'Not found'}`);
console.log(
`Expected to match in: ${content.split('\n').find(line => line.includes(constantName)) || 'Not found'}`
);
} else {
const newContent = content.replace(pattern, replacement);
return newContent;
@ -473,12 +512,16 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
// Regex patterns that match whole lines with export const
const patterns = {
APP_NAME: /^export const APP_NAME\s*=\s*['"`][^'"`]*['"`];$/m,
APP_DESCRIPTION: /^export const APP_DESCRIPTION\s*=\s*['"`][^'"`]*['"`];$/m,
APP_PRIMARY_CATEGORY: /^export const APP_PRIMARY_CATEGORY\s*=\s*['"`][^'"`]*['"`];$/m,
APP_DESCRIPTION:
/^export const APP_DESCRIPTION\s*=\s*['"`][^'"`]*['"`];$/m,
APP_PRIMARY_CATEGORY:
/^export const APP_PRIMARY_CATEGORY\s*=\s*['"`][^'"`]*['"`];$/m,
APP_TAGS: /^export const APP_TAGS\s*=\s*\[[^\]]*\];$/m,
APP_BUTTON_TEXT: /^export const APP_BUTTON_TEXT\s*=\s*['"`][^'"`]*['"`];$/m,
APP_BUTTON_TEXT:
/^export const APP_BUTTON_TEXT\s*=\s*['"`][^'"`]*['"`];$/m,
USE_WALLET: /^export const USE_WALLET\s*=\s*(true|false);$/m,
ANALYTICS_ENABLED: /^export const ANALYTICS_ENABLED\s*=\s*(true|false);$/m
ANALYTICS_ENABLED:
/^export const ANALYTICS_ENABLED\s*=\s*(true|false);$/m,
};
// Update APP_NAME
@ -506,9 +549,10 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
);
// Update APP_TAGS
const tagsString = answers.tags.length > 0
? `['${answers.tags.map(tag => escapeString(tag)).join("', '")}']`
: "['neynar', 'starter-kit', 'demo']";
const tagsString =
answers.tags.length > 0
? `['${answers.tags.map(tag => escapeString(tag)).join("', '")}']`
: "['neynar', 'starter-kit', 'demo']";
constantsContent = safeReplace(
constantsContent,
patterns.APP_TAGS,
@ -545,18 +589,25 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
console.log('⚠️ constants.ts not found, skipping constants update');
}
fs.appendFileSync(envPath, `\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`);
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}"`);
} else if (useNeynar) {
console.log('\n⚠ Could not find a Neynar client ID and/or API key. Please configure Neynar manually in .env.local with NEYNAR_API_KEY and NEYNAR_CLIENT_ID');
console.log(
'\n⚠ Could not find a Neynar client ID and/or API key. Please configure Neynar manually in .env.local with NEYNAR_API_KEY and NEYNAR_CLIENT_ID'
);
}
fs.appendFileSync(envPath, `\nUSE_TUNNEL="${answers.useTunnel}"`);
fs.unlinkSync(envExamplePath);
} else {
console.log('\n.env.example does not exist, skipping copy and remove operations');
console.log(
'\n.env.example does not exist, skipping copy and remove operations'
);
}
// Update README
@ -564,7 +615,9 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
const readmePath = path.join(projectPath, 'README.md');
const prependText = `<!-- generated by @neynar/create-farcaster-mini-app version ${SCRIPT_VERSION} -->\n\n`;
if (fs.existsSync(readmePath)) {
const originalReadmeContent = fs.readFileSync(readmePath, { encoding: 'utf8' });
const originalReadmeContent = fs.readFileSync(readmePath, {
encoding: 'utf8',
});
const updatedReadmeContent = prependText + originalReadmeContent;
fs.writeFileSync(readmePath, updatedReadmeContent);
} else {
@ -577,12 +630,12 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
execSync('npm cache clean --force', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
execSync('npm install', {
cwd: projectPath,
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
// Remove the bin directory
@ -596,12 +649,15 @@ export async function init(projectName = null, autoAcceptDefaults = false) {
console.log('\nInitializing git repository...');
execSync('git init', { cwd: projectPath });
execSync('git add .', { cwd: projectPath });
execSync('git commit -m "initial commit from @neynar/create-farcaster-mini-app"', { cwd: projectPath });
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 mini app ${finalProjectName} with git and dependencies installed! 🪐✨`;
const borderLength = message.length;
const borderStars = '✨'.repeat((borderLength / 2) + 1);
const borderStars = '✨'.repeat(borderLength / 2 + 1);
console.log(`\n${borderStars}`);
console.log(`${message}`);

View File

@ -1,4 +1,4 @@
import type { NextConfig } from "next";
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
/* config options here */

4302
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -35,6 +35,14 @@
"build:raw": "next build",
"start": "next start",
"lint": "next lint",
"lint:fix": "next lint --fix",
"lint:check": "next lint --max-warnings 0",
"format": "prettier --write .",
"format:check": "prettier --check .",
"format:fix": "prettier --write . && eslint --fix .",
"type-check": "tsc --noEmit",
"check": "npm run type-check && npm run lint:check && npm run format:check",
"prepare": "npm run check",
"deploy:vercel": "node scripts/deploy.js",
"deploy:raw": "vercel --prod",
"cleanup": "node scripts/cleanup.js"
@ -50,6 +58,13 @@
"devDependencies": {
"@neynar/nodejs-sdk": "^2.19.0",
"@types/node": "^22.13.10",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"eslint": "^8.57.0",
"eslint-config-next": "^15.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"prettier": "^3.3.3",
"typescript": "^5.6.3"
}
}

View File

@ -26,9 +26,9 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
{
headers: {
'accept': 'application/json',
'x-api-key': 'FARCASTER_V2_FRAMES_DEMO'
}
accept: 'application/json',
'x-api-key': 'FARCASTER_V2_FRAMES_DEMO',
},
}
);
@ -37,7 +37,10 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
}
const data = await response.json();
if (!data[lowerCasedCustodyAddress]?.length || !data[lowerCasedCustodyAddress][0].custody_address) {
if (
!data[lowerCasedCustodyAddress]?.length ||
!data[lowerCasedCustodyAddress][0].custody_address
) {
throw new Error('No FID found for this custody address');
}
@ -51,9 +54,10 @@ async function loadEnvLocal() {
{
type: 'confirm',
name: 'loadLocal',
message: 'Found .env.local, likely created by the install script - would you like to load its values?',
default: false
}
message:
'Found .env.local, likely created by the install script - would you like to load its values?',
default: false,
},
]);
if (loadLocal) {
@ -61,7 +65,9 @@ async function loadEnvLocal() {
const localEnv = dotenv.parse(fs.readFileSync('.env.local'));
// Copy all values except SEED_PHRASE to .env
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') + '\n' : '';
const envContent = fs.existsSync('.env')
? fs.readFileSync('.env', 'utf8') + '\n'
: '';
let newEnvContent = envContent;
for (const [key, value] of Object.entries(localEnv)) {
@ -104,7 +110,11 @@ async function validateDomain(domain) {
const cleanDomain = domain.replace(/^https?:\/\//, '');
// Basic domain validation
if (!cleanDomain.match(/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/)) {
if (
!cleanDomain.match(
/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/
)
) {
throw new Error('Invalid domain format');
}
@ -120,8 +130,8 @@ async function queryNeynarApp(apiKey) {
`https://api.neynar.com/portal/app_by_api_key`,
{
headers: {
'x-api-key': apiKey
}
'x-api-key': apiKey,
},
}
);
const data = await response.json();
@ -142,24 +152,36 @@ async function validateSeedPhrase(seedPhrase) {
}
}
async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase, webhookUrl) {
async function generateFarcasterMetadata(
domain,
fid,
accountAddress,
seedPhrase,
webhookUrl
) {
const header = {
type: 'custody',
key: accountAddress,
fid,
};
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString('base64');
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString(
'base64'
);
const payload = {
domain
domain,
};
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString(
'base64url'
);
const account = mnemonicToAccount(seedPhrase);
const signature = await account.signMessage({
message: `${encodedHeader}.${encodedPayload}`
message: `${encodedHeader}.${encodedPayload}`,
});
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
const encodedSignature = Buffer.from(signature, 'utf-8').toString(
'base64url'
);
const tags = process.env.NEXT_PUBLIC_MINI_APP_TAGS?.split(',');
@ -167,17 +189,17 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
accountAssociation: {
header: encodedHeader,
payload: encodedPayload,
signature: encodedSignature
signature: encodedSignature,
},
frame: {
version: "1",
version: '1',
name: process.env.NEXT_PUBLIC_MINI_APP_NAME,
iconUrl: `https://${domain}/icon.png`,
homeUrl: `https://${domain}`,
imageUrl: `https://${domain}/api/opengraph-image`,
buttonTitle: process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT,
splashImageUrl: `https://${domain}/splash.png`,
splashBackgroundColor: "#f7f7f7",
splashBackgroundColor: '#f7f7f7',
webhookUrl,
description: process.env.NEXT_PUBLIC_MINI_APP_DESCRIPTION,
primaryCategory: process.env.NEXT_PUBLIC_MINI_APP_PRIMARY_CATEGORY,
@ -199,16 +221,17 @@ async function main() {
{
type: 'input',
name: 'domain',
message: 'Enter the domain where your mini app will be deployed (e.g., example.com):',
validate: async (input) => {
message:
'Enter the domain where your mini app will be deployed (e.g., example.com):',
validate: async input => {
try {
await validateDomain(input);
return true;
} catch (error) {
return error.message;
}
}
}
},
},
]);
// Get frame name from user
@ -218,13 +241,13 @@ async function main() {
name: 'frameName',
message: 'Enter the name for your mini app (e.g., My Cool Mini App):',
default: process.env.NEXT_PUBLIC_MINI_APP_NAME,
validate: (input) => {
validate: input => {
if (input.trim() === '') {
return 'Mini app name cannot be empty';
}
return true;
}
}
},
},
]);
// Get button text from user
@ -233,14 +256,15 @@ async function main() {
type: 'input',
name: 'buttonText',
message: 'Enter the text for your mini app button:',
default: process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT || 'Launch Mini App',
validate: (input) => {
default:
process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT || 'Launch Mini App',
validate: input => {
if (input.trim() === '') {
return 'Button text cannot be empty';
}
return true;
}
}
},
},
]);
// Get Neynar configuration
@ -254,9 +278,10 @@ async function main() {
{
type: 'password',
name: 'neynarApiKey',
message: 'Enter your Neynar API key (optional - leave blank to skip):',
default: null
}
message:
'Enter your Neynar API key (optional - leave blank to skip):',
default: null,
},
]);
neynarApiKey = inputNeynarApiKey;
} else {
@ -284,14 +309,16 @@ async function main() {
}
// If we get here, the API key was invalid
console.log('\n⚠ Could not find Neynar app information. The API key may be incorrect.');
console.log(
'\n⚠ Could not find Neynar app information. The API key may be incorrect.'
);
const { retry } = await inquirer.prompt([
{
type: 'confirm',
name: 'retry',
message: 'Would you like to try a different API key?',
default: true
}
default: true,
},
]);
// Reset for retry
@ -311,18 +338,19 @@ 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 mini app manifest, then discarded${reset} ⚠️\n` +
'Seed phrase:',
validate: async (input) => {
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 mini app manifest, then discarded${reset} ⚠️\n` +
'Seed phrase:',
validate: async input => {
try {
await validateSeedPhrase(input);
return true;
} catch (error) {
return error.message;
}
}
}
},
},
]);
seedPhrase = inputSeedPhrase;
} else {
@ -333,22 +361,36 @@ async function main() {
const accountAddress = await validateSeedPhrase(seedPhrase);
console.log('✅ Generated account address from seed phrase');
const fid = await lookupFidByCustodyAddress(accountAddress, neynarApiKey ?? 'FARCASTER_V2_FRAMES_DEMO');
const fid = await lookupFidByCustodyAddress(
accountAddress,
neynarApiKey ?? 'FARCASTER_V2_FRAMES_DEMO'
);
// Generate and sign manifest
console.log('\n🔨 Generating mini app manifest...');
// Determine webhook URL based on environment variables
const webhookUrl = neynarApiKey && neynarClientId
? `https://api.neynar.com/f/app/${neynarClientId}/event`
: `${domain}/api/webhook`;
const webhookUrl =
neynarApiKey && neynarClientId
? `https://api.neynar.com/f/app/${neynarClientId}/event`
: `${domain}/api/webhook`;
const metadata = await generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase, webhookUrl);
console.log('\n✅ Mini app manifest generated' + (seedPhrase ? ' and signed' : ''));
const metadata = await generateFarcasterMetadata(
domain,
fid,
accountAddress,
seedPhrase,
webhookUrl
);
console.log(
'\n✅ Mini app manifest generated' + (seedPhrase ? ' and signed' : '')
);
// Read existing .env file or create new one
const envPath = path.join(projectRoot, '.env');
let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : '';
let envContent = fs.existsSync(envPath)
? fs.readFileSync(envPath, 'utf8')
: '';
// Add or update environment variables
const newEnvVars = [
@ -366,10 +408,10 @@ async function main() {
`NEXT_PUBLIC_ANALYTICS_ENABLED="${process.env.NEXT_PUBLIC_ANALYTICS_ENABLED || 'false'}"`,
// Neynar configuration (if it exists in current env)
...(process.env.NEYNAR_API_KEY ?
[`NEYNAR_API_KEY="${process.env.NEYNAR_API_KEY}"`] : []),
...(neynarClientId ?
[`NEYNAR_CLIENT_ID="${neynarClientId}"`] : []),
...(process.env.NEYNAR_API_KEY
? [`NEYNAR_API_KEY="${process.env.NEYNAR_API_KEY}"`]
: []),
...(neynarClientId ? [`NEYNAR_CLIENT_ID="${neynarClientId}"`] : []),
// FID (if it exists in current env)
...(process.env.FID ? [`FID="${process.env.FID}"`] : []),
@ -406,16 +448,21 @@ async function main() {
// Run next build
console.log('\nBuilding Next.js application...');
const nextBin = path.normalize(path.join(projectRoot, 'node_modules', '.bin', 'next'));
const nextBin = path.normalize(
path.join(projectRoot, 'node_modules', '.bin', 'next')
);
execSync(`"${nextBin}" build`, {
cwd: projectRoot,
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
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');
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) {
console.error('\n❌ Error:', error.message);
process.exit(1);

View File

@ -34,9 +34,9 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
{
headers: {
'accept': 'application/json',
'x-api-key': apiKey
}
accept: 'application/json',
'x-api-key': apiKey,
},
}
);
@ -45,32 +45,47 @@ async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
}
const data = await response.json();
if (!data[lowerCasedCustodyAddress]?.length || !data[lowerCasedCustodyAddress][0].custody_address) {
if (
!data[lowerCasedCustodyAddress]?.length ||
!data[lowerCasedCustodyAddress][0].custody_address
) {
throw new Error('No FID found for this custody address');
}
return data[lowerCasedCustodyAddress][0].fid;
}
async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase, webhookUrl) {
async function generateFarcasterMetadata(
domain,
fid,
accountAddress,
seedPhrase,
webhookUrl
) {
const trimmedDomain = domain.trim();
const header = {
type: 'custody',
key: accountAddress,
fid,
};
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString('base64');
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString(
'base64'
);
const payload = {
domain: trimmedDomain
domain: trimmedDomain,
};
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString(
'base64url'
);
const account = mnemonicToAccount(seedPhrase);
const signature = await account.signMessage({
message: `${encodedHeader}.${encodedPayload}`
message: `${encodedHeader}.${encodedPayload}`,
});
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
const encodedSignature = Buffer.from(signature, 'utf-8').toString(
'base64url'
);
const tags = process.env.NEXT_PUBLIC_MINI_APP_TAGS?.split(',');
@ -78,17 +93,17 @@ async function generateFarcasterMetadata(domain, fid, accountAddress, seedPhrase
accountAssociation: {
header: encodedHeader,
payload: encodedPayload,
signature: encodedSignature
signature: encodedSignature,
},
frame: {
version: "1",
version: '1',
name: process.env.NEXT_PUBLIC_MINI_APP_NAME,
iconUrl: `https://${trimmedDomain}/icon.png`,
homeUrl: `https://${trimmedDomain}`,
imageUrl: `https://${trimmedDomain}/api/opengraph-image`,
buttonTitle: process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT,
splashImageUrl: `https://${trimmedDomain}/splash.png`,
splashBackgroundColor: "#f7f7f7",
splashBackgroundColor: '#f7f7f7',
webhookUrl: webhookUrl?.trim(),
description: process.env.NEXT_PUBLIC_MINI_APP_DESCRIPTION,
primaryCategory: process.env.NEXT_PUBLIC_MINI_APP_PRIMARY_CATEGORY,
@ -104,9 +119,10 @@ async function loadEnvLocal() {
{
type: 'confirm',
name: 'loadLocal',
message: 'Found .env.local - would you like to load its values in addition to .env values? (except for SEED_PHRASE, values will be written to .env)',
default: true
}
message:
'Found .env.local - would you like to load its values in addition to .env values? (except for SEED_PHRASE, values will be written to .env)',
default: true,
},
]);
if (loadLocal) {
@ -122,10 +138,12 @@ async function loadEnvLocal() {
'NEXT_PUBLIC_MINI_APP_BUTTON_TEXT',
'NEXT_PUBLIC_ANALYTICS_ENABLED',
'NEYNAR_API_KEY',
'NEYNAR_CLIENT_ID'
'NEYNAR_CLIENT_ID',
];
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') + '\n' : '';
const envContent = fs.existsSync('.env')
? fs.readFileSync('.env', 'utf8') + '\n'
: '';
let newEnvContent = envContent;
for (const [key, value] of Object.entries(localEnv)) {
@ -157,20 +175,23 @@ async function checkRequiredEnvVars() {
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'
validate: input => input.trim() !== '' || 'Mini app name cannot be empty',
},
{
name: 'NEXT_PUBLIC_MINI_APP_BUTTON_TEXT',
message: 'Enter the text for your frame button:',
default: process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT ?? 'Launch Mini App',
validate: input => input.trim() !== '' || 'Button text cannot be empty'
}
default:
process.env.NEXT_PUBLIC_MINI_APP_BUTTON_TEXT ?? 'Launch Mini App',
validate: input => input.trim() !== '' || 'Button text cannot be empty',
},
];
const missingVars = requiredVars.filter(varConfig => !process.env[varConfig.name]);
const missingVars = requiredVars.filter(
varConfig => !process.env[varConfig.name]
);
if (missingVars.length > 0) {
console.log('\n⚠ Some required information is missing. Let\'s set it up:');
console.log("\n⚠ Some required information is missing. Let's set it up:");
for (const varConfig of missingVars) {
const { value } = await inquirer.prompt([
{
@ -178,17 +199,22 @@ async function checkRequiredEnvVars() {
name: 'value',
message: varConfig.message,
default: varConfig.default,
validate: varConfig.validate
}
validate: varConfig.validate,
},
]);
process.env[varConfig.name] = value;
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') : '';
const envContent = fs.existsSync('.env')
? fs.readFileSync('.env', 'utf8')
: '';
if (!envContent.includes(`${varConfig.name}=`)) {
const newLine = envContent ? '\n' : '';
fs.appendFileSync('.env', `${newLine}${varConfig.name}="${value.trim()}"`);
fs.appendFileSync(
'.env',
`${newLine}${varConfig.name}="${value.trim()}"`
);
}
}
}
@ -201,9 +227,10 @@ async function checkRequiredEnvVars() {
{
type: 'password',
name: 'seedPhrase',
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
}
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,
},
]);
if (seedPhrase) {
@ -213,9 +240,10 @@ async function checkRequiredEnvVars() {
{
type: 'confirm',
name: 'storeSeedPhrase',
message: 'Would you like to store this seed phrase in .env.local for future use?',
default: false
}
message:
'Would you like to store this seed phrase in .env.local for future use?',
default: false,
},
]);
if (storeSeedPhrase) {
@ -232,7 +260,7 @@ async function getGitRemote() {
try {
const remoteUrl = execSync('git remote get-url origin', {
cwd: projectRoot,
encoding: 'utf8'
encoding: 'utf8',
}).trim();
return remoteUrl;
} catch (error) {
@ -244,7 +272,7 @@ async function checkVercelCLI() {
try {
execSync('vercel --version', {
stdio: 'ignore',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
return true;
} catch (error) {
@ -256,7 +284,7 @@ async function installVercelCLI() {
console.log('Installing Vercel CLI...');
execSync('npm install -g vercel', {
stdio: 'inherit',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
}
@ -281,7 +309,7 @@ async function getVercelToken() {
try {
const whoamiOutput = execSync('vercel whoami', {
encoding: 'utf8',
stdio: 'pipe'
stdio: 'pipe',
});
// If we can get whoami, we're logged in, but we need the actual token
@ -289,7 +317,9 @@ async function getVercelToken() {
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.');
throw new Error(
'Not logged in to Vercel CLI. Please run this script again to login.'
);
}
}
@ -303,20 +333,24 @@ async function loginToVercel() {
console.log('2. Authorize GitHub access');
console.log('3. Complete the Vercel account setup in your browser');
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');
console.log(
'\nNote: you may need to cancel this script with ctrl+c and run it again if creating a new vercel account'
);
const child = spawn('vercel', ['login'], {
stdio: 'inherit'
stdio: 'inherit',
});
await new Promise((resolve, reject) => {
child.on('close', (code) => {
child.on('close', code => {
resolve();
});
});
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.');
console.log(
"If you're creating a new account, please complete the Vercel account setup in your browser first."
);
for (let i = 0; i < 150; i++) {
try {
@ -349,11 +383,11 @@ async function setVercelEnvVarSDK(vercelClient, projectId, key, value) {
// Get existing environment variables
const existingVars = await vercelClient.projects.getEnvironmentVariables({
idOrName: projectId
idOrName: projectId,
});
const existingVar = existingVars.envs?.find(env =>
env.key === key && env.target?.includes('production')
const existingVar = existingVars.envs?.find(
env => env.key === key && env.target?.includes('production')
);
if (existingVar) {
@ -363,8 +397,8 @@ async function setVercelEnvVarSDK(vercelClient, projectId, key, value) {
id: existingVar.id,
requestBody: {
value: processedValue,
target: ['production']
}
target: ['production'],
},
});
console.log(`✅ Updated environment variable: ${key}`);
} else {
@ -375,15 +409,18 @@ async function setVercelEnvVarSDK(vercelClient, projectId, key, value) {
key: key,
value: processedValue,
type: 'encrypted',
target: ['production']
}
target: ['production'],
},
});
console.log(`✅ Created environment variable: ${key}`);
}
return true;
} catch (error) {
console.warn(`⚠️ Warning: Failed to set environment variable ${key}:`, error.message);
console.warn(
`⚠️ Warning: Failed to set environment variable ${key}:`,
error.message
);
return false;
}
}
@ -395,7 +432,7 @@ async function setVercelEnvVarCLI(key, value, projectRoot) {
execSync(`vercel env rm ${key} production -y`, {
cwd: projectRoot,
stdio: 'ignore',
env: process.env
env: process.env,
});
} catch (error) {
// Ignore errors from removal
@ -424,7 +461,7 @@ async function setVercelEnvVarCLI(key, value, projectRoot) {
cwd: projectRoot,
stdio: 'pipe', // Changed from 'inherit' to avoid interactive prompts
shell: true,
env: process.env
env: process.env,
});
fs.unlinkSync(tempFilePath);
@ -435,12 +472,20 @@ async function setVercelEnvVarCLI(key, value, projectRoot) {
if (fs.existsSync(tempFilePath)) {
fs.unlinkSync(tempFilePath);
}
console.warn(`⚠️ Warning: Failed to set environment variable ${key}:`, error.message);
console.warn(
`⚠️ Warning: Failed to set environment variable ${key}:`,
error.message
);
return false;
}
}
async function setEnvironmentVariables(vercelClient, projectId, envVars, projectRoot) {
async function setEnvironmentVariables(
vercelClient,
projectId,
envVars,
projectRoot
) {
console.log('\n📝 Setting up environment variables...');
const results = [];
@ -468,7 +513,9 @@ async function setEnvironmentVariables(vercelClient, projectId, envVars, project
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.');
console.warn(
'\nYou may need to set these manually in the Vercel dashboard.'
);
}
return results;
@ -482,25 +529,38 @@ async function deployToVercel(useGitHub = false) {
const vercelConfigPath = path.join(projectRoot, 'vercel.json');
if (!fs.existsSync(vercelConfigPath)) {
console.log('📝 Creating vercel.json configuration...');
fs.writeFileSync(vercelConfigPath, JSON.stringify({
buildCommand: "next build",
framework: "nextjs"
}, null, 2));
fs.writeFileSync(
vercelConfigPath,
JSON.stringify(
{
buildCommand: 'next build',
framework: 'nextjs',
},
null,
2
)
);
}
// 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 mini app manifest\n');
console.log('\n⚠ Note: choosing a longer, more unique project name will help avoid conflicts with other existing domains\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',
shell: process.platform === 'win32'
shell: process.platform === 'win32',
});
// Load project info
const projectJson = JSON.parse(fs.readFileSync('.vercel/project.json', 'utf8'));
const projectJson = JSON.parse(
fs.readFileSync('.vercel/project.json', 'utf8')
);
const projectId = projectJson.projectId;
// Get Vercel token and initialize SDK client
@ -509,12 +569,14 @@ async function deployToVercel(useGitHub = false) {
const token = await getVercelToken();
if (token) {
vercelClient = new Vercel({
bearerToken: token
bearerToken: token,
});
console.log('✅ Initialized Vercel SDK client');
}
} catch (error) {
console.warn('⚠️ Could not initialize Vercel SDK, falling back to CLI operations');
console.warn(
'⚠️ Could not initialize Vercel SDK, falling back to CLI operations'
);
}
// Get project details
@ -525,22 +587,27 @@ async function deployToVercel(useGitHub = false) {
if (vercelClient) {
try {
const project = await vercelClient.projects.get({
idOrName: projectId
idOrName: projectId,
});
projectName = project.name;
domain = `${projectName}.vercel.app`;
console.log('🌐 Using project name for domain:', domain);
} catch (error) {
console.warn('⚠️ Could not get project details via SDK, using CLI fallback');
console.warn(
'⚠️ Could not get project details via SDK, using CLI fallback'
);
}
}
// Fallback to CLI method if SDK failed
if (!domain) {
const inspectOutput = execSync(`vercel project inspect ${projectId} 2>&1`, {
cwd: projectRoot,
encoding: 'utf8'
});
const inspectOutput = execSync(
`vercel project inspect ${projectId} 2>&1`,
{
cwd: projectRoot,
encoding: 'utf8',
}
);
const nameMatch = inspectOutput.match(/Name\s+([^\n]+)/);
if (nameMatch) {
@ -554,7 +621,9 @@ async function deployToVercel(useGitHub = false) {
domain = `${projectName}.vercel.app`;
console.log('🌐 Using project name for domain:', domain);
} else {
throw new Error('Could not determine project name from inspection output');
throw new Error(
'Could not determine project name from inspection output'
);
}
}
}
@ -565,36 +634,57 @@ async function deployToVercel(useGitHub = false) {
if (process.env.SEED_PHRASE) {
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');
fid = await lookupFidByCustodyAddress(
accountAddress,
process.env.NEYNAR_API_KEY ?? 'FARCASTER_V2_FRAMES_DEMO'
);
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`;
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`;
miniAppMetadata = await generateFarcasterMetadata(domain, fid, accountAddress, process.env.SEED_PHRASE, webhookUrl);
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 nextAuthSecret =
process.env.NEXTAUTH_SECRET || crypto.randomBytes(32).toString('hex');
const vercelEnv = {
NEXTAUTH_SECRET: nextAuthSecret,
AUTH_SECRET: nextAuthSecret,
NEXTAUTH_URL: `https://${domain}`,
NEXT_PUBLIC_URL: `https://${domain}`,
...(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 }),
...(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 }),
...Object.fromEntries(
Object.entries(process.env)
.filter(([key]) => key.startsWith('NEXT_PUBLIC_'))
)
Object.entries(process.env).filter(([key]) =>
key.startsWith('NEXT_PUBLIC_')
)
),
};
// Set environment variables
await setEnvironmentVariables(vercelClient, projectId, vercelEnv, projectRoot);
await setEnvironmentVariables(
vercelClient,
projectId,
vercelEnv,
projectRoot
);
// Deploy the project
if (useGitHub) {
@ -602,7 +692,7 @@ async function deployToVercel(useGitHub = false) {
execSync('vercel link', {
cwd: projectRoot,
stdio: 'inherit',
env: process.env
env: process.env,
});
console.log('\n📦 Deploying with GitHub integration...');
} else {
@ -612,7 +702,7 @@ async function deployToVercel(useGitHub = false) {
execSync('vercel deploy --prod', {
cwd: projectRoot,
stdio: 'inherit',
env: process.env
env: process.env,
});
// Verify actual domain after deployment
@ -623,7 +713,7 @@ async function deployToVercel(useGitHub = false) {
try {
const deployments = await vercelClient.deployments.list({
projectId: projectId,
limit: 1
limit: 1,
});
if (deployments.deployments?.[0]?.url) {
@ -631,7 +721,9 @@ async function deployToVercel(useGitHub = false) {
console.log('🌐 Verified actual domain:', actualDomain);
}
} catch (error) {
console.warn('⚠️ Could not verify domain via SDK, using assumed domain');
console.warn(
'⚠️ Could not verify domain via SDK, using assumed domain'
);
}
}
@ -639,27 +731,39 @@ async function deployToVercel(useGitHub = false) {
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 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}`
NEXT_PUBLIC_URL: `https://${actualDomain}`,
};
if (miniAppMetadata) {
const updatedMetadata = await generateFarcasterMetadata(actualDomain, fid, await validateSeedPhrase(process.env.SEED_PHRASE), process.env.SEED_PHRASE, webhookUrl);
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);
await setEnvironmentVariables(
vercelClient,
projectId,
updatedEnv,
projectRoot
);
console.log('\n📦 Redeploying with correct domain...');
execSync('vercel deploy --prod', {
cwd: projectRoot,
stdio: 'inherit',
env: process.env
env: process.env,
});
domain = actualDomain;
@ -667,8 +771,9 @@ async function deployToVercel(useGitHub = false) {
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');
console.log(
'\n📝 You can manage your project at https://vercel.com/dashboard'
);
} catch (error) {
console.error('\n❌ Deployment failed:', error.message);
process.exit(1);
@ -678,7 +783,9 @@ async function deployToVercel(useGitHub = false) {
async function main() {
try {
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(
'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)');
@ -692,7 +799,7 @@ async function main() {
console.log('📦 Installing @vercel/sdk...');
execSync('npm install @vercel/sdk', {
cwd: projectRoot,
stdio: 'inherit'
stdio: 'inherit',
});
console.log('✅ @vercel/sdk installed successfully');
}
@ -709,8 +816,8 @@ async function main() {
type: 'confirm',
name: 'useGitHubDeploy',
message: 'Would you like to deploy from the GitHub repository?',
default: true
}
default: true,
},
]);
useGitHub = useGitHubDeploy;
} else {
@ -722,10 +829,10 @@ async function main() {
message: 'What would you like to do?',
choices: [
{ name: 'Deploy local code directly', value: 'deploy' },
{ name: 'Set up GitHub repository first', value: 'setup' }
{ name: 'Set up GitHub repository first', value: 'setup' },
],
default: 'deploy'
}
default: 'deploy',
},
]);
if (action === 'setup') {
@ -739,18 +846,17 @@ async function main() {
}
}
if (!await checkVercelCLI()) {
if (!(await checkVercelCLI())) {
console.log('Vercel CLI not found. Installing...');
await installVercelCLI();
}
if (!await loginToVercel()) {
if (!(await loginToVercel())) {
console.error('\n❌ Failed to log in to Vercel. Please try again.');
process.exit(1);
}
await deployToVercel(useGitHub);
} catch (error) {
console.error('\n❌ Error:', error.message);
process.exit(1);

View File

@ -33,7 +33,7 @@ args.forEach((arg, index) => {
});
async function checkPort(port) {
return new Promise((resolve) => {
return new Promise(resolve => {
const server = createServer();
server.once('error', () => {
@ -54,29 +54,32 @@ async function killProcessOnPort(port) {
if (process.platform === 'win32') {
// Windows: Use netstat to find the process
const netstat = spawn('netstat', ['-ano', '|', 'findstr', `:${port}`]);
netstat.stdout.on('data', (data) => {
netstat.stdout.on('data', data => {
const match = data.toString().match(/\s+(\d+)$/);
if (match) {
const pid = match[1];
spawn('taskkill', ['/F', '/PID', pid]);
}
});
await new Promise((resolve) => netstat.on('close', resolve));
await new Promise(resolve => netstat.on('close', resolve));
} else {
// Unix-like systems: Use lsof
const lsof = spawn('lsof', ['-ti', `:${port}`]);
lsof.stdout.on('data', (data) => {
data.toString().split('\n').forEach(pid => {
if (pid) {
try {
process.kill(parseInt(pid), 'SIGKILL');
} catch (e) {
if (e.code !== 'ESRCH') throw e;
lsof.stdout.on('data', data => {
data
.toString()
.split('\n')
.forEach(pid => {
if (pid) {
try {
process.kill(parseInt(pid), 'SIGKILL');
} catch (e) {
if (e.code !== 'ESRCH') throw e;
}
}
}
});
});
});
await new Promise((resolve) => lsof.on('close', resolve));
await new Promise(resolve => lsof.on('close', resolve));
}
} catch (e) {
// Ignore errors if no process found
@ -87,13 +90,15 @@ async function startDev() {
// Check if the specified port is already in use
const isPortInUse = await checkPort(port);
if (isPortInUse) {
console.error(`Port ${port} is already in use. To find and kill the process using this port:\n\n` +
(process.platform === 'win32'
? `1. Run: netstat -ano | findstr :${port}\n` +
'2. Note the PID (Process ID) from the output\n' +
'3. Run: taskkill /PID <PID> /F\n'
: `On macOS/Linux, run:\nnpm run cleanup\n`) +
'\nThen try running this command again.');
console.error(
`Port ${port} is already in use. To find and kill the process using this port:\n\n` +
(process.platform === 'win32'
? `1. Run: netstat -ano | findstr :${port}\n` +
'2. Note the PID (Process ID) from the output\n' +
'3. Run: taskkill /PID <PID> /F\n'
: `On macOS/Linux, run:\nnpm run cleanup\n`) +
'\nThen try running this command again.'
);
process.exit(1);
}
@ -105,7 +110,9 @@ async function startDev() {
tunnel = await localtunnel({ port: port });
let ip;
try {
ip = await fetch('https://ipv4.icanhazip.com').then(res => res.text()).then(ip => ip.trim());
ip = await fetch('https://ipv4.icanhazip.com')
.then(res => res.text())
.then(ip => ip.trim());
} catch (error) {
console.error('Error getting IP address:', error);
}
@ -145,13 +152,19 @@ async function startDev() {
}
// Start next dev with appropriate configuration
const nextBin = path.normalize(path.join(projectRoot, 'node_modules', '.bin', 'next'));
const nextBin = path.normalize(
path.join(projectRoot, 'node_modules', '.bin', 'next')
);
nextDev = spawn(nextBin, ['dev', '-p', port.toString()], {
stdio: 'inherit',
env: { ...process.env, NEXT_PUBLIC_URL: miniAppUrl, NEXTAUTH_URL: miniAppUrl },
env: {
...process.env,
NEXT_PUBLIC_URL: miniAppUrl,
NEXTAUTH_URL: miniAppUrl,
},
cwd: projectRoot,
shell: process.platform === 'win32' // Add shell option for Windows
shell: process.platform === 'win32', // Add shell option for Windows
});
// Handle cleanup

View File

@ -1,6 +1,6 @@
import NextAuth from "next-auth"
import { authOptions } from "~/auth"
import NextAuth from 'next-auth';
import { authOptions } from '~/auth';
const handler = NextAuth(authOptions)
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }
export { handler as GET, handler as POST };

View File

@ -7,7 +7,10 @@ export async function GET(request: Request) {
if (!apiKey) {
return NextResponse.json(
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
{
error:
'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.',
},
{ status: 500 }
);
}
@ -24,7 +27,7 @@ export async function GET(request: Request) {
`https://api.neynar.com/v2/farcaster/user/best_friends?fid=${fid}&limit=3`,
{
headers: {
"x-api-key": apiKey,
'x-api-key': apiKey,
},
}
);
@ -33,13 +36,18 @@ export async function GET(request: Request) {
throw new Error(`Neynar API error: ${response.statusText}`);
}
const { users } = await response.json() as { users: { user: { fid: number; username: string } }[] };
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.' },
{
error:
'Failed to fetch best friends. Please check your Neynar API key and try again.',
},
{ status: 500 }
);
}

View File

@ -1,6 +1,6 @@
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
import { getNeynarUser } from "~/lib/neynar";
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import { getNeynarUser } from '~/lib/neynar';
export const dynamic = 'force-dynamic';
@ -15,10 +15,18 @@ export async function GET(request: NextRequest) {
<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" />
<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>
<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>
),

View File

@ -1,9 +1,9 @@
import { notificationDetailsSchema } from "@farcaster/frame-sdk";
import { NextRequest } from "next/server";
import { z } from "zod";
import { setUserNotificationDetails } from "~/lib/kv";
import { sendMiniAppNotification } from "~/lib/notifs";
import { sendNeynarMiniAppNotification } from "~/lib/neynar";
import { notificationDetailsSchema } from '@farcaster/frame-sdk';
import { NextRequest } from 'next/server';
import { z } from 'zod';
import { setUserNotificationDetails } from '~/lib/kv';
import { sendMiniAppNotification } from '~/lib/notifs';
import { sendNeynarMiniAppNotification } from '~/lib/neynar';
const requestSchema = z.object({
fid: z.number(),
@ -13,7 +13,8 @@ const requestSchema = z.object({
export async function POST(request: NextRequest) {
// If Neynar is enabled, we don't need to store notification details
// as they will be managed by Neynar's system
const neynarEnabled = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
const neynarEnabled =
process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
const requestJson = await request.json();
const requestBody = requestSchema.safeParse(requestJson);
@ -34,21 +35,23 @@ export async function POST(request: NextRequest) {
}
// Use appropriate notification function based on Neynar status
const sendNotification = neynarEnabled ? sendNeynarMiniAppNotification : sendMiniAppNotification;
const sendNotification = neynarEnabled
? sendNeynarMiniAppNotification
: sendMiniAppNotification;
const sendResult = await sendNotification({
fid: Number(requestBody.data.fid),
title: "Test notification",
body: "Sent at " + new Date().toISOString(),
title: 'Test notification',
body: 'Sent at ' + new Date().toISOString(),
});
if (sendResult.state === "error") {
if (sendResult.state === 'error') {
return Response.json(
{ success: false, error: sendResult.error },
{ status: 500 }
);
} else if (sendResult.state === "rate_limit") {
} else if (sendResult.state === 'rate_limit') {
return Response.json(
{ success: false, error: "Rate limited" },
{ success: false, error: 'Rate limited' },
{ status: 429 }
);
}

View File

@ -8,7 +8,10 @@ export async function GET(request: Request) {
if (!apiKey) {
return NextResponse.json(
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
{
error:
'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.',
},
{ status: 500 }
);
}
@ -32,7 +35,10 @@ export async function GET(request: Request) {
} 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.' },
{
error:
'Failed to fetch users. Please check your Neynar API key and try again.',
},
{ status: 500 }
);
}

View File

@ -2,19 +2,20 @@ import {
ParseWebhookEvent,
parseWebhookEvent,
verifyAppKeyWithNeynar,
} from "@farcaster/frame-node";
import { NextRequest } from "next/server";
import { APP_NAME } from "~/lib/constants";
} from '@farcaster/frame-node';
import { NextRequest } from 'next/server';
import { APP_NAME } from '~/lib/constants';
import {
deleteUserNotificationDetails,
setUserNotificationDetails,
} from "~/lib/kv";
import { sendMiniAppNotification } from "~/lib/notifs";
} from '~/lib/kv';
import { sendMiniAppNotification } from '~/lib/notifs';
export async function POST(request: NextRequest) {
// If Neynar is enabled, we don't need to handle webhooks here
// as they will be handled by Neynar's webhook endpoint
const neynarEnabled = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
const neynarEnabled =
process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
if (neynarEnabled) {
return Response.json({ success: true });
}
@ -28,20 +29,20 @@ export async function POST(request: NextRequest) {
const error = e as ParseWebhookEvent.ErrorType;
switch (error.name) {
case "VerifyJsonFarcasterSignature.InvalidDataError":
case "VerifyJsonFarcasterSignature.InvalidEventDataError":
case 'VerifyJsonFarcasterSignature.InvalidDataError':
case 'VerifyJsonFarcasterSignature.InvalidEventDataError':
// The request data is invalid
return Response.json(
{ success: false, error: error.message },
{ status: 400 }
);
case "VerifyJsonFarcasterSignature.InvalidAppKeyError":
case 'VerifyJsonFarcasterSignature.InvalidAppKeyError':
// The app key is invalid
return Response.json(
{ success: false, error: error.message },
{ status: 401 }
);
case "VerifyJsonFarcasterSignature.VerifyAppKeyError":
case 'VerifyJsonFarcasterSignature.VerifyAppKeyError':
// Internal error verifying the app key (caller may want to try again)
return Response.json(
{ success: false, error: error.message },
@ -56,33 +57,33 @@ export async function POST(request: NextRequest) {
// Only handle notifications if Neynar is not enabled
// When Neynar is enabled, notifications are handled through their webhook
switch (event.event) {
case "frame_added":
case 'frame_added':
if (event.notificationDetails) {
await setUserNotificationDetails(fid, event.notificationDetails);
await sendMiniAppNotification({
fid,
title: `Welcome to ${APP_NAME}`,
body: "Mini app is now added to your client",
body: 'Mini app is now added to your client',
});
} else {
await deleteUserNotificationDetails(fid);
}
break;
case "frame_removed":
case 'frame_removed':
await deleteUserNotificationDetails(fid);
break;
case "notifications_enabled":
case 'notifications_enabled':
await setUserNotificationDetails(fid, event.notificationDetails);
await sendMiniAppNotification({
fid,
title: `Welcome to ${APP_NAME}`,
body: "Notifications are now enabled",
body: 'Notifications are now enabled',
});
break;
case "notifications_disabled":
case 'notifications_disabled':
await deleteUserNotificationDetails(fid);
break;
}

View File

@ -1,10 +1,10 @@
"use client";
'use client';
import dynamic from "next/dynamic";
import { APP_NAME } from "~/lib/constants";
import dynamic from 'next/dynamic';
import { APP_NAME } from '~/lib/constants';
// note: dynamic import is required for components that use the Frame SDK
const AppComponent = dynamic(() => import("~/components/App"), {
const AppComponent = dynamic(() => import('~/components/App'), {
ssr: false,
});

View File

@ -1,9 +1,9 @@
import type { Metadata } from "next";
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";
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: APP_NAME,
@ -15,7 +15,7 @@ export default async function RootLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getSession()
const session = await getSession();
return (
<html lang="en">

View File

@ -1,7 +1,7 @@
import { Metadata } from "next";
import App from "./app";
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from "~/lib/constants";
import { getMiniAppEmbedMetadata } from "~/lib/utils";
import { Metadata } from 'next';
import App from './app';
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from '~/lib/constants';
import { getMiniAppEmbedMetadata } from '~/lib/utils';
export const revalidate = 300;
@ -14,11 +14,11 @@ export async function generateMetadata(): Promise<Metadata> {
images: [APP_OG_IMAGE_URL],
},
other: {
"fc:frame": JSON.stringify(getMiniAppEmbedMetadata()),
'fc:frame': JSON.stringify(getMiniAppEmbedMetadata()),
},
};
}
export default function Home() {
return (<App />);
return <App />;
}

View File

@ -1,25 +1,35 @@
"use client";
'use client';
import dynamic from "next/dynamic";
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";
import dynamic from 'next/dynamic';
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"),
() => import('~/components/providers/WagmiProvider'),
{
ssr: false,
}
);
export function Providers({ session, children }: { session: Session | null, children: React.ReactNode }) {
const solanaEndpoint = process.env.SOLANA_RPC_ENDPOINT || "https://solana-rpc.publicnode.com";
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>
<MiniAppProvider analyticsEnabled={ANALYTICS_ENABLED} backButtonEnabled={true}>
<MiniAppProvider
analyticsEnabled={ANALYTICS_ENABLED}
backButtonEnabled={true}
>
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
{children}
</SafeFarcasterSolanaProvider>

View File

@ -1,7 +1,7 @@
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";
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:
@ -23,12 +23,12 @@ export async function generateMetadata({
images: [imageUrl],
},
other: {
"fc:frame": JSON.stringify(getMiniAppEmbedMetadata(imageUrl)),
'fc:frame': JSON.stringify(getMiniAppEmbedMetadata(imageUrl)),
},
};
}
export default function SharePage() {
// redirect to home page
redirect("/");
redirect('/');
}

View File

@ -1,8 +1,8 @@
import { AuthOptions, getServerSession } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import { createAppClient, viemConnector } from "@farcaster/auth-client";
import { AuthOptions, getServerSession } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { createAppClient, viemConnector } from '@farcaster/auth-client';
declare module "next-auth" {
declare module 'next-auth' {
interface Session {
user: {
fid: number;
@ -26,34 +26,34 @@ function getDomainFromUrl(urlString: string | undefined): string {
}
export const authOptions: AuthOptions = {
// Configure one or more authentication providers
// Configure one or more authentication providers
providers: [
CredentialsProvider({
name: "Sign in with Farcaster",
name: 'Sign in with Farcaster',
credentials: {
message: {
label: "Message",
type: "text",
placeholder: "0x0",
label: 'Message',
type: 'text',
placeholder: '0x0',
},
signature: {
label: "Signature",
type: "text",
placeholder: "0x0",
label: 'Signature',
type: 'text',
placeholder: '0x0',
},
// In a production app with a server, these should be fetched from
// your Farcaster data indexer rather than have them accepted as part
// of credentials.
// question: should these natively use the Neynar API?
name: {
label: "Name",
type: "text",
placeholder: "0x0",
label: 'Name',
type: 'text',
placeholder: '0x0',
},
pfp: {
label: "Pfp",
type: "text",
placeholder: "0x0",
label: 'Pfp',
type: 'text',
placeholder: '0x0',
},
},
async authorize(credentials, req) {
@ -100,30 +100,30 @@ export const authOptions: AuthOptions = {
name: `next-auth.session-token`,
options: {
httpOnly: true,
sameSite: "none",
path: "/",
secure: true
}
sameSite: 'none',
path: '/',
secure: true,
},
},
callbackUrl: {
name: `next-auth.callback-url`,
options: {
sameSite: "none",
path: "/",
secure: true
}
sameSite: 'none',
path: '/',
secure: true,
},
},
csrfToken: {
name: `next-auth.csrf-token`,
options: {
httpOnly: true,
sameSite: "none",
path: "/",
secure: true
}
}
}
}
sameSite: 'none',
path: '/',
secure: true,
},
},
},
};
export const getSession = async () => {
try {
@ -132,4 +132,4 @@ export const getSession = async () => {
console.error('Error getting server session:', error);
return null;
}
}
};

View File

@ -1,19 +1,24 @@
"use client";
'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";
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",
Home = 'home',
Actions = 'actions',
Context = 'context',
Wallet = 'wallet',
}
export interface AppProps {
@ -50,16 +55,11 @@ export interface AppProps {
* ```
*/
export default function App(
{ title }: AppProps = { title: "Neynar Starter Kit" }
{ title }: AppProps = { title: 'Neynar Starter Kit' }
) {
// --- Hooks ---
const {
isSDKLoaded,
context,
setInitialTab,
setActiveTab,
currentTab,
} = useMiniApp();
const { isSDKLoaded, context, setInitialTab, setActiveTab, currentTab } =
useMiniApp();
// --- Neynar user hook ---
const { user: neynarUser } = useNeynarUser(context || undefined);
@ -115,9 +115,12 @@ export default function App(
{currentTab === Tab.Wallet && <WalletTab />}
{/* Footer with navigation */}
<Footer activeTab={currentTab as Tab} setActiveTab={setActiveTab} showWallet={USE_WALLET} />
<Footer
activeTab={currentTab as Tab}
setActiveTab={setActiveTab}
showWallet={USE_WALLET}
/>
</div>
</div>
);
}

View File

@ -1,9 +1,12 @@
import React, { createContext, useEffect, useState } from "react";
import dynamic from "next/dynamic";
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),
() =>
import('@farcaster/mini-app-solana').then(
mod => mod.FarcasterSolanaProvider
),
{ ssr: false }
);
@ -12,10 +15,15 @@ type SafeFarcasterSolanaProviderProps = {
children: React.ReactNode;
};
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({ hasSolanaProvider: false });
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({
hasSolanaProvider: false,
});
export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcasterSolanaProviderProps) {
const isClient = typeof window !== "undefined";
export function SafeFarcasterSolanaProvider({
endpoint,
children,
}: SafeFarcasterSolanaProviderProps) {
const isClient = typeof window !== 'undefined';
const [hasSolanaProvider, setHasSolanaProvider] = useState<boolean>(false);
const [checked, setChecked] = useState<boolean>(false);
@ -48,8 +56,8 @@ export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcaste
const origError = console.error;
console.error = (...args) => {
if (
typeof args[0] === "string" &&
args[0].includes("WalletConnectionError: could not get Solana provider")
typeof args[0] === 'string' &&
args[0].includes('WalletConnectionError: could not get Solana provider')
) {
if (!errorShown) {
origError(...args);

View File

@ -1,12 +1,12 @@
import { createConfig, http, WagmiProvider } from "wagmi";
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 { createConfig, http, WagmiProvider } from 'wagmi';
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";
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() {
@ -17,7 +17,8 @@ function useCoinbaseWalletAutoConnect() {
useEffect(() => {
// Check if we're running in Coinbase Wallet
const checkCoinbaseWallet = () => {
const isInCoinbaseWallet = window.ethereum?.isCoinbaseWallet ||
const isInCoinbaseWallet =
window.ethereum?.isCoinbaseWallet ||
window.ethereum?.isCoinbaseWalletExtension ||
window.ethereum?.isCoinbaseWalletBrowser;
setIsCoinbaseWallet(!!isInCoinbaseWallet);
@ -70,7 +71,11 @@ export const config = createConfig({
const queryClient = new QueryClient();
// Wrapper component that provides Coinbase Wallet auto-connection
function CoinbaseWalletAutoConnect({ children }: { children: React.ReactNode }) {
function CoinbaseWalletAutoConnect({
children,
}: {
children: React.ReactNode;
}) {
useCoinbaseWalletAutoConnect();
return <>{children}</>;
}
@ -79,9 +84,7 @@ export default function Provider({ children }: { children: React.ReactNode }) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<CoinbaseWalletAutoConnect>
{children}
</CoinbaseWalletAutoConnect>
<CoinbaseWalletAutoConnect>{children}</CoinbaseWalletAutoConnect>
</QueryClientProvider>
</WagmiProvider>
);

View File

@ -7,41 +7,38 @@ interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
export function Button({
children,
className = "",
className = '',
isLoading = false,
variant = 'primary',
size = 'md',
...props
}: ButtonProps) {
const baseClasses = "btn";
const baseClasses = 'btn';
const variantClasses = {
primary: "btn-primary",
secondary: "btn-secondary",
outline: "btn-outline"
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"
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 fullWidthClasses = 'w-full max-w-xs mx-auto block';
const combinedClasses = [
baseClasses,
variantClasses[variant],
sizeClasses[size],
fullWidthClasses,
className
className,
].join(' ');
return (
<button
className={combinedClasses}
{...props}
>
<button className={combinedClasses} {...props}>
{isLoading ? (
<div className="flex items-center justify-center">
<div className="spinner-primary h-5 w-5" />

View File

@ -1,5 +1,5 @@
import React from "react";
import { Tab } from "~/components/App";
import React from 'react';
import { Tab } from '~/components/App';
interface FooterProps {
activeTab: Tab;
@ -7,13 +7,19 @@ interface FooterProps {
showWallet?: boolean;
}
export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWallet = false }) => (
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'
activeTab === Tab.Home
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl">🏠</span>
@ -22,7 +28,9 @@ export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWal
<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'
activeTab === Tab.Actions
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl"></span>
@ -31,7 +39,9 @@ export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWal
<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'
activeTab === Tab.Context
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl">📋</span>
@ -41,7 +51,9 @@ export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWal
<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'
activeTab === Tab.Wallet
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl">👛</span>

View File

@ -1,9 +1,9 @@
"use client";
'use client';
import { useState } from "react";
import { APP_NAME } from "~/lib/constants";
import sdk from "@farcaster/frame-sdk";
import { useMiniApp } from "@neynar/react";
import { useState } from 'react';
import { APP_NAME } from '~/lib/constants';
import sdk from '@farcaster/frame-sdk';
import { useMiniApp } from '@neynar/react';
type HeaderProps = {
neynarUser?: {
@ -18,12 +18,8 @@ export function Header({ neynarUser }: HeaderProps) {
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>
<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"
@ -49,7 +45,9 @@ export function Header({ neynarUser }: HeaderProps) {
<div className="text-right">
<h3
className="font-bold text-sm hover:underline cursor-pointer inline-block"
onClick={() => sdk.actions.viewProfile({ fid: context.user.fid })}
onClick={() =>
sdk.actions.viewProfile({ fid: context.user.fid })
}
>
{context.user.displayName || context.user.username}
</h3>

View File

@ -3,7 +3,7 @@
import { useCallback, useState, useEffect } from 'react';
import { Button } from './Button';
import { useMiniApp } from '@neynar/react';
import { type ComposeCast } from "@farcaster/frame-sdk";
import { type ComposeCast } from '@farcaster/frame-sdk';
interface EmbedConfig {
path?: string;
@ -23,9 +23,16 @@ interface ShareButtonProps {
isLoading?: boolean;
}
export function ShareButton({ buttonText, cast, className = '', isLoading = false }: ShareButtonProps) {
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 [bestFriends, setBestFriends] = useState<
{ fid: number; username: string }[] | null
>(null);
const [isLoadingBestFriends, setIsLoadingBestFriends] = useState(false);
const { context, actions } = useMiniApp();
@ -51,7 +58,7 @@ export function ShareButton({ buttonText, cast, className = '', isLoading = fals
if (cast.bestFriends) {
if (bestFriends) {
// Replace @N with usernames, or remove if no matching friend
finalText = finalText.replace(/@\d+/g, (match) => {
finalText = finalText.replace(/@\d+/g, match => {
const friendIndex = parseInt(match.slice(1)) - 1;
const friend = bestFriends[friendIndex];
if (friend) {
@ -67,16 +74,20 @@ export function ShareButton({ buttonText, cast, className = '', isLoading = fals
// Process embeds
const processedEmbeds = await Promise.all(
(cast.embeds || []).map(async (embed) => {
(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 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'}`);
url.searchParams.set(
'utm_source',
`share-cast-${context?.user?.fid || 'unknown'}`
);
// If custom image generator is provided, use it
if (embed.imageUrl) {

View File

@ -1,22 +1,22 @@
import * as React from "react"
import * as React from 'react';
import { cn } from "~/lib/utils"
import { cn } from '~/lib/utils';
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-base ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-neutral-800 dark:bg-neutral-950 dark:ring-offset-neutral-950 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300",
'flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-base ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-neutral-800 dark:bg-neutral-950 dark:ring-offset-neutral-950 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300',
className
)}
ref={ref}
{...props}
/>
)
);
}
)
Input.displayName = "Input"
);
Input.displayName = 'Input';
export { Input }
export { Input };

View File

@ -1,14 +1,14 @@
"use client"
'use client';
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from "~/lib/utils"
import { cn } from '~/lib/utils';
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
@ -20,7 +20,7 @@ const Label = React.forwardRef<
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label }
export { Label };

View File

@ -1,11 +1,11 @@
"use client";
'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";
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.
@ -28,20 +28,16 @@ import { type Haptics } from "@farcaster/frame-sdk";
*/
export function ActionsTab() {
// --- Hooks ---
const {
actions,
added,
notificationDetails,
haptics,
context,
} = useMiniApp();
const { actions, added, notificationDetails, haptics, context } =
useMiniApp();
// --- State ---
const [notificationState, setNotificationState] = useState({
sendStatus: "",
sendStatus: '',
shareUrlCopied: false,
});
const [selectedHapticIntensity, setSelectedHapticIntensity] = useState<Haptics.ImpactOccurredType>('medium');
const [selectedHapticIntensity, setSelectedHapticIntensity] =
useState<Haptics.ImpactOccurredType>('medium');
// --- Handlers ---
/**
@ -54,31 +50,37 @@ export function ActionsTab() {
* @returns Promise that resolves when the notification is sent or fails
*/
const sendFarcasterNotification = useCallback(async () => {
setNotificationState((prev) => ({ ...prev, sendStatus: "" }));
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" },
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" }));
setNotificationState(prev => ({ ...prev, sendStatus: 'Success' }));
return;
} else if (response.status === 429) {
setNotificationState((prev) => ({ ...prev, sendStatus: "Rate limited" }));
setNotificationState(prev => ({ ...prev, sendStatus: 'Rate limited' }));
return;
}
const responseText = await response.text();
setNotificationState((prev) => ({ ...prev, sendStatus: `Error: ${responseText}` }));
setNotificationState(prev => ({
...prev,
sendStatus: `Error: ${responseText}`,
}));
} catch (error) {
setNotificationState((prev) => ({ ...prev, sendStatus: `Error: ${error}` }));
setNotificationState(prev => ({
...prev,
sendStatus: `Error: ${error}`,
}));
}
}, [context, notificationDetails]);
@ -92,8 +94,12 @@ export function ActionsTab() {
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);
setNotificationState(prev => ({ ...prev, shareUrlCopied: true }));
setTimeout(
() =>
setNotificationState(prev => ({ ...prev, shareUrlCopied: false })),
2000
);
}
}, [context?.user?.fid]);
@ -118,9 +124,11 @@ export function ActionsTab() {
<ShareButton
buttonText="Share Mini App"
cast={{
text: "Check out this awesome frame @1 @2 @3! 🚀🪐",
text: 'Check out this awesome frame @1 @2 @3! 🚀🪐',
bestFriends: true,
embeds: [`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`]
embeds: [
`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`,
],
}}
className="w-full"
/>
@ -129,7 +137,14 @@ export function ActionsTab() {
<SignIn />
{/* Mini app actions */}
<Button onClick={() => actions.openUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")} className="w-full">Open Link</Button>
<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
@ -141,7 +156,11 @@ export function ActionsTab() {
Send notification result: {notificationState.sendStatus}
</div>
)}
<Button onClick={sendFarcasterNotification} disabled={!notificationDetails} className="w-full">
<Button
onClick={sendFarcasterNotification}
disabled={!notificationDetails}
className="w-full"
>
Send notification
</Button>
@ -151,7 +170,7 @@ export function ActionsTab() {
disabled={!context?.user?.fid}
className="w-full"
>
{notificationState.shareUrlCopied ? "Copied!" : "Copy share URL"}
{notificationState.shareUrlCopied ? 'Copied!' : 'Copy share URL'}
</Button>
{/* Haptic feedback controls */}
@ -161,7 +180,11 @@ export function ActionsTab() {
</label>
<select
value={selectedHapticIntensity}
onChange={(e) => setSelectedHapticIntensity(e.target.value as Haptics.ImpactOccurredType)}
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>
@ -170,10 +193,7 @@ export function ActionsTab() {
<option value={'soft'}>Soft</option>
<option value={'rigid'}>Rigid</option>
</select>
<Button
onClick={triggerHapticFeedback}
className="w-full"
>
<Button onClick={triggerHapticFeedback} className="w-full">
Trigger Haptic Feedback
</Button>
</div>

View File

@ -1,6 +1,6 @@
"use client";
'use client';
import { useMiniApp } from "@neynar/react";
import { useMiniApp } from '@neynar/react';
/**
* ContextTab component displays the current mini app context in JSON format.

View File

@ -1,4 +1,4 @@
"use client";
'use client';
/**
* HomeTab component displays the main landing content for the mini app.

View File

@ -1,18 +1,28 @@
"use client";
'use client';
import { useCallback, useMemo, useState, useEffect } from "react";
import { useAccount, useSendTransaction, useSignTypedData, useWaitForTransactionReceipt, useDisconnect, useConnect, useSwitchChain, useChainId, type Connector } from "wagmi";
import { useCallback, useMemo, useState, useEffect } from 'react';
import {
useAccount,
useSendTransaction,
useSignTypedData,
useWaitForTransactionReceipt,
useDisconnect,
useConnect,
useSwitchChain,
useChainId,
type Connector,
} 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";
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.
@ -47,7 +57,8 @@ function WalletStatus({ address, chainId }: WalletStatusProps) {
<>
{address && (
<div className="text-xs w-full">
Address: <pre className="inline w-full">{truncateAddress(address)}</pre>
Address:{' '}
<pre className="inline w-full">{truncateAddress(address)}</pre>
</div>
)}
{chainId && (
@ -90,13 +101,19 @@ function ConnectionControls({
if (context) {
return (
<div className="space-y-2 w-full">
<Button onClick={() => connect({ connector: connectors[0] })} className="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}`));
console.log('Manual Farcaster connection attempt');
console.log(
'Connectors:',
connectors.map((c, i) => `${i}: ${c.name}`)
);
connect({ connector: connectors[0] });
}}
className="w-full"
@ -108,10 +125,16 @@ function ConnectionControls({
}
return (
<div className="space-y-3 w-full">
<Button onClick={() => connect({ connector: connectors[1] })} className="w-full">
<Button
onClick={() => connect({ connector: connectors[1] })}
className="w-full"
>
Connect Coinbase Wallet
</Button>
<Button onClick={() => connect({ connector: connectors[2] })} className="w-full">
<Button
onClick={() => connect({ connector: connectors[2] })}
className="w-full"
>
Connect MetaMask
</Button>
</div>
@ -120,7 +143,9 @@ function ConnectionControls({
export function WalletTab() {
// --- State ---
const [evmContractTransactionHash, setEvmContractTransactionHash] = useState<string | null>(null);
const [evmContractTransactionHash, setEvmContractTransactionHash] = useState<
string | null
>(null);
// --- Hooks ---
const { context } = useMiniApp();
@ -137,10 +162,12 @@ export function WalletTab() {
isPending: isEvmTransactionPending,
} = useSendTransaction();
const { isLoading: isEvmTransactionConfirming, isSuccess: isEvmTransactionConfirmed } =
useWaitForTransactionReceipt({
hash: evmContractTransactionHash as `0x${string}`,
});
const {
isLoading: isEvmTransactionConfirming,
isSuccess: isEvmTransactionConfirmed,
} = useWaitForTransactionReceipt({
hash: evmContractTransactionHash as `0x${string}`,
});
const {
signTypedData,
@ -169,31 +196,40 @@ export function WalletTab() {
*/
useEffect(() => {
// Check if we're in a Farcaster client environment
const isInFarcasterClient = typeof window !== 'undefined' &&
const isInFarcasterClient =
typeof window !== 'undefined' &&
(window.location.href.includes('warpcast.com') ||
window.location.href.includes('farcaster') ||
window.ethereum?.isFarcaster ||
context?.client);
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);
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);
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);
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]);
@ -235,11 +271,11 @@ export function WalletTab() {
sendTransaction(
{
// call yoink() on Yoink contract
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
data: "0x9846cd9efc000023c0",
to: '0x4bBFD120d9f352A0BEd7a014bd67913a2007a878',
data: '0x9846cd9efc000023c0',
},
{
onSuccess: (hash) => {
onSuccess: hash => {
setEvmContractTransactionHash(hash);
},
}
@ -256,16 +292,16 @@ export function WalletTab() {
signTypedData({
domain: {
name: APP_NAME,
version: "1",
version: '1',
chainId,
},
types: {
Message: [{ name: "content", type: "string" }],
Message: [{ name: 'content', type: 'string' }],
},
message: {
content: `Hello from ${APP_NAME}!`,
},
primaryType: "Message",
primaryType: 'Message',
});
}, [chainId, signTypedData]);
@ -308,12 +344,12 @@ export function WalletTab() {
<div className="text-xs w-full">
<div>Hash: {truncateAddress(evmContractTransactionHash)}</div>
<div>
Status:{" "}
Status:{' '}
{isEvmTransactionConfirming
? "Confirming..."
? 'Confirming...'
: isEvmTransactionConfirmed
? "Confirmed!"
: "Pending"}
? 'Confirmed!'
: 'Pending'}
</div>
</div>
)}

View File

@ -1,11 +1,15 @@
"use client";
'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";
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.
@ -36,10 +40,12 @@ export function SendEth() {
isPending: isEthTransactionPending,
} = useSendTransaction();
const { isLoading: isEthTransactionConfirming, isSuccess: isEthTransactionConfirmed } =
useWaitForTransactionReceipt({
hash: ethTransactionHash,
});
const {
isLoading: isEthTransactionConfirming,
isSuccess: isEthTransactionConfirmed,
} = useWaitForTransactionReceipt({
hash: ethTransactionHash,
});
// --- Computed Values ---
/**
@ -54,8 +60,8 @@ export function SendEth() {
const protocolGuildRecipientAddress = useMemo(() => {
// Protocol guild address
return chainId === base.id
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
? '0x32e3C7fD24e175701A35c224f2238d18439C7dBC'
: '0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830';
}, [chainId]);
// --- Handlers ---
@ -88,12 +94,12 @@ export function SendEth() {
<div className="mt-2 text-xs">
<div>Hash: {truncateAddress(ethTransactionHash)}</div>
<div>
Status:{" "}
Status:{' '}
{isEthTransactionConfirming
? "Confirming..."
? 'Confirming...'
: isEthTransactionConfirmed
? "Confirmed!"
: "Pending"}
? 'Confirmed!'
: 'Pending'}
</div>
</div>
)}

View File

@ -1,11 +1,14 @@
"use client";
'use client';
import { useCallback, useState } from "react";
import { useConnection as useSolanaConnection, useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
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";
import { Button } from '../Button';
import { truncateAddress } from '../../../lib/truncateAddress';
import { renderError } from '../../../lib/errorUtils';
/**
* SendSolana component handles sending SOL transactions on Solana.
@ -42,7 +45,8 @@ export function SendSolana() {
// This should be replaced but including it from the original demo
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx#L718
const ashoatsPhantomSolanaWallet = 'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
const ashoatsPhantomSolanaWallet =
'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
/**
* Handles sending the Solana transaction
@ -67,12 +71,13 @@ export function SendSolana() {
fromPubkey: new PublicKey(fromPubkeyStr),
toPubkey: new PublicKey(toPubkeyStr),
lamports: 0n,
}),
})
);
transaction.recentBlockhash = blockhash;
transaction.feePayer = new PublicKey(fromPubkeyStr);
const simulation = await solanaConnection.simulateTransaction(transaction);
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';
@ -100,7 +105,8 @@ export function SendSolana() {
>
Send Transaction (sol)
</Button>
{solanaTransactionState.status === 'error' && renderError(solanaTransactionState.error)}
{solanaTransactionState.status === 'error' &&
renderError(solanaTransactionState.error)}
{solanaTransactionState.status === 'success' && (
<div className="mt-2 text-xs">
<div>Hash: {truncateAddress(solanaTransactionState.signature)}</div>

View File

@ -1,12 +1,12 @@
"use client";
'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";
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.

View File

@ -1,10 +1,10 @@
"use client";
'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";
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).
@ -55,7 +55,7 @@ export function SignIn() {
*/
const getNonce = useCallback(async () => {
const nonce = await getCsrfToken();
if (!nonce) throw new Error("Unable to generate nonce");
if (!nonce) throw new Error('Unable to generate nonce');
return nonce;
}, []);
@ -72,24 +72,24 @@ export function SignIn() {
*/
const handleSignIn = useCallback(async () => {
try {
setAuthState((prev) => ({ ...prev, signingIn: true }));
setAuthState(prev => ({ ...prev, signingIn: true }));
setSignInFailure(undefined);
const nonce = await getNonce();
const result = await sdk.actions.signIn({ nonce });
setSignInResult(result);
await signIn("credentials", {
await signIn('credentials', {
message: result.message,
signature: result.signature,
redirect: false,
});
} catch (e) {
if (e instanceof SignInCore.RejectedByUser) {
setSignInFailure("Rejected by user");
setSignInFailure('Rejected by user');
return;
}
setSignInFailure("Unknown error");
setSignInFailure('Unknown error');
} finally {
setAuthState((prev) => ({ ...prev, signingIn: false }));
setAuthState(prev => ({ ...prev, signingIn: false }));
}
}, [getNonce]);
@ -103,11 +103,11 @@ export function SignIn() {
*/
const handleSignOut = useCallback(async () => {
try {
setAuthState((prev) => ({ ...prev, signingOut: true }));
setAuthState(prev => ({ ...prev, signingOut: true }));
await signOut({ redirect: false });
setSignInResult(undefined);
} finally {
setAuthState((prev) => ({ ...prev, signingOut: false }));
setAuthState(prev => ({ ...prev, signingOut: false }));
}
}, []);
@ -115,12 +115,12 @@ export function SignIn() {
return (
<>
{/* Authentication Buttons */}
{status !== "authenticated" && (
{status !== 'authenticated' && (
<Button onClick={handleSignIn} disabled={authState.signingIn}>
Sign In with Farcaster
</Button>
)}
{status === "authenticated" && (
{status === 'authenticated' && (
<Button onClick={handleSignOut} disabled={authState.signingOut}>
Sign out
</Button>

View File

@ -1,8 +1,8 @@
"use client";
'use client';
import { useCallback, useState } from "react";
import { Button } from "../Button";
import { renderError } from "../../../lib/errorUtils";
import { useCallback, useState } from 'react';
import { Button } from '../Button';
import { renderError } from '../../../lib/errorUtils';
interface SignSolanaMessageProps {
signMessage?: (message: Uint8Array) => Promise<Uint8Array>;
@ -51,7 +51,7 @@ export function SignSolanaMessage({ signMessage }: SignSolanaMessageProps) {
if (!signMessage) {
throw new Error('no Solana signMessage');
}
const input = new TextEncoder().encode("Hello from Solana!");
const input = new TextEncoder().encode('Hello from Solana!');
const signatureBytes = await signMessage(input);
const signature = btoa(String.fromCharCode(...signatureBytes));
setSignature(signature);

View File

@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useState } from 'react';
export interface NeynarUser {
fid: number;
@ -19,18 +19,19 @@ export function useNeynarUser(context?: { user?: { fid?: number } }) {
setLoading(true);
setError(null);
fetch(`/api/users?fids=${context.user.fid}`)
.then((response) => {
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
.then(response => {
if (!response.ok)
throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
})
.then((data) => {
.then(data => {
if (data.users?.[0]) {
setUser(data.users[0]);
} else {
setUser(null);
}
})
.catch((err) => setError(err.message))
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, [context?.user?.fid]);

View File

@ -63,7 +63,7 @@ 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";
export const APP_SPLASH_BACKGROUND_COLOR = '#f7f7f7';
// --- UI Configuration ---
/**
@ -80,7 +80,8 @@ export const APP_BUTTON_TEXT = 'Launch NSK';
* 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
export const APP_WEBHOOK_URL =
process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
: `${APP_URL}/api/webhook`;

View File

@ -1,5 +1,5 @@
import { type ReactElement } from "react";
import { BaseError, UserRejectedRequestError } from "viem";
import { type ReactElement } from 'react';
import { BaseError, UserRejectedRequestError } from 'viem';
/**
* Renders an error object in a user-friendly format.
@ -31,7 +31,7 @@ export function renderError(error: unknown): ReactElement | null {
// Special handling for user rejections in wallet operations
if (error instanceof BaseError) {
const isUserRejection = error.walk(
(e) => e instanceof UserRejectedRequestError
e => e instanceof UserRejectedRequestError
);
if (isUserRejection) {

View File

@ -1,16 +1,18 @@
import { FrameNotificationDetails } from "@farcaster/frame-sdk";
import { Redis } from "@upstash/redis";
import { APP_NAME } from "./constants";
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>();
// Use Redis if KV env vars are present, otherwise use in-memory
const useRedis = process.env.KV_REST_API_URL && process.env.KV_REST_API_TOKEN;
const redis = useRedis ? new Redis({
url: process.env.KV_REST_API_URL!,
token: process.env.KV_REST_API_TOKEN!,
}) : null;
const redis = useRedis
? new Redis({
url: process.env.KV_REST_API_URL!,
token: process.env.KV_REST_API_TOKEN!,
})
: null;
function getUserNotificationDetailsKey(fid: number): string {
return `${APP_NAME}:user:${fid}`;

View File

@ -1,4 +1,8 @@
import { NeynarAPIClient, Configuration, WebhookUserCreated } from '@neynar/nodejs-sdk';
import {
NeynarAPIClient,
Configuration,
WebhookUserCreated,
} from '@neynar/nodejs-sdk';
import { APP_URL } from './constants';
let neynarClient: NeynarAPIClient | null = null;
@ -33,12 +37,12 @@ export async function getNeynarUser(fid: number): Promise<User | null> {
type SendMiniAppNotificationResult =
| {
state: "error";
state: 'error';
error: unknown;
}
| { state: "no_token" }
| { state: "rate_limit" }
| { state: "success" };
| { state: 'no_token' }
| { state: 'rate_limit' }
| { state: 'success' };
export async function sendNeynarMiniAppNotification({
fid,
@ -60,17 +64,17 @@ export async function sendNeynarMiniAppNotification({
const result = await client.publishFrameNotifications({
targetFids,
notification
notification,
});
if (result.notification_deliveries.length > 0) {
return { state: "success" };
return { state: 'success' };
} else if (result.notification_deliveries.length === 0) {
return { state: "no_token" };
return { state: 'no_token' };
} else {
return { state: "error", error: result || "Unknown error" };
return { state: 'error', error: result || 'Unknown error' };
}
} catch (error) {
return { state: "error", error };
return { state: 'error', error };
}
}

View File

@ -1,18 +1,18 @@
import {
SendNotificationRequest,
sendNotificationResponseSchema,
} from "@farcaster/frame-sdk";
import { getUserNotificationDetails } from "~/lib/kv";
import { APP_URL } from "./constants";
} from '@farcaster/frame-sdk';
import { getUserNotificationDetails } from '~/lib/kv';
import { APP_URL } from './constants';
type SendMiniAppNotificationResult =
| {
state: "error";
state: 'error';
error: unknown;
}
| { state: "no_token" }
| { state: "rate_limit" }
| { state: "success" };
| { state: 'no_token' }
| { state: 'rate_limit' }
| { state: 'success' };
export async function sendMiniAppNotification({
fid,
@ -25,13 +25,13 @@ export async function sendMiniAppNotification({
}): Promise<SendMiniAppNotificationResult> {
const notificationDetails = await getUserNotificationDetails(fid);
if (!notificationDetails) {
return { state: "no_token" };
return { state: 'no_token' };
}
const response = await fetch(notificationDetails.url, {
method: "POST",
method: 'POST',
headers: {
"Content-Type": "application/json",
'Content-Type': 'application/json',
},
body: JSON.stringify({
notificationId: crypto.randomUUID(),
@ -48,17 +48,17 @@ export async function sendMiniAppNotification({
const responseBody = sendNotificationResponseSchema.safeParse(responseJson);
if (responseBody.success === false) {
// Malformed response
return { state: "error", error: responseBody.error.errors };
return { state: 'error', error: responseBody.error.errors };
}
if (responseBody.data.result.rateLimitedTokens.length) {
// Rate limited
return { state: "rate_limit" };
return { state: 'rate_limit' };
}
return { state: "success" };
return { state: 'success' };
} else {
// Error response
return { state: "error", error: responseJson };
return { state: 'error', error: responseJson };
}
}

View File

@ -1,4 +1,4 @@
export const truncateAddress = (address: string) => {
if (!address) return "";
if (!address) return '';
return `${address.slice(0, 14)}...${address.slice(-12)}`;
};

View File

@ -1,7 +1,18 @@
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_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 MiniAppMetadata {
@ -17,7 +28,7 @@ interface MiniAppMetadata {
description?: string;
primaryCategory?: string;
tags?: string[];
};
}
interface MiniAppManifest {
accountAssociation?: {
@ -45,12 +56,12 @@ export function getSecretEnvVars() {
export function getMiniAppEmbedMetadata(ogImageUrl?: string) {
return {
version: "next",
version: 'next',
imageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
button: {
title: APP_BUTTON_TEXT,
action: {
type: "launch_frame",
type: 'launch_frame',
name: APP_NAME,
url: APP_URL,
splashImageUrl: APP_SPLASH_URL,
@ -72,7 +83,10 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
console.log('Using pre-signed mini app metadata from environment');
return metadata;
} catch (error) {
console.warn('Failed to parse MINI_APP_METADATA from environment:', error);
console.warn(
'Failed to parse MINI_APP_METADATA from environment:',
error
);
}
}
@ -86,7 +100,9 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
const secretEnvVars = getSecretEnvVars();
if (!secretEnvVars) {
console.warn('No seed phrase or FID found in environment variables -- generating unsigned metadata');
console.warn(
'No seed phrase or FID found in environment variables -- generating unsigned metadata'
);
}
let accountAssociation;
@ -100,34 +116,41 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
type: 'custody',
key: custodyAddress,
};
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString('base64');
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString(
'base64'
);
const payload = {
domain
domain,
};
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
const encodedPayload = Buffer.from(
JSON.stringify(payload),
'utf-8'
).toString('base64url');
const signature = await account.signMessage({
message: `${encodedHeader}.${encodedPayload}`
message: `${encodedHeader}.${encodedPayload}`,
});
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
const encodedSignature = Buffer.from(signature, 'utf-8').toString(
'base64url'
);
accountAssociation = {
header: encodedHeader,
payload: encodedPayload,
signature: encodedSignature
signature: encodedSignature,
};
}
return {
accountAssociation,
frame: {
version: "1",
name: APP_NAME ?? "Neynar Starter Kit",
version: '1',
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",
buttonTitle: APP_BUTTON_TEXT ?? 'Launch Mini App',
splashImageUrl: APP_SPLASH_URL,
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
webhookUrl: APP_WEBHOOK_URL,

View File

@ -1,4 +1,4 @@
import type { Config } from "tailwindcss";
import type { Config } from 'tailwindcss';
/**
* Tailwind CSS Configuration
@ -13,48 +13,48 @@ import type { Config } from "tailwindcss";
* - Orange theme: primary: "#EA580C"
*/
export default {
darkMode: "media",
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
darkMode: 'media',
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
],
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
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
// 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)'
},
borderRadius: {
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',
}
}
// Legacy CSS variables for backward compatibility
background: 'var(--background)',
foreground: 'var(--foreground)',
},
borderRadius: {
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',
},
},
},
plugins: [require("tailwindcss-animate")],
plugins: [require('tailwindcss-animate')],
} satisfies Config;