Compare commits

..

27 Commits

Author SHA1 Message Date
veganbeef
36b4540e47 fix: update protocol guild donation addresses to latest 2025-12-01 09:01:00 -08:00
Lucas Myers
c5fef388b2 Merge pull request #30 from vaibhavmule/fix/add-pigment-css-react-dependency
fix: add @pigment-css/react as dependency
2025-12-01 10:49:46 -06:00
Vaibhav Mule
91658503ff fix: add @pigment-css/react as dependency
@neynar/react requires @pigment-css/react at runtime but it wasn't
included in the generated package.json, causing module resolution errors.

This fixes the issue where newly created mini apps fail with:
'Module not found: Can't resolve @pigment-css/react'
2025-11-30 13:01:09 +05:30
veganbeef
760d2f28ec feat: remove localtunnel and recommend ngrok 2025-10-29 17:16:48 -07:00
veganbeef
8d37c83ee8 bump @neynar/react version 2025-10-13 14:50:57 -07:00
Bob Obringer
2254f0d9a7 Merge pull request #28 from neynarxyz/enforce-neynar-react-1.2.14
Enforce @neynar/react version 1.2.14
2025-10-12 12:45:23 -04:00
Bob Obringer
29fe3d82ca fixed lockfiled 2025-10-12 12:43:35 -04:00
Bob Obringer
258eba7bfc fixed lockfile 2025-10-12 12:42:30 -04:00
Bob Obringer
3921ab4258 Enforce @neynar/react version 1.2.14
This update enforces @neynar/react version 1.2.14 to include the fix for the miniapp data context issue resolved in https://github.com/neynarxyz/frontend-monorepo/pull/512

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 12:38:17 -04:00
Shreyaschorge
6a8fa017e5 Merge pull request #27 from neynarxyz/shreyas/neyn-7098-move-siwn-to-be-fully-embeddable-within-the-host-app
Fix terminology for siwn
2025-09-30 18:59:47 +05:30
Shreyaschorge
c872bdd4ee Fix terminology 2025-09-30 18:51:49 +05:30
veganbeef
c5ca1618ed bump @neynar/react version 2025-09-09 23:36:13 -07:00
veganbeef
db735d7568 fix: frame_* to miniapp_* 2025-09-09 23:20:35 -07:00
veganbeef
ccd27f53b3 fix: build failure 2025-09-09 23:07:53 -07:00
veganbeef
f14493e35b fix: deploy script dependency issue 2025-09-09 22:53:03 -07:00
veganbeef
3af6ee0e71 upgrade to @neynar/react v1.2.12 2025-09-09 22:25:23 -07:00
veganbeef
54646a5035 fix: support yarn and pnpm 2025-09-08 16:23:24 -07:00
veganbeef
be7d6b76ae fix: update @neynar/react version and add overrides for qix vulnerable packages 2025-09-08 16:00:14 -07:00
veganbeef
09ef2e374e feat: bump @neynar/react version 2025-08-21 11:31:40 -07:00
veganbeef
1cce5835d4 feat: bump neynar/react version 2025-08-11 17:21:09 -07:00
veganbeef
55c7c4b129 feat: udpate script to support --return-url flag [NEYN-6533] 2025-08-07 16:11:45 -07:00
veganbeef
055dc4adbd feat: integrate returnUrl to config [NEYN-6533] 2025-08-07 16:02:46 -07:00
veganbeef
98579bcea9 fix: constants format 2025-07-23 19:29:00 -07:00
veganbeef
ea7ee37e71 fix: siwn csrf config 2025-07-23 19:23:03 -07:00
veganbeef
feb9f3e161 fix: authkit provider 2025-07-23 18:57:24 -07:00
veganbeef
8c5b8d8329 move conditional next-auth code to alternate files 2025-07-23 18:54:08 -07:00
Shreyaschorge
d0f8c75a2e Merge pull request #24 from neynarxyz/sc/fix-401-for-siwn-auth
fix:401 for SIWN and remove farcaster login mechanism
2025-07-21 16:24:59 +05:30
19 changed files with 1288 additions and 938 deletions

View File

@@ -4,8 +4,3 @@ KV_REST_API_TOKEN=''
KV_REST_API_URL='' KV_REST_API_URL=''
NEXT_PUBLIC_URL='http://localhost:3000' NEXT_PUBLIC_URL='http://localhost:3000'
NEXTAUTH_URL='http://localhost:3000' NEXTAUTH_URL='http://localhost:3000'
NEXTAUTH_SECRET=""
NEYNAR_API_KEY=""
NEYNAR_CLIENT_ID=""
USE_TUNNEL="false"

View File

@@ -8,9 +8,9 @@ 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;
// Check for -y flag // Check for -y flag
const yIndex = args.indexOf('-y'); const yIndex = args.indexOf('-y');
@@ -53,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
@@ -74,6 +70,19 @@ if (yIndex !== -1) {
console.error('Error: --seed-phrase requires a seed phrase'); console.error('Error: --seed-phrase requires a seed phrase');
process.exit(1); 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);
}
} }
} }
@@ -85,7 +94,7 @@ if (autoAcceptDefaults && !projectName) {
process.exit(1); process.exit(1);
} }
init(projectName, autoAcceptDefaults, apiKey, noWallet, noTunnel, sponsoredSigner, seedPhrase).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);
}); });

View File

@@ -63,7 +63,15 @@ async function queryNeynarApp(apiKey) {
} }
// Export the main CLI function for programmatic use // Export the main CLI function for programmatic use
export async function init(projectName = null, autoAcceptDefaults = false, apiKey = null, noWallet = false, noTunnel = false, sponsoredSigner = false, seedPhrase = null) { export async function init(
projectName = null,
autoAcceptDefaults = false,
apiKey = null,
noWallet = false,
sponsoredSigner = false,
seedPhrase = null,
returnUrl = null
) {
printWelcomeMessage(); printWelcomeMessage();
// Ask about Neynar usage // Ask about Neynar usage
@@ -242,10 +250,10 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
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,
returnUrl: returnUrl,
}; };
} else { } else {
// If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options // If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options
@@ -351,24 +359,6 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
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
@@ -505,7 +495,8 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
'@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.5', '@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',
@@ -535,11 +526,12 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
"crypto": "^1.0.1", "crypto": "^1.0.1",
"eslint": "^8", "eslint": "^8",
"eslint-config-next": "15.0.3", "eslint-config-next": "15.0.3",
"localtunnel": "^2.0.2", "inquirer": "^10.2.2",
"pino-pretty": "^13.0.0", "pino-pretty": "^13.0.0",
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.1",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"tsx": "^4.20.5",
"typescript": "^5" "typescript": "^5"
}; };
@@ -554,6 +546,38 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
packageJson.dependencies['next-auth'] = '^4.24.11'; 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)); fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
// Handle .env file // Handle .env file
@@ -610,13 +634,14 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
USE_WALLET: /^export const USE_WALLET\s*:\s*boolean\s*=\s*(true|false);$/m, USE_WALLET: /^export const USE_WALLET\s*:\s*boolean\s*=\s*(true|false);$/m,
ANALYTICS_ENABLED: ANALYTICS_ENABLED:
/^export const ANALYTICS_ENABLED\s*:\s*boolean\s*=\s*(true|false);$/m, /^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 // Update APP_NAME
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.APP_NAME, patterns.APP_NAME,
`export const APP_NAME = '${escapeString(answers.projectName)}';`, `export const APP_NAME: string = '${escapeString(answers.projectName)}';`,
'APP_NAME' 'APP_NAME'
); );
@@ -624,7 +649,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.APP_DESCRIPTION, patterns.APP_DESCRIPTION,
`export const APP_DESCRIPTION = '${escapeString( `export const APP_DESCRIPTION: string = '${escapeString(
answers.description answers.description
)}';`, )}';`,
'APP_DESCRIPTION' 'APP_DESCRIPTION'
@@ -634,7 +659,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.APP_PRIMARY_CATEGORY, patterns.APP_PRIMARY_CATEGORY,
`export const APP_PRIMARY_CATEGORY = '${escapeString( `export const APP_PRIMARY_CATEGORY: string = '${escapeString(
answers.primaryCategory || '' answers.primaryCategory || ''
)}';`, )}';`,
'APP_PRIMARY_CATEGORY' 'APP_PRIMARY_CATEGORY'
@@ -648,7 +673,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.APP_TAGS, patterns.APP_TAGS,
`export const APP_TAGS = ${tagsString};`, `export const APP_TAGS: string[] = ${tagsString};`,
'APP_TAGS' 'APP_TAGS'
); );
@@ -656,7 +681,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.APP_BUTTON_TEXT, patterns.APP_BUTTON_TEXT,
`export const APP_BUTTON_TEXT = '${escapeString( `export const APP_BUTTON_TEXT: string = '${escapeString(
answers.buttonText || '' answers.buttonText || ''
)}';`, )}';`,
'APP_BUTTON_TEXT' 'APP_BUTTON_TEXT'
@@ -666,7 +691,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.USE_WALLET, patterns.USE_WALLET,
`export const USE_WALLET = ${answers.useWallet};`, `export const USE_WALLET: boolean = ${answers.useWallet};`,
'USE_WALLET' 'USE_WALLET'
); );
@@ -674,10 +699,19 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace( constantsContent = safeReplace(
constantsContent, constantsContent,
patterns.ANALYTICS_ENABLED, patterns.ANALYTICS_ENABLED,
`export const ANALYTICS_ENABLED = ${answers.enableAnalytics};`, `export const ANALYTICS_ENABLED: boolean = ${answers.enableAnalytics};`,
'ANALYTICS_ENABLED' '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); fs.writeFileSync(constantsPath, constantsContent);
} else { } else {
console.log('⚠️ constants.ts not found, skipping constants update'); console.log('⚠️ constants.ts not found, skipping constants update');
@@ -693,6 +727,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
); );
} }
if (answers.seedPhrase) { if (answers.seedPhrase) {
console.log('✅ Writing SEED_PHRASE and NEXTAUTH_SECRET to .env.local');
fs.appendFileSync(envPath, `\nSEED_PHRASE="${answers.seedPhrase}"`); fs.appendFileSync(envPath, `\nSEED_PHRASE="${answers.seedPhrase}"`);
// Add NextAuth secret for SIWN // Add NextAuth secret for SIWN
fs.appendFileSync( fs.appendFileSync(
@@ -700,7 +735,6 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
`\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"`);
} }
@@ -747,9 +781,12 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
fs.rmSync(binPath, { recursive: true, force: true }); fs.rmSync(binPath, { recursive: true, force: true });
} }
// Remove NeynarAuthButton directory, NextAuth API routes, and auth directory if SIWN is not enabled (no seed phrase) // Handle SIWN-related files based on whether seed phrase is provided
if (!answers.seedPhrase) { if (!answers.seedPhrase) {
console.log('\nRemoving NeynarAuthButton directory, NextAuth API routes, and auth directory (SIWN not enabled)...'); // 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'); const neynarAuthButtonPath = path.join(projectPath, 'src', 'components', 'ui', 'NeynarAuthButton');
if (fs.existsSync(neynarAuthButtonPath)) { if (fs.existsSync(neynarAuthButtonPath)) {
fs.rmSync(neynarAuthButtonPath, { recursive: true, force: true }); fs.rmSync(neynarAuthButtonPath, { recursive: true, force: true });
@@ -772,19 +809,56 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
fs.rmSync(authFilePath, { force: true }); fs.rmSync(authFilePath, { force: true });
} }
// Replace NeynarAuthButton import in ActionsTab.tsx with null component // 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'); const actionsTabPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.tsx');
if (fs.existsSync(actionsTabPath)) { if (fs.existsSync(actionsTabNeynarAuthPath)) {
let actionsTabContent = fs.readFileSync(actionsTabPath, 'utf8'); if (fs.existsSync(actionsTabPath)) {
fs.rmSync(actionsTabPath, { force: true }); // Delete original
// Replace the dynamic import of NeynarAuthButton with a null component }
actionsTabContent = actionsTabContent.replace( fs.renameSync(actionsTabNeynarAuthPath, actionsTabPath);
/const NeynarAuthButton = dynamic\([\s\S]*?\);/, console.log('✅ Moved ActionsTab.NeynarAuth.tsx to ActionsTab.tsx');
'// NeynarAuthButton disabled - SIWN not enabled\nconst NeynarAuthButton = () => {\n return null;\n};' }
);
// Move layout.NeynarAuth.tsx to layout.tsx
fs.writeFileSync(actionsTabPath, actionsTabContent); const layoutNeynarAuthPath = path.join(projectPath, 'src', 'app', 'layout.NeynarAuth.tsx');
console.log('✅ Replaced NeynarAuthButton import in ActionsTab.tsx with null component'); 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');
} }
} }

1133
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@neynar/create-farcaster-mini-app", "name": "@neynar/create-farcaster-mini-app",
"version": "1.7.14", "version": "1.9.0",
"type": "module", "type": "module",
"private": false, "private": false,
"access": "public", "access": "public",
@@ -35,7 +35,7 @@
"build:raw": "next build", "build:raw": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"deploy:vercel": "node --loader ts-node/esm scripts/deploy.ts", "deploy:vercel": "tsx scripts/deploy.ts",
"deploy:raw": "vercel --prod", "deploy:raw": "vercel --prod",
"cleanup": "node scripts/cleanup.js" "cleanup": "node scripts/cleanup.js"
}, },
@@ -51,5 +51,17 @@
"@neynar/nodejs-sdk": "^2.19.0", "@neynar/nodejs-sdk": "^2.19.0",
"@types/node": "^22.13.10", "@types/node": "^22.13.10",
"typescript": "^5.6.3" "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"
} }
} }

View File

@@ -115,80 +115,143 @@ async function checkRequiredEnvVars(): Promise<void> {
`${newLine}${varConfig.name}="${value.trim()}"`, `${newLine}${varConfig.name}="${value.trim()}"`,
); );
} }
}
// Ask about SIWN if SEED_PHRASE is provided // Ask about SIWN if SEED_PHRASE is provided (moved outside the loop)
if (process.env.SEED_PHRASE && !process.env.SPONSOR_SIGNER) { if (process.env.SEED_PHRASE && !process.env.SPONSOR_SIGNER) {
const { sponsorSigner } = await inquirer.prompt([ 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,
},
]);
process.env.SPONSOR_SIGNER = sponsorSigner.toString();
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([
{ {
type: 'confirm', type: 'confirm',
name: 'useRequiredChains', name: 'sponsorSigner',
message: message:
'Does your mini app require support for specific blockchains?\n' + 'You have provided a seed phrase, which enables Sign In With Neynar (SIWN).\n' +
'If yes, the host will only render your mini app if it supports all the chains you specify.\n' + 'Do you want to sponsor the signer? (This will be used in Sign In With Neynar)\n' +
'If no, the mini app will be rendered regardless of chain support.', '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, default: false,
}, },
]); ]);
let requiredChains: string[] = []; process.env.SPONSOR_SIGNER = sponsorSigner.toString();
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 fs.appendFileSync(
const constantsPath = path.join(projectRoot, 'src', 'lib', 'constants.ts'); '.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)) { if (fs.existsSync(constantsPath)) {
let constantsContent = fs.readFileSync(constantsPath, 'utf8'); let constantsContent = fs.readFileSync(constantsPath, 'utf8');
// Replace the APP_REQUIRED_CHAINS line // Replace the APP_ACCOUNT_ASSOCIATION line
const requiredChainsString = JSON.stringify(requiredChains); const newAccountAssociation = `export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined = ${JSON.stringify(parsedAccountAssociation, null, 2)};`;
constantsContent = constantsContent.replace( constantsContent = constantsContent.replace(
/^export const APP_REQUIRED_CHAINS\s*:\s*string\[\]\s*=\s*\[[^\]]*\];$/m, /^export const APP_ACCOUNT_ASSOCIATION\s*:\s*AccountAssociation \| undefined\s*=\s*[^;]*;/m,
`export const APP_REQUIRED_CHAINS: string[] = ${requiredChainsString};`, newAccountAssociation,
); );
fs.writeFileSync(constantsPath, constantsContent); 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');
} }
} }
@@ -878,55 +941,17 @@ async function deployToVercel(useGitHub = false): Promise<void> {
console.log( console.log(
'\n📝 You can manage your project at https://vercel.com/dashboard', '\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( 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( console.log(
'1. Go to: https://farcaster.xyz/~/developers/mini-apps/manifest?domain=' + ` https://farcaster.xyz/~/developers/mini-apps/manifest?domain=${domain}`,
domain,
); );
console.log( 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) { } catch (error: unknown) {
if (error instanceof Error) { if (error instanceof Error) {
console.error('\n❌ Deployment failed:', error.message); console.error('\n❌ Deployment failed:', error.message);

View File

@@ -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;
@@ -88,7 +86,7 @@ async function startDev() {
const isPortInUse = await checkPort(port); const isPortInUse = await checkPort(port);
if (isPortInUse) { if (isPortInUse) {
console.error(`Port ${port} is already in use. To find and kill the process using this port:\n\n` + console.error(`Port ${port} is already in use. To find and kill the process using this port:\n\n` +
(process.platform === 'win32' (process.platform === 'win32'
? `1. Run: netstat -ano | findstr :${port}\n` + ? `1. Run: netstat -ano | findstr :${port}\n` +
'2. Note the PID (Process ID) from the output\n' + '2. Note the PID (Process ID) from the output\n' +
'3. Run: taskkill /PID <PID> /F\n' '3. Run: taskkill /PID <PID> /F\n'
@@ -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'));
@@ -181,15 +147,6 @@ async function startDev() {
console.log('Note: Next.js process already terminated'); console.log('Note: Next.js process already terminated');
} }
} }
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);
@@ -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);

View File

@@ -7,6 +7,7 @@ export async function GET() {
return NextResponse.json(config); return NextResponse.json(config);
} catch (error) { } catch (error) {
console.error('Error generating metadata:', 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 });
} }
} }

View File

@@ -56,7 +56,7 @@ export async function POST(request: NextRequest) {
// Only handle notifications if Neynar is not enabled // Only handle notifications if Neynar is not enabled
// When Neynar is enabled, notifications are handled through their webhook // When Neynar is enabled, notifications are handled through their webhook
switch (event.event) { switch (event.event) {
case "frame_added": case "miniapp_added":
if (event.notificationDetails) { if (event.notificationDetails) {
await setUserNotificationDetails(fid, event.notificationDetails); await setUserNotificationDetails(fid, event.notificationDetails);
await sendMiniAppNotification({ await sendMiniAppNotification({
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
} }
break; break;
case "frame_removed": case "miniapp_removed":
await deleteUserNotificationDetails(fid); await deleteUserNotificationDetails(fid);
break; break;

View 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>
);
}

View File

@@ -14,25 +14,10 @@ export default async function RootLayout({
}: Readonly<{ }: Readonly<{
children: React.ReactNode; 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;
const shouldUseSession = sponsorSigner || hasSeedPhrase;
let session = null;
if (shouldUseSession) {
try {
const { getSession } = await import('~/auth');
session = await getSession();
} catch (error) {
console.warn('Failed to get session:', error);
}
}
return ( return (
<html lang="en"> <html lang="en">
<body> <body>
<Providers session={session} shouldUseSession={shouldUseSession}> <Providers>
{children} {children}
</Providers> </Providers>
</body> </body>

View 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>
);
}

View File

@@ -3,8 +3,7 @@
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import { MiniAppProvider } from '@neynar/react'; import { MiniAppProvider } from '@neynar/react';
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider'; import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
import { ANALYTICS_ENABLED } from '~/lib/constants'; import { ANALYTICS_ENABLED, RETURN_URL } from '~/lib/constants';
import React, { useState, useEffect } from 'react';
const WagmiProvider = dynamic( const WagmiProvider = dynamic(
() => import('~/components/providers/WagmiProvider'), () => import('~/components/providers/WagmiProvider'),
@@ -13,117 +12,22 @@ const WagmiProvider = dynamic(
} }
); );
// Helper component to conditionally render auth providers
function AuthProviders({
children,
session,
shouldUseSession,
}: {
children: React.ReactNode;
session: any;
shouldUseSession: boolean;
}) {
const [authComponents, setAuthComponents] = useState<{
SessionProvider: React.ComponentType<any> | null;
AuthKitProvider: React.ComponentType<any> | null;
loaded: boolean;
}>({
SessionProvider: null,
AuthKitProvider: null,
loaded: false,
});
useEffect(() => {
if (!shouldUseSession) {
setAuthComponents({
SessionProvider: null,
AuthKitProvider: null,
loaded: true,
});
return;
}
const loadAuthComponents = async () => {
try {
// Dynamic imports for auth modules
let SessionProvider = null;
let AuthKitProvider = null;
try {
const nextAuth = await import('next-auth/react');
SessionProvider = nextAuth.SessionProvider;
} catch (error) {
console.warn('NextAuth not available:', error);
}
try {
const authKit = await import('@farcaster/auth-kit');
AuthKitProvider = authKit.AuthKitProvider;
} catch (error) {
console.warn('Farcaster AuthKit not available:', error);
}
setAuthComponents({
SessionProvider,
AuthKitProvider,
loaded: true,
});
} catch (error) {
console.error('Error loading auth components:', error);
setAuthComponents({
SessionProvider: null,
AuthKitProvider: null,
loaded: true,
});
}
};
loadAuthComponents();
}, [shouldUseSession]);
if (!authComponents.loaded) {
return <></>;
}
if (!shouldUseSession || !authComponents.SessionProvider) {
return <>{children}</>;
}
const { SessionProvider, AuthKitProvider } = authComponents;
if (AuthKitProvider) {
return (
<SessionProvider session={session}>
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
</SessionProvider>
);
}
return <SessionProvider session={session}>{children}</SessionProvider>;
}
export function Providers({ export function Providers({
session,
children, children,
shouldUseSession = false,
}: { }: {
session: any | null;
children: React.ReactNode; children: React.ReactNode;
shouldUseSession?: boolean;
}) { }) {
const solanaEndpoint = const solanaEndpoint =
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com'; process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
return ( return (
<WagmiProvider> <WagmiProvider>
<MiniAppProvider <MiniAppProvider
analyticsEnabled={ANALYTICS_ENABLED} analyticsEnabled={ANALYTICS_ENABLED}
backButtonEnabled={true} backButtonEnabled={true}
returnUrl={RETURN_URL}
> >
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}> <SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
<AuthProviders session={session} shouldUseSession={shouldUseSession}> {children}
{children}
</AuthProviders>
</SafeFarcasterSolanaProvider> </SafeFarcasterSolanaProvider>
</MiniAppProvider> </MiniAppProvider>
</WagmiProvider> </WagmiProvider>

View File

@@ -274,7 +274,7 @@ export const authOptions: AuthOptions = {
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
: process.env.VERCEL_URL : process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}` ? `https://${process.env.VERCEL_URL}`
: `http://localhost:${process.env.PORT ?? 3000}`; : process.env.NEXTAUTH_URL || `http://localhost:${process.env.PORT ?? 3000}`;
const domain = getDomainFromUrl(baseUrl); const domain = getDomainFromUrl(baseUrl);
@@ -339,26 +339,26 @@ export const authOptions: AuthOptions = {
name: `next-auth.session-token`, name: `next-auth.session-token`,
options: { options: {
httpOnly: true, httpOnly: true,
sameSite: 'none', sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
path: '/', path: '/',
secure: true, secure: process.env.NODE_ENV === 'production',
}, },
}, },
callbackUrl: { callbackUrl: {
name: `next-auth.callback-url`, name: `next-auth.callback-url`,
options: { options: {
sameSite: 'none', sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
path: '/', path: '/',
secure: true, secure: process.env.NODE_ENV === 'production',
}, },
}, },
csrfToken: { csrfToken: {
name: `next-auth.csrf-token`, name: `next-auth.csrf-token`,
options: { options: {
httpOnly: true, httpOnly: true,
sameSite: 'none', sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
path: '/', path: '/',
secure: true, secure: process.env.NODE_ENV === 'production',
}, },
}, },
}, },

View File

@@ -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,11 +17,11 @@ 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/frame-sdk'; import sdk, { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
type User = { type User = {
fid: number; fid: number;
@@ -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,32 +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 {
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);
} }
@@ -618,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 &&
@@ -630,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 || '',
@@ -662,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>

View 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>
);
}

View File

@@ -1,6 +1,5 @@
'use client'; 'use client';
import dynamic from 'next/dynamic';
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { useMiniApp } from '@neynar/react'; import { useMiniApp } from '@neynar/react';
import { ShareButton } from '../Share'; import { ShareButton } from '../Share';
@@ -9,15 +8,6 @@ import { SignIn } from '../wallet/SignIn';
import { type Haptics } from '@farcaster/miniapp-sdk'; import { type Haptics } from '@farcaster/miniapp-sdk';
import { APP_URL } from '~/lib/constants'; import { APP_URL } from '~/lib/constants';
// Import NeynarAuthButton
const NeynarAuthButton = dynamic(
() =>
import('../NeynarAuthButton').then((module) => ({
default: module.NeynarAuthButton,
})),
{ ssr: false }
);
/** /**
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback. * ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
* *
@@ -148,9 +138,6 @@ export function ActionsTab() {
{/* Authentication */} {/* Authentication */}
<SignIn /> <SignIn />
{/* Neynar Authentication */}
{NeynarAuthButton && <NeynarAuthButton />}
{/* Mini app actions */} {/* Mini app actions */}
<Button <Button
onClick={() => onClick={() =>

View File

@@ -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";
@@ -44,18 +44,37 @@ export function SendEth() {
// --- Computed Values --- // --- Computed Values ---
/** /**
* 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 ---

View File

@@ -80,7 +80,7 @@ export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined =
* Text displayed on the main action button. * Text displayed on the main action button.
* Used for the primary call-to-action in the mini app. * Used for the primary call-to-action in the mini app.
*/ */
export const APP_BUTTON_TEXT = 'Launch Mini App'; export const APP_BUTTON_TEXT: string = 'Launch Mini App';
// --- Integration Configuration --- // --- Integration Configuration ---
/** /**
@@ -102,7 +102,7 @@ export const APP_WEBHOOK_URL: string =
* When false, wallet functionality is completely hidden from the UI. * When false, wallet functionality is completely hidden from the UI.
* Useful for mini apps that don't require wallet integration. * Useful for mini apps that don't require wallet integration.
*/ */
export const USE_WALLET = false; export const USE_WALLET: boolean = false;
/** /**
* Flag to enable/disable analytics tracking. * Flag to enable/disable analytics tracking.
@@ -111,7 +111,7 @@ export const USE_WALLET = false;
* When false, analytics collection is disabled. * When false, analytics collection is disabled.
* Useful for privacy-conscious users or development environments. * Useful for privacy-conscious users or development environments.
*/ */
export const ANALYTICS_ENABLED = true; export const ANALYTICS_ENABLED: boolean = true;
/** /**
* Required chains for the mini app. * Required chains for the mini app.
@@ -125,6 +125,14 @@ export const ANALYTICS_ENABLED = true;
*/ */
export const APP_REQUIRED_CHAINS: string[] = []; 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 // PLEASE DO NOT UPDATE THIS
export const SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN = { export const SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN = {
name: 'Farcaster SignedKeyRequestValidator', name: 'Farcaster SignedKeyRequestValidator',