mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-11 11:52:35 -05:00
Compare commits
118 Commits
arthur/ney
...
shreyas/ne
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76ad200a22 | ||
|
|
86b79e7f3f | ||
|
|
aac3a739cd | ||
|
|
f20f65f966 | ||
|
|
a287d55641 | ||
|
|
53d6ce6a94 | ||
|
|
ebb8068ade | ||
|
|
8124fe5f6c | ||
|
|
9ea40a5f92 | ||
|
|
e61bc88aaa | ||
|
|
8eabbd3ba1 | ||
|
|
f7392dc3cb | ||
|
|
bf563154ca | ||
|
|
196378daeb | ||
|
|
89f82253ca | ||
|
|
c786cabe84 | ||
|
|
760efdb96b | ||
|
|
5fd0e21532 | ||
|
|
0d43b35c28 | ||
|
|
349cdea489 | ||
|
|
181c364de4 | ||
|
|
78626c2dc7 | ||
|
|
b72198575a | ||
|
|
b1fdfc19a9 | ||
|
|
4ba9480832 | ||
|
|
378ea65154 | ||
|
|
b366d97b53 | ||
|
|
16c433a13c | ||
|
|
b9e2087bd8 | ||
|
|
86029b2bd9 | ||
|
|
5fbd9c5c09 | ||
|
|
3815f45b44 | ||
|
|
c713d53054 | ||
|
|
d10bee4d4c | ||
|
|
44d0c6f905 | ||
|
|
4f308d3f07 | ||
|
|
4b370746cb | ||
|
|
00fdd21044 | ||
|
|
8475b28107 | ||
|
|
e74b2581df | ||
|
|
505aa54b16 | ||
|
|
8de3f598b7 | ||
|
|
fb4f8b8b53 | ||
|
|
5fa624a063 | ||
|
|
36d2b5d0f7 | ||
|
|
73617a18f2 | ||
|
|
d487a3e8e5 | ||
|
|
5724c92b88 | ||
|
|
c7583b2ffe | ||
|
|
8ff7080e84 | ||
|
|
e0ca42169b | ||
|
|
2d259d22b0 | ||
|
|
16896db17c | ||
|
|
f4c6f16712 | ||
|
|
4715edabb7 | ||
|
|
7b431677dc | ||
|
|
797c5b7154 | ||
|
|
96bb45ede0 | ||
|
|
6a7d1424e9 | ||
|
|
a7eb3fd716 | ||
|
|
45f8b980b9 | ||
|
|
8c2603098a | ||
|
|
5dcdd05c0a | ||
|
|
7de86c4a15 | ||
|
|
718d365221 | ||
|
|
822db9101f | ||
|
|
485c190695 | ||
|
|
65419a76ee | ||
|
|
f898e23299 | ||
|
|
1d736d823e | ||
|
|
bed12bd303 | ||
|
|
bbc8d81613 | ||
|
|
cc84b0a882 | ||
|
|
ea52f72a73 | ||
|
|
822147d0c7 | ||
|
|
6b0350d477 | ||
|
|
2a1a3d7c40 | ||
|
|
193dffe03a | ||
|
|
4884ac402d | ||
|
|
f42a5f8d33 | ||
|
|
f92becd789 | ||
|
|
8563812b4f | ||
|
|
02146b4ff5 | ||
|
|
1fe4d30134 | ||
|
|
56517dc41a | ||
|
|
0ee5cace75 | ||
|
|
857125035f | ||
|
|
ab42334f2c | ||
|
|
e6654a5e5b | ||
|
|
4fbcbdba6f | ||
|
|
1093eb64a1 | ||
|
|
1648971d15 | ||
|
|
6f0300fd7c | ||
|
|
e20a2a397d | ||
|
|
bef42eddd4 | ||
|
|
3a9f2cf8b8 | ||
|
|
4301252202 | ||
|
|
2b85800ba7 | ||
|
|
9f5d80fddd | ||
|
|
601f20bca3 | ||
|
|
e349724267 | ||
|
|
f97a697f88 | ||
|
|
4831308983 | ||
|
|
cfe51f067c | ||
|
|
8966dcee30 | ||
|
|
6a056cb30c | ||
|
|
7263cdef0e | ||
|
|
21ccdf3623 | ||
|
|
42152c3492 | ||
|
|
3bf80740c0 | ||
|
|
39437af6f0 | ||
|
|
7b87bc4dfa | ||
|
|
5420b8fca0 | ||
|
|
9cd07170b9 | ||
|
|
3e1acfce42 | ||
|
|
0b139f184d | ||
|
|
16a3e69a43 | ||
|
|
7df556740d |
@@ -4,3 +4,8 @@ KV_REST_API_TOKEN=''
|
|||||||
KV_REST_API_URL=''
|
KV_REST_API_URL=''
|
||||||
NEXT_PUBLIC_URL='http://localhost:3000'
|
NEXT_PUBLIC_URL='http://localhost:3000'
|
||||||
NEXTAUTH_URL='http://localhost:3000'
|
NEXTAUTH_URL='http://localhost:3000'
|
||||||
|
|
||||||
|
NEXTAUTH_SECRET=""
|
||||||
|
NEYNAR_API_KEY=""
|
||||||
|
NEYNAR_CLIENT_ID=""
|
||||||
|
USE_TUNNEL="false"
|
||||||
|
|||||||
30
.github/workflows/publish.yml
vendored
Normal file
30
.github/workflows/publish.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: Publish to npm 🚀
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- package.json
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
env:
|
||||||
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Publish to npm
|
||||||
|
run: npm publish --access public
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Farcaster Mini Apps (formerly Frames) Quickstart by Neynar 🪐
|
# Farcaster Mini Apps (formerly Frames v2) Quickstart by Neynar 🪐
|
||||||
|
|
||||||
A Farcaster Mini Apps quickstart npx script.
|
A Farcaster Mini Apps quickstart npx script.
|
||||||
|
|
||||||
|
|||||||
56
bin/index.js
56
bin/index.js
@@ -2,7 +2,61 @@
|
|||||||
|
|
||||||
import { init } from './init.js';
|
import { init } from './init.js';
|
||||||
|
|
||||||
init().catch((err) => {
|
// Parse command line arguments
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
let projectName = null;
|
||||||
|
let autoAcceptDefaults = false;
|
||||||
|
let apiKey = null;
|
||||||
|
|
||||||
|
// Check for -y flag
|
||||||
|
const yIndex = args.indexOf('-y');
|
||||||
|
if (yIndex !== -1) {
|
||||||
|
autoAcceptDefaults = true;
|
||||||
|
args.splice(yIndex, 1); // Remove -y from args
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse other arguments
|
||||||
|
for (let i = 0; i < args.length; i++) {
|
||||||
|
const arg = args[i];
|
||||||
|
|
||||||
|
if (arg === '-p' || arg === '--project') {
|
||||||
|
if (i + 1 < args.length) {
|
||||||
|
projectName = args[i + 1];
|
||||||
|
if (projectName.startsWith('-')) {
|
||||||
|
console.error('Error: Project name cannot start with a dash (-)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
args.splice(i, 2); // Remove both the flag and its value
|
||||||
|
i--; // Adjust index since we removed 2 elements
|
||||||
|
} else {
|
||||||
|
console.error('Error: -p/--project requires a project name');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} else if (arg === '-k' || arg === '--api-key') {
|
||||||
|
if (i + 1 < args.length) {
|
||||||
|
apiKey = args[i + 1];
|
||||||
|
if (apiKey.startsWith('-')) {
|
||||||
|
console.error('Error: API key cannot start with a dash (-)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
args.splice(i, 2); // Remove both the flag and its value
|
||||||
|
i--; // Adjust index since we removed 2 elements
|
||||||
|
} else {
|
||||||
|
console.error('Error: -k/--api-key requires an API key');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Validate that if -y is used, a project name must be provided
|
||||||
|
if (autoAcceptDefaults && !projectName) {
|
||||||
|
console.error('Error: -y flag requires a project name. Use -p/--project to specify the project name.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
init(projectName, autoAcceptDefaults, apiKey).catch((err) => {
|
||||||
console.error('Error:', err);
|
console.error('Error:', err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
486
bin/init.js
486
bin/init.js
@@ -12,7 +12,9 @@ const __filename = fileURLToPath(import.meta.url);
|
|||||||
const __dirname = dirname(__filename);
|
const __dirname = dirname(__filename);
|
||||||
|
|
||||||
const REPO_URL = 'https://github.com/neynarxyz/create-farcaster-mini-app.git';
|
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
|
// ANSI color codes
|
||||||
const purple = '\x1b[35m';
|
const purple = '\x1b[35m';
|
||||||
@@ -27,7 +29,7 @@ function printWelcomeMessage() {
|
|||||||
console.log(`
|
console.log(`
|
||||||
${purple}╔═══════════════════════════════════════════════════╗${reset}
|
${purple}╔═══════════════════════════════════════════════════╗${reset}
|
||||||
${purple}║ ║${reset}
|
${purple}║ ║${reset}
|
||||||
${purple}║${reset} ${bright}Welcome to Mini Apps Quickstart by Neynar${reset} ${purple}║${reset}
|
${purple}║${reset} ${bright}Welcome to the Neynar Starter Kit${reset} ${purple}║${reset}
|
||||||
${purple}║${reset} ${dim}the quickest way to build Farcaster mini apps${reset} ${purple}║${reset}
|
${purple}║${reset} ${dim}the quickest way to build Farcaster mini apps${reset} ${purple}║${reset}
|
||||||
${purple}║ ║${reset}
|
${purple}║ ║${reset}
|
||||||
${purple}╚═══════════════════════════════════════════════════╝${reset}
|
${purple}╚═══════════════════════════════════════════════════╝${reset}
|
||||||
@@ -48,8 +50,8 @@ async function queryNeynarApp(apiKey) {
|
|||||||
`https://api.neynar.com/portal/app_by_api_key?starter_kit=true`,
|
`https://api.neynar.com/portal/app_by_api_key?starter_kit=true`,
|
||||||
{
|
{
|
||||||
headers: {
|
headers: {
|
||||||
'x-api-key': apiKey
|
'x-api-key': apiKey,
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
@@ -61,7 +63,7 @@ async function queryNeynarApp(apiKey) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Export the main CLI function for programmatic use
|
// Export the main CLI function for programmatic use
|
||||||
export async function init() {
|
export async function init(projectName = null, autoAcceptDefaults = false, apiKey = null) {
|
||||||
printWelcomeMessage();
|
printWelcomeMessage();
|
||||||
|
|
||||||
// Ask about Neynar usage
|
// Ask about Neynar usage
|
||||||
@@ -72,11 +74,16 @@ export async function init() {
|
|||||||
let neynarAppLogoUrl = null;
|
let neynarAppLogoUrl = null;
|
||||||
|
|
||||||
while (useNeynar) {
|
while (useNeynar) {
|
||||||
const neynarAnswers = await inquirer.prompt([
|
let neynarAnswers;
|
||||||
|
if (autoAcceptDefaults) {
|
||||||
|
neynarAnswers = { useNeynar: true };
|
||||||
|
} else {
|
||||||
|
neynarAnswers = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'confirm',
|
type: 'confirm',
|
||||||
name: 'useNeynar',
|
name: 'useNeynar',
|
||||||
message: '🪐 Neynar is an API that makes it easy to build on Farcaster.\n\n' +
|
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' +
|
'Benefits of using Neynar in your mini app:\n' +
|
||||||
'- Pre-configured webhook handling (no setup required)\n' +
|
'- Pre-configured webhook handling (no setup required)\n' +
|
||||||
'- Automatic mini app analytics in your dev portal\n' +
|
'- Automatic mini app analytics in your dev portal\n' +
|
||||||
@@ -84,53 +91,87 @@ export async function init() {
|
|||||||
'- Built-in rate limiting and error handling\n\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` +
|
`${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?',
|
'Would you like to use Neynar in your mini app?',
|
||||||
default: true
|
default: true,
|
||||||
}
|
},
|
||||||
]);
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
if (!neynarAnswers.useNeynar) {
|
if (!neynarAnswers.useNeynar) {
|
||||||
useNeynar = false;
|
useNeynar = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const neynarKeyAnswer = await inquirer.prompt([
|
// Use provided API key if available, otherwise prompt for it
|
||||||
|
if (apiKey) {
|
||||||
|
neynarApiKey = apiKey;
|
||||||
|
} else {
|
||||||
|
if (!autoAcceptDefaults) {
|
||||||
|
console.log(
|
||||||
|
'\n🪐 Find your Neynar API key at: https://dev.neynar.com/app\n'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let neynarKeyAnswer;
|
||||||
|
if (autoAcceptDefaults) {
|
||||||
|
neynarKeyAnswer = { neynarApiKey: null };
|
||||||
|
} else {
|
||||||
|
neynarKeyAnswer = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'password',
|
type: 'password',
|
||||||
name: 'neynarApiKey',
|
name: 'neynarApiKey',
|
||||||
message: 'Enter your Neynar API key (or press enter to skip):',
|
message: 'Enter your Neynar API key (or press enter to skip):',
|
||||||
default: null
|
default: null,
|
||||||
}
|
},
|
||||||
]);
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
if (neynarKeyAnswer.neynarApiKey) {
|
if (neynarKeyAnswer.neynarApiKey) {
|
||||||
neynarApiKey = neynarKeyAnswer.neynarApiKey;
|
neynarApiKey = neynarKeyAnswer.neynarApiKey;
|
||||||
} else {
|
} else {
|
||||||
const useDemoKey = await inquirer.prompt([
|
let useDemoKey;
|
||||||
|
if (autoAcceptDefaults) {
|
||||||
|
useDemoKey = { useDemo: true };
|
||||||
|
} else {
|
||||||
|
useDemoKey = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'confirm',
|
type: 'confirm',
|
||||||
name: 'useDemo',
|
name: 'useDemo',
|
||||||
message: 'Would you like to try the demo Neynar API key?',
|
message: 'Would you like to try the demo Neynar API key?',
|
||||||
default: true
|
default: true,
|
||||||
}
|
},
|
||||||
]);
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
if (useDemoKey.useDemo) {
|
if (useDemoKey.useDemo) {
|
||||||
console.warn('\n⚠️ Note: the demo key is for development purposes only and is aggressively rate limited.');
|
console.warn(
|
||||||
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.');
|
'\n⚠️ Note: the demo key is for development purposes only and is aggressively rate limited.'
|
||||||
console.log(`\n${purple}${bright}${italic}Neynar now has a free tier! See https://neynar.com/#pricing for details.\n${reset}`);
|
);
|
||||||
|
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';
|
neynarApiKey = 'FARCASTER_V2_FRAMES_DEMO';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!neynarApiKey) {
|
if (!neynarApiKey) {
|
||||||
console.log('\n⚠️ No valid API key provided. Would you like to try again?');
|
if (autoAcceptDefaults) {
|
||||||
|
useNeynar = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
'\n⚠️ No valid API key provided. Would you like to try again?'
|
||||||
|
);
|
||||||
const { retry } = await inquirer.prompt([
|
const { retry } = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'confirm',
|
type: 'confirm',
|
||||||
name: 'retry',
|
name: 'retry',
|
||||||
message: 'Try configuring Neynar again?',
|
message: 'Try configuring Neynar again?',
|
||||||
default: true
|
default: true,
|
||||||
}
|
},
|
||||||
]);
|
]);
|
||||||
if (!retry) {
|
if (!retry) {
|
||||||
useNeynar = false;
|
useNeynar = false;
|
||||||
@@ -147,13 +188,18 @@ export async function init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!neynarClientId) {
|
if (!neynarClientId) {
|
||||||
|
if (autoAcceptDefaults) {
|
||||||
|
useNeynar = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
const { retry } = await inquirer.prompt([
|
const { retry } = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'confirm',
|
type: 'confirm',
|
||||||
name: 'retry',
|
name: 'retry',
|
||||||
message: '⚠️ Could not find a client ID for this API key. Would you like to try configuring Neynar again?',
|
message:
|
||||||
default: true
|
'⚠️ Could not find a client ID for this API key. Would you like to try configuring Neynar again?',
|
||||||
}
|
default: true,
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
if (!retry) {
|
if (!retry) {
|
||||||
useNeynar = false;
|
useNeynar = false;
|
||||||
@@ -166,31 +212,54 @@ export async function init() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultFrameName = (neynarAppName && !neynarAppName.toLowerCase().includes('demo')) ? neynarAppName : undefined;
|
const defaultMiniAppName =
|
||||||
|
neynarAppName && !neynarAppName.toLowerCase().includes('demo')
|
||||||
|
? neynarAppName
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const answers = await inquirer.prompt([
|
let answers;
|
||||||
|
if (autoAcceptDefaults) {
|
||||||
|
answers = {
|
||||||
|
projectName: projectName || defaultMiniAppName || 'my-farcaster-mini-app',
|
||||||
|
description: 'A Farcaster mini app created with Neynar',
|
||||||
|
primaryCategory: null,
|
||||||
|
tags: [],
|
||||||
|
buttonText: 'Launch Mini App',
|
||||||
|
useWallet: true,
|
||||||
|
useTunnel: true,
|
||||||
|
enableAnalytics: true,
|
||||||
|
seedPhrase: null,
|
||||||
|
useSponsoredSigner: false,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options
|
||||||
|
const projectNamePrompt = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'input',
|
type: 'input',
|
||||||
name: 'projectName',
|
name: 'projectName',
|
||||||
message: 'What is the name of your mini app?',
|
message: 'What is the name of your mini app?',
|
||||||
default: defaultFrameName,
|
default: projectName || defaultMiniAppName,
|
||||||
validate: (input) => {
|
validate: (input) => {
|
||||||
if (input.trim() === '') {
|
if (input.trim() === '') {
|
||||||
return 'Project name cannot be empty';
|
return 'Project name cannot be empty';
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
answers = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'input',
|
type: 'input',
|
||||||
name: 'description',
|
name: 'description',
|
||||||
message: 'Give a one-line description of your mini app (optional):',
|
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',
|
type: 'list',
|
||||||
name: 'primaryCategory',
|
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: [
|
choices: [
|
||||||
new inquirer.Separator(),
|
new inquirer.Separator(),
|
||||||
{ name: 'Skip (not recommended)', value: null },
|
{ name: 'Skip (not recommended)', value: null },
|
||||||
@@ -207,23 +276,24 @@ export async function init() {
|
|||||||
{ name: 'Education', value: 'education' },
|
{ name: 'Education', value: 'education' },
|
||||||
{ name: 'Developer Tools', value: 'developer-tools' },
|
{ name: 'Developer Tools', value: 'developer-tools' },
|
||||||
{ name: 'Entertainment', value: 'entertainment' },
|
{ name: 'Entertainment', value: 'entertainment' },
|
||||||
{ name: 'Art & Creativity', value: 'art-creativity' }
|
{ name: 'Art & Creativity', value: 'art-creativity' },
|
||||||
],
|
],
|
||||||
default: null
|
default: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'input',
|
type: 'input',
|
||||||
name: 'tags',
|
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: '',
|
default: '',
|
||||||
filter: (input) => {
|
filter: (input) => {
|
||||||
if (!input.trim()) return [];
|
if (!input.trim()) return [];
|
||||||
// Split by both spaces and commas, trim whitespace, and filter out empty strings
|
// Split by both spaces and commas, trim whitespace, and filter out empty strings
|
||||||
return input
|
return input
|
||||||
.split(/[,\s]+/)
|
.split(/[,\s]+/)
|
||||||
.map(tag => tag.trim())
|
.map((tag) => tag.trim())
|
||||||
.filter(tag => tag.length > 0);
|
.filter((tag) => tag.length > 0);
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'input',
|
type: 'input',
|
||||||
@@ -235,25 +305,91 @@ export async function init() {
|
|||||||
return 'Button text cannot be empty';
|
return 'Button text cannot be empty';
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Merge project name from the first prompt
|
||||||
|
answers.projectName = projectNamePrompt.projectName;
|
||||||
|
|
||||||
|
// Ask about wallet and transaction tooling
|
||||||
|
const walletAnswer = await inquirer.prompt([
|
||||||
|
{
|
||||||
|
type: 'confirm',
|
||||||
|
name: 'useWallet',
|
||||||
|
message:
|
||||||
|
'Would you like to include wallet and transaction tooling in your mini app?\n' +
|
||||||
|
'This includes:\n' +
|
||||||
|
'- EVM wallet connection\n' +
|
||||||
|
'- Transaction signing\n' +
|
||||||
|
'- Message signing\n' +
|
||||||
|
'- Chain switching\n' +
|
||||||
|
'- Solana support\n\n' +
|
||||||
|
'Include wallet and transaction features?',
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
answers.useWallet = walletAnswer.useWallet;
|
||||||
|
|
||||||
// Ask about localhost vs tunnel
|
// Ask about localhost vs tunnel
|
||||||
const hostingAnswer = await inquirer.prompt([
|
const hostingAnswer = await inquirer.prompt([
|
||||||
{
|
{
|
||||||
type: 'confirm',
|
type: 'confirm',
|
||||||
name: 'useTunnel',
|
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}` +
|
`⚠️ ${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?',
|
'Configure a tunnel for mobile testing and/or Warpcast developer tools?',
|
||||||
default: true
|
default: true,
|
||||||
}
|
},
|
||||||
]);
|
]);
|
||||||
answers.useTunnel = hostingAnswer.useTunnel;
|
answers.useTunnel = hostingAnswer.useTunnel;
|
||||||
|
|
||||||
const projectName = answers.projectName;
|
// Ask about Neynar Sponsored Signers / SIWN
|
||||||
const projectDirName = projectName.replace(/\s+/g, '-').toLowerCase();
|
const sponsoredSignerAnswer = await inquirer.prompt([
|
||||||
|
{
|
||||||
|
type: 'confirm',
|
||||||
|
name: 'useSponsoredSigner',
|
||||||
|
message:
|
||||||
|
'Would you like to write data to Farcaster on behalf of your miniapp users? This involves using Neynar Sponsored Signers and SIWN.\n' +
|
||||||
|
'\n⚠️ A seed phrase is required for this option.\n',
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
answers.useSponsoredSigner = sponsoredSignerAnswer.useSponsoredSigner;
|
||||||
|
|
||||||
|
if (answers.useSponsoredSigner) {
|
||||||
|
const { seedPhrase } = await inquirer.prompt([
|
||||||
|
{
|
||||||
|
type: 'password',
|
||||||
|
name: 'seedPhrase',
|
||||||
|
message: 'Enter your Farcaster custody account seed phrase (required for Neynar Sponsored Signers/SIWN):',
|
||||||
|
validate: (input) => {
|
||||||
|
if (!input || input.trim().split(' ').length < 12) {
|
||||||
|
return 'Seed phrase must be at least 12 words';
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
answers.seedPhrase = seedPhrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ask about analytics opt-out
|
||||||
|
const analyticsAnswer = await inquirer.prompt([
|
||||||
|
{
|
||||||
|
type: 'confirm',
|
||||||
|
name: 'enableAnalytics',
|
||||||
|
message:
|
||||||
|
'Would you like to help improve Neynar products by sharing usage data from your mini app?',
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
answers.enableAnalytics = analyticsAnswer.enableAnalytics;
|
||||||
|
}
|
||||||
|
|
||||||
|
const finalProjectName = answers.projectName;
|
||||||
|
const projectDirName = finalProjectName.replace(/\s+/g, '-').toLowerCase();
|
||||||
const projectPath = path.join(process.cwd(), projectDirName);
|
const projectPath = path.join(process.cwd(), projectDirName);
|
||||||
|
|
||||||
console.log(`\nCreating a new mini app in ${projectPath}`);
|
console.log(`\nCreating a new mini app in ${projectPath}`);
|
||||||
@@ -264,17 +400,17 @@ export async function init() {
|
|||||||
// Use separate commands for better cross-platform compatibility
|
// Use separate commands for better cross-platform compatibility
|
||||||
execSync(`git clone ${REPO_URL} "${projectPath}"`, {
|
execSync(`git clone ${REPO_URL} "${projectPath}"`, {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
shell: process.platform === 'win32'
|
shell: process.platform === 'win32',
|
||||||
});
|
});
|
||||||
execSync('git fetch origin main', {
|
execSync('git fetch origin main', {
|
||||||
cwd: projectPath,
|
cwd: projectPath,
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
shell: process.platform === 'win32'
|
shell: process.platform === 'win32',
|
||||||
});
|
});
|
||||||
execSync('git reset --hard origin/main', {
|
execSync('git reset --hard origin/main', {
|
||||||
cwd: projectPath,
|
cwd: projectPath,
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
shell: process.platform === 'win32'
|
shell: process.platform === 'win32',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('\n❌ Error: Failed to create project directory.');
|
console.error('\n❌ Error: Failed to create project directory.');
|
||||||
@@ -298,7 +434,7 @@ export async function init() {
|
|||||||
const packageJsonPath = path.join(projectPath, 'package.json');
|
const packageJsonPath = path.join(projectPath, 'package.json');
|
||||||
let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
||||||
|
|
||||||
packageJson.name = projectName;
|
packageJson.name = finalProjectName;
|
||||||
packageJson.version = '0.1.0';
|
packageJson.version = '0.1.0';
|
||||||
delete packageJson.author;
|
delete packageJson.author;
|
||||||
delete packageJson.keywords;
|
delete packageJson.keywords;
|
||||||
@@ -310,38 +446,41 @@ export async function init() {
|
|||||||
delete packageJson.devDependencies;
|
delete packageJson.devDependencies;
|
||||||
|
|
||||||
// Add dependencies
|
// Add dependencies
|
||||||
|
// question: remove auth-client?
|
||||||
packageJson.dependencies = {
|
packageJson.dependencies = {
|
||||||
"@farcaster/auth-client": ">=0.3.0 <1.0.0",
|
'@farcaster/auth-client': '>=0.3.0 <1.0.0',
|
||||||
"@farcaster/auth-kit": ">=0.6.0 <1.0.0",
|
'@farcaster/miniapp-node': '>=0.1.5 <1.0.0',
|
||||||
"@farcaster/frame-core": ">=0.0.29 <1.0.0",
|
'@farcaster/miniapp-sdk': '>=0.1.6 <1.0.0',
|
||||||
"@farcaster/frame-node": ">=0.0.18 <1.0.0",
|
'@farcaster/miniapp-wagmi-connector': '^1.0.0',
|
||||||
"@farcaster/frame-sdk": ">=0.0.31 <1.0.0",
|
'@farcaster/mini-app-solana': '>=0.0.17 <1.0.0',
|
||||||
"@farcaster/frame-wagmi-connector": ">=0.0.19 <1.0.0",
|
'@farcaster/quick-auth': '>=0.0.7 <1.0.0',
|
||||||
"@farcaster/mini-app-solana": "^0.0.5",
|
'@neynar/react': '^1.2.5',
|
||||||
"@radix-ui/react-label": "^2.1.1",
|
'@radix-ui/react-label': '^2.1.1',
|
||||||
"@solana/wallet-adapter-react": "^0.15.38",
|
'@solana/wallet-adapter-react': '^0.15.38',
|
||||||
"@tanstack/react-query": "^5.61.0",
|
'@tanstack/react-query': '^5.61.0',
|
||||||
"@upstash/redis": "^1.34.3",
|
'@upstash/redis': '^1.34.3',
|
||||||
"class-variance-authority": "^0.7.1",
|
'class-variance-authority': '^0.7.1',
|
||||||
"clsx": "^2.1.1",
|
clsx: '^2.1.1',
|
||||||
"dotenv": "^16.4.7",
|
dotenv: '^16.4.7',
|
||||||
"lucide-react": "^0.469.0",
|
'lucide-react': '^0.469.0',
|
||||||
"mipd": "^0.0.7",
|
mipd: '^0.0.7',
|
||||||
"next": "15.0.3",
|
next: '^15',
|
||||||
"next-auth": "^4.24.11",
|
react: '^19',
|
||||||
"react": "^18",
|
'react-dom': '^19',
|
||||||
"react-dom": "^18",
|
'tailwind-merge': '^2.6.0',
|
||||||
"tailwind-merge": "^2.6.0",
|
'tailwindcss-animate': '^1.0.7',
|
||||||
"tailwindcss-animate": "^1.0.7",
|
viem: '^2.23.6',
|
||||||
"viem": "^2.23.6",
|
wagmi: '^2.14.12',
|
||||||
"wagmi": "^2.14.12",
|
zod: '^3.24.2',
|
||||||
"zod": "^3.24.2"
|
siwe: '^3.0.0',
|
||||||
};
|
};
|
||||||
|
|
||||||
packageJson.devDependencies = {
|
packageJson.devDependencies = {
|
||||||
|
"@types/inquirer": "^9.0.8",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^18",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^18",
|
"@types/react-dom": "^19",
|
||||||
|
"@vercel/sdk": "^1.9.0",
|
||||||
"crypto": "^1.0.1",
|
"crypto": "^1.0.1",
|
||||||
"eslint": "^8",
|
"eslint": "^8",
|
||||||
"eslint-config-next": "15.0.3",
|
"eslint-config-next": "15.0.3",
|
||||||
@@ -349,13 +488,19 @@ export async function init() {
|
|||||||
"pino-pretty": "^13.0.0",
|
"pino-pretty": "^13.0.0",
|
||||||
"postcss": "^8",
|
"postcss": "^8",
|
||||||
"tailwindcss": "^3.4.1",
|
"tailwindcss": "^3.4.1",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add Neynar dependencies if selected
|
// Add Neynar SDK if selected
|
||||||
if (useNeynar) {
|
if (useNeynar) {
|
||||||
packageJson.dependencies['@neynar/nodejs-sdk'] = '^2.19.0';
|
packageJson.dependencies['@neynar/nodejs-sdk'] = '^2.19.0';
|
||||||
packageJson.dependencies['@neynar/react'] = '^0.9.7';
|
}
|
||||||
|
|
||||||
|
// Add auth-kit and next-auth dependencies if useSponsoredSigner is true
|
||||||
|
if (answers.useSponsoredSigner) {
|
||||||
|
packageJson.dependencies['@farcaster/auth-kit'] = '>=0.6.0 <1.0.0';
|
||||||
|
packageJson.dependencies['next-auth'] = '^4.24.11';
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
|
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
|
||||||
@@ -370,25 +515,149 @@ export async function init() {
|
|||||||
// Write it to .env.local
|
// Write it to .env.local
|
||||||
fs.writeFileSync(envPath, envExampleContent);
|
fs.writeFileSync(envPath, envExampleContent);
|
||||||
|
|
||||||
// Append all remaining environment variables
|
// Append remaining environment variables
|
||||||
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_NAME="${answers.projectName}"`);
|
// Update constants.ts file with user-provided values
|
||||||
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_DESCRIPTION="${answers.description}"`);
|
console.log('\nUpdating constants.ts...');
|
||||||
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_PRIMARY_CATEGORY="${answers.primaryCategory}"`);
|
const constantsPath = path.join(projectPath, 'src', 'lib', 'constants.ts');
|
||||||
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_TAGS="${answers.tags.join(',')}"`);
|
if (fs.existsSync(constantsPath)) {
|
||||||
fs.appendFileSync(envPath, `\nNEXT_PUBLIC_FRAME_BUTTON_TEXT="${answers.buttonText}"`);
|
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
|
||||||
fs.appendFileSync(envPath, `\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`);
|
|
||||||
|
// Helper function to escape single quotes in strings
|
||||||
|
const escapeString = (str) => str.replace(/'/g, "\\'");
|
||||||
|
|
||||||
|
// Helper function to safely replace constants with validation
|
||||||
|
const safeReplace = (content, pattern, replacement, constantName) => {
|
||||||
|
const match = content.match(pattern);
|
||||||
|
if (!match) {
|
||||||
|
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'
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const newContent = content.replace(pattern, replacement);
|
||||||
|
return newContent;
|
||||||
|
}
|
||||||
|
return content;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Regex patterns that match whole lines with export const (with TypeScript types)
|
||||||
|
const patterns = {
|
||||||
|
APP_NAME: /^export const APP_NAME\s*:\s*string\s*=\s*['"`][^'"`]*['"`];$/m,
|
||||||
|
APP_DESCRIPTION:
|
||||||
|
/^export const APP_DESCRIPTION\s*:\s*string\s*=\s*['"`][^'"`]*['"`];$/m,
|
||||||
|
APP_PRIMARY_CATEGORY:
|
||||||
|
/^export const APP_PRIMARY_CATEGORY\s*:\s*string\s*=\s*['"`][^'"`]*['"`];$/m,
|
||||||
|
APP_TAGS: /^export const APP_TAGS\s*:\s*string\[\]\s*=\s*\[[^\]]*\];$/m,
|
||||||
|
APP_BUTTON_TEXT:
|
||||||
|
/^export const APP_BUTTON_TEXT\s*:\s*string\s*=\s*['"`][^'"`]*['"`];$/m,
|
||||||
|
USE_WALLET: /^export const USE_WALLET\s*:\s*boolean\s*=\s*(true|false);$/m,
|
||||||
|
ANALYTICS_ENABLED:
|
||||||
|
/^export const ANALYTICS_ENABLED\s*:\s*boolean\s*=\s*(true|false);$/m,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update APP_NAME
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.APP_NAME,
|
||||||
|
`export const APP_NAME = '${escapeString(answers.projectName)}';`,
|
||||||
|
'APP_NAME'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update APP_DESCRIPTION
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.APP_DESCRIPTION,
|
||||||
|
`export const APP_DESCRIPTION = '${escapeString(
|
||||||
|
answers.description
|
||||||
|
)}';`,
|
||||||
|
'APP_DESCRIPTION'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update APP_PRIMARY_CATEGORY (always update, null becomes empty string)
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.APP_PRIMARY_CATEGORY,
|
||||||
|
`export const APP_PRIMARY_CATEGORY = '${escapeString(
|
||||||
|
answers.primaryCategory || ''
|
||||||
|
)}';`,
|
||||||
|
'APP_PRIMARY_CATEGORY'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update APP_TAGS
|
||||||
|
const tagsString =
|
||||||
|
answers.tags.length > 0
|
||||||
|
? `['${answers.tags.map((tag) => escapeString(tag)).join("', '")}']`
|
||||||
|
: "['neynar', 'starter-kit', 'demo']";
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.APP_TAGS,
|
||||||
|
`export const APP_TAGS = ${tagsString};`,
|
||||||
|
'APP_TAGS'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update APP_BUTTON_TEXT (always update, use answers value)
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.APP_BUTTON_TEXT,
|
||||||
|
`export const APP_BUTTON_TEXT = '${escapeString(
|
||||||
|
answers.buttonText || ''
|
||||||
|
)}';`,
|
||||||
|
'APP_BUTTON_TEXT'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update USE_WALLET
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.USE_WALLET,
|
||||||
|
`export const USE_WALLET = ${answers.useWallet};`,
|
||||||
|
'USE_WALLET'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update ANALYTICS_ENABLED
|
||||||
|
constantsContent = safeReplace(
|
||||||
|
constantsContent,
|
||||||
|
patterns.ANALYTICS_ENABLED,
|
||||||
|
`export const ANALYTICS_ENABLED = ${answers.enableAnalytics};`,
|
||||||
|
'ANALYTICS_ENABLED'
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(constantsPath, constantsContent);
|
||||||
|
} else {
|
||||||
|
console.log('⚠️ constants.ts not found, skipping constants update');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
if (useNeynar && neynarApiKey && neynarClientId) {
|
if (useNeynar && neynarApiKey && neynarClientId) {
|
||||||
fs.appendFileSync(envPath, `\nNEYNAR_API_KEY="${neynarApiKey}"`);
|
fs.appendFileSync(envPath, `\nNEYNAR_API_KEY="${neynarApiKey}"`);
|
||||||
fs.appendFileSync(envPath, `\nNEYNAR_CLIENT_ID="${neynarClientId}"`);
|
fs.appendFileSync(envPath, `\nNEYNAR_CLIENT_ID="${neynarClientId}"`);
|
||||||
} else if (useNeynar) {
|
} 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'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (answers.seedPhrase) {
|
||||||
|
fs.appendFileSync(envPath, `\nSEED_PHRASE="${answers.seedPhrase}"`);
|
||||||
}
|
}
|
||||||
fs.appendFileSync(envPath, `\nUSE_TUNNEL="${answers.useTunnel}"`);
|
fs.appendFileSync(envPath, `\nUSE_TUNNEL="${answers.useTunnel}"`);
|
||||||
|
if (answers.useSponsoredSigner) {
|
||||||
|
fs.appendFileSync(envPath, `\nSPONSOR_SIGNER="true"`);
|
||||||
|
fs.appendFileSync(
|
||||||
|
envPath,
|
||||||
|
`\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
fs.unlinkSync(envExamplePath);
|
fs.unlinkSync(envExamplePath);
|
||||||
console.log('\nCreated .env.local file from .env.example');
|
|
||||||
} else {
|
} 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
|
// Update README
|
||||||
@@ -396,7 +665,9 @@ export async function init() {
|
|||||||
const readmePath = path.join(projectPath, 'README.md');
|
const readmePath = path.join(projectPath, 'README.md');
|
||||||
const prependText = `<!-- generated by @neynar/create-farcaster-mini-app version ${SCRIPT_VERSION} -->\n\n`;
|
const prependText = `<!-- generated by @neynar/create-farcaster-mini-app version ${SCRIPT_VERSION} -->\n\n`;
|
||||||
if (fs.existsSync(readmePath)) {
|
if (fs.existsSync(readmePath)) {
|
||||||
const originalReadmeContent = fs.readFileSync(readmePath, { encoding: 'utf8' });
|
const originalReadmeContent = fs.readFileSync(readmePath, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
});
|
||||||
const updatedReadmeContent = prependText + originalReadmeContent;
|
const updatedReadmeContent = prependText + originalReadmeContent;
|
||||||
fs.writeFileSync(readmePath, updatedReadmeContent);
|
fs.writeFileSync(readmePath, updatedReadmeContent);
|
||||||
} else {
|
} else {
|
||||||
@@ -409,12 +680,12 @@ export async function init() {
|
|||||||
execSync('npm cache clean --force', {
|
execSync('npm cache clean --force', {
|
||||||
cwd: projectPath,
|
cwd: projectPath,
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
shell: process.platform === 'win32'
|
shell: process.platform === 'win32',
|
||||||
});
|
});
|
||||||
execSync('npm install', {
|
execSync('npm install', {
|
||||||
cwd: projectPath,
|
cwd: projectPath,
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
shell: process.platform === 'win32'
|
shell: process.platform === 'win32',
|
||||||
});
|
});
|
||||||
|
|
||||||
// Remove the bin directory
|
// Remove the bin directory
|
||||||
@@ -424,21 +695,50 @@ export async function init() {
|
|||||||
fs.rmSync(binPath, { recursive: true, force: true });
|
fs.rmSync(binPath, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove NeynarAuthButton directory, NextAuth API routes, and auth directory if useSponsoredSigner is false
|
||||||
|
if (!answers.useSponsoredSigner) {
|
||||||
|
console.log('\nRemoving NeynarAuthButton directory, NextAuth API routes, and auth directory (useSponsoredSigner is false)...');
|
||||||
|
const neynarAuthButtonPath = path.join(projectPath, 'src', 'components', 'ui', 'NeynarAuthButton');
|
||||||
|
if (fs.existsSync(neynarAuthButtonPath)) {
|
||||||
|
fs.rmSync(neynarAuthButtonPath, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove NextAuth API routes
|
||||||
|
const nextAuthRoutePath = path.join(projectPath, 'src', 'app', 'api', 'auth', '[...nextauth]', 'route.ts');
|
||||||
|
if (fs.existsSync(nextAuthRoutePath)) {
|
||||||
|
fs.rmSync(nextAuthRoutePath, { force: true });
|
||||||
|
// Remove the directory if it's empty
|
||||||
|
const nextAuthDir = path.dirname(nextAuthRoutePath);
|
||||||
|
if (fs.readdirSync(nextAuthDir).length === 0) {
|
||||||
|
fs.rmSync(nextAuthDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove src/auth.ts file
|
||||||
|
const authFilePath = path.join(projectPath, 'src', 'auth.ts');
|
||||||
|
if (fs.existsSync(authFilePath)) {
|
||||||
|
fs.rmSync(authFilePath, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Initialize git repository
|
// Initialize git repository
|
||||||
console.log('\nInitializing git repository...');
|
console.log('\nInitializing git repository...');
|
||||||
execSync('git init', { cwd: projectPath });
|
execSync('git init', { cwd: projectPath });
|
||||||
execSync('git add .', { 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
|
// Calculate border length based on message length
|
||||||
const message = `✨🪐 Successfully created frame ${projectName} with git and dependencies installed! 🪐✨`;
|
const message = `✨🪐 Successfully created mini app ${finalProjectName} with git and dependencies installed! 🪐✨`;
|
||||||
const borderLength = message.length;
|
const borderLength = message.length;
|
||||||
const borderStars = '✨'.repeat((borderLength / 2) + 1);
|
const borderStars = '✨'.repeat(borderLength / 2 + 1);
|
||||||
|
|
||||||
console.log(`\n${borderStars}`);
|
console.log(`\n${borderStars}`);
|
||||||
console.log(`${message}`);
|
console.log(`${message}`);
|
||||||
console.log(`${borderStars}`);
|
console.log(`${borderStars}`);
|
||||||
console.log('\nTo run the app:');
|
console.log('\nTo run the app:');
|
||||||
console.log(` cd ${projectName}`);
|
console.log(` cd ${finalProjectName}`);
|
||||||
console.log(' npm run dev\n');
|
console.log(' npm run dev\n');
|
||||||
}
|
}
|
||||||
|
|||||||
631
package-lock.json
generated
631
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@neynar/create-farcaster-mini-app",
|
"name": "@neynar/create-farcaster-mini-app",
|
||||||
"version": "1.2.5",
|
"version": "1.5.3",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@neynar/create-farcaster-mini-app",
|
"name": "@neynar/create-farcaster-mini-app",
|
||||||
"version": "1.2.5",
|
"version": "1.5.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv": "^16.4.7",
|
"dotenv": "^16.4.7",
|
||||||
"inquirer": "^12.4.3",
|
"inquirer": "^12.4.3",
|
||||||
@@ -344,6 +344,132 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@isaacs/balanced-match": {
|
||||||
|
"version": "4.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz",
|
||||||
|
"integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "20 || >=22"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/brace-expansion": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@isaacs/balanced-match": "^4.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "20 || >=22"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui": {
|
||||||
|
"version": "8.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
||||||
|
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"string-width": "^5.1.2",
|
||||||
|
"string-width-cjs": "npm:string-width@^4.2.0",
|
||||||
|
"strip-ansi": "^7.0.1",
|
||||||
|
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
|
||||||
|
"wrap-ansi": "^8.1.0",
|
||||||
|
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui/node_modules/ansi-regex": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui/node_modules/ansi-styles": {
|
||||||
|
"version": "6.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz",
|
||||||
|
"integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui/node_modules/emoji-regex": {
|
||||||
|
"version": "9.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
|
||||||
|
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui/node_modules/string-width": {
|
||||||
|
"version": "5.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
|
||||||
|
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"eastasianwidth": "^0.2.0",
|
||||||
|
"emoji-regex": "^9.2.2",
|
||||||
|
"strip-ansi": "^7.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui/node_modules/strip-ansi": {
|
||||||
|
"version": "7.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz",
|
||||||
|
"integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-regex": "^6.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@isaacs/cliui/node_modules/wrap-ansi": {
|
||||||
|
"version": "8.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
|
||||||
|
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-styles": "^6.1.0",
|
||||||
|
"string-width": "^5.0.1",
|
||||||
|
"strip-ansi": "^7.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@lukeed/csprng": {
|
"node_modules/@lukeed/csprng": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
|
||||||
@@ -355,25 +481,27 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nestjs/axios": {
|
"node_modules/@nestjs/axios": {
|
||||||
"version": "3.1.3",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz",
|
||||||
"integrity": "sha512-RZ/63c1tMxGLqyG3iOCVt7A72oy4x1eM6QEhd4KzCYpaVWW0igq0WSREeRoEZhIxRcZfDfIIkvsOMiM7yfVGZQ==",
|
"integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
|
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
||||||
"axios": "^1.3.1",
|
"axios": "^1.3.1",
|
||||||
"rxjs": "^6.0.0 || ^7.0.0"
|
"rxjs": "^7.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nestjs/common": {
|
"node_modules/@nestjs/common": {
|
||||||
"version": "10.4.15",
|
"version": "11.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.15.tgz",
|
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.3.tgz",
|
||||||
"integrity": "sha512-vaLg1ZgwhG29BuLDxPA9OAcIlgqzp9/N8iG0wGapyUNTf4IY4O6zAHgN6QalwLhFxq7nOI021vdRojR1oF3bqg==",
|
"integrity": "sha512-ogEK+GriWodIwCw6buQ1rpcH4Kx+G7YQ9EwuPySI3rS05pSdtQ++UhucjusSI9apNidv+QURBztJkRecwwJQXg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"file-type": "21.0.0",
|
||||||
"iterare": "1.2.1",
|
"iterare": "1.2.1",
|
||||||
|
"load-esm": "1.0.2",
|
||||||
"tslib": "2.8.1",
|
"tslib": "2.8.1",
|
||||||
"uid": "2.0.2"
|
"uid": "2.0.2"
|
||||||
},
|
},
|
||||||
@@ -382,8 +510,8 @@
|
|||||||
"url": "https://opencollective.com/nest"
|
"url": "https://opencollective.com/nest"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"class-transformer": "*",
|
"class-transformer": ">=0.4.1",
|
||||||
"class-validator": "*",
|
"class-validator": ">=0.13.2",
|
||||||
"reflect-metadata": "^0.1.12 || ^0.2.0",
|
"reflect-metadata": "^0.1.12 || ^0.2.0",
|
||||||
"rxjs": "^7.1.0"
|
"rxjs": "^7.1.0"
|
||||||
},
|
},
|
||||||
@@ -397,29 +525,32 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nestjs/core": {
|
"node_modules/@nestjs/core": {
|
||||||
"version": "10.4.15",
|
"version": "11.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-10.4.15.tgz",
|
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.3.tgz",
|
||||||
"integrity": "sha512-UBejmdiYwaH6fTsz2QFBlC1cJHM+3UDeLZN+CiP9I1fRv2KlBZsmozGLbV5eS1JAVWJB4T5N5yQ0gjN8ZvcS2w==",
|
"integrity": "sha512-5lTni0TCh8x7bXETRD57pQFnKnEg1T6M+VLE7wAmyQRIecKQU+2inRGZD+A4v2DC1I04eA0WffP0GKLxjOKlzw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nuxtjs/opencollective": "0.3.2",
|
"@nuxt/opencollective": "0.4.1",
|
||||||
"fast-safe-stringify": "2.1.1",
|
"fast-safe-stringify": "2.1.1",
|
||||||
"iterare": "1.2.1",
|
"iterare": "1.2.1",
|
||||||
"path-to-regexp": "3.3.0",
|
"path-to-regexp": "8.2.0",
|
||||||
"tslib": "2.8.1",
|
"tslib": "2.8.1",
|
||||||
"uid": "2.0.2"
|
"uid": "2.0.2"
|
||||||
},
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 20"
|
||||||
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
"url": "https://opencollective.com/nest"
|
"url": "https://opencollective.com/nest"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@nestjs/common": "^10.0.0",
|
"@nestjs/common": "^11.0.0",
|
||||||
"@nestjs/microservices": "^10.0.0",
|
"@nestjs/microservices": "^11.0.0",
|
||||||
"@nestjs/platform-express": "^10.0.0",
|
"@nestjs/platform-express": "^11.0.0",
|
||||||
"@nestjs/websockets": "^10.0.0",
|
"@nestjs/websockets": "^11.0.0",
|
||||||
"reflect-metadata": "^0.1.12 || ^0.2.0",
|
"reflect-metadata": "^0.1.12 || ^0.2.0",
|
||||||
"rxjs": "^7.1.0"
|
"rxjs": "^7.1.0"
|
||||||
},
|
},
|
||||||
@@ -477,6 +608,23 @@
|
|||||||
"url": "https://paulmillr.com/funding/"
|
"url": "https://paulmillr.com/funding/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@nuxt/opencollective": {
|
||||||
|
"version": "0.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz",
|
||||||
|
"integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"consola": "^3.2.3"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"opencollective": "bin/opencollective.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^14.18.0 || >=16.10.0",
|
||||||
|
"npm": ">=5.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@nuxtjs/opencollective": {
|
"node_modules/@nuxtjs/opencollective": {
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz",
|
||||||
@@ -496,26 +644,33 @@
|
|||||||
"npm": ">=5.0.0"
|
"npm": ">=5.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@nuxtjs/opencollective/node_modules/consola": {
|
||||||
|
"version": "2.15.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz",
|
||||||
|
"integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@openapitools/openapi-generator-cli": {
|
"node_modules/@openapitools/openapi-generator-cli": {
|
||||||
"version": "2.18.4",
|
"version": "2.21.0",
|
||||||
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.18.4.tgz",
|
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.21.0.tgz",
|
||||||
"integrity": "sha512-wer7rWp92fLcHqRG/2XS2bGqGUo2qVO0MseUgcpbxyVzBrKZZJh5c0dxQWTD3V178laj1ndC6w1Parn3fjKolg==",
|
"integrity": "sha512-NdDvCd7hya+UucxH7G94Jf6tmA6641I4CF/T3xtFhM+NQQNWAP5tpiOBN4Ub9ocU6cCgQgXdWl4EpwlEwW7JDQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nestjs/axios": "3.1.3",
|
"@nestjs/axios": "4.0.0",
|
||||||
"@nestjs/common": "10.4.15",
|
"@nestjs/common": "11.1.3",
|
||||||
"@nestjs/core": "10.4.15",
|
"@nestjs/core": "11.1.3",
|
||||||
"@nuxtjs/opencollective": "0.3.2",
|
"@nuxtjs/opencollective": "0.3.2",
|
||||||
"axios": "1.8.3",
|
"axios": "1.10.0",
|
||||||
"chalk": "4.1.2",
|
"chalk": "4.1.2",
|
||||||
"commander": "8.3.0",
|
"commander": "8.3.0",
|
||||||
"compare-versions": "4.1.4",
|
"compare-versions": "4.1.4",
|
||||||
"concurrently": "6.5.1",
|
"concurrently": "6.5.1",
|
||||||
"console.table": "0.10.0",
|
"console.table": "0.10.0",
|
||||||
"fs-extra": "11.3.0",
|
"fs-extra": "11.3.0",
|
||||||
"glob": "9.3.5",
|
"glob": "11.0.3",
|
||||||
"inquirer": "8.2.6",
|
"inquirer": "8.2.6",
|
||||||
"lodash": "4.17.21",
|
"lodash": "4.17.21",
|
||||||
"proxy-agent": "6.5.0",
|
"proxy-agent": "6.5.0",
|
||||||
@@ -624,6 +779,32 @@
|
|||||||
"url": "https://paulmillr.com/funding/"
|
"url": "https://paulmillr.com/funding/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tokenizer/inflate": {
|
||||||
|
"version": "0.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz",
|
||||||
|
"integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"debug": "^4.4.0",
|
||||||
|
"fflate": "^0.8.2",
|
||||||
|
"token-types": "^6.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Borewit"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tokenizer/token": {
|
||||||
|
"version": "0.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
|
||||||
|
"integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@tootallnate/quickjs-emscripten": {
|
"node_modules/@tootallnate/quickjs-emscripten": {
|
||||||
"version": "0.23.0",
|
"version": "0.23.0",
|
||||||
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
|
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
|
||||||
@@ -732,9 +913,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/axios": {
|
"node_modules/axios": {
|
||||||
"version": "1.8.3",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.3.tgz",
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
||||||
"integrity": "sha512-iP4DebzoNlP/YN2dpwCgb8zoCmhtkajzS48JvwmkSkXvPI3DHc7m+XYL5tGnSlJtR6nImXZmdCuN5aP8dh1d8A==",
|
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -743,13 +924,6 @@
|
|||||||
"proxy-from-env": "^1.1.0"
|
"proxy-from-env": "^1.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/balanced-match": {
|
|
||||||
"version": "1.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
|
||||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/base64-js": {
|
"node_modules/base64-js": {
|
||||||
"version": "1.5.1",
|
"version": "1.5.1",
|
||||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||||
@@ -793,16 +967,6 @@
|
|||||||
"readable-stream": "^3.4.0"
|
"readable-stream": "^3.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/brace-expansion": {
|
|
||||||
"version": "2.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
|
|
||||||
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/buffer": {
|
"node_modules/buffer": {
|
||||||
"version": "5.7.1",
|
"version": "5.7.1",
|
||||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
|
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
|
||||||
@@ -1048,11 +1212,14 @@
|
|||||||
"license": "0BSD"
|
"license": "0BSD"
|
||||||
},
|
},
|
||||||
"node_modules/consola": {
|
"node_modules/consola": {
|
||||||
"version": "2.15.3",
|
"version": "3.4.2",
|
||||||
"resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz",
|
"resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",
|
||||||
"integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==",
|
"integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^14.18.0 || >=16.10.0"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"node_modules/console.table": {
|
"node_modules/console.table": {
|
||||||
"version": "0.10.0",
|
"version": "0.10.0",
|
||||||
@@ -1067,6 +1234,21 @@
|
|||||||
"node": "> 0.10"
|
"node": "> 0.10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cross-spawn": {
|
||||||
|
"version": "7.0.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||||
|
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"path-key": "^3.1.0",
|
||||||
|
"shebang-command": "^2.0.0",
|
||||||
|
"which": "^2.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/data-uri-to-buffer": {
|
"node_modules/data-uri-to-buffer": {
|
||||||
"version": "6.0.2",
|
"version": "6.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
|
||||||
@@ -1177,6 +1359,13 @@
|
|||||||
"node": ">= 0.4"
|
"node": ">= 0.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/eastasianwidth": {
|
||||||
|
"version": "0.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
|
||||||
|
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/easy-table": {
|
"node_modules/easy-table": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz",
|
||||||
@@ -1345,6 +1534,13 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/fflate": {
|
||||||
|
"version": "0.8.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
|
||||||
|
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/figures": {
|
"node_modules/figures": {
|
||||||
"version": "3.2.0",
|
"version": "3.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz",
|
||||||
@@ -1361,6 +1557,25 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/file-type": {
|
||||||
|
"version": "21.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/file-type/-/file-type-21.0.0.tgz",
|
||||||
|
"integrity": "sha512-ek5xNX2YBYlXhiUXui3D/BXa3LdqPmoLJ7rqEx2bKJ7EAUEfmXgW0Das7Dc6Nr9MvqaOnIqiPV0mZk/r/UpNAg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@tokenizer/inflate": "^0.2.7",
|
||||||
|
"strtok3": "^10.2.2",
|
||||||
|
"token-types": "^6.0.0",
|
||||||
|
"uint8array-extras": "^1.4.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sindresorhus/file-type?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/follow-redirects": {
|
"node_modules/follow-redirects": {
|
||||||
"version": "1.15.9",
|
"version": "1.15.9",
|
||||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
|
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
|
||||||
@@ -1382,16 +1597,34 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/foreground-child": {
|
||||||
|
"version": "3.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
|
||||||
|
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"cross-spawn": "^7.0.6",
|
||||||
|
"signal-exit": "^4.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/form-data": {
|
"node_modules/form-data": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.3.tgz",
|
||||||
"integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
|
"integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"asynckit": "^0.4.0",
|
"asynckit": "^0.4.0",
|
||||||
"combined-stream": "^1.0.8",
|
"combined-stream": "^1.0.8",
|
||||||
"es-set-tostringtag": "^2.1.0",
|
"es-set-tostringtag": "^2.1.0",
|
||||||
|
"hasown": "^2.0.2",
|
||||||
"mime-types": "^2.1.12"
|
"mime-types": "^2.1.12"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -1413,13 +1646,6 @@
|
|||||||
"node": ">=14.14"
|
"node": ">=14.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/fs.realpath": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "ISC"
|
|
||||||
},
|
|
||||||
"node_modules/function-bind": {
|
"node_modules/function-bind": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||||
@@ -1495,19 +1721,24 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/glob": {
|
"node_modules/glob": {
|
||||||
"version": "9.3.5",
|
"version": "11.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz",
|
"resolved": "https://registry.npmjs.org/glob/-/glob-11.0.3.tgz",
|
||||||
"integrity": "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q==",
|
"integrity": "sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fs.realpath": "^1.0.0",
|
"foreground-child": "^3.3.1",
|
||||||
"minimatch": "^8.0.2",
|
"jackspeak": "^4.1.1",
|
||||||
"minipass": "^4.2.4",
|
"minimatch": "^10.0.3",
|
||||||
"path-scurry": "^1.6.1"
|
"minipass": "^7.1.2",
|
||||||
|
"package-json-from-dist": "^1.0.0",
|
||||||
|
"path-scurry": "^2.0.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"glob": "dist/esm/bin.mjs"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16 || 14 >=14.17"
|
"node": "20 || >=22"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
@@ -1725,6 +1956,13 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/isexe": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/isows": {
|
"node_modules/isows": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/isows/-/isows-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/isows/-/isows-1.0.6.tgz",
|
||||||
@@ -1750,6 +1988,22 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/jackspeak": {
|
||||||
|
"version": "4.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz",
|
||||||
|
"integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "BlueOak-1.0.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@isaacs/cliui": "^8.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "20 || >=22"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/jsbn": {
|
"node_modules/jsbn": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",
|
||||||
@@ -1770,6 +2024,26 @@
|
|||||||
"graceful-fs": "^4.1.6"
|
"graceful-fs": "^4.1.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/load-esm": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-nVAvWk/jeyrWyXEAs84mpQCYccxRqgKY4OznLuJhJCa0XsPSfdOIr2zvBZEj3IHEHbX97jjscKRRV539bW0Gpw==",
|
||||||
|
"dev": true,
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Borewit"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "buymeacoffee",
|
||||||
|
"url": "https://buymeacoffee.com/borewit"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=13.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lodash": {
|
"node_modules/lodash": {
|
||||||
"version": "4.17.21",
|
"version": "4.17.21",
|
||||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||||
@@ -1795,11 +2069,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/lru-cache": {
|
"node_modules/lru-cache": {
|
||||||
"version": "10.4.3",
|
"version": "11.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.1.0.tgz",
|
||||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
"integrity": "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": "20 || >=22"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"node_modules/math-intrinsics": {
|
"node_modules/math-intrinsics": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
@@ -1845,29 +2122,29 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/minimatch": {
|
"node_modules/minimatch": {
|
||||||
"version": "8.0.4",
|
"version": "10.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-8.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.3.tgz",
|
||||||
"integrity": "sha512-W0Wvr9HyFXZRGIDgCicunpQ299OKXs9RgZfaukz4qAW/pJhcpUfupc9c+OObPOFueNy8VSrZgEmDtk6Kh4WzDA==",
|
"integrity": "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"brace-expansion": "^2.0.1"
|
"@isaacs/brace-expansion": "^5.0.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16 || 14 >=14.17"
|
"node": "20 || >=22"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/minipass": {
|
"node_modules/minipass": {
|
||||||
"version": "4.2.8",
|
"version": "7.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz",
|
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
|
||||||
"integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==",
|
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=8"
|
"node": ">=16 || 14 >=14.17"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/ms": {
|
"node_modules/ms": {
|
||||||
@@ -2029,39 +2306,49 @@
|
|||||||
"node": ">= 14"
|
"node": ">= 14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/package-json-from-dist": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "BlueOak-1.0.0"
|
||||||
|
},
|
||||||
|
"node_modules/path-key": {
|
||||||
|
"version": "3.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||||
|
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/path-scurry": {
|
"node_modules/path-scurry": {
|
||||||
"version": "1.11.1",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
|
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz",
|
||||||
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
|
"integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "BlueOak-1.0.0",
|
"license": "BlueOak-1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"lru-cache": "^10.2.0",
|
"lru-cache": "^11.0.0",
|
||||||
"minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
|
"minipass": "^7.1.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16 || 14 >=14.18"
|
"node": "20 || >=22"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/path-scurry/node_modules/minipass": {
|
|
||||||
"version": "7.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
|
|
||||||
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "ISC",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=16 || 14 >=14.17"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/path-to-regexp": {
|
"node_modules/path-to-regexp": {
|
||||||
"version": "3.3.0",
|
"version": "8.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz",
|
||||||
"integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==",
|
"integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"node_modules/proxy-agent": {
|
"node_modules/proxy-agent": {
|
||||||
"version": "6.5.0",
|
"version": "6.5.0",
|
||||||
@@ -2218,6 +2505,29 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/shebang-command": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"shebang-regex": "^3.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/shebang-regex": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/signal-exit": {
|
"node_modules/signal-exit": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
|
||||||
@@ -2319,6 +2629,22 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/string-width-cjs": {
|
||||||
|
"name": "string-width",
|
||||||
|
"version": "4.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||||
|
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"emoji-regex": "^8.0.0",
|
||||||
|
"is-fullwidth-code-point": "^3.0.0",
|
||||||
|
"strip-ansi": "^6.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/strip-ansi": {
|
"node_modules/strip-ansi": {
|
||||||
"version": "6.0.1",
|
"version": "6.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||||
@@ -2331,6 +2657,37 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/strip-ansi-cjs": {
|
||||||
|
"name": "strip-ansi",
|
||||||
|
"version": "6.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||||
|
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-regex": "^5.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/strtok3": {
|
||||||
|
"version": "10.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.1.tgz",
|
||||||
|
"integrity": "sha512-3JWEZM6mfix/GCJBBUrkA8p2Id2pBkyTkVCJKto55w080QBKZ+8R171fGrbiSp+yMO/u6F8/yUh7K4V9K+YCnw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@tokenizer/token": "^0.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Borewit"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/supports-color": {
|
"node_modules/supports-color": {
|
||||||
"version": "7.2.0",
|
"version": "7.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
||||||
@@ -2363,6 +2720,24 @@
|
|||||||
"node": ">=0.6.0"
|
"node": ">=0.6.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/token-types": {
|
||||||
|
"version": "6.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.3.tgz",
|
||||||
|
"integrity": "sha512-IKJ6EzuPPWtKtEIEPpIdXv9j5j2LGJEYk0CKY2efgKoYKLBiZdh6iQkLVBow/CB3phyWAWCyk+bZeaimJn6uRQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@tokenizer/token": "^0.3.0",
|
||||||
|
"ieee754": "^1.2.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.16"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Borewit"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tr46": {
|
"node_modules/tr46": {
|
||||||
"version": "0.0.3",
|
"version": "0.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||||
@@ -2425,6 +2800,19 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/uint8array-extras": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/undici-types": {
|
"node_modules/undici-types": {
|
||||||
"version": "6.20.0",
|
"version": "6.20.0",
|
||||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
|
||||||
@@ -2507,6 +2895,22 @@
|
|||||||
"webidl-conversions": "^3.0.0"
|
"webidl-conversions": "^3.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/which": {
|
||||||
|
"version": "2.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||||
|
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"isexe": "^2.0.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"node-which": "bin/node-which"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/wrap-ansi": {
|
"node_modules/wrap-ansi": {
|
||||||
"version": "6.2.0",
|
"version": "6.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||||
@@ -2521,6 +2925,25 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/wrap-ansi-cjs": {
|
||||||
|
"name": "wrap-ansi",
|
||||||
|
"version": "7.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
|
||||||
|
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-styles": "^4.0.0",
|
||||||
|
"string-width": "^4.1.0",
|
||||||
|
"strip-ansi": "^6.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ws": {
|
"node_modules/ws": {
|
||||||
"version": "8.18.1",
|
"version": "8.18.1",
|
||||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz",
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz",
|
||||||
|
|||||||
10
package.json
10
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@neynar/create-farcaster-mini-app",
|
"name": "@neynar/create-farcaster-mini-app",
|
||||||
"version": "1.2.28",
|
"version": "1.7.8",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": false,
|
"private": false,
|
||||||
"access": "public",
|
"access": "public",
|
||||||
@@ -31,11 +31,13 @@
|
|||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node scripts/dev.js",
|
"dev": "node scripts/dev.js",
|
||||||
"build": "node scripts/build.js",
|
"build": "next build",
|
||||||
|
"build:raw": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "next lint",
|
"lint": "next lint",
|
||||||
"deploy:vercel": "node scripts/deploy.js",
|
"deploy:vercel": "ts-node scripts/deploy.ts",
|
||||||
"cleanup": "lsof -ti :3000 | xargs kill -9"
|
"deploy:raw": "vercel --prod",
|
||||||
|
"cleanup": "node scripts/cleanup.js"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"@neynar/create-farcaster-mini-app": "./bin/index.js"
|
"@neynar/create-farcaster-mini-app": "./bin/index.js"
|
||||||
|
|||||||
414
scripts/build.js
414
scripts/build.js
@@ -1,414 +0,0 @@
|
|||||||
import { execSync } from 'child_process';
|
|
||||||
import fs from 'fs';
|
|
||||||
import path from 'path';
|
|
||||||
import { mnemonicToAccount } from 'viem/accounts';
|
|
||||||
import { fileURLToPath } from 'url';
|
|
||||||
import inquirer from 'inquirer';
|
|
||||||
import dotenv from 'dotenv';
|
|
||||||
import crypto from 'crypto';
|
|
||||||
|
|
||||||
// ANSI color codes
|
|
||||||
const yellow = '\x1b[33m';
|
|
||||||
const italic = '\x1b[3m';
|
|
||||||
const reset = '\x1b[0m';
|
|
||||||
|
|
||||||
// Load environment variables in specific order
|
|
||||||
// First load .env for main config
|
|
||||||
dotenv.config({ path: '.env' });
|
|
||||||
|
|
||||||
async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
|
|
||||||
if (!apiKey) {
|
|
||||||
throw new Error('Neynar API key is required');
|
|
||||||
}
|
|
||||||
const lowerCasedCustodyAddress = custodyAddress.toLowerCase();
|
|
||||||
|
|
||||||
const response = await fetch(
|
|
||||||
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'accept': 'application/json',
|
|
||||||
'x-api-key': apiKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to lookup FID: ${response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
if (!data[lowerCasedCustodyAddress]?.length || !data[lowerCasedCustodyAddress][0].custody_address) {
|
|
||||||
throw new Error('No FID found for this custody address');
|
|
||||||
}
|
|
||||||
|
|
||||||
return data[lowerCasedCustodyAddress][0].fid;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadEnvLocal() {
|
|
||||||
try {
|
|
||||||
if (fs.existsSync('.env.local')) {
|
|
||||||
const { loadLocal } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'confirm',
|
|
||||||
name: 'loadLocal',
|
|
||||||
message: 'Found .env.local, likely created by the install script - would you like to load its values?',
|
|
||||||
default: false
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (loadLocal) {
|
|
||||||
console.log('Loading values from .env.local...');
|
|
||||||
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' : '';
|
|
||||||
let newEnvContent = envContent;
|
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(localEnv)) {
|
|
||||||
if (key !== 'SEED_PHRASE') {
|
|
||||||
// Update process.env
|
|
||||||
process.env[key] = value;
|
|
||||||
// Add to .env content if not already there
|
|
||||||
if (!envContent.includes(`${key}=`)) {
|
|
||||||
newEnvContent += `${key}="${value}"\n`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write updated content to .env
|
|
||||||
fs.writeFileSync('.env', newEnvContent);
|
|
||||||
console.log('✅ Values from .env.local have been written to .env');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always try to load SEED_PHRASE from .env.local
|
|
||||||
if (fs.existsSync('.env.local')) {
|
|
||||||
const localEnv = dotenv.parse(fs.readFileSync('.env.local'));
|
|
||||||
if (localEnv.SEED_PHRASE) {
|
|
||||||
process.env.SEED_PHRASE = localEnv.SEED_PHRASE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// Error reading .env.local, which is fine
|
|
||||||
console.log('Note: No .env.local file found');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: make sure rebuilding is supported
|
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
const projectRoot = path.join(__dirname, '..');
|
|
||||||
|
|
||||||
async function validateDomain(domain) {
|
|
||||||
// Remove http:// or https:// if present
|
|
||||||
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,})+$/)) {
|
|
||||||
throw new Error('Invalid domain format');
|
|
||||||
}
|
|
||||||
|
|
||||||
return cleanDomain;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function queryNeynarApp(apiKey) {
|
|
||||||
if (!apiKey) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const response = await fetch(
|
|
||||||
`https://api.neynar.com/portal/app_by_api_key`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'x-api-key': apiKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
const data = await response.json();
|
|
||||||
return data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error querying Neynar app data:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function validateSeedPhrase(seedPhrase) {
|
|
||||||
try {
|
|
||||||
// Try to create an account from the seed phrase
|
|
||||||
const account = mnemonicToAccount(seedPhrase);
|
|
||||||
return account.address;
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error('Invalid seed phrase');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 payload = {
|
|
||||||
domain
|
|
||||||
};
|
|
||||||
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
|
|
||||||
|
|
||||||
const account = mnemonicToAccount(seedPhrase);
|
|
||||||
const signature = await account.signMessage({
|
|
||||||
message: `${encodedHeader}.${encodedPayload}`
|
|
||||||
});
|
|
||||||
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
|
|
||||||
|
|
||||||
const tags = process.env.NEXT_PUBLIC_FRAME_TAGS?.split(',');
|
|
||||||
|
|
||||||
return {
|
|
||||||
accountAssociation: {
|
|
||||||
header: encodedHeader,
|
|
||||||
payload: encodedPayload,
|
|
||||||
signature: encodedSignature
|
|
||||||
},
|
|
||||||
frame: {
|
|
||||||
version: "1",
|
|
||||||
name: process.env.NEXT_PUBLIC_FRAME_NAME,
|
|
||||||
iconUrl: `https://${domain}/icon.png`,
|
|
||||||
homeUrl: `https://${domain}`,
|
|
||||||
imageUrl: `https://${domain}/api/opengraph-image`,
|
|
||||||
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT,
|
|
||||||
splashImageUrl: `https://${domain}/splash.png`,
|
|
||||||
splashBackgroundColor: "#f7f7f7",
|
|
||||||
webhookUrl,
|
|
||||||
description: process.env.NEXT_PUBLIC_FRAME_DESCRIPTION,
|
|
||||||
primaryCategory: process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY,
|
|
||||||
tags,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
try {
|
|
||||||
console.log('\n📝 Checking environment variables...');
|
|
||||||
console.log('Loading values from .env...');
|
|
||||||
|
|
||||||
// Load .env.local if user wants to
|
|
||||||
await loadEnvLocal();
|
|
||||||
|
|
||||||
// Get domain from user
|
|
||||||
const { domain } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'input',
|
|
||||||
name: 'domain',
|
|
||||||
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
|
|
||||||
const { frameName } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'input',
|
|
||||||
name: 'frameName',
|
|
||||||
message: 'Enter the name for your mini app (e.g., My Cool Mini App):',
|
|
||||||
default: process.env.NEXT_PUBLIC_FRAME_NAME,
|
|
||||||
validate: (input) => {
|
|
||||||
if (input.trim() === '') {
|
|
||||||
return 'Mini app name cannot be empty';
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Get button text from user
|
|
||||||
const { buttonText } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'input',
|
|
||||||
name: 'buttonText',
|
|
||||||
message: 'Enter the text for your mini app button:',
|
|
||||||
default: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT || 'Launch Mini App',
|
|
||||||
validate: (input) => {
|
|
||||||
if (input.trim() === '') {
|
|
||||||
return 'Button text cannot be empty';
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Get Neynar configuration
|
|
||||||
let neynarApiKey = process.env.NEYNAR_API_KEY;
|
|
||||||
let neynarClientId = process.env.NEYNAR_CLIENT_ID;
|
|
||||||
let useNeynar = true;
|
|
||||||
|
|
||||||
while (useNeynar) {
|
|
||||||
if (!neynarApiKey) {
|
|
||||||
const { neynarApiKey: inputNeynarApiKey } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'password',
|
|
||||||
name: 'neynarApiKey',
|
|
||||||
message: 'Enter your Neynar API key (optional - leave blank to skip):',
|
|
||||||
default: null
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
neynarApiKey = inputNeynarApiKey;
|
|
||||||
} else {
|
|
||||||
console.log('Using existing Neynar API key from .env');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!neynarApiKey) {
|
|
||||||
useNeynar = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to get client ID from API
|
|
||||||
const appInfo = await queryNeynarApp(neynarApiKey);
|
|
||||||
if (appInfo) {
|
|
||||||
neynarClientId = appInfo.app_uuid;
|
|
||||||
console.log('✅ Fetched Neynar app client ID');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we get here, the API key was invalid
|
|
||||||
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
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Reset for retry
|
|
||||||
neynarApiKey = null;
|
|
||||||
neynarClientId = null;
|
|
||||||
|
|
||||||
if (!retry) {
|
|
||||||
useNeynar = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get seed phrase from user
|
|
||||||
let seedPhrase = process.env.SEED_PHRASE;
|
|
||||||
if (!seedPhrase) {
|
|
||||||
const { seedPhrase: inputSeedPhrase } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
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) => {
|
|
||||||
try {
|
|
||||||
await validateSeedPhrase(input);
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
return error.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
seedPhrase = inputSeedPhrase;
|
|
||||||
} else {
|
|
||||||
console.log('Using existing seed phrase from .env');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate seed phrase and get account address
|
|
||||||
const accountAddress = await validateSeedPhrase(seedPhrase);
|
|
||||||
console.log('✅ Generated account address from seed phrase');
|
|
||||||
|
|
||||||
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 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') : '';
|
|
||||||
|
|
||||||
// Add or update environment variables
|
|
||||||
const newEnvVars = [
|
|
||||||
// Base URL
|
|
||||||
`NEXT_PUBLIC_URL=https://${domain}`,
|
|
||||||
|
|
||||||
// Frame metadata
|
|
||||||
`NEXT_PUBLIC_FRAME_NAME="${frameName}"`,
|
|
||||||
`NEXT_PUBLIC_FRAME_DESCRIPTION="${process.env.NEXT_PUBLIC_FRAME_DESCRIPTION || ''}"`,
|
|
||||||
`NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY="${process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY || ''}"`,
|
|
||||||
`NEXT_PUBLIC_FRAME_TAGS="${process.env.NEXT_PUBLIC_FRAME_TAGS || ''}"`,
|
|
||||||
`NEXT_PUBLIC_FRAME_BUTTON_TEXT="${buttonText}"`,
|
|
||||||
|
|
||||||
// Neynar configuration (if it exists in current env)
|
|
||||||
...(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}"`] : []),
|
|
||||||
|
|
||||||
// NextAuth configuration
|
|
||||||
`NEXTAUTH_SECRET="${process.env.NEXTAUTH_SECRET || crypto.randomBytes(32).toString('hex')}"`,
|
|
||||||
`NEXTAUTH_URL="https://${domain}"`,
|
|
||||||
|
|
||||||
// Frame manifest with signature
|
|
||||||
`FRAME_METADATA=${JSON.stringify(metadata)}`,
|
|
||||||
];
|
|
||||||
|
|
||||||
// Filter out empty values and join with newlines
|
|
||||||
const validEnvVars = newEnvVars.filter(line => {
|
|
||||||
const [, value] = line.split('=');
|
|
||||||
return value && value !== '""';
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update or append each environment variable
|
|
||||||
validEnvVars.forEach(varLine => {
|
|
||||||
const [key] = varLine.split('=');
|
|
||||||
if (envContent.includes(`${key}=`)) {
|
|
||||||
envContent = envContent.replace(new RegExp(`${key}=.*`), varLine);
|
|
||||||
} else {
|
|
||||||
envContent += `\n${varLine}`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Write updated .env file
|
|
||||||
fs.writeFileSync(envPath, envContent);
|
|
||||||
|
|
||||||
console.log('\n✅ Environment variables updated');
|
|
||||||
|
|
||||||
// Run next build
|
|
||||||
console.log('\nBuilding Next.js application...');
|
|
||||||
const nextBin = path.normalize(path.join(projectRoot, 'node_modules', '.bin', 'next'));
|
|
||||||
execSync(`"${nextBin}" build`, {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'inherit',
|
|
||||||
shell: process.platform === 'win32'
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('\n✨ Build complete! Your 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
main();
|
|
||||||
45
scripts/cleanup.js
Normal file
45
scripts/cleanup.js
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { execSync } from 'child_process';
|
||||||
|
|
||||||
|
// Parse arguments
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
let port = 3000; // default port
|
||||||
|
|
||||||
|
// Look for --port=XXXX, --port XXXX, -p=XXXX, or -p XXXX
|
||||||
|
args.forEach((arg, index) => {
|
||||||
|
if (arg.startsWith('--port=')) {
|
||||||
|
port = arg.split('=')[1];
|
||||||
|
} else if (arg === '--port' && args[index + 1]) {
|
||||||
|
port = args[index + 1];
|
||||||
|
} else if (arg.startsWith('-p=')) {
|
||||||
|
port = arg.split('=')[1];
|
||||||
|
} else if (arg === '-p' && args[index + 1]) {
|
||||||
|
port = args[index + 1];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log(`Checking for processes on port ${port}...`);
|
||||||
|
|
||||||
|
// Find processes using the port
|
||||||
|
const pids = execSync(`lsof -ti :${port}`, { encoding: 'utf8' }).trim();
|
||||||
|
|
||||||
|
if (pids) {
|
||||||
|
console.log(`Found processes: ${pids.replace(/\n/g, ', ')}`);
|
||||||
|
|
||||||
|
// Kill the processes
|
||||||
|
execSync(`kill -9 ${pids.replace(/\n/g, ' ')}`);
|
||||||
|
console.log(`✓ Processes on port ${port} have been terminated`);
|
||||||
|
} else {
|
||||||
|
console.log(`No processes found on port ${port}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.status === 1) {
|
||||||
|
// lsof returns status 1 when no processes found
|
||||||
|
console.log(`No processes found on port ${port}`);
|
||||||
|
} else {
|
||||||
|
console.error(`Error: ${error.message}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,675 +0,0 @@
|
|||||||
import { execSync, spawn } from 'child_process';
|
|
||||||
import fs from 'fs';
|
|
||||||
import path from 'path';
|
|
||||||
import { fileURLToPath } from 'url';
|
|
||||||
import inquirer from 'inquirer';
|
|
||||||
import dotenv from 'dotenv';
|
|
||||||
import crypto from 'crypto';
|
|
||||||
import { mnemonicToAccount } from 'viem/accounts';
|
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
const projectRoot = path.join(__dirname, '..');
|
|
||||||
|
|
||||||
// Load environment variables in specific order
|
|
||||||
// First load .env for main config
|
|
||||||
dotenv.config({ path: '.env' });
|
|
||||||
|
|
||||||
async function validateSeedPhrase(seedPhrase) {
|
|
||||||
try {
|
|
||||||
// Try to create an account from the seed phrase
|
|
||||||
const account = mnemonicToAccount(seedPhrase);
|
|
||||||
return account.address;
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error('Invalid seed phrase');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function lookupFidByCustodyAddress(custodyAddress, apiKey) {
|
|
||||||
if (!apiKey) {
|
|
||||||
throw new Error('Neynar API key is required');
|
|
||||||
}
|
|
||||||
const lowerCasedCustodyAddress = custodyAddress.toLowerCase();
|
|
||||||
|
|
||||||
const response = await fetch(
|
|
||||||
`https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${lowerCasedCustodyAddress}&address_types=custody_address`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'accept': 'application/json',
|
|
||||||
'x-api-key': apiKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to lookup FID: ${response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
if (!data[lowerCasedCustodyAddress]?.length || !data[lowerCasedCustodyAddress][0].custody_address) {
|
|
||||||
throw new Error('No FID found for this custody address');
|
|
||||||
}
|
|
||||||
|
|
||||||
return data[lowerCasedCustodyAddress][0].fid;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 payload = {
|
|
||||||
domain: trimmedDomain
|
|
||||||
};
|
|
||||||
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
|
|
||||||
|
|
||||||
const account = mnemonicToAccount(seedPhrase);
|
|
||||||
const signature = await account.signMessage({
|
|
||||||
message: `${encodedHeader}.${encodedPayload}`
|
|
||||||
});
|
|
||||||
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
|
|
||||||
|
|
||||||
const tags = process.env.NEXT_PUBLIC_FRAME_TAGS?.split(',');
|
|
||||||
|
|
||||||
return {
|
|
||||||
accountAssociation: {
|
|
||||||
header: encodedHeader,
|
|
||||||
payload: encodedPayload,
|
|
||||||
signature: encodedSignature
|
|
||||||
},
|
|
||||||
frame: {
|
|
||||||
version: "1",
|
|
||||||
name: process.env.NEXT_PUBLIC_FRAME_NAME,
|
|
||||||
iconUrl: `https://${trimmedDomain}/icon.png`,
|
|
||||||
homeUrl: `https://${trimmedDomain}`,
|
|
||||||
imageUrl: `https://${trimmedDomain}/api/opengraph-image`,
|
|
||||||
buttonTitle: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT,
|
|
||||||
splashImageUrl: `https://${trimmedDomain}/splash.png`,
|
|
||||||
splashBackgroundColor: "#f7f7f7",
|
|
||||||
webhookUrl: webhookUrl?.trim(),
|
|
||||||
description: process.env.NEXT_PUBLIC_FRAME_DESCRIPTION,
|
|
||||||
primaryCategory: process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY,
|
|
||||||
tags,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadEnvLocal() {
|
|
||||||
try {
|
|
||||||
if (fs.existsSync('.env.local')) {
|
|
||||||
const { loadLocal } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
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
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (loadLocal) {
|
|
||||||
console.log('Loading values from .env.local...');
|
|
||||||
const localEnv = dotenv.parse(fs.readFileSync('.env.local'));
|
|
||||||
|
|
||||||
// Define allowed variables to load from .env.local
|
|
||||||
const allowedVars = [
|
|
||||||
'SEED_PHRASE',
|
|
||||||
'NEXT_PUBLIC_FRAME_NAME',
|
|
||||||
'NEXT_PUBLIC_FRAME_DESCRIPTION',
|
|
||||||
'NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY',
|
|
||||||
'NEXT_PUBLIC_FRAME_TAGS',
|
|
||||||
'NEXT_PUBLIC_FRAME_BUTTON_TEXT',
|
|
||||||
'NEYNAR_API_KEY',
|
|
||||||
'NEYNAR_CLIENT_ID'
|
|
||||||
];
|
|
||||||
|
|
||||||
// Copy allowed values except SEED_PHRASE to .env
|
|
||||||
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') + '\n' : '';
|
|
||||||
let newEnvContent = envContent;
|
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(localEnv)) {
|
|
||||||
if (allowedVars.includes(key)) {
|
|
||||||
// Update process.env
|
|
||||||
process.env[key] = value;
|
|
||||||
// Add to .env content if not already there (except for SEED_PHRASE)
|
|
||||||
if (key !== 'SEED_PHRASE' && !envContent.includes(`${key}=`)) {
|
|
||||||
newEnvContent += `${key}="${value}"\n`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write updated content to .env
|
|
||||||
fs.writeFileSync('.env', newEnvContent);
|
|
||||||
console.log('✅ Values from .env.local have been written to .env');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// Error reading .env.local, which is fine
|
|
||||||
console.log('Note: No .env.local file found');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkRequiredEnvVars() {
|
|
||||||
console.log('\n📝 Checking environment variables...');
|
|
||||||
console.log('Loading values from .env...');
|
|
||||||
|
|
||||||
// Load .env.local if user wants to
|
|
||||||
await loadEnvLocal();
|
|
||||||
|
|
||||||
const requiredVars = [
|
|
||||||
{
|
|
||||||
name: 'NEXT_PUBLIC_FRAME_NAME',
|
|
||||||
message: 'Enter the name for your frame (e.g., My Cool Mini App):',
|
|
||||||
default: process.env.NEXT_PUBLIC_FRAME_NAME,
|
|
||||||
validate: input => input.trim() !== '' || 'Mini app name cannot be empty'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'NEXT_PUBLIC_FRAME_BUTTON_TEXT',
|
|
||||||
message: 'Enter the text for your frame button:',
|
|
||||||
default: process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT ?? 'Launch Mini App',
|
|
||||||
validate: input => input.trim() !== '' || 'Button text cannot be empty'
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
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:');
|
|
||||||
for (const varConfig of missingVars) {
|
|
||||||
const { value } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'input',
|
|
||||||
name: 'value',
|
|
||||||
message: varConfig.message,
|
|
||||||
default: varConfig.default,
|
|
||||||
validate: varConfig.validate
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
// Write to both process.env and .env file
|
|
||||||
process.env[varConfig.name] = value;
|
|
||||||
|
|
||||||
// Read existing .env content
|
|
||||||
const envContent = fs.existsSync('.env') ? fs.readFileSync('.env', 'utf8') : '';
|
|
||||||
|
|
||||||
// Check if the variable already exists in .env
|
|
||||||
if (!envContent.includes(`${varConfig.name}=`)) {
|
|
||||||
// Append the new variable to .env without extra newlines
|
|
||||||
const newLine = envContent ? '\n' : '';
|
|
||||||
fs.appendFileSync('.env', `${newLine}${varConfig.name}="${value.trim()}"`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for seed phrase
|
|
||||||
if (!process.env.SEED_PHRASE) {
|
|
||||||
console.log('\n🔑 Mini App Manifest Signing');
|
|
||||||
console.log('A signed manifest helps users trust your mini app.');
|
|
||||||
const { seedPhrase } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'password',
|
|
||||||
name: 'seedPhrase',
|
|
||||||
message: 'Enter your Farcaster custody account seed phrase to sign the mini app manifest\n(optional -- leave blank to create an unsigned mini app)\n\nSeed phrase:',
|
|
||||||
default: null
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (seedPhrase) {
|
|
||||||
process.env.SEED_PHRASE = seedPhrase;
|
|
||||||
|
|
||||||
const { storeSeedPhrase } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'confirm',
|
|
||||||
name: 'storeSeedPhrase',
|
|
||||||
message: 'Would you like to store this seed phrase in .env.local for future use?',
|
|
||||||
default: false
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (storeSeedPhrase) {
|
|
||||||
// Write to .env.local
|
|
||||||
fs.appendFileSync('.env.local', `\nSEED_PHRASE="${seedPhrase}"`);
|
|
||||||
console.log('✅ Seed phrase stored in .env.local');
|
|
||||||
} else {
|
|
||||||
console.log('ℹ️ Seed phrase will only be used for this deployment');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getGitRemote() {
|
|
||||||
try {
|
|
||||||
const remoteUrl = execSync('git remote get-url origin', {
|
|
||||||
cwd: projectRoot,
|
|
||||||
encoding: 'utf8'
|
|
||||||
}).trim();
|
|
||||||
return remoteUrl;
|
|
||||||
} catch (error) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkVercelCLI() {
|
|
||||||
try {
|
|
||||||
execSync('vercel --version', {
|
|
||||||
stdio: 'ignore',
|
|
||||||
shell: process.platform === 'win32'
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function installVercelCLI() {
|
|
||||||
console.log('Installing Vercel CLI...');
|
|
||||||
execSync('npm install -g vercel', {
|
|
||||||
stdio: 'inherit',
|
|
||||||
shell: process.platform === 'win32'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loginToVercel() {
|
|
||||||
console.log('\n🔑 Vercel Login');
|
|
||||||
console.log('You can either:');
|
|
||||||
console.log('1. Log in to an existing Vercel account');
|
|
||||||
console.log('2. Create a new Vercel account during login\n');
|
|
||||||
console.log('If creating a new account:');
|
|
||||||
console.log('1. Click "Continue with GitHub"');
|
|
||||||
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');
|
|
||||||
|
|
||||||
// Start the login process
|
|
||||||
const child = spawn('vercel', ['login'], {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Wait for the login process to complete
|
|
||||||
await new Promise((resolve, reject) => {
|
|
||||||
child.on('close', (code) => {
|
|
||||||
if (code === 0) {
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
// Don't reject here, as the process might exit with non-zero
|
|
||||||
// during the browser auth flow
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// After the browser flow completes, verify we're actually logged in
|
|
||||||
// Keep checking for up to 5 minutes (increased timeout for new account setup)
|
|
||||||
console.log('\n📱 Waiting for login to complete...');
|
|
||||||
console.log('If you\'re creating a new account, please complete the Vercel account setup in your browser first.');
|
|
||||||
|
|
||||||
for (let i = 0; i < 150; i++) {
|
|
||||||
try {
|
|
||||||
execSync('vercel whoami', { stdio: 'ignore' });
|
|
||||||
console.log('✅ Successfully logged in to Vercel!');
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
if (error.message.includes('Account not found')) {
|
|
||||||
console.log('ℹ️ Waiting for Vercel account setup to complete...');
|
|
||||||
}
|
|
||||||
// Still not logged in, wait 2 seconds before trying again
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error('\n❌ Login timed out. Please ensure you have:');
|
|
||||||
console.error('1. Completed the Vercel account setup in your browser');
|
|
||||||
console.error('2. Authorized the GitHub integration');
|
|
||||||
console.error('Then try running this script again.');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function setVercelEnvVar(key, value, projectRoot) {
|
|
||||||
try {
|
|
||||||
// First try to remove the existing env var if it exists
|
|
||||||
try {
|
|
||||||
execSync(`vercel env rm ${key} production -y`, {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'ignore',
|
|
||||||
env: process.env
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
// Ignore errors from removal (var might not exist)
|
|
||||||
}
|
|
||||||
|
|
||||||
// For complex objects like frameMetadata, use a temporary file approach
|
|
||||||
if (typeof value === 'object') {
|
|
||||||
const tempFilePath = path.join(projectRoot, `${key}_temp.json`);
|
|
||||||
// Write the value to a temporary file with proper JSON formatting
|
|
||||||
fs.writeFileSync(tempFilePath, JSON.stringify(value));
|
|
||||||
|
|
||||||
// Use the file to add the environment variable
|
|
||||||
execSync(`vercel env add ${key} production < "${tempFilePath}"`, {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'inherit',
|
|
||||||
env: process.env
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clean up the temporary file
|
|
||||||
fs.unlinkSync(tempFilePath);
|
|
||||||
} else {
|
|
||||||
// For simple string values, use a different approach to avoid shell interpretation issues
|
|
||||||
const tempFilePath = path.join(projectRoot, `${key}_temp.txt`);
|
|
||||||
fs.writeFileSync(tempFilePath, value.toString());
|
|
||||||
|
|
||||||
execSync(`vercel env add ${key} production < "${tempFilePath}"`, {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'inherit',
|
|
||||||
env: process.env
|
|
||||||
});
|
|
||||||
|
|
||||||
fs.unlinkSync(tempFilePath);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`⚠️ Warning: Failed to set environment variable ${key}:`, error.message);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deployToVercel(useGitHub = false) {
|
|
||||||
try {
|
|
||||||
console.log('\n🚀 Deploying to Vercel...');
|
|
||||||
|
|
||||||
// Ensure vercel.json exists
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: check if project already exists here
|
|
||||||
|
|
||||||
// Set up Vercel project
|
|
||||||
console.log('\n📦 Setting up Vercel project...');
|
|
||||||
console.log(' An initial deployment is required to get an assigned domain that can be used in the 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'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Load project info from .vercel/project.json
|
|
||||||
const projectJson = JSON.parse(fs.readFileSync('.vercel/project.json', 'utf8'));
|
|
||||||
const projectId = projectJson.projectId;
|
|
||||||
|
|
||||||
// Get project details using project inspect
|
|
||||||
console.log('\n🔍 Getting project details...');
|
|
||||||
const inspectOutput = execSync(`vercel project inspect ${projectId} 2>&1`, {
|
|
||||||
cwd: projectRoot,
|
|
||||||
encoding: 'utf8'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Extract project name from inspect output
|
|
||||||
let projectName;
|
|
||||||
let domain;
|
|
||||||
const nameMatch = inspectOutput.match(/Name\s+([^\n]+)/);
|
|
||||||
if (nameMatch) {
|
|
||||||
projectName = nameMatch[1].trim();
|
|
||||||
domain = `${projectName}.vercel.app`;
|
|
||||||
console.log('🌐 Using project name for domain:', domain);
|
|
||||||
} else {
|
|
||||||
// Try alternative format
|
|
||||||
const altMatch = inspectOutput.match(/Found Project [^/]+\/([^\n]+)/);
|
|
||||||
if (altMatch) {
|
|
||||||
projectName = altMatch[1].trim();
|
|
||||||
domain = `${projectName}.vercel.app`;
|
|
||||||
console.log('🌐 Using project name for domain:', domain);
|
|
||||||
} else {
|
|
||||||
throw new Error('Could not determine project name from inspection output');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate frame metadata if we have a seed phrase
|
|
||||||
let frameMetadata;
|
|
||||||
let fid;
|
|
||||||
if (process.env.SEED_PHRASE) {
|
|
||||||
console.log('\n🔨 Generating frame metadata...');
|
|
||||||
const accountAddress = await validateSeedPhrase(process.env.SEED_PHRASE);
|
|
||||||
fid = await lookupFidByCustodyAddress(accountAddress, process.env.NEYNAR_API_KEY ?? 'FARCASTER_V2_FRAMES_DEMO');
|
|
||||||
|
|
||||||
// Determine webhook URL based on Neynar configuration
|
|
||||||
const webhookUrl = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
|
||||||
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
|
||||||
: `https://${domain}/api/webhook`;
|
|
||||||
|
|
||||||
frameMetadata = await generateFarcasterMetadata(domain, fid, accountAddress, process.env.SEED_PHRASE, webhookUrl);
|
|
||||||
console.log('✅ Frame metadata generated and signed');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prepare environment variables
|
|
||||||
const nextAuthSecret = process.env.NEXTAUTH_SECRET || crypto.randomBytes(32).toString('hex');
|
|
||||||
const vercelEnv = {
|
|
||||||
// Required vars
|
|
||||||
NEXTAUTH_SECRET: nextAuthSecret,
|
|
||||||
AUTH_SECRET: nextAuthSecret, // Fallback for some NextAuth versions
|
|
||||||
NEXTAUTH_URL: `https://${domain}`, // Add the deployment URL
|
|
||||||
NEXT_PUBLIC_URL: `https://${domain}`,
|
|
||||||
|
|
||||||
// Optional vars that should be set if they exist
|
|
||||||
...(process.env.NEYNAR_API_KEY && { NEYNAR_API_KEY: process.env.NEYNAR_API_KEY }),
|
|
||||||
...(process.env.NEYNAR_CLIENT_ID && { NEYNAR_CLIENT_ID: process.env.NEYNAR_CLIENT_ID }),
|
|
||||||
|
|
||||||
// Frame metadata - don't stringify here
|
|
||||||
...(frameMetadata && { FRAME_METADATA: frameMetadata }),
|
|
||||||
|
|
||||||
// Public vars
|
|
||||||
...Object.fromEntries(
|
|
||||||
Object.entries(process.env)
|
|
||||||
.filter(([key]) => key.startsWith('NEXT_PUBLIC_'))
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add or update env vars in Vercel project
|
|
||||||
console.log('\n📝 Setting up environment variables...');
|
|
||||||
for (const [key, value] of Object.entries(vercelEnv)) {
|
|
||||||
if (value) {
|
|
||||||
await setVercelEnvVar(key, value, projectRoot);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deploy the project
|
|
||||||
if (useGitHub) {
|
|
||||||
console.log('\nSetting up GitHub integration...');
|
|
||||||
execSync('vercel link', {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'inherit',
|
|
||||||
env: process.env
|
|
||||||
});
|
|
||||||
console.log('\n📦 Deploying with GitHub integration...');
|
|
||||||
} else {
|
|
||||||
console.log('\n📦 Deploying local code directly...');
|
|
||||||
}
|
|
||||||
|
|
||||||
execSync('vercel deploy --prod', {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'inherit',
|
|
||||||
env: process.env
|
|
||||||
});
|
|
||||||
// Verify the actual domain after deployment
|
|
||||||
|
|
||||||
console.log('\n🔍 Verifying deployment domain...');
|
|
||||||
|
|
||||||
// Create a temporary file path
|
|
||||||
const tempOutputFile = path.join(projectRoot, 'vercel_output.txt');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Redirect output to a file
|
|
||||||
execSync(`vercel project ls > "${tempOutputFile}" 2>&1`, {
|
|
||||||
cwd: projectRoot,
|
|
||||||
shell: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// Read the output file
|
|
||||||
const projectOutput = fs.readFileSync(tempOutputFile, 'utf8');
|
|
||||||
|
|
||||||
// Process the output
|
|
||||||
const projectLines = projectOutput
|
|
||||||
.split('\n')
|
|
||||||
.filter(line => line.includes('https://'));
|
|
||||||
|
|
||||||
// Find the line containing our project name
|
|
||||||
const currentProject = projectLines.find(line =>
|
|
||||||
line.includes(projectName)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (currentProject) {
|
|
||||||
// Extract the domain from the line
|
|
||||||
const domainMatch = currentProject.match(/https:\/\/([^\s]+)/);
|
|
||||||
if (domainMatch) {
|
|
||||||
const actualDomain = domainMatch[1];
|
|
||||||
if (actualDomain !== domain) {
|
|
||||||
console.log(`⚠️ Actual domain (${actualDomain}) differs from assumed domain (${domain})`);
|
|
||||||
console.log('🔄 Updating environment variables with correct domain...');
|
|
||||||
|
|
||||||
// Update domain-dependent environment variables
|
|
||||||
const webhookUrl = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
|
||||||
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
|
||||||
: `https://${actualDomain}/api/webhook`;
|
|
||||||
|
|
||||||
if (frameMetadata) {
|
|
||||||
frameMetadata = await generateFarcasterMetadata(actualDomain, fid, await validateSeedPhrase(process.env.SEED_PHRASE), process.env.SEED_PHRASE, webhookUrl);
|
|
||||||
// Update FRAME_METADATA env var using the new function
|
|
||||||
await setVercelEnvVar('FRAME_METADATA', frameMetadata, projectRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update NEXTAUTH_URL
|
|
||||||
await setVercelEnvVar('NEXTAUTH_URL', `https://${actualDomain}`, projectRoot);
|
|
||||||
|
|
||||||
// Update NEXT_PUBLIC_URL
|
|
||||||
await setVercelEnvVar('NEXT_PUBLIC_URL', `https://${actualDomain}`, projectRoot);
|
|
||||||
|
|
||||||
// Redeploy with updated environment variables
|
|
||||||
console.log('\n📦 Redeploying with correct domain...');
|
|
||||||
execSync('vercel deploy --prod', {
|
|
||||||
cwd: projectRoot,
|
|
||||||
stdio: 'inherit',
|
|
||||||
env: process.env
|
|
||||||
});
|
|
||||||
|
|
||||||
domain = actualDomain;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.warn('⚠️ Could not extract domain from project line');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.warn('⚠️ Could not find project in Vercel project list');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up the temporary file
|
|
||||||
fs.unlinkSync(tempOutputFile);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error:', error);
|
|
||||||
|
|
||||||
// Try to read the output file even if there was an error
|
|
||||||
try {
|
|
||||||
if (fs.existsSync(tempOutputFile)) {
|
|
||||||
const errorOutput = fs.readFileSync(tempOutputFile, 'utf8');
|
|
||||||
console.log('Error output file contents:', errorOutput);
|
|
||||||
fs.unlinkSync(tempOutputFile);
|
|
||||||
}
|
|
||||||
} catch (readError) {
|
|
||||||
console.error('Error reading output file:', readError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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');
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('\n❌ Deployment failed:', error.message);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
try {
|
|
||||||
// Print welcome message
|
|
||||||
console.log('🚀 Vercel Mini App Deployment');
|
|
||||||
console.log('This script will deploy your mini app to Vercel.');
|
|
||||||
console.log('\nThe script will:');
|
|
||||||
console.log('1. Check for required environment variables');
|
|
||||||
console.log('2. Set up a Vercel project (new or existing)');
|
|
||||||
console.log('3. Configure environment variables in Vercel');
|
|
||||||
console.log('4. Deploy and build your mini app (Vercel will run the build automatically)\n');
|
|
||||||
|
|
||||||
// Check for required environment variables
|
|
||||||
await checkRequiredEnvVars();
|
|
||||||
|
|
||||||
// Check for git remote
|
|
||||||
const remoteUrl = await getGitRemote();
|
|
||||||
let useGitHub = false;
|
|
||||||
|
|
||||||
if (remoteUrl) {
|
|
||||||
console.log('\n📦 Found GitHub repository:', remoteUrl);
|
|
||||||
const { useGitHubDeploy } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'confirm',
|
|
||||||
name: 'useGitHubDeploy',
|
|
||||||
message: 'Would you like to deploy from the GitHub repository?',
|
|
||||||
default: true
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
useGitHub = useGitHubDeploy;
|
|
||||||
} else {
|
|
||||||
console.log('\n⚠️ No GitHub repository found.');
|
|
||||||
const { action } = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'list',
|
|
||||||
name: 'action',
|
|
||||||
message: 'What would you like to do?',
|
|
||||||
choices: [
|
|
||||||
{ name: 'Deploy local code directly', value: 'deploy' },
|
|
||||||
{ name: 'Set up GitHub repository first', value: 'setup' }
|
|
||||||
],
|
|
||||||
default: 'deploy'
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (action === 'setup') {
|
|
||||||
console.log('\n👋 Please set up your GitHub repository first:');
|
|
||||||
console.log('1. Create a new repository on GitHub');
|
|
||||||
console.log('2. Run these commands:');
|
|
||||||
console.log(' git remote add origin <your-repo-url>');
|
|
||||||
console.log(' git push -u origin main');
|
|
||||||
console.log('\nThen run this script again to deploy.');
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check and install Vercel CLI if needed
|
|
||||||
if (!await checkVercelCLI()) {
|
|
||||||
console.log('Vercel CLI not found. Installing...');
|
|
||||||
await installVercelCLI();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login to Vercel
|
|
||||||
console.log('pre login');
|
|
||||||
if (!await loginToVercel()) {
|
|
||||||
console.error('\n❌ Failed to log in to Vercel. Please try again.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deploy to Vercel
|
|
||||||
await deployToVercel(useGitHub);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('\n❌ Error:', error.message);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
main();
|
|
||||||
|
|
||||||
1028
scripts/deploy.ts
Executable file
1028
scripts/deploy.ts
Executable file
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,23 @@ let tunnel;
|
|||||||
let nextDev;
|
let nextDev;
|
||||||
let isCleaningUp = false;
|
let isCleaningUp = false;
|
||||||
|
|
||||||
|
// Parse command line arguments for port
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
let port = 3000; // default port
|
||||||
|
|
||||||
|
// Look for --port=XXXX, --port XXXX, -p=XXXX, or -p XXXX
|
||||||
|
args.forEach((arg, index) => {
|
||||||
|
if (arg.startsWith('--port=')) {
|
||||||
|
port = parseInt(arg.split('=')[1]);
|
||||||
|
} else if (arg === '--port' && args[index + 1]) {
|
||||||
|
port = parseInt(args[index + 1]);
|
||||||
|
} else if (arg.startsWith('-p=')) {
|
||||||
|
port = parseInt(arg.split('=')[1]);
|
||||||
|
} else if (arg === '-p' && args[index + 1]) {
|
||||||
|
port = parseInt(args[index + 1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
async function checkPort(port) {
|
async function checkPort(port) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const server = createServer();
|
const server = createServer();
|
||||||
@@ -67,12 +84,12 @@ async function killProcessOnPort(port) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function startDev() {
|
async function startDev() {
|
||||||
// Check if port 3000 is already in use
|
// Check if the specified port is already in use
|
||||||
const isPortInUse = await checkPort(3000);
|
const isPortInUse = await checkPort(port);
|
||||||
if (isPortInUse) {
|
if (isPortInUse) {
|
||||||
console.error('Port 3000 is already in use. To find and kill the process using this port:\n\n' +
|
console.error(`Port ${port} is already in use. To find and kill the process using this port:\n\n` +
|
||||||
(process.platform === 'win32'
|
(process.platform === 'win32'
|
||||||
? '1. Run: netstat -ano | findstr :3000\n' +
|
? `1. Run: netstat -ano | findstr :${port}\n` +
|
||||||
'2. Note the PID (Process ID) from the output\n' +
|
'2. Note the PID (Process ID) from the output\n' +
|
||||||
'3. Run: taskkill /PID <PID> /F\n'
|
'3. Run: taskkill /PID <PID> /F\n'
|
||||||
: `On macOS/Linux, run:\nnpm run cleanup\n`) +
|
: `On macOS/Linux, run:\nnpm run cleanup\n`) +
|
||||||
@@ -81,11 +98,11 @@ async function startDev() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const useTunnel = process.env.USE_TUNNEL === 'true';
|
const useTunnel = process.env.USE_TUNNEL === 'true';
|
||||||
let frameUrl;
|
let miniAppUrl;
|
||||||
|
|
||||||
if (useTunnel) {
|
if (useTunnel) {
|
||||||
// Start localtunnel and get URL
|
// Start localtunnel and get URL
|
||||||
tunnel = await localtunnel({ port: 3000 });
|
tunnel = await localtunnel({ port: port });
|
||||||
let ip;
|
let ip;
|
||||||
try {
|
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());
|
||||||
@@ -93,7 +110,7 @@ async function startDev() {
|
|||||||
console.error('Error getting IP address:', error);
|
console.error('Error getting IP address:', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
frameUrl = tunnel.url;
|
miniAppUrl = tunnel.url;
|
||||||
console.log(`
|
console.log(`
|
||||||
🌐 Local tunnel URL: ${tunnel.url}
|
🌐 Local tunnel URL: ${tunnel.url}
|
||||||
|
|
||||||
@@ -117,12 +134,12 @@ async function startDev() {
|
|||||||
5. Click "Preview" (note that it may take ~10 seconds to load)
|
5. Click "Preview" (note that it may take ~10 seconds to load)
|
||||||
`);
|
`);
|
||||||
} else {
|
} else {
|
||||||
frameUrl = 'http://localhost:3000';
|
miniAppUrl = `http://localhost:${port}`;
|
||||||
console.log(`
|
console.log(`
|
||||||
💻 To test your mini app:
|
💻 To test your mini app:
|
||||||
1. Open the Warpcast Mini App Developer Tools: https://warpcast.com/~/developers
|
1. Open the Warpcast Mini App Developer Tools: https://warpcast.com/~/developers
|
||||||
2. Scroll down to the "Preview Mini App" tool
|
2. Scroll down to the "Preview Mini App" tool
|
||||||
3. Enter this URL: ${frameUrl}
|
3. Enter this URL: ${miniAppUrl}
|
||||||
4. Click "Preview" to test your mini app (note that it may take ~5 seconds to load the first time)
|
4. Click "Preview" to test your mini app (note that it may take ~5 seconds to load the first time)
|
||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
@@ -130,9 +147,9 @@ async function startDev() {
|
|||||||
// Start next dev with appropriate configuration
|
// 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'], {
|
nextDev = spawn(nextBin, ['dev', '-p', port.toString()], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
env: { ...process.env, NEXT_PUBLIC_URL: frameUrl, NEXTAUTH_URL: frameUrl },
|
env: { ...process.env, NEXT_PUBLIC_URL: miniAppUrl, NEXTAUTH_URL: miniAppUrl },
|
||||||
cwd: projectRoot,
|
cwd: projectRoot,
|
||||||
shell: process.platform === 'win32' // Add shell option for Windows
|
shell: process.platform === 'win32' // Add shell option for Windows
|
||||||
});
|
});
|
||||||
@@ -174,8 +191,8 @@ async function startDev() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Force kill any remaining processes on port 3000
|
// Force kill any remaining processes on the specified port
|
||||||
await killProcessOnPort(3000);
|
await killProcessOnPort(port);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error during cleanup:', error);
|
console.error('Error during cleanup:', error);
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import { getFarcasterMetadata } from '../../../lib/utils';
|
import { getFarcasterDomainManifest } from '~/lib/utils';
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const config = await getFarcasterMetadata();
|
const config = await getFarcasterDomainManifest();
|
||||||
return NextResponse.json(config);
|
return NextResponse.json(config);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error generating metadata:', error);
|
console.error('Error generating metadata:', error);
|
||||||
|
|||||||
16
src/app/api/auth/nonce/route.ts
Normal file
16
src/app/api/auth/nonce/route.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { getNeynarClient } from '~/lib/neynar';
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const client = getNeynarClient();
|
||||||
|
const response = await client.fetchNonce();
|
||||||
|
return NextResponse.json(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching nonce:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch nonce' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/app/api/auth/session-signers/route.ts
Normal file
43
src/app/api/auth/session-signers/route.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { getNeynarClient } from '~/lib/neynar';
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
try {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const message = searchParams.get('message');
|
||||||
|
const signature = searchParams.get('signature');
|
||||||
|
|
||||||
|
if (!message || !signature) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Message and signature are required' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = getNeynarClient();
|
||||||
|
const data = await client.fetchSigners({ message, signature });
|
||||||
|
const signers = data.signers;
|
||||||
|
|
||||||
|
// Fetch user data if signers exist
|
||||||
|
let user = null;
|
||||||
|
if (signers && signers.length > 0 && signers[0].fid) {
|
||||||
|
const {
|
||||||
|
users: [fetchedUser],
|
||||||
|
} = await client.fetchBulkUsers({
|
||||||
|
fids: [signers[0].fid],
|
||||||
|
});
|
||||||
|
user = fetchedUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
signers,
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in session-signers API:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch signers' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
42
src/app/api/auth/signer/route.ts
Normal file
42
src/app/api/auth/signer/route.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { getNeynarClient } from '~/lib/neynar';
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
try {
|
||||||
|
const neynarClient = getNeynarClient();
|
||||||
|
const signer = await neynarClient.createSigner();
|
||||||
|
return NextResponse.json(signer);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching signer:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch signer' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const signerUuid = searchParams.get('signerUuid');
|
||||||
|
|
||||||
|
if (!signerUuid) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'signerUuid is required' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const neynarClient = getNeynarClient();
|
||||||
|
const signer = await neynarClient.lookupSigner({
|
||||||
|
signerUuid,
|
||||||
|
});
|
||||||
|
return NextResponse.json(signer);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching signed key:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch signed key' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
91
src/app/api/auth/signer/signed_key/route.ts
Normal file
91
src/app/api/auth/signer/signed_key/route.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { getNeynarClient } from '~/lib/neynar';
|
||||||
|
import { mnemonicToAccount } from 'viem/accounts';
|
||||||
|
import {
|
||||||
|
SIGNED_KEY_REQUEST_TYPE,
|
||||||
|
SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN,
|
||||||
|
} from '~/lib/constants';
|
||||||
|
|
||||||
|
const postRequiredFields = ['signerUuid', 'publicKey'];
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json();
|
||||||
|
|
||||||
|
// Validate required fields
|
||||||
|
for (const field of postRequiredFields) {
|
||||||
|
if (!body[field]) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `${field} is required` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { signerUuid, publicKey, redirectUrl } = body;
|
||||||
|
|
||||||
|
if (redirectUrl && typeof redirectUrl !== 'string') {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'redirectUrl must be a string' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get the app's account from seed phrase
|
||||||
|
const seedPhrase = process.env.SEED_PHRASE;
|
||||||
|
const shouldSponsor = process.env.SPONSOR_SIGNER === 'true';
|
||||||
|
|
||||||
|
if (!seedPhrase) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'App configuration missing (SEED_PHRASE or FID)' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const neynarClient = getNeynarClient();
|
||||||
|
|
||||||
|
const account = mnemonicToAccount(seedPhrase);
|
||||||
|
|
||||||
|
const {
|
||||||
|
user: { fid },
|
||||||
|
} = await neynarClient.lookupUserByCustodyAddress({
|
||||||
|
custodyAddress: account.address,
|
||||||
|
});
|
||||||
|
|
||||||
|
const appFid = fid;
|
||||||
|
|
||||||
|
// Generate deadline (24 hours from now)
|
||||||
|
const deadline = Math.floor(Date.now() / 1000) + 86400;
|
||||||
|
|
||||||
|
// Generate EIP-712 signature
|
||||||
|
const signature = await account.signTypedData({
|
||||||
|
domain: SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN,
|
||||||
|
types: {
|
||||||
|
SignedKeyRequest: SIGNED_KEY_REQUEST_TYPE,
|
||||||
|
},
|
||||||
|
primaryType: 'SignedKeyRequest',
|
||||||
|
message: {
|
||||||
|
requestFid: BigInt(appFid),
|
||||||
|
key: publicKey,
|
||||||
|
deadline: BigInt(deadline),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const signer = await neynarClient.registerSignedKey({
|
||||||
|
appFid,
|
||||||
|
deadline,
|
||||||
|
signature,
|
||||||
|
signerUuid,
|
||||||
|
...(redirectUrl && { redirectUrl }),
|
||||||
|
...(shouldSponsor && { sponsor: { sponsored_by_neynar: true } }),
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(signer);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error registering signed key:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to register signed key' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
38
src/app/api/auth/signers/route.ts
Normal file
38
src/app/api/auth/signers/route.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { getNeynarClient } from '~/lib/neynar';
|
||||||
|
|
||||||
|
const requiredParams = ['message', 'signature'];
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const params: Record<string, string | null> = {};
|
||||||
|
for (const param of requiredParams) {
|
||||||
|
params[param] = searchParams.get(param);
|
||||||
|
if (!params[param]) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: `${param} parameter is required`,
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = params.message as string;
|
||||||
|
const signature = params.signature as string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = getNeynarClient();
|
||||||
|
const data = await client.fetchSigners({ message, signature });
|
||||||
|
const signers = data.signers;
|
||||||
|
return NextResponse.json({
|
||||||
|
signers,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching signers:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch signers' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
46
src/app/api/auth/validate/route.ts
Normal file
46
src/app/api/auth/validate/route.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { createClient, Errors } from '@farcaster/quick-auth';
|
||||||
|
|
||||||
|
const client = createClient();
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
const { token } = await request.json();
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json({ error: 'Token is required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get domain from environment or request
|
||||||
|
const domain = process.env.NEXT_PUBLIC_URL
|
||||||
|
? new URL(process.env.NEXT_PUBLIC_URL).hostname
|
||||||
|
: request.headers.get('host') || 'localhost';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Use the official QuickAuth library to verify the JWT
|
||||||
|
const payload = await client.verifyJwt({
|
||||||
|
token,
|
||||||
|
domain,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
user: {
|
||||||
|
fid: payload.sub,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Errors.InvalidTokenError) {
|
||||||
|
console.info('Invalid token:', e.message);
|
||||||
|
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Token validation error:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Internal server error' },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
46
src/app/api/best-friends/route.ts
Normal file
46
src/app/api/best-friends/route.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const apiKey = process.env.NEYNAR_API_KEY;
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const fid = searchParams.get('fid');
|
||||||
|
|
||||||
|
if (!apiKey) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fid) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'FID parameter is required' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`https://api.neynar.com/v2/farcaster/user/best_friends?fid=${fid}&limit=3`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"x-api-key": apiKey,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Neynar API error: ${response.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { users } = await response.json() as { users: { user: { fid: number; username: string } }[] };
|
||||||
|
|
||||||
|
return NextResponse.json({ bestFriends: users });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch best friends:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch best friends. Please check your Neynar API key and try again.' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
return new ImageResponse(
|
return new ImageResponse(
|
||||||
(
|
(
|
||||||
<div tw="flex h-full w-full flex-col justify-center items-center relative bg-purple-600">
|
<div tw="flex h-full w-full flex-col justify-center items-center relative bg-primary">
|
||||||
{user?.pfp_url && (
|
{user?.pfp_url && (
|
||||||
<div tw="flex w-96 h-96 rounded-full overflow-hidden mb-8 border-8 border-white">
|
<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" />
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { notificationDetailsSchema } from "@farcaster/frame-sdk";
|
import { notificationDetailsSchema } from "@farcaster/miniapp-sdk";
|
||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { setUserNotificationDetails } from "~/lib/kv";
|
import { setUserNotificationDetails } from "~/lib/kv";
|
||||||
import { sendFrameNotification } from "~/lib/notifs";
|
import { sendMiniAppNotification } from "~/lib/notifs";
|
||||||
import { sendNeynarFrameNotification } from "~/lib/neynar";
|
import { sendNeynarMiniAppNotification } from "~/lib/neynar";
|
||||||
|
|
||||||
const requestSchema = z.object({
|
const requestSchema = z.object({
|
||||||
fid: z.number(),
|
fid: z.number(),
|
||||||
@@ -34,7 +34,7 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Use appropriate notification function based on Neynar status
|
// Use appropriate notification function based on Neynar status
|
||||||
const sendNotification = neynarEnabled ? sendNeynarFrameNotification : sendFrameNotification;
|
const sendNotification = neynarEnabled ? sendNeynarMiniAppNotification : sendMiniAppNotification;
|
||||||
const sendResult = await sendNotification({
|
const sendResult = await sendNotification({
|
||||||
fid: Number(requestBody.data.fid),
|
fid: Number(requestBody.data.fid),
|
||||||
title: "Test notification",
|
title: "Test notification",
|
||||||
|
|||||||
39
src/app/api/users/route.ts
Normal file
39
src/app/api/users/route.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { NeynarAPIClient } from '@neynar/nodejs-sdk';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const apiKey = process.env.NEYNAR_API_KEY;
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const fids = searchParams.get('fids');
|
||||||
|
|
||||||
|
if (!apiKey) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fids) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'FIDs parameter is required' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const neynar = new NeynarAPIClient({ apiKey });
|
||||||
|
const fidsArray = fids.split(',').map(fid => parseInt(fid.trim()));
|
||||||
|
|
||||||
|
const { users } = await neynar.fetchBulkUsers({
|
||||||
|
fids: fidsArray,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ users });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch users:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to fetch users. Please check your Neynar API key and try again.' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,13 +2,14 @@ import {
|
|||||||
ParseWebhookEvent,
|
ParseWebhookEvent,
|
||||||
parseWebhookEvent,
|
parseWebhookEvent,
|
||||||
verifyAppKeyWithNeynar,
|
verifyAppKeyWithNeynar,
|
||||||
} from "@farcaster/frame-node";
|
} from "@farcaster/miniapp-node";
|
||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
|
import { APP_NAME } from "~/lib/constants";
|
||||||
import {
|
import {
|
||||||
deleteUserNotificationDetails,
|
deleteUserNotificationDetails,
|
||||||
setUserNotificationDetails,
|
setUserNotificationDetails,
|
||||||
} from "~/lib/kv";
|
} from "~/lib/kv";
|
||||||
import { sendFrameNotification } from "~/lib/notifs";
|
import { sendMiniAppNotification } from "~/lib/notifs";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
// If Neynar is enabled, we don't need to handle webhooks here
|
// If Neynar is enabled, we don't need to handle webhooks here
|
||||||
@@ -58,10 +59,10 @@ export async function POST(request: NextRequest) {
|
|||||||
case "frame_added":
|
case "frame_added":
|
||||||
if (event.notificationDetails) {
|
if (event.notificationDetails) {
|
||||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||||
await sendFrameNotification({
|
await sendMiniAppNotification({
|
||||||
fid,
|
fid,
|
||||||
title: "Welcome to Frames v2",
|
title: `Welcome to ${APP_NAME}`,
|
||||||
body: "Frame is now added to your client",
|
body: "Mini app is now added to your client",
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await deleteUserNotificationDetails(fid);
|
await deleteUserNotificationDetails(fid);
|
||||||
@@ -74,9 +75,9 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
case "notifications_enabled":
|
case "notifications_enabled":
|
||||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||||
await sendFrameNotification({
|
await sendMiniAppNotification({
|
||||||
fid,
|
fid,
|
||||||
title: "Ding ding ding",
|
title: `Welcome to ${APP_NAME}`,
|
||||||
body: "Notifications are now enabled",
|
body: "Notifications are now enabled",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ import dynamic from "next/dynamic";
|
|||||||
import { APP_NAME } from "~/lib/constants";
|
import { APP_NAME } from "~/lib/constants";
|
||||||
|
|
||||||
// note: dynamic import is required for components that use the Frame SDK
|
// note: dynamic import is required for components that use the Frame SDK
|
||||||
const Demo = dynamic(() => import("~/components/Demo"), {
|
const AppComponent = dynamic(() => import("~/components/App"), {
|
||||||
ssr: false,
|
ssr: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function App(
|
export default function App(
|
||||||
{ title }: { title?: string } = { title: APP_NAME }
|
{ title }: { title?: string } = { title: APP_NAME }
|
||||||
) {
|
) {
|
||||||
return <Demo title={title} />;
|
return <AppComponent title={title} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* DESIGN SYSTEM - DO NOT EDIT UNLESS NECESSARY
|
||||||
|
*
|
||||||
|
* This file contains the centralized design system for the mini app.
|
||||||
|
* These component classes establish the visual consistency across all components.
|
||||||
|
*
|
||||||
|
* ⚠️ AI SHOULD NOT NORMALLY EDIT THIS FILE ⚠️
|
||||||
|
*
|
||||||
|
* Instead of modifying these classes, AI should:
|
||||||
|
* 1. Use existing component classes (e.g., .btn, .card, .input)
|
||||||
|
* 2. Use Tailwind utilities for one-off styling
|
||||||
|
* 3. Create new React components rather than new CSS classes
|
||||||
|
* 4. Only edit this file for specific bug fixes or accessibility improvements
|
||||||
|
*
|
||||||
|
* When AI needs to style something:
|
||||||
|
* ✅ Good: <button className="btn btn-primary">Click me</button>
|
||||||
|
* ✅ Good: <div className="bg-primary text-white px-4 py-2 rounded">Custom</div>
|
||||||
|
* ❌ Bad: Adding new CSS classes here for component-specific styling
|
||||||
|
*
|
||||||
|
* This design system is intentionally minimal to prevent bloat and maintain consistency.
|
||||||
|
*/
|
||||||
|
|
||||||
@tailwind base;
|
@tailwind base;
|
||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
@@ -34,3 +56,63 @@ body {
|
|||||||
--radius: 0.5rem;
|
--radius: 0.5rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
/* Global container styles for consistent layout */
|
||||||
|
.container {
|
||||||
|
@apply mx-auto max-w-md px-4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container-wide {
|
||||||
|
@apply mx-auto max-w-lg px-4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container-narrow {
|
||||||
|
@apply mx-auto max-w-sm px-4;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Global card styles */
|
||||||
|
.card {
|
||||||
|
@apply bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-primary {
|
||||||
|
@apply bg-primary/10 border-primary/20;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Global button styles */
|
||||||
|
.btn {
|
||||||
|
@apply inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
@apply bg-primary text-white hover:bg-primary-dark focus:ring-primary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
@apply bg-secondary text-gray-900 hover:bg-gray-200 focus:ring-gray-500 dark:bg-secondary-dark dark:text-gray-100 dark:hover:bg-gray-600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-outline {
|
||||||
|
@apply border border-gray-300 bg-transparent hover:bg-gray-50 focus:ring-gray-500 dark:border-gray-600 dark:hover:bg-gray-800;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Global input styles */
|
||||||
|
.input {
|
||||||
|
@apply block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 placeholder-gray-500 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder-gray-400;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Global loading spinner */
|
||||||
|
.spinner {
|
||||||
|
@apply animate-spin rounded-full border-2 border-gray-300 border-t-primary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner-primary {
|
||||||
|
@apply animate-spin rounded-full border-2 border-white border-t-transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Global focus styles */
|
||||||
|
.focus-ring {
|
||||||
|
@apply focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from 'next';
|
||||||
|
|
||||||
import { getSession } from "~/auth"
|
import '~/app/globals.css';
|
||||||
import "~/app/globals.css";
|
import { Providers } from '~/app/providers';
|
||||||
import { Providers } from "~/app/providers";
|
import { APP_NAME, APP_DESCRIPTION } from '~/lib/constants';
|
||||||
import { APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: APP_NAME,
|
title: APP_NAME,
|
||||||
@@ -15,12 +14,27 @@ export default async function RootLayout({
|
|||||||
}: Readonly<{
|
}: Readonly<{
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}>) {
|
}>) {
|
||||||
const session = await getSession()
|
// Only get session if sponsored signer is enabled or seed phrase is provided
|
||||||
|
const sponsorSigner = process.env.SPONSOR_SIGNER === 'true';
|
||||||
|
const hasSeedPhrase = !!process.env.SEED_PHRASE;
|
||||||
|
const shouldUseSession = sponsorSigner || hasSeedPhrase;
|
||||||
|
|
||||||
|
let session = null;
|
||||||
|
if (shouldUseSession) {
|
||||||
|
try {
|
||||||
|
const { getSession } = await import('~/auth');
|
||||||
|
session = await getSession();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to get session:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<body>
|
<body>
|
||||||
<Providers session={session}>{children}</Providers>
|
<Providers session={session} shouldUseSession={shouldUseSession}>
|
||||||
|
{children}
|
||||||
|
</Providers>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Metadata } from "next";
|
import { Metadata } from "next";
|
||||||
import App from "./app";
|
import App from "./app";
|
||||||
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from "~/lib/constants";
|
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from "~/lib/constants";
|
||||||
import { getFrameEmbedMetadata } from "~/lib/utils";
|
import { getMiniAppEmbedMetadata } from "~/lib/utils";
|
||||||
|
|
||||||
export const revalidate = 300;
|
export const revalidate = 300;
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
|||||||
images: [APP_OG_IMAGE_URL],
|
images: [APP_OG_IMAGE_URL],
|
||||||
},
|
},
|
||||||
other: {
|
other: {
|
||||||
"fc:frame": JSON.stringify(getFrameEmbedMetadata()),
|
"fc:frame": JSON.stringify(getMiniAppEmbedMetadata()),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,61 @@
|
|||||||
"use client";
|
'use client';
|
||||||
|
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from 'next/dynamic';
|
||||||
import type { Session } from "next-auth"
|
import type { Session } from 'next-auth';
|
||||||
import { SessionProvider } from "next-auth/react"
|
import { SessionProvider } from 'next-auth/react';
|
||||||
import { FrameProvider } from "~/components/providers/FrameProvider";
|
import { MiniAppProvider } from '@neynar/react';
|
||||||
import { SafeFarcasterSolanaProvider } from "~/components/providers/SafeFarcasterSolanaProvider";
|
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
|
||||||
|
import { ANALYTICS_ENABLED } from '~/lib/constants';
|
||||||
|
import { AuthKitProvider } from '@farcaster/auth-kit';
|
||||||
|
|
||||||
const WagmiProvider = dynamic(
|
const WagmiProvider = dynamic(
|
||||||
() => import("~/components/providers/WagmiProvider"),
|
() => import('~/components/providers/WagmiProvider'),
|
||||||
{
|
{
|
||||||
ssr: false,
|
ssr: false,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
export function Providers({ session, children }: { session: Session | null, children: React.ReactNode }) {
|
export function Providers({
|
||||||
const solanaEndpoint = process.env.SOLANA_RPC_ENDPOINT || "https://solana-rpc.publicnode.com";
|
session,
|
||||||
|
children,
|
||||||
|
shouldUseSession = false,
|
||||||
|
}: {
|
||||||
|
session: Session | null;
|
||||||
|
children: React.ReactNode;
|
||||||
|
shouldUseSession?: boolean;
|
||||||
|
}) {
|
||||||
|
const solanaEndpoint =
|
||||||
|
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
|
||||||
|
|
||||||
|
// Only wrap with SessionProvider if next auth is used
|
||||||
|
if (shouldUseSession) {
|
||||||
return (
|
return (
|
||||||
<SessionProvider session={session}>
|
<SessionProvider session={session}>
|
||||||
<WagmiProvider>
|
<WagmiProvider>
|
||||||
<FrameProvider>
|
<MiniAppProvider
|
||||||
|
analyticsEnabled={ANALYTICS_ENABLED}
|
||||||
|
backButtonEnabled={true}
|
||||||
|
>
|
||||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||||
{children}
|
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||||
</SafeFarcasterSolanaProvider>
|
</SafeFarcasterSolanaProvider>
|
||||||
</FrameProvider>
|
</MiniAppProvider>
|
||||||
</WagmiProvider>
|
</WagmiProvider>
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Return without SessionProvider if no session
|
||||||
|
return (
|
||||||
|
<WagmiProvider>
|
||||||
|
<MiniAppProvider
|
||||||
|
analyticsEnabled={ANALYTICS_ENABLED}
|
||||||
|
backButtonEnabled={true}
|
||||||
|
>
|
||||||
|
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||||
|
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||||
|
</SafeFarcasterSolanaProvider>
|
||||||
|
</MiniAppProvider>
|
||||||
|
</WagmiProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
import { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { APP_URL, APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
|
import { APP_URL, APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
|
||||||
import { getFrameEmbedMetadata } from "~/lib/utils";
|
import { getMiniAppEmbedMetadata } from "~/lib/utils";
|
||||||
export const revalidate = 300;
|
export const revalidate = 300;
|
||||||
|
|
||||||
// This is an example of how to generate a dynamically generated share page based on fid:
|
// This is an example of how to generate a dynamically generated share page based on fid:
|
||||||
// Sharing this route e.g. exmaple.com/share/123 will generate a share page for fid 123,
|
// Sharing this route e.g. exmaple.com/share/123 will generate a share page for fid 123,
|
||||||
// with the image dynamically generated by the opengraph-image API route.
|
// with the image dynamically generated by the opengraph-image API route.
|
||||||
export async function generateMetadata({ params }: { params: { fid: string } }): Promise<Metadata> {
|
export async function generateMetadata({
|
||||||
const fid = params.fid;
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ fid: string }>;
|
||||||
|
}): Promise<Metadata> {
|
||||||
|
const { fid } = await params;
|
||||||
const imageUrl = `${APP_URL}/api/opengraph-image?fid=${fid}`;
|
const imageUrl = `${APP_URL}/api/opengraph-image?fid=${fid}`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -19,7 +23,7 @@ export async function generateMetadata({ params }: { params: { fid: string } }):
|
|||||||
images: [imageUrl],
|
images: [imageUrl],
|
||||||
},
|
},
|
||||||
other: {
|
other: {
|
||||||
"fc:frame": JSON.stringify(getFrameEmbedMetadata(imageUrl)),
|
"fc:frame": JSON.stringify(getMiniAppEmbedMetadata(imageUrl)),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
386
src/auth.ts
386
src/auth.ts
@@ -1,11 +1,200 @@
|
|||||||
import { AuthOptions, getServerSession } from "next-auth"
|
import { AuthOptions, getServerSession } from 'next-auth';
|
||||||
import CredentialsProvider from "next-auth/providers/credentials";
|
import CredentialsProvider from 'next-auth/providers/credentials';
|
||||||
import { createAppClient, viemConnector } from "@farcaster/auth-client";
|
import { createAppClient, viemConnector } from '@farcaster/auth-client';
|
||||||
|
|
||||||
declare module "next-auth" {
|
declare module 'next-auth' {
|
||||||
interface Session {
|
interface Session {
|
||||||
user: {
|
provider?: string;
|
||||||
|
user?: {
|
||||||
fid: number;
|
fid: number;
|
||||||
|
object?: 'user';
|
||||||
|
username?: string;
|
||||||
|
display_name?: string;
|
||||||
|
pfp_url?: string;
|
||||||
|
custody_address?: string;
|
||||||
|
profile?: {
|
||||||
|
bio: {
|
||||||
|
text: string;
|
||||||
|
mentioned_profiles?: Array<{
|
||||||
|
object: 'user_dehydrated';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
}>;
|
||||||
|
mentioned_profiles_ranges?: Array<{
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
location?: {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
address: {
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
country: string;
|
||||||
|
country_code: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
follower_count?: number;
|
||||||
|
following_count?: number;
|
||||||
|
verifications?: string[];
|
||||||
|
verified_addresses?: {
|
||||||
|
eth_addresses: string[];
|
||||||
|
sol_addresses: string[];
|
||||||
|
primary: {
|
||||||
|
eth_address: string;
|
||||||
|
sol_address: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
verified_accounts?: Array<Record<string, unknown>>;
|
||||||
|
power_badge?: boolean;
|
||||||
|
url?: string;
|
||||||
|
experimental?: {
|
||||||
|
neynar_user_score: number;
|
||||||
|
deprecation_notice: string;
|
||||||
|
};
|
||||||
|
score?: number;
|
||||||
|
};
|
||||||
|
signers?: {
|
||||||
|
object: 'signer';
|
||||||
|
signer_uuid: string;
|
||||||
|
public_key: string;
|
||||||
|
status: 'approved';
|
||||||
|
fid: number;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
provider?: string;
|
||||||
|
signers?: Array<{
|
||||||
|
object: 'signer';
|
||||||
|
signer_uuid: string;
|
||||||
|
public_key: string;
|
||||||
|
status: 'approved';
|
||||||
|
fid: number;
|
||||||
|
}>;
|
||||||
|
user?: {
|
||||||
|
object: 'user';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
profile: {
|
||||||
|
bio: {
|
||||||
|
text: string;
|
||||||
|
mentioned_profiles?: Array<{
|
||||||
|
object: 'user_dehydrated';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
}>;
|
||||||
|
mentioned_profiles_ranges?: Array<{
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
location?: {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
address: {
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
country: string;
|
||||||
|
country_code: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
follower_count: number;
|
||||||
|
following_count: number;
|
||||||
|
verifications: string[];
|
||||||
|
verified_addresses: {
|
||||||
|
eth_addresses: string[];
|
||||||
|
sol_addresses: string[];
|
||||||
|
primary: {
|
||||||
|
eth_address: string;
|
||||||
|
sol_address: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
verified_accounts: Array<Record<string, unknown>>;
|
||||||
|
power_badge: boolean;
|
||||||
|
url?: string;
|
||||||
|
experimental?: {
|
||||||
|
neynar_user_score: number;
|
||||||
|
deprecation_notice: string;
|
||||||
|
};
|
||||||
|
score: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface JWT {
|
||||||
|
provider?: string;
|
||||||
|
signers?: Array<{
|
||||||
|
object: 'signer';
|
||||||
|
signer_uuid: string;
|
||||||
|
public_key: string;
|
||||||
|
status: 'approved';
|
||||||
|
fid: number;
|
||||||
|
}>;
|
||||||
|
user?: {
|
||||||
|
object: 'user';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
profile: {
|
||||||
|
bio: {
|
||||||
|
text: string;
|
||||||
|
mentioned_profiles?: Array<{
|
||||||
|
object: 'user_dehydrated';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
}>;
|
||||||
|
mentioned_profiles_ranges?: Array<{
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
location?: {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
address: {
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
country: string;
|
||||||
|
country_code: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
follower_count: number;
|
||||||
|
following_count: number;
|
||||||
|
verifications: string[];
|
||||||
|
verified_addresses: {
|
||||||
|
eth_addresses: string[];
|
||||||
|
sol_addresses: string[];
|
||||||
|
primary: {
|
||||||
|
eth_address: string;
|
||||||
|
sol_address: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
verified_accounts?: Array<Record<string, unknown>>;
|
||||||
|
power_badge?: boolean;
|
||||||
|
url?: string;
|
||||||
|
experimental?: {
|
||||||
|
neynar_user_score: number;
|
||||||
|
deprecation_notice: string;
|
||||||
|
};
|
||||||
|
score?: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,40 +218,46 @@ export const authOptions: AuthOptions = {
|
|||||||
// Configure one or more authentication providers
|
// Configure one or more authentication providers
|
||||||
providers: [
|
providers: [
|
||||||
CredentialsProvider({
|
CredentialsProvider({
|
||||||
name: "Sign in with Farcaster",
|
id: 'farcaster',
|
||||||
|
name: 'Sign in with Farcaster',
|
||||||
credentials: {
|
credentials: {
|
||||||
message: {
|
message: {
|
||||||
label: "Message",
|
label: 'Message',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
},
|
},
|
||||||
signature: {
|
signature: {
|
||||||
label: "Signature",
|
label: 'Signature',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
|
},
|
||||||
|
nonce: {
|
||||||
|
label: 'Nonce',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'Custom nonce (optional)',
|
||||||
},
|
},
|
||||||
// In a production app with a server, these should be fetched from
|
// In a production app with a server, these should be fetched from
|
||||||
// your Farcaster data indexer rather than have them accepted as part
|
// your Farcaster data indexer rather than have them accepted as part
|
||||||
// of credentials.
|
// of credentials.
|
||||||
// question: should these natively use the Neynar API?
|
// question: should these natively use the Neynar API?
|
||||||
name: {
|
name: {
|
||||||
label: "Name",
|
label: 'Name',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
},
|
},
|
||||||
pfp: {
|
pfp: {
|
||||||
label: "Pfp",
|
label: 'Pfp',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
async authorize(credentials, req) {
|
async authorize(credentials, req) {
|
||||||
const csrfToken = req?.body?.csrfToken;
|
const nonce = req?.body?.csrfToken;
|
||||||
if (!csrfToken) {
|
|
||||||
console.error('CSRF token is missing from request');
|
if (!nonce) {
|
||||||
|
console.error('No nonce or CSRF token provided');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const appClient = createAppClient({
|
const appClient = createAppClient({
|
||||||
ethereum: viemConnector(),
|
ethereum: viemConnector(),
|
||||||
});
|
});
|
||||||
@@ -73,8 +268,9 @@ export const authOptions: AuthOptions = {
|
|||||||
message: credentials?.message as string,
|
message: credentials?.message as string,
|
||||||
signature: credentials?.signature as `0x${string}`,
|
signature: credentials?.signature as `0x${string}`,
|
||||||
domain,
|
domain,
|
||||||
nonce: csrfToken,
|
nonce,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { success, fid } = verifyResponse;
|
const { success, fid } = verifyResponse;
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
@@ -83,47 +279,155 @@ export const authOptions: AuthOptions = {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
id: fid.toString(),
|
id: fid.toString(),
|
||||||
|
name: credentials?.name || `User ${fid}`,
|
||||||
|
image: credentials?.pfp || null,
|
||||||
|
provider: 'farcaster',
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
CredentialsProvider({
|
||||||
|
id: 'neynar',
|
||||||
|
name: 'Sign in with Neynar',
|
||||||
|
credentials: {
|
||||||
|
message: {
|
||||||
|
label: 'Message',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: '0x0',
|
||||||
|
},
|
||||||
|
signature: {
|
||||||
|
label: 'Signature',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: '0x0',
|
||||||
|
},
|
||||||
|
nonce: {
|
||||||
|
label: 'Nonce',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'Custom nonce (optional)',
|
||||||
|
},
|
||||||
|
fid: {
|
||||||
|
label: 'FID',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: '0',
|
||||||
|
},
|
||||||
|
signers: {
|
||||||
|
label: 'Signers',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'JSON string of signers',
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
label: 'User Data',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'JSON string of user data',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async authorize(credentials) {
|
||||||
|
const nonce = credentials?.nonce;
|
||||||
|
|
||||||
|
if (!nonce) {
|
||||||
|
console.error('No nonce or CSRF token provided for Neynar auth');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For Neynar, we can use a different validation approach
|
||||||
|
// This could involve validating against Neynar's API or using their SDK
|
||||||
|
try {
|
||||||
|
// Validate the signature using Farcaster's auth client (same as Farcaster provider)
|
||||||
|
const appClient = createAppClient({
|
||||||
|
ethereum: viemConnector(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const domain = getDomainFromUrl(process.env.NEXTAUTH_URL);
|
||||||
|
|
||||||
|
const verifyResponse = await appClient.verifySignInMessage({
|
||||||
|
message: credentials?.message as string,
|
||||||
|
signature: credentials?.signature as `0x${string}`,
|
||||||
|
domain,
|
||||||
|
nonce,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { success, fid } = verifyResponse;
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate that the provided FID matches the verified FID
|
||||||
|
if (credentials?.fid && parseInt(credentials.fid) !== fid) {
|
||||||
|
console.error('FID mismatch in Neynar auth');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: fid.toString(),
|
||||||
|
provider: 'neynar',
|
||||||
|
signers: credentials?.signers
|
||||||
|
? JSON.parse(credentials.signers)
|
||||||
|
: undefined,
|
||||||
|
user: credentials?.user ? JSON.parse(credentials.user) : undefined,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in Neynar auth:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
callbacks: {
|
callbacks: {
|
||||||
session: async ({ session, token }) => {
|
session: async ({ session, token }) => {
|
||||||
if (session?.user) {
|
// Set provider at the root level
|
||||||
session.user.fid = parseInt(token.sub ?? '');
|
session.provider = token.provider as string;
|
||||||
|
|
||||||
|
if (token.provider === 'farcaster') {
|
||||||
|
// For Farcaster, simple structure
|
||||||
|
session.user = {
|
||||||
|
fid: parseInt(token.sub ?? ''),
|
||||||
|
};
|
||||||
|
} else if (token.provider === 'neynar') {
|
||||||
|
// For Neynar, use full user data structure from user
|
||||||
|
session.user = token.user as typeof session.user;
|
||||||
|
session.signers = token.signers as typeof session.signers;
|
||||||
}
|
}
|
||||||
|
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
|
jwt: async ({ token, user }) => {
|
||||||
|
if (user) {
|
||||||
|
token.provider = user.provider;
|
||||||
|
token.signers = user.signers;
|
||||||
|
token.user = user.user;
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
cookies: {
|
cookies: {
|
||||||
sessionToken: {
|
sessionToken: {
|
||||||
name: `next-auth.session-token`,
|
name: `next-auth.session-token`,
|
||||||
options: {
|
options: {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: "none",
|
sameSite: 'none',
|
||||||
path: "/",
|
path: '/',
|
||||||
secure: true
|
secure: true,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
callbackUrl: {
|
callbackUrl: {
|
||||||
name: `next-auth.callback-url`,
|
name: `next-auth.callback-url`,
|
||||||
options: {
|
options: {
|
||||||
sameSite: "none",
|
sameSite: 'none',
|
||||||
path: "/",
|
path: '/',
|
||||||
secure: true
|
secure: true,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
csrfToken: {
|
csrfToken: {
|
||||||
name: `next-auth.csrf-token`,
|
name: `next-auth.csrf-token`,
|
||||||
options: {
|
options: {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: "none",
|
sameSite: 'none',
|
||||||
path: "/",
|
path: '/',
|
||||||
secure: true
|
secure: true,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
|
|
||||||
export const getSession = async () => {
|
export const getSession = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -132,4 +436,4 @@ export const getSession = async () => {
|
|||||||
console.error('Error getting server session:', error);
|
console.error('Error getting server session:', error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|||||||
123
src/components/App.tsx
Normal file
123
src/components/App.tsx
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useMiniApp } from "@neynar/react";
|
||||||
|
import { Header } from "~/components/ui/Header";
|
||||||
|
import { Footer } from "~/components/ui/Footer";
|
||||||
|
import { HomeTab, ActionsTab, ContextTab, WalletTab } from "~/components/ui/tabs";
|
||||||
|
import { USE_WALLET } from "~/lib/constants";
|
||||||
|
import { useNeynarUser } from "../hooks/useNeynarUser";
|
||||||
|
|
||||||
|
// --- Types ---
|
||||||
|
export enum Tab {
|
||||||
|
Home = "home",
|
||||||
|
Actions = "actions",
|
||||||
|
Context = "context",
|
||||||
|
Wallet = "wallet",
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AppProps {
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* App component serves as the main container for the mini app interface.
|
||||||
|
*
|
||||||
|
* This component orchestrates the overall mini app experience by:
|
||||||
|
* - Managing tab navigation and state
|
||||||
|
* - Handling Farcaster mini app initialization
|
||||||
|
* - Coordinating wallet and context state
|
||||||
|
* - Providing error handling and loading states
|
||||||
|
* - Rendering the appropriate tab content based on user selection
|
||||||
|
*
|
||||||
|
* The component integrates with the Neynar SDK for Farcaster functionality
|
||||||
|
* and Wagmi for wallet management. It provides a complete mini app
|
||||||
|
* experience with multiple tabs for different functionality areas.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Tab-based navigation (Home, Actions, Context, Wallet)
|
||||||
|
* - Farcaster mini app integration
|
||||||
|
* - Wallet connection management
|
||||||
|
* - Error handling and display
|
||||||
|
* - Loading states for async operations
|
||||||
|
*
|
||||||
|
* @param props - Component props
|
||||||
|
* @param props.title - Optional title for the mini app (defaults to "Neynar Starter Kit")
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <App title="My Mini App" />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export default function App(
|
||||||
|
{ title }: AppProps = { title: "Neynar Starter Kit" }
|
||||||
|
) {
|
||||||
|
// --- Hooks ---
|
||||||
|
const {
|
||||||
|
isSDKLoaded,
|
||||||
|
context,
|
||||||
|
setInitialTab,
|
||||||
|
setActiveTab,
|
||||||
|
currentTab,
|
||||||
|
} = useMiniApp();
|
||||||
|
|
||||||
|
// --- Neynar user hook ---
|
||||||
|
const { user: neynarUser } = useNeynarUser(context || undefined);
|
||||||
|
|
||||||
|
// --- Effects ---
|
||||||
|
/**
|
||||||
|
* Sets the initial tab to "home" when the SDK is loaded.
|
||||||
|
*
|
||||||
|
* This effect ensures that users start on the home tab when they first
|
||||||
|
* load the mini app. It only runs when the SDK is fully loaded to
|
||||||
|
* prevent errors during initialization.
|
||||||
|
*/
|
||||||
|
useEffect(() => {
|
||||||
|
if (isSDKLoaded) {
|
||||||
|
setInitialTab(Tab.Home);
|
||||||
|
}
|
||||||
|
}, [isSDKLoaded, setInitialTab]);
|
||||||
|
|
||||||
|
// --- Early Returns ---
|
||||||
|
if (!isSDKLoaded) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-screen">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="spinner h-8 w-8 mx-auto mb-4"></div>
|
||||||
|
<p>Loading SDK...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
paddingTop: context?.client.safeAreaInsets?.top ?? 0,
|
||||||
|
paddingBottom: context?.client.safeAreaInsets?.bottom ?? 0,
|
||||||
|
paddingLeft: context?.client.safeAreaInsets?.left ?? 0,
|
||||||
|
paddingRight: context?.client.safeAreaInsets?.right ?? 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Header should be full width */}
|
||||||
|
<Header neynarUser={neynarUser} />
|
||||||
|
|
||||||
|
{/* Main content and footer should be centered */}
|
||||||
|
<div className="container py-2 pb-20">
|
||||||
|
{/* Main title */}
|
||||||
|
<h1 className="text-2xl font-bold text-center mb-4">{title}</h1>
|
||||||
|
|
||||||
|
{/* Tab content rendering */}
|
||||||
|
{currentTab === Tab.Home && <HomeTab />}
|
||||||
|
{currentTab === Tab.Actions && <ActionsTab />}
|
||||||
|
{currentTab === Tab.Context && <ContextTab />}
|
||||||
|
{currentTab === Tab.Wallet && <WalletTab />}
|
||||||
|
|
||||||
|
{/* Footer with navigation */}
|
||||||
|
<Footer activeTab={currentTab as Tab} setActiveTab={setActiveTab} showWallet={USE_WALLET} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,804 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
||||||
import { Input } from "../components/ui/input";
|
|
||||||
import { signIn, signOut, getCsrfToken } from "next-auth/react";
|
|
||||||
import sdk, {
|
|
||||||
SignIn as SignInCore,
|
|
||||||
} from "@farcaster/frame-sdk";
|
|
||||||
import {
|
|
||||||
useAccount,
|
|
||||||
useSendTransaction,
|
|
||||||
useSignMessage,
|
|
||||||
useSignTypedData,
|
|
||||||
useWaitForTransactionReceipt,
|
|
||||||
useDisconnect,
|
|
||||||
useConnect,
|
|
||||||
useSwitchChain,
|
|
||||||
useChainId,
|
|
||||||
} from "wagmi";
|
|
||||||
import {
|
|
||||||
useConnection as useSolanaConnection,
|
|
||||||
useWallet as useSolanaWallet,
|
|
||||||
} from '@solana/wallet-adapter-react';
|
|
||||||
import { useHasSolanaProvider } from "./providers/SafeFarcasterSolanaProvider";
|
|
||||||
|
|
||||||
import { config } from "~/components/providers/WagmiProvider";
|
|
||||||
import { Button } from "~/components/ui/Button";
|
|
||||||
import { truncateAddress } from "~/lib/truncateAddress";
|
|
||||||
import { base, degen, mainnet, optimism, unichain } from "wagmi/chains";
|
|
||||||
import { BaseError, UserRejectedRequestError } from "viem";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import { Label } from "~/components/ui/label";
|
|
||||||
import { useFrame } from "~/components/providers/FrameProvider";
|
|
||||||
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
|
|
||||||
|
|
||||||
export default function Demo(
|
|
||||||
{ title }: { title?: string } = { title: "Frames v2 Demo" }
|
|
||||||
) {
|
|
||||||
const { isSDKLoaded, context, added, notificationDetails, lastEvent, addFrame, addFrameResult, openUrl, close } = useFrame();
|
|
||||||
const [isContextOpen, setIsContextOpen] = useState(false);
|
|
||||||
const [txHash, setTxHash] = useState<string | null>(null);
|
|
||||||
const [sendNotificationResult, setSendNotificationResult] = useState("");
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
|
|
||||||
const { address, isConnected } = useAccount();
|
|
||||||
const chainId = useChainId();
|
|
||||||
const hasSolanaProvider = useHasSolanaProvider();
|
|
||||||
let solanaWallet, solanaPublicKey, solanaSignMessage, solanaAddress;
|
|
||||||
if (hasSolanaProvider) {
|
|
||||||
solanaWallet = useSolanaWallet();
|
|
||||||
({ publicKey: solanaPublicKey, signMessage: solanaSignMessage } = solanaWallet);
|
|
||||||
solanaAddress = solanaPublicKey?.toBase58();
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
console.log("isSDKLoaded", isSDKLoaded);
|
|
||||||
console.log("context", context);
|
|
||||||
console.log("address", address);
|
|
||||||
console.log("isConnected", isConnected);
|
|
||||||
console.log("chainId", chainId);
|
|
||||||
}, [context, address, isConnected, chainId, isSDKLoaded]);
|
|
||||||
|
|
||||||
const {
|
|
||||||
sendTransaction,
|
|
||||||
error: sendTxError,
|
|
||||||
isError: isSendTxError,
|
|
||||||
isPending: isSendTxPending,
|
|
||||||
} = useSendTransaction();
|
|
||||||
|
|
||||||
const { isLoading: isConfirming, isSuccess: isConfirmed } =
|
|
||||||
useWaitForTransactionReceipt({
|
|
||||||
hash: txHash as `0x${string}`,
|
|
||||||
});
|
|
||||||
|
|
||||||
const {
|
|
||||||
signTypedData,
|
|
||||||
error: signTypedError,
|
|
||||||
isError: isSignTypedError,
|
|
||||||
isPending: isSignTypedPending,
|
|
||||||
} = useSignTypedData();
|
|
||||||
|
|
||||||
const { disconnect } = useDisconnect();
|
|
||||||
const { connect, connectors } = useConnect();
|
|
||||||
|
|
||||||
const {
|
|
||||||
switchChain,
|
|
||||||
error: switchChainError,
|
|
||||||
isError: isSwitchChainError,
|
|
||||||
isPending: isSwitchChainPending,
|
|
||||||
} = useSwitchChain();
|
|
||||||
|
|
||||||
const nextChain = useMemo(() => {
|
|
||||||
if (chainId === base.id) {
|
|
||||||
return optimism;
|
|
||||||
} else if (chainId === optimism.id) {
|
|
||||||
return degen;
|
|
||||||
} else if (chainId === degen.id) {
|
|
||||||
return mainnet;
|
|
||||||
} else if (chainId === mainnet.id) {
|
|
||||||
return unichain;
|
|
||||||
} else {
|
|
||||||
return base;
|
|
||||||
}
|
|
||||||
}, [chainId]);
|
|
||||||
|
|
||||||
const handleSwitchChain = useCallback(() => {
|
|
||||||
switchChain({ chainId: nextChain.id });
|
|
||||||
}, [switchChain, nextChain.id]);
|
|
||||||
|
|
||||||
const sendNotification = useCallback(async () => {
|
|
||||||
setSendNotificationResult("");
|
|
||||||
if (!notificationDetails || !context) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/send-notification", {
|
|
||||||
method: "POST",
|
|
||||||
mode: "same-origin",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
fid: context.user.fid,
|
|
||||||
notificationDetails,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.status === 200) {
|
|
||||||
setSendNotificationResult("Success");
|
|
||||||
return;
|
|
||||||
} else if (response.status === 429) {
|
|
||||||
setSendNotificationResult("Rate limited");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.text();
|
|
||||||
setSendNotificationResult(`Error: ${data}`);
|
|
||||||
} catch (error) {
|
|
||||||
setSendNotificationResult(`Error: ${error}`);
|
|
||||||
}
|
|
||||||
}, [context, notificationDetails]);
|
|
||||||
|
|
||||||
const sendTx = useCallback(() => {
|
|
||||||
sendTransaction(
|
|
||||||
{
|
|
||||||
// call yoink() on Yoink contract
|
|
||||||
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
|
|
||||||
data: "0x9846cd9efc000023c0",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: (hash) => {
|
|
||||||
setTxHash(hash);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}, [sendTransaction]);
|
|
||||||
|
|
||||||
const signTyped = useCallback(() => {
|
|
||||||
signTypedData({
|
|
||||||
domain: {
|
|
||||||
name: "Frames v2 Demo",
|
|
||||||
version: "1",
|
|
||||||
chainId,
|
|
||||||
},
|
|
||||||
types: {
|
|
||||||
Message: [{ name: "content", type: "string" }],
|
|
||||||
},
|
|
||||||
message: {
|
|
||||||
content: "Hello from Frames v2!",
|
|
||||||
},
|
|
||||||
primaryType: "Message",
|
|
||||||
});
|
|
||||||
}, [chainId, signTypedData]);
|
|
||||||
|
|
||||||
const toggleContext = useCallback(() => {
|
|
||||||
setIsContextOpen((prev) => !prev);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (!isSDKLoaded) {
|
|
||||||
return <div>Loading...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
paddingTop: context?.client.safeAreaInsets?.top ?? 0,
|
|
||||||
paddingBottom: context?.client.safeAreaInsets?.bottom ?? 0,
|
|
||||||
paddingLeft: context?.client.safeAreaInsets?.left ?? 0,
|
|
||||||
paddingRight: context?.client.safeAreaInsets?.right ?? 0,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="w-[300px] mx-auto py-2 px-2">
|
|
||||||
<h1 className="text-2xl font-bold text-center mb-4">{title}</h1>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<h2 className="font-2xl font-bold">Context</h2>
|
|
||||||
<button
|
|
||||||
onClick={toggleContext}
|
|
||||||
className="flex items-center gap-2 transition-colors"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={`transform transition-transform ${
|
|
||||||
isContextOpen ? "rotate-90" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
➤
|
|
||||||
</span>
|
|
||||||
Tap to expand
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{isContextOpen && (
|
|
||||||
<div className="p-4 mt-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
{JSON.stringify(context, null, 2)}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<h2 className="font-2xl font-bold">Actions</h2>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
sdk.actions.signIn
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
<SignIn />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
sdk.actions.openUrl
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
<Button onClick={() => openUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")}>Open Link</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
sdk.actions.viewProfile
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
<ViewProfile />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
sdk.actions.close
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
<Button onClick={close}>Close Frame</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<h2 className="font-2xl font-bold">Last event</h2>
|
|
||||||
|
|
||||||
<div className="p-4 mt-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
{lastEvent || "none"}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<h2 className="font-2xl font-bold">Add to client & notifications</h2>
|
|
||||||
|
|
||||||
<div className="mt-2 mb-4 text-sm">
|
|
||||||
Client fid {context?.client.clientFid},
|
|
||||||
{added ? " frame added to client," : " frame not added to client,"}
|
|
||||||
{notificationDetails
|
|
||||||
? " notifications enabled"
|
|
||||||
: " notifications disabled"}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
|
|
||||||
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
|
|
||||||
sdk.actions.addFrame
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
{addFrameResult && (
|
|
||||||
<div className="mb-2 text-sm">
|
|
||||||
Add frame result: {addFrameResult}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button onClick={addFrame} disabled={added}>
|
|
||||||
Add frame to client
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{sendNotificationResult && (
|
|
||||||
<div className="mb-2 text-sm">
|
|
||||||
Send notification result: {sendNotificationResult}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="mb-4">
|
|
||||||
<Button onClick={sendNotification} disabled={!notificationDetails}>
|
|
||||||
Send notification
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<Button
|
|
||||||
onClick={async () => {
|
|
||||||
if (context?.user?.fid) {
|
|
||||||
const shareUrl = `${process.env.NEXT_PUBLIC_URL}/share/${context.user.fid}`;
|
|
||||||
await navigator.clipboard.writeText(shareUrl);
|
|
||||||
setCopied(true);
|
|
||||||
setTimeout(() => setCopied(false), 2000);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
disabled={!context?.user?.fid}
|
|
||||||
>
|
|
||||||
{copied ? "Copied!" : "Copy share URL"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<h2 className="font-2xl font-bold">Wallet</h2>
|
|
||||||
|
|
||||||
{address && (
|
|
||||||
<div className="my-2 text-xs">
|
|
||||||
Address: <pre className="inline">{truncateAddress(address)}</pre>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{chainId && (
|
|
||||||
<div className="my-2 text-xs">
|
|
||||||
Chain ID: <pre className="inline">{chainId}</pre>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
{isConnected ? (
|
|
||||||
<Button
|
|
||||||
onClick={() => disconnect()}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
Disconnect
|
|
||||||
</Button>
|
|
||||||
) : context ? (
|
|
||||||
/* if context is not null, mini app is running in frame client */
|
|
||||||
<Button
|
|
||||||
onClick={() => connect({ connector: connectors[0] })}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
Connect
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
/* if context is null, mini app is running in browser */
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Button
|
|
||||||
onClick={() => connect({ connector: connectors[1] })}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
Connect Coinbase Wallet
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => connect({ connector: connectors[2] })}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
Connect MetaMask
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<SignEvmMessage />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isConnected && (
|
|
||||||
<>
|
|
||||||
<div className="mb-4">
|
|
||||||
<SendEth />
|
|
||||||
</div>
|
|
||||||
<div className="mb-4">
|
|
||||||
<Button
|
|
||||||
onClick={sendTx}
|
|
||||||
disabled={!isConnected || isSendTxPending}
|
|
||||||
isLoading={isSendTxPending}
|
|
||||||
>
|
|
||||||
Send Transaction (contract)
|
|
||||||
</Button>
|
|
||||||
{isSendTxError && renderError(sendTxError)}
|
|
||||||
{txHash && (
|
|
||||||
<div className="mt-2 text-xs">
|
|
||||||
<div>Hash: {truncateAddress(txHash)}</div>
|
|
||||||
<div>
|
|
||||||
Status:{" "}
|
|
||||||
{isConfirming
|
|
||||||
? "Confirming..."
|
|
||||||
: isConfirmed
|
|
||||||
? "Confirmed!"
|
|
||||||
: "Pending"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="mb-4">
|
|
||||||
<Button
|
|
||||||
onClick={signTyped}
|
|
||||||
disabled={!isConnected || isSignTypedPending}
|
|
||||||
isLoading={isSignTypedPending}
|
|
||||||
>
|
|
||||||
Sign Typed Data
|
|
||||||
</Button>
|
|
||||||
{isSignTypedError && renderError(signTypedError)}
|
|
||||||
</div>
|
|
||||||
<div className="mb-4">
|
|
||||||
<Button
|
|
||||||
onClick={handleSwitchChain}
|
|
||||||
disabled={isSwitchChainPending}
|
|
||||||
isLoading={isSwitchChainPending}
|
|
||||||
>
|
|
||||||
Switch to {nextChain.name}
|
|
||||||
</Button>
|
|
||||||
{isSwitchChainError && renderError(switchChainError)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{solanaAddress && (
|
|
||||||
<div>
|
|
||||||
<h2 className="font-2xl font-bold">Solana</h2>
|
|
||||||
<div className="my-2 text-xs">
|
|
||||||
Address: <pre className="inline">{truncateAddress(solanaAddress)}</pre>
|
|
||||||
</div>
|
|
||||||
<SignSolanaMessage signMessage={solanaSignMessage} />
|
|
||||||
<div className="mb-4">
|
|
||||||
<SendSolana />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Solana functions inspired by farcaster demo
|
|
||||||
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx
|
|
||||||
function SignSolanaMessage({ signMessage }: { signMessage?: (message: Uint8Array) => Promise<Uint8Array> }) {
|
|
||||||
const [signature, setSignature] = useState<string | undefined>();
|
|
||||||
const [signError, setSignError] = useState<Error | undefined>();
|
|
||||||
const [signPending, setSignPending] = useState(false);
|
|
||||||
|
|
||||||
const handleSignMessage = useCallback(async () => {
|
|
||||||
setSignPending(true);
|
|
||||||
try {
|
|
||||||
if (!signMessage) {
|
|
||||||
throw new Error('no Solana signMessage');
|
|
||||||
}
|
|
||||||
const input = new TextEncoder().encode("Hello from Solana!");
|
|
||||||
const signatureBytes = await signMessage(input);
|
|
||||||
const signature = btoa(String.fromCharCode(...signatureBytes));
|
|
||||||
setSignature(signature);
|
|
||||||
setSignError(undefined);
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof Error) {
|
|
||||||
setSignError(e);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setSignPending(false);
|
|
||||||
}
|
|
||||||
}, [signMessage]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
onClick={handleSignMessage}
|
|
||||||
disabled={signPending}
|
|
||||||
isLoading={signPending}
|
|
||||||
className="mb-4"
|
|
||||||
>
|
|
||||||
Sign Message
|
|
||||||
</Button>
|
|
||||||
{signError && renderError(signError)}
|
|
||||||
{signature && (
|
|
||||||
<div className="mt-2 text-xs">
|
|
||||||
<div>Signature: {signature}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SendSolana() {
|
|
||||||
const [state, setState] = useState<
|
|
||||||
| { status: 'none' }
|
|
||||||
| { status: 'pending' }
|
|
||||||
| { status: 'error'; error: Error }
|
|
||||||
| { status: 'success'; signature: string }
|
|
||||||
>({ status: 'none' });
|
|
||||||
|
|
||||||
const { connection: solanaConnection } = useSolanaConnection();
|
|
||||||
const { sendTransaction, publicKey } = useSolanaWallet();
|
|
||||||
|
|
||||||
// This should be replaced but including it from the original demo
|
|
||||||
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx#L718
|
|
||||||
const ashoatsPhantomSolanaWallet = 'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
|
|
||||||
|
|
||||||
const handleSend = useCallback(async () => {
|
|
||||||
setState({ status: 'pending' });
|
|
||||||
try {
|
|
||||||
if (!publicKey) {
|
|
||||||
throw new Error('no Solana publicKey');
|
|
||||||
}
|
|
||||||
|
|
||||||
const { blockhash } = await solanaConnection.getLatestBlockhash();
|
|
||||||
if (!blockhash) {
|
|
||||||
throw new Error('failed to fetch latest Solana blockhash');
|
|
||||||
}
|
|
||||||
|
|
||||||
const fromPubkeyStr = publicKey.toBase58();
|
|
||||||
const toPubkeyStr = ashoatsPhantomSolanaWallet;
|
|
||||||
const transaction = new Transaction();
|
|
||||||
transaction.add(
|
|
||||||
SystemProgram.transfer({
|
|
||||||
fromPubkey: new PublicKey(fromPubkeyStr),
|
|
||||||
toPubkey: new PublicKey(toPubkeyStr),
|
|
||||||
lamports: 0n,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
transaction.recentBlockhash = blockhash;
|
|
||||||
transaction.feePayer = new PublicKey(fromPubkeyStr);
|
|
||||||
|
|
||||||
const simulation = await solanaConnection.simulateTransaction(transaction);
|
|
||||||
if (simulation.value.err) {
|
|
||||||
// Gather logs and error details for debugging
|
|
||||||
const logs = simulation.value.logs?.join('\n') ?? 'No logs';
|
|
||||||
const errDetail = JSON.stringify(simulation.value.err);
|
|
||||||
throw new Error(`Simulation failed: ${errDetail}\nLogs:\n${logs}`);
|
|
||||||
}
|
|
||||||
const signature = await sendTransaction(transaction, solanaConnection);
|
|
||||||
setState({ status: 'success', signature });
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof Error) {
|
|
||||||
setState({ status: 'error', error: e });
|
|
||||||
} else {
|
|
||||||
setState({ status: 'none' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [sendTransaction, publicKey, solanaConnection]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
onClick={handleSend}
|
|
||||||
disabled={state.status === 'pending'}
|
|
||||||
isLoading={state.status === 'pending'}
|
|
||||||
className="mb-4"
|
|
||||||
>
|
|
||||||
Send Transaction (sol)
|
|
||||||
</Button>
|
|
||||||
{state.status === 'error' && renderError(state.error)}
|
|
||||||
{state.status === 'success' && (
|
|
||||||
<div className="mt-2 text-xs">
|
|
||||||
<div>Hash: {truncateAddress(state.signature)}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SignEvmMessage() {
|
|
||||||
const { isConnected } = useAccount();
|
|
||||||
const { connectAsync } = useConnect();
|
|
||||||
const {
|
|
||||||
signMessage,
|
|
||||||
data: signature,
|
|
||||||
error: signError,
|
|
||||||
isError: isSignError,
|
|
||||||
isPending: isSignPending,
|
|
||||||
} = useSignMessage();
|
|
||||||
|
|
||||||
const handleSignMessage = useCallback(async () => {
|
|
||||||
if (!isConnected) {
|
|
||||||
await connectAsync({
|
|
||||||
chainId: base.id,
|
|
||||||
connector: config.connectors[0],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
signMessage({ message: "Hello from Frames v2!" });
|
|
||||||
}, [connectAsync, isConnected, signMessage]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
onClick={handleSignMessage}
|
|
||||||
disabled={isSignPending}
|
|
||||||
isLoading={isSignPending}
|
|
||||||
>
|
|
||||||
Sign Message
|
|
||||||
</Button>
|
|
||||||
{isSignError && renderError(signError)}
|
|
||||||
{signature && (
|
|
||||||
<div className="mt-2 text-xs">
|
|
||||||
<div>Signature: {signature}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SendEth() {
|
|
||||||
const { isConnected, chainId } = useAccount();
|
|
||||||
const {
|
|
||||||
sendTransaction,
|
|
||||||
data,
|
|
||||||
error: sendTxError,
|
|
||||||
isError: isSendTxError,
|
|
||||||
isPending: isSendTxPending,
|
|
||||||
} = useSendTransaction();
|
|
||||||
|
|
||||||
const { isLoading: isConfirming, isSuccess: isConfirmed } =
|
|
||||||
useWaitForTransactionReceipt({
|
|
||||||
hash: data,
|
|
||||||
});
|
|
||||||
|
|
||||||
const toAddr = useMemo(() => {
|
|
||||||
// Protocol guild address
|
|
||||||
return chainId === base.id
|
|
||||||
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
|
|
||||||
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
|
|
||||||
}, [chainId]);
|
|
||||||
|
|
||||||
const handleSend = useCallback(() => {
|
|
||||||
sendTransaction({
|
|
||||||
to: toAddr,
|
|
||||||
value: 1n,
|
|
||||||
});
|
|
||||||
}, [toAddr, sendTransaction]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
onClick={handleSend}
|
|
||||||
disabled={!isConnected || isSendTxPending}
|
|
||||||
isLoading={isSendTxPending}
|
|
||||||
>
|
|
||||||
Send Transaction (eth)
|
|
||||||
</Button>
|
|
||||||
{isSendTxError && renderError(sendTxError)}
|
|
||||||
{data && (
|
|
||||||
<div className="mt-2 text-xs">
|
|
||||||
<div>Hash: {truncateAddress(data)}</div>
|
|
||||||
<div>
|
|
||||||
Status:{" "}
|
|
||||||
{isConfirming
|
|
||||||
? "Confirming..."
|
|
||||||
: isConfirmed
|
|
||||||
? "Confirmed!"
|
|
||||||
: "Pending"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SignIn() {
|
|
||||||
const [signingIn, setSigningIn] = useState(false);
|
|
||||||
const [signingOut, setSigningOut] = useState(false);
|
|
||||||
const [signInResult, setSignInResult] = useState<SignInCore.SignInResult>();
|
|
||||||
const [signInFailure, setSignInFailure] = useState<string>();
|
|
||||||
const { data: session, status } = useSession();
|
|
||||||
|
|
||||||
const getNonce = useCallback(async () => {
|
|
||||||
const nonce = await getCsrfToken();
|
|
||||||
if (!nonce) throw new Error("Unable to generate nonce");
|
|
||||||
return nonce;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleSignIn = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setSigningIn(true);
|
|
||||||
setSignInFailure(undefined);
|
|
||||||
const nonce = await getNonce();
|
|
||||||
const result = await sdk.actions.signIn({ nonce });
|
|
||||||
setSignInResult(result);
|
|
||||||
|
|
||||||
await signIn("credentials", {
|
|
||||||
message: result.message,
|
|
||||||
signature: result.signature,
|
|
||||||
redirect: false,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof SignInCore.RejectedByUser) {
|
|
||||||
setSignInFailure("Rejected by user");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setSignInFailure("Unknown error");
|
|
||||||
} finally {
|
|
||||||
setSigningIn(false);
|
|
||||||
}
|
|
||||||
}, [getNonce]);
|
|
||||||
|
|
||||||
const handleSignOut = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setSigningOut(true);
|
|
||||||
await signOut({ redirect: false });
|
|
||||||
setSignInResult(undefined);
|
|
||||||
} finally {
|
|
||||||
setSigningOut(false);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{status !== "authenticated" && (
|
|
||||||
<Button onClick={handleSignIn} disabled={signingIn}>
|
|
||||||
Sign In with Farcaster
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{status === "authenticated" && (
|
|
||||||
<Button onClick={handleSignOut} disabled={signingOut}>
|
|
||||||
Sign out
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{session && (
|
|
||||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
|
||||||
<div className="font-semibold text-gray-500 mb-1">Session</div>
|
|
||||||
<div className="whitespace-pre">
|
|
||||||
{JSON.stringify(session, null, 2)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{signInFailure && !signingIn && (
|
|
||||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
|
||||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
|
||||||
<div className="whitespace-pre">{signInFailure}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{signInResult && !signingIn && (
|
|
||||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
|
||||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
|
||||||
<div className="whitespace-pre">
|
|
||||||
{JSON.stringify(signInResult, null, 2)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ViewProfile() {
|
|
||||||
const [fid, setFid] = useState("3");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div>
|
|
||||||
<Label
|
|
||||||
className="text-xs font-semibold text-gray-500 mb-1"
|
|
||||||
htmlFor="view-profile-fid"
|
|
||||||
>
|
|
||||||
Fid
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="view-profile-fid"
|
|
||||||
type="number"
|
|
||||||
value={fid}
|
|
||||||
className="mb-2"
|
|
||||||
onChange={(e) => {
|
|
||||||
setFid(e.target.value);
|
|
||||||
}}
|
|
||||||
step="1"
|
|
||||||
min="1"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
sdk.actions.viewProfile({ fid: parseInt(fid) });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
View Profile
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const renderError = (error: Error | null) => {
|
|
||||||
if (!error) return null;
|
|
||||||
if (error instanceof BaseError) {
|
|
||||||
const isUserRejection = error.walk(
|
|
||||||
(e) => e instanceof UserRejectedRequestError
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isUserRejection) {
|
|
||||||
return <div className="text-red-500 text-xs mt-1">Rejected by user.</div>;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return <div className="text-red-500 text-xs mt-1">{error.message}</div>;
|
|
||||||
};
|
|
||||||
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
|
||||||
import sdk, { type Context, type FrameNotificationDetails, AddMiniApp } from "@farcaster/frame-sdk";
|
|
||||||
import { createStore } from "mipd";
|
|
||||||
import React from "react";
|
|
||||||
|
|
||||||
interface FrameContextType {
|
|
||||||
isSDKLoaded: boolean;
|
|
||||||
context: Context.FrameContext | undefined;
|
|
||||||
openUrl: (url: string) => Promise<void>;
|
|
||||||
close: () => Promise<void>;
|
|
||||||
added: boolean;
|
|
||||||
notificationDetails: FrameNotificationDetails | null;
|
|
||||||
lastEvent: string;
|
|
||||||
addFrame: () => Promise<void>;
|
|
||||||
addFrameResult: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const FrameContext = React.createContext<FrameContextType | undefined>(undefined);
|
|
||||||
|
|
||||||
export function useFrame() {
|
|
||||||
const [isSDKLoaded, setIsSDKLoaded] = useState(false);
|
|
||||||
const [context, setContext] = useState<Context.FrameContext>();
|
|
||||||
const [added, setAdded] = useState(false);
|
|
||||||
const [notificationDetails, setNotificationDetails] = useState<FrameNotificationDetails | null>(null);
|
|
||||||
const [lastEvent, setLastEvent] = useState("");
|
|
||||||
const [addFrameResult, setAddFrameResult] = useState("");
|
|
||||||
|
|
||||||
// SDK actions only work in mini app clients, so this pattern supports browser actions as well
|
|
||||||
const openUrl = useCallback(async (url: string) => {
|
|
||||||
if (context) {
|
|
||||||
await sdk.actions.openUrl(url);
|
|
||||||
} else {
|
|
||||||
window.open(url, '_blank');
|
|
||||||
}
|
|
||||||
}, [context]);
|
|
||||||
|
|
||||||
const close = useCallback(async () => {
|
|
||||||
if (context) {
|
|
||||||
await sdk.actions.close();
|
|
||||||
} else {
|
|
||||||
window.close();
|
|
||||||
}
|
|
||||||
}, [context]);
|
|
||||||
|
|
||||||
const addFrame = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setNotificationDetails(null);
|
|
||||||
const result = await sdk.actions.addFrame();
|
|
||||||
|
|
||||||
if (result.notificationDetails) {
|
|
||||||
setNotificationDetails(result.notificationDetails);
|
|
||||||
}
|
|
||||||
setAddFrameResult(
|
|
||||||
result.notificationDetails
|
|
||||||
? `Added, got notificaton token ${result.notificationDetails.token} and url ${result.notificationDetails.url}`
|
|
||||||
: "Added, got no notification details"
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AddMiniApp.RejectedByUser || error instanceof AddMiniApp.InvalidDomainManifest) {
|
|
||||||
setAddFrameResult(`Not added: ${error.message}`);
|
|
||||||
}else {
|
|
||||||
setAddFrameResult(`Error: ${error}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const load = async () => {
|
|
||||||
const context = await sdk.context;
|
|
||||||
setContext(context);
|
|
||||||
setIsSDKLoaded(true);
|
|
||||||
|
|
||||||
// Set up event listeners
|
|
||||||
sdk.on("frameAdded", ({ notificationDetails }) => {
|
|
||||||
console.log("Frame added", notificationDetails);
|
|
||||||
setAdded(true);
|
|
||||||
setNotificationDetails(notificationDetails ?? null);
|
|
||||||
setLastEvent("Frame added");
|
|
||||||
});
|
|
||||||
|
|
||||||
sdk.on("frameAddRejected", ({ reason }) => {
|
|
||||||
console.log("Frame add rejected", reason);
|
|
||||||
setAdded(false);
|
|
||||||
setLastEvent(`Frame add rejected: ${reason}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
sdk.on("frameRemoved", () => {
|
|
||||||
console.log("Frame removed");
|
|
||||||
setAdded(false);
|
|
||||||
setLastEvent("Frame removed");
|
|
||||||
});
|
|
||||||
|
|
||||||
sdk.on("notificationsEnabled", ({ notificationDetails }) => {
|
|
||||||
console.log("Notifications enabled", notificationDetails);
|
|
||||||
setNotificationDetails(notificationDetails ?? null);
|
|
||||||
setLastEvent("Notifications enabled");
|
|
||||||
});
|
|
||||||
|
|
||||||
sdk.on("notificationsDisabled", () => {
|
|
||||||
console.log("Notifications disabled");
|
|
||||||
setNotificationDetails(null);
|
|
||||||
setLastEvent("Notifications disabled");
|
|
||||||
});
|
|
||||||
|
|
||||||
sdk.on("primaryButtonClicked", () => {
|
|
||||||
console.log("Primary button clicked");
|
|
||||||
setLastEvent("Primary button clicked");
|
|
||||||
});
|
|
||||||
|
|
||||||
// Call ready action
|
|
||||||
console.log("Calling ready");
|
|
||||||
sdk.actions.ready({});
|
|
||||||
|
|
||||||
// Set up MIPD Store
|
|
||||||
const store = createStore();
|
|
||||||
store.subscribe((providerDetails) => {
|
|
||||||
console.log("PROVIDER DETAILS", providerDetails);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
if (sdk && !isSDKLoaded) {
|
|
||||||
console.log("Calling load");
|
|
||||||
setIsSDKLoaded(true);
|
|
||||||
load();
|
|
||||||
return () => {
|
|
||||||
sdk.removeAllListeners();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}, [isSDKLoaded]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
isSDKLoaded,
|
|
||||||
context,
|
|
||||||
added,
|
|
||||||
notificationDetails,
|
|
||||||
lastEvent,
|
|
||||||
addFrame,
|
|
||||||
addFrameResult,
|
|
||||||
openUrl,
|
|
||||||
close,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function FrameProvider({ children }: { children: React.ReactNode }) {
|
|
||||||
const frameContext = useFrame();
|
|
||||||
|
|
||||||
if (!frameContext.isSDKLoaded) {
|
|
||||||
return <div>Loading...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<FrameContext.Provider value={frameContext}>
|
|
||||||
{children}
|
|
||||||
</FrameContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { createContext, useEffect, useState } from "react";
|
import React, { createContext, useEffect, useState } from "react";
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
import { sdk } from '@farcaster/frame-sdk';
|
import { sdk } from '@farcaster/miniapp-sdk';
|
||||||
|
|
||||||
const FarcasterSolanaProvider = dynamic(
|
const FarcasterSolanaProvider = dynamic(
|
||||||
() => import('@farcaster/mini-app-solana').then(mod => mod.FarcasterSolanaProvider),
|
() => import('@farcaster/mini-app-solana').then(mod => mod.FarcasterSolanaProvider),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createConfig, http, WagmiProvider } from "wagmi";
|
import { createConfig, http, WagmiProvider } from "wagmi";
|
||||||
import { base, degen, mainnet, optimism, unichain } from "wagmi/chains";
|
import { base, degen, mainnet, optimism, unichain, celo } from "wagmi/chains";
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { farcasterFrame } from "@farcaster/frame-wagmi-connector";
|
import { farcasterFrame } from "@farcaster/miniapp-wagmi-connector";
|
||||||
import { coinbaseWallet, metaMask } from 'wagmi/connectors';
|
import { coinbaseWallet, metaMask } from 'wagmi/connectors';
|
||||||
import { APP_NAME, APP_ICON_URL, APP_URL } from "~/lib/constants";
|
import { APP_NAME, APP_ICON_URL, APP_URL } from "~/lib/constants";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
@@ -42,13 +42,14 @@ function useCoinbaseWalletAutoConnect() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const config = createConfig({
|
export const config = createConfig({
|
||||||
chains: [base, optimism, mainnet, degen, unichain],
|
chains: [base, optimism, mainnet, degen, unichain, celo],
|
||||||
transports: {
|
transports: {
|
||||||
[base.id]: http(),
|
[base.id]: http(),
|
||||||
[optimism.id]: http(),
|
[optimism.id]: http(),
|
||||||
[mainnet.id]: http(),
|
[mainnet.id]: http(),
|
||||||
[degen.id]: http(),
|
[degen.id]: http(),
|
||||||
[unichain.id]: http(),
|
[unichain.id]: http(),
|
||||||
|
[celo.id]: http(),
|
||||||
},
|
},
|
||||||
connectors: [
|
connectors: [
|
||||||
farcasterFrame(),
|
farcasterFrame(),
|
||||||
|
|||||||
@@ -1,17 +1,50 @@
|
|||||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
isLoading?: boolean;
|
isLoading?: boolean;
|
||||||
|
variant?: 'primary' | 'secondary' | 'outline';
|
||||||
|
size?: 'sm' | 'md' | 'lg';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Button({ children, className = "", isLoading = false, ...props }: ButtonProps) {
|
export function Button({
|
||||||
|
children,
|
||||||
|
className = "",
|
||||||
|
isLoading = false,
|
||||||
|
variant = 'primary',
|
||||||
|
size = 'md',
|
||||||
|
...props
|
||||||
|
}: ButtonProps) {
|
||||||
|
const baseClasses = "btn";
|
||||||
|
|
||||||
|
const variantClasses = {
|
||||||
|
primary: "btn-primary",
|
||||||
|
secondary: "btn-secondary",
|
||||||
|
outline: "btn-outline"
|
||||||
|
};
|
||||||
|
|
||||||
|
const sizeClasses = {
|
||||||
|
sm: "px-3 py-1.5 text-xs",
|
||||||
|
md: "px-4 py-2 text-sm",
|
||||||
|
lg: "px-6 py-3 text-base"
|
||||||
|
};
|
||||||
|
|
||||||
|
const fullWidthClasses = "w-full max-w-xs mx-auto block";
|
||||||
|
|
||||||
|
const combinedClasses = [
|
||||||
|
baseClasses,
|
||||||
|
variantClasses[variant],
|
||||||
|
sizeClasses[size],
|
||||||
|
fullWidthClasses,
|
||||||
|
className
|
||||||
|
].join(' ');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
className={`w-full max-w-xs mx-auto block bg-[#7C65C1] text-white py-3 px-6 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-[#7C65C1] hover:bg-[#6952A3] ${className}`}
|
className={combinedClasses}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<div className="flex items-center justify-center">
|
<div className="flex items-center justify-center">
|
||||||
<div className="animate-spin h-5 w-5 border-2 border-white border-t-transparent rounded-full" />
|
<div className="spinner-primary h-5 w-5" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
children
|
children
|
||||||
|
|||||||
53
src/components/ui/Footer.tsx
Normal file
53
src/components/ui/Footer.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Tab } from "~/components/App";
|
||||||
|
|
||||||
|
interface FooterProps {
|
||||||
|
activeTab: Tab;
|
||||||
|
setActiveTab: (tab: Tab) => void;
|
||||||
|
showWallet?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWallet = false }) => (
|
||||||
|
<div className="fixed bottom-0 left-0 right-0 mx-4 mb-4 bg-gray-100 dark:bg-gray-800 border-[3px] border-double border-primary px-2 py-2 rounded-lg z-50">
|
||||||
|
<div className="flex justify-around items-center h-14">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab(Tab.Home)}
|
||||||
|
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||||
|
activeTab === Tab.Home ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-xl">🏠</span>
|
||||||
|
<span className="text-xs mt-1">Home</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab(Tab.Actions)}
|
||||||
|
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||||
|
activeTab === Tab.Actions ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-xl">⚡</span>
|
||||||
|
<span className="text-xs mt-1">Actions</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab(Tab.Context)}
|
||||||
|
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||||
|
activeTab === Tab.Context ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-xl">📋</span>
|
||||||
|
<span className="text-xs mt-1">Context</span>
|
||||||
|
</button>
|
||||||
|
{showWallet && (
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab(Tab.Wallet)}
|
||||||
|
className={`flex flex-col items-center justify-center w-full h-full ${
|
||||||
|
activeTab === Tab.Wallet ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-xl">👛</span>
|
||||||
|
<span className="text-xs mt-1">Wallet</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
77
src/components/ui/Header.tsx
Normal file
77
src/components/ui/Header.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { APP_NAME } from "~/lib/constants";
|
||||||
|
import sdk from "@farcaster/miniapp-sdk";
|
||||||
|
import { useMiniApp } from "@neynar/react";
|
||||||
|
|
||||||
|
type HeaderProps = {
|
||||||
|
neynarUser?: {
|
||||||
|
fid: number;
|
||||||
|
score: number;
|
||||||
|
} | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function Header({ neynarUser }: HeaderProps) {
|
||||||
|
const { context } = useMiniApp();
|
||||||
|
const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative">
|
||||||
|
<div
|
||||||
|
className="mt-4 mb-4 mx-4 px-2 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-between border-[3px] border-double border-primary"
|
||||||
|
>
|
||||||
|
<div className="text-lg font-light">
|
||||||
|
Welcome to {APP_NAME}!
|
||||||
|
</div>
|
||||||
|
{context?.user && (
|
||||||
|
<div
|
||||||
|
className="cursor-pointer"
|
||||||
|
onClick={() => {
|
||||||
|
setIsUserDropdownOpen(!isUserDropdownOpen);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{context.user.pfpUrl && (
|
||||||
|
<img
|
||||||
|
src={context.user.pfpUrl}
|
||||||
|
alt="Profile"
|
||||||
|
className="w-10 h-10 rounded-full border-2 border-primary"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{context?.user && (
|
||||||
|
<>
|
||||||
|
{isUserDropdownOpen && (
|
||||||
|
<div className="absolute top-full right-0 z-50 w-fit mt-1 mx-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
|
||||||
|
<div className="p-3 space-y-2">
|
||||||
|
<div className="text-right">
|
||||||
|
<h3
|
||||||
|
className="font-bold text-sm hover:underline cursor-pointer inline-block"
|
||||||
|
onClick={() => sdk.actions.viewProfile({ fid: context.user.fid })}
|
||||||
|
>
|
||||||
|
{context.user.displayName || context.user.username}
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs text-gray-600 dark:text-gray-400">
|
||||||
|
@{context.user.username}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||||
|
FID: {context.user.fid}
|
||||||
|
</p>
|
||||||
|
{neynarUser && (
|
||||||
|
<>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||||
|
Neynar Score: {neynarUser.score}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
221
src/components/ui/NeynarAuthButton/AuthDialog.tsx
Normal file
221
src/components/ui/NeynarAuthButton/AuthDialog.tsx
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
export function AuthDialog({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
url,
|
||||||
|
isError,
|
||||||
|
error,
|
||||||
|
step,
|
||||||
|
isLoading,
|
||||||
|
signerApprovalUrl,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
url?: string;
|
||||||
|
isError: boolean;
|
||||||
|
error?: Error | null;
|
||||||
|
step: 'signin' | 'access' | 'loading';
|
||||||
|
isLoading?: boolean;
|
||||||
|
signerApprovalUrl?: string | null;
|
||||||
|
}) {
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const getStepContent = () => {
|
||||||
|
switch (step) {
|
||||||
|
case 'signin':
|
||||||
|
return {
|
||||||
|
title: 'Sign in',
|
||||||
|
description:
|
||||||
|
"To sign in, scan the code below with your phone's camera.",
|
||||||
|
showQR: true,
|
||||||
|
qrUrl: url,
|
||||||
|
showOpenButton: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'loading':
|
||||||
|
return {
|
||||||
|
title: 'Setting up access...',
|
||||||
|
description:
|
||||||
|
'Checking your account permissions and setting up secure access.',
|
||||||
|
showQR: false,
|
||||||
|
qrUrl: '',
|
||||||
|
showOpenButton: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'access':
|
||||||
|
return {
|
||||||
|
title: 'Grant Access',
|
||||||
|
description: (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-gray-600 dark:text-gray-400">
|
||||||
|
Allow this app to access your Farcaster account:
|
||||||
|
</p>
|
||||||
|
<div className="space-y-2 text-sm">
|
||||||
|
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
|
<div className="w-6 h-6 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
|
||||||
|
<svg
|
||||||
|
className="w-3 h-3 text-green-600 dark:text-green-400"
|
||||||
|
fill="currentColor"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
fillRule="evenodd"
|
||||||
|
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||||
|
clipRule="evenodd"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="font-medium text-gray-900 dark:text-gray-100">
|
||||||
|
Read Access
|
||||||
|
</div>
|
||||||
|
<div className="text-gray-500 dark:text-gray-400">
|
||||||
|
View your profile and public information
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
|
<div className="w-6 h-6 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
|
||||||
|
<svg
|
||||||
|
className="w-3 h-3 text-blue-600 dark:text-blue-400"
|
||||||
|
fill="currentColor"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
>
|
||||||
|
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="font-medium text-gray-900 dark:text-gray-100">
|
||||||
|
Write Access
|
||||||
|
</div>
|
||||||
|
<div className="text-gray-500 dark:text-gray-400">
|
||||||
|
Post casts, likes, and update your profile
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
// Show QR code if we have signer approval URL, otherwise show loading
|
||||||
|
showQR: !!signerApprovalUrl,
|
||||||
|
qrUrl: signerApprovalUrl || '',
|
||||||
|
showOpenButton: !!signerApprovalUrl,
|
||||||
|
};
|
||||||
|
|
||||||
|
default:
|
||||||
|
return {
|
||||||
|
title: 'Sign in',
|
||||||
|
description:
|
||||||
|
"To signin, scan the code below with your phone's camera.",
|
||||||
|
showQR: true,
|
||||||
|
qrUrl: url,
|
||||||
|
showOpenButton: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const content = getStepContent();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
|
||||||
|
<div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-md shadow-2xl border border-gray-200 dark:border-gray-700 max-h-[80vh] sm:max-h-[90vh] flex flex-col">
|
||||||
|
<div className="flex justify-between items-center p-4 sm:p-6 pb-3 sm:pb-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||||
|
{isError ? 'Error' : content.title}
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-6 h-6"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M6 18L18 6M6 6l12 12"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto p-4 sm:p-6 pt-3 sm:pt-4 min-h-0">
|
||||||
|
{isError ? (
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-red-600 dark:text-red-400 mb-4">
|
||||||
|
{error?.message || 'Unknown error, please try again.'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="mb-6">
|
||||||
|
{typeof content.description === 'string' ? (
|
||||||
|
<p className="text-gray-600 dark:text-gray-400">
|
||||||
|
{content.description}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
content.description
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6 flex justify-center">
|
||||||
|
{content.showQR && content.qrUrl ? (
|
||||||
|
<div className="p-4 bg-white rounded-lg">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
|
||||||
|
content.qrUrl
|
||||||
|
)}`}
|
||||||
|
alt="QR Code"
|
||||||
|
className="w-48 h-48"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : step === 'loading' || isLoading ? (
|
||||||
|
<div className="w-48 h-48 flex items-center justify-center bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
<div className="spinner w-8 h-8" />
|
||||||
|
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||||
|
{step === 'loading'
|
||||||
|
? 'Setting up access...'
|
||||||
|
: 'Loading...'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{content.showOpenButton && content.qrUrl && (
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (content.qrUrl) {
|
||||||
|
window.open(
|
||||||
|
content.qrUrl
|
||||||
|
.replace(
|
||||||
|
'https://farcaster.xyz/',
|
||||||
|
'https://client.farcaster.xyz/deeplinks/'
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
'https://client.farcaster.xyz/deeplinks/signed-key-request',
|
||||||
|
'https://farcaster.xyz/~/connect'
|
||||||
|
),
|
||||||
|
'_blank'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="btn btn-outline flex items-center justify-center gap-2 w-full"
|
||||||
|
>
|
||||||
|
I'm using my phone →
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
92
src/components/ui/NeynarAuthButton/ProfileButton.tsx
Normal file
92
src/components/ui/NeynarAuthButton/ProfileButton.tsx
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useRef, useState } from 'react';
|
||||||
|
import { useDetectClickOutside } from '~/hooks/useDetectClickOutside';
|
||||||
|
import { cn } from '~/lib/utils';
|
||||||
|
|
||||||
|
export function ProfileButton({
|
||||||
|
userData,
|
||||||
|
onSignOut,
|
||||||
|
}: {
|
||||||
|
userData?: { fid?: number; pfpUrl?: string; username?: string };
|
||||||
|
onSignOut: () => void;
|
||||||
|
}) {
|
||||||
|
const [showDropdown, setShowDropdown] = useState(false);
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useDetectClickOutside(ref, () => setShowDropdown(false));
|
||||||
|
|
||||||
|
const name = userData?.username ?? `!${userData?.fid}`;
|
||||||
|
const pfpUrl = userData?.pfpUrl ?? 'https://farcaster.xyz/avatar.png';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative" ref={ref}>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowDropdown(!showDropdown)}
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-3 px-4 py-2 min-w-0 rounded-lg',
|
||||||
|
'bg-transparent border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100',
|
||||||
|
'hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors',
|
||||||
|
'focus:outline-none focus:ring-1 focus:ring-primary'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={pfpUrl}
|
||||||
|
alt="Profile"
|
||||||
|
className="w-6 h-6 rounded-full object-cover flex-shrink-0"
|
||||||
|
onError={(e) => {
|
||||||
|
(e.target as HTMLImageElement).src =
|
||||||
|
'https://farcaster.xyz/avatar.png';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium truncate max-w-[120px]">
|
||||||
|
{name ? name : '...'}
|
||||||
|
</span>
|
||||||
|
<svg
|
||||||
|
className={cn(
|
||||||
|
'w-4 h-4 transition-transform flex-shrink-0',
|
||||||
|
showDropdown && 'rotate-180'
|
||||||
|
)}
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M19 9l-7 7-7-7"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{showDropdown && (
|
||||||
|
<div className="absolute top-full right-0 left-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-50">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
onSignOut();
|
||||||
|
setShowDropdown(false);
|
||||||
|
}}
|
||||||
|
className="w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={1.5}
|
||||||
|
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
710
src/components/ui/NeynarAuthButton/index.tsx
Normal file
710
src/components/ui/NeynarAuthButton/index.tsx
Normal file
@@ -0,0 +1,710 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import '@farcaster/auth-kit/styles.css';
|
||||||
|
import { useSignIn, UseSignInData } from '@farcaster/auth-kit';
|
||||||
|
import { useCallback, useEffect, useState, useRef } from 'react';
|
||||||
|
import { cn } from '~/lib/utils';
|
||||||
|
import { Button } from '~/components/ui/Button';
|
||||||
|
import { ProfileButton } from '~/components/ui/NeynarAuthButton/ProfileButton';
|
||||||
|
import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
|
||||||
|
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
||||||
|
import { useMiniApp } from '@neynar/react';
|
||||||
|
import {
|
||||||
|
signIn as backendSignIn,
|
||||||
|
signOut as backendSignOut,
|
||||||
|
useSession,
|
||||||
|
} from 'next-auth/react';
|
||||||
|
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
|
||||||
|
|
||||||
|
type User = {
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
// Add other user properties as needed
|
||||||
|
};
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'neynar_authenticated_user';
|
||||||
|
const FARCASTER_FID = 9152;
|
||||||
|
|
||||||
|
interface StoredAuthState {
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
user: {
|
||||||
|
object: 'user';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
profile: {
|
||||||
|
bio: {
|
||||||
|
text: string;
|
||||||
|
mentioned_profiles?: Array<{
|
||||||
|
object: 'user_dehydrated';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
}>;
|
||||||
|
mentioned_profiles_ranges?: Array<{
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
location?: {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
address: {
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
country: string;
|
||||||
|
country_code: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
follower_count: number;
|
||||||
|
following_count: number;
|
||||||
|
verifications: string[];
|
||||||
|
verified_addresses: {
|
||||||
|
eth_addresses: string[];
|
||||||
|
sol_addresses: string[];
|
||||||
|
primary: {
|
||||||
|
eth_address: string;
|
||||||
|
sol_address: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
verified_accounts: Array<Record<string, unknown>>;
|
||||||
|
power_badge: boolean;
|
||||||
|
url?: string;
|
||||||
|
experimental?: {
|
||||||
|
neynar_user_score: number;
|
||||||
|
deprecation_notice: string;
|
||||||
|
};
|
||||||
|
score: number;
|
||||||
|
} | null;
|
||||||
|
signers: {
|
||||||
|
object: 'signer';
|
||||||
|
signer_uuid: string;
|
||||||
|
public_key: string;
|
||||||
|
status: 'approved';
|
||||||
|
fid: number;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main Custom SignInButton Component
|
||||||
|
export function NeynarAuthButton() {
|
||||||
|
const [nonce, setNonce] = useState<string | null>(null);
|
||||||
|
const [storedAuth, setStoredAuth] = useState<StoredAuthState | null>(null);
|
||||||
|
const [signersLoading, setSignersLoading] = useState(false);
|
||||||
|
const { context } = useMiniApp();
|
||||||
|
const { data: session } = useSession();
|
||||||
|
// New state for unified dialog flow
|
||||||
|
const [showDialog, setShowDialog] = useState(false);
|
||||||
|
const [dialogStep, setDialogStep] = useState<'signin' | 'access' | 'loading'>(
|
||||||
|
'loading'
|
||||||
|
);
|
||||||
|
const [signerApprovalUrl, setSignerApprovalUrl] = useState<string | null>(
|
||||||
|
null
|
||||||
|
);
|
||||||
|
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(
|
||||||
|
null
|
||||||
|
);
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
const [signature, setSignature] = useState<string | null>(null);
|
||||||
|
const [isSignerFlowRunning, setIsSignerFlowRunning] = useState(false);
|
||||||
|
const signerFlowStartedRef = useRef(false);
|
||||||
|
|
||||||
|
// Determine which flow to use based on context
|
||||||
|
const useBackendFlow = context !== undefined;
|
||||||
|
|
||||||
|
// Helper function to create a signer
|
||||||
|
const createSigner = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/auth/signer', {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to create signer');
|
||||||
|
}
|
||||||
|
|
||||||
|
const signerData = await response.json();
|
||||||
|
return signerData;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error creating signer:', error);
|
||||||
|
// throw error;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Helper function to update session with signers (backend flow only)
|
||||||
|
const updateSessionWithSigners = useCallback(
|
||||||
|
async (
|
||||||
|
signers: StoredAuthState['signers'],
|
||||||
|
user: StoredAuthState['user']
|
||||||
|
) => {
|
||||||
|
if (!useBackendFlow) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// For backend flow, we need to sign in again with the additional data
|
||||||
|
if (message && signature) {
|
||||||
|
const signInData = {
|
||||||
|
message,
|
||||||
|
signature,
|
||||||
|
redirect: false,
|
||||||
|
nonce: nonce || '',
|
||||||
|
fid: user?.fid?.toString() || '',
|
||||||
|
signers: JSON.stringify(signers),
|
||||||
|
user: JSON.stringify(user),
|
||||||
|
};
|
||||||
|
|
||||||
|
await backendSignIn('neynar', signInData);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error updating session with signers:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[useBackendFlow, message, signature, nonce]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Helper function to fetch user data from Neynar API
|
||||||
|
const fetchUserData = useCallback(
|
||||||
|
async (fid: number): Promise<User | null> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/users?fids=${fid}`);
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
return data.users?.[0] || null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching user data:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Helper function to generate signed key request
|
||||||
|
const generateSignedKeyRequest = useCallback(
|
||||||
|
async (signerUuid: string, publicKey: string) => {
|
||||||
|
try {
|
||||||
|
// Prepare request body
|
||||||
|
const requestBody: {
|
||||||
|
signerUuid: string;
|
||||||
|
publicKey: string;
|
||||||
|
sponsor?: { sponsored_by_neynar: boolean };
|
||||||
|
} = {
|
||||||
|
signerUuid,
|
||||||
|
publicKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch('/api/auth/signer/signed_key', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(requestBody),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(
|
||||||
|
`Failed to generate signed key request: ${errorData.error}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error generating signed key request:', error);
|
||||||
|
// throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Helper function to fetch all signers
|
||||||
|
const fetchAllSigners = useCallback(
|
||||||
|
async (message: string, signature: string) => {
|
||||||
|
try {
|
||||||
|
setSignersLoading(true);
|
||||||
|
|
||||||
|
const endpoint = useBackendFlow
|
||||||
|
? `/api/auth/session-signers?message=${encodeURIComponent(
|
||||||
|
message
|
||||||
|
)}&signature=${signature}`
|
||||||
|
: `/api/auth/signers?message=${encodeURIComponent(
|
||||||
|
message
|
||||||
|
)}&signature=${signature}`;
|
||||||
|
|
||||||
|
const response = await fetch(endpoint);
|
||||||
|
const signerData = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
if (useBackendFlow) {
|
||||||
|
// For backend flow, update session with signers
|
||||||
|
if (signerData.signers && signerData.signers.length > 0) {
|
||||||
|
const user =
|
||||||
|
signerData.user ||
|
||||||
|
(await fetchUserData(signerData.signers[0].fid));
|
||||||
|
await updateSessionWithSigners(signerData.signers, user);
|
||||||
|
}
|
||||||
|
return signerData.signers;
|
||||||
|
} else {
|
||||||
|
// For frontend flow, store in localStorage
|
||||||
|
let user: StoredAuthState['user'] | null = null;
|
||||||
|
|
||||||
|
if (signerData.signers && signerData.signers.length > 0) {
|
||||||
|
const fetchedUser = (await fetchUserData(
|
||||||
|
signerData.signers[0].fid
|
||||||
|
)) as StoredAuthState['user'];
|
||||||
|
user = fetchedUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store signers in localStorage, preserving existing auth data
|
||||||
|
const updatedState: StoredAuthState = {
|
||||||
|
isAuthenticated: !!user,
|
||||||
|
signers: signerData.signers || [],
|
||||||
|
user,
|
||||||
|
};
|
||||||
|
setItem<StoredAuthState>(STORAGE_KEY, updatedState);
|
||||||
|
setStoredAuth(updatedState);
|
||||||
|
|
||||||
|
return signerData.signers;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('❌ Failed to fetch signers');
|
||||||
|
// throw new Error('Failed to fetch signers');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error fetching signers:', error);
|
||||||
|
// throw error;
|
||||||
|
} finally {
|
||||||
|
setSignersLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[useBackendFlow, fetchUserData, updateSessionWithSigners]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Helper function to poll signer status
|
||||||
|
const startPolling = useCallback(
|
||||||
|
(signerUuid: string, message: string, signature: string) => {
|
||||||
|
// Clear any existing polling interval before starting a new one
|
||||||
|
if (pollingInterval) {
|
||||||
|
clearInterval(pollingInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
let retryCount = 0;
|
||||||
|
const maxRetries = 10; // Maximum 10 retries (20 seconds total)
|
||||||
|
const maxPollingTime = 60000; // Maximum 60 seconds of polling
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
const interval = setInterval(async () => {
|
||||||
|
// Check if we've been polling too long
|
||||||
|
if (Date.now() - startTime > maxPollingTime) {
|
||||||
|
clearInterval(interval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/auth/signer?signerUuid=${signerUuid}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
// Check if it's a rate limit error
|
||||||
|
if (response.status === 429) {
|
||||||
|
clearInterval(interval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increment retry count for other errors
|
||||||
|
retryCount++;
|
||||||
|
if (retryCount >= maxRetries) {
|
||||||
|
clearInterval(interval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Failed to poll signer status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const signerData = await response.json();
|
||||||
|
|
||||||
|
if (signerData.status === 'approved') {
|
||||||
|
clearInterval(interval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
setShowDialog(false);
|
||||||
|
setDialogStep('signin');
|
||||||
|
setSignerApprovalUrl(null);
|
||||||
|
|
||||||
|
// Refetch all signers
|
||||||
|
await fetchAllSigners(message, signature);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error polling signer:', error);
|
||||||
|
}
|
||||||
|
}, 2000); // Poll every 2 second
|
||||||
|
|
||||||
|
setPollingInterval(interval);
|
||||||
|
},
|
||||||
|
[fetchAllSigners, pollingInterval]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Cleanup polling on unmount
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (pollingInterval) {
|
||||||
|
clearInterval(pollingInterval);
|
||||||
|
}
|
||||||
|
signerFlowStartedRef.current = false;
|
||||||
|
};
|
||||||
|
}, [pollingInterval]);
|
||||||
|
|
||||||
|
// Generate nonce
|
||||||
|
useEffect(() => {
|
||||||
|
const generateNonce = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/auth/nonce');
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
setNonce(data.nonce);
|
||||||
|
} else {
|
||||||
|
console.error('Failed to fetch nonce');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating nonce:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
generateNonce();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Load stored auth state on mount (only for frontend flow)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!useBackendFlow) {
|
||||||
|
const stored = getItem<StoredAuthState>(STORAGE_KEY);
|
||||||
|
if (stored && stored.isAuthenticated) {
|
||||||
|
setStoredAuth(stored);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [useBackendFlow]);
|
||||||
|
|
||||||
|
// Success callback - this is critical!
|
||||||
|
const onSuccessCallback = useCallback(
|
||||||
|
async (res: UseSignInData) => {
|
||||||
|
if (!useBackendFlow) {
|
||||||
|
// Only handle localStorage for frontend flow
|
||||||
|
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||||
|
const user = res.fid ? await fetchUserData(res.fid) : null;
|
||||||
|
const authState: StoredAuthState = {
|
||||||
|
...existingAuth,
|
||||||
|
isAuthenticated: true,
|
||||||
|
user: user as StoredAuthState['user'],
|
||||||
|
signers: existingAuth?.signers || [], // Preserve existing signers
|
||||||
|
};
|
||||||
|
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
||||||
|
setStoredAuth(authState);
|
||||||
|
}
|
||||||
|
// For backend flow, the session will be handled by NextAuth
|
||||||
|
},
|
||||||
|
[useBackendFlow, fetchUserData]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Error callback
|
||||||
|
const onErrorCallback = useCallback((error?: Error | null) => {
|
||||||
|
console.error('❌ Sign in error:', error);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const signInState = useSignIn({
|
||||||
|
nonce: nonce || undefined,
|
||||||
|
onSuccess: onSuccessCallback,
|
||||||
|
onError: onErrorCallback,
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
signIn: frontendSignIn,
|
||||||
|
signOut: frontendSignOut,
|
||||||
|
connect,
|
||||||
|
reconnect,
|
||||||
|
isSuccess,
|
||||||
|
isError,
|
||||||
|
error,
|
||||||
|
channelToken,
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
validSignature,
|
||||||
|
} = signInState;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMessage(data?.message || null);
|
||||||
|
setSignature(data?.signature || null);
|
||||||
|
|
||||||
|
// Reset the signer flow flag when message/signature change
|
||||||
|
if (data?.message && data?.signature) {
|
||||||
|
signerFlowStartedRef.current = false;
|
||||||
|
}
|
||||||
|
}, [data?.message, data?.signature]);
|
||||||
|
|
||||||
|
// Connect for frontend flow when nonce is available
|
||||||
|
useEffect(() => {
|
||||||
|
if (!useBackendFlow && nonce && !channelToken) {
|
||||||
|
connect();
|
||||||
|
}
|
||||||
|
}, [useBackendFlow, nonce, channelToken, connect]);
|
||||||
|
|
||||||
|
// Handle fetching signers after successful authentication
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
message &&
|
||||||
|
signature &&
|
||||||
|
!isSignerFlowRunning &&
|
||||||
|
!signerFlowStartedRef.current
|
||||||
|
) {
|
||||||
|
signerFlowStartedRef.current = true;
|
||||||
|
|
||||||
|
const handleSignerFlow = async () => {
|
||||||
|
setIsSignerFlowRunning(true);
|
||||||
|
try {
|
||||||
|
const clientContext = context?.client as Record<string, unknown>;
|
||||||
|
const isMobileContext =
|
||||||
|
clientContext?.platformType === 'mobile' &&
|
||||||
|
clientContext?.clientFid === FARCASTER_FID;
|
||||||
|
|
||||||
|
// Step 1: Change to loading state
|
||||||
|
setDialogStep('loading');
|
||||||
|
|
||||||
|
// Show dialog if not using backend flow or in browser farcaster
|
||||||
|
if ((useBackendFlow && !isMobileContext) || !useBackendFlow)
|
||||||
|
setShowDialog(true);
|
||||||
|
|
||||||
|
// First, fetch existing signers
|
||||||
|
const signers = await fetchAllSigners(message, signature);
|
||||||
|
|
||||||
|
if (useBackendFlow && isMobileContext) setSignersLoading(true);
|
||||||
|
|
||||||
|
// Check if no signers exist or if we have empty signers
|
||||||
|
if (!signers || signers.length === 0) {
|
||||||
|
// Step 1: Create a signer
|
||||||
|
const newSigner = await createSigner();
|
||||||
|
|
||||||
|
// Step 2: Generate signed key request
|
||||||
|
const signedKeyData = await generateSignedKeyRequest(
|
||||||
|
newSigner.signer_uuid,
|
||||||
|
newSigner.public_key
|
||||||
|
);
|
||||||
|
|
||||||
|
// Step 3: Show QR code in access dialog for signer approval
|
||||||
|
setSignerApprovalUrl(signedKeyData.signer_approval_url);
|
||||||
|
|
||||||
|
if (isMobileContext) {
|
||||||
|
setShowDialog(false);
|
||||||
|
await sdk.actions.openUrl(
|
||||||
|
signedKeyData.signer_approval_url.replace(
|
||||||
|
'https://client.farcaster.xyz/deeplinks/signed-key-request',
|
||||||
|
'https://farcaster.xyz/~/connect'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setShowDialog(true); // Ensure dialog is shown during loading
|
||||||
|
setDialogStep('access');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 4: Start polling for signer approval
|
||||||
|
startPolling(newSigner.signer_uuid, message, signature);
|
||||||
|
} else {
|
||||||
|
// If signers exist, close the dialog
|
||||||
|
setSignersLoading(false);
|
||||||
|
setShowDialog(false);
|
||||||
|
setDialogStep('signin');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error in signer flow:', error);
|
||||||
|
// On error, reset to signin step and hide dialog
|
||||||
|
setDialogStep('signin');
|
||||||
|
setSignersLoading(false);
|
||||||
|
setShowDialog(false);
|
||||||
|
setSignerApprovalUrl(null);
|
||||||
|
} finally {
|
||||||
|
setIsSignerFlowRunning(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleSignerFlow();
|
||||||
|
}
|
||||||
|
}, [message, signature]); // Simplified dependencies
|
||||||
|
|
||||||
|
// Backend flow using NextAuth
|
||||||
|
const handleBackendSignIn = useCallback(async () => {
|
||||||
|
if (!nonce) {
|
||||||
|
console.error('❌ No nonce available for backend sign-in');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSignersLoading(true);
|
||||||
|
const result = await sdk.actions.signIn({ nonce });
|
||||||
|
|
||||||
|
const signInData = {
|
||||||
|
message: result.message,
|
||||||
|
signature: result.signature,
|
||||||
|
redirect: false,
|
||||||
|
nonce: nonce,
|
||||||
|
};
|
||||||
|
|
||||||
|
const nextAuthResult = await backendSignIn('neynar', signInData);
|
||||||
|
if (nextAuthResult?.ok) {
|
||||||
|
setMessage(result.message);
|
||||||
|
setSignature(result.signature);
|
||||||
|
} else {
|
||||||
|
console.error('❌ NextAuth sign-in failed:', nextAuthResult);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof SignInCore.RejectedByUser) {
|
||||||
|
console.log('ℹ️ Sign-in rejected by user');
|
||||||
|
} else {
|
||||||
|
console.error('❌ Backend sign-in error:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [nonce]);
|
||||||
|
|
||||||
|
const handleFrontEndSignIn = useCallback(() => {
|
||||||
|
if (isError) {
|
||||||
|
reconnect();
|
||||||
|
}
|
||||||
|
setDialogStep('signin');
|
||||||
|
setShowDialog(true);
|
||||||
|
frontendSignIn();
|
||||||
|
}, [isError, reconnect, frontendSignIn]);
|
||||||
|
|
||||||
|
const handleSignOut = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setSignersLoading(true);
|
||||||
|
|
||||||
|
if (useBackendFlow) {
|
||||||
|
// Only sign out from NextAuth if the current session is from Neynar provider
|
||||||
|
if (session?.provider === 'neynar') {
|
||||||
|
await backendSignOut({ redirect: false });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Frontend flow sign out
|
||||||
|
frontendSignOut();
|
||||||
|
removeItem(STORAGE_KEY);
|
||||||
|
setStoredAuth(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common cleanup for both flows
|
||||||
|
setShowDialog(false);
|
||||||
|
setDialogStep('signin');
|
||||||
|
setSignerApprovalUrl(null);
|
||||||
|
setMessage(null);
|
||||||
|
setSignature(null);
|
||||||
|
|
||||||
|
// Reset polling interval
|
||||||
|
if (pollingInterval) {
|
||||||
|
clearInterval(pollingInterval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset signer flow flag
|
||||||
|
signerFlowStartedRef.current = false;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error during sign out:', error);
|
||||||
|
// Optionally handle error state
|
||||||
|
} finally {
|
||||||
|
setSignersLoading(false);
|
||||||
|
}
|
||||||
|
}, [useBackendFlow, frontendSignOut, pollingInterval, session]);
|
||||||
|
|
||||||
|
const authenticated = useBackendFlow
|
||||||
|
? !!(
|
||||||
|
session?.provider === 'neynar' &&
|
||||||
|
session?.user?.fid &&
|
||||||
|
session?.signers &&
|
||||||
|
session.signers.length > 0
|
||||||
|
)
|
||||||
|
: ((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
||||||
|
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||||
|
|
||||||
|
const userData = useBackendFlow
|
||||||
|
? {
|
||||||
|
fid: session?.user?.fid,
|
||||||
|
username: session?.user?.username || '',
|
||||||
|
pfpUrl: session?.user?.pfp_url || '',
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
fid: storedAuth?.user?.fid,
|
||||||
|
username: storedAuth?.user?.username || '',
|
||||||
|
pfpUrl: storedAuth?.user?.pfp_url || '',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Show loading state while nonce is being fetched or signers are loading
|
||||||
|
if (!nonce || signersLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center">
|
||||||
|
<div className="flex items-center gap-3 px-4 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||||
|
<div className="spinner w-4 h-4" />
|
||||||
|
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
Loading...
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{authenticated ? (
|
||||||
|
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
onClick={useBackendFlow ? handleBackendSignIn : handleFrontEndSignIn}
|
||||||
|
disabled={!useBackendFlow && !url}
|
||||||
|
className={cn(
|
||||||
|
'btn btn-primary flex items-center gap-3',
|
||||||
|
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||||
|
'transform transition-all duration-200 active:scale-[0.98]',
|
||||||
|
!url && !useBackendFlow && 'cursor-not-allowed'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{!useBackendFlow && !url ? (
|
||||||
|
<>
|
||||||
|
<div className="spinner-primary w-5 h-5" />
|
||||||
|
<span>Initializing...</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span>Sign in with Neynar</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Unified Auth Dialog */}
|
||||||
|
{
|
||||||
|
<AuthDialog
|
||||||
|
open={showDialog}
|
||||||
|
onClose={() => {
|
||||||
|
setShowDialog(false);
|
||||||
|
setDialogStep('signin');
|
||||||
|
setSignerApprovalUrl(null);
|
||||||
|
if (pollingInterval) {
|
||||||
|
clearInterval(pollingInterval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
url={url}
|
||||||
|
isError={isError}
|
||||||
|
error={error}
|
||||||
|
step={dialogStep}
|
||||||
|
isLoading={signersLoading}
|
||||||
|
signerApprovalUrl={signerApprovalUrl}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
119
src/components/ui/Share.tsx
Normal file
119
src/components/ui/Share.tsx
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useState, useEffect } from 'react';
|
||||||
|
import { Button } from './Button';
|
||||||
|
import { useMiniApp } from '@neynar/react';
|
||||||
|
import { type ComposeCast } from "@farcaster/miniapp-sdk";
|
||||||
|
import { APP_URL } from '~/lib/constants';
|
||||||
|
|
||||||
|
interface EmbedConfig {
|
||||||
|
path?: string;
|
||||||
|
url?: string;
|
||||||
|
imageUrl?: () => Promise<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CastConfig extends Omit<ComposeCast.Options, 'embeds'> {
|
||||||
|
bestFriends?: boolean;
|
||||||
|
embeds?: (string | EmbedConfig)[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShareButtonProps {
|
||||||
|
buttonText: string;
|
||||||
|
cast: CastConfig;
|
||||||
|
className?: string;
|
||||||
|
isLoading?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShareButton({ buttonText, cast, className = '', isLoading = false }: ShareButtonProps) {
|
||||||
|
const [isProcessing, setIsProcessing] = useState(false);
|
||||||
|
const [bestFriends, setBestFriends] = useState<{ fid: number; username: string; }[] | null>(null);
|
||||||
|
const [isLoadingBestFriends, setIsLoadingBestFriends] = useState(false);
|
||||||
|
const { context, actions } = useMiniApp();
|
||||||
|
|
||||||
|
// Fetch best friends if needed
|
||||||
|
useEffect(() => {
|
||||||
|
if (cast.bestFriends && context?.user?.fid) {
|
||||||
|
setIsLoadingBestFriends(true);
|
||||||
|
fetch(`/api/best-friends?fid=${context.user.fid}`)
|
||||||
|
.then(res => res.json())
|
||||||
|
.then(data => setBestFriends(data.bestFriends))
|
||||||
|
.catch(err => console.error('Failed to fetch best friends:', err))
|
||||||
|
.finally(() => setIsLoadingBestFriends(false));
|
||||||
|
}
|
||||||
|
}, [cast.bestFriends, context?.user?.fid]);
|
||||||
|
|
||||||
|
const handleShare = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setIsProcessing(true);
|
||||||
|
|
||||||
|
let finalText = cast.text || '';
|
||||||
|
|
||||||
|
// Process best friends if enabled and data is loaded
|
||||||
|
if (cast.bestFriends) {
|
||||||
|
if (bestFriends) {
|
||||||
|
// Replace @N with usernames, or remove if no matching friend
|
||||||
|
finalText = finalText.replace(/@\d+/g, (match) => {
|
||||||
|
const friendIndex = parseInt(match.slice(1)) - 1;
|
||||||
|
const friend = bestFriends[friendIndex];
|
||||||
|
if (friend) {
|
||||||
|
return `@${friend.username}`;
|
||||||
|
}
|
||||||
|
return ''; // Remove @N if no matching friend
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// If bestFriends is not loaded but bestFriends is enabled, remove @N patterns
|
||||||
|
finalText = finalText.replace(/@\d+/g, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process embeds
|
||||||
|
const processedEmbeds = await Promise.all(
|
||||||
|
(cast.embeds || []).map(async (embed) => {
|
||||||
|
if (typeof embed === 'string') {
|
||||||
|
return embed;
|
||||||
|
}
|
||||||
|
if (embed.path) {
|
||||||
|
const baseUrl = APP_URL || window.location.origin;
|
||||||
|
const url = new URL(`${baseUrl}${embed.path}`);
|
||||||
|
|
||||||
|
// Add UTM parameters
|
||||||
|
url.searchParams.set('utm_source', `share-cast-${context?.user?.fid || 'unknown'}`);
|
||||||
|
|
||||||
|
// If custom image generator is provided, use it
|
||||||
|
if (embed.imageUrl) {
|
||||||
|
const imageUrl = await embed.imageUrl();
|
||||||
|
url.searchParams.set('share_image_url', imageUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
return embed.url || '';
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open cast composer with all supported intents
|
||||||
|
await actions.composeCast({
|
||||||
|
text: finalText,
|
||||||
|
embeds: processedEmbeds as [string] | [string, string] | undefined,
|
||||||
|
parent: cast.parent,
|
||||||
|
channelKey: cast.channelKey,
|
||||||
|
close: cast.close,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to share:', error);
|
||||||
|
} finally {
|
||||||
|
setIsProcessing(false);
|
||||||
|
}
|
||||||
|
}, [cast, bestFriends, context?.user?.fid, actions]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
onClick={handleShare}
|
||||||
|
className={className}
|
||||||
|
isLoading={isLoading || isProcessing}
|
||||||
|
disabled={isLoadingBestFriends}
|
||||||
|
>
|
||||||
|
{buttonText}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
218
src/components/ui/tabs/ActionsTab.tsx
Normal file
218
src/components/ui/tabs/ActionsTab.tsx
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useState, type ComponentType } 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/miniapp-sdk';
|
||||||
|
import { APP_URL } from '~/lib/constants';
|
||||||
|
|
||||||
|
// Optional import for NeynarAuthButton - may not exist in all templates
|
||||||
|
let NeynarAuthButton: ComponentType | null = null;
|
||||||
|
try {
|
||||||
|
const module = require('../NeynarAuthButton/index');
|
||||||
|
NeynarAuthButton = module.NeynarAuthButton;
|
||||||
|
} catch (error) {
|
||||||
|
// Component doesn't exist, that's okay
|
||||||
|
console.log('NeynarAuthButton not available in this template');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
|
||||||
|
*
|
||||||
|
* This component provides the main interaction interface for users to:
|
||||||
|
* - Share the mini app with others
|
||||||
|
* - Sign in with Farcaster
|
||||||
|
* - Send notifications to their account
|
||||||
|
* - Trigger haptic feedback
|
||||||
|
* - Add the mini app to their client
|
||||||
|
* - Copy share URLs
|
||||||
|
*
|
||||||
|
* The component uses the useMiniApp hook to access Farcaster context and actions.
|
||||||
|
* All state is managed locally within this component.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <ActionsTab />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function ActionsTab() {
|
||||||
|
// --- Hooks ---
|
||||||
|
const { actions, added, notificationDetails, haptics, context } =
|
||||||
|
useMiniApp();
|
||||||
|
|
||||||
|
// --- State ---
|
||||||
|
const [notificationState, setNotificationState] = useState({
|
||||||
|
sendStatus: '',
|
||||||
|
shareUrlCopied: false,
|
||||||
|
});
|
||||||
|
const [selectedHapticIntensity, setSelectedHapticIntensity] =
|
||||||
|
useState<Haptics.ImpactOccurredType>('medium');
|
||||||
|
|
||||||
|
// --- Handlers ---
|
||||||
|
/**
|
||||||
|
* Sends a notification to the current user's Farcaster account.
|
||||||
|
*
|
||||||
|
* This function makes a POST request to the /api/send-notification endpoint
|
||||||
|
* with the user's FID and notification details. It handles different response
|
||||||
|
* statuses including success (200), rate limiting (429), and errors.
|
||||||
|
*
|
||||||
|
* @returns Promise that resolves when the notification is sent or fails
|
||||||
|
*/
|
||||||
|
const sendFarcasterNotification = useCallback(async () => {
|
||||||
|
setNotificationState((prev) => ({ ...prev, sendStatus: '' }));
|
||||||
|
if (!notificationDetails || !context) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/send-notification', {
|
||||||
|
method: 'POST',
|
||||||
|
mode: 'same-origin',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
fid: context.user.fid,
|
||||||
|
notificationDetails,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (response.status === 200) {
|
||||||
|
setNotificationState((prev) => ({ ...prev, sendStatus: 'Success' }));
|
||||||
|
return;
|
||||||
|
} else if (response.status === 429) {
|
||||||
|
setNotificationState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
sendStatus: 'Rate limited',
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const responseText = await response.text();
|
||||||
|
setNotificationState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
sendStatus: `Error: ${responseText}`,
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
setNotificationState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
sendStatus: `Error: ${error}`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}, [context, notificationDetails]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copies the share URL for the current user to the clipboard.
|
||||||
|
*
|
||||||
|
* This function generates a share URL using the user's FID and copies it
|
||||||
|
* to the clipboard. It shows a temporary "Copied!" message for 2 seconds.
|
||||||
|
*/
|
||||||
|
const copyUserShareUrl = useCallback(async () => {
|
||||||
|
if (context?.user?.fid) {
|
||||||
|
const userShareUrl = `${APP_URL}/share/${context.user.fid}`;
|
||||||
|
await navigator.clipboard.writeText(userShareUrl);
|
||||||
|
setNotificationState((prev) => ({ ...prev, shareUrlCopied: true }));
|
||||||
|
setTimeout(
|
||||||
|
() =>
|
||||||
|
setNotificationState((prev) => ({ ...prev, shareUrlCopied: false })),
|
||||||
|
2000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, [context?.user?.fid]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Triggers haptic feedback with the selected intensity.
|
||||||
|
*
|
||||||
|
* This function calls the haptics.impactOccurred method with the current
|
||||||
|
* selectedHapticIntensity setting. It handles errors gracefully by logging them.
|
||||||
|
*/
|
||||||
|
const triggerHapticFeedback = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
await haptics.impactOccurred(selectedHapticIntensity);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Haptic feedback failed:', error);
|
||||||
|
}
|
||||||
|
}, [haptics, selectedHapticIntensity]);
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
|
||||||
|
{/* Share functionality */}
|
||||||
|
<ShareButton
|
||||||
|
buttonText="Share Mini App"
|
||||||
|
cast={{
|
||||||
|
text: 'Check out this awesome frame @1 @2 @3! 🚀🪐',
|
||||||
|
bestFriends: true,
|
||||||
|
embeds: [`${APP_URL}/share/${context?.user?.fid || ''}`],
|
||||||
|
}}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Authentication */}
|
||||||
|
<SignIn />
|
||||||
|
|
||||||
|
{/* Neynar Authentication */}
|
||||||
|
{NeynarAuthButton && <NeynarAuthButton />}
|
||||||
|
|
||||||
|
{/* Mini app actions */}
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
actions.openUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
|
||||||
|
}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Open Link
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button onClick={actions.addMiniApp} disabled={added} className="w-full">
|
||||||
|
Add Mini App to Client
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* Notification functionality */}
|
||||||
|
{notificationState.sendStatus && (
|
||||||
|
<div className="text-sm w-full">
|
||||||
|
Send notification result: {notificationState.sendStatus}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
onClick={sendFarcasterNotification}
|
||||||
|
disabled={!notificationDetails}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Send notification
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* Share URL copying */}
|
||||||
|
<Button
|
||||||
|
onClick={copyUserShareUrl}
|
||||||
|
disabled={!context?.user?.fid}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
{notificationState.shareUrlCopied ? 'Copied!' : 'Copy share URL'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* Haptic feedback controls */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||||
|
Haptic Intensity
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={selectedHapticIntensity}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSelectedHapticIntensity(
|
||||||
|
e.target.value as Haptics.ImpactOccurredType
|
||||||
|
)
|
||||||
|
}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
|
||||||
|
>
|
||||||
|
<option value={'light'}>Light</option>
|
||||||
|
<option value={'medium'}>Medium</option>
|
||||||
|
<option value={'heavy'}>Heavy</option>
|
||||||
|
<option value={'soft'}>Soft</option>
|
||||||
|
<option value={'rigid'}>Rigid</option>
|
||||||
|
</select>
|
||||||
|
<Button onClick={triggerHapticFeedback} className="w-full">
|
||||||
|
Trigger Haptic Feedback
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
35
src/components/ui/tabs/ContextTab.tsx
Normal file
35
src/components/ui/tabs/ContextTab.tsx
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMiniApp } from "@neynar/react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ContextTab component displays the current mini app context in JSON format.
|
||||||
|
*
|
||||||
|
* This component provides a developer-friendly view of the Farcaster mini app context,
|
||||||
|
* including user information, client details, and other contextual data. It's useful
|
||||||
|
* for debugging and understanding what data is available to the mini app.
|
||||||
|
*
|
||||||
|
* The context includes:
|
||||||
|
* - User information (FID, username, display name, profile picture)
|
||||||
|
* - Client information (safe area insets, platform details)
|
||||||
|
* - Mini app configuration and state
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <ContextTab />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function ContextTab() {
|
||||||
|
const { context } = useMiniApp();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-6">
|
||||||
|
<h2 className="text-lg font-semibold mb-2">Context</h2>
|
||||||
|
<div className="p-4 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||||
|
<pre className="font-mono text-xs whitespace-pre-wrap break-words w-full">
|
||||||
|
{JSON.stringify(context, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
24
src/components/ui/tabs/HomeTab.tsx
Normal file
24
src/components/ui/tabs/HomeTab.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HomeTab component displays the main landing content for the mini app.
|
||||||
|
*
|
||||||
|
* This is the default tab that users see when they first open the mini app.
|
||||||
|
* It provides a simple welcome message and placeholder content that can be
|
||||||
|
* customized for specific use cases.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <HomeTab />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function HomeTab() {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-[calc(100vh-200px)] px-6">
|
||||||
|
<div className="text-center w-full max-w-md mx-auto">
|
||||||
|
<p className="text-lg mb-2">Put your content here!</p>
|
||||||
|
<p className="text-sm text-gray-500 dark:text-gray-400">Powered by Neynar 🪐</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
350
src/components/ui/tabs/WalletTab.tsx
Normal file
350
src/components/ui/tabs/WalletTab.tsx
Normal file
@@ -0,0 +1,350 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
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";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WalletTab component manages wallet-related UI for both EVM and Solana chains.
|
||||||
|
*
|
||||||
|
* This component provides a comprehensive wallet interface that supports:
|
||||||
|
* - EVM wallet connections (Farcaster Frame, Coinbase Wallet, MetaMask)
|
||||||
|
* - Solana wallet integration
|
||||||
|
* - Message signing for both chains
|
||||||
|
* - Transaction sending for both chains
|
||||||
|
* - Chain switching for EVM chains
|
||||||
|
* - Auto-connection in Farcaster clients
|
||||||
|
*
|
||||||
|
* The component automatically detects when running in a Farcaster client
|
||||||
|
* and attempts to auto-connect using the Farcaster Frame connector.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <WalletTab />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface WalletStatusProps {
|
||||||
|
address?: string;
|
||||||
|
chainId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays the current wallet address and chain ID.
|
||||||
|
*/
|
||||||
|
function WalletStatus({ address, chainId }: WalletStatusProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{address && (
|
||||||
|
<div className="text-xs w-full">
|
||||||
|
Address: <pre className="inline w-full">{truncateAddress(address)}</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{chainId && (
|
||||||
|
<div className="text-xs w-full">
|
||||||
|
Chain ID: <pre className="inline w-full">{chainId}</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConnectionControlsProps {
|
||||||
|
isConnected: boolean;
|
||||||
|
context: {
|
||||||
|
user?: { fid?: number };
|
||||||
|
client?: unknown;
|
||||||
|
} | null;
|
||||||
|
connect: (args: { connector: Connector }) => void;
|
||||||
|
connectors: readonly Connector[];
|
||||||
|
disconnect: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders wallet connection controls based on connection state and context.
|
||||||
|
*/
|
||||||
|
function ConnectionControls({
|
||||||
|
isConnected,
|
||||||
|
context,
|
||||||
|
connect,
|
||||||
|
connectors,
|
||||||
|
disconnect,
|
||||||
|
}: ConnectionControlsProps) {
|
||||||
|
if (isConnected) {
|
||||||
|
return (
|
||||||
|
<Button onClick={() => disconnect()} className="w-full">
|
||||||
|
Disconnect
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (context) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-2 w-full">
|
||||||
|
<Button onClick={() => connect({ connector: connectors[0] })} className="w-full">
|
||||||
|
Connect (Auto)
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
console.log("Manual Farcaster connection attempt");
|
||||||
|
console.log("Connectors:", connectors.map((c, i) => `${i}: ${c.name}`));
|
||||||
|
connect({ connector: connectors[0] });
|
||||||
|
}}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Connect Farcaster (Manual)
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="space-y-3 w-full">
|
||||||
|
<Button onClick={() => connect({ connector: connectors[1] })} className="w-full">
|
||||||
|
Connect Coinbase Wallet
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => connect({ connector: connectors[2] })} className="w-full">
|
||||||
|
Connect MetaMask
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WalletTab() {
|
||||||
|
// --- State ---
|
||||||
|
const [evmContractTransactionHash, setEvmContractTransactionHash] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// --- Hooks ---
|
||||||
|
const { context } = useMiniApp();
|
||||||
|
const { address, isConnected } = useAccount();
|
||||||
|
const chainId = useChainId();
|
||||||
|
const solanaWallet = useSolanaWallet();
|
||||||
|
const { publicKey: solanaPublicKey } = solanaWallet;
|
||||||
|
|
||||||
|
// --- Wagmi Hooks ---
|
||||||
|
const {
|
||||||
|
sendTransaction,
|
||||||
|
error: evmTransactionError,
|
||||||
|
isError: isEvmTransactionError,
|
||||||
|
isPending: isEvmTransactionPending,
|
||||||
|
} = useSendTransaction();
|
||||||
|
|
||||||
|
const { isLoading: isEvmTransactionConfirming, isSuccess: isEvmTransactionConfirmed } =
|
||||||
|
useWaitForTransactionReceipt({
|
||||||
|
hash: evmContractTransactionHash as `0x${string}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
signTypedData,
|
||||||
|
error: evmSignTypedDataError,
|
||||||
|
isError: isEvmSignTypedDataError,
|
||||||
|
isPending: isEvmSignTypedDataPending,
|
||||||
|
} = useSignTypedData();
|
||||||
|
|
||||||
|
const { disconnect } = useDisconnect();
|
||||||
|
const { connect, connectors } = useConnect();
|
||||||
|
|
||||||
|
const {
|
||||||
|
switchChain,
|
||||||
|
error: chainSwitchError,
|
||||||
|
isError: isChainSwitchError,
|
||||||
|
isPending: isChainSwitchPending,
|
||||||
|
} = useSwitchChain();
|
||||||
|
|
||||||
|
// --- Effects ---
|
||||||
|
/**
|
||||||
|
* Auto-connect when Farcaster context is available.
|
||||||
|
*
|
||||||
|
* This effect detects when the app is running in a Farcaster client
|
||||||
|
* and automatically attempts to connect using the Farcaster Frame connector.
|
||||||
|
* It includes comprehensive logging for debugging connection issues.
|
||||||
|
*/
|
||||||
|
useEffect(() => {
|
||||||
|
// Check if we're in a Farcaster client environment
|
||||||
|
const isInFarcasterClient = typeof window !== 'undefined' &&
|
||||||
|
(window.location.href.includes('warpcast.com') ||
|
||||||
|
window.location.href.includes('farcaster') ||
|
||||||
|
window.ethereum?.isFarcaster ||
|
||||||
|
context?.client);
|
||||||
|
|
||||||
|
if (context?.user?.fid && !isConnected && connectors.length > 0 && isInFarcasterClient) {
|
||||||
|
console.log("Attempting auto-connection with Farcaster context...");
|
||||||
|
console.log("- User FID:", context.user.fid);
|
||||||
|
console.log("- Available connectors:", connectors.map((c, i) => `${i}: ${c.name}`));
|
||||||
|
console.log("- Using connector:", connectors[0].name);
|
||||||
|
console.log("- In Farcaster client:", isInFarcasterClient);
|
||||||
|
|
||||||
|
// Use the first connector (farcasterFrame) for auto-connection
|
||||||
|
try {
|
||||||
|
connect({ connector: connectors[0] });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Auto-connection failed:", error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log("Auto-connection conditions not met:");
|
||||||
|
console.log("- Has context:", !!context?.user?.fid);
|
||||||
|
console.log("- Is connected:", isConnected);
|
||||||
|
console.log("- Has connectors:", connectors.length > 0);
|
||||||
|
console.log("- In Farcaster client:", isInFarcasterClient);
|
||||||
|
}
|
||||||
|
}, [context?.user?.fid, isConnected, connectors, connect, context?.client]);
|
||||||
|
|
||||||
|
// --- Computed Values ---
|
||||||
|
/**
|
||||||
|
* Determines the next chain to switch to based on the current chain.
|
||||||
|
* Cycles through: Base → Optimism → Degen → Mainnet → Unichain → Base
|
||||||
|
*/
|
||||||
|
const nextChain = useMemo(() => {
|
||||||
|
if (chainId === base.id) {
|
||||||
|
return optimism;
|
||||||
|
} else if (chainId === optimism.id) {
|
||||||
|
return degen;
|
||||||
|
} else if (chainId === degen.id) {
|
||||||
|
return mainnet;
|
||||||
|
} else if (chainId === mainnet.id) {
|
||||||
|
return unichain;
|
||||||
|
} else {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
}, [chainId]);
|
||||||
|
|
||||||
|
// --- Handlers ---
|
||||||
|
/**
|
||||||
|
* Handles switching to the next chain in the rotation.
|
||||||
|
* Uses the switchChain function from wagmi to change the active chain.
|
||||||
|
*/
|
||||||
|
const handleSwitchChain = useCallback(() => {
|
||||||
|
switchChain({ chainId: nextChain.id });
|
||||||
|
}, [switchChain, nextChain.id]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends a transaction to call the yoink() function on the Yoink contract.
|
||||||
|
*
|
||||||
|
* This function sends a transaction to a specific contract address with
|
||||||
|
* the encoded function call data for the yoink() function.
|
||||||
|
*/
|
||||||
|
const sendEvmContractTransaction = useCallback(() => {
|
||||||
|
sendTransaction(
|
||||||
|
{
|
||||||
|
// call yoink() on Yoink contract
|
||||||
|
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
|
||||||
|
data: "0x9846cd9efc000023c0",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: (hash) => {
|
||||||
|
setEvmContractTransactionHash(hash);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}, [sendTransaction]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs typed data using EIP-712 standard.
|
||||||
|
*
|
||||||
|
* This function creates a typed data structure with the app name, version,
|
||||||
|
* and chain ID, then requests the user to sign it.
|
||||||
|
*/
|
||||||
|
const signTyped = useCallback(() => {
|
||||||
|
signTypedData({
|
||||||
|
domain: {
|
||||||
|
name: APP_NAME,
|
||||||
|
version: "1",
|
||||||
|
chainId,
|
||||||
|
},
|
||||||
|
types: {
|
||||||
|
Message: [{ name: "content", type: "string" }],
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
content: `Hello from ${APP_NAME}!`,
|
||||||
|
},
|
||||||
|
primaryType: "Message",
|
||||||
|
});
|
||||||
|
}, [chainId, signTypedData]);
|
||||||
|
|
||||||
|
// --- Early Return ---
|
||||||
|
if (!USE_WALLET) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
|
||||||
|
{/* Wallet Information Display */}
|
||||||
|
<WalletStatus address={address} chainId={chainId} />
|
||||||
|
|
||||||
|
{/* Connection Controls */}
|
||||||
|
<ConnectionControls
|
||||||
|
isConnected={isConnected}
|
||||||
|
context={context}
|
||||||
|
connect={connect}
|
||||||
|
connectors={connectors}
|
||||||
|
disconnect={disconnect}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* EVM Wallet Components */}
|
||||||
|
<SignEvmMessage />
|
||||||
|
|
||||||
|
{isConnected && (
|
||||||
|
<>
|
||||||
|
<SendEth />
|
||||||
|
<Button
|
||||||
|
onClick={sendEvmContractTransaction}
|
||||||
|
disabled={!isConnected || isEvmTransactionPending}
|
||||||
|
isLoading={isEvmTransactionPending}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Send Transaction (contract)
|
||||||
|
</Button>
|
||||||
|
{isEvmTransactionError && renderError(evmTransactionError)}
|
||||||
|
{evmContractTransactionHash && (
|
||||||
|
<div className="text-xs w-full">
|
||||||
|
<div>Hash: {truncateAddress(evmContractTransactionHash)}</div>
|
||||||
|
<div>
|
||||||
|
Status:{" "}
|
||||||
|
{isEvmTransactionConfirming
|
||||||
|
? "Confirming..."
|
||||||
|
: isEvmTransactionConfirmed
|
||||||
|
? "Confirmed!"
|
||||||
|
: "Pending"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
onClick={signTyped}
|
||||||
|
disabled={!isConnected || isEvmSignTypedDataPending}
|
||||||
|
isLoading={isEvmSignTypedDataPending}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Sign Typed Data
|
||||||
|
</Button>
|
||||||
|
{isEvmSignTypedDataError && renderError(evmSignTypedDataError)}
|
||||||
|
<Button
|
||||||
|
onClick={handleSwitchChain}
|
||||||
|
disabled={isChainSwitchPending}
|
||||||
|
isLoading={isChainSwitchPending}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Switch to {nextChain.name}
|
||||||
|
</Button>
|
||||||
|
{isChainSwitchError && renderError(chainSwitchError)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Solana Wallet Components */}
|
||||||
|
{solanaPublicKey && (
|
||||||
|
<>
|
||||||
|
<SignSolanaMessage signMessage={solanaWallet.signMessage} />
|
||||||
|
<SendSolana />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
src/components/ui/tabs/index.ts
Normal file
4
src/components/ui/tabs/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export { HomeTab } from './HomeTab';
|
||||||
|
export { ActionsTab } from './ActionsTab';
|
||||||
|
export { ContextTab } from './ContextTab';
|
||||||
|
export { WalletTab } from './WalletTab';
|
||||||
102
src/components/ui/wallet/SendEth.tsx
Normal file
102
src/components/ui/wallet/SendEth.tsx
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useMemo } from "react";
|
||||||
|
import { useAccount, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
|
||||||
|
import { base } from "wagmi/chains";
|
||||||
|
import { Button } from "../Button";
|
||||||
|
import { truncateAddress } from "../../../lib/truncateAddress";
|
||||||
|
import { renderError } from "../../../lib/errorUtils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SendEth component handles sending ETH transactions to protocol guild addresses.
|
||||||
|
*
|
||||||
|
* This component provides a simple interface for users to send small amounts
|
||||||
|
* of ETH to protocol guild addresses. It automatically selects the appropriate
|
||||||
|
* recipient address based on the current chain and displays transaction status.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Chain-specific recipient addresses
|
||||||
|
* - Transaction status tracking
|
||||||
|
* - Error handling and display
|
||||||
|
* - Transaction hash display
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <SendEth />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function SendEth() {
|
||||||
|
// --- Hooks ---
|
||||||
|
const { isConnected, chainId } = useAccount();
|
||||||
|
const {
|
||||||
|
sendTransaction,
|
||||||
|
data: ethTransactionHash,
|
||||||
|
error: ethTransactionError,
|
||||||
|
isError: isEthTransactionError,
|
||||||
|
isPending: isEthTransactionPending,
|
||||||
|
} = useSendTransaction();
|
||||||
|
|
||||||
|
const { isLoading: isEthTransactionConfirming, isSuccess: isEthTransactionConfirmed } =
|
||||||
|
useWaitForTransactionReceipt({
|
||||||
|
hash: ethTransactionHash,
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Computed Values ---
|
||||||
|
/**
|
||||||
|
* Determines the recipient address based on the current chain.
|
||||||
|
*
|
||||||
|
* Uses different protocol guild addresses for different chains:
|
||||||
|
* - Base: 0x32e3C7fD24e175701A35c224f2238d18439C7dBC
|
||||||
|
* - Other chains: 0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830
|
||||||
|
*
|
||||||
|
* @returns string - The recipient address for the current chain
|
||||||
|
*/
|
||||||
|
const protocolGuildRecipientAddress = useMemo(() => {
|
||||||
|
// Protocol guild address
|
||||||
|
return chainId === base.id
|
||||||
|
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
|
||||||
|
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
|
||||||
|
}, [chainId]);
|
||||||
|
|
||||||
|
// --- Handlers ---
|
||||||
|
/**
|
||||||
|
* Handles sending the ETH transaction.
|
||||||
|
*
|
||||||
|
* This function sends a small amount of ETH (1 wei) to the protocol guild
|
||||||
|
* address for the current chain. The transaction is sent using the wagmi
|
||||||
|
* sendTransaction hook.
|
||||||
|
*/
|
||||||
|
const sendEthTransaction = useCallback(() => {
|
||||||
|
sendTransaction({
|
||||||
|
to: protocolGuildRecipientAddress,
|
||||||
|
value: 1n,
|
||||||
|
});
|
||||||
|
}, [protocolGuildRecipientAddress, sendTransaction]);
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
onClick={sendEthTransaction}
|
||||||
|
disabled={!isConnected || isEthTransactionPending}
|
||||||
|
isLoading={isEthTransactionPending}
|
||||||
|
>
|
||||||
|
Send Transaction (eth)
|
||||||
|
</Button>
|
||||||
|
{isEthTransactionError && renderError(ethTransactionError)}
|
||||||
|
{ethTransactionHash && (
|
||||||
|
<div className="mt-2 text-xs">
|
||||||
|
<div>Hash: {truncateAddress(ethTransactionHash)}</div>
|
||||||
|
<div>
|
||||||
|
Status:{" "}
|
||||||
|
{isEthTransactionConfirming
|
||||||
|
? "Confirming..."
|
||||||
|
: isEthTransactionConfirmed
|
||||||
|
? "Confirmed!"
|
||||||
|
: "Pending"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
111
src/components/ui/wallet/SendSolana.tsx
Normal file
111
src/components/ui/wallet/SendSolana.tsx
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useState } from "react";
|
||||||
|
import { useConnection as useSolanaConnection, useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
|
||||||
|
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
|
||||||
|
import { Button } from "../Button";
|
||||||
|
import { truncateAddress } from "../../../lib/truncateAddress";
|
||||||
|
import { renderError } from "../../../lib/errorUtils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SendSolana component handles sending SOL transactions on Solana.
|
||||||
|
*
|
||||||
|
* This component provides a simple interface for users to send SOL transactions
|
||||||
|
* using their connected Solana wallet. It includes transaction status tracking
|
||||||
|
* and error handling.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - SOL transaction sending
|
||||||
|
* - Transaction status tracking
|
||||||
|
* - Error handling and display
|
||||||
|
* - Loading state management
|
||||||
|
*
|
||||||
|
* Note: This component is a placeholder implementation. In a real application,
|
||||||
|
* you would integrate with a Solana wallet adapter and transaction library
|
||||||
|
* like @solana/web3.js to handle actual transactions.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <SendSolana />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function SendSolana() {
|
||||||
|
const [solanaTransactionState, setSolanaTransactionState] = useState<
|
||||||
|
| { status: 'none' }
|
||||||
|
| { status: 'pending' }
|
||||||
|
| { status: 'error'; error: Error }
|
||||||
|
| { status: 'success'; signature: string }
|
||||||
|
>({ status: 'none' });
|
||||||
|
|
||||||
|
const { connection: solanaConnection } = useSolanaConnection();
|
||||||
|
const { sendTransaction, publicKey } = useSolanaWallet();
|
||||||
|
|
||||||
|
// This should be replaced but including it from the original demo
|
||||||
|
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx#L718
|
||||||
|
const ashoatsPhantomSolanaWallet = 'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles sending the Solana transaction
|
||||||
|
*/
|
||||||
|
const sendSolanaTransaction = useCallback(async () => {
|
||||||
|
setSolanaTransactionState({ status: 'pending' });
|
||||||
|
try {
|
||||||
|
if (!publicKey) {
|
||||||
|
throw new Error('no Solana publicKey');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { blockhash } = await solanaConnection.getLatestBlockhash();
|
||||||
|
if (!blockhash) {
|
||||||
|
throw new Error('failed to fetch latest Solana blockhash');
|
||||||
|
}
|
||||||
|
|
||||||
|
const fromPubkeyStr = publicKey.toBase58();
|
||||||
|
const toPubkeyStr = ashoatsPhantomSolanaWallet;
|
||||||
|
const transaction = new Transaction();
|
||||||
|
transaction.add(
|
||||||
|
SystemProgram.transfer({
|
||||||
|
fromPubkey: new PublicKey(fromPubkeyStr),
|
||||||
|
toPubkey: new PublicKey(toPubkeyStr),
|
||||||
|
lamports: 0n,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
transaction.recentBlockhash = blockhash;
|
||||||
|
transaction.feePayer = new PublicKey(fromPubkeyStr);
|
||||||
|
|
||||||
|
const simulation = await solanaConnection.simulateTransaction(transaction);
|
||||||
|
if (simulation.value.err) {
|
||||||
|
// Gather logs and error details for debugging
|
||||||
|
const logs = simulation.value.logs?.join('\n') ?? 'No logs';
|
||||||
|
const errDetail = JSON.stringify(simulation.value.err);
|
||||||
|
throw new Error(`Simulation failed: ${errDetail}\nLogs:\n${logs}`);
|
||||||
|
}
|
||||||
|
const signature = await sendTransaction(transaction, solanaConnection);
|
||||||
|
setSolanaTransactionState({ status: 'success', signature });
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Error) {
|
||||||
|
setSolanaTransactionState({ status: 'error', error: e });
|
||||||
|
} else {
|
||||||
|
setSolanaTransactionState({ status: 'none' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [sendTransaction, publicKey, solanaConnection]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
onClick={sendSolanaTransaction}
|
||||||
|
disabled={solanaTransactionState.status === 'pending'}
|
||||||
|
isLoading={solanaTransactionState.status === 'pending'}
|
||||||
|
className="mb-4"
|
||||||
|
>
|
||||||
|
Send Transaction (sol)
|
||||||
|
</Button>
|
||||||
|
{solanaTransactionState.status === 'error' && renderError(solanaTransactionState.error)}
|
||||||
|
{solanaTransactionState.status === 'success' && (
|
||||||
|
<div className="mt-2 text-xs">
|
||||||
|
<div>Hash: {truncateAddress(solanaTransactionState.signature)}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
81
src/components/ui/wallet/SignEvmMessage.tsx
Normal file
81
src/components/ui/wallet/SignEvmMessage.tsx
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useAccount, useConnect, useSignMessage } from "wagmi";
|
||||||
|
import { base } from "wagmi/chains";
|
||||||
|
import { Button } from "../Button";
|
||||||
|
import { config } from "../../providers/WagmiProvider";
|
||||||
|
import { APP_NAME } from "../../../lib/constants";
|
||||||
|
import { renderError } from "../../../lib/errorUtils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SignEvmMessage component handles signing messages on EVM-compatible chains.
|
||||||
|
*
|
||||||
|
* This component provides a simple interface for users to sign messages using
|
||||||
|
* their connected EVM wallet. It automatically handles wallet connection if
|
||||||
|
* the user is not already connected, and displays the signature result.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Automatic wallet connection if needed
|
||||||
|
* - Message signing with app name
|
||||||
|
* - Error handling and display
|
||||||
|
* - Signature result display
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <SignEvmMessage />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function SignEvmMessage() {
|
||||||
|
// --- Hooks ---
|
||||||
|
const { isConnected } = useAccount();
|
||||||
|
const { connectAsync } = useConnect();
|
||||||
|
const {
|
||||||
|
signMessage,
|
||||||
|
data: evmMessageSignature,
|
||||||
|
error: evmSignMessageError,
|
||||||
|
isError: isEvmSignMessageError,
|
||||||
|
isPending: isEvmSignMessagePending,
|
||||||
|
} = useSignMessage();
|
||||||
|
|
||||||
|
// --- Handlers ---
|
||||||
|
/**
|
||||||
|
* Handles the message signing process.
|
||||||
|
*
|
||||||
|
* This function first ensures the user is connected to an EVM wallet,
|
||||||
|
* then requests them to sign a message containing the app name.
|
||||||
|
* If the user is not connected, it automatically connects using the
|
||||||
|
* Farcaster Frame connector.
|
||||||
|
*
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
|
const signEvmMessage = useCallback(async () => {
|
||||||
|
if (!isConnected) {
|
||||||
|
await connectAsync({
|
||||||
|
chainId: base.id,
|
||||||
|
connector: config.connectors[0],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
signMessage({ message: `Hello from ${APP_NAME}!` });
|
||||||
|
}, [connectAsync, isConnected, signMessage]);
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
onClick={signEvmMessage}
|
||||||
|
disabled={isEvmSignMessagePending}
|
||||||
|
isLoading={isEvmSignMessagePending}
|
||||||
|
>
|
||||||
|
Sign Message
|
||||||
|
</Button>
|
||||||
|
{isEvmSignMessageError && renderError(evmSignMessageError)}
|
||||||
|
{evmMessageSignature && (
|
||||||
|
<div className="mt-2 text-xs">
|
||||||
|
<div>Signature: {evmMessageSignature}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
130
src/components/ui/wallet/SignIn.tsx
Normal file
130
src/components/ui/wallet/SignIn.tsx
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useState } from 'react';
|
||||||
|
import { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
|
||||||
|
import { useQuickAuth } from '~/hooks/useQuickAuth';
|
||||||
|
import { Button } from '../Button';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SignIn component handles Farcaster authentication using QuickAuth.
|
||||||
|
*
|
||||||
|
* This component provides a complete authentication flow for Farcaster users:
|
||||||
|
* - Uses the built-in QuickAuth functionality from the Farcaster SDK
|
||||||
|
* - Manages authentication state in memory (no persistence)
|
||||||
|
* - Provides sign-out functionality
|
||||||
|
* - Displays authentication status and results
|
||||||
|
*
|
||||||
|
* The component integrates with the Farcaster Frame SDK and QuickAuth
|
||||||
|
* to provide seamless authentication within mini apps.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <SignIn />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
signingIn: boolean;
|
||||||
|
signingOut: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SignIn() {
|
||||||
|
// --- State ---
|
||||||
|
const [authState, setAuthState] = useState<AuthState>({
|
||||||
|
signingIn: false,
|
||||||
|
signingOut: false,
|
||||||
|
});
|
||||||
|
const [signInFailure, setSignInFailure] = useState<string>();
|
||||||
|
|
||||||
|
// --- Hooks ---
|
||||||
|
const { authenticatedUser, status, signIn, signOut } = useQuickAuth();
|
||||||
|
|
||||||
|
// --- Handlers ---
|
||||||
|
/**
|
||||||
|
* Handles the sign-in process using QuickAuth.
|
||||||
|
*
|
||||||
|
* This function uses the built-in QuickAuth functionality:
|
||||||
|
* 1. Gets a token from QuickAuth (handles SIWF flow automatically)
|
||||||
|
* 2. Validates the token with our server
|
||||||
|
* 3. Updates the session state
|
||||||
|
*
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
|
const handleSignIn = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setAuthState(prev => ({ ...prev, signingIn: true }));
|
||||||
|
setSignInFailure(undefined);
|
||||||
|
|
||||||
|
const success = await signIn();
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
setSignInFailure('Authentication failed');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof SignInCore.RejectedByUser) {
|
||||||
|
setSignInFailure('Rejected by user');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSignInFailure('Unknown error');
|
||||||
|
} finally {
|
||||||
|
setAuthState(prev => ({ ...prev, signingIn: false }));
|
||||||
|
}
|
||||||
|
}, [signIn]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the sign-out process.
|
||||||
|
*
|
||||||
|
* This function clears the QuickAuth session and resets the local state.
|
||||||
|
*
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
|
const handleSignOut = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setAuthState(prev => ({ ...prev, signingOut: true }));
|
||||||
|
await signOut();
|
||||||
|
} finally {
|
||||||
|
setAuthState(prev => ({ ...prev, signingOut: false }));
|
||||||
|
}
|
||||||
|
}, [signOut]);
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Authentication Buttons */}
|
||||||
|
{status !== 'authenticated' && (
|
||||||
|
<Button onClick={handleSignIn} disabled={authState.signingIn}>
|
||||||
|
Sign In with Farcaster
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{status === 'authenticated' && (
|
||||||
|
<Button onClick={handleSignOut} disabled={authState.signingOut}>
|
||||||
|
Sign out
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Session Information */}
|
||||||
|
{authenticatedUser && (
|
||||||
|
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-900 rounded-lg font-mono">
|
||||||
|
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">
|
||||||
|
Authenticated User
|
||||||
|
</div>
|
||||||
|
<div className="whitespace-pre text-gray-700 dark:text-gray-200">
|
||||||
|
{JSON.stringify(authenticatedUser, null, 2)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error Display */}
|
||||||
|
{signInFailure && !authState.signingIn && (
|
||||||
|
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-900 rounded-lg font-mono">
|
||||||
|
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">
|
||||||
|
Authentication Error
|
||||||
|
</div>
|
||||||
|
<div className="whitespace-pre text-gray-700 dark:text-gray-200">
|
||||||
|
{signInFailure}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
87
src/components/ui/wallet/SignSolanaMessage.tsx
Normal file
87
src/components/ui/wallet/SignSolanaMessage.tsx
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useState } from "react";
|
||||||
|
import { Button } from "../Button";
|
||||||
|
import { renderError } from "../../../lib/errorUtils";
|
||||||
|
|
||||||
|
interface SignSolanaMessageProps {
|
||||||
|
signMessage?: (message: Uint8Array) => Promise<Uint8Array>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SignSolanaMessage component handles signing messages on Solana.
|
||||||
|
*
|
||||||
|
* This component provides a simple interface for users to sign messages using
|
||||||
|
* their connected Solana wallet. It accepts a signMessage function as a prop
|
||||||
|
* and handles the complete signing flow including error handling.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Message signing with Solana wallet
|
||||||
|
* - Error handling and display
|
||||||
|
* - Signature result display (base64 encoded)
|
||||||
|
* - Loading state management
|
||||||
|
*
|
||||||
|
* @param props - Component props
|
||||||
|
* @param props.signMessage - Function to sign messages with Solana wallet
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* <SignSolanaMessage signMessage={solanaWallet.signMessage} />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function SignSolanaMessage({ signMessage }: SignSolanaMessageProps) {
|
||||||
|
// --- State ---
|
||||||
|
const [signature, setSignature] = useState<string | undefined>();
|
||||||
|
const [signError, setSignError] = useState<Error | undefined>();
|
||||||
|
const [signPending, setSignPending] = useState(false);
|
||||||
|
|
||||||
|
// --- Handlers ---
|
||||||
|
/**
|
||||||
|
* Handles the Solana message signing process.
|
||||||
|
*
|
||||||
|
* This function encodes a message as UTF-8 bytes, signs it using the provided
|
||||||
|
* signMessage function, and displays the base64-encoded signature result.
|
||||||
|
* It includes comprehensive error handling and loading state management.
|
||||||
|
*
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
|
const handleSignMessage = useCallback(async () => {
|
||||||
|
setSignPending(true);
|
||||||
|
try {
|
||||||
|
if (!signMessage) {
|
||||||
|
throw new Error('no Solana signMessage');
|
||||||
|
}
|
||||||
|
const input = new TextEncoder().encode("Hello from Solana!");
|
||||||
|
const signatureBytes = await signMessage(input);
|
||||||
|
const signature = btoa(String.fromCharCode(...signatureBytes));
|
||||||
|
setSignature(signature);
|
||||||
|
setSignError(undefined);
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Error) {
|
||||||
|
setSignError(e);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setSignPending(false);
|
||||||
|
}
|
||||||
|
}, [signMessage]);
|
||||||
|
|
||||||
|
// --- Render ---
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
onClick={handleSignMessage}
|
||||||
|
disabled={signPending}
|
||||||
|
isLoading={signPending}
|
||||||
|
className="mb-4"
|
||||||
|
>
|
||||||
|
Sign Message
|
||||||
|
</Button>
|
||||||
|
{signError && renderError(signError)}
|
||||||
|
{signature && (
|
||||||
|
<div className="mt-2 text-xs">
|
||||||
|
<div>Signature: {signature}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
5
src/components/ui/wallet/index.ts
Normal file
5
src/components/ui/wallet/index.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export { SignIn } from './SignIn';
|
||||||
|
export { SignEvmMessage } from './SignEvmMessage';
|
||||||
|
export { SendEth } from './SendEth';
|
||||||
|
export { SignSolanaMessage } from './SignSolanaMessage';
|
||||||
|
export { SendSolana } from './SendSolana';
|
||||||
18
src/hooks/useDetectClickOutside.ts
Normal file
18
src/hooks/useDetectClickOutside.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
export function useDetectClickOutside<T extends HTMLElement>(
|
||||||
|
ref: React.RefObject<T | null>,
|
||||||
|
callback: () => void
|
||||||
|
) {
|
||||||
|
useEffect(() => {
|
||||||
|
function handleClickOutside(event: MouseEvent) {
|
||||||
|
if (ref.current && !ref.current.contains(event.target as Node)) {
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
};
|
||||||
|
}, [ref, callback]);
|
||||||
|
}
|
||||||
38
src/hooks/useNeynarUser.ts
Normal file
38
src/hooks/useNeynarUser.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
export interface NeynarUser {
|
||||||
|
fid: number;
|
||||||
|
score: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useNeynarUser(context?: { user?: { fid?: number } }) {
|
||||||
|
const [user, setUser] = useState<NeynarUser | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!context?.user?.fid) {
|
||||||
|
setUser(null);
|
||||||
|
setError(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
fetch(`/api/users?fids=${context.user.fid}`)
|
||||||
|
.then((response) => {
|
||||||
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
if (data.users?.[0]) {
|
||||||
|
setUser(data.users[0]);
|
||||||
|
} else {
|
||||||
|
setUser(null);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((err) => setError(err.message))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [context?.user?.fid]);
|
||||||
|
|
||||||
|
return { user, loading, error };
|
||||||
|
}
|
||||||
207
src/hooks/useQuickAuth.ts
Normal file
207
src/hooks/useQuickAuth.ts
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { sdk } from '@farcaster/miniapp-sdk';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the current authenticated user state
|
||||||
|
*/
|
||||||
|
interface AuthenticatedUser {
|
||||||
|
/** The user's Farcaster ID (FID) */
|
||||||
|
fid: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Possible authentication states for QuickAuth
|
||||||
|
*/
|
||||||
|
type QuickAuthStatus = 'loading' | 'authenticated' | 'unauthenticated';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return type for the useQuickAuth hook
|
||||||
|
*/
|
||||||
|
interface UseQuickAuthReturn {
|
||||||
|
/** Current authenticated user data, or null if not authenticated */
|
||||||
|
authenticatedUser: AuthenticatedUser | null;
|
||||||
|
/** Current authentication status */
|
||||||
|
status: QuickAuthStatus;
|
||||||
|
/** Function to initiate the sign-in process using QuickAuth */
|
||||||
|
signIn: () => Promise<boolean>;
|
||||||
|
/** Function to sign out and clear the current authentication state */
|
||||||
|
signOut: () => Promise<void>;
|
||||||
|
/** Function to retrieve the current authentication token */
|
||||||
|
getToken: () => Promise<string | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom hook for managing QuickAuth authentication state
|
||||||
|
*
|
||||||
|
* This hook provides a complete authentication flow using Farcaster's QuickAuth:
|
||||||
|
* - Automatically checks for existing authentication on mount
|
||||||
|
* - Validates tokens with the server-side API
|
||||||
|
* - Manages authentication state in memory (no persistence)
|
||||||
|
* - Provides sign-in/sign-out functionality
|
||||||
|
*
|
||||||
|
* QuickAuth tokens are managed in memory only, so signing out of the Farcaster
|
||||||
|
* client will automatically sign the user out of this mini app as well.
|
||||||
|
*
|
||||||
|
* @returns {UseQuickAuthReturn} Object containing user state and authentication methods
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* const { authenticatedUser, status, signIn, signOut } = useQuickAuth();
|
||||||
|
*
|
||||||
|
* if (status === 'loading') return <div>Loading...</div>;
|
||||||
|
* if (status === 'unauthenticated') return <button onClick={signIn}>Sign In</button>;
|
||||||
|
*
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* <p>Welcome, FID: {authenticatedUser?.fid}</p>
|
||||||
|
* <button onClick={signOut}>Sign Out</button>
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function useQuickAuth(): UseQuickAuthReturn {
|
||||||
|
// Current authenticated user data
|
||||||
|
const [authenticatedUser, setAuthenticatedUser] =
|
||||||
|
useState<AuthenticatedUser | null>(null);
|
||||||
|
// Current authentication status
|
||||||
|
const [status, setStatus] = useState<QuickAuthStatus>('loading');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a QuickAuth token with the server-side API
|
||||||
|
*
|
||||||
|
* @param {string} authToken - The JWT token to validate
|
||||||
|
* @returns {Promise<AuthenticatedUser | null>} User data if valid, null otherwise
|
||||||
|
*/
|
||||||
|
const validateTokenWithServer = async (
|
||||||
|
authToken: string,
|
||||||
|
): Promise<AuthenticatedUser | null> => {
|
||||||
|
try {
|
||||||
|
const validationResponse = await fetch('/api/auth/validate', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ token: authToken }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (validationResponse.ok) {
|
||||||
|
const responseData = await validationResponse.json();
|
||||||
|
return responseData.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Token validation failed:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks for existing authentication token and validates it on component mount
|
||||||
|
* This runs automatically when the hook is first used
|
||||||
|
*/
|
||||||
|
useEffect(() => {
|
||||||
|
const checkExistingAuthentication = async () => {
|
||||||
|
try {
|
||||||
|
// Attempt to retrieve existing token from QuickAuth SDK
|
||||||
|
const { token } = await sdk.quickAuth.getToken();
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
// Validate the token with our server-side API
|
||||||
|
const validatedUserSession = await validateTokenWithServer(token);
|
||||||
|
|
||||||
|
if (validatedUserSession) {
|
||||||
|
// Token is valid, set authenticated state
|
||||||
|
setAuthenticatedUser(validatedUserSession);
|
||||||
|
setStatus('authenticated');
|
||||||
|
} else {
|
||||||
|
// Token is invalid or expired, clear authentication state
|
||||||
|
setStatus('unauthenticated');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No existing token found, user is not authenticated
|
||||||
|
setStatus('unauthenticated');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking existing authentication:', error);
|
||||||
|
setStatus('unauthenticated');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
checkExistingAuthentication();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiates the QuickAuth sign-in process
|
||||||
|
*
|
||||||
|
* Uses sdk.quickAuth.getToken() to get a QuickAuth session token.
|
||||||
|
* If there is already a session token in memory that hasn't expired,
|
||||||
|
* it will be immediately returned, otherwise a fresh one will be acquired.
|
||||||
|
*
|
||||||
|
* @returns {Promise<boolean>} True if sign-in was successful, false otherwise
|
||||||
|
*/
|
||||||
|
const signIn = useCallback(async (): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
setStatus('loading');
|
||||||
|
|
||||||
|
// Get QuickAuth session token
|
||||||
|
const { token } = await sdk.quickAuth.getToken();
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
// Validate the token with our server-side API
|
||||||
|
const validatedUserSession = await validateTokenWithServer(token);
|
||||||
|
|
||||||
|
if (validatedUserSession) {
|
||||||
|
// Authentication successful, update user state
|
||||||
|
setAuthenticatedUser(validatedUserSession);
|
||||||
|
setStatus('authenticated');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authentication failed, clear user state
|
||||||
|
setStatus('unauthenticated');
|
||||||
|
return false;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Sign-in process failed:', error);
|
||||||
|
setStatus('unauthenticated');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs out the current user and clears the authentication state
|
||||||
|
*
|
||||||
|
* Since QuickAuth tokens are managed in memory only, this simply clears
|
||||||
|
* the local user state. The actual token will be cleared when the
|
||||||
|
* user signs out of their Farcaster client.
|
||||||
|
*/
|
||||||
|
const signOut = useCallback(async (): Promise<void> => {
|
||||||
|
// Clear local user state
|
||||||
|
setAuthenticatedUser(null);
|
||||||
|
setStatus('unauthenticated');
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the current authentication token from QuickAuth
|
||||||
|
*
|
||||||
|
* @returns {Promise<string | null>} The current auth token, or null if not authenticated
|
||||||
|
*/
|
||||||
|
const getToken = useCallback(async (): Promise<string | null> => {
|
||||||
|
try {
|
||||||
|
const { token } = await sdk.quickAuth.getToken();
|
||||||
|
return token;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to retrieve authentication token:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
authenticatedUser,
|
||||||
|
status,
|
||||||
|
signIn,
|
||||||
|
signOut,
|
||||||
|
getToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,13 +1,140 @@
|
|||||||
export const APP_URL = process.env.NEXT_PUBLIC_URL!;
|
import { type AccountAssociation } from '@farcaster/miniapp-node';
|
||||||
export const APP_NAME = process.env.NEXT_PUBLIC_FRAME_NAME;
|
|
||||||
export const APP_DESCRIPTION = process.env.NEXT_PUBLIC_FRAME_DESCRIPTION;
|
/**
|
||||||
export const APP_PRIMARY_CATEGORY = process.env.NEXT_PUBLIC_FRAME_PRIMARY_CATEGORY;
|
* Application constants and configuration values.
|
||||||
export const APP_TAGS = process.env.NEXT_PUBLIC_FRAME_TAGS?.split(',');
|
*
|
||||||
export const APP_ICON_URL = `${APP_URL}/icon.png`;
|
* This file contains all the configuration constants used throughout the mini app.
|
||||||
export const APP_OG_IMAGE_URL = `${APP_URL}/api/opengraph-image`;
|
* These values are either sourced from environment variables or hardcoded and provide
|
||||||
export const APP_SPLASH_URL = `${APP_URL}/splash.png`;
|
* configuration for the app's appearance, behavior, and integration settings.
|
||||||
export const APP_SPLASH_BACKGROUND_COLOR = "#f7f7f7";
|
*
|
||||||
export const APP_BUTTON_TEXT = process.env.NEXT_PUBLIC_FRAME_BUTTON_TEXT;
|
* NOTE: This file is automatically updated by the init script.
|
||||||
export const APP_WEBHOOK_URL = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
* Manual changes may be overwritten during project initialization.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// --- App Configuration ---
|
||||||
|
/**
|
||||||
|
* The base URL of the application.
|
||||||
|
* Used for generating absolute URLs for assets and API endpoints.
|
||||||
|
*/
|
||||||
|
export const APP_URL: string = process.env.NEXT_PUBLIC_URL!;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the mini app as displayed to users.
|
||||||
|
* Used in titles, headers, and app store listings.
|
||||||
|
*/
|
||||||
|
export const APP_NAME: string = 'Starter Kit';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A brief description of the mini app's functionality.
|
||||||
|
* Used in app store listings and metadata.
|
||||||
|
*/
|
||||||
|
export const APP_DESCRIPTION: string = 'A demo of the Neynar Starter Kit';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The primary category for the mini app.
|
||||||
|
* Used for app store categorization and discovery.
|
||||||
|
*/
|
||||||
|
export const APP_PRIMARY_CATEGORY: string = 'developer-tools';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tags associated with the mini app.
|
||||||
|
* Used for search and discovery in app stores.
|
||||||
|
*/
|
||||||
|
export const APP_TAGS: string[] = ['neynar', 'starter-kit', 'demo'];
|
||||||
|
|
||||||
|
// --- Asset URLs ---
|
||||||
|
/**
|
||||||
|
* URL for the app's icon image.
|
||||||
|
* Used in app store listings and UI elements.
|
||||||
|
*/
|
||||||
|
export const APP_ICON_URL: string = `${APP_URL}/icon.png`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL for the app's Open Graph image.
|
||||||
|
* Used for social media sharing and previews.
|
||||||
|
*/
|
||||||
|
export const APP_OG_IMAGE_URL: string = `${APP_URL}/api/opengraph-image`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL for the app's splash screen image.
|
||||||
|
* Displayed during app loading.
|
||||||
|
*/
|
||||||
|
export const APP_SPLASH_URL: string = `${APP_URL}/splash.png`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Background color for the splash screen.
|
||||||
|
* Used as fallback when splash image is loading.
|
||||||
|
*/
|
||||||
|
export const APP_SPLASH_BACKGROUND_COLOR: string = "#f7f7f7";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Account association for the mini app.
|
||||||
|
* Used to associate the mini app with a Farcaster account.
|
||||||
|
* If not provided, the mini app will be unsigned and have limited capabilities.
|
||||||
|
*/
|
||||||
|
export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined = undefined;
|
||||||
|
|
||||||
|
// --- UI Configuration ---
|
||||||
|
/**
|
||||||
|
* Text displayed on the main action button.
|
||||||
|
* Used for the primary call-to-action in the mini app.
|
||||||
|
*/
|
||||||
|
export const APP_BUTTON_TEXT: string = 'Launch NSK';
|
||||||
|
|
||||||
|
// --- Integration Configuration ---
|
||||||
|
/**
|
||||||
|
* Webhook URL for receiving events from Neynar.
|
||||||
|
*
|
||||||
|
* If Neynar API key and client ID are configured, uses the official
|
||||||
|
* Neynar webhook endpoint. Otherwise, falls back to a local webhook
|
||||||
|
* endpoint for development and testing.
|
||||||
|
*/
|
||||||
|
export const APP_WEBHOOK_URL: string = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
|
||||||
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
|
||||||
: `${APP_URL}/api/webhook`;
|
: `${APP_URL}/api/webhook`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag to enable/disable wallet functionality.
|
||||||
|
*
|
||||||
|
* When true, wallet-related components and features are rendered.
|
||||||
|
* When false, wallet functionality is completely hidden from the UI.
|
||||||
|
* Useful for mini apps that don't require wallet integration.
|
||||||
|
*/
|
||||||
|
export const USE_WALLET: boolean = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag to enable/disable analytics tracking.
|
||||||
|
*
|
||||||
|
* When true, usage analytics are collected and sent to Neynar.
|
||||||
|
* When false, analytics collection is disabled.
|
||||||
|
* Useful for privacy-conscious users or development environments.
|
||||||
|
*/
|
||||||
|
export const ANALYTICS_ENABLED: boolean = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Required chains for the mini app.
|
||||||
|
*
|
||||||
|
* Contains an array of CAIP-2 identifiers for blockchains that the mini app requires.
|
||||||
|
* If the host does not support all chains listed here, it will not render the mini app.
|
||||||
|
* If empty or undefined, the mini app will be rendered regardless of chain support.
|
||||||
|
*
|
||||||
|
* Supported chains: eip155:1, eip155:137, eip155:42161, eip155:10, eip155:8453,
|
||||||
|
* solana:mainnet, solana:devnet
|
||||||
|
*/
|
||||||
|
export const APP_REQUIRED_CHAINS: string[] = [];
|
||||||
|
|
||||||
|
// PLEASE DO NOT UPDATE THIS
|
||||||
|
export const SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN = {
|
||||||
|
name: 'Farcaster SignedKeyRequestValidator',
|
||||||
|
version: '1',
|
||||||
|
chainId: 10,
|
||||||
|
verifyingContract:
|
||||||
|
'0x00000000fc700472606ed4fa22623acf62c60553' as `0x${string}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
// PLEASE DO NOT UPDATE THIS
|
||||||
|
export const SIGNED_KEY_REQUEST_TYPE = [
|
||||||
|
{ name: 'requestFid', type: 'uint256' },
|
||||||
|
{ name: 'key', type: 'bytes' },
|
||||||
|
{ name: 'deadline', type: 'uint256' },
|
||||||
|
];
|
||||||
|
|||||||
27
src/lib/devices.ts
Normal file
27
src/lib/devices.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
function isAndroid(): boolean {
|
||||||
|
return (
|
||||||
|
typeof navigator !== 'undefined' && /android/i.test(navigator.userAgent)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSmallIOS(): boolean {
|
||||||
|
return (
|
||||||
|
typeof navigator !== 'undefined' && /iPhone|iPod/.test(navigator.userAgent)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLargeIOS(): boolean {
|
||||||
|
return (
|
||||||
|
typeof navigator !== 'undefined' &&
|
||||||
|
(/iPad/.test(navigator.userAgent) ||
|
||||||
|
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isIOS(): boolean {
|
||||||
|
return isSmallIOS() || isLargeIOS();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMobile(): boolean {
|
||||||
|
return isAndroid() || isIOS();
|
||||||
|
}
|
||||||
66
src/lib/errorUtils.tsx
Normal file
66
src/lib/errorUtils.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { type ReactElement } from "react";
|
||||||
|
import { BaseError, UserRejectedRequestError } from "viem";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders an error object in a user-friendly format.
|
||||||
|
*
|
||||||
|
* This utility function takes an error object and renders it as a React element
|
||||||
|
* with consistent styling. It handles different types of errors including:
|
||||||
|
* - Error objects with message properties
|
||||||
|
* - Objects with error properties
|
||||||
|
* - String errors
|
||||||
|
* - Unknown error types
|
||||||
|
* - User rejection errors (special handling for wallet rejections)
|
||||||
|
*
|
||||||
|
* The rendered error is displayed in a gray container with monospace font
|
||||||
|
* for better readability of technical error details. User rejections are
|
||||||
|
* displayed with a simpler, more user-friendly message.
|
||||||
|
*
|
||||||
|
* @param error - The error object to render
|
||||||
|
* @returns ReactElement - A styled error display component, or null if no error
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* {isError && renderError(error)}
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function renderError(error: unknown): ReactElement | null {
|
||||||
|
// Handle null/undefined errors
|
||||||
|
if (!error) return null;
|
||||||
|
|
||||||
|
// Special handling for user rejections in wallet operations
|
||||||
|
if (error instanceof BaseError) {
|
||||||
|
const isUserRejection = error.walk(
|
||||||
|
(e) => e instanceof UserRejectedRequestError
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isUserRejection) {
|
||||||
|
return (
|
||||||
|
<div className="mt-2 p-2 text-xs bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||||
|
<div className="font-semibold text-red-500 mb-1">User Rejection</div>
|
||||||
|
<div>Transaction was rejected by user.</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract error message from different error types
|
||||||
|
let errorMessage: string;
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
errorMessage = error.message;
|
||||||
|
} else if (typeof error === 'object' && error !== null && 'error' in error) {
|
||||||
|
errorMessage = String(error.error);
|
||||||
|
} else if (typeof error === 'string') {
|
||||||
|
errorMessage = error;
|
||||||
|
} else {
|
||||||
|
errorMessage = 'Unknown error occurred';
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-800 rounded-lg font-mono">
|
||||||
|
<div className="font-semibold text-red-500 mb-1">Error</div>
|
||||||
|
<div className="whitespace-pre-wrap break-words">{errorMessage}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { FrameNotificationDetails } from "@farcaster/frame-sdk";
|
import { FrameNotificationDetails } from "@farcaster/miniapp-sdk";
|
||||||
import { Redis } from "@upstash/redis";
|
import { Redis } from "@upstash/redis";
|
||||||
import { APP_NAME } from "./constants";
|
import { APP_NAME } from "./constants";
|
||||||
|
|
||||||
|
|||||||
25
src/lib/localStorage.ts
Normal file
25
src/lib/localStorage.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
export function setItem<T>(key: string, value: T) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(key, JSON.stringify(value));
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to save item:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getItem<T>(key: string): T | null {
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem(key);
|
||||||
|
return stored ? JSON.parse(stored) : null;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to load item:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeItem(key: string) {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to remove item:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ export async function getNeynarUser(fid: number): Promise<User | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type SendFrameNotificationResult =
|
type SendMiniAppNotificationResult =
|
||||||
| {
|
| {
|
||||||
state: "error";
|
state: "error";
|
||||||
error: unknown;
|
error: unknown;
|
||||||
@@ -40,7 +40,7 @@ type SendFrameNotificationResult =
|
|||||||
| { state: "rate_limit" }
|
| { state: "rate_limit" }
|
||||||
| { state: "success" };
|
| { state: "success" };
|
||||||
|
|
||||||
export async function sendNeynarFrameNotification({
|
export async function sendNeynarMiniAppNotification({
|
||||||
fid,
|
fid,
|
||||||
title,
|
title,
|
||||||
body,
|
body,
|
||||||
@@ -48,7 +48,7 @@ export async function sendNeynarFrameNotification({
|
|||||||
fid: number;
|
fid: number;
|
||||||
title: string;
|
title: string;
|
||||||
body: string;
|
body: string;
|
||||||
}): Promise<SendFrameNotificationResult> {
|
}): Promise<SendMiniAppNotificationResult> {
|
||||||
try {
|
try {
|
||||||
const client = getNeynarClient();
|
const client = getNeynarClient();
|
||||||
const targetFids = [fid];
|
const targetFids = [fid];
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import {
|
import {
|
||||||
SendNotificationRequest,
|
SendNotificationRequest,
|
||||||
sendNotificationResponseSchema,
|
sendNotificationResponseSchema,
|
||||||
} from "@farcaster/frame-sdk";
|
} from "@farcaster/miniapp-sdk";
|
||||||
import { getUserNotificationDetails } from "~/lib/kv";
|
import { getUserNotificationDetails } from "~/lib/kv";
|
||||||
import { APP_URL } from "./constants";
|
import { APP_URL } from "./constants";
|
||||||
|
|
||||||
type SendFrameNotificationResult =
|
type SendMiniAppNotificationResult =
|
||||||
| {
|
| {
|
||||||
state: "error";
|
state: "error";
|
||||||
error: unknown;
|
error: unknown;
|
||||||
@@ -14,7 +14,7 @@ type SendFrameNotificationResult =
|
|||||||
| { state: "rate_limit" }
|
| { state: "rate_limit" }
|
||||||
| { state: "success" };
|
| { state: "success" };
|
||||||
|
|
||||||
export async function sendFrameNotification({
|
export async function sendMiniAppNotification({
|
||||||
fid,
|
fid,
|
||||||
title,
|
title,
|
||||||
body,
|
body,
|
||||||
@@ -22,7 +22,7 @@ export async function sendFrameNotification({
|
|||||||
fid: number;
|
fid: number;
|
||||||
title: string;
|
title: string;
|
||||||
body: string;
|
body: string;
|
||||||
}): Promise<SendFrameNotificationResult> {
|
}): Promise<SendMiniAppNotificationResult> {
|
||||||
const notificationDetails = await getUserNotificationDetails(fid);
|
const notificationDetails = await getUserNotificationDetails(fid);
|
||||||
if (!notificationDetails) {
|
if (!notificationDetails) {
|
||||||
return { state: "no_token" };
|
return { state: "no_token" };
|
||||||
|
|||||||
126
src/lib/utils.ts
126
src/lib/utils.ts
@@ -1,52 +1,32 @@
|
|||||||
import { type ClassValue, clsx } from 'clsx';
|
import { type ClassValue, clsx } from 'clsx';
|
||||||
import { twMerge } from 'tailwind-merge';
|
import { twMerge } from 'tailwind-merge';
|
||||||
import { mnemonicToAccount } from 'viem/accounts';
|
import { type Manifest } from '@farcaster/miniapp-node';
|
||||||
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 {
|
||||||
import { APP_SPLASH_URL } from './constants';
|
APP_BUTTON_TEXT,
|
||||||
|
APP_DESCRIPTION,
|
||||||
interface FrameMetadata {
|
APP_ICON_URL,
|
||||||
version: string;
|
APP_NAME,
|
||||||
name: string;
|
APP_OG_IMAGE_URL,
|
||||||
iconUrl: string;
|
APP_PRIMARY_CATEGORY,
|
||||||
homeUrl: string;
|
APP_SPLASH_BACKGROUND_COLOR,
|
||||||
imageUrl?: string;
|
APP_SPLASH_URL,
|
||||||
buttonTitle?: string;
|
APP_TAGS, APP_URL,
|
||||||
splashImageUrl?: string;
|
APP_WEBHOOK_URL,
|
||||||
splashBackgroundColor?: string;
|
APP_ACCOUNT_ASSOCIATION,
|
||||||
webhookUrl?: string;
|
APP_REQUIRED_CHAINS,
|
||||||
description?: string;
|
} from './constants';
|
||||||
primaryCategory?: string;
|
|
||||||
tags?: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
interface FrameManifest {
|
|
||||||
accountAssociation?: {
|
|
||||||
header: string;
|
|
||||||
payload: string;
|
|
||||||
signature: string;
|
|
||||||
};
|
|
||||||
frame: FrameMetadata;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs));
|
return twMerge(clsx(inputs));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getSecretEnvVars() {
|
export function getMiniAppEmbedMetadata(ogImageUrl?: string) {
|
||||||
const seedPhrase = process.env.SEED_PHRASE;
|
|
||||||
const fid = process.env.FID;
|
|
||||||
|
|
||||||
if (!seedPhrase || !fid) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return { seedPhrase, fid };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFrameEmbedMetadata(ogImageUrl?: string) {
|
|
||||||
return {
|
return {
|
||||||
version: "next",
|
version: "next",
|
||||||
imageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
|
imageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
|
||||||
|
ogTitle: APP_NAME,
|
||||||
|
ogDescription: APP_DESCRIPTION,
|
||||||
|
ogImageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
|
||||||
button: {
|
button: {
|
||||||
title: APP_BUTTON_TEXT,
|
title: APP_BUTTON_TEXT,
|
||||||
action: {
|
action: {
|
||||||
@@ -64,76 +44,26 @@ export function getFrameEmbedMetadata(ogImageUrl?: string) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getFarcasterMetadata(): Promise<FrameManifest> {
|
export async function getFarcasterDomainManifest(): Promise<Manifest> {
|
||||||
// First check for FRAME_METADATA in .env and use that if it exists
|
|
||||||
if (process.env.FRAME_METADATA) {
|
|
||||||
try {
|
|
||||||
const metadata = JSON.parse(process.env.FRAME_METADATA);
|
|
||||||
console.log('Using pre-signed frame metadata from environment');
|
|
||||||
return metadata;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to parse FRAME_METADATA from environment:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!APP_URL) {
|
|
||||||
throw new Error('NEXT_PUBLIC_URL not configured');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the domain from the URL (without https:// prefix)
|
|
||||||
const domain = new URL(APP_URL).hostname;
|
|
||||||
console.log('Using domain for manifest:', domain);
|
|
||||||
|
|
||||||
const secretEnvVars = getSecretEnvVars();
|
|
||||||
if (!secretEnvVars) {
|
|
||||||
console.warn('No seed phrase or FID found in environment variables -- generating unsigned metadata');
|
|
||||||
}
|
|
||||||
|
|
||||||
let accountAssociation;
|
|
||||||
if (secretEnvVars) {
|
|
||||||
// Generate account from seed phrase
|
|
||||||
const account = mnemonicToAccount(secretEnvVars.seedPhrase);
|
|
||||||
const custodyAddress = account.address;
|
|
||||||
|
|
||||||
const header = {
|
|
||||||
fid: parseInt(secretEnvVars.fid),
|
|
||||||
type: 'custody',
|
|
||||||
key: custodyAddress,
|
|
||||||
};
|
|
||||||
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString('base64');
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
domain
|
|
||||||
};
|
|
||||||
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
|
|
||||||
|
|
||||||
const signature = await account.signMessage({
|
|
||||||
message: `${encodedHeader}.${encodedPayload}`
|
|
||||||
});
|
|
||||||
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
|
|
||||||
|
|
||||||
accountAssociation = {
|
|
||||||
header: encodedHeader,
|
|
||||||
payload: encodedPayload,
|
|
||||||
signature: encodedSignature
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
accountAssociation,
|
accountAssociation: APP_ACCOUNT_ASSOCIATION,
|
||||||
frame: {
|
miniapp: {
|
||||||
version: "1",
|
version: "1",
|
||||||
name: APP_NAME ?? "Frames v2 Demo",
|
name: APP_NAME ?? "Neynar Starter Kit",
|
||||||
iconUrl: APP_ICON_URL,
|
iconUrl: APP_ICON_URL,
|
||||||
homeUrl: APP_URL,
|
homeUrl: APP_URL,
|
||||||
imageUrl: APP_OG_IMAGE_URL,
|
imageUrl: APP_OG_IMAGE_URL,
|
||||||
buttonTitle: APP_BUTTON_TEXT ?? "Launch Frame",
|
buttonTitle: APP_BUTTON_TEXT ?? "Launch Mini App",
|
||||||
splashImageUrl: APP_SPLASH_URL,
|
splashImageUrl: APP_SPLASH_URL,
|
||||||
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
|
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
|
||||||
webhookUrl: APP_WEBHOOK_URL,
|
webhookUrl: APP_WEBHOOK_URL,
|
||||||
description: APP_DESCRIPTION,
|
description: APP_DESCRIPTION,
|
||||||
primaryCategory: APP_PRIMARY_CATEGORY,
|
primaryCategory: APP_PRIMARY_CATEGORY,
|
||||||
tags: APP_TAGS,
|
tags: APP_TAGS,
|
||||||
|
requiredChains: APP_REQUIRED_CHAINS.length > 0 ? APP_REQUIRED_CHAINS : undefined,
|
||||||
|
ogTitle: APP_NAME,
|
||||||
|
ogDescription: APP_DESCRIPTION,
|
||||||
|
ogImageUrl: APP_OG_IMAGE_URL,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,19 @@
|
|||||||
import type { Config } from "tailwindcss";
|
import type { Config } from "tailwindcss";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tailwind CSS Configuration
|
||||||
|
*
|
||||||
|
* This configuration centralizes all theme colors for the mini app.
|
||||||
|
* To change the app's color scheme, simply update the 'primary' color value below.
|
||||||
|
*
|
||||||
|
* Example theme changes:
|
||||||
|
* - Blue theme: primary: "#3182CE"
|
||||||
|
* - Green theme: primary: "#059669"
|
||||||
|
* - Red theme: primary: "#DC2626"
|
||||||
|
* - Orange theme: primary: "#EA580C"
|
||||||
|
*/
|
||||||
export default {
|
export default {
|
||||||
darkMode: ["class"],
|
darkMode: "media",
|
||||||
content: [
|
content: [
|
||||||
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
|
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
|
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
@@ -10,6 +22,16 @@ export default {
|
|||||||
theme: {
|
theme: {
|
||||||
extend: {
|
extend: {
|
||||||
colors: {
|
colors: {
|
||||||
|
// Main theme color - change this to update the entire app's color scheme
|
||||||
|
primary: "#8b5cf6", // Main brand color
|
||||||
|
"primary-light": "#a78bfa", // For hover states
|
||||||
|
"primary-dark": "#7c3aed", // For active states
|
||||||
|
|
||||||
|
// Secondary colors for backgrounds and text
|
||||||
|
secondary: "#f8fafc", // Light backgrounds
|
||||||
|
"secondary-dark": "#334155", // Dark backgrounds
|
||||||
|
|
||||||
|
// Legacy CSS variables for backward compatibility
|
||||||
background: 'var(--background)',
|
background: 'var(--background)',
|
||||||
foreground: 'var(--foreground)'
|
foreground: 'var(--foreground)'
|
||||||
},
|
},
|
||||||
@@ -17,6 +39,20 @@ export default {
|
|||||||
lg: 'var(--radius)',
|
lg: 'var(--radius)',
|
||||||
md: 'calc(var(--radius) - 2px)',
|
md: 'calc(var(--radius) - 2px)',
|
||||||
sm: 'calc(var(--radius) - 4px)'
|
sm: 'calc(var(--radius) - 4px)'
|
||||||
|
},
|
||||||
|
// Custom spacing for consistent layout
|
||||||
|
spacing: {
|
||||||
|
'18': '4.5rem',
|
||||||
|
'88': '22rem',
|
||||||
|
},
|
||||||
|
// Custom container sizes
|
||||||
|
maxWidth: {
|
||||||
|
'xs': '20rem',
|
||||||
|
'sm': '24rem',
|
||||||
|
'md': '28rem',
|
||||||
|
'lg': '32rem',
|
||||||
|
'xl': '36rem',
|
||||||
|
'2xl': '42rem',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user