0

How would I be able to get smart contract data to load on a site when someone has metamask installed but is not logged in? At the moment the data loads if you don't have metamask installed. I'm using ethers.js:

let provider = window.ethereum ? new ethers.providers.Web3Provider(window.ethereum) : new ethers.providers.JsonRpcProvider("URL");

let signer = window.ethereum ? provider.getSigner() : undefined;

let contract = new ethers.Contract(
   contractAddress,
   ABI,
   signer ?? provider
);
3
  • Can you add more detail of what you need seems like you are answering your own question
    – Julissa DC
    Commented Jul 11, 2022 at 13:45
  • @JulissaDC It only works if the user doesn't have metamask installed. How would I make it work so that if the user has metamask installed (BUT IS NOT LOGGED IN) the data is still displayed?
    – user104397
    Commented Jul 11, 2022 at 19:40
  • Yes the data would display
    – Julissa DC
    Commented Jul 12, 2022 at 13:37

1 Answer 1

0

In this case, I would set the default provider as the RPC provider, then check to see if window.ethereum exists. If it does exist, then we can try to use it as a provider and list accounts available to us. If the accounts array returns as empty, then we know there is no wallet connected to the site. Otherwise if the array returns one or more accounts, then set the signer and provider to MetaMask, overriding the original RPC provider.

Under the hood, this will call eth_accounts via RPC. If no accounts are returned, then the user hasn't connected any of their metamask accounts to the site and thus none are available to use (I assume this is what you mean by "not logged in").

let provider = new ethers.providers.JsonRpcProvider("URL");
let signer;

if(window.ethereum) {
  try {
    const metaMaskProvider = new ethers.providers.Web3Provider(window.ethereum);
    const accounts = await metaMaskProvider.listAccounts();
    if (accounts.length) {
      provider = metaMaskProvider;
      signer = metaMaskProvider.getSigner();
    }
  } catch (exception) {
    console.error('Unable to list accounts', exception);
  }
}

let contract = new ethers.Contract(
   contractAddress,
   ABI,
   signer ?? provider
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.