0

I'm trying to connect the user wallet to my dApp programmatically. That is, I created my own "connect wallet" button and when clicked it should execute the connect function that wallet-adapter exposes through its React Context.

import { clusterApiUrl } from '@solana/web3.js'
import { useWallet } from '@solana/wallet-adapter-react'
import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'
import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets'
import {
  ConnectionProvider,
  WalletProvider
} from '@solana/wallet-adapter-react'

const Button = () => {
    const { connect } = useWallet()

    return (
        <button onClick={connect}>
          Connect wallet
        </button>
    )
}

const App = () => {
    return (
        <ConnectionProvider endpoint={clusterApiUrl(WalletAdapterNetwork.Devnet)}>
            <WalletProvider wallets={[new PhantomWalletAdapter()]}>
                <Button />
            </WalletProvider>
        </ConnectionProvider>
    )

}

But this approach throws the error that is in the title. At this point I'm wondering if it's possible to use wallet-adapter without using its components.

1 Answer 1

4

connect() name could be misleading. This function connects to an adapter that the user has already chosen and authenticated with. WalletProvider only declares the supported adapters.

Before you can connect(), you need to select() the wallet you want to use.

import { PhantomWalletName } from "@solana/wallet-adapter-phantom";
const { select } = useWallet();
select(PhantomWalletName);
2
  • I also would add that TypeScript will raise an error if you pass a string to the select function. I had to import PhantomWalletName from @solana/wallet-adapter-phantom and pass it to the select function to resolve this error. Aug 1, 2022 at 0:54
  • Good call! I've updated the answer.
    – sohrab
    Aug 1, 2022 at 3:06

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.