mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-11 11:52:35 -05:00
Compare commits
15 Commits
shreyas/ne
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
405abb24e1 | ||
|
|
c535332e30 | ||
|
|
c73b955cf9 | ||
|
|
76396153a1 | ||
|
|
36b4540e47 | ||
|
|
c5fef388b2 | ||
|
|
91658503ff | ||
|
|
760d2f28ec | ||
|
|
8d37c83ee8 | ||
|
|
2254f0d9a7 | ||
|
|
29fe3d82ca | ||
|
|
258eba7bfc | ||
|
|
3921ab4258 | ||
|
|
6a8fa017e5 | ||
|
|
c872bdd4ee |
@@ -8,7 +8,6 @@ let projectName = null;
|
|||||||
let autoAcceptDefaults = false;
|
let autoAcceptDefaults = false;
|
||||||
let apiKey = null;
|
let apiKey = null;
|
||||||
let noWallet = false;
|
let noWallet = false;
|
||||||
let noTunnel = false;
|
|
||||||
let sponsoredSigner = false;
|
let sponsoredSigner = false;
|
||||||
let seedPhrase = null;
|
let seedPhrase = null;
|
||||||
let returnUrl = null;
|
let returnUrl = null;
|
||||||
@@ -54,10 +53,6 @@ if (yIndex !== -1) {
|
|||||||
noWallet = true;
|
noWallet = true;
|
||||||
args.splice(i, 1); // Remove the flag
|
args.splice(i, 1); // Remove the flag
|
||||||
i--; // Adjust index since we removed 1 element
|
i--; // Adjust index since we removed 1 element
|
||||||
} else if (arg === '--no-tunnel') {
|
|
||||||
noTunnel = true;
|
|
||||||
args.splice(i, 1); // Remove the flag
|
|
||||||
i--; // Adjust index since we removed 1 element
|
|
||||||
} else if (arg === '--sponsored-signer') {
|
} else if (arg === '--sponsored-signer') {
|
||||||
sponsoredSigner = true;
|
sponsoredSigner = true;
|
||||||
args.splice(i, 1); // Remove the flag
|
args.splice(i, 1); // Remove the flag
|
||||||
@@ -99,7 +94,7 @@ if (autoAcceptDefaults && !projectName) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
init(projectName, autoAcceptDefaults, apiKey, noWallet, noTunnel, sponsoredSigner, seedPhrase, returnUrl).catch((err) => {
|
init(projectName, autoAcceptDefaults, apiKey, noWallet, sponsoredSigner, seedPhrase, returnUrl).catch((err) => {
|
||||||
console.error('Error:', err);
|
console.error('Error:', err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
33
bin/init.js
33
bin/init.js
@@ -68,7 +68,6 @@ export async function init(
|
|||||||
autoAcceptDefaults = false,
|
autoAcceptDefaults = false,
|
||||||
apiKey = null,
|
apiKey = null,
|
||||||
noWallet = false,
|
noWallet = false,
|
||||||
noTunnel = false,
|
|
||||||
sponsoredSigner = false,
|
sponsoredSigner = false,
|
||||||
seedPhrase = null,
|
seedPhrase = null,
|
||||||
returnUrl = null
|
returnUrl = null
|
||||||
@@ -251,7 +250,6 @@ export async function init(
|
|||||||
tags: [],
|
tags: [],
|
||||||
buttonText: 'Launch Mini App',
|
buttonText: 'Launch Mini App',
|
||||||
useWallet: !noWallet,
|
useWallet: !noWallet,
|
||||||
useTunnel: true,
|
|
||||||
enableAnalytics: true,
|
enableAnalytics: true,
|
||||||
seedPhrase: seedPhraseValue,
|
seedPhrase: seedPhraseValue,
|
||||||
useSponsoredSigner: useSponsoredSignerValue,
|
useSponsoredSigner: useSponsoredSignerValue,
|
||||||
@@ -361,24 +359,6 @@ export async function init(
|
|||||||
answers.useWallet = walletAnswer.useWallet;
|
answers.useWallet = walletAnswer.useWallet;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ask about localhost vs tunnel
|
|
||||||
if (noTunnel) {
|
|
||||||
answers.useTunnel = false;
|
|
||||||
} else {
|
|
||||||
const hostingAnswer = await inquirer.prompt([
|
|
||||||
{
|
|
||||||
type: 'confirm',
|
|
||||||
name: 'useTunnel',
|
|
||||||
message:
|
|
||||||
'Would you like to test on mobile and/or test the app with Warpcast developer tools?\n' +
|
|
||||||
`⚠️ ${yellow}${italic}Both mobile testing and the Warpcast debugger require setting up a tunnel to serve your app from localhost to the broader internet.\n${reset}` +
|
|
||||||
'Configure a tunnel for mobile testing and/or Warpcast developer tools?',
|
|
||||||
default: true,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
answers.useTunnel = hostingAnswer.useTunnel;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ask about Sign In With Neynar (SIWN) - requires seed phrase
|
// Ask about Sign In With Neynar (SIWN) - requires seed phrase
|
||||||
if (seedPhrase) {
|
if (seedPhrase) {
|
||||||
// If --seed-phrase flag is used, validate it
|
// If --seed-phrase flag is used, validate it
|
||||||
@@ -515,7 +495,8 @@ export async function init(
|
|||||||
'@farcaster/miniapp-wagmi-connector': '^1.0.0',
|
'@farcaster/miniapp-wagmi-connector': '^1.0.0',
|
||||||
'@farcaster/mini-app-solana': '>=0.0.17 <1.0.0',
|
'@farcaster/mini-app-solana': '>=0.0.17 <1.0.0',
|
||||||
'@farcaster/quick-auth': '>=0.0.7 <1.0.0',
|
'@farcaster/quick-auth': '>=0.0.7 <1.0.0',
|
||||||
'@neynar/react': '^1.2.13',
|
'@neynar/react': '^1.2.15',
|
||||||
|
'@pigment-css/react': '^0.0.30',
|
||||||
'@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',
|
||||||
@@ -525,7 +506,7 @@ export async function init(
|
|||||||
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',
|
next: '^15.5.7',
|
||||||
react: '^19',
|
react: '^19',
|
||||||
'react-dom': '^19',
|
'react-dom': '^19',
|
||||||
'tailwind-merge': '^2.6.0',
|
'tailwind-merge': '^2.6.0',
|
||||||
@@ -544,9 +525,8 @@ export async function init(
|
|||||||
"@vercel/sdk": "^1.9.0",
|
"@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.5.7",
|
||||||
"inquirer": "^10.2.2",
|
"inquirer": "^10.2.2",
|
||||||
"localtunnel": "^2.0.2",
|
|
||||||
"pino-pretty": "^13.0.0",
|
"pino-pretty": "^13.0.0",
|
||||||
"postcss": "^8",
|
"postcss": "^8",
|
||||||
"tailwindcss": "^3.4.1",
|
"tailwindcss": "^3.4.1",
|
||||||
@@ -584,9 +564,7 @@ export async function init(
|
|||||||
"supports-color": "10.2.0",
|
"supports-color": "10.2.0",
|
||||||
"strip-ansi": "7.1.0",
|
"strip-ansi": "7.1.0",
|
||||||
"chalk": "5.6.0",
|
"chalk": "5.6.0",
|
||||||
"ansi-styles": "6.2.1",
|
"ansi-styles": "6.2.1"
|
||||||
"axios@^1": ">=1 <2",
|
|
||||||
"axios@^0": ">=0 <1",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// npm v8.3+ overrides
|
// npm v8.3+ overrides
|
||||||
@@ -757,7 +735,6 @@ export async function init(
|
|||||||
`\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`
|
`\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
fs.appendFileSync(envPath, `\nUSE_TUNNEL="${answers.useTunnel}"`);
|
|
||||||
if (answers.useSponsoredSigner) {
|
if (answers.useSponsoredSigner) {
|
||||||
fs.appendFileSync(envPath, `\nSPONSOR_SIGNER="true"`);
|
fs.appendFileSync(envPath, `\nSPONSOR_SIGNER="true"`);
|
||||||
}
|
}
|
||||||
|
|||||||
34
package-lock.json
generated
34
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@neynar/create-farcaster-mini-app",
|
"name": "@neynar/create-farcaster-mini-app",
|
||||||
"version": "1.8.8",
|
"version": "1.8.15",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@neynar/create-farcaster-mini-app",
|
"name": "@neynar/create-farcaster-mini-app",
|
||||||
"version": "1.8.8",
|
"version": "1.8.15",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv": "^16.4.7",
|
"dotenv": "^16.4.7",
|
||||||
"inquirer": "^12.4.3",
|
"inquirer": "^12.4.3",
|
||||||
@@ -614,9 +614,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@openapitools/openapi-generator-cli": {
|
"node_modules/@openapitools/openapi-generator-cli": {
|
||||||
"version": "2.23.1",
|
"version": "2.25.0",
|
||||||
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.23.1.tgz",
|
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.25.0.tgz",
|
||||||
"integrity": "sha512-Kd5EZqzbcIXf6KRlpUrheHMzQNRHsJWzAGrm4ncWCNhnQl+Mh6TsFcqq+hIetgiFCknWBH6cZ2f37SxPxaon4w==",
|
"integrity": "sha512-u/3VAbF8c68AXBgm8nBAdDPLPW/KgrtHz28yemf92zNB0iDZFGdRUX2W80Lzf177g6ctYLz0GIPHCOU0LTJegQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
@@ -625,13 +625,13 @@
|
|||||||
"@nestjs/common": "11.1.6",
|
"@nestjs/common": "11.1.6",
|
||||||
"@nestjs/core": "11.1.6",
|
"@nestjs/core": "11.1.6",
|
||||||
"@nuxtjs/opencollective": "0.3.2",
|
"@nuxtjs/opencollective": "0.3.2",
|
||||||
"axios": "1.11.0",
|
"axios": "1.12.2",
|
||||||
"chalk": "4.1.2",
|
"chalk": "4.1.2",
|
||||||
"commander": "8.3.0",
|
"commander": "8.3.0",
|
||||||
"compare-versions": "4.1.4",
|
"compare-versions": "6.1.1",
|
||||||
"concurrently": "9.2.1",
|
"concurrently": "9.2.1",
|
||||||
"console.table": "0.10.0",
|
"console.table": "0.10.0",
|
||||||
"fs-extra": "11.3.1",
|
"fs-extra": "11.3.2",
|
||||||
"glob": "11.0.3",
|
"glob": "11.0.3",
|
||||||
"inquirer": "8.2.7",
|
"inquirer": "8.2.7",
|
||||||
"proxy-agent": "6.5.0",
|
"proxy-agent": "6.5.0",
|
||||||
@@ -896,9 +896,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/axios": {
|
"node_modules/axios": {
|
||||||
"version": "1.11.0",
|
"version": "1.12.2",
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz",
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||||
"integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==",
|
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -1153,9 +1153,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/compare-versions": {
|
"node_modules/compare-versions": {
|
||||||
"version": "4.1.4",
|
"version": "6.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-4.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz",
|
||||||
"integrity": "sha512-FemMreK9xNyL8gQevsdRMrvO4lFCkQP7qbuktn1q8ndcNk1+0mz7lgE7b/sNvbhVgY4w6tMN1FDp6aADjqw2rw==",
|
"integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
@@ -1589,9 +1589,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/fs-extra": {
|
"node_modules/fs-extra": {
|
||||||
"version": "11.3.1",
|
"version": "11.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz",
|
||||||
"integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==",
|
"integrity": "sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@neynar/create-farcaster-mini-app",
|
"name": "@neynar/create-farcaster-mini-app",
|
||||||
"version": "1.8.13",
|
"version": "1.9.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": false,
|
"private": false,
|
||||||
"access": "public",
|
"access": "public",
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import localtunnel from 'localtunnel';
|
|
||||||
import { spawn } from 'child_process';
|
import { spawn } from 'child_process';
|
||||||
import { createServer } from 'net';
|
import { createServer } from 'net';
|
||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
@@ -11,7 +10,6 @@ dotenv.config({ path: '.env.local' });
|
|||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const projectRoot = path.resolve(path.normalize(path.join(__dirname, '..')));
|
const projectRoot = path.resolve(path.normalize(path.join(__dirname, '..')));
|
||||||
|
|
||||||
let tunnel;
|
|
||||||
let nextDev;
|
let nextDev;
|
||||||
let isCleaningUp = false;
|
let isCleaningUp = false;
|
||||||
|
|
||||||
@@ -97,52 +95,20 @@ async function startDev() {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const useTunnel = process.env.USE_TUNNEL === 'true';
|
const miniAppUrl = `http://localhost:${port}`;
|
||||||
let miniAppUrl;
|
|
||||||
|
|
||||||
if (useTunnel) {
|
console.log(`
|
||||||
// Start localtunnel and get URL
|
💻 Your mini app is running at: ${miniAppUrl}
|
||||||
tunnel = await localtunnel({ port: port });
|
|
||||||
let ip;
|
|
||||||
try {
|
|
||||||
ip = await fetch('https://ipv4.icanhazip.com').then(res => res.text()).then(ip => ip.trim());
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error getting IP address:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
miniAppUrl = tunnel.url;
|
🌐 To test with the Farcaster preview tool:
|
||||||
console.log(`
|
|
||||||
🌐 Local tunnel URL: ${tunnel.url}
|
|
||||||
|
|
||||||
💻 To test on desktop:
|
1. Create a free ngrok account at https://ngrok.com/download/mac-os
|
||||||
1. Open the localtunnel URL in your browser: ${tunnel.url}
|
2. Download and install ngrok following the instructions
|
||||||
2. Enter your IP address in the password field${ip ? `: ${ip}` : ''} (note that this IP may be incorrect if you are using a VPN)
|
3. In a NEW terminal window, run: ngrok http ${port}
|
||||||
3. Click "Click to Submit" -- your mini app should now load in the browser
|
4. Copy the forwarding URL (e.g., https://xxxx-xx-xx-xx-xx.ngrok-free.app)
|
||||||
4. Navigate to the Warpcast Mini App Developer Tools: https://warpcast.com/~/developers
|
5. Navigate to: https://farcaster.xyz/~/developers/mini-apps/preview
|
||||||
5. Enter your mini app URL: ${tunnel.url}
|
6. Enter your ngrok URL and click "Preview" to test your mini app
|
||||||
6. Click "Preview" to launch your mini app within Warpcast (note that it may take ~10 seconds to load)
|
`)
|
||||||
|
|
||||||
|
|
||||||
❗️ You will not be able to load your mini app in Warpcast until ❗️
|
|
||||||
❗️ you submit your IP address in the localtunnel password field ❗️
|
|
||||||
|
|
||||||
|
|
||||||
📱 To test in Warpcast mobile app:
|
|
||||||
1. Open Warpcast on your phone
|
|
||||||
2. Go to Settings > Developer > Mini Apps
|
|
||||||
4. Enter this URL: ${tunnel.url}
|
|
||||||
5. Click "Preview" (note that it may take ~10 seconds to load)
|
|
||||||
`);
|
|
||||||
} else {
|
|
||||||
miniAppUrl = `http://localhost:${port}`;
|
|
||||||
console.log(`
|
|
||||||
💻 To test your mini app:
|
|
||||||
1. Open the Warpcast Mini App Developer Tools: https://warpcast.com/~/developers
|
|
||||||
2. Scroll down to the "Preview Mini App" tool
|
|
||||||
3. Enter this URL: ${miniAppUrl}
|
|
||||||
4. Click "Preview" to test your mini app (note that it may take ~5 seconds to load the first time)
|
|
||||||
`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start next dev with appropriate configuration
|
// 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'));
|
||||||
@@ -182,15 +148,6 @@ async function startDev() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tunnel) {
|
|
||||||
try {
|
|
||||||
await tunnel.close();
|
|
||||||
console.log('🌐 Tunnel closed');
|
|
||||||
} catch (e) {
|
|
||||||
console.log('Note: Tunnel already closed');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Force kill any remaining processes on the specified port
|
// Force kill any remaining processes on the specified port
|
||||||
await killProcessOnPort(port);
|
await killProcessOnPort(port);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -204,9 +161,6 @@ async function startDev() {
|
|||||||
process.on('SIGINT', cleanup);
|
process.on('SIGINT', cleanup);
|
||||||
process.on('SIGTERM', cleanup);
|
process.on('SIGTERM', cleanup);
|
||||||
process.on('exit', cleanup);
|
process.on('exit', cleanup);
|
||||||
if (tunnel) {
|
|
||||||
tunnel.on('close', cleanup);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
startDev().catch(console.error);
|
startDev().catch(console.error);
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This authentication system is designed to work both in a regular web browser and inside a miniapp.
|
||||||
|
* In other words, it supports authentication when the miniapp context is not present (web browser) as well as when the app is running inside the miniapp.
|
||||||
|
* If you only need authentication for a web application, follow the Webapp flow;
|
||||||
|
* if you only need authentication inside a miniapp, follow the Miniapp flow.
|
||||||
|
*/
|
||||||
|
|
||||||
import '@farcaster/auth-kit/styles.css';
|
import '@farcaster/auth-kit/styles.css';
|
||||||
import { useSignIn, UseSignInData } from '@farcaster/auth-kit';
|
import { useSignIn, UseSignInData } from '@farcaster/auth-kit';
|
||||||
import { useCallback, useEffect, useState, useRef } from 'react';
|
import { useCallback, useEffect, useState, useRef } from 'react';
|
||||||
@@ -10,8 +17,8 @@ import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
|
|||||||
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
||||||
import { useMiniApp } from '@neynar/react';
|
import { useMiniApp } from '@neynar/react';
|
||||||
import {
|
import {
|
||||||
signIn as backendSignIn,
|
signIn as miniappSignIn,
|
||||||
signOut as backendSignOut,
|
signOut as miniappSignOut,
|
||||||
useSession,
|
useSession,
|
||||||
} from 'next-auth/react';
|
} from 'next-auth/react';
|
||||||
import sdk, { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
|
import sdk, { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
|
||||||
@@ -116,7 +123,7 @@ export function NeynarAuthButton() {
|
|||||||
const signerFlowStartedRef = useRef(false);
|
const signerFlowStartedRef = useRef(false);
|
||||||
|
|
||||||
// Determine which flow to use based on context
|
// Determine which flow to use based on context
|
||||||
const useBackendFlow = context !== undefined;
|
const useMiniappFlow = context !== undefined;
|
||||||
|
|
||||||
// Helper function to create a signer
|
// Helper function to create a signer
|
||||||
const createSigner = useCallback(async () => {
|
const createSigner = useCallback(async () => {
|
||||||
@@ -137,16 +144,16 @@ export function NeynarAuthButton() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Helper function to update session with signers (backend flow only)
|
// Helper function to update session with signers (miniapp flow only)
|
||||||
const updateSessionWithSigners = useCallback(
|
const updateSessionWithSigners = useCallback(
|
||||||
async (
|
async (
|
||||||
signers: StoredAuthState['signers'],
|
signers: StoredAuthState['signers'],
|
||||||
user: StoredAuthState['user']
|
user: StoredAuthState['user']
|
||||||
) => {
|
) => {
|
||||||
if (!useBackendFlow) return;
|
if (!useMiniappFlow) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// For backend flow, we need to sign in again with the additional data
|
// For miniapp flow, we need to sign in again with the additional data
|
||||||
if (message && signature) {
|
if (message && signature) {
|
||||||
const signInData = {
|
const signInData = {
|
||||||
message,
|
message,
|
||||||
@@ -158,13 +165,13 @@ export function NeynarAuthButton() {
|
|||||||
user: JSON.stringify(user),
|
user: JSON.stringify(user),
|
||||||
};
|
};
|
||||||
|
|
||||||
await backendSignIn('neynar', signInData);
|
await miniappSignIn('neynar', signInData);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Error updating session with signers:', error);
|
console.error('❌ Error updating session with signers:', error);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[useBackendFlow, message, signature, nonce]
|
[useMiniappFlow, message, signature, nonce]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Helper function to fetch user data from Neynar API
|
// Helper function to fetch user data from Neynar API
|
||||||
@@ -231,7 +238,7 @@ export function NeynarAuthButton() {
|
|||||||
try {
|
try {
|
||||||
setSignersLoading(true);
|
setSignersLoading(true);
|
||||||
|
|
||||||
const endpoint = useBackendFlow
|
const endpoint = useMiniappFlow
|
||||||
? `/api/auth/session-signers?message=${encodeURIComponent(
|
? `/api/auth/session-signers?message=${encodeURIComponent(
|
||||||
message
|
message
|
||||||
)}&signature=${signature}`
|
)}&signature=${signature}`
|
||||||
@@ -243,8 +250,8 @@ export function NeynarAuthButton() {
|
|||||||
const signerData = await response.json();
|
const signerData = await response.json();
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
if (useBackendFlow) {
|
if (useMiniappFlow) {
|
||||||
// For backend flow, update session with signers
|
// For miniapp flow, update session with signers
|
||||||
if (signerData.signers && signerData.signers.length > 0) {
|
if (signerData.signers && signerData.signers.length > 0) {
|
||||||
const user =
|
const user =
|
||||||
signerData.user ||
|
signerData.user ||
|
||||||
@@ -253,7 +260,7 @@ export function NeynarAuthButton() {
|
|||||||
}
|
}
|
||||||
return signerData.signers;
|
return signerData.signers;
|
||||||
} else {
|
} else {
|
||||||
// For frontend flow, store in localStorage
|
// For webapp flow, store in localStorage
|
||||||
let user: StoredAuthState['user'] | null = null;
|
let user: StoredAuthState['user'] | null = null;
|
||||||
|
|
||||||
if (signerData.signers && signerData.signers.length > 0) {
|
if (signerData.signers && signerData.signers.length > 0) {
|
||||||
@@ -285,7 +292,7 @@ export function NeynarAuthButton() {
|
|||||||
setSignersLoading(false);
|
setSignersLoading(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[useBackendFlow, fetchUserData, updateSessionWithSigners]
|
[useMiniappFlow, fetchUserData, updateSessionWithSigners]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Helper function to poll signer status
|
// Helper function to poll signer status
|
||||||
@@ -384,21 +391,21 @@ export function NeynarAuthButton() {
|
|||||||
generateNonce();
|
generateNonce();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Load stored auth state on mount (only for frontend flow)
|
// Load stored auth state on mount (only for webapp flow)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!useBackendFlow) {
|
if (!useMiniappFlow) {
|
||||||
const stored = getItem<StoredAuthState>(STORAGE_KEY);
|
const stored = getItem<StoredAuthState>(STORAGE_KEY);
|
||||||
if (stored && stored.isAuthenticated) {
|
if (stored && stored.isAuthenticated) {
|
||||||
setStoredAuth(stored);
|
setStoredAuth(stored);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [useBackendFlow]);
|
}, [useMiniappFlow]);
|
||||||
|
|
||||||
// Success callback - this is critical!
|
// Success callback - this is critical!
|
||||||
const onSuccessCallback = useCallback(
|
const onSuccessCallback = useCallback(
|
||||||
async (res: UseSignInData) => {
|
async (res: UseSignInData) => {
|
||||||
if (!useBackendFlow) {
|
if (!useMiniappFlow) {
|
||||||
// Only handle localStorage for frontend flow
|
// Only handle localStorage for webapp flow
|
||||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||||
const user = res.fid ? await fetchUserData(res.fid) : null;
|
const user = res.fid ? await fetchUserData(res.fid) : null;
|
||||||
const authState: StoredAuthState = {
|
const authState: StoredAuthState = {
|
||||||
@@ -410,9 +417,9 @@ export function NeynarAuthButton() {
|
|||||||
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
||||||
setStoredAuth(authState);
|
setStoredAuth(authState);
|
||||||
}
|
}
|
||||||
// For backend flow, the session will be handled by NextAuth
|
// For miniapp flow, the session will be handled by NextAuth
|
||||||
},
|
},
|
||||||
[useBackendFlow, fetchUserData]
|
[useMiniappFlow, fetchUserData]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Error callback
|
// Error callback
|
||||||
@@ -427,8 +434,8 @@ export function NeynarAuthButton() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const {
|
const {
|
||||||
signIn: frontendSignIn,
|
signIn: webappSignIn,
|
||||||
signOut: frontendSignOut,
|
signOut: webappSignOut,
|
||||||
connect,
|
connect,
|
||||||
reconnect,
|
reconnect,
|
||||||
isSuccess,
|
isSuccess,
|
||||||
@@ -450,12 +457,12 @@ export function NeynarAuthButton() {
|
|||||||
}
|
}
|
||||||
}, [data?.message, data?.signature]);
|
}, [data?.message, data?.signature]);
|
||||||
|
|
||||||
// Connect for frontend flow when nonce is available
|
// Connect for webapp flow when nonce is available
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!useBackendFlow && nonce && !channelToken) {
|
if (!useMiniappFlow && nonce && !channelToken) {
|
||||||
connect();
|
connect();
|
||||||
}
|
}
|
||||||
}, [useBackendFlow, nonce, channelToken, connect]);
|
}, [useMiniappFlow, nonce, channelToken, connect]);
|
||||||
|
|
||||||
// Handle fetching signers after successful authentication
|
// Handle fetching signers after successful authentication
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -478,14 +485,14 @@ export function NeynarAuthButton() {
|
|||||||
// Step 1: Change to loading state
|
// Step 1: Change to loading state
|
||||||
setDialogStep('loading');
|
setDialogStep('loading');
|
||||||
|
|
||||||
// Show dialog if not using backend flow or in browser farcaster
|
// Show dialog if not using miniapp flow or in browser farcaster
|
||||||
if ((useBackendFlow && !isMobileContext) || !useBackendFlow)
|
if ((useMiniappFlow && !isMobileContext) || !useMiniappFlow)
|
||||||
setShowDialog(true);
|
setShowDialog(true);
|
||||||
|
|
||||||
// First, fetch existing signers
|
// First, fetch existing signers
|
||||||
const signers = await fetchAllSigners(message, signature);
|
const signers = await fetchAllSigners(message, signature);
|
||||||
|
|
||||||
if (useBackendFlow && isMobileContext) setSignersLoading(true);
|
if (useMiniappFlow && isMobileContext) setSignersLoading(true);
|
||||||
|
|
||||||
// Check if no signers exist or if we have empty signers
|
// Check if no signers exist or if we have empty signers
|
||||||
if (!signers || signers.length === 0) {
|
if (!signers || signers.length === 0) {
|
||||||
@@ -538,10 +545,10 @@ export function NeynarAuthButton() {
|
|||||||
}
|
}
|
||||||
}, [message, signature]); // Simplified dependencies
|
}, [message, signature]); // Simplified dependencies
|
||||||
|
|
||||||
// Backend flow using NextAuth
|
// Miniapp flow using NextAuth
|
||||||
const handleBackendSignIn = useCallback(async () => {
|
const handleMiniappSignIn = useCallback(async () => {
|
||||||
if (!nonce) {
|
if (!nonce) {
|
||||||
console.error('❌ No nonce available for backend sign-in');
|
console.error('❌ No nonce available for miniapp sign-in');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -556,7 +563,7 @@ export function NeynarAuthButton() {
|
|||||||
nonce: nonce,
|
nonce: nonce,
|
||||||
};
|
};
|
||||||
|
|
||||||
const nextAuthResult = await backendSignIn('neynar', signInData);
|
const nextAuthResult = await miniappSignIn('neynar', signInData);
|
||||||
if (nextAuthResult?.ok) {
|
if (nextAuthResult?.ok) {
|
||||||
setMessage(result.message);
|
setMessage(result.message);
|
||||||
setSignature(result.signature);
|
setSignature(result.signature);
|
||||||
@@ -567,34 +574,34 @@ export function NeynarAuthButton() {
|
|||||||
if (e instanceof SignInCore.RejectedByUser) {
|
if (e instanceof SignInCore.RejectedByUser) {
|
||||||
console.log('ℹ️ Sign-in rejected by user');
|
console.log('ℹ️ Sign-in rejected by user');
|
||||||
} else {
|
} else {
|
||||||
console.error('❌ Backend sign-in error:', e);
|
console.error('❌ Miniapp sign-in error:', e);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setSignersLoading(false);
|
setSignersLoading(false);
|
||||||
}
|
}
|
||||||
}, [nonce]);
|
}, [nonce]);
|
||||||
|
|
||||||
const handleFrontEndSignIn = useCallback(() => {
|
const handleWebappSignIn = useCallback(() => {
|
||||||
if (isError) {
|
if (isError) {
|
||||||
reconnect();
|
reconnect();
|
||||||
}
|
}
|
||||||
setDialogStep('signin');
|
setDialogStep('signin');
|
||||||
setShowDialog(true);
|
setShowDialog(true);
|
||||||
frontendSignIn();
|
webappSignIn();
|
||||||
}, [isError, reconnect, frontendSignIn]);
|
}, [isError, reconnect, webappSignIn]);
|
||||||
|
|
||||||
const handleSignOut = useCallback(async () => {
|
const handleSignOut = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
setSignersLoading(true);
|
setSignersLoading(true);
|
||||||
|
|
||||||
if (useBackendFlow) {
|
if (useMiniappFlow) {
|
||||||
// Only sign out from NextAuth if the current session is from Neynar provider
|
// Only sign out from NextAuth if the current session is from Neynar provider
|
||||||
if (session?.provider === 'neynar') {
|
if (session?.provider === 'neynar') {
|
||||||
await backendSignOut({ redirect: false });
|
await miniappSignOut({ redirect: false });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Frontend flow sign out
|
// Webapp flow sign out
|
||||||
frontendSignOut();
|
webappSignOut();
|
||||||
removeItem(STORAGE_KEY);
|
removeItem(STORAGE_KEY);
|
||||||
setStoredAuth(null);
|
setStoredAuth(null);
|
||||||
}
|
}
|
||||||
@@ -620,9 +627,9 @@ export function NeynarAuthButton() {
|
|||||||
} finally {
|
} finally {
|
||||||
setSignersLoading(false);
|
setSignersLoading(false);
|
||||||
}
|
}
|
||||||
}, [useBackendFlow, frontendSignOut, pollingInterval, session]);
|
}, [useMiniappFlow, webappSignOut, pollingInterval, session]);
|
||||||
|
|
||||||
const authenticated = useBackendFlow
|
const authenticated = useMiniappFlow
|
||||||
? !!(
|
? !!(
|
||||||
session?.provider === 'neynar' &&
|
session?.provider === 'neynar' &&
|
||||||
session?.user?.fid &&
|
session?.user?.fid &&
|
||||||
@@ -632,7 +639,7 @@ export function NeynarAuthButton() {
|
|||||||
: ((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
: ((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
||||||
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||||
|
|
||||||
const userData = useBackendFlow
|
const userData = useMiniappFlow
|
||||||
? {
|
? {
|
||||||
fid: session?.user?.fid,
|
fid: session?.user?.fid,
|
||||||
username: session?.user?.username || '',
|
username: session?.user?.username || '',
|
||||||
@@ -664,16 +671,16 @@ export function NeynarAuthButton() {
|
|||||||
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
onClick={useBackendFlow ? handleBackendSignIn : handleFrontEndSignIn}
|
onClick={useMiniappFlow ? handleMiniappSignIn : handleWebappSignIn}
|
||||||
disabled={!useBackendFlow && !url}
|
disabled={!useMiniappFlow && !url}
|
||||||
className={cn(
|
className={cn(
|
||||||
'btn btn-primary flex items-center gap-3',
|
'btn btn-primary flex items-center gap-3',
|
||||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||||
'transform transition-all duration-200 active:scale-[0.98]',
|
'transform transition-all duration-200 active:scale-[0.98]',
|
||||||
!url && !useBackendFlow && 'cursor-not-allowed'
|
!url && !useMiniappFlow && 'cursor-not-allowed'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{!useBackendFlow && !url ? (
|
{!useMiniappFlow && !url ? (
|
||||||
<>
|
<>
|
||||||
<div className="spinner-primary w-5 h-5" />
|
<div className="spinner-primary w-5 h-5" />
|
||||||
<span>Initializing...</span>
|
<span>Initializing...</span>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useCallback, useMemo } from "react";
|
import { useCallback, useMemo } from "react";
|
||||||
import { useAccount, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
|
import { useAccount, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
|
||||||
import { base } from "wagmi/chains";
|
import { arbitrum, base, mainnet, optimism, polygon, scroll, shape, zkSync, zora } from "wagmi/chains";
|
||||||
import { Button } from "../Button";
|
import { Button } from "../Button";
|
||||||
import { truncateAddress } from "../../../lib/truncateAddress";
|
import { truncateAddress } from "../../../lib/truncateAddress";
|
||||||
import { renderError } from "../../../lib/errorUtils";
|
import { renderError } from "../../../lib/errorUtils";
|
||||||
@@ -45,17 +45,36 @@ export function SendEth() {
|
|||||||
/**
|
/**
|
||||||
* Determines the recipient address based on the current chain.
|
* Determines the recipient address based on the current chain.
|
||||||
*
|
*
|
||||||
* Uses different protocol guild addresses for different chains:
|
* Uses different protocol guild addresses for different chains.
|
||||||
* - Base: 0x32e3C7fD24e175701A35c224f2238d18439C7dBC
|
* Defaults to Ethereum mainnet address if chain is not recognized.
|
||||||
* - Other chains: 0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830
|
* Addresses are taken from the protocol guilds documentation: https://protocol-guild.readthedocs.io/en/latest/
|
||||||
*
|
*
|
||||||
* @returns string - The recipient address for the current chain
|
* @returns string - The recipient address for the current chain
|
||||||
*/
|
*/
|
||||||
const protocolGuildRecipientAddress = useMemo(() => {
|
const protocolGuildRecipientAddress = useMemo(() => {
|
||||||
// Protocol guild address
|
switch (chainId) {
|
||||||
return chainId === base.id
|
case mainnet.id:
|
||||||
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
|
return "0x25941dC771bB64514Fc8abBce970307Fb9d477e9";
|
||||||
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
|
case arbitrum.id:
|
||||||
|
return "0x7F8DCFd764bA8e9B3BA577dC641D5c664B74c47b";
|
||||||
|
case base.id:
|
||||||
|
return "0xd16713A5D4Eb7E3aAc9D2228eB72f6f7328FADBD";
|
||||||
|
case optimism.id:
|
||||||
|
return "0x58ae0925077527a87D3B785aDecA018F9977Ec34";
|
||||||
|
case polygon.id:
|
||||||
|
return "0xccccEbdBdA2D68bABA6da99449b9CA41Dba9d4FF";
|
||||||
|
case scroll.id:
|
||||||
|
return "0xccccEbdBdA2D68bABA6da99449b9CA41Dba9d4FF";
|
||||||
|
case shape.id:
|
||||||
|
return "0x700fccD433E878F1AF9B64A433Cb2E09f5226CE8";
|
||||||
|
case zkSync.id:
|
||||||
|
return "0x9fb5F754f5222449F98b904a34494cB21AADFdf8";
|
||||||
|
case zora.id:
|
||||||
|
return "0x32e3C7fD24e175701A35c224f2238d18439C7dBC";
|
||||||
|
default:
|
||||||
|
// Default to Ethereum mainnet address
|
||||||
|
return "0x25941dC771bB64514Fc8abBce970307Fb9d477e9";
|
||||||
|
}
|
||||||
}, [chainId]);
|
}, [chainId]);
|
||||||
|
|
||||||
// --- Handlers ---
|
// --- Handlers ---
|
||||||
|
|||||||
Reference in New Issue
Block a user