Skip to content

Instantly share code, notes, and snippets.

@bhavya2611
Last active May 22, 2021 11:39
Show Gist options
  • Save bhavya2611/020e485d2fe3e8fc44632afe6d5c2a74 to your computer and use it in GitHub Desktop.
Save bhavya2611/020e485d2fe3e8fc44632afe6d5c2a74 to your computer and use it in GitHub Desktop.
const calculateAPY = async () => {
try {
//BLOCKS_PER_DAY varies acccording to network all values are approx and they keep changing
//BLOCKS_PER_DAY = 21600 for Kovan Testnet
//BLOCKS_PER_DAY = 28800 for BSC Testnet
//BLOCKS_PER_DAY = 6400 for Ethereum Mainnet
//I am using the value for Ethereum mainnet
const BLOCKS_PER_YEAR = 6400 * 365;
let rewardTokenPrice = 0;
// For Price IN ETH
// Reward Token is Dodgecoin in our case
rewardTokenPrice = await getDogecoinPriceInETH();
// For Price in BNB
// If you want to do calculations in BNB uncomment line below and comment line number 13
// rewardTokenPrice = await getDodgecoinPriceInBNB()
// REWARD_PER_BLOCK = Number of tokens your farming contract gives out per block
const REWARD_PER_BLOCK = 10000000000;
const totalRewardPricePerYear = new BigNumber(rewardTokenPrice)
.times(REWARD_PER_BLOCK)
.times(BLOCKS_PER_YEAR);
// Get Total LP Tokens Deposited in Farming Contract
const LpTokenContract = new web3.eth.Contract(
IUniswapV2Pair,
LP_TOKEN_ADDRESS
);
const totalLpDepositedInFarmingContract = await LpTokenContract.methods
.balanceOf(FARMING_CONTRACT_ADDRESS)
.call();
// Calculate LP Token Price
const lpTokenPrice = await calculateLpTokenPrice();
// Calculate Total Price Of LP Tokens in Contract
const totalPriceOfLpTokensInFarmingContract = new BigNumber(
lpTokenPrice
).times(totalLpDepositedInFarmingContract);
// Calculate APY
const apy = totalRewardPricePerYear
.div(totalPriceOfLpTokensInFarmingContract)
.times(100);
// Return apy if apy is a valid number or return 0
return apy.isNaN() || !apy.isFinite() ? 0 : apy.toNumber();
} catch (e) {
console.log(e);
return 0;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment