Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```
- 'use client';
- import { useEffect, useState, createContext, useContext } from 'react';
- import sdk, { Context } from '@farcaster/frame-sdk';
- import { useLoginToFrame } from '@privy-io/react-auth/farcaster';
- import { usePrivy, useWallets } from '@privy-io/react-auth';
- import { useIsFrameOnMobile } from '@/lib/hooks/useIsFrameOnMobile';
- import { useAccount, useConnect } from 'wagmi';
- import farcasterFrame from '@farcaster/frame-wagmi-connector';
- const FrameContext = createContext<{
- isSDKLoaded: boolean;
- frameContext: Context.FrameContext | null;
- loginIntoFrame: () => Promise<void>;
- }>({
- isSDKLoaded: false,
- frameContext: null,
- loginIntoFrame: () => Promise.resolve(),
- });
- export const useFrameContext = () => {
- const context = useContext(FrameContext);
- if (!context) {
- throw new Error('useFrame must be used within a FrameProvider');
- }
- return context;
- };
- export default function FrameProvider({
- children,
- }: {
- children: React.ReactNode;
- }) {
- const [isSDKLoaded, setIsSDKLoaded] = useState(false);
- const [frameContext, setFrameContext] = useState<Context.FrameContext | null>(
- null,
- );
- const { ready, authenticated, user } = usePrivy();
- const { initLoginToFrame, loginToFrame } = useLoginToFrame();
- const isFrameOnMobile = useIsFrameOnMobile();
- const { connect } = useConnect();
- const { wallets } = useWallets();
- const { isConnected } = useAccount();
- // Setup SDK
- useEffect(() => {
- const load = async () => {
- const frameContext = await sdk.context;
- // await setTimeout(10000);
- setFrameContext(frameContext);
- sdk.actions.ready();
- };
- if (sdk && !isSDKLoaded) {
- setIsSDKLoaded(true);
- load();
- }
- }, [isSDKLoaded]);
- const login = async () => {
- const { nonce } = await initLoginToFrame();
- const result = await sdk.actions.signIn({ nonce: nonce });
- await loginToFrame({
- message: result.message,
- signature: result.signature,
- });
- };
- // Login to Frame
- // useEffect(() => {
- // if (!frameContext) {
- // return;
- // }
- // if (ready && !authenticated) {
- // login();
- // }
- // }, [ready, authenticated, frameContext]);
- // Add Frame
- useEffect(() => {
- if (!frameContext || !authenticated) {
- return;
- }
- const addFrame = async () => {
- await sdk.actions.addFrame();
- };
- if (!frameContext?.client.added) {
- addFrame();
- }
- }, [frameContext, authenticated, ready, user]);
- // If we are on mobile and have frame context, connect to warpcast wallet
- useEffect(() => {
- if (isConnected) {
- return;
- }
- if (frameContext && isFrameOnMobile) {
- connect({ connector: farcasterFrame() });
- }
- }, [frameContext, isFrameOnMobile, isConnected, wallets]);
- return (
- <FrameContext.Provider
- value={{ isSDKLoaded, frameContext, loginIntoFrame: login }}
- >
- {children}
- </FrameContext.Provider>
- );
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment