How to Calculate the Numbers Pulled from Blockchain by Moralis?

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.

Also, wouldn’t it be repeating the same codes?

Section one of the codes uses Moralis to get the specific token of a user:

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);
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    console.log(tokenBalance.balance); // do your log here
    return tokenBalance.balance;
}

I think I got this section from a post I saw in this forum:

and then I added this section:

const tokenBalance = await userBudsBalance()

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

Because @cryptokid had helped me in a different issue so I thought maybe the same code would work for two different sections. Am I making any sense? Lol I feel like I got lost in my brain

You can use await only inside async function. Try to make the code refactoring . For example:

async function userBudsBalance(){
    const chainOptions = { chain: "bsc" }
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    const tokenAddress =  "0x058cdf0ff70f19629d4f50fac03610302e746e58"; // Buds Contract Address
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    return tokenBalance.balance;
}

async function updateHTML(value) {
   document.getElementById("budsBalanceNum").innerHTML = value/10**9;
}

userBudsBalance().then((balance) => {
   updateHTML(balance);
})

And the reason I added a second section was just to make sure the user’s tokenBalance can be displayed on the frontend, somewhere in the html

You can display it without any magic :mage: . All you need is async and await :grinning:

so then in this case, I can just use (value) to complete the original calculation I was trying to do?

It would be…
((value) * x.budsAccumulationFromRewards) / sumOfAllHOLDRSBalances

would this be correct?

this looks pretty magical to someone who’s used to looking at Wordpress drag and drop lol. Coding is literally kicking my butt. I like the challenge and I love learning but wow, doing it all from scratch and knowing absolutely nothing about javascript is intense

I replaced the two sections of codes with yours:

async function userBudsBalance(){
    const chainOptions = { chain: "bsc" }
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    const tokenAddress =  "0x058cdf0ff70f19629d4f50fac03610302e746e58"; // Buds Contract Address
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    return tokenBalance.balance;
}

async function updateHTML(value) {
   document.getElementById("budsBalanceNum").innerHTML = value/10**9;
}

userBudsBalance().then((balance) => {
   updateHTML(balance);
})

and console returned error, uncaught (in promise), tokenBalance is not defined

full code please :raised_hands:

The error message speaks about the error itself

maybe I should just change my title in the forum to asking if any developers are for hire and can get this job done within a couple days lol. By the time I learn Javascript it’ll be 2025 :rofl:

Full code:

Moralis.initialize("KVsRENKf8Y0FrI0l57LMYMjRJsQTd8UbYP36qFV0"); // Application id from moralis.io
Moralis.serverURL = "https://gdbymlyoujf7.moralishost.com:2053/server"; // Server url from moralis.io


 async function login() {
    const web3 = await Moralis.enable();

    try {
        currentUser = await Moralis.User.current();
        if (!currentUser) {
            currentUser = await Moralis.authenticate().then(function (user) {
                console.log(user.get('ethAddress'))
            })
        }
        console.log(currentUser);
        document.getElementById("connectWalletBtn").style.display = "none";
        document.getElementById("connectWalletBtnRt").style.display = "none";
        document.getElementById("BudsRewardsDapp").style.display = "block";
        document.getElementById("logoutBtn").style.display = "block";
        totalRewards();
    } catch (error) {
        console.log(error);
    }
}


logout = async () => {
    await Moralis.User.logOut();
    console.log(currentUser);
    document.getElementById("connectWalletBtn").style.display = "block";
    document.getElementById("connectWalletBtnRt").style.display = "block";
    document.getElementById("BudsRewardsDapp").style.display = "none";
}

/*
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);
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    console.log(tokenBalance.balance); // do your log here
    return tokenBalance.balance;
}

const tokenBalance = await userBudsBalance()

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


async function userBudsBalance(){
    const chainOptions = { chain: "bsc" }
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    const tokenAddress =  "0x058cdf0ff70f19629d4f50fac03610302e746e58"; // Buds Contract Address
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    return tokenBalance.balance;
}

async function updateHTML(value) {
   document.getElementById("budsBalanceNum").innerHTML = value/10**9;
}

userBudsBalance().then((balance) => {
   updateHTML(balance);
})




async function claimBudsRewards() {
    const web3 = await Moralis.enable();
    const Rewards = {
        contractAddress: "0x058cdF0fF70f19629D4F50faC03610302e746e58",
        functionName: "claimRewards",
        abi: window.abi
    };
    const BudsRewards = await Moralis.executeFunction(Rewards);
}

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);
    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("sumOfHolders").innerHTML = x.sumOfAllHOLDRBalances / 10**9;
  //  document.getElementById("rewardsAmount").innerHTML = a;
}, function (error) {
    console.log(error);
});


document.getElementById("connectWalletBtn").onclick = login;
document.getElementById("connectWalletBtnRt").onclick = login;
document.getElementById("logoutBtn").onclick = logout;
document.getElementById("budsClaimRewards").onclick = claimBudsRewards;

you’re right, I am a big doofus. I forgot to comment out

b = tokenBalance
console.log(b)

leave it up to me to make the simplest mistakes lol I’m sorry :man_facepalming:

So does it work correctly now?

Also I suggest you to “upgrade” return for this function:

async function userBudsBalance() {
  const chainOptions = { chain: "bsc" };
  const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
  const tokenAddress = "0x058cdf0ff70f19629d4f50fac03610302e746e58"; // Buds Contract Address
  const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
  if (tokenBalance) {
    return tokenBalance.balance;
  } else {
    return null;
  }
}

it called the balance of the user correctly, but I’m trying to figure out how to use that balance to calculate the amount of rewards that the user gets.

async function userBudsBalance(){
    const chainOptions = { chain: "bsc" }
    const balances = await Moralis.Web3API.account.getTokenBalances(chainOptions);
    const tokenAddress =  "0x058cdf0ff70f19629d4f50fac03610302e746e58"; // Buds Contract Address
    const tokenBalance = balances.find((token) => token.token_address === tokenAddress);
    return tokenBalance.balance;
}

async function updateHTML(value) {
   document.getElementById("budsBalanceNum").innerHTML = value/10**9;
}

userBudsBalance().then((balance) => {
   updateHTML(balance);
})

I tried going to the browser to open up the console where the html/js file are on the VS code live server and I typed in these values:

  • userBudsBalance - which returned the async function
  • value - as soon I click enter, it turns into valueOf
  • balance - this comes back as undefined

so now I’m not sure which of these values I can use to add to the equation to get the user’s reward amount