Skip to content

Commit c968b2e

Browse files
committed
feat: refactored actions on reserve-overview page
1 parent 1bad771 commit c968b2e

File tree

8 files changed

+77
-95
lines changed

8 files changed

+77
-95
lines changed

src/components/transactions/Borrow/BorrowActionsSDK.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,6 @@ export const BorrowActionsSDK = React.memo(
6666
const [requiresApproval, setRequiresApproval] = useState(
6767
borrowNative && poolAddress === API_ETH_MOCK_ADDRESS
6868
);
69-
console.log('BorrowActionsSDK render requiresApproval:', requiresApproval);
70-
console.log('PoolAddress', poolAddress);
7169
useEffect(() => {
7270
setRequiresApproval(
7371
borrowNative && poolAddress === API_ETH_MOCK_ADDRESS && !approvalTxState.success

src/components/transactions/Borrow/BorrowModalContentSDK.tsx

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,13 @@ export const BorrowModalContentSDK = ({
5757
const currentNetworkConfig = useRootStore((store) => store.currentNetworkConfig);
5858
const { borrowCap } = useAssetCapsSDK();
5959
const borrowNative = borrowUnWrapped && !!poolReserve.acceptsNative;
60-
console.log('BorrowModalContentSDK render borrowNative:', borrowNative);
6160
const borrowProtocolIncentives = mapAaveProtocolIncentives(poolReserve.incentives, 'borrow');
6261

6362
const [amount, setAmount] = useState('');
6463
const [hfPreviewAfter, setHfPreviewAfter] = useState<string | undefined>();
6564
const [riskCheckboxAccepted, setRiskCheckboxAccepted] = useState(false);
6665

6766
// amount calculations
68-
// const maxAmountToBorrow = getMaxAmountAvailableToBorrow(poolReserve, user);
6967
const maxAmountToBorrow = poolReserve.userState?.borrowable.amount.value || '0';
7068

7169
// We set this in a useEffect, so it doesn't constantly change when
@@ -116,14 +114,11 @@ export const BorrowModalContentSDK = ({
116114
});
117115

118116
if (result.isOk()) {
119-
//!Debug
120-
console.log('healthFactorPreview result', result.value);
121117
setHfPreviewAfter(result.value.after?.toString());
122118
} else {
123119
setHfPreviewAfter(undefined);
124120
}
125121
} catch (error) {
126-
console.error('healthFactorPreview failed', error);
127122
setHfPreviewAfter(undefined);
128123
}
129124
}, 300);

src/components/transactions/FlowCommons/ModalWrapperSDK.tsx

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,18 +71,13 @@ export const ModalWrapperSDK: React.FC<{
7171
);
7272

7373
if (!poolReserveSDK) throw new Error(`Reserve not found for ${underlyingAsset}`);
74-
75-
//!Debug
76-
console.log('poolReserveSDK', poolReserveSDK);
77-
7874
const reserveUserState = poolReserveSDK.userState;
7975
const marketUserState = sdkMarket?.userState;
8076

8177
const symbol =
8278
poolReserveSDK.acceptsNative && !keepWrappedSymbol
8379
? currentNetworkConfig.baseAssetSymbol
8480
: poolReserveSDK.underlyingToken.symbol;
85-
//!Para balacne nativo, no se si esto esta correcto
8681
const nativeKey = API_ETH_MOCK_ADDRESS.toLowerCase();
8782
const tokenKey = poolReserveSDK.underlyingToken.address.toLowerCase();
8883
const nativeBalance = walletBalances[nativeKey]?.amount || '0';
@@ -112,10 +107,6 @@ export const ModalWrapperSDK: React.FC<{
112107
isWrongNetwork,
113108
nativeBalance,
114109
tokenBalance,
115-
//!esto es lo que habia, lo he cambiado por lo de arriba como recomendacion para ensenar el correcto balance
116-
// nativeBalance: walletBalances[API_ETH_MOCK_ADDRESS.toLowerCase()]?.amount || '0',
117-
// tokenBalance:
118-
// walletBalances[poolReserveSDK.underlyingToken.address.toLowerCase()]?.amount || '0',
119110
poolReserve: poolReserveSDK,
120111
symbol,
121112
underlyingAsset,

src/components/transactions/Supply/SupplyModalContentSDK.tsx

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,12 @@ export const SupplyModalContentWrapperSDK = (
7272
const wrappedTokenReserves = useWrappedTokens();
7373
const { walletBalances } = useWalletBalances(currentMarketData);
7474
const { supplyCap: supplyCapUsage, debtCeiling: debtCeilingUsage } = useAssetCapsSDK();
75-
const { supplyReserves } = useAppDataContext(); //! with SDK
75+
const { supplyReserves } = useAppDataContext();
7676
const { poolReserve, reserveUserState, marketUserState } = params;
7777

7878
const wrappedToken = wrappedTokenReserves.find(
7979
(r) => r.tokenOut.underlyingAsset === params.underlyingAsset
8080
);
81-
8281
const canSupplyAsWrappedToken =
8382
wrappedToken &&
8483
walletBalances[wrappedToken.tokenIn.underlyingAsset.toLowerCase()].amount !== '0';
@@ -153,15 +152,10 @@ export const SupplyModalContentSDK = React.memo(
153152
debtCeilingWarning,
154153
user,
155154
}: SupplyModalContentPropsSDK) => {
156-
// const { marketReferencePriceInUsd } = useAppDataContext();
157155
const { mainTxState: supplyTxState, gasLimit, txError } = useModalContext();
158156
const { chainId, currentAccount } = useWeb3Context();
159-
const [minRemainingBaseTokenBalance, currentMarketData, currentNetworkConfig] = useRootStore(
160-
useShallow((state) => [
161-
state.poolComputed.minRemainingBaseTokenBalance,
162-
state.currentMarketData,
163-
state.currentNetworkConfig,
164-
])
157+
const [currentMarketData, currentNetworkConfig] = useRootStore(
158+
useShallow((state) => [state.currentMarketData, state.currentNetworkConfig])
165159
);
166160

167161
// states
@@ -175,12 +169,11 @@ export const SupplyModalContentSDK = React.memo(
175169
const supplyApy = poolReserve.supplyInfo.apy.value;
176170

177171
// Calculate max amount to supply
178-
const maxAmountToSupply = getMaxAmountAvailableToSupplySDK({
172+
const maxAmountToSupply = getMaxAmountAvailableToSupplySDK(
179173
walletBalance,
180-
reserve: poolReserve, // ReserveWithId del SDK
181-
isNativeSelected: !!poolReserve.acceptsNative && supplyUnWrapped,
182-
minRemainingBaseTokenBalance,
183-
});
174+
poolReserve,
175+
underlyingAsset.toLowerCase()
176+
);
184177

185178
const handleChange = (value: string) => {
186179
if (value === '-1') {
@@ -230,17 +223,14 @@ export const SupplyModalContentSDK = React.memo(
230223
});
231224

232225
if (result.isOk()) {
233-
//!Debug
234-
console.log('healthFactorPreview result', result.value);
235226
setHfPreviewAfter(result.value.after?.toString());
236227
} else {
237228
setHfPreviewAfter(undefined);
238229
}
239230
} catch (error) {
240-
console.error('healthFactorPreview failed', error);
241231
setHfPreviewAfter(undefined);
242232
}
243-
}, 2000);
233+
}, 300);
244234

245235
return () => clearTimeout(timer);
246236
}, [
@@ -343,7 +333,7 @@ export const SupplyModalContentSDK = React.memo(
343333
<DetailsHFLine
344334
visibleHfChange={!!amount}
345335
healthFactor={user ? user.healthFactor : '-1'}
346-
futureHealthFactor={hfPreviewAfter?.toString()}
336+
futureHealthFactor={hfPreviewAfter?.toString() ? hfPreviewAfter.toString() : '-1'}
347337
/>
348338
</TxModalDetails>
349339

@@ -372,9 +362,6 @@ export const SupplyWrappedTokenModalContentSDK = ({
372362
const { mainTxState: supplyTxState, gasLimit, txError } = useModalContext();
373363
const { currentAccount } = useWeb3Context();
374364
const { walletBalances } = useWalletBalances(currentMarketData);
375-
const minRemainingBaseTokenBalance = useRootStore(
376-
(state) => state.poolComputed.minRemainingBaseTokenBalance
377-
);
378365
const [hfPreviewAfter, setHfPreviewAfter] = useState<string | undefined>();
379366
const supplyProtocolIncentives = mapAaveProtocolIncentives(poolReserve.incentives, 'supply');
380367

@@ -421,12 +408,11 @@ export const SupplyWrappedTokenModalContentSDK = ({
421408
const supplyCap = poolReserve.supplyInfo.supplyCap.amount.value;
422409
const totalLiquidity = poolReserve.supplyInfo.total.value;
423410

424-
const maxAmountToSupplyTokenOut = getMaxAmountAvailableToSupplySDK({
425-
walletBalance: tokenOutBalance,
426-
reserve: poolReserve,
427-
isNativeSelected: false,
428-
minRemainingBaseTokenBalance,
429-
});
411+
const maxAmountToSupplyTokenOut = getMaxAmountAvailableToSupplySDK(
412+
tokenOutBalance,
413+
poolReserve,
414+
poolReserve.underlyingToken.address
415+
);
430416

431417
const tokenOutRemainingSupplyCap = remainingCap(supplyCap, totalLiquidity);
432418

@@ -512,10 +498,9 @@ export const SupplyWrappedTokenModalContentSDK = ({
512498
setHfPreviewAfter(undefined);
513499
}
514500
} catch (error) {
515-
console.error('healthFactorPreview failed', error);
516501
setHfPreviewAfter(undefined);
517502
}
518-
}, 2000);
503+
}, 300);
519504

520505
return () => clearTimeout(timer);
521506
}, [

src/components/transactions/utils.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -110,17 +110,13 @@ export const getAssetCollateralTypeSdk = ({
110110
marketUserState?: MarketUserState | null;
111111
debtCeilingIsMaxed: boolean;
112112
}) => {
113-
// el asset se puede usar como colateral a nivel de protocolo
114113
if (!reserve.supplyInfo.canBeCollateral) return CollateralType.UNAVAILABLE;
115114

116115
const isIsolationAsset = reserve.isolationModeConfig?.canBeCollateral === true;
117116
const userIsInIsolationMode = marketUserState?.isInIsolationMode === true;
118117
const userHasSuppliedReserve = (reserveUserState?.balance.amount.value ?? '0') !== '0';
119118
const userHasCollateral = (marketUserState?.totalCollateralBase ?? '0') !== '0';
120-
121-
// No tenemos usageAsCollateralEnabledOnUser; usamos el estado actual del SDK
122-
const userCollateralEnabled =
123-
reserveUserState?.canBeCollateral === true || !userHasSuppliedReserve;
119+
const userCollateralEnabled = reserveUserState?.canBeCollateral === true;
124120

125121
let collateralType: CollateralType = CollateralType.ENABLED;
126122

@@ -146,6 +142,6 @@ export const getAssetCollateralTypeSdk = ({
146142
collateralType = userCollateralEnabled ? CollateralType.ENABLED : CollateralType.DISABLED;
147143
}
148144
}
149-
145+
console.log('collateralType', collateralType);
150146
return collateralType;
151147
};

src/modules/reserve-overview/ReserveActions.tsx

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { API_ETH_MOCK_ADDRESS } from '@aave/contract-helpers';
2+
import { valueToBigNumber } from '@aave/math-utils';
23
import { Trans } from '@lingui/macro';
34
import { Box, Button, Divider, Paper, Skeleton, Stack, Typography, useTheme } from '@mui/material';
45
import React, { ReactNode, useState } from 'react';
@@ -16,6 +17,7 @@ import { useWeb3Context } from 'src/libs/hooks/useWeb3Context';
1617
import { BuyWithFiat } from 'src/modules/staking/BuyWithFiat';
1718
import { useRootStore } from 'src/store/root';
1819
import { GENERAL } from 'src/utils/events';
20+
import { getMaxAmountAvailableToSupplySDK } from 'src/utils/getMaxAmountAvailableToSupply';
1921
import { useShallow } from 'zustand/shallow';
2022

2123
import { CapType } from '../../components/caps/helper';
@@ -29,7 +31,6 @@ interface ReserveActionsProps {
2931

3032
export const ReserveActions = ({ reserve }: ReserveActionsProps) => {
3133
const [selectedAsset, setSelectedAsset] = useState<string>(reserve.underlyingToken.symbol);
32-
3334
const { currentAccount } = useWeb3Context();
3435
const { openBorrowSDK, openSupplySDK } = useModalContext();
3536
const [currentMarket, currentNetworkConfig, currentMarketData] = useRootStore(
@@ -42,28 +43,27 @@ export const ReserveActions = ({ reserve }: ReserveActionsProps) => {
4243
const { loading: loadingReserves } = useAppDataContext();
4344
const { walletBalances, loading: loadingWalletBalance } = useWalletBalances(currentMarketData);
4445
const { baseAssetSymbol } = currentNetworkConfig;
45-
let balance = walletBalances[reserve.underlyingToken.address.toLowerCase()];
46-
if (!!reserve.acceptsNative && selectedAsset === baseAssetSymbol) {
47-
balance = walletBalances[API_ETH_MOCK_ADDRESS.toLowerCase()];
48-
}
49-
46+
const isNativeSelected = reserve.acceptsNative && selectedAsset === baseAssetSymbol;
47+
const walletBalance = isNativeSelected
48+
? walletBalances[API_ETH_MOCK_ADDRESS.toLowerCase()]?.amount ?? '0'
49+
: walletBalances[reserve.underlyingToken.address.toLowerCase()]?.amount ?? '0';
50+
const underlyingAsset =
51+
selectedAsset === baseAssetSymbol ? API_ETH_MOCK_ADDRESS : reserve.underlyingToken.address;
5052
let maxAmountToBorrow = '0';
51-
5253
let maxAmountToSupply = '0';
53-
//! MaxAmountToSupply no funciona para NATIVE TOKEN
54+
5455
if (reserve.userState) {
5556
maxAmountToBorrow = reserve.userState.borrowable.amount.value || '0';
56-
console.log('maxAmountToBorrow', maxAmountToBorrow);
57-
maxAmountToSupply = reserve.userState.suppliable.amount.value || '0';
58-
console.log('maxAmountToSupply', maxAmountToSupply);
57+
maxAmountToSupply = getMaxAmountAvailableToSupplySDK(walletBalance, reserve, underlyingAsset);
5958
}
6059

6160
const maxAmountToBorrowUsd = reserve.userState?.borrowable.usd || '0';
62-
63-
const maxAmountToSupplyUsd = reserve.userState?.suppliable.usd || '0';
61+
const maxAmountToSupplyUsd = valueToBigNumber(maxAmountToSupply)
62+
.multipliedBy(reserve.usdExchangeRate ?? '0')
63+
.toString();
6464

6565
const { disableSupplyButton, disableBorrowButton, alerts } = useReserveActionState({
66-
balance: balance?.amount || '0',
66+
balance: walletBalance || '0',
6767
maxAmountToSupply: maxAmountToSupply.toString(),
6868
maxAmountToBorrow: maxAmountToBorrow.toString(),
6969
reserve,
@@ -112,7 +112,7 @@ export const ReserveActions = ({ reserve }: ReserveActionsProps) => {
112112
</Box>
113113
)}
114114
<WalletBalance
115-
balance={balance.amount}
115+
balance={walletBalance}
116116
symbol={selectedAsset}
117117
marketTitle={market.marketTitle}
118118
/>
@@ -375,7 +375,11 @@ const WrappedBaseAssetSelector = ({
375375
color="primary"
376376
value={selectedAsset}
377377
exclusive
378-
onChange={(_, value) => setSelectedAsset(value)}
378+
onChange={(_, value) => {
379+
if (value !== null) {
380+
setSelectedAsset(value);
381+
}
382+
}}
379383
sx={{ mb: 4 }}
380384
>
381385
<StyledTxModalToggleButton value={assetSymbol}>

src/modules/umbrella/StakeAssets/UmbrellaAssetsList.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,15 +86,15 @@ export default function UmbrellaAssetsList({
8686
const balanceB = Number(b.formattedBalances.totalAvailableToStake);
8787
return sortDesc ? balanceB - balanceA : balanceA - balanceB;
8888
}
89-
//! Your Staked Amount: shows the underlying of assets(ej. USDC, WETH) staked or equivalent to the
90-
//! shares.
91-
//! Using stakeTokenReedemableAmount should be the equivalent in Asset to the shares
89+
// Your Staked Amount: shows the underlying of assets(ej. USDC, WETH) staked or equivalent to the
90+
// shares.
91+
// Using stakeTokenReedemableAmount should be the equivalent in Asset to the shares
9292
if (sortName === 'stakeTokenUnderlyingBalance') {
9393
const balanceA = Number(a.formattedBalances?.stakeTokenRedeemableAmount || '0');
9494
const balanceB = Number(b.formattedBalances?.stakeTokenRedeemableAmount || '0');
9595
return sortDesc ? balanceB - balanceA : balanceA - balanceB;
9696
}
97-
//!trial: Shares shows the staked StkToken obtained from the staked asset amount
97+
9898
if (sortName === 'stakeSharesTokens') {
9999
const balanceA = Number(a.formattedBalances?.stakeTokenBalance || '0');
100100
const balanceB = Number(b.formattedBalances?.stakeTokenBalance || '0');

src/utils/getMaxAmountAvailableToSupply.ts

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -56,28 +56,41 @@ export function getMaxAmountAvailableToSupply(
5656
return roundToTokenDecimals(maxAmountToSupply.toString(10), poolReserve.decimals);
5757
}
5858

59-
export const getMaxAmountAvailableToSupplySDK = ({
60-
walletBalance,
61-
reserve,
62-
isNativeSelected,
63-
minRemainingBaseTokenBalance,
64-
}: {
65-
walletBalance: string; // balance ya normalizado a decimales del token
66-
reserve: ReserveWithId;
67-
isNativeSelected: boolean;
68-
minRemainingBaseTokenBalance: string;
69-
}) => {
70-
// 1) saldo de wallet, dejando buffer si es nativo
71-
const walletAfterBuffer = isNativeSelected
72-
? BigNumber.max(
73-
valueToBigNumber(walletBalance).minus(minRemainingBaseTokenBalance),
74-
0
75-
).toString()
76-
: walletBalance;
59+
export function getMaxAmountAvailableToSupplySDK(
60+
walletBalance: string,
61+
poolReserve: ReserveWithId,
62+
underlyingAsset: string
63+
): string {
64+
if (poolReserve.isFrozen) {
65+
return '0';
66+
}
67+
68+
// Calculate max amount to supply
69+
let maxAmountToSupply = valueToBigNumber(walletBalance);
70+
71+
// keep a bit for other transactions
72+
if (
73+
maxAmountToSupply.gt(0) &&
74+
underlyingAsset.toLowerCase() === API_ETH_MOCK_ADDRESS.toLowerCase()
75+
) {
76+
maxAmountToSupply;
77+
}
7778

78-
// 2) límite de protocolo (caps/debt ceiling/estado user) ya calculado por el SDK
79-
const protocolLimit = reserve.userState?.suppliable.amount.value ?? '0';
79+
// make sure we don't try to supply more then maximum supply cap
80+
if (poolReserve.supplyInfo.supplyCap.amount.value !== '0') {
81+
maxAmountToSupply = BigNumber.min(
82+
maxAmountToSupply,
83+
remainingCap(
84+
poolReserve.supplyInfo.supplyCap.amount.value,
85+
poolReserve.supplyInfo.total.value
86+
)
87+
);
88+
}
8089

81-
// 3) máximo final = mínimo entre saldo y límite
82-
return BigNumber.min(walletAfterBuffer, protocolLimit).toString();
83-
};
90+
if (maxAmountToSupply.lte(0)) {
91+
return '0';
92+
}
93+
94+
// Convert amount to smallest allowed precision based on token decimals
95+
return roundToTokenDecimals(maxAmountToSupply.toString(10), poolReserve.underlyingToken.decimals);
96+
}

0 commit comments

Comments
 (0)