Last active
May 22, 2021 11:39
-
-
Save bhavya2611/020e485d2fe3e8fc44632afe6d5c2a74 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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