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

add finite consolidation approvals #3224

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
52 changes: 0 additions & 52 deletions src/abi/CoolerConsolidation.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,58 +54,6 @@
],
"stateMutability": "view"
},
{
0xJem marked this conversation as resolved.
Show resolved Hide resolved
"type": "function",
"name": "VERSION",
"inputs": [],
"outputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "pure"
},
{
"type": "function",
"name": "collateralRequired",
"inputs": [
{
"name": "clearinghouse_",
"type": "address",
"internalType": "address"
},
{
"name": "cooler_",
"type": "address",
"internalType": "address"
},
{
"name": "ids_",
"type": "uint256[]",
"internalType": "uint256[]"
}
],
"outputs": [
{
"name": "consolidatedLoanCollateral",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "existingLoanCollateral",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "additionalCollateral",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "view"
},
{
"type": "function",
"name": "collector",
Expand Down
2 changes: 1 addition & 1 deletion src/components/TokenAllowanceGuard/TokenAllowanceGuard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export const TokenAllowanceGuard: React.FC<{
loading={approveMutation.isLoading}
fullWidth
className=""
onClick={() => approveMutation.mutate({ spenderAddressMap })}
onClick={() => approveMutation.mutate({ spenderAddressMap, spendAmount })}
disabled={approveMutation.isLoading}
>
{approveMutation.isLoading ? `${approvalPendingText}` : `${approvalText}`}
Expand Down
7 changes: 4 additions & 3 deletions src/components/TokenAllowanceGuard/hooks/useApproveToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ContractReceipt } from "@ethersproject/contracts";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { AddressMap } from "src/constants/addresses";
import { DecimalBigNumber } from "src/helpers/DecimalBigNumber/DecimalBigNumber";
import { useDynamicTokenContract } from "src/hooks/useContract";
import { contractAllowanceQueryKey } from "src/hooks/useContractAllowance";
import { EthersError } from "src/lib/EthersTypes";
Expand All @@ -15,14 +16,14 @@ export const useApproveToken = (tokenAddressMap: AddressMap) => {
const { chain = { id: 1 } } = useNetwork();
const token = useDynamicTokenContract(tokenAddressMap, true);

return useMutation<ContractReceipt, EthersError, { spenderAddressMap: AddressMap }>(
async ({ spenderAddressMap }) => {
return useMutation<ContractReceipt, EthersError, { spenderAddressMap: AddressMap; spendAmount?: DecimalBigNumber }>(
async ({ spenderAddressMap, spendAmount }) => {
const contractAddress = spenderAddressMap[chain.id as keyof typeof spenderAddressMap];

if (!token) throw new Error("Token doesn't exist on current network. Please switch networks.");
if (!contractAddress) throw new Error("Contract doesn't exist on current network. Please switch networks.");

const transaction = await token.approve(contractAddress, MaxUint256);
const transaction = await token.approve(contractAddress, spendAmount?.toBigNumber() || MaxUint256);

return transaction.wait();
},
Expand Down
41 changes: 41 additions & 0 deletions src/views/Lending/Cooler/hooks/useGetConsolidationAllowances.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useQuery } from "@tanstack/react-query";
import { COOLER_CONSOLIDATION_CONTRACT } from "src/constants/contracts";
import { DecimalBigNumber } from "src/helpers/DecimalBigNumber/DecimalBigNumber";
import { useTestableNetworks } from "src/hooks/useTestableNetworks";
import { CoolerConsolidation__factory } from "src/typechain";
import { useProvider } from "wagmi";

export const useGetConsolidationAllowances = ({
clearingHouseAddress,
coolerAddress,
loanIds,
}: {
clearingHouseAddress: string;
coolerAddress: string;
loanIds: number[];
}) => {
const provider = useProvider();
const networks = useTestableNetworks();

const { data, isFetched, isLoading } = useQuery(
["useGetConsolidationAllowances", clearingHouseAddress, coolerAddress],
async () => {
try {
const contractAddress = COOLER_CONSOLIDATION_CONTRACT.addresses[networks.MAINNET];
const contract = CoolerConsolidation__factory.connect(contractAddress, provider);
const requiredApprovals = await contract.requiredApprovals(clearingHouseAddress, coolerAddress, loanIds);
return {
consolidatedLoanCollateral: new DecimalBigNumber(requiredApprovals[1], 18),
totalDebtWithFee: new DecimalBigNumber(requiredApprovals[2], 18),
};
} catch {
return {
consolidatedLoanCollateral: new DecimalBigNumber("0", 18),
totalDebtWithFee: new DecimalBigNumber("0", 18),
};
}
},
{ enabled: !!coolerAddress },
);
return { data, isFetched, isLoading };
};
137 changes: 134 additions & 3 deletions src/views/Lending/Cooler/positions/ConsolidateLoan.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { Box, SvgIcon, Typography } from "@mui/material";
import { InfoNotification, Modal, PrimaryButton } from "@olympusdao/component-library";
import { BigNumber, ethers } from "ethers";
import { BigNumber } from "ethers";
import { formatEther } from "ethers/lib/utils.js";
import { useEffect, useState } from "react";
import lendAndBorrowIcon from "src/assets/icons/lendAndBorrow.svg?react";
import { TokenAllowanceGuard } from "src/components/TokenAllowanceGuard/TokenAllowanceGuard";
import { COOLER_CONSOLIDATION_ADDRESSES, DAI_ADDRESSES, GOHM_ADDRESSES } from "src/constants/addresses";
import { formatNumber } from "src/helpers";
import { DecimalBigNumber } from "src/helpers/DecimalBigNumber/DecimalBigNumber";
import { useBalance } from "src/hooks/useBalance";
import { useTestableNetworks } from "src/hooks/useTestableNetworks";
import { useConsolidateCooler } from "src/views/Lending/Cooler/hooks/useConsolidateCooler";
import { useGetConsolidationAllowances } from "src/views/Lending/Cooler/hooks/useGetConsolidationAllowances";
import { useGetCoolerLoans } from "src/views/Lending/Cooler/hooks/useGetCoolerLoans";

export const ConsolidateLoans = ({
Expand Down Expand Up @@ -39,6 +39,7 @@ export const ConsolidateLoans = ({
},
{ principal: BigNumber.from(0), interest: BigNumber.from(0), collateral: BigNumber.from(0) },
);
const { data: allowances } = useGetConsolidationAllowances({ clearingHouseAddress, coolerAddress, loanIds });
const maturityDate = new Date();
maturityDate.setDate(maturityDate.getDate() + Number(duration || 0));
const { data: daiBalance } = useBalance({ [networks.MAINNET]: debtAddress || "" })[networks.MAINNET];
Expand All @@ -56,9 +57,139 @@ export const ConsolidateLoans = ({
}
}, [daiBalance, totals.interest]);

console.log("consolidate loans");
return (
<>
<PrimaryButton onClick={() => setOpen(!open)}>Consolidate Loans</PrimaryButton>
<Modal
maxWidth="476px"
minHeight="200px"
open={open}
headerContent={
<Box display="flex" alignItems="center" gap="6px">
<SvgIcon component={lendAndBorrowIcon} /> <Box fontWeight="500">Consolidate Loans</Box>
</Box>
}
onClose={() => setOpen(false)}
>
<>
<InfoNotification>
All existing open loans for this Cooler and Clearinghouse will be repaid and consolidated into a new loan
with a {duration} day duration. You must hold enough DAI in your wallet to cover the interest owed at
consolidation.
</InfoNotification>
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
alignItems="center"
mb={"9px"}
mt={"21px"}
>
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>Loans to Consolidate</Typography>
<Box display="flex" flexDirection="column" textAlign="right">
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>{loans.length}</Typography>
</Box>
</Box>
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
alignItems="center"
mb={"9px"}
mt={"21px"}
>
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>New Principal Amount</Typography>
<Box display="flex" flexDirection="column" textAlign="right">
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>
{formatNumber(parseFloat(formatEther(totals.principal)), 4)} DAI
</Typography>
</Box>
</Box>
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
alignItems="center"
mb={"9px"}
mt={"21px"}
>
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>Interest Owed At Consolidation</Typography>
<Box display="flex" flexDirection="column" textAlign="right">
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>
{formatNumber(parseFloat(formatEther(totals.interest)), 4)} DAI
</Typography>
</Box>
</Box>
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
alignItems="center"
mb={"9px"}
mt={"21px"}
>
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>New Maturity Date</Typography>
<Box display="flex" flexDirection="column" textAlign="right">
<Typography sx={{ fontSize: "15px", lineHeight: "21px" }}>
{maturityDate.toLocaleDateString([], {
month: "long",
day: "numeric",
year: "numeric",
}) || ""}{" "}
{maturityDate.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}
</Typography>
</Box>
</Box>
{insufficientCollateral ? (
<PrimaryButton disabled fullWidth>
Insufficient DAI Balance
</PrimaryButton>
) : (
<TokenAllowanceGuard
tokenAddressMap={DAI_ADDRESSES}
spenderAddressMap={COOLER_CONSOLIDATION_ADDRESSES}
isVertical
message={<>Approve DAI for Spending on the Consolidation Contract</>}
spendAmount={allowances?.totalDebtWithFee}
approvalText="Approve DAI for Spending"
>
<TokenAllowanceGuard
tokenAddressMap={GOHM_ADDRESSES}
spenderAddressMap={COOLER_CONSOLIDATION_ADDRESSES}
isVertical
message={<>Approve gOHM for Spending on the Consolidation Contract</>}
spendAmount={allowances?.consolidatedLoanCollateral}
approvalText="Approve gOHM for Spending"
>
<PrimaryButton
onClick={() => {
coolerMutation.mutate(
{
coolerAddress,
clearingHouseAddress,
loanIds,
},
{
onSuccess: () => {
setOpen(false);
},
},
);
}}
loading={coolerMutation.isLoading}
disabled={coolerMutation.isLoading}
fullWidth
>
Consolidate Loans
</PrimaryButton>
</TokenAllowanceGuard>
</TokenAllowanceGuard>
)}
</>
</Modal>
</>
);
};
Loading