How to Calculate the Numbers Pulled from Blockchain by Moralis?

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

thanks lol I’ve been using the html to fill in ā€œBuy Some Budsā€ if the function calls back they have zero balance. Your method works way better

Hey @derekryansnzy

How is it going? :man_factory_worker:

Sorry for the late response! I fell asleep last night lol and spent most of today figuring out stuff for my BSC project. I am back to the javascript codes now. I will report back shortly with results. Really appreciate you checking in on me :sob:

1 Like

Hey Yomoo, I am still super stuck lol. I got most of the codes to work, but really, they’re just the codes you guys have helped me out with. I did do a quick crash course on javascript, async and await and I have a much better understanding of it now. Take a look at the codes below:

login = async () => {
    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";
}

userBudsBalance = async () => {
    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;
    }
}

// after userBudsBalance is called
// this is the section that returns the balance
userBudsBalance().then((balance) => {
    updateHTML(balance);
    console.log(balance);
})
// I need the balance from this function 
// to calculate the amount of rewards
// an user is eligible for

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

totalRewards = async () => {
    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)
    console.log(options);
}

x = totalRewards()
x.then(function (value) {
    document.getElementById("budsRewardPool").innerHTML = x.budsAccumulationFromRewardsFee / 10 ** 9;
    document.getElementById("rewardsCycle").innerHTML = x.theCurrentRewardsCycle;
    document.getElementById("sumOfHolders").innerHTML = x.sumOfAllHOLDRBalances / 10 ** 9;
    document.getElementById("budsDividendsPool").innerHTML = x.sumOfAllHOLDRBalances / 10 ** 9;
})

// so I thought maybe I'd do another function
// to calculate claimableRewards:
claimableRewards = async () => {
    const userEligibility = await userBudsBalance();
    console.log(userEligibility);
    // I'm not sure how to call balance from userBudsBalance.then(balance)

};

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


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

I left some comments in the code, but I’ll explain here as well, just in case it’s still unclear.
I am trying to get the balance from userBudsBalance to put into another equation.
The equation would be to find out claimableRewards.
The equation is:
(balance * x.budsAccumulationFromRewardsFee) / sumOfAllHOLDRSBalances

Hope this makes sense!

Hey Yoomoo, I left an update here about 4 days ago, I was wondering if you had time to take a look at the more cleaned up codes for me? Still stuck on that one calculation bit lol