11// @ts -nocheck
22"use client"
33
4- import { createContext , useContext , useEffect , useState , type ReactNode } from "react"
4+ import { createContext , useContext , useEffect , useRef , useState , type ReactNode } from "react"
55import { approvePiPayment , completePiPayment , cancelPiPayment } from "@/lib/api/pi-payments"
66
77interface PiUser {
@@ -42,11 +42,10 @@ export function PiProvider({ children }: { children: ReactNode }) {
4242 const [ authResult , setAuthResult ] = useState < PiAuthResult | null > ( null )
4343 const [ isAuthenticated , setIsAuthenticated ] = useState ( false )
4444 const [ isLoading , setIsLoading ] = useState ( false )
45+ const autoAuthAttempted = useRef ( false )
4546
4647 useEffect ( ( ) => {
4748 if ( typeof window === "undefined" ) return
48- // No auto-login: clear saved Pi auth so user must explicitly connect.
49- // Do not clear zyradex-wallet-address - that can disrupt wallet display before re-auth.
5049 const savedToken = localStorage . getItem ( "pi_access_token" )
5150 const savedUser = localStorage . getItem ( "pi_user" )
5251 if ( savedToken && savedUser ) {
@@ -60,6 +59,22 @@ export function PiProvider({ children }: { children: ReactNode }) {
6059 }
6160 } , [ ] )
6261
62+ useEffect ( ( ) => {
63+ if ( autoAuthAttempted . current ) return
64+ if ( typeof window === "undefined" ) return
65+ if ( ! window . Pi ) return
66+
67+ autoAuthAttempted . current = true
68+
69+ const timer = setTimeout ( ( ) => {
70+ authenticate ( ) . catch ( ( ) => {
71+ // silent — user can manually sign in via button
72+ } )
73+ } , 500 )
74+
75+ return ( ) => clearTimeout ( timer )
76+ } , [ ] )
77+
6378 const authenticate = async ( ) : Promise < PiAuthResult > => {
6479 if ( typeof window === "undefined" ) {
6580 throw new Error ( "Window not available. Please refresh the page." )
@@ -71,17 +86,16 @@ export function PiProvider({ children }: { children: ReactNode }) {
7186
7287 setIsLoading ( true )
7388 try {
74- window . Pi . init ( { version : "2.0" } )
89+ await window . Pi . init ( { version : "2.0" } )
7590
7691 const onIncompletePaymentFound = ( payment : any ) => {
7792 console . log ( "Incomplete payment found:" , payment )
78- // Fire-and-forget: don't block authenticate if cancel fails
7993 cancelPiPayment ( payment . identifier ) . catch ( ( err ) =>
8094 console . error ( "Error cancelling incomplete payment:" , err )
8195 )
8296 }
8397
84- const auth = await window . Pi . authenticate ( [ "username" , "payments" , "wallet_address" ] , onIncompletePaymentFound )
98+ const auth = await window . Pi . authenticate ( [ "username" ] , onIncompletePaymentFound )
8599
86100 if ( ! auth ?. accessToken ) {
87101 throw new Error ( "No access token received from Pi SDK" )
0 commit comments