How to Calculate the Numbers Pulled from Blockchain by Moralis?

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

given this equation, what is the problem that you have? what it doesnā€™t work? do you have the right data in the variables? the result is not the expected one? the formatting of the result is not the e expected one?

In the codes itself I left some comments because I think it doesnā€™t quite make sense if I asked the question without showing the codes.

Thereā€™s an async function userBudsBalance that uses Moralis to find the balance of the token. After that, userBudsBalance().then((balance) => {} shows the value of the balance.

Further down in the code, after using another function totalRewards to get the other information I need for the equation, I created another async function called claimableRewards. I need to figure out how to call the (balance) from userBudsBalance in order to use it for the equation (balance * x.budsAccumulationFromRewardsFee) / sumOfAllHOLDRSBalances

Does this make sense?

I just looked at random lines, here donā€™t you want to log BudsRewards instead of Rewards.
Donā€™t you also want to return something from this function?

You should be able to call userBudsBalance like this: n = await userBudsBalance()

Actually right now I just ran into a different problemā€¦all of the codes stopped working and I havenā€™t change anything for the last few days because I was waiting on a response from this thread.

Right now console shows this error:
moralis.js:6325 Uncaught (in promise) Error: Web3Api not initialized, run Moralis.start() first

but I have web3 enabledā€¦am I missing something?

regarding your question about logging BudsRewards, I just did log Rewards because I was checking to make sure the numbers came back. Youā€™re the person that helped me write the rewards codes here:

yes, something changed from yesterday, now you have to use a different syntax:
instead of:

         Moralis.initialize("asgasdasdfasdf");
         Moralis.serverURL = "https://afasdfasdf:2053/server";

Now you can write:

        serverUrl = "https://asdfadf:2053/server"
        appId =  "asdfasgasdgasg" 
        Moralis.start({ serverUrl, appId});

Thanks. I thought I broke something lol. Did anything else change? Because the totalRewards stopped working too. And I got this cool response from console:

Uncaught (in promise) Error: Returned values arenā€™t valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

You may get that error because your MetaMask is not connected to Binance chain.

haha! sorry for that silly mistake, I usually never connect to other chains. I was testing NFTs yesterday and forgot to switch back. weā€™re back in business! now back to what I was asking about earlier.

you suggested that I can use n = await userBudsBalance(), which was what I did in my codes:

claimableRewards = async () => {
    const userEligibility = await userBudsBalance();
    console.log(userEligibility);
};

but the log doesnā€™t show anythingā€¦

To get this equation (balance * x.budsAccumulationFromRewardsFee) / sumOfAllHOLDRSBalances

I need the (balance) from this section:

userBudsBalance = async () => {
    const web3 = await Moralis.enable();
    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;
    }
}

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

and x.budsAccumulationFromRewardsFee and sumOfAllHOLDRSBalances
from this section:

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;
})

Individually, they work fine. But now I am using a function to call the values from these two other functions and I just canā€™t get them to work

you can also set the address there in case that you current selected address from metamask doesnā€™t have tokens

ah okay Iā€™ll play around with that after I get the calculation problem solved. Right now Iā€™m kinda baffled because the claimRewards functions stopped working a few days ago too and I canā€™t figure it out either lol. My codes are exactly the same as they were when they were working. But anyway, right now the focus is the calculation problem. Iā€™m sure the claimRewards function is something I accidentally changed and didnā€™t even know it.