[SOLVED] Display BSC Contract Info

I pasted this code directly into the web console and I get the error:
Uncaught Error: Missing web3 instance, make sure to call Moralis.enable() or Moralis.authenticate()

I tried using const web3 = await Moralis.enable(); at the very top of my main.js file, then I get the error about await must be in asyncā€¦etc

I think maybe itā€™s the SDK version you were talking about, but Iā€™m so confused on what Iā€™m supposed to do to be on the latest version?

you have the right Moralis SDK version

you can also add this line: web3 = await Moralis.enable();
I tested in a page that was already doing this.

1 Like

Is there a way that I can set up a page that has the web3 enabled line to cover the whole page? whenever I put the line const web3 = await Moralis.enable(); by itself in the js file, console shows an error of ā€œawait must be inside async functionā€

this works:

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
    <script>
async function totalRewards(){
    web3 = await Moralis.enable();
    let contractAbi = [{"inputs":[],
    "name":"viewRewardsAndLiquidityInfo",
    "outputs":[
        {"internalType":"uint256","name":"budsAccumulationFromRewardsFee","type":"uint256"},
        {"internalType":"uint256","name":"sumOfAllHOLDRBalances","type":"uint256"},
        {"internalType":"uint256","name":"theCurrentRewardsCycle","type":"uint256"},
        {"internalType":"uint256","name":"lengthOfRewardsCycle","type":"uint256"},
        {"internalType":"uint256","name":"budsAccumulationFromLiquidityFee","type":"uint256"},
        {"internalType":"uint256","name":"lastTimeDividendsWereReleased","type":"uint256"},
        {"internalType":"uint256","name":"dividendsClaimableNow","type":"uint256"},
        {"internalType":"uint256","name":"dividendsLeftFromReservedSupplyForHOLDRs","type":"uint256"}
        ],"stateMutability":"view","type":"function"}];
    const options = {
    contractAddress: "0x058cdF0fF70f19629D4F50faC03610302e746e58",
    functionName: "viewRewardsAndLiquidityInfo",
    abi: contractAbi,
    };  
    x = await Moralis.executeFunction(options)
    return x;
}             
  x = totalRewards()
  x.then(
        function(value) {console.log(value);},
        function(error) {console.log(error);}
      );
    </script>
</body>
</html>
1 Like

Thanks for your help on that! I managed to get it into the frontend html file as well.
Now I have a new issue lolā€¦

I tried using these codes to test out getting BNB balance as well as all bep20 tokens, and they worked.

async function userBNB(){
// get BSC native balance for a given address
const optionsBNB = { chain: "bsc"};
const balance = await Moralis.Web3API.account.getNativeBalance(optionsBNB);
console.log(balance)
}

async function userBudsBalance(){
    const chainOptions = { chain: 'bsc' }
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    console.log(balances);
}

But I saw this snippet in the forum:

And so I attempted to add to my code:

async function userBudsBalance(){
    const chainOptions = { chain: 'bsc', address: "0xa...96eE1" } // used an address that has a bunch of bep20 tokens
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    //const tokenAddress =  "0x720b40cd711df11e62dfd0c88797da100d5f09e6"; // 420 Contract Address
    //const tokenAddress =  "0x058cdF0fF70f19629D4F50faC03610302e746e58"; // Buds Contract Address
    //const tokenBalance = balance.find((token) => token.token_address === tokenAddress);
    console.log(balances);
}

I tried it with two different tokenā€™s contract addresses, because I donā€™t currently have Buds in the wallet, but I do have 420 tokens. In both cases, I got a console error that ā€œbalance is not definedā€ and it was pointing to the line const tokenBalance. I also tried replacing token with the token name but it didnā€™t work. Maybe itā€™s because 420 Token has a space in the name and I donā€™t know how to properly format it for javascript to read. Or maybe Iā€™m just completely missing something, like I usually do lol. Any help I can get from you would be amazing! By the way, are you on Github? I am planning on using the dapp I code for my token project to use, Iā€™d like to credit you somehow. Really grateful for all your help.

it looks like you used balance.find instead of balances.find.

So console.log shows the balances fine for BNB & the specific token. I tried them using these codes:

BNB:

async function userBNB(){
// get BSC native balance for a given address
const optionsBNB = { chain: "bsc"};
const balance = await Moralis.Web3API.account.getNativeBalance(optionsBNB);
console.log(balance)
return balance;
}

/* I'm not actually sure if I need this section below, but I just did it
because you previously helped me with another set of codes and they worked. */

const balance = userBNB()

    balance.then(
        function(value) {console.log(value);},
        function(error) {console.log(error);}
    );

Specific Token, in this case 420 Token

async function userBudsBalance(){
    const chainOptions = { chain: 'bsc', address: "0xaF88...96eE1" }
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    const tokenAddress =  "0x720b40cd711df11e62dfd0c88797da100d5f09e6"; // 420 Contract Address
    // const tokenAddress =  "0x058cdF0fF70f19629D4F50faC03610302e746e58"; // Buds Contract Address
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    console.log(tokenBalance.balance); // I changed the log so it'd only show the balance
    return tokenBalance.balance;
}

const tokenBalance = userBudsBalance()

    tokenBalance.then(
        function(value) {console.log(value);},
        function(error) {console.log(error);}
      );

Then I tried to get it to show up in the frontend html:

document.getElementById("budsBalance").innerHTML = tokenBalance.balance;

and I got the error undefined. Iā€™ve tried other options like balance, userBNB, userBudsBalance, they came back undefined or just shows the entire function on the frontend.

please help lol and thank you for your patience

maybe this works for you:

const tokenBalance = userBudsBalance()

    tokenBalance.then(
        function(value) {
               console.log(value);
               document.getElementById("budsBalance").innerHTML = value;},
        function(error) {console.log(error);}
      );
1 Like

You sir, are a rock star! Thank you!

funny that none of the video tutorials had this line, I ahd the same error and I tyhink this will fix it (letā€™s seeā€¦)

I also want to show the balance of users native token
So

const chainOptions = { chain: ā€˜bscā€™, address: ā€œ0xaF88ā€¦96eE1ā€ }

In this line which address should be given ?

I think that the address of the wallet for which you want to get the native balance should be there

i put the same code but changing token address and wallet address but balance did not shows in my console ā€¦

async function usercptBalance(){

const chainOptions = { chain: 'bsc' ,address:"0x5974c357769D77a04CD87AeE3e49e5bf719d1CFe" }

const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);

const tokenAddress =  "0x28e4f32fa7e842ad0a6e530bb6b4ec03b36d5078";

const tokenBalance = balances.find((token) => token.token_address === tokenAddress);

console.log(tokenBalance.balance);

return tokenBalance.balance;

} https://bscscan.com/token/0x28e4f32fa7e842ad0a6e530bb6b4ec03b36d5078?a=0x88a393f2aff8d8e0dd7bb4add82cd8ebac439b9e
my contract
is there any way to call balanceof function of my contract ?

when i m doing through console browser it shows balance but when i m doing through my code its nothing shows there why it is ? due to moralis.start ?

this returns the balances of ERC20 tokens, but not also the native balance
for native balance you have to use getNativeBalance: https://docs.moralis.io/moralis-server/web3-sdk/account#getnativebalance

if that code works in your browser console, it should work in your main js code too

yes it is working on my console for both my cpt token and bnb balance but it does not working on my codeā€¦
what u think i have to do moralis.intiliaze in the starting?

if it works in your browser console, it means that it should work in your code too,
but latest Moralis SDK syntax doesnā€™t use initialize any more, only Moralis.start

an example: https://github.com/MoralisWeb3/demo-apps/tree/main/moralis-vanilla-boilerplate

i try many times but it dont show on my console

<script>
    /* Moralis init code */
    const serverUrl = "https://4l81fhpvqkit.usemoralis.com:2053/server";
    const appId = "pfaPMZpSl0COD4qDiZ6ytcu2ePIMaPWI2pSrhTZm";
    Moralis.start({ serverUrl, appId });

    async function login() {
      let currentuser = Moralis.User.current();
      if (!currentuser) {
        currentuser = await Moralis.authenticate({ signingMessage: "welcome to crypto planet " })

      }
      console.log("logged in user:", currentuser);
      console.log(currentuser.get('ethAddress'))
    }

    async function logOut() {
      await Moralis.User.logOut();
      console.log("logged out");
    }
    async function userBNB(user) {


      // get BSC native balance for a given address

      const optionsBNB = { chain: "bsc" };

      const balance = await Moralis.Web3API.account.getNativeBalance(optionsBNB);

      console.log(balance)

    }

    async function usercptBalance() {
      const chainOptions = { chain: 'bsc' }
      const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
      const tokenAddress = "0x28e4f32fa7e842ad0a6e530bb6b4ec03b36d5078";
      const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
      console.log(tokenBalance.balance);
      return tokenBalance.balance;
    }

    document.getElementById("btn-login").onclick = login;
    document.getElementById("btn-logout").onclick = logOut;ype or paste code here