[SOLVED]How to get nativeBalance?

Which should follow? Github or docs.moralis.io?

If follow https://github.com/MoralisWeb3/react-moralis#usenativebalance, got error :

image

Also official web site, cannot work, too.

https://docs.moralis.io/moralis-dapp/web3-sdk/account

You have latest version of Moralis SDK?

1 Like
{
  "name": "moralis-dashboard3",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@chakra-ui/react": "^1.8.8",
    "@emotion/react": "^11",
    "@emotion/styled": "^11",
    "@walletconnect/web3-provider": "^1.7.7",
    "@web3auth/web3auth": "^0.9.0",
    "framer-motion": "^6",
    "magic-sdk": "7.0.0",
    "moralis": "^1.5.9",
    "next": "12.1.5",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "react-moralis": "^1.3.5"
  },
  "devDependencies": {
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5"
  }
}

image

It looks like a typo there, use Web3API.account.getNativeBalance

2 Likes

You are right.

image

Fixed the typo. Still cannot get the native balance.

import Moralis from "moralis";
import { useEffect, useState } from "react";
import { Text } from "@chakra-ui/react";
import { useMoralisWeb3Api } from "react-moralis";
import CustomContainer from "./CustomContainer"

export default function Balance({ user }) {
  const Web3API = useMoralisWeb3Api()
  const [ethBalance, setEthBalance] = useState()
  useEffect(() => {
    // 1. Native Balance
    const fetchNativeBalance = async () => {
      const result = await Web3API.account.getNativeBalance({
        chain: process.env.CHAIN_NAME,
        address: user.get("ethAddress")
      })
      console.log("result -> ", result)
      if (result && result.balance) {
        setEthBalance(Moralis.Units.FromWei(result.balance))
      } else {
        console.log("No balance ??? ")
      }
    }
    fetchNativeBalance()
  }, [Web3API.account, user, Web3API])

  return (
    <CustomContainer>
      <Text mb="6" fontSize={"xl"} fontWeight="bold">My ERC20 Tokens</Text>
      {ethBalance && <Text>๐Ÿ’ฒ&nbsp;  {ethBalance} <b>ETH</b></Text>}
    </CustomContainer>
  )
}

Can you log the values for those parameters? To see if they have the expected value.

1 Like

Sorry, itโ€™s my fault.
The root cause is process.env.CHAIN_NAME , it is undefined.

image

image

image

why it is undefinedโ€ฆ

summary:

For APP, building with NEXT, the environment variable should start with NEXT_PUBLIC_

Change CHAIN_NAME to NEXT_PUBLIC_CHAIN_NAME can solve this issue.

Comment here for later coming friend.

1 Like