Get current user Wallet Address for function

I am in need of the current connected wallet’s address for use within a smart contract read function.

I am trying to call a smart contract read function with:

function ViewUserDeposits() {
    const { runContractFunction, data, error, isLoading, isFetching } =
      useApiContract({
        address: contrAddress,
        functionName: "getUserDepositHistory",
        chain: "mumbai",
        abi: Abi,
        params: {
          _user: account,
          _numBack: 1,
        },
      });
    useEffect(() => {
      const interval = setInterval(() => {
        runContractFunction();
      }, 4000);
      return () => clearInterval(interval);
    }, []);
    return; //setting this to "return account;" will show the wallet address correctly wherever ViewUserDeposits() is rendered
}

My problem is within the params option in ViewUserDeposits(), I require sending the users wallet address for “_user”.

        params: {
          _user: account,
          _numBack: 1,
        },

I can render the address by using “account” from

const { authenticate, isAuthenticated, account, chainId, logout } =
useMoralis();

By calling {account} in html i get a 0x address to display. The “account” does contain the address i need but when i use it in the parameters of the function it doesn’t return anything. It does however work if i manually hardcode the 0x address instead of using a variable like account. I have tried sending account into the parameters of the ViewUserDeposits (ViewUserDeposits(account)) function and using it from there but i get the same results.
Have tried making changes to the “account” such as JSON.stringify(), toLowerCase(), and Removing quotes (with .replace(/[’"]+/g, ‘’) ). These all some to do the trick when displaying the address on the page but there is no change when used in the function.

Have also tried using

const { Moralis } = useMoralis();
Moralis.User.current().get("ethAddress");

Although whenever I try this approach I cannot get the address to display and the page doesn’t render.

1 Like

not sure if it will work:

const { user } = useMoralis();

Just tried with same results as

Moralis.User.current().get(“ethAddress”);

Not rendering page when called, wont work when used in function. How would i use user, could i do the same as with the Moralis.User above? user.current() doesn’t seem to work, but Moralis.User.current() does.

you may need to use useEffect with user object

Thank you for the quick replies!
I am trying to do this now, have only used useEffect for repeating timers. How would I properly use useEffect with user?

    useEffect((user) => {
      addy = user;
    });
    useEffect(() => {
      addy = user;
    });

Have read https://www.w3schools.com/react/react_useeffect.asp but still unable to comprehend.

this may help you:

1 Like

I have tried refetchUserData but it hasn’t helped.I found that JSON.stringify(user) does bring up information

{"username":"#############","authData":{"moralisEth":{"id":"############","signature":"#############","data":"Moralis Authentication\n\nId: #############################"}},"createdAt":"2022-03-16T20:25:25.812Z","updatedAt":"2022-03-25T19:39:57.079Z","accounts":["0x96d2f56547375a784Aa2abB0eC9CA93c6a6A36c5"],"ethAddress":"0x96d2f56547375a784Aa2abB0eC9CA93c6a6A36c5","ACL":{"WQbzLRjvDqLF0u58wPsmw417":{"read":true,"write":true},"role:coreservices":{"read":true,"write":true}},"sessionToken":"r:f3f52a0a73c0737f1d69bf76db6e2819","objectId":"WQbzLRjvDqLF0u58wPsmw417"}

I have tried using JSON.stringify(user.get(“ethAddress”)) but the page just stops rendering. The info seems to be there, I just cant figure out how to access it. Even if I can access it, I worry that the same issue will occur (Can get address but cannot use it within the option parameter for the useApiContract) as with the account variable previously used.

try this:

export default function ViewUserDeposits() {
    const { account } = useMoralis(); 
    const { runContractFunction, data, error, isLoading, isFetching } =
      useApiContract({
        address: contractAddress,
        functionName: "getUserDepositHistory",
        chain: "mumbai",
        abi: Abi,
        params: {
          _user: account,
          _numBack: 1,
        },
      });

    useEffect(() => {
      if(account && !data && !isFecthing){
        runContractFunction();
      };
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [account, data, isFetching]);

    return (
        <div>{data}</div>
    )
}

It waits for the account of the current connected wallet address to load. Checks if the data has already been fetched. Makes sure the function is not already in the process of fetching. Then calls the contract function and returns the data in a div

1 Like

Works great, can now use the account variable inside the function!
Thank you!

1 Like

Spent so many hours searching for this and this forum post helped me immensely!!! I realized that I was originally doing this:

const userAddress = user?.get("username")

I noticed that in the Moralis server databases now, there isn’t an automatically generated field called the ethAddress but now one that is called authData that can contain many different wallets/addresses, which gives more utility but will cause previous fetches of the .get("ethAddress") to fail because it will look for a field that isn’t automatically generated via pointer / cloud job anymore.

This is the code I use now to get the eth wallet for the current user is this:

const userAddress = user?.attributes.authData["moralisEth"]["id"];

Hopefully this helps anyone searching for how to do this with a React-based framework :blush:

Today August 2022, the solution to know the currentAddress of the connected Wallet is:

const { account } = useMoralis();

And to know the current balance of a specific Token:

import Moralis from 'moralis';

const result = await Moralis.Web3API.account.getTokenBalances({
        chain: 'ropsten', // example chain
        address: account ?? '',
        token_addresses: ['0x...'] // contract address,
      });

result:

// balance: ‘5000000000000000000’;
// decimals: 18;
// logo: null;
// name: ‘ADA Token’;
// symbol: ‘ADA’;
// thumbnail: null;
// token_address: ‘0x…’;

Link reference: https://v1docs.moralis.io/moralis-dapp/web3-api/account#gettokenbalances