Skip to content

Commit 989a8a9

Browse files
committed
fix: bug with swift msg encoding + margin ratio
1 parent 51aae70 commit 989a8a9

File tree

2 files changed

+76
-37
lines changed

2 files changed

+76
-37
lines changed

sdk/src/driftClient.ts

Lines changed: 42 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4035,7 +4035,10 @@ export class DriftClient {
40354035
const marketIndex = orderParams.marketIndex;
40364036
const orderId = userAccount.nextOrderId;
40374037

4038-
const ixPromisesForTxs: Record<TxKeys, Promise<TransactionInstruction | TransactionInstruction[]>> = {
4038+
const ixPromisesForTxs: Record<
4039+
TxKeys,
4040+
Promise<TransactionInstruction | TransactionInstruction[]>
4041+
> = {
40394042
cancelExistingOrdersTx: undefined,
40404043
settlePnlTx: undefined,
40414044
fillTx: undefined,
@@ -4044,14 +4047,16 @@ export class DriftClient {
40444047

40454048
const txKeys = Object.keys(ixPromisesForTxs);
40464049

4047-
const marketOrderTxIxs = positionMaxLev ? this.getPlaceOrdersAndSetPositionMaxLevIx(
4048-
[orderParams, ...bracketOrdersParams],
4049-
positionMaxLev,
4050-
userAccount.subAccountId
4051-
) : this.getPlaceOrdersIx(
4052-
[orderParams, ...bracketOrdersParams],
4053-
userAccount.subAccountId
4054-
);
4050+
const marketOrderTxIxs = positionMaxLev
4051+
? this.getPlaceOrdersAndSetPositionMaxLevIx(
4052+
[orderParams, ...bracketOrdersParams],
4053+
positionMaxLev,
4054+
userAccount.subAccountId
4055+
)
4056+
: this.getPlaceOrdersIx(
4057+
[orderParams, ...bracketOrdersParams],
4058+
userAccount.subAccountId
4059+
);
40554060

40564061
ixPromisesForTxs.marketOrderTx = marketOrderTxIxs;
40574062

@@ -4094,7 +4099,10 @@ export class DriftClient {
40944099
const ixsMap = ixs.reduce((acc, ix, i) => {
40954100
acc[txKeys[i]] = ix;
40964101
return acc;
4097-
}, {}) as MappedRecord<typeof ixPromisesForTxs, TransactionInstruction | TransactionInstruction[]>;
4102+
}, {}) as MappedRecord<
4103+
typeof ixPromisesForTxs,
4104+
TransactionInstruction | TransactionInstruction[]
4105+
>;
40984106

40994107
const txsMap = (await this.buildTransactionsMap(
41004108
ixsMap,
@@ -4717,22 +4725,26 @@ export class DriftClient {
47174725

47184726
const formattedParams = params.map((item) => getOrderParams(item));
47194727

4720-
const placeOrdersIxs = await this.program.instruction.placeOrders(formattedParams, {
4721-
accounts: {
4722-
state: await this.getStatePublicKey(),
4723-
user,
4724-
userStats: this.getUserStatsAccountPublicKey(),
4725-
authority: this.wallet.publicKey,
4726-
},
4727-
remainingAccounts,
4728-
});
4728+
const placeOrdersIxs = await this.program.instruction.placeOrders(
4729+
formattedParams,
4730+
{
4731+
accounts: {
4732+
state: await this.getStatePublicKey(),
4733+
user,
4734+
userStats: this.getUserStatsAccountPublicKey(),
4735+
authority: this.wallet.publicKey,
4736+
},
4737+
remainingAccounts,
4738+
}
4739+
);
47294740

47304741
// TODO: Handle multiple markets?
4731-
const setPositionMaxLevIxs = await this.getUpdateUserPerpPositionCustomMarginRatioIx(
4732-
readablePerpMarketIndex[0],
4733-
1 / positionMaxLev,
4734-
subAccountId
4735-
);
4742+
const setPositionMaxLevIxs =
4743+
await this.getUpdateUserPerpPositionCustomMarginRatioIx(
4744+
readablePerpMarketIndex[0],
4745+
1 / positionMaxLev,
4746+
subAccountId
4747+
);
47364748

47374749
return [placeOrdersIxs, setPositionMaxLevIxs];
47384750
}
@@ -4893,8 +4905,9 @@ export class DriftClient {
48934905
subAccountId?: number
48944906
): Promise<TransactionSignature> {
48954907
const { txSig, slot } = await this.sendTransaction(
4896-
(await this.preparePlaceSpotOrderTx(orderParams, txParams, subAccountId))
4897-
.placeSpotOrderTx,
4908+
(
4909+
await this.preparePlaceSpotOrderTx(orderParams, txParams, subAccountId)
4910+
).placeSpotOrderTx,
48984911
[],
48994912
this.opts,
49004913
false
@@ -6558,6 +6571,9 @@ export class DriftClient {
65586571
| SignedMsgOrderParamsDelegateMessage,
65596572
delegateSigner?: boolean
65606573
): Buffer {
6574+
if (orderParamsMessage.maxMarginRatio === undefined) {
6575+
orderParamsMessage.maxMarginRatio = null;
6576+
}
65616577
const anchorIxName = delegateSigner
65626578
? 'global' + ':' + 'SignedMsgOrderParamsDelegateMessage'
65636579
: 'global' + ':' + 'SignedMsgOrderParamsMessage';

sdk/src/user.ts

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ export class User {
473473
freeCollateral,
474474
worstCaseBaseAssetAmount,
475475
enterHighLeverageMode,
476-
perpPosition
476+
perpPosition.maxMarginRatio
477477
);
478478
}
479479

@@ -482,13 +482,17 @@ export class User {
482482
freeCollateral: BN,
483483
baseAssetAmount: BN,
484484
enterHighLeverageMode = undefined,
485-
perpPosition?: PerpPosition
485+
perpMarketMaxMarginRatio = undefined
486486
): BN {
487+
const maxMarginRatio = Math.max(
488+
perpMarketMaxMarginRatio,
489+
this.getUserAccount().maxMarginRatio
490+
);
487491
const marginRatio = calculateMarketMarginRatio(
488492
this.driftClient.getPerpMarketAccount(marketIndex),
489493
baseAssetAmount,
490494
'Initial',
491-
this.getUserAccount().maxMarginRatio,
495+
maxMarginRatio,
492496
enterHighLeverageMode || this.isHighLeverageMode('Initial')
493497
);
494498

@@ -1023,6 +1027,7 @@ export class User {
10231027

10241028
if (marketIndex === undefined || marketIndex === QUOTE_SPOT_MARKET_INDEX) {
10251029
if (netQuoteValue.gt(ZERO)) {
1030+
10261031
totalAssetValue = totalAssetValue.add(netQuoteValue);
10271032
} else {
10281033
totalLiabilityValue = totalLiabilityValue.add(netQuoteValue.abs());
@@ -1243,7 +1248,10 @@ export class User {
12431248
}
12441249

12451250
if (marginCategory) {
1246-
const userCustomMargin = this.getUserAccount().maxMarginRatio;
1251+
const userCustomMargin = Math.max(
1252+
perpPosition.maxMarginRatio,
1253+
this.getUserAccount().maxMarginRatio
1254+
);
12471255
let marginRatio = new BN(
12481256
calculateMarketMarginRatio(
12491257
market,
@@ -2165,7 +2173,10 @@ export class User {
21652173
);
21662174
}
21672175

2168-
const userCustomMargin = this.getUserAccount().maxMarginRatio;
2176+
const userCustomMargin = Math.max(
2177+
perpPosition.maxMarginRatio,
2178+
this.getUserAccount().maxMarginRatio
2179+
);
21692180
const marginRatio = calculateMarketMarginRatio(
21702181
market,
21712182
baseAssetAmount.abs(),
@@ -2338,13 +2349,18 @@ export class User {
23382349
public getMarginUSDCRequiredForTrade(
23392350
targetMarketIndex: number,
23402351
baseSize: BN,
2341-
estEntryPrice?: BN
2352+
estEntryPrice?: BN,
2353+
perpMarketMaxMarginRatio?: number
23422354
): BN {
2355+
const maxMarginRatio = Math.max(
2356+
perpMarketMaxMarginRatio,
2357+
this.getUserAccount().maxMarginRatio
2358+
);
23432359
return calculateMarginUSDCRequiredForTrade(
23442360
this.driftClient,
23452361
targetMarketIndex,
23462362
baseSize,
2347-
this.getUserAccount().maxMarginRatio,
2363+
maxMarginRatio,
23482364
undefined,
23492365
estEntryPrice
23502366
);
@@ -2353,14 +2369,19 @@ export class User {
23532369
public getCollateralDepositRequiredForTrade(
23542370
targetMarketIndex: number,
23552371
baseSize: BN,
2356-
collateralIndex: number
2372+
collateralIndex: number,
2373+
perpMarketMaxMarginRatio?: number
23572374
): BN {
2375+
const maxMarginRatio = Math.max(
2376+
perpMarketMaxMarginRatio,
2377+
this.getUserAccount().maxMarginRatio
2378+
);
23582379
return calculateCollateralDepositRequiredForTrade(
23592380
this.driftClient,
23602381
targetMarketIndex,
23612382
baseSize,
23622383
collateralIndex,
2363-
this.getUserAccount().maxMarginRatio,
2384+
maxMarginRatio,
23642385
false // assume user cant be high leverage if they havent created user account ?
23652386
);
23662387
}
@@ -2444,8 +2465,9 @@ export class User {
24442465
const marginRequirement = this.getInitialMarginRequirement(
24452466
enterHighLeverageMode
24462467
);
2468+
const marginRatio = Math.max(currentPosition.maxMarginRatio, this.getUserAccount().maxMarginRatio);
24472469
const marginFreedByClosing = perpLiabilityValue
2448-
.mul(new BN(market.marginRatioInitial))
2470+
.mul(new BN(marginRatio))
24492471
.div(MARGIN_PRECISION);
24502472
const marginRequirementAfterClosing =
24512473
marginRequirement.sub(marginFreedByClosing);
@@ -2461,7 +2483,8 @@ export class User {
24612483
this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(
24622484
targetMarketIndex,
24632485
freeCollateralAfterClose,
2464-
ZERO
2486+
ZERO,
2487+
currentPosition.maxMarginRatio
24652488
);
24662489
oppositeSideTradeSize = perpLiabilityValue;
24672490
tradeSize = buyingPowerAfterClose;

0 commit comments

Comments
 (0)