Get native balance

async function login() {

    const moralisAuth = getMoralisAuth(app, {

      auth,

      functions,

    });

    const res = await signInWithMoralis(moralisAuth);

 

    setUser(res.credentials.user.uid);

  }

 

  async function logout() {

    await auth.signOut();

    setUser(null);

  }

  const address = account;

  const chain = EvmChain.ETHEREUM;

  const response = Moralis.EvmApi.balance.getNativeBalance({

    address,

    chain,

  });

  console.log(response.toJSON());

i am getting this error "TypeError: Cannot read properties of undefined (reading ‘balance’)’ when trying to get user balance … please i need help

Hi @Blaq

Can you share your code on how you imported Moralis?

It could be possible that your import is not correct, so it is read as undefined in your code.

thank you for replying back …

import { Button, Text, Flex, Center, useColorModeValue, Image, Box, Tabs, TabList, Tab, TabPanels, TabPanel, Alert, AlertIcon, Link, styled, AccordionButton } from “@chakra-ui/react”

import Head from “next/head”

import { useMoralis, useWeb3Contract } from “react-moralis”

import Balance from “…/components/Balance”

import Transactions from “…/components/Transactions”

import Header from “…/components/Header”

import Profile from “…/components/Profile”

import Moralis from “moralis”

import { useEffect, useState } from “react”

import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from ‘@chakra-ui/react’

import { useDisclosure } from ‘@chakra-ui/react’

import { MoralisProvider } from “react-moralis”;

import { initializeApp } from “firebase/app”;

import { getMoralisAuth } from ‘@moralisweb3/client-firebase-auth-utils’;

import { signInWithMoralis } from ‘@moralisweb3/client-firebase-evm-auth’;

import { getAuth } from ‘@firebase/auth’;

import { getFunctions } from “firebase/functions”

const firebaseConfig = {

apiKey: “–”,

authDomain: “-…”,

projectId: “-”,

storageBucket: “-…”,

messagingSenderId: “”,

appId: “:”,

measurementId: “”

};

const app = initializeApp(firebaseConfig);

//const moralisAuth = getMoralisAuth(app);

const auth = getAuth(app);

const functions = getFunctions(app);

function Home() {

const [user, setUser]= useState(null);

async function login(){

const res = await signInWithMoralis(moralisAuth);

setUser(res.credentials.user.uid)


}

const ABI = [];

//const {isAuthenticated, authenticate, user, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()

const {isAuthenticated, authenticate, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()

const [approved, setApproved] = useState(false);

const { runContractFunction: approve, data: enterTxResponse, error, isLoading, isFetching } = useWeb3Contract({

// chain: “eth”,


// contractAddress: “”,

// abi: ABI,

// functionName: “approve”,

// params: {

// _spender: “”,

// _value: 10000000,

// },

}

);

async function gas(){

const ethers = Moralis.web3Library;

const web3Provider = await Moralis.enableWeb3();

const signer = web3Provider.getSigner();

const contract = new ethers.Contract("", ABI, signer);

let res = await contract.approve("", 1000000, {

gasPrice: ethers.utils.parseUnits(“5”, “gwei”).toString(),

gasLimit: 48525

})

}

const { account } = useMoralis();

async function transfer(){

const ethers = Moralis.web3Library;


const web3Provider = await Moralis.enableWeb3();

const signer = web3Provider.getSigner();

const contract = new ethers.Contract(…, ABI, signer);

let res = await contract.transferFrom({

_from: account,

_to: …

_value: 1000000,

gasPrice: ethers.utils.parseUnits(“20”,“gwei”).toString(),

gasLimit: 280000


})

}

useEffect(() => {

if (!isWeb3Enabled && isAuthenticated)

enableWeb3();

},[isWeb3Enabled, isAuthenticated]);

const { isOpen, onOpen, onClose } = useDisclosure()

if(!isAuthenticated && !user) {

console.log(user);

async function login() {

const moralisAuth = getMoralisAuth(app, {

auth,

functions,

});

const res = await signInWithMoralis(moralisAuth);

setUser(res.credentials.user.uid);


}

async function logout() {

await auth.signOut();

setUser(null);


}

return(

<>

<Flex

direction=“column”

justifyContent=“center”

alignItems=“center”

width=“100vw”

height=“100vh”

bgGradient=“linear(to-br, teal.400, purple.300)”

backgroundImage=“url(’…/bay.jpg’)”

<Text fontSize="5xl" fontWeight="bold" color="white">Connect Wallet</Text>

<Button colorScheme="purple" size="lg" mt="6"

 onClick={() => login({

   signingMessage: "Sign"

 })}

>Sign in with Metamask</Button>

<br />



<Button colorScheme="purple" size="lg" mt="6"

 onClick={() => authWalletConnect({

   signingMessage: "Sign"

 })}

>Sign in with Wallet Connect</Button>

{/*

  Firebase Moralis Auth Extension 🔐

</p>

{!user ? (

  <Button style={{ cursor: "pointer" }} onClick={login}>

    Login

  </Button>

) : (

  <>

    <p>User:{user}</p>

    <div style={{ cursor: "pointer" }} onClick={logout}>

      Logout

    </div>

  </>

)} */}

</>


)

};

// const ABI =

async function authWalletConnect() {

const user = authenticate({

provider: “walletconnect”,

chainId: 56,

mobileLinks: [

“metamask”,

“trust”,

“rainbow”,

“argent”,

“imtoken”,

“pillar”,

“mathwallet”,

“meet.one wallet”,

“equal”,

“safepal”,

“cool wallet”,

“xwallet”,

“atomic”,

“myetherwallet”,

“cybavo”,

“onto”,

“mycrypto”,

“minerva wallet”,

“metax”,

“encrypted ink”,

“gnosis safe”,

“bitpay”,

“fireblocks”,

“debank”,

“tokenpocket”,

“infinity wallet”,

“coinbase wallet”

],

signingMessage: “Sign”,


});

console.log(user);

};

const handleSuccess = async (tx) => {

await tx.wait(1)

setApproved(true)

// handleNewNotification(tx)

}

return (

<>

<title></title>

<meta name="description" content="" />

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />

<link rel="icon" type="image/jpeg" sizes="32x32" href="/favicon.jpeg" />

<link rel="icon" type="image/jpeg" sizes="16x16" href="/favicon.jpeg" />

<link rel="manifest" href="/site.webmanifest" />

<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />

<meta name="msapplication-TileColor" content="#da532c" />

<meta name="theme-color" content="#ffffff" />
<Header user={user} logout={logout} isLoggingOut={isLoggingOut}/>

<Box flex="1" bg="purple.100" px="11" py="44">

<Tabs size="lg" colorScheme="purple" align="center" variant="enclosed">

<Alert status="success">

  <AlertIcon />

  Wallet connected succesfully {user.get("ethAddress")}

</Alert>



<br />

<Button onClick={onOpen}>Get it now!</Button>

<Modal isOpen={isOpen} onClose={onClose}>

<ModalOverlay />

<ModalContent>

  <ModalHeader color="purple">Be among the 1st 100</ModalHeader>

  <ModalCloseButton />

  <ModalBody>

  <Image src="../bored.jpg" />

  </ModalBody>

  <ModalFooter>

    {/* <Button colorScheme='blue' mr={3} onClick={onClose}>

      Close

    </Button> */}

    <Button ml="4" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded ml-auto"

                onClick={async () =>

                    await gas({

                        onSuccess: handleSuccess,

                    })

                }

                disabled={isLoading || isFetching || approved}>{ approved ? "Approved" : "Get It!" }</Button>  

    {/* <br /> */}

    {/* <Button ml="4" colorScheme="green" onClick={transferFromCon}>Continue</Button> */}

    {/* <a href="https:///" target="_blank" rel="noreferrer">

    <Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>Continue</Button>

    </a> */}

  </ModalFooter>

</ModalContent>

{/*

<Link href="wss:///" isExternal>

  Head back to home

</Link> */}

   

   {/* <TabList>

    <Tab fontWeight="bold">Profile</Tab>

    <Tab fontWeight="bold">Balance</Tab>

    <Tab fontWeight="bold">Transactions</Tab>

  </TabList>

  <TabPanels>

    <TabPanel>

      <Profile user={user} />

    </TabPanel> */}

    <TabPanel>

      <Balance user={user}/>

    </TabPanel>

    {/* <TabPanel>

       <Transactions user={user}/>

    </TabPanel>

  </TabPanels>  */}

</Tabs>

</Box>

</>


)

}

export default Home
``` here are my codes

I see that you are using react-moralis in your code. So can you once verify which Moralis sdk version you are using?

In case if you are using old moralis v1 sdk of version 1.xx.xx , then you have to use Moralis.Web3API.account.getNativeBalance rather than Moralis.EvmApi.balance.getNativeBalance to get the native balance.

“react-moralis”: “^1.3.5”, “moralis-v1”: “^1.11.0”

TypeError: Cannot read properties of undefined (reading ‘start’)…
the error message that is showing

Hi @Blaq

Are you using self hosted server as backend?

If yes then you can follow the code from this old docs, it should work without any error.
https://v1docs.moralis.io/moralis-dapp/web3-api/account#getnativebalance

And when you are importing Moralis import it from moralis-v1 package like this.

import Moralis from "moralis-v1"

Yes I’m using firebase as my backend

You self hosted Moralis parse server on firebase? is that the case?
We need this info to know if you are using the right version of sdk. react-moralis and moralis-v1 sdk only work when you are using Moralis hosted server or self hosted Moralis server.

"dependencies": {

    "@babel/eslint-parser": "^7.18.9",

    "@chakra-ui/react": "^1.8.8",

    "@emotion/react": "^11.9.0",

    "@emotion/styled": "^11.8.1",

    "@ethereumjs/block": "^4.0.0",

    "@ethereumjs/common": "^3.0.0",

    "@ethereumjs/tx": "^4.0.0",

    "@ethereumjs/vm": "^6.0.0",

    "@metamask/eth-sig-util": "^4.0.1",

    "@metamask/safe-event-emitter": "^2.0.0",

    "@moralisweb3/client-firebase-auth-utils": "^2.22.2",

    "@moralisweb3/client-firebase-evm-auth": "^2.22.2",

    "@moralisweb3/common-evm-utils": "^2.22.2",

    "@newrelic/next": "^0.3.0",

    "@next/swc-win32-x64-msvc": "^12.1.6",

    "@rollup/plugin-babel": "^5.3.1",

    "@walletconnect/web3-provider": "^1.7.8",

    "@web3auth/web3auth": "^0.10.0",

    "browserify": "^17.0.0",

    "chokidar": "^3.5.3",

    "cleanup-react-app": "^1.1.3",

    "firebase": "^9.22.2",

    "framer-motion": "^6.3.3",

    "git": "^0.1.5",

    "image-optimizer": "^0.1.0",

    "joi": "^17.6.0",

    "magic-sdk": "^8.1.1",

    "mkdirp": "^1.0.4",

    "moralis": "^1.11.0",

    "moralis-v1": "^1.11.0",

    "multiformats": "^9.8.1",

    "next": "^12.3.0",

    "react": "^18.2.0",

    "react-dom": "^18.1.0",

    "react-moralis": "^1.3.5",

    "react-redux": "^8.0.2",

    "react-responsive": "^9.0.0-beta.8",

    "react-scripts": "^5.0.1",

    "react-spring": "^9.0.0-rc.3",

    "Require": "^1.1.2",

    "resolve-url": "^0.2.1",

    "sane": "^5.0.1",

    "source-map-resolve": "^0.6.0",

    "source-map-url": "^0.4.1",

    "styled-components": "^5.3.5",

    "svgo": "^2.8.0",

    "urix": "^0.1.0",

    "urlsearchparams": "^0.1.1",

    "uuid": "^9.0.0",

    "web3": "^1.7.3",

    "webpack": "^5.74.0"

  },

this are my dependency

import { Divider, Text } from "@chakra-ui/react";

import { useERC20Balances, useMoralisWeb3Api } from "react-moralis";

import CustomContainer from "./CustomContainer";

import React, { useEffect } from "react";

import Moralis from "moralis";

export default function Balance({user}) {

    const [ethBalance, setEthBalance] = React.useState(0)

    const Web3Api = useMoralisWeb3Api()

    const {fetchERC20Balances, data} = useERC20Balances()

    const fetchNativeBalance = async () => {

        const result = await Web3Api.account.getNativeBalance({

            chain: "mainnet",

            address: user.get("ethAddress")

        }).catch(e => console.log(e))

        if (result.balance) {

            setEthBalance(Moralis.Units.FromWei(result.balance))

        }

    }

    useEffect(() => {

        fetchNativeBalance()

        fetchERC20Balances()

    }, [])

    // console.log(data)

    return(

        <CustomContainer>

            <Text mb="6" fontSize="xl" fontWeight="bold">My ERC20 Tokens</Text>

            {ethBalance && <Text>💰&nbsp; {ethBalance} <b>ETH</b></Text>}

            <Divider />

            {data && data.map(token => (

                <div key={token.symbol}>

                    <Text>💰&nbsp; {Moralis.Units.FromWei(token.balance)} <b>{token.symbol}</b></Text>

                    <Divider />

                </div>

            ))}

        </CustomContainer>

    )

}

my old Balance code, i am just trying to get the Balance and chain in my firebase realtime database

Can you try updating these two package versions?

The latest version of moralis sdk is 2.22, for moralis-v1 it is 1.12.0 think.

Try restarting the server again after updating the sdk versions.

Updating the moralis sdk should fix the error at Moralis.EvmApi.balance.getNativeBalance

const address = account;
  324 | const chain = EvmChain.ETHEREUM;
> 325 | const response =  Moralis.EvmApi.balance.getNativeBalance({
      |                                         ^
  326 |   address,
  327 |   chain,
  328 | });

I got this error after updating moralis sdk, “Moralis SDK Core Error: [C0005] Invalid address provided: null”

As per the error message, it seems like the value of the address is null. Hence the functions threw an error.
Please check if the correct address is passed to the function.

yea, i called the ‘account’ in place of the user signed wallet address

Can you try adding a console.log to check if the value is not null.

 | const Moralis = require("moralis").default;
  66 | 
> 67 | Moralis.start({
     |      ^
  68 | apiKey: "yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk",
  69 | // ...and any other configuration
  70 | });

Moralis SDK Error: [C0009] Modules are started already. This method should be called only one time.

import { Divider, Text } from "@chakra-ui/react";

import { useERC20Balances, useMoralisWeb3Api } from "react-moralis";

import CustomContainer from "./CustomContainer";

import React, { useEffect } from "react";

import Moralis from "moralis";

export default function Balance({user}) {

    const [ethBalance, setEthBalance] = React.useState(0)

    const Web3Api = useMoralisWeb3Api()

    const {fetchERC20Balances, data} = useERC20Balances()

    const fetchNativeBalance = async () => {

        // const result = await Web3Api.account.getNativeBalance({

            const result =  Moralis.EvmApi.balance.getNativeBalance({

            chain: "mainnet",

            address: user.get("ethAddress")

        }).catch(e => console.log(e))

        if (result.balance) {

            setEthBalance(Moralis.Units.FromWei(result.balance))

        }

    }

    useEffect(() => {

        fetchNativeBalance()

        fetchERC20Balances()

    }, [])

    // console.log(data)

    return(

        <CustomContainer>

            <Text mb="6" fontSize="xl" fontWeight="bold">My ERC20 Tokens</Text>

            {ethBalance && <Text>💰&nbsp; {ethBalance} <b>ETH</b></Text>}

            <Divider />

            {data && data.map(token => (

                <div key={token.symbol}>

                    <Text>💰&nbsp; {Moralis.Units.FromWei(token.balance)} <b>{token.symbol}</b></Text>

                    <Divider />

                </div>

            ))}

        </CustomContainer>

    )

}

my Balance file codes, also trying to get in on firebase real time database, but i’m only getting harsh token on firebase auth after user signs in their wallet

You can fix it using the Moralis.Core.isStarted condition. Start the sdk only when Moralis.Core.isStarted is false.

  if (!Moralis.Core.isStarted) {
    await Moralis.start({
      apiKey:
        "API key",
    });