Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor and delete unused code #872

Merged
merged 3 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed earn/public/privacy.pdf
Binary file not shown.
Binary file removed earn/public/terms.pdf
Binary file not shown.
2 changes: 1 addition & 1 deletion earn/src/components/advanced/BorrowGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
RESPONSIVE_BREAKPOINT_MD,
RESPONSIVE_BREAKPOINT_SM,
RESPONSIVE_BREAKPOINTS,
} from '../../data/constants/Breakpoints';
} from 'shared/lib/data/constants/Breakpoints';
import Graph from '../graph/Graph';

const TEXT_COLOR = '#82a0b6';
Expand Down
67 changes: 35 additions & 32 deletions earn/src/components/advanced/BorrowMetrics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ import { formatDistanceToNowStrict } from 'date-fns';
import Tooltip from 'shared/lib/components/common/Tooltip';
import { Display, Text } from 'shared/lib/components/common/Typography';
import { auctionCurve, sqrtRatioToTick } from 'shared/lib/data/BalanceSheet';
import { RESPONSIVE_BREAKPOINT_MD, RESPONSIVE_BREAKPOINT_SM } from 'shared/lib/data/constants/Breakpoints';
import { MANAGER_NAME_MAP } from 'shared/lib/data/constants/ChainSpecific';
import { GREY_700 } from 'shared/lib/data/constants/Colors';
import { LendingPair } from 'shared/lib/data/LendingPair';
import useChain from 'shared/lib/hooks/UseChain';
import { getEtherscanUrlForChain } from 'shared/lib/util/Chains';
import { getBlockExplorerUrl } from 'shared/lib/util/Chains';
import { formatTokenAmount } from 'shared/lib/util/Numbers';
import styled from 'styled-components';
import { Address } from 'viem';
import { usePublicClient } from 'wagmi';

import { BorrowerNftBorrower } from '../../data/BorrowerNft';
import { RESPONSIVE_BREAKPOINT_MD, RESPONSIVE_BREAKPOINT_SM } from '../../data/constants/Breakpoints';
import { BorrowerNftBorrower } from '../../data/hooks/useDeprecatedMarginAccountShim';

const BORROW_TITLE_TEXT_COLOR = 'rgba(130, 160, 182, 1)';
const MAX_HEALTH = 10;
Expand Down Expand Up @@ -165,42 +166,44 @@ function HealthMetricCard(props: { health: number }) {
}

export type BorrowMetricsProps = {
marginAccount?: BorrowerNftBorrower;
dailyInterest0: number;
dailyInterest1: number;
borrowerNft?: BorrowerNftBorrower;
market?: LendingPair;
userHasNoMarginAccounts: boolean;
};

export function BorrowMetrics(props: BorrowMetricsProps) {
const { marginAccount, dailyInterest0, dailyInterest1, userHasNoMarginAccounts } = props;
const { borrowerNft, market, userHasNoMarginAccounts } = props;

const dailyInterest0 = ((market?.kitty0Info.borrowAPR || 0) / 365) * (borrowerNft?.liabilities.amount0 || 0);
const dailyInterest1 = ((market?.kitty1Info.borrowAPR || 0) / 365) * (borrowerNft?.liabilities.amount1 || 0);

const activeChain = useChain();

const [, setCurrentTime] = useState(Date.now());
const [mostRecentModifyTime, setMostRecentModifyTime] = useState<Date | null>(null);

const [token0Collateral, token1Collateral] = useMemo(
() => marginAccount?.assets.amountsAt(sqrtRatioToTick(marginAccount.sqrtPriceX96)) ?? [0, 0],
[marginAccount]
() => borrowerNft?.assets.amountsAt(sqrtRatioToTick(borrowerNft.sqrtPriceX96)) ?? [0, 0],
[borrowerNft]
);

const publicClient = usePublicClient({ chainId: activeChain.id });
useEffect(() => {
(async () => {
setMostRecentModifyTime(null);
if (!publicClient || !marginAccount?.mostRecentModify) return;
const block = await publicClient.getBlock({ blockNumber: marginAccount.mostRecentModify.blockNumber });
if (!publicClient || !borrowerNft?.mostRecentModify?.blockNumber) return;
const block = await publicClient.getBlock({ blockNumber: borrowerNft.mostRecentModify.blockNumber });
setMostRecentModifyTime(new Date(Number(block.timestamp) * 1000));
})();
}, [publicClient, marginAccount, setMostRecentModifyTime]);
}, [publicClient, borrowerNft?.mostRecentModify?.blockNumber, setMostRecentModifyTime]);

useEffect(() => {
const interval = setInterval(() => setCurrentTime(Date.now()), 200);
if (!marginAccount?.warningTime) clearInterval(interval);
if (!borrowerNft?.warningTime) clearInterval(interval);
return () => clearInterval(interval);
}, [marginAccount?.warningTime]);
}, [borrowerNft]);

if (!marginAccount)
if (!borrowerNft)
return (
<MetricsGrid>
<MetricsGridUpper>
Expand All @@ -218,17 +221,17 @@ export function BorrowMetrics(props: BorrowMetricsProps) {
</MetricsGrid>
);

const etherscanUrl = getEtherscanUrlForChain(activeChain);
const etherscanUrl = getBlockExplorerUrl(activeChain);

const mostRecentManager = marginAccount.mostRecentModify
? (marginAccount.mostRecentModify.args.manager as Address)
const mostRecentManager = borrowerNft.mostRecentModify
? (borrowerNft.mostRecentModify.args.manager as Address)
: '0x';
const mostRecentManagerName = Object.hasOwn(MANAGER_NAME_MAP, mostRecentManager)
? MANAGER_NAME_MAP[mostRecentManager]
: undefined;
const mostRecentManagerUrl = `${etherscanUrl}/address/${mostRecentManager}`;

const mostRecentModifyHash = marginAccount.mostRecentModify?.transactionHash;
const mostRecentModifyHash = borrowerNft.mostRecentModify?.transactionHash;
const mostRecentModifyUrl = `${etherscanUrl}/tx/${mostRecentModifyHash}`;
const mostRecentModifyTimeStr = mostRecentModifyTime
? formatDistanceToNowStrict(mostRecentModifyTime, {
Expand All @@ -238,8 +241,8 @@ export function BorrowMetrics(props: BorrowMetricsProps) {
: '';

let liquidationAuctionStr = 'Not started';
if (marginAccount.warningTime > 0) {
const auctionStartTime = marginAccount.warningTime + 5 * 60;
if (borrowerNft.warningTime > 0) {
const auctionStartTime = borrowerNft.warningTime + 5 * 60;
const currentTime = Date.now() / 1000;
if (currentTime < auctionStartTime) {
liquidationAuctionStr = `Begins in ${(auctionStartTime - currentTime).toFixed(1)} seconds`;
Expand All @@ -252,34 +255,34 @@ export function BorrowMetrics(props: BorrowMetricsProps) {
<MetricsGrid>
<MetricsGridUpper>
<MetricCard
label={`${marginAccount.token0.symbol} Collateral`}
label={`${borrowerNft.token0.symbol} Collateral`}
value={formatTokenAmount(token0Collateral, 3)}
valueClassName='underline underline-offset-2 decoration-[#00C143f0]'
/>
<MetricCard
label={`${marginAccount.token1.symbol} Collateral`}
label={`${borrowerNft.token1.symbol} Collateral`}
value={formatTokenAmount(token1Collateral, 3)}
valueClassName='underline underline-offset-2 decoration-[#00C143f0]'
/>
<MetricCard
label={`${marginAccount.token0.symbol} Borrows`}
value={formatTokenAmount(marginAccount.liabilities.amount0 || 0, 3)}
label={`${borrowerNft.token0.symbol} Borrows`}
value={formatTokenAmount(borrowerNft.liabilities.amount0 || 0, 3)}
valueClassName='underline underline-offset-2 decoration-[#EC2D5Bf0]'
/>
<MetricCard
label={`${marginAccount.token1.symbol} Borrows`}
value={formatTokenAmount(marginAccount.liabilities.amount1 || 0, 3)}
label={`${borrowerNft.token1.symbol} Borrows`}
value={formatTokenAmount(borrowerNft.liabilities.amount1 || 0, 3)}
valueClassName='underline underline-offset-2 decoration-[#EC2D5Bf0]'
/>
</MetricsGridUpper>
<MetricsGridLower>
<HealthMetricCard health={marginAccount.health || 0} />
<HealthMetricCard health={borrowerNft.health} />
<HorizontalMetricCard
label='Daily Interest Owed'
value={`${formatTokenAmount(dailyInterest0, 2)} ${marginAccount.token0.symbol},  ${formatTokenAmount(
value={`${formatTokenAmount(dailyInterest0, 2)} ${borrowerNft.token0.symbol},  ${formatTokenAmount(
dailyInterest1,
2
)} ${marginAccount.token1.symbol}`}
)} ${borrowerNft.token1.symbol}`}
/>
{mostRecentModifyHash && (
<HorizontalMetricCard label='Last Modified'>
Expand All @@ -295,9 +298,9 @@ export function BorrowMetrics(props: BorrowMetricsProps) {
</HorizontalMetricCard>
)}
<HorizontalMetricCard label='Custom Tag'>
<Text size='M'>{marginAccount.userDataHex}</Text>
<Text size='M'>{borrowerNft.userDataHex}</Text>
</HorizontalMetricCard>
{marginAccount.warningTime > 0 && (
{borrowerNft.warningTime > 0 && (
<HorizontalMetricCard label='Liquidation Auction'>
<Text size='M'>{liquidationAuctionStr}</Text>
</HorizontalMetricCard>
Expand Down
3 changes: 1 addition & 2 deletions earn/src/components/advanced/GlobalStatsTable.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Display, Text } from 'shared/lib/components/common/Typography';
import { RESPONSIVE_BREAKPOINT_XS } from 'shared/lib/data/constants/Breakpoints';
import { GREY_700 } from 'shared/lib/data/constants/Colors';
import { GNFormat } from 'shared/lib/data/GoodNumber';
import { LendingPair } from 'shared/lib/data/LendingPair';
import { roundPercentage } from 'shared/lib/util/Numbers';
import styled from 'styled-components';

import { RESPONSIVE_BREAKPOINT_XS } from '../../data/constants/Breakpoints';

const STAT_LABEL_TEXT_COLOR = 'rgba(130, 160, 182, 1)';
const STAT_VALUE_TEXT_COLOR = 'rgba(255, 255, 255, 1)';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { rgb, rgba } from 'shared/lib/util/Colors';
import styled from 'styled-components';
import tw from 'twin.macro';

import { BorrowerNftBorrower } from '../../data/BorrowerNft';
import { BorrowerNftBorrower } from '../../data/hooks/useDeprecatedMarginAccountShim';

// MARK: Capturing Mouse Data on container div ---------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion earn/src/components/advanced/TokenAllocationWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styled from 'styled-components';

import TokenAllocationPieChartWidget from './TokenAllocationPieChartWidget';
import { ReactComponent as PieChartIcon } from '../../assets/svg/pie_chart.svg';
import { BorrowerNftBorrower } from '../../data/BorrowerNft';
import { BorrowerNftBorrower } from '../../data/hooks/useDeprecatedMarginAccountShim';

const ACCENT_COLOR = 'rgba(130, 160, 182, 1)';

Expand Down
2 changes: 1 addition & 1 deletion earn/src/components/advanced/UniswapPositionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import styled from 'styled-components';

import ImportUniswapNFTModal from './modal/ImportUniswapNFTModal';
import { WithdrawUniswapNFTModal } from './modal/WithdrawUniswapNFTModal';
import { BorrowerNftBorrower } from '../../data/BorrowerNft';
import { BorrowerNftBorrower } from '../../data/hooks/useDeprecatedMarginAccountShim';
import TokenPairIcons from '../common/TokenPairIcons';
import {
InRangeBadge,
Expand Down
7 changes: 3 additions & 4 deletions earn/src/components/advanced/modal/AddCollateralModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import { UniswapNFTPosition } from 'shared/lib/data/Uniswap';

import { AddCollateralTab } from './tab/AddCollateralTab';
import { AddUniswapNFTAsCollateralTab } from './tab/AddUniswapNFTAsCollateralTab';
import { BorrowerNftBorrower } from '../../../data/BorrowerNft';
import { MAX_UNISWAP_POSITIONS } from '../../../data/constants/Values';
import { BorrowerNftBorrower } from '../../../data/hooks/useDeprecatedMarginAccountShim';

const SECONDARY_COLOR = '#CCDFED';

Expand All @@ -33,7 +32,7 @@ export default function AddCollateralModal(props: AddCollateralModalProps) {
const [modalState, setModalState] = useState(() => {
// Only show the select collateral type modal if there are uniswap NFT positions and the user has not already
// added the maximum number of uniswap positions.
if (uniswapNFTPositions.size > 0 && borrower.assets.uniswapPositions.length < MAX_UNISWAP_POSITIONS) {
if (uniswapNFTPositions.size > 0 && borrower.assets.uniswapPositions.length < 3) {
return AddCollateralModalState.SELECT_COLLATERAL_TYPE;
}
return AddCollateralModalState.TOKENS;
Expand All @@ -44,7 +43,7 @@ export default function AddCollateralModal(props: AddCollateralModalProps) {
setModalState(() => {
// Only show the select collateral type modal if there are uniswap NFT positions and the user has not already
// added the maximum number of uniswap positions.
if (uniswapNFTPositions.size > 0 && borrower.assets.uniswapPositions.length < MAX_UNISWAP_POSITIONS) {
if (uniswapNFTPositions.size > 0 && borrower.assets.uniswapPositions.length < 3) {
return AddCollateralModalState.SELECT_COLLATERAL_TYPE;
}
return AddCollateralModalState.TOKENS;
Expand Down
60 changes: 19 additions & 41 deletions earn/src/components/advanced/modal/BorrowModal.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { useState, useMemo, useEffect } from 'react';
import { useState, useEffect } from 'react';

import { ethers } from 'ethers';
import { borrowerAbi } from 'shared/lib/abis/Borrower';
import { borrowerNftAbi } from 'shared/lib/abis/BorrowerNft';
import { factoryAbi } from 'shared/lib/abis/Factory';
import { FilledStylizedButton } from 'shared/lib/components/common/Buttons';
import { CustomMaxButton } from 'shared/lib/components/common/Input';
import Modal from 'shared/lib/components/common/Modal';
Expand All @@ -13,7 +11,6 @@ import { Assets, Liabilities } from 'shared/lib/data/Borrower';
import {
ALOE_II_BORROWER_NFT_ADDRESS,
ALOE_II_BORROWER_NFT_SIMPLE_MANAGER_ADDRESS,
ALOE_II_FACTORY_ADDRESS,
} from 'shared/lib/data/constants/ChainSpecific';
import { TERMS_OF_SERVICE_URL } from 'shared/lib/data/constants/Values';
import { GN, GNFormat } from 'shared/lib/data/GoodNumber';
Expand All @@ -22,10 +19,10 @@ import { Token } from 'shared/lib/data/Token';
import useChain from 'shared/lib/hooks/UseChain';
import { formatNumberInput, truncateDecimals } from 'shared/lib/util/Numbers';
import styled from 'styled-components';
import { Address, Hex, WriteContractReturnType } from 'viem';
import { useAccount, useReadContract, useSimulateContract, useWriteContract } from 'wagmi';
import { Address, encodeFunctionData, formatEther, WriteContractReturnType } from 'viem';
import { useAccount, useSimulateContract, useWriteContract } from 'wagmi';

import { BorrowerNftBorrower } from '../../../data/BorrowerNft';
import { BorrowerNftBorrower } from '../../../data/hooks/useDeprecatedMarginAccountShim';
import HealthBar from '../../common/HealthBar';
import TokenAmountSelectInput from '../../portfolio/TokenAmountSelectInput';

Expand Down Expand Up @@ -68,7 +65,7 @@ function getConfirmButton(state: ConfirmButtonState, token: Token): { text: stri

type BorrowButtonProps = {
borrower: BorrowerNftBorrower;
etherToSend: GN;
etherToSend: bigint;
userAddress: Address;
borrowToken: Token;
borrowAmount: GN;
Expand Down Expand Up @@ -101,12 +98,11 @@ function BorrowButton(props: BorrowButtonProps) {
const amount0Big = isBorrowingToken0 ? borrowAmount : GN.zero(borrowToken.decimals);
const amount1Big = isBorrowingToken0 ? GN.zero(borrowToken.decimals) : borrowAmount;

const borrowerInterface = new ethers.utils.Interface(borrowerAbi);
const encodedData = borrowerInterface.encodeFunctionData('borrow', [
amount0Big.toBigNumber(),
amount1Big.toBigNumber(),
shouldWithdrawToWallet ? userAddress : borrower.address,
]);
const encodedData = encodeFunctionData({
abi: borrowerAbi,
functionName: 'borrow',
args: [amount0Big.toBigInt(), amount1Big.toBigInt(), shouldWithdrawToWallet ? userAddress : borrower.address],
});

const { data: borrowConfig, isLoading: prepareContractIsLoading } = useSimulateContract({
address: ALOE_II_BORROWER_NFT_ADDRESS[activeChain.id],
Expand All @@ -116,10 +112,10 @@ function BorrowButton(props: BorrowButtonProps) {
userAddress,
[borrower.index],
[ALOE_II_BORROWER_NFT_SIMPLE_MANAGER_ADDRESS[activeChain.id]],
[encodedData as Hex],
[etherToSend.toBigNumber().div(1e13).toNumber()],
[encodedData],
[Number(etherToSend / 10_000_000_000_000n)],
],
value: etherToSend.toBigInt(),
value: etherToSend,
query: { enabled: Boolean(userAddress) && borrowAmount.isGtZero() && !isUnhealthy && !notEnoughSupply },
chainId: activeChain.id,
});
Expand Down Expand Up @@ -175,15 +171,13 @@ function BorrowButton(props: BorrowButtonProps) {
export type BorrowModalProps = {
borrower: BorrowerNftBorrower;
market: LendingPair;
accountEtherBalance?: GN;
isOpen: boolean;
setIsOpen: (open: boolean) => void;
setPendingTxn: (pendingTxn: WriteContractReturnType | null) => void;
};

export default function BorrowModal(props: BorrowModalProps) {
const { borrower, market, accountEtherBalance, isOpen, setIsOpen, setPendingTxn } = props;
const activeChain = useChain();
const { borrower, market, isOpen, setIsOpen, setPendingTxn } = props;

const [borrowAmountStr, setBorrowAmountStr] = useState('');
const [borrowToken, setBorrowToken] = useState<Token>(borrower.token0);
Expand All @@ -199,19 +193,6 @@ export default function BorrowModal(props: BorrowModalProps) {
setShouldWithdrawToWallet(true);
}, [isOpen, borrower.token0]);

const { data: anteData } = useReadContract({
abi: factoryAbi,
address: ALOE_II_FACTORY_ADDRESS[activeChain.id],
functionName: 'getParameters',
args: [borrower.uniswapPool as Address],
chainId: activeChain.id,
});

const ante = useMemo(() => {
if (!anteData) return GN.zero(18);
return GN.fromBigInt(anteData[0], 18);
}, [anteData]);

const tokenOptions = [borrower.token0, borrower.token1];
const isToken0 = borrowToken.equals(borrower.token0);

Expand All @@ -221,10 +202,7 @@ export default function BorrowModal(props: BorrowModalProps) {

const newLiability = existingLiability.add(borrowAmount);

let etherToSend = GN.zero(18, 10);
if (accountEtherBalance !== undefined && accountEtherBalance.lt(ante)) {
etherToSend = ante.sub(accountEtherBalance);
}
let etherToSend = market.amountEthRequiredBeforeBorrowing(borrower.ethBalance!.toBigInt());

if (!userAddress || !isOpen) {
return null;
Expand Down Expand Up @@ -342,10 +320,10 @@ export default function BorrowModal(props: BorrowModalProps) {
<strong>{newLiability.toString(GNFormat.DECIMAL)}</strong>. The borrowed funds will be{' '}
{shouldWithdrawToWallet ? 'withdrawn to your wallet for immediate use.' : 'left in the NFT for future use.'}
</Text>
{etherToSend.isGtZero() && (
{etherToSend > 0n && (
<Text size='XS' color={TERTIARY_COLOR} className='overflow-hidden text-ellipsis'>
You will need to provide an additional {etherToSend.toString(GNFormat.DECIMAL)} ETH to cover the gas fees
in the event that you are liquidated.
You will need to provide an additional {formatEther(etherToSend)} ETH to
cover the gas fees in the event that you are liquidated.
</Text>
)}
<div className='flex gap-2 mt-2'>
Expand All @@ -370,7 +348,7 @@ export default function BorrowModal(props: BorrowModalProps) {
setPendingTxn={setPendingTxn}
/>
<Text size='XS' color={TERTIARY_COLOR} className='w-full mt-2'>
By using our service, you agree to our{' '}
By using this interface, you agree to our{' '}
<a href={TERMS_OF_SERVICE_URL} className='underline' rel='noreferrer' target='_blank'>
Terms of Service
</a>{' '}
Expand Down
Loading