Spaces:
Running
Running
File size: 2,657 Bytes
2acde71 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | 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;
}; |