Fetch user address and balance for 1 token

Iโ€™m trying to fetch the current user address into ABI and to output the token balance.
Stuck on this for two days straight now, reached the far lands of github, circled google - any advice ?

 import { useMoralis, useMoralisWeb3Api } from "react-moralis"
 import {useEffect, useState} from "react"
 
 function AVAXToken() {
 
   const web3api = useMoralisWeb3Api();
   const [balance, setBalance] = useState(0);
   //const user = Moralis.User.current();
   //const { account, isAuthenticated } = useMoralis();
   //const [address, setAddress] = useState();
   //const { Moralis, chainId } = useMoralis();
   //const web3 = await Moralis.enableWeb3();
 
   const { user } = useMoralis();
 
   const ABI = [{
     "inputs": [
       {
         "internalType": "address",
         "name": "account",
         "type": "address"
       }
     ],
     "name": "balanceOf",
     "outputs": [
       {
         "internalType": "uint256",
         "name": "",
         "type": "uint256"
       }
     ],
     "stateMutability": "view",
     "type": "function"
   }];
 
   const options = {
     chain: "avalanche",
     function_name: "balanceOf",
     address: "0x95c8c21c261e3855b62f45121197c5a533a8a4a3",
     abi: ABI,
     params: {account: user.get("ethAddress")} //Here
   }
 
   useEffect(() = {
     web3api.native.runContractFunction(options).then(result = {
       setBalance(result)
     })
   },[]);
 
   const ABI2 = [
       "inputs": [],
       "name": "totalSupply",
       "outputs": [
         {
           "internalType": "uint256",
           "name": "",
           "type": "uint256"
         }
       ],
 
       "stateMutability": "view",
       "type": "function"
     }
 
   ]
 
   const options2 = {
     chain: "avalanche",
     function_name: "totalSupply",
     address: "0x95c8c21c261e3855b62f45121197c5a533a8a4a3",
     abi: ABI2
   }
 
   const [supply, setSupply] = useState(0);
   useEffect(() = {
     web3api.native.runContractFunction(options2).then(result = {
       setSupply(result);
     })
   },[])
 
   return (
 
     <div className="text-center p-5"
       <div{`My Balance: ${balance}`}</div
       <div{`Token supply: ${supply}`}</div
       <div{`My percentage: ${balance/supply*100}%`}</div
     </div
   )
 }
 
 export default AVAXToken

what are the problems that you have here, it looks like the code tries to call 2 contract functions

It outputs a white page, tried to add a check function in between so that no ethaddress will be outputted but a simple โ€œโ€ if none but that didnโ€™t work either.

you could look here: https://github.com/MoralisWeb3/react-moralis#useapicontract
you could look to see if you have any error in the browser console

you can also try on codesandbox

No need for #useapicontract, it fetches fine with a static ethaddress, just need a way to push it into the options. I need it in params, even with your way.

Not helpful

2022-02-01T16:37:08.795Z - Error: invalid address (argument="address", value={"ethAddress":"0x0000000000000000000000000000000000000000"}, code=INVALID_ARGUMENT, version=address/5.4.0) (argument="account", value={"ethAddress":"0x0000000000000000000000000000000000000000"}, code=INVALID_ARGUMENT, version=abi/5.0.7)
    at fetch (/moralis-server/lib/cloud-code/plugins/convenience/web3Api.js:165:26)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-02-01T16:37:08.793Z - Failed running cloud function runContractFunction for user undefined with:
  Input: {"chain":"avalanche","function_name":"balanceOf","address":"0x95c8c21c261e3855b62f45121197c5a533a8a4a3","abi":[{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}],"params":{"account":{"ethAddress":"0x0000000000000000000000000000000000000000"}}}
  Error: {"message":"invalid address (argument=\"address\", value={\"ethAddress\":\"0x0000000000000000000000000000000000000000\"}, code=INVALID_ARGUMENT, version=address/5.4.0) (argument=\"account\", value={\"ethAddress\":\"0x0000000000000000000000000000000000000000\"}, code=INVALID_ARGUMENT, version=abi/5.0.7)","code":141}
2022-02-01T16:05:39.155Z - Error: invalid address (argument="address", value={"ethAddress":"0x0000000000000000000000000000000000000000"}, code=INVALID_ARGUMENT, version=address/5.4.0) (argument="account", value={"ethAddress":"0x0000000000000000000000000000000000000000"}, code=INVALID_ARGUMENT, version=abi/5.0.7)
    at fetch (/moralis-server/lib/cloud-code/plugins/convenience/web3Api.js:165:26)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

A bit lost here

import { useMoralis, useMoralisWeb3Api } from "react-moralis"
import {useEffect, useState} from "react"
import NumberFormat from 'react-number-format';

function AVAXToken() {
  const web3api = useMoralisWeb3Api();
  const [balance, setBalance] = useState(0);

  //const user = Moralis.User.current();
  //const { account, isAuthenticated } = useMoralis();
  //const { Moralis, chainId } = useMoralis();
  //const web3 = await Moralis.enableWeb3();
  //const [userAddress] = useState(0);
  const { user } = useMoralis();
  
  const [ethAddress, setAddress] = useState("0x0000000000000000000000000000000000000000");

  const ABI = [{
    "inputs": [
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "balanceOf",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  }];

  const options = {
    
    chain: "avalanche",
    function_name: "balanceOf",
    address: "0x95c8c21c261e3855b62f45121197c5a533a8a4a3",
    abi: ABI,
    params: {account: {ethAddress}} //Get user address
  }

  useEffect(() => {
    if (!user) return null;
    setAddress(user.get("ethAddress"))
  }, [user]);
  
  useEffect(() => {
    const lendbal = web3api.native.runContractFunction(options).then(result => {
      setBalance(result)
      console.log("responce:", lendbal)
    })

  },[]);

  const ABI2 = [
    {
      "inputs": [],
      "name": "totalSupply",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    }
  ]
  const options2 = {
    chain: "avalanche",
    function_name: "totalSupply",
    address: "0x95c8c21c261e3855b62f45121197c5a533a8a4a3",
    abi: ABI2
  }

  const [supply, setSupply] = useState(0);

  useEffect(() => {
    web3api.native.runContractFunction(options2).then(result => {
      setSupply(result);
    })
    
  },[])

  return (
    <div className="text-center p-5">
      <div>{`My Balance: ${balance}`}</div>
      <text>Total Supply</text><NumberFormat value={supply} displayType={'text'} thousandSeparator={true} />
      <div>{`My percentage: ${balance/supply*100}%`}</div>
    </div>
  )
}

export default AVAXToken

it looks like it doesnโ€™t send the parameter the value and it also adds that ethAddress name

I donโ€™t know how to do it in react to send only the value from that variable

import { useMoralis, useMoralisWeb3Api } from "react-moralis"
import {useEffect, useState} from "react"
import NumberFormat from 'react-number-format';

function AVAXToken() {
  const [balance, setBalance] = useState(0);

  //const { Moralis } = useMoralis();
  const { isInitialized } = useMoralis();
  //const user = Moralis.User.current();
  const { user } = useMoralis();
  const web3 = useMoralisWeb3Api();
  //const [userAddress] = useState(0);
  const userAddr = user?.get("ethAddress");


  const ABI = [{
    "inputs": [
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "balanceOf",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  }];

  const options = {
    
    chain: "0xa86a",
    function_name: "balanceOf",
    address: "0x95c8c21C261E3855b62F45121197c5a533a8a4A3",
    abi: ABI,
    params: {who: {userAddr}} //Get user address
  }
  
  useEffect(() => {
    if(isInitialized){  

      console.log(options);
      const lendbal = web3.native.runContractFunction(options).then(result => {
        setBalance(result)
        console.log(result)
      })
    }
  },[isInitialized]);

  const ABI2 = [
    {
      
      "inputs": [],
      "name": "totalSupply",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    }
  ]
  const options2 = {
    chain: "avalanche",
    function_name: "totalSupply",
    address: "0x95c8c21c261e3855b62f45121197c5a533a8a4a3",
    abi: ABI2
  }

  const [supply, setSupply] = useState(0);

  useEffect(() => {
    const lendbal2 = web3.native.runContractFunction(options2).then(result => {
      setSupply(result);
    })
    
  },[])

  return (
    <div className="text-center p-5">
      <div>{`My Balance: ${balance}`}</div>
      <text>Total Supply</text>{  }<NumberFormat value={supply} displayType={'text'} thousandSeparator={true} />
      <div>{`My percentage: ${balance/supply*100}%`}</div>
    </div>
  )
}

export default AVAXToken

Try 5034, no luck

I think that here is the problem, I guess that if you hardcode the address there then it would work

yeah try that first as @cryptokid says, I think might be you need to use useMemo for userAddr so it updates whenever user changes, coz user will be null in first render, making your userAddr undefined.

import { useMemo } from "react";

const userAddr = useMemo(() => user?.get("ethAddress"), [user]);
2 Likes