1
+ import BigNumber from 'bignumber.js'
1
2
import { Action , ActionAmount } from 'types/generated/mars-credit-manager/MarsCreditManager.types'
2
3
3
4
export const getClosePositionActions = (
4
5
vault : ActiveVault ,
5
- exchangeRate : number ,
6
+ primaryToSecondaryRate : number ,
6
7
slippage : number ,
7
8
) : Action [ ] => {
8
9
const swapMessage : Action [ ] = [ ]
@@ -12,20 +13,33 @@ export const getClosePositionActions = (
12
13
Math . max ( vault . position . amounts . borrowedPrimary , vault . position . amounts . borrowedSecondary ) *
13
14
1.001 ,
14
15
)
15
- const secondaryAmount = vault . position . amounts . lp . secondary
16
+ const borrowType =
17
+ vault . position . amounts . borrowedPrimary > vault . position . amounts . borrowedSecondary
18
+ ? 'primary'
19
+ : 'secondary'
20
+
21
+ const availableAmountForRepay = vault . position . amounts . lp [ borrowType ]
22
+
23
+ if ( availableAmountForRepay < borrowAmount ) {
24
+ const swapTargetAmount = borrowAmount - availableAmountForRepay
25
+ const exchangeRate =
26
+ borrowType === 'secondary'
27
+ ? new BigNumber ( 1 ) . div ( primaryToSecondaryRate )
28
+ : new BigNumber ( primaryToSecondaryRate )
29
+ const swapAmount = Math . max (
30
+ exchangeRate . times ( swapTargetAmount ) . integerValue ( BigNumber . ROUND_CEIL ) . toNumber ( ) ,
31
+ 10 ,
32
+ )
16
33
17
- if ( secondaryAmount < borrowAmount ) {
18
- const swapTargetAmount = borrowAmount - secondaryAmount
19
- const swapAmount = Math . max ( Math . ceil ( swapTargetAmount / exchangeRate ) , 10 )
20
34
swapMessage . push ( {
21
35
swap_exact_in : {
22
36
coin_in : {
23
37
amount : {
24
38
exact : swapAmount . toString ( ) ,
25
39
} ,
26
- denom : vault . denoms . primary ,
40
+ denom : borrowType === 'secondary' ? vault . denoms . primary : vault . denoms . secondary ,
27
41
} ,
28
- denom_out : vault . denoms . secondary ,
42
+ denom_out : vault . denoms [ borrowType ] ,
29
43
slippage : slippage . toString ( ) ,
30
44
} ,
31
45
} )
0 commit comments