@@ -330,6 +330,7 @@ export class User {
330330 lastBaseAssetAmountPerLp : ZERO ,
331331 lastQuoteAssetAmountPerLp : ZERO ,
332332 perLpBase : 0 ,
333+ maxMarginRatio : 0 ,
333334 } ;
334335 }
335336
@@ -471,21 +472,27 @@ export class User {
471472 marketIndex ,
472473 freeCollateral ,
473474 worstCaseBaseAssetAmount ,
474- enterHighLeverageMode
475+ enterHighLeverageMode ,
476+ perpPosition
475477 ) ;
476478 }
477479
478480 getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount (
479481 marketIndex : number ,
480482 freeCollateral : BN ,
481483 baseAssetAmount : BN ,
482- enterHighLeverageMode = undefined
484+ enterHighLeverageMode = undefined ,
485+ perpPosition ?: PerpPosition
483486 ) : BN {
487+ const userCustomMargin = Math . max (
488+ perpPosition ?. maxMarginRatio ?? 0 ,
489+ this . getUserAccount ( ) . maxMarginRatio
490+ ) ;
484491 const marginRatio = calculateMarketMarginRatio (
485492 this . driftClient . getPerpMarketAccount ( marketIndex ) ,
486493 baseAssetAmount ,
487494 'Initial' ,
488- this . getUserAccount ( ) . maxMarginRatio ,
495+ userCustomMargin ,
489496 enterHighLeverageMode || this . isHighLeverageMode ( 'Initial' )
490497 ) ;
491498
@@ -2162,7 +2169,10 @@ export class User {
21622169 ) ;
21632170 }
21642171
2165- const userCustomMargin = this . getUserAccount ( ) . maxMarginRatio ;
2172+ const userCustomMargin = Math . max (
2173+ perpPosition . maxMarginRatio ,
2174+ this . getUserAccount ( ) . maxMarginRatio
2175+ ) ;
21662176 const marginRatio = calculateMarketMarginRatio (
21672177 market ,
21682178 baseAssetAmount . abs ( ) ,
@@ -2212,7 +2222,10 @@ export class User {
22122222
22132223 const proposedBaseAssetAmount = baseAssetAmount . add ( positionBaseSizeChange ) ;
22142224
2215- const userCustomMargin = this . getUserAccount ( ) . maxMarginRatio ;
2225+ const userCustomMargin = Math . max (
2226+ perpPosition . maxMarginRatio ,
2227+ this . getUserAccount ( ) . maxMarginRatio
2228+ ) ;
22162229
22172230 const marginRatio = calculateMarketMarginRatio (
22182231 market ,
@@ -3578,12 +3591,16 @@ export class User {
35783591 oraclePrice
35793592 ) ;
35803593
3594+ const userCustomMargin = Math . max (
3595+ perpPosition . maxMarginRatio ,
3596+ this . getUserAccount ( ) . maxMarginRatio
3597+ ) ;
35813598 const marginRatio = new BN (
35823599 calculateMarketMarginRatio (
35833600 perpMarket ,
35843601 worstCaseBaseAmount . abs ( ) ,
35853602 marginCategory ,
3586- this . getUserAccount ( ) . maxMarginRatio ,
3603+ userCustomMargin ,
35873604 this . isHighLeverageMode ( marginCategory )
35883605 )
35893606 ) ;
0 commit comments