ghost-dao-interface/src/containers/Dex/PoolContainer.jsx
Uncle Fatso 132bd0986b
migrate to PAPI and integrate weaver protocol
Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
2026-11-05 21:59:19 +03:00

346 lines
15 KiB
JavaScript

import { useState, useEffect, useMemo } from "react";
import { Box, Typography, useTheme, useMediaQuery } from "@mui/material";
import toast from "react-hot-toast";
import TokenStack from "../../components/TokenStack/TokenStack";
import SwapCard from "../../components/Swap/SwapCard";
import SwapCollection from "../../components/Swap/SwapCollection";
import { TokenAllowanceGuard } from "../../components/TokenAllowanceGuard/TokenAllowanceGuard";
import { SecondaryButton } from "../../components/Button";
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
import { formatNumber, formatCurrency, bigIntSqrt } from "../../helpers";
import { useBalance, useTotalSupply } from "../../hooks/tokens";
import {
useUniswapV2Pair,
useUniswapV2PairReserves,
addLiquidity,
addLiquidityETH,
} from "../../hooks/uniswapv2";
import { useLocalStorage } from "../../hooks/localstorage";
const PoolContainer = ({
chainSymbol,
tokenNameTop,
tokenNameBottom,
onCardsSwap,
address,
chainId,
dexAddresses,
connect,
slippage,
destination,
secondsToWait,
setTopTokenListOpen,
setBottomTokenListOpen,
formatDecimals,
}) => {
const theme = useTheme();
const isSmallScreen = useMediaQuery("(max-width: 456px)");
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
const [isPending, setIsPending] = useState(false);
const [amountTop, setAmountTop] = useState("");
const [amountBottom, setAmountBottom] = useState("");
const {
balance: balanceTop,
refetch: balanceRefetchTop,
contractAddress: addressTop,
isNative: topIsNative,
} = useBalance(chainId, tokenNameTop, address);
const {
balance: balanceBottom,
refetch: balanceRefetchBottom,
contractAddress: addressBottom,
isNative: bottomIsNative,
} = useBalance(chainId, tokenNameBottom, address);
const {
pairAddress,
refetch: pairAddressRefetch,
} = useUniswapV2Pair(chainId, dexAddresses.factory, addressTop, addressBottom);
const {
balance: lpBalance,
refetch: lpRefetch,
} = useBalance(chainId, pairAddress, address);
const {
totalSupply: lpTotalSupply,
refetch: lpTotalSupplyRefetch
} = useTotalSupply(chainId, pairAddress);
const {
reserves: pairReserves,
tokens: tokenAddresses,
refetch: pairReservesRefetch,
} = useUniswapV2PairReserves(
chainId,
pairAddress,
);
const onSwap = () => {
setAmountTop(amountBottom);
onCardsSwap();
}
const setMaxTop = () => setAmountTop(balanceTop.toString());
const setMaxBottom = () => setAmountBottom(balanceBottom.toString());
const estimatedAmountOut = useMemo(() => {
const pairReserves0 = addressTop.toUpperCase() === tokenAddresses.token0.toUpperCase()
? pairReserves.reserve0
: pairReserves.reserve1;
const pairReserves1 = addressBottom.toUpperCase() === tokenAddresses.token1.toUpperCase()
? pairReserves.reserve1
: pairReserves.reserve0;
const zero = new DecimalBigNumber(0n, 0);
const value0 = new DecimalBigNumber(amountTop, balanceTop._decimals)
const value1 = new DecimalBigNumber(amountBottom, balanceBottom._decimals);
const amountToAddA = new DecimalBigNumber(value0._value.toBigInt(), balanceTop._decimals);
const amountToAddB = new DecimalBigNumber(value1._value.toBigInt(), balanceBottom._decimals);
if (
pairReserves0.gt(zero) &&
pairReserves1.gt(zero) &&
lpTotalSupply.gt(new DecimalBigNumber(0n, 0))
) {
const lpTokensFromA = (amountToAddA.mul(lpTotalSupply).div(pairReserves0));
const lpTokensFromB = (amountToAddB.mul(lpTotalSupply).div(pairReserves1));
const lpTokensToMint = lpTokensFromA.gt(lpTokensFromB) ? lpTokensFromB : lpTokensFromA;
return lpTokensToMint;
} else {
const tokens = bigIntSqrt(BigInt(amountToAddA.mul(amountToAddB)._value));
const lpTokensToMint = new DecimalBigNumber(tokens, 18);
return lpTokensToMint;
}
}, [pairReserves, amountTop, amountBottom, balanceTop, balanceBottom]);
useEffect(() => {
if (addressTop.toUpperCase() === tokenAddresses.token1.toUpperCase()) {
if (pairReserves?.reserve1.gt(new DecimalBigNumber(0n, 0))) {
const value = new DecimalBigNumber(amountTop, balanceTop._decimals)
const amountToAdd = new DecimalBigNumber(value._value.toBigInt(), balanceTop._decimals);
const amount = amountToAdd.mul(pairReserves.reserve0).div(pairReserves.reserve1);
setAmountBottom(amount.toString());
}
} else if (addressTop.toUpperCase() === tokenAddresses.token0.toUpperCase()) {
if (pairReserves?.reserve0.gt(new DecimalBigNumber(0n, 0))) {
const value = new DecimalBigNumber(amountTop, balanceBottom._decimals)
const amountToAdd = new DecimalBigNumber(value._value.toBigInt(), balanceBottom._decimals);
const amount = amountToAdd.mul(pairReserves.reserve1).div(pairReserves.reserve0);
setAmountBottom(amount.toString());
}
}
}, [addressBottom, balanceTop, balanceBottom, amountTop, amountBottom, tokenAddresses, pairReserves]);
const poolShares = useMemo(() => {
const hundred = new DecimalBigNumber(1n, 2);
if (lpTotalSupply?._value == 0n) {
return { currentShares: lpTotalSupply, nextShares: lpTotalSupply };
}
const currentShares = lpBalance.div(lpTotalSupply).div(hundred);
const nextShares = (lpBalance.add(estimatedAmountOut)).div(lpTotalSupply.add(estimatedAmountOut)).div(hundred);
return { currentShares, nextShares };
}, [lpBalance, lpTotalSupply, estimatedAmountOut]);
const poolPrices = useMemo(() => {
const amountIn = addressTop.toUpperCase() === tokenAddresses.token0.toUpperCase()
? pairReserves.reserve0
: pairReserves.reserve1;
const amountOut = addressBottom.toUpperCase() === tokenAddresses.token1.toUpperCase()
? pairReserves.reserve1
: pairReserves.reserve0;
let priceIn = "0";
let priceOut = "0";
if (amountIn?._value > 0n) priceIn = (amountOut.div(amountIn)).toString();
if (amountOut?._value > 0n) priceOut = (amountIn.div(amountOut)).toString();
return { priceIn , priceOut }
}, [addressTop, addressBottom, balanceTop, tokenAddresses, pairReserves]);
const addLiquidityInner = async () => {
setIsPending(true);
const numericSecondsToWait = parseInt(secondsToWait, 10);
const safeSecondsToWait = (!isNaN(numericSecondsToWait) && numericSecondsToWait > 0)
? numericSecondsToWait
: 0;
const deadline = Math.floor(Date.now() / 1000) + safeSecondsToWait;
const shares = 100000;
const one = BigInt(shares * 100);
const floatSlippage = slippage === "" ? 0 : parseFloat(slippage);
const bigIntSlippage = one - BigInt(Math.round(floatSlippage * shares));
if (floatSlippage < 3) toast("Slippage is too low, transaction highly likely will fail.");
const amountADesired = BigInt(Math.round(parseFloat(amountTop) * Math.pow(10, balanceTop._decimals)));
const amountBDesired = BigInt(Math.round(parseFloat(amountBottom) * Math.pow(10, balanceBottom._decimals)));
const amountAMin = amountADesired * bigIntSlippage / one;
const amountBMin = amountBDesired * bigIntSlippage / one;
const params = {
chainId,
tokenNameTop,
tokenNameBottom,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
address,
destination,
deadline,
}
let txHash;
if (topIsNative || bottomIsNative) {
txHash = await addLiquidityETH(params)
} else {
txHash = await addLiquidity(params);
}
if (txHash) tryStoreInHistory(chainId, address, CONSTANTS.dex.key, txHash, CONSTANTS.dex.add);
await balanceRefetchTop();
await balanceRefetchBottom();
await pairAddressRefetch();
await lpRefetch();
await lpTotalSupplyRefetch();
await pairReservesRefetch();
setAmountTop("");
setAmountBottom("");
setIsPending(false);
}
const emptyPool = useMemo(() => {
return pairAddress === "" || pairAddress === "0x0000000000000000000000000000000000000000"
}, [pairAddress])
return (
<Box maxWidth="390px" display="flex" flexDirection="column" justifyContent="space-between" height="100%">
<SwapCollection
UpperSwapCard={
<SwapCard
id="from"
token={tokenNameTop}
chainTokenName={tokenNameTop !== chainSymbol && chainSymbol}
tokenName={tokenNameTop}
info={(!isSmallScreen ? "Balance: " : "") + formatCurrency(balanceTop, formatDecimals, tokenNameTop)}
endString="Max"
endStringOnClick={setMaxTop}
value={amountTop}
onChange={event => setAmountTop(event.currentTarget.value)}
tokenOnClick={() => setTopTokenListOpen(true)}
inputProps={{ "data-testid": "fromInput" }}
/>
}
LowerSwapCard={
<SwapCard
id="to"
token={tokenNameBottom}
chainTokenName={tokenNameBottom !== chainSymbol && chainSymbol}
tokenName={tokenNameBottom}
value={amountBottom}
onChange={event => emptyPool ? setAmountBottom(event.currentTarget.value) : {}}
endString={emptyPool ? "Max" : undefined}
endStringOnClick={emptyPool ? setMaxBottom : {}}
inputProps={{ "data-testid": "toInput" }}
tokenOnClick={() => setBottomTokenListOpen(true)}
info={(!isSmallScreen ? "Balance: " : "") + formatCurrency(balanceBottom, formatDecimals, tokenNameBottom)}
/>
}
arrowOnClick={onSwap}
/>
<Box
m="10px 0"
display="flex"
flexDirection="column"
justifyContent="space-between"
alignItems="center"
gap="0px"
maxWidth="390px"
style={{ fontSize: "12px", color: theme.colors.gray[40] }}
>
<Box width="100%" display="flex" justifyContent="space-between">
<Typography fontSize="12px" lineHeight="15px">{`1 ${tokenNameTop}`}</Typography>
<Typography fontSize="12px" lineHeight="15px">{formatCurrency(poolPrices.priceIn, formatDecimals, tokenNameBottom)}</Typography>
</Box>
<Box width="100%" display="flex" justifyContent="space-between">
<Typography fontSize="12px" lineHeight="15px">{`1 ${tokenNameBottom}`}</Typography>
<Typography fontSize="12px" lineHeight="15px">{formatCurrency(poolPrices.priceOut, formatDecimals, tokenNameTop)}</Typography>
</Box>
<Box width="100%" display="flex" justifyContent="space-between">
<Typography fontSize="12px" lineHeight="15px">Current Pool Share:</Typography>
<Typography fontSize="12px" lineHeight="15px">{formatNumber(poolShares.currentShares, formatDecimals)}%</Typography>
</Box>
<Box width="100%" display="flex" justifyContent="space-between">
<Typography fontSize="12px" lineHeight="15px">Next Pool Share:</Typography>
<Typography fontSize="12px" lineHeight="15px">{formatNumber(poolShares.nextShares, formatDecimals)}%</Typography>
</Box>
</Box>
<TokenAllowanceGuard
spendAmount={new DecimalBigNumber(amountTop, balanceTop._decimals)}
tokenName={tokenNameTop}
owner={address}
spender={dexAddresses.router}
decimals={balanceTop._decimals}
isNative={topIsNative}
approvalText={"Approve " + tokenNameTop}
approvalPendingText={"Approving..."}
connect={connect}
width="100%"
height="60px"
>
<TokenAllowanceGuard
spendAmount={new DecimalBigNumber(amountBottom, balanceBottom._decimals)}
tokenName={tokenNameBottom}
owner={address}
spender={dexAddresses.router}
decimals={balanceBottom._decimals}
isNative={bottomIsNative}
approvalText={"Approve " + tokenNameBottom}
approvalPendingText={"Approving..."}
connect={connect}
width="100%"
height="60px"
>
<SecondaryButton
fullWidth
disabled={
address !== "" && (
(new DecimalBigNumber(amountTop, balanceTop._decimals)).eq(new DecimalBigNumber("0", 18)) ||
(new DecimalBigNumber(amountBottom, balanceBottom._decimals)).eq(new DecimalBigNumber("0", 18)) ||
balanceTop?.lt(new DecimalBigNumber(amountTop, balanceTop._decimals)) ||
balanceBottom?.lt(new DecimalBigNumber(amountBottom, balanceBottom._decimals)) ||
isPending
)
}
loading={isPending}
onClick={() => address === "" ? connect() : addLiquidityInner()}
>
{address === "" ?
"Connect"
:
pairAddress === "0x0000000000000000000000000000000000000000" ?
isPending ? "Creating Pool..." : "Create Pool"
:
isPending ? "Adding Liquidity..." : "Add Liquidity"
}
</SecondaryButton>
</TokenAllowanceGuard>
</TokenAllowanceGuard>
</Box>
)
}
export default PoolContainer;