Format after fixing conflicts

This commit is contained in:
Shreyaschorge
2025-07-14 20:04:44 +05:30
parent 505aa54b16
commit e74b2581df
30 changed files with 515 additions and 469 deletions

View File

@@ -10,7 +10,7 @@ export async function GET() {
console.error('Error fetching nonce:', error);
return NextResponse.json(
{ error: 'Failed to fetch nonce' },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -10,7 +10,7 @@ export async function GET(request: Request) {
if (!message || !signature) {
return NextResponse.json(
{ error: 'Message and signature are required' },
{ status: 400 }
{ status: 400 },
);
}
@@ -37,7 +37,7 @@ export async function GET(request: Request) {
console.error('Error in session-signers API:', error);
return NextResponse.json(
{ error: 'Failed to fetch signers' },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -10,7 +10,7 @@ export async function POST() {
console.error('Error fetching signer:', error);
return NextResponse.json(
{ error: 'Failed to fetch signer' },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -22,7 +22,7 @@ export async function GET(request: Request) {
if (!signerUuid) {
return NextResponse.json(
{ error: 'signerUuid is required' },
{ status: 400 }
{ status: 400 },
);
}
@@ -36,7 +36,7 @@ export async function GET(request: Request) {
console.error('Error fetching signed key:', error);
return NextResponse.json(
{ error: 'Failed to fetch signed key' },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -1,10 +1,10 @@
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';
import { getNeynarClient } from '~/lib/neynar';
const postRequiredFields = ['signerUuid', 'publicKey'];
@@ -16,7 +16,7 @@ export async function POST(request: Request) {
if (!body[field]) {
return NextResponse.json(
{ error: `${field} is required` },
{ status: 400 }
{ status: 400 },
);
}
}
@@ -26,7 +26,7 @@ export async function POST(request: Request) {
if (redirectUrl && typeof redirectUrl !== 'string') {
return NextResponse.json(
{ error: 'redirectUrl must be a string' },
{ status: 400 }
{ status: 400 },
);
}
@@ -38,7 +38,7 @@ export async function POST(request: Request) {
if (!seedPhrase) {
return NextResponse.json(
{ error: 'App configuration missing (SEED_PHRASE or FID)' },
{ status: 500 }
{ status: 500 },
);
}
@@ -85,7 +85,7 @@ export async function POST(request: Request) {
console.error('Error registering signed key:', error);
return NextResponse.json(
{ error: 'Failed to register signed key' },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -13,7 +13,7 @@ export async function GET(request: Request) {
{
error: `${param} parameter is required`,
},
{ status: 400 }
{ status: 400 },
);
}
}
@@ -32,7 +32,7 @@ export async function GET(request: Request) {
console.error('Error fetching signers:', error);
return NextResponse.json(
{ error: 'Failed to fetch signers' },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -9,7 +9,7 @@ export async function POST(request: Request) {
if (!session?.user?.fid) {
return NextResponse.json(
{ error: 'No authenticated session found' },
{ status: 401 }
{ status: 401 },
);
}
@@ -19,7 +19,7 @@ export async function POST(request: Request) {
if (!signers || !user) {
return NextResponse.json(
{ error: 'Signers and user are required' },
{ status: 400 }
{ status: 400 },
);
}
@@ -40,7 +40,7 @@ export async function POST(request: Request) {
console.error('Error preparing session update:', error);
return NextResponse.json(
{ error: 'Failed to prepare session update' },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -1,9 +1,9 @@
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";
import { NextRequest } from 'next/server';
import { notificationDetailsSchema } from '@farcaster/miniapp-sdk';
import { z } from 'zod';
import { setUserNotificationDetails } from '~/lib/kv';
import { sendNeynarMiniAppNotification } from '~/lib/neynar';
import { sendMiniAppNotification } from '~/lib/notifs';
const requestSchema = z.object({
fid: z.number(),
@@ -13,7 +13,8 @@ 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);
@@ -21,7 +22,7 @@ export async function POST(request: NextRequest) {
if (requestBody.success === false) {
return Response.json(
{ success: false, errors: requestBody.error.errors },
{ status: 400 }
{ status: 400 },
);
}
@@ -29,29 +30,31 @@ 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 });
}
}

View File

@@ -1,20 +1,21 @@
import { NextRequest } from 'next/server';
import {
ParseWebhookEvent,
parseWebhookEvent,
verifyAppKeyWithNeynar,
} from "@farcaster/miniapp-node";
import { NextRequest } from "next/server";
import { APP_NAME } from "~/lib/constants";
} from '@farcaster/miniapp-node';
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 });
}
@@ -28,24 +29,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 },
);
}
}
@@ -56,36 +57,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 });
}
}

View File

@@ -1,18 +1,18 @@
'use client';
import dynamic from 'next/dynamic';
import { AuthKitProvider } from '@farcaster/auth-kit';
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({
@@ -38,4 +38,4 @@ export function Providers({
</WagmiProvider>
</SessionProvider>
);
}
}

View File

@@ -1,6 +1,6 @@
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 {
@@ -401,7 +401,7 @@ export const authOptions: AuthOptions = {
},
cookies: {
sessionToken: {
name: `next-auth.session-token`,
name: 'next-auth.session-token',
options: {
httpOnly: true,
sameSite: 'none',
@@ -410,7 +410,7 @@ export const authOptions: AuthOptions = {
},
},
callbackUrl: {
name: `next-auth.callback-url`,
name: 'next-auth.callback-url',
options: {
sameSite: 'none',
path: '/',
@@ -418,7 +418,7 @@ export const authOptions: AuthOptions = {
},
},
csrfToken: {
name: `next-auth.csrf-token`,
name: 'next-auth.csrf-token',
options: {
httpOnly: true,
sameSite: 'none',
@@ -436,4 +436,4 @@ export const getSession = async () => {
console.error('Error getting server session:', error);
return null;
}
};
};

View File

@@ -1,10 +1,13 @@
import React, { createContext, useEffect, useState } from "react";
import dynamic from "next/dynamic";
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 = {
@@ -12,10 +15,15 @@ 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);
@@ -48,8 +56,8 @@ export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcaste
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);
@@ -83,4 +91,4 @@ export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcaste
export function useHasSolanaProvider() {
return React.useContext(SolanaProviderContext).hasSolanaProvider;
}
}

View File

@@ -1,12 +1,12 @@
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 React from 'react';
import { useEffect, useState } from 'react';
import { farcasterFrame } from '@farcaster/miniapp-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 { coinbaseWallet, metaMask } from 'wagmi/connectors';
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";
import { APP_NAME, APP_ICON_URL, APP_URL } from '~/lib/constants';
// Custom hook for Coinbase Wallet detection and auto-connection
function useCoinbaseWalletAutoConnect() {
@@ -17,15 +17,16 @@ 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);
};
@@ -70,7 +71,11 @@ 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}</>;
}
@@ -79,10 +84,8 @@ export default function Provider({ children }: { children: React.ReactNode }) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<CoinbaseWalletAutoConnect>
{children}
</CoinbaseWalletAutoConnect>
<CoinbaseWalletAutoConnect>{children}</CoinbaseWalletAutoConnect>
</QueryClientProvider>
</WagmiProvider>
);
}
}

View File

@@ -1,9 +1,9 @@
"use client";
'use client';
import { useState } from "react";
import { APP_NAME } from "~/lib/constants";
import sdk from "@farcaster/miniapp-sdk";
import { useMiniApp } from "@neynar/react";
import { useState } from 'react';
import sdk from '@farcaster/miniapp-sdk';
import { useMiniApp } from '@neynar/react';
import { APP_NAME } from '~/lib/constants';
type HeaderProps = {
neynarUser?: {
@@ -18,23 +18,19 @@ 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"
/>
)}
@@ -42,14 +38,16 @@ 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>
@@ -74,4 +72,4 @@ export function Header({ neynarUser }: HeaderProps) {
)}
</div>
);
}
}

View File

@@ -169,7 +169,7 @@ export function AuthDialog({
{/* 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
content.qrUrl,
)}`}
alt="QR Code"
className="w-48 h-48"
@@ -197,14 +197,14 @@ export function AuthDialog({
content.qrUrl
.replace(
'https://farcaster.xyz/',
'https://client.farcaster.xyz/deeplinks/'
'https://client.farcaster.xyz/deeplinks/',
)
.replace(
'https://client.farcaster.xyz/deeplinks/signed-key-request',
'https://farcaster.xyz/~/connect'
'https://farcaster.xyz/~/connect',
),
'_blank'
)
'_blank',
);
}
}}
className="btn btn-outline flex items-center justify-center gap-2 w-full"

View File

@@ -27,7 +27,7 @@ export function ProfileButton({
'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'
'focus:outline-none focus:ring-1 focus:ring-primary',
)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
@@ -35,7 +35,7 @@ export function ProfileButton({
src={pfpUrl}
alt="Profile"
className="w-6 h-6 rounded-full object-cover flex-shrink-0"
onError={(e) => {
onError={e => {
(e.target as HTMLImageElement).src =
'https://farcaster.xyz/avatar.png';
}}
@@ -46,7 +46,7 @@ export function ProfileButton({
<svg
className={cn(
'w-4 h-4 transition-transform flex-shrink-0',
showDropdown && 'rotate-180'
showDropdown && 'rotate-180',
)}
fill="none"
stroke="currentColor"

View File

@@ -1,20 +1,20 @@
'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 { useSignIn, UseSignInData } from '@farcaster/auth-kit';
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
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';
import { Button } from '~/components/ui/Button';
import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
import { ProfileButton } from '~/components/ui/NeynarAuthButton/ProfileButton';
import { getItem, removeItem, setItem } from '~/lib/localStorage';
import { cn } from '~/lib/utils';
type User = {
fid: number;
@@ -102,13 +102,13 @@ export function NeynarAuthButton() {
// New state for unified dialog flow
const [showDialog, setShowDialog] = useState(false);
const [dialogStep, setDialogStep] = useState<'signin' | 'access' | 'loading'>(
'loading'
'loading',
);
const [signerApprovalUrl, setSignerApprovalUrl] = useState<string | null>(
null
null,
);
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(
null
null,
);
const [message, setMessage] = useState<string | null>(null);
const [signature, setSignature] = useState<string | null>(null);
@@ -141,7 +141,7 @@ export function NeynarAuthButton() {
const updateSessionWithSigners = useCallback(
async (
signers: StoredAuthState['signers'],
user: StoredAuthState['user']
user: StoredAuthState['user'],
) => {
if (!useBackendFlow) return;
@@ -164,7 +164,7 @@ export function NeynarAuthButton() {
console.error('❌ Error updating session with signers:', error);
}
},
[useBackendFlow, message, signature, nonce]
[useBackendFlow, message, signature, nonce],
);
// Helper function to fetch user data from Neynar API
@@ -182,7 +182,7 @@ export function NeynarAuthButton() {
return null;
}
},
[]
[],
);
// Helper function to generate signed key request
@@ -210,7 +210,7 @@ export function NeynarAuthButton() {
if (!response.ok) {
const errorData = await response.json();
throw new Error(
`Failed to generate signed key request: ${errorData.error}`
`Failed to generate signed key request: ${errorData.error}`,
);
}
@@ -222,7 +222,7 @@ export function NeynarAuthButton() {
// throw error;
}
},
[]
[],
);
// Helper function to fetch all signers
@@ -233,10 +233,10 @@ export function NeynarAuthButton() {
const endpoint = useBackendFlow
? `/api/auth/session-signers?message=${encodeURIComponent(
message
message,
)}&signature=${signature}`
: `/api/auth/signers?message=${encodeURIComponent(
message
message,
)}&signature=${signature}`;
const response = await fetch(endpoint);
@@ -258,7 +258,7 @@ export function NeynarAuthButton() {
if (signerData.signers && signerData.signers.length > 0) {
const fetchedUser = (await fetchUserData(
signerData.signers[0].fid
signerData.signers[0].fid,
)) as StoredAuthState['user'];
user = fetchedUser;
}
@@ -285,7 +285,7 @@ export function NeynarAuthButton() {
setSignersLoading(false);
}
},
[useBackendFlow, fetchUserData, updateSessionWithSigners]
[useBackendFlow, fetchUserData, updateSessionWithSigners],
);
// Helper function to poll signer status
@@ -308,10 +308,10 @@ export function NeynarAuthButton() {
setPollingInterval(null);
return;
}
try {
const response = await fetch(
`/api/auth/signer?signerUuid=${signerUuid}`
`/api/auth/signer?signerUuid=${signerUuid}`,
);
if (!response.ok) {
@@ -321,7 +321,7 @@ export function NeynarAuthButton() {
setPollingInterval(null);
return;
}
// Increment retry count for other errors
retryCount++;
if (retryCount >= maxRetries) {
@@ -329,7 +329,7 @@ export function NeynarAuthButton() {
setPollingInterval(null);
return;
}
throw new Error(`Failed to poll signer status: ${response.status}`);
}
@@ -352,7 +352,7 @@ export function NeynarAuthButton() {
setPollingInterval(interval);
},
[fetchAllSigners, pollingInterval]
[fetchAllSigners, pollingInterval],
);
// Cleanup polling on unmount
@@ -412,7 +412,7 @@ export function NeynarAuthButton() {
}
// For backend flow, the session will be handled by NextAuth
},
[useBackendFlow, fetchUserData]
[useBackendFlow, fetchUserData],
);
// Error callback
@@ -443,7 +443,7 @@ export function NeynarAuthButton() {
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;
@@ -459,9 +459,14 @@ export function NeynarAuthButton() {
// Handle fetching signers after successful authentication
useEffect(() => {
if (message && signature && !isSignerFlowRunning && !signerFlowStartedRef.current) {
if (
message &&
signature &&
!isSignerFlowRunning &&
!signerFlowStartedRef.current
) {
signerFlowStartedRef.current = true;
const handleSignerFlow = async () => {
setIsSignerFlowRunning(true);
try {
@@ -479,7 +484,7 @@ export function NeynarAuthButton() {
// 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
@@ -490,7 +495,7 @@ export function NeynarAuthButton() {
// Step 2: Generate signed key request
const signedKeyData = await generateSignedKeyRequest(
newSigner.signer_uuid,
newSigner.public_key
newSigner.public_key,
);
// Step 3: Show QR code in access dialog for signer approval
@@ -501,8 +506,8 @@ export function NeynarAuthButton() {
await sdk.actions.openUrl(
signedKeyData.signer_approval_url.replace(
'https://client.farcaster.xyz/deeplinks/signed-key-request',
'https://farcaster.xyz/~/connect'
)
'https://farcaster.xyz/~/connect',
),
);
} else {
setShowDialog(true); // Ensure dialog is shown during loading
@@ -604,7 +609,7 @@ export function NeynarAuthButton() {
clearInterval(pollingInterval);
setPollingInterval(null);
}
// Reset signer flow flag
signerFlowStartedRef.current = false;
} catch (error) {
@@ -663,7 +668,7 @@ export function NeynarAuthButton() {
'btn btn-primary flex items-center gap-3',
'disabled:opacity-50 disabled:cursor-not-allowed',
'transform transition-all duration-200 active:scale-[0.98]',
!url && !useBackendFlow && 'cursor-not-allowed'
!url && !useBackendFlow && 'cursor-not-allowed',
)}
>
{!useBackendFlow && !url ? (

View File

@@ -1,9 +1,9 @@
'use client';
import { useCallback, useState, useEffect } from 'react';
import { Button } from './Button';
import { type ComposeCast } from '@farcaster/miniapp-sdk';
import { useMiniApp } from '@neynar/react';
import { type ComposeCast } from "@farcaster/miniapp-sdk";
import { Button } from './Button';
interface EmbedConfig {
path?: string;
@@ -23,9 +23,16 @@ 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();
@@ -51,7 +58,7 @@ export function ShareButton({ buttonText, cast, className = '', isLoading = fals
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) {
@@ -67,16 +74,20 @@ export function ShareButton({ buttonText, cast, className = '', isLoading = fals
// 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) {
@@ -87,7 +98,7 @@ export function ShareButton({ buttonText, cast, className = '', isLoading = fals
return url.toString();
}
return embed.url || '';
})
}),
);
// Open cast composer with all supported intents
@@ -115,4 +126,4 @@ export function ShareButton({ buttonText, cast, className = '', isLoading = fals
{buttonText}
</Button>
);
}
}

View File

@@ -1,12 +1,12 @@
'use client';
import { useCallback, useState } from "react";
import { useMiniApp } from "@neynar/react";
import { ShareButton } from "../Share";
import { Button } from "../Button";
import { SignIn } from "../wallet/SignIn";
import { type Haptics } from "@farcaster/miniapp-sdk";
import { useCallback, useState } from 'react';
import { type Haptics } from '@farcaster/miniapp-sdk';
import { useMiniApp } from '@neynar/react';
import { Button } from '../Button';
import { NeynarAuthButton } from '../NeynarAuthButton/index';
import { ShareButton } from '../Share';
import { SignIn } from '../wallet/SignIn';
/**
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
@@ -51,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;
}
@@ -66,22 +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) => ({
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}`,
}));
@@ -98,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]);
@@ -123,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,
@@ -134,7 +134,7 @@ export function ActionsTab() {
`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`,
],
}}
className='w-full'
className="w-full"
/>
{/* Authentication */}
@@ -148,25 +148,25 @@ export function ActionsTab() {
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>
@@ -175,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>
@@ -200,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>
);
}
}

View File

@@ -17,7 +17,9 @@ 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 dark:text-gray-400">Powered by Neynar 🪐</p>
<p className="text-sm text-gray-500 dark:text-gray-400">
Powered by Neynar 🪐
</p>
</div>
</div>
);

View File

@@ -1,10 +1,10 @@
'use client';
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";
import { useCallback, useState } from 'react';
import sdk, { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
import { signIn, signOut, getCsrfToken } from 'next-auth/react';
import { useSession } from 'next-auth/react';
import { Button } from '../Button';
/**
* SignIn component handles Farcaster authentication using Sign-In with Farcaster (SIWF).
@@ -72,7 +72,7 @@ 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 });
@@ -89,7 +89,7 @@ export function SignIn() {
}
setSignInFailure('Unknown error');
} finally {
setAuthState((prev) => ({ ...prev, signingIn: false }));
setAuthState(prev => ({ ...prev, signingIn: false }));
}
}, [getNonce]);
@@ -103,14 +103,14 @@ export function SignIn() {
*/
const handleSignOut = useCallback(async () => {
try {
setAuthState((prev) => ({ ...prev, signingOut: true }));
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]);
@@ -132,7 +132,9 @@ export function SignIn() {
{/* Session Information */}
{session && (
<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="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>
@@ -142,15 +144,21 @@ export function SignIn() {
{/* Error Display */}
{signInFailure && !authState.signingIn && (
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 dark:bg-gray-900 rounded-lg font-mono">
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">SIWF Result</div>
<div className="whitespace-pre text-gray-700 dark:text-gray-200">{signInFailure}</div>
<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 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="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>
@@ -158,4 +166,4 @@ export function SignIn() {
)}
</>
);
}
}

View File

@@ -2,7 +2,7 @@ import { useEffect } from 'react';
export function useDetectClickOutside<T extends HTMLElement>(
ref: React.RefObject<T | null>,
callback: () => void
callback: () => void,
) {
useEffect(() => {
function handleClickOutside(event: MouseEvent) {

View File

@@ -1,23 +1,25 @@
import { FrameNotificationDetails } from "@farcaster/miniapp-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) {
@@ -28,7 +30,7 @@ export async function getUserNotificationDetails(
export async function setUserNotificationDetails(
fid: number,
notificationDetails: FrameNotificationDetails
notificationDetails: FrameNotificationDetails,
): Promise<void> {
const key = getUserNotificationDetailsKey(fid);
if (redis) {
@@ -39,7 +41,7 @@ export async function setUserNotificationDetails(
}
export async function deleteUserNotificationDetails(
fid: number
fid: number,
): Promise<void> {
const key = getUserNotificationDetailsKey(fid);
if (redis) {
@@ -47,4 +49,4 @@ export async function deleteUserNotificationDetails(
} else {
localStore.delete(key);
}
}
}

View File

@@ -1,18 +1,18 @@
import {
SendNotificationRequest,
sendNotificationResponseSchema,
} from "@farcaster/miniapp-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 };
}
}
}

View File

@@ -1,6 +1,5 @@
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 {
APP_BUTTON_TEXT,
APP_DESCRIPTION,
@@ -12,8 +11,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;
@@ -45,12 +44,12 @@ export function cn(...inputs: ClassValue[]) {
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,
@@ -69,37 +68,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);
console.log('Using domain for manifest:', domain);
return {
accountAssociation: {
header: "",
payload: "",
signature: "",
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,
@@ -108,4 +107,4 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
tags: APP_TAGS,
},
};
}
}