Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
marshall2112 committed Jan 3, 2025
1 parent 3c3f2a3 commit f66d5ca
Show file tree
Hide file tree
Showing 7 changed files with 268 additions and 140 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ import { useMediaQuery } from 'react-responsive';
import { queryPhone } from 'styles/breakpoints';
import { useWallet } from 'providers/WalletProvider';
import { TICKER_SYMBOL } from 'enums/ticker-symbol';
import { formatToken } from 'utils/formatter';
import { useEffect, useState } from 'react';
import { formatNumberWithCommas, formatToken } from 'utils/formatter';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSpiceBazaar } from 'providers/SpiceBazaarProvider';
import { formatBigNumber } from 'components/Vault/utils';
import { formatNumberAbbreviated } from 'utils/formatter';
import { ZERO } from 'utils/bigNumber';
import { getTokenInfo } from 'components/Vault/utils';

const PRICE_UPDATE_INTERVAL = 5000;
const FADE_EFFECT_DURATION = 500;

interface BidUSDSProps {
onBidSubmitted?: () => void;
mode: BidUSDSMode;
Expand All @@ -36,6 +38,10 @@ export const BidUSDS = ({
query: queryPhone,
});

const [lastTgldPrice, setLastTgldPrice] = useState('0');
const [lastPriceUpdate, setLastPriceUpdate] = useState(Date.now());
const [fadeEffect, setFadeEffect] = useState(false);

const {
daiGoldAuctions: { bid },
daiGoldAuctionInfo,
Expand All @@ -47,7 +53,26 @@ export const BidUSDS = ({
updateBalance();
}, [updateBalance]);

const fetchTGLDPrice = useCallback(async () => {
await daiGoldAuctionInfo.fetch(true);
return daiGoldAuctionInfo?.data?.priceRatio || '0';
}, [daiGoldAuctionInfo]);

const handleBidClick = async (value: string) => {
const now = Date.now();

// Check if the price was not updated in the last n seconds
if (now - lastPriceUpdate > PRICE_UPDATE_INTERVAL) {
const newPrice = await fetchTGLDPrice().toString();
if (lastTgldPrice !== newPrice) {
setFadeEffect(true);
setTimeout(() => setFadeEffect(false), FADE_EFFECT_DURATION);
setLastTgldPrice(newPrice);
setLastPriceUpdate(now);
return;
}
}

if (mode === BidUSDSMode.IncreaseBid) {
// Possible we only want to increase bid
// by the difference between the current bid and the new bid
Expand All @@ -72,19 +97,57 @@ export const BidUSDS = ({
setInputValue(value);
};

const calculateTGLDAmount = (usdsAmount: string): string => {
if (!usdsAmount || !daiGoldAuctionInfo?.data?.priceRatio) return '0';
const numericAmount = parseFloat(usdsAmount);
if (isNaN(numericAmount)) return '0';
return (numericAmount / daiGoldAuctionInfo.data.priceRatio).toFixed(2);
};
const calculateTGLDAmount = useCallback(
(inputUsdsAmount: string): string => {
if (!inputUsdsAmount || !daiGoldAuctionInfo?.data?.priceRatio) return '0';
let numericAmount = Number(inputUsdsAmount);

if (mode === BidUSDSMode.IncreaseBid) {
numericAmount += Number(currentBidAmount);
}

if (isNaN(numericAmount)) return '0';

const priceRatioAfterBid =
(Number(daiGoldAuctionInfo?.data?.totalBidTokenAmount) +
numericAmount) /
Number(daiGoldAuctionInfo?.data?.totalAuctionTokenAmount);

const amountToReceive = numericAmount / priceRatioAfterBid;
return amountToReceive.toFixed(2);
},
[
currentBidAmount,
daiGoldAuctionInfo?.data?.priceRatio,
daiGoldAuctionInfo?.data?.totalAuctionTokenAmount,
daiGoldAuctionInfo?.data?.totalBidTokenAmount,
mode,
]
);

const exceededAmount =
Number(
calculateTGLDAmount(
(Number(inputValue) + Number(currentBidAmount)).toString()
)
) > Number(daiGoldAuctionInfo?.data?.totalAuctionTokenAmount);
const exceededAmount = useMemo(() => {
return (
Number(
calculateTGLDAmount(
(Number(inputValue) + Number(currentBidAmount)).toString()
)
) > Number(daiGoldAuctionInfo?.data?.totalAuctionTokenAmount)
);
}, [inputValue, currentBidAmount, daiGoldAuctionInfo, calculateTGLDAmount]);

useEffect(() => {
// Update price every n seconds
if (!inputValue) return;
const interval = setInterval(async () => {
const newPrice = await fetchTGLDPrice().toString();
setFadeEffect(true);
setTimeout(() => setFadeEffect(false), FADE_EFFECT_DURATION);
setLastTgldPrice(newPrice);
setLastPriceUpdate(Date.now());
}, PRICE_UPDATE_INTERVAL);

return () => clearInterval(interval);
}, [fetchTGLDPrice, lastTgldPrice, inputValue]);

return (
<ContentContainer>
Expand Down Expand Up @@ -145,23 +208,16 @@ export const BidUSDS = ({
/>
</BidContent>
</BidContainer>
<ReceiveAmountContainer>
<ReceiveAmountContainer fadeEffect={fadeEffect}>
<ReceiveTextTop>You will receive</ReceiveTextTop>
<ReceiveContainer>
<TempleGoldIcon />
<ReceiveAmount>
<ReceiveAmount fadeEffect={fadeEffect}>
{inputValue === '' || exceededAmount
? '0'
: (() => {
const totalAmount =
Number(inputValue) + Number(currentBidAmount);
const calculatedAmount = calculateTGLDAmount(
totalAmount.toString()
);
return Number(calculatedAmount) > 1e8
? formatNumberAbbreviated(Number(calculatedAmount)).string
: calculatedAmount;
})()}{' '}
: formatNumberWithCommas(
Number(calculateTGLDAmount(inputValue))
)}{' '}
TGLD
</ReceiveAmount>
</ReceiveContainer>
Expand Down Expand Up @@ -201,7 +257,7 @@ export const BidUSDS = ({
<TradeButton
style={{ whiteSpace: 'nowrap', margin: '0px', alignSelf: 'center' }}
onClick={() => handleBidClick(inputValue)}
disabled={!inputValue || exceededAmount}
disabled={!inputValue || exceededAmount || fadeEffect}
>
SUBMIT BID
</TradeButton>
Expand Down Expand Up @@ -321,7 +377,7 @@ const TitleBid = styled.div`
color: ${({ theme }) => theme.palette.brandLight};
`;

const ReceiveAmountContainer = styled.div`
const ReceiveAmountContainer = styled.div<{ fadeEffect: boolean }>`
display: flex;
flex-direction: column;
align-items: center;
Expand All @@ -331,6 +387,8 @@ const ReceiveAmountContainer = styled.div`
background: ${({ theme }) => theme.palette.black};
gap: 20px;
padding: 16px;
opacity: ${({ fadeEffect }) => (fadeEffect ? 0 : 1)};
transition: opacity 0.5s ease-in-out;
`;

const TempleGoldIcon = styled(templeGold)``;
Expand All @@ -356,12 +414,14 @@ const ReceiveTextBottom = styled.div`
color: ${({ theme }) => theme.palette.brandLight};
`;

const ReceiveAmount = styled.h3`
const ReceiveAmount = styled.h3<{ fadeEffect: boolean }>`
line-height: 52px;
font-size: 28px;
line-height: 52px;
color: ${({ theme }) => theme.palette.gold};
margin: 0px;
opacity: ${({ fadeEffect }) => (fadeEffect ? 0.4 : 1)};
transition: opacity 0.5s ease-in-out;
`;

const InfoCircle = styled.div`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import linkSvg from 'assets/icons/link.svg?react';
import active from 'assets/icons/active.svg?react';
import scheduled from 'assets/icons/scheduled.svg?react';
import styled from 'styled-components';
import { useCallback, useEffect, useState } from 'react';
import { TradeButton } from '../StakeTemple/Stake';
import { useEffect, useState } from 'react';
import { Chart } from './Chart/Chart';
import { BidUSDS, BidUSDSMode } from './BidUSDS';
import { Popover } from 'components/Pages/Core/DappPages/SpiceBazaar/components/Popover';
Expand All @@ -16,7 +15,11 @@ import * as breakpoints from 'styles/breakpoints';
import { useMediaQuery } from 'react-responsive';
import { queryPhone } from 'styles/breakpoints';
import { useWallet } from 'providers/WalletProvider';
import { useConnectWallet } from '@web3-onboard/react';
import wallet from 'assets/icons/wallet.svg?react';
import { Button } from 'components/Button/Button';
import { BidHistory } from 'components/Pages/Core/DappPages/SpiceBazaar/Earn/Auctions/BidHistoryTable/Table';
import { useAuctionCountdown } from 'hooks/spicebazaar/use-auction-countdown';

const DEVMODE_QUERY_PARAM = 'devmode';

Expand All @@ -26,6 +29,7 @@ export const Auctions = () => {
});
const [modal, setModal] = useState<'closed' | 'bidDai'>('closed');

const [{}, connect] = useConnectWallet();
const { wallet } = useWallet();

const {
Expand All @@ -36,46 +40,7 @@ export const Auctions = () => {
},
} = useSpiceBazaar();

const [countdown, setCountdown] = useState<string>('');

const calculateTimeLeft = useCallback(
(endTime: number) => {
const difference = endTime - Date.now();

if (difference <= 0) {
return daiGoldAuctionInfo?.currentEpochAuctionLive
? '0d 0h 0m 0s'
: 'Starts soon';
}

const days = Math.floor(difference / (1000 * 60 * 60 * 24));
const hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
const minutes = Math.floor((difference / 1000 / 60) % 60);
const seconds = Math.floor((difference / 1000) % 60);

return `${days}d ${hours}h ${minutes}m ${seconds}s`;
},
[daiGoldAuctionInfo?.currentEpochAuctionLive]
);

useEffect(() => {
if (!daiGoldAuctionInfo?.auctionEndTime) return;

const targetTime = daiGoldAuctionInfo.currentEpochAuctionLive
? daiGoldAuctionInfo.auctionEndTime
: daiGoldAuctionInfo.auctionEndTime + daiGoldAuctionInfo.auctionDuration;
setCountdown(calculateTimeLeft(targetTime));

const timer = setInterval(() => {
const targetTime = daiGoldAuctionInfo.currentEpochAuctionLive
? daiGoldAuctionInfo.auctionEndTime
: daiGoldAuctionInfo.auctionEndTime +
daiGoldAuctionInfo.auctionDuration;
setCountdown(calculateTimeLeft(targetTime));
}, 1000);

return () => clearInterval(timer);
}, [daiGoldAuctionInfo, calculateTimeLeft]);
const countdown = useAuctionCountdown();

useEffect(() => {
const fetchData = async () => {
Expand Down Expand Up @@ -250,12 +215,24 @@ export const Auctions = () => {
)}
{daiGoldAuctionInfo?.currentEpochAuctionLive && (
<ButtonContainer>
<TradeButton
onClick={() => setModal('bidDai')}
style={{ whiteSpace: 'nowrap', margin: 0 }}
>
BID USDS FOR TGLD
</TradeButton>
{wallet ? (
<TradeButton
onClick={() => setModal('bidDai')}
style={{ whiteSpace: 'nowrap', margin: 0 }}
>
BID USDS FOR TGLD
</TradeButton>
) : (
<TradeButton
onClick={() => {
connect();
}}
style={{ margin: 'auto', whiteSpace: 'nowrap' }}
>
<WalletIcon />
Connect Wallet
</TradeButton>
)}
</ButtonContainer>
)}
</CurrentAuction>
Expand Down Expand Up @@ -542,3 +519,35 @@ const ButtonContainer = styled.div`
display: flex;
justify-content: center;
`;

const WalletIcon = styled(wallet)`
min-width: 24px;
min-height: 24px;
`;

const TradeButton = styled(Button)`
padding: 12px 20px 12px 20px;
width: ${(props) => props.width || 'min-content'};
height: min-content;
background: ${({ theme }) => theme.palette.gradients.dark};
border: 1px solid ${({ theme }) => theme.palette.brandDark};
box-shadow: 0px 0px 20px rgba(222, 92, 6, 0.4);
border-radius: 10px;
font-size: 16px;
line-height: 19px;
text-transform: uppercase;
color: ${({ theme }) => theme.palette.brandLight};
/* Flex settings for centering button content */
display: flex;
align-items: center;
justify-content: center;
/* Flex settings for the span inside the button */
& > span {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -154,16 +154,19 @@ export const DataTable: React.FC<TableProps> = ({
Increase Bid
</TradeButton>
)}
{action === 'Claim' && (
<TradeButton
onClick={() =>
daiGoldAuctionClaim(Number(transaction.epochId))
}
style={{ whiteSpace: 'nowrap', margin: 0 }}
>
Claim
</TradeButton>
)}
{action === 'Claim' &&
Number(transaction.claimableTokens) > 0 && (
<TradeButton
onClick={() =>
daiGoldAuctionClaim(
Number(transaction.epochId)
)
}
style={{ whiteSpace: 'nowrap', margin: 0 }}
>
Claim
</TradeButton>
)}
</ButtonContainer>
</DataCell>
</DataRow>
Expand Down
3 changes: 2 additions & 1 deletion apps/dapp/src/components/Pages/Core/NewUI/HomeInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import daiImg from 'assets/images/newui-images/tokens/dai.png';
import fraxImg from 'assets/images/newui-images/tokens/frax.png';
import usdcImg from 'assets/images/newui-images/tokens/usdc.png';
import usdtImg from 'assets/images/newui-images/tokens/usdt.png';
import usdsImg from 'assets/images/newui-images/tokens/usds.png';
import templeImg from 'assets/images/newui-images/tokens/temple.png';
import ohmImg from 'assets/images/newui-images/tokens/ohm.png';

Expand Down Expand Up @@ -58,7 +59,7 @@ const TickerImages: Record<TICKER_SYMBOL, string> = {
ETH: ethImg,
WETH: wethImg,
DAI: daiImg,
USDS: daiImg, // TODO: Replace with USDS image
USDS: usdsImg,
FRAX: fraxImg,
USDC: usdcImg,
USDT: usdtImg,
Expand Down
Loading

0 comments on commit f66d5ca

Please sign in to comment.