How to connect to Solana Wallet and get the public key for an account

Ly Channa
2 min readOct 19, 2022
Connect to Solana wallet and get the account public key

There is an excellent Solana dev tutorial to interact with wallets here, but you may have missed an important point in the tutorial as noted below:

For these to work properly, any use of useWallet and useConnection should be wrapped in WalletProvider and ConnectionProvider. One of the best ways to ensure this is to wrap your entire app in ConnectionProvider and WalletProvider:

const WalletContextProvider = (props: any) => {
const wallets = [
new WalletAdapter.PhantomWalletAdapter(),
new WalletAdapter.SolflareWalletAdapter(),
new WalletAdapter.SlopeWalletAdapter(),
new WalletAdapter.GlowWalletAdapter(),
new WalletAdapter.TorusWalletAdapter(),
new WalletAdapter.SolletWalletAdapter(),
new WalletAdapter.SolongWalletAdapter(),
new WalletAdapter.TokenPocketWalletAdapter()
]
const endpoint = Web3.clusterApiUrl('devnet')return(
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={wallets}>
<WalletModalProvider>
{ props.children }
</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
)
}
export default WalletContextProvider;

An Ideal place to put this is at the root of your component

const defaultPageTitle = 'Welcome to Solana DEV';
const defaultTitle = 'Welcome to our Solana DEV portal';
export default function Layout(props: { children: any, home: boolean, title?: string, pageTitle?: string}) {
const pageTitle = props.pageTitle || defaultPageTitle;
const title = props.title || defaultTitle;
return (
<div className={styles.container}>
<WalletContextProvider>
<main>
{props.children}
</main>
</WalletContextProvider>
</div>
);
}

Put everything together in a Nextjs page:

// pages/index.tsxconst Home: NextPage = () => {
return (
<Layout home={true}>
<ReviewForm />
</Layout>
)
}
export default Home

And the ReviewForm looks like this:

const ReviewForm: FC = () => {
const { connection } = useConnection()
const { publicKey, sendTransaction} = useWallet()
const handleSubmit = (e: any) => {
e.preventDefault();
const movie = new Movie(title, rating, description)
handleTransactionMovie(movie)
}
const handleTransactionMovie = async (movie: Movie) => {
if(!publicKey) {
alert('Please connect your wallet');
return false
}
alert(`your account publicKey: ${publicKey}`)
}
return (
<form onSubmit={handleSubmit}>
{publicKey ? `${publicKey}` : '' }
<p>Any input here ...</p>
<button>Submit</button>
</form>
)
}export default ReviewForm;

--

--