mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-06 09:22:32 -05:00
Revert "Merge pull request #15 from neynarxyz/shreyas-formatting"
This reverts commitb1fdfc19a9, reversing changes made tob9e2087bd8.
This commit is contained in:
@@ -1,24 +1,19 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { Footer } from '~/components/ui/Footer';
|
||||
import { Header } from '~/components/ui/Header';
|
||||
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 {
|
||||
@@ -27,39 +22,44 @@ 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,12 +115,9 @@ 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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
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 = {
|
||||
@@ -15,15 +12,10 @@ type SafeFarcasterSolanaProviderProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({
|
||||
hasSolanaProvider: false,
|
||||
});
|
||||
const SolanaProviderContext = createContext<{ hasSolanaProvider: boolean }>({ hasSolanaProvider: false });
|
||||
|
||||
export function SafeFarcasterSolanaProvider({
|
||||
endpoint,
|
||||
children,
|
||||
}: SafeFarcasterSolanaProviderProps) {
|
||||
const isClient = typeof window !== 'undefined';
|
||||
export function SafeFarcasterSolanaProvider({ endpoint, children }: SafeFarcasterSolanaProviderProps) {
|
||||
const isClient = typeof window !== "undefined";
|
||||
const [hasSolanaProvider, setHasSolanaProvider] = useState<boolean>(false);
|
||||
const [checked, setChecked] = useState<boolean>(false);
|
||||
|
||||
@@ -56,8 +48,8 @@ export function SafeFarcasterSolanaProvider({
|
||||
const origError = console.error;
|
||||
console.error = (...args) => {
|
||||
if (
|
||||
typeof args[0] === 'string' &&
|
||||
args[0].includes('WalletConnectionError: could not get Solana provider')
|
||||
typeof args[0] === "string" &&
|
||||
args[0].includes("WalletConnectionError: could not get Solana provider")
|
||||
) {
|
||||
if (!errorShown) {
|
||||
origError(...args);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
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 { createConfig, http, WagmiProvider } from "wagmi";
|
||||
import { base, degen, mainnet, optimism, unichain, celo } from "wagmi/chains";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { farcasterFrame } from "@farcaster/miniapp-wagmi-connector";
|
||||
import { coinbaseWallet, metaMask } from 'wagmi/connectors';
|
||||
import { APP_NAME, APP_ICON_URL, APP_URL } from '~/lib/constants';
|
||||
import { APP_NAME, APP_ICON_URL, APP_URL } from "~/lib/constants";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useConnect, useAccount } from "wagmi";
|
||||
import React from "react";
|
||||
|
||||
// Custom hook for Coinbase Wallet detection and auto-connection
|
||||
function useCoinbaseWalletAutoConnect() {
|
||||
@@ -17,16 +17,15 @@ function useCoinbaseWalletAutoConnect() {
|
||||
useEffect(() => {
|
||||
// Check if we're running in Coinbase Wallet
|
||||
const checkCoinbaseWallet = () => {
|
||||
const isInCoinbaseWallet =
|
||||
window.ethereum?.isCoinbaseWallet ||
|
||||
const isInCoinbaseWallet = window.ethereum?.isCoinbaseWallet ||
|
||||
window.ethereum?.isCoinbaseWalletExtension ||
|
||||
window.ethereum?.isCoinbaseWalletBrowser;
|
||||
setIsCoinbaseWallet(!!isInCoinbaseWallet);
|
||||
};
|
||||
|
||||
|
||||
checkCoinbaseWallet();
|
||||
window.addEventListener('ethereum#initialized', checkCoinbaseWallet);
|
||||
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('ethereum#initialized', checkCoinbaseWallet);
|
||||
};
|
||||
@@ -71,11 +70,7 @@ export const config = createConfig({
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
// Wrapper component that provides Coinbase Wallet auto-connection
|
||||
function CoinbaseWalletAutoConnect({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
function CoinbaseWalletAutoConnect({ children }: { children: React.ReactNode }) {
|
||||
useCoinbaseWalletAutoConnect();
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -84,7 +79,9 @@ export default function Provider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<WagmiProvider config={config}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CoinbaseWalletAutoConnect>{children}</CoinbaseWalletAutoConnect>
|
||||
<CoinbaseWalletAutoConnect>
|
||||
{children}
|
||||
</CoinbaseWalletAutoConnect>
|
||||
</QueryClientProvider>
|
||||
</WagmiProvider>
|
||||
);
|
||||
|
||||
@@ -5,40 +5,43 @@ 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',
|
||||
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',
|
||||
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 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" />
|
||||
|
||||
@@ -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,19 +7,13 @@ 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>
|
||||
@@ -28,9 +22,7 @@ export const Footer: React.FC<FooterProps> = ({
|
||||
<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>
|
||||
@@ -39,9 +31,7 @@ export const Footer: React.FC<FooterProps> = ({
|
||||
<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>
|
||||
@@ -51,9 +41,7 @@ export const Footer: React.FC<FooterProps> = ({
|
||||
<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>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useState } from 'react';
|
||||
import Image from 'next/image';
|
||||
import sdk from '@farcaster/miniapp-sdk';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { APP_NAME } from '~/lib/constants';
|
||||
import { useState } from "react";
|
||||
import { APP_NAME } from "~/lib/constants";
|
||||
import sdk from "@farcaster/miniapp-sdk";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
|
||||
type HeaderProps = {
|
||||
neynarUser?: {
|
||||
@@ -19,19 +18,23 @@ export function Header({ neynarUser }: HeaderProps) {
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="mt-4 mb-4 mx-4 px-2 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-between border-[3px] border-double border-primary">
|
||||
<div className="text-lg font-light">Welcome to {APP_NAME}!</div>
|
||||
<div
|
||||
className="mt-4 mb-4 mx-4 px-2 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-between border-[3px] border-double border-primary"
|
||||
>
|
||||
<div className="text-lg font-light">
|
||||
Welcome to {APP_NAME}!
|
||||
</div>
|
||||
{context?.user && (
|
||||
<div
|
||||
<div
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
setIsUserDropdownOpen(!isUserDropdownOpen);
|
||||
}}
|
||||
>
|
||||
{context.user.pfpUrl && (
|
||||
<Image
|
||||
src={context.user.pfpUrl}
|
||||
alt="Profile"
|
||||
<img
|
||||
src={context.user.pfpUrl}
|
||||
alt="Profile"
|
||||
className="w-10 h-10 rounded-full border-2 border-primary"
|
||||
/>
|
||||
)}
|
||||
@@ -39,16 +42,14 @@ export function Header({ neynarUser }: HeaderProps) {
|
||||
)}
|
||||
</div>
|
||||
{context?.user && (
|
||||
<>
|
||||
<>
|
||||
{isUserDropdownOpen && (
|
||||
<div className="absolute top-full right-0 z-50 w-fit mt-1 mx-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="p-3 space-y-2">
|
||||
<div className="text-right">
|
||||
<h3
|
||||
<h3
|
||||
className="font-bold text-sm hover:underline cursor-pointer inline-block"
|
||||
onClick={() =>
|
||||
sdk.actions.viewProfile({ fid: context.user.fid })
|
||||
}
|
||||
onClick={() => sdk.actions.viewProfile({ fid: context.user.fid })}
|
||||
>
|
||||
{context.user.displayName || context.user.username}
|
||||
</h3>
|
||||
|
||||
@@ -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,13 +197,13 @@ 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'
|
||||
);
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -16,14 +16,8 @@ export function ProfileButton({
|
||||
|
||||
useDetectClickOutside(ref, () => setShowDropdown(false));
|
||||
|
||||
const name =
|
||||
userData?.username && userData.username.trim() !== ''
|
||||
? userData.username
|
||||
: `!${userData?.fid}`;
|
||||
const pfpUrl =
|
||||
userData?.pfpUrl && userData.pfpUrl.trim() !== ''
|
||||
? userData.pfpUrl
|
||||
: 'https://farcaster.xyz/avatar.png';
|
||||
const name = userData?.username && userData.username.trim() !== '' ? userData.username : `!${userData?.fid}`;
|
||||
const pfpUrl = userData?.pfpUrl && userData.pfpUrl.trim() !== '' ? userData.pfpUrl : 'https://farcaster.xyz/avatar.png';
|
||||
|
||||
return (
|
||||
<div className="relative" ref={ref}>
|
||||
@@ -33,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 */}
|
||||
@@ -41,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';
|
||||
}}
|
||||
@@ -52,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"
|
||||
|
||||
@@ -96,31 +96,24 @@ export function NeynarAuthButton() {
|
||||
const [storedAuth, setStoredAuth] = useState<StoredAuthState | null>(null);
|
||||
const [signersLoading, setSignersLoading] = useState(false);
|
||||
const { context } = useMiniApp();
|
||||
const {
|
||||
authenticatedUser: quickAuthUser,
|
||||
signIn: quickAuthSignIn,
|
||||
signOut: quickAuthSignOut,
|
||||
} = useQuickAuth();
|
||||
|
||||
const { authenticatedUser: quickAuthUser, signIn: quickAuthSignIn, signOut: quickAuthSignOut } = useQuickAuth();
|
||||
|
||||
// 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);
|
||||
const [isSignerFlowRunning, setIsSignerFlowRunning] = useState(false);
|
||||
const signerFlowStartedRef = useRef(false);
|
||||
const [backendUserProfile, setBackendUserProfile] = useState<{
|
||||
username?: string;
|
||||
pfpUrl?: string;
|
||||
}>({});
|
||||
const [backendUserProfile, setBackendUserProfile] = useState<{ username?: string; pfpUrl?: string }>({});
|
||||
|
||||
// Determine which flow to use based on context
|
||||
const useBackendFlow = context !== undefined;
|
||||
@@ -148,7 +141,7 @@ export function NeynarAuthButton() {
|
||||
const updateSessionWithSigners = useCallback(
|
||||
async (
|
||||
signers: StoredAuthState['signers'],
|
||||
_user: StoredAuthState['user'],
|
||||
user: StoredAuthState['user']
|
||||
) => {
|
||||
if (!useBackendFlow) return;
|
||||
|
||||
@@ -161,7 +154,7 @@ export function NeynarAuthButton() {
|
||||
console.error('❌ Error updating session with signers:', error);
|
||||
}
|
||||
},
|
||||
[useBackendFlow, quickAuthSignIn],
|
||||
[useBackendFlow, quickAuthSignIn]
|
||||
);
|
||||
|
||||
// Helper function to fetch user data from Neynar API
|
||||
@@ -179,7 +172,7 @@ export function NeynarAuthButton() {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
[]
|
||||
);
|
||||
|
||||
// Helper function to generate signed key request
|
||||
@@ -207,7 +200,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}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -219,7 +212,7 @@ export function NeynarAuthButton() {
|
||||
// throw error;
|
||||
}
|
||||
},
|
||||
[],
|
||||
[]
|
||||
);
|
||||
|
||||
// Helper function to fetch all signers
|
||||
@@ -230,10 +223,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);
|
||||
@@ -242,13 +235,11 @@ export function NeynarAuthButton() {
|
||||
if (response.ok) {
|
||||
if (useBackendFlow) {
|
||||
// For backend flow, update session with signers
|
||||
if (signerData.signers && signerData.signers.length > 0) {
|
||||
if (signerData.signers && signerData.signers.length > 0) {
|
||||
// Get user data for the first signer
|
||||
let user: StoredAuthState['user'] | null = null;
|
||||
if (signerData.signers[0].fid) {
|
||||
user = (await fetchUserData(
|
||||
signerData.signers[0].fid,
|
||||
)) as StoredAuthState['user'];
|
||||
user = await fetchUserData(signerData.signers[0].fid) as StoredAuthState['user'];
|
||||
}
|
||||
await updateSessionWithSigners(signerData.signers, user);
|
||||
}
|
||||
@@ -259,7 +250,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 +276,7 @@ export function NeynarAuthButton() {
|
||||
setSignersLoading(false);
|
||||
}
|
||||
},
|
||||
[useBackendFlow, fetchUserData, updateSessionWithSigners],
|
||||
[useBackendFlow, fetchUserData, updateSessionWithSigners]
|
||||
);
|
||||
|
||||
// Helper function to poll signer status
|
||||
@@ -308,10 +299,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 +312,7 @@ export function NeynarAuthButton() {
|
||||
setPollingInterval(null);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Increment retry count for other errors
|
||||
retryCount++;
|
||||
if (retryCount >= maxRetries) {
|
||||
@@ -329,7 +320,7 @@ export function NeynarAuthButton() {
|
||||
setPollingInterval(null);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
throw new Error(`Failed to poll signer status: ${response.status}`);
|
||||
}
|
||||
|
||||
@@ -352,7 +343,7 @@ export function NeynarAuthButton() {
|
||||
|
||||
setPollingInterval(interval);
|
||||
},
|
||||
[fetchAllSigners, pollingInterval],
|
||||
[fetchAllSigners, pollingInterval]
|
||||
);
|
||||
|
||||
// Cleanup polling on unmount
|
||||
@@ -398,7 +389,7 @@ export function NeynarAuthButton() {
|
||||
setMessage(result.message);
|
||||
setSignature(result.signature);
|
||||
// Use QuickAuth to sign in
|
||||
await quickAuthSignIn();
|
||||
const signInResult = await quickAuthSignIn();
|
||||
// Fetch user profile after sign in
|
||||
if (quickAuthUser?.fid) {
|
||||
const user = await fetchUserData(quickAuthUser.fid);
|
||||
@@ -433,10 +424,10 @@ export function NeynarAuthButton() {
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
const result = await sdk.actions.signIn({ nonce: nonce || '' });
|
||||
|
||||
|
||||
setMessage(result.message);
|
||||
setSignature(result.signature);
|
||||
|
||||
|
||||
// For frontend flow, we'll handle the signer flow in the useEffect
|
||||
} catch (e) {
|
||||
if (e instanceof SignInCore.RejectedByUser) {
|
||||
@@ -473,7 +464,7 @@ export function NeynarAuthButton() {
|
||||
clearInterval(pollingInterval);
|
||||
setPollingInterval(null);
|
||||
}
|
||||
|
||||
|
||||
// Reset signer flow flag
|
||||
signerFlowStartedRef.current = false;
|
||||
} catch (error) {
|
||||
@@ -486,14 +477,9 @@ 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 {
|
||||
@@ -511,7 +497,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
|
||||
@@ -522,7 +508,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
|
||||
@@ -533,8 +519,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
|
||||
@@ -567,8 +553,7 @@ export function NeynarAuthButton() {
|
||||
|
||||
const authenticated = useBackendFlow
|
||||
? !!quickAuthUser?.fid
|
||||
: storedAuth?.isAuthenticated &&
|
||||
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||
: storedAuth?.isAuthenticated && !!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||
|
||||
const userData = useBackendFlow
|
||||
? {
|
||||
@@ -607,7 +592,7 @@ export function NeynarAuthButton() {
|
||||
className={cn(
|
||||
'btn btn-primary flex items-center gap-3',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
'transform transition-all duration-200 active:scale-[0.98]',
|
||||
'transform transition-all duration-200 active:scale-[0.98]'
|
||||
)}
|
||||
>
|
||||
{signersLoading ? (
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState, useEffect } from 'react';
|
||||
import { type ComposeCast } from '@farcaster/miniapp-sdk';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { APP_URL } from '~/lib/constants';
|
||||
import { Button } from './Button';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { type ComposeCast } from "@farcaster/miniapp-sdk";
|
||||
import { APP_URL } from '~/lib/constants';
|
||||
|
||||
interface EmbedConfig {
|
||||
path?: string;
|
||||
@@ -24,16 +24,9 @@ interface ShareButtonProps {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function ShareButton({
|
||||
buttonText,
|
||||
cast,
|
||||
className = '',
|
||||
isLoading = false,
|
||||
}: ShareButtonProps) {
|
||||
export function ShareButton({ buttonText, cast, className = '', isLoading = false }: ShareButtonProps) {
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [bestFriends, setBestFriends] = useState<
|
||||
{ fid: number; username: string }[] | null
|
||||
>(null);
|
||||
const [bestFriends, setBestFriends] = useState<{ fid: number; username: string; }[] | null>(null);
|
||||
const [isLoadingBestFriends, setIsLoadingBestFriends] = useState(false);
|
||||
const { context, actions } = useMiniApp();
|
||||
|
||||
@@ -59,7 +52,7 @@ export function ShareButton({
|
||||
if (cast.bestFriends) {
|
||||
if (bestFriends) {
|
||||
// Replace @N with usernames, or remove if no matching friend
|
||||
finalText = finalText.replace(/@\d+/g, match => {
|
||||
finalText = finalText.replace(/@\d+/g, (match) => {
|
||||
const friendIndex = parseInt(match.slice(1)) - 1;
|
||||
const friend = bestFriends[friendIndex];
|
||||
if (friend) {
|
||||
@@ -75,7 +68,7 @@ export function ShareButton({
|
||||
|
||||
// Process embeds
|
||||
const processedEmbeds = await Promise.all(
|
||||
(cast.embeds || []).map(async embed => {
|
||||
(cast.embeds || []).map(async (embed) => {
|
||||
if (typeof embed === 'string') {
|
||||
return embed;
|
||||
}
|
||||
@@ -84,10 +77,7 @@ export function ShareButton({
|
||||
const url = new URL(`${baseUrl}${embed.path}`);
|
||||
|
||||
// Add UTM parameters
|
||||
url.searchParams.set(
|
||||
'utm_source',
|
||||
`share-cast-${context?.user?.fid || 'unknown'}`,
|
||||
);
|
||||
url.searchParams.set('utm_source', `share-cast-${context?.user?.fid || 'unknown'}`);
|
||||
|
||||
// If custom image generator is provided, use it
|
||||
if (embed.imageUrl) {
|
||||
@@ -98,7 +88,7 @@ export function ShareButton({
|
||||
return url.toString();
|
||||
}
|
||||
return embed.url || '';
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
// Open cast composer with all supported intents
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '~/lib/utils';
|
||||
import * as React from "react"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
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',
|
||||
className,
|
||||
"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 }
|
||||
|
||||
@@ -1,13 +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 { cn } from '~/lib/utils';
|
||||
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"
|
||||
|
||||
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>,
|
||||
@@ -19,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 }
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { type Haptics } from '@farcaster/miniapp-sdk';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
import { APP_URL } from '~/lib/constants';
|
||||
import { Button } from '../Button';
|
||||
import { useCallback, useState } from "react";
|
||||
import { useMiniApp } from "@neynar/react";
|
||||
import { ShareButton } from "../Share";
|
||||
import { Button } from "../Button";
|
||||
import { SignIn } from "../wallet/SignIn";
|
||||
import { type Haptics } from "@farcaster/miniapp-sdk";
|
||||
import { APP_URL } from "~/lib/constants";
|
||||
import { NeynarAuthButton } from '../NeynarAuthButton/index';
|
||||
import { ShareButton } from '../Share';
|
||||
import { SignIn } from '../wallet/SignIn';
|
||||
|
||||
/**
|
||||
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
|
||||
@@ -52,7 +52,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;
|
||||
}
|
||||
@@ -67,22 +67,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}`,
|
||||
}));
|
||||
@@ -99,11 +99,11 @@ export function ActionsTab() {
|
||||
if (context?.user?.fid) {
|
||||
const userShareUrl = `${APP_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]);
|
||||
@@ -124,16 +124,16 @@ 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,
|
||||
embeds: [`${APP_URL}/share/${context?.user?.fid || ''}`],
|
||||
embeds: [`${APP_URL}/share/${context?.user?.fid || ''}`]
|
||||
}}
|
||||
className="w-full"
|
||||
className='w-full'
|
||||
/>
|
||||
|
||||
{/* Authentication */}
|
||||
@@ -147,25 +147,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>
|
||||
@@ -174,24 +174,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>
|
||||
@@ -199,7 +199,7 @@ 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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 />
|
||||
@@ -17,10 +17,8 @@ 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>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,22 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState, useEffect } from 'react';
|
||||
import { useMiniApp } from '@neynar/react';
|
||||
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 {
|
||||
useAccount,
|
||||
useSendTransaction,
|
||||
useSignTypedData,
|
||||
useWaitForTransactionReceipt,
|
||||
useDisconnect,
|
||||
useConnect,
|
||||
useSwitchChain,
|
||||
useChainId,
|
||||
type Connector,
|
||||
} from 'wagmi';
|
||||
import { base, degen, mainnet, optimism, unichain } from 'wagmi/chains';
|
||||
import { USE_WALLET, APP_NAME } from '../../../lib/constants';
|
||||
import { renderError } from '../../../lib/errorUtils';
|
||||
import { truncateAddress } from '../../../lib/truncateAddress';
|
||||
import { Button } from '../Button';
|
||||
import { SendEth } from '../wallet/SendEth';
|
||||
import { SendSolana } from '../wallet/SendSolana';
|
||||
import { SignEvmMessage } from '../wallet/SignEvmMessage';
|
||||
import { SignSolanaMessage } from '../wallet/SignSolanaMessage';
|
||||
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
|
||||
@@ -34,10 +24,10 @@ import { SignSolanaMessage } from '../wallet/SignSolanaMessage';
|
||||
* - 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 />
|
||||
@@ -57,8 +47,7 @@ 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 && (
|
||||
@@ -101,14 +90,13 @@ 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}`));
|
||||
connect({ connector: connectors[0] });
|
||||
}}
|
||||
className="w-full"
|
||||
@@ -120,16 +108,10 @@ 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>
|
||||
@@ -138,10 +120,8 @@ 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();
|
||||
@@ -157,12 +137,10 @@ 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,
|
||||
@@ -184,32 +162,38 @@ 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
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}, [context?.user?.fid, isConnected, connectors, connect, context?.client]);
|
||||
|
||||
@@ -243,7 +227,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.
|
||||
*/
|
||||
@@ -251,20 +235,20 @@ export function WalletTab() {
|
||||
sendTransaction(
|
||||
{
|
||||
// call yoink() on Yoink contract
|
||||
to: '0x4bBFD120d9f352A0BEd7a014bd67913a2007a878',
|
||||
data: '0x9846cd9efc000023c0',
|
||||
to: "0x4bBFD120d9f352A0BEd7a014bd67913a2007a878",
|
||||
data: "0x9846cd9efc000023c0",
|
||||
},
|
||||
{
|
||||
onSuccess: hash => {
|
||||
onSuccess: (hash) => {
|
||||
setEvmContractTransactionHash(hash);
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [sendTransaction]);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@@ -272,16 +256,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]);
|
||||
|
||||
@@ -324,12 +308,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>
|
||||
)}
|
||||
@@ -363,4 +347,4 @@ export function WalletTab() {
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export { HomeTab } from './HomeTab';
|
||||
export { ActionsTab } from './ActionsTab';
|
||||
export { ContextTab } from './ContextTab';
|
||||
export { WalletTab } from './WalletTab';
|
||||
export { WalletTab } from './WalletTab';
|
||||
@@ -1,29 +1,25 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import {
|
||||
useAccount,
|
||||
useSendTransaction,
|
||||
useWaitForTransactionReceipt,
|
||||
} from 'wagmi';
|
||||
import { base } from 'wagmi/chains';
|
||||
import { renderError } from '../../../lib/errorUtils';
|
||||
import { truncateAddress } from '../../../lib/truncateAddress';
|
||||
import { Button } from '../Button';
|
||||
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 />
|
||||
@@ -40,34 +36,32 @@ 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.
|
||||
@@ -94,15 +88,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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,29 @@
|
||||
'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 { renderError } from '../../../lib/errorUtils';
|
||||
import { truncateAddress } from '../../../lib/truncateAddress';
|
||||
import { Button } from '../Button';
|
||||
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 />
|
||||
@@ -45,8 +42,7 @@ 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
|
||||
@@ -76,8 +72,7 @@ export function SendSolana() {
|
||||
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';
|
||||
@@ -105,8 +100,7 @@ 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>
|
||||
@@ -114,4 +108,4 @@ export function SendSolana() {
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,26 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useCallback } from 'react';
|
||||
import { useAccount, useConnect, useSignMessage } from 'wagmi';
|
||||
import { base } from 'wagmi/chains';
|
||||
import { APP_NAME } from '../../../lib/constants';
|
||||
import { renderError } from '../../../lib/errorUtils';
|
||||
import { config } from '../../providers/WagmiProvider';
|
||||
import { Button } from '../Button';
|
||||
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() {
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
|
||||
import { useQuickAuth } from '~/hooks/useQuickAuth';
|
||||
import { Button } from '../Button';
|
||||
import { useCallback, useState } from "react";
|
||||
import sdk, { SignIn as SignInCore } from "@farcaster/miniapp-sdk";
|
||||
import { Button } from "../Button";
|
||||
import { useQuickAuth } from "~/hooks/useQuickAuth";
|
||||
|
||||
/**
|
||||
* SignIn component handles Farcaster authentication using QuickAuth.
|
||||
@@ -52,11 +52,11 @@ export function SignIn() {
|
||||
*/
|
||||
const handleSignIn = useCallback(async () => {
|
||||
try {
|
||||
setAuthState(prev => ({ ...prev, signingIn: true }));
|
||||
setAuthState((prev) => ({ ...prev, signingIn: true }));
|
||||
setSignInFailure(undefined);
|
||||
|
||||
|
||||
const success = await signIn();
|
||||
|
||||
|
||||
if (!success) {
|
||||
setSignInFailure('Authentication failed');
|
||||
}
|
||||
@@ -67,7 +67,7 @@ export function SignIn() {
|
||||
}
|
||||
setSignInFailure('Unknown error');
|
||||
} finally {
|
||||
setAuthState(prev => ({ ...prev, signingIn: false }));
|
||||
setAuthState((prev) => ({ ...prev, signingIn: false }));
|
||||
}
|
||||
}, [signIn]);
|
||||
|
||||
@@ -80,10 +80,10 @@ export function SignIn() {
|
||||
*/
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setAuthState(prev => ({ ...prev, signingOut: true }));
|
||||
setAuthState((prev) => ({ ...prev, signingOut: true }));
|
||||
await signOut();
|
||||
} finally {
|
||||
setAuthState(prev => ({ ...prev, signingOut: false }));
|
||||
setAuthState((prev) => ({ ...prev, signingOut: false }));
|
||||
}
|
||||
}, [signOut]);
|
||||
|
||||
@@ -105,9 +105,7 @@ export function SignIn() {
|
||||
{/* Session Information */}
|
||||
{authenticatedUser && (
|
||||
<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">
|
||||
Authenticated User
|
||||
</div>
|
||||
<div className="font-semibold text-gray-500 dark:text-gray-300 mb-1">Authenticated User</div>
|
||||
<div className="whitespace-pre text-gray-700 dark:text-gray-200">
|
||||
{JSON.stringify(authenticatedUser, null, 2)}
|
||||
</div>
|
||||
@@ -117,12 +115,8 @@ 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">
|
||||
Authentication Error
|
||||
</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">Authentication Error</div>
|
||||
<div className="whitespace-pre text-gray-700 dark:text-gray-200">{signInFailure}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { renderError } from '../../../lib/errorUtils';
|
||||
import { Button } from '../Button';
|
||||
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) {
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
Reference in New Issue
Block a user