Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
105 changes: 95 additions & 10 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1570,14 +1570,21 @@ export class DriftClient {
perpMarketIndex: number,
marginRatio: number,
subAccountId = 0,
txParams?: TxParams
txParams?: TxParams,
enterHighLeverageMode?: boolean
): Promise<TransactionSignature> {
const ix = await this.getUpdateUserPerpPositionCustomMarginRatioIx(
const ixs = [];
if (enterHighLeverageMode) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lowkeynicc I think just wanna call out that we will need to update the slider in the modal to always have the HLM max as the absolute max leverage available.

const enableIx = await this.getEnableHighLeverageModeIx(subAccountId);
ixs.push(enableIx);
}
const updateIx = await this.getUpdateUserPerpPositionCustomMarginRatioIx(
perpMarketIndex,
marginRatio,
subAccountId
);
const tx = await this.buildTransaction(ix, txParams ?? this.txParams);
ixs.push(updateIx);
const tx = await this.buildTransaction(ixs, txParams ?? this.txParams);
const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}
Expand Down Expand Up @@ -4071,7 +4078,8 @@ export class DriftClient {
bracketOrdersParams = new Array<OptionalOrderParams>(),
referrerInfo?: ReferrerInfo,
cancelExistingOrders?: boolean,
settlePnl?: boolean
settlePnl?: boolean,
positionMaxLev?: number
): Promise<{
cancelExistingOrdersTx?: Transaction | VersionedTransaction;
settlePnlTx?: Transaction | VersionedTransaction;
Expand All @@ -4087,7 +4095,10 @@ export class DriftClient {
const marketIndex = orderParams.marketIndex;
const orderId = userAccount.nextOrderId;

const ixPromisesForTxs: Record<TxKeys, Promise<TransactionInstruction>> = {
const ixPromisesForTxs: Record<
TxKeys,
Promise<TransactionInstruction | TransactionInstruction[]>
> = {
cancelExistingOrdersTx: undefined,
settlePnlTx: undefined,
fillTx: undefined,
Expand All @@ -4096,10 +4107,18 @@ export class DriftClient {

const txKeys = Object.keys(ixPromisesForTxs);

ixPromisesForTxs.marketOrderTx = this.getPlaceOrdersIx(
[orderParams, ...bracketOrdersParams],
userAccount.subAccountId
);
const marketOrderTxIxs = positionMaxLev
? this.getPlaceOrdersAndSetPositionMaxLevIx(
[orderParams, ...bracketOrdersParams],
positionMaxLev,
userAccount.subAccountId
)
: this.getPlaceOrdersIx(
[orderParams, ...bracketOrdersParams],
userAccount.subAccountId
);

ixPromisesForTxs.marketOrderTx = marketOrderTxIxs;

/* Cancel open orders in market if requested */
if (cancelExistingOrders && isVariant(orderParams.marketType, 'perp')) {
Expand Down Expand Up @@ -4140,7 +4159,10 @@ export class DriftClient {
const ixsMap = ixs.reduce((acc, ix, i) => {
acc[txKeys[i]] = ix;
return acc;
}, {}) as MappedRecord<typeof ixPromisesForTxs, TransactionInstruction>;
}, {}) as MappedRecord<
typeof ixPromisesForTxs,
TransactionInstruction | TransactionInstruction[]
>;

const txsMap = (await this.buildTransactionsMap(
ixsMap,
Expand Down Expand Up @@ -4724,6 +4746,69 @@ export class DriftClient {
});
}

public async getPlaceOrdersAndSetPositionMaxLevIx(
params: OptionalOrderParams[],
positionMaxLev: number,
subAccountId?: number
): Promise<TransactionInstruction[]> {
const user = await this.getUserAccountPublicKey(subAccountId);

const readablePerpMarketIndex: number[] = [];
const readableSpotMarketIndexes: number[] = [];
for (const param of params) {
if (!param.marketType) {
throw new Error('must set param.marketType');
}
if (isVariant(param.marketType, 'perp')) {
readablePerpMarketIndex.push(param.marketIndex);
} else {
readableSpotMarketIndexes.push(param.marketIndex);
}
}

const remainingAccounts = this.getRemainingAccounts({
userAccounts: [this.getUserAccount(subAccountId)],
readablePerpMarketIndex,
readableSpotMarketIndexes,
useMarketLastSlotCache: true,
});

for (const param of params) {
if (isUpdateHighLeverageMode(param.bitFlags)) {
remainingAccounts.push({
pubkey: getHighLeverageModeConfigPublicKey(this.program.programId),
isWritable: true,
isSigner: false,
});
}
}

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

const placeOrdersIxs = await this.program.instruction.placeOrders(
formattedParams,
{
accounts: {
state: await this.getStatePublicKey(),
user,
userStats: this.getUserStatsAccountPublicKey(),
authority: this.wallet.publicKey,
},
remainingAccounts,
}
);

// TODO: Handle multiple markets?
const setPositionMaxLevIxs =
await this.getUpdateUserPerpPositionCustomMarginRatioIx(
readablePerpMarketIndex[0],
1 / positionMaxLev,
subAccountId
);

return [placeOrdersIxs, setPositionMaxLevIxs];
}

public async fillPerpOrder(
userAccountPublicKey: PublicKey,
user: UserAccount,
Expand Down
2 changes: 2 additions & 0 deletions sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1247,6 +1247,7 @@ export type SignedMsgOrderParamsMessage = {
uuid: Uint8Array;
takeProfitOrderParams: SignedMsgTriggerOrderParams | null;
stopLossOrderParams: SignedMsgTriggerOrderParams | null;
maxMarginRatio: number | null;
};

export type SignedMsgOrderParamsDelegateMessage = {
Expand All @@ -1256,6 +1257,7 @@ export type SignedMsgOrderParamsDelegateMessage = {
takerPubkey: PublicKey;
takeProfitOrderParams: SignedMsgTriggerOrderParams | null;
stopLossOrderParams: SignedMsgTriggerOrderParams | null;
maxMarginRatio: number | null;
};

export type SignedMsgTriggerOrderParams = {
Expand Down
42 changes: 30 additions & 12 deletions sdk/src/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ export class User {
freeCollateral,
worstCaseBaseAssetAmount,
enterHighLeverageMode,
perpPosition
perpPosition.maxMarginRatio
);
}

Expand All @@ -482,17 +482,17 @@ export class User {
freeCollateral: BN,
baseAssetAmount: BN,
enterHighLeverageMode = undefined,
perpPosition?: PerpPosition
perpMarketMaxMarginRatio = undefined
): BN {
const userCustomMargin = Math.max(
perpPosition?.maxMarginRatio ?? 0,
const maxMarginRatio = Math.max(
perpMarketMaxMarginRatio,
this.getUserAccount().maxMarginRatio
);
const marginRatio = calculateMarketMarginRatio(
this.driftClient.getPerpMarketAccount(marketIndex),
baseAssetAmount,
'Initial',
userCustomMargin,
maxMarginRatio,
enterHighLeverageMode || this.isHighLeverageMode('Initial')
);

Expand Down Expand Up @@ -1247,7 +1247,10 @@ export class User {
}

if (marginCategory) {
const userCustomMargin = this.getUserAccount().maxMarginRatio;
const userCustomMargin = Math.max(
perpPosition.maxMarginRatio,
this.getUserAccount().maxMarginRatio
);
let marginRatio = new BN(
calculateMarketMarginRatio(
market,
Expand Down Expand Up @@ -2345,13 +2348,18 @@ export class User {
public getMarginUSDCRequiredForTrade(
targetMarketIndex: number,
baseSize: BN,
estEntryPrice?: BN
estEntryPrice?: BN,
perpMarketMaxMarginRatio?: number
): BN {
const maxMarginRatio = Math.max(
perpMarketMaxMarginRatio,
this.getUserAccount().maxMarginRatio
);
return calculateMarginUSDCRequiredForTrade(
this.driftClient,
targetMarketIndex,
baseSize,
this.getUserAccount().maxMarginRatio,
maxMarginRatio,
undefined,
estEntryPrice
);
Expand All @@ -2360,14 +2368,19 @@ export class User {
public getCollateralDepositRequiredForTrade(
targetMarketIndex: number,
baseSize: BN,
collateralIndex: number
collateralIndex: number,
perpMarketMaxMarginRatio?: number
): BN {
const maxMarginRatio = Math.max(
perpMarketMaxMarginRatio,
this.getUserAccount().maxMarginRatio
);
return calculateCollateralDepositRequiredForTrade(
this.driftClient,
targetMarketIndex,
baseSize,
collateralIndex,
this.getUserAccount().maxMarginRatio,
maxMarginRatio,
false // assume user cant be high leverage if they havent created user account ?
);
}
Expand Down Expand Up @@ -2451,8 +2464,12 @@ export class User {
const marginRequirement = this.getInitialMarginRequirement(
enterHighLeverageMode
);
const marginRatio = Math.max(
currentPosition.maxMarginRatio,
this.getUserAccount().maxMarginRatio
);
const marginFreedByClosing = perpLiabilityValue
.mul(new BN(market.marginRatioInitial))
.mul(new BN(marginRatio))
.div(MARGIN_PRECISION);
const marginRequirementAfterClosing =
marginRequirement.sub(marginFreedByClosing);
Expand All @@ -2468,7 +2485,8 @@ export class User {
this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(
targetMarketIndex,
freeCollateralAfterClose,
ZERO
ZERO,
currentPosition.maxMarginRatio
);
oppositeSideTradeSize = perpLiabilityValue;
tradeSize = buyingPowerAfterClose;
Expand Down