Skip to content

Commit 94a3921

Browse files
committed
refactor: move 'loan exists' logic out of fetchLoanDetails
1 parent 641de68 commit 94a3921

File tree

13 files changed

+105
-80
lines changed

13 files changed

+105
-80
lines changed

apps/main/src/llamalend/queries/loan-exists.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export const {
77
useQuery: useLoanExists,
88
refetchQuery: refetchLoanExists,
99
getQueryData: getLoanExists,
10+
invalidate: invalidateLoanExists,
1011
} = queryFactory({
1112
queryKey: (params: UserMarketParams) => [...rootKeys.userMarket(params), 'loan-exists'] as const,
1213
queryFn: async ({ marketId, userAddress }: UserMarketQuery) => {

apps/main/src/loan/components/PageLoanManage/LoanDecrease/index.tsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'
22
import { useAccount } from 'wagmi'
3+
import { refetchLoanExists } from '@/llamalend/queries/loan-exists'
34
import AlertFormError from '@/loan/components/AlertFormError'
45
import AlertFormWarning from '@/loan/components/AlertFormWarning'
56
import DetailInfoBorrowRate from '@/loan/components/DetailInfoBorrowRate'
@@ -148,7 +149,13 @@ const LoanDecrease = ({ curve, llamma, llammaId, params, rChainId }: Props) => {
148149
const resp = await fetchStepDecrease(payloadActiveKey, curve, llamma, formValues)
149150

150151
if (isSubscribed.current && resp && resp.hash && resp.activeKey === activeKey) {
151-
const txInfoBarMessage = resp.loanExists
152+
const loanExists = await refetchLoanExists({
153+
chainId,
154+
marketId: llammaId,
155+
userAddress,
156+
})
157+
158+
const txInfoBarMessage = loanExists
152159
? t`Transaction complete`
153160
: t`Transaction complete. This loan is payoff and will no longer be manageable.`
154161

@@ -157,7 +164,7 @@ const LoanDecrease = ({ curve, llamma, llammaId, params, rChainId }: Props) => {
157164
description={txInfoBarMessage}
158165
txHash={scanTxPath(networks[rChainId], resp.hash)}
159166
onClose={() => {
160-
if (resp.loanExists) {
167+
if (loanExists) {
161168
reset(false, true)
162169
} else {
163170
push(getCollateralListPathname(params))
@@ -168,7 +175,7 @@ const LoanDecrease = ({ curve, llamma, llammaId, params, rChainId }: Props) => {
168175
}
169176
notification?.dismiss()
170177
},
171-
[activeKey, fetchStepDecrease, push, params, rChainId, reset],
178+
[fetchStepDecrease, activeKey, chainId, llammaId, userAddress, rChainId, reset, push, params],
172179
)
173180

174181
const getSteps = useCallback(

apps/main/src/loan/components/PageLoanManage/LoanDeleverage/index.tsx

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'
22
import { styled } from 'styled-components'
33
import { useAccount } from 'wagmi'
4+
import { refetchLoanExists } from '@/llamalend/queries/loan-exists'
45
import AlertFormError from '@/loan/components/AlertFormError'
56
import AlertFormWarning from '@/loan/components/AlertFormWarning'
67
import DetailInfoBorrowRate from '@/loan/components/DetailInfoBorrowRate'
@@ -135,7 +136,13 @@ const LoanDeleverage = ({
135136
const resp = await fetchStepRepay(payloadActiveKey, curve, llamma, formValues, maxSlippage)
136137

137138
if (isSubscribed.current && resp && resp.hash && resp.activeKey === activeKey) {
138-
const txInfoBarMessage = resp.loanExists
139+
const loanExists = await refetchLoanExists({
140+
chainId,
141+
marketId: llammaId,
142+
userAddress,
143+
})
144+
145+
const txInfoBarMessage = loanExists
139146
? t`Transaction complete`
140147
: t`Transaction complete. This loan is paid-off and will no longer be manageable.`
141148

@@ -144,7 +151,7 @@ const LoanDeleverage = ({
144151
description={txInfoBarMessage}
145152
txHash={scanTxPath(networks[rChainId], resp.hash)}
146153
onClose={() => {
147-
if (resp.loanExists) {
154+
if (loanExists) {
148155
updateFormValues({}, '', true)
149156
} else {
150157
push(getCollateralListPathname(params))
@@ -155,7 +162,18 @@ const LoanDeleverage = ({
155162
}
156163
if (typeof dismiss === 'function') dismiss()
157164
},
158-
[activeKey, collateralName, fetchStepRepay, push, params, rChainId, updateFormValues],
165+
[
166+
collateralName,
167+
fetchStepRepay,
168+
activeKey,
169+
chainId,
170+
llammaId,
171+
userAddress,
172+
rChainId,
173+
updateFormValues,
174+
push,
175+
params,
176+
],
159177
)
160178

161179
const getSteps = useCallback(

apps/main/src/loan/components/PageLoanManage/LoanLiquidate/index.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'
22
import { styled } from 'styled-components'
33
import { useAccount } from 'wagmi'
4+
import { refetchLoanExists } from '@/llamalend/queries/loan-exists'
45
import AlertFormError from '@/loan/components/AlertFormError'
56
import AlertFormWarning from '@/loan/components/AlertFormWarning'
67
import DetailInfoEstimateGas from '@/loan/components/DetailInfoEstimateGas'
@@ -126,8 +127,13 @@ const LoanLiquidate = ({ curve, llamma, llammaId, params, rChainId }: Props) =>
126127
const notification = notify(notifyMessage, 'pending')
127128

128129
const resp = await fetchStepLiquidate(curve, llamma, liquidationAmt, maxSlippage)
130+
const loanExists = await refetchLoanExists({
131+
chainId,
132+
marketId: llammaId,
133+
userAddress,
134+
})
129135

130-
if (isSubscribed.current && resp && resp.hash && !resp.loanExists) {
136+
if (isSubscribed.current && resp && resp.hash && !loanExists) {
131137
const TxDescription = (
132138
<>
133139
<Trans>
@@ -161,7 +167,7 @@ const LoanLiquidate = ({ curve, llamma, llammaId, params, rChainId }: Props) =>
161167

162168
return stepsKey.map((k) => stepsObj[k])
163169
},
164-
[fetchStepApprove, fetchStepLiquidate, params, reset],
170+
[fetchStepApprove, fetchStepLiquidate, llammaId, params, reset, userAddress],
165171
)
166172

167173
// onMount

apps/main/src/loan/components/PageLoanManage/Page.tsx

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from 'react'
1+
import { useEffect } from 'react'
22
import { styled } from 'styled-components'
33
import { Address } from 'viem'
44
import { useAccount } from 'wagmi'
@@ -56,10 +56,7 @@ const Page = () => {
5656
const setChartExpanded = useStore((state) => state.ohlcCharts.setChartExpanded)
5757
const { provider, connect: connectWallet } = useWallet()
5858

59-
const [loaded, setLoaded] = useState(false)
60-
6159
const isValidRouterParams = !!rChainId && !!rCollateralId && !!rFormType
62-
const isReady = !!curve?.signerAddress && !!market
6360

6461
const marketDetails = useMarketDetails({ chainId: rChainId, llamma: market, llammaId: marketId })
6562
const positionDetails = useLoanPositionDetails({
@@ -89,27 +86,24 @@ const Page = () => {
8986
})
9087

9188
useEffect(() => {
92-
if (isHydrated && curve && rCollateralId && market) {
93-
void (async () => {
94-
const fetchedLoanDetails = await fetchLoanDetails(curve, market)
95-
if (!fetchedLoanDetails.loanExists) {
96-
push(getLoanCreatePathname(params, rCollateralId))
97-
}
98-
setLoaded(true)
99-
})()
89+
if (curve && market) {
90+
if (loanExists === false) {
91+
push(getLoanCreatePathname(params, rCollateralId))
92+
} else {
93+
void fetchLoanDetails(curve, market)
94+
}
10095
}
101-
}, [isReady, isHydrated, rFormType, curve, rCollateralId, market, fetchLoanDetails, push, params])
96+
}, [curve, fetchLoanDetails, loanExists, market, params, push, rCollateralId])
10297

10398
// redirect if form is deleverage but no deleverage option
10499
useEffect(() => {
105100
if (market && rFormType === 'deleverage' && !hasDeleverage(market)) {
106101
push(getLoanCreatePathname(params, market.id))
107102
}
108-
// eslint-disable-next-line react-hooks/exhaustive-deps
109-
}, [loaded, rFormType, market])
103+
}, [rFormType, market, push, params])
110104

111105
usePageVisibleInterval(() => {
112-
if (curve?.signerAddress && market && loanExists) {
106+
if (curve && market && loanExists) {
113107
void fetchLoanDetails(curve, market)
114108
}
115109
}, REFRESH_INTERVAL['1m'])

apps/main/src/loan/store/createLoanCollateralDecreaseSlice.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import lodash from 'lodash'
22
import type { StoreApi } from 'zustand'
3+
import { invalidateLoanExists } from '@/llamalend/queries/loan-exists'
34
import type { FormStatus, FormValues } from '@/loan/components/PageLoanManage/CollateralDecrease/types'
45
import type { FormDetailInfo, FormEstGas } from '@/loan/components/PageLoanManage/types'
56
import {
@@ -168,10 +169,13 @@ const createLoanCollateralDecrease = (set: StoreApi<State>['setState'], get: Sto
168169
// update user events api
169170
void getUserMarketCollateralEvents(wallet?.account?.address, networks[chainId].id, llamma.controller, resp.hash)
170171
void get()[sliceKey].fetchMaxRemovable(chainId, llamma)
171-
const { loanExists } = await get().loans.fetchLoanDetails(curve, llamma)
172-
if (!loanExists) {
173-
invalidateUserLoanDetails({ chainId, marketId: llamma.id, userAddress: wallet?.account?.address })
174-
}
172+
173+
await get().loans.fetchLoanDetails(curve, llamma)
174+
175+
const queryParams = { chainId, marketId: llamma.id, userAddress: wallet?.account?.address }
176+
invalidateLoanExists(queryParams)
177+
invalidateUserLoanDetails(queryParams)
178+
175179
if (resp.activeKey === get()[sliceKey].activeKey) {
176180
get()[sliceKey].setStateByKeys({
177181
detailInfo: {},

apps/main/src/loan/store/createLoanCollateralIncreaseSlice.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import lodash from 'lodash'
22
import type { StoreApi } from 'zustand'
3+
import { invalidateLoanExists } from '@/llamalend/queries/loan-exists'
34
import type { FormStatus, FormValues } from '@/loan/components/PageLoanManage/CollateralIncrease/types'
45
import type { FormDetailInfo, FormEstGas } from '@/loan/components/PageLoanManage/types'
56
import {
@@ -47,7 +48,7 @@ export type LoanCollateralIncreaseSlice = {
4748
curve: LlamaApi,
4849
llamma: Llamma,
4950
formValues: FormValues,
50-
): Promise<{ activeKey: string; error: string; hash: string; loanExists: boolean } | undefined>
51+
): Promise<{ activeKey: string; error: string; hash: string } | undefined>
5152

5253
// steps helper
5354
setStateByActiveKey<T>(key: StateKey, activeKey: string, value: T): void
@@ -186,12 +187,11 @@ const createLoanCollateralIncrease = (set: StoreApi<State>['setState'], get: Sto
186187
// update user events api
187188
void getUserMarketCollateralEvents(wallet?.account?.address, networks[chainId].id, llamma.controller, resp.hash)
188189
if (activeKey === get()[sliceKey].activeKey) {
189-
// re-fetch loan info
190-
const { loanExists } = await get().loans.fetchLoanDetails(curve, llamma)
190+
await get().loans.fetchLoanDetails(curve, llamma)
191191

192-
if (!loanExists) {
193-
invalidateUserLoanDetails({ chainId, marketId: llamma.id, userAddress: wallet?.account?.address })
194-
}
192+
const queryParams = { chainId, marketId: llamma.id, userAddress: wallet?.account?.address }
193+
invalidateLoanExists(queryParams)
194+
invalidateUserLoanDetails(queryParams)
195195

196196
get()[sliceKey].setStateByKeys({
197197
detailInfo: {},
@@ -206,7 +206,7 @@ const createLoanCollateralIncrease = (set: StoreApi<State>['setState'], get: Sto
206206
},
207207
})
208208

209-
return { ...resp, loanExists }
209+
return resp
210210
}
211211
},
212212

apps/main/src/loan/store/createLoanCreateSlice.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import lodash from 'lodash'
22
import type { StoreApi } from 'zustand'
3-
import { refetchLoanExists } from '@/llamalend/queries/loan-exists'
3+
import { invalidateLoanExists, refetchLoanExists } from '@/llamalend/queries/loan-exists'
44
import type {
55
FormDetailInfoLeverage,
66
FormStatus,
@@ -431,11 +431,11 @@ const createLoanCreate = (set: StoreApi<State>['setState'], get: StoreApi<State>
431431
liqRangesMapper: {},
432432
})
433433

434-
// re-fetch loan info
435-
const { loanExists } = await get().loans.fetchLoanDetails(curve, llamma)
436-
if (!loanExists) {
437-
invalidateUserLoanDetails({ chainId, marketId: llamma.id, userAddress: wallet?.account?.address })
438-
}
434+
await get().loans.fetchLoanDetails(curve, llamma)
435+
436+
const queryParams = { chainId, marketId: llamma.id, userAddress: wallet?.account?.address }
437+
invalidateLoanExists(queryParams)
438+
invalidateUserLoanDetails(queryParams)
439439

440440
// reset form values
441441
const updatedFormValues = DEFAULT_FORM_VALUES
@@ -453,7 +453,7 @@ const createLoanCreate = (set: StoreApi<State>['setState'], get: StoreApi<State>
453453
maxRecv: {},
454454
})
455455

456-
return { ...resp, loanExists }
456+
return resp
457457
}
458458
}
459459
},

apps/main/src/loan/store/createLoanDecreaseSlice.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import lodash from 'lodash'
22
import { zeroAddress } from 'viem'
33
import type { StoreApi } from 'zustand'
4+
import { invalidateLoanExists } from '@/llamalend/queries/loan-exists'
45
import type { FormStatus, FormValues } from '@/loan/components/PageLoanManage/LoanDecrease/types'
56
import type { FormDetailInfo, FormEstGas } from '@/loan/components/PageLoanManage/types'
67
import {
@@ -48,7 +49,7 @@ export type LoanDecreaseSlice = {
4849
curve: LlamaApi,
4950
llamma: Llamma,
5051
formValues: FormValues,
51-
): Promise<{ activeKey: string; error: string; hash: string; loanExists: boolean } | undefined>
52+
): Promise<{ activeKey: string; error: string; hash: string } | undefined>
5253

5354
// steps helper
5455
setStateByActiveKey<T>(key: StateKey, activeKey: string, value: T): void
@@ -215,12 +216,11 @@ const createLoanDecrease = (set: StoreApi<State>['setState'], get: StoreApi<Stat
215216
// update user events api
216217
void getUserMarketCollateralEvents(wallet?.account?.address, networks[chainId].id, llamma.controller, resp.hash)
217218
if (activeKey === get()[sliceKey].activeKey) {
218-
// re-fetch loan info
219-
const { loanExists } = await get().loans.fetchLoanDetails(curve, llamma)
219+
await get().loans.fetchLoanDetails(curve, llamma)
220220

221-
if (!loanExists) {
222-
invalidateUserLoanDetails({ chainId, marketId: llamma.id, userAddress: wallet?.account?.address })
223-
}
221+
const queryParams = { chainId, marketId: llamma.id, userAddress: wallet?.account?.address }
222+
invalidateLoanExists(queryParams)
223+
invalidateUserLoanDetails(queryParams)
224224

225225
get()[sliceKey].setStateByKey('formStatus', {
226226
...get()[sliceKey].formStatus,
@@ -236,7 +236,7 @@ const createLoanDecrease = (set: StoreApi<State>['setState'], get: StoreApi<Stat
236236
formValues: DEFAULT_FORM_VALUES,
237237
})
238238

239-
return { ...resp, loanExists }
239+
return resp
240240
}
241241
},
242242

apps/main/src/loan/store/createLoanDeleverageSlice.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import lodash from 'lodash'
22
import type { StoreApi } from 'zustand'
3+
import { invalidateLoanExists } from '@/llamalend/queries/loan-exists'
34
import type { FormDetailInfo, FormStatus, FormValues } from '@/loan/components/PageLoanManage/LoanDeleverage/types'
45
import {
56
DEFAULT_DETAIL_INFO,
@@ -35,7 +36,7 @@ export type LoanDeleverageSlice = {
3536
fetchDetailInfo(activeKey: string, curve: LlamaApi, llamma: Llamma, formValues: FormValues, maxSlippage: string, userState: UserLoanDetails['userState']): Promise<FormDetailInfo>
3637
setFormValues(llammaId: string, curve: LlamaApi | null, llamma: Llamma | null, formValues: Partial<FormValues>, maxSlippage: string, isFullReset?: boolean): Promise<void>
3738
fetchEstGas(activeKey: string, chainId: ChainId, llamma: Llamma, formValues: FormValues, maxSlippage: string): Promise<void>
38-
fetchStepRepay(activeKey: string, curve: LlamaApi, llamma: Llamma, formValues: FormValues, maxSlippage: string): Promise<{ activeKey: string; error: string; hash: string; loanExists: boolean } | undefined>
39+
fetchStepRepay(activeKey: string, curve: LlamaApi, llamma: Llamma, formValues: FormValues, maxSlippage: string): Promise<{ activeKey: string; error: string; hash: string; } | undefined>
3940
setStateByActiveKey<T>(key: StateKey, activeKey: string, value: T): void
4041
setStateByKey<T>(key: StateKey, value: T): void
4142
setStateByKeys(SliceState: Partial<SliceState>): void
@@ -169,20 +170,17 @@ const createLoanDeleverageSlice = (
169170
// update user events api
170171
void getUserMarketCollateralEvents(wallet?.account?.address, networks[chainId].id, llamma.controller, resp.hash)
171172
if (resp.activeKey === get()[sliceKey].activeKey) {
172-
let loanExists = true
173173
const cFormStatus = cloneDeep(DEFAULT_FORM_STATUS)
174174
cFormStatus.isApproved = get()[sliceKey].formStatus.isApproved
175175

176176
if (resp.error) {
177177
get()[sliceKey].setStateByKey('formStatus', cloneDeep({ ...cFormStatus, error: resp.error }))
178178
} else {
179-
// re-fetch loan info
180-
const respLoanDetails = await get().loans.fetchLoanDetails(curve, llamma)
181-
loanExists = respLoanDetails.loanExists
179+
await get().loans.fetchLoanDetails(curve, llamma)
182180

183-
if (!loanExists) {
184-
invalidateUserLoanDetails({ chainId, marketId: llamma.id, userAddress: wallet?.account?.address })
185-
}
181+
const queryParams = { chainId, marketId: llamma.id, userAddress: wallet?.account?.address }
182+
invalidateLoanExists(queryParams)
183+
invalidateUserLoanDetails(queryParams)
186184

187185
get()[sliceKey].setStateByKeys({
188186
formValues: DEFAULT_FORM_VALUES,
@@ -192,7 +190,7 @@ const createLoanDeleverageSlice = (
192190
})
193191
}
194192

195-
return { ...resp, loanExists }
193+
return resp
196194
}
197195
},
198196

0 commit comments

Comments
 (0)