mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-06 17:32:31 -05:00
Merge branch 'main' into shreyas-formatting
This commit is contained in:
16
src/app/api/auth/nonce/route.ts
Normal file
16
src/app/api/auth/nonce/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getNeynarClient } from '~/lib/neynar';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const client = getNeynarClient();
|
||||
const response = await client.fetchNonce();
|
||||
return NextResponse.json(response);
|
||||
} catch (error) {
|
||||
console.error('Error fetching nonce:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch nonce' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
43
src/app/api/auth/session-signers/route.ts
Normal file
43
src/app/api/auth/session-signers/route.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getNeynarClient } from '~/lib/neynar';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const message = searchParams.get('message');
|
||||
const signature = searchParams.get('signature');
|
||||
|
||||
if (!message || !signature) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Message and signature are required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const client = getNeynarClient();
|
||||
const data = await client.fetchSigners({ message, signature });
|
||||
const signers = data.signers;
|
||||
|
||||
// Fetch user data if signers exist
|
||||
let user = null;
|
||||
if (signers && signers.length > 0 && signers[0].fid) {
|
||||
const {
|
||||
users: [fetchedUser],
|
||||
} = await client.fetchBulkUsers({
|
||||
fids: [signers[0].fid],
|
||||
});
|
||||
user = fetchedUser;
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
signers,
|
||||
user,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error in session-signers API:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch signers' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
42
src/app/api/auth/signer/route.ts
Normal file
42
src/app/api/auth/signer/route.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getNeynarClient } from '~/lib/neynar';
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const neynarClient = getNeynarClient();
|
||||
const signer = await neynarClient.createSigner();
|
||||
return NextResponse.json(signer);
|
||||
} catch (error) {
|
||||
console.error('Error fetching signer:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch signer' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const signerUuid = searchParams.get('signerUuid');
|
||||
|
||||
if (!signerUuid) {
|
||||
return NextResponse.json(
|
||||
{ error: 'signerUuid is required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const neynarClient = getNeynarClient();
|
||||
const signer = await neynarClient.lookupSigner({
|
||||
signerUuid,
|
||||
});
|
||||
return NextResponse.json(signer);
|
||||
} catch (error) {
|
||||
console.error('Error fetching signed key:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch signed key' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
91
src/app/api/auth/signer/signed_key/route.ts
Normal file
91
src/app/api/auth/signer/signed_key/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getNeynarClient } from '~/lib/neynar';
|
||||
import { mnemonicToAccount } from 'viem/accounts';
|
||||
import {
|
||||
SIGNED_KEY_REQUEST_TYPE,
|
||||
SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN,
|
||||
} from '~/lib/constants';
|
||||
|
||||
const postRequiredFields = ['signerUuid', 'publicKey'];
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
|
||||
// Validate required fields
|
||||
for (const field of postRequiredFields) {
|
||||
if (!body[field]) {
|
||||
return NextResponse.json(
|
||||
{ error: `${field} is required` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const { signerUuid, publicKey, redirectUrl } = body;
|
||||
|
||||
if (redirectUrl && typeof redirectUrl !== 'string') {
|
||||
return NextResponse.json(
|
||||
{ error: 'redirectUrl must be a string' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the app's account from seed phrase
|
||||
const seedPhrase = process.env.SEED_PHRASE;
|
||||
const shouldSponsor = process.env.SPONSOR_SIGNER === 'true';
|
||||
|
||||
if (!seedPhrase) {
|
||||
return NextResponse.json(
|
||||
{ error: 'App configuration missing (SEED_PHRASE or FID)' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
const neynarClient = getNeynarClient();
|
||||
|
||||
const account = mnemonicToAccount(seedPhrase);
|
||||
|
||||
const {
|
||||
user: { fid },
|
||||
} = await neynarClient.lookupUserByCustodyAddress({
|
||||
custodyAddress: account.address,
|
||||
});
|
||||
|
||||
const appFid = fid;
|
||||
|
||||
// Generate deadline (24 hours from now)
|
||||
const deadline = Math.floor(Date.now() / 1000) + 86400;
|
||||
|
||||
// Generate EIP-712 signature
|
||||
const signature = await account.signTypedData({
|
||||
domain: SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN,
|
||||
types: {
|
||||
SignedKeyRequest: SIGNED_KEY_REQUEST_TYPE,
|
||||
},
|
||||
primaryType: 'SignedKeyRequest',
|
||||
message: {
|
||||
requestFid: BigInt(appFid),
|
||||
key: publicKey,
|
||||
deadline: BigInt(deadline),
|
||||
},
|
||||
});
|
||||
|
||||
const signer = await neynarClient.registerSignedKey({
|
||||
appFid,
|
||||
deadline,
|
||||
signature,
|
||||
signerUuid,
|
||||
...(redirectUrl && { redirectUrl }),
|
||||
...(shouldSponsor && { sponsor: { sponsored_by_neynar: true } }),
|
||||
});
|
||||
|
||||
return NextResponse.json(signer);
|
||||
} catch (error) {
|
||||
console.error('Error registering signed key:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to register signed key' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
38
src/app/api/auth/signers/route.ts
Normal file
38
src/app/api/auth/signers/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getNeynarClient } from '~/lib/neynar';
|
||||
|
||||
const requiredParams = ['message', 'signature'];
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const params: Record<string, string | null> = {};
|
||||
for (const param of requiredParams) {
|
||||
params[param] = searchParams.get(param);
|
||||
if (!params[param]) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `${param} parameter is required`,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const message = params.message as string;
|
||||
const signature = params.signature as string;
|
||||
|
||||
try {
|
||||
const client = getNeynarClient();
|
||||
const data = await client.fetchSigners({ message, signature });
|
||||
const signers = data.signers;
|
||||
return NextResponse.json({
|
||||
signers,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching signers:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch signers' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
46
src/app/api/auth/update-session/route.ts
Normal file
46
src/app/api/auth/update-session/route.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '~/auth';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user?.fid) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No authenticated session found' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { signers, user } = body;
|
||||
|
||||
if (!signers || !user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Signers and user are required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// For NextAuth to update the session, we need to trigger the JWT callback
|
||||
// This is typically done by calling the session endpoint with updated data
|
||||
// However, we can't directly modify the session token from here
|
||||
|
||||
// Instead, we'll store the data temporarily and let the client refresh the session
|
||||
// The session will be updated when the JWT callback is triggered
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Session update prepared',
|
||||
signers,
|
||||
user,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error preparing session update:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to prepare session update' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { notificationDetailsSchema } from '@farcaster/frame-sdk';
|
||||
import { z } from 'zod';
|
||||
import { setUserNotificationDetails } from '~/lib/kv';
|
||||
import { sendNeynarMiniAppNotification } from '~/lib/neynar';
|
||||
import { sendMiniAppNotification } from '~/lib/notifs';
|
||||
import { notificationDetailsSchema } from "@farcaster/miniapp-sdk";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { setUserNotificationDetails } from "~/lib/kv";
|
||||
import { sendMiniAppNotification } from "~/lib/notifs";
|
||||
import { sendNeynarMiniAppNotification } from "~/lib/neynar";
|
||||
|
||||
const requestSchema = z.object({
|
||||
fid: z.number(),
|
||||
@@ -13,8 +13,7 @@ const requestSchema = z.object({
|
||||
export async function POST(request: NextRequest) {
|
||||
// If Neynar is enabled, we don't need to store notification details
|
||||
// as they will be managed by Neynar's system
|
||||
const neynarEnabled =
|
||||
process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
|
||||
const neynarEnabled = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
|
||||
|
||||
const requestJson = await request.json();
|
||||
const requestBody = requestSchema.safeParse(requestJson);
|
||||
@@ -22,7 +21,7 @@ export async function POST(request: NextRequest) {
|
||||
if (requestBody.success === false) {
|
||||
return Response.json(
|
||||
{ success: false, errors: requestBody.error.errors },
|
||||
{ status: 400 },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,31 +29,29 @@ export async function POST(request: NextRequest) {
|
||||
if (!neynarEnabled) {
|
||||
await setUserNotificationDetails(
|
||||
Number(requestBody.data.fid),
|
||||
requestBody.data.notificationDetails,
|
||||
requestBody.data.notificationDetails
|
||||
);
|
||||
}
|
||||
|
||||
// Use appropriate notification function based on Neynar status
|
||||
const sendNotification = neynarEnabled
|
||||
? sendNeynarMiniAppNotification
|
||||
: sendMiniAppNotification;
|
||||
const sendNotification = neynarEnabled ? sendNeynarMiniAppNotification : sendMiniAppNotification;
|
||||
const sendResult = await sendNotification({
|
||||
fid: Number(requestBody.data.fid),
|
||||
title: 'Test notification',
|
||||
body: 'Sent at ' + new Date().toISOString(),
|
||||
title: "Test notification",
|
||||
body: "Sent at " + new Date().toISOString(),
|
||||
});
|
||||
|
||||
if (sendResult.state === 'error') {
|
||||
if (sendResult.state === "error") {
|
||||
return Response.json(
|
||||
{ success: false, error: sendResult.error },
|
||||
{ status: 500 },
|
||||
{ status: 500 }
|
||||
);
|
||||
} else if (sendResult.state === 'rate_limit') {
|
||||
} else if (sendResult.state === "rate_limit") {
|
||||
return Response.json(
|
||||
{ success: false, error: 'Rate limited' },
|
||||
{ status: 429 },
|
||||
{ success: false, error: "Rate limited" },
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import {
|
||||
ParseWebhookEvent,
|
||||
parseWebhookEvent,
|
||||
verifyAppKeyWithNeynar,
|
||||
} from '@farcaster/frame-node';
|
||||
import { APP_NAME } from '~/lib/constants';
|
||||
} from "@farcaster/miniapp-node";
|
||||
import { NextRequest } from "next/server";
|
||||
import { APP_NAME } from "~/lib/constants";
|
||||
import {
|
||||
deleteUserNotificationDetails,
|
||||
setUserNotificationDetails,
|
||||
} from '~/lib/kv';
|
||||
import { sendMiniAppNotification } from '~/lib/notifs';
|
||||
} from "~/lib/kv";
|
||||
import { sendMiniAppNotification } from "~/lib/notifs";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
// If Neynar is enabled, we don't need to handle webhooks here
|
||||
// as they will be handled by Neynar's webhook endpoint
|
||||
const neynarEnabled =
|
||||
process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
|
||||
const neynarEnabled = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID;
|
||||
if (neynarEnabled) {
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
@@ -29,24 +28,24 @@ export async function POST(request: NextRequest) {
|
||||
const error = e as ParseWebhookEvent.ErrorType;
|
||||
|
||||
switch (error.name) {
|
||||
case 'VerifyJsonFarcasterSignature.InvalidDataError':
|
||||
case 'VerifyJsonFarcasterSignature.InvalidEventDataError':
|
||||
case "VerifyJsonFarcasterSignature.InvalidDataError":
|
||||
case "VerifyJsonFarcasterSignature.InvalidEventDataError":
|
||||
// The request data is invalid
|
||||
return Response.json(
|
||||
{ success: false, error: error.message },
|
||||
{ status: 400 },
|
||||
{ status: 400 }
|
||||
);
|
||||
case 'VerifyJsonFarcasterSignature.InvalidAppKeyError':
|
||||
case "VerifyJsonFarcasterSignature.InvalidAppKeyError":
|
||||
// The app key is invalid
|
||||
return Response.json(
|
||||
{ success: false, error: error.message },
|
||||
{ status: 401 },
|
||||
{ status: 401 }
|
||||
);
|
||||
case 'VerifyJsonFarcasterSignature.VerifyAppKeyError':
|
||||
case "VerifyJsonFarcasterSignature.VerifyAppKeyError":
|
||||
// Internal error verifying the app key (caller may want to try again)
|
||||
return Response.json(
|
||||
{ success: false, error: error.message },
|
||||
{ status: 500 },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -57,36 +56,36 @@ export async function POST(request: NextRequest) {
|
||||
// Only handle notifications if Neynar is not enabled
|
||||
// When Neynar is enabled, notifications are handled through their webhook
|
||||
switch (event.event) {
|
||||
case 'frame_added':
|
||||
case "frame_added":
|
||||
if (event.notificationDetails) {
|
||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||
await sendMiniAppNotification({
|
||||
fid,
|
||||
title: `Welcome to ${APP_NAME}`,
|
||||
body: 'Mini app is now added to your client',
|
||||
body: "Mini app is now added to your client",
|
||||
});
|
||||
} else {
|
||||
await deleteUserNotificationDetails(fid);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'frame_removed':
|
||||
case "frame_removed":
|
||||
await deleteUserNotificationDetails(fid);
|
||||
break;
|
||||
|
||||
case 'notifications_enabled':
|
||||
case "notifications_enabled":
|
||||
await setUserNotificationDetails(fid, event.notificationDetails);
|
||||
await sendMiniAppNotification({
|
||||
fid,
|
||||
title: `Welcome to ${APP_NAME}`,
|
||||
body: 'Notifications are now enabled',
|
||||
body: "Notifications are now enabled",
|
||||
});
|
||||
break;
|
||||
|
||||
case 'notifications_disabled':
|
||||
case "notifications_disabled":
|
||||
await deleteUserNotificationDetails(fid);
|
||||
break;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,18 @@
|
||||
'use client';
|
||||
|
||||
import dynamic from 'next/dynamic';
|
||||
import { MiniAppProvider } from '@neynar/react';
|
||||
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';
|
||||
|
||||
const WagmiProvider = dynamic(
|
||||
() => import('~/components/providers/WagmiProvider'),
|
||||
{
|
||||
ssr: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export function Providers({
|
||||
@@ -31,10 +32,10 @@ export function Providers({
|
||||
backButtonEnabled={true}
|
||||
>
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
{children}
|
||||
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</MiniAppProvider>
|
||||
</WagmiProvider>
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
}
|
||||
330
src/auth.ts
330
src/auth.ts
@@ -1,11 +1,200 @@
|
||||
import { createAppClient, viemConnector } from '@farcaster/auth-client';
|
||||
import { AuthOptions, getServerSession } from 'next-auth';
|
||||
import CredentialsProvider from 'next-auth/providers/credentials';
|
||||
import { createAppClient, viemConnector } from '@farcaster/auth-client';
|
||||
|
||||
declare module 'next-auth' {
|
||||
interface Session {
|
||||
user: {
|
||||
provider?: string;
|
||||
user?: {
|
||||
fid: number;
|
||||
object?: 'user';
|
||||
username?: string;
|
||||
display_name?: string;
|
||||
pfp_url?: string;
|
||||
custody_address?: string;
|
||||
profile?: {
|
||||
bio: {
|
||||
text: string;
|
||||
mentioned_profiles?: Array<{
|
||||
object: 'user_dehydrated';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
}>;
|
||||
mentioned_profiles_ranges?: Array<{
|
||||
start: number;
|
||||
end: number;
|
||||
}>;
|
||||
};
|
||||
location?: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
address: {
|
||||
city: string;
|
||||
state: string;
|
||||
country: string;
|
||||
country_code: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
follower_count?: number;
|
||||
following_count?: number;
|
||||
verifications?: string[];
|
||||
verified_addresses?: {
|
||||
eth_addresses: string[];
|
||||
sol_addresses: string[];
|
||||
primary: {
|
||||
eth_address: string;
|
||||
sol_address: string;
|
||||
};
|
||||
};
|
||||
verified_accounts?: Array<Record<string, unknown>>;
|
||||
power_badge?: boolean;
|
||||
url?: string;
|
||||
experimental?: {
|
||||
neynar_user_score: number;
|
||||
deprecation_notice: string;
|
||||
};
|
||||
score?: number;
|
||||
};
|
||||
signers?: {
|
||||
object: 'signer';
|
||||
signer_uuid: string;
|
||||
public_key: string;
|
||||
status: 'approved';
|
||||
fid: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
interface User {
|
||||
provider?: string;
|
||||
signers?: Array<{
|
||||
object: 'signer';
|
||||
signer_uuid: string;
|
||||
public_key: string;
|
||||
status: 'approved';
|
||||
fid: number;
|
||||
}>;
|
||||
user?: {
|
||||
object: 'user';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
profile: {
|
||||
bio: {
|
||||
text: string;
|
||||
mentioned_profiles?: Array<{
|
||||
object: 'user_dehydrated';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
}>;
|
||||
mentioned_profiles_ranges?: Array<{
|
||||
start: number;
|
||||
end: number;
|
||||
}>;
|
||||
};
|
||||
location?: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
address: {
|
||||
city: string;
|
||||
state: string;
|
||||
country: string;
|
||||
country_code: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
follower_count: number;
|
||||
following_count: number;
|
||||
verifications: string[];
|
||||
verified_addresses: {
|
||||
eth_addresses: string[];
|
||||
sol_addresses: string[];
|
||||
primary: {
|
||||
eth_address: string;
|
||||
sol_address: string;
|
||||
};
|
||||
};
|
||||
verified_accounts: Array<Record<string, unknown>>;
|
||||
power_badge: boolean;
|
||||
url?: string;
|
||||
experimental?: {
|
||||
neynar_user_score: number;
|
||||
deprecation_notice: string;
|
||||
};
|
||||
score: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface JWT {
|
||||
provider?: string;
|
||||
signers?: Array<{
|
||||
object: 'signer';
|
||||
signer_uuid: string;
|
||||
public_key: string;
|
||||
status: 'approved';
|
||||
fid: number;
|
||||
}>;
|
||||
user?: {
|
||||
object: 'user';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
profile: {
|
||||
bio: {
|
||||
text: string;
|
||||
mentioned_profiles?: Array<{
|
||||
object: 'user_dehydrated';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
}>;
|
||||
mentioned_profiles_ranges?: Array<{
|
||||
start: number;
|
||||
end: number;
|
||||
}>;
|
||||
};
|
||||
location?: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
address: {
|
||||
city: string;
|
||||
state: string;
|
||||
country: string;
|
||||
country_code: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
follower_count: number;
|
||||
following_count: number;
|
||||
verifications: string[];
|
||||
verified_addresses: {
|
||||
eth_addresses: string[];
|
||||
sol_addresses: string[];
|
||||
primary: {
|
||||
eth_address: string;
|
||||
sol_address: string;
|
||||
};
|
||||
};
|
||||
verified_accounts?: Array<Record<string, unknown>>;
|
||||
power_badge?: boolean;
|
||||
url?: string;
|
||||
experimental?: {
|
||||
neynar_user_score: number;
|
||||
deprecation_notice: string;
|
||||
};
|
||||
score?: number;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -29,6 +218,7 @@ export const authOptions: AuthOptions = {
|
||||
// Configure one or more authentication providers
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
id: 'farcaster',
|
||||
name: 'Sign in with Farcaster',
|
||||
credentials: {
|
||||
message: {
|
||||
@@ -41,6 +231,11 @@ export const authOptions: AuthOptions = {
|
||||
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.
|
||||
@@ -57,12 +252,12 @@ export const authOptions: AuthOptions = {
|
||||
},
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
const csrfToken = req?.body?.csrfToken;
|
||||
if (!csrfToken) {
|
||||
console.error('CSRF token is missing from request');
|
||||
const nonce = req?.body?.csrfToken;
|
||||
|
||||
if (!nonce) {
|
||||
console.error('No nonce or CSRF token provided');
|
||||
return null;
|
||||
}
|
||||
|
||||
const appClient = createAppClient({
|
||||
ethereum: viemConnector(),
|
||||
});
|
||||
@@ -73,8 +268,9 @@ export const authOptions: AuthOptions = {
|
||||
message: credentials?.message as string,
|
||||
signature: credentials?.signature as `0x${string}`,
|
||||
domain,
|
||||
nonce: csrfToken,
|
||||
nonce,
|
||||
});
|
||||
|
||||
const { success, fid } = verifyResponse;
|
||||
|
||||
if (!success) {
|
||||
@@ -83,21 +279,129 @@ export const authOptions: AuthOptions = {
|
||||
|
||||
return {
|
||||
id: fid.toString(),
|
||||
name: credentials?.name || `User ${fid}`,
|
||||
image: credentials?.pfp || null,
|
||||
provider: 'farcaster',
|
||||
};
|
||||
},
|
||||
}),
|
||||
CredentialsProvider({
|
||||
id: 'neynar',
|
||||
name: 'Sign in with Neynar',
|
||||
credentials: {
|
||||
message: {
|
||||
label: 'Message',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
signature: {
|
||||
label: 'Signature',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
nonce: {
|
||||
label: 'Nonce',
|
||||
type: 'text',
|
||||
placeholder: 'Custom nonce (optional)',
|
||||
},
|
||||
fid: {
|
||||
label: 'FID',
|
||||
type: 'text',
|
||||
placeholder: '0',
|
||||
},
|
||||
signers: {
|
||||
label: 'Signers',
|
||||
type: 'text',
|
||||
placeholder: 'JSON string of signers',
|
||||
},
|
||||
user: {
|
||||
label: 'User Data',
|
||||
type: 'text',
|
||||
placeholder: 'JSON string of user data',
|
||||
},
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const nonce = credentials?.nonce;
|
||||
|
||||
if (!nonce) {
|
||||
console.error('No nonce or CSRF token provided for Neynar auth');
|
||||
return null;
|
||||
}
|
||||
|
||||
// For Neynar, we can use a different validation approach
|
||||
// This could involve validating against Neynar's API or using their SDK
|
||||
try {
|
||||
// Validate the signature using Farcaster's auth client (same as Farcaster provider)
|
||||
const appClient = createAppClient({
|
||||
ethereum: viemConnector(),
|
||||
});
|
||||
|
||||
const domain = getDomainFromUrl(process.env.NEXTAUTH_URL);
|
||||
|
||||
const verifyResponse = await appClient.verifySignInMessage({
|
||||
message: credentials?.message as string,
|
||||
signature: credentials?.signature as `0x${string}`,
|
||||
domain,
|
||||
nonce,
|
||||
});
|
||||
|
||||
const { success, fid } = verifyResponse;
|
||||
|
||||
if (!success) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Validate that the provided FID matches the verified FID
|
||||
if (credentials?.fid && parseInt(credentials.fid) !== fid) {
|
||||
console.error('FID mismatch in Neynar auth');
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: fid.toString(),
|
||||
provider: 'neynar',
|
||||
signers: credentials?.signers
|
||||
? JSON.parse(credentials.signers)
|
||||
: undefined,
|
||||
user: credentials?.user ? JSON.parse(credentials.user) : undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error in Neynar auth:', error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
session: async ({ session, token }) => {
|
||||
if (session?.user) {
|
||||
session.user.fid = parseInt(token.sub ?? '');
|
||||
// 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') {
|
||||
// For Neynar, use full user data structure from user
|
||||
session.user = token.user as typeof session.user;
|
||||
session.signers = token.signers as typeof session.signers;
|
||||
}
|
||||
|
||||
return session;
|
||||
},
|
||||
jwt: async ({ token, user }) => {
|
||||
if (user) {
|
||||
token.provider = user.provider;
|
||||
token.signers = user.signers;
|
||||
token.user = user.user;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
},
|
||||
cookies: {
|
||||
sessionToken: {
|
||||
name: 'next-auth.session-token',
|
||||
name: `next-auth.session-token`,
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
@@ -106,7 +410,7 @@ export const authOptions: AuthOptions = {
|
||||
},
|
||||
},
|
||||
callbackUrl: {
|
||||
name: 'next-auth.callback-url',
|
||||
name: `next-auth.callback-url`,
|
||||
options: {
|
||||
sameSite: 'none',
|
||||
path: '/',
|
||||
@@ -114,7 +418,7 @@ export const authOptions: AuthOptions = {
|
||||
},
|
||||
},
|
||||
csrfToken: {
|
||||
name: 'next-auth.csrf-token',
|
||||
name: `next-auth.csrf-token`,
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
@@ -132,4 +436,4 @@ export const getSession = async () => {
|
||||
console.error('Error getting server session:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,13 +1,10 @@
|
||||
import React, { createContext, useEffect, useState } from 'react';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { sdk } from '@farcaster/frame-sdk';
|
||||
import React, { createContext, useEffect, useState } from "react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { sdk } from '@farcaster/miniapp-sdk';
|
||||
|
||||
const FarcasterSolanaProvider = dynamic(
|
||||
() =>
|
||||
import('@farcaster/mini-app-solana').then(
|
||||
mod => mod.FarcasterSolanaProvider,
|
||||
),
|
||||
{ ssr: false },
|
||||
() => import('@farcaster/mini-app-solana').then(mod => mod.FarcasterSolanaProvider),
|
||||
{ ssr: false }
|
||||
);
|
||||
|
||||
type SafeFarcasterSolanaProviderProps = {
|
||||
@@ -15,15 +12,10 @@ type SafeFarcasterSolanaProviderProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({
|
||||
hasSolanaProvider: false,
|
||||
});
|
||||
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({ hasSolanaProvider: false });
|
||||
|
||||
export function SafeFarcasterSolanaProvider({
|
||||
endpoint,
|
||||
children,
|
||||
}: SafeFarcasterSolanaProviderProps) {
|
||||
const isClient = typeof window !== 'undefined';
|
||||
export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcasterSolanaProviderProps) {
|
||||
const isClient = typeof window !== "undefined";
|
||||
const [hasSolanaProvider, setHasSolanaProvider] = useState<boolean>(false);
|
||||
const [checked, setChecked] = useState<boolean>(false);
|
||||
|
||||
@@ -56,8 +48,8 @@ export function SafeFarcasterSolanaProvider({
|
||||
const origError = console.error;
|
||||
console.error = (...args) => {
|
||||
if (
|
||||
typeof args[0] === 'string' &&
|
||||
args[0].includes('WalletConnectionError: could not get Solana provider')
|
||||
typeof args[0] === "string" &&
|
||||
args[0].includes("WalletConnectionError: could not get Solana provider")
|
||||
) {
|
||||
if (!errorShown) {
|
||||
origError(...args);
|
||||
@@ -91,4 +83,4 @@ export function SafeFarcasterSolanaProvider({
|
||||
|
||||
export function useHasSolanaProvider() {
|
||||
return React.useContext(SolanaProviderContext).hasSolanaProvider;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import React from 'react';
|
||||
import { farcasterFrame } from '@farcaster/frame-wagmi-connector';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { createConfig, http, WagmiProvider } from 'wagmi';
|
||||
import { useConnect, useAccount } from 'wagmi';
|
||||
import { base, degen, mainnet, optimism, unichain, celo } from 'wagmi/chains';
|
||||
import { createConfig, http, WagmiProvider } from "wagmi";
|
||||
import { base, degen, mainnet, optimism, unichain, celo } from "wagmi/chains";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { farcasterFrame } from "@farcaster/miniapp-wagmi-connector";
|
||||
import { coinbaseWallet, metaMask } from 'wagmi/connectors';
|
||||
import { APP_NAME, APP_ICON_URL, APP_URL } from '~/lib/constants';
|
||||
import { APP_NAME, APP_ICON_URL, APP_URL } from "~/lib/constants";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useConnect, useAccount } from "wagmi";
|
||||
import React from "react";
|
||||
|
||||
// Custom hook for Coinbase Wallet detection and auto-connection
|
||||
function useCoinbaseWalletAutoConnect() {
|
||||
@@ -17,16 +17,15 @@ function useCoinbaseWalletAutoConnect() {
|
||||
useEffect(() => {
|
||||
// Check if we're running in Coinbase Wallet
|
||||
const checkCoinbaseWallet = () => {
|
||||
const isInCoinbaseWallet =
|
||||
window.ethereum?.isCoinbaseWallet ||
|
||||
const isInCoinbaseWallet = window.ethereum?.isCoinbaseWallet ||
|
||||
window.ethereum?.isCoinbaseWalletExtension ||
|
||||
window.ethereum?.isCoinbaseWalletBrowser;
|
||||
setIsCoinbaseWallet(!!isInCoinbaseWallet);
|
||||
};
|
||||
|
||||
|
||||
checkCoinbaseWallet();
|
||||
window.addEventListener('ethereum#initialized', checkCoinbaseWallet);
|
||||
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('ethereum#initialized', checkCoinbaseWallet);
|
||||
};
|
||||
@@ -71,11 +70,7 @@ export const config = createConfig({
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
// Wrapper component that provides Coinbase Wallet auto-connection
|
||||
function CoinbaseWalletAutoConnect({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
function CoinbaseWalletAutoConnect({ children }: { children: React.ReactNode }) {
|
||||
useCoinbaseWalletAutoConnect();
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -84,8 +79,10 @@ export default function Provider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<WagmiProvider config={config}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CoinbaseWalletAutoConnect>{children}</CoinbaseWalletAutoConnect>
|
||||
<CoinbaseWalletAutoConnect>
|
||||
{children}
|
||||
</CoinbaseWalletAutoConnect>
|
||||
</QueryClientProvider>
|
||||
</WagmiProvider>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useState } from 'react';
|
||||
import sdk from '@farcaster/frame-sdk';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { APP_NAME } from '~/lib/constants';
|
||||
import { useState } from "react";
|
||||
import { APP_NAME } from "~/lib/constants";
|
||||
import sdk from "@farcaster/miniapp-sdk";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
|
||||
type HeaderProps = {
|
||||
neynarUser?: {
|
||||
@@ -18,19 +18,23 @@ export function Header({ neynarUser }: HeaderProps) {
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="mt-4 mb-4 mx-4 px-2 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-between border-[3px] border-double border-primary">
|
||||
<div className="text-lg font-light">Welcome to {APP_NAME}!</div>
|
||||
<div
|
||||
className="mt-4 mb-4 mx-4 px-2 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-between border-[3px] border-double border-primary"
|
||||
>
|
||||
<div className="text-lg font-light">
|
||||
Welcome to {APP_NAME}!
|
||||
</div>
|
||||
{context?.user && (
|
||||
<div
|
||||
<div
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
setIsUserDropdownOpen(!isUserDropdownOpen);
|
||||
}}
|
||||
>
|
||||
{context.user.pfpUrl && (
|
||||
<img
|
||||
src={context.user.pfpUrl}
|
||||
alt="Profile"
|
||||
<img
|
||||
src={context.user.pfpUrl}
|
||||
alt="Profile"
|
||||
className="w-10 h-10 rounded-full border-2 border-primary"
|
||||
/>
|
||||
)}
|
||||
@@ -38,16 +42,14 @@ export function Header({ neynarUser }: HeaderProps) {
|
||||
)}
|
||||
</div>
|
||||
{context?.user && (
|
||||
<>
|
||||
<>
|
||||
{isUserDropdownOpen && (
|
||||
<div className="absolute top-full right-0 z-50 w-fit mt-1 mx-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="p-3 space-y-2">
|
||||
<div className="text-right">
|
||||
<h3
|
||||
<h3
|
||||
className="font-bold text-sm hover:underline cursor-pointer inline-block"
|
||||
onClick={() =>
|
||||
sdk.actions.viewProfile({ fid: context.user.fid })
|
||||
}
|
||||
onClick={() => sdk.actions.viewProfile({ fid: context.user.fid })}
|
||||
>
|
||||
{context.user.displayName || context.user.username}
|
||||
</h3>
|
||||
@@ -72,4 +74,4 @@ export function Header({ neynarUser }: HeaderProps) {
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
221
src/components/ui/NeynarAuthButton/AuthDialog.tsx
Normal file
221
src/components/ui/NeynarAuthButton/AuthDialog.tsx
Normal file
@@ -0,0 +1,221 @@
|
||||
'use client';
|
||||
|
||||
export function AuthDialog({
|
||||
open,
|
||||
onClose,
|
||||
url,
|
||||
isError,
|
||||
error,
|
||||
step,
|
||||
isLoading,
|
||||
signerApprovalUrl,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
url?: string;
|
||||
isError: boolean;
|
||||
error?: Error | null;
|
||||
step: 'signin' | 'access' | 'loading';
|
||||
isLoading?: boolean;
|
||||
signerApprovalUrl?: string | null;
|
||||
}) {
|
||||
if (!open) return null;
|
||||
|
||||
const getStepContent = () => {
|
||||
switch (step) {
|
||||
case 'signin':
|
||||
return {
|
||||
title: 'Sign in',
|
||||
description:
|
||||
"To sign in, scan the code below with your phone's camera.",
|
||||
showQR: true,
|
||||
qrUrl: url,
|
||||
showOpenButton: true,
|
||||
};
|
||||
|
||||
case 'loading':
|
||||
return {
|
||||
title: 'Setting up access...',
|
||||
description:
|
||||
'Checking your account permissions and setting up secure access.',
|
||||
showQR: false,
|
||||
qrUrl: '',
|
||||
showOpenButton: false,
|
||||
};
|
||||
|
||||
case 'access':
|
||||
return {
|
||||
title: 'Grant Access',
|
||||
description: (
|
||||
<div className="space-y-3">
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
Allow this app to access your Farcaster account:
|
||||
</p>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
<div className="w-6 h-6 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className="w-3 h-3 text-green-600 dark:text-green-400"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100">
|
||||
Read Access
|
||||
</div>
|
||||
<div className="text-gray-500 dark:text-gray-400">
|
||||
View your profile and public information
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
<div className="w-6 h-6 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className="w-3 h-3 text-blue-600 dark:text-blue-400"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100">
|
||||
Write Access
|
||||
</div>
|
||||
<div className="text-gray-500 dark:text-gray-400">
|
||||
Post casts, likes, and update your profile
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
// Show QR code if we have signer approval URL, otherwise show loading
|
||||
showQR: !!signerApprovalUrl,
|
||||
qrUrl: signerApprovalUrl || '',
|
||||
showOpenButton: !!signerApprovalUrl,
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
title: 'Sign in',
|
||||
description:
|
||||
"To signin, scan the code below with your phone's camera.",
|
||||
showQR: true,
|
||||
qrUrl: url,
|
||||
showOpenButton: true,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const content = getStepContent();
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-md shadow-2xl border border-gray-200 dark:border-gray-700 max-h-[80vh] sm:max-h-[90vh] flex flex-col">
|
||||
<div className="flex justify-between items-center p-4 sm:p-6 pb-3 sm:pb-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{isError ? 'Error' : content.title}
|
||||
</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4 sm:p-6 pt-3 sm:pt-4 min-h-0">
|
||||
{isError ? (
|
||||
<div className="text-center">
|
||||
<div className="text-red-600 dark:text-red-400 mb-4">
|
||||
{error?.message || 'Unknown error, please try again.'}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center">
|
||||
<div className="mb-6">
|
||||
{typeof content.description === 'string' ? (
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
{content.description}
|
||||
</p>
|
||||
) : (
|
||||
content.description
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mb-6 flex justify-center">
|
||||
{content.showQR && content.qrUrl ? (
|
||||
<div className="p-4 bg-white rounded-lg">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
|
||||
content.qrUrl
|
||||
)}`}
|
||||
alt="QR Code"
|
||||
className="w-48 h-48"
|
||||
/>
|
||||
</div>
|
||||
) : step === 'loading' || isLoading ? (
|
||||
<div className="w-48 h-48 flex items-center justify-center bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="spinner w-8 h-8" />
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{step === 'loading'
|
||||
? 'Setting up access...'
|
||||
: 'Loading...'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{content.showOpenButton && content.qrUrl && (
|
||||
<button
|
||||
onClick={() => {
|
||||
if (content.qrUrl) {
|
||||
window.open(
|
||||
content.qrUrl
|
||||
.replace(
|
||||
'https://farcaster.xyz/',
|
||||
'https://client.farcaster.xyz/deeplinks/'
|
||||
)
|
||||
.replace(
|
||||
'https://client.farcaster.xyz/deeplinks/signed-key-request',
|
||||
'https://farcaster.xyz/~/connect'
|
||||
),
|
||||
'_blank'
|
||||
)
|
||||
}
|
||||
}}
|
||||
className="btn btn-outline flex items-center justify-center gap-2 w-full"
|
||||
>
|
||||
I'm using my phone →
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
92
src/components/ui/NeynarAuthButton/ProfileButton.tsx
Normal file
92
src/components/ui/NeynarAuthButton/ProfileButton.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
'use client';
|
||||
|
||||
import { useRef, useState } from 'react';
|
||||
import { useDetectClickOutside } from '~/hooks/useDetectClickOutside';
|
||||
import { cn } from '~/lib/utils';
|
||||
|
||||
export function ProfileButton({
|
||||
userData,
|
||||
onSignOut,
|
||||
}: {
|
||||
userData?: { fid?: number; pfpUrl?: string; username?: string };
|
||||
onSignOut: () => void;
|
||||
}) {
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useDetectClickOutside(ref, () => setShowDropdown(false));
|
||||
|
||||
const name = userData?.username ?? `!${userData?.fid}`;
|
||||
const pfpUrl = userData?.pfpUrl ?? 'https://farcaster.xyz/avatar.png';
|
||||
|
||||
return (
|
||||
<div className="relative" ref={ref}>
|
||||
<button
|
||||
onClick={() => setShowDropdown(!showDropdown)}
|
||||
className={cn(
|
||||
'flex items-center gap-3 px-4 py-2 min-w-0 rounded-lg',
|
||||
'bg-transparent border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100',
|
||||
'hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors',
|
||||
'focus:outline-none focus:ring-1 focus:ring-primary'
|
||||
)}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={pfpUrl}
|
||||
alt="Profile"
|
||||
className="w-6 h-6 rounded-full object-cover flex-shrink-0"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).src =
|
||||
'https://farcaster.xyz/avatar.png';
|
||||
}}
|
||||
/>
|
||||
<span className="text-sm font-medium truncate max-w-[120px]">
|
||||
{name ? name : '...'}
|
||||
</span>
|
||||
<svg
|
||||
className={cn(
|
||||
'w-4 h-4 transition-transform flex-shrink-0',
|
||||
showDropdown && 'rotate-180'
|
||||
)}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{showDropdown && (
|
||||
<div className="absolute top-full right-0 left-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-50">
|
||||
<button
|
||||
onClick={() => {
|
||||
onSignOut();
|
||||
setShowDropdown(false);
|
||||
}}
|
||||
className="w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 rounded-lg transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
|
||||
/>
|
||||
</svg>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
705
src/components/ui/NeynarAuthButton/index.tsx
Normal file
705
src/components/ui/NeynarAuthButton/index.tsx
Normal file
@@ -0,0 +1,705 @@
|
||||
'use client';
|
||||
|
||||
import '@farcaster/auth-kit/styles.css';
|
||||
import { useSignIn, UseSignInData } from '@farcaster/auth-kit';
|
||||
import { useCallback, useEffect, useState, useRef } from 'react';
|
||||
import { cn } from '~/lib/utils';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { ProfileButton } from '~/components/ui/NeynarAuthButton/ProfileButton';
|
||||
import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
|
||||
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import {
|
||||
signIn as backendSignIn,
|
||||
signOut as backendSignOut,
|
||||
useSession,
|
||||
} from 'next-auth/react';
|
||||
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
|
||||
|
||||
type User = {
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
// Add other user properties as needed
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'neynar_authenticated_user';
|
||||
const FARCASTER_FID = 9152;
|
||||
|
||||
interface StoredAuthState {
|
||||
isAuthenticated: boolean;
|
||||
user: {
|
||||
object: 'user';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
profile: {
|
||||
bio: {
|
||||
text: string;
|
||||
mentioned_profiles?: Array<{
|
||||
object: 'user_dehydrated';
|
||||
fid: number;
|
||||
username: string;
|
||||
display_name: string;
|
||||
pfp_url: string;
|
||||
custody_address: string;
|
||||
}>;
|
||||
mentioned_profiles_ranges?: Array<{
|
||||
start: number;
|
||||
end: number;
|
||||
}>;
|
||||
};
|
||||
location?: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
address: {
|
||||
city: string;
|
||||
state: string;
|
||||
country: string;
|
||||
country_code: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
follower_count: number;
|
||||
following_count: number;
|
||||
verifications: string[];
|
||||
verified_addresses: {
|
||||
eth_addresses: string[];
|
||||
sol_addresses: string[];
|
||||
primary: {
|
||||
eth_address: string;
|
||||
sol_address: string;
|
||||
};
|
||||
};
|
||||
verified_accounts: Array<Record<string, unknown>>;
|
||||
power_badge: boolean;
|
||||
url?: string;
|
||||
experimental?: {
|
||||
neynar_user_score: number;
|
||||
deprecation_notice: string;
|
||||
};
|
||||
score: number;
|
||||
} | null;
|
||||
signers: {
|
||||
object: 'signer';
|
||||
signer_uuid: string;
|
||||
public_key: string;
|
||||
status: 'approved';
|
||||
fid: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
// Main Custom SignInButton Component
|
||||
export function NeynarAuthButton() {
|
||||
const [nonce, setNonce] = useState<string | null>(null);
|
||||
const [storedAuth, setStoredAuth] = useState<StoredAuthState | null>(null);
|
||||
const [signersLoading, setSignersLoading] = useState(false);
|
||||
const { context } = useMiniApp();
|
||||
const { data: session } = useSession();
|
||||
// New state for unified dialog flow
|
||||
const [showDialog, setShowDialog] = useState(false);
|
||||
const [dialogStep, setDialogStep] = useState<'signin' | 'access' | 'loading'>(
|
||||
'loading'
|
||||
);
|
||||
const [signerApprovalUrl, setSignerApprovalUrl] = useState<string | null>(
|
||||
null
|
||||
);
|
||||
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(
|
||||
null
|
||||
);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [signature, setSignature] = useState<string | null>(null);
|
||||
const [isSignerFlowRunning, setIsSignerFlowRunning] = useState(false);
|
||||
const signerFlowStartedRef = useRef(false);
|
||||
|
||||
// Determine which flow to use based on context
|
||||
const useBackendFlow = context !== undefined;
|
||||
|
||||
// Helper function to create a signer
|
||||
const createSigner = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/auth/signer', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to create signer');
|
||||
}
|
||||
|
||||
const signerData = await response.json();
|
||||
return signerData;
|
||||
} catch (error) {
|
||||
console.error('❌ Error creating signer:', error);
|
||||
// throw error;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Helper function to update session with signers (backend flow only)
|
||||
const updateSessionWithSigners = useCallback(
|
||||
async (
|
||||
signers: StoredAuthState['signers'],
|
||||
user: StoredAuthState['user']
|
||||
) => {
|
||||
if (!useBackendFlow) return;
|
||||
|
||||
try {
|
||||
// For backend flow, we need to sign in again with the additional data
|
||||
if (message && signature) {
|
||||
const signInData = {
|
||||
message,
|
||||
signature,
|
||||
redirect: false,
|
||||
nonce: nonce || '',
|
||||
fid: user?.fid?.toString() || '',
|
||||
signers: JSON.stringify(signers),
|
||||
user: JSON.stringify(user),
|
||||
};
|
||||
|
||||
await backendSignIn('neynar', signInData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error updating session with signers:', error);
|
||||
}
|
||||
},
|
||||
[useBackendFlow, message, signature, nonce]
|
||||
);
|
||||
|
||||
// Helper function to fetch user data from Neynar API
|
||||
const fetchUserData = useCallback(
|
||||
async (fid: number): Promise<User | null> => {
|
||||
try {
|
||||
const response = await fetch(`/api/users?fids=${fid}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return data.users?.[0] || null;
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error fetching user data:', error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Helper function to generate signed key request
|
||||
const generateSignedKeyRequest = useCallback(
|
||||
async (signerUuid: string, publicKey: string) => {
|
||||
try {
|
||||
// Prepare request body
|
||||
const requestBody: {
|
||||
signerUuid: string;
|
||||
publicKey: string;
|
||||
sponsor?: { sponsored_by_neynar: boolean };
|
||||
} = {
|
||||
signerUuid,
|
||||
publicKey,
|
||||
};
|
||||
|
||||
const response = await fetch('/api/auth/signer/signed_key', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
`Failed to generate signed key request: ${errorData.error}`
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('❌ Error generating signed key request:', error);
|
||||
// throw error;
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Helper function to fetch all signers
|
||||
const fetchAllSigners = useCallback(
|
||||
async (message: string, signature: string) => {
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
|
||||
const endpoint = useBackendFlow
|
||||
? `/api/auth/session-signers?message=${encodeURIComponent(
|
||||
message
|
||||
)}&signature=${signature}`
|
||||
: `/api/auth/signers?message=${encodeURIComponent(
|
||||
message
|
||||
)}&signature=${signature}`;
|
||||
|
||||
const response = await fetch(endpoint);
|
||||
const signerData = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
if (useBackendFlow) {
|
||||
// For backend flow, update session with signers
|
||||
if (signerData.signers && signerData.signers.length > 0) {
|
||||
const user =
|
||||
signerData.user ||
|
||||
(await fetchUserData(signerData.signers[0].fid));
|
||||
await updateSessionWithSigners(signerData.signers, user);
|
||||
}
|
||||
return signerData.signers;
|
||||
} else {
|
||||
// For frontend flow, store in localStorage
|
||||
let user: StoredAuthState['user'] | null = null;
|
||||
|
||||
if (signerData.signers && signerData.signers.length > 0) {
|
||||
const fetchedUser = (await fetchUserData(
|
||||
signerData.signers[0].fid
|
||||
)) as StoredAuthState['user'];
|
||||
user = fetchedUser;
|
||||
}
|
||||
|
||||
// Store signers in localStorage, preserving existing auth data
|
||||
const updatedState: StoredAuthState = {
|
||||
isAuthenticated: !!user,
|
||||
signers: signerData.signers || [],
|
||||
user,
|
||||
};
|
||||
setItem<StoredAuthState>(STORAGE_KEY, updatedState);
|
||||
setStoredAuth(updatedState);
|
||||
|
||||
return signerData.signers;
|
||||
}
|
||||
} else {
|
||||
console.error('❌ Failed to fetch signers');
|
||||
// throw new Error('Failed to fetch signers');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error fetching signers:', error);
|
||||
// throw error;
|
||||
} finally {
|
||||
setSignersLoading(false);
|
||||
}
|
||||
},
|
||||
[useBackendFlow, fetchUserData, updateSessionWithSigners]
|
||||
);
|
||||
|
||||
// Helper function to poll signer status
|
||||
const startPolling = useCallback(
|
||||
(signerUuid: string, message: string, signature: string) => {
|
||||
// Clear any existing polling interval before starting a new one
|
||||
if (pollingInterval) {
|
||||
clearInterval(pollingInterval);
|
||||
}
|
||||
|
||||
let retryCount = 0;
|
||||
const maxRetries = 10; // Maximum 10 retries (20 seconds total)
|
||||
const maxPollingTime = 60000; // Maximum 60 seconds of polling
|
||||
const startTime = Date.now();
|
||||
|
||||
const interval = setInterval(async () => {
|
||||
// Check if we've been polling too long
|
||||
if (Date.now() - startTime > maxPollingTime) {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/auth/signer?signerUuid=${signerUuid}`
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
// Check if it's a rate limit error
|
||||
if (response.status === 429) {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Increment retry count for other errors
|
||||
retryCount++;
|
||||
if (retryCount >= maxRetries) {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Failed to poll signer status: ${response.status}`);
|
||||
}
|
||||
|
||||
const signerData = await response.json();
|
||||
|
||||
if (signerData.status === 'approved') {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
setShowDialog(false);
|
||||
setDialogStep('signin');
|
||||
setSignerApprovalUrl(null);
|
||||
|
||||
// Refetch all signers
|
||||
await fetchAllSigners(message, signature);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error polling signer:', error);
|
||||
}
|
||||
}, 2000); // Poll every 2 second
|
||||
|
||||
setPollingInterval(interval);
|
||||
},
|
||||
[fetchAllSigners, pollingInterval]
|
||||
);
|
||||
|
||||
// Cleanup polling on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (pollingInterval) {
|
||||
clearInterval(pollingInterval);
|
||||
}
|
||||
signerFlowStartedRef.current = false;
|
||||
};
|
||||
}, [pollingInterval]);
|
||||
|
||||
// Generate nonce
|
||||
useEffect(() => {
|
||||
const generateNonce = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/auth/nonce');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setNonce(data.nonce);
|
||||
} else {
|
||||
console.error('Failed to fetch nonce');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error generating nonce:', error);
|
||||
}
|
||||
};
|
||||
|
||||
generateNonce();
|
||||
}, []);
|
||||
|
||||
// Load stored auth state on mount (only for frontend flow)
|
||||
useEffect(() => {
|
||||
if (!useBackendFlow) {
|
||||
const stored = getItem<StoredAuthState>(STORAGE_KEY);
|
||||
if (stored && stored.isAuthenticated) {
|
||||
setStoredAuth(stored);
|
||||
}
|
||||
}
|
||||
}, [useBackendFlow]);
|
||||
|
||||
// Success callback - this is critical!
|
||||
const onSuccessCallback = useCallback(
|
||||
async (res: UseSignInData) => {
|
||||
if (!useBackendFlow) {
|
||||
// Only handle localStorage for frontend flow
|
||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||
const user = res.fid ? await fetchUserData(res.fid) : null;
|
||||
const authState: StoredAuthState = {
|
||||
...existingAuth,
|
||||
isAuthenticated: true,
|
||||
user: user as StoredAuthState['user'],
|
||||
signers: existingAuth?.signers || [], // Preserve existing signers
|
||||
};
|
||||
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
||||
setStoredAuth(authState);
|
||||
}
|
||||
// For backend flow, the session will be handled by NextAuth
|
||||
},
|
||||
[useBackendFlow, fetchUserData]
|
||||
);
|
||||
|
||||
// Error callback
|
||||
const onErrorCallback = useCallback((error?: Error | null) => {
|
||||
console.error('❌ Sign in error:', error);
|
||||
}, []);
|
||||
|
||||
const signInState = useSignIn({
|
||||
nonce: nonce || undefined,
|
||||
onSuccess: onSuccessCallback,
|
||||
onError: onErrorCallback,
|
||||
});
|
||||
|
||||
const {
|
||||
signIn: frontendSignIn,
|
||||
signOut: frontendSignOut,
|
||||
connect,
|
||||
reconnect,
|
||||
isSuccess,
|
||||
isError,
|
||||
error,
|
||||
channelToken,
|
||||
url,
|
||||
data,
|
||||
validSignature,
|
||||
} = signInState;
|
||||
|
||||
useEffect(() => {
|
||||
setMessage(data?.message || null);
|
||||
setSignature(data?.signature || null);
|
||||
|
||||
// Reset the signer flow flag when message/signature change
|
||||
if (data?.message && data?.signature) {
|
||||
signerFlowStartedRef.current = false;
|
||||
}
|
||||
}, [data?.message, data?.signature]);
|
||||
|
||||
// Connect for frontend flow when nonce is available
|
||||
useEffect(() => {
|
||||
if (!useBackendFlow && nonce && !channelToken) {
|
||||
connect();
|
||||
}
|
||||
}, [useBackendFlow, nonce, channelToken, connect]);
|
||||
|
||||
// Handle fetching signers after successful authentication
|
||||
useEffect(() => {
|
||||
if (message && signature && !isSignerFlowRunning && !signerFlowStartedRef.current) {
|
||||
signerFlowStartedRef.current = true;
|
||||
|
||||
const handleSignerFlow = async () => {
|
||||
setIsSignerFlowRunning(true);
|
||||
try {
|
||||
const clientContext = context?.client as Record<string, unknown>;
|
||||
const isMobileContext =
|
||||
clientContext?.platformType === 'mobile' &&
|
||||
clientContext?.clientFid === FARCASTER_FID;
|
||||
|
||||
// Step 1: Change to loading state
|
||||
setDialogStep('loading');
|
||||
|
||||
// Show dialog if not using backend flow or in browser farcaster
|
||||
if ((useBackendFlow && !isMobileContext) || !useBackendFlow)
|
||||
setShowDialog(true);
|
||||
|
||||
// First, fetch existing signers
|
||||
const signers = await fetchAllSigners(message, signature);
|
||||
|
||||
if (useBackendFlow && isMobileContext) setSignersLoading(true);
|
||||
|
||||
// Check if no signers exist or if we have empty signers
|
||||
if (!signers || signers.length === 0) {
|
||||
// Step 1: Create a signer
|
||||
const newSigner = await createSigner();
|
||||
|
||||
// Step 2: Generate signed key request
|
||||
const signedKeyData = await generateSignedKeyRequest(
|
||||
newSigner.signer_uuid,
|
||||
newSigner.public_key
|
||||
);
|
||||
|
||||
// Step 3: Show QR code in access dialog for signer approval
|
||||
setSignerApprovalUrl(signedKeyData.signer_approval_url);
|
||||
|
||||
if (isMobileContext) {
|
||||
setShowDialog(false);
|
||||
await sdk.actions.openUrl(
|
||||
signedKeyData.signer_approval_url.replace(
|
||||
'https://client.farcaster.xyz/deeplinks/signed-key-request',
|
||||
'https://farcaster.xyz/~/connect'
|
||||
)
|
||||
);
|
||||
} else {
|
||||
setShowDialog(true); // Ensure dialog is shown during loading
|
||||
setDialogStep('access');
|
||||
}
|
||||
|
||||
// Step 4: Start polling for signer approval
|
||||
startPolling(newSigner.signer_uuid, message, signature);
|
||||
} else {
|
||||
// If signers exist, close the dialog
|
||||
setSignersLoading(false);
|
||||
setShowDialog(false);
|
||||
setDialogStep('signin');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error in signer flow:', error);
|
||||
// On error, reset to signin step and hide dialog
|
||||
setDialogStep('signin');
|
||||
setSignersLoading(false);
|
||||
setShowDialog(false);
|
||||
setSignerApprovalUrl(null);
|
||||
} finally {
|
||||
setIsSignerFlowRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
handleSignerFlow();
|
||||
}
|
||||
}, [message, signature]); // Simplified dependencies
|
||||
|
||||
// Backend flow using NextAuth
|
||||
const handleBackendSignIn = useCallback(async () => {
|
||||
if (!nonce) {
|
||||
console.error('❌ No nonce available for backend sign-in');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
const result = await sdk.actions.signIn({ nonce });
|
||||
|
||||
const signInData = {
|
||||
message: result.message,
|
||||
signature: result.signature,
|
||||
redirect: false,
|
||||
nonce: nonce,
|
||||
};
|
||||
|
||||
const nextAuthResult = await backendSignIn('neynar', signInData);
|
||||
if (nextAuthResult?.ok) {
|
||||
setMessage(result.message);
|
||||
setSignature(result.signature);
|
||||
} else {
|
||||
console.error('❌ NextAuth sign-in failed:', nextAuthResult);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof SignInCore.RejectedByUser) {
|
||||
console.log('ℹ️ Sign-in rejected by user');
|
||||
} else {
|
||||
console.error('❌ Backend sign-in error:', e);
|
||||
}
|
||||
}
|
||||
}, [nonce]);
|
||||
|
||||
const handleFrontEndSignIn = useCallback(() => {
|
||||
if (isError) {
|
||||
reconnect();
|
||||
}
|
||||
setDialogStep('signin');
|
||||
setShowDialog(true);
|
||||
frontendSignIn();
|
||||
}, [isError, reconnect, frontendSignIn]);
|
||||
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
|
||||
if (useBackendFlow) {
|
||||
// Only sign out from NextAuth if the current session is from Neynar provider
|
||||
if (session?.provider === 'neynar') {
|
||||
await backendSignOut({ redirect: false });
|
||||
}
|
||||
} else {
|
||||
// Frontend flow sign out
|
||||
frontendSignOut();
|
||||
removeItem(STORAGE_KEY);
|
||||
setStoredAuth(null);
|
||||
}
|
||||
|
||||
// Common cleanup for both flows
|
||||
setShowDialog(false);
|
||||
setDialogStep('signin');
|
||||
setSignerApprovalUrl(null);
|
||||
setMessage(null);
|
||||
setSignature(null);
|
||||
|
||||
// Reset polling interval
|
||||
if (pollingInterval) {
|
||||
clearInterval(pollingInterval);
|
||||
setPollingInterval(null);
|
||||
}
|
||||
|
||||
// Reset signer flow flag
|
||||
signerFlowStartedRef.current = false;
|
||||
} catch (error) {
|
||||
console.error('❌ Error during sign out:', error);
|
||||
// Optionally handle error state
|
||||
} finally {
|
||||
setSignersLoading(false);
|
||||
}
|
||||
}, [useBackendFlow, frontendSignOut, pollingInterval, session]);
|
||||
|
||||
const authenticated = useBackendFlow
|
||||
? !!(
|
||||
session?.provider === 'neynar' &&
|
||||
session?.user?.fid &&
|
||||
session?.signers &&
|
||||
session.signers.length > 0
|
||||
)
|
||||
: ((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
||||
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||
|
||||
const userData = useBackendFlow
|
||||
? {
|
||||
fid: session?.user?.fid,
|
||||
username: session?.user?.username || '',
|
||||
pfpUrl: session?.user?.pfp_url || '',
|
||||
}
|
||||
: {
|
||||
fid: storedAuth?.user?.fid,
|
||||
username: storedAuth?.user?.username || '',
|
||||
pfpUrl: storedAuth?.user?.pfp_url || '',
|
||||
};
|
||||
|
||||
// Show loading state while nonce is being fetched or signers are loading
|
||||
if (!nonce || signersLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="flex items-center gap-3 px-4 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||
<div className="spinner w-4 h-4" />
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Loading...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{authenticated ? (
|
||||
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
||||
) : (
|
||||
<Button
|
||||
onClick={useBackendFlow ? handleBackendSignIn : handleFrontEndSignIn}
|
||||
disabled={!useBackendFlow && !url}
|
||||
className={cn(
|
||||
'btn btn-primary flex items-center gap-3',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
'transform transition-all duration-200 active:scale-[0.98]',
|
||||
!url && !useBackendFlow && 'cursor-not-allowed'
|
||||
)}
|
||||
>
|
||||
{!useBackendFlow && !url ? (
|
||||
<>
|
||||
<div className="spinner-primary w-5 h-5" />
|
||||
<span>Initializing...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>Sign in with Neynar</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Unified Auth Dialog */}
|
||||
{
|
||||
<AuthDialog
|
||||
open={showDialog}
|
||||
onClose={() => {
|
||||
setShowDialog(false);
|
||||
setDialogStep('signin');
|
||||
setSignerApprovalUrl(null);
|
||||
if (pollingInterval) {
|
||||
clearInterval(pollingInterval);
|
||||
setPollingInterval(null);
|
||||
}
|
||||
}}
|
||||
url={url}
|
||||
isError={isError}
|
||||
error={error}
|
||||
step={dialogStep}
|
||||
isLoading={signersLoading}
|
||||
signerApprovalUrl={signerApprovalUrl}
|
||||
/>
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState, useEffect } from 'react';
|
||||
import { type ComposeCast } from '@farcaster/frame-sdk';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { Button } from './Button';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { type ComposeCast } from "@farcaster/miniapp-sdk";
|
||||
|
||||
interface EmbedConfig {
|
||||
path?: string;
|
||||
@@ -23,16 +23,9 @@ interface ShareButtonProps {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function ShareButton({
|
||||
buttonText,
|
||||
cast,
|
||||
className = '',
|
||||
isLoading = false,
|
||||
}: ShareButtonProps) {
|
||||
export function ShareButton({ buttonText, cast, className = '', isLoading = false }: ShareButtonProps) {
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [bestFriends, setBestFriends] = useState<
|
||||
{ fid: number; username: string }[] | null
|
||||
>(null);
|
||||
const [bestFriends, setBestFriends] = useState<{ fid: number; username: string; }[] | null>(null);
|
||||
const [isLoadingBestFriends, setIsLoadingBestFriends] = useState(false);
|
||||
const { context, actions } = useMiniApp();
|
||||
|
||||
@@ -58,7 +51,7 @@ export function ShareButton({
|
||||
if (cast.bestFriends) {
|
||||
if (bestFriends) {
|
||||
// Replace @N with usernames, or remove if no matching friend
|
||||
finalText = finalText.replace(/@\d+/g, match => {
|
||||
finalText = finalText.replace(/@\d+/g, (match) => {
|
||||
const friendIndex = parseInt(match.slice(1)) - 1;
|
||||
const friend = bestFriends[friendIndex];
|
||||
if (friend) {
|
||||
@@ -74,20 +67,16 @@ export function ShareButton({
|
||||
|
||||
// Process embeds
|
||||
const processedEmbeds = await Promise.all(
|
||||
(cast.embeds || []).map(async embed => {
|
||||
(cast.embeds || []).map(async (embed) => {
|
||||
if (typeof embed === 'string') {
|
||||
return embed;
|
||||
}
|
||||
if (embed.path) {
|
||||
const baseUrl =
|
||||
process.env.NEXT_PUBLIC_URL || window.location.origin;
|
||||
const baseUrl = process.env.NEXT_PUBLIC_URL || window.location.origin;
|
||||
const url = new URL(`${baseUrl}${embed.path}`);
|
||||
|
||||
// Add UTM parameters
|
||||
url.searchParams.set(
|
||||
'utm_source',
|
||||
`share-cast-${context?.user?.fid || 'unknown'}`,
|
||||
);
|
||||
url.searchParams.set('utm_source', `share-cast-${context?.user?.fid || 'unknown'}`);
|
||||
|
||||
// If custom image generator is provided, use it
|
||||
if (embed.imageUrl) {
|
||||
@@ -98,7 +87,7 @@ export function ShareButton({
|
||||
return url.toString();
|
||||
}
|
||||
return embed.url || '';
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
// Open cast composer with all supported intents
|
||||
@@ -126,4 +115,4 @@ export function ShareButton({
|
||||
{buttonText}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { type Haptics } from '@farcaster/frame-sdk';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { Button } from '../Button';
|
||||
import { ShareButton } from '../Share';
|
||||
import { SignIn } from '../wallet/SignIn';
|
||||
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 { NeynarAuthButton } from '../NeynarAuthButton/index';
|
||||
|
||||
/**
|
||||
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
|
||||
@@ -50,7 +51,7 @@ export function ActionsTab() {
|
||||
* @returns Promise that resolves when the notification is sent or fails
|
||||
*/
|
||||
const sendFarcasterNotification = useCallback(async () => {
|
||||
setNotificationState(prev => ({ ...prev, sendStatus: '' }));
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: '' }));
|
||||
if (!notificationDetails || !context) {
|
||||
return;
|
||||
}
|
||||
@@ -65,19 +66,22 @@ export function ActionsTab() {
|
||||
}),
|
||||
});
|
||||
if (response.status === 200) {
|
||||
setNotificationState(prev => ({ ...prev, sendStatus: 'Success' }));
|
||||
setNotificationState((prev) => ({ ...prev, sendStatus: 'Success' }));
|
||||
return;
|
||||
} else if (response.status === 429) {
|
||||
setNotificationState(prev => ({ ...prev, sendStatus: 'Rate limited' }));
|
||||
setNotificationState((prev) => ({
|
||||
...prev,
|
||||
sendStatus: 'Rate limited',
|
||||
}));
|
||||
return;
|
||||
}
|
||||
const responseText = await response.text();
|
||||
setNotificationState(prev => ({
|
||||
setNotificationState((prev) => ({
|
||||
...prev,
|
||||
sendStatus: `Error: ${responseText}`,
|
||||
}));
|
||||
} catch (error) {
|
||||
setNotificationState(prev => ({
|
||||
setNotificationState((prev) => ({
|
||||
...prev,
|
||||
sendStatus: `Error: ${error}`,
|
||||
}));
|
||||
@@ -94,11 +98,11 @@ export function ActionsTab() {
|
||||
if (context?.user?.fid) {
|
||||
const userShareUrl = `${process.env.NEXT_PUBLIC_URL}/share/${context.user.fid}`;
|
||||
await navigator.clipboard.writeText(userShareUrl);
|
||||
setNotificationState(prev => ({ ...prev, shareUrlCopied: true }));
|
||||
setNotificationState((prev) => ({ ...prev, shareUrlCopied: true }));
|
||||
setTimeout(
|
||||
() =>
|
||||
setNotificationState(prev => ({ ...prev, shareUrlCopied: false })),
|
||||
2000,
|
||||
setNotificationState((prev) => ({ ...prev, shareUrlCopied: false })),
|
||||
2000
|
||||
);
|
||||
}
|
||||
}, [context?.user?.fid]);
|
||||
@@ -119,10 +123,10 @@ export function ActionsTab() {
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
|
||||
<div className='space-y-3 px-6 w-full max-w-md mx-auto'>
|
||||
{/* Share functionality */}
|
||||
<ShareButton
|
||||
buttonText="Share Mini App"
|
||||
buttonText='Share Mini App'
|
||||
cast={{
|
||||
text: 'Check out this awesome frame @1 @2 @3! 🚀🪐',
|
||||
bestFriends: true,
|
||||
@@ -130,36 +134,39 @@ export function ActionsTab() {
|
||||
`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`,
|
||||
],
|
||||
}}
|
||||
className="w-full"
|
||||
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"
|
||||
className='w-full'
|
||||
>
|
||||
Open Link
|
||||
</Button>
|
||||
|
||||
<Button onClick={actions.addMiniApp} disabled={added} className="w-full">
|
||||
<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">
|
||||
<div className='text-sm w-full'>
|
||||
Send notification result: {notificationState.sendStatus}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={sendFarcasterNotification}
|
||||
disabled={!notificationDetails}
|
||||
className="w-full"
|
||||
className='w-full'
|
||||
>
|
||||
Send notification
|
||||
</Button>
|
||||
@@ -168,24 +175,24 @@ export function ActionsTab() {
|
||||
<Button
|
||||
onClick={copyUserShareUrl}
|
||||
disabled={!context?.user?.fid}
|
||||
className="w-full"
|
||||
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">
|
||||
<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 =>
|
||||
onChange={(e) =>
|
||||
setSelectedHapticIntensity(
|
||||
e.target.value as Haptics.ImpactOccurredType,
|
||||
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"
|
||||
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>
|
||||
@@ -193,10 +200,10 @@ export function ActionsTab() {
|
||||
<option value={'soft'}>Soft</option>
|
||||
<option value={'rigid'}>Rigid</option>
|
||||
</select>
|
||||
<Button onClick={triggerHapticFeedback} className="w-full">
|
||||
<Button onClick={triggerHapticFeedback} className='w-full'>
|
||||
Trigger Haptic Feedback
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export function HomeTab() {
|
||||
<div className="flex items-center justify-center h-[calc(100vh-200px)] px-6">
|
||||
<div className="text-center w-full max-w-md mx-auto">
|
||||
<p className="text-lg mb-2">Put your content here!</p>
|
||||
<p className="text-sm text-gray-500">Powered by Neynar 🪐</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Powered by Neynar 🪐</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
|
||||
import { signIn, signOut, getCsrfToken } from 'next-auth/react';
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { Button } from '../Button';
|
||||
import { useCallback, useState } from "react";
|
||||
import { signIn, signOut, getCsrfToken } from "next-auth/react";
|
||||
import sdk, { SignIn as SignInCore } from "@farcaster/miniapp-sdk";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { Button } from "../Button";
|
||||
|
||||
/**
|
||||
* SignIn component handles Farcaster authentication using Sign-In with Farcaster (SIWF).
|
||||
@@ -72,12 +72,12 @@ export function SignIn() {
|
||||
*/
|
||||
const handleSignIn = useCallback(async () => {
|
||||
try {
|
||||
setAuthState(prev => ({ ...prev, signingIn: true }));
|
||||
setAuthState((prev) => ({ ...prev, signingIn: true }));
|
||||
setSignInFailure(undefined);
|
||||
const nonce = await getNonce();
|
||||
const result = await sdk.actions.signIn({ nonce });
|
||||
setSignInResult(result);
|
||||
await signIn('credentials', {
|
||||
await signIn('farcaster', {
|
||||
message: result.message,
|
||||
signature: result.signature,
|
||||
redirect: false,
|
||||
@@ -89,38 +89,41 @@ export function SignIn() {
|
||||
}
|
||||
setSignInFailure('Unknown error');
|
||||
} finally {
|
||||
setAuthState(prev => ({ ...prev, signingIn: false }));
|
||||
setAuthState((prev) => ({ ...prev, signingIn: false }));
|
||||
}
|
||||
}, [getNonce]);
|
||||
|
||||
/**
|
||||
* Handles the sign-out process.
|
||||
*
|
||||
* This function clears the NextAuth session and resets the local
|
||||
* sign-in result state to complete the sign-out flow.
|
||||
* This function clears the NextAuth session only if the current session
|
||||
* is using the Farcaster provider, and resets the local sign-in result state.
|
||||
*
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setAuthState(prev => ({ ...prev, signingOut: true }));
|
||||
await signOut({ redirect: false });
|
||||
setAuthState((prev) => ({ ...prev, signingOut: true }));
|
||||
// Only sign out if the current session is from Farcaster provider
|
||||
if (session?.provider === 'farcaster') {
|
||||
await signOut({ redirect: false });
|
||||
}
|
||||
setSignInResult(undefined);
|
||||
} finally {
|
||||
setAuthState(prev => ({ ...prev, signingOut: false }));
|
||||
setAuthState((prev) => ({ ...prev, signingOut: false }));
|
||||
}
|
||||
}, []);
|
||||
}, [session]);
|
||||
|
||||
// --- Render ---
|
||||
return (
|
||||
<>
|
||||
{/* Authentication Buttons */}
|
||||
{status !== 'authenticated' && (
|
||||
{(status !== 'authenticated' || session?.provider !== 'farcaster') && (
|
||||
<Button onClick={handleSignIn} disabled={authState.signingIn}>
|
||||
Sign In with Farcaster
|
||||
</Button>
|
||||
)}
|
||||
{status === 'authenticated' && (
|
||||
{status === 'authenticated' && session?.provider === 'farcaster' && (
|
||||
<Button onClick={handleSignOut} disabled={authState.signingOut}>
|
||||
Sign out
|
||||
</Button>
|
||||
@@ -128,9 +131,9 @@ export function SignIn() {
|
||||
|
||||
{/* Session Information */}
|
||||
{session && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">Session</div>
|
||||
<div className="whitespace-pre">
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-900 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">Session</div>
|
||||
<div className="whitespace-pre text-gray-700 dark:text-gray-200">
|
||||
{JSON.stringify(session, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -138,21 +141,21 @@ export function SignIn() {
|
||||
|
||||
{/* Error Display */}
|
||||
{signInFailure && !authState.signingIn && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre">{signInFailure}</div>
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-900 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre text-gray-700 dark:text-gray-200">{signInFailure}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success Result Display */}
|
||||
{signInResult && !authState.signingIn && (
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre">
|
||||
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-900 rounded-lg font-mono">
|
||||
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">SIWF Result</div>
|
||||
<div className="whitespace-pre text-gray-700 dark:text-gray-200">
|
||||
{JSON.stringify(signInResult, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
18
src/hooks/useDetectClickOutside.ts
Normal file
18
src/hooks/useDetectClickOutside.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export function useDetectClickOutside<T extends HTMLElement>(
|
||||
ref: React.RefObject<T | null>,
|
||||
callback: () => void
|
||||
) {
|
||||
useEffect(() => {
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(event.target as Node)) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [ref, callback]);
|
||||
}
|
||||
@@ -20,19 +20,19 @@ export const APP_URL = process.env.NEXT_PUBLIC_URL!;
|
||||
* The name of the mini app as displayed to users.
|
||||
* Used in titles, headers, and app store listings.
|
||||
*/
|
||||
export const APP_NAME = 'Starter Kit';
|
||||
export const APP_NAME = 'shreyas-testing-mini-app';
|
||||
|
||||
/**
|
||||
* A brief description of the mini app's functionality.
|
||||
* Used in app store listings and metadata.
|
||||
*/
|
||||
export const APP_DESCRIPTION = 'A demo of the Neynar Starter Kit';
|
||||
export const APP_DESCRIPTION = 'A Farcaster mini app created with Neynar';
|
||||
|
||||
/**
|
||||
* The primary category for the mini app.
|
||||
* Used for app store categorization and discovery.
|
||||
*/
|
||||
export const APP_PRIMARY_CATEGORY = 'developer-tools';
|
||||
export const APP_PRIMARY_CATEGORY = '';
|
||||
|
||||
/**
|
||||
* Tags associated with the mini app.
|
||||
@@ -70,7 +70,7 @@ export const APP_SPLASH_BACKGROUND_COLOR = '#f7f7f7';
|
||||
* Text displayed on the main action button.
|
||||
* Used for the primary call-to-action in the mini app.
|
||||
*/
|
||||
export const APP_BUTTON_TEXT = 'Launch NSK';
|
||||
export const APP_BUTTON_TEXT = 'Launch Mini App';
|
||||
|
||||
// --- Integration Configuration ---
|
||||
/**
|
||||
@@ -102,3 +102,19 @@ export const USE_WALLET = true;
|
||||
* Useful for privacy-conscious users or development environments.
|
||||
*/
|
||||
export const ANALYTICS_ENABLED = true;
|
||||
|
||||
// PLEASE DO NOT UPDATE THIS
|
||||
export const SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN = {
|
||||
name: 'Farcaster SignedKeyRequestValidator',
|
||||
version: '1',
|
||||
chainId: 10,
|
||||
verifyingContract:
|
||||
'0x00000000fc700472606ed4fa22623acf62c60553' as `0x${string}`,
|
||||
};
|
||||
|
||||
// PLEASE DO NOT UPDATE THIS
|
||||
export const SIGNED_KEY_REQUEST_TYPE = [
|
||||
{ name: 'requestFid', type: 'uint256' },
|
||||
{ name: 'key', type: 'bytes' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
];
|
||||
|
||||
27
src/lib/devices.ts
Normal file
27
src/lib/devices.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
function isAndroid(): boolean {
|
||||
return (
|
||||
typeof navigator !== 'undefined' && /android/i.test(navigator.userAgent)
|
||||
);
|
||||
}
|
||||
|
||||
function isSmallIOS(): boolean {
|
||||
return (
|
||||
typeof navigator !== 'undefined' && /iPhone|iPod/.test(navigator.userAgent)
|
||||
);
|
||||
}
|
||||
|
||||
function isLargeIOS(): boolean {
|
||||
return (
|
||||
typeof navigator !== 'undefined' &&
|
||||
(/iPad/.test(navigator.userAgent) ||
|
||||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1))
|
||||
);
|
||||
}
|
||||
|
||||
function isIOS(): boolean {
|
||||
return isSmallIOS() || isLargeIOS();
|
||||
}
|
||||
|
||||
export function isMobile(): boolean {
|
||||
return isAndroid() || isIOS();
|
||||
}
|
||||
@@ -1,25 +1,23 @@
|
||||
import { FrameNotificationDetails } from '@farcaster/frame-sdk';
|
||||
import { Redis } from '@upstash/redis';
|
||||
import { APP_NAME } from './constants';
|
||||
import { FrameNotificationDetails } from "@farcaster/miniapp-sdk";
|
||||
import { Redis } from "@upstash/redis";
|
||||
import { APP_NAME } from "./constants";
|
||||
|
||||
// In-memory fallback storage
|
||||
const localStore = new Map<string, FrameNotificationDetails>();
|
||||
|
||||
// Use Redis if KV env vars are present, otherwise use in-memory
|
||||
const useRedis = process.env.KV_REST_API_URL && process.env.KV_REST_API_TOKEN;
|
||||
const redis = useRedis
|
||||
? new Redis({
|
||||
url: process.env.KV_REST_API_URL!,
|
||||
token: process.env.KV_REST_API_TOKEN!,
|
||||
})
|
||||
: null;
|
||||
const redis = useRedis ? new Redis({
|
||||
url: process.env.KV_REST_API_URL!,
|
||||
token: process.env.KV_REST_API_TOKEN!,
|
||||
}) : null;
|
||||
|
||||
function getUserNotificationDetailsKey(fid: number): string {
|
||||
return `${APP_NAME}:user:${fid}`;
|
||||
}
|
||||
|
||||
export async function getUserNotificationDetails(
|
||||
fid: number,
|
||||
fid: number
|
||||
): Promise<FrameNotificationDetails | null> {
|
||||
const key = getUserNotificationDetailsKey(fid);
|
||||
if (redis) {
|
||||
@@ -30,7 +28,7 @@ export async function getUserNotificationDetails(
|
||||
|
||||
export async function setUserNotificationDetails(
|
||||
fid: number,
|
||||
notificationDetails: FrameNotificationDetails,
|
||||
notificationDetails: FrameNotificationDetails
|
||||
): Promise<void> {
|
||||
const key = getUserNotificationDetailsKey(fid);
|
||||
if (redis) {
|
||||
@@ -41,7 +39,7 @@ export async function setUserNotificationDetails(
|
||||
}
|
||||
|
||||
export async function deleteUserNotificationDetails(
|
||||
fid: number,
|
||||
fid: number
|
||||
): Promise<void> {
|
||||
const key = getUserNotificationDetailsKey(fid);
|
||||
if (redis) {
|
||||
@@ -49,4 +47,4 @@ export async function deleteUserNotificationDetails(
|
||||
} else {
|
||||
localStore.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
25
src/lib/localStorage.ts
Normal file
25
src/lib/localStorage.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
export function setItem<T>(key: string, value: T) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch (error) {
|
||||
console.warn('Failed to save item:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function getItem<T>(key: string): T | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(key);
|
||||
return stored ? JSON.parse(stored) : null;
|
||||
} catch (error) {
|
||||
console.warn('Failed to load item:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function removeItem(key: string) {
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch (error) {
|
||||
console.warn('Failed to remove item:', error);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
import {
|
||||
SendNotificationRequest,
|
||||
sendNotificationResponseSchema,
|
||||
} from '@farcaster/frame-sdk';
|
||||
import { getUserNotificationDetails } from '~/lib/kv';
|
||||
import { APP_URL } from './constants';
|
||||
} from "@farcaster/miniapp-sdk";
|
||||
import { getUserNotificationDetails } from "~/lib/kv";
|
||||
import { APP_URL } from "./constants";
|
||||
|
||||
type SendMiniAppNotificationResult =
|
||||
| {
|
||||
state: 'error';
|
||||
state: "error";
|
||||
error: unknown;
|
||||
}
|
||||
| { state: 'no_token' }
|
||||
| { state: 'rate_limit' }
|
||||
| { state: 'success' };
|
||||
| { state: "no_token" }
|
||||
| { state: "rate_limit" }
|
||||
| { state: "success" };
|
||||
|
||||
export async function sendMiniAppNotification({
|
||||
fid,
|
||||
@@ -25,13 +25,13 @@ export async function sendMiniAppNotification({
|
||||
}): Promise<SendMiniAppNotificationResult> {
|
||||
const notificationDetails = await getUserNotificationDetails(fid);
|
||||
if (!notificationDetails) {
|
||||
return { state: 'no_token' };
|
||||
return { state: "no_token" };
|
||||
}
|
||||
|
||||
const response = await fetch(notificationDetails.url, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
notificationId: crypto.randomUUID(),
|
||||
@@ -48,17 +48,17 @@ export async function sendMiniAppNotification({
|
||||
const responseBody = sendNotificationResponseSchema.safeParse(responseJson);
|
||||
if (responseBody.success === false) {
|
||||
// Malformed response
|
||||
return { state: 'error', error: responseBody.error.errors };
|
||||
return { state: "error", error: responseBody.error.errors };
|
||||
}
|
||||
|
||||
if (responseBody.data.result.rateLimitedTokens.length) {
|
||||
// Rate limited
|
||||
return { state: 'rate_limit' };
|
||||
return { state: "rate_limit" };
|
||||
}
|
||||
|
||||
return { state: 'success' };
|
||||
return { state: "success" };
|
||||
} else {
|
||||
// Error response
|
||||
return { state: 'error', error: responseJson };
|
||||
return { state: "error", error: responseJson };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
import { mnemonicToAccount } from 'viem/accounts';
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { mnemonicToAccount } from "viem/accounts";
|
||||
import {
|
||||
APP_BUTTON_TEXT,
|
||||
APP_DESCRIPTION,
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
APP_TAGS,
|
||||
APP_URL,
|
||||
APP_WEBHOOK_URL,
|
||||
} from './constants';
|
||||
import { APP_SPLASH_URL } from './constants';
|
||||
} from "./constants";
|
||||
import { APP_SPLASH_URL } from "./constants";
|
||||
|
||||
interface MiniAppMetadata {
|
||||
version: string;
|
||||
@@ -43,25 +43,14 @@ export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function getSecretEnvVars() {
|
||||
const seedPhrase = process.env.SEED_PHRASE;
|
||||
const fid = process.env.FID;
|
||||
|
||||
if (!seedPhrase || !fid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { seedPhrase, fid };
|
||||
}
|
||||
|
||||
export function getMiniAppEmbedMetadata(ogImageUrl?: string) {
|
||||
return {
|
||||
version: 'next',
|
||||
version: "next",
|
||||
imageUrl: ogImageUrl ?? APP_OG_IMAGE_URL,
|
||||
button: {
|
||||
title: APP_BUTTON_TEXT,
|
||||
action: {
|
||||
type: 'launch_frame',
|
||||
type: "launch_frame",
|
||||
name: APP_NAME,
|
||||
url: APP_URL,
|
||||
splashImageUrl: APP_SPLASH_URL,
|
||||
@@ -80,77 +69,37 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
|
||||
if (process.env.MINI_APP_METADATA) {
|
||||
try {
|
||||
const metadata = JSON.parse(process.env.MINI_APP_METADATA);
|
||||
console.log('Using pre-signed mini app metadata from environment');
|
||||
console.log("Using pre-signed mini app metadata from environment");
|
||||
return metadata;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'Failed to parse MINI_APP_METADATA from environment:',
|
||||
error,
|
||||
"Failed to parse MINI_APP_METADATA from environment:",
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!APP_URL) {
|
||||
throw new Error('NEXT_PUBLIC_URL not configured');
|
||||
throw new Error("NEXT_PUBLIC_URL not configured");
|
||||
}
|
||||
|
||||
// Get the domain from the URL (without https:// prefix)
|
||||
const domain = new URL(APP_URL).hostname;
|
||||
console.log('Using domain for manifest:', domain);
|
||||
|
||||
const secretEnvVars = getSecretEnvVars();
|
||||
if (!secretEnvVars) {
|
||||
console.warn(
|
||||
'No seed phrase or FID found in environment variables -- generating unsigned metadata',
|
||||
);
|
||||
}
|
||||
|
||||
let accountAssociation;
|
||||
if (secretEnvVars) {
|
||||
// Generate account from seed phrase
|
||||
const account = mnemonicToAccount(secretEnvVars.seedPhrase);
|
||||
const custodyAddress = account.address;
|
||||
|
||||
const header = {
|
||||
fid: parseInt(secretEnvVars.fid),
|
||||
type: 'custody',
|
||||
key: custodyAddress,
|
||||
};
|
||||
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString(
|
||||
'base64',
|
||||
);
|
||||
|
||||
const payload = {
|
||||
domain,
|
||||
};
|
||||
const encodedPayload = Buffer.from(
|
||||
JSON.stringify(payload),
|
||||
'utf-8',
|
||||
).toString('base64url');
|
||||
|
||||
const signature = await account.signMessage({
|
||||
message: `${encodedHeader}.${encodedPayload}`,
|
||||
});
|
||||
const encodedSignature = Buffer.from(signature, 'utf-8').toString(
|
||||
'base64url',
|
||||
);
|
||||
|
||||
accountAssociation = {
|
||||
header: encodedHeader,
|
||||
payload: encodedPayload,
|
||||
signature: encodedSignature,
|
||||
};
|
||||
}
|
||||
console.log("Using domain for manifest:", domain);
|
||||
|
||||
return {
|
||||
accountAssociation,
|
||||
accountAssociation: {
|
||||
header: "",
|
||||
payload: "",
|
||||
signature: "",
|
||||
},
|
||||
frame: {
|
||||
version: '1',
|
||||
name: APP_NAME ?? 'Neynar Starter Kit',
|
||||
version: "1",
|
||||
name: APP_NAME ?? "Neynar Starter Kit",
|
||||
iconUrl: APP_ICON_URL,
|
||||
homeUrl: APP_URL,
|
||||
imageUrl: APP_OG_IMAGE_URL,
|
||||
buttonTitle: APP_BUTTON_TEXT ?? 'Launch Mini App',
|
||||
buttonTitle: APP_BUTTON_TEXT ?? "Launch Mini App",
|
||||
splashImageUrl: APP_SPLASH_URL,
|
||||
splashBackgroundColor: APP_SPLASH_BACKGROUND_COLOR,
|
||||
webhookUrl: APP_WEBHOOK_URL,
|
||||
@@ -159,4 +108,4 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
|
||||
tags: APP_TAGS,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user