From 6bb94253ff70e39e849fbe8afdcfa2af8576b257 Mon Sep 17 00:00:00 2001 From: Godswill Adigwe Date: Thu, 30 Mar 2023 10:30:00 +0100 Subject: [PATCH 1/2] init --- package.json | 1 + src/pages/FarmingV2/ShowYieldFarmDetails.tsx | 417 ++-- src/pages/FarmingV2/YieldFarm.tsx | 98 +- src/pages/FarmingV2/index.tsx | 1899 ++---------------- src/state/farm/actions.ts | 53 +- src/state/farm/reducer.ts | 95 +- src/state/farm/types.ts | 589 +++--- src/state/index.ts | 6 +- src/utils/hooks/useFarm.ts | 1621 +++++++++++++++ src/utils/hooks/useGetFarmData.ts | 22 +- yarn.lock | 13 + 11 files changed, 2456 insertions(+), 2358 deletions(-) create mode 100644 src/utils/hooks/useFarm.ts diff --git a/package.json b/package.json index d5e00d7f..19556ede 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "@ethersproject/abi": "^5.5.0", "@ethersproject/address": "^5.5.0", "@ethersproject/providers": "^5.4.5", + "@indexed-finance/multicall": "^2.0.0", "@metamask/detect-provider": "^1.2.0", "@reduxjs/toolkit": "^1.6.1", "@rigelprotocol_01/default-token-list": "2.0.1", diff --git a/src/pages/FarmingV2/ShowYieldFarmDetails.tsx b/src/pages/FarmingV2/ShowYieldFarmDetails.tsx index ce865f25..ddf02bc7 100644 --- a/src/pages/FarmingV2/ShowYieldFarmDetails.tsx +++ b/src/pages/FarmingV2/ShowYieldFarmDetails.tsx @@ -1,5 +1,5 @@ -import React, {useEffect, useState} from "react"; -import {ethers} from "ethers"; +import React, { useEffect, useState } from "react"; +import { ethers } from "ethers"; import Web3 from "web3"; import { Box, @@ -25,15 +25,15 @@ import { useDisclosure, useMediaQuery, } from "@chakra-ui/react"; -import {QuestionOutlineIcon} from "@chakra-ui/icons"; -import {SupportedChainId} from "../../constants/chains"; +import { QuestionOutlineIcon } from "@chakra-ui/icons"; +import { SupportedChainId } from "../../constants/chains"; import Switch from "react-switch"; -import {DARK_THEME, farmSection} from "./index"; -import {addToast} from "../../components/Toast/toastSlice"; -import {useDispatch, useSelector} from "react-redux"; -import {setOpenModal, TrxState} from "../../state/application/reducer"; +import { DARK_THEME, farmSection } from "./index"; +import { addToast } from "../../components/Toast/toastSlice"; +import { useDispatch, useSelector } from "react-redux"; +import { setOpenModal, TrxState } from "../../state/application/reducer"; import { setLoadingState } from "../../state/farm/actions"; -import {ExplorerDataType, getExplorerLink} from "../../utils/getExplorerLink"; +import { ExplorerDataType, getExplorerLink } from "../../utils/getExplorerLink"; import { MasterChefV2Contract, RGPSpecialPool, @@ -49,32 +49,38 @@ import { RGPSPECIALPOOLADDRESSES2, SMARTSWAPLP_TOKEN1ADDRESSES, } from "../../utils/addresses"; -import {clearInputInfo, convertFromWei, convertToNumber} from "../../utils"; -import {useRGPBalance} from "../../utils/hooks/useBalances"; -import {updateFarmAllowances} from "../../state/farm/actions"; -import {useActiveWeb3React} from "../../utils/hooks/useActiveWeb3React"; +import { clearInputInfo, convertFromWei, convertToNumber } from "../../utils"; +import { useRGPBalance } from "../../utils/hooks/useBalances"; +import { updateFarmAllowances } from "../../state/farm/actions"; +import { useActiveWeb3React } from "../../utils/hooks/useActiveWeb3React"; import Joyride from "react-joyride"; -import {steps} from "../../components/Onboarding/YieldSteps"; -import {Contract} from "@ethersproject/contracts"; -import {calculateGas} from "../Swap/components/sendToken"; -import {useUserGasPricePercentage} from "../../state/gas/hooks"; +import { steps } from "../../components/Onboarding/YieldSteps"; +import { Contract } from "@ethersproject/contracts"; +import { calculateGas } from "../Swap/components/sendToken"; +import { useUserGasPricePercentage } from "../../state/gas/hooks"; -import {useFetchYieldFarmDetails, useUpdateFarm} from "../../state/newfarm/hooks"; -import {useNewYieldFarmDetails, useUpdateNewFarm} from "../../state/LPFarm/hooks"; +import { + useFetchYieldFarmDetails, + useUpdateFarm, +} from "../../state/newfarm/hooks"; +import { + useNewYieldFarmDetails, + useUpdateNewFarm, +} from "../../state/LPFarm/hooks"; import { GButtonClicked, GButtonIntialized, GFarmingFailedTransaction, GFarmingSpecialPoolReferral, - GFarmingSuccessTransaction + GFarmingSuccessTransaction, } from "../../components/G-analytics/gFarming"; -import {ZERO_ADDRESS} from "../../constants"; +import { ZERO_ADDRESS } from "../../constants"; const ShowYieldFarmDetails = ({ content, wallet, URLReferrerAddress, - refreshSpecialData, + refreshSpecialData, LoadingState, section, showYieldfarm, @@ -93,11 +99,11 @@ const ShowYieldFarmDetails = ({ poolAllowance: any; RGPEarned: string; poolVersion: number | string; - type?:string; + type?: string; }; wallet: any; - URLReferrerAddress:string; - refreshSpecialData:()=>void; + URLReferrerAddress: string; + refreshSpecialData: () => void; LoadingState: boolean; section: string; showYieldfarm: boolean; @@ -141,23 +147,20 @@ const ShowYieldFarmDetails = ({ const signer = library?.getSigner(); const [reload, setReload] = useState(false); const [contentid, setContentId] = useState(undefined); - const [loading, setLoading] = useState(true); + const [loading, setLoading] = useState(false); // const data = useGetFarmData(reload, setReload); + const { loadingState } = useUpdateFarm({ reload, setReload, content }); - const {loadingState} = useUpdateFarm({reload, setReload, content}); - - useFetchYieldFarmDetails({content, section, setLoading, loading}); + useFetchYieldFarmDetails({ content, section, setLoading, loading }); //const {loadingFarm} = useUpdateNewFarm({reload, setReload, content}); - // useNewYieldFarmDetails({content, section, setLoading, loading}); - - + // useNewYieldFarmDetails({content, section, setLoading, loading}); const closeModal = () => { - GButtonIntialized("close unstaked",content.deposit,"v2") + GButtonIntialized("close unstaked", content.deposit, "v2"); modal2Disclosure.onClose(); }; // useUpdate(reload, setReload, contentid, setContentId); @@ -177,22 +180,23 @@ const ShowYieldFarmDetails = ({ setIsReferrerCheck(false); } }; -useEffect(()=>{ - const checkEnoughApproval = (allowance: any, balance: any) => { - // console.log("checkEnoughApproval",allowance.toString(),balance); - if (allowance && balance) { - - let approve = parseFloat(allowance) >= parseFloat(depositTokenValue); - // let approve = content.type === "RGP" - // ? allowance.gte(ethers.utils.parseEther(balance)) - // : parseFloat(allowance) >= parseFloat(depositTokenValue); - console.log(parseFloat(allowance), parseFloat(depositTokenValue),{approve}) - approve ? setEnoughApproval(true) : setEnoughApproval(false) - } - return true; - }; - checkEnoughApproval(content.poolAllowance,content.availableToken) -},[depositTokenValue]) + useEffect(() => { + const checkEnoughApproval = (allowance: any, balance: any) => { + // console.log("checkEnoughApproval",allowance.toString(),balance); + if (allowance && balance) { + let approve = parseFloat(allowance) >= parseFloat(depositTokenValue); + // let approve = content.type === "RGP" + // ? allowance.gte(ethers.utils.parseEther(balance)) + // : parseFloat(allowance) >= parseFloat(depositTokenValue); + console.log(parseFloat(allowance), parseFloat(depositTokenValue), { + approve, + }); + approve ? setEnoughApproval(true) : setEnoughApproval(false); + } + return true; + }; + checkEnoughApproval(content.poolAllowance, content.availableToken); + }, [depositTokenValue]); useEffect(() => { const poolAllowance = async (contract: Contract) => { if (account) { @@ -224,7 +228,7 @@ useEffect(()=>{ account, RGPSPECIALPOOLADDRESSES2[chainId as number] ); - console.log({rgpApproval}) + console.log({ rgpApproval }); return !(rgpApproval.toString() <= 0); } }; @@ -236,14 +240,13 @@ useEffect(()=>{ const specialPoolV1Approval = await specialPoolV1Allowance(rgp); changeApprovalButton(true, specialPoolV1Approval); } else if (content.deposit === "RGP" && Number(content.id) === 13) { - const specialPoolV2Approval = await specialPoolV2Allowance(rgp); changeApprovalButton(true, specialPoolV2Approval); } else { const pool = await smartSwapLPTokenPoolTwo(content.address, library); const approvalForRGPBNB = await poolAllowance(pool); - console.log({approvalForRGPBNB,rgpApproval}) + console.log({ approvalForRGPBNB, rgpApproval }); changeApprovalButton(approvalForRGPBNB, rgpApproval); } }; @@ -281,7 +284,7 @@ useEffect(()=>{ }) ); const rgp = await rigelToken(RGP[chainId as number], library); - const walletBal = (await rgp.balanceOf(account)) ; + const walletBal = await rgp.balanceOf(account); const data = await rgp.approve( RGPSPECIALPOOLADDRESSES[chainId as number], walletBal, @@ -295,7 +298,7 @@ useEffect(()=>{ const { confirmations, status } = await fetchTransactionData(data); if (confirmations >= 3) { setApproveValueForRGP(true); - GFarmingSuccessTransaction("special pool", "approval", "RGP","v1") + GFarmingSuccessTransaction("special pool", "approval", "RGP", "v1"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -304,9 +307,15 @@ useEffect(()=>{ ); } getAllowances(); - } catch (error:any) { + } catch (error: any) { console.error(error); - GFarmingFailedTransaction("special pool", "approval", error.message, "RGP","v1") + GFarmingFailedTransaction( + "special pool", + "approval", + error.message, + "RGP", + "v1" + ); dispatch( setOpenModal({ message: `Transaction failed`, @@ -327,9 +336,9 @@ useEffect(()=>{ trxState: TrxState.WaitingForConfirmation, }) ); - + const rgp = await rigelToken(RGP[chainId as number], library); - const walletBal = (await rgp.balanceOf(account)) ; + const walletBal = await rgp.balanceOf(account); const data = await rgp.approve( RGPSPECIALPOOLADDRESSES2[chainId as number], walletBal, @@ -343,7 +352,7 @@ useEffect(()=>{ const { confirmations, status } = await fetchTransactionData(data); if (confirmations >= 3) { setApproveValueForRGP(true); - GFarmingSuccessTransaction("special pool", "approval", "RGP","v2") + GFarmingSuccessTransaction("special pool", "approval", "RGP", "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -352,9 +361,15 @@ useEffect(()=>{ ); } getAllowances(); - } catch (error:any) { + } catch (error: any) { console.error(error); - GFarmingFailedTransaction("special pool", "approval", error.message, "RGP","v2") + GFarmingFailedTransaction( + "special pool", + "approval", + error.message, + "RGP", + "v2" + ); dispatch( setOpenModal({ message: `Transaction failed`, @@ -367,17 +382,17 @@ useEffect(()=>{ }; const setApprove = (val: string) => { - console.log({approveValueForOtherToken,approveValueForRGP}) + console.log({ approveValueForOtherToken, approveValueForRGP }); if (approveValueForOtherToken && approveValueForRGP) { - GButtonClicked("unstake",content.deposit,"v2") + GButtonClicked("unstake", content.deposit, "v2"); modal2Disclosure.onOpen(); } else { - GButtonClicked("approval",content.deposit,"v2") + GButtonClicked("approval", content.deposit, "v2"); checkUser(val); } }; - const checkUser = async (val :string) => { + const checkUser = async (val: string) => { if (content.deposit === "RGP" && Number(content.id) === 1) { await RGPSpecialPoolV1Approval(); setApproveValueForOtherToken(true); @@ -390,11 +405,11 @@ useEffect(()=>{ const pool = await smartSwapLPTokenPoolTwo(content.address, library); if (!approveValueForOtherToken && !approveValueForRGP) { await RGPApproval(); - await LPApproval(pool,content.deposit); + await LPApproval(pool, content.deposit); } else if (!approveValueForRGP) { await RGPApproval(); } else { - await LPApproval(pool,content.deposit); + await LPApproval(pool, content.deposit); } setApproveValueForOtherToken(true); setApproveValueForRGP(true); @@ -402,14 +417,14 @@ useEffect(()=>{ }; const openDepositeModal = () => { - GButtonClicked("stake",content.deposit,"v2") + GButtonClicked("stake", content.deposit, "v2"); //if (approveValueForOtherToken && approveValueForRGP) { modal1Disclosure.onOpen(); // } }; const closeDepositeModal = () => { - GButtonClicked("close staked modal",content.deposit,"v2") + GButtonClicked("close staked modal", content.deposit, "v2"); modal1Disclosure.onClose(); }; @@ -443,10 +458,7 @@ useEffect(()=>{ const getAllowances = async () => { if (account) { try { - const [ - rigel, - pool1, - ] = await Promise.all([ + const [rigel, pool1] = await Promise.all([ rigelToken(RGP[chainId as number], library), smartSwapLPTokenPoolOne( SMARTSWAPLP_TOKEN1ADDRESSES[chainId as number], @@ -454,11 +466,7 @@ useEffect(()=>{ ), ]); - const [ - pool1Allowance, - ] = await Promise.all([ - allowance(pool1), - ]); + const [pool1Allowance] = await Promise.all([allowance(pool1)]); let rigelAllowance; let rigelAllowance2; if (RGPSPECIALPOOLADDRESSES[chainId as number]) { @@ -469,7 +477,7 @@ useEffect(()=>{ } else { rigelAllowance = pool1Allowance; } - + if (RGPSPECIALPOOLADDRESSES2[chainId as number]) { rigelAllowance2 = await rigel.allowance( account, @@ -477,19 +485,10 @@ useEffect(()=>{ ); } - if (Number(chainId) === Number(SupportedChainId.BINANCE)) { - dispatch( - updateFarmAllowances([ - rigelAllowance2 - ]) - ); + dispatch(updateFarmAllowances([rigelAllowance2])); } else { - dispatch( - updateFarmAllowances([ - rigelAllowance2 - ]) - ); + dispatch(updateFarmAllowances([rigelAllowance2])); } } catch (error) { console.error(error, "something went wrong"); @@ -595,7 +594,7 @@ useEffect(()=>{ const showMaxValue = async (deposit: any, input: any) => { try { if (input === "deposit") { - GButtonClicked(`max_button for ${input}`,content.deposit,"v2") + GButtonClicked(`max_button for ${input}`, content.deposit, "v2"); setDepositTokenValue(content.availableToken); } else if (input === "unstake") { setUnstakeToken( @@ -610,12 +609,11 @@ useEffect(()=>{ ); } }; - async function confirmUnstakeDeposit(val: string) { try { setUnstakeButtonValue("Pending Confirmation"); - GButtonIntialized("unstake",content.deposit,"v2") + GButtonIntialized("unstake", content.deposit, "v2"); dispatch( setOpenModal({ message: `Unstaking ${unstakeToken} ${val}`, @@ -629,7 +627,7 @@ useEffect(()=>{ } else if (val === "RGP" && Number(content.id) === 13) { await RGPUnstakeV2(val); } else { - tokensWithdrawal(content.id,val); + tokensWithdrawal(content.id, val); } } } catch (err) { @@ -653,7 +651,7 @@ useEffect(()=>{ }; // withdrawal for the Liquidity Provider tokens for all pools - const tokensWithdrawal = async (pid: number,val:string) => { + const tokensWithdrawal = async (pid: number, val: string) => { if (account) { try { const lpTokens = await MasterChefV2Contract( @@ -700,7 +698,7 @@ useEffect(()=>{ hash, ExplorerDataType.TRANSACTION ); - GFarmingSuccessTransaction("farming", "unstake", val,"v2") + GFarmingSuccessTransaction("farming", "unstake", val, "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -721,9 +719,9 @@ useEffect(()=>{ setReload(true); // dispatch the getTokenStaked action from here when data changes //callRefreshFarm(confirmations, status); - } catch (e:any) { + } catch (e: any) { console.log(e); - GFarmingFailedTransaction("farming", "unstake", e.message, val,"v2") + GFarmingFailedTransaction("farming", "unstake", e.message, val, "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionFailed, @@ -736,8 +734,8 @@ useEffect(()=>{ const harvestTokens = async (id: string | number) => { if (account) { try { - GButtonClicked("harvest",content.deposit,"v2") - GButtonIntialized("harvest",content.deposit,"v2") + GButtonClicked("harvest", content.deposit, "v2"); + GButtonIntialized("harvest", content.deposit, "v2"); dispatch( setOpenModal({ message: `Harvesting RGP ${content.RGPEarned} Tokens`, @@ -779,7 +777,7 @@ useEffect(()=>{ const amountOfRgbSpecial = convertToNumber(logs[1].data); if (confirmations >= 1 && status) { - GFarmingSuccessTransaction("special pool", "harvest", "RGP","v1") + GFarmingSuccessTransaction("special pool", "harvest", "RGP", "v1"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -824,8 +822,8 @@ useEffect(()=>{ const amountOfRgbSpecial = convertToNumber(logs[1].data); if (confirmations >= 1 && status) { - GFarmingSuccessTransaction("special pool", "harvest", "RGP","v2") - refreshSpecialData() + GFarmingSuccessTransaction("special pool", "harvest", "RGP", "v2"); + refreshSpecialData(); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -834,7 +832,6 @@ useEffect(()=>{ )} RGP `, }) ); - } } else { const lpTokens = await MasterChefV2Contract( @@ -871,7 +868,7 @@ useEffect(()=>{ const { hash } = withdraw; if (confirmations >= 1 && status) { - GFarmingSuccessTransaction("farming", "harvest", "RGP","v2") + GFarmingSuccessTransaction("farming", "harvest", "RGP", "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -880,7 +877,7 @@ useEffect(()=>{ )} RGP `, }) ); - refreshSpecialData() + refreshSpecialData(); } const explorerLink = getExplorerLink( @@ -898,26 +895,30 @@ useEffect(()=>{ ); setReload(true); } - } catch (error:any) { - GFarmingFailedTransaction( "special pool","harvest", error.message, "RGP","v2") + } catch (error: any) { + GFarmingFailedTransaction( + "special pool", + "harvest", + error.message, + "RGP", + "v2" + ); dispatch( setOpenModal({ trxState: TrxState.TransactionFailed, message: `Transaction was not successful`, }) ); - } } }; // deposit for the Liquidity Provider tokens for all pools - const LPDeposit = async (pid: any,val:string) => { + const LPDeposit = async (pid: any, val: string) => { if (account) { try { if (parseFloat(content.tokenStaked[1]) == 0) { if (parseFloat(RGPBalance) < parseFloat(farmingFee)) { - dispatch( setOpenModal({ trxState: TrxState.TransactionFailed, @@ -961,7 +962,7 @@ useEffect(()=>{ const { confirmations, status, logs } = await fetchTransactionData( data ); - GFarmingSuccessTransaction("farming", "stake", val,"v2") + GFarmingSuccessTransaction("farming", "stake", val, "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -1016,14 +1017,14 @@ useEffect(()=>{ message: `Successfully deposited`, }) ); - GFarmingSuccessTransaction("farming", "stake", val,"v2") + GFarmingSuccessTransaction("farming", "stake", val, "v2"); setDeposited(true); setReload(true); setContentId(content.deposit === "RGP" ? undefined : content.id); // callRefreshFarm(confirmations, status); } } catch (error: any) { - GFarmingFailedTransaction("farming", "stake", error.message, val,"v2") + GFarmingFailedTransaction("farming", "stake", error.message, val, "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionFailed, @@ -1035,7 +1036,7 @@ useEffect(()=>{ const confirmDeposit = async (val: any) => { setDepositValue("Pending Confirmation"); - GButtonIntialized("deposit",content.deposit,"v2") + GButtonIntialized("deposit", content.deposit, "v2"); dispatch( setOpenModal({ message: `Staking ${depositTokenValue} ${val}`, @@ -1049,12 +1050,12 @@ useEffect(()=>{ } else if (val === "RGP" && Number(content.id) === 13) { await RGPuseStakeV2(); } else { - LPDeposit(content.id,val); + LPDeposit(content.id, val); } } - } catch (error:any) { + } catch (error: any) { console.log(error); - GFarmingFailedTransaction("farming", "stake", error.message, val,"v2") + GFarmingFailedTransaction("farming", "stake", error.message, val, "v2"); dispatch( setOpenModal({ message: `Failed to deposit LP tokens.`, @@ -1068,8 +1069,6 @@ useEffect(()=>{ clearInputInfo(setDepositTokenValue, setDepositValue, "Confirm"); }; - - const RGPuseStake = async () => { if (account) { try { @@ -1107,7 +1106,7 @@ useEffect(()=>{ } ); const { confirmations, status } = await fetchTransactionData(data); - GFarmingSuccessTransaction("special pool", "staking", "RGP","v1") + GFarmingSuccessTransaction("special pool", "staking", "RGP", "v1"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -1115,9 +1114,15 @@ useEffect(()=>{ }) ); // callRefreshFarm(confirmations, status); - } catch (error:any) { + } catch (error: any) { console.log(error); - GFarmingFailedTransaction("special pool", "stake", error.message, "RGP","v1") + GFarmingFailedTransaction( + "special pool", + "stake", + error.message, + "RGP", + "v1" + ); dispatch( setOpenModal({ message: `Transaction failed`, @@ -1134,7 +1139,9 @@ useEffect(()=>{ RGPSPECIALPOOLADDRESSES2[chainId as number], library ); - GFarmingSpecialPoolReferral(referrerAddress===ZERO_ADDRESS ? false:true) + GFarmingSpecialPoolReferral( + referrerAddress === ZERO_ADDRESS ? false : true + ); const data = await specialPool.stake( ethers.utils.parseEther(depositTokenValue.toString()), referrerAddress, @@ -1145,10 +1152,10 @@ useEffect(()=>{ } ); await fetchTransactionData(data); - GFarmingSuccessTransaction("special pool", "stake", "RGP","v2") //122 - - refreshSpecialData() - + GFarmingSuccessTransaction("special pool", "stake", "RGP", "v2"); //122 + + refreshSpecialData(); + dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -1156,15 +1163,20 @@ useEffect(()=>{ }) ); // callRefreshFarm(confirmations, status); - setReload(true); - } catch (error:any) { + setReload(true); + } catch (error: any) { console.log(error); - GFarmingFailedTransaction("special pool", "stake", error.message, "RGP","v2") + GFarmingFailedTransaction( + "special pool", + "stake", + error.message, + "RGP", + "v2" + ); dispatch( setOpenModal({ message: `Transaction failed`, trxState: TrxState.TransactionFailed, - }) ); } @@ -1207,19 +1219,25 @@ useEffect(()=>{ } ); const { confirmations, status } = await fetchTransactionData(data); - GFarmingSuccessTransaction("special pool", "unstake", "RGP","v1") + GFarmingSuccessTransaction("special pool", "unstake", "RGP", "v1"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, message: `Successfully unstaked ${unstakeToken} RGP `, }) ); - refreshSpecialData() + refreshSpecialData(); // dispatch the getTokenStaked action from here when data changes // callRefreshFarm(confirmations, status); - } catch (e:any) { + } catch (e: any) { console.log(e); - GFarmingFailedTransaction("special pool", "unstake", e.message, "RGP","v1") + GFarmingFailedTransaction( + "special pool", + "unstake", + e.message, + "RGP", + "v1" + ); dispatch( setOpenModal({ trxState: TrxState.TransactionFailed, @@ -1230,7 +1248,7 @@ useEffect(()=>{ } }; - const RGPUnstakeV2 = async (val:string) => { + const RGPUnstakeV2 = async (val: string) => { if (account) { try { const specialPool = await RGPSpecialPool2( @@ -1265,19 +1283,25 @@ useEffect(()=>{ } ); const { confirmations, status } = await fetchTransactionData(data); - GFarmingSuccessTransaction("special pool", "unstake", "RGP","v2") + GFarmingSuccessTransaction("special pool", "unstake", "RGP", "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, message: `Successfully unstaked ${unstakeToken} RGP `, }) ); - - refreshSpecialData() + + refreshSpecialData(); // dispatch the getTokenStaked action from here when data changes // callRefreshFarm(confirmations, status); - } catch (error:any) { - GFarmingFailedTransaction("special pool", "unstake", error.message, "RGP","v2") + } catch (error: any) { + GFarmingFailedTransaction( + "special pool", + "unstake", + error.message, + "RGP", + "v2" + ); dispatch( setOpenModal({ trxState: TrxState.TransactionFailed, @@ -1288,7 +1312,7 @@ useEffect(()=>{ } }; - const LPApproval = async (contract: any,deposit:string) => { + const LPApproval = async (contract: any, deposit: string) => { if (account) { try { dispatch( @@ -1297,7 +1321,7 @@ useEffect(()=>{ trxState: TrxState.WaitingForConfirmation, }) ); - const walletBal = (await contract.balanceOf(account)) ; + const walletBal = await contract.balanceOf(account); const data = await contract.approve( MASTERCHEFV2ADDRESSES[chainId as number], walletBal, @@ -1309,7 +1333,7 @@ useEffect(()=>{ ); setApprovalLoading(true); const { confirmations, status } = await fetchTransactionData(data); - GFarmingSuccessTransaction("farming", "approval", deposit,"v2") + GFarmingSuccessTransaction("farming", "approval", deposit, "v2"); if (status) { setApproveValueForOtherToken(true); dispatch( @@ -1321,10 +1345,16 @@ useEffect(()=>{ } getAllowances(); setReload(true); - } catch (e:any) { + } catch (e: any) { // props.showErrorMessage(e); // console.log(e:any); - GFarmingFailedTransaction("farming", "approval", e.message, deposit ,"v2") + GFarmingFailedTransaction( + "farming", + "approval", + e.message, + deposit, + "v2" + ); dispatch( setOpenModal({ message: `Transaction failed`, @@ -1341,7 +1371,7 @@ useEffect(()=>{ switch (content?.type) { case "LP": const poolOne = await smartSwapLPTokenPoolOne(content.address, library); - LPApproval(poolOne,content.deposit); + LPApproval(poolOne, content.deposit); break; default: @@ -1350,7 +1380,6 @@ useEffect(()=>{ } }; - const RGPApproval = async () => { if (account) { try { @@ -1361,7 +1390,7 @@ useEffect(()=>{ }) ); const rgp = await rigelToken(RGP[chainId as number], library); - const walletBal = (await rgp.balanceOf(account)) ; + const walletBal = await rgp.balanceOf(account); const data = await rgp.approve( MASTERCHEFV2ADDRESSES[chainId as number], walletBal, @@ -1375,7 +1404,7 @@ useEffect(()=>{ const { confirmations, status } = await fetchTransactionData(data); if (confirmations >= 3) { setApproveValueForRGP(true); - GFarmingSuccessTransaction("farming", "approval", "RGP","v2") + GFarmingSuccessTransaction("farming", "approval", "RGP", "v2"); dispatch( setOpenModal({ trxState: TrxState.TransactionSuccessful, @@ -1385,9 +1414,15 @@ useEffect(()=>{ } getAllowances(); setReload(true); - } catch (error:any) { + } catch (error: any) { console.error(error); - GFarmingFailedTransaction("farming", "approval", error.message ,"RGP","v2") + GFarmingFailedTransaction( + "farming", + "approval", + error.message, + "RGP", + "v2" + ); dispatch( setOpenModal({ message: `Transaction failed`, @@ -1429,8 +1464,9 @@ useEffect(()=>{ fontSize='16px' _hover={{ background: "rgba(64, 186, 213, 0.15)" }} onClick={() => { - GButtonIntialized("approval",content.deposit,"v2") - approveLPToken(LPToken)}} + GButtonIntialized("approval", content.deposit, "v2"); + approveLPToken(LPToken); + }} > {approvalLoading ? "Approving..." : "Approve"} {LPToken} @@ -1471,7 +1507,7 @@ useEffect(()=>{ ) : ( - + { padding='10px 40px' cursor='pointer' onClick={() => { - setApprove(content.deposit)}} + setApprove(content.deposit); + }} className={ approveValueForRGP && approveValueForOtherToken ? "unstake" @@ -1748,7 +1785,7 @@ useEffect(()=>{ justifyContent='space-around' > - @@ -1781,7 +1818,7 @@ useEffect(()=>{ > {content.deposit} Tokens Staked - + ) : !depositTokenValue ? ( - + ) : ( approvalButton(content.deposit) )} @@ -2349,22 +2386,22 @@ useEffect(()=>{ > {depositValue} - ) : !depositTokenValue ? ( - + ) : !depositTokenValue ? ( + ) : ( approvalButton(content.deposit) )} diff --git a/src/pages/FarmingV2/YieldFarm.tsx b/src/pages/FarmingV2/YieldFarm.tsx index e3c48f28..6113af72 100644 --- a/src/pages/FarmingV2/YieldFarm.tsx +++ b/src/pages/FarmingV2/YieldFarm.tsx @@ -87,6 +87,8 @@ const YieldFarm = ({ selectedField === farmSection.NEW_LP || selectedField === farmSection.SECOND_NEW_LP; + console.log("selected", selected); + // useEffect(() => { // const getSingleFarm = async () => { // await content2; @@ -102,7 +104,7 @@ const YieldFarm = ({ // }, [symbolName, params]); const totalLiquidityValue = () => { - if (farmDataLoading) return ; + if (farmDataLoading) return ; if (content.totalLiquidity) { return ` ${formatAmount(content.totalLiquidity)}`; @@ -115,9 +117,9 @@ const YieldFarm = ({ <> - + Deposit {content?.type === "RGP" ? content.deposit : content2?.deposit} @@ -189,62 +191,62 @@ const YieldFarm = ({ ) : null} - + Earn {/* */} - {" "} - + {" "} + {content?.type === "RGP" ? content.earn : content2?.earn} - + APY - + {content?.type === "RGP" ? `${formatAmount(content.ARYValue)}%` : `${formatAmount(content2?.APY.toFixed(2))}%`} Total Liquidity ${" "} {content?.type === "RGP" @@ -254,33 +256,33 @@ const YieldFarm = ({ {selected && ( LP Locked {content2?.LPLocked} )} - + */} - {/* */} - {/* */} - {/* */} - - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* Deposit*/} - {/* Earn*/} - {/* APY*/} - {/* Total Liquidity*/} - {/* */} - {/* */} - - {/* {loadingState ? (*/} - {/* */} - {/* {new Array(5).fill("1").map((item, index) => {*/} - {/* return (*/} - {/* */} - {/* */} - {/* {new Array(5).fill("1").map((item, index) => {*/} - {/* return (*/} - {/* */} - {/* */} - {/* */} - {/* );*/} - {/* })}*/} - {/* */} - {/* */} - {/* );*/} - {/* })}*/} - {/* */} - {/* ) : // */} - {/* keyword &&*/} - {/* searchResults.searchResult === undefined ? null : keyword &&*/} - {/* searchResults.searchResult !== undefined ? (*/} - {/* searchSection.newSearchResult === undefined ? (*/} - {/* searchResults.searchResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* ) : (*/} - {/* searchSection.newSearchResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* )*/} - {/* ) : searchResults.filterResult !== undefined ? (*/} - {/* searchSection.newFilterResult === undefined ? (*/} - {/* searchResults.filterResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* ) : (*/} - {/* searchSection.newFilterResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* )*/} - {/* ) : searchResults.filterResult === undefined ? (*/} - {/* farms === undefined ? (*/} - {/* data.contents?.map((content: any, index: number) => (*/} - {/* */} - {/* ))*/} - {/* ) : (*/} - {/* farms.map((content: any, index: number) => (*/} - {/* */} - {/* ))*/} - {/* )*/} - {/* ) : null}*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* //STAKING V2 PANEL*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* Deposit*/} - {/* Earn*/} - {/* APY*/} - {/* Total Liquidity*/} - {/* */} - {/* */} - {/* {specialPool?.map((content: any, index: number) => (*/} - {/* */} - {/* ))}*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* // PRODUCT FARM PANEL*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* {selected === farmSection.PRODUCT_FARM*/} - {/* ? "Auto-Period Product"*/} - {/* : "Deposit"}*/} - {/* */} - {/* */} - {/* {selected === farmSection.PRODUCT_FARM*/} - {/* ? "Percentage Profit Share"*/} - {/* : "Earn"}*/} - {/* */} - {/* */} - {/* {selected === farmSection.PRODUCT_FARM*/} - {/* ? "Profit Timeline"*/} - {/* : "APY"}*/} - {/* */} - {/* */} - {/* Total Liquidity*/} - {/* */} - {/* {selected === farmSection.PRODUCT_FARM && (*/} - {/* */} - {/* Estimated Total Profits*/} - {/* */} - {/* )}*/} - {/* */} - {/* */} - {/* {FarmData.productFarm.map((content: any, index: number) =>*/} - {/* index === 0 ? (*/} - {/* */} - {/* ) : null*/} - {/* )}*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* Deposit*/} - {/* Earn*/} - {/* APY*/} - {/* Total Liquidity*/} - {/* */} - {/* */} - {/* {FarmData.contents.map((content: any, index: number) =>*/} - {/* index === 0 ? (*/} - {/* */} - {/* ) : null*/} - {/* )}*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* /!* special *!/*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* Please Migrate your LP token farming from farming V1 to*/} - {/* this V2*/} - {/* */} - {/* */} - - {/* */} - {/* */} - {/* Go to farming V1*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* Deposit*/} - {/* Earn*/} - {/* APY*/} - {/* Total Liquidity*/} - {/* LP Locked*/} - {/* */} - {/* */} - - {/* {loadingLP ? (*/} - {/* */} - {/* {new Array(4).fill("1").map((item, index) => {*/} - {/* return (*/} - {/* */} - {/* */} - {/* {new Array(5).fill("1").map((item, index) => {*/} - {/* return (*/} - {/* */} - {/* */} - {/* */} - {/* );*/} - {/* })}*/} - {/* */} - {/* */} - {/* );*/} - {/* })}*/} - {/* */} - {/* ) : // */} - {/* keyword &&*/} - {/* searchResults.searchResult === undefined ? null : keyword &&*/} - {/* searchResults.searchResult !== undefined ? (*/} - {/* newSearchSection.newSearchResult === undefined ? (*/} - {/* searchResults.searchResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* ) : (*/} - {/* newSearchSection.newSearchResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* )*/} - {/* ) : searchResults.filterResult !== undefined ? (*/} - {/* newSearchSection.newFilterResult === undefined ? (*/} - {/* searchResults.filterResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* ) : (*/} - {/* newSearchSection.newFilterResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* )*/} - {/* ) : searchResults.filterResult === undefined ? (*/} - {/* recentFarms === undefined ? (*/} - {/* newLP.contents?.map((content: any, index: number) => (*/} - {/* */} - {/* ))*/} - {/* ) : (*/} - {/* recentFarms.map((content: any, index: number) => (*/} - {/* */} - {/* ))*/} - {/* )*/} - {/* ) : null}*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/* Deposit*/} - {/* Earn*/} - {/* APY*/} - {/* Total Liquidity*/} - {/* LP Locked*/} - {/* */} - {/* */} - - {/* {loadingLP ? (*/} - {/* */} - {/* {new Array(4).fill("1").map((item, index) => {*/} - {/* return (*/} - {/* */} - {/* */} - {/* {new Array(4).fill("1").map((item, index) => {*/} - {/* return (*/} - {/* */} - {/* */} - {/* */} - {/* );*/} - {/* })}*/} - {/* */} - {/* */} - {/* );*/} - {/* })}*/} - {/* */} - {/* ) : keyword &&*/} - {/* searchResults.searchResult === undefined ? null : keyword &&*/} - {/* searchResults.searchResult !== undefined ? (*/} - {/* newSearchSection.newSearchResult === undefined ? (*/} - {/* searchResults.searchResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* ) : (*/} - {/* newSearchSection.newSearchResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* )*/} - {/* ) : searchResults.filterResult !== undefined ? (*/} - {/* newSearchSection.newFilterResult === undefined ? (*/} - {/* searchResults.filterResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* ) : (*/} - {/* newSearchSection.newFilterResult.map(*/} - {/* (content: any, index: number) => (*/} - {/* */} - {/* )*/} - {/* )*/} - {/* )*/} - {/* ) : searchResults.filterResult === undefined ? (*/} - {/* recentFarms === undefined ? (*/} - {/* newLP.contents?.map((content: any, index: number) => (*/} - {/* */} - {/* ))*/} - {/* ) : (*/} - {/* recentFarms.map((content: any, index: number) => (*/} - {/* */} - {/* ))*/} - {/* )*/} - {/* ) : null}*/} - {/* */} - {/* */} - {/* */} - {/* */} - {/* */} - {/**/} - Farm @@ -2167,7 +786,7 @@ export function Index() { handleSelect(1)} > - {/**/} - {/* */} - {/* {FarmData.contents.map((content: any, index: number) =>*/} - {/* index === 0 ? (*/} - {/* */} - {/* ) : null*/} - {/* )}*/} - {/**/} - - {specialPool?.map((content: any, index: number) => ( + Special pool + {/* {specialPool?.map((content: any, index: number) => ( - ))} + ))} */} - handleSelect(2)}> + handleSelect(2)}> - + - + {selected === farmSection.PRODUCT_FARM ? "AutoTrade Product" : "Deposit"} - + {selected === farmSection.PRODUCT_FARM ? "Percentage Profit Share" : "Earn"} - + {selected === farmSection.PRODUCT_FARM ? "Profit Timeline" : "APY"} - + Total Liquidity {selected === farmSection.PRODUCT_FARM && ( - + Estimated Total Profits )} @@ -2347,7 +944,7 @@ export function Index() { handleSelect(index + 3)} > - + - ) : keyword && - searchResults.searchResult === - undefined ? null : keyword && - searchResults.searchResult !== undefined ? ( - newSearchSection.newSearchResult === undefined ? ( - searchResults.searchResult.map( - (content: any, index: number) => ( - - ) - ) - ) : ( - newSearchSection.newSearchResult.map( - (content: any, index: number) => ( - - ) - ) - ) - ) : searchResults.filterResult !== undefined ? ( - newSearchSection.newFilterResult === undefined ? ( - searchResults.filterResult.map( - (content: any, index: number) => ( - - ) - ) - ) : ( - newSearchSection.newFilterResult.map( - (content: any, index: number) => ( - - ) - ) - ) - ) : searchResults.filterResult === undefined ? ( - recentFarms === undefined ? ( - newLP.contents?.map( - (content: any, index: number) => ( - - ) - ) - ) : ( - recentFarms.map((content: any, index: number) => ( - - )) - ) - ) : null} + /> */} - + - ) : keyword && - searchResults.searchResult === - undefined ? null : keyword && - searchResults.searchResult !== undefined ? ( - newSearchSection.newSearchResult === undefined ? ( - searchResults.searchResult.map( - (content: any, index: number) => ( - - ) - ) - ) : ( - newSearchSection.newSearchResult.map( - (content: any, index: number) => ( - - ) - ) - ) - ) : searchResults.filterResult !== undefined ? ( - newSearchSection.newFilterResult === undefined ? ( - searchResults.filterResult.map( - (content: any, index: number) => ( - - ) - ) - ) : ( - newSearchSection.newFilterResult.map( - (content: any, index: number) => ( - - ) - ) - ) - ) : searchResults.filterResult === undefined ? ( - recentFarms === undefined ? ( - newLP.contents?.map( - (content: any, index: number) => ( - - ) - ) - ) : ( - recentFarms.map((content: any, index: number) => ( - - )) - ) - ) : null} + /> */} diff --git a/src/state/farm/actions.ts b/src/state/farm/actions.ts index 1be9f785..3bdb1b35 100644 --- a/src/state/farm/actions.ts +++ b/src/state/farm/actions.ts @@ -1,21 +1,40 @@ -import { createAction } from '@reduxjs/toolkit' +import { createAction } from "@reduxjs/toolkit"; export interface valuenterface { - reserves0?: any - reserves1?: any, - symbol0?: any, - symbol1?: any + reserves0?: any; + reserves1?: any; + symbol0?: any; + symbol1?: any; } - - -export const changeFarmingContent = createAction<{ value: valuenterface }>('farm/changeFarmingContent'); -export const updateTotalLiquidity = createAction<{ liquidity: any, apy: any, deposit: string}[]>('farm/updateTotalLiquidity'); -export const updateFarmProductLiquidity = createAction<{ liquidity: any, deposit: string}[]>('farm/updateFarmProductLiquidity'); -export const updateTokenStaked = createAction<{ staked: any, earned: any,symbol?:string }[]>('farm/updateTokenStaked'); -export const updateProductStaked = createAction<{ staked: any, }[]>('farm/updateProductStaked'); -export const updateFarmAllowances = createAction('farm/updateFarmAllowances'); -export const updateFarmProductAllowances = createAction('farm/updateFarmProductAllowances'); -export const updateFarmBalances = createAction('farm/updateFarmBalances'); -export const updatePoolId = createAction('farm/updatePoolId'); -export const setLoadingState = createAction('farm/setLoadingState'); +export const changeFarmingContent = createAction<{ value: valuenterface }>( + "farm/changeFarmingContent" +); +export const updateTotalLiquidity = createAction< + { liquidity: any; apy: any; deposit: string }[] +>("farm/updateTotalLiquidity"); +export const updateFarmProductLiquidity = createAction< + { liquidity: any; deposit: string }[] +>("farm/updateFarmProductLiquidity"); +export const updateTokenStaked = createAction< + { staked: any; earned: any; symbol?: string }[] +>("farm/updateTokenStaked"); +export const updateProductStaked = createAction<{ staked: any }[]>( + "farm/updateProductStaked" +); +export const updateFarmAllowances = createAction( + "farm/updateFarmAllowances" +); +export const updateFarmProductAllowances = createAction( + "farm/updateFarmProductAllowances" +); +export const updateFarmBalances = createAction( + "farm/updateFarmBalances" +); +export const updatePoolId = createAction("farm/updatePoolId"); +export const setLoadingState = createAction("farm/setLoadingState"); +export const updateLpFarm = createAction("farm/updateLpFarm"); +export const updateQuickSwapFarm = createAction( + "farm/updateQuickSwapFarm" +); +export const updateStableFarm = createAction("farm/updateStableFarm"); diff --git a/src/state/farm/reducer.ts b/src/state/farm/reducer.ts index 0347a442..640036e5 100644 --- a/src/state/farm/reducer.ts +++ b/src/state/farm/reducer.ts @@ -9,7 +9,10 @@ import { updatePoolId, updateFarmProductLiquidity, updateProductStaked, - setLoadingState + setLoadingState, + updateLpFarm, + updateQuickSwapFarm, + updateStableFarm, } from "./actions"; export interface farmStateInterface { @@ -34,32 +37,16 @@ export interface farmStateInterface { poolAllowance?: any; poolVersion?: string; }>; - productFarm?: any + productFarm?: any; + LpFarm: any; + QuickswapFarm: any; + StableFarm: any; } export const initialState: farmStateInterface = { loadingValue: false, error: null, contents: [ - // { - // id: "1", - // img: "rgp.svg", - // // deposit: 'RGP', - // deposit: "RGP", - // earn: "RGP", - // type: "RGP", - // ARYValue: "0", - // totalLiquidity: "1223", - // tokensStaked: ["RGP", "0"], - // RGPEarned: "0", - // availableToken: "", - // inflationPerDay: 0, - // tokenPrice: 0, - // totalVolumePerPool: 0, - // farmingFee: 0, - // pId: 0, - // poolAllowance: "", - // }, { id: "13", img: "rgp.svg", @@ -81,20 +68,23 @@ export const initialState: farmStateInterface = { poolVersion: "2", }, ], - productFarm :[ + productFarm: [ { - feature:"AutoTrade", - percentageProfitShare:"25%", - profitTimeLine:"6 months", - totalLiquidity:"", - estimatedTotalProfit:"1774000", + feature: "AutoTrade", + percentageProfitShare: "25%", + profitTimeLine: "6 months", + totalLiquidity: "", + estimatedTotalProfit: "1774000", deposit: "RGP", - pid:93903, + pid: 93903, poolAllowance: "", - type:"AT", - RGPStaked:"" - } - ] + type: "AT", + RGPStaked: "", + }, + ], + LpFarm: [], + QuickswapFarm: [], + StableFarm: [], }; export default createReducer(initialState, (builder) => @@ -130,7 +120,7 @@ export default createReducer(initialState, (builder) => }) .addCase(updateTokenStaked, (state, action) => { - console.log(action.payload) + console.log(action.payload); const stakedToken = action.payload; // stakedToken.forEach((item, index) => { // state.contents[index].tokensStaked = [ @@ -139,17 +129,17 @@ export default createReducer(initialState, (builder) => // ]; // state.contents[index].RGPEarned = item.earned; // }); - let index =state.contents.findIndex((item)=>item?.poolVersion ==="2") - state.contents[index].tokensStaked = [ - state.contents[index].tokensStaked[0], - stakedToken[0].staked, - ]; - state.contents[index].RGPEarned = stakedToken[0].earned; + let index = state.contents.findIndex((item) => item?.poolVersion === "2"); + state.contents[index].tokensStaked = [ + state.contents[index].tokensStaked[0], + stakedToken[0].staked, + ]; + state.contents[index].RGPEarned = stakedToken[0].earned; }) .addCase(updateProductStaked, (state, action) => { const stakedToken = action.payload; - console.log({stakedToken}) - state.productFarm[0].RGPStaked = stakedToken[0].staked + console.log({ stakedToken }); + state.productFarm[0].RGPStaked = stakedToken[0].staked; // stakedToken.forEach((item, index) => { // state.contents[index].tokensStaked = [ // state.contents[index].tokensStaked[0], @@ -161,7 +151,7 @@ export default createReducer(initialState, (builder) => .addCase(updateFarmAllowances, (state, action) => { const allowances = action.payload; - console.log(allowances.length,state.contents.length,"iieii") + console.log(allowances.length, state.contents.length, "iieii"); allowances.forEach((item, index) => { state.contents[index].poolAllowance = item; }); @@ -169,7 +159,7 @@ export default createReducer(initialState, (builder) => .addCase(updateFarmProductAllowances, (state, action) => { const allowances = action.payload; - console.log({allowances}) + console.log({ allowances }); allowances.forEach((item, index) => { state.productFarm[index].poolAllowance = item; }); @@ -177,9 +167,9 @@ export default createReducer(initialState, (builder) => .addCase(updateFarmBalances, (state, action) => { const balances = action.payload; - let index =state.contents.findIndex((item)=>item?.poolVersion ==="2") - - state.contents[index].availableToken = balances[0]; + let index = state.contents.findIndex((item) => item?.poolVersion === "2"); + + state.contents[index].availableToken = balances[0]; }) .addCase(updatePoolId, (state, action) => { @@ -189,7 +179,18 @@ export default createReducer(initialState, (builder) => }); }) .addCase(setLoadingState, (state, action) => { - state.loadingValue = !state.loadingValue; }) + + .addCase(updateLpFarm, (state, action) => { + state.LpFarm = action.payload; + }) + + .addCase(updateQuickSwapFarm, (state, action) => { + state.QuickswapFarm = action.payload; + }) + + .addCase(updateStableFarm, (state, action) => { + state.StableFarm = action.payload; + }) ); diff --git a/src/state/farm/types.ts b/src/state/farm/types.ts index 5c54401d..6836a309 100644 --- a/src/state/farm/types.ts +++ b/src/state/farm/types.ts @@ -1,89 +1,92 @@ -import { ThunkAction } from 'redux-thunk' -import { AnyAction } from '@reduxjs/toolkit' -import BigNumber from 'bignumber.js' -import { ethers } from 'ethers' -import { Token } from '../../utils/helpers/token' -import { State } from '../types' -import { SerializedToken } from '../../utils/constants/types' - -export type AppThunk = ThunkAction +import { ThunkAction } from "redux-thunk"; +import { AnyAction } from "@reduxjs/toolkit"; +import BigNumber from "bignumber.js"; +import { ethers } from "ethers"; +import { Token } from "../../utils/helpers/token"; +import { State } from "../types"; +import { SerializedToken } from "../../utils/constants/types"; + +export type AppThunk = ThunkAction< + ReturnType, + State, + unknown, + AnyAction +>; export interface BigNumberToJson { - type: 'BigNumber' - hex: string + type: "BigNumber"; + hex: string; } -export type SerializedBigNumber = string +export type SerializedBigNumber = string; interface SerializedFarmUserData { - allowance: string - tokenBalance: string - stakedBalance: string - earnings: string + allowance: string; + tokenBalance: string; + stakedBalance: string; + earnings: string; } export interface DeserializedFarmUserData { - allowance: BigNumber - tokenBalance: BigNumber - stakedBalance: BigNumber - earnings: BigNumber + allowance: BigNumber; + tokenBalance: BigNumber; + stakedBalance: BigNumber; + earnings: BigNumber; } export interface FarmWithStakedValue extends DeserializedFarm { - apr?: number - lpRewardsApr?: number - liquidity?: BigNumber - } + apr?: number; + lpRewardsApr?: number; + liquidity?: BigNumber; +} export interface Address { - 97?: string - 56: string - } - - + 97?: string; + 56: string; +} interface FarmConfigBaseProps { - pid: number - lpSymbol: string - lpAddresses: Address - multiplier?: string - isCommunity?: boolean - inflation: number - dual?: { - rewardPerBlock: number - earnLabel: string - endBlock: number - } - } - - export interface SerializedFarmConfig extends FarmConfigBaseProps { - token: SerializedToken - quoteToken: SerializedToken - } - - export interface DeserializedFarmConfig extends FarmConfigBaseProps { - token: Token - quoteToken: Token - } + pid: number; + lpSymbol: string; + lpAddresses: Address; + multiplier?: string; + isCommunity?: boolean; + inflation: number; + dual?: { + rewardPerBlock: number; + earnLabel: string; + endBlock: number; + }; +} + +export interface SerializedFarmConfig extends FarmConfigBaseProps { + token: SerializedToken; + quoteToken: SerializedToken; +} + +export interface DeserializedFarmConfig extends FarmConfigBaseProps { + token: Token; + quoteToken: Token; +} export interface SerializedFarm extends SerializedFarmConfig { - inflation: number - tokenPriceBusd?: string - quoteTokenPriceBusd?: string - tokenAmountTotal?: SerializedBigNumber - lpTotalInQuoteToken?: SerializedBigNumber - lpTotalSupply?: SerializedBigNumber - tokenPriceVsQuote?: SerializedBigNumber - poolWeight?: SerializedBigNumber - userData?: SerializedFarmUserData + inflation: number; + tokenPriceBusd?: string; + quoteTokenPriceBusd?: string; + tokenAmountTotal?: SerializedBigNumber; + lpTotalInQuoteToken?: SerializedBigNumber; + lpTotalSupply?: SerializedBigNumber; + tokenPriceVsQuote?: SerializedBigNumber; + poolWeight?: SerializedBigNumber; + userData?: SerializedFarmUserData; } export interface DeserializedFarm extends DeserializedFarmConfig { - tokenPriceBusd?: string - quoteTokenPriceBusd?: string - tokenAmountTotal?: BigNumber - lpTotalInQuoteToken?: BigNumber - lpTotalSupply?: BigNumber - tokenPriceVsQuote?: BigNumber - poolWeight: BigNumber - userData: DeserializedFarmUserData + tokenPriceBusd?: string; + quoteTokenPriceBusd?: string; + tokenAmountTotal?: BigNumber; + lpTotalInQuoteToken?: BigNumber; + lpTotalSupply?: BigNumber; + tokenPriceVsQuote?: BigNumber; + poolWeight: BigNumber; + userData: DeserializedFarmUserData; } // interface CorePoolProps { @@ -117,43 +120,42 @@ export interface DeserializedFarm extends DeserializedFarmConfig { // } // } - // Slices states export interface SerializedFarmsState { - data: SerializedFarm[] - loadArchivedFarmsData: boolean - userDataLoaded: boolean + data: SerializedFarm[]; + loadArchivedFarmsData: boolean; + userDataLoaded: boolean; } export interface DeserializedFarmsState { - data: DeserializedFarm[] - loadArchivedFarmsData: boolean - userDataLoaded: boolean + data: DeserializedFarm[]; + loadArchivedFarmsData: boolean; + userDataLoaded: boolean; } export interface VaultFees { - performanceFee: number - callFee: number - withdrawalFee: number - withdrawalFeePeriod: number + performanceFee: number; + callFee: number; + withdrawalFee: number; + withdrawalFeePeriod: number; } export interface VaultUser { - isLoading: boolean - userShares: string - cakeAtLastUserAction: string - lastDepositedTime: string - lastUserActionTime: string + isLoading: boolean; + userShares: string; + cakeAtLastUserAction: string; + lastDepositedTime: string; + lastUserActionTime: string; } export interface CakeVault { - totalShares?: string - pricePerFullShare?: string - totalCakeInVault?: string - estimatedCakeBountyReward?: string - totalPendingCakeHarvest?: string - fees?: VaultFees - userData?: VaultUser + totalShares?: string; + pricePerFullShare?: string; + totalCakeInVault?: string; + estimatedCakeBountyReward?: string; + totalPendingCakeHarvest?: string; + fees?: VaultFees; + userData?: VaultUser; } // export interface PoolsState { @@ -163,183 +165,176 @@ export interface CakeVault { // } export enum ProfileAvatarFetchStatus { - NOT_FETCHED = 'not-fetched', - FETCHING = 'fetching', - FETCHED = 'fetched', + NOT_FETCHED = "not-fetched", + FETCHING = "fetching", + FETCHED = "fetched", } - - export type TeamResponse = { - 0: string - 1: string - 2: string - 3: string - 4: boolean -} - - - + 0: string; + 1: string; + 2: string; + 3: string; + 4: boolean; +}; export enum AchievementFetchStatus { - ERROR = 'error', - NOT_FETCHED = 'not-fetched', - FETCHING = 'fetching', - FETCHED = 'fetched', + ERROR = "error", + NOT_FETCHED = "not-fetched", + FETCHING = "fetching", + FETCHED = "fetched", } - - // Block export interface BlockState { - currentBlock: number - initialBlock: number + currentBlock: number; + initialBlock: number; } // Predictions export enum BetPosition { - BULL = 'Bull', - BEAR = 'Bear', - HOUSE = 'House', + BULL = "Bull", + BEAR = "Bear", + HOUSE = "House", } export enum PredictionStatus { - INITIAL = 'initial', - LIVE = 'live', - PAUSED = 'paused', - ERROR = 'error', + INITIAL = "initial", + LIVE = "live", + PAUSED = "paused", + ERROR = "error", } export interface Round { - id: string - epoch: number - position: BetPosition - failed: boolean - startAt: number - startBlock: number - startHash: string - lockAt: number - lockBlock: number - lockHash: string - lockPrice: number - lockRoundId: string - closeAt: number - closeBlock: number - closeHash: string - closePrice: number - closeRoundId: string - totalBets: number - totalAmount: number - bullBets: number - bullAmount: number - bearBets: number - bearAmount: number - bets?: Bet[] + id: string; + epoch: number; + position: BetPosition; + failed: boolean; + startAt: number; + startBlock: number; + startHash: string; + lockAt: number; + lockBlock: number; + lockHash: string; + lockPrice: number; + lockRoundId: string; + closeAt: number; + closeBlock: number; + closeHash: string; + closePrice: number; + closeRoundId: string; + totalBets: number; + totalAmount: number; + bullBets: number; + bullAmount: number; + bearBets: number; + bearAmount: number; + bets?: Bet[]; } export interface Market { - paused: boolean - epoch: number + paused: boolean; + epoch: number; } export interface Bet { - id?: string - hash?: string - amount: number - position: BetPosition - claimed: boolean - claimedAt: number - claimedBlock: number - claimedHash: string - claimedBNB: number - claimedNetBNB: number - createdAt: number - updatedAt: number - user?: PredictionUser - round?: Round + id?: string; + hash?: string; + amount: number; + position: BetPosition; + claimed: boolean; + claimedAt: number; + claimedBlock: number; + claimedHash: string; + claimedBNB: number; + claimedNetBNB: number; + createdAt: number; + updatedAt: number; + user?: PredictionUser; + round?: Round; } export interface PredictionUser { - id: string - createdAt: number - updatedAt: number - block: number - totalBets: number - totalBetsBull: number - totalBetsBear: number - totalBNB: number - totalBNBBull: number - totalBNBBear: number - totalBetsClaimed: number - totalBNBClaimed: number - winRate: number - averageBNB: number - netBNB: number - bets?: Bet[] + id: string; + createdAt: number; + updatedAt: number; + block: number; + totalBets: number; + totalBetsBull: number; + totalBetsBear: number; + totalBNB: number; + totalBNBBull: number; + totalBNBBear: number; + totalBetsClaimed: number; + totalBNBClaimed: number; + winRate: number; + averageBNB: number; + netBNB: number; + bets?: Bet[]; } export enum HistoryFilter { - ALL = 'all', - COLLECTED = 'collected', - UNCOLLECTED = 'uncollected', + ALL = "all", + COLLECTED = "collected", + UNCOLLECTED = "uncollected", } export interface LedgerData { [key: string]: { - [key: string]: ReduxNodeLedger - } + [key: string]: ReduxNodeLedger; + }; } export interface RoundData { - [key: string]: ReduxNodeRound + [key: string]: ReduxNodeRound; } export interface ReduxNodeLedger { - position: BetPosition - amount: BigNumberToJson - claimed: boolean + position: BetPosition; + amount: BigNumberToJson; + claimed: boolean; } export interface NodeLedger { - position: BetPosition - amount: ethers.BigNumber - claimed: boolean + position: BetPosition; + amount: ethers.BigNumber; + claimed: boolean; } export interface ReduxNodeRound { - epoch: number - startTimestamp: number | null - lockTimestamp: number | null - closeTimestamp: number | null - lockPrice: BigNumberToJson | null - closePrice: BigNumberToJson | null - totalAmount: BigNumberToJson - bullAmount: BigNumberToJson - bearAmount: BigNumberToJson - rewardBaseCalAmount: BigNumberToJson - rewardAmount: BigNumberToJson - oracleCalled: boolean - lockOracleId: string - closeOracleId: string + epoch: number; + startTimestamp: number | null; + lockTimestamp: number | null; + closeTimestamp: number | null; + lockPrice: BigNumberToJson | null; + closePrice: BigNumberToJson | null; + totalAmount: BigNumberToJson; + bullAmount: BigNumberToJson; + bearAmount: BigNumberToJson; + rewardBaseCalAmount: BigNumberToJson; + rewardAmount: BigNumberToJson; + oracleCalled: boolean; + lockOracleId: string; + closeOracleId: string; } export interface NodeRound { - epoch: number - startTimestamp: number | null - lockTimestamp: number | null - closeTimestamp: number | null - lockPrice: ethers.BigNumber | null - closePrice: ethers.BigNumber | null - totalAmount: ethers.BigNumber - bullAmount: ethers.BigNumber - bearAmount: ethers.BigNumber - rewardBaseCalAmount: ethers.BigNumber - rewardAmount: ethers.BigNumber - oracleCalled: boolean - closeOracleId: string - lockOracleId: string + epoch: number; + startTimestamp: number | null; + lockTimestamp: number | null; + closeTimestamp: number | null; + lockPrice: ethers.BigNumber | null; + closePrice: ethers.BigNumber | null; + totalAmount: ethers.BigNumber; + bullAmount: ethers.BigNumber; + bearAmount: ethers.BigNumber; + rewardBaseCalAmount: ethers.BigNumber; + rewardAmount: ethers.BigNumber; + oracleCalled: boolean; + closeOracleId: string; + lockOracleId: string; } export enum LeaderboardLoadingState { @@ -348,46 +343,46 @@ export enum LeaderboardLoadingState { IDLE, } -export type LeaderboardFilterTimePeriod = '1d' | '7d' | '1m' | 'all' +export type LeaderboardFilterTimePeriod = "1d" | "7d" | "1m" | "all"; export interface LeaderboardFilter { - address?: string - orderBy?: string - timePeriod?: LeaderboardFilterTimePeriod + address?: string; + orderBy?: string; + timePeriod?: LeaderboardFilterTimePeriod; } export interface PredictionsState { - status: PredictionStatus - isLoading: boolean - isHistoryPaneOpen: boolean - isChartPaneOpen: boolean - isFetchingHistory: boolean - historyFilter: HistoryFilter - currentEpoch: number - intervalSeconds: number - minBetAmount: string - bufferSeconds: number - lastOraclePrice: string - history: Bet[] - totalHistory: number - currentHistoryPage: number - hasHistoryLoaded: boolean - rounds?: RoundData - ledgers?: LedgerData + status: PredictionStatus; + isLoading: boolean; + isHistoryPaneOpen: boolean; + isChartPaneOpen: boolean; + isFetchingHistory: boolean; + historyFilter: HistoryFilter; + currentEpoch: number; + intervalSeconds: number; + minBetAmount: string; + bufferSeconds: number; + lastOraclePrice: string; + history: Bet[]; + totalHistory: number; + currentHistoryPage: number; + hasHistoryLoaded: boolean; + rounds?: RoundData; + ledgers?: LedgerData; claimableStatuses: { - [key: string]: boolean - } + [key: string]: boolean; + }; leaderboard: { - selectedAddress: string - loadingState: LeaderboardLoadingState - filters: LeaderboardFilter - skip: number - hasMoreResults: boolean + selectedAddress: string; + loadingState: LeaderboardLoadingState; + filters: LeaderboardFilter; + skip: number; + hasMoreResults: boolean; addressResults: { - [key: string]: PredictionUser - } - results: PredictionUser[] - } + [key: string]: PredictionUser; + }; + results: PredictionUser[]; + }; } // Voting @@ -397,85 +392,83 @@ export interface PredictionsState { * @see https://hub.snapshot.page/graphql */ export interface VoteWhere { - id?: string - id_in?: string[] - voter?: string - voter_in?: string[] - proposal?: string - proposal_in?: string[] + id?: string; + id_in?: string[]; + voter?: string; + voter_in?: string[]; + proposal?: string; + proposal_in?: string[]; } export enum SnapshotCommand { - PROPOSAL = 'proposal', - VOTE = 'vote', + PROPOSAL = "proposal", + VOTE = "vote", } export enum ProposalType { - ALL = 'all', - CORE = 'core', - COMMUNITY = 'community', + ALL = "all", + CORE = "core", + COMMUNITY = "community", } export enum ProposalState { - ACTIVE = 'active', - PENDING = 'pending', - CLOSED = 'closed', + ACTIVE = "active", + PENDING = "pending", + CLOSED = "closed", } export interface Space { - id: string - name: string + id: string; + name: string; } export interface Proposal { - author: string - body: string - choices: string[] - end: number - id: string - snapshot: string - space: Space - start: number - state: ProposalState - title: string + author: string; + body: string; + choices: string[]; + end: number; + id: string; + snapshot: string; + space: Space; + start: number; + state: ProposalState; + title: string; } export interface Vote { - id: string - voter: string - created: number - space: Space + id: string; + voter: string; + created: number; + space: Space; proposal: { - choices: Proposal['choices'] - } - choice: number + choices: Proposal["choices"]; + }; + choice: number; metadata?: { - votingPower: string - verificationHash: string - } - _inValid?: boolean + votingPower: string; + verificationHash: string; + }; + _inValid?: boolean; } export enum VotingStateLoadingStatus { - INITIAL = 'initial', - IDLE = 'idle', - LOADING = 'loading', - ERROR = 'error', + INITIAL = "initial", + IDLE = "idle", + LOADING = "loading", + ERROR = "error", } export interface VotingState { - proposalLoadingStatus: VotingStateLoadingStatus + proposalLoadingStatus: VotingStateLoadingStatus; proposals: { - [key: string]: Proposal - } - voteLoadingStatus: VotingStateLoadingStatus + [key: string]: Proposal; + }; + voteLoadingStatus: VotingStateLoadingStatus; votes: { - [key: string]: Vote[] - } + [key: string]: Vote[]; + }; } - - -export type UserTicketsResponse = [ethers.BigNumber[], number[], boolean[]] +export type UserTicketsResponse = [ethers.BigNumber[], number[], boolean[]]; // Global state diff --git a/src/state/index.ts b/src/state/index.ts index b2144d11..9d0e9509 100644 --- a/src/state/index.ts +++ b/src/state/index.ts @@ -37,10 +37,8 @@ const store = configureStore({ farms, gas, farming, - newfarm, - lpfarm, - newFarming, - chainId + + chainId, }, middleware: [ ...getDefaultMiddleware({ thunk: true }), diff --git a/src/utils/hooks/useFarm.ts b/src/utils/hooks/useFarm.ts new file mode 100644 index 00000000..66d8bdb7 --- /dev/null +++ b/src/utils/hooks/useFarm.ts @@ -0,0 +1,1621 @@ +import { useState, useEffect } from "react"; +import { useWeb3React } from "@web3-react/core"; +import MultiCall from "@indexed-finance/multicall"; +import MasterChefAbi from "../../utils/abis/masterChefV2.json"; +import { + MASTERCHEFV2ADDRESSES, + SMARTSWAPFACTORYADDRESSES, + RGPADDRESSES, + BUSD, + USDT, + USDC, + MASTERCHEFNEWLPADDRESSES, + SMARTSWAPLP_TOKEN3ADDRESSES, + SYMBOLS, +} from "../addresses"; +import LiquidityPairAbi from "../../utils/abis/smartSwapLPToken.json"; +import ERC20TokenAbi from "../../utils/abis/erc20.json"; +import smartFactoryAbi from "../../utils/abis/SmartSwapFactoryForSwap.json"; +import { useSelector } from "react-redux"; +import { RootState } from "../../state"; +import { ethers } from "ethers"; +import { smartSwapLPTokenPoolThree } from "../Contracts"; +import smartswapLpTokenThreeAbi from "../abis/SmartSwapLPTokenThree.json"; +import { + updateLpFarm, + updateQuickSwapFarm, + updateStableFarm, +} from "../../state/farm/actions"; +import { useDispatch } from "react-redux"; + +type FarmData = Array<{ + id: number | undefined; + img: string; + deposit: string; + symbol0: string; + symbol1: string; + earn: string; + type: string; + totalLiquidity: number; + APY: number; + address: string; +}>; + +export const useFetchFarm = () => { + const { account, library, chainId } = useWeb3React(); + + const dispatch = useDispatch(); + + const ChainId = useSelector((state) => state.chainId.chainId); + + const formatSymbol = (symbol: string) => { + let formatted; + if (symbol === "WMATIC") { + formatted = "MATIC"; + } else if (symbol === "WBNB") { + formatted = "BNB"; + } else if (symbol === "wROSE") { + formatted = "ROSE"; + } else if (symbol === "WROSE") { + formatted = "ROSE"; + } else { + formatted = symbol; + } + + return formatted; + }; + + const calculateLiquidityandApy = async ( + pools: any[], + rgpPrice: number | undefined, + + reward?: number + ) => { + try { + const multi = new MultiCall(library); + + const farms = []; + + const totalAllocPoint = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFV2ADDRESSES[chainId as number], + function: "totalAllocPoint", + }, + ]); + + const reserves = await getLpTokenReserve(pools); + + if (reserves) { + for (let i = 0; i < reserves?.length; i++) { + if (reserves[i].reserves0 !== null) { + const totalRGP = reserves + ? RGPADDRESSES[ChainId as number] === reserves[i].tokenAddress0 + ? reserves[i].reserves0.toString() + : reserves[i].reserves1.toString() + : "1"; + + const totalStable = reserves + ? BUSD[ChainId as number] === reserves[i].tokenAddress0 || + USDT[ChainId as number] === reserves[i].tokenAddress0 || + USDC[ChainId as number] === reserves[i].tokenAddress0 + ? ethers.utils.formatUnits( + reserves[i].reserves0.toString(), + reserves[i].decimals0 + ) + : ethers.utils.formatUnits( + reserves[i].reserves1.toString(), + reserves[i].decimals1 + ) + : "1"; + + const totalLiquidity = + reserves[i]?.symbol0 === "BUSD" || + reserves[i]?.symbol1 === "BUSD" || + reserves[i]?.symbol0 === "USDT" || + reserves[i]?.symbol1 === "USDT" || + reserves[i]?.symbol0 === "USDC" || + reserves[i]?.symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * + (rgpPrice as number) * + 2; + const allocPoint = reserves[i].allocPoint; + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint[1][0].toString())) * + (reward as number); + const APY = + ((rgpPrice as number) * poolReward * 365 * 100) / totalLiquidity; + + farms.push({ + id: reserves[i].pid, + img: "rgp.svg", + deposit: `${formatSymbol(reserves[i]?.symbol0)}-${formatSymbol( + reserves[i]?.symbol1 + )}`, + symbol0: formatSymbol(reserves[i]?.symbol0), + symbol1: formatSymbol(reserves[i]?.symbol1), + earn: "RGP", + type: "LP", + totalLiquidity, + APY, + allocPoint: parseFloat(allocPoint.toString()), + address: pools[i].poolAddress, + tokenStaked: [ + `${formatSymbol(reserves[i]?.symbol0)}-${formatSymbol( + reserves[i]?.symbol1 + )}`, + ], + }); + } + } + return farms; + } + } catch (err) { + console.log(err); + } + }; + + const calculateRigelPrice = async () => { + try { + const multi = new MultiCall(library); + let rgpPrice; + + if (ChainId === 56 || ChainId === 97) { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [RGPADDRESSES[ChainId as number], BUSD[ChainId as number]], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalBUSD: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + + rgpPrice = totalBUSD / totalRGP; + } else { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [RGPADDRESSES[ChainId as number], USDT[ChainId as number]], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalUSDT: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === USDT[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === USDT[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + rgpPrice = totalUSDT / totalRGP; + } + + return rgpPrice; + } catch (err) { + console.log(err); + } + }; + + const getLpTokenReserve = async (pools: any[]) => { + try { + const multi = new MultiCall(library); + + const LpReserves = []; + + const reservesInputs = []; + const poolInfoInputs = []; + + const token0Inputs = []; + const token1Inputs = []; + + const symbol0Inputs = []; + const symbol1Inputs = []; + const decimal0Inputs = []; + const decimal1Inputs = []; + + for (let i = 0; i < pools.length; i++) { + reservesInputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "getReserves", + }); + + poolInfoInputs.push({ + interface: MasterChefAbi, + args: [i], + target: MASTERCHEFV2ADDRESSES[chainId as number], + function: "poolInfo", + }); + + token0Inputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "token0", + }); + + token1Inputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "token1", + }); + } + + const reserves = await multi.multiCall(reservesInputs); + const poolInfo = await multi.multiCall(poolInfoInputs); + const token0 = await multi.multiCall(token0Inputs); + const token1 = await multi.multiCall(token1Inputs); + + console.log(reserves[1]); + + console.log("token0", token0); + + for (let i = 0; i < token0[1].length; i++) { + symbol0Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token0[1][i] == null + ? RGPADDRESSES[chainId as number] + : token0[1][i], + function: "symbol", + }); + + decimal0Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token0[1][i] == null + ? RGPADDRESSES[chainId as number] + : token0[1][i], + function: "decimals", + }); + } + + for (let i = 0; i < token1[1].length; i++) { + symbol1Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token1[1][i] == null + ? RGPADDRESSES[chainId as number] + : token1[1][i], + function: "symbol", + }); + + decimal1Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token1[1][i] == null + ? RGPADDRESSES[chainId as number] + : token1[1][i], + function: "decimals", + }); + } + + const symbol0 = await multi.multiCall(symbol0Inputs); + const symbol1 = await multi.multiCall(symbol1Inputs); + const decimals0 = await multi.multiCall(decimal0Inputs); + const decimals1 = await multi.multiCall(decimal1Inputs); + + for (let i = 0; i < reserves[1].length; i++) { + LpReserves.push({ + pid: i, + reserves0: reserves[1][i] == null ? null : reserves[1][i][0], + reserves1: reserves[1][i] == null ? null : reserves[1][i][1], + allocPoint: parseFloat(poolInfo[1][i].allocPoint.toString()), + tokenAddress0: token0[1][i], + tokenAddress1: token1[1][i], + decimals0: decimals0[1][i], + decimals1: decimals1[1][i], + symbol0: symbol0[1][i], + symbol1: symbol1[1][i], + }); + } + + console.log("Lpreserves", LpReserves); + + return LpReserves; + } catch (err) { + console.log(err); + } + }; + + useEffect(() => { + const fetchPools = async () => { + if (account) { + try { + console.log("started"); + const multi = new MultiCall(library); + + const poolAddresses = []; + + const rgpPrice = await calculateRigelPrice(); + + const poolLength = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFV2ADDRESSES[chainId as number], + function: "poolLength", + }, + ]); + + console.log("poolLength", poolLength); + + for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { + const poolInfo = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [i], + target: MASTERCHEFV2ADDRESSES[chainId as number], + function: "poolInfo", + }, + ]); + + poolAddresses.push({ + poolAddress: poolInfo[1][0]?.lpToken, + allocPoint: poolInfo[1][0]?.allocPoint, + }); + } + + const farm = await calculateLiquidityandApy( + poolAddresses, + rgpPrice, + ChainId === 137 || ChainId === 80001 + ? 2014.83125 + : ChainId === 56 || ChainId === 97 + ? 4300 + : ChainId === 42262 || ChainId === 42261 + ? 1343.220833 + : undefined + ); + + if (farm) { + dispatch(updateLpFarm(farm)); + } + + console.log("useFarm", farm); + } catch (err) { + console.log(err); + } + } + }; + + fetchPools(); + }, [account, ChainId]); +}; + +export const useFetchQuickSwap = () => { + const { account, library, chainId } = useWeb3React(); + + const dispatch = useDispatch(); + + const ChainId = useSelector((state) => state.chainId.chainId); + + const formatSymbol = async (symbol: string) => { + let formatted; + if (symbol === "WMATIC") { + formatted = "MATIC"; + } else if (symbol === "WBNB") { + formatted = "BNB"; + } else if (symbol === "wROSE") { + formatted = "ROSE"; + } else if (symbol === "WROSE") { + formatted = "ROSE"; + } else { + formatted = symbol; + } + + return formatted; + }; + + const calculateLiquidityandApy = async ( + pools: any[], + rgpPrice: number | undefined, + BNBPrice: number | undefined, + + reward?: number + ) => { + try { + const multi = new MultiCall(library); + + const farms = []; + + const totalAllocPoint = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], + function: "totalAllocPoint", + }, + ]); + + const reserves = await getLpTokenReserve(pools); + + if (reserves) { + for (let i = 0; i < reserves?.length; i++) { + if (reserves[i].reserves0 !== null) { + const totalRGP = reserves + ? RGPADDRESSES[ChainId as number] === reserves[i].tokenAddress0 + ? reserves[i].reserves0.toString() + : reserves[i].reserves1.toString() + : "1"; + + const totalBNB = reserves + ? SYMBOLS["BNB"][ChainId as number] === reserves[i].tokenAddress0 + ? reserves[i].reserves0.toString() + : reserves[i].reserves1.toString() + : "1"; + + const totalStable = reserves + ? BUSD[ChainId as number] === reserves[i].tokenAddress0 || + USDT[ChainId as number] === reserves[i].tokenAddress0 || + USDC[ChainId as number] === reserves[i].tokenAddress0 + ? ethers.utils.formatUnits( + reserves[i].reserves0.toString(), + reserves[i].decimals0 + ) + : ethers.utils.formatUnits( + reserves[i].reserves1.toString(), + reserves[i].decimals1 + ) + : "1"; + + const totalLiquidity = + reserves[i]?.symbol0 === "BUSD" || + reserves[i]?.symbol1 === "BUSD" || + reserves[i]?.symbol0 === "USDT" || + reserves[i]?.symbol1 === "USDT" || + reserves[i]?.symbol0 === "USDC" || + reserves[i]?.symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : reserves[i]?.symbol0 === "WBNB" || + reserves[i]?.symbol1 === "WBNB" + ? parseFloat(ethers.utils.formatEther(totalBNB)) * + (BNBPrice as number) * + 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * + (rgpPrice as number) * + 2; + const allocPoint = reserves[i].allocPoint; + + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint[1][0].toString())) * + (reward as number); + + const LiquidityLocked = + parseFloat(ethers.utils.formatEther(reserves[i].lockedSupply)) / + parseFloat(ethers.utils.formatEther(reserves[i].totalSupply)); + + const newLiquidity = LiquidityLocked * totalLiquidity; + const APY = + ((rgpPrice as number) * poolReward * 365 * 100) / newLiquidity; + + farms.push({ + id: reserves[i].pid, + img: "rgp.svg", + deposit: `${await formatSymbol( + reserves[i]?.symbol0 + )}-${await formatSymbol(reserves[i]?.symbol1)}`, + symbol0: await formatSymbol(reserves[i]?.symbol0), + symbol1: await formatSymbol(reserves[i]?.symbol1), + earn: "RGP", + type: "LP", + totalLiquidity, + APY, + allocPoint: parseFloat(allocPoint.toString()), + address: pools[i].poolAddress, + LPLocked: newLiquidity.toFixed(2), + }); + } + } + return farms; + } + } catch (err) { + console.log(err); + } + }; + + const getBNBPrice = async () => { + try { + const multi = new MultiCall(library); + let BNBPrice; + + // const pair = await smartSwapLPTokenPoolThree( + // SMARTSWAPLP_TOKEN3ADDRESSES[ChainId as number], + // lib + // ); + + const reserves = await multi.multiCall([ + { + interface: smartswapLpTokenThreeAbi, + target: SMARTSWAPLP_TOKEN3ADDRESSES[ChainId as number], + args: [], + function: "getReserves", + }, + ]); + + // const reserves = await pair.getReserves(); + const testNetPair = SMARTSWAPLP_TOKEN3ADDRESSES[97]; + + // BUSD is token0 on testnet but token1 on mainnet, thus the reason to check + // before calculating the price based on BUSD + + if (SMARTSWAPLP_TOKEN3ADDRESSES[ChainId as number] === testNetPair) { + BNBPrice = ethers.utils.formatUnits( + reserves[1][0][0].mul(1000).div(reserves[1][0][1]), + 3 + ); + } else { + BNBPrice = ethers.utils.formatUnits( + reserves[1][0][1].mul(1000).div(reserves[1][0][0]), + 3 + ); + } + return Number(BNBPrice); + } catch (e) { + console.log("Could not fetch BNB Price."); + } + }; + + const calculateRigelPrice = async () => { + try { + const multi = new MultiCall(library); + let rgpPrice; + + if (ChainId === 56 || ChainId === 97) { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [RGPADDRESSES[ChainId as number], BUSD[ChainId as number]], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalBUSD: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + + rgpPrice = totalBUSD / totalRGP; + } else { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [RGPADDRESSES[ChainId as number], USDT[ChainId as number]], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalUSDT: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === USDT[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === USDT[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + rgpPrice = totalUSDT / totalRGP; + } + + return rgpPrice; + } catch (err) { + console.log(err); + } + }; + + const getLpTokenReserve = async (pools: any[]) => { + try { + const multi = new MultiCall(library); + + const LpReserves = []; + + const reservesInputs = []; + const poolInfoInputs = []; + + const token0Inputs = []; + const token1Inputs = []; + + const symbol0Inputs = []; + const symbol1Inputs = []; + const decimal0Inputs = []; + const decimal1Inputs = []; + const totalSupplyInputs = []; + const lockedSupplyInputs = []; + + for (let i = 0; i < pools.length; i++) { + console.log("before-anything", [ + MASTERCHEFNEWLPADDRESSES[ChainId as number][1], + ]); + reservesInputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i]?.poolAddress, + function: "getReserves", + }); + + poolInfoInputs.push({ + interface: MasterChefAbi, + args: [i], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], + function: "poolInfo", + }); + + token0Inputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i]?.poolAddress, + function: "token0", + }); + + token1Inputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i]?.poolAddress, + function: "token1", + }); + + totalSupplyInputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i]?.poolAddress, + function: "totalSupply", + }); + + lockedSupplyInputs.push({ + interface: LiquidityPairAbi, + args: [MASTERCHEFNEWLPADDRESSES[ChainId as number][1]], + target: pools[i]?.poolAddress, + function: "balanceOf", + }); + } + + console.log("got here", pools); + + const reserves = await multi.multiCall(reservesInputs); + + console.log("reserves", reserves); + const poolInfo = await multi.multiCall(poolInfoInputs); + const token0 = await multi.multiCall(token0Inputs); + const token1 = await multi.multiCall(token1Inputs); + const totalSupply = await multi.multiCall(totalSupplyInputs); + const lockedSupply = await multi.multiCall(lockedSupplyInputs); + + console.log(reserves[1]); + + console.log("token0", token0); + + for (let i = 0; i < token0[1].length; i++) { + symbol0Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token0[1][i] == null + ? RGPADDRESSES[chainId as number] + : token0[1][i], + function: "symbol", + }); + + decimal0Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token0[1][i] == null + ? RGPADDRESSES[chainId as number] + : token0[1][i], + function: "decimals", + }); + } + + for (let i = 0; i < token1[1].length; i++) { + symbol1Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token1[1][i] == null + ? RGPADDRESSES[chainId as number] + : token1[1][i], + function: "symbol", + }); + + decimal1Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token1[1][i] == null + ? RGPADDRESSES[chainId as number] + : token1[1][i], + function: "decimals", + }); + } + + const symbol0 = await multi.multiCall(symbol0Inputs); + const symbol1 = await multi.multiCall(symbol1Inputs); + const decimals0 = await multi.multiCall(decimal0Inputs); + const decimals1 = await multi.multiCall(decimal1Inputs); + + for (let i = 0; i < reserves[1].length; i++) { + LpReserves.push({ + pid: i, + reserves0: reserves[1][i] == null ? null : reserves[1][i][0], + reserves1: reserves[1][i] == null ? null : reserves[1][i][1], + allocPoint: parseFloat(poolInfo[1][i].allocPoint.toString()), + tokenAddress0: token0[1][i], + tokenAddress1: token1[1][i], + decimals0: decimals0[1][i], + decimals1: decimals1[1][i], + symbol0: symbol0[1][i], + symbol1: symbol1[1][i], + totalSupply: totalSupply[1][i], + lockedSupply: lockedSupply[1][i], + tokenStaked: [ + `${await formatSymbol(symbol0[1][i])}-${await formatSymbol( + symbol1[1][i] + )}`, + ], + }); + } + + console.log("Lpreserves", LpReserves); + + return LpReserves; + } catch (err) { + console.log(err); + } + }; + + useEffect(() => { + const fetchPools = async () => { + if (account) { + try { + console.log("started"); + const multi = new MultiCall(library); + + const poolAddresses = []; + + const rgpPrice = await calculateRigelPrice(); + + const BNBPrice = await getBNBPrice(); + + const poolLength = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], + function: "poolLength", + }, + ]); + + console.log("poolLength", poolLength); + + for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { + const poolInfo = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [i], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], + function: "poolInfo", + }, + ]); + + console.log("before fail", poolInfo[1][0]); + + poolInfo[1][0]?.lpToken !== undefined && + poolAddresses.push({ + pid: i, + poolAddress: poolInfo[1][0]?.lpToken, + allocPoint: poolInfo[1][0]?.allocPoint, + }); + } + + console.log("before fail", poolAddresses); + + const farm = await calculateLiquidityandApy( + poolAddresses, + rgpPrice, + BNBPrice, + ChainId === 137 || ChainId === 80001 + ? 2014.83125 + : ChainId === 56 || ChainId === 97 + ? 4300 + : ChainId === 42262 || ChainId === 42261 + ? 1343.220833 + : undefined + ); + + if (farm) { + dispatch(updateQuickSwapFarm(farm)); + } + + console.log("useFarm-quick", farm); + } catch (err) { + console.log(err); + } + } + }; + + fetchPools(); + }, [account, ChainId]); +}; + +export const useFetchStable = () => { + const { account, library, chainId } = useWeb3React(); + const dispatch = useDispatch(); + + const ChainId = useSelector((state) => state.chainId.chainId); + + const formatSymbol = async (symbol: string) => { + let formatted; + if (symbol === "WMATIC") { + formatted = "MATIC"; + } else if (symbol === "WBNB") { + formatted = "BNB"; + } else if (symbol === "wROSE") { + formatted = "ROSE"; + } else if (symbol === "WROSE") { + formatted = "ROSE"; + } else { + formatted = symbol; + } + + return formatted; + }; + + const calculateLiquidityandApy = async ( + pools: any[], + rgpPrice: number | undefined, + BNBPrice: number | undefined, + + reward?: number + ) => { + try { + const multi = new MultiCall(library); + + const farms = []; + + const totalAllocPoint = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], + function: "totalAllocPoint", + }, + ]); + + const reserves = await getLpTokenReserve(pools); + + if (reserves) { + for (let i = 0; i < reserves?.length; i++) { + if (reserves[i].reserves0 !== null) { + const totalRGP = reserves + ? RGPADDRESSES[ChainId as number] === reserves[i].tokenAddress0 + ? reserves[i].reserves0.toString() + : reserves[i].reserves1.toString() + : "1"; + + const totalBNB = reserves + ? SYMBOLS["BNB"][ChainId as number] === reserves[i].tokenAddress0 + ? reserves[i].reserves0.toString() + : reserves[i].reserves1.toString() + : "1"; + + const totalStable = reserves + ? BUSD[ChainId as number] === reserves[i].tokenAddress0 || + USDT[ChainId as number] === reserves[i].tokenAddress0 || + USDC[ChainId as number] === reserves[i].tokenAddress0 + ? ethers.utils.formatUnits( + reserves[i].reserves0.toString(), + reserves[i].decimals0 + ) + : ethers.utils.formatUnits( + reserves[i].reserves1.toString(), + reserves[i].decimals1 + ) + : "1"; + + const totalLiquidity = + reserves[i]?.symbol0 === "BUSD" || + reserves[i]?.symbol1 === "BUSD" || + reserves[i]?.symbol0 === "USDT" || + reserves[i]?.symbol1 === "USDT" || + reserves[i]?.symbol0 === "USDC" || + reserves[i]?.symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : reserves[i]?.symbol0 === "WBNB" || + reserves[i]?.symbol1 === "WBNB" + ? parseFloat(ethers.utils.formatEther(totalBNB)) * + (BNBPrice as number) * + 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * + (rgpPrice as number) * + 2; + const allocPoint = reserves[i].allocPoint; + + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint[1][0].toString())) * + (reward as number); + + const LiquidityLocked = + parseFloat(ethers.utils.formatEther(reserves[i].lockedSupply)) / + parseFloat(ethers.utils.formatEther(reserves[i].totalSupply)); + + const newLiquidity = LiquidityLocked * totalLiquidity; + const APY = + ((rgpPrice as number) * poolReward * 365 * 100) / newLiquidity; + + farms.push({ + id: reserves[i].pid, + img: "rgp.svg", + deposit: `${await formatSymbol( + reserves[i]?.symbol0 + )}-${await formatSymbol(reserves[i]?.symbol1)}`, + symbol0: await formatSymbol(reserves[i]?.symbol0), + symbol1: await formatSymbol(reserves[i]?.symbol1), + earn: "RGP", + type: "LP", + totalLiquidity, + APY, + allocPoint: parseFloat(allocPoint.toString()), + address: pools[i].poolAddress, + LPLocked: newLiquidity.toFixed(2), + tokenStaked: [ + `${await formatSymbol( + reserves[i]?.symbol0 + )}-${await formatSymbol(reserves[i]?.symbol1)}`, + ], + }); + } + } + return farms; + } + } catch (err) { + console.log(err); + } + }; + + const getBNBPrice = async () => { + try { + const multi = new MultiCall(library); + let BNBPrice; + + // const pair = await smartSwapLPTokenPoolThree( + // SMARTSWAPLP_TOKEN3ADDRESSES[ChainId as number], + // lib + // ); + + const reserves = await multi.multiCall([ + { + interface: smartswapLpTokenThreeAbi, + target: SMARTSWAPLP_TOKEN3ADDRESSES[ChainId as number], + args: [], + function: "getReserves", + }, + ]); + + // const reserves = await pair.getReserves(); + const testNetPair = SMARTSWAPLP_TOKEN3ADDRESSES[97]; + + // BUSD is token0 on testnet but token1 on mainnet, thus the reason to check + // before calculating the price based on BUSD + + if (SMARTSWAPLP_TOKEN3ADDRESSES[ChainId as number] === testNetPair) { + BNBPrice = ethers.utils.formatUnits( + reserves[1][0][0].mul(1000).div(reserves[1][0][1]), + 3 + ); + } else { + BNBPrice = ethers.utils.formatUnits( + reserves[1][0][1].mul(1000).div(reserves[1][0][0]), + 3 + ); + } + return Number(BNBPrice); + } catch (e) { + console.log("Could not fetch BNB Price."); + } + }; + + const calculateRigelPrice = async () => { + try { + const multi = new MultiCall(library); + let rgpPrice; + + if (ChainId === 56 || ChainId === 97) { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [RGPADDRESSES[ChainId as number], BUSD[ChainId as number]], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalBUSD: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + + rgpPrice = totalBUSD / totalRGP; + } else { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [RGPADDRESSES[ChainId as number], USDT[ChainId as number]], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalUSDT: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === USDT[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === USDT[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + rgpPrice = totalUSDT / totalRGP; + } + + return rgpPrice; + } catch (err) { + console.log(err); + } + }; + + const getLpTokenReserve = async (pools: any[]) => { + try { + const multi = new MultiCall(library); + + const LpReserves = []; + + const reservesInputs = []; + const poolInfoInputs = []; + + const token0Inputs = []; + const token1Inputs = []; + + const symbol0Inputs = []; + const symbol1Inputs = []; + const decimal0Inputs = []; + const decimal1Inputs = []; + const totalSupplyInputs = []; + const lockedSupplyInputs = []; + + for (let i = 0; i < pools.length; i++) { + reservesInputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "getReserves", + }); + + poolInfoInputs.push({ + interface: MasterChefAbi, + args: [i], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][2], + function: "poolInfo", + }); + + token0Inputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "token0", + }); + + token1Inputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "token1", + }); + + totalSupplyInputs.push({ + interface: LiquidityPairAbi, + args: [], + target: pools[i].poolAddress, + function: "totalSupply", + }); + + lockedSupplyInputs.push({ + interface: LiquidityPairAbi, + args: [MASTERCHEFNEWLPADDRESSES[ChainId as number][2]], + target: pools[i].poolAddress, + function: "balanceOf", + }); + } + + console.log("got here", pools); + + const reserves = await multi.multiCall(reservesInputs); + + console.log("reserves", reserves); + const poolInfo = await multi.multiCall(poolInfoInputs); + const token0 = await multi.multiCall(token0Inputs); + const token1 = await multi.multiCall(token1Inputs); + const totalSupply = await multi.multiCall(totalSupplyInputs); + const lockedSupply = await multi.multiCall(lockedSupplyInputs); + + console.log(reserves[1]); + + console.log("token0", token0); + + for (let i = 0; i < token0[1].length; i++) { + symbol0Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token0[1][i] == null + ? RGPADDRESSES[chainId as number] + : token0[1][i], + function: "symbol", + }); + + decimal0Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token0[1][i] == null + ? RGPADDRESSES[chainId as number] + : token0[1][i], + function: "decimals", + }); + } + + for (let i = 0; i < token1[1].length; i++) { + symbol1Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token1[1][i] == null + ? RGPADDRESSES[chainId as number] + : token1[1][i], + function: "symbol", + }); + + decimal1Inputs.push({ + interface: ERC20TokenAbi, + args: [], + target: + token1[1][i] == null + ? RGPADDRESSES[chainId as number] + : token1[1][i], + function: "decimals", + }); + } + + const symbol0 = await multi.multiCall(symbol0Inputs); + const symbol1 = await multi.multiCall(symbol1Inputs); + const decimals0 = await multi.multiCall(decimal0Inputs); + const decimals1 = await multi.multiCall(decimal1Inputs); + + for (let i = 0; i < reserves[1].length; i++) { + LpReserves.push({ + pid: i, + reserves0: reserves[1][i] == null ? null : reserves[1][i][0], + reserves1: reserves[1][i] == null ? null : reserves[1][i][1], + allocPoint: parseFloat(poolInfo[1][i].allocPoint.toString()), + tokenAddress0: token0[1][i], + tokenAddress1: token1[1][i], + decimals0: decimals0[1][i], + decimals1: decimals1[1][i], + symbol0: symbol0[1][i], + symbol1: symbol1[1][i], + totalSupply: totalSupply[1][i], + lockedSupply: lockedSupply[1][i], + tokenStaked: [ + `${await formatSymbol(symbol0[1][i])}-${await formatSymbol( + symbol1[1][i] + )}`, + ], + }); + } + + console.log("Lpreserves", LpReserves); + + return LpReserves; + } catch (err) { + console.log(err); + } + }; + + useEffect(() => { + const fetchPools = async () => { + if (account) { + try { + console.log("started"); + const multi = new MultiCall(library); + + const poolAddresses = []; + + const rgpPrice = await calculateRigelPrice(); + + const BNBPrice = await getBNBPrice(); + + const poolLength = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][2], + function: "poolLength", + }, + ]); + + console.log("poolLength", poolLength); + + for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { + const poolInfo = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [i], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][2], + function: "poolInfo", + }, + ]); + + poolInfo[1][0]?.lpToken !== undefined && + poolAddresses.push({ + pid: i, + poolAddress: poolInfo[1][0]?.lpToken, + allocPoint: poolInfo[1][0]?.allocPoint, + }); + } + + const farm = await calculateLiquidityandApy( + poolAddresses, + rgpPrice, + BNBPrice, + ChainId === 137 || ChainId === 80001 + ? 2014.83125 + : ChainId === 56 || ChainId === 97 + ? 4300 + : ChainId === 42262 || ChainId === 42261 + ? 1343.220833 + : undefined + ); + + if (farm) { + dispatch(updateStableFarm(farm)); + } + + console.log("useFarm-quick", farm); + } catch (err) { + console.log(err); + } + } + }; + + fetchPools(); + }, [account, ChainId]); +}; diff --git a/src/utils/hooks/useGetFarmData.ts b/src/utils/hooks/useGetFarmData.ts index 998f0116..506d1b45 100644 --- a/src/utils/hooks/useGetFarmData.ts +++ b/src/utils/hooks/useGetFarmData.ts @@ -231,8 +231,7 @@ export const useGetFarmData = (reload?: boolean, setReload?: any) => { address: string, rgpPrice: number | undefined, pid?: number, - reward?: number, - Lp?: boolean + reward?: number ) => { try { const masterchef = await MasterChefV2Contract( @@ -290,18 +289,6 @@ export const useGetFarmData = (reload?: boolean, setReload?: any) => { parseFloat(totalAllocPoint.toString())) * reward; const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; - // const [tokenEarned, userInfo, FarmTokenBalance, allowance] = - // await Promise.all([ - // masterchef.pendingRigel(pid, account), - // masterchef.userInfo(pid, account), - // LPInstance.balanceOf(account), - // LPInstance.allowance( - // account, - // MASTERCHEFV2ADDRESSES[ChainId as number] - // ), - // ]); - // const tokenStaked = await userInfo.amount; - return { id: pid, img: "rgp.svg", @@ -315,13 +302,6 @@ export const useGetFarmData = (reload?: boolean, setReload?: any) => { totalLiquidity, APY, allocPoint: parseFloat(allocPoint.toString()), - // tokenStaked: [ - // `${await formatSymbol(symbol0)}-${await formatSymbol(symbol1)}`, - // ethers.utils.formatEther(tokenStaked.toString()), - // ], - // RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), - // availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), - // poolAllowance: ethers.utils.formatEther(allowance.toString()), address: address, }; } catch (err) { diff --git a/yarn.lock b/yarn.lock index 2d82c7cd..6e0c40b4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2487,6 +2487,11 @@ resolved "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz" integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA== +"@indexed-finance/multicall@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@indexed-finance/multicall/-/multicall-2.0.0.tgz#ec82a51701bb702e7dd4cb06ab81cf9315fa3b0b" + integrity sha512-UgwW+XfLvjjswWc4OWAK8xtSZcW4BEaIA14bebE5JePt2b35gab9W72MKrrL0Wp5hGvAtuaQXbPHgOFuKcqR4g== + "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" resolved "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz" @@ -3415,6 +3420,14 @@ dependencies: "@types/react" "^16" +"@types/react-lazy-load-image-component@^1.5.2": + version "1.5.2" + resolved "https://registry.yarnpkg.com/@types/react-lazy-load-image-component/-/react-lazy-load-image-component-1.5.2.tgz#b87e814b6b91853b802f04465364ff1e913dce6a" + integrity sha512-4NLJsMJVrMv18FuMIkUUBVj/PH9A+BvLKrZC75EWiEFn1IsMrZHgL1tVKw5QBfoa0Qjz6SkWIzEvwcyZ8PgnIg== + dependencies: + "@types/react" "*" + csstype "^3.0.2" + "@types/react-redux@^7.1.20": version "7.1.20" resolved "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.20.tgz" From 04243dc60add6b74c5209ac80e7046308109cc79 Mon Sep 17 00:00:00 2001 From: Godswill Adigwe Date: Fri, 31 Mar 2023 11:13:18 +0100 Subject: [PATCH 2/2] farm fix --- src/pages/FarmingV2/ShowYieldFarmDetails.tsx | 86 +- src/pages/FarmingV2/index.tsx | 74 +- src/state/LPFarm/hooks.ts | 1460 +++++++++--------- src/state/farm/actions.ts | 1 + src/state/farm/reducer.ts | 7 + src/state/newfarm/hooks.ts | 627 +++++--- src/utils/hooks/useFarm.ts | 582 ++++--- 7 files changed, 1597 insertions(+), 1240 deletions(-) diff --git a/src/pages/FarmingV2/ShowYieldFarmDetails.tsx b/src/pages/FarmingV2/ShowYieldFarmDetails.tsx index ddf02bc7..d7869d15 100644 --- a/src/pages/FarmingV2/ShowYieldFarmDetails.tsx +++ b/src/pages/FarmingV2/ShowYieldFarmDetails.tsx @@ -147,13 +147,13 @@ const ShowYieldFarmDetails = ({ const signer = library?.getSigner(); const [reload, setReload] = useState(false); const [contentid, setContentId] = useState(undefined); - const [loading, setLoading] = useState(false); + const [loading, setLoading] = useState(true); // const data = useGetFarmData(reload, setReload); const { loadingState } = useUpdateFarm({ reload, setReload, content }); - useFetchYieldFarmDetails({ content, section, setLoading, loading }); + useFetchYieldFarmDetails({ content, section, setLoading, loading, reload }); //const {loadingFarm} = useUpdateNewFarm({reload, setReload, content}); @@ -236,10 +236,10 @@ const ShowYieldFarmDetails = ({ const checkForApproval = async () => { const rgp = await rigelToken(RGP[chainId as number], library); const rgpApproval = await poolAllowance(rgp); - if (content.deposit === "RGP" && Number(content.id) === 1) { + if (content.deposit === "RGP" && content.version === "v1") { const specialPoolV1Approval = await specialPoolV1Allowance(rgp); changeApprovalButton(true, specialPoolV1Approval); - } else if (content.deposit === "RGP" && Number(content.id) === 13) { + } else if (content.deposit === "RGP" && content.version === "v2") { const specialPoolV2Approval = await specialPoolV2Allowance(rgp); changeApprovalButton(true, specialPoolV2Approval); @@ -305,6 +305,7 @@ const ShowYieldFarmDetails = ({ message: `Successful RGP Approval`, }) ); + setReload(true); } getAllowances(); } catch (error: any) { @@ -360,6 +361,7 @@ const ShowYieldFarmDetails = ({ }) ); } + setReload(true); getAllowances(); } catch (error: any) { console.error(error); @@ -393,11 +395,11 @@ const ShowYieldFarmDetails = ({ }; const checkUser = async (val: string) => { - if (content.deposit === "RGP" && Number(content.id) === 1) { + if (content.deposit === "RGP" && content.version === "v1") { await RGPSpecialPoolV1Approval(); setApproveValueForOtherToken(true); setApproveValueForRGP(true); - } else if (content.deposit === "RGP" && Number(content.id) === 13) { + } else if (content.deposit === "RGP" && content.version === "v2") { await RGPSpecialPoolV2Approval(); setApproveValueForOtherToken(true); setApproveValueForRGP(true); @@ -622,10 +624,11 @@ const ShowYieldFarmDetails = ({ ); if (account) { - if (val === "RGP" && Number(content.id) === 1) { - await RGPUnstake(val); - } else if (val === "RGP" && Number(content.id) === 13) { - await RGPUnstakeV2(val); + console.log("id", content.id); + if (val === "RGP" && content?.version === "v1") { + await RGPUnstake(RGPSPECIALPOOLADDRESSES[chainId as number]); + } else if (val === "RGP" && content?.version === "v2") { + await RGPUnstake(RGPSPECIALPOOLADDRESSES2[chainId as number]); } else { tokensWithdrawal(content.id, val); } @@ -959,9 +962,9 @@ const ShowYieldFarmDetails = ({ : ethers.utils.parseUnits(format3, 9).toString(), } ); - const { confirmations, status, logs } = await fetchTransactionData( - data - ); + const receipt = await data.wait(3); + setDeposited(true); + setReload(!reload); GFarmingSuccessTransaction("farming", "stake", val, "v2"); dispatch( setOpenModal({ @@ -972,7 +975,6 @@ const ShowYieldFarmDetails = ({ //callRefreshFarm(confirmations, status); //temporal - setDeposited(true); } } else { const lpTokens = await MasterChefV2Contract( @@ -1017,9 +1019,10 @@ const ShowYieldFarmDetails = ({ message: `Successfully deposited`, }) ); + setReload(!reload); GFarmingSuccessTransaction("farming", "stake", val, "v2"); setDeposited(true); - setReload(true); + setContentId(content.deposit === "RGP" ? undefined : content.id); // callRefreshFarm(confirmations, status); } @@ -1045,11 +1048,12 @@ const ShowYieldFarmDetails = ({ ); try { if (account) { - if (val === "RGP" && Number(content.id) === 1) { - await RGPuseStake(); - } else if (val === "RGP" && Number(content.id) === 13) { - await RGPuseStakeV2(); + if (val === "RGP" && content?.version === "v1") { + await RGPuseStakeV2(RGPSPECIALPOOLADDRESSES[chainId as number]); + } else if (val === "RGP" && content?.version === "v2") { + await RGPuseStakeV2(RGPSPECIALPOOLADDRESSES2[chainId as number]); } else { + console.log("deposit lp"); LPDeposit(content.id, val); } } @@ -1132,13 +1136,10 @@ const ShowYieldFarmDetails = ({ } } }; - const RGPuseStakeV2 = async () => { + const RGPuseStakeV2 = async (poolAddress: string) => { if (account) { try { - const specialPool = await RGPSpecialPool2( - RGPSPECIALPOOLADDRESSES2[chainId as number], - library - ); + const specialPool = await RGPSpecialPool2(poolAddress, library); GFarmingSpecialPoolReferral( referrerAddress === ZERO_ADDRESS ? false : true ); @@ -1184,13 +1185,10 @@ const ShowYieldFarmDetails = ({ }; // withdrawal of funds - const RGPUnstake = async () => { + const RGPUnstake = async (poolAddress: string) => { if (account) { try { - const specialPool = await RGPSpecialPool( - RGPSPECIALPOOLADDRESSES[chainId as number], - library - ); + const specialPool = await RGPSpecialPool(poolAddress, library); const { format1, format2, format3 } = await calculateGas( userGasPricePercentage, library, @@ -1219,14 +1217,23 @@ const ShowYieldFarmDetails = ({ } ); const { confirmations, status } = await fetchTransactionData(data); - GFarmingSuccessTransaction("special pool", "unstake", "RGP", "v1"); - dispatch( - setOpenModal({ - trxState: TrxState.TransactionSuccessful, - message: `Successfully unstaked ${unstakeToken} RGP `, - }) - ); - refreshSpecialData(); + if (confirmations > 1) { + GFarmingSuccessTransaction( + "special pool", + "unstake", + "RGP", + content?.version + ); + dispatch( + setOpenModal({ + trxState: TrxState.TransactionSuccessful, + message: `Successfully unstaked ${unstakeToken} RGP `, + }) + ); + + refreshSpecialData(); + setReload(true); + } // dispatch the getTokenStaked action from here when data changes // callRefreshFarm(confirmations, status); } catch (e: any) { @@ -2382,7 +2389,10 @@ const ShowYieldFarmDetails = ({ ? { background: "rgba(64, 186, 213, 0.15)" } : { background: "#444159" } } - onClick={() => confirmDeposit(content.deposit)} + onClick={() => { + console.log("confirm"); + confirmDeposit(content.deposit); + }} > {depositValue} diff --git a/src/pages/FarmingV2/index.tsx b/src/pages/FarmingV2/index.tsx index daf5c2b0..f397539c 100644 --- a/src/pages/FarmingV2/index.tsx +++ b/src/pages/FarmingV2/index.tsx @@ -85,6 +85,7 @@ import { useFetchFarm, useFetchQuickSwap, useFetchStable, + useSpecialPool, } from "../../utils/hooks/useFarm"; export const BIG_TEN = new bigNumber(10); @@ -166,9 +167,10 @@ export function Index() { const farms = useSelector((state: any) => state.farms); - useFetchFarm(); - useFetchQuickSwap(); - useFetchStable(); + const { loading: LpfarmLoading } = useFetchFarm(); + const { loading: quickswapLoading } = useFetchQuickSwap(); + const { loading: stableFarmLoading } = useFetchStable(); + useSpecialPool(); useEffect(() => { if (location && location.includes("RGPv2")) { @@ -618,7 +620,7 @@ export function Index() { - {loadingState ? ( + {LpfarmLoading ? ( {new Array(4).fill("1").map((item, index) => { return ( @@ -668,7 +670,7 @@ export function Index() { refreshSpecialData={refreshSpecialData} section={"normal"} wallet={wallet} - LoadingState={loadingState} + LoadingState={LpfarmLoading} /> )) )} @@ -808,8 +810,8 @@ export function Index() { - Special pool - {/* {specialPool?.map((content: any, index: number) => ( + + {farms?.SpecialPool?.map((content: any, index: number) => ( - ))} */} + ))} @@ -1052,7 +1054,7 @@ export function Index() { - {loadingLP ? ( + {quickswapLoading ? ( {new Array(4).fill("1").map((item, index) => { return ( @@ -1101,18 +1103,20 @@ export function Index() { ); })} - ) : null} - - {/* */} + ) : ( + farms?.QuickswapFarm.map((content: any) => ( + + )) + )} @@ -1193,7 +1197,7 @@ export function Index() { - {loadingLP ? ( + {stableFarmLoading ? ( {new Array(4).fill("1").map((item, index) => { return ( @@ -1242,18 +1246,20 @@ export function Index() { ); })} - ) : null} - - {/* */} + ) : ( + farms?.StableFarm.map((content: any) => ( + + )) + )} diff --git a/src/state/LPFarm/hooks.ts b/src/state/LPFarm/hooks.ts index 48254e48..322ed10d 100644 --- a/src/state/LPFarm/hooks.ts +++ b/src/state/LPFarm/hooks.ts @@ -5,765 +5,779 @@ import { useMemo, useState, useCallback } from "react"; import { useDispatch } from "react-redux"; import { useWeb3React } from "@web3-react/core"; import { - MasterChefNEWLPContract, - LiquidityPairInstance, - smartFactory, - productStakingContract, smartSwapLPTokenPoolThree, + MasterChefNEWLPContract, + LiquidityPairInstance, + smartFactory, + productStakingContract, + smartSwapLPTokenPoolThree, } from "../../utils/Contracts"; import { - MASTERCHEFNEWLPADDRESSES, - SMARTSWAPFACTORYADDRESSES, - RGPADDRESSES, - BUSD, - USDT, - USDC, - PRODUCTSTAKINGADDRESSES, SMARTSWAPLP_TOKEN3ADDRESSES, SYMBOLS, + MASTERCHEFNEWLPADDRESSES, + SMARTSWAPFACTORYADDRESSES, + RGPADDRESSES, + BUSD, + USDT, + USDC, + PRODUCTSTAKINGADDRESSES, + SMARTSWAPLP_TOKEN3ADDRESSES, + SYMBOLS, } from "../../utils/addresses"; import { getERC20Token } from "../../utils/utilsFunctions"; import { ethers } from "ethers"; import { - updateYieldFarmDetails, - updateNewFilterResult, - updateNewSearchResult, - updateProductFarmDetails, + updateYieldFarmDetails, + updateNewFilterResult, + updateNewSearchResult, + updateProductFarmDetails, } from "../newFarming/action"; import Web3 from "web3"; -import {RootState} from "../index"; -import {farmSection} from "../../pages/FarmingV2"; - -export const useNewLPData = (): farmDataInterface => { - const farms = useSelector((state: State) => state.lpfarm); - return farms; +import { RootState } from "../index"; +import { farmSection } from "../../pages/FarmingV2"; +import { updateQuickSwapFarm, updateStableFarm } from "../farm/actions"; + +export const useNewLPData = (content: any): farmDataInterface => { + const farms = useSelector((state: State) => state.farms); + const farm = + content?.farm === "quick" + ? farms?.QuickswapFarm + : content?.farm === "stable" + ? farms?.StableFarm + : null; + return farm; }; interface updateFarmInterface { - reload: boolean; - setReload: React.Dispatch>; - content: { - id: number | undefined; - img: string; - deposit: string; - symbol0: string; - symbol1: string; - earn: string; - type: string; - totalLiquidity: number; - APY: number; - address: string; - }; - contractID: number; - section: string; - + reload: boolean; + setReload: React.Dispatch>; + content: { + id: number | undefined; + img: string; + deposit: string; + symbol0: string; + symbol1: string; + earn: string; + type: string; + totalLiquidity: number; + APY: number; + address: string; + }; + contractID: number; + section: string; } const getBNBPrice = async (address: string, library: any) => { - try { - let BNBPrice; - const pair = await smartSwapLPTokenPoolThree( - address, - library - ); - const reserves = await pair.getReserves(); - const testNetPair = SMARTSWAPLP_TOKEN3ADDRESSES[97]; - - // BUSD is token0 on testnet but token1 on mainnet, thus the reason to check - // before calculating the price based on BUSD - - if (pair.address === testNetPair) { - BNBPrice = ethers.utils.formatUnits( - reserves[0].mul(1000).div(reserves[1]), - 3 - ); - } else { - BNBPrice = ethers.utils.formatUnits( - reserves[1].mul(1000).div(reserves[0]), - 3 - ); - } - return Number(BNBPrice); - - } catch (e) { - console.log('Could not fetch BNB Price.') + try { + let BNBPrice; + const pair = await smartSwapLPTokenPoolThree(address, library); + const reserves = await pair.getReserves(); + const testNetPair = SMARTSWAPLP_TOKEN3ADDRESSES[97]; + + // BUSD is token0 on testnet but token1 on mainnet, thus the reason to check + // before calculating the price based on BUSD + + if (pair.address === testNetPair) { + BNBPrice = ethers.utils.formatUnits( + reserves[0].mul(1000).div(reserves[1]), + 3 + ); + } else { + BNBPrice = ethers.utils.formatUnits( + reserves[1].mul(1000).div(reserves[0]), + 3 + ); } + return Number(BNBPrice); + } catch (e) { + console.log("Could not fetch BNB Price."); + } }; export const useUpdateNewFarm = ({ - reload, - setReload, - content, contractID, section - }: updateFarmInterface) => { - const data = useNewLPData(); - const searchSection = useSelector((state) => state.newFarming); - - const selectedField = useSelector((state: State) => state.farming.selectedField); - const selected = selectedField === farmSection.SECOND_NEW_LP; - const mainLP = selectedField === farmSection.NEW_LP; - - const trxState = useSelector((state) => state.application.modal?.trxState); - const stateChanged : boolean = trxState === 2; - - const { account, chainId, library } = useWeb3React(); - const [loadingFarm, setLoadingState] = useState(false); - - const dispatch = useDispatch(); - - const handleUpdateFarms = useCallback( - (value) => { - dispatch( - section === "filter" - ? updateNewFilterResult({ farmData: value }) - : section === "search" - ? updateNewSearchResult({ farmData: value }) - : updateYieldFarmDetails({ value }) - ); - }, - [dispatch] - ); + reload, + setReload, + content, + contractID, + section, +}: updateFarmInterface) => { + const data = useNewLPData(content); + const searchSection = useSelector((state) => state.newFarming); + + const selectedField = useSelector( + (state: State) => state.farming.selectedField + ); + const selected = selectedField === farmSection.SECOND_NEW_LP; + const mainLP = selectedField === farmSection.NEW_LP; + + const trxState = useSelector( + (state) => state.application.modal?.trxState + ); + const stateChanged: boolean = trxState === 2; + + const { account, chainId, library } = useWeb3React(); + const [loadingFarm, setLoadingState] = useState(false); + + const dispatch = useDispatch(); + + const handleUpdateFarms = useCallback( + (value) => { + dispatch( + content?.farm === "quick" + ? updateQuickSwapFarm(value) + : content?.farm === "stable" + ? updateStableFarm(value) + : null + ); + }, + [dispatch] + ); + + const calculateRigelPrice = async () => { + try { + let rgpPrice; + const pair = await smartFactory( + SMARTSWAPFACTORYADDRESSES[chainId as number], + library + ); + + if (chainId === 56 || chainId === 97) { + const pairAddress = await pair.getPair( + RGPADDRESSES[chainId as number], + BUSD[chainId as number] + ); + const LpTokenContract = await LiquidityPairInstance( + pairAddress, + library + ); + const token0Address = await LpTokenContract.token0(); + const token1Address = await LpTokenContract.token1(); + + const [token0Contract, token1Contract] = await Promise.all([ + getERC20Token(token0Address, library), + getERC20Token(token1Address, library), + ]); + + const [decimal0, decimal1] = await Promise.all([ + token0Contract.decimals(), + token1Contract.decimals(), + ]); + + const reserves = await LpTokenContract.getReserves(); + const totalBUSD: number | any = ethers.utils.formatUnits( + token0Address === BUSD[chainId as number] ? reserves[0] : reserves[1], + token0Address === BUSD[chainId as number] ? decimal0 : decimal1 + ); - const calculateRigelPrice = async () => { - try { - let rgpPrice; - const pair = await smartFactory( - SMARTSWAPFACTORYADDRESSES[chainId as number], - library - ); - - if (chainId === 56 || chainId === 97) { - const pairAddress = await pair.getPair( - RGPADDRESSES[chainId as number], - BUSD[chainId as number] - ); - const LpTokenContract = await LiquidityPairInstance( - pairAddress, - library - ); - const token0Address = await LpTokenContract.token0(); - const token1Address = await LpTokenContract.token1(); - - const [token0Contract, token1Contract] = await Promise.all([ - getERC20Token(token0Address, library), - getERC20Token(token1Address, library), - ]); - - const [decimal0, decimal1] = await Promise.all([ - token0Contract.decimals(), - token1Contract.decimals(), - ]); - - const reserves = await LpTokenContract.getReserves(); - const totalBUSD: number | any = ethers.utils.formatUnits( - token0Address === BUSD[chainId as number] ? reserves[0] : reserves[1], - token0Address === BUSD[chainId as number] ? decimal0 : decimal1 - ); - - const totalRGP: number | any = ethers.utils.formatUnits( - token0Address === BUSD[chainId as number] ? reserves[1] : reserves[0], - token0Address === BUSD[chainId as number] ? decimal1 : decimal0 - ); - - rgpPrice = totalBUSD / totalRGP; - } else { - const pairAddress = await pair.getPair( - RGPADDRESSES[chainId as number], - USDT[chainId as number] - ); - const LpTokenContract = await LiquidityPairInstance( - pairAddress, - library - ); - const token0Address = await LpTokenContract.token0(); - const token1Address = await LpTokenContract.token1(); - const [token0Contract, token1Contract] = await Promise.all([ - getERC20Token(token0Address, library), - getERC20Token(token1Address, library), - ]); - const [symbol0, symbol1] = await Promise.all([ - token0Contract.symbol(), - token1Contract.symbol(), - ]); - - const [decimal0, decimal1] = await Promise.all([ - token0Contract.decimals(), - token1Contract.decimals(), - ]); - const reserves = await LpTokenContract.getReserves(); - const totalUSDT: number | any = ethers.utils.formatUnits( - token0Address === USDT[chainId as number] ? reserves[0] : reserves[1], - token0Address === USDT[chainId as number] ? decimal0 : decimal1 - ); - const totalRGP: number | any = ethers.utils.formatUnits( - token0Address === USDT[chainId as number] ? reserves[1] : reserves[0], - token0Address === USDT[chainId as number] ? decimal1 : decimal0 - ); - rgpPrice = totalUSDT / totalRGP; - } - - return rgpPrice; - } catch (err) { - console.log(err); - } - }; + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address === BUSD[chainId as number] ? reserves[1] : reserves[0], + token0Address === BUSD[chainId as number] ? decimal1 : decimal0 + ); - const getLpTokenReserve = async (address: string) => { - //this function gets the reserves of an LP token, it takes the LP token address as an argument - try { - const LpTokenContract = await LiquidityPairInstance(address, library); - const [totalReserves, token0, token1, LPLockedPair, LPTotalSupply] = await Promise.all([ - LpTokenContract.getReserves(), - LpTokenContract.token0(), - LpTokenContract.token1(), - LpTokenContract.balanceOf(MASTERCHEFNEWLPADDRESSES[chainId as number][contractID]), - LpTokenContract.totalSupply() - ]); - - const [token0Contract, token1Contract] = await Promise.all([ - getERC20Token(token0, library), - getERC20Token(token1, library), - ]); - const [symbol0, decimals0, symbol1, decimals1] = await Promise.all([ - token0Contract.symbol(), - token0Contract.decimals(), - token1Contract.symbol(), - token1Contract.decimals(), - ]); - return { - reserves0: totalReserves[0], - reserves1: totalReserves[1], - tokenAddress0: token0, - tokenAddress1: token1, - symbol0, - symbol1, - decimals0, - decimals1, - LPSupply: LPLockedPair, - LPTotalSupply - }; - } catch (err) { - console.log(err); - } - }; + rgpPrice = totalBUSD / totalRGP; + } else { + const pairAddress = await pair.getPair( + RGPADDRESSES[chainId as number], + USDT[chainId as number] + ); + const LpTokenContract = await LiquidityPairInstance( + pairAddress, + library + ); + const token0Address = await LpTokenContract.token0(); + const token1Address = await LpTokenContract.token1(); + const [token0Contract, token1Contract] = await Promise.all([ + getERC20Token(token0Address, library), + getERC20Token(token1Address, library), + ]); + const [symbol0, symbol1] = await Promise.all([ + token0Contract.symbol(), + token1Contract.symbol(), + ]); + + const [decimal0, decimal1] = await Promise.all([ + token0Contract.decimals(), + token1Contract.decimals(), + ]); + const reserves = await LpTokenContract.getReserves(); + const totalUSDT: number | any = ethers.utils.formatUnits( + token0Address === USDT[chainId as number] ? reserves[0] : reserves[1], + token0Address === USDT[chainId as number] ? decimal0 : decimal1 + ); + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address === USDT[chainId as number] ? reserves[1] : reserves[0], + token0Address === USDT[chainId as number] ? decimal1 : decimal0 + ); + rgpPrice = totalUSDT / totalRGP; + } - const calculateLiquidityAndApy = async (reward: number | undefined) => { - try { - const masterchef = await MasterChefNEWLPContract( - MASTERCHEFNEWLPADDRESSES[chainId as number][contractID], - library - ); - const LPInstance = await LiquidityPairInstance(content.address, library); - const reserves = await getLpTokenReserve(content.address); - const totalStable = reserves - ? BUSD[chainId as number] === reserves.tokenAddress0 || - USDT[chainId as number] === reserves.tokenAddress0 || - USDC[chainId as number] === reserves.tokenAddress0 - ? ethers.utils.formatUnits( - reserves.reserves0.toString(), - reserves.decimals0 - ) - : ethers.utils.formatUnits( - reserves.reserves1.toString(), - reserves.decimals1 - ) - : "1"; - - const totalBNB = reserves - ? SYMBOLS['BNB'][chainId as number] === reserves.tokenAddress0 - ? reserves.reserves0.toString() - : reserves.reserves1.toString() - : "1"; - - const rgpPrice = await calculateRigelPrice(); - const BNBPrice = await getBNBPrice(SMARTSWAPLP_TOKEN3ADDRESSES[chainId as number], library); - - const [token0, token1] = await Promise.all([ - getERC20Token(reserves && reserves.tokenAddress0, library), - getERC20Token(reserves && reserves.tokenAddress1, library), - ]); - - const [symbol0, symbol1] = await Promise.all([ - token0.symbol(), - token1.symbol(), - ]); - - const totalRGP = reserves - ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 - ? reserves.reserves0.toString() - : reserves.reserves1.toString() - : "1"; - - const totalLiquidity = - symbol0 === "BUSD" || - symbol1 === "BUSD" || - symbol0 === "USDT" || - symbol1 === "USDT" || - symbol0 === "USDC" || - symbol1 === "USDC" - ? parseFloat(totalStable) * 2 : - symbol0 === "WBNB" || symbol1 === "WBNB" - ? parseFloat(ethers.utils.formatEther(totalBNB)) * BNBPrice * 2 - : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; - - const LiquidityLocked = parseFloat(ethers.utils.formatEther(reserves.LPSupply)) / parseFloat(ethers.utils.formatEther(reserves.LPTotalSupply)); - - const newLiquidity = (LiquidityLocked * totalLiquidity); - - const [poolInfo, totalAllocPoint] = await Promise.all([ - masterchef.poolInfo(content.id), - masterchef.totalAllocPoint(), - ]); - const allocPoint = await poolInfo.allocPoint; - const poolReward = - (parseFloat(allocPoint.toString()) / - parseFloat(totalAllocPoint.toString())) * - reward; - const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; - const newAPY = (rgpPrice * poolReward * 365 * 100) / newLiquidity; - - const [tokenEarned, userInfo, FarmTokenBalance, allowance] = - await Promise.all([ - masterchef.pendingRigel(content.id, account), - masterchef.userInfo(content.id, account), - LPInstance.balanceOf(account), - LPInstance.allowance( - account, - MASTERCHEFNEWLPADDRESSES[chainId as number][contractID] - ), - ]); - const tokenStaked = await userInfo.amount; - - return { - id: content.id, - img: "rgp.svg", - deposit: content.deposit, - earn: "RGP", - type: "LP", - totalLiquidity, - APY: newAPY, - tokenStaked: [ - `${content.symbol0}-${content.symbol1}`, - ethers.utils.formatEther(tokenStaked.toString()), - ], - RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), - availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), - poolAllowance: ethers.utils.formatEther(allowance.toString()), - address: content.address, - LPLocked: newLiquidity.toFixed(2), - }; - } catch (err) { - console.log(err); - } - }; + return rgpPrice; + } catch (err) { + console.log(err); + } + }; + + const getLpTokenReserve = async (address: string) => { + //this function gets the reserves of an LP token, it takes the LP token address as an argument + try { + const LpTokenContract = await LiquidityPairInstance(address, library); + const [totalReserves, token0, token1, LPLockedPair, LPTotalSupply] = + await Promise.all([ + LpTokenContract.getReserves(), + LpTokenContract.token0(), + LpTokenContract.token1(), + LpTokenContract.balanceOf( + MASTERCHEFNEWLPADDRESSES[chainId as number][contractID] + ), + LpTokenContract.totalSupply(), + ]); + + const [token0Contract, token1Contract] = await Promise.all([ + getERC20Token(token0, library), + getERC20Token(token1, library), + ]); + const [symbol0, decimals0, symbol1, decimals1] = await Promise.all([ + token0Contract.symbol(), + token0Contract.decimals(), + token1Contract.symbol(), + token1Contract.decimals(), + ]); + return { + reserves0: totalReserves[0], + reserves1: totalReserves[1], + tokenAddress0: token0, + tokenAddress1: token1, + symbol0, + symbol1, + decimals0, + decimals1, + LPSupply: LPLockedPair, + LPTotalSupply, + }; + } catch (err) { + console.log(err); + } + }; - useMemo(async () => { - if (data !== undefined && account) { - if (reload) { - setLoadingState(true); - let newArray = - section === "search" - ? searchSection.newSearchResult !== undefined - ? [...searchSection.newSearchResult] - : [...searchSection.searchResult] - : section === "filter" - ? searchSection.newFilterResult !== undefined - ? [...searchSection.newFilterResult] - : [...searchSection.filterResult] - : searchSection.content !== undefined - ? [...searchSection.content] - : [...data.contents]; - - const updatedFarm = await calculateLiquidityAndApy( - chainId === 137 || chainId === 80001 - ? 2014.83125 - : chainId === 56 || chainId === 97 - ? 4300 - : chainId === 42262 || chainId === 42261 - ? 1343.220833 - : undefined - ); - const index = newArray.findIndex((item) => item.id === content.id); - newArray[index] = updatedFarm; - handleUpdateFarms(newArray); - - setLoadingState(false); - setReload(false); - } - } - }, [reload, stateChanged, chainId, selected, mainLP]); - return { loadingFarm }; + const calculateLiquidityAndApy = async (reward: number | undefined) => { + try { + const masterchef = await MasterChefNEWLPContract( + MASTERCHEFNEWLPADDRESSES[chainId as number][contractID], + library + ); + const LPInstance = await LiquidityPairInstance(content.address, library); + const reserves = await getLpTokenReserve(content.address); + const totalStable = reserves + ? BUSD[chainId as number] === reserves.tokenAddress0 || + USDT[chainId as number] === reserves.tokenAddress0 || + USDC[chainId as number] === reserves.tokenAddress0 + ? ethers.utils.formatUnits( + reserves.reserves0.toString(), + reserves.decimals0 + ) + : ethers.utils.formatUnits( + reserves.reserves1.toString(), + reserves.decimals1 + ) + : "1"; + + const totalBNB = reserves + ? SYMBOLS["BNB"][chainId as number] === reserves.tokenAddress0 + ? reserves.reserves0.toString() + : reserves.reserves1.toString() + : "1"; + + const rgpPrice = await calculateRigelPrice(); + const BNBPrice = await getBNBPrice( + SMARTSWAPLP_TOKEN3ADDRESSES[chainId as number], + library + ); + + const [token0, token1] = await Promise.all([ + getERC20Token(reserves && reserves.tokenAddress0, library), + getERC20Token(reserves && reserves.tokenAddress1, library), + ]); + + const [symbol0, symbol1] = await Promise.all([ + token0.symbol(), + token1.symbol(), + ]); + + const totalRGP = reserves + ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 + ? reserves.reserves0.toString() + : reserves.reserves1.toString() + : "1"; + + const totalLiquidity = + symbol0 === "BUSD" || + symbol1 === "BUSD" || + symbol0 === "USDT" || + symbol1 === "USDT" || + symbol0 === "USDC" || + symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : symbol0 === "WBNB" || symbol1 === "WBNB" + ? parseFloat(ethers.utils.formatEther(totalBNB)) * BNBPrice * 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; + + const LiquidityLocked = + parseFloat(ethers.utils.formatEther(reserves.LPSupply)) / + parseFloat(ethers.utils.formatEther(reserves.LPTotalSupply)); + + const newLiquidity = LiquidityLocked * totalLiquidity; + + const [poolInfo, totalAllocPoint] = await Promise.all([ + masterchef.poolInfo(content.id), + masterchef.totalAllocPoint(), + ]); + const allocPoint = await poolInfo.allocPoint; + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint.toString())) * + reward; + const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; + const newAPY = (rgpPrice * poolReward * 365 * 100) / newLiquidity; + + const [tokenEarned, userInfo, FarmTokenBalance, allowance] = + await Promise.all([ + masterchef.pendingRigel(content.id, account), + masterchef.userInfo(content.id, account), + LPInstance.balanceOf(account), + LPInstance.allowance( + account, + MASTERCHEFNEWLPADDRESSES[chainId as number][contractID] + ), + ]); + const tokenStaked = await userInfo.amount; + + return { + id: content.id, + img: "rgp.svg", + deposit: content.deposit, + earn: "RGP", + type: "LP", + totalLiquidity, + APY: newAPY, + tokenStaked: [ + `${content.symbol0}-${content.symbol1}`, + ethers.utils.formatEther(tokenStaked.toString()), + ], + RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), + availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), + poolAllowance: ethers.utils.formatEther(allowance.toString()), + address: content.address, + LPLocked: newLiquidity.toFixed(2), + farm: content?.farm, + }; + } catch (err) { + console.log(err); + } + }; + + useMemo(async () => { + if (data !== undefined && account) { + if (reload) { + setLoadingState(true); + let newArray = [...data]; + + const updatedFarm = await calculateLiquidityAndApy( + chainId === 137 || chainId === 80001 + ? 2014.83125 + : chainId === 56 || chainId === 97 + ? 4300 + : chainId === 42262 || chainId === 42261 + ? 1343.220833 + : undefined + ); + const index = newArray.findIndex((item) => item.id === content.id); + newArray[index] = updatedFarm; + handleUpdateFarms(newArray); + + setLoadingState(false); + setReload(false); + } + } + }, [reload, stateChanged, chainId, selected, mainLP]); + return { loadingFarm }; }; interface FetchYieldFarmDetails { - content: { - id: number | undefined; - img: string; - deposit: string; - symbol0: string; - symbol1: string; - earn: string; - type: string; - totalLiquidity: number; - APY: number; - address: string; - }; - section: string; - loading: boolean; - setLoading: React.Dispatch>; - contractID: number + content: { + id: number | undefined; + img: string; + deposit: string; + symbol0: string; + symbol1: string; + earn: string; + type: string; + totalLiquidity: number; + APY: number; + address: string; + }; + section: string; + loading: boolean; + setLoading: React.Dispatch>; + contractID: number; } -export const useNewYieldFarmDetails = ({content, section, loading, setLoading, contractID}: FetchYieldFarmDetails) => { - const data = useNewLPData(); - const searchSection = useSelector((state) => state.newFarming); - const { account, chainId, library } = useWeb3React(); - // const [loading, setLoading] = useState(true); - - const trxState = useSelector((state) => state.application.modal?.trxState); - const stateChanged : boolean = trxState === 2; - - const selectedField = useSelector((state: State) => state.farming.selectedField); - const selected = selectedField === farmSection.SECOND_NEW_LP; - const mainLP = selectedField === farmSection.NEW_LP; - - const dispatch = useDispatch(); - - const handleUpdateFarms = useCallback( - (value) => { - dispatch( - section === "filter" - ? updateNewFilterResult({ farmData: value }) - : section === "search" - ? updateNewSearchResult({ farmData: value }) - : updateYieldFarmDetails({ value }) - ); - }, - [dispatch] - ); +export const useNewYieldFarmDetails = ({ + content, + section, + loading, + setLoading, + contractID, +}: FetchYieldFarmDetails) => { + const data = useNewLPData(content); + const searchSection = useSelector((state) => state.newFarming); + const { account, chainId, library } = useWeb3React(); + // const [loading, setLoading] = useState(true); + + const trxState = useSelector( + (state) => state.application.modal?.trxState + ); + const stateChanged: boolean = trxState === 2; + + const selectedField = useSelector( + (state: State) => state.farming.selectedField + ); + const selected = selectedField === farmSection.SECOND_NEW_LP; + const mainLP = selectedField === farmSection.NEW_LP; + + const dispatch = useDispatch(); + + const handleUpdateFarms = useCallback( + (value) => { + dispatch( + content?.farm === "quick" + ? updateQuickSwapFarm(value) + : content?.farm === "stable" + ? updateStableFarm(value) + : null + ); + }, + [dispatch] + ); + + const calculateRigelPrice = async () => { + try { + let rgpPrice; + const pair = await smartFactory( + SMARTSWAPFACTORYADDRESSES[chainId as number], + library + ); + + if (chainId === 56 || chainId === 97) { + const pairAddress = await pair.getPair( + RGPADDRESSES[chainId as number], + BUSD[chainId as number] + ); + const LpTokenContract = await LiquidityPairInstance( + pairAddress, + library + ); + const token0Address = await LpTokenContract.token0(); + const token1Address = await LpTokenContract.token1(); + + const [token0Contract, token1Contract] = await Promise.all([ + getERC20Token(token0Address, library), + getERC20Token(token1Address, library), + ]); + + const [decimal0, decimal1] = await Promise.all([ + token0Contract.decimals(), + token1Contract.decimals(), + ]); + + const reserves = await LpTokenContract.getReserves(); + const totalBUSD: number | any = ethers.utils.formatUnits( + token0Address === BUSD[chainId as number] ? reserves[0] : reserves[1], + token0Address === BUSD[chainId as number] ? decimal0 : decimal1 + ); - const calculateRigelPrice = async () => { - try { - let rgpPrice; - const pair = await smartFactory( - SMARTSWAPFACTORYADDRESSES[chainId as number], - library - ); - - if (chainId === 56 || chainId === 97) { - const pairAddress = await pair.getPair( - RGPADDRESSES[chainId as number], - BUSD[chainId as number] - ); - const LpTokenContract = await LiquidityPairInstance( - pairAddress, - library - ); - const token0Address = await LpTokenContract.token0(); - const token1Address = await LpTokenContract.token1(); - - const [token0Contract, token1Contract] = await Promise.all([ - getERC20Token(token0Address, library), - getERC20Token(token1Address, library), - ]); - - const [decimal0, decimal1] = await Promise.all([ - token0Contract.decimals(), - token1Contract.decimals(), - ]); - - const reserves = await LpTokenContract.getReserves(); - const totalBUSD: number | any = ethers.utils.formatUnits( - token0Address === BUSD[chainId as number] ? reserves[0] : reserves[1], - token0Address === BUSD[chainId as number] ? decimal0 : decimal1 - ); - - const totalRGP: number | any = ethers.utils.formatUnits( - token0Address === BUSD[chainId as number] ? reserves[1] : reserves[0], - token0Address === BUSD[chainId as number] ? decimal1 : decimal0 - ); - - rgpPrice = totalBUSD / totalRGP; - } else { - const pairAddress = await pair.getPair( - RGPADDRESSES[chainId as number], - USDT[chainId as number] - ); - const LpTokenContract = await LiquidityPairInstance( - pairAddress, - library - ); - const token0Address = await LpTokenContract.token0(); - const token1Address = await LpTokenContract.token1(); - const [token0Contract, token1Contract] = await Promise.all([ - getERC20Token(token0Address, library), - getERC20Token(token1Address, library), - ]); - const [symbol0, symbol1] = await Promise.all([ - token0Contract.symbol(), - token1Contract.symbol(), - ]); - - const [decimal0, decimal1] = await Promise.all([ - token0Contract.decimals(), - token1Contract.decimals(), - ]); - const reserves = await LpTokenContract.getReserves(); - const totalUSDT: number | any = ethers.utils.formatUnits( - token0Address === USDT[chainId as number] ? reserves[0] : reserves[1], - token0Address === USDT[chainId as number] ? decimal0 : decimal1 - ); - const totalRGP: number | any = ethers.utils.formatUnits( - token0Address === USDT[chainId as number] ? reserves[1] : reserves[0], - token0Address === USDT[chainId as number] ? decimal1 : decimal0 - ); - rgpPrice = totalUSDT / totalRGP; - } - - return rgpPrice; - } catch (err) { - console.log(err); - } - }; + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address === BUSD[chainId as number] ? reserves[1] : reserves[0], + token0Address === BUSD[chainId as number] ? decimal1 : decimal0 + ); - const getLpTokenReserve = async (address: string) => { - //this function gets the reserves of an LP token, it takes the LP token address as an argument - try { - const LpTokenContract = await LiquidityPairInstance(address, library); - const [totalReserves, token0, token1, LPLockedPair, LPTotalSupply] = await Promise.all([ - LpTokenContract.getReserves(), - LpTokenContract.token0(), - LpTokenContract.token1(), - LpTokenContract.balanceOf(MASTERCHEFNEWLPADDRESSES[chainId as number][contractID]), - LpTokenContract.totalSupply() - ]); - - const [token0Contract, token1Contract] = await Promise.all([ - getERC20Token(token0, library), - getERC20Token(token1, library), - ]); - const [symbol0, decimals0, symbol1, decimals1] = await Promise.all([ - token0Contract.symbol(), - token0Contract.decimals(), - token1Contract.symbol(), - token1Contract.decimals(), - ]); - return { - reserves0: totalReserves[0], - reserves1: totalReserves[1], - tokenAddress0: token0, - tokenAddress1: token1, - symbol0, - symbol1, - decimals0, - decimals1, - LPSupply: LPLockedPair, - LPTotalSupply - }; - } catch (err) { - console.log(err); - } - }; + rgpPrice = totalBUSD / totalRGP; + } else { + const pairAddress = await pair.getPair( + RGPADDRESSES[chainId as number], + USDT[chainId as number] + ); + const LpTokenContract = await LiquidityPairInstance( + pairAddress, + library + ); + const token0Address = await LpTokenContract.token0(); + const token1Address = await LpTokenContract.token1(); + const [token0Contract, token1Contract] = await Promise.all([ + getERC20Token(token0Address, library), + getERC20Token(token1Address, library), + ]); + const [symbol0, symbol1] = await Promise.all([ + token0Contract.symbol(), + token1Contract.symbol(), + ]); + + const [decimal0, decimal1] = await Promise.all([ + token0Contract.decimals(), + token1Contract.decimals(), + ]); + const reserves = await LpTokenContract.getReserves(); + const totalUSDT: number | any = ethers.utils.formatUnits( + token0Address === USDT[chainId as number] ? reserves[0] : reserves[1], + token0Address === USDT[chainId as number] ? decimal0 : decimal1 + ); + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address === USDT[chainId as number] ? reserves[1] : reserves[0], + token0Address === USDT[chainId as number] ? decimal1 : decimal0 + ); + rgpPrice = totalUSDT / totalRGP; + } - const calculateLiquidityAndApy = async (reward: number | undefined) => { - try { - const masterchef = await MasterChefNEWLPContract( - MASTERCHEFNEWLPADDRESSES[chainId as number][contractID], - library - ); - const LPInstance = await LiquidityPairInstance(content.address, library); - const reserves = await getLpTokenReserve(content.address); - const totalStable = reserves - ? BUSD[chainId as number] === reserves.tokenAddress0 || - USDT[chainId as number] === reserves.tokenAddress0 || - USDC[chainId as number] === reserves.tokenAddress0 - ? ethers.utils.formatUnits( - reserves.reserves0.toString(), - reserves.decimals0 - ) - : ethers.utils.formatUnits( - reserves.reserves1.toString(), - reserves.decimals1 - ) - : "1"; - - const rgpPrice = await calculateRigelPrice(); - const BNBPrice = await getBNBPrice(SMARTSWAPLP_TOKEN3ADDRESSES[chainId as number], library); - - const [token0, token1] = await Promise.all([ - getERC20Token(reserves && reserves.tokenAddress0, library), - getERC20Token(reserves && reserves.tokenAddress1, library), - ]); - - const [symbol0, symbol1] = await Promise.all([ - token0.symbol(), - token1.symbol(), - ]); - - const totalRGP = reserves - ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 - ? reserves.reserves0.toString() - : reserves.reserves1.toString() - : "1"; - - const totalBNB = reserves - ? SYMBOLS['BNB'][chainId as number] === reserves.tokenAddress0 - ? reserves.reserves0.toString() - : reserves.reserves1.toString() - : "1"; - - const totalLiquidity = - symbol0 === "BUSD" || - symbol1 === "BUSD" || - symbol0 === "USDT" || - symbol1 === "USDT" || - symbol0 === "USDC" || - symbol1 === "USDC" - ? parseFloat(totalStable) * 2 : - symbol0 === "WBNB" || symbol1 === "WBNB" - ? parseFloat(ethers.utils.formatEther(totalBNB)) * BNBPrice * 2 - : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; - - const LiquidityLocked = parseFloat(ethers.utils.formatEther(reserves.LPSupply)) / parseFloat(ethers.utils.formatEther(reserves.LPTotalSupply)); - const newLiquidity = (LiquidityLocked * totalLiquidity); - - const [poolInfo, totalAllocPoint] = await Promise.all([ - masterchef.poolInfo(content.id), - masterchef.totalAllocPoint(), - ]); - const allocPoint = await poolInfo.allocPoint; - const poolReward = - (parseFloat(allocPoint.toString()) / - parseFloat(totalAllocPoint.toString())) * - reward; - const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; - const newAPY = (rgpPrice * poolReward * 365 * 100) / newLiquidity; - - - const [tokenEarned, userInfo, FarmTokenBalance, allowance] = - await Promise.all([ - masterchef.pendingRigel(content.id, account), - masterchef.userInfo(content.id, account), - LPInstance.balanceOf(account), - LPInstance.allowance( - account, - MASTERCHEFNEWLPADDRESSES[chainId as number][contractID] - ), - ]); - const tokenStaked = await userInfo.amount; - - return { - id: content.id, - img: "rgp.svg", - deposit: content.deposit, - earn: "RGP", - type: "LP", - totalLiquidity, - APY: newAPY, - tokenStaked: [ - `${content.symbol0}-${content.symbol1}`, - ethers.utils.formatEther(tokenStaked.toString()), - ], - RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), - availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), - poolAllowance: ethers.utils.formatEther(allowance.toString()), - address: content.address, - LPLocked: newLiquidity.toFixed(2) - }; - } catch (err) { - console.log(err); - } - }; + return rgpPrice; + } catch (err) { + console.log(err); + } + }; + + const getLpTokenReserve = async (address: string) => { + //this function gets the reserves of an LP token, it takes the LP token address as an argument + try { + const LpTokenContract = await LiquidityPairInstance(address, library); + const [totalReserves, token0, token1, LPLockedPair, LPTotalSupply] = + await Promise.all([ + LpTokenContract.getReserves(), + LpTokenContract.token0(), + LpTokenContract.token1(), + LpTokenContract.balanceOf( + MASTERCHEFNEWLPADDRESSES[chainId as number][contractID] + ), + LpTokenContract.totalSupply(), + ]); + + const [token0Contract, token1Contract] = await Promise.all([ + getERC20Token(token0, library), + getERC20Token(token1, library), + ]); + const [symbol0, decimals0, symbol1, decimals1] = await Promise.all([ + token0Contract.symbol(), + token0Contract.decimals(), + token1Contract.symbol(), + token1Contract.decimals(), + ]); + return { + reserves0: totalReserves[0], + reserves1: totalReserves[1], + tokenAddress0: token0, + tokenAddress1: token1, + symbol0, + symbol1, + decimals0, + decimals1, + LPSupply: LPLockedPair, + LPTotalSupply, + }; + } catch (err) { + console.log(err); + } + }; - useMemo(async () => { - if (data !== undefined && account) { - setLoading(true); - let newArray = - section === "search" - ? searchSection.newSearchResult !== undefined - ? [...searchSection.newSearchResult] - : [...searchSection.searchResult] - : section === "filter" - ? searchSection.newFilterResult !== undefined - ? [...searchSection.newFilterResult] - : [...searchSection.filterResult] - : searchSection.content !== undefined - ? [...searchSection.content] - : [...data.contents]; - - const updatedFarm = await calculateLiquidityAndApy( - chainId === 137 || chainId === 80001 - ? 2014.83125 - : chainId === 56 || chainId === 97 - ? 4300 - : chainId === 42262 || chainId === 42261 - ? 1343.220833 - : undefined - ); - const index = newArray.findIndex((item) => item.id === content.id); - - newArray[index] = updatedFarm; - - console.log("updated", newArray); - - handleUpdateFarms(newArray); - - setLoading(false); - } - }, [account, stateChanged, chainId, selected, mainLP]); - return { loading }; + const calculateLiquidityAndApy = async (reward: number | undefined) => { + try { + const masterchef = await MasterChefNEWLPContract( + MASTERCHEFNEWLPADDRESSES[chainId as number][contractID], + library + ); + const LPInstance = await LiquidityPairInstance(content.address, library); + const reserves = await getLpTokenReserve(content.address); + const totalStable = reserves + ? BUSD[chainId as number] === reserves.tokenAddress0 || + USDT[chainId as number] === reserves.tokenAddress0 || + USDC[chainId as number] === reserves.tokenAddress0 + ? ethers.utils.formatUnits( + reserves.reserves0.toString(), + reserves.decimals0 + ) + : ethers.utils.formatUnits( + reserves.reserves1.toString(), + reserves.decimals1 + ) + : "1"; + + const rgpPrice = await calculateRigelPrice(); + const BNBPrice = await getBNBPrice( + SMARTSWAPLP_TOKEN3ADDRESSES[chainId as number], + library + ); + + const [token0, token1] = await Promise.all([ + getERC20Token(reserves && reserves.tokenAddress0, library), + getERC20Token(reserves && reserves.tokenAddress1, library), + ]); + + const [symbol0, symbol1] = await Promise.all([ + token0.symbol(), + token1.symbol(), + ]); + + const totalRGP = reserves + ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 + ? reserves.reserves0.toString() + : reserves.reserves1.toString() + : "1"; + + const totalBNB = reserves + ? SYMBOLS["BNB"][chainId as number] === reserves.tokenAddress0 + ? reserves.reserves0.toString() + : reserves.reserves1.toString() + : "1"; + + const totalLiquidity = + symbol0 === "BUSD" || + symbol1 === "BUSD" || + symbol0 === "USDT" || + symbol1 === "USDT" || + symbol0 === "USDC" || + symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : symbol0 === "WBNB" || symbol1 === "WBNB" + ? parseFloat(ethers.utils.formatEther(totalBNB)) * BNBPrice * 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; + + const LiquidityLocked = + parseFloat(ethers.utils.formatEther(reserves.LPSupply)) / + parseFloat(ethers.utils.formatEther(reserves.LPTotalSupply)); + const newLiquidity = LiquidityLocked * totalLiquidity; + + const [poolInfo, totalAllocPoint] = await Promise.all([ + masterchef.poolInfo(content.id), + masterchef.totalAllocPoint(), + ]); + const allocPoint = await poolInfo.allocPoint; + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint.toString())) * + reward; + const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; + const newAPY = (rgpPrice * poolReward * 365 * 100) / newLiquidity; + + const [tokenEarned, userInfo, FarmTokenBalance, allowance] = + await Promise.all([ + masterchef.pendingRigel(content.id, account), + masterchef.userInfo(content.id, account), + LPInstance.balanceOf(account), + LPInstance.allowance( + account, + MASTERCHEFNEWLPADDRESSES[chainId as number][contractID] + ), + ]); + const tokenStaked = await userInfo.amount; + + return { + id: content.id, + img: "rgp.svg", + deposit: content.deposit, + earn: "RGP", + type: "LP", + totalLiquidity, + APY: newAPY, + tokenStaked: [ + `${content.symbol0}-${content.symbol1}`, + ethers.utils.formatEther(tokenStaked.toString()), + ], + RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), + availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), + poolAllowance: ethers.utils.formatEther(allowance.toString()), + address: content.address, + LPLocked: newLiquidity.toFixed(2), + farm: content?.farm, + }; + } catch (err) { + console.log(err); + } + }; + + useMemo(async () => { + if (data !== undefined && account) { + setLoading(true); + let newArray = [...data]; + + const updatedFarm = await calculateLiquidityAndApy( + chainId === 137 || chainId === 80001 + ? 2014.83125 + : chainId === 56 || chainId === 97 + ? 4300 + : chainId === 42262 || chainId === 42261 + ? 1343.220833 + : undefined + ); + const index = newArray.findIndex((item) => item.id === content.id); + + newArray[index] = updatedFarm; + + console.log("updated", newArray); + + handleUpdateFarms(newArray); + + setLoading(false); + } + }, [account, stateChanged, chainId, selected, mainLP]); + return { loading }; }; interface productFarmState { - content: { - feature:string, - percentageProfitShare:string, - profitTimeLine:string, - totalLiquidity:string, - estimatedTotalProfit:string, - pid:number, - deposit:string, - poolAllowance: "", - type:string - }; - loading: boolean; - setLoading: React.Dispatch>; + content: { + feature: string; + percentageProfitShare: string; + profitTimeLine: string; + totalLiquidity: string; + estimatedTotalProfit: string; + pid: number; + deposit: string; + poolAllowance: ""; + type: string; + }; + loading: boolean; + setLoading: React.Dispatch>; } export const useProductFarmDetails = ({ - content, - loading, - setLoading - }:productFarmState) =>{ - const { account, chainId, library } = useWeb3React(); - const getUserValue = async ()=> { - const productFarm = await productStakingContract( - PRODUCTSTAKINGADDRESSES[chainId as number], - library - ); - const [ userInfo, FarmTokenBalance] = - await Promise.all([ - productFarm.userInfo(account), - productFarm.userData(account), - ]); - const tokenStaked = await FarmTokenBalance.tokenQuantity; - - return { - feature:"AutoTrade", - percentageProfitShare:"25%", - profitTimeLine:"6 months", - totalLiquidity:"188839", - estimatedTotalProfit:"929020003", - deposit: "RGP", - pid:93903, - poolAllowance: "", - type:"AT", - tokenStaked: Web3.utils.fromWei(tokenStaked.toString()) - }; - } - - useMemo(async ()=>{ - let response =await getUserValue() + content, + loading, + setLoading, +}: productFarmState) => { + const { account, chainId, library } = useWeb3React(); + const getUserValue = async () => { + const productFarm = await productStakingContract( + PRODUCTSTAKINGADDRESSES[chainId as number], + library + ); + const [userInfo, FarmTokenBalance] = await Promise.all([ + productFarm.userInfo(account), + productFarm.userData(account), + ]); + const tokenStaked = await FarmTokenBalance.tokenQuantity; + + return { + feature: "AutoTrade", + percentageProfitShare: "25%", + profitTimeLine: "6 months", + totalLiquidity: "188839", + estimatedTotalProfit: "929020003", + deposit: "RGP", + pid: 93903, + poolAllowance: "", + type: "AT", + tokenStaked: Web3.utils.fromWei(tokenStaked.toString()), + }; + }; - updateProductFarmDetails({value:[response]}) + useMemo(async () => { + let response = await getUserValue(); - setLoading(false) - },[]) - return {loading} + updateProductFarmDetails({ value: [response] }); -} + setLoading(false); + }, []); + return { loading }; +}; diff --git a/src/state/farm/actions.ts b/src/state/farm/actions.ts index 3bdb1b35..5bc16b6b 100644 --- a/src/state/farm/actions.ts +++ b/src/state/farm/actions.ts @@ -38,3 +38,4 @@ export const updateQuickSwapFarm = createAction( "farm/updateQuickSwapFarm" ); export const updateStableFarm = createAction("farm/updateStableFarm"); +export const updateSpecialPool = createAction("farm/updateSpecialPool"); diff --git a/src/state/farm/reducer.ts b/src/state/farm/reducer.ts index 640036e5..b7399f87 100644 --- a/src/state/farm/reducer.ts +++ b/src/state/farm/reducer.ts @@ -13,6 +13,7 @@ import { updateLpFarm, updateQuickSwapFarm, updateStableFarm, + updateSpecialPool, } from "./actions"; export interface farmStateInterface { @@ -41,6 +42,7 @@ export interface farmStateInterface { LpFarm: any; QuickswapFarm: any; StableFarm: any; + SpecialPool: any; } export const initialState: farmStateInterface = { @@ -85,6 +87,7 @@ export const initialState: farmStateInterface = { LpFarm: [], QuickswapFarm: [], StableFarm: [], + SpecialPool: [], }; export default createReducer(initialState, (builder) => @@ -193,4 +196,8 @@ export default createReducer(initialState, (builder) => .addCase(updateStableFarm, (state, action) => { state.StableFarm = action.payload; }) + + .addCase(updateSpecialPool, (state, action) => { + state.SpecialPool = action.payload; + }) ); diff --git a/src/state/newfarm/hooks.ts b/src/state/newfarm/hooks.ts index b83227fa..4bb3b165 100644 --- a/src/state/newfarm/hooks.ts +++ b/src/state/newfarm/hooks.ts @@ -12,6 +12,7 @@ import { LiquidityPairInstance, smartFactory, productStakingContract, + RGPSpecialPool2, } from "../../utils/Contracts"; import { MASTERCHEFV2ADDRESSES, @@ -21,6 +22,7 @@ import { USDT, USDC, PRODUCTSTAKINGADDRESSES, + RGPSPECIALPOOLADDRESSES2, } from "../../utils/addresses"; import { getERC20Token } from "../../utils/utilsFunctions"; import { ethers } from "ethers"; @@ -34,10 +36,28 @@ import { updateProductFarmDetails, } from "../farming/action"; import Web3 from "web3"; - -export const useFarmData = (): farmDataInterface => { - const farms = useSelector((state: State) => state.newfarm); - return farms; +import { + updateQuickSwapFarm, + updateLpFarm, + updateStableFarm, + updateSpecialPool, +} from "../farm/actions"; +import farm from "../farm"; + +export const useFarmData = (content: any): farmDataInterface => { + const farms = useSelector((state: State) => state.farms); + const farm = + content?.farm === "lp" + ? farms.LpFarm + : content?.farm === "quick" + ? farms.QuickswapFarm + : content?.farm === "stable" + ? farms.StableFarm + : content?.farm === "special" + ? farms.SpecialPool + : null; + + return farm; }; interface updateFarmInterface { @@ -63,9 +83,10 @@ export const useUpdateFarm = ({ reload, setReload, content, - section, address + section, + address, }: updateFarmInterface) => { - const data = useFarmData(); + const data = useFarmData(content); const searchSection = useSelector((state) => state.farming); const { account, chainId, library } = useWeb3React(); @@ -76,11 +97,15 @@ export const useUpdateFarm = ({ const handleUpdateFarms = useCallback( (value) => { dispatch( - section === "filter" - ? updateNewFilterResult({ farmData: value }) - : section === "search" - ? updateNewSearchResult({ farmData: value }) - : updateYieldFarmDetails({ value }) + content?.farm === "lp" + ? updateLpFarm(value) + : content?.farm === "quick" + ? updateQuickSwapFarm(value) + : content?.farm === "stable" + ? updateStableFarm(value) + : content?.farm === "special" + ? updateSpecialPool(value) + : null ); }, [dispatch] @@ -207,114 +232,156 @@ export const useUpdateFarm = ({ const calculateLiquidityAndApy = async (reward: number | undefined) => { try { - const masterchef = await MasterChefV2Contract( - MASTERCHEFV2ADDRESSES[chainId as number], - library - ); - const LPInstance = await LiquidityPairInstance(content.address, library); - const reserves = await getLpTokenReserve(content.address); - const totalStable = reserves - ? BUSD[chainId as number] === reserves.tokenAddress0 || - USDT[chainId as number] === reserves.tokenAddress0 || - USDC[chainId as number] === reserves.tokenAddress0 - ? ethers.utils.formatUnits( - reserves.reserves0.toString(), - reserves.decimals0 - ) - : ethers.utils.formatUnits( - reserves.reserves1.toString(), - reserves.decimals1 - ) - : "1"; - - const rgpPrice = await calculateRigelPrice(); - - const [token0, token1] = await Promise.all([ - getERC20Token(reserves && reserves.tokenAddress0, library), - getERC20Token(reserves && reserves.tokenAddress1, library), - ]); + if (content?.farm === "special") { + const specialPool = await RGPSpecialPool2(content?.address, library); - const [symbol0, symbol1] = await Promise.all([ - token0.symbol(), - token1.symbol(), - ]); + const token = await getERC20Token( + RGPADDRESSES[chainId as number], + library + ); - const totalRGP = reserves - ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 - ? reserves.reserves0.toString() - : reserves.reserves1.toString() - : "1"; - - const totalLiquidity = - symbol0 === "BUSD" || - symbol1 === "BUSD" || - symbol0 === "USDT" || - symbol1 === "USDT" || - symbol0 === "USDC" || - symbol1 === "USDC" - ? parseFloat(totalStable) * 2 - : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; - - const [poolInfo, totalAllocPoint] = await Promise.all([ - masterchef.poolInfo(content.id), - masterchef.totalAllocPoint(), - ]); - const allocPoint = await poolInfo.allocPoint; - const poolReward = - (parseFloat(allocPoint.toString()) / - parseFloat(totalAllocPoint.toString())) * - reward; - const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; - const [tokenEarned, userInfo, FarmTokenBalance, allowance] = - await Promise.all([ - masterchef.pendingRigel(content.id, account), - masterchef.userInfo(content.id, account), - LPInstance.balanceOf(account), - LPInstance.allowance( - account, - MASTERCHEFV2ADDRESSES[chainId as number] + const [amountStaked, allowance, balance] = await Promise.all([ + specialPool.userInfo(account), + token.allowance(account, RGPSPECIALPOOLADDRESSES2[chainId as number]), + token.balanceOf(account), + ]); + + return { + id: content?.id, + img: "rgp.svg", + // deposit: 'RGP', + deposit: "RGP", + earn: "RGP", + type: "RGP", + ARYValue: content?.ARYValue, + totalLiquidity: content?.totalLiquidity, + tokensStaked: [ + "RGP", + parseFloat( + ethers.utils.formatEther(amountStaked?._amountStaked.toString()) + ), + ], + RGPEarned: parseFloat( + ethers.utils.formatEther(amountStaked?._userReward.toString()) + ), + availableToken: parseFloat( + ethers.utils.formatEther(balance.toString()) + ), + inflationPerDay: 0, + tokenPrice: content?.rgpPrice, + totalVolumePerPool: 0, + farmingFee: 0, + pId: content?.pId, + poolAllowance: parseFloat( + ethers.utils.formatEther(allowance.toString()) ), + poolVersion: content?.poolVersion, + version: content?.version, + farm: "special", + address: content?.address, + }; + } else { + const masterchef = await MasterChefV2Contract( + MASTERCHEFV2ADDRESSES[chainId as number], + library + ); + const LPInstance = await LiquidityPairInstance( + content.address, + library + ); + const reserves = await getLpTokenReserve(content.address); + const totalStable = reserves + ? BUSD[chainId as number] === reserves.tokenAddress0 || + USDT[chainId as number] === reserves.tokenAddress0 || + USDC[chainId as number] === reserves.tokenAddress0 + ? ethers.utils.formatUnits( + reserves.reserves0.toString(), + reserves.decimals0 + ) + : ethers.utils.formatUnits( + reserves.reserves1.toString(), + reserves.decimals1 + ) + : "1"; + + const rgpPrice = await calculateRigelPrice(); + + const [token0, token1] = await Promise.all([ + getERC20Token(reserves && reserves.tokenAddress0, library), + getERC20Token(reserves && reserves.tokenAddress1, library), ]); - const tokenStaked = await userInfo.amount; - return { - id: content.id, - img: "rgp.svg", - deposit: content.deposit, - earn: "RGP", - type: "LP", - totalLiquidity, - APY, - tokenStaked: [ - `${content.symbol0}-${content.symbol1}`, - ethers.utils.formatEther(tokenStaked.toString()), - ], - RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), - availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), - poolAllowance: ethers.utils.formatEther(allowance.toString()), - address: content.address, - }; + const [symbol0, symbol1] = await Promise.all([ + token0.symbol(), + token1.symbol(), + ]); + + const totalRGP = reserves + ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 + ? reserves.reserves0.toString() + : reserves.reserves1.toString() + : "1"; + + const totalLiquidity = + symbol0 === "BUSD" || + symbol1 === "BUSD" || + symbol0 === "USDT" || + symbol1 === "USDT" || + symbol0 === "USDC" || + symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; + + const [poolInfo, totalAllocPoint] = await Promise.all([ + masterchef.poolInfo(content.id), + masterchef.totalAllocPoint(), + ]); + const allocPoint = await poolInfo.allocPoint; + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint.toString())) * + reward; + const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; + const [tokenEarned, userInfo, FarmTokenBalance, allowance] = + await Promise.all([ + masterchef.pendingRigel(content.id, account), + masterchef.userInfo(content.id, account), + LPInstance.balanceOf(account), + LPInstance.allowance( + account, + MASTERCHEFV2ADDRESSES[chainId as number] + ), + ]); + const tokenStaked = await userInfo.amount; + + return { + id: content.id, + img: "rgp.svg", + deposit: content.deposit, + earn: "RGP", + type: "LP", + totalLiquidity, + APY, + tokenStaked: [ + `${content.symbol0}-${content.symbol1}`, + ethers.utils.formatEther(tokenStaked.toString()), + ], + RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), + availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), + poolAllowance: ethers.utils.formatEther(allowance.toString()), + address: content.address, + farm: content?.farm, + }; + } } catch (err) { console.log(err); } }; - useMemo(async () => { if (data !== undefined && account) { if (reload) { setLoadingState(true); - let newArray = - section === "search" - ? searchSection.newSearchResult !== undefined - ? [...searchSection.newSearchResult] - : [...searchSection.searchResult] - : section === "filter" - ? searchSection.newFilterResult !== undefined - ? [...searchSection.newFilterResult] - : [...searchSection.filterResult] - : searchSection.content !== undefined - ? [...searchSection.content] - : [...data.contents]; + let newArray = [...data]; const updatedFarm = await calculateLiquidityAndApy( chainId === 137 || chainId === 80001 @@ -353,15 +420,17 @@ interface FetchYieldFarmDetails { section: string; loading: boolean; setLoading: React.Dispatch>; + reload: boolean; } export const useFetchYieldFarmDetails = ({ content, section, loading, - setLoading + setLoading, + reload, }: FetchYieldFarmDetails) => { - const data = useFarmData(); + const data = useFarmData(content); const searchSection = useSelector((state) => state.farming); const { account, chainId, library } = useWeb3React(); // const [loading, setLoading] = useState(true); @@ -371,11 +440,15 @@ export const useFetchYieldFarmDetails = ({ const handleUpdateFarms = useCallback( (value) => { dispatch( - section === "filter" - ? updateNewFilterResult({ farmData: value }) - : section === "search" - ? updateNewSearchResult({ farmData: value }) - : updateYieldFarmDetails({ value }) + content?.farm === "lp" + ? updateLpFarm(value) + : content?.farm === "quick" + ? updateQuickSwapFarm(value) + : content?.farm === "stable" + ? updateStableFarm(value) + : content?.farm === "special" + ? updateSpecialPool(value) + : null ); }, [dispatch] @@ -505,93 +578,147 @@ export const useFetchYieldFarmDetails = ({ const calculateLiquidityAndApy = async (reward: number | undefined) => { try { - const masterchef = await MasterChefV2Contract( - MASTERCHEFV2ADDRESSES[chainId as number], - library - ); - const LPInstance = await LiquidityPairInstance(content.address, library); - const reserves = await getLpTokenReserve(content.address); - const totalStable = reserves - ? BUSD[chainId as number] === reserves.tokenAddress0 || - USDT[chainId as number] === reserves.tokenAddress0 || - USDC[chainId as number] === reserves.tokenAddress0 - ? ethers.utils.formatUnits( - reserves.reserves0.toString(), - reserves.decimals0 - ) - : ethers.utils.formatUnits( - reserves.reserves1.toString(), - reserves.decimals1 - ) - : "1"; - - const rgpPrice = await calculateRigelPrice(); - - const [token0, token1] = await Promise.all([ - getERC20Token(reserves && reserves.tokenAddress0, library), - getERC20Token(reserves && reserves.tokenAddress1, library), - ]); + if (content?.farm === "special") { + const specialPool = await RGPSpecialPool2(content?.address, library); - const [symbol0, symbol1] = await Promise.all([ - token0.symbol(), - token1.symbol(), - ]); + const token = await getERC20Token( + RGPADDRESSES[chainId as number], + library + ); - const totalRGP = reserves - ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 - ? reserves.reserves0.toString() - : reserves.reserves1.toString() - : "1"; - - const totalLiquidity = - symbol0 === "BUSD" || - symbol1 === "BUSD" || - symbol0 === "USDT" || - symbol1 === "USDT" || - symbol0 === "USDC" || - symbol1 === "USDC" - ? parseFloat(totalStable) * 2 - : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; - - const [poolInfo, totalAllocPoint] = await Promise.all([ - masterchef.poolInfo(content.id), - masterchef.totalAllocPoint(), - ]); - const allocPoint = await poolInfo.allocPoint; - const poolReward = - (parseFloat(allocPoint.toString()) / - parseFloat(totalAllocPoint.toString())) * - reward; - const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; - const [tokenEarned, userInfo, FarmTokenBalance, allowance] = - await Promise.all([ - masterchef.pendingRigel(content.id, account), - masterchef.userInfo(content.id, account), - LPInstance.balanceOf(account), - LPInstance.allowance( - account, - MASTERCHEFV2ADDRESSES[chainId as number] + const [amountStaked, allowance, balance] = await Promise.all([ + specialPool.userInfo(account), + token.allowance(account, RGPSPECIALPOOLADDRESSES2[chainId as number]), + token.balanceOf(account), + ]); + + return { + id: content?.id, + img: "rgp.svg", + // deposit: 'RGP', + deposit: "RGP", + earn: "RGP", + type: "RGP", + ARYValue: content?.ARYValue, + totalLiquidity: content?.totalLiquidity, + tokensStaked: [ + "RGP", + parseFloat( + ethers.utils.formatEther(amountStaked?._amountStaked.toString()) + ), + ], + RGPEarned: parseFloat( + ethers.utils.formatEther(amountStaked?._userReward.toString()) ), + availableToken: parseFloat( + ethers.utils.formatEther(balance.toString()) + ), + inflationPerDay: 0, + tokenPrice: content?.rgpPrice, + totalVolumePerPool: 0, + farmingFee: 0, + pId: content?.pId, + poolAllowance: parseFloat( + ethers.utils.formatEther(allowance.toString()) + ), + poolVersion: content?.poolVersion, + version: content?.version, + farm: "special", + address: content?.address, + }; + } else { + const masterchef = await MasterChefV2Contract( + MASTERCHEFV2ADDRESSES[chainId as number], + library + ); + const LPInstance = await LiquidityPairInstance( + content.address, + library + ); + const reserves = await getLpTokenReserve(content.address); + const totalStable = reserves + ? BUSD[chainId as number] === reserves.tokenAddress0 || + USDT[chainId as number] === reserves.tokenAddress0 || + USDC[chainId as number] === reserves.tokenAddress0 + ? ethers.utils.formatUnits( + reserves.reserves0.toString(), + reserves.decimals0 + ) + : ethers.utils.formatUnits( + reserves.reserves1.toString(), + reserves.decimals1 + ) + : "1"; + + const rgpPrice = await calculateRigelPrice(); + + const [token0, token1] = await Promise.all([ + getERC20Token(reserves && reserves.tokenAddress0, library), + getERC20Token(reserves && reserves.tokenAddress1, library), ]); - const tokenStaked = await userInfo.amount; - return { - id: content.id, - img: "rgp.svg", - deposit: content.deposit, - earn: "RGP", - type: "LP", - totalLiquidity, - APY, - tokenStaked: [ - `${content.symbol0}-${content.symbol1}`, - ethers.utils.formatEther(tokenStaked.toString()), - ], - RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), - availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), - poolAllowance: ethers.utils.formatEther(allowance.toString()), - address: content.address, - }; + const [symbol0, symbol1] = await Promise.all([ + token0.symbol(), + token1.symbol(), + ]); + + const totalRGP = reserves + ? RGPADDRESSES[chainId as number] === reserves.tokenAddress0 + ? reserves.reserves0.toString() + : reserves.reserves1.toString() + : "1"; + + const totalLiquidity = + symbol0 === "BUSD" || + symbol1 === "BUSD" || + symbol0 === "USDT" || + symbol1 === "USDT" || + symbol0 === "USDC" || + symbol1 === "USDC" + ? parseFloat(totalStable) * 2 + : parseFloat(ethers.utils.formatEther(totalRGP)) * rgpPrice * 2; + + const [poolInfo, totalAllocPoint] = await Promise.all([ + masterchef.poolInfo(content.id), + masterchef.totalAllocPoint(), + ]); + const allocPoint = await poolInfo.allocPoint; + const poolReward = + (parseFloat(allocPoint.toString()) / + parseFloat(totalAllocPoint.toString())) * + reward; + const APY = (rgpPrice * poolReward * 365 * 100) / totalLiquidity; + const [tokenEarned, userInfo, FarmTokenBalance, allowance] = + await Promise.all([ + masterchef.pendingRigel(content.id, account), + masterchef.userInfo(content.id, account), + LPInstance.balanceOf(account), + LPInstance.allowance( + account, + MASTERCHEFV2ADDRESSES[chainId as number] + ), + ]); + const tokenStaked = await userInfo.amount; + + return { + id: content.id, + img: "rgp.svg", + deposit: content.deposit, + earn: "RGP", + type: "LP", + totalLiquidity, + APY, + tokenStaked: [ + `${content.symbol0}-${content.symbol1}`, + ethers.utils.formatEther(tokenStaked.toString()), + ], + RGPEarned: ethers.utils.formatEther(tokenEarned.toString()), + availableToken: ethers.utils.formatEther(FarmTokenBalance.toString()), + poolAllowance: ethers.utils.formatEther(allowance.toString()), + address: content.address, + farm: content?.farm, + }; + } } catch (err) { console.log(err); } @@ -600,18 +727,7 @@ export const useFetchYieldFarmDetails = ({ useMemo(async () => { if (data !== undefined && account) { setLoading(true); - let newArray = - section === "search" - ? searchSection.newSearchResult !== undefined - ? [...searchSection.newSearchResult] - : [...searchSection.searchResult] - : section === "filter" - ? searchSection.newFilterResult !== undefined - ? [...searchSection.newFilterResult] - : [...searchSection.filterResult] - : searchSection.content !== undefined - ? [...searchSection.content] - : [...data.contents]; + let newArray = [...data]; const updatedFarm = await calculateLiquidityAndApy( chainId === 137 || chainId === 80001 @@ -622,6 +738,7 @@ export const useFetchYieldFarmDetails = ({ ? 1343.220833 : undefined ); + const index = newArray.findIndex((item) => item.id === content.id); newArray[index] = updatedFarm; @@ -632,21 +749,21 @@ export const useFetchYieldFarmDetails = ({ setLoading(false); } - }, []); + }, [reload]); return { loading }; }; interface productFarmState { content: { - feature:string, - percentageProfitShare:string, - profitTimeLine:string, - totalLiquidity:string, - estimatedTotalProfit:string, - pid:number, - deposit:string, - poolAllowance: "", - type:string + feature: string; + percentageProfitShare: string; + profitTimeLine: string; + totalLiquidity: string; + estimatedTotalProfit: string; + pid: number; + deposit: string; + poolAllowance: ""; + type: string; }; loading: boolean; setLoading: React.Dispatch>; @@ -654,53 +771,55 @@ interface productFarmState { export const useProductFarmDetails = ({ content, loading, - setLoading -}:productFarmState) =>{ + setLoading, +}: productFarmState) => { const { account, chainId, library } = useWeb3React(); -const getUserValue = async ()=> { - const productFarm = await productStakingContract( - PRODUCTSTAKINGADDRESSES[chainId as number], - library - ); - const [ userInfo, FarmTokenBalance] = - await Promise.all([ - productFarm.userInfo(account), - productFarm.userData(account), - ]); - const tokenStaked = await FarmTokenBalance.tokenQuantity - console.log({tokenStaked},tokenStaked.toString(),Web3.utils.fromWei(tokenStaked.toString())) - - return { - feature:"AutoTrade", - percentageProfitShare:"25%", - profitTimeLine:"6 months", - totalLiquidity:"188839", - estimatedTotalProfit:"929020003", - deposit: "RGP", - pid:93903, - poolAllowance: "", - type:"AT", - tokenStaked: Web3.utils.fromWei(tokenStaked.toString()) - }; -} - -useMemo(async ()=>{ - let response =await getUserValue() + const getUserValue = async () => { + const productFarm = await productStakingContract( + PRODUCTSTAKINGADDRESSES[chainId as number], + library + ); + const [userInfo, FarmTokenBalance] = await Promise.all([ + productFarm.userInfo(account), + productFarm.userData(account), + ]); + const tokenStaked = await FarmTokenBalance.tokenQuantity; + console.log( + { tokenStaked }, + tokenStaked.toString(), + Web3.utils.fromWei(tokenStaked.toString()) + ); + + return { + feature: "AutoTrade", + percentageProfitShare: "25%", + profitTimeLine: "6 months", + totalLiquidity: "188839", + estimatedTotalProfit: "929020003", + deposit: "RGP", + pid: 93903, + poolAllowance: "", + type: "AT", + tokenStaked: Web3.utils.fromWei(tokenStaked.toString()), + }; + }; - updateProductFarmDetails({value:[response]}) + useMemo(async () => { + let response = await getUserValue(); -setLoading(false) -},[]) -return {loading} + updateProductFarmDetails({ value: [response] }); -} + setLoading(false); + }, []); + return { loading }; +}; export const useUpdateProductFarm = ({ reload, setReload, content, section, }: updateFarmInterface) => { - const data = useFarmData(); + const data = useFarmData(content); const searchSection = useSelector((state) => state.farming); const { account, chainId, library } = useWeb3React(); diff --git a/src/utils/hooks/useFarm.ts b/src/utils/hooks/useFarm.ts index 66d8bdb7..01860ec7 100644 --- a/src/utils/hooks/useFarm.ts +++ b/src/utils/hooks/useFarm.ts @@ -12,6 +12,7 @@ import { MASTERCHEFNEWLPADDRESSES, SMARTSWAPLP_TOKEN3ADDRESSES, SYMBOLS, + RGPSPECIALPOOLADDRESSES2, } from "../addresses"; import LiquidityPairAbi from "../../utils/abis/smartSwapLPToken.json"; import ERC20TokenAbi from "../../utils/abis/erc20.json"; @@ -19,14 +20,17 @@ import smartFactoryAbi from "../../utils/abis/SmartSwapFactoryForSwap.json"; import { useSelector } from "react-redux"; import { RootState } from "../../state"; import { ethers } from "ethers"; -import { smartSwapLPTokenPoolThree } from "../Contracts"; +import { RGPSpecialPool2, smartSwapLPTokenPoolThree } from "../Contracts"; import smartswapLpTokenThreeAbi from "../abis/SmartSwapLPTokenThree.json"; import { updateLpFarm, updateQuickSwapFarm, + updateSpecialPool, updateStableFarm, } from "../../state/farm/actions"; import { useDispatch } from "react-redux"; +import { SupportedChainId } from "../../constants/chains"; +import { getERC20Token, useProvider } from "../utilsFunctions"; type FarmData = Array<{ id: number | undefined; @@ -42,7 +46,10 @@ type FarmData = Array<{ }>; export const useFetchFarm = () => { - const { account, library, chainId } = useWeb3React(); + const { account, library: lib, chainId } = useWeb3React(); + const { prov } = useProvider(); + const library = lib ? lib : prov; + const [loading, setLoading] = useState(true); const dispatch = useDispatch(); @@ -143,11 +150,7 @@ export const useFetchFarm = () => { APY, allocPoint: parseFloat(allocPoint.toString()), address: pools[i].poolAddress, - tokenStaked: [ - `${formatSymbol(reserves[i]?.symbol0)}-${formatSymbol( - reserves[i]?.symbol1 - )}`, - ], + farm: "lp", }); } } @@ -362,10 +365,6 @@ export const useFetchFarm = () => { const token0 = await multi.multiCall(token0Inputs); const token1 = await multi.multiCall(token1Inputs); - console.log(reserves[1]); - - console.log("token0", token0); - for (let i = 0; i < token0[1].length; i++) { symbol0Inputs.push({ interface: ERC20TokenAbi, @@ -430,8 +429,6 @@ export const useFetchFarm = () => { }); } - console.log("Lpreserves", LpReserves); - return LpReserves; } catch (err) { console.log(err); @@ -440,71 +437,74 @@ export const useFetchFarm = () => { useEffect(() => { const fetchPools = async () => { - if (account) { - try { - console.log("started"); - const multi = new MultiCall(library); + try { + setLoading(true); - const poolAddresses = []; + const multi = new MultiCall(library); - const rgpPrice = await calculateRigelPrice(); + const poolAddresses = []; + + const rgpPrice = await calculateRigelPrice(); + + const poolLength = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFV2ADDRESSES[chainId as number], + function: "poolLength", + }, + ]); - const poolLength = await multi.multiCall([ + for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { + const poolInfo = await multi.multiCall([ { interface: MasterChefAbi, - args: [], + args: [i], target: MASTERCHEFV2ADDRESSES[chainId as number], - function: "poolLength", + function: "poolInfo", }, ]); - console.log("poolLength", poolLength); - - for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { - const poolInfo = await multi.multiCall([ - { - interface: MasterChefAbi, - args: [i], - target: MASTERCHEFV2ADDRESSES[chainId as number], - function: "poolInfo", - }, - ]); - - poolAddresses.push({ - poolAddress: poolInfo[1][0]?.lpToken, - allocPoint: poolInfo[1][0]?.allocPoint, - }); - } - - const farm = await calculateLiquidityandApy( - poolAddresses, - rgpPrice, - ChainId === 137 || ChainId === 80001 - ? 2014.83125 - : ChainId === 56 || ChainId === 97 - ? 4300 - : ChainId === 42262 || ChainId === 42261 - ? 1343.220833 - : undefined - ); + poolAddresses.push({ + poolAddress: poolInfo[1][0]?.lpToken, + allocPoint: poolInfo[1][0]?.allocPoint, + }); + } - if (farm) { - dispatch(updateLpFarm(farm)); - } + const farm = await calculateLiquidityandApy( + poolAddresses, + rgpPrice, + ChainId === 137 || ChainId === 80001 + ? 2014.83125 + : ChainId === 56 || ChainId === 97 + ? 4300 + : ChainId === 42262 || ChainId === 42261 + ? 1343.220833 + : undefined + ); - console.log("useFarm", farm); - } catch (err) { - console.log(err); + if (farm) { + dispatch(updateLpFarm(farm)); } + + setLoading(false); + } catch (err) { + setLoading(false); + console.log(err); } }; fetchPools(); - }, [account, ChainId]); + }, [account, ChainId, library]); + + return { loading }; }; export const useFetchQuickSwap = () => { - const { account, library, chainId } = useWeb3React(); + const { account, library: lib, chainId } = useWeb3React(); + const { prov } = useProvider(); + const library = lib ? lib : prov; + const [loading, setLoading] = useState(true); const dispatch = useDispatch(); @@ -625,6 +625,7 @@ export const useFetchQuickSwap = () => { allocPoint: parseFloat(allocPoint.toString()), address: pools[i].poolAddress, LPLocked: newLiquidity.toFixed(2), + farm: "quick", }); } } @@ -849,9 +850,6 @@ export const useFetchQuickSwap = () => { const lockedSupplyInputs = []; for (let i = 0; i < pools.length; i++) { - console.log("before-anything", [ - MASTERCHEFNEWLPADDRESSES[ChainId as number][1], - ]); reservesInputs.push({ interface: LiquidityPairAbi, args: [], @@ -895,21 +893,14 @@ export const useFetchQuickSwap = () => { }); } - console.log("got here", pools); - const reserves = await multi.multiCall(reservesInputs); - console.log("reserves", reserves); const poolInfo = await multi.multiCall(poolInfoInputs); const token0 = await multi.multiCall(token0Inputs); const token1 = await multi.multiCall(token1Inputs); const totalSupply = await multi.multiCall(totalSupplyInputs); const lockedSupply = await multi.multiCall(lockedSupplyInputs); - console.log(reserves[1]); - - console.log("token0", token0); - for (let i = 0; i < token0[1].length; i++) { symbol0Inputs.push({ interface: ERC20TokenAbi, @@ -981,8 +972,6 @@ export const useFetchQuickSwap = () => { }); } - console.log("Lpreserves", LpReserves); - return LpReserves; } catch (err) { console.log(err); @@ -991,80 +980,80 @@ export const useFetchQuickSwap = () => { useEffect(() => { const fetchPools = async () => { - if (account) { - try { - console.log("started"); - const multi = new MultiCall(library); + try { + setLoading(true); - const poolAddresses = []; + const multi = new MultiCall(library); - const rgpPrice = await calculateRigelPrice(); + const poolAddresses = []; + + const rgpPrice = await calculateRigelPrice(); - const BNBPrice = await getBNBPrice(); + const BNBPrice = await getBNBPrice(); - const poolLength = await multi.multiCall([ + const poolLength = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], + function: "poolLength", + }, + ]); + + for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { + const poolInfo = await multi.multiCall([ { interface: MasterChefAbi, - args: [], + args: [i], target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], - function: "poolLength", + function: "poolInfo", }, ]); - console.log("poolLength", poolLength); - - for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { - const poolInfo = await multi.multiCall([ - { - interface: MasterChefAbi, - args: [i], - target: MASTERCHEFNEWLPADDRESSES[chainId as number][1], - function: "poolInfo", - }, - ]); - - console.log("before fail", poolInfo[1][0]); - - poolInfo[1][0]?.lpToken !== undefined && - poolAddresses.push({ - pid: i, - poolAddress: poolInfo[1][0]?.lpToken, - allocPoint: poolInfo[1][0]?.allocPoint, - }); - } - - console.log("before fail", poolAddresses); - - const farm = await calculateLiquidityandApy( - poolAddresses, - rgpPrice, - BNBPrice, - ChainId === 137 || ChainId === 80001 - ? 2014.83125 - : ChainId === 56 || ChainId === 97 - ? 4300 - : ChainId === 42262 || ChainId === 42261 - ? 1343.220833 - : undefined - ); + poolInfo[1][0]?.lpToken !== undefined && + poolAddresses.push({ + pid: i, + poolAddress: poolInfo[1][0]?.lpToken, + allocPoint: poolInfo[1][0]?.allocPoint, + }); + } - if (farm) { - dispatch(updateQuickSwapFarm(farm)); - } + const farm = await calculateLiquidityandApy( + poolAddresses, + rgpPrice, + BNBPrice, + ChainId === 137 || ChainId === 80001 + ? 2014.83125 + : ChainId === 56 || ChainId === 97 + ? 4300 + : ChainId === 42262 || ChainId === 42261 + ? 1343.220833 + : undefined + ); - console.log("useFarm-quick", farm); - } catch (err) { - console.log(err); + if (farm) { + dispatch(updateQuickSwapFarm(farm)); } + + setLoading(false); + } catch (err) { + console.log(err); + setLoading(false); } }; fetchPools(); - }, [account, ChainId]); + }, [account, ChainId, library]); + + return { loading }; }; export const useFetchStable = () => { - const { account, library, chainId } = useWeb3React(); + const { account, library: lib, chainId } = useWeb3React(); + const { prov } = useProvider(); + const library = lib ? lib : prov; + + const [loading, setLoading] = useState(true); const dispatch = useDispatch(); const ChainId = useSelector((state) => state.chainId.chainId); @@ -1184,11 +1173,7 @@ export const useFetchStable = () => { allocPoint: parseFloat(allocPoint.toString()), address: pools[i].poolAddress, LPLocked: newLiquidity.toFixed(2), - tokenStaked: [ - `${await formatSymbol( - reserves[i]?.symbol0 - )}-${await formatSymbol(reserves[i]?.symbol1)}`, - ], + farm: "stable", }); } } @@ -1456,21 +1441,14 @@ export const useFetchStable = () => { }); } - console.log("got here", pools); - const reserves = await multi.multiCall(reservesInputs); - console.log("reserves", reserves); const poolInfo = await multi.multiCall(poolInfoInputs); const token0 = await multi.multiCall(token0Inputs); const token1 = await multi.multiCall(token1Inputs); const totalSupply = await multi.multiCall(totalSupplyInputs); const lockedSupply = await multi.multiCall(lockedSupplyInputs); - console.log(reserves[1]); - - console.log("token0", token0); - for (let i = 0; i < token0[1].length; i++) { symbol0Inputs.push({ interface: ERC20TokenAbi, @@ -1534,16 +1512,10 @@ export const useFetchStable = () => { symbol1: symbol1[1][i], totalSupply: totalSupply[1][i], lockedSupply: lockedSupply[1][i], - tokenStaked: [ - `${await formatSymbol(symbol0[1][i])}-${await formatSymbol( - symbol1[1][i] - )}`, - ], + farm: "stable", }); } - console.log("Lpreserves", LpReserves); - return LpReserves; } catch (err) { console.log(err); @@ -1552,70 +1524,298 @@ export const useFetchStable = () => { useEffect(() => { const fetchPools = async () => { - if (account) { - try { - console.log("started"); - const multi = new MultiCall(library); + try { + setLoading(true); - const poolAddresses = []; + const multi = new MultiCall(library); - const rgpPrice = await calculateRigelPrice(); + const poolAddresses = []; - const BNBPrice = await getBNBPrice(); + const rgpPrice = await calculateRigelPrice(); - const poolLength = await multi.multiCall([ + const BNBPrice = await getBNBPrice(); + + const poolLength = await multi.multiCall([ + { + interface: MasterChefAbi, + args: [], + target: MASTERCHEFNEWLPADDRESSES[chainId as number][2], + function: "poolLength", + }, + ]); + + for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { + const poolInfo = await multi.multiCall([ { interface: MasterChefAbi, - args: [], + args: [i], target: MASTERCHEFNEWLPADDRESSES[chainId as number][2], - function: "poolLength", + function: "poolInfo", }, ]); - console.log("poolLength", poolLength); + poolInfo[1][0]?.lpToken !== undefined && + poolAddresses.push({ + pid: i, + poolAddress: poolInfo[1][0]?.lpToken, + allocPoint: poolInfo[1][0]?.allocPoint, + }); + } - for (let i = 0; i < parseFloat(poolLength[1][0].toString()); i++) { - const poolInfo = await multi.multiCall([ - { - interface: MasterChefAbi, - args: [i], - target: MASTERCHEFNEWLPADDRESSES[chainId as number][2], - function: "poolInfo", - }, - ]); - - poolInfo[1][0]?.lpToken !== undefined && - poolAddresses.push({ - pid: i, - poolAddress: poolInfo[1][0]?.lpToken, - allocPoint: poolInfo[1][0]?.allocPoint, - }); - } + const farm = await calculateLiquidityandApy( + poolAddresses, + rgpPrice, + BNBPrice, + ChainId === 137 || ChainId === 80001 + ? 2014.83125 + : ChainId === 56 || ChainId === 97 + ? 4300 + : ChainId === 42262 || ChainId === 42261 + ? 1343.220833 + : undefined + ); + + if (farm) { + dispatch(updateStableFarm(farm)); + } + setLoading(false); + } catch (err) { + console.log(err); + setLoading(false); + } + }; + + fetchPools(); + }, [account, ChainId, library]); + + return { loading }; +}; + +export const useSpecialPool = () => { + const { account, library } = useWeb3React(); + const ChainId = useSelector((state) => state.chainId.chainId); + + const { prov } = useProvider(); + const lib = library ? library : prov; + const dispatch = useDispatch(); - const farm = await calculateLiquidityandApy( - poolAddresses, - rgpPrice, - BNBPrice, - ChainId === 137 || ChainId === 80001 - ? 2014.83125 - : ChainId === 56 || ChainId === 97 - ? 4300 - : ChainId === 42262 || ChainId === 42261 - ? 1343.220833 - : undefined + useEffect(() => { + const fetch = async () => { + try { + if ( + ChainId !== SupportedChainId.OASISMAINNET && + ChainId !== SupportedChainId.OASISTEST + ) { + const specialPool = await RGPSpecialPool2( + RGPSPECIALPOOLADDRESSES2[ChainId as number], + lib + ); + const rgp = await getERC20Token(RGPADDRESSES[ChainId as number], lib); + const RGPBallance = await rgp.balanceOf( + RGPSPECIALPOOLADDRESSES2[ChainId as number] ); - if (farm) { - dispatch(updateStableFarm(farm)); - } + const calculateRigelPrice = async () => { + try { + const multi = new MultiCall(library); + let rgpPrice; + + if (ChainId === 56 || ChainId === 97) { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [ + RGPADDRESSES[ChainId as number], + BUSD[ChainId as number], + ], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalBUSD: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === BUSD[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === BUSD[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + + rgpPrice = totalBUSD / totalRGP; + } else { + const pairAddress = await multi.multiCall([ + { + interface: smartFactoryAbi, + args: [ + RGPADDRESSES[ChainId as number], + USDT[ChainId as number], + ], + target: SMARTSWAPFACTORYADDRESSES[ChainId as number], + function: "getPair", + }, + ]); + + const token0Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token0", + }, + ]); + const token1Address = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "token1", + }, + ]); + const decimal0 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token0Address[1][0], + function: "decimals", + }, + ]); + + const decimal1 = await multi.multiCall([ + { + interface: ERC20TokenAbi, + args: [], + target: token1Address[1][0], + function: "decimals", + }, + ]); + const reserves = await multi.multiCall([ + { + interface: LiquidityPairAbi, + args: [], + target: pairAddress[1][0], + function: "getReserves", + }, + ]); + const totalUSDT: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][0] + : reserves[1][0][1], + token0Address[1][0] === USDT[ChainId as number] + ? decimal0[1][0] + : decimal1[1][0] + ); + const totalRGP: number | any = ethers.utils.formatUnits( + token0Address[1][0] === USDT[ChainId as number] + ? reserves[1][0][1] + : reserves[1][0][0], + token0Address[1][0] === USDT[ChainId as number] + ? decimal1[1][0] + : decimal0[1][0] + ); + rgpPrice = totalUSDT / totalRGP; + } + + return rgpPrice; + } catch (err) { + console.log(err); + } + }; + + const rgpPrice = await calculateRigelPrice(); + + const RGPLiquidity = + parseFloat(ethers.utils.formatUnits(RGPBallance)) * + (rgpPrice as number); - console.log("useFarm-quick", farm); - } catch (err) { - console.log(err); + const yeaRate = await specialPool.YEAR_RATE(); + + //this is temporal + + dispatch( + updateSpecialPool([ + { + id: "0", + img: "rgp.svg", + // deposit: 'RGP', + deposit: "RGP", + earn: "RGP", + type: "RGP", + ARYValue: ethers.utils.formatUnits(yeaRate), + totalLiquidity: RGPLiquidity, + tokensStaked: ["RGP", "0"], + RGPEarned: "0", + availableToken: "", + inflationPerDay: 0, + tokenPrice: rgpPrice, + totalVolumePerPool: 0, + farmingFee: 0, + pId: 10793, + poolAllowance: "", + poolVersion: "2", + version: "v2", + farm: "special", + address: RGPSPECIALPOOLADDRESSES2[ChainId as number], + }, + ]) + ); } + } catch (err) { + console.log(err); } }; - fetchPools(); - }, [account, ChainId]); + fetch(); + }, [ChainId, account, lib]); };