formatting

This commit is contained in:
Shreyaschorge
2025-07-07 14:10:47 +05:30
parent f42a5f8d33
commit 193dffe03a
64 changed files with 6398 additions and 985 deletions

View File

@@ -1,6 +1,6 @@
import NextAuth from "next-auth"
import { authOptions } from "~/auth"
import NextAuth from 'next-auth';
import { authOptions } from '~/auth';
const handler = NextAuth(authOptions)
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }
export { handler as GET, handler as POST };

View File

@@ -4,10 +4,13 @@ export async function GET(request: Request) {
const apiKey = process.env.NEYNAR_API_KEY;
const { searchParams } = new URL(request.url);
const fid = searchParams.get('fid');
if (!apiKey) {
return NextResponse.json(
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
{
error:
'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.',
},
{ status: 500 }
);
}
@@ -24,7 +27,7 @@ export async function GET(request: Request) {
`https://api.neynar.com/v2/farcaster/user/best_friends?fid=${fid}&limit=3`,
{
headers: {
"x-api-key": apiKey,
'x-api-key': apiKey,
},
}
);
@@ -33,14 +36,19 @@ export async function GET(request: Request) {
throw new Error(`Neynar API error: ${response.statusText}`);
}
const { users } = await response.json() as { users: { user: { fid: number; username: string } }[] };
const { users } = (await response.json()) as {
users: { user: { fid: number; username: string } }[];
};
return NextResponse.json({ bestFriends: users });
} catch (error) {
console.error('Failed to fetch best friends:', error);
return NextResponse.json(
{ error: 'Failed to fetch best friends. Please check your Neynar API key and try again.' },
{
error:
'Failed to fetch best friends. Please check your Neynar API key and try again.',
},
{ status: 500 }
);
}
}
}

View File

@@ -1,6 +1,6 @@
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
import { getNeynarUser } from "~/lib/neynar";
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import { getNeynarUser } from '~/lib/neynar';
export const dynamic = 'force-dynamic';
@@ -15,10 +15,18 @@ export async function GET(request: NextRequest) {
<div tw="flex h-full w-full flex-col justify-center items-center relative bg-primary">
{user?.pfp_url && (
<div tw="flex w-96 h-96 rounded-full overflow-hidden mb-8 border-8 border-white">
<img src={user.pfp_url} alt="Profile" tw="w-full h-full object-cover" />
<img
src={user.pfp_url}
alt="Profile"
tw="w-full h-full object-cover"
/>
</div>
)}
<h1 tw="text-8xl text-white">{user?.display_name ? `Hello from ${user.display_name ?? user.username}!` : 'Hello!'}</h1>
<h1 tw="text-8xl text-white">
{user?.display_name
? `Hello from ${user.display_name ?? user.username}!`
: 'Hello!'}
</h1>
<p tw="text-5xl mt-4 text-white opacity-80">Powered by Neynar 🪐</p>
</div>
),
@@ -27,4 +35,4 @@ export async function GET(request: NextRequest) {
height: 800,
}
);
}
}

View File

@@ -1,9 +1,9 @@
import { notificationDetailsSchema } from "@farcaster/frame-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 { notificationDetailsSchema } from '@farcaster/frame-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,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);
@@ -34,21 +35,23 @@ export async function POST(request: NextRequest) {
}
// 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 }
);
} else if (sendResult.state === "rate_limit") {
} else if (sendResult.state === 'rate_limit') {
return Response.json(
{ success: false, error: "Rate limited" },
{ success: false, error: 'Rate limited' },
{ status: 429 }
);
}

View File

@@ -5,10 +5,13 @@ export async function GET(request: Request) {
const apiKey = process.env.NEYNAR_API_KEY;
const { searchParams } = new URL(request.url);
const fids = searchParams.get('fids');
if (!apiKey) {
return NextResponse.json(
{ error: 'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.' },
{
error:
'Neynar API key is not configured. Please add NEYNAR_API_KEY to your environment variables.',
},
{ status: 500 }
);
}
@@ -23,7 +26,7 @@ export async function GET(request: Request) {
try {
const neynar = new NeynarAPIClient({ apiKey });
const fidsArray = fids.split(',').map(fid => parseInt(fid.trim()));
const { users } = await neynar.fetchBulkUsers({
fids: fidsArray,
});
@@ -32,7 +35,10 @@ export async function GET(request: Request) {
} catch (error) {
console.error('Failed to fetch users:', error);
return NextResponse.json(
{ error: 'Failed to fetch users. Please check your Neynar API key and try again.' },
{
error:
'Failed to fetch users. Please check your Neynar API key and try again.',
},
{ status: 500 }
);
}

View File

@@ -2,19 +2,20 @@ import {
ParseWebhookEvent,
parseWebhookEvent,
verifyAppKeyWithNeynar,
} from "@farcaster/frame-node";
import { NextRequest } from "next/server";
import { APP_NAME } from "~/lib/constants";
} from '@farcaster/frame-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 });
}
@@ -28,20 +29,20 @@ 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 }
);
case "VerifyJsonFarcasterSignature.InvalidAppKeyError":
case 'VerifyJsonFarcasterSignature.InvalidAppKeyError':
// The app key is invalid
return Response.json(
{ success: false, error: error.message },
{ 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 },
@@ -56,33 +57,33 @@ 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;
}

View File

@@ -1,10 +1,10 @@
"use client";
'use client';
import dynamic from "next/dynamic";
import { APP_NAME } from "~/lib/constants";
import dynamic from 'next/dynamic';
import { APP_NAME } from '~/lib/constants';
// note: dynamic import is required for components that use the Frame SDK
const AppComponent = dynamic(() => import("~/components/App"), {
const AppComponent = dynamic(() => import('~/components/App'), {
ssr: false,
});

View File

@@ -62,11 +62,11 @@ body {
.container {
@apply mx-auto max-w-md px-4;
}
.container-wide {
@apply mx-auto max-w-lg px-4;
}
.container-narrow {
@apply mx-auto max-w-sm px-4;
}
@@ -75,7 +75,7 @@ body {
.card {
@apply bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm;
}
.card-primary {
@apply bg-primary/10 border-primary/20;
}
@@ -84,15 +84,15 @@ body {
.btn {
@apply inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none;
}
.btn-primary {
@apply bg-primary text-white hover:bg-primary-dark focus:ring-primary;
}
.btn-secondary {
@apply bg-secondary text-gray-900 hover:bg-gray-200 focus:ring-gray-500 dark:bg-secondary-dark dark:text-gray-100 dark:hover:bg-gray-600;
}
.btn-outline {
@apply border border-gray-300 bg-transparent hover:bg-gray-50 focus:ring-gray-500 dark:border-gray-600 dark:hover:bg-gray-800;
}
@@ -106,7 +106,7 @@ body {
.spinner {
@apply animate-spin rounded-full border-2 border-gray-300 border-t-primary;
}
.spinner-primary {
@apply animate-spin rounded-full border-2 border-white border-t-transparent;
}

View File

@@ -1,9 +1,9 @@
import type { Metadata } from "next";
import type { Metadata } from 'next';
import { getSession } from "~/auth"
import "~/app/globals.css";
import { Providers } from "~/app/providers";
import { APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
import { getSession } from '~/auth';
import '~/app/globals.css';
import { Providers } from '~/app/providers';
import { APP_NAME, APP_DESCRIPTION } from '~/lib/constants';
export const metadata: Metadata = {
title: APP_NAME,
@@ -14,8 +14,8 @@ export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getSession()
}>) {
const session = await getSession();
return (
<html lang="en">

View File

@@ -1,7 +1,7 @@
import { Metadata } from "next";
import App from "./app";
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from "~/lib/constants";
import { getMiniAppEmbedMetadata } from "~/lib/utils";
import { Metadata } from 'next';
import App from './app';
import { APP_NAME, APP_DESCRIPTION, APP_OG_IMAGE_URL } from '~/lib/constants';
import { getMiniAppEmbedMetadata } from '~/lib/utils';
export const revalidate = 300;
@@ -14,11 +14,11 @@ export async function generateMetadata(): Promise<Metadata> {
images: [APP_OG_IMAGE_URL],
},
other: {
"fc:frame": JSON.stringify(getMiniAppEmbedMetadata()),
'fc:frame': JSON.stringify(getMiniAppEmbedMetadata()),
},
};
}
export default function Home() {
return (<App />);
return <App />;
}

View File

@@ -1,25 +1,35 @@
"use client";
'use client';
import dynamic from "next/dynamic";
import type { Session } from "next-auth";
import { SessionProvider } from "next-auth/react";
import { MiniAppProvider } from "@neynar/react";
import { SafeFarcasterSolanaProvider } from "~/components/providers/SafeFarcasterSolanaProvider";
import { ANALYTICS_ENABLED } from "~/lib/constants";
import dynamic from 'next/dynamic';
import type { Session } from 'next-auth';
import { SessionProvider } from 'next-auth/react';
import { MiniAppProvider } from '@neynar/react';
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
import { ANALYTICS_ENABLED } from '~/lib/constants';
const WagmiProvider = dynamic(
() => import("~/components/providers/WagmiProvider"),
() => import('~/components/providers/WagmiProvider'),
{
ssr: false,
}
);
export function Providers({ session, children }: { session: Session | null, children: React.ReactNode }) {
const solanaEndpoint = process.env.SOLANA_RPC_ENDPOINT || "https://solana-rpc.publicnode.com";
export function Providers({
session,
children,
}: {
session: Session | null;
children: React.ReactNode;
}) {
const solanaEndpoint =
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
return (
<SessionProvider session={session}>
<WagmiProvider>
<MiniAppProvider analyticsEnabled={ANALYTICS_ENABLED} backButtonEnabled={true}>
<MiniAppProvider
analyticsEnabled={ANALYTICS_ENABLED}
backButtonEnabled={true}
>
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
{children}
</SafeFarcasterSolanaProvider>

View File

@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { APP_URL, APP_NAME, APP_DESCRIPTION } from "~/lib/constants";
import { getMiniAppEmbedMetadata } from "~/lib/utils";
import type { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { APP_URL, APP_NAME, APP_DESCRIPTION } from '~/lib/constants';
import { getMiniAppEmbedMetadata } from '~/lib/utils';
export const revalidate = 300;
// This is an example of how to generate a dynamically generated share page based on fid:
@@ -23,12 +23,12 @@ export async function generateMetadata({
images: [imageUrl],
},
other: {
"fc:frame": JSON.stringify(getMiniAppEmbedMetadata(imageUrl)),
'fc:frame': JSON.stringify(getMiniAppEmbedMetadata(imageUrl)),
},
};
}
export default function SharePage() {
// redirect to home page
redirect("/");
redirect('/');
}

View File

@@ -1,8 +1,8 @@
import { AuthOptions, getServerSession } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
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" {
declare module 'next-auth' {
interface Session {
user: {
fid: number;
@@ -26,34 +26,34 @@ function getDomainFromUrl(urlString: string | undefined): string {
}
export const authOptions: AuthOptions = {
// Configure one or more authentication providers
// Configure one or more authentication providers
providers: [
CredentialsProvider({
name: "Sign in with Farcaster",
name: 'Sign in with Farcaster',
credentials: {
message: {
label: "Message",
type: "text",
placeholder: "0x0",
label: 'Message',
type: 'text',
placeholder: '0x0',
},
signature: {
label: "Signature",
type: "text",
placeholder: "0x0",
label: 'Signature',
type: 'text',
placeholder: '0x0',
},
// In a production app with a server, these should be fetched from
// your Farcaster data indexer rather than have them accepted as part
// of credentials.
// question: should these natively use the Neynar API?
name: {
label: "Name",
type: "text",
placeholder: "0x0",
label: 'Name',
type: 'text',
placeholder: '0x0',
},
pfp: {
label: "Pfp",
type: "text",
placeholder: "0x0",
label: 'Pfp',
type: 'text',
placeholder: '0x0',
},
},
async authorize(credentials, req) {
@@ -100,30 +100,30 @@ export const authOptions: AuthOptions = {
name: `next-auth.session-token`,
options: {
httpOnly: true,
sameSite: "none",
path: "/",
secure: true
}
sameSite: 'none',
path: '/',
secure: true,
},
},
callbackUrl: {
name: `next-auth.callback-url`,
options: {
sameSite: "none",
path: "/",
secure: true
}
sameSite: 'none',
path: '/',
secure: true,
},
},
csrfToken: {
name: `next-auth.csrf-token`,
options: {
httpOnly: true,
sameSite: "none",
path: "/",
secure: true
}
}
}
}
sameSite: 'none',
path: '/',
secure: true,
},
},
},
};
export const getSession = async () => {
try {
@@ -132,4 +132,4 @@ export const getSession = async () => {
console.error('Error getting server session:', error);
return null;
}
}
};

View File

@@ -1,19 +1,24 @@
"use client";
'use client';
import { useEffect } from "react";
import { useMiniApp } from "@neynar/react";
import { Header } from "~/components/ui/Header";
import { Footer } from "~/components/ui/Footer";
import { HomeTab, ActionsTab, ContextTab, WalletTab } from "~/components/ui/tabs";
import { USE_WALLET } from "~/lib/constants";
import { useNeynarUser } from "../hooks/useNeynarUser";
import { useEffect } from 'react';
import { useMiniApp } from '@neynar/react';
import { Header } from '~/components/ui/Header';
import { Footer } from '~/components/ui/Footer';
import {
HomeTab,
ActionsTab,
ContextTab,
WalletTab,
} from '~/components/ui/tabs';
import { USE_WALLET } from '~/lib/constants';
import { useNeynarUser } from '../hooks/useNeynarUser';
// --- Types ---
export enum Tab {
Home = "home",
Actions = "actions",
Context = "context",
Wallet = "wallet",
Home = 'home',
Actions = 'actions',
Context = 'context',
Wallet = 'wallet',
}
export interface AppProps {
@@ -22,44 +27,39 @@ export interface AppProps {
/**
* App component serves as the main container for the mini app interface.
*
*
* This component orchestrates the overall mini app experience by:
* - Managing tab navigation and state
* - Handling Farcaster mini app initialization
* - Coordinating wallet and context state
* - Providing error handling and loading states
* - Rendering the appropriate tab content based on user selection
*
*
* The component integrates with the Neynar SDK for Farcaster functionality
* and Wagmi for wallet management. It provides a complete mini app
* experience with multiple tabs for different functionality areas.
*
*
* Features:
* - Tab-based navigation (Home, Actions, Context, Wallet)
* - Farcaster mini app integration
* - Wallet connection management
* - Error handling and display
* - Loading states for async operations
*
*
* @param props - Component props
* @param props.title - Optional title for the mini app (defaults to "Neynar Starter Kit")
*
*
* @example
* ```tsx
* <App title="My Mini App" />
* ```
*/
export default function App(
{ title }: AppProps = { title: "Neynar Starter Kit" }
{ title }: AppProps = { title: 'Neynar Starter Kit' }
) {
// --- Hooks ---
const {
isSDKLoaded,
context,
setInitialTab,
setActiveTab,
currentTab,
} = useMiniApp();
const { isSDKLoaded, context, setInitialTab, setActiveTab, currentTab } =
useMiniApp();
// --- Neynar user hook ---
const { user: neynarUser } = useNeynarUser(context || undefined);
@@ -67,7 +67,7 @@ export default function App(
// --- Effects ---
/**
* Sets the initial tab to "home" when the SDK is loaded.
*
*
* This effect ensures that users start on the home tab when they first
* load the mini app. It only runs when the SDK is fully loaded to
* prevent errors during initialization.
@@ -115,9 +115,12 @@ export default function App(
{currentTab === Tab.Wallet && <WalletTab />}
{/* Footer with navigation */}
<Footer activeTab={currentTab as Tab} setActiveTab={setActiveTab} showWallet={USE_WALLET} />
<Footer
activeTab={currentTab as Tab}
setActiveTab={setActiveTab}
showWallet={USE_WALLET}
/>
</div>
</div>
);
}

View File

@@ -1,9 +1,12 @@
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/frame-sdk';
const FarcasterSolanaProvider = dynamic(
() => import('@farcaster/mini-app-solana').then(mod => mod.FarcasterSolanaProvider),
() =>
import('@farcaster/mini-app-solana').then(
mod => mod.FarcasterSolanaProvider
),
{ ssr: false }
);
@@ -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);

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/frame-wagmi-connector";
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/frame-wagmi-connector';
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';
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,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,9 +84,7 @@ 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

@@ -5,43 +5,40 @@ interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
size?: 'sm' | 'md' | 'lg';
}
export function Button({
children,
className = "",
isLoading = false,
export function Button({
children,
className = '',
isLoading = false,
variant = 'primary',
size = 'md',
...props
...props
}: ButtonProps) {
const baseClasses = "btn";
const baseClasses = 'btn';
const variantClasses = {
primary: "btn-primary",
secondary: "btn-secondary",
outline: "btn-outline"
};
const sizeClasses = {
sm: "px-3 py-1.5 text-xs",
md: "px-4 py-2 text-sm",
lg: "px-6 py-3 text-base"
primary: 'btn-primary',
secondary: 'btn-secondary',
outline: 'btn-outline',
};
const fullWidthClasses = "w-full max-w-xs mx-auto block";
const sizeClasses = {
sm: 'px-3 py-1.5 text-xs',
md: 'px-4 py-2 text-sm',
lg: 'px-6 py-3 text-base',
};
const fullWidthClasses = 'w-full max-w-xs mx-auto block';
const combinedClasses = [
baseClasses,
variantClasses[variant],
sizeClasses[size],
fullWidthClasses,
className
className,
].join(' ');
return (
<button
className={combinedClasses}
{...props}
>
<button className={combinedClasses} {...props}>
{isLoading ? (
<div className="flex items-center justify-center">
<div className="spinner-primary h-5 w-5" />

View File

@@ -1,5 +1,5 @@
import React from "react";
import { Tab } from "~/components/App";
import React from 'react';
import { Tab } from '~/components/App';
interface FooterProps {
activeTab: Tab;
@@ -7,13 +7,19 @@ interface FooterProps {
showWallet?: boolean;
}
export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWallet = false }) => (
export const Footer: React.FC<FooterProps> = ({
activeTab,
setActiveTab,
showWallet = false,
}) => (
<div className="fixed bottom-0 left-0 right-0 mx-4 mb-4 bg-gray-100 dark:bg-gray-800 border-[3px] border-double border-primary px-2 py-2 rounded-lg z-50">
<div className="flex justify-around items-center h-14">
<button
onClick={() => setActiveTab(Tab.Home)}
className={`flex flex-col items-center justify-center w-full h-full ${
activeTab === Tab.Home ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
activeTab === Tab.Home
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl">🏠</span>
@@ -22,7 +28,9 @@ export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWal
<button
onClick={() => setActiveTab(Tab.Actions)}
className={`flex flex-col items-center justify-center w-full h-full ${
activeTab === Tab.Actions ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
activeTab === Tab.Actions
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl"></span>
@@ -31,7 +39,9 @@ export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWal
<button
onClick={() => setActiveTab(Tab.Context)}
className={`flex flex-col items-center justify-center w-full h-full ${
activeTab === Tab.Context ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
activeTab === Tab.Context
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl">📋</span>
@@ -41,7 +51,9 @@ export const Footer: React.FC<FooterProps> = ({ activeTab, setActiveTab, showWal
<button
onClick={() => setActiveTab(Tab.Wallet)}
className={`flex flex-col items-center justify-center w-full h-full ${
activeTab === Tab.Wallet ? 'text-primary dark:text-primary-light' : 'text-gray-500 dark:text-gray-400'
activeTab === Tab.Wallet
? 'text-primary dark:text-primary-light'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<span className="text-xl">👛</span>

View File

@@ -1,9 +1,9 @@
"use client";
'use client';
import { useState } from "react";
import { APP_NAME } from "~/lib/constants";
import sdk from "@farcaster/frame-sdk";
import { useMiniApp } from "@neynar/react";
import { useState } from 'react';
import { APP_NAME } from '~/lib/constants';
import sdk from '@farcaster/frame-sdk';
import { useMiniApp } from '@neynar/react';
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>

View File

@@ -3,7 +3,7 @@
import { useCallback, useState, useEffect } from 'react';
import { Button } from './Button';
import { useMiniApp } from '@neynar/react';
import { type ComposeCast } from "@farcaster/frame-sdk";
import { type ComposeCast } from '@farcaster/frame-sdk';
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) {

View File

@@ -1,22 +1,22 @@
import * as React from "react"
import * as React from 'react';
import { cn } from "~/lib/utils"
import { cn } from '~/lib/utils';
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-base ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-neutral-800 dark:bg-neutral-950 dark:ring-offset-neutral-950 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300",
'flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-base ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-neutral-800 dark:bg-neutral-950 dark:ring-offset-neutral-950 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300',
className
)}
ref={ref}
{...props}
/>
)
);
}
)
Input.displayName = "Input"
);
Input.displayName = 'Input';
export { Input }
export { Input };

View File

@@ -1,14 +1,14 @@
"use client"
'use client';
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from "~/lib/utils"
import { cn } from '~/lib/utils';
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
@@ -20,7 +20,7 @@ const Label = React.forwardRef<
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label }
export { Label };

View File

@@ -1,15 +1,15 @@
"use client";
'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/frame-sdk";
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/frame-sdk';
/**
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
*
*
* This component provides the main interaction interface for users to:
* - Share the mini app with others
* - Sign in with Farcaster
@@ -17,10 +17,10 @@ import { type Haptics } from "@farcaster/frame-sdk";
* - Trigger haptic feedback
* - Add the mini app to their client
* - Copy share URLs
*
*
* The component uses the useMiniApp hook to access Farcaster context and actions.
* All state is managed locally within this component.
*
*
* @example
* ```tsx
* <ActionsTab />
@@ -28,63 +28,65 @@ import { type Haptics } from "@farcaster/frame-sdk";
*/
export function ActionsTab() {
// --- Hooks ---
const {
actions,
added,
notificationDetails,
haptics,
context,
} = useMiniApp();
const { actions, added, notificationDetails, haptics, context } =
useMiniApp();
// --- State ---
const [notificationState, setNotificationState] = useState({
sendStatus: "",
sendStatus: '',
shareUrlCopied: false,
});
const [selectedHapticIntensity, setSelectedHapticIntensity] = useState<Haptics.ImpactOccurredType>('medium');
const [selectedHapticIntensity, setSelectedHapticIntensity] =
useState<Haptics.ImpactOccurredType>('medium');
// --- Handlers ---
/**
* Sends a notification to the current user's Farcaster account.
*
*
* This function makes a POST request to the /api/send-notification endpoint
* with the user's FID and notification details. It handles different response
* statuses including success (200), rate limiting (429), and errors.
*
*
* @returns Promise that resolves when the notification is sent or fails
*/
const sendFarcasterNotification = useCallback(async () => {
setNotificationState((prev) => ({ ...prev, sendStatus: "" }));
setNotificationState(prev => ({ ...prev, sendStatus: '' }));
if (!notificationDetails || !context) {
return;
}
try {
const response = await fetch("/api/send-notification", {
method: "POST",
mode: "same-origin",
headers: { "Content-Type": "application/json" },
const response = await fetch('/api/send-notification', {
method: 'POST',
mode: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fid: context.user.fid,
notificationDetails,
}),
});
if (response.status === 200) {
setNotificationState((prev) => ({ ...prev, sendStatus: "Success" }));
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) => ({ ...prev, sendStatus: `Error: ${responseText}` }));
setNotificationState(prev => ({
...prev,
sendStatus: `Error: ${responseText}`,
}));
} catch (error) {
setNotificationState((prev) => ({ ...prev, sendStatus: `Error: ${error}` }));
setNotificationState(prev => ({
...prev,
sendStatus: `Error: ${error}`,
}));
}
}, [context, notificationDetails]);
/**
* Copies the share URL for the current user to the clipboard.
*
*
* This function generates a share URL using the user's FID and copies it
* to the clipboard. It shows a temporary "Copied!" message for 2 seconds.
*/
@@ -92,14 +94,18 @@ 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 }));
setTimeout(() => setNotificationState((prev) => ({ ...prev, shareUrlCopied: false })), 2000);
setNotificationState(prev => ({ ...prev, shareUrlCopied: true }));
setTimeout(
() =>
setNotificationState(prev => ({ ...prev, shareUrlCopied: false })),
2000
);
}
}, [context?.user?.fid]);
/**
* Triggers haptic feedback with the selected intensity.
*
*
* This function calls the haptics.impactOccurred method with the current
* selectedHapticIntensity setting. It handles errors gracefully by logging them.
*/
@@ -115,12 +121,14 @@ export function ActionsTab() {
return (
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
{/* Share functionality */}
<ShareButton
<ShareButton
buttonText="Share Mini App"
cast={{
text: "Check out this awesome frame @1 @2 @3! 🚀🪐",
text: 'Check out this awesome frame @1 @2 @3! 🚀🪐',
bestFriends: true,
embeds: [`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`]
embeds: [
`${process.env.NEXT_PUBLIC_URL}/share/${context?.user?.fid || ''}`,
],
}}
className="w-full"
/>
@@ -129,7 +137,14 @@ export function ActionsTab() {
<SignIn />
{/* Mini app actions */}
<Button onClick={() => actions.openUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")} className="w-full">Open Link</Button>
<Button
onClick={() =>
actions.openUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
}
className="w-full"
>
Open Link
</Button>
<Button onClick={actions.addMiniApp} disabled={added} className="w-full">
Add Mini App to Client
@@ -141,17 +156,21 @@ export function ActionsTab() {
Send notification result: {notificationState.sendStatus}
</div>
)}
<Button onClick={sendFarcasterNotification} disabled={!notificationDetails} className="w-full">
<Button
onClick={sendFarcasterNotification}
disabled={!notificationDetails}
className="w-full"
>
Send notification
</Button>
{/* Share URL copying */}
<Button
<Button
onClick={copyUserShareUrl}
disabled={!context?.user?.fid}
className="w-full"
>
{notificationState.shareUrlCopied ? "Copied!" : "Copy share URL"}
{notificationState.shareUrlCopied ? 'Copied!' : 'Copy share URL'}
</Button>
{/* Haptic feedback controls */}
@@ -161,7 +180,11 @@ export function ActionsTab() {
</label>
<select
value={selectedHapticIntensity}
onChange={(e) => setSelectedHapticIntensity(e.target.value as Haptics.ImpactOccurredType)}
onChange={e =>
setSelectedHapticIntensity(
e.target.value as Haptics.ImpactOccurredType
)
}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value={'light'}>Light</option>
@@ -170,13 +193,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

@@ -1,19 +1,19 @@
"use client";
'use client';
import { useMiniApp } from "@neynar/react";
import { useMiniApp } from '@neynar/react';
/**
* ContextTab component displays the current mini app context in JSON format.
*
*
* This component provides a developer-friendly view of the Farcaster mini app context,
* including user information, client details, and other contextual data. It's useful
* for debugging and understanding what data is available to the mini app.
*
*
* The context includes:
* - User information (FID, username, display name, profile picture)
* - Client information (safe area insets, platform details)
* - Mini app configuration and state
*
*
* @example
* ```tsx
* <ContextTab />
@@ -21,7 +21,7 @@ import { useMiniApp } from "@neynar/react";
*/
export function ContextTab() {
const { context } = useMiniApp();
return (
<div className="mx-6">
<h2 className="text-lg font-semibold mb-2">Context</h2>
@@ -32,4 +32,4 @@ export function ContextTab() {
</div>
</div>
);
}
}

View File

@@ -1,12 +1,12 @@
"use client";
'use client';
/**
* HomeTab component displays the main landing content for the mini app.
*
*
* This is the default tab that users see when they first open the mini app.
* It provides a simple welcome message and placeholder content that can be
* customized for specific use cases.
*
*
* @example
* ```tsx
* <HomeTab />
@@ -21,4 +21,4 @@ export function HomeTab() {
</div>
</div>
);
}
}

View File

@@ -1,22 +1,32 @@
"use client";
'use client';
import { useCallback, useMemo, useState, useEffect } from "react";
import { useAccount, useSendTransaction, useSignTypedData, useWaitForTransactionReceipt, useDisconnect, useConnect, useSwitchChain, useChainId, type Connector } from "wagmi";
import { useCallback, useMemo, useState, useEffect } from 'react';
import {
useAccount,
useSendTransaction,
useSignTypedData,
useWaitForTransactionReceipt,
useDisconnect,
useConnect,
useSwitchChain,
useChainId,
type Connector,
} from 'wagmi';
import { useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
import { base, degen, mainnet, optimism, unichain } from "wagmi/chains";
import { Button } from "../Button";
import { truncateAddress } from "../../../lib/truncateAddress";
import { renderError } from "../../../lib/errorUtils";
import { SignEvmMessage } from "../wallet/SignEvmMessage";
import { SendEth } from "../wallet/SendEth";
import { SignSolanaMessage } from "../wallet/SignSolanaMessage";
import { SendSolana } from "../wallet/SendSolana";
import { USE_WALLET, APP_NAME } from "../../../lib/constants";
import { useMiniApp } from "@neynar/react";
import { base, degen, mainnet, optimism, unichain } from 'wagmi/chains';
import { Button } from '../Button';
import { truncateAddress } from '../../../lib/truncateAddress';
import { renderError } from '../../../lib/errorUtils';
import { SignEvmMessage } from '../wallet/SignEvmMessage';
import { SendEth } from '../wallet/SendEth';
import { SignSolanaMessage } from '../wallet/SignSolanaMessage';
import { SendSolana } from '../wallet/SendSolana';
import { USE_WALLET, APP_NAME } from '../../../lib/constants';
import { useMiniApp } from '@neynar/react';
/**
* WalletTab component manages wallet-related UI for both EVM and Solana chains.
*
*
* This component provides a comprehensive wallet interface that supports:
* - EVM wallet connections (Farcaster Frame, Coinbase Wallet, MetaMask)
* - Solana wallet integration
@@ -24,10 +34,10 @@ import { useMiniApp } from "@neynar/react";
* - Transaction sending for both chains
* - Chain switching for EVM chains
* - Auto-connection in Farcaster clients
*
*
* The component automatically detects when running in a Farcaster client
* and attempts to auto-connect using the Farcaster Frame connector.
*
*
* @example
* ```tsx
* <WalletTab />
@@ -47,7 +57,8 @@ function WalletStatus({ address, chainId }: WalletStatusProps) {
<>
{address && (
<div className="text-xs w-full">
Address: <pre className="inline w-full">{truncateAddress(address)}</pre>
Address:{' '}
<pre className="inline w-full">{truncateAddress(address)}</pre>
</div>
)}
{chainId && (
@@ -90,13 +101,19 @@ function ConnectionControls({
if (context) {
return (
<div className="space-y-2 w-full">
<Button onClick={() => connect({ connector: connectors[0] })} className="w-full">
<Button
onClick={() => connect({ connector: connectors[0] })}
className="w-full"
>
Connect (Auto)
</Button>
<Button
onClick={() => {
console.log("Manual Farcaster connection attempt");
console.log("Connectors:", connectors.map((c, i) => `${i}: ${c.name}`));
console.log('Manual Farcaster connection attempt');
console.log(
'Connectors:',
connectors.map((c, i) => `${i}: ${c.name}`)
);
connect({ connector: connectors[0] });
}}
className="w-full"
@@ -108,10 +125,16 @@ function ConnectionControls({
}
return (
<div className="space-y-3 w-full">
<Button onClick={() => connect({ connector: connectors[1] })} className="w-full">
<Button
onClick={() => connect({ connector: connectors[1] })}
className="w-full"
>
Connect Coinbase Wallet
</Button>
<Button onClick={() => connect({ connector: connectors[2] })} className="w-full">
<Button
onClick={() => connect({ connector: connectors[2] })}
className="w-full"
>
Connect MetaMask
</Button>
</div>
@@ -120,8 +143,10 @@ function ConnectionControls({
export function WalletTab() {
// --- State ---
const [evmContractTransactionHash, setEvmContractTransactionHash] = useState<string | null>(null);
const [evmContractTransactionHash, setEvmContractTransactionHash] = useState<
string | null
>(null);
// --- Hooks ---
const { context } = useMiniApp();
const { address, isConnected } = useAccount();
@@ -137,10 +162,12 @@ export function WalletTab() {
isPending: isEvmTransactionPending,
} = useSendTransaction();
const { isLoading: isEvmTransactionConfirming, isSuccess: isEvmTransactionConfirmed } =
useWaitForTransactionReceipt({
hash: evmContractTransactionHash as `0x${string}`,
});
const {
isLoading: isEvmTransactionConfirming,
isSuccess: isEvmTransactionConfirmed,
} = useWaitForTransactionReceipt({
hash: evmContractTransactionHash as `0x${string}`,
});
const {
signTypedData,
@@ -162,38 +189,47 @@ export function WalletTab() {
// --- Effects ---
/**
* Auto-connect when Farcaster context is available.
*
*
* This effect detects when the app is running in a Farcaster client
* and automatically attempts to connect using the Farcaster Frame connector.
* It includes comprehensive logging for debugging connection issues.
*/
useEffect(() => {
// Check if we're in a Farcaster client environment
const isInFarcasterClient = typeof window !== 'undefined' &&
(window.location.href.includes('warpcast.com') ||
window.location.href.includes('farcaster') ||
window.ethereum?.isFarcaster ||
context?.client);
if (context?.user?.fid && !isConnected && connectors.length > 0 && isInFarcasterClient) {
console.log("Attempting auto-connection with Farcaster context...");
console.log("- User FID:", context.user.fid);
console.log("- Available connectors:", connectors.map((c, i) => `${i}: ${c.name}`));
console.log("- Using connector:", connectors[0].name);
console.log("- In Farcaster client:", isInFarcasterClient);
const isInFarcasterClient =
typeof window !== 'undefined' &&
(window.location.href.includes('warpcast.com') ||
window.location.href.includes('farcaster') ||
window.ethereum?.isFarcaster ||
context?.client);
if (
context?.user?.fid &&
!isConnected &&
connectors.length > 0 &&
isInFarcasterClient
) {
console.log('Attempting auto-connection with Farcaster context...');
console.log('- User FID:', context.user.fid);
console.log(
'- Available connectors:',
connectors.map((c, i) => `${i}: ${c.name}`)
);
console.log('- Using connector:', connectors[0].name);
console.log('- In Farcaster client:', isInFarcasterClient);
// Use the first connector (farcasterFrame) for auto-connection
try {
connect({ connector: connectors[0] });
} catch (error) {
console.error("Auto-connection failed:", error);
console.error('Auto-connection failed:', error);
}
} else {
console.log("Auto-connection conditions not met:");
console.log("- Has context:", !!context?.user?.fid);
console.log("- Is connected:", isConnected);
console.log("- Has connectors:", connectors.length > 0);
console.log("- In Farcaster client:", isInFarcasterClient);
console.log('Auto-connection conditions not met:');
console.log('- Has context:', !!context?.user?.fid);
console.log('- Is connected:', isConnected);
console.log('- Has connectors:', connectors.length > 0);
console.log('- In Farcaster client:', isInFarcasterClient);
}
}, [context?.user?.fid, isConnected, connectors, connect, context?.client]);
@@ -227,7 +263,7 @@ export function WalletTab() {
/**
* Sends a transaction to call the yoink() function on the Yoink contract.
*
*
* This function sends a transaction to a specific contract address with
* the encoded function call data for the yoink() function.
*/
@@ -235,11 +271,11 @@ export function WalletTab() {
sendTransaction(
{
// call yoink() on Yoink contract
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
data: "0x9846cd9efc000023c0",
to: '0x4bBFD120d9f352A0BEd7a014bd67913a2007a878',
data: '0x9846cd9efc000023c0',
},
{
onSuccess: (hash) => {
onSuccess: hash => {
setEvmContractTransactionHash(hash);
},
}
@@ -248,7 +284,7 @@ export function WalletTab() {
/**
* Signs typed data using EIP-712 standard.
*
*
* This function creates a typed data structure with the app name, version,
* and chain ID, then requests the user to sign it.
*/
@@ -256,16 +292,16 @@ export function WalletTab() {
signTypedData({
domain: {
name: APP_NAME,
version: "1",
version: '1',
chainId,
},
types: {
Message: [{ name: "content", type: "string" }],
Message: [{ name: 'content', type: 'string' }],
},
message: {
content: `Hello from ${APP_NAME}!`,
},
primaryType: "Message",
primaryType: 'Message',
});
}, [chainId, signTypedData]);
@@ -308,12 +344,12 @@ export function WalletTab() {
<div className="text-xs w-full">
<div>Hash: {truncateAddress(evmContractTransactionHash)}</div>
<div>
Status:{" "}
Status:{' '}
{isEvmTransactionConfirming
? "Confirming..."
? 'Confirming...'
: isEvmTransactionConfirmed
? "Confirmed!"
: "Pending"}
? 'Confirmed!'
: 'Pending'}
</div>
</div>
)}
@@ -347,4 +383,4 @@ export function WalletTab() {
)}
</div>
);
}
}

View File

@@ -1,4 +1,4 @@
export { HomeTab } from './HomeTab';
export { ActionsTab } from './ActionsTab';
export { ContextTab } from './ContextTab';
export { WalletTab } from './WalletTab';
export { WalletTab } from './WalletTab';

View File

@@ -1,25 +1,29 @@
"use client";
'use client';
import { useCallback, useMemo } from "react";
import { useAccount, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
import { base } from "wagmi/chains";
import { Button } from "../Button";
import { truncateAddress } from "../../../lib/truncateAddress";
import { renderError } from "../../../lib/errorUtils";
import { useCallback, useMemo } from 'react';
import {
useAccount,
useSendTransaction,
useWaitForTransactionReceipt,
} from 'wagmi';
import { base } from 'wagmi/chains';
import { Button } from '../Button';
import { truncateAddress } from '../../../lib/truncateAddress';
import { renderError } from '../../../lib/errorUtils';
/**
* SendEth component handles sending ETH transactions to protocol guild addresses.
*
*
* This component provides a simple interface for users to send small amounts
* of ETH to protocol guild addresses. It automatically selects the appropriate
* recipient address based on the current chain and displays transaction status.
*
*
* Features:
* - Chain-specific recipient addresses
* - Transaction status tracking
* - Error handling and display
* - Transaction hash display
*
*
* @example
* ```tsx
* <SendEth />
@@ -36,32 +40,34 @@ export function SendEth() {
isPending: isEthTransactionPending,
} = useSendTransaction();
const { isLoading: isEthTransactionConfirming, isSuccess: isEthTransactionConfirmed } =
useWaitForTransactionReceipt({
hash: ethTransactionHash,
});
const {
isLoading: isEthTransactionConfirming,
isSuccess: isEthTransactionConfirmed,
} = useWaitForTransactionReceipt({
hash: ethTransactionHash,
});
// --- Computed Values ---
/**
* Determines the recipient address based on the current chain.
*
*
* Uses different protocol guild addresses for different chains:
* - Base: 0x32e3C7fD24e175701A35c224f2238d18439C7dBC
* - Other chains: 0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830
*
*
* @returns string - The recipient address for the current chain
*/
const protocolGuildRecipientAddress = useMemo(() => {
// Protocol guild address
return chainId === base.id
? "0x32e3C7fD24e175701A35c224f2238d18439C7dBC"
: "0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830";
? '0x32e3C7fD24e175701A35c224f2238d18439C7dBC'
: '0xB3d8d7887693a9852734b4D25e9C0Bb35Ba8a830';
}, [chainId]);
// --- Handlers ---
/**
* Handles sending the ETH transaction.
*
*
* This function sends a small amount of ETH (1 wei) to the protocol guild
* address for the current chain. The transaction is sent using the wagmi
* sendTransaction hook.
@@ -88,15 +94,15 @@ export function SendEth() {
<div className="mt-2 text-xs">
<div>Hash: {truncateAddress(ethTransactionHash)}</div>
<div>
Status:{" "}
Status:{' '}
{isEthTransactionConfirming
? "Confirming..."
? 'Confirming...'
: isEthTransactionConfirmed
? "Confirmed!"
: "Pending"}
? 'Confirmed!'
: 'Pending'}
</div>
</div>
)}
</>
);
}
}

View File

@@ -1,29 +1,32 @@
"use client";
'use client';
import { useCallback, useState } from "react";
import { useConnection as useSolanaConnection, useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
import { useCallback, useState } from 'react';
import {
useConnection as useSolanaConnection,
useWallet as useSolanaWallet,
} from '@solana/wallet-adapter-react';
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
import { Button } from "../Button";
import { truncateAddress } from "../../../lib/truncateAddress";
import { renderError } from "../../../lib/errorUtils";
import { Button } from '../Button';
import { truncateAddress } from '../../../lib/truncateAddress';
import { renderError } from '../../../lib/errorUtils';
/**
* SendSolana component handles sending SOL transactions on Solana.
*
*
* This component provides a simple interface for users to send SOL transactions
* using their connected Solana wallet. It includes transaction status tracking
* and error handling.
*
*
* Features:
* - SOL transaction sending
* - Transaction status tracking
* - Error handling and display
* - Loading state management
*
*
* Note: This component is a placeholder implementation. In a real application,
* you would integrate with a Solana wallet adapter and transaction library
* like @solana/web3.js to handle actual transactions.
*
*
* @example
* ```tsx
* <SendSolana />
@@ -42,7 +45,8 @@ export function SendSolana() {
// This should be replaced but including it from the original demo
// https://github.com/farcasterxyz/frames-v2-demo/blob/main/src/components/Demo.tsx#L718
const ashoatsPhantomSolanaWallet = 'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
const ashoatsPhantomSolanaWallet =
'Ao3gLNZAsbrmnusWVqQCPMrcqNi6jdYgu8T6NCoXXQu1';
/**
* Handles sending the Solana transaction
@@ -67,12 +71,13 @@ export function SendSolana() {
fromPubkey: new PublicKey(fromPubkeyStr),
toPubkey: new PublicKey(toPubkeyStr),
lamports: 0n,
}),
})
);
transaction.recentBlockhash = blockhash;
transaction.feePayer = new PublicKey(fromPubkeyStr);
const simulation = await solanaConnection.simulateTransaction(transaction);
const simulation =
await solanaConnection.simulateTransaction(transaction);
if (simulation.value.err) {
// Gather logs and error details for debugging
const logs = simulation.value.logs?.join('\n') ?? 'No logs';
@@ -100,7 +105,8 @@ export function SendSolana() {
>
Send Transaction (sol)
</Button>
{solanaTransactionState.status === 'error' && renderError(solanaTransactionState.error)}
{solanaTransactionState.status === 'error' &&
renderError(solanaTransactionState.error)}
{solanaTransactionState.status === 'success' && (
<div className="mt-2 text-xs">
<div>Hash: {truncateAddress(solanaTransactionState.signature)}</div>
@@ -108,4 +114,4 @@ export function SendSolana() {
)}
</>
);
}
}

View File

@@ -1,26 +1,26 @@
"use client";
'use client';
import { useCallback } from "react";
import { useAccount, useConnect, useSignMessage } from "wagmi";
import { base } from "wagmi/chains";
import { Button } from "../Button";
import { config } from "../../providers/WagmiProvider";
import { APP_NAME } from "../../../lib/constants";
import { renderError } from "../../../lib/errorUtils";
import { useCallback } from 'react';
import { useAccount, useConnect, useSignMessage } from 'wagmi';
import { base } from 'wagmi/chains';
import { Button } from '../Button';
import { config } from '../../providers/WagmiProvider';
import { APP_NAME } from '../../../lib/constants';
import { renderError } from '../../../lib/errorUtils';
/**
* SignEvmMessage component handles signing messages on EVM-compatible chains.
*
*
* This component provides a simple interface for users to sign messages using
* their connected EVM wallet. It automatically handles wallet connection if
* the user is not already connected, and displays the signature result.
*
*
* Features:
* - Automatic wallet connection if needed
* - Message signing with app name
* - Error handling and display
* - Signature result display
*
*
* @example
* ```tsx
* <SignEvmMessage />
@@ -41,12 +41,12 @@ export function SignEvmMessage() {
// --- Handlers ---
/**
* Handles the message signing process.
*
*
* This function first ensures the user is connected to an EVM wallet,
* then requests them to sign a message containing the app name.
* If the user is not connected, it automatically connects using the
* Farcaster Frame connector.
*
*
* @returns Promise<void>
*/
const signEvmMessage = useCallback(async () => {
@@ -78,4 +78,4 @@ export function SignEvmMessage() {
)}
</>
);
}
}

View File

@@ -1,24 +1,24 @@
"use client";
'use client';
import { useCallback, useState } from "react";
import { signIn, signOut, getCsrfToken } from "next-auth/react";
import sdk, { SignIn as SignInCore } from "@farcaster/frame-sdk";
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/frame-sdk';
import { useSession } from 'next-auth/react';
import { Button } from '../Button';
/**
* SignIn component handles Farcaster authentication using Sign-In with Farcaster (SIWF).
*
*
* This component provides a complete authentication flow for Farcaster users:
* - Generates nonces for secure authentication
* - Handles the SIWF flow using the Farcaster SDK
* - Manages NextAuth session state
* - Provides sign-out functionality
* - Displays authentication status and results
*
*
* The component integrates with both the Farcaster Frame SDK and NextAuth
* to provide seamless authentication within mini apps.
*
*
* @example
* ```tsx
* <SignIn />
@@ -45,69 +45,69 @@ export function SignIn() {
// --- Handlers ---
/**
* Generates a nonce for the sign-in process.
*
*
* This function retrieves a CSRF token from NextAuth to use as a nonce
* for the SIWF authentication flow. The nonce ensures the authentication
* request is fresh and prevents replay attacks.
*
*
* @returns Promise<string> - The generated nonce token
* @throws Error if unable to generate nonce
*/
const getNonce = useCallback(async () => {
const nonce = await getCsrfToken();
if (!nonce) throw new Error("Unable to generate nonce");
if (!nonce) throw new Error('Unable to generate nonce');
return nonce;
}, []);
/**
* Handles the sign-in process using Farcaster SDK.
*
*
* This function orchestrates the complete SIWF flow:
* 1. Generates a nonce for security
* 2. Calls the Farcaster SDK to initiate sign-in
* 3. Submits the result to NextAuth for session management
* 4. Handles various error conditions including user rejection
*
*
* @returns Promise<void>
*/
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('credentials', {
message: result.message,
signature: result.signature,
redirect: false,
});
} catch (e) {
if (e instanceof SignInCore.RejectedByUser) {
setSignInFailure("Rejected by user");
setSignInFailure('Rejected by user');
return;
}
setSignInFailure("Unknown error");
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.
*
*
* @returns Promise<void>
*/
const handleSignOut = useCallback(async () => {
try {
setAuthState((prev) => ({ ...prev, signingOut: true }));
setAuthState(prev => ({ ...prev, signingOut: true }));
await signOut({ redirect: false });
setSignInResult(undefined);
} finally {
setAuthState((prev) => ({ ...prev, signingOut: false }));
setAuthState(prev => ({ ...prev, signingOut: false }));
}
}, []);
@@ -115,12 +115,12 @@ export function SignIn() {
return (
<>
{/* Authentication Buttons */}
{status !== "authenticated" && (
{status !== 'authenticated' && (
<Button onClick={handleSignIn} disabled={authState.signingIn}>
Sign In with Farcaster
</Button>
)}
{status === "authenticated" && (
{status === 'authenticated' && (
<Button onClick={handleSignOut} disabled={authState.signingOut}>
Sign out
</Button>
@@ -155,4 +155,4 @@ export function SignIn() {
)}
</>
);
}
}

View File

@@ -1,8 +1,8 @@
"use client";
'use client';
import { useCallback, useState } from "react";
import { Button } from "../Button";
import { renderError } from "../../../lib/errorUtils";
import { useCallback, useState } from 'react';
import { Button } from '../Button';
import { renderError } from '../../../lib/errorUtils';
interface SignSolanaMessageProps {
signMessage?: (message: Uint8Array) => Promise<Uint8Array>;
@@ -10,20 +10,20 @@ interface SignSolanaMessageProps {
/**
* SignSolanaMessage component handles signing messages on Solana.
*
*
* This component provides a simple interface for users to sign messages using
* their connected Solana wallet. It accepts a signMessage function as a prop
* and handles the complete signing flow including error handling.
*
*
* Features:
* - Message signing with Solana wallet
* - Error handling and display
* - Signature result display (base64 encoded)
* - Loading state management
*
*
* @param props - Component props
* @param props.signMessage - Function to sign messages with Solana wallet
*
*
* @example
* ```tsx
* <SignSolanaMessage signMessage={solanaWallet.signMessage} />
@@ -38,11 +38,11 @@ export function SignSolanaMessage({ signMessage }: SignSolanaMessageProps) {
// --- Handlers ---
/**
* Handles the Solana message signing process.
*
*
* This function encodes a message as UTF-8 bytes, signs it using the provided
* signMessage function, and displays the base64-encoded signature result.
* It includes comprehensive error handling and loading state management.
*
*
* @returns Promise<void>
*/
const handleSignMessage = useCallback(async () => {
@@ -51,7 +51,7 @@ export function SignSolanaMessage({ signMessage }: SignSolanaMessageProps) {
if (!signMessage) {
throw new Error('no Solana signMessage');
}
const input = new TextEncoder().encode("Hello from Solana!");
const input = new TextEncoder().encode('Hello from Solana!');
const signatureBytes = await signMessage(input);
const signature = btoa(String.fromCharCode(...signatureBytes));
setSignature(signature);
@@ -84,4 +84,4 @@ export function SignSolanaMessage({ signMessage }: SignSolanaMessageProps) {
)}
</>
);
}
}

View File

@@ -2,4 +2,4 @@ export { SignIn } from './SignIn';
export { SignEvmMessage } from './SignEvmMessage';
export { SendEth } from './SendEth';
export { SignSolanaMessage } from './SignSolanaMessage';
export { SendSolana } from './SendSolana';
export { SendSolana } from './SendSolana';

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useState } from 'react';
export interface NeynarUser {
fid: number;
@@ -19,20 +19,21 @@ export function useNeynarUser(context?: { user?: { fid?: number } }) {
setLoading(true);
setError(null);
fetch(`/api/users?fids=${context.user.fid}`)
.then((response) => {
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
.then(response => {
if (!response.ok)
throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
})
.then((data) => {
.then(data => {
if (data.users?.[0]) {
setUser(data.users[0]);
} else {
setUser(null);
}
})
.catch((err) => setError(err.message))
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, [context?.user?.fid]);
return { user, loading, error };
}
}

View File

@@ -1,10 +1,10 @@
/**
* Application constants and configuration values.
*
*
* This file contains all the configuration constants used throughout the mini app.
* These values are either sourced from environment variables or hardcoded and provide
* configuration for the app's appearance, behavior, and integration settings.
*
*
* NOTE: This file is automatically updated by the init script.
* Manual changes may be overwritten during project initialization.
*/
@@ -63,7 +63,7 @@ export const APP_SPLASH_URL = `${APP_URL}/splash.png`;
* Background color for the splash screen.
* Used as fallback when splash image is loading.
*/
export const APP_SPLASH_BACKGROUND_COLOR = "#f7f7f7";
export const APP_SPLASH_BACKGROUND_COLOR = '#f7f7f7';
// --- UI Configuration ---
/**
@@ -75,18 +75,19 @@ export const APP_BUTTON_TEXT = 'Launch NSK';
// --- Integration Configuration ---
/**
* Webhook URL for receiving events from Neynar.
*
*
* If Neynar API key and client ID are configured, uses the official
* Neynar webhook endpoint. Otherwise, falls back to a local webhook
* endpoint for development and testing.
*/
export const APP_WEBHOOK_URL = process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
export const APP_WEBHOOK_URL =
process.env.NEYNAR_API_KEY && process.env.NEYNAR_CLIENT_ID
? `https://api.neynar.com/f/app/${process.env.NEYNAR_CLIENT_ID}/event`
: `${APP_URL}/api/webhook`;
/**
* Flag to enable/disable wallet functionality.
*
*
* When true, wallet-related components and features are rendered.
* When false, wallet functionality is completely hidden from the UI.
* Useful for mini apps that don't require wallet integration.
@@ -95,7 +96,7 @@ export const USE_WALLET = true;
/**
* Flag to enable/disable analytics tracking.
*
*
* When true, usage analytics are collected and sent to Neynar.
* When false, analytics collection is disabled.
* Useful for privacy-conscious users or development environments.

View File

@@ -1,9 +1,9 @@
import { type ReactElement } from "react";
import { BaseError, UserRejectedRequestError } from "viem";
import { type ReactElement } from 'react';
import { BaseError, UserRejectedRequestError } from 'viem';
/**
* Renders an error object in a user-friendly format.
*
*
* This utility function takes an error object and renders it as a React element
* with consistent styling. It handles different types of errors including:
* - Error objects with message properties
@@ -11,14 +11,14 @@ import { BaseError, UserRejectedRequestError } from "viem";
* - String errors
* - Unknown error types
* - User rejection errors (special handling for wallet rejections)
*
*
* The rendered error is displayed in a gray container with monospace font
* for better readability of technical error details. User rejections are
* displayed with a simpler, more user-friendly message.
*
*
* @param error - The error object to render
* @returns ReactElement - A styled error display component, or null if no error
*
*
* @example
* ```tsx
* {isError && renderError(error)}
@@ -27,11 +27,11 @@ import { BaseError, UserRejectedRequestError } from "viem";
export function renderError(error: unknown): ReactElement | null {
// Handle null/undefined errors
if (!error) return null;
// Special handling for user rejections in wallet operations
if (error instanceof BaseError) {
const isUserRejection = error.walk(
(e) => e instanceof UserRejectedRequestError
e => e instanceof UserRejectedRequestError
);
if (isUserRejection) {
@@ -43,10 +43,10 @@ export function renderError(error: unknown): ReactElement | null {
);
}
}
// Extract error message from different error types
let errorMessage: string;
if (error instanceof Error) {
errorMessage = error.message;
} else if (typeof error === 'object' && error !== null && 'error' in error) {
@@ -63,4 +63,4 @@ export function renderError(error: unknown): ReactElement | null {
<div className="whitespace-pre-wrap break-words">{errorMessage}</div>
</div>
);
}
}

View File

@@ -1,16 +1,18 @@
import { FrameNotificationDetails } from "@farcaster/frame-sdk";
import { Redis } from "@upstash/redis";
import { APP_NAME } from "./constants";
import { FrameNotificationDetails } from '@farcaster/frame-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}`;

View File

@@ -1,11 +1,15 @@
import { NeynarAPIClient, Configuration, WebhookUserCreated } from '@neynar/nodejs-sdk';
import {
NeynarAPIClient,
Configuration,
WebhookUserCreated,
} from '@neynar/nodejs-sdk';
import { APP_URL } from './constants';
let neynarClient: NeynarAPIClient | null = null;
// Example usage:
// const client = getNeynarClient();
// const user = await client.lookupUserByFid(fid);
// const user = await client.lookupUserByFid(fid);
export function getNeynarClient() {
if (!neynarClient) {
const apiKey = process.env.NEYNAR_API_KEY;
@@ -33,12 +37,12 @@ export async function getNeynarUser(fid: number): Promise<User | null> {
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 sendNeynarMiniAppNotification({
fid,
@@ -58,19 +62,19 @@ export async function sendNeynarMiniAppNotification({
target_url: APP_URL,
};
const result = await client.publishFrameNotifications({
targetFids,
notification
const result = await client.publishFrameNotifications({
targetFids,
notification,
});
if (result.notification_deliveries.length > 0) {
return { state: "success" };
return { state: 'success' };
} else if (result.notification_deliveries.length === 0) {
return { state: "no_token" };
return { state: 'no_token' };
} else {
return { state: "error", error: result || "Unknown error" };
return { state: 'error', error: result || 'Unknown error' };
}
} catch (error) {
return { state: "error", error };
return { state: 'error', error };
}
}
}

View File

@@ -1,18 +1,18 @@
import {
SendNotificationRequest,
sendNotificationResponseSchema,
} from "@farcaster/frame-sdk";
import { getUserNotificationDetails } from "~/lib/kv";
import { APP_URL } from "./constants";
} from '@farcaster/frame-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,4 +1,4 @@
export const truncateAddress = (address: string) => {
if (!address) return "";
if (!address) return '';
return `${address.slice(0, 14)}...${address.slice(-12)}`;
};

View File

@@ -1,7 +1,18 @@
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { mnemonicToAccount } from 'viem/accounts';
import { APP_BUTTON_TEXT, APP_DESCRIPTION, APP_ICON_URL, APP_NAME, APP_OG_IMAGE_URL, APP_PRIMARY_CATEGORY, APP_SPLASH_BACKGROUND_COLOR, APP_TAGS, APP_URL, APP_WEBHOOK_URL } from './constants';
import {
APP_BUTTON_TEXT,
APP_DESCRIPTION,
APP_ICON_URL,
APP_NAME,
APP_OG_IMAGE_URL,
APP_PRIMARY_CATEGORY,
APP_SPLASH_BACKGROUND_COLOR,
APP_TAGS,
APP_URL,
APP_WEBHOOK_URL,
} from './constants';
import { APP_SPLASH_URL } from './constants';
interface MiniAppMetadata {
@@ -17,7 +28,7 @@ interface MiniAppMetadata {
description?: string;
primaryCategory?: string;
tags?: string[];
};
}
interface MiniAppManifest {
accountAssociation?: {
@@ -35,7 +46,7 @@ export function cn(...inputs: ClassValue[]) {
export function getSecretEnvVars() {
const seedPhrase = process.env.SEED_PHRASE;
const fid = process.env.FID;
if (!seedPhrase || !fid) {
return null;
}
@@ -45,12 +56,12 @@ export function getSecretEnvVars() {
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,
@@ -72,7 +83,10 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
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);
console.warn(
'Failed to parse MINI_APP_METADATA from environment:',
error
);
}
}
@@ -86,7 +100,9 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
const secretEnvVars = getSecretEnvVars();
if (!secretEnvVars) {
console.warn('No seed phrase or FID found in environment variables -- generating unsigned metadata');
console.warn(
'No seed phrase or FID found in environment variables -- generating unsigned metadata'
);
}
let accountAssociation;
@@ -100,34 +116,41 @@ export async function getFarcasterMetadata(): Promise<MiniAppManifest> {
type: 'custody',
key: custodyAddress,
};
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString('base64');
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8').toString(
'base64'
);
const payload = {
domain
domain,
};
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url');
const encodedPayload = Buffer.from(
JSON.stringify(payload),
'utf-8'
).toString('base64url');
const signature = await account.signMessage({
message: `${encodedHeader}.${encodedPayload}`
const signature = await account.signMessage({
message: `${encodedHeader}.${encodedPayload}`,
});
const encodedSignature = Buffer.from(signature, 'utf-8').toString('base64url');
const encodedSignature = Buffer.from(signature, 'utf-8').toString(
'base64url'
);
accountAssociation = {
header: encodedHeader,
payload: encodedPayload,
signature: encodedSignature
signature: encodedSignature,
};
}
return {
accountAssociation,
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,