How to Calculate the Numbers Pulled from Blockchain by Moralis?

The first snippet of code gets the user’s balance tokenBalance using Moralis

async function userBudsBalance(){
    const chainOptions = { chain: "bsc" }
    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); //do your log here
    return tokenBalance.balance;
}

const tokenBalance = userBudsBalance()

    tokenBalance.then(
        function(value) {
            console.log(value);
            document.getElementById("budsBalanceNum").innerHTML = value/10**9;},
        function(error) {console.log(error);}
      );

the second snippet of code calls a smart contract for information to be displayed:

async function totalRewards(){
    const 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)
}



x = totalRewards()

    x.then(
        function(value) {
            console.log(value);
            const calcStepOne = tokenBalance;
            console.log(calcStepOne);
            y = x.budsAccumulationFromRewardsFee;
            console.log(y);
            z = y * calcStepOne;
            console.log(z);

            /* amount of rewards is calculated by:
            ((tokenBalance * x.budsAccumulationFromRewardsFee) / x.sumOfAllHOLDRBalances) / 10**9;
            problem is the first two steps are already resulting in NaN
            */

            document.getElementById("budsRewardPool").innerHTML = y / 10**9;
            document.getElementById("rewardsCycle").innerHTML = x.theCurrentRewardsCycle;
            document.getElementById("budsDividendsPool").innerHTML = x.dividendsLeftFromReservedSupplyForHOLDRs/10**9;},
        function(error) {console.log(error);}
      );

I am trying to calculate the amount of rewards a signed in user can get by doing the equation

((tokenBalance * x.budsAccumulationFromRewardsFee) / x.sumOfAllHOLDRBalances) / 10**9;

but I guess because one of them is a “promise fulfilled” object and the others are strings, I am getting a NaN error? Google led me to promise.resolve() but I am wildly confused on how to use that.

Thanks for the help!

ah. wait. I found another one to use. “Parse” I’m gonna try it

I was able to parse the information that was called from the smart contract, but still unable to figure out how to decipher the tokenBalance that was called using Moralis.

here’s what the console shows when I type in tokenBalance:

and here’s the code snippet I’ve used to get calculations done:

x = totalRewards()

    x.then(
        function(value) {
            console.log(value);
            b = tokenBalance;
            console.log(b);
    
            // need a way to parse b

            y = x.budsAccumulationFromRewardsFee / 10**9;
            console.log(y);
            parseInt(y);
            console.log(parseInt(y)); 
            z = x.sumOfAllHOLDRBalances / 10**9;
            console.log(z);
            
            a = y / z;
            console.log(a); //this worked
            
        

            /* amount of rewards is calculated by:
            ((tokenBalance * x.budsAccumulationFromRewardsFee) / x.sumOfAllHOLDRBalances) / 10**9;
            problem is the first two steps are already resulting in NaN
            */

            document.getElementById("budsRewardPool").innerHTML = y;
            document.getElementById("rewardsCycle").innerHTML = x.theCurrentRewardsCycle;
            document.getElementById("budsDividendsPool").innerHTML = x.dividendsLeftFromReservedSupplyForHOLDRs/10**9;
            document.getElementById("rewardsAmount").innerHTML = a;},
        function(error) {console.log(error);}
      );

Hi @derekryansnzy

Sorry for the long response. It really took a while to figure out what’s going on in your code.

And I’m still not sure if I understood the whole problem. Please try to clearly formulate the problem and “highligt” problem areas of the code.

instead of

y = x.budsAccumulationFromRewardsFee;

try to use:

y = value.budsAccumulationFromRewardsFee;

thanks for your response!

okay so basically, one of the functions of userBudsBalance uses Moralis to find the specific token balance of a user.

another function called totalRewards calls on a smart contract on BSC to return information to be displayed.

These are the information that totalRewards returns:

  • budsAccumulationFromRewardsFee
  • sumOfAllHOLDRBalances
  • theCurrentRewardsCycle
  • lengthOfRewardsCycle
  • budsAccumulationFromLiquidityFee
  • lastTimeDividendsWereReleased
  • dividendsClaimableNow
  • dividendsLeftFromReservedSupplyForHOLDRs

What I am trying to do is calculate the amount of rewards that a user can claim, based on how much tokens they have in their wallet.

The way to get that amount is (userBalance*budsAccumulationFromRewardsFee) / sumOfAllHOLDRBalances

the problem I am having is that the userBalance returned by Moralis is a promise and I don’t know how to use Javascript to turn it into numbers to fit into the above equation.

I have the full set of codes on Github if you’d like to take a look: https://github.com/derekryansnzy/CareBuds-Dapp/blob/main/main.js

or if you’d like me to paste the codes here for you once you understand my question I can do that too.

I’m so sorry if I word things wrong, I’m so new to this that the mess you see is literally the stuff I pull out of my brain lol. Thank you so much for your patience and your willingness to help me!

It returns promise only if you don’t await it. I sent you a place in the code where it is possible you have this error.

Why do you use:

const tokenBalance = userBudsBalance()

    tokenBalance.then(
        (value) => {
            console.log(value);
            document.getElementById("budsBalanceNum").innerHTML = value/10**9;},
        function(error) {console.log(error);}
      );

Instead of:

userBudsBalance.then(
        (value) => {
            console.log(value);
            document.getElementById("budsBalanceNum").innerHTML = value/10**9;},
        function(error) {console.log(error);}
      );

Function totalRewards() doesn’t return anything.
Why do you use variable x, but I don’t see that it was declared

Most of the codes you see on there are from the Moralis docs and I just did my best to modify them to get something that works lol. Sorry, super new to this and that’s my best explanation.

and here’s the link to how the function totalReWards was set up:

another Moralis member helped me with it. I will go through and check with your codes! Thank you so much, I’ll report back shortly.

1 Like

Feel free to ask any questions. Looking forward to see your code after refactoring :man_mechanic:

The Person Who Never Makes a Mistake Will Never Make Anything

I tried using value.budsAccumulationFromRewardsFee instead and I got this error:

b receives a promise and you don’t await it.

If you want to declare a variable from async function you need to use await:

const tokenBalance = await userBudsBalance();

Constrcution like this:

const tokenBalance = userBudsBalance();

tokenBalance.then((value) => {
    console.log(value)})

works because then is the same as await

It’s not a problem for me to rewrite your code. But I suggest you to spend some time and try to figure out what the problem is.

Thanks for your help! Yeah, I didn’t learn how to even write a single line of code till like last week. I was actually trying to hire developers for my project because the original developer I was working with said he coudln’t figure out Moralis. But I really wanted to use Moralis technology and couldn’t hire someone in time. So I just started watching videos, took some courses in Ivan On Tech and got to workk.

I am a bit confused right now though. When you say construction like this, because then is the same as result, I pulled the same code from my Github js file:

const tokenBalance = userBudsBalance()

    tokenBalance.then(
        (value) => {
            console.log(value);
            document.getElementById("budsBalanceNum").innerHTML = value/10**9;},
        function(error) {console.log(error);}
      );

Do you mean that I have to add the “await” to const tokenBalance as well?

So it would be like this:

const tokenBalance = await userBudsBalance()

    tokenBalance.then(
        (value) => {
            console.log(value);
            document.getElementById("budsBalanceNum").innerHTML = value/10**9;},
        function(error) {console.log(error);}
      );

Again, thank you for your patience. I went from Wordpress drag and drop to learning how to use Github ( I still don’t know what I’m doing on Github) and now I’m learning javascript as quickly as I can to implement Moralis into my dapp for my projects.

Yes, I do. Because you use the tokenBalance variable there:

x = totalRewards()

x.then(
        function(value) {
            console.log(value);
            b = tokenBalance;
            console.log(b);
})

and that’s why you see a Promise in console

another question. in order to use await, the entire thing would have to be an async function, right? because if I just wrote

const tokenBalance = await userBudsBalance();

then console shows a reference error and says that await needs to be inside of an async function.