1

I have taken the standard code from Solana for the wallet-adapter implementation which works to connect to the wallet. But I cannot get the balance to work. I tried connection.getBalance() but the method is not found. Has anyone a suggestion?

import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui';
import { UnsafeBurnerWalletAdapter } from '@solana/wallet-adapter-wallets';
import { clusterApiUrl } from '@solana/web3.js';
import React, { FC, ReactNode, useMemo } from 'react';

require('./App.css');
require('@solana/wallet-adapter-react-ui/styles.css');

const App: FC = () => {
    return (
        <Context>
            <Content />
        </Context>
    );
};
export default App;

const Context: FC<{ children: ReactNode }> = ({ children }) => {
    // The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
    const network = WalletAdapterNetwork.Devnet;

    // You can also provide a custom RPC endpoint.
    const endpoint = useMemo(() => clusterApiUrl(network), [network]);

    const wallets = useMemo(
        () => [
            new UnsafeBurnerWalletAdapter(),
        ],
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [network]
    );

    return (
        <ConnectionProvider endpoint={endpoint}>
            <WalletProvider wallets={wallets} autoConnect>
                <WalletModalProvider>{children}</WalletModalProvider>
            </WalletProvider>
        </ConnectionProvider>
    );
};

const Content: FC = () => {
    return (
        <div className="App">
            <WalletMultiButton />
        </div>
    );
};

I then tried -

const  connection  = useConnection();
     const  publicKey  = useWallet();
     const [balance, setBalance] = useState<string | null>(null);
           const fetchBalance = async () => {
               const balance1 = await connection.getBalance(publicKey);
               console.log("balance == "+ balance1);
               setBalance(balance1);
           };

    useEffect(() => {
        fetchBalance();
    }, [connection, publicKey]);

The error is getBalance is not available on connection.

1 Answer 1

1

I think you want to deconstruct publicKey from useWallet like this:

     const  { publicKey } = useWallet();

Take a look at the dapp scaffold: https://github.com/solana-labs/dapp-scaffold/blob/6d441f295f2036994321ff5281105d009a17fd73/src/views/home/index.tsx#L25

1
  • 1
    I also added {connection}=useConnection(); and a test is needed before getBalance to test for null.
    – trevoro
    Feb 11, 2023 at 16:31

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.