From d0c000a4f346ecf93c33e8c70935b36c27255762 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 16 Aug 2023 15:51:19 +0530 Subject: [PATCH 01/27] removed manage & addliq btn from unsupported farms --- src/components/Common/Layout/evmUtils.tsx | 8 +++----- src/components/FarmPage/index.tsx | 4 ++++ src/utils/farmListMethods.ts | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/components/Common/Layout/evmUtils.tsx b/src/components/Common/Layout/evmUtils.tsx index fde7c0e..06c81a6 100644 --- a/src/components/Common/Layout/evmUtils.tsx +++ b/src/components/Common/Layout/evmUtils.tsx @@ -1,9 +1,7 @@ -interface SupportedPoolsType { - [pool: string]: string[]; -} - // Pools which are supported for interacting in current version -export const supportedPools: SupportedPoolsType = { +export const supportedPools: { + [pool: string]: string[]; +} = { moonriver: ["zenlink", "solarbeam", "sushiswap"], moonbeam: ["curve", "zenlink", "stellaswap", "solarflare", "beamswap"], astar: ["zenlink", "sirius", "arthswap"], diff --git a/src/components/FarmPage/index.tsx b/src/components/FarmPage/index.tsx index 8036409..4b9f7d2 100644 --- a/src/components/FarmPage/index.tsx +++ b/src/components/FarmPage/index.tsx @@ -25,6 +25,7 @@ import MetaTags from "@components/Common/metaTags/MetaTags"; import useSpecificFarm from "@hooks/useSpecificFarm"; import { fetchListicleFarms } from "@utils/api"; import { + checkIfPoolSupported, farmURL, formatFarmType, formatFirstLetter, @@ -156,6 +157,8 @@ const FarmPage: NextPage = () => { const safetyScore = parseFloat((farm?.safetyScore * 10).toFixed(1)); const safetyScoreColor = useSafetyscoreColor(safetyScore); + const isSupported = checkIfPoolSupported(farm); + return !isLoading && idQuery ? (
@@ -189,6 +192,7 @@ const FarmPage: NextPage = () => {
)} {!hasPosition && + isSupported && (farm?.chain.toLowerCase() == "mangata kusama" || farm?.protocol.toLowerCase() == "mangata x" ? isConnectedDot diff --git a/src/utils/farmListMethods.ts b/src/utils/farmListMethods.ts index a47bba1..7686eab 100644 --- a/src/utils/farmListMethods.ts +++ b/src/utils/farmListMethods.ts @@ -97,7 +97,8 @@ export function getWalletInstallUrl(walletName: string): string { } } -export function checkIfPoolSupported(farm: FarmType) { +export function checkIfPoolSupported(farm: FarmType): boolean { + if (farm?.farmType == "SingleStaking") return false; const protocols = supportedPools[farm.chain.toLocaleLowerCase()]; if (!!protocols) return protocols.includes(farm.protocol.toLowerCase()); return false; From f6b8114c6eef1d77e3c0b40ff006080680277d8c Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 16 Aug 2023 17:02:06 +0530 Subject: [PATCH 02/27] Gas estimation loading state --- .../AddLiquidityModal/AddSectionMangata.tsx | 18 ++++++++++----- .../AddLiquidityModal/AddSectionStable.tsx | 22 +++++++++++-------- .../AddLiquidityModal/AddSectionStandard.tsx | 22 +++++++++++-------- .../RemoveSectionStable.tsx | 18 +++++++++------ .../RemoveSectionStandard.tsx | 18 +++++++++------ src/components/Library/StakingModal/index.tsx | 18 +++++++++------ .../Library/UnstakingModal/index.tsx | 18 +++++++++------ src/hooks/useGasEstimation.ts | 17 ++++++++++++-- 8 files changed, 97 insertions(+), 54 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx b/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx index c73ac37..6fb7706 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx @@ -65,6 +65,7 @@ const AddSectionMangata: FC = () => { // const [lpBalance, setLpBalance] = useState(null); const [lpBalance, setLpBalance] = useState(0); const [fees, setFees] = useState(0); + const [isErrorFees, setIsErrorFees] = useState(false); const [selectedFarm, setSelectedFarm] = useAtom(selectedFarmAtom); const [isSlippageModalOpen, setIsSlippageModalOpen] = useAtom( @@ -376,6 +377,7 @@ const AddSectionMangata: FC = () => { setFees(parseFloat(fees)); } catch (error) { console.log("Error while fetching Fees", error); + setIsErrorFees(true); } }; @@ -1048,12 +1050,16 @@ const AddSectionMangata: FC = () => { >
Estimated Gas Fees: -

- - {fees.toLocaleString("en-US") ?? 0} MGX - - ${(fees * mgxPrice).toFixed(5)} -

+ {fees === 0 && !isErrorFees ? ( +

Estimating Gas...

+ ) : ( +

+ + {fees.toLocaleString("en-US") ?? 0} MGX + + ${(fees * mgxPrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index 3593ef4..9013544 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -441,7 +441,7 @@ const AddSectionStable: FC = () => { const ConfirmStep = () => { // Gas estimate - const { gasEstimate } = useGasEstimation( + const { gasEstimate, isError } = useGasEstimation( farm!.router, 1, 0, @@ -528,7 +528,7 @@ const AddSectionStable: FC = () => {
gasEstimate + fixedAmtNum(nativeBal?.formatted) > gasEstimate ? "bg-[#C0F9C9]" : "bg-[#FFB7B7]" )} @@ -536,19 +536,23 @@ const AddSectionStable: FC = () => {
gasEstimate + fixedAmtNum(nativeBal?.formatted) > gasEstimate ? "bg-[#ECFFEF]" : "bg-[#FFE8E8]" )} >
Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

+ {gasEstimate === 0 && !isError ? ( +

Estimating Gas...

+ ) : ( +

+ + {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + + ${(gasEstimate * nativePrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index a8196a1..482a1f0 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -89,8 +89,8 @@ const AddSectionStandard: FC = () => { const [positions, setPositions] = useAtom(positionsAtom); const [lpTokenPricesMap] = useAtom(lpTokenPricesAtom); const [tokenPricesMap] = useAtom(tokenPricesAtom); - const [, setIsEvmPosLoading] = useAtom(evmPosLoadingAtom); - const [lpUpdated, setLpUpdated] = useAtom(lpUpdatedAtom); + // const [, setIsEvmPosLoading] = useAtom(evmPosLoadingAtom); + // const [lpUpdated, setLpUpdated] = useAtom(lpUpdatedAtom); const [SLIPPAGE] = useAtom(slippageAtom); const [txnHash, setTxnHash] = useState(""); @@ -917,7 +917,7 @@ const AddSectionStandard: FC = () => { const ConfirmStep = () => { // Gas estimate - const { gasEstimate } = useGasEstimation( + const { gasEstimate, isError } = useGasEstimation( selectedFarm!.router, 1, 0, @@ -1052,12 +1052,16 @@ const AddSectionStandard: FC = () => { >
Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

+ {gasEstimate === 0 && !isError ? ( +

Estimating Gas...

+ ) : ( +

+ + {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + + ${(gasEstimate * nativePrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index e777ff7..01297ae 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -595,7 +595,7 @@ const RemoveSectionStable: FC = () => { ) as any ); // Gas estimate - const { gasEstimate } = useGasEstimation( + const { gasEstimate, isError } = useGasEstimation( farm!.router, 1, 1, @@ -684,12 +684,16 @@ const RemoveSectionStable: FC = () => { >
Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

+ {gasEstimate === 0 && !isError ? ( +

Estimating Gas...

+ ) : ( +

+ + {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + + ${(gasEstimate * nativePrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx index 2911cfe..c52cc0e 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx @@ -609,7 +609,7 @@ const RemoveSectionStandard = () => { const ConfirmStep = () => { // Gas estimate - const { gasEstimate } = useGasEstimation( + const { gasEstimate, isError } = useGasEstimation( farm!.router, 1, 1, @@ -720,12 +720,16 @@ const RemoveSectionStandard = () => { >
Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

+ {gasEstimate === 0 && !isError ? ( +

Estimating Gas...

+ ) : ( +

+ + {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + + ${(gasEstimate * nativePrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index 0a5f091..66dc4d0 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -435,7 +435,7 @@ const StakingModal = () => { const ConfirmStep = () => { // Gas estimate - const { gasEstimate } = useGasEstimation( + const { gasEstimate, isError } = useGasEstimation( farm!.chef, 0, 2, @@ -505,12 +505,16 @@ const StakingModal = () => { >
Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

+ {gasEstimate === 0 && !isError ? ( +

Estimating Gas...

+ ) : ( +

+ + {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + + ${(gasEstimate * nativePrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/components/Library/UnstakingModal/index.tsx b/src/components/Library/UnstakingModal/index.tsx index 00b7866..8491c57 100644 --- a/src/components/Library/UnstakingModal/index.tsx +++ b/src/components/Library/UnstakingModal/index.tsx @@ -401,7 +401,7 @@ const UnstakingModal = () => { const ConfirmStep = () => { // Gas estimate - const { gasEstimate } = useGasEstimation( + const { gasEstimate, isError } = useGasEstimation( farm!.chef, 0, 3, @@ -466,12 +466,16 @@ const UnstakingModal = () => { >
Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

+ {gasEstimate === 0 && !isError ? ( +

Estimating Gas...

+ ) : ( +

+ + {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + + ${(gasEstimate * nativePrice).toFixed(5)} +

+ )}
Slippage Tolerance: {SLIPPAGE}% diff --git a/src/hooks/useGasEstimation.ts b/src/hooks/useGasEstimation.ts index 74951d4..a19e3f6 100644 --- a/src/hooks/useGasEstimation.ts +++ b/src/hooks/useGasEstimation.ts @@ -69,7 +69,11 @@ const useGasEstimation = ( farmition: FarmType | PortfolioPositionType, account: Address, args: Array -) => { +): { + gasEstimate: number; + // isLoading: boolean; + isError: boolean; +} => { // const { chain } = useNetwork(); // const publicClient = usePublicClient({ chainId: 1284 }); const publicClient = usePublicClient(); @@ -79,6 +83,8 @@ const useGasEstimation = ( // }); const [gasEstimateAmount, setGasEstimateAmount] = useState(0); const [gasPrice, setGasPrice] = useState(0); + // const [isLoading, setIsLoading] = useState(false); + const [isError, setIsError] = useState(false); // if any arg is 0 if ( @@ -92,6 +98,8 @@ const useGasEstimation = ( console.log("arg0"); return { gasEstimate: 0, + // isLoading: false, + isError: false, }; } else if ( farmition.farmType == "StableAmm" && @@ -103,6 +111,8 @@ const useGasEstimation = ( console.log("arg0"); return { gasEstimate: 0, + // isLoading: false, + isError: false, }; // } else { } else { @@ -120,6 +130,7 @@ const useGasEstimation = ( setGasEstimateAmount(Number(res)); }); } catch (error) { + setIsError(true); setGasEstimateAmount(0); console.log("Error: Estimating Gas", error); } @@ -131,6 +142,7 @@ const useGasEstimation = ( }); } catch (error) { setGasPrice(0); + setIsError(true); console.log("Error: Getting Gas Price", error); } @@ -142,9 +154,10 @@ const useGasEstimation = ( "gas", (gasEstimateAmount * gasPrice) / 10 ** 18 ); - return { gasEstimate: (gasEstimateAmount * gasPrice) / 10 ** 18, + // isLoading, + isError, }; } }; From 08307f3499e03d1eb8aa963f7457be9d0599b1a4 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 16 Aug 2023 21:20:29 +0530 Subject: [PATCH 03/27] charcter restrictions in inputs --- .../AddLiquidityModal/AddSectionMangata.tsx | 2 +- .../AddLiquidityModal/AddSectionStable.tsx | 2 +- .../AddLiquidityModal/AddSectionStandard.tsx | 15 ++++++++---- .../Library/AddLiquidityModal/TokenInput.tsx | 6 ++++- .../RemoveSectionMangata.tsx | 24 ++++++++----------- .../RemoveSectionStable.tsx | 19 ++++++++------- .../RemoveSectionStandard.tsx | 20 +++++++++------- src/components/Library/SlippageModal.tsx | 5 +++- src/components/Library/StakingModal/index.tsx | 20 +++++++++++----- .../Library/UnstakingModal/index.tsx | 20 +++++++++++----- 10 files changed, 82 insertions(+), 51 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx b/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx index 6fb7706..58c84b7 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx @@ -1051,7 +1051,7 @@ const AddSectionMangata: FC = () => {
Estimated Gas Fees: {fees === 0 && !isErrorFees ? ( -

Estimating Gas...

+

estimating gas...

) : (

diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index 9013544..78d0290 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -544,7 +544,7 @@ const AddSectionStable: FC = () => {

Estimated Gas Fees: {gasEstimate === 0 && !isError ? ( -

Estimating Gas...

+

estimating gas...

) : (

diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 482a1f0..35311b3 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -506,18 +506,23 @@ const AddSectionStandard: FC = () => { const handleChangeFirstTokenAmount = async ( e: React.ChangeEvent ) => { - setFirstTokenAmount(e.target.value); + const value = e.target.value; + // regex only let numerical values + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + setFirstTokenAmount(value); + } // update first amount based on second - updateSecondTokenAmount(parseFloat(e.target.value)); + updateSecondTokenAmount(parseFloat(value)); }; // update token values const handleChangeSecondTokenAmount = async ( e: React.ChangeEvent ) => { - setSecondTokenAmount(e.target.value); + const value = e.target.value; + setSecondTokenAmount(value); // update first amount based on second - updateFirstTokenAmount(parseFloat(e.target.value)); + updateFirstTokenAmount(parseFloat(value)); }; useEffect(() => { @@ -1053,7 +1058,7 @@ const AddSectionStandard: FC = () => {

Estimated Gas Fees: {gasEstimate === 0 && !isError ? ( -

Estimating Gas...

+

estimating gas...

) : (

diff --git a/src/components/Library/AddLiquidityModal/TokenInput.tsx b/src/components/Library/AddLiquidityModal/TokenInput.tsx index 7519c96..108de10 100644 --- a/src/components/Library/AddLiquidityModal/TokenInput.tsx +++ b/src/components/Library/AddLiquidityModal/TokenInput.tsx @@ -107,7 +107,11 @@ const TokenInput: React.FC = ({ value={inputMap[token?.address] ?? ""} onChange={(event) => { event.preventDefault(); - handleInput(token, event.target.value); + const value = event.target.value; + // regex for inputing decimals upto 10 digits + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + handleInput(token, value); + } }} ref={inputRef} onFocus={() => setFocusedInput(index)} diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx index 6e45959..eb5f3f3 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx @@ -237,10 +237,15 @@ const RemoveSectionMangata: FC = () => { const handlePercChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = parseFloat(event.target.value); - if ((value >= 0 && value <= 100) || event.target.value == "") { - setPercentage(event.target.value); - } else { - alert("Percentage must be between 0 & 100!"); + if ( + /^(?:[1-9][0-9]{0,1}|0|100)$/.test(event.target.value) || + event.target.value === "" + ) { + if ((value >= 0 && value <= 100) || event.target.value == "") { + setPercentage(event.target.value); + } else { + alert("Percentage must be between 0 & 100!"); + } } }; @@ -248,17 +253,8 @@ const RemoveSectionMangata: FC = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (parseFloat(value) >= 0 || value == "") { + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { setLpTokens(event.target.value); - } else { - alert("LP Amount can't be negative!"); - // toast({ - // position: "top", - // duration: 3000, - // render: () => ( - // - // ), - // }); } }; diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index 01297ae..70d9d2c 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -108,10 +108,15 @@ const RemoveSectionStable: FC = () => { const handlePercChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = parseFloat(event.target.value); - if ((value >= 0 && value <= 100) || event.target.value == "") { - setPercentage(event.target.value); - } else { - alert("Percentage must be between 0 & 100!"); + if ( + /^(?:[1-9][0-9]{0,1}|0|100)$/.test(event.target.value) || + event.target.value === "" + ) { + if ((value >= 0 && value <= 100) || event.target.value == "") { + setPercentage(event.target.value); + } else { + alert("Percentage must be between 0 & 100!"); + } } }; @@ -119,10 +124,8 @@ const RemoveSectionStable: FC = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (parseFloat(value) >= 0 || value == "") { + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { setLpTokens(event.target.value); - } else { - alert("LP Amount can't be negative!"); } }; @@ -685,7 +688,7 @@ const RemoveSectionStable: FC = () => {

Estimated Gas Fees: {gasEstimate === 0 && !isError ? ( -

Estimating Gas...

+

estimating gas...

) : (

diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx index c52cc0e..7ff3da5 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx @@ -110,10 +110,16 @@ const RemoveSectionStandard = () => { const handlePercChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = parseFloat(event.target.value); // Removes any non-number items and converts to Number - if ((value >= 0 && value <= 100) || event.target.value == "") { - setPercentage(event.target.value); - } else { - alert("Percentage must be between 0 & 100!"); + // if ((value >= 0 && value <= 100) || event.target.value == "") { + if ( + /^(?:[1-9][0-9]{0,1}|0|100)$/.test(event.target.value) || + event.target.value === "" + ) { + if ((value >= 0 && value <= 100) || event.target.value == "") { + setPercentage(event.target.value); + } else { + alert("Percentage must be between 0 & 100!"); + } } }; @@ -121,10 +127,8 @@ const RemoveSectionStandard = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (parseFloat(value) >= 0 || value == "") { + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { setLpTokens(event.target.value); - } else { - alert("LP Amount can't be negative!"); } }; @@ -721,7 +725,7 @@ const RemoveSectionStandard = () => {

Estimated Gas Fees: {gasEstimate === 0 && !isError ? ( -

Estimating Gas...

+

estimating gas...

) : (

diff --git a/src/components/Library/SlippageModal.tsx b/src/components/Library/SlippageModal.tsx index 56f50a0..1167816 100644 --- a/src/components/Library/SlippageModal.tsx +++ b/src/components/Library/SlippageModal.tsx @@ -51,7 +51,10 @@ const SlippageModal = () => { placeholder="0" className="text-lg leading-[27px] w-full font-bold text-[#344054] text-left bg-transparent focus:outline-none" onChange={(event: React.ChangeEvent) => { - setInputSlippage(event.target.value); + const value = event.target.value; + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + setInputSlippage(event.target.value); + } }} value={inputSlippage} name="slippage" diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index 66dc4d0..f5a7a07 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -89,17 +89,25 @@ const StakingModal = () => { const handlePercChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = parseFloat(event.target.value); // Removes any non-number items and converts to Number - if ((value >= 0 && value <= 100) || event.target.value == "") { - setPercentage(event.target.value); - } else { - alert("Percentage must be between 0 & 100!"); + if ( + /^(?:[1-9][0-9]{0,1}|0|100)$/.test(event.target.value) || + event.target.value === "" + ) { + if ((value >= 0 && value <= 100) || event.target.value == "") { + setPercentage(event.target.value); + } else { + alert("Percentage must be between 0 & 100!"); + } } }; // When InputType.Token const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); - setLpTokens(event.target.value); + const value = event.target.value; + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + setLpTokens(value); + } }; useEffect(() => { @@ -506,7 +514,7 @@ const StakingModal = () => {

Estimated Gas Fees: {gasEstimate === 0 && !isError ? ( -

Estimating Gas...

+

estimating gas...

) : (

diff --git a/src/components/Library/UnstakingModal/index.tsx b/src/components/Library/UnstakingModal/index.tsx index 8491c57..eed0668 100644 --- a/src/components/Library/UnstakingModal/index.tsx +++ b/src/components/Library/UnstakingModal/index.tsx @@ -82,17 +82,25 @@ const UnstakingModal = () => { const handlePercChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = parseFloat(event.target.value); - if ((value >= 0 && value <= 100) || event.target.value == "") { - setPercentage(event.target.value); - } else { - alert("Percentage must be between 0 & 100!"); + if ( + /^(?:[1-9][0-9]{0,1}|0|100)$/.test(event.target.value) || + event.target.value === "" + ) { + if ((value >= 0 && value <= 100) || event.target.value == "") { + setPercentage(event.target.value); + } else { + alert("Percentage must be between 0 & 100!"); + } } }; // When InputType.Token const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); - setLpTokens(event.target.value); + const value = event.target.value; + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + setLpTokens(event.target.value); + } }; useEffect(() => { @@ -467,7 +475,7 @@ const UnstakingModal = () => {

Estimated Gas Fees: {gasEstimate === 0 && !isError ? ( -

Estimating Gas...

+

estimating gas...

) : (

From 7ab09f64f306f02969f3ef6ab73a05c851a0e515 Mon Sep 17 00:00:00 2001 From: Jack Sparrow Date: Wed, 16 Aug 2023 22:21:48 +0530 Subject: [PATCH 04/27] skywalker: disable input @addstandard --- .../Library/AddLiquidityModal/AddSectionStandard.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 35311b3..e6ecbf9 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -654,6 +654,12 @@ const AddSectionStandard: FC = () => { className={clsx( "text-base text-[#4E4C4C] font-bold leading-6 text-left bg-transparent focus:outline-none" )} + disabled={ + approveToken0CallLoading || + approveToken0TxnLoading || + approveToken1CallLoading || + approveToken1TxnLoading + } onChange={handleChangeFirstTokenAmount} value={firstTokenAmount} name="firstTokenAmount" From a7dd778d686562221bf6fd0d055154e31ea42ce6 Mon Sep 17 00:00:00 2001 From: Jack Sparrow Date: Wed, 16 Aug 2023 23:00:11 +0530 Subject: [PATCH 05/27] skywalker: disable input @addstable wip --- .../AddLiquidityModal/AddSectionStable.tsx | 9 ++++++- .../Library/AddLiquidityModal/TokenButton.tsx | 24 +++++++++++++++++++ .../Library/AddLiquidityModal/TokenInput.tsx | 17 +++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index 78d0290..962338f 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -58,6 +58,8 @@ const AddSectionStable: FC = () => { const { address, connector } = useAccount(); const { chain } = useNetwork(); + const [isApproving, setIsApproving] = useState(false); + // Transaction Process Steps const [isConfirmStep, setIsConfirmStep] = useState(false); const [isProcessStep, setIsProcessStep] = useState(false); @@ -81,8 +83,11 @@ const AddSectionStable: FC = () => { const [balanceMap, setBalanceMap] = useState<{ [address: Address]: string; }>({}); + const [isApprovingMap, setIsApprovingMap] = useState<{ + [address: Address]: boolean; + }>({}); - const [farms] = useAtom(farmsAtom); + // const [farms] = useAtom(farmsAtom); const [positions, setPositions] = useAtom(positionsAtom); const [lpTokenPricesMap, setLpTokenPricesMap] = useAtom(lpTokenPricesAtom); const [lpUpdated, setLpUpdated] = useAtom(lpUpdatedAtom); @@ -365,6 +370,7 @@ const AddSectionStable: FC = () => { index={index} handleInput={handleInput} inputMap={inputMap} + isApproving={isApprovingMap} balanceMap={balanceMap} setBalanceMap={setBalanceMap} nativeBal={parseFloat(nativeBal?.formatted!).toLocaleString( @@ -406,6 +412,7 @@ const AddSectionStable: FC = () => { token={token} inputMapAmount={inputMapAmount} selectedFarm={farm!} + setIsApproving={setIsApprovingMap} approvalMap={approvalMap} setApprovalMap={setApprovalMap} /> diff --git a/src/components/Library/AddLiquidityModal/TokenButton.tsx b/src/components/Library/AddLiquidityModal/TokenButton.tsx index 2fca4d7..92fd87c 100644 --- a/src/components/Library/AddLiquidityModal/TokenButton.tsx +++ b/src/components/Library/AddLiquidityModal/TokenButton.tsx @@ -15,6 +15,11 @@ interface Props { [address: Address]: boolean; }> >; + setIsApproving: React.Dispatch< + React.SetStateAction<{ + [address: `0x${string}`]: boolean; + }> + >; } const TokenButton: React.FC = ({ @@ -23,6 +28,7 @@ const TokenButton: React.FC = ({ selectedFarm, approvalMap, setApprovalMap, + setIsApproving, }) => { // Check Approval Token const { isSuccess: isApprovedSuccess } = useIsApprovedToken( @@ -38,6 +44,24 @@ const TokenButton: React.FC = ({ writeAsync: approveToken, } = useApproveToken(token?.address, selectedFarm?.router, token?.symbol); + // useEffect(() => { + // if (isLoadingApproveCall || isLoadingApproveTxn) { + // setIsApproving((prev) => { + // return { + // ...prev, + // [token?.address]: true, + // }; + // }); + // } else { + // setIsApproving((prev) => { + // return { + // ...prev, + // [token?.address]: false, + // }; + // }); + // } + // }, [isLoadingApproveCall || isLoadingApproveTxn]); + useEffect(() => { // Either already approved or approved after transaction if ( diff --git a/src/components/Library/AddLiquidityModal/TokenInput.tsx b/src/components/Library/AddLiquidityModal/TokenInput.tsx index 108de10..b5f9c9a 100644 --- a/src/components/Library/AddLiquidityModal/TokenInput.tsx +++ b/src/components/Library/AddLiquidityModal/TokenInput.tsx @@ -19,6 +19,9 @@ interface TokenInputProps { }> >; nativeBal: string; + isApproving: { + [address: Address]: boolean; + }; logos: string | string[]; tokensLength: number; focusedInput: number; @@ -33,6 +36,7 @@ const TokenInput: React.FC = ({ balanceMap, setBalanceMap, nativeBal, + isApproving, logos, tokensLength, focusedInput, @@ -70,6 +74,18 @@ const TokenInput: React.FC = ({ } }, [isSuccess]); + function isAllTrue(isApprovingMap: { [address: string]: boolean }): boolean { + // Iterate over the keys in isApprovingMap + for (const address in isApprovingMap) { + // If any value is false, return false + if (!isApprovingMap[address]) { + return false; + } + } + // If all values are true, return true + return true; + } + return (

@@ -104,6 +120,7 @@ const TokenInput: React.FC = ({ : "text-[#4E4C4C]" )} min={0} + disabled={isAllTrue(isApproving)} value={inputMap[token?.address] ?? ""} onChange={(event) => { event.preventDefault(); From f969a4b20609780f76aa56843a3a425f5211852c Mon Sep 17 00:00:00 2001 From: Jack Sparrow Date: Wed, 16 Aug 2023 23:17:17 +0530 Subject: [PATCH 06/27] lint fix --- src/utils/farmListMethods.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils/farmListMethods.ts b/src/utils/farmListMethods.ts index 7686eab..d3e562b 100644 --- a/src/utils/farmListMethods.ts +++ b/src/utils/farmListMethods.ts @@ -98,6 +98,7 @@ export function getWalletInstallUrl(walletName: string): string { } export function checkIfPoolSupported(farm: FarmType): boolean { + if (farm == undefined) return false; if (farm?.farmType == "SingleStaking") return false; const protocols = supportedPools[farm.chain.toLocaleLowerCase()]; if (!!protocols) return protocols.includes(farm.protocol.toLowerCase()); From 2dc965620bc698b8c90171d4788e76502ad1639a Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Thu, 17 Aug 2023 14:56:55 +0530 Subject: [PATCH 07/27] Added max decimal places limit based on tokens --- .../AddLiquidityModal/AddSectionStandard.tsx | 20 ++++++++++++------- .../Library/AddLiquidityModal/TokenInput.tsx | 6 ++++-- .../RemoveSectionMangata.tsx | 4 +++- .../RemoveSectionStable.tsx | 4 +++- .../RemoveSectionStandard.tsx | 4 +++- src/components/Library/StakingModal/index.tsx | 4 +++- .../Library/UnstakingModal/index.tsx | 4 +++- src/utils/createRegex.ts | 6 ++++++ 8 files changed, 38 insertions(+), 14 deletions(-) create mode 100644 src/utils/createRegex.ts diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index e6ecbf9..44541f8 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -62,6 +62,7 @@ import { } from "@utils/position-utils/evmPositions"; import BigNumber from "bignumber.js"; import Countdown from "../Countdown"; +import { createNumRegex } from "@utils/createRegex"; enum InputType { Off = -1, @@ -507,12 +508,13 @@ const AddSectionStandard: FC = () => { e: React.ChangeEvent ) => { const value = e.target.value; - // regex only let numerical values - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + // regex only let numerical values upto token decimals + const regex = createNumRegex(farmAsset0.decimals); + if (regex.test(value) || value === "") { setFirstTokenAmount(value); + // update first amount based on second + updateSecondTokenAmount(parseFloat(value)); } - // update first amount based on second - updateSecondTokenAmount(parseFloat(value)); }; // update token values @@ -520,9 +522,13 @@ const AddSectionStandard: FC = () => { e: React.ChangeEvent ) => { const value = e.target.value; - setSecondTokenAmount(value); - // update first amount based on second - updateFirstTokenAmount(parseFloat(value)); + // regex only let numerical values upto token decimals + const regex = createNumRegex(farmAsset1.decimals); + if (regex.test(value) || value === "") { + setSecondTokenAmount(value); + // update first amount based on second + updateFirstTokenAmount(parseFloat(value)); + } }; useEffect(() => { diff --git a/src/components/Library/AddLiquidityModal/TokenInput.tsx b/src/components/Library/AddLiquidityModal/TokenInput.tsx index b5f9c9a..96b2f05 100644 --- a/src/components/Library/AddLiquidityModal/TokenInput.tsx +++ b/src/components/Library/AddLiquidityModal/TokenInput.tsx @@ -4,6 +4,7 @@ import Image from "next/image"; import { Address, useAccount, useBalance, useNetwork } from "wagmi"; import clsx from "clsx"; import { fixedAmtNum } from "@utils/abis/contract-helper-methods"; +import { createNumRegex } from "@utils/createRegex"; interface TokenInputProps { token: UnderlyingAssets; @@ -125,8 +126,9 @@ const TokenInput: React.FC = ({ onChange={(event) => { event.preventDefault(); const value = event.target.value; - // regex for inputing decimals upto 10 digits - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + // regex for inputing decimals upto token decimal places + const regex = createNumRegex(token?.decimals); + if (regex.test(value) || value === "") { handleInput(token, value); } }} diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx index eb5f3f3..477db9d 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionMangata.tsx @@ -45,6 +45,7 @@ import getTimestamp from "@utils/getTimestamp"; import { fixedAmtNum } from "@utils/abis/contract-helper-methods"; import { fetchTokenPricesMangata } from "@utils/fetch-prices"; import Countdown from "../Countdown"; +import { createNumRegex } from "@utils/createRegex"; interface ChosenMethodProps { farm: FarmType; @@ -253,7 +254,8 @@ const RemoveSectionMangata: FC = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + const regex = createNumRegex(18); + if (regex.test(value) || value === "") { setLpTokens(event.target.value); } }; diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index 70d9d2c..1077f33 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -52,6 +52,7 @@ import { handleRemoveLiquidityEvent } from "@utils/tracking"; import getTimestamp from "@utils/getTimestamp"; import { updateEvmPositions } from "@utils/position-utils/evmPositions"; import Countdown from "../Countdown"; +import { createNumRegex } from "@utils/createRegex"; enum RemoveMethod { ALL = 0, @@ -124,7 +125,8 @@ const RemoveSectionStable: FC = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + const regex = createNumRegex(18); + if (regex.test(value) || value === "") { setLpTokens(event.target.value); } }; diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx index 7ff3da5..ca3f3d1 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx @@ -55,6 +55,7 @@ import { handleRemoveLiquidityEvent } from "@utils/tracking"; import getTimestamp from "@utils/getTimestamp"; import BigNumber from "bignumber.js"; import Countdown from "../Countdown"; +import { createNumRegex } from "@utils/createRegex"; const RemoveSectionStandard = () => { const { address, connector } = useAccount(); @@ -127,7 +128,8 @@ const RemoveSectionStandard = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + const regex = createNumRegex(18); + if (regex.test(value) || value === "") { setLpTokens(event.target.value); } }; diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index f5a7a07..d85c691 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -41,6 +41,7 @@ import toUnits from "@utils/toUnits"; import BigNumber from "bignumber.js"; import { updateEvmPositions } from "@utils/position-utils/evmPositions"; import Countdown from "../Countdown"; +import { createNumRegex } from "@utils/createRegex"; interface ChosenMethodProps { farm: FarmType; @@ -105,7 +106,8 @@ const StakingModal = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + const regex = createNumRegex(18); + if (regex.test(value) || value === "") { setLpTokens(value); } }; diff --git a/src/components/Library/UnstakingModal/index.tsx b/src/components/Library/UnstakingModal/index.tsx index eed0668..4857538 100644 --- a/src/components/Library/UnstakingModal/index.tsx +++ b/src/components/Library/UnstakingModal/index.tsx @@ -40,6 +40,7 @@ import getTimestamp from "@utils/getTimestamp"; import BigNumber from "bignumber.js"; import { updateEvmPositions } from "@utils/position-utils/evmPositions"; import Countdown from "../Countdown"; +import { createNumRegex } from "@utils/createRegex"; interface ChosenMethodProps { farm: FarmType; @@ -98,7 +99,8 @@ const UnstakingModal = () => { const handleLpTokensChange = (event: React.ChangeEvent) => { event.preventDefault(); const value = event.target.value; - if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + const regex = createNumRegex(18); + if (regex.test(value) || value === "") { setLpTokens(event.target.value); } }; diff --git a/src/utils/createRegex.ts b/src/utils/createRegex.ts new file mode 100644 index 0000000..e126f60 --- /dev/null +++ b/src/utils/createRegex.ts @@ -0,0 +1,6 @@ +export function createNumRegex(decimal: number): RegExp { + if (!decimal || decimal == undefined) { + return new RegExp(`^(\\d+\\.?\\d*|\\.\\d+)$`); + } + return new RegExp(`^(\\d+\\.?\\d{0,${decimal}}|\\.\\d{1,${decimal}})$`); +} From d7ffe3a0163edf8b6473ce2b356f46da649353d4 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Thu, 17 Aug 2023 17:00:41 +0530 Subject: [PATCH 08/27] updated // token allownace method --- .../AddLiquidityModal/AddSectionStandard.tsx | 18 +++- .../Library/AddLiquidityModal/TokenButton.tsx | 28 ++++- .../RemoveSectionStable.tsx | 5 +- .../RemoveSectionStandard.tsx | 5 +- src/components/Library/StakingModal/index.tsx | 9 +- src/hooks/useApprovalHooks.ts | 102 ++++++++++-------- 6 files changed, 110 insertions(+), 57 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 44541f8..2b0a5d3 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -312,13 +312,21 @@ const AddSectionStandard: FC = () => { // data: isToken0Approved, isLoading: isToken0ApprovedLoading, isSuccess: isToken0ApprovedSuccess, - } = useIsApprovedToken(farmAsset0?.address, selectedFarm?.router!); + } = useIsApprovedToken( + farmAsset0?.address, + selectedFarm?.router!, + token0Balance?.formatted + ); const { // data: isToken1Approved, isLoading: isToken1ApprovedLoading, isSuccess: isToken1ApprovedSuccess, - } = useIsApprovedToken(farmAsset1?.address, selectedFarm?.router!); + } = useIsApprovedToken( + farmAsset1?.address, + selectedFarm?.router!, + token1Balance?.formatted + ); // To approve token0 and token1 const { @@ -330,7 +338,8 @@ const AddSectionStandard: FC = () => { } = useApproveToken( farmAsset0?.address, selectedFarm?.router!, - farmAsset0?.symbol + farmAsset0?.symbol, + token0Balance?.formatted ); const { isLoadingApproveCall: approveToken1CallLoading, @@ -341,7 +350,8 @@ const AddSectionStandard: FC = () => { } = useApproveToken( farmAsset1?.address, selectedFarm?.router!, - farmAsset1?.symbol + farmAsset1?.symbol, + token1Balance?.formatted ); const { diff --git a/src/components/Library/AddLiquidityModal/TokenButton.tsx b/src/components/Library/AddLiquidityModal/TokenButton.tsx index 92fd87c..f97594f 100644 --- a/src/components/Library/AddLiquidityModal/TokenButton.tsx +++ b/src/components/Library/AddLiquidityModal/TokenButton.tsx @@ -4,6 +4,7 @@ import MButton from "../MButton"; import { useApproveToken, useIsApprovedToken } from "@hooks/useApprovalHooks"; import { Address } from "viem"; import clsx from "clsx"; +import { useAccount, useBalance, useNetwork } from "wagmi"; interface Props { token: UnderlyingAssets; @@ -30,10 +31,28 @@ const TokenButton: React.FC = ({ setApprovalMap, setIsApproving, }) => { + const { address } = useAccount(); + const { chain } = useNetwork(); + + // Balance Token + const { + data: balance, + isLoading: balanceLoading, + isSuccess, + } = useBalance({ + address: address, + chainId: chain?.id, + token: token?.address, + enabled: !!address && !!token, + }); + + console.log("balance in tokenbutton", balance, isSuccess); + // Check Approval Token const { isSuccess: isApprovedSuccess } = useIsApprovedToken( token?.address, - selectedFarm?.router + selectedFarm?.router, + balance?.formatted ); // Approve token @@ -42,7 +61,12 @@ const TokenButton: React.FC = ({ isLoadingApproveTxn, isSuccessApproveTxn, writeAsync: approveToken, - } = useApproveToken(token?.address, selectedFarm?.router, token?.symbol); + } = useApproveToken( + token?.address, + selectedFarm?.router, + token?.symbol, + balance?.formatted + ); // useEffect(() => { // if (isLoadingApproveCall || isLoadingApproveTxn) { diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index 1077f33..9df08c7 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -223,7 +223,7 @@ const RemoveSectionStable: FC = () => { data: isLpApprovedData, isLoading: isLpApprovedLoading, isSuccess: isLpApprovedSuccess, - } = useIsApprovedToken(farm?.asset.address!, farm?.router!); + } = useIsApprovedToken(farm?.asset.address!, farm?.router!, lpBalance); // Approve LP token const { @@ -234,7 +234,8 @@ const RemoveSectionStable: FC = () => { } = useApproveToken( farm?.asset.address!, farm?.router!, - getLpTokenSymbol(tokenNames) + getLpTokenSymbol(tokenNames), + lpBalance ); // Remove Liquidity Call diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx index ca3f3d1..66105e0 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx @@ -171,7 +171,7 @@ const RemoveSectionStandard = () => { data: isLpApprovedData, isLoading: isLpApprovedLoading, isSuccess: isLpApprovedSuccess, - } = useIsApprovedToken(farm?.asset.address!, farm?.router!); + } = useIsApprovedToken(farm?.asset.address!, farm?.router!, lpBalance); const { isLoadingApproveCall: approveLpLoading, @@ -181,7 +181,8 @@ const RemoveSectionStandard = () => { } = useApproveToken( farm?.asset.address!, farm?.router!, - getLpTokenSymbol(tokenNames) + getLpTokenSymbol(tokenNames), + lpBalance ); // Remove Liquidity diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index d85c691..284c19f 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -218,7 +218,11 @@ const StakingModal = () => { // data: isApprovedData, // isLoading: isApprovedLoading, isSuccess: isApprovedSuccess, - } = useIsApprovedToken(farm?.asset.address!, farm?.chef as Address); + } = useIsApprovedToken( + farm?.asset.address!, + farm?.chef as Address, + lpBalance?.formatted + ); const { isLoadingApproveCall, @@ -228,7 +232,8 @@ const StakingModal = () => { } = useApproveToken( farm?.asset.address!, farm?.chef as Address, - getLpTokenSymbol(tokenNames) + getLpTokenSymbol(tokenNames), + lpBalance?.formatted ); // Stake LP Tokens diff --git a/src/hooks/useApprovalHooks.ts b/src/hooks/useApprovalHooks.ts index 6395556..a12e1f6 100644 --- a/src/hooks/useApprovalHooks.ts +++ b/src/hooks/useApprovalHooks.ts @@ -16,7 +16,11 @@ import toast from "react-hot-toast"; * @param spender spender Contract Address * @returns data, isLoading, isError, isSuccess */ -const useIsApprovedToken = (tokenAddress: Address, spender: Address) => { +const useIsApprovedToken = ( + tokenAddress: Address, + spender: Address, + tokenBalance: string | undefined +) => { const { address } = useAccount(); const { data, isLoading, isError } = useContractRead({ address: tokenAddress, @@ -33,40 +37,45 @@ const useIsApprovedToken = (tokenAddress: Address, spender: Address) => { console.log( "appdata", tokenAddress, - data, - Number(data) == - parseInt( - ( - BigInt( - 2 ** - (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || - tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" - ? 128 - : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" - ? 96 - : 256) - ) - BigInt(1) - ).toString() - ) + Number(data), + !tokenBalance ? false : Number(data) >= parseInt(tokenBalance) + // Number(data) == + // parseInt( + // ( + // BigInt( + // 2 ** + // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || + // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" + // ? 128 + // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" + // ? 96 + // : 256) + // ) - BigInt(1) + // ).toString() + // ) ); - return ( - Number(data) == - parseInt( - ( - BigInt( - 2 ** - (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || - tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" - ? 128 - : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" - ? 96 - : 256) - ) - BigInt(1) - ).toString() - ) - ); - }, [data]); + // allowed tokens >= token balance + if (!tokenBalance) return false; // if balance not fetched yet show false + return Number(data) >= parseInt(tokenBalance); + // Allowed tokens are equal to MaxInt + // return ( + // Number(data) == + // parseInt( + // ( + // BigInt( + // 2 ** + // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || + // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" + // ? 128 + // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" + // ? 96 + // : 256) + // ) - BigInt(1) + // ).toString() + // ) + // ); + }, [data]); return { data, isLoading, isError, isSuccess }; }; @@ -79,9 +88,11 @@ const useIsApprovedToken = (tokenAddress: Address, spender: Address) => { const useApproveToken = ( tokenAddress: Address, spender: Address, - tokenSymbol: string + tokenSymbol: string, + tokenBalance: string | undefined ) => { const { chain } = useNetwork(); + console.log("token", tokenSymbol, "\ntokenBalance", tokenBalance); const { data, isLoading: isLoadingApproveCall, @@ -95,17 +106,18 @@ const useApproveToken = ( chainId: chain?.id, args: [ spender, // spender - ( - BigInt( - 2 ** - (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || - tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" - ? 128 - : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" - ? 96 - : 256) - ) - BigInt(1) - ).toString(), + tokenBalance, + // ( + // BigInt( + // 2 ** + // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || + // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" + // ? 128 + // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" + // ? 96 + // : 256) + // ) - BigInt(1) + // ).toString(), ], onError: (error) => { console.log(`Error while Approving:`, error); From ab0903569677606b697249470a3960f178a26bed Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Fri, 18 Aug 2023 16:33:03 +0530 Subject: [PATCH 09/27] fixed: token approval limit --- src/hooks/useApprovalHooks.ts | 50 ++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/hooks/useApprovalHooks.ts b/src/hooks/useApprovalHooks.ts index a12e1f6..167f96d 100644 --- a/src/hooks/useApprovalHooks.ts +++ b/src/hooks/useApprovalHooks.ts @@ -33,32 +33,33 @@ const useIsApprovedToken = ( enabled: !!address && !!spender, }); + const formatData = (num: number) => { + if (!num) return 0; + const parts = num.toString().split("."); + return parseFloat(parts[0] + "." + parts[1].substring(0, 12)); + }; + const isSuccess = useMemo(() => { + const numdata = Number(data) / 10 ** 12; console.log( - "appdata", + "token_address", tokenAddress, - Number(data), - !tokenBalance ? false : Number(data) >= parseInt(tokenBalance) - // Number(data) == - // parseInt( - // ( - // BigInt( - // 2 ** - // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || - // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" - // ? 128 - // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" - // ? 96 - // : 256) - // ) - BigInt(1) - // ).toString() - // ) + "\ndata", + data, + "\nnumber_data", + numdata, + "\ntokenBalance", + formatData(parseFloat(tokenBalance ?? "0")), + "\nisApproved: should be true if data >= tokenBalance", + !tokenBalance ? false : numdata >= formatData(parseFloat(tokenBalance)) ); + // allowed tokens >= token balance - if (!tokenBalance) return false; // if balance not fetched yet show false - return Number(data) >= parseInt(tokenBalance); + return !tokenBalance + ? false + : numdata >= formatData(parseFloat(tokenBalance)); - // Allowed tokens are equal to MaxInt + // Infinite token allowance // return ( // Number(data) == // parseInt( @@ -106,9 +107,11 @@ const useApproveToken = ( chainId: chain?.id, args: [ spender, // spender - tokenBalance, - // ( - // BigInt( + BigInt( + parseInt((parseFloat(tokenBalance ?? "0") * 10 ** 12).toString()) + ).toString(), + // BigInt( + // parseFloat(tokenBalance!) * // 2 ** // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" @@ -116,7 +119,6 @@ const useApproveToken = ( // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" // ? 96 // : 256) - // ) - BigInt(1) // ).toString(), ], onError: (error) => { From 08425c51814bb47bffe8e26ec7809b0c1b710040 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Fri, 18 Aug 2023 17:44:19 +0530 Subject: [PATCH 10/27] revamped the approval logic, using input for checking --- .../AddLiquidityModal/AddSectionStable.tsx | 4 +- .../AddLiquidityModal/AddSectionStandard.tsx | 14 ++- .../Library/AddLiquidityModal/TokenButton.tsx | 3 +- .../RemoveSectionStable.tsx | 9 +- .../RemoveSectionStandard.tsx | 9 +- src/components/Library/StakingModal/index.tsx | 5 +- src/hooks/useApprovalHooks.ts | 102 ++++++++---------- 7 files changed, 78 insertions(+), 68 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index 962338f..f615604 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -46,7 +46,7 @@ import WrongNetworkModal from "../WrongNetworkModal"; import useGasEstimation from "@hooks/useGasEstimation"; import { getNativeTokenAddress } from "@utils/network"; import { - fetchEvmPositions, + // fetchEvmPositions, updateEvmPositions, } from "@utils/position-utils/evmPositions"; import { handleAddLiquidityEvent } from "@utils/tracking"; @@ -58,7 +58,7 @@ const AddSectionStable: FC = () => { const { address, connector } = useAccount(); const { chain } = useNetwork(); - const [isApproving, setIsApproving] = useState(false); + // const [isApproving, setIsApproving] = useState(false); // Transaction Process Steps const [isConfirmStep, setIsConfirmStep] = useState(false); diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 2b0a5d3..dd02d85 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -299,6 +299,8 @@ const AddSectionStandard: FC = () => { enabled: !!address && !!selectedFarm, }); + console.log("token0Balance", token0Balance); + // Balance Token1 const { data: token1Balance, isLoading: token1BalanceLoading } = useBalance({ address, @@ -307,6 +309,8 @@ const AddSectionStandard: FC = () => { enabled: !!address && !!selectedFarm, }); + console.log("token0Balance", token0Balance); + // Check Approval Token0 & Token1 const { // data: isToken0Approved, @@ -315,7 +319,8 @@ const AddSectionStandard: FC = () => { } = useIsApprovedToken( farmAsset0?.address, selectedFarm?.router!, - token0Balance?.formatted + token0Balance, + fixedAmtNum(firstTokenAmount) ); const { @@ -325,7 +330,8 @@ const AddSectionStandard: FC = () => { } = useIsApprovedToken( farmAsset1?.address, selectedFarm?.router!, - token1Balance?.formatted + token1Balance, + fixedAmtNum(secondTokenAmount) ); // To approve token0 and token1 @@ -339,7 +345,7 @@ const AddSectionStandard: FC = () => { farmAsset0?.address, selectedFarm?.router!, farmAsset0?.symbol, - token0Balance?.formatted + token0Balance ); const { isLoadingApproveCall: approveToken1CallLoading, @@ -351,7 +357,7 @@ const AddSectionStandard: FC = () => { farmAsset1?.address, selectedFarm?.router!, farmAsset1?.symbol, - token1Balance?.formatted + token1Balance ); const { diff --git a/src/components/Library/AddLiquidityModal/TokenButton.tsx b/src/components/Library/AddLiquidityModal/TokenButton.tsx index f97594f..d11010b 100644 --- a/src/components/Library/AddLiquidityModal/TokenButton.tsx +++ b/src/components/Library/AddLiquidityModal/TokenButton.tsx @@ -52,7 +52,8 @@ const TokenButton: React.FC = ({ const { isSuccess: isApprovedSuccess } = useIsApprovedToken( token?.address, selectedFarm?.router, - balance?.formatted + balance?.formatted, + inputMapAmount[token?.address] ); // Approve token diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index 9df08c7..c2906f1 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -223,7 +223,14 @@ const RemoveSectionStable: FC = () => { data: isLpApprovedData, isLoading: isLpApprovedLoading, isSuccess: isLpApprovedSuccess, - } = useIsApprovedToken(farm?.asset.address!, farm?.router!, lpBalance); + } = useIsApprovedToken( + farm?.asset.address!, + farm?.router!, + lpBalance, + methodId == Method.PERCENTAGE + ? (fixedAmtNum(lpBalance) * fixedAmtNum(percentage)) / 100 + : fixedAmtNum(lpTokens) + ); // Approve LP token const { diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx index 66105e0..ac9436f 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx @@ -171,7 +171,14 @@ const RemoveSectionStandard = () => { data: isLpApprovedData, isLoading: isLpApprovedLoading, isSuccess: isLpApprovedSuccess, - } = useIsApprovedToken(farm?.asset.address!, farm?.router!, lpBalance); + } = useIsApprovedToken( + farm?.asset.address!, + farm?.router!, + lpBalance, + methodId == Method.PERCENTAGE + ? (fixedAmtNum(lpBalance) * fixedAmtNum(percentage)) / 100 + : fixedAmtNum(lpTokens) + ); const { isLoadingApproveCall: approveLpLoading, diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index 284c19f..64c7a5e 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -221,7 +221,10 @@ const StakingModal = () => { } = useIsApprovedToken( farm?.asset.address!, farm?.chef as Address, - lpBalance?.formatted + lpBalance?.formatted, + methodId == 0 + ? (lpBalanceNum * fixedAmtNum(percentage)) / 100 + : fixedAmtNum(lpTokens) ); const { diff --git a/src/hooks/useApprovalHooks.ts b/src/hooks/useApprovalHooks.ts index 167f96d..9635630 100644 --- a/src/hooks/useApprovalHooks.ts +++ b/src/hooks/useApprovalHooks.ts @@ -7,8 +7,9 @@ import { useWaitForTransaction, } from "wagmi"; import { tokenAbi } from "@components/Common/Layout/evmUtils"; -import { useEffect, useMemo } from "react"; +import { useEffect } from "react"; import toast from "react-hot-toast"; +import BigNumber from "bignumber.js"; /** * @@ -19,7 +20,8 @@ import toast from "react-hot-toast"; const useIsApprovedToken = ( tokenAddress: Address, spender: Address, - tokenBalance: string | undefined + tokenBalance: any | undefined, + input: number ) => { const { address } = useAccount(); const { data, isLoading, isError } = useContractRead({ @@ -33,51 +35,44 @@ const useIsApprovedToken = ( enabled: !!address && !!spender, }); - const formatData = (num: number) => { - if (!num) return 0; - const parts = num.toString().split("."); - return parseFloat(parts[0] + "." + parts[1].substring(0, 12)); - }; + const allow = data as bigint; + + const allowance = BigNumber(allow.toString(), 10) + // .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals)) + .decimalPlaces(0, 1); + // console.log("allowance bigint", allow); + console.log("allowance", allowance.toString()); + + const inputAmount = BigNumber(input.toString(), 10) + .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals)) + .decimalPlaces(0, 1); + console.log("inputAmount", inputAmount.toString()); - const isSuccess = useMemo(() => { - const numdata = Number(data) / 10 ** 12; - console.log( - "token_address", - tokenAddress, - "\ndata", - data, - "\nnumber_data", - numdata, - "\ntokenBalance", - formatData(parseFloat(tokenBalance ?? "0")), - "\nisApproved: should be true if data >= tokenBalance", - !tokenBalance ? false : numdata >= formatData(parseFloat(tokenBalance)) - ); + const compare = inputAmount.isLessThanOrEqualTo(allowance); + console.log("compare", compare); - // allowed tokens >= token balance - return !tokenBalance - ? false - : numdata >= formatData(parseFloat(tokenBalance)); + // const isSuccess = useMemo(() => { + // const numdata = Number(data) / 10 ** 12; + // // console.log( + // // "token_address", + // // tokenAddress, + // // "\ndata", + // // data, + // // "\nnumber_data", + // // numdata, + // // "\ntokenBalance", + // // parseFloat(tokenBalance ?? "0"), + // // "\nisApproved: should be true if data >= tokenBalance" + // // // !tokenBalance ? false : numdata >= formatData(parseFloat(tokenBalance)) + // // // !input ? false : numdata >= formatData(parseFloat(tokenBalance)) + // // ); - // Infinite token allowance - // return ( - // Number(data) == - // parseInt( - // ( - // BigInt( - // 2 ** - // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || - // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" - // ? 128 - // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" - // ? 96 - // : 256) - // ) - BigInt(1) - // ).toString() - // ) - // ); - }, [data]); - return { data, isLoading, isError, isSuccess }; + // // allowed tokens >= token balance + // // return !tokenBalance + // // ? false + // // : numdata >= formatData(parseFloat(tokenBalance)); + // return compare; + return { data, isLoading, isError, isSuccess: compare }; }; /** @@ -90,7 +85,7 @@ const useApproveToken = ( tokenAddress: Address, spender: Address, tokenSymbol: string, - tokenBalance: string | undefined + tokenBalance: any | undefined ) => { const { chain } = useNetwork(); console.log("token", tokenSymbol, "\ntokenBalance", tokenBalance); @@ -107,19 +102,10 @@ const useApproveToken = ( chainId: chain?.id, args: [ spender, // spender - BigInt( - parseInt((parseFloat(tokenBalance ?? "0") * 10 ** 12).toString()) - ).toString(), - // BigInt( - // parseFloat(tokenBalance!) * - // 2 ** - // (tokenAddress == "0xFFFFFFfFea09FB06d082fd1275CD48b191cbCD1d" || - // tokenAddress == "0xFfFFfFff1FcaCBd218EDc0EbA20Fc2308C778080" - // ? 128 - // : tokenAddress == "0x511aB53F793683763E5a8829738301368a2411E3" - // ? 96 - // : 256) - // ).toString(), + BigNumber(tokenBalance?.formatted, 10) + .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals)) + .decimalPlaces(0, 1) + .toString(), ], onError: (error) => { console.log(`Error while Approving:`, error); From a81001a6a8b4a9cdfac526868a6d6391790ccddd Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Fri, 18 Aug 2023 22:08:49 +0530 Subject: [PATCH 11/27] set slippage box revamp/fix --- .../AddLiquidityModal/AddSectionMangata.tsx | 12 ++- .../AddLiquidityModal/AddSectionStable.tsx | 13 ++- .../AddLiquidityModal/AddSectionStandard.tsx | 13 ++- .../RemoveSectionMangata.tsx | 12 ++- .../RemoveSectionStable.tsx | 13 ++- .../RemoveSectionStandard.tsx | 67 ++----------- src/components/Library/SlippageBox.tsx | 97 +++++++++++++++++++ src/components/Library/StakingModal/index.tsx | 13 ++- .../Library/UnstakingModal/index.tsx | 13 ++- 9 files changed, 177 insertions(+), 76 deletions(-) create mode 100644 src/components/Library/SlippageBox.tsx diff --git a/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx b/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx index 58c84b7..c1c08c5 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionMangata.tsx @@ -52,6 +52,7 @@ import { handleAddLiquidityEvent } from "@utils/tracking"; import getTimestamp from "@utils/getTimestamp"; import { fetchTokenPricesMangata } from "@utils/fetch-prices"; import Countdown from "../Countdown"; +import SlippageBox from "../SlippageBox"; enum InputType { Off = -1, @@ -86,6 +87,8 @@ const AddSectionMangata: FC = () => { const [tokenPricesMap] = useAtom(tokenPricesAtom); const [, setIsSubPosLoading] = useAtom(subPosLoadingAtom); + const [isSlippageStep, setIsSlippageStep] = useState(false); + const [SLIPPAGE] = useAtom(slippageAtom); // Input focus states @@ -1065,8 +1068,8 @@ const AddSectionMangata: FC = () => { Slippage Tolerance: {SLIPPAGE}%
+ ) : isSlippageStep ? ( + ) : isProcessStep ? ( ) : isConfirmStep ? ( diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index f615604..b16a853 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -52,6 +52,7 @@ import { import { handleAddLiquidityEvent } from "@utils/tracking"; import getTimestamp from "@utils/getTimestamp"; import Countdown from "../Countdown"; +import SlippageBox from "../SlippageBox"; const AddSectionStable: FC = () => { const publicClient = usePublicClient(); @@ -63,6 +64,7 @@ const AddSectionStable: FC = () => { // Transaction Process Steps const [isConfirmStep, setIsConfirmStep] = useState(false); const [isProcessStep, setIsProcessStep] = useState(false); + const [isSlippageStep, setIsSlippageStep] = useState(false); const [isSlippageModalOpen, setIsSlippageModalOpen] = useAtom( slippageModalOpenAtom @@ -565,8 +567,8 @@ const AddSectionStable: FC = () => { Slippage Tolerance: {SLIPPAGE}%
+ ) : isSlippageStep ? ( + ) : isProcessStep ? ( ) : isConfirmStep ? ( diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index c2906f1..8f97109 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -53,6 +53,7 @@ import getTimestamp from "@utils/getTimestamp"; import { updateEvmPositions } from "@utils/position-utils/evmPositions"; import Countdown from "../Countdown"; import { createNumRegex } from "@utils/createRegex"; +import SlippageBox from "../SlippageBox"; enum RemoveMethod { ALL = 0, @@ -78,6 +79,7 @@ const RemoveSectionStable: FC = () => { const [positions, setPositions] = useAtom(positionsAtom); const [lpTokenPricesMap, setLpTokenPricesMap] = useAtom(lpTokenPricesAtom); const [tokenPricesMap] = useAtom(tokenPricesAtom); + const [isSlippageStep, setIsSlippageStep] = useState(false); // const [, setIsEvmPosLoading] = useAtom(evmPosLoadingAtom); useEffect(() => console.log("farm @removeliq", farm), [farm]); @@ -712,8 +714,8 @@ const RemoveSectionStable: FC = () => { Slippage Tolerance: {SLIPPAGE}%
- {/* Estimate Gas and Slippage Tolerance */} - {/* Gas Fees // Slippage // Suff. Wallet balance */} - {/*
gasEstimate - ? "bg-[#C0F9C9]" - : "bg-[#FFB7B7]" - )} - > -
gasEstimate - ? "bg-[#ECFFEF]" - : "bg-[#FFE8E8]" - )} - > -
- Estimated Gas Fees: -

- - {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} - - ${(gasEstimate * nativePrice).toFixed(5)} -

-
-
- Slippage Tolerance: {SLIPPAGE}% - -
-
-
-

- {parseFloat(nativeBal?.formatted ?? "0") > gasEstimate - ? "Sufficient" - : "Insufficient"}{" "} - Wallet Balance -

- - {parseFloat(nativeBal?.formatted!).toLocaleString("en-US")}{" "} - {nativeBal?.symbol} - -
-
*/}
{isLpApprovedLoading ? ( { Slippage Tolerance: {SLIPPAGE}% +

Set Slippage Tolerance

+ + + +
+
+
+ ) => { + const value = event.target.value; + if (/^(\d+\.?\d*|\.\d+)$/.test(value) || value === "") { + setInputSlippage(event.target.value); + } + }} + value={inputSlippage} + name="slippage" + id="slippage" + /> + + % + +
+ +
+ { + submitSlippage(); + setPrevStep(true); + setCurrentStep(false); + }} + /> +
+ ); +}; + +export default SlippageBox; diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index 64c7a5e..6745613 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -42,6 +42,7 @@ import BigNumber from "bignumber.js"; import { updateEvmPositions } from "@utils/position-utils/evmPositions"; import Countdown from "../Countdown"; import { createNumRegex } from "@utils/createRegex"; +import SlippageBox from "../SlippageBox"; interface ChosenMethodProps { farm: FarmType; @@ -79,6 +80,7 @@ const StakingModal = () => { // Transaction Process Steps const [isConfirmStep, setIsConfirmStep] = useState(false); const [isProcessStep, setIsProcessStep] = useState(false); + const [isSlippageStep, setIsSlippageStep] = useState(false); const tokenNames = formatTokenSymbols(farm?.asset.symbol ?? ""); @@ -538,8 +540,8 @@ const StakingModal = () => { Slippage Tolerance: {SLIPPAGE}%
diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 1c7d779..0983887 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -10,7 +10,7 @@ import { import { useAtom } from "jotai"; import clsx from "clsx"; import Image from "next/image"; -import { parseAbi, parseUnits, parseEther } from "viem"; +import { parseAbi } from "viem"; import { useAccount, useBalance, @@ -26,17 +26,11 @@ import { CogIcon } from "@heroicons/react/solid"; // Component, Util and Hook Imports import MButton from "@components/Library/MButton"; import Spinner from "@components/Library/Spinner"; -import { - addLiqModalOpenAtom, - evmPosLoadingAtom, - lpUpdatedAtom, - slippageModalOpenAtom, -} from "@store/commonAtoms"; +import { addLiqModalOpenAtom, slippageModalOpenAtom } from "@store/commonAtoms"; import { selectedFarmAtom, slippageAtom, tokenPricesAtom, - farmsAtom, positionsAtom, lpTokenPricesAtom, } from "@store/atoms"; @@ -56,10 +50,7 @@ import { getNativeTokenAddress } from "@utils/network"; import WrongNetworkModal from "../WrongNetworkModal"; import { handleAddLiquidityEvent } from "@utils/tracking"; import getTimestamp from "@utils/getTimestamp"; -import { - // fetchEvmPositions, - updateEvmPositions, -} from "@utils/position-utils/evmPositions"; +import { updateEvmPositions } from "@utils/position-utils/evmPositions"; import BigNumber from "bignumber.js"; import Countdown from "../Countdown"; import { createNumRegex } from "@utils/createRegex"; @@ -87,12 +78,9 @@ const AddSectionStandard: FC = () => { const [isSlippageModalOpen, setIsSlippageModalOpen] = useAtom( slippageModalOpenAtom ); - const [farms] = useAtom(farmsAtom); const [positions, setPositions] = useAtom(positionsAtom); const [lpTokenPricesMap] = useAtom(lpTokenPricesAtom); const [tokenPricesMap] = useAtom(tokenPricesAtom); - // const [, setIsEvmPosLoading] = useAtom(evmPosLoadingAtom); - // const [lpUpdated, setLpUpdated] = useAtom(lpUpdatedAtom); const [SLIPPAGE] = useAtom(slippageAtom); const [txnHash, setTxnHash] = useState(""); @@ -124,121 +112,6 @@ const AddSectionStandard: FC = () => { selectedFarm?.protocol!, selectedFarm?.router! ); - // let iface = new ethers.Interface( - // getRouterAbi( - // selectedFarm?.protocol!, - // selectedFarm?.farmType == "StandardAmm" ? false : true - // ) - // ); - // const fdata = new ethers.Interface( - // getRouterAbi( - // selectedFarm?.protocol!, - // selectedFarm?.farmType == "StandardAmm" ? false : true - // ) - // ).encodeFunctionData( - // getAddLiqFunctionName(selectedFarm?.protocol as string) as any, - // [ - // farmAsset0?.address, // TokenA Address - // farmAsset1?.address, // TokenB Address - // // 1, - // // 1, - // // 1, - // // 1, - // parseUnits( - // `${ - // firstTokenAmount == "" || firstTokenAmount == "0" - // ? 1 - // : parseFloat(firstTokenAmount) - // }`, - // farmAsset0?.decimals - // ), - // parseUnits( - // `${ - // secondTokenAmount == "" || secondTokenAmount == "0" - // ? 1 / - // getPoolRatio( - // reserve0, - // reserve1, - // farmAsset0.decimals, - // farmAsset1.decimals - // ) - // : parseFloat(secondTokenAmount) - // }`, - // farmAsset1?.decimals - // ), - // parseUnits( - // `${ - // (firstTokenAmount == "" || firstTokenAmount == "0" - // ? 1 - // : parseFloat(firstTokenAmount) * (100 - SLIPPAGE)) / 100 - // }`, - // farmAsset0?.decimals - // ), // amountAMin - // parseUnits( - // `${ - // (secondTokenAmount == "" || secondTokenAmount == "0" - // ? 1 / - // getPoolRatio( - // reserve0, - // reserve1, - // farmAsset0.decimals, - // farmAsset1.decimals - // ) - // : parseFloat(secondTokenAmount) * (100 - SLIPPAGE)) / 100 - // }`, - // farmAsset1?.decimals - // ), // amountBMin - // address, // To - // 1784096161000, // deadline (uint256) - // ] - // ); - // const x = estimateGas(iface, fdata, selectedFarm!.router, address!); - - // useEffect(function siriusReserves() { - // if (selectedFarm?.protocol!.toLowerCase() == "sirius") { - // const { data: bal0 } = useContractRead({ - // address: selectedFarm?.router!, - // abi: parseAbi(siriusRouterAbi), - // functionName: "getTokenBalance", - // args: [0], - // enabled: !!selectedFarm?.protocol! && !!selectedFarm?.router!, - // }); - // const { data: bal1 } = useContractRead({ - // address: selectedFarm?.router!, - // abi: parseAbi(siriusRouterAbi), - // functionName: "getTokenBalance", - // args: [1], - // enabled: !!selectedFarm?.protocol! && !!selectedFarm?.router!, - // }); - // reserve0 = (bal0 as bigint).toString(); - // reserve1 = (bal1 as bigint).toString(); - // // console.log("sirbal", bal0, bal1, router, selectedFarm?.protocol!); - // // return { - // // reserve0: (bal0 as bigint).toString(), - // // reserve1: (bal1 as bigint).toString(), - // // }; - // } - // }); - // const { data: bal0 } = useContractRead({ - // address: selectedFarm?.router!, - // abi: parseAbi(siriusRouterAbi), - // functionName: "getTokenBalance", - // args: [0], - // enabled: !!selectedFarm?.protocol! && !!selectedFarm?.router!, - // }); - // // eslint-disable-next-line react-hooks/rules-of-hooks - // const { data: bal1 } = useContractRead({ - // address: selectedFarm?.router!, - // abi: parseAbi(siriusRouterAbi), - // functionName: "getTokenBalance", - // args: [1], - // enabled: !!selectedFarm?.protocol! && !!selectedFarm?.router!, - // }); - // // console.log("sirbal", bal0, bal1, router, selectedFarm?.protocol!); - // // return { - // // reserve0: (bal0 as bigint).toString(), - // // reserve1: (bal1 as bigint).toString(), - // // }; const { minLpTokens, totalSupply } = useMinimumLPTokens( selectedFarm?.asset.address!, diff --git a/src/components/Library/AddLiquidityModal/TokenInput.tsx b/src/components/Library/AddLiquidityModal/TokenInput.tsx index 2ff13b8..8502a3c 100644 --- a/src/components/Library/AddLiquidityModal/TokenInput.tsx +++ b/src/components/Library/AddLiquidityModal/TokenInput.tsx @@ -75,17 +75,17 @@ const TokenInput: React.FC = ({ } }, [isSuccess]); - function isAllTrue(isApprovingMap: { [address: string]: boolean }): boolean { - // Iterate over the keys in isApprovingMap - for (const address in isApprovingMap) { - // If any value is false, return false - if (!isApprovingMap[address]) { - return false; - } - } - // If all values are true, return true - return true; - } + // function isAllTrue(isApprovingMap: { [address: string]: boolean }): boolean { + // // Iterate over the keys in isApprovingMap + // for (const address in isApprovingMap) { + // // If any value is false, return false + // if (!isApprovingMap[address]) { + // return false; + // } + // } + // // If all values are true, return true + // return true; + // } return (
@@ -121,7 +121,7 @@ const TokenInput: React.FC = ({ : "text-[#4E4C4C]" )} min={0} - disabled={isAllTrue(isApproving)} + // disabled={isAllTrue(isApproving)} value={inputMap[token?.address] ?? ""} onChange={(event) => { event.preventDefault(); From fbd95aca0c047ba6ef2cce63bc2fb621ae178757 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 23 Aug 2023 16:04:34 +0530 Subject: [PATCH 17/27] revamped: useapprovalhooks improvised --- src/hooks/useApprovalHooks.ts | 91 +++++++++++++++++------------------ 1 file changed, 44 insertions(+), 47 deletions(-) diff --git a/src/hooks/useApprovalHooks.ts b/src/hooks/useApprovalHooks.ts index c4cd117..763c8dc 100644 --- a/src/hooks/useApprovalHooks.ts +++ b/src/hooks/useApprovalHooks.ts @@ -7,70 +7,63 @@ import { useWaitForTransaction, } from "wagmi"; import { tokenAbi } from "@components/Common/Layout/evmUtils"; -import { useEffect } from "react"; +import { useEffect, useMemo } from "react"; import toast from "react-hot-toast"; import BigNumber from "bignumber.js"; +// Define known structure for tokenBalance (Modify as needed) +interface TokenBalance { + decimals: number; + formatted: string; + symbol: string; + value: bigint; +} + /** + * Check if a token is approved. * - * @param token Underlying Asset - * @param spender spender Contract Address - * @returns data, isLoading, isError, isSuccess + * @param tokenAddress Address of the token + * @param spender Contract address of the spender + * @param tokenBalance Balance of the token + * @param input Input value + * @returns Object containing data, isLoading, isError, and isSuccess */ const useIsApprovedToken = ( tokenAddress: Address, spender: Address, - tokenBalance: any | undefined, + tokenBalance: TokenBalance | undefined, input: number ) => { const { address } = useAccount(); + const { data, isLoading, isError } = useContractRead({ address: tokenAddress, abi: parseAbi(tokenAbi), - functionName: "allowance" as any, - args: [ - address, // owner - spender, // spender - ], + functionName: "allowance", + args: [address, spender], // owner, spender enabled: !!address && !!spender, }); - const allow = data as bigint; + const allowanceRaw = data as bigint; - const allowance = BigNumber(allow?.toString() ?? "0", 10) - // .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals)) - .decimalPlaces(0, 1); + const allowance = new BigNumber( + allowanceRaw?.toString() ?? "0" + ).decimalPlaces(0, 1); // // console.log("allowance bigint", allow); // console.log("allowance", allowance.toString()); - // console.log("rawinput", input); - // console.log("tokenbalance", tokenBalance); - - const inputAmount = BigNumber(input.toString(), 10) - .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals)) - .decimalPlaces(0, 1); - // console.log("inputAmount", inputAmount.toString()); + const inputAmount = useMemo(() => { + if (tokenBalance?.decimals && input) { + return new BigNumber(input.toString()) + .multipliedBy(new BigNumber(10).pow(tokenBalance.decimals)) + .decimalPlaces(0, 1); + } + return new BigNumber(0); + }, [tokenBalance, input]); const compare = inputAmount.isLessThanOrEqualTo(allowance); // console.log("compare", compare); - // const isSuccess = useMemo(() => { - // const numdata = Number(data) / 10 ** 12; - // // // console.log( - // // "token_address", - // // tokenAddress, - // // "\ndata", - // // data, - // // "\nnumber_data", - // // numdata, - // // "\ntokenBalance", - // // parseFloat(tokenBalance ?? "0"), - // // "\nisApproved: should be true if data >= tokenBalance" - // // // !tokenBalance ? false : numdata >= formatData(parseFloat(tokenBalance)) - // // // !input ? false : numdata >= formatData(parseFloat(tokenBalance)) - // // ); - - // // allowed tokens >= token balance // // return !tokenBalance // // ? false // // : numdata >= formatData(parseFloat(tokenBalance)); @@ -79,19 +72,22 @@ const useIsApprovedToken = ( }; /** + * Approve a token. * - * @param token Underlying Asset - * @param spender spender Contract Address - * @returns data, isLoadingApproveCall, isLoadingApproveTxn, isError, isSuccessApproveCall, isSuccessApproveTxn, writeAsync + * @param tokenAddress Address of the token + * @param spender Contract address of the spender + * @param tokenSymbol Symbol of the token + * @param tokenBalance Balance of the token + * @returns Object containing various states and the writeAsync function */ const useApproveToken = ( tokenAddress: Address, spender: Address, tokenSymbol: string, - tokenBalance: any | undefined + tokenBalance: TokenBalance | undefined ) => { const { chain } = useNetwork(); - // console.log("token", tokenSymbol, "\ntokenBalance", tokenBalance); + const { data, isLoading: isLoadingApproveCall, @@ -104,14 +100,15 @@ const useApproveToken = ( functionName: "approve" as any, chainId: chain?.id, args: [ - spender, // spender - BigNumber(tokenBalance?.formatted, 10) - .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals)) + spender, + new BigNumber(tokenBalance?.formatted ?? "0") + .multipliedBy(new BigNumber(10).pow(tokenBalance?.decimals ?? 0)) .decimalPlaces(0, 1) .toString(), ], onError: (error) => { - // console.log(`Error while Approving:`, error); + // This is just logging the error. Depending on your needs, you might want to show this to the user or take corrective action. + console.error(`Error while Approving:`, error); }, }); From 9cca276b2658b0a7bba0d55ca0e95a1a04284007 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 23 Aug 2023 17:05:42 +0530 Subject: [PATCH 18/27] addstable fix --- .../Library/AddLiquidityModal/AddSectionStable.tsx | 2 +- src/components/Library/AddLiquidityModal/TokenButton.tsx | 2 ++ src/hooks/useApprovalHooks.ts | 9 ++++++--- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index 1848345..0926b3e 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -172,7 +172,7 @@ const AddSectionStable: FC = () => { // Setting inputMapAmount of amount array for calculation setInputMapAmount((pre: any) => ({ ...pre, - [token.address]: isNaN(parseFloat(value)) ? 0 : value, + [token.address]: isNaN(parseFloat(value)) ? 0 : parseFloat(value), })); }, []); diff --git a/src/components/Library/AddLiquidityModal/TokenButton.tsx b/src/components/Library/AddLiquidityModal/TokenButton.tsx index 7b241d3..3ec3283 100644 --- a/src/components/Library/AddLiquidityModal/TokenButton.tsx +++ b/src/components/Library/AddLiquidityModal/TokenButton.tsx @@ -56,6 +56,8 @@ const TokenButton: React.FC = ({ inputMapAmount[token?.address] ); + console.log("inputMapAmount[token?.address]", inputMapAmount, token?.address); + // Approve token const { isLoadingApproveCall, diff --git a/src/hooks/useApprovalHooks.ts b/src/hooks/useApprovalHooks.ts index 763c8dc..f244879 100644 --- a/src/hooks/useApprovalHooks.ts +++ b/src/hooks/useApprovalHooks.ts @@ -49,8 +49,8 @@ const useIsApprovedToken = ( const allowance = new BigNumber( allowanceRaw?.toString() ?? "0" ).decimalPlaces(0, 1); - // // console.log("allowance bigint", allow); - // console.log("allowance", allowance.toString()); + // console.log("allowance bigint", allowance); + console.log("allowance", allowanceRaw); const inputAmount = useMemo(() => { if (tokenBalance?.decimals && input) { @@ -61,8 +61,11 @@ const useIsApprovedToken = ( return new BigNumber(0); }, [tokenBalance, input]); + console.log("input", input); + console.log("inputAmount", inputAmount); + const compare = inputAmount.isLessThanOrEqualTo(allowance); - // console.log("compare", compare); + console.log("compare", compare); // const isSuccess = useMemo(() => { // // return !tokenBalance // // ? false From cdea57a81637d1911c59d8cc334bc383ef3d1d6e Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 23 Aug 2023 20:32:05 +0530 Subject: [PATCH 19/27] approval stable fix --- .../Library/AddLiquidityModal/TokenButton.tsx | 3 +- src/hooks/useApprovalHooks.ts | 32 +++++++++++-------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/TokenButton.tsx b/src/components/Library/AddLiquidityModal/TokenButton.tsx index 3ec3283..9eb8550 100644 --- a/src/components/Library/AddLiquidityModal/TokenButton.tsx +++ b/src/components/Library/AddLiquidityModal/TokenButton.tsx @@ -56,8 +56,6 @@ const TokenButton: React.FC = ({ inputMapAmount[token?.address] ); - console.log("inputMapAmount[token?.address]", inputMapAmount, token?.address); - // Approve token const { isLoadingApproveCall, @@ -106,6 +104,7 @@ const TokenButton: React.FC = ({ !inputMapAmount[token?.address] || Object.keys(approvalMap).find((key) => key === token?.address) ) { + // console.log("ApprovalMap", approvalMap, !inputMapAmount[token?.address]); return <>; } diff --git a/src/hooks/useApprovalHooks.ts b/src/hooks/useApprovalHooks.ts index f244879..a88e042 100644 --- a/src/hooks/useApprovalHooks.ts +++ b/src/hooks/useApprovalHooks.ts @@ -46,26 +46,29 @@ const useIsApprovedToken = ( const allowanceRaw = data as bigint; - const allowance = new BigNumber( - allowanceRaw?.toString() ?? "0" - ).decimalPlaces(0, 1); + const allowance = BigNumber(allowanceRaw?.toString() ?? "0").decimalPlaces( + 0, + 1 + ); // console.log("allowance bigint", allowance); - console.log("allowance", allowanceRaw); + // console.log("allowance", allowanceRaw); const inputAmount = useMemo(() => { if (tokenBalance?.decimals && input) { - return new BigNumber(input.toString()) - .multipliedBy(new BigNumber(10).pow(tokenBalance.decimals)) + return BigNumber(input.toString()) + .multipliedBy(BigNumber(10).pow(tokenBalance.decimals)) .decimalPlaces(0, 1); } - return new BigNumber(0); + return BigNumber(0); }, [tokenBalance, input]); - console.log("input", input); - console.log("inputAmount", inputAmount); + // console.log("input", input); - const compare = inputAmount.isLessThanOrEqualTo(allowance); - console.log("compare", compare); + const compare = + input == undefined || input == 0 + ? false + : inputAmount.isLessThanOrEqualTo(allowance); + // console.log("compare", compare); // const isSuccess = useMemo(() => { // // return !tokenBalance // // ? false @@ -104,8 +107,8 @@ const useApproveToken = ( chainId: chain?.id, args: [ spender, - new BigNumber(tokenBalance?.formatted ?? "0") - .multipliedBy(new BigNumber(10).pow(tokenBalance?.decimals ?? 0)) + BigNumber(tokenBalance?.formatted ?? "0") + .multipliedBy(BigNumber(10).pow(tokenBalance?.decimals ?? 0)) .decimalPlaces(0, 1) .toString(), ], @@ -124,6 +127,9 @@ const useApproveToken = ( useEffect(() => { if (isSuccessApproveTxn) { toast(`${tokenSymbol} Approved!`); + // console.log( + // `${tokenSymbol} Approved by ${tokenBalance?.formatted} Amount` + // ); } }, [isSuccessApproveTxn]); From bf000ac1235a3680d1706a4137c478d4e7de6c40 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 23 Aug 2023 20:54:14 +0530 Subject: [PATCH 20/27] add standard approve btn copy --- .../AddLiquidityModal/AddSectionStandard.tsx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 0983887..7b24b69 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -733,7 +733,9 @@ const AddSectionStandard: FC = () => { approveToken0CallLoading || approveToken0TxnLoading } text={ - approveToken0CallLoading + fixedAmtNum(firstTokenAmount) <= 0 + ? "Please enter amount" + : approveToken0CallLoading ? "Sign the Txn in Wallet" : approveToken0TxnLoading ? "Waiting for Approval" @@ -743,7 +745,8 @@ const AddSectionStandard: FC = () => { approveToken0TxnSuccess || approveToken0CallLoading || approveToken0TxnLoading || - typeof approveToken0 == "undefined" + typeof approveToken0 == "undefined" || + fixedAmtNum(firstTokenAmount) <= 0 // fixedAmtNum(nativeBal?.formatted) <= gasEstimate } onClick={async () => { @@ -768,7 +771,9 @@ const AddSectionStandard: FC = () => { approveToken1CallLoading || approveToken1TxnLoading } text={ - approveToken1CallLoading + fixedAmtNum(secondTokenAmount) <= 0 + ? "Please enter amount" + : approveToken1CallLoading ? "Sign the Txn in Wallet" : approveToken1TxnLoading ? "Waiting for Approval" @@ -778,7 +783,8 @@ const AddSectionStandard: FC = () => { approveToken1TxnSuccess || approveToken1CallLoading || approveToken1TxnLoading || - typeof approveToken1 == "undefined" + typeof approveToken1 == "undefined" || + fixedAmtNum(secondTokenAmount) <= 0 // fixedAmtNum(nativeBal?.formatted) <= gasEstimate } onClick={async () => { From 32f4fb1865eea11e07e77a62b63162eaaa647467 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Wed, 23 Aug 2023 21:11:48 +0530 Subject: [PATCH 21/27] rest modals approve btn copy --- .../Library/RemoveLiquidityModal/ChosenMethod.tsx | 8 ++++---- .../RemoveLiquidityModal/RemoveSectionStable.tsx | 13 +++++++++++-- .../RemoveLiquidityModal/RemoveSectionStandard.tsx | 13 +++++++++++-- src/components/Library/StakingModal/index.tsx | 13 ++++++++++++- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/components/Library/RemoveLiquidityModal/ChosenMethod.tsx b/src/components/Library/RemoveLiquidityModal/ChosenMethod.tsx index 4104b7c..76b0e02 100644 --- a/src/components/Library/RemoveLiquidityModal/ChosenMethod.tsx +++ b/src/components/Library/RemoveLiquidityModal/ChosenMethod.tsx @@ -122,22 +122,22 @@ const ChosenMethod: React.FC = ({ autoFocus />
-

+

{lpBalLoading ? ( loading... ) : ( !!lpBal && ( -
+

Balance {parseFloat(lpBal) < 0.01 ? "<0.01" : toUnits(parseFloat(lpBal), 2)} -

+

) )} -

+
-
-
- {fixedAmtNum(firstTokenAmount) > - fixedAmtNum(token0Balance?.formatted) && ( -
- {focusedInput == InputType.First - ? "Insufficient Balance" - : `You need ${ - fixedAmtNum(firstTokenAmount) - - fixedAmtNum(token0Balance?.formatted) - } ${ - farmAsset0?.symbol - } for creating an LP token with ${fixedAmtNum( - secondTokenAmount - )} ${farmAsset1?.symbol}`} -
- )} + {/* Plus Icon */}
Plus
{/* Second token container */} -
-
-
- {selectedFarm?.asset.logos[1] -
- - {farmAsset1?.symbol} - -
- setFocusedInput(InputType.Off)} - onFocus={() => setFocusedInput(InputType.Second)} - autoFocus={focusedInput === InputType.Second} - /> -
-
- {token1BalanceLoading ? ( - loading... - ) : ( - !!token1Balance && ( -

- Balance - - {parseFloat(token1Balance?.formatted).toLocaleString( - "en-US" - )} - -

- ) - )} -
- -
-
- {fixedAmtNum(secondTokenAmount) > - fixedAmtNum(token1Balance?.formatted) && ( -
- {focusedInput == InputType.Second - ? "Insufficient Balance" - : `You need ${ - fixedAmtNum(secondTokenAmount) - - fixedAmtNum(token1Balance?.formatted) - } ${ - farmAsset1?.symbol - } for creating an LP token with ${fixedAmtNum( - firstTokenAmount - )} ${farmAsset0?.symbol}`} -
- )} - + {/* Relative Conversion and Share of Pool */}
@@ -741,14 +631,7 @@ const AddSectionStandard: FC = () => { ? "Waiting for Approval" : `Approve ${farmAsset0.symbol}` } - disabled={ - approveToken0TxnSuccess || - approveToken0CallLoading || - approveToken0TxnLoading || - typeof approveToken0 == "undefined" || - fixedAmtNum(firstTokenAmount) <= 0 - // fixedAmtNum(nativeBal?.formatted) <= gasEstimate - } + disabled={disableApproveFirstToken} onClick={async () => { try { const txn = await approveToken0?.(); @@ -779,14 +662,7 @@ const AddSectionStandard: FC = () => { ? "Waiting for Approval" : `Approve ${farmAsset1.symbol}` } - disabled={ - approveToken1TxnSuccess || - approveToken1CallLoading || - approveToken1TxnLoading || - typeof approveToken1 == "undefined" || - fixedAmtNum(secondTokenAmount) <= 0 - // fixedAmtNum(nativeBal?.formatted) <= gasEstimate - } + disabled={disableApproveSecondToken} onClick={async () => { try { const txn = await approveToken1?.(); @@ -803,20 +679,7 @@ const AddSectionStandard: FC = () => { - fixedAmtNum(token0Balance?.formatted) || - fixedAmtNum(secondTokenAmount) > - fixedAmtNum(token1Balance?.formatted) - } + disabled={disableConfirmButton} text="Confirm Adding Liquidity" onClick={() => { setIsConfirmStep(true); @@ -841,32 +704,23 @@ const AddSectionStandard: FC = () => { [ farmAsset0?.address, farmAsset1?.address, - BigNumber(firstTokenAmount, 10) - .multipliedBy(BigNumber(10).pow(farmAsset0?.decimals)) - .decimalPlaces(0, 1) - .toString(), - BigNumber(secondTokenAmount, 10) - .multipliedBy(BigNumber(10).pow(farmAsset1?.decimals)) - .decimalPlaces(0, 1) - .toString(), - BigNumber(firstTokenAmount, 10) - .multipliedBy((100 - SLIPPAGE) / 100) - .multipliedBy(BigNumber(10).pow(farmAsset0?.decimals)) - .decimalPlaces(0, 1) - .toString(), - BigNumber(secondTokenAmount, 10) - .multipliedBy((100 - SLIPPAGE) / 100) - .multipliedBy(BigNumber(10).pow(farmAsset1?.decimals)) - .decimalPlaces(0, 1) - .toString(), + formatTokenAmount(firstTokenAmount, farmAsset0?.decimals), + formatTokenAmount(secondTokenAmount, farmAsset1?.decimals), + formatTokenAmount( + firstTokenAmount, + farmAsset0?.decimals, + (100 - SLIPPAGE) / 100 + ), + formatTokenAmount( + secondTokenAmount, + farmAsset1?.decimals, + (100 - SLIPPAGE) / 100 + ), address, // To 1784096161000, // deadline (uint256) ] ); - // console.log("firstTokenAmount", firstTokenAmount); - // console.log("secondTokenAmount", secondTokenAmount); - return (
+
+
+ {fixedAmtNum(tokenAmount) > fixedAmtNum(tokenBalance?.formatted) && ( +
+ {focusedInput == inputToFocus + ? "Insufficient Balance" + : `You need ${ + fixedAmtNum(tokenAmount) - fixedAmtNum(tokenBalance?.formatted) + } ${tokenSymbol} for creating an LP token with ${fixedAmtNum( + otherTokenAmount + )} ${otherTokenSymbol}`} +
+ )} + + ); +}; + +export default TokenContainer; From 25320ca59053471066abde5fa73ab42b3f83d29f Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Thu, 24 Aug 2023 08:28:02 +0530 Subject: [PATCH 23/27] gasEstimate UI error handling & small amounts --- .../Library/AddLiquidityModal/AddSectionStable.tsx | 14 +++++++++++--- .../AddLiquidityModal/AddSectionStandard.tsx | 14 +++++++++++--- .../RemoveLiquidityModal/RemoveSectionStable.tsx | 14 +++++++++++--- .../RemoveLiquidityModal/RemoveSectionStandard.tsx | 14 +++++++++++--- src/components/Library/StakingModal/index.tsx | 14 +++++++++++--- src/components/Library/UnstakingModal/index.tsx | 14 +++++++++++--- 6 files changed, 66 insertions(+), 18 deletions(-) diff --git a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx index 0926b3e..d81c0b6 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStable.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStable.tsx @@ -544,14 +544,21 @@ const AddSectionStable: FC = () => { >
Estimated Gas Fees: - {gasEstimate === 0 && !isError ? ( + {isError ? ( +

Error estimating gas

+ ) : gasEstimate === 0 ? (

estimating gas...

) : (

- {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + {gasEstimate < 0.001 ? "<0.001" : gasEstimate.toFixed(3)}{" "} + {nativeBal?.symbol} - ${(gasEstimate * nativePrice).toFixed(5)} + {gasEstimate * nativePrice < 0.00001 ? ( + "<$0.00001" + ) : ( + ${(gasEstimate * nativePrice).toFixed(5)} + )}

)}
@@ -583,6 +590,7 @@ const AddSectionStable: FC = () => { { // console.log("args:", {}); diff --git a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx index 2e3ce3c..adf1bcd 100644 --- a/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx +++ b/src/components/Library/AddLiquidityModal/AddSectionStandard.tsx @@ -823,14 +823,21 @@ const AddSectionStandard: FC = () => { >
Estimated Gas Fees: - {gasEstimate === 0 && !isError ? ( + {isError ? ( +

Error estimating gas

+ ) : gasEstimate === 0 ? (

estimating gas...

) : (

- {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + {gasEstimate < 0.001 ? "<0.001" : gasEstimate.toFixed(3)}{" "} + {nativeBal?.symbol} - ${(gasEstimate * nativePrice).toFixed(5)} + {gasEstimate * nativePrice < 0.00001 ? ( + "<$0.00001" + ) : ( + ${(gasEstimate * nativePrice).toFixed(5)} + )}

)}
@@ -862,6 +869,7 @@ const AddSectionStandard: FC = () => { { // console.log("args:", { diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx index 0edd6d6..8220d6b 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStable.tsx @@ -710,14 +710,21 @@ const RemoveSectionStable: FC = () => { >
Estimated Gas Fees: - {gasEstimate === 0 && !isError ? ( + {isError ? ( +

Error estimating gas

+ ) : gasEstimate === 0 ? (

estimating gas...

) : (

- {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + {gasEstimate < 0.001 ? "<0.001" : gasEstimate.toFixed(3)}{" "} + {nativeBal?.symbol} - ${(gasEstimate * nativePrice).toFixed(5)} + {gasEstimate * nativePrice < 0.00001 ? ( + "<$0.00001" + ) : ( + ${(gasEstimate * nativePrice).toFixed(5)} + )}

)}
@@ -749,6 +756,7 @@ const RemoveSectionStable: FC = () => { { handleRemoveLiquidity(); diff --git a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx index 50e567c..6cb444d 100644 --- a/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx +++ b/src/components/Library/RemoveLiquidityModal/RemoveSectionStandard.tsx @@ -693,14 +693,21 @@ const RemoveSectionStandard = () => { >
Estimated Gas Fees: - {gasEstimate === 0 && !isError ? ( + {isError ? ( +

Error estimating gas

+ ) : gasEstimate === 0 ? (

estimating gas...

) : (

- {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + {gasEstimate < 0.001 ? "<0.001" : gasEstimate.toFixed(3)}{" "} + {nativeBal?.symbol} - ${(gasEstimate * nativePrice).toFixed(5)} + {gasEstimate * nativePrice < 0.00001 ? ( + "<$0.00001" + ) : ( + ${(gasEstimate * nativePrice).toFixed(5)} + )}

)}
@@ -732,6 +739,7 @@ const RemoveSectionStandard = () => { { await handleRemoveLiquidity(); diff --git a/src/components/Library/StakingModal/index.tsx b/src/components/Library/StakingModal/index.tsx index cd6691d..a7b185c 100644 --- a/src/components/Library/StakingModal/index.tsx +++ b/src/components/Library/StakingModal/index.tsx @@ -536,14 +536,21 @@ const StakingModal = () => { >
Estimated Gas Fees: - {gasEstimate === 0 && !isError ? ( + {isError ? ( +

Error estimating gas

+ ) : gasEstimate === 0 ? (

estimating gas...

) : (

- {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + {gasEstimate < 0.001 ? "<0.001" : gasEstimate.toFixed(3)}{" "} + {nativeBal?.symbol} - ${(gasEstimate * nativePrice).toFixed(5)} + {gasEstimate * nativePrice < 0.00001 ? ( + "<$0.00001" + ) : ( + ${(gasEstimate * nativePrice).toFixed(5)} + )}

)}
@@ -575,6 +582,7 @@ const StakingModal = () => { { handleStaking(); diff --git a/src/components/Library/UnstakingModal/index.tsx b/src/components/Library/UnstakingModal/index.tsx index 4d20c7a..68249aa 100644 --- a/src/components/Library/UnstakingModal/index.tsx +++ b/src/components/Library/UnstakingModal/index.tsx @@ -478,14 +478,21 @@ const UnstakingModal = () => { >
Estimated Gas Fees: - {gasEstimate === 0 && !isError ? ( + {isError ? ( +

Error estimating gas

+ ) : gasEstimate === 0 ? (

estimating gas...

) : (

- {gasEstimate.toFixed(3) ?? 0} {nativeBal?.symbol} + {gasEstimate < 0.001 ? "<0.001" : gasEstimate.toFixed(3)}{" "} + {nativeBal?.symbol} - ${(gasEstimate * nativePrice).toFixed(5)} + {gasEstimate * nativePrice < 0.00001 ? ( + "<$0.00001" + ) : ( + ${(gasEstimate * nativePrice).toFixed(5)} + )}

)}
@@ -517,6 +524,7 @@ const UnstakingModal = () => { { handleUnstaking(); From c77753ee898ffe0a67073b3f16827d41242ea2b1 Mon Sep 17 00:00:00 2001 From: Luke Skywalker Date: Thu, 24 Aug 2023 17:36:39 +0530 Subject: [PATCH 24/27] AddStable minor-audit, tokenInput for ASTR, Hide a pool --- src/components/App/FarmList.tsx | 8 +++ .../AddLiquidityModal/AddSectionStable.tsx | 70 +++++++++---------- .../Library/AddLiquidityModal/TokenInput.tsx | 14 +++- 3 files changed, 53 insertions(+), 39 deletions(-) diff --git a/src/components/App/FarmList.tsx b/src/components/App/FarmList.tsx index f9b122a..71c679b 100644 --- a/src/components/App/FarmList.tsx +++ b/src/components/App/FarmList.tsx @@ -55,6 +55,14 @@ const FarmsList: FC = ({ farms, positions }) => { undefined; const isSupported = checkIfPoolSupported(farm); + // Skipping a particular farm + if ( + farm?.id == 1 && + farm?.asset.address == "0xcB274236fBA7B873FC8F154bb0475a166C24B119" + ) { + return; + } + return ( { const publicClient = usePublicClient(); const { address, connector } = useAccount(); const { chain } = useNetwork(); - // const [isApproving, setIsApproving] = useState(false); - // Transaction Process Steps const [isConfirmStep, setIsConfirmStep] = useState(false); const [isProcessStep, setIsProcessStep] = useState(false); @@ -92,7 +104,7 @@ const AddSectionStable: FC = () => { // const [farms] = useAtom(farmsAtom); const [positions, setPositions] = useAtom(positionsAtom); const [lpTokenPricesMap, setLpTokenPricesMap] = useAtom(lpTokenPricesAtom); - const [lpUpdated, setLpUpdated] = useAtom(lpUpdatedAtom); + // const [lpUpdated, setLpUpdated] = useAtom(lpUpdatedAtom); const [tokenPricesMap] = useAtom(tokenPricesAtom); const [, setIsEvmPosLoading] = useAtom(evmPosLoadingAtom); // Checking if farm assets have a lp-token pair @@ -100,19 +112,7 @@ const AddSectionStable: FC = () => { const symbol = farm?.asset.symbol; const assetLogos = farm?.asset.logos; let logos: (string | string[])[]; - if ( - symbol == "MAI-tripool" || - symbol == "FRAX-3pool" || - symbol == "MIM-3pool" || - symbol == "MAI-3pool" || - symbol == "4PUSDT" || - symbol == "4JPYC" || - symbol == "4WETH" || - symbol == "4oUSD" || - symbol == "4BAI" || - symbol == "4WBNB" - ) { - // eg. FRAX-tripool -- logos = [FRAX, [USDC, BUSD, USDT]] + if (STABLE_AMM_SYMBOLS.includes(symbol ?? "")) { logos = [ assetLogos?.[0]!, [assetLogos?.[1]!, assetLogos?.[2]!, assetLogos?.[3]!], @@ -164,15 +164,16 @@ const AddSectionStable: FC = () => { // const tokens = farm?.asset.underlyingAssets ?? []; const handleInput = useCallback((token: UnderlyingAssets, value: string) => { + const parsedValue = isNaN(parseFloat(value)) ? 0 : parseFloat(value); // Setting inputMap for Input fields - setInputMap((pre: any) => ({ + setInputMap((pre: { [address: Address]: string }) => ({ ...pre, [token.address]: value, })); // Setting inputMapAmount of amount array for calculation - setInputMapAmount((pre: any) => ({ + setInputMapAmount((pre: { [address: Address]: number }) => ({ ...pre, - [token.address]: isNaN(parseFloat(value)) ? 0 : parseFloat(value), + [token.address]: parsedValue, })); }, []); @@ -301,9 +302,9 @@ const AddSectionStable: FC = () => { }); }, [approvalMap, inputMapAmount]); - useEffect(() => { - // console.log("balanceMap", balanceMap); - }, [balanceMap]); + // useEffect(() => { + // console.log("balanceMap", balanceMap); + // }, [balanceMap]); const isSufficientBalance = useMemo(() => { return Object.entries(balanceMap).every(([tokenAddress, balance]) => { @@ -315,11 +316,11 @@ const AddSectionStable: FC = () => { }); }, [inputMapAmount, balanceMap]); - useEffect(() => { - // console.log("isRequirementApproved", isRequirementApproved); - // console.log("approvalMap", approvalMap); - // console.log("inputMapAmount", inputMapAmount); - }, [isRequirementApproved]); + // useEffect(() => { + // console.log("isRequirementApproved", isRequirementApproved); + // console.log("approvalMap", approvalMap); + // console.log("inputMapAmount", inputMapAmount); + // }, [isRequirementApproved]); const handleAddLiquidity = async () => { try { @@ -327,18 +328,19 @@ const AddSectionStable: FC = () => { const block = await publicClient.getBlock(); const blocktimestamp = Number(block.timestamp.toString() + "000") + 60000 * 30; // Adding 30 minutes - // console.log("timestamp fetched //", blocktimestamp); - // console.log("calling addliquidity method...", amounts, estLpAmount); - + const minToMint = parseUnits( + `${(estLpAmount * (100 - SLIPPAGE)) / 100}`, + 18 + ); const args_to_pass = farm?.protocol.toLowerCase() == "curve" ? [ amounts, // amounts (uint256[]) - parseUnits(`${(estLpAmount * (100 - SLIPPAGE)) / 100}`, 18), // minToMint (uint256) + minToMint, // minToMint (uint256) ] : [ amounts, // amounts (uint256[]) - parseUnits(`${(estLpAmount * (100 - SLIPPAGE)) / 100}`, 18), // minToMint (uint256) + minToMint, // minToMint (uint256) blocktimestamp, // deadline (uint256) ]; @@ -387,10 +389,6 @@ const AddSectionStable: FC = () => { {/* Relative Conversion and Share of Pool */}
- {/*
-

0.1234 GLMR per STELLA

-

0.1234 STELLA per GLMR

-
*/}

{(totalSupply !== 0 && estLpAmount > 0 diff --git a/src/components/Library/AddLiquidityModal/TokenInput.tsx b/src/components/Library/AddLiquidityModal/TokenInput.tsx index 8502a3c..d8dbe5a 100644 --- a/src/components/Library/AddLiquidityModal/TokenInput.tsx +++ b/src/components/Library/AddLiquidityModal/TokenInput.tsx @@ -116,7 +116,9 @@ const TokenInput: React.FC = ({ className={clsx( "text-base font-bold leading-6 text-left bg-transparent focus:outline-none", fixedAmtNum(inputMap[token.address]) > - fixedAmtNum(balance?.formatted) + fixedAmtNum( + token?.symbol == "ASTR" ? nativeBal : balance?.formatted + ) ? "text-[#FF9999]" : "text-[#4E4C4C]" )} @@ -159,7 +161,10 @@ const TokenInput: React.FC = ({

)} -
- - Staked at {(thisFarm?.apr.base + thisFarm?.apr.reward).toFixed(2)}% - APY - - - View Farm - -
+ {/* Banner -- Display the APR at which liquidity is staked in a Pool */} + {position.staked.amount > 0 && !!thisFarm && ( +
+ + Staked at {(thisFarm.apr.base + thisFarm.apr.reward).toFixed(2)}% + APY + + + View Farm + +
+ )}
);