solana / src /hooks /useWalletDetection.ts
dronesplace's picture
Initial upload
2acde71 verified
Raw
History Blame Contribute Delete
2.66 kB
import { useEffect, useState } from 'react';
interface WalletDetectionState {
isPhantomInstalled: boolean;
isWalletReady: boolean;
error: string | null;
}
export const useWalletDetection = (): WalletDetectionState => {
const [state, setState] = useState<WalletDetectionState>({
isPhantomInstalled: false,
isWalletReady: false,
error: null,
});
useEffect(() => {
let mounted = true;
const checkWallet = () => {
if (typeof window === 'undefined') {
setState({
isPhantomInstalled: false,
isWalletReady: false,
error: 'Window not available',
});
return;
}
try {
const windowAny = window as any;
// Check for Phantom wallet
const phantom = windowAny.phantom?.solana || windowAny.solana;
const isPhantomInstalled = phantom?.isPhantom === true;
console.log('Wallet detection:', {
phantom: !!phantom,
isPhantom: phantom?.isPhantom,
isConnected: phantom?.isConnected,
publicKey: phantom?.publicKey?.toString(),
});
if (mounted) {
setState({
isPhantomInstalled,
isWalletReady: isPhantomInstalled && phantom.readyState === 'Ready',
error: isPhantomInstalled ? null : 'Phantom wallet not detected',
});
}
} catch (error) {
console.error('Error detecting wallet:', error);
if (mounted) {
setState({
isPhantomInstalled: false,
isWalletReady: false,
error: 'Error detecting wallet',
});
}
}
};
// Initial check
checkWallet();
// Listen for wallet events
const handleLoad = () => checkWallet();
const handlePhantomLoad = () => {
console.log('Phantom load event detected');
setTimeout(checkWallet, 100);
};
window.addEventListener('load', handleLoad);
// Some wallets fire custom events
window.addEventListener('phantom_loaded', handlePhantomLoad);
// Periodic check for wallet readiness
const interval = setInterval(checkWallet, 1000);
// Cleanup after 10 seconds
const timeout = setTimeout(() => {
clearInterval(interval);
}, 10000);
return () => {
mounted = false;
window.removeEventListener('load', handleLoad);
window.removeEventListener('phantom_loaded', handlePhantomLoad);
clearInterval(interval);
clearTimeout(timeout);
};
}, []);
return state;
};