Skip to content
Merged
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
2 changes: 0 additions & 2 deletions apps/main/src/lend/entities/user-loan-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ type UserLoanDetails = {
state: { collateral: string; borrowed: string; debt: string; N: string }
status: { label: string; colorKey: HealthColorKey; tooltip: string }
leverage: string
pnl: Record<string, string>
}

const _getUserLoanDetails = async ({ marketId, userAddress }: UserLoanDetailsQuery): Promise<UserLoanDetails> => {
Expand Down Expand Up @@ -79,7 +78,6 @@ const _getUserLoanDetails = async ({ marketId, userAddress }: UserLoanDetailsQue
prices,
loss,
leverage,
pnl,
status: getLiquidationStatus(healthNotFull, isCloseToLiquidation, state.borrowed),
}
}
Expand Down
26 changes: 19 additions & 7 deletions apps/main/src/lend/hooks/useBorrowPositionDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { ChainId, OneWayMarketTemplate } from '@/lend/types/lend.types'
import type { BorrowPositionDetailsProps } from '@/llamalend/features/market-position-details'
import { calculateRangeToLiquidation } from '@/llamalend/features/market-position-details/utils'
import { calculateLtv } from '@/llamalend/llama.utils'
import { useLoanExists } from '@/llamalend/queries/loan-exists'
import { useUserPnl } from '@/llamalend/queries/user-pnl.query'
import type { Address, Chain } from '@curvefi/prices-api'
import { useCampaignsByAddress } from '@ui-kit/entities/campaigns'
import { useLendingSnapshots } from '@ui-kit/entities/lending-snapshots'
Expand Down Expand Up @@ -41,14 +43,24 @@ export const useBorrowPositionDetails = ({
bands,
health,
leverage,
pnl,
loss,
prices: liquidationPrices,
status,
state: { collateral, borrowed, debt } = {},
} = userLoanDetails ?? {}
const prices = useStore((state) => state.markets.pricesMapper[chainId]?.[marketId])

const { data: loanExists } = useLoanExists({
chainId,
marketId,
userAddress,
})
const { data: userPnl, isLoading: isUserPnlLoading } = useUserPnl({
chainId,
marketId,
userAddress,
loanExists,
hasV2Leverage: true,
})
const blockchainId = networks[chainId].id as Chain
const { data: campaigns } = useCampaignsByAddress({ blockchainId, address: controller as Address })
const { data: onChainRatesData, isLoading: isOnchainRatesLoading } = useMarketOnChainRates({
Expand Down Expand Up @@ -141,11 +153,11 @@ export const useBorrowPositionDetails = ({
loading: !market || isUserLoanDetailsLoading,
},
pnl: {
currentProfit: pnl?.currentProfit ? Number(pnl.currentProfit) : null,
currentPositionValue: pnl?.currentPosition ? Number(pnl.currentPosition) : null,
depositedValue: pnl?.deposited ? Number(pnl.deposited) : null,
percentageChange: pnl?.percentage ? Number(pnl.percentage) : null,
loading: !market || isUserLoanDetailsLoading,
currentProfit: userPnl?.currentProfit,
currentPositionValue: userPnl?.currentPosition,
depositedValue: userPnl?.deposited,
percentageChange: userPnl?.percentage,
loading: !market || isUserPnlLoading,
},
leverage: {
value: leverage ? Number(leverage) : null,
Expand Down
4 changes: 1 addition & 3 deletions apps/main/src/lend/lib/apiLending.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ const user = {
.process(async (market) => {
const userActiveKey = helpers.getUserActiveKey(api, market)

const [state, healthFull, healthNotFull, range, bands, prices, bandsBalances, oraclePriceBand, leverage, pnl] =
const [state, healthFull, healthNotFull, range, bands, prices, bandsBalances, oraclePriceBand, leverage] =
await Promise.all([
market.userState(),
market.userHealth(),
Expand All @@ -274,7 +274,6 @@ const user = {
market.userBandsBalances(),
market.oraclePriceBand(),
market.currentLeverage(signerAddress),
market.currentPnL(signerAddress),
])

// Fetch user loss separately to prevent prices-api dependency from blocking contract read data
Expand Down Expand Up @@ -311,7 +310,6 @@ const user = {
prices,
loss,
leverage,
pnl,
status: getLiquidationStatus(healthNotFull, isCloseToLiquidation, state.borrowed),
},
error: '',
Expand Down
1 change: 0 additions & 1 deletion apps/main/src/lend/types/lend.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,6 @@ export type UserLoanDetails = {
state: { collateral: string; borrowed: string; debt: string; N: string }
status: { label: string; colorKey: HealthColorKey; tooltip: string }
leverage: string
pnl: Record<string, string>
} | null
error: string
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,13 @@ export const BorrowInformation = ({
label={t`PNL`}
valueOptions={{ unit: 'dollar' }}
value={
pnl?.currentPositionValue && pnl?.currentProfit && pnl?.depositedValue ? pnl?.currentProfit : undefined
pnl?.currentPositionValue && pnl?.currentProfit && pnl?.depositedValue
? Number(pnl?.currentProfit)
: undefined
}
change={
pnl?.currentPositionValue && pnl?.percentageChange && pnl?.depositedValue
? pnl?.percentageChange
? Number(pnl?.percentageChange)
: undefined
}
loading={pnl?.currentProfit == null && pnl?.loading}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ export type LiquidationAlert = {
hardLiquidation: boolean
}
export type Pnl = {
currentProfit: number | undefined | null
currentPositionValue: number | undefined | null
depositedValue: number | undefined | null
percentageChange: number | undefined | null
currentProfit: Decimal | undefined
currentPositionValue: Decimal | undefined
depositedValue: Decimal | undefined
percentageChange: Decimal | undefined
loading: boolean
}
export type Health = { value: number | undefined | null; loading: boolean }
Expand Down Expand Up @@ -69,7 +69,7 @@ export type BorrowPositionDetailsProps = {
liquidationAlert: LiquidationAlert
health: Health
borrowAPY: BorrowAPY
pnl?: Pnl // doesn't exist yet for crvusd
pnl?: Pnl // not all mint markets has PNL data (requires v2 leverage support)
liquidationRange: LiquidationRange
bandRange: BandRange
leverage?: Leverage // doesn't exist yet for crvusd
Expand Down
42 changes: 42 additions & 0 deletions apps/main/src/llamalend/queries/user-pnl.query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { enforce, group, test } from 'vest'
import { getLlamaMarket } from '@/llamalend/llama.utils'
import type { IChainId } from '@curvefi/api/lib/interfaces'
import { type FieldsOf } from '@ui-kit/lib'
import { type MarketQuery, queryFactory, rootKeys, type UserQuery } from '@ui-kit/lib/model'
import { loanExistsValidationGroup } from '@ui-kit/lib/model/query/loan-exists-validation'
import { marketIdValidationSuite } from '@ui-kit/lib/model/query/market-id-validation'
import { createValidationSuite } from '@ui-kit/lib/validation'
import { decimal } from '@ui-kit/utils'

/**
* Query for fetching user PNL data in lend and mint markets.
* PNL data from llamalend-js for mint markets is currently only available when v2 leverage is enabled.
*/
type UserPnlQuery = UserQuery & MarketQuery<IChainId> & { loanExists: boolean; hasV2Leverage: boolean }
type UserPnlParams = FieldsOf<UserPnlQuery>

export const { useQuery: useUserPnl, invalidate: invalidateUserPnl } = queryFactory({
queryKey: ({ chainId, marketId, userAddress }: UserPnlParams) =>
[...rootKeys.userMarket({ chainId, marketId, userAddress }), 'user-pnl'] as const,
queryFn: async ({ marketId, userAddress }: UserPnlQuery) => {
const market = getLlamaMarket(marketId)

const pnl = await market.currentPnL(userAddress)
return {
currentPosition: decimal(pnl?.currentPosition),
deposited: decimal(pnl?.deposited),
currentProfit: decimal(pnl?.currentProfit),
percentage: decimal(pnl?.percentage),
}
},
staleTime: '1m',
validationSuite: createValidationSuite((params: UserPnlParams) => {
marketIdValidationSuite(params)
loanExistsValidationGroup(params)
group('hasV2LeverageValidation', () => {
test('hasV2Leverage', () => {
enforce(params.hasV2Leverage).isBoolean().equals(true)
})
})
}),
})
28 changes: 28 additions & 0 deletions apps/main/src/loan/hooks/useLoanPositionDetails.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import lodash from 'lodash'
import { useEffect, useMemo, useState } from 'react'
import { useAccount } from 'wagmi'
import { DEFAULT_HEALTH_MODE } from '@/llamalend/constants'
import type { BorrowPositionDetailsProps } from '@/llamalend/features/market-position-details'
import { calculateRangeToLiquidation } from '@/llamalend/features/market-position-details/utils'
import { DEFAULT_BORROW_TOKEN_SYMBOL, getHealthMode } from '@/llamalend/health.util'
import { calculateLtv } from '@/llamalend/llama.utils'
import { useLoanExists } from '@/llamalend/queries/loan-exists'
import { useUserPnl } from '@/llamalend/queries/user-pnl.query'
import { CRVUSD_ADDRESS } from '@/loan/constants'
import { useUserLoanDetails } from '@/loan/hooks/useUserLoanDetails'
import networks from '@/loan/networks'
import useStore from '@/loan/store/useStore'
import { ChainId, Llamma } from '@/loan/types/loan.types'
import { hasV2Leverage } from '@/loan/utils/leverage'
import { Address } from '@curvefi/prices-api'
import { useCampaignsByAddress } from '@ui-kit/entities/campaigns'
import { useCrvUsdSnapshots } from '@ui-kit/entities/crvusd-snapshots'
Expand All @@ -33,6 +37,7 @@ export const useLoanPositionDetails = ({
llammaId,
}: UseLoanPositionDetailsProps): BorrowPositionDetailsProps => {
const blockchainId = networks[chainId]?.id
const { address: userAddress } = useAccount()
const { data: campaigns } = useCampaignsByAddress({
blockchainId,
address: llamma?.controller?.toLocaleLowerCase() as Address,
Expand All @@ -45,6 +50,20 @@ export const useLoanPositionDetails = ({
const userLoanDetailsLoading = useStore((state) => state.loans.userDetailsMapper[llammaId]?.loading)
const loanDetails = useStore((state) => state.loans.detailsMapper[llammaId ?? ''])
const { healthFull, healthNotFull } = useUserLoanDetails(llammaId) ?? {}
const v2LeverageEnabled = useMemo(() => hasV2Leverage(llamma ?? null), [llamma])

const { data: loanExists } = useLoanExists({
chainId,
marketId: llammaId,
userAddress,
})
const { data: userPnl, isLoading: isUserPnlLoading } = useUserPnl({
chainId,
marketId: llammaId,
userAddress,
loanExists,
hasV2Leverage: v2LeverageEnabled,
})
const { oraclePriceBand } = loanDetails ?? {}

const [healthMode, setHealthMode] = useState(DEFAULT_HEALTH_MODE)
Expand Down Expand Up @@ -155,6 +174,15 @@ export const useLoanPositionDetails = ({
: null,
loading: userLoanDetailsLoading ?? true,
},
pnl: v2LeverageEnabled
? {
currentProfit: userPnl?.currentProfit,
currentPositionValue: userPnl?.currentPosition,
depositedValue: userPnl?.deposited,
percentageChange: userPnl?.percentage,
loading: isUserPnlLoading ?? true,
}
: undefined,
totalDebt: {
value: debt ? Number(debt) : null,
loading: userLoanDetailsLoading ?? true,
Expand Down
Loading