[SOLVED] useEvmNativeBalance undefined address error

function HomePage (){
const [ addy, setAddy ] = useState();
    
    const { connectAsync } = useConnect();

    const handleAuth = async () => {
        const { account } = await connectAsync({
        connector: new MetaMaskConnector(),
        });
        if (account){
        setAddy(account)
        }
        
    };

    const { data: nativeBalance } = useEvmNativeBalance({ addy });
  
    console.log(nativeBalance)

I continuously get nativeBalance as undefined and I am unsure as to why that is

Hi @CleanMcGerk

Please try logging the native balance like this. Since nativeBalance is a state variable it will initially be undefined or null

const { data: nativeBalance } = useEvmNativeBalance({ addy });

useEffect(() => {
if(nativeBalance){
console.log(nativeBalance)
}
}, [nativeBalance])

1 Like

I get the same result

It could be possible that there was an error from the hook. Try logging the error like this.

const { data: nativeBalance, error } = useEvmNativeBalance({ addy });

useEffect(() => {
if(error){
console.log(error)
}
}, [error])
> 24 |     useEffect(() => {
     |    ^
  25 |         if(error){
  26 |         console.log(error)
  27 |         }

it returns this. I don’t follow

What does the error message say?

I get the following two errors

WebSocket connection closed abnormally with code: 3000 (Authorization error: Unauthorized: invalid key)

and

Moralis SDK Core Error: [C0005] Invalid address provided: undefined
    at EvmAddress.parse 

the last error occurs after my console.log(addy) returns the correct address

Hi @CleanMcGerk

This error is caused from the wagmi sdk. Please update your wagmi config code as per this docs.
If you are using wallet connect authentication in your code please follow as per this docs.


For this error please verify if the correct address is passed to the sdk function. This error is thrown if the address is invalid or undefined.

This is my _app.jsx

import { createConfig, configureChains, WagmiConfig } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { SessionProvider } from "next-auth/react";
import { mainnet } from "wagmi/chains";

const { publicClient, webSocketPublicClient } = configureChains(
  [mainnet],
  [publicProvider()]
);

const config = createConfig({
  autoConnect: true,
  publicClient,
  webSocketPublicClient,
});

function MyApp({ Component, pageProps }) {
  return (
    
    <WagmiConfig config={config}>
      <SessionProvider session={pageProps.session} refetchInterval={0}>
        <Component {...pageProps} />
      </SessionProvider>
    </WagmiConfig>
  );
}

export default MyApp;

This looks correct. Do you still have any errors?

I keep getting this error

Moralis SDK Core Error: [C0005] Invalid address provided: undefined

However on the line before I console.log the address that I set in state and it returns correctly

Can you share the code related to it?

import { useEvmNativeBalance} from '@moralisweb3/next';
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { useState, useEffect } from 'react';
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";


  

function HomePage() {
    const { connectAsync } = useConnect();
  const { disconnectAsync } = useDisconnect();
  const { isConnected } = useAccount();
  const { signMessageAsync } = useSignMessage();
  const { requestChallengeAsync } = useAuthRequestChallengeEvm();

    const [ addy, setAddy ] = useState();
    
    

    const handleAuth = async () => {
        if (isConnected) {
          await disconnectAsync();
        }
    
        const { account, chain } = await connectAsync({
          connector: new MetaMaskConnector(),
        });
    
        const { message } = await requestChallengeAsync({
          address: account,
          chainId: chain.id,
        });
    
        const signature = await signMessageAsync({ message });
        setAddy(account)
        console.log(signature);
      };
  
            console.log(addy)

    const { data: nativeBalance, error } = useEvmNativeBalance({ addy });
    // const {data: allBalance } = useEvmWalletTokenBalances({address})
    useEffect(() => {
        if(error){
        console.log(error)
        }
        }, [error])
    
    
    return (
        <div>
            <button onClick={handleAuth}> </button>
            {/* <button onClick={signOut}></button> */}
            <h3>Wallet: {addy}</h3>
            <h3>Native Balance: {nativeBalance?.balance.ether} ETH</h3>
            {/* <h3>All Balance: {allBalance} ETH</h3> */}
        </div>
    );
}

export default HomePage;


The same happens when I hardcode the the address

Replace it with this code.
I used fetch from useEvmNativeBalance to get the balance of the address.

When the component inistally renders the value of addy is undefined so we cant directly use useEvmNativeBalance directly to fetch the balance.
And you also need to assign the value of addy to address param, to read and pass the value correctly to API.

Please check with this code and let me know if you have any questions.

import { useEvmNativeBalance } from "@moralisweb3/next";
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { useState, useEffect } from "react";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";

function HomePage() {
  const { connectAsync } = useConnect();
  const { disconnectAsync } = useDisconnect();
  const { isConnected } = useAccount();
  const { signMessageAsync } = useSignMessage();
  const { requestChallengeAsync } = useAuthRequestChallengeEvm();

  const [addy, setAddy] = useState();

  const handleAuth = async () => {
    if (isConnected) {
      await disconnectAsync();
    }

    const { account, chain } = await connectAsync({
      connector: new MetaMaskConnector(),
    });

    const { message } = await requestChallengeAsync({
      address: account,
      chainId: chain.id,
    });

    const signature = await signMessageAsync({ message });
    setAddy(account);
    console.log(signature);
  };

  const { data: nativeBalance, error, fetch } = useEvmNativeBalance();
  // const {data: allBalance } = useEvmWalletTokenBalances({address})
  useEffect(() => {
    if (addy) {
      fetch({
        address: addy,
      });
    }
  }, [addy]);
  useEffect(() => {
    if (error) {
      console.log(error);
    }
  }, [error]);

  return (
    <div>
      <button onClick={handleAuth}> </button>
      {/* <button onClick={signOut}></button> */}
      <h3>Wallet: {addy}</h3>
      <h3>Native Balance: {nativeBalance?.balance.ether} ETH</h3>
      {/* <h3>All Balance: {allBalance} ETH</h3> */}
    </div>
  );
}

export default HomePage;

1 Like

Ahh thanks man - it worked without the fetch although with error (simply changed the useState to address instead of addy - didn’t read enough) will use the fetch thank you.

3 Likes