async function web3Login() { console.log("Starting web3Login process..."); // Check if MetaMask is available if (!window.ethereum) { console.warn('MetaMask not detected.'); alert('MetaMask not detected. Please install MetaMask first.'); return { error: 'MetaMask not detected' }; } try { console.log("Initializing Web3 provider..."); const provider = new ethers.providers.Web3Provider(window.ethereum); console.log("Requesting account access..."); await provider.send("eth_requestAccounts", []); const signer = provider.getSigner(); console.log("Getting user's Ethereum address..."); const address = await signer.getAddress(); console.log(`Address: ${address}`); console.log("Fetching unique message for signing..."); let response = await fetch('/web3-login-message'); if (!response.ok) throw new Error('Failed to fetch login message'); const message = await response.text(); console.log(`Message: ${message}`); console.log("Requesting user to sign the message..."); const signature = await signer.signMessage(message); console.log(`Signature: ${signature}`); console.log("Verifying the signature on the server..."); response = await fetch('/web3-login-verify', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }, body: JSON.stringify({ address, signature }) }); if (!response.ok) { const errorData = await response.json(); // Assuming error details are in JSON format throw new Error(`Login verification failed: ${errorData.message || 'Unknown error'}`); } console.log("Web3 login process completed successfully."); return { address, signature }; } catch (error) { console.error('Web3 login/signature process failed:', error); return { error: error.message }; } }