mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-11 11:52:35 -05:00
Compare commits
37 Commits
veganbeef/
...
enforce-ne
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29fe3d82ca | ||
|
|
258eba7bfc | ||
|
|
3921ab4258 | ||
|
|
6a8fa017e5 | ||
|
|
c872bdd4ee | ||
|
|
c5ca1618ed | ||
|
|
db735d7568 | ||
|
|
ccd27f53b3 | ||
|
|
f14493e35b | ||
|
|
3af6ee0e71 | ||
|
|
54646a5035 | ||
|
|
be7d6b76ae | ||
|
|
09ef2e374e | ||
|
|
1cce5835d4 | ||
|
|
55c7c4b129 | ||
|
|
055dc4adbd | ||
|
|
98579bcea9 | ||
|
|
ea7ee37e71 | ||
|
|
feb9f3e161 | ||
|
|
8c5b8d8329 | ||
|
|
d0f8c75a2e | ||
|
|
e115520aa7 | ||
|
|
7dff4cd81a | ||
|
|
d1ec161f47 | ||
|
|
572ab9aa44 | ||
|
|
501bc84512 | ||
|
|
85b39a6397 | ||
|
|
61df6d6a64 | ||
|
|
9ee370628d | ||
|
|
882e4f166f | ||
|
|
e8fa822638 | ||
|
|
bade04b785 | ||
|
|
d9c74f163b | ||
|
|
2edd1bd2ae | ||
|
|
76ad200a22 | ||
|
|
86b79e7f3f | ||
|
|
aac3a739cd |
@@ -4,8 +4,3 @@ KV_REST_API_TOKEN=''
|
||||
KV_REST_API_URL=''
|
||||
NEXT_PUBLIC_URL='http://localhost:3000'
|
||||
NEXTAUTH_URL='http://localhost:3000'
|
||||
|
||||
NEXTAUTH_SECRET=""
|
||||
NEYNAR_API_KEY=""
|
||||
NEYNAR_CLIENT_ID=""
|
||||
USE_TUNNEL="false"
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
{
|
||||
"extends": ["next/core-web-vitals", "next/typescript"]
|
||||
"extends": ["next/core-web-vitals", "next/typescript"],
|
||||
"rules": {
|
||||
// Disable img warnings since you're using them intentionally in specific contexts
|
||||
"@next/next/no-img-element": "off",
|
||||
|
||||
// Allow @ts-ignore comments (though @ts-expect-error is preferred)
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
|
||||
// Allow explicit any types (sometimes necessary for dynamic imports and APIs)
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
|
||||
// Allow unused variables that start with underscore
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_",
|
||||
"caughtErrorsIgnorePattern": "^_"
|
||||
}
|
||||
],
|
||||
|
||||
// Make display name warnings instead of errors for dynamic components
|
||||
"react/display-name": "warn",
|
||||
|
||||
// Allow module assignment for dynamic imports
|
||||
"@next/next/no-assign-module-variable": "warn",
|
||||
|
||||
// Make exhaustive deps a warning instead of error for complex hooks
|
||||
"react-hooks/exhaustive-deps": "warn"
|
||||
}
|
||||
}
|
||||
|
||||
45
bin/index.js
45
bin/index.js
@@ -7,6 +7,11 @@ const args = process.argv.slice(2);
|
||||
let projectName = null;
|
||||
let autoAcceptDefaults = false;
|
||||
let apiKey = null;
|
||||
let noWallet = false;
|
||||
let noTunnel = false;
|
||||
let sponsoredSigner = false;
|
||||
let seedPhrase = null;
|
||||
let returnUrl = null;
|
||||
|
||||
// Check for -y flag
|
||||
const yIndex = args.indexOf('-y');
|
||||
@@ -45,6 +50,44 @@ if (yIndex !== -1) {
|
||||
console.error('Error: -k/--api-key requires an API key');
|
||||
process.exit(1);
|
||||
}
|
||||
} else if (arg === '--no-wallet') {
|
||||
noWallet = true;
|
||||
args.splice(i, 1); // Remove the flag
|
||||
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') {
|
||||
sponsoredSigner = true;
|
||||
args.splice(i, 1); // Remove the flag
|
||||
i--; // Adjust index since we removed 1 element
|
||||
} else if (arg === '--seed-phrase') {
|
||||
if (i + 1 < args.length) {
|
||||
seedPhrase = args[i + 1];
|
||||
if (seedPhrase.startsWith('-')) {
|
||||
console.error('Error: Seed phrase 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: --seed-phrase requires a seed phrase');
|
||||
process.exit(1);
|
||||
}
|
||||
} else if (arg === '-r' || arg === '--return-url') {
|
||||
if (i + 1 < args.length) {
|
||||
returnUrl = args[i + 1];
|
||||
if (returnUrl.startsWith('-')) {
|
||||
console.error('Error: Return URL 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: -r/--return-url requires a return URL');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +99,7 @@ if (autoAcceptDefaults && !projectName) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
init(projectName, autoAcceptDefaults, apiKey).catch((err) => {
|
||||
init(projectName, autoAcceptDefaults, apiKey, noWallet, noTunnel, sponsoredSigner, seedPhrase, returnUrl).catch((err) => {
|
||||
console.error('Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
318
bin/init.js
318
bin/init.js
@@ -63,7 +63,16 @@ async function queryNeynarApp(apiKey) {
|
||||
}
|
||||
|
||||
// Export the main CLI function for programmatic use
|
||||
export async function init(projectName = null, autoAcceptDefaults = false, apiKey = null) {
|
||||
export async function init(
|
||||
projectName = null,
|
||||
autoAcceptDefaults = false,
|
||||
apiKey = null,
|
||||
noWallet = false,
|
||||
noTunnel = false,
|
||||
sponsoredSigner = false,
|
||||
seedPhrase = null,
|
||||
returnUrl = null
|
||||
) {
|
||||
printWelcomeMessage();
|
||||
|
||||
// Ask about Neynar usage
|
||||
@@ -219,17 +228,34 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
|
||||
let answers;
|
||||
if (autoAcceptDefaults) {
|
||||
// Handle SIWN logic for autoAcceptDefaults
|
||||
let seedPhraseValue = null;
|
||||
let useSponsoredSignerValue = false;
|
||||
|
||||
// Only set seed phrase and sponsored signer if explicitly provided via flags
|
||||
if (seedPhrase) {
|
||||
// Validate the provided seed phrase
|
||||
if (!seedPhrase || seedPhrase.trim().split(' ').length < 12) {
|
||||
console.error('Error: Seed phrase must be at least 12 words');
|
||||
process.exit(1);
|
||||
}
|
||||
seedPhraseValue = seedPhrase;
|
||||
// If sponsoredSigner flag is provided, enable it; otherwise default to false
|
||||
useSponsoredSignerValue = sponsoredSigner;
|
||||
}
|
||||
|
||||
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,
|
||||
useWallet: !noWallet,
|
||||
useTunnel: true,
|
||||
enableAnalytics: true,
|
||||
seedPhrase: null,
|
||||
useSponsoredSigner: false,
|
||||
seedPhrase: seedPhraseValue,
|
||||
useSponsoredSigner: useSponsoredSignerValue,
|
||||
returnUrl: returnUrl,
|
||||
};
|
||||
} else {
|
||||
// If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options
|
||||
@@ -312,67 +338,102 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
// 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
|
||||
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 Neynar Sponsored Signers / SIWN
|
||||
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([
|
||||
// Ask about wallet and transaction tooling (skip if --no-wallet flag is used)
|
||||
if (noWallet) {
|
||||
answers.useWallet = false;
|
||||
} else {
|
||||
const walletAnswer = 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;
|
||||
},
|
||||
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
|
||||
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
|
||||
if (seedPhrase) {
|
||||
// If --seed-phrase flag is used, validate it
|
||||
if (!seedPhrase || seedPhrase.trim().split(' ').length < 12) {
|
||||
console.error('Error: Seed phrase must be at least 12 words');
|
||||
process.exit(1);
|
||||
}
|
||||
answers.seedPhrase = seedPhrase;
|
||||
// If --sponsored-signer flag is also provided, enable it
|
||||
answers.useSponsoredSigner = sponsoredSigner;
|
||||
} else {
|
||||
const siwnAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useSIWN',
|
||||
message:
|
||||
'Would you like to enable Sign In With Neynar (SIWN)? This allows your mini app to write data to Farcaster on behalf of users.\n' +
|
||||
'\n⚠️ A seed phrase is required for this option.\n',
|
||||
default: false,
|
||||
},
|
||||
]);
|
||||
|
||||
if (siwnAnswer.useSIWN) {
|
||||
const { seedPhrase } = await inquirer.prompt([
|
||||
{
|
||||
type: 'password',
|
||||
name: 'seedPhrase',
|
||||
message: 'Enter your Farcaster custody account seed phrase (required for 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 sponsor signer if seed phrase is provided
|
||||
const { sponsorSigner } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'sponsorSigner',
|
||||
message:
|
||||
'You have provided a seed phrase, which enables Sign In With Neynar (SIWN).\n' +
|
||||
'Do you want to sponsor the signer? (This will be used in Sign In With Neynar)\n' +
|
||||
'Note: If you choose to sponsor the signer, Neynar will sponsor it for you and you will be charged in CUs.\n' +
|
||||
'For more information, see https://docs.neynar.com/docs/two-ways-to-sponsor-a-farcaster-signer-via-neynar#sponsor-signers',
|
||||
default: false,
|
||||
},
|
||||
]);
|
||||
answers.useSponsoredSigner = sponsorSigner;
|
||||
} else {
|
||||
answers.useSponsoredSigner = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Ask about analytics opt-out
|
||||
@@ -454,7 +515,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
'@farcaster/miniapp-wagmi-connector': '^1.0.0',
|
||||
'@farcaster/mini-app-solana': '>=0.0.17 <1.0.0',
|
||||
'@farcaster/quick-auth': '>=0.0.7 <1.0.0',
|
||||
'@neynar/react': '^1.2.5',
|
||||
'@neynar/react': '^1.2.14',
|
||||
'@radix-ui/react-label': '^2.1.1',
|
||||
'@solana/wallet-adapter-react': '^0.15.38',
|
||||
'@tanstack/react-query': '^5.61.0',
|
||||
@@ -484,11 +545,13 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
"crypto": "^1.0.1",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "15.0.3",
|
||||
"inquirer": "^10.2.2",
|
||||
"localtunnel": "^2.0.2",
|
||||
"pino-pretty": "^13.0.0",
|
||||
"postcss": "^8",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsx": "^4.20.5",
|
||||
"typescript": "^5"
|
||||
};
|
||||
|
||||
@@ -497,12 +560,44 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
packageJson.dependencies['@neynar/nodejs-sdk'] = '^2.19.0';
|
||||
}
|
||||
|
||||
// Add auth-kit and next-auth dependencies if useSponsoredSigner is true
|
||||
if (answers.useSponsoredSigner) {
|
||||
// Add auth-kit and next-auth dependencies if SIWN is enabled (seed phrase is present)
|
||||
if (answers.seedPhrase) {
|
||||
packageJson.dependencies['@farcaster/auth-kit'] = '>=0.6.0 <1.0.0';
|
||||
packageJson.dependencies['next-auth'] = '^4.24.11';
|
||||
}
|
||||
|
||||
// Add security overrides for vulnerable packages (compatible with npm, Yarn, and pnpm)
|
||||
const securityOverrides = {
|
||||
"backslash": "0.2.0",
|
||||
"chalk-template": "1.1.0",
|
||||
"supports-hyperlinks": "4.1.0",
|
||||
"has-ansi": "6.0.0",
|
||||
"simple-swizzle": "0.2.2",
|
||||
"color-string": "2.1.0",
|
||||
"error-ex": "1.3.2",
|
||||
"color-name": "2.0.0",
|
||||
"is-arrayish": "0.3.2",
|
||||
"slice-ansi": "7.1.0",
|
||||
"color-convert": "3.1.0",
|
||||
"wrap-ansi": "9.0.0",
|
||||
"ansi-regex": "6.2.0",
|
||||
"supports-color": "10.2.0",
|
||||
"strip-ansi": "7.1.0",
|
||||
"chalk": "5.6.0",
|
||||
"ansi-styles": "6.2.1"
|
||||
};
|
||||
|
||||
// npm v8.3+ overrides
|
||||
packageJson.overrides = securityOverrides;
|
||||
|
||||
// Yarn (v1 and Berry) resolutions
|
||||
packageJson.resolutions = securityOverrides;
|
||||
|
||||
// pnpm overrides (namespaced)
|
||||
packageJson.pnpm = {
|
||||
overrides: securityOverrides
|
||||
};
|
||||
|
||||
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
|
||||
|
||||
// Handle .env file
|
||||
@@ -559,13 +654,14 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
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,
|
||||
RETURN_URL: /^export const RETURN_URL\s*:\s*string\s*\|\s*undefined\s*=\s*(undefined|['"`][^'"`]*['"`]);$/m,
|
||||
};
|
||||
|
||||
// Update APP_NAME
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.APP_NAME,
|
||||
`export const APP_NAME = '${escapeString(answers.projectName)}';`,
|
||||
`export const APP_NAME: string = '${escapeString(answers.projectName)}';`,
|
||||
'APP_NAME'
|
||||
);
|
||||
|
||||
@@ -573,7 +669,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.APP_DESCRIPTION,
|
||||
`export const APP_DESCRIPTION = '${escapeString(
|
||||
`export const APP_DESCRIPTION: string = '${escapeString(
|
||||
answers.description
|
||||
)}';`,
|
||||
'APP_DESCRIPTION'
|
||||
@@ -583,7 +679,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.APP_PRIMARY_CATEGORY,
|
||||
`export const APP_PRIMARY_CATEGORY = '${escapeString(
|
||||
`export const APP_PRIMARY_CATEGORY: string = '${escapeString(
|
||||
answers.primaryCategory || ''
|
||||
)}';`,
|
||||
'APP_PRIMARY_CATEGORY'
|
||||
@@ -597,7 +693,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.APP_TAGS,
|
||||
`export const APP_TAGS = ${tagsString};`,
|
||||
`export const APP_TAGS: string[] = ${tagsString};`,
|
||||
'APP_TAGS'
|
||||
);
|
||||
|
||||
@@ -605,7 +701,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.APP_BUTTON_TEXT,
|
||||
`export const APP_BUTTON_TEXT = '${escapeString(
|
||||
`export const APP_BUTTON_TEXT: string = '${escapeString(
|
||||
answers.buttonText || ''
|
||||
)}';`,
|
||||
'APP_BUTTON_TEXT'
|
||||
@@ -615,7 +711,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.USE_WALLET,
|
||||
`export const USE_WALLET = ${answers.useWallet};`,
|
||||
`export const USE_WALLET: boolean = ${answers.useWallet};`,
|
||||
'USE_WALLET'
|
||||
);
|
||||
|
||||
@@ -623,10 +719,19 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.ANALYTICS_ENABLED,
|
||||
`export const ANALYTICS_ENABLED = ${answers.enableAnalytics};`,
|
||||
`export const ANALYTICS_ENABLED: boolean = ${answers.enableAnalytics};`,
|
||||
'ANALYTICS_ENABLED'
|
||||
);
|
||||
|
||||
// Update RETURN_URL
|
||||
const returnUrlValue = answers.returnUrl ? `'${escapeString(answers.returnUrl)}'` : 'undefined';
|
||||
constantsContent = safeReplace(
|
||||
constantsContent,
|
||||
patterns.RETURN_URL,
|
||||
`export const RETURN_URL: string | undefined = ${returnUrlValue};`,
|
||||
'RETURN_URL'
|
||||
);
|
||||
|
||||
fs.writeFileSync(constantsPath, constantsContent);
|
||||
} else {
|
||||
console.log('⚠️ constants.ts not found, skipping constants update');
|
||||
@@ -642,16 +747,18 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
);
|
||||
}
|
||||
if (answers.seedPhrase) {
|
||||
console.log('✅ Writing SEED_PHRASE and NEXTAUTH_SECRET to .env.local');
|
||||
fs.appendFileSync(envPath, `\nSEED_PHRASE="${answers.seedPhrase}"`);
|
||||
}
|
||||
fs.appendFileSync(envPath, `\nUSE_TUNNEL="${answers.useTunnel}"`);
|
||||
if (answers.useSponsoredSigner) {
|
||||
fs.appendFileSync(envPath, `\nSPONSOR_SIGNER="true"`);
|
||||
// Add NextAuth secret for SIWN
|
||||
fs.appendFileSync(
|
||||
envPath,
|
||||
`\nNEXTAUTH_SECRET="${crypto.randomBytes(32).toString('hex')}"`
|
||||
);
|
||||
}
|
||||
fs.appendFileSync(envPath, `\nUSE_TUNNEL="${answers.useTunnel}"`);
|
||||
if (answers.useSponsoredSigner) {
|
||||
fs.appendFileSync(envPath, `\nSPONSOR_SIGNER="true"`);
|
||||
}
|
||||
|
||||
fs.unlinkSync(envExamplePath);
|
||||
} else {
|
||||
@@ -695,9 +802,12 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
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)...');
|
||||
// Handle SIWN-related files based on whether seed phrase is provided
|
||||
if (!answers.seedPhrase) {
|
||||
// Remove SIWN-related files when SIWN is not enabled (no seed phrase)
|
||||
console.log('\nRemoving SIWN-related files (SIWN not enabled)...');
|
||||
|
||||
// Remove NeynarAuthButton directory
|
||||
const neynarAuthButtonPath = path.join(projectPath, 'src', 'components', 'ui', 'NeynarAuthButton');
|
||||
if (fs.existsSync(neynarAuthButtonPath)) {
|
||||
fs.rmSync(neynarAuthButtonPath, { recursive: true, force: true });
|
||||
@@ -719,6 +829,58 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
|
||||
if (fs.existsSync(authFilePath)) {
|
||||
fs.rmSync(authFilePath, { force: true });
|
||||
}
|
||||
|
||||
// Remove SIWN-specific files
|
||||
const actionsTabNeynarAuthPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.NeynarAuth.tsx');
|
||||
if (fs.existsSync(actionsTabNeynarAuthPath)) {
|
||||
fs.rmSync(actionsTabNeynarAuthPath, { force: true });
|
||||
}
|
||||
|
||||
const layoutNeynarAuthPath = path.join(projectPath, 'src', 'app', 'layout.NeynarAuth.tsx');
|
||||
if (fs.existsSync(layoutNeynarAuthPath)) {
|
||||
fs.rmSync(layoutNeynarAuthPath, { force: true });
|
||||
}
|
||||
|
||||
const providersNeynarAuthPath = path.join(projectPath, 'src', 'app', 'providers.NeynarAuth.tsx');
|
||||
if (fs.existsSync(providersNeynarAuthPath)) {
|
||||
fs.rmSync(providersNeynarAuthPath, { force: true });
|
||||
}
|
||||
} else {
|
||||
// Move SIWN-specific files to replace the regular versions when SIWN is enabled
|
||||
console.log('\nMoving SIWN-specific files to replace regular versions (SIWN enabled)...');
|
||||
|
||||
// Move ActionsTab.NeynarAuth.tsx to ActionsTab.tsx
|
||||
const actionsTabNeynarAuthPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.NeynarAuth.tsx');
|
||||
const actionsTabPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.tsx');
|
||||
if (fs.existsSync(actionsTabNeynarAuthPath)) {
|
||||
if (fs.existsSync(actionsTabPath)) {
|
||||
fs.rmSync(actionsTabPath, { force: true }); // Delete original
|
||||
}
|
||||
fs.renameSync(actionsTabNeynarAuthPath, actionsTabPath);
|
||||
console.log('✅ Moved ActionsTab.NeynarAuth.tsx to ActionsTab.tsx');
|
||||
}
|
||||
|
||||
// Move layout.NeynarAuth.tsx to layout.tsx
|
||||
const layoutNeynarAuthPath = path.join(projectPath, 'src', 'app', 'layout.NeynarAuth.tsx');
|
||||
const layoutPath = path.join(projectPath, 'src', 'app', 'layout.tsx');
|
||||
if (fs.existsSync(layoutNeynarAuthPath)) {
|
||||
if (fs.existsSync(layoutPath)) {
|
||||
fs.rmSync(layoutPath, { force: true }); // Delete original
|
||||
}
|
||||
fs.renameSync(layoutNeynarAuthPath, layoutPath);
|
||||
console.log('✅ Moved layout.NeynarAuth.tsx to layout.tsx');
|
||||
}
|
||||
|
||||
// Move providers.NeynarAuth.tsx to providers.tsx
|
||||
const providersNeynarAuthPath = path.join(projectPath, 'src', 'app', 'providers.NeynarAuth.tsx');
|
||||
const providersPath = path.join(projectPath, 'src', 'app', 'providers.tsx');
|
||||
if (fs.existsSync(providersNeynarAuthPath)) {
|
||||
if (fs.existsSync(providersPath)) {
|
||||
fs.rmSync(providersPath, { force: true }); // Delete original
|
||||
}
|
||||
fs.renameSync(providersNeynarAuthPath, providersPath);
|
||||
console.log('✅ Moved providers.NeynarAuth.tsx to providers.tsx');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize git repository
|
||||
|
||||
1125
package-lock.json
generated
1125
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@neynar/create-farcaster-mini-app",
|
||||
"version": "1.7.6",
|
||||
"version": "1.8.13",
|
||||
"type": "module",
|
||||
"private": false,
|
||||
"access": "public",
|
||||
@@ -35,7 +35,7 @@
|
||||
"build:raw": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"deploy:vercel": "ts-node scripts/deploy.ts",
|
||||
"deploy:vercel": "tsx scripts/deploy.ts",
|
||||
"deploy:raw": "vercel --prod",
|
||||
"cleanup": "node scripts/cleanup.js"
|
||||
},
|
||||
@@ -51,5 +51,17 @@
|
||||
"@neynar/nodejs-sdk": "^2.19.0",
|
||||
"@types/node": "^22.13.10",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"overrides": {
|
||||
"chalk": "5.3.0",
|
||||
"strip-ansi": "6.0.1",
|
||||
"wrap-ansi": "8.1.0",
|
||||
"ansi-styles": "6.2.3",
|
||||
"color-convert": "2.0.1",
|
||||
"color-name": "1.1.4",
|
||||
"is-core-module": "2.13.1",
|
||||
"error-ex": "1.3.2",
|
||||
"simple-swizzle": "0.2.2",
|
||||
"has-ansi": "5.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import inquirer from 'inquirer';
|
||||
import dotenv from 'dotenv';
|
||||
import crypto from 'crypto';
|
||||
import { Vercel } from '@vercel/sdk';
|
||||
import { APP_NAME, APP_BUTTON_TEXT } from '../src/lib/constants';
|
||||
import { APP_NAME, APP_BUTTON_TEXT } from '../src/lib/constants.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const projectRoot = path.join(__dirname, '..');
|
||||
@@ -115,85 +115,147 @@ async function checkRequiredEnvVars(): Promise<void> {
|
||||
`${newLine}${varConfig.name}="${value.trim()}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Ask about sponsor signer if SEED_PHRASE is provided
|
||||
if (!process.env.SPONSOR_SIGNER) {
|
||||
const { sponsorSigner } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'sponsorSigner',
|
||||
message:
|
||||
'Do you want to sponsor the signer? (This will be used in Sign In With Neynar)\n' +
|
||||
'Note: If you choose to sponsor the signer, Neynar will sponsor it for you and you will be charged in CUs.\n' +
|
||||
'For more information, see https://docs.neynar.com/docs/two-ways-to-sponsor-a-farcaster-signer-via-neynar#sponsor-signers',
|
||||
default: false,
|
||||
},
|
||||
]);
|
||||
|
||||
process.env.SPONSOR_SIGNER = sponsorSigner.toString();
|
||||
|
||||
if (process.env.SEED_PHRASE) {
|
||||
fs.appendFileSync(
|
||||
'.env.local',
|
||||
`\nSPONSOR_SIGNER="${sponsorSigner}"`,
|
||||
);
|
||||
console.log('✅ Sponsor signer preference stored in .env.local');
|
||||
}
|
||||
}
|
||||
|
||||
// Ask about required chains
|
||||
const { useRequiredChains } = await inquirer.prompt([
|
||||
// Ask about SIWN if SEED_PHRASE is provided (moved outside the loop)
|
||||
if (process.env.SEED_PHRASE && !process.env.SPONSOR_SIGNER) {
|
||||
const { sponsorSigner } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useRequiredChains',
|
||||
name: 'sponsorSigner',
|
||||
message:
|
||||
'Does your mini app require support for specific blockchains?\n' +
|
||||
'If yes, the host will only render your mini app if it supports all the chains you specify.\n' +
|
||||
'If no, the mini app will be rendered regardless of chain support.',
|
||||
'You have provided a seed phrase, which enables Sign In With Neynar (SIWN).\n' +
|
||||
'Do you want to sponsor the signer? (This will be used in Sign In With Neynar)\n' +
|
||||
'Note: If you choose to sponsor the signer, Neynar will sponsor it for you and you will be charged in CUs.\n' +
|
||||
'For more information, see https://docs.neynar.com/docs/two-ways-to-sponsor-a-farcaster-signer-via-neynar#sponsor-signers',
|
||||
default: false,
|
||||
},
|
||||
]);
|
||||
|
||||
let requiredChains: string[] = [];
|
||||
if (useRequiredChains) {
|
||||
const { selectedChains } = await inquirer.prompt([
|
||||
{
|
||||
type: 'checkbox',
|
||||
name: 'selectedChains',
|
||||
message: 'Select the required chains (CAIP-2 identifiers):',
|
||||
choices: [
|
||||
{ name: 'Ethereum Mainnet (eip155:1)', value: 'eip155:1' },
|
||||
{ name: 'Polygon (eip155:137)', value: 'eip155:137' },
|
||||
{ name: 'Arbitrum One (eip155:42161)', value: 'eip155:42161' },
|
||||
{ name: 'Optimism (eip155:10)', value: 'eip155:10' },
|
||||
{ name: 'Base (eip155:8453)', value: 'eip155:8453' },
|
||||
{ name: 'Solana (solana:mainnet)', value: 'solana:mainnet' },
|
||||
{ name: 'Solana Devnet (solana:devnet)', value: 'solana:devnet' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
requiredChains = selectedChains;
|
||||
}
|
||||
process.env.SPONSOR_SIGNER = sponsorSigner.toString();
|
||||
|
||||
// Update constants.ts with required chains
|
||||
const constantsPath = path.join(projectRoot, 'src', 'lib', 'constants.ts');
|
||||
fs.appendFileSync(
|
||||
'.env.local',
|
||||
`\nSPONSOR_SIGNER="${sponsorSigner}"`,
|
||||
);
|
||||
console.log('✅ Sponsor signer preference stored in .env.local');
|
||||
}
|
||||
|
||||
// Ask about required chains (moved outside the loop)
|
||||
const { useRequiredChains } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'useRequiredChains',
|
||||
message:
|
||||
'Does your mini app require support for specific blockchains?\n' +
|
||||
'If yes, the host will only render your mini app if it supports all the chains you specify.\n' +
|
||||
'If no, the mini app will be rendered regardless of chain support.',
|
||||
default: false,
|
||||
},
|
||||
]);
|
||||
|
||||
let requiredChains: string[] = [];
|
||||
if (useRequiredChains) {
|
||||
const { selectedChains } = await inquirer.prompt([
|
||||
{
|
||||
type: 'checkbox',
|
||||
name: 'selectedChains',
|
||||
message: 'Select the required chains (CAIP-2 identifiers):',
|
||||
choices: [
|
||||
{ name: 'Ethereum Mainnet (eip155:1)', value: 'eip155:1' },
|
||||
{ name: 'Polygon (eip155:137)', value: 'eip155:137' },
|
||||
{ name: 'Arbitrum One (eip155:42161)', value: 'eip155:42161' },
|
||||
{ name: 'Optimism (eip155:10)', value: 'eip155:10' },
|
||||
{ name: 'Base (eip155:8453)', value: 'eip155:8453' },
|
||||
{ name: 'Solana (solana:mainnet)', value: 'solana:mainnet' },
|
||||
{ name: 'Solana Devnet (solana:devnet)', value: 'solana:devnet' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
requiredChains = selectedChains;
|
||||
}
|
||||
|
||||
// Update constants.ts with required chains
|
||||
const constantsPath = path.join(projectRoot, 'src', 'lib', 'constants.ts');
|
||||
if (fs.existsSync(constantsPath)) {
|
||||
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
|
||||
|
||||
// Replace the APP_REQUIRED_CHAINS line
|
||||
const requiredChainsString = JSON.stringify(requiredChains);
|
||||
constantsContent = constantsContent.replace(
|
||||
/^export const APP_REQUIRED_CHAINS\s*:\s*string\[\]\s*=\s*\[[^\]]*\];$/m,
|
||||
`export const APP_REQUIRED_CHAINS: string[] = ${requiredChainsString};`,
|
||||
);
|
||||
|
||||
fs.writeFileSync(constantsPath, constantsContent);
|
||||
console.log('✅ Required chains updated in constants.ts');
|
||||
}
|
||||
|
||||
// Ask for account association
|
||||
console.log(
|
||||
`\n⚠️ To complete your mini app manifest, you need to sign it using the Farcaster developer portal.`,
|
||||
);
|
||||
console.log(
|
||||
'1. Go to: https://farcaster.xyz/~/developers/mini-apps/manifest',
|
||||
);
|
||||
console.log(
|
||||
'2. Enter your app domain (you\'ll get this after deployment)',
|
||||
);
|
||||
console.log(
|
||||
'3. Click "Transfer Ownership" and follow the instructions to sign the manifest.',
|
||||
);
|
||||
console.log(
|
||||
'4. Copy the resulting accountAssociation JSON.',
|
||||
);
|
||||
console.log('5. Paste it below when prompted.');
|
||||
console.log(
|
||||
'\nNote: If you don\'t have the accountAssociation yet, you can press Ctrl+C to skip and add it later.',
|
||||
);
|
||||
|
||||
try {
|
||||
const { userAccountAssociation } = await inquirer.prompt([
|
||||
{
|
||||
type: 'editor',
|
||||
name: 'userAccountAssociation',
|
||||
message: 'Paste the accountAssociation JSON here (or press Ctrl+C to skip):',
|
||||
validate: (input: string) => {
|
||||
if (!input.trim()) {
|
||||
return 'You can press Ctrl+C to skip this step';
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(input);
|
||||
if (parsed.header && parsed.payload && parsed.signature) {
|
||||
return true;
|
||||
}
|
||||
return 'Invalid accountAssociation: must have header, payload, and signature';
|
||||
} catch (e) {
|
||||
return 'Invalid JSON';
|
||||
}
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const parsedAccountAssociation = JSON.parse(userAccountAssociation);
|
||||
|
||||
// Write APP_ACCOUNT_ASSOCIATION to constants.ts
|
||||
if (fs.existsSync(constantsPath)) {
|
||||
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
|
||||
|
||||
// Replace the APP_REQUIRED_CHAINS line
|
||||
const requiredChainsString = JSON.stringify(requiredChains);
|
||||
// Replace the APP_ACCOUNT_ASSOCIATION line
|
||||
const newAccountAssociation = `export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined = ${JSON.stringify(parsedAccountAssociation, null, 2)};`;
|
||||
constantsContent = constantsContent.replace(
|
||||
/^export const APP_REQUIRED_CHAINS\s*:\s*string\[\]\s*=\s*\[[^\]]*\];$/m,
|
||||
`export const APP_REQUIRED_CHAINS: string[] = ${requiredChainsString};`,
|
||||
/^export const APP_ACCOUNT_ASSOCIATION\s*:\s*AccountAssociation \| undefined\s*=\s*[^;]*;/m,
|
||||
newAccountAssociation,
|
||||
);
|
||||
|
||||
fs.writeFileSync(constantsPath, constantsContent);
|
||||
console.log('✅ Required chains updated in constants.ts');
|
||||
console.log('✅ APP_ACCOUNT_ASSOCIATION updated in constants.ts');
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('\nℹ️ Skipping account association for now. You can add it later by updating APP_ACCOUNT_ASSOCIATION in src/lib/constants.ts');
|
||||
}
|
||||
}
|
||||
|
||||
// Load SPONSOR_SIGNER from .env.local if SEED_PHRASE exists but SPONSOR_SIGNER doesn't
|
||||
// Load SPONSOR_SIGNER from .env.local if SEED_PHRASE exists (SIWN enabled) but SPONSOR_SIGNER doesn't
|
||||
if (
|
||||
process.env.SEED_PHRASE &&
|
||||
!process.env.SPONSOR_SIGNER &&
|
||||
@@ -732,8 +794,9 @@ async function deployToVercel(useGitHub = false): Promise<void> {
|
||||
SPONSOR_SIGNER: process.env.SPONSOR_SIGNER,
|
||||
}),
|
||||
|
||||
// Include NextAuth environment variables if SEED_PHRASE is present or SPONSOR_SIGNER is true
|
||||
...((process.env.SEED_PHRASE || process.env.SPONSOR_SIGNER === 'true') && {
|
||||
// Include NextAuth environment variables if SEED_PHRASE is present (SIWN enabled)
|
||||
...(process.env.SEED_PHRASE && {
|
||||
SEED_PHRASE: process.env.SEED_PHRASE,
|
||||
NEXTAUTH_SECRET: nextAuthSecret,
|
||||
AUTH_SECRET: nextAuthSecret,
|
||||
NEXTAUTH_URL: `https://${domain}`,
|
||||
@@ -834,8 +897,8 @@ async function deployToVercel(useGitHub = false): Promise<void> {
|
||||
NEXT_PUBLIC_URL: `https://${actualDomain}`,
|
||||
};
|
||||
|
||||
// Include NextAuth URL if SEED_PHRASE is present or SPONSOR_SIGNER is true
|
||||
if (process.env.SEED_PHRASE || process.env.SPONSOR_SIGNER === 'true') {
|
||||
// Include NextAuth URL if SEED_PHRASE is present (SIWN enabled)
|
||||
if (process.env.SEED_PHRASE) {
|
||||
updatedEnv.NEXTAUTH_URL = `https://${actualDomain}`;
|
||||
}
|
||||
|
||||
@@ -878,55 +941,17 @@ async function deployToVercel(useGitHub = false): Promise<void> {
|
||||
console.log(
|
||||
'\n📝 You can manage your project at https://vercel.com/dashboard',
|
||||
);
|
||||
|
||||
// Prompt user to sign manifest in browser and paste accountAssociation
|
||||
|
||||
// Remind user about account association if not already set
|
||||
console.log(
|
||||
`\n⚠️ To complete your mini app manifest, you must sign it using the Farcaster developer portal.`,
|
||||
`\n💡 Remember: If you haven't already signed your manifest, go to:`,
|
||||
);
|
||||
console.log(
|
||||
'1. Go to: https://farcaster.xyz/~/developers/mini-apps/manifest?domain=' +
|
||||
domain,
|
||||
` https://farcaster.xyz/~/developers/mini-apps/manifest?domain=${domain}`,
|
||||
);
|
||||
console.log(
|
||||
'2. Click "Transfer Ownership" and follow the instructions to sign the manifest.',
|
||||
' to complete the ownership transfer and update APP_ACCOUNT_ASSOCIATION in src/lib/constants.ts',
|
||||
);
|
||||
console.log(
|
||||
'3. Copy the resulting accountAssociation JSON from the browser.',
|
||||
);
|
||||
console.log('4. Paste it below when prompted.');
|
||||
|
||||
const { userAccountAssociation } = await inquirer.prompt([
|
||||
{
|
||||
type: 'editor',
|
||||
name: 'userAccountAssociation',
|
||||
message: 'Paste the accountAssociation JSON here:',
|
||||
validate: (input: string) => {
|
||||
try {
|
||||
const parsed = JSON.parse(input);
|
||||
if (parsed.header && parsed.payload && parsed.signature) {
|
||||
return true;
|
||||
}
|
||||
return 'Invalid accountAssociation: must have header, payload, and signature';
|
||||
} catch (e) {
|
||||
return 'Invalid JSON';
|
||||
}
|
||||
},
|
||||
},
|
||||
]);
|
||||
const parsedAccountAssociation = JSON.parse(userAccountAssociation);
|
||||
|
||||
// Write APP_ACCOUNT_ASSOCIATION to src/lib/constants.ts
|
||||
const constantsPath = path.join(projectRoot, 'src', 'lib', 'constants.ts');
|
||||
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
|
||||
|
||||
// Replace the APP_ACCOUNT_ASSOCIATION line using a robust, anchored, multiline regex
|
||||
const newAccountAssociation = `export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined = ${JSON.stringify(parsedAccountAssociation, null, 2)};`;
|
||||
constantsContent = constantsContent.replace(
|
||||
/^export const APP_ACCOUNT_ASSOCIATION\s*:\s*AccountAssociation \| undefined\s*=\s*[^;]*;/m,
|
||||
newAccountAssociation,
|
||||
);
|
||||
fs.writeFileSync(constantsPath, constantsContent);
|
||||
console.log('\n✅ APP_ACCOUNT_ASSOCIATION updated in src/lib/constants.ts');
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
console.error('\n❌ Deployment failed:', error.message);
|
||||
|
||||
@@ -7,6 +7,7 @@ export async function GET() {
|
||||
return NextResponse.json(config);
|
||||
} catch (error) {
|
||||
console.error('Error generating metadata:', error);
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ export async function POST(request: NextRequest) {
|
||||
// Only handle notifications if Neynar is not enabled
|
||||
// When Neynar is enabled, notifications are handled through their webhook
|
||||
switch (event.event) {
|
||||
case "frame_added":
|
||||
case "miniapp_added":
|
||||
if (event.notificationDetails) {
|
||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||
await sendMiniAppNotification({
|
||||
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
break;
|
||||
|
||||
case "frame_removed":
|
||||
case "miniapp_removed":
|
||||
await deleteUserNotificationDetails(fid);
|
||||
break;
|
||||
|
||||
|
||||
29
src/app/layout.NeynarAuth.tsx
Normal file
29
src/app/layout.NeynarAuth.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
import { getSession } from '~/auth';
|
||||
import '~/app/globals.css';
|
||||
import { Providers } from '~/app/providers';
|
||||
import { APP_NAME, APP_DESCRIPTION } from '~/lib/constants';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: APP_NAME,
|
||||
description: APP_DESCRIPTION,
|
||||
};
|
||||
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const session = await getSession();
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<Providers session={session}>
|
||||
{children}
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Metadata } from "next";
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
import "~/app/globals.css";
|
||||
import { Providers } from "~/app/providers";
|
||||
import { APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
|
||||
import '~/app/globals.css';
|
||||
import { Providers } from '~/app/providers';
|
||||
import { APP_NAME, APP_DESCRIPTION } from '~/lib/constants';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: APP_NAME,
|
||||
@@ -13,25 +13,13 @@ export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
// 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;
|
||||
|
||||
let session = null;
|
||||
if (sponsorSigner || hasSeedPhrase) {
|
||||
try {
|
||||
const { getSession } = await import("~/auth");
|
||||
session = await getSession();
|
||||
} catch (error) {
|
||||
console.warn('Failed to get session:', error);
|
||||
}
|
||||
}
|
||||
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<Providers session={session}>{children}</Providers>
|
||||
<Providers>
|
||||
{children}
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
44
src/app/providers.NeynarAuth.tsx
Normal file
44
src/app/providers.NeynarAuth.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
'use client';
|
||||
|
||||
import dynamic from 'next/dynamic';
|
||||
import type { Session } from 'next-auth';
|
||||
import { SessionProvider } from 'next-auth/react';
|
||||
import { AuthKitProvider } from '@farcaster/auth-kit';
|
||||
import { MiniAppProvider } from '@neynar/react';
|
||||
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
|
||||
import { ANALYTICS_ENABLED, RETURN_URL } from '~/lib/constants';
|
||||
|
||||
const WagmiProvider = dynamic(
|
||||
() => import('~/components/providers/WagmiProvider'),
|
||||
{
|
||||
ssr: false,
|
||||
}
|
||||
);
|
||||
|
||||
export function Providers({
|
||||
session,
|
||||
children,
|
||||
}: {
|
||||
session: Session | null;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const solanaEndpoint =
|
||||
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
|
||||
return (
|
||||
<SessionProvider session={session}>
|
||||
<WagmiProvider>
|
||||
<MiniAppProvider
|
||||
analyticsEnabled={ANALYTICS_ENABLED}
|
||||
backButtonEnabled={true}
|
||||
returnUrl={RETURN_URL}
|
||||
>
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
<AuthKitProvider config={{}}>
|
||||
{children}
|
||||
</AuthKitProvider>
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</MiniAppProvider>
|
||||
</WagmiProvider>
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import dynamic from 'next/dynamic';
|
||||
import type { Session } from 'next-auth';
|
||||
import { SessionProvider } from 'next-auth/react';
|
||||
import { MiniAppProvider } from '@neynar/react';
|
||||
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
|
||||
import { ANALYTICS_ENABLED } from '~/lib/constants';
|
||||
import { AuthKitProvider } from '@farcaster/auth-kit';
|
||||
import { ANALYTICS_ENABLED, RETURN_URL } from '~/lib/constants';
|
||||
|
||||
const WagmiProvider = dynamic(
|
||||
() => import('~/components/providers/WagmiProvider'),
|
||||
@@ -16,42 +13,21 @@ const WagmiProvider = dynamic(
|
||||
);
|
||||
|
||||
export function Providers({
|
||||
session,
|
||||
children,
|
||||
}: {
|
||||
session: Session | null;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const solanaEndpoint =
|
||||
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
|
||||
|
||||
// Only wrap with SessionProvider if session is provided
|
||||
if (session) {
|
||||
return (
|
||||
<SessionProvider session={session}>
|
||||
<WagmiProvider>
|
||||
<MiniAppProvider
|
||||
analyticsEnabled={ANALYTICS_ENABLED}
|
||||
backButtonEnabled={true}
|
||||
>
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</MiniAppProvider>
|
||||
</WagmiProvider>
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// Return without SessionProvider if no session
|
||||
return (
|
||||
<WagmiProvider>
|
||||
<MiniAppProvider
|
||||
analyticsEnabled={ANALYTICS_ENABLED}
|
||||
backButtonEnabled={true}
|
||||
returnUrl={RETURN_URL}
|
||||
>
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||
{children}
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</MiniAppProvider>
|
||||
</WagmiProvider>
|
||||
|
||||
97
src/auth.ts
97
src/auth.ts
@@ -217,74 +217,6 @@ function getDomainFromUrl(urlString: string | undefined): string {
|
||||
export const authOptions: AuthOptions = {
|
||||
// Configure one or more authentication providers
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
id: 'farcaster',
|
||||
name: 'Sign in with Farcaster',
|
||||
credentials: {
|
||||
message: {
|
||||
label: 'Message',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
signature: {
|
||||
label: 'Signature',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
nonce: {
|
||||
label: 'Nonce',
|
||||
type: 'text',
|
||||
placeholder: 'Custom nonce (optional)',
|
||||
},
|
||||
// In a production app with a server, these should be fetched from
|
||||
// your Farcaster data indexer rather than have them accepted as part
|
||||
// of credentials.
|
||||
// question: should these natively use the Neynar API?
|
||||
name: {
|
||||
label: 'Name',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
pfp: {
|
||||
label: 'Pfp',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
const nonce = req?.body?.csrfToken;
|
||||
|
||||
if (!nonce) {
|
||||
console.error('No nonce or CSRF token provided');
|
||||
return null;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
return {
|
||||
id: fid.toString(),
|
||||
name: credentials?.name || `User ${fid}`,
|
||||
image: credentials?.pfp || null,
|
||||
provider: 'farcaster',
|
||||
};
|
||||
},
|
||||
}),
|
||||
CredentialsProvider({
|
||||
id: 'neynar',
|
||||
name: 'Sign in with Neynar',
|
||||
@@ -333,10 +265,18 @@ export const authOptions: AuthOptions = {
|
||||
try {
|
||||
// Validate the signature using Farcaster's auth client (same as Farcaster provider)
|
||||
const appClient = createAppClient({
|
||||
// USE your own RPC URL or else you might get 401 error
|
||||
ethereum: viemConnector(),
|
||||
});
|
||||
|
||||
const domain = getDomainFromUrl(process.env.NEXTAUTH_URL);
|
||||
const baseUrl =
|
||||
process.env.VERCEL_ENV === 'production'
|
||||
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
|
||||
: process.env.VERCEL_URL
|
||||
? `https://${process.env.VERCEL_URL}`
|
||||
: process.env.NEXTAUTH_URL || `http://localhost:${process.env.PORT ?? 3000}`;
|
||||
|
||||
const domain = getDomainFromUrl(baseUrl);
|
||||
|
||||
const verifyResponse = await appClient.verifySignInMessage({
|
||||
message: credentials?.message as string,
|
||||
@@ -377,12 +317,7 @@ export const authOptions: AuthOptions = {
|
||||
// Set provider at the root level
|
||||
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') {
|
||||
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;
|
||||
@@ -404,26 +339,26 @@ export const authOptions: AuthOptions = {
|
||||
name: `next-auth.session-token`,
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
|
||||
path: '/',
|
||||
secure: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
},
|
||||
},
|
||||
callbackUrl: {
|
||||
name: `next-auth.callback-url`,
|
||||
options: {
|
||||
sameSite: 'none',
|
||||
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
|
||||
path: '/',
|
||||
secure: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
},
|
||||
},
|
||||
csrfToken: {
|
||||
name: `next-auth.csrf-token`,
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
|
||||
path: '/',
|
||||
secure: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
'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 { useSignIn, UseSignInData } from '@farcaster/auth-kit';
|
||||
import { useCallback, useEffect, useState, useRef } from 'react';
|
||||
@@ -10,11 +17,11 @@ 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,
|
||||
signIn as miniappSignIn,
|
||||
signOut as miniappSignOut,
|
||||
useSession,
|
||||
} from 'next-auth/react';
|
||||
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
|
||||
import sdk, { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
|
||||
|
||||
type User = {
|
||||
fid: number;
|
||||
@@ -116,7 +123,7 @@ export function NeynarAuthButton() {
|
||||
const signerFlowStartedRef = useRef(false);
|
||||
|
||||
// Determine which flow to use based on context
|
||||
const useBackendFlow = context !== undefined;
|
||||
const useMiniappFlow = context !== undefined;
|
||||
|
||||
// Helper function to create a signer
|
||||
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(
|
||||
async (
|
||||
signers: StoredAuthState['signers'],
|
||||
user: StoredAuthState['user']
|
||||
) => {
|
||||
if (!useBackendFlow) return;
|
||||
if (!useMiniappFlow) return;
|
||||
|
||||
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) {
|
||||
const signInData = {
|
||||
message,
|
||||
@@ -158,13 +165,13 @@ export function NeynarAuthButton() {
|
||||
user: JSON.stringify(user),
|
||||
};
|
||||
|
||||
await backendSignIn('neynar', signInData);
|
||||
await miniappSignIn('neynar', signInData);
|
||||
}
|
||||
} catch (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
|
||||
@@ -231,7 +238,7 @@ export function NeynarAuthButton() {
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
|
||||
const endpoint = useBackendFlow
|
||||
const endpoint = useMiniappFlow
|
||||
? `/api/auth/session-signers?message=${encodeURIComponent(
|
||||
message
|
||||
)}&signature=${signature}`
|
||||
@@ -243,8 +250,8 @@ export function NeynarAuthButton() {
|
||||
const signerData = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
if (useBackendFlow) {
|
||||
// For backend flow, update session with signers
|
||||
if (useMiniappFlow) {
|
||||
// For miniapp flow, update session with signers
|
||||
if (signerData.signers && signerData.signers.length > 0) {
|
||||
const user =
|
||||
signerData.user ||
|
||||
@@ -253,7 +260,7 @@ export function NeynarAuthButton() {
|
||||
}
|
||||
return signerData.signers;
|
||||
} else {
|
||||
// For frontend flow, store in localStorage
|
||||
// For webapp flow, store in localStorage
|
||||
let user: StoredAuthState['user'] | null = null;
|
||||
|
||||
if (signerData.signers && signerData.signers.length > 0) {
|
||||
@@ -285,7 +292,7 @@ export function NeynarAuthButton() {
|
||||
setSignersLoading(false);
|
||||
}
|
||||
},
|
||||
[useBackendFlow, fetchUserData, updateSessionWithSigners]
|
||||
[useMiniappFlow, fetchUserData, updateSessionWithSigners]
|
||||
);
|
||||
|
||||
// Helper function to poll signer status
|
||||
@@ -384,21 +391,21 @@ export function NeynarAuthButton() {
|
||||
generateNonce();
|
||||
}, []);
|
||||
|
||||
// Load stored auth state on mount (only for frontend flow)
|
||||
// Load stored auth state on mount (only for webapp flow)
|
||||
useEffect(() => {
|
||||
if (!useBackendFlow) {
|
||||
if (!useMiniappFlow) {
|
||||
const stored = getItem<StoredAuthState>(STORAGE_KEY);
|
||||
if (stored && stored.isAuthenticated) {
|
||||
setStoredAuth(stored);
|
||||
}
|
||||
}
|
||||
}, [useBackendFlow]);
|
||||
}, [useMiniappFlow]);
|
||||
|
||||
// Success callback - this is critical!
|
||||
const onSuccessCallback = useCallback(
|
||||
async (res: UseSignInData) => {
|
||||
if (!useBackendFlow) {
|
||||
// Only handle localStorage for frontend flow
|
||||
if (!useMiniappFlow) {
|
||||
// Only handle localStorage for webapp flow
|
||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||
const user = res.fid ? await fetchUserData(res.fid) : null;
|
||||
const authState: StoredAuthState = {
|
||||
@@ -410,9 +417,9 @@ export function NeynarAuthButton() {
|
||||
setItem<StoredAuthState>(STORAGE_KEY, 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
|
||||
@@ -427,8 +434,8 @@ export function NeynarAuthButton() {
|
||||
});
|
||||
|
||||
const {
|
||||
signIn: frontendSignIn,
|
||||
signOut: frontendSignOut,
|
||||
signIn: webappSignIn,
|
||||
signOut: webappSignOut,
|
||||
connect,
|
||||
reconnect,
|
||||
isSuccess,
|
||||
@@ -450,12 +457,12 @@ export function NeynarAuthButton() {
|
||||
}
|
||||
}, [data?.message, data?.signature]);
|
||||
|
||||
// Connect for frontend flow when nonce is available
|
||||
// Connect for webapp flow when nonce is available
|
||||
useEffect(() => {
|
||||
if (!useBackendFlow && nonce && !channelToken) {
|
||||
if (!useMiniappFlow && nonce && !channelToken) {
|
||||
connect();
|
||||
}
|
||||
}, [useBackendFlow, nonce, channelToken, connect]);
|
||||
}, [useMiniappFlow, nonce, channelToken, connect]);
|
||||
|
||||
// Handle fetching signers after successful authentication
|
||||
useEffect(() => {
|
||||
@@ -478,14 +485,14 @@ export function NeynarAuthButton() {
|
||||
// Step 1: Change to loading state
|
||||
setDialogStep('loading');
|
||||
|
||||
// Show dialog if not using backend flow or in browser farcaster
|
||||
if ((useBackendFlow && !isMobileContext) || !useBackendFlow)
|
||||
// Show dialog if not using miniapp flow or in browser farcaster
|
||||
if ((useMiniappFlow && !isMobileContext) || !useMiniappFlow)
|
||||
setShowDialog(true);
|
||||
|
||||
// First, fetch existing signers
|
||||
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
|
||||
if (!signers || signers.length === 0) {
|
||||
@@ -538,10 +545,10 @@ export function NeynarAuthButton() {
|
||||
}
|
||||
}, [message, signature]); // Simplified dependencies
|
||||
|
||||
// Backend flow using NextAuth
|
||||
const handleBackendSignIn = useCallback(async () => {
|
||||
// Miniapp flow using NextAuth
|
||||
const handleMiniappSignIn = useCallback(async () => {
|
||||
if (!nonce) {
|
||||
console.error('❌ No nonce available for backend sign-in');
|
||||
console.error('❌ No nonce available for miniapp sign-in');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -556,7 +563,7 @@ export function NeynarAuthButton() {
|
||||
nonce: nonce,
|
||||
};
|
||||
|
||||
const nextAuthResult = await backendSignIn('neynar', signInData);
|
||||
const nextAuthResult = await miniappSignIn('neynar', signInData);
|
||||
if (nextAuthResult?.ok) {
|
||||
setMessage(result.message);
|
||||
setSignature(result.signature);
|
||||
@@ -567,32 +574,34 @@ export function NeynarAuthButton() {
|
||||
if (e instanceof SignInCore.RejectedByUser) {
|
||||
console.log('ℹ️ Sign-in rejected by user');
|
||||
} else {
|
||||
console.error('❌ Backend sign-in error:', e);
|
||||
console.error('❌ Miniapp sign-in error:', e);
|
||||
}
|
||||
} finally {
|
||||
setSignersLoading(false);
|
||||
}
|
||||
}, [nonce]);
|
||||
|
||||
const handleFrontEndSignIn = useCallback(() => {
|
||||
const handleWebappSignIn = useCallback(() => {
|
||||
if (isError) {
|
||||
reconnect();
|
||||
}
|
||||
setDialogStep('signin');
|
||||
setShowDialog(true);
|
||||
frontendSignIn();
|
||||
}, [isError, reconnect, frontendSignIn]);
|
||||
webappSignIn();
|
||||
}, [isError, reconnect, webappSignIn]);
|
||||
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
|
||||
if (useBackendFlow) {
|
||||
if (useMiniappFlow) {
|
||||
// Only sign out from NextAuth if the current session is from Neynar provider
|
||||
if (session?.provider === 'neynar') {
|
||||
await backendSignOut({ redirect: false });
|
||||
await miniappSignOut({ redirect: false });
|
||||
}
|
||||
} else {
|
||||
// Frontend flow sign out
|
||||
frontendSignOut();
|
||||
// Webapp flow sign out
|
||||
webappSignOut();
|
||||
removeItem(STORAGE_KEY);
|
||||
setStoredAuth(null);
|
||||
}
|
||||
@@ -618,9 +627,9 @@ export function NeynarAuthButton() {
|
||||
} finally {
|
||||
setSignersLoading(false);
|
||||
}
|
||||
}, [useBackendFlow, frontendSignOut, pollingInterval, session]);
|
||||
}, [useMiniappFlow, webappSignOut, pollingInterval, session]);
|
||||
|
||||
const authenticated = useBackendFlow
|
||||
const authenticated = useMiniappFlow
|
||||
? !!(
|
||||
session?.provider === 'neynar' &&
|
||||
session?.user?.fid &&
|
||||
@@ -630,7 +639,7 @@ export function NeynarAuthButton() {
|
||||
: ((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
||||
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||
|
||||
const userData = useBackendFlow
|
||||
const userData = useMiniappFlow
|
||||
? {
|
||||
fid: session?.user?.fid,
|
||||
username: session?.user?.username || '',
|
||||
@@ -662,16 +671,16 @@ export function NeynarAuthButton() {
|
||||
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
||||
) : (
|
||||
<Button
|
||||
onClick={useBackendFlow ? handleBackendSignIn : handleFrontEndSignIn}
|
||||
disabled={!useBackendFlow && !url}
|
||||
onClick={useMiniappFlow ? handleMiniappSignIn : handleWebappSignIn}
|
||||
disabled={!useMiniappFlow && !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'
|
||||
!url && !useMiniappFlow && 'cursor-not-allowed'
|
||||
)}
|
||||
>
|
||||
{!useBackendFlow && !url ? (
|
||||
{!useMiniappFlow && !url ? (
|
||||
<>
|
||||
<div className="spinner-primary w-5 h-5" />
|
||||
<span>Initializing...</span>
|
||||
|
||||
208
src/components/ui/tabs/ActionsTab.NeynarAuth.tsx
Normal file
208
src/components/ui/tabs/ActionsTab.NeynarAuth.tsx
Normal file
@@ -0,0 +1,208 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { ShareButton } from '../Share';
|
||||
import { Button } from '../Button';
|
||||
import { SignIn } from '../wallet/SignIn';
|
||||
import { type Haptics } from '@farcaster/miniapp-sdk';
|
||||
import { APP_URL } from '~/lib/constants';
|
||||
import { NeynarAuthButton } from '../NeynarAuthButton';
|
||||
|
||||
/**
|
||||
* 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 />
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState, type ComponentType } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { ShareButton } from '../Share';
|
||||
import { Button } from '../Button';
|
||||
@@ -8,17 +8,6 @@ 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.
|
||||
*
|
||||
@@ -149,9 +138,6 @@ export function ActionsTab() {
|
||||
{/* Authentication */}
|
||||
<SignIn />
|
||||
|
||||
{/* Neynar Authentication */}
|
||||
{NeynarAuthButton && <NeynarAuthButton />}
|
||||
|
||||
{/* Mini app actions */}
|
||||
<Button
|
||||
onClick={() =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type AccountAssociation } from '@farcaster/miniapp-node';
|
||||
import { type AccountAssociation } from '@farcaster/miniapp-core/src/manifest';
|
||||
|
||||
/**
|
||||
* Application constants and configuration values.
|
||||
@@ -65,21 +65,22 @@ 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";
|
||||
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;
|
||||
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';
|
||||
export const APP_BUTTON_TEXT: string = 'Launch Mini App';
|
||||
|
||||
// --- Integration Configuration ---
|
||||
/**
|
||||
@@ -89,7 +90,8 @@ export const APP_BUTTON_TEXT: string = 'Launch NSK';
|
||||
* 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
|
||||
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`
|
||||
: `${APP_URL}/api/webhook`;
|
||||
|
||||
@@ -100,7 +102,7 @@ export const APP_WEBHOOK_URL: string = process.env.NEYNAR_API_KEY && process.env
|
||||
* 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;
|
||||
export const USE_WALLET: boolean = false;
|
||||
|
||||
/**
|
||||
* Flag to enable/disable analytics tracking.
|
||||
@@ -117,12 +119,20 @@ export const ANALYTICS_ENABLED: boolean = true;
|
||||
* 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[] = [];
|
||||
|
||||
/**
|
||||
* Return URL for the mini app.
|
||||
*
|
||||
* If provided, the mini app will be rendered with a return URL to be rendered if the
|
||||
* back button is pressed from the home page.
|
||||
*/
|
||||
export const RETURN_URL: string | undefined = undefined;
|
||||
|
||||
// PLEASE DO NOT UPDATE THIS
|
||||
export const SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN = {
|
||||
name: 'Farcaster SignedKeyRequestValidator',
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { FrameNotificationDetails } from "@farcaster/miniapp-sdk";
|
||||
import { Redis } from "@upstash/redis";
|
||||
import { APP_NAME } from "./constants";
|
||||
import { MiniAppNotificationDetails } from '@farcaster/miniapp-sdk';
|
||||
import { Redis } from '@upstash/redis';
|
||||
import { APP_NAME } from './constants';
|
||||
|
||||
// In-memory fallback storage
|
||||
const localStore = new Map<string, FrameNotificationDetails>();
|
||||
const localStore = new Map<string, MiniAppNotificationDetails>();
|
||||
|
||||
// Use Redis if KV env vars are present, otherwise use in-memory
|
||||
const useRedis = process.env.KV_REST_API_URL && process.env.KV_REST_API_TOKEN;
|
||||
const redis = useRedis ? new Redis({
|
||||
url: process.env.KV_REST_API_URL!,
|
||||
token: process.env.KV_REST_API_TOKEN!,
|
||||
}) : null;
|
||||
const redis = useRedis
|
||||
? new Redis({
|
||||
url: process.env.KV_REST_API_URL!,
|
||||
token: process.env.KV_REST_API_TOKEN!,
|
||||
})
|
||||
: null;
|
||||
|
||||
function getUserNotificationDetailsKey(fid: number): string {
|
||||
return `${APP_NAME}:user:${fid}`;
|
||||
@@ -18,17 +20,17 @@ function getUserNotificationDetailsKey(fid: number): string {
|
||||
|
||||
export async function getUserNotificationDetails(
|
||||
fid: number
|
||||
): Promise<FrameNotificationDetails | null> {
|
||||
): Promise<MiniAppNotificationDetails | null> {
|
||||
const key = getUserNotificationDetailsKey(fid);
|
||||
if (redis) {
|
||||
return await redis.get<FrameNotificationDetails>(key);
|
||||
return await redis.get<MiniAppNotificationDetails>(key);
|
||||
}
|
||||
return localStore.get(key) || null;
|
||||
}
|
||||
|
||||
export async function setUserNotificationDetails(
|
||||
fid: number,
|
||||
notificationDetails: FrameNotificationDetails
|
||||
notificationDetails: MiniAppNotificationDetails
|
||||
): Promise<void> {
|
||||
const key = getUserNotificationDetailsKey(fid);
|
||||
if (redis) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
import { type Manifest } from '@farcaster/miniapp-node';
|
||||
import { Manifest } from '@farcaster/miniapp-core/src/manifest';
|
||||
import {
|
||||
APP_BUTTON_TEXT,
|
||||
APP_DESCRIPTION,
|
||||
@@ -10,10 +10,10 @@ import {
|
||||
APP_PRIMARY_CATEGORY,
|
||||
APP_SPLASH_BACKGROUND_COLOR,
|
||||
APP_SPLASH_URL,
|
||||
APP_TAGS, APP_URL,
|
||||
APP_TAGS,
|
||||
APP_URL,
|
||||
APP_WEBHOOK_URL,
|
||||
APP_ACCOUNT_ASSOCIATION,
|
||||
APP_REQUIRED_CHAINS,
|
||||
} from './constants';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
@@ -22,7 +22,7 @@ export function cn(...inputs: ClassValue[]) {
|
||||
|
||||
export function getMiniAppEmbedMetadata(ogImageUrl?: string) {
|
||||
return {
|
||||
version: "next",
|
||||
version: 'next',
|
||||
imageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
|
||||
ogTitle: APP_NAME,
|
||||
ogDescription: APP_DESCRIPTION,
|
||||
@@ -30,7 +30,7 @@ export function getMiniAppEmbedMetadata(ogImageUrl?: string) {
|
||||
button: {
|
||||
title: APP_BUTTON_TEXT,
|
||||
action: {
|
||||
type: "launch_frame",
|
||||
type: 'launch_frame',
|
||||
name: APP_NAME,
|
||||
url: APP_URL,
|
||||
splashImageUrl: APP_SPLASH_URL,
|
||||
@@ -46,24 +46,17 @@ export function getMiniAppEmbedMetadata(ogImageUrl?: string) {
|
||||
|
||||
export async function getFarcasterDomainManifest(): Promise<Manifest> {
|
||||
return {
|
||||
accountAssociation: APP_ACCOUNT_ASSOCIATION,
|
||||
accountAssociation: APP_ACCOUNT_ASSOCIATION!,
|
||||
miniapp: {
|
||||
version: "1",
|
||||
name: APP_NAME ?? "Neynar Starter Kit",
|
||||
iconUrl: APP_ICON_URL,
|
||||
version: '1',
|
||||
name: APP_NAME ?? 'Neynar Starter Kit',
|
||||
homeUrl: APP_URL,
|
||||
iconUrl: APP_ICON_URL,
|
||||
imageUrl: APP_OG_IMAGE_URL,
|
||||
buttonTitle: APP_BUTTON_TEXT ?? "Launch Mini App",
|
||||
buttonTitle: APP_BUTTON_TEXT ?? 'Launch Mini App',
|
||||
splashImageUrl: APP_SPLASH_URL,
|
||||
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
|
||||
webhookUrl: APP_WEBHOOK_URL,
|
||||
description: APP_DESCRIPTION,
|
||||
primaryCategory: APP_PRIMARY_CATEGORY,
|
||||
tags: APP_TAGS,
|
||||
requiredChains: APP_REQUIRED_CHAINS.length > 0 ? APP_REQUIRED_CHAINS : undefined,
|
||||
ogTitle: APP_NAME,
|
||||
ogDescription: APP_DESCRIPTION,
|
||||
ogImageUrl: APP_OG_IMAGE_URL,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,6 +22,13 @@
|
||||
"~/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"ts-node": {
|
||||
"esm": true,
|
||||
"compilerOptions": {
|
||||
"module": "ES2020",
|
||||
"moduleResolution": "node"
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user