Skip to content

Commit

Permalink
feat: update
Browse files Browse the repository at this point in the history
  • Loading branch information
Space-Bean committed Jul 14, 2024
1 parent 68eaa50 commit 2e83c71
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 40 deletions.
8 changes: 8 additions & 0 deletions projects/dex-ui/src/assets/images/tokens/BEANWSTETHCP2w.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 1 addition & 6 deletions projects/dex-ui/src/components/Liquidity/AddLiquidity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const AddLiquidityContent = ({
staleTime: 15 * 1000,
refetchOnWindowFocus: "always",
select: (data) => {
return [data[token1.symbol] || null, data[token2.symbol] || null];
return [data[token1.symbol] || null, data[token2.symbol] || null]; // price indexed by token symbol
}
});
const invalidate = useInvalidateScopedQueries();
Expand All @@ -91,11 +91,6 @@ const AddLiquidityContent = ({
const someWellReservesEmpty = Boolean(wellReserves && wellReserves.some((reserve) => reserve.eq(0)));
const areSomeInputsZero = Boolean(inputs.some((amt) => amt.value.eq("0")));

useEffect(() => {
console.log({ someWellReservesEmpty, areSomeInputsZero });

}, [someWellReservesEmpty, areSomeInputsZero])

const atLeastOneAmountNonZero = useMemo(() => {
if (!well.tokens || well.tokens.length === 0) return false;

Expand Down
123 changes: 90 additions & 33 deletions projects/dex-ui/src/components/Liquidity/RemoveLiquidity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import React, { useCallback, useEffect, useMemo, useState } from "react";
import { TokenInput } from "src/components/Swap/TokenInput";
import { Token, TokenValue } from "@beanstalk/sdk";
import styled from "styled-components";
import { images } from "src/assets/images/tokens";
import { useAccount } from "wagmi";
import { Well } from "@beanstalk/sdk/Wells";
import { useLiquidityQuote } from "src/wells/useLiquidityQuote";
Expand All @@ -24,7 +23,6 @@ import { displayTokenSymbol } from "src/utils/format";
import { LoadingTemplate } from "../LoadingTemplate";
import { useLPPositionSummary } from "src/tokens/useLPPositionSummary";
import { ActionWalletButtonWrapper } from "src/components/Wallet";
import { useQueryClient } from "@tanstack/react-query";
import { useInvalidateScopedQueries } from "src/utils/query/useInvalidateQueries";
import { queryKeys } from "src/utils/query/queryKeys";

Expand All @@ -38,24 +36,31 @@ type RemoveLiquidityProps = {
well: Well;
} & BaseRemoveLiquidityProps;

const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler, handleSlippageValueChange }: RemoveLiquidityProps) => {
const RemoveLiquidityContent = ({
well,
slippage,
slippageSettingsClickHandler,
handleSlippageValueChange
}: RemoveLiquidityProps) => {
const { address } = useAccount();
const [wellLpToken, setWellLpToken] = useState<Token | null>(null);
const [lpTokenAmount, setLpTokenAmount] = useState<TokenValue | undefined>();
const [removeLiquidityMode, setRemoveLiquidityMode] = useState<REMOVE_LIQUIDITY_MODE>(REMOVE_LIQUIDITY_MODE.Balanced);
const [removeLiquidityMode, setRemoveLiquidityMode] = useState<REMOVE_LIQUIDITY_MODE>(
REMOVE_LIQUIDITY_MODE.Balanced
);
const [singleTokenIndex, setSingleTokenIndex] = useState<number>(0);
const [amounts, setAmounts] = useState<TokenValue[]>([]);
const [prices, setPrices] = useState<(TokenValue | null)[]>();
const [tokenAllowance, setTokenAllowance] = useState<boolean>(false);

const { getPositionWithWell, refetch: refetchLPSummary } = useLPPositionSummary();
const position = getPositionWithWell(well);
const invalidateScopedQuery = useInvalidateScopedQueries();

const { reserves: wellReserves, refetch: refetchWellReserves } = useWellReserves(well);
const sdk = useSdk();
const lpBalance = position?.external || TokenValue.ZERO;

useEffect(() => {
const run = async () => {
if (!well.tokens) return;
Expand All @@ -78,14 +83,13 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
const { oneTokenQuote } = oneToken;
const { customRatioQuote } = custom;

const hasEnoughBalance = !address || !wellLpToken || !lpTokenAmount || !lpBalance ? false : lpTokenAmount.lte(lpBalance);
const hasEnoughBalance =
!address || !wellLpToken || !lpTokenAmount || !lpBalance ? false : lpTokenAmount.lte(lpBalance);

useEffect(() => {
if (well.lpToken) {
let lpTokenWithMetadata = well.lpToken;
lpTokenWithMetadata.setMetadata({ logo: images[well.lpToken.symbol] ?? images.DEFAULT });
setLpTokenAmount(undefined);
setWellLpToken(lpTokenWithMetadata);
setWellLpToken(well.lpToken);
}
}, [well.lpToken]);

Expand Down Expand Up @@ -137,34 +141,46 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
return;
}
const quoteAmountLessSlippage = balancedQuote.quote.map((q) => q.subSlippage(slippage));
removeLiquidityTxn = await well.removeLiquidity(lpTokenAmount, quoteAmountLessSlippage, address, undefined, {
gasLimit: balancedQuote.estimate.mul(1.2).toBigNumber()
});
removeLiquidityTxn = await well.removeLiquidity(
lpTokenAmount,
quoteAmountLessSlippage,
address,
undefined,
{
gasLimit: balancedQuote.estimate.mul(1.2).toBigNumber()
}
);
toast.confirming(removeLiquidityTxn);
} else {
if (!customRatioQuote) {
return;
}
const quoteAmountWithSlippage = lpTokenAmount.addSlippage(slippage);
removeLiquidityTxn = await well.removeLiquidityImbalanced(quoteAmountWithSlippage, amounts, address, undefined, {
removeLiquidityTxn = await well.removeLiquidityImbalanced(
quoteAmountWithSlippage,
amounts,
address,
undefined,
{
gasLimit: customRatioQuote.estimate.mul(1.2).toBigNumber()
});
}
);
toast.confirming(removeLiquidityTxn);
}
const receipt = await removeLiquidityTxn.wait();
toast.success(receipt);
resetState();
refetchWellReserves();
refetchLPSummary();
invalidateScopedQuery(queryKeys.tokenBalance(wellLpToken?.symbol));
invalidateScopedQuery(queryKeys.tokenBalance(well?.tokens?.[0]?.symbol));
invalidateScopedQuery(queryKeys.tokenBalance(well?.tokens?.[1]?.symbol));
invalidateScopedQuery(queryKeys.tokenBalance(wellLpToken?.address));
invalidateScopedQuery(queryKeys.tokenBalance(well?.tokens?.[0]?.address));
invalidateScopedQuery(queryKeys.tokenBalance(well?.tokens?.[1]?.address));
} catch (error) {
Log.module("RemoveLiquidity").error("Error removing liquidity: ", (error as Error).message);
toast.error(error);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
well,
lpTokenAmount,
Expand All @@ -181,8 +197,11 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
]);

const handleSwitchRemoveMode = (newMode: REMOVE_LIQUIDITY_MODE) => {
const currentMode = removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Custom || removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Balanced;
const _newMode = newMode === REMOVE_LIQUIDITY_MODE.Custom || newMode === REMOVE_LIQUIDITY_MODE.Balanced;
const currentMode =
removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Custom ||
removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Balanced;
const _newMode =
newMode === REMOVE_LIQUIDITY_MODE.Custom || newMode === REMOVE_LIQUIDITY_MODE.Balanced;
if (currentMode && _newMode) {
setRemoveLiquidityMode(newMode);
} else {
Expand Down Expand Up @@ -224,7 +243,12 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
);

const buttonLabel = useMemo(
() => (lpTokenAmountNonZero ? (hasEnoughBalance ? "Remove Liquidity →" : "Insufficient Balance") : "Input Token Amount"),
() =>
lpTokenAmountNonZero
? hasEnoughBalance
? "Remove Liquidity →"
: "Insufficient Balance"
: "Input Token Amount",
[hasEnoughBalance, lpTokenAmountNonZero]
);

Expand All @@ -234,7 +258,12 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
}

if (lpTokenAmount && lpTokenAmount.gt(0)) {
const tokenHasMinAllowance = await hasMinimumAllowance(address, well.address, wellLpToken, lpTokenAmount);
const tokenHasMinAllowance = await hasMinimumAllowance(
address,
well.address,
wellLpToken,
lpTokenAmount
);
Log.module("addliquidity").debug(
`Token ${wellLpToken.symbol} with amount ${lpTokenAmount.toHuman()} has approval ${tokenHasMinAllowance}`
);
Expand Down Expand Up @@ -268,7 +297,8 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
checkMinAllowanceForLpToken();
}, [well.tokens, address, lpTokenAmount, checkMinAllowanceForLpToken]);

const approveButtonDisabled = !tokenAllowance && !!lpTokenAmount && lpTokenAmount.lte(TokenValue.ZERO);
const approveButtonDisabled =
!tokenAllowance && !!lpTokenAmount && lpTokenAmount.lte(TokenValue.ZERO);

const selectedQuote = useMemo(() => {
if (removeLiquidityMode === REMOVE_LIQUIDITY_MODE.OneToken) {
Expand Down Expand Up @@ -324,8 +354,16 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
active={removeLiquidityMode === REMOVE_LIQUIDITY_MODE.OneToken}
stretch
>
<Checkbox checked={removeLiquidityMode === REMOVE_LIQUIDITY_MODE.OneToken} mode={"checkOnly"} checkboxColor="#46b955" />
<TabLabel onClick={() => handleSwitchRemoveMode(REMOVE_LIQUIDITY_MODE.OneToken)}>Single Token</TabLabel>
<Checkbox
checked={removeLiquidityMode === REMOVE_LIQUIDITY_MODE.OneToken}
mode={"checkOnly"}
checkboxColor="#46b955"
/>
<TabLabel
onClick={() => handleSwitchRemoveMode(REMOVE_LIQUIDITY_MODE.OneToken)}
>
Single Token
</TabLabel>
</TabButton>
</Tab>
<Tab>
Expand All @@ -334,8 +372,16 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
active={removeLiquidityMode !== REMOVE_LIQUIDITY_MODE.OneToken}
stretch
>
<Checkbox checked={removeLiquidityMode !== REMOVE_LIQUIDITY_MODE.OneToken} mode={"checkOnly"} checkboxColor="#46b955" />
<TabLabel onClick={() => handleSwitchRemoveMode(REMOVE_LIQUIDITY_MODE.Balanced)}>Multiple Tokens</TabLabel>
<Checkbox
checked={removeLiquidityMode !== REMOVE_LIQUIDITY_MODE.OneToken}
mode={"checkOnly"}
checkboxColor="#46b955"
/>
<TabLabel
onClick={() => handleSwitchRemoveMode(REMOVE_LIQUIDITY_MODE.Balanced)}
>
Multiple Tokens
</TabLabel>
</TabButton>
</Tab>
</Tabs>
Expand Down Expand Up @@ -369,13 +415,22 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
{removeLiquidityMode === REMOVE_LIQUIDITY_MODE.OneToken && (
<MediumGapContainer>
{well.tokens!.map((token: Token, index: number) => (
<ContainerSingleTokenRow key={`token${index}`} onClick={() => handleSwitchSingleToken(index)}>
<ContainerSingleTokenRow
key={`token${index}`}
onClick={() => handleSwitchSingleToken(index)}
>
<ReadOnlyTokenValueRow selected={singleTokenIndex === index}>
<Checkbox checked={singleTokenIndex === index} mode={"checkOnly"} checkboxColor="#46b955" />
<Checkbox
checked={singleTokenIndex === index}
mode={"checkOnly"}
checkboxColor="#46b955"
/>
<SmallTokenLogo src={token.logo} />
<TokenSymbol>{token.symbol}</TokenSymbol>
{singleTokenIndex === index ? (
<TokenAmount>{oneTokenQuote ? oneTokenQuote.quote.toHuman() : "0"}</TokenAmount>
<TokenAmount>
{oneTokenQuote ? oneTokenQuote.quote.toHuman() : "0"}
</TokenAmount>
) : (
<TokenAmount>{"0"}</TokenAmount>
)}
Expand All @@ -392,7 +447,9 @@ const RemoveLiquidityContent = ({ well, slippage, slippageSettingsClickHandler,
checked={removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Balanced}
onClick={() =>
handleSwitchRemoveMode(
removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Custom ? REMOVE_LIQUIDITY_MODE.Balanced : REMOVE_LIQUIDITY_MODE.Custom
removeLiquidityMode === REMOVE_LIQUIDITY_MODE.Custom
? REMOVE_LIQUIDITY_MODE.Balanced
: REMOVE_LIQUIDITY_MODE.Custom
)
}
/>
Expand Down
2 changes: 1 addition & 1 deletion projects/dex-ui/src/utils/addresses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ export const toAddressMap = <T extends { address: string }>(
prev[key] = curr;
return prev;
}, {});
};
};
6 changes: 6 additions & 0 deletions projects/dex-ui/src/wells/useWells.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ const tokenMetadata = tokenMetadataJson as TokenMetadataMap;
const setTokenMetadatas = (wells: Well[]) => {
for (const well of wells) {
if (!well.tokens) continue;
if (well.lpToken) {
const lpLogo = images[well.lpToken.symbol];
if (lpLogo) {
well.lpToken.setMetadata({ logo: lpLogo });
}
}
well.tokens.forEach((token) => {
const address = token.address.toLowerCase();

Expand Down

0 comments on commit 2e83c71

Please sign in to comment.