0

I want to connect a Solana wallet (phantom or any other) to a web application through the web3js library. I've read docs for most wallets and it seems like it's just as simple as await window.solana.request({ method: "connect" }); but window.solana is undefined in my case.

When I do console.log(window) I can see the Solana value with all its corresponding keys and values.

How can I do this?

TylerH
  • 20,799
  • 66
  • 75
  • 101

3 Answers3

1

Is your website https enabled? If not then it won't work

user2179059
  • 326
  • 1
  • 9
0

I've found a working code that solved my issue. I am not sure what was the issue as I'm not very experienced with js, but the following code lets me connect to phantom. I found this on StackOverflow on a similar thread, although I belive the original answer is missing some brackets. Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps?

const getProvider = async () => {
    if ("solana" in window) {
      await window.solana.connect(); // opens wallet to connect to

      const provider = window.solana;
      if (provider.isPhantom) {
        console.log("Is Phantom installed?  ", provider.isPhantom);
        return provider;
      }
    } else {
      document.write('Install https://www.phantom.app/');
    }
};

window.onload = () => {

    getProvider().then(provider => {
        console.log('key', provider.publicKey.toString())
    })
    .catch(function(error){
        console.log(error)
    });

}
ZygD
  • 22,092
  • 39
  • 79
  • 102
0

With your current implementation, everytime you refresh the app, you will get pop up to connect to the wallet. Instead you add {onlyIfTrusted:true} option to connect.

const getProvider = async () => { if ("solana" in window) { await window.solana.connect({onlyIfTrusted:true}); // opens wallet to connect to

  const provider = window.solana;
  if (provider.isPhantom) {
    console.log("Is Phantom installed?  ", provider.isPhantom);
    return provider;
  }
} else {
  document.write('Install https://www.phantom.app/');
}
};

then instead of getting pop up when you reload the app, write a connection function to handle the connection when a user clicks on the button

const connectToWallet=async ()=>{
    const {solana}=window
    if(solana){
      const response=await solana.connect()
      console.log('address',response.publicKey.toString())
      
    }
  }


<button onClick={connectToWallet}  >
    Connect to Wallet
    </button>

Now once user is connected, when you reload the app, it you wont get pop up to connect to the wallet

Yilmaz
  • 35,338
  • 10
  • 157
  • 202