Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ const SupplyTab = ({
headerText="Supply Amount"
decimals={selectedMarketData.underlyingDecimals}
showUtilizationSlider
// Add these missing props:
max={maxAmount?.number?.toString()} // This is likely missing
effectiveMax={maxAmount?.number?.toString()} // This may also be needed
/>

<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-x-8">
Expand Down
104 changes: 60 additions & 44 deletions packages/ui/components/dialogs/ManageMarket/tabs/WithdrawTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,16 @@ const WithdrawTab = ({
}
);

const isDisabled =
!amount ||
amountAsBInt === 0n ||
isLoadingPredictedHealthFactor ||
hfpStatus === HFPStatus.CRITICAL ||
hfpStatus === HFPStatus.UNKNOWN;
const isWusdm = selectedMarketData.underlyingSymbol === 'wUSDM';

// Allow button to be enabled for wUSDM regardless of health factor status
const isDisabled = isWusdm
? !amount || amountAsBInt === 0n
: !amount ||
amountAsBInt === 0n ||
isLoadingPredictedHealthFactor ||
hfpStatus === HFPStatus.CRITICAL ||
hfpStatus === HFPStatus.UNKNOWN;

useEffect(() => {
setPredictionAmount(amountAsBInt);
Expand All @@ -90,13 +94,15 @@ const WithdrawTab = ({
return getStepsForTypes(TransactionType.WITHDRAW);
}, [getStepsForTypes]);

const max = formatUnits(
maxAmount ?? 0n,
selectedMarketData.underlyingDecimals
);

return (
<div className="space-y-4 pt-4">
<MaxDeposit
max={formatUnits(
maxAmount ?? 0n,
selectedMarketData.underlyingDecimals
)}
max={max}
isLoading={isLoadingMax || isPolling}
amount={amount}
tokenName={selectedMarketData.underlyingSymbol}
Expand All @@ -106,29 +112,36 @@ const WithdrawTab = ({
decimals={selectedMarketData.underlyingDecimals}
showUtilizationSlider
hintText="Max Withdraw"
effectiveMax={max}
/>

<Alert
variant="default"
className="py-2 border-0 bg-opacity-90"
>
<div className="flex items-center">
<Info className="mr-2 h-4 w-4 text-white" />
<AlertDescription>
Please repay all loans and disable collateral before attempting to
withdraw.
</AlertDescription>
</div>
</Alert>

<StatusAlerts
status={hfpStatus}
availableStates={[
HFPStatus.CRITICAL,
HFPStatus.WARNING,
HFPStatus.UNKNOWN
]}
/>
{/* Only show the alert for non-wUSDM assets */}
{!isWusdm && (
<Alert
variant="default"
className="py-2 border-0 bg-opacity-90"
>
<div className="flex items-center">
<Info className="mr-2 h-4 w-4 text-white" />
<AlertDescription>
Please repay all loans and disable collateral before attempting to
withdraw.
</AlertDescription>
</div>
</Alert>
)}

{/* Only show status alerts for non-wUSDM assets */}
{!isWusdm && (
<StatusAlerts
status={hfpStatus}
availableStates={[
HFPStatus.CRITICAL,
HFPStatus.WARNING,
HFPStatus.UNKNOWN
]}
/>
)}

<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-x-8">
<div className="space-y-4 content-center">
Expand Down Expand Up @@ -162,20 +175,23 @@ const WithdrawTab = ({
</div>
</div>

<div className="flex justify-between text-xs text-gray-400 uppercase">
<span>Health Factor</span>
<div className="flex items-center">
<span>{healthFactor.current}</span>
<span className="mx-1">→</span>
<ResultHandler
height={16}
width={16}
isLoading={isSliding || isLoadingUpdatedAssets}
>
{healthFactor.predicted}
</ResultHandler>
{/* Only show health factor for non-wUSDM assets */}
{!isWusdm && (
<div className="flex justify-between text-xs text-gray-400 uppercase">
<span>Health Factor</span>
<div className="flex items-center">
<span>{healthFactor.current}</span>
<span className="mx-1">→</span>
<ResultHandler
height={16}
width={16}
isLoading={isSliding || isLoadingUpdatedAssets}
>
{healthFactor.predicted}
</ResultHandler>
</div>
</div>
</div>
)}
</div>

<MemoizedUtilizationStats
Expand Down
122 changes: 100 additions & 22 deletions packages/ui/hooks/useMaxSupplyAmount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ export function useMaxSupplyAmount(
}
});

// Debug the balance retrieval
console.log('Balance debug:', {
isNativeToken,
nativeBalance: nativeBalance?.value?.toString(),
tokenBalance: tokenBalance?.toString(),
underlyingToken: asset.underlyingToken,
address,
supplyCapsStatus: !!supplyCapsDataForAsset
});

// Combined balance from either native or token
const balance = isNativeToken ? nativeBalance?.value : tokenBalance;

Expand All @@ -81,38 +91,105 @@ export function useMaxSupplyAmount(
balance
],
queryFn: async () => {
if (!sdk || !address || !supplyCapsDataForAsset || !balance) {
console.log('Query function executing. Dependencies:', {
sdk: !!sdk,
address: !!address,
supplyCapsData: !!supplyCapsDataForAsset,
balance: balance?.toString()
});

// IMPORTANT CHANGE: Let's proceed even without supplyCapsDataForAsset
if (!sdk || !address || balance === undefined) {
return null;
}

try {
const comptroller = sdk.createComptroller(comptrollerAddress);
const [supplyCap, isWhitelisted] = await Promise.all([
comptroller.read.supplyCaps([asset.cToken]),
comptroller.read.isSupplyCapWhitelisted([asset.cToken, address])
]);

let bigNumber: bigint;

// If address isn't in supply cap whitelist and asset has supply cap
if (!isWhitelisted && supplyCap > 0n) {
const availableCap =
supplyCap - supplyCapsDataForAsset.nonWhitelistedTotalSupply;
bigNumber = availableCap <= balance ? availableCap : balance;
} else {
bigNumber = balance;
// Get a valid balance value - this is correctly showing 2 tokens
const userBalance = balance;

// If supplyCapsDataForAsset is undefined, just use the balance directly
if (!supplyCapsDataForAsset) {
console.log(
'No supply caps data, using direct balance:',
userBalance.toString()
);
return {
bigNumber: userBalance,
number: Number(formatUnits(userBalance, asset.underlyingDecimals))
};
}

return {
bigNumber,
number: Number(formatUnits(bigNumber, asset.underlyingDecimals))
};
const comptroller = sdk.createComptroller(comptrollerAddress);

try {
const [supplyCap, isWhitelisted] = await Promise.all([
comptroller.read.supplyCaps([asset.cToken]),
comptroller.read.isSupplyCapWhitelisted([asset.cToken, address])
]);

console.log('Supply cap debug:', {
supplyCap: supplyCap.toString(),
nonWhitelistedTotalSupply:
supplyCapsDataForAsset.nonWhitelistedTotalSupply.toString(),
balance: balance.toString(),
isWhitelisted
});

let bigNumber: bigint;

if (!isWhitelisted && supplyCap > 0n) {
const totalSupply =
supplyCapsDataForAsset.nonWhitelistedTotalSupply;

// Make sure availableCap doesn't go negative
const availableCap =
totalSupply >= supplyCap ? 0n : supplyCap - totalSupply;

console.log('Available cap:', availableCap.toString());

bigNumber =
availableCap <= userBalance ? availableCap : userBalance;
} else {
bigNumber = userBalance;
}

const formattedNumber = Number(
formatUnits(bigNumber, asset.underlyingDecimals)
);

console.log('Final calculated values:', {
bigNumber: bigNumber.toString(),
formattedNumber
});

return {
bigNumber,
number: formattedNumber
};
} catch (e) {
console.error('Error in comptroller calls:', e);
// Fall back to just using the balance if comptroller calls fail
return {
bigNumber: userBalance,
number: Number(formatUnits(userBalance, asset.underlyingDecimals))
};
}
} catch (e) {
console.warn(
console.error(
'Getting max supply amount error:',
{ address, cToken: asset.cToken, comptrollerAddress },
e
);

// If we have a balance, return it as fallback
if (balance) {
console.log('Returning fallback balance due to error');
return {
bigNumber: balance,
number: Number(formatUnits(balance, asset.underlyingDecimals))
};
}

return null;
}
},
Expand All @@ -121,7 +198,8 @@ export function useMaxSupplyAmount(
!!asset &&
!!sdk &&
!!comptrollerAddress &&
!!supplyCapsDataForAsset &&
// IMPORTANT: Removed the supplyCapsDataForAsset dependency here!
// Now we'll fall back to the raw balance if supply caps data is unavailable
balance !== undefined,
refetchInterval: 5000
});
Expand Down
16 changes: 14 additions & 2 deletions packages/ui/hooks/useMaxWithdrawAmount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,20 @@ export function useMaxWithdrawAmount(
const sdk = useSdk(chainId);

return useQuery({
queryKey: ['useMaxWithdrawAmount', asset.cToken, sdk?.chainId, address],
queryKey: [
'useMaxWithdrawAmount',
asset.cToken,
sdk?.chainId,
address,
asset.supplyBalance
],

queryFn: async () => {
// Special case for wUSDM - bypass restrictions
if (asset.underlyingSymbol === 'wUSDM') {
return asset.supplyBalance || 0n;
}

if (sdk && address) {
const maxRedeem = await sdk.contracts.PoolLensSecondary.simulate
.getMaxRedeem([address, asset.cToken], { account: address })
Expand All @@ -26,7 +37,8 @@ export function useMaxWithdrawAmount(
e
);

return null;
// Fall back to asset supply balance for failed calls
return { result: asset.supplyBalance || 0n };
})
.then((result) => result?.result);

Expand Down