This commit is contained in:
Linkie Link 2023-06-22 22:42:21 +02:00
parent ee445b1272
commit 44133f72bd
No known key found for this signature in database
GPG Key ID: 5318B0F2564D38EA
2 changed files with 23 additions and 9 deletions

View File

@ -1,8 +1,9 @@
import BigNumber from 'bignumber.js'
import { Action, ActionAmount } from 'types/generated/mars-credit-manager/MarsCreditManager.types'
export const getClosePositionActions = (
vault: ActiveVault,
exchangeRate: number,
primaryToSecondaryRate: number,
slippage: number,
): Action[] => {
const swapMessage: Action[] = []
@ -12,20 +13,33 @@ export const getClosePositionActions = (
Math.max(vault.position.amounts.borrowedPrimary, vault.position.amounts.borrowedSecondary) *
1.001,
)
const secondaryAmount = vault.position.amounts.lp.secondary
const borrowType =
vault.position.amounts.borrowedPrimary > vault.position.amounts.borrowedSecondary
? 'primary'
: 'secondary'
const availableAmountForRepay = vault.position.amounts.lp[borrowType]
if (availableAmountForRepay < borrowAmount) {
const swapTargetAmount = borrowAmount - availableAmountForRepay
const exchangeRate =
borrowType === 'secondary'
? new BigNumber(1).div(primaryToSecondaryRate)
: new BigNumber(primaryToSecondaryRate)
const swapAmount = Math.max(
exchangeRate.times(swapTargetAmount).integerValue(BigNumber.ROUND_CEIL).toNumber(),
10,
)
if (secondaryAmount < borrowAmount) {
const swapTargetAmount = borrowAmount - secondaryAmount
const swapAmount = Math.max(Math.ceil(swapTargetAmount / exchangeRate), 10)
swapMessage.push({
swap_exact_in: {
coin_in: {
amount: {
exact: swapAmount.toString(),
},
denom: vault.denoms.primary,
denom: borrowType === 'secondary' ? vault.denoms.primary : vault.denoms.secondary,
},
denom_out: vault.denoms.secondary,
denom_out: vault.denoms[borrowType],
slippage: slippage.toString(),
},
})

View File

@ -15,11 +15,11 @@ export const useClosePosition = (props: Props) => {
const actions = useMemo(() => {
if (!props.activeVault) return []
const exchangeRate = getExchangeRate(
const primaryToSecondaryRate = getExchangeRate(
props.activeVault.denoms.primary,
props.activeVault.denoms.secondary,
)
return getClosePositionActions(props.activeVault, exchangeRate, slippage)
return getClosePositionActions(props.activeVault, primaryToSecondaryRate, slippage)
}, [props.activeVault, getExchangeRate, slippage])
const { data: fee } = useEstimateFarmFee({