[SOLVED] Obtain the web3 without authentication

Ok, so not sure how to formulate my current issueā€¦ but here is the contextā€¦

Iā€™m currently building a dappā€¦ I use Moralis to authenticate usersā€¦

My issue is that if I close the browser and re-open it, my Moralis session is still up whereas my wallet connection (Metamask) is dead.

Iā€™m trying to verify in my router code if the wallet is still connected and if so, is it connected to the same user as the metamask account.

Tried using Moralis.Web3.enable(), but it pops out Metamaskā€¦ but I want to redirect to the login page myself.

Any suggestion?

1 Like

Hey @mathieu166

Moralis SDK doesnā€™t provide a simple solution to your problem. Because validation of the connected wallet is not necessary for everyone.

Hereā€™s one possible solution:

async function authenticateMoralis() {
 if (window.ethereum) {
    let user = await Moralis.User.current();
    await Moralis.Web3.enable();
    let currentAddress = await window.ethereum.send("eth_requestAccounts");
    currentAddress = currentAddress.result[0];
    if (user && user.attributes.ethAddress == currentAddress) {
      return user;
    } else {
      return await authenticate(provider);
    }
 } else {
  alert("Non ethereum browser")
 }
}

It checks the userā€™s wallet with an open session and the connected wallet and compares them

problem is that window.ethereum.send(ā€œeth_requestAccountsā€) triggers MetaMask for loginā€¦ to bad there is no way to get the account if MM is connected otherwise, just return an empty or undefined array of addresses

Hi,
Donā€™t know this if this helps: it looks like web3.currentProvider.selectedAddress, ethereum.selectedAddress returns current selected address in MetaMask for me

Ok, let me try that later todayā€¦ thanks!

Oh man!! My savior! the code bellow worked out well for me

const walletAddress = window.ethereum.selectedAddress
2 Likes