-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy pathCollateralSwapModalContent.tsx
More file actions
286 lines (260 loc) · 10.9 KB
/
CollateralSwapModalContent.tsx
File metadata and controls
286 lines (260 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { valueToBigNumber } from '@aave/math-utils';
import { SupportedChainId, WRAPPED_NATIVE_CURRENCIES } from '@cowprotocol/cow-sdk';
import { useQueryClient } from '@tanstack/react-query';
import {
ComputedReserveData,
useAppDataContext,
} from 'src/hooks/app-data-provider/useAppDataProvider';
import { TokenInfoWithBalance } from 'src/hooks/generic/useTokensBalance';
import { ExtendedFormattedUser } from 'src/hooks/pool/useExtendedUserSummaryAndIncentives';
import { useRootStore } from 'src/store/root';
import { TOKEN_LIST, TokenInfo } from 'src/ui-config/TokenList';
import { displayGhoForMintableMarket } from 'src/utils/ghoUtilities';
import { useShallow } from 'zustand/shallow';
import { isHorizonMarket } from '../../constants/shared.constants';
import { invalidateAppStateForSwap } from '../../helpers/shared';
import { SwappableToken, SwapParams, SwapType, TokenType } from '../../types';
import { BaseSwapModalContent } from './BaseSwapModalContent';
export const CollateralSwapModalContent = ({ underlyingAsset }: { underlyingAsset: string }) => {
const { user, reserves } = useAppDataContext();
const [account, chainId, currentMarketName] = useRootStore(
useShallow((store) => [store.account, store.currentChainId, store.currentMarket])
);
const queryClient = useQueryClient();
const currentNetworkConfig = useRootStore((store) => store.currentNetworkConfig);
const isHorizon = isHorizonMarket(currentMarketName);
const baseTokens: TokenInfo[] = reserves.map((reserve) => {
return {
address: reserve.underlyingAsset,
symbol: reserve.symbol,
logoURI: `/icons/tokens/${reserve.iconSymbol.toLowerCase()}.svg`,
chainId: currentNetworkConfig.wagmiChain.id,
name: reserve.name,
decimals: reserve.decimals,
};
});
const tokensFrom = getTokensFrom(user, baseTokens, chainId, isHorizon);
const tokensTo = getTokensTo(user, reserves, baseTokens, currentMarketName, chainId, isHorizon);
const userSelectedInputToken = tokensFrom.find(
(token) => token.underlyingAddress.toLowerCase() === underlyingAsset?.toLowerCase()
);
const defaultInputToken =
userSelectedInputToken ?? (tokensFrom.length > 0 ? tokensFrom[0] : undefined);
const defaultOutputToken = getDefaultOutputToken(tokensTo, defaultInputToken);
const invalidateAppState = () => {
invalidateAppStateForSwap({
swapType: SwapType.CollateralSwap,
chainId,
account,
queryClient,
});
};
const initialSourceUserReserve = user?.userReservesData.find(
(userReserve) =>
userReserve.underlyingAsset.toLowerCase() ===
defaultInputToken?.underlyingAddress.toLowerCase()
);
const initialTargetUserReserve = user?.userReservesData.find(
(userReserve) =>
userReserve.underlyingAsset.toLowerCase() ===
defaultOutputToken?.underlyingAddress.toLowerCase()
);
const params: Partial<SwapParams> = {
swapType: SwapType.CollateralSwap,
allowLimitOrders: true,
forcedInputToken: defaultInputToken,
suggestedDefaultOutputToken: defaultOutputToken,
invalidateAppState,
sourceTokens: tokensFrom,
destinationTokens: tokensTo,
showSwitchInputAndOutputAssetsButton: false,
chainId: currentNetworkConfig.wagmiChain.id,
titleTokenPostfix: 'supply',
sourceReserve: initialSourceUserReserve,
destinationReserve: initialTargetUserReserve,
resultScreenTokensFromTitle: 'Collateral sent',
resultScreenTokensToTitle: 'Collateral received',
resultScreenTitleItems: 'collateral',
// Note: Collateral Swap order is not inverted
inputInputTitleSell: 'Swap',
outputInputTitleSell: 'Receive at most',
inputInputTitleBuy: 'Swap at most',
outputInputTitleBuy: 'Receive',
};
return <BaseSwapModalContent params={params} />;
};
const getDefaultOutputToken = (
tokensTo: SwappableToken[],
defaultInputToken: SwappableToken | undefined
) => {
const tokensWithoutInputToken = tokensTo.filter(
(token) =>
// Filter out tokens that match by addressToSwap OR underlyingAddress OR symbol
// This prevents the same asset from appearing in both lists (triple check for robustness)
token.addressToSwap.toLowerCase() !== defaultInputToken?.addressToSwap.toLowerCase() &&
token.underlyingAddress.toLowerCase() !==
defaultInputToken?.underlyingAddress.toLowerCase() &&
token.symbol !== defaultInputToken?.symbol
);
// 1. Highest balance
const highestBalanceToken = tokensWithoutInputToken
.filter((token) => token.balance !== '0')
.sort((a, b) => Number(b.balance) - Number(a.balance));
if (highestBalanceToken.length > 0) {
return highestBalanceToken[0];
}
// 2. USDT or USDC or AAVE (but not the input token)
const usdtOrUsdcOrAaveToken = tokensWithoutInputToken.filter(
(token) =>
(token.symbol === 'USDT' || token.symbol === 'USDC' || token.symbol === 'AAVE') &&
token.symbol !== defaultInputToken?.symbol
);
if (usdtOrUsdcOrAaveToken.length > 0) {
return usdtOrUsdcOrAaveToken[0];
}
// 3. Other not the default input token
if (tokensWithoutInputToken.length > 0) {
return tokensWithoutInputToken[0];
}
return undefined;
};
const getTokensFrom = (
user: ExtendedFormattedUser | undefined,
baseTokensInfo: TokenInfo[],
chainId: number,
isHorizon: boolean
): SwappableToken[] => {
// Tokens From should be the supplied tokens
const suppliedPositions =
user?.userReservesData
.filter((userReserve) => userReserve.underlyingBalance !== '0')
.filter((userReserve) => !isHorizon || userReserve.reserve.borrowingEnabled) || [];
return suppliedPositions
.map<SwappableToken | undefined>((position) => {
const baseToken = baseTokensInfo.find(
(baseToken) =>
baseToken.address.toLowerCase() === position.reserve.underlyingAsset.toLowerCase()
);
if (baseToken) {
// Prefer showing native symbol (e.g., ETH) instead of WETH when applicable, but keep underlying address
const wrappedNative =
WRAPPED_NATIVE_CURRENCIES[chainId as SupportedChainId]?.address?.toLowerCase();
const isWrappedNative =
wrappedNative && position.reserve.underlyingAsset.toLowerCase() === wrappedNative;
const nativeToken = isWrappedNative
? TOKEN_LIST.tokens.find(
(t) => (t as TokenInfoWithBalance).extensions?.isNative && t.chainId === chainId
)
: undefined;
let balance = position.underlyingBalance;
if (position.reserve.supplyAPY === '0') {
// remove one wei from balance because is rounded up
const balanceBN = valueToBigNumber(balance);
const decimals = balanceBN.decimalPlaces();
if (decimals && decimals > 15) {
const oneWei = valueToBigNumber(1).dividedBy(10 ** (decimals ?? 18));
balance = balanceBN.minus(oneWei).toString();
}
}
return {
addressToSwap: position.reserve.aTokenAddress,
addressForUsdPrice: position.reserve.aTokenAddress,
underlyingAddress: position.reserve.underlyingAsset,
decimals: baseToken.decimals,
symbol: nativeToken?.symbol ?? baseToken.symbol,
name: nativeToken?.name ?? baseToken.name,
balance,
chainId,
usdPrice: position.reserve.priceInUSD,
supplyAPY: position.reserve.supplyAPY,
variableBorrowAPY: position.reserve.variableBorrowAPY,
logoURI: nativeToken?.logoURI ?? baseToken.logoURI,
tokenType: nativeToken?.extensions?.isNative ? TokenType.NATIVE : TokenType.ERC20,
};
}
return undefined;
})
.filter((token) => token !== undefined)
.sort((a, b) => {
const aBalance = parseFloat(a?.balance ?? '0');
const bBalance = parseFloat(b?.balance ?? '0');
if (bBalance !== aBalance) {
return bBalance - aBalance;
}
// If balances are equal, sort by symbol alphabetically
const aSymbol = a?.symbol?.toLowerCase() ?? '';
const bSymbol = b?.symbol?.toLowerCase() ?? '';
if (aSymbol < bSymbol) return -1;
if (aSymbol > bSymbol) return 1;
return 0;
});
};
const getTokensTo = (
user: ExtendedFormattedUser | undefined,
reserves: ComputedReserveData[],
baseTokensInfo: TokenInfo[],
currentMarket: string,
chainId: number,
isHorizon: boolean
): SwappableToken[] => {
// Tokens To should be the potential supply tokens (so we have an aToken)
const tokensToSupply = reserves.filter(
(reserve: ComputedReserveData) =>
!(reserve.isFrozen || reserve.isPaused) &&
(!isHorizon || reserve.borrowingEnabled) &&
!displayGhoForMintableMarket({ symbol: reserve.symbol, currentMarket: currentMarket })
);
const suppliedPositions =
user?.userReservesData.filter((userReserve) => userReserve.underlyingBalance !== '0') || [];
return tokensToSupply
.map<SwappableToken | undefined>((reserve) => {
// Find the base token for this reserve
const baseToken = baseTokensInfo.find(
(baseToken) => baseToken.address.toLowerCase() === reserve.underlyingAsset.toLowerCase()
);
if (!baseToken) return undefined;
const currentCollateral =
suppliedPositions.find(
(position) =>
position.reserve.underlyingAsset.toLowerCase() === reserve.underlyingAsset.toLowerCase()
)?.underlyingBalance ?? '0';
// Prefer showing native symbol (e.g., ETH) instead of WETH when applicable, but keep underlying address
const wrappedNative =
WRAPPED_NATIVE_CURRENCIES[chainId as SupportedChainId]?.address?.toLowerCase();
const isWrappedNative =
wrappedNative && reserve.underlyingAsset.toLowerCase() === wrappedNative;
const nativeToken = isWrappedNative
? TOKEN_LIST.tokens.find(
(t) => (t as TokenInfoWithBalance).extensions?.isNative && t.chainId === chainId
)
: undefined;
return {
addressToSwap: reserve.aTokenAddress,
addressForUsdPrice: reserve.aTokenAddress,
underlyingAddress: reserve.underlyingAsset,
decimals: baseToken.decimals,
symbol: nativeToken?.symbol ?? baseToken.symbol,
name: baseToken.name,
balance: currentCollateral,
chainId,
usdPrice: reserve.priceInUSD,
supplyAPY: reserve.supplyAPY,
variableBorrowAPY: reserve.variableBorrowAPY,
logoURI: nativeToken?.logoURI ?? baseToken.logoURI,
};
})
.filter((token) => token !== undefined)
.sort((a, b) => {
const aBalance = parseFloat(a?.balance ?? '0');
const bBalance = parseFloat(b?.balance ?? '0');
if (bBalance !== aBalance) {
return bBalance - aBalance;
}
// If balances are equal, sort by symbol alphabetically
const aSymbol = a?.symbol?.toLowerCase() ?? '';
const bSymbol = b?.symbol?.toLowerCase() ?? '';
if (aSymbol < bSymbol) return -1;
if (aSymbol > bSymbol) return 1;
return 0;
});
};