@drift-labs/common 1.0.23 → 1.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -68,7 +68,7 @@ export declare const COMMON_UI_UTILS: {
68
68
  notionalSizeAtEntry: BigNum;
69
69
  notionalSizeAtExit: BigNum;
70
70
  };
71
- calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, }: {
71
+ calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, marginType, }: {
72
72
  estEntryPrice: BN;
73
73
  orderType: import("src/types").UIOrderType;
74
74
  perpMarketIndex: number;
@@ -81,6 +81,7 @@ export declare const COMMON_UI_UTILS: {
81
81
  precision?: number;
82
82
  isEnteringHighLeverageMode?: boolean;
83
83
  capLiqPrice?: boolean;
84
+ marginType?: "Cross" | "Isolated";
84
85
  }) => number;
85
86
  checkIsMarketOrderType: (orderType: import("src/types").UIOrderType) => boolean;
86
87
  convertLeverageToMarginRatio: (leverage: number) => number;
@@ -32,7 +32,7 @@ export declare const TRADING_UTILS: {
32
32
  notionalSizeAtEntry: BigNum;
33
33
  notionalSizeAtExit: BigNum;
34
34
  };
35
- calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, }: {
35
+ calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, marginType, }: {
36
36
  estEntryPrice: BN;
37
37
  orderType: UIOrderType;
38
38
  perpMarketIndex: number;
@@ -45,6 +45,7 @@ export declare const TRADING_UTILS: {
45
45
  precision?: number;
46
46
  isEnteringHighLeverageMode?: boolean;
47
47
  capLiqPrice?: boolean;
48
+ marginType?: 'Cross' | 'Isolated';
48
49
  }) => number;
49
50
  checkIsMarketOrderType: (orderType: UIOrderType) => boolean;
50
51
  convertLeverageToMarginRatio: (leverage: number) => number | undefined;
@@ -92,7 +92,7 @@ const checkIsMarketOrderType = (orderType) => {
92
92
  * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.
93
93
  * If the order type is limit order, a limit price must be provided.
94
94
  */
95
- const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision = 2, isEnteringHighLeverageMode, capLiqPrice, }) => {
95
+ const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision = 2, isEnteringHighLeverageMode, capLiqPrice, marginType, }) => {
96
96
  var _a, _b;
97
97
  const ALLOWED_ORDER_TYPES = [
98
98
  'limit',
@@ -120,7 +120,7 @@ const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, per
120
120
  ? limitPrice
121
121
  : estEntryPrice;
122
122
  const liqPriceBn = userClient.liquidationPrice(perpMarketIndex, signedBaseSize, priceToUse, undefined, undefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation
123
- offsetCollateral, isEnteringHighLeverageMode);
123
+ offsetCollateral, isEnteringHighLeverageMode, marginType === 'Isolated' ? 'Isolated' : undefined);
124
124
  if (liqPriceBn.isNeg()) {
125
125
  // means no liquidation price
126
126
  return 0;
@@ -1 +1 @@
1
- {"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/common-ui-utils/trading.ts"],"names":[],"mappings":";;;AAAA,yCAiByB;AAGzB,MAAM,2BAA2B,GAAG,CACn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C,qBAAqB,CAAC;YAC/D,cAAc,EAAE,SAAS;YACzB,YAAY;SACZ,CAAC,CAAC,aAAa,CAAC;QAEjB,oEAAoE;QACpE,MAAM,gBAAgB,GAAG;YACxB,GAAG,YAAY;YACf,cAAc,EAAE,cAAc;SAC9B,CAAC;QAEF,0DAA0D;QAC1D,MAAM,wBAAwB,GAAG,IAAI,CAAC,qBAAqB,CAAC;YAC3D,cAAc,EAAE,SAAS;YACzB,YAAY,EAAE,gBAAgB;SAC9B,CAAC,CAAC,aAAa,CAAC;QAEjB,MAAM,8BAA8B,GAAG,wBAAwB,CAAC,GAAG,CAClE,4BAA4B,CAC5B,CAAC;QAEF,MAAM,cAAc,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAEhD,wDAAwD;QACxD,OAAO,8BAA8B,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QACzD,OAAO,IAAI,CAAC,CAAC,mCAAmC;IACjD,CAAC;AACF,CAAC,CAAC;AAEW,QAAA,aAAa,GAAG;IAC5B,2BAA2B;IAC3B,wBAAwB;IACxB,uCAAuC;IACvC,sBAAsB;IACtB,4BAA4B;IAC5B,4BAA4B;IAC5B,iBAAiB;IACjB,yBAAyB;IACzB,iBAAiB;IACjB,yBAAyB;IACzB,qBAAqB,EAArB,6BAAqB;IACrB,wBAAwB;IACxB,sBAAsB;CACtB,CAAC","sourcesContent":["import {\n\tAMM_RESERVE_PRECISION,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMARGIN_PRECISION,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketAccount,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tconst quoteEntryAmountNum = BigNum.from(\n\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\tQUOTE_PRECISION_EXP\n\t\t).toNum();\n\n\t\tif (leverage <= 0 || quoteEntryAmountNum <= 0) {\n\t\t\tmarginUsedNum = 0;\n\t\t} else {\n\t\t\tmarginUsedNum = quoteEntryAmountNum / leverage;\n\t\t}\n\t}\n\n\tif (marginUsedNum <= 0) {\n\t\treturn 0;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\treturn Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n};\n\n/**\n * Calculate the margin used for a specific perp position\n * Returns the minimum of user's total collateral or the position's weighted value\n */\nconst getMarginUsedForPosition = (\n\tuser: User,\n\tmarketIndex: number,\n\tincludeOpenOrders = true\n): BN | undefined => {\n\tconst perpPosition = user.getPerpPosition(marketIndex);\n\tif (!perpPosition) return undefined;\n\n\tconst hc = user.getPerpPositionHealth({\n\t\tmarginCategory: 'Initial',\n\t\tperpPosition,\n\t\tincludeOpenOrders,\n\t});\n\tconst userCollateral = user.getTotalCollateral();\n\treturn userCollateral.lt(hc.weightedValue)\n\t\t? userCollateral\n\t\t: hc.weightedValue;\n};\n\n/**\n * Validate if a leverage change would exceed the user's free collateral\n * Returns true if the change is valid (doesn't exceed free collateral), false otherwise\n */\nconst validateLeverageChange = ({\n\tuser,\n\tmarketIndex,\n\tnewLeverage,\n}: {\n\tuser: User;\n\tmarketIndex: number;\n\tnewLeverage: number;\n}): boolean => {\n\ttry {\n\t\t// Convert leverage to margin ratio\n\t\tconst newMarginRatio = convertLeverageToMarginRatio(newLeverage);\n\t\tif (!newMarginRatio) return true;\n\n\t\t// Get the perp position from the user\n\t\tconst perpPosition = user.getPerpPosition(marketIndex);\n\t\tif (!perpPosition) return true;\n\n\t\t// Get current position weighted value\n\t\tconst currentPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition,\n\t\t}).weightedValue;\n\n\t\t// Create a modified version of the position with new maxMarginRatio\n\t\tconst modifiedPosition = {\n\t\t\t...perpPosition,\n\t\t\tmaxMarginRatio: newMarginRatio,\n\t\t};\n\n\t\t// Calculate new weighted value with the modified position\n\t\tconst newPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition: modifiedPosition,\n\t\t}).weightedValue;\n\n\t\tconst perpPositionWeightedValueDelta = newPositionWeightedValue.sub(\n\t\t\tcurrentPositionWeightedValue\n\t\t);\n\n\t\tconst freeCollateral = user.getFreeCollateral();\n\n\t\t// Check if weighted value delta exceeds free collateral\n\t\treturn perpPositionWeightedValueDelta.lte(freeCollateral);\n\t} catch (error) {\n\t\tconsole.warn('Error validating leverage change:', error);\n\t\treturn true; // Allow change if validation fails\n\t}\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n\tgetMarginUsed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\tBN,\n\tBigNum,\n\tDriftClient,\n\tMARGIN_PRECISION,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketAccount,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tconst quoteEntryAmountNum = BigNum.from(\n\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\tQUOTE_PRECISION_EXP\n\t\t).toNum();\n\n\t\tif (leverage <= 0 || quoteEntryAmountNum <= 0) {\n\t\t\tmarginUsedNum = 0;\n\t\t} else {\n\t\t\tmarginUsedNum = quoteEntryAmountNum / leverage;\n\t\t}\n\t}\n\n\tif (marginUsedNum <= 0) {\n\t\treturn 0;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n\tmarginType,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n\tmarginType?: 'Cross' | 'Isolated';\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode,\n\t\tmarginType === 'Isolated' ? 'Isolated' : undefined\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\treturn Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n};\n\n/**\n * Calculate the margin used for a specific perp position\n * Returns the minimum of user's total collateral or the position's weighted value\n */\nconst getMarginUsedForPosition = (\n\tuser: User,\n\tmarketIndex: number,\n\tincludeOpenOrders = true\n): BN | undefined => {\n\tconst perpPosition = user.getPerpPosition(marketIndex);\n\tif (!perpPosition) return undefined;\n\n\tconst hc = user.getPerpPositionHealth({\n\t\tmarginCategory: 'Initial',\n\t\tperpPosition,\n\t\tincludeOpenOrders,\n\t});\n\tconst userCollateral = user.getTotalCollateral();\n\treturn userCollateral.lt(hc.weightedValue)\n\t\t? userCollateral\n\t\t: hc.weightedValue;\n};\n\n/**\n * Validate if a leverage change would exceed the user's free collateral\n * Returns true if the change is valid (doesn't exceed free collateral), false otherwise\n */\nconst validateLeverageChange = ({\n\tuser,\n\tmarketIndex,\n\tnewLeverage,\n}: {\n\tuser: User;\n\tmarketIndex: number;\n\tnewLeverage: number;\n}): boolean => {\n\ttry {\n\t\t// Convert leverage to margin ratio\n\t\tconst newMarginRatio = convertLeverageToMarginRatio(newLeverage);\n\t\tif (!newMarginRatio) return true;\n\n\t\t// Get the perp position from the user\n\t\tconst perpPosition = user.getPerpPosition(marketIndex);\n\t\tif (!perpPosition) return true;\n\n\t\t// Get current position weighted value\n\t\tconst currentPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition,\n\t\t}).weightedValue;\n\n\t\t// Create a modified version of the position with new maxMarginRatio\n\t\tconst modifiedPosition = {\n\t\t\t...perpPosition,\n\t\t\tmaxMarginRatio: newMarginRatio,\n\t\t};\n\n\t\t// Calculate new weighted value with the modified position\n\t\tconst newPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition: modifiedPosition,\n\t\t}).weightedValue;\n\n\t\tconst perpPositionWeightedValueDelta = newPositionWeightedValue.sub(\n\t\t\tcurrentPositionWeightedValue\n\t\t);\n\n\t\tconst freeCollateral = user.getFreeCollateral();\n\n\t\t// Check if weighted value delta exceeds free collateral\n\t\treturn perpPositionWeightedValueDelta.lte(freeCollateral);\n\t} catch (error) {\n\t\tconsole.warn('Error validating leverage change:', error);\n\t\treturn true; // Allow change if validation fails\n\t}\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n\tgetMarginUsedForPosition,\n\tvalidateLeverageChange,\n};\n"]}
@@ -1,6 +1,30 @@
1
1
  import { BN, DriftClient, User, PositionDirection } from '@drift-labs/sdk';
2
2
  import { PublicKey, TransactionInstruction } from '@solana/web3.js';
3
- export declare const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 20;
3
+ export declare const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;
4
+ export interface IsolatedMarginShortfall {
5
+ marketIndex: number;
6
+ shortfall: BN;
7
+ }
8
+ /**
9
+ * Computes the initial margin shortfall for all isolated perp positions.
10
+ * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).
11
+ * Only includes positions that are under initial margin (shortfall > 0).
12
+ */
13
+ export declare function getIsolatedMarginShortfalls(user: User): Map<number, BN>;
14
+ /**
15
+ * Computes the initial margin shortfall for a single isolated perp position.
16
+ * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.
17
+ */
18
+ export declare function getIsolatedMarginShortfall(user: User, marketIndex: number): BN;
19
+ /**
20
+ * Returns all isolated margin shortfalls as an array, excluding a specific market index.
21
+ * Useful for getting shortfalls for "other" isolated positions.
22
+ */
23
+ export declare function getOtherIsolatedMarginShortfalls(user: User, excludeMarketIndex?: number): IsolatedMarginShortfall[];
24
+ /**
25
+ * Computes the total of all isolated margin shortfalls.
26
+ */
27
+ export declare function getTotalIsolatedMarginShortfall(user: User, excludeMarketIndex?: number): BN;
4
28
  export interface ComputeIsolatedPositionDepositParams {
5
29
  driftClient: DriftClient;
6
30
  user: User;
@@ -45,10 +69,15 @@ export interface ComputeIsolatedPositionDepositParams {
45
69
  * 200 -> 0.50%
46
70
  */
47
71
  bufferDenominator?: number;
72
+ /**
73
+ * If true, the current market's initial margin shortfall (if any)
74
+ * will be added to the deposit amount.
75
+ */
76
+ includeExistingShortfall?: boolean;
48
77
  }
49
78
  /**
50
79
  * Computes the isolated position deposit required for opening an isolated perp position.
51
80
  * Returns a BN in QUOTE_PRECISION (USDC).
52
81
  */
53
- export declare function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferDenominator, }: ComputeIsolatedPositionDepositParams): BN | null;
82
+ export declare function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferDenominator, includeExistingShortfall, }: ComputeIsolatedPositionDepositParams): BN | null;
54
83
  export declare function getIsolatedPositionDepositIxIfNeeded(driftClient: DriftClient, user: User, marketIndex: number, isolatedPositionDeposit?: BN, signingAuthority?: PublicKey): Promise<TransactionInstruction | undefined>;
@@ -1,13 +1,68 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getIsolatedPositionDepositIxIfNeeded = exports.computeIsolatedPositionDepositForTrade = exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = void 0;
3
+ exports.getIsolatedPositionDepositIxIfNeeded = exports.computeIsolatedPositionDepositForTrade = exports.getTotalIsolatedMarginShortfall = exports.getOtherIsolatedMarginShortfalls = exports.getIsolatedMarginShortfall = exports.getIsolatedMarginShortfalls = exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
- exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 20;
5
+ exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;
6
+ /**
7
+ * Computes the initial margin shortfall for all isolated perp positions.
8
+ * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).
9
+ * Only includes positions that are under initial margin (shortfall > 0).
10
+ */
11
+ function getIsolatedMarginShortfalls(user) {
12
+ const shortfalls = new Map();
13
+ const marginCalc = user.getMarginCalculation('Initial');
14
+ for (const [marketIndex, isolatedCalc,] of marginCalc.isolatedMarginCalculations) {
15
+ const shortfall = isolatedCalc.marginShortage();
16
+ if (shortfall.gt(sdk_1.ZERO)) {
17
+ shortfalls.set(marketIndex, shortfall);
18
+ }
19
+ }
20
+ return shortfalls;
21
+ }
22
+ exports.getIsolatedMarginShortfalls = getIsolatedMarginShortfalls;
23
+ /**
24
+ * Computes the initial margin shortfall for a single isolated perp position.
25
+ * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.
26
+ */
27
+ function getIsolatedMarginShortfall(user, marketIndex) {
28
+ const marginCalc = user.getMarginCalculation('Initial');
29
+ const isolatedCalc = marginCalc.isolatedMarginCalculations.get(marketIndex);
30
+ if (!isolatedCalc) {
31
+ return sdk_1.ZERO;
32
+ }
33
+ return isolatedCalc.marginShortage();
34
+ }
35
+ exports.getIsolatedMarginShortfall = getIsolatedMarginShortfall;
36
+ /**
37
+ * Returns all isolated margin shortfalls as an array, excluding a specific market index.
38
+ * Useful for getting shortfalls for "other" isolated positions.
39
+ */
40
+ function getOtherIsolatedMarginShortfalls(user, excludeMarketIndex) {
41
+ const shortfalls = getIsolatedMarginShortfalls(user);
42
+ const result = [];
43
+ for (const [marketIndex, shortfall] of shortfalls) {
44
+ if (excludeMarketIndex !== undefined &&
45
+ marketIndex === excludeMarketIndex) {
46
+ continue;
47
+ }
48
+ result.push({ marketIndex, shortfall });
49
+ }
50
+ return result;
51
+ }
52
+ exports.getOtherIsolatedMarginShortfalls = getOtherIsolatedMarginShortfalls;
53
+ /**
54
+ * Computes the total of all isolated margin shortfalls.
55
+ */
56
+ function getTotalIsolatedMarginShortfall(user, excludeMarketIndex) {
57
+ const shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);
58
+ return shortfalls.reduce((acc, s) => acc.add(s.shortfall), sdk_1.ZERO);
59
+ }
60
+ exports.getTotalIsolatedMarginShortfall = getTotalIsolatedMarginShortfall;
6
61
  /**
7
62
  * Computes the isolated position deposit required for opening an isolated perp position.
8
63
  * Returns a BN in QUOTE_PRECISION (USDC).
9
64
  */
10
- function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferDenominator, }) {
65
+ function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferDenominator, includeExistingShortfall, }) {
11
66
  var _a;
12
67
  // Only require isolated deposit if the order will increase the position (when direction is provided)
13
68
  if (direction !== undefined) {
@@ -28,7 +83,17 @@ function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex
28
83
  const hasOpenHighLeverageSpots = numOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;
29
84
  const enteringHighLeverageMode = userIsInHighLeverageMode || hasOpenHighLeverageSpots;
30
85
  const marginRequired = (0, sdk_1.calculateMarginUSDCRequiredForTrade)(driftClient, marketIndex, baseAssetAmount, marginRatio, enteringHighLeverageMode, entryPrice);
31
- return marginRequired.add(marginRequired.div(new sdk_1.BN(bufferDenominator !== null && bufferDenominator !== void 0 ? bufferDenominator : exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS))); // buffer in basis points
86
+ let depositAmount = marginRequired.add(marginRequired.div(new sdk_1.BN(bufferDenominator !== null && bufferDenominator !== void 0 ? bufferDenominator : exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS))); // buffer in basis points
87
+ // Add existing shortfall for this market if requested
88
+ if (includeExistingShortfall) {
89
+ const existingShortfall = getIsolatedMarginShortfall(user, marketIndex);
90
+ if (existingShortfall.gt(sdk_1.ZERO)) {
91
+ // Add shortfall with a 5% buffer on top (same as new margin)
92
+ const shortfallWithBuffer = existingShortfall.add(existingShortfall.div(new sdk_1.BN(bufferDenominator !== null && bufferDenominator !== void 0 ? bufferDenominator : exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)));
93
+ depositAmount = depositAmount.add(shortfallWithBuffer);
94
+ }
95
+ }
96
+ return depositAmount;
32
97
  }
33
98
  exports.computeIsolatedPositionDepositForTrade = computeIsolatedPositionDepositForTrade;
34
99
  async function getIsolatedPositionDepositIxIfNeeded(driftClient, user, marketIndex, isolatedPositionDeposit, signingAuthority) {
@@ -1 +1 @@
1
- {"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.ts"],"names":[],"mappings":";;;AAAA,yCASyB;AAGZ,QAAA,oCAAoC,GAAG,EAAE,CAAC;AAgDvD;;;GAGG;AACH,SAAgB,sCAAsC,CAAC,EACtD,WAAW,EACX,IAAI,EACJ,WAAW,EACX,eAAe,EACf,SAAS,EACT,WAAW,EACX,UAAU,EACV,0BAA0B,EAC1B,iBAAiB,GACqB;;IACtC,qGAAqG;IACrG,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC7B,MAAM,gBAAgB,GAAwB;YAC7C,WAAW;YACX,UAAU,EAAE,gBAAU,CAAC,IAAI;YAC3B,SAAS,EAAE,eAAS,CAAC,MAAM;YAC3B,SAAS;YACT,eAAe;SACf,CAAC;QACF,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,CAAC;QACxD,MAAM,YAAY,GAAG,WAAW,CAAC,yBAAyB,CACzD,gBAAgB,EAChB,YAAY,CACZ,CAAC;QACF,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,MAAM,wBAAwB,GAAG,MAAA,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,mCAAI,KAAK,CAAC;IAC7E,MAAM,wBAAwB,GAC7B,0BAA0B,KAAK,SAAS,IAAI,0BAA0B,GAAG,CAAC,CAAC;IAC5E,MAAM,wBAAwB,GAC7B,wBAAwB,IAAI,wBAAwB,CAAC;IAEtD,MAAM,cAAc,GAAG,IAAA,yCAAmC,EACzD,WAAW,EACX,WAAW,EACX,eAAe,EACf,WAAW,EACX,wBAAwB,EACxB,UAAU,CACV,CAAC;IAEF,OAAO,cAAc,CAAC,GAAG,CACxB,cAAc,CAAC,GAAG,CACjB,IAAI,QAAE,CAAC,iBAAiB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,4CAAoC,CAAC,CACjE,CACD,CAAC,CAAC,yBAAyB;AAC7B,CAAC;AAlDD,wFAkDC;AAEM,KAAK,UAAU,oCAAoC,CACzD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,uBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,uBAAuB,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,WAAW,CAAC,wCAAwC,CAC1D,uBAAuB,EACvB,WAAW,EACX,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,EAClC,SAAS,EAAE,iBAAiB;IAC5B,gBAAgB,CAChB,CAAC;AACH,CAAC;AArBD,oFAqBC","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tUser,\n\tcalculateMarginUSDCRequiredForTrade,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tMarketType,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\n\nexport const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 20;\n\nexport interface ComputeIsolatedPositionDepositParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\t/**\n\t * Optional direction of the order.\n\t * If provided, we will check if the order will increase the position.\n\t * If the order will not increase the position, we will return 0.\n\t */\n\tdirection?: PositionDirection;\n\t/**\n\t * Margin ratio to use for the position (e.g. 2000 for 5x leverage).\n\t */\n\tmarginRatio: number;\n\t/**\n\t * Optional estimated entry price to use for the margin calculation.\n\t */\n\tentryPrice?: BN;\n\t/**\n\t * Number of open high leverage spots available to the user (if any).\n\t * If greater than 0, we will consider the trade as entering high leverage mode.\n\t */\n\tnumOfOpenHighLeverageSpots?: number;\n\t/**\n\t * Optional buffer denominator for the isolated position deposit.\n\t * \n\t * Smaller numbers mean a bigger buffer.\n\t * \n\t * bufferDenominator -> Buffer %\n\t * \n\t * 15 -> 6.67%\n\t * \n\t * 20 (default) -> 5.00%\n\t * \n\t * 50 -> 2.00%\n\t * \n\t * 100 -> 1.00%\n\t * \n\t * 180 -> 0.56%\n\t * \n\t * 200 -> 0.50%\n\t */\n\tbufferDenominator?: number;\n}\n\n/**\n * Computes the isolated position deposit required for opening an isolated perp position.\n * Returns a BN in QUOTE_PRECISION (USDC).\n */\nexport function computeIsolatedPositionDepositForTrade({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tbaseAssetAmount,\n\tdirection,\n\tmarginRatio,\n\tentryPrice,\n\tnumOfOpenHighLeverageSpots,\n\tbufferDenominator,\n}: ComputeIsolatedPositionDepositParams): BN | null {\n\t// Only require isolated deposit if the order will increase the position (when direction is provided)\n\tif (direction !== undefined) {\n\t\tconst maybeOrderParams: OptionalOrderParams = {\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\torderType: OrderType.MARKET,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount,\n\t\t};\n\t\tconst subAccountId = user.getUserAccount().subAccountId;\n\t\tconst isIncreasing = driftClient.isOrderIncreasingPosition(\n\t\t\tmaybeOrderParams,\n\t\t\tsubAccountId\n\t\t);\n\t\tif (!isIncreasing) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tconst userIsInHighLeverageMode = user.isHighLeverageMode('Initial') ?? false;\n\tconst hasOpenHighLeverageSpots =\n\t\tnumOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;\n\tconst enteringHighLeverageMode =\n\t\tuserIsInHighLeverageMode || hasOpenHighLeverageSpots;\n\n\tconst marginRequired = calculateMarginUSDCRequiredForTrade(\n\t\tdriftClient,\n\t\tmarketIndex,\n\t\tbaseAssetAmount,\n\t\tmarginRatio,\n\t\tenteringHighLeverageMode,\n\t\tentryPrice\n\t);\n\n\treturn marginRequired.add(\n\t\tmarginRequired.div(\n\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t)\n\t); // buffer in basis points\n}\n\nexport async function getIsolatedPositionDepositIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tisolatedPositionDeposit?: BN,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!isolatedPositionDeposit) {\n\t\treturn undefined;\n\t}\n\tif (isolatedPositionDeposit.isZero()) {\n\t\treturn undefined;\n\t}\n\n\treturn driftClient.getTransferIsolatedPerpPositionDepositIx(\n\t\tisolatedPositionDeposit,\n\t\tmarketIndex,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined, // noAmountBuffer\n\t\tsigningAuthority\n\t);\n}\n"]}
1
+ {"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAGZ,QAAA,oCAAoC,GAAG,EAAE,CAAC;AAOvD;;;;GAIG;AACH,SAAgB,2BAA2B,CAAC,IAAU;IACrD,MAAM,UAAU,GAAG,IAAI,GAAG,EAAc,CAAC;IAEzC,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAExD,KAAK,MAAM,CACV,W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iB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,4CAAoC,CAAC,CACjE,CACD,CAAC,CAAC,yBAAyB;IAE5B,sDAAsD;IACtD,IAAI,wBAAwB,EAAE,CAAC;QAC9B,MAAM,iBAAiB,GAAG,0BAA0B,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACxE,IAAI,iBAAiB,CAAC,EAAE,CAAC,UAAI,CAAC,EAAE,CAAC;YAChC,6DAA6D;YAC7D,MAAM,mBAAmB,GAAG,iBAAiB,CAAC,GAAG,CAChD,iBAAiB,CAAC,GAAG,CACpB,IAAI,QAAE,CAAC,iBAAiB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,4CAAoC,CAAC,CACjE,CACD,CAAC;YACF,aAAa,GAAG,aAAa,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACxD,CAAC;IACF,CAAC;IAED,OAAO,aAAa,CAAC;AACtB,CAAC;AAnED,wFAmEC;AAEM,KAAK,UAAU,oCAAoC,CACzD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,uBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,uBAAuB,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,WAAW,CAAC,wCAAwC,CAC1D,uBAAuB,EACvB,WAAW,EACX,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,EAClC,SAAS,EAAE,iBAAiB;IAC5B,gBAAgB,CAChB,CAAC;AACH,CAAC;AArBD,oFAqBC","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tUser,\n\tcalculateMarginUSDCRequiredForTrade,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tMarketType,\n\tOrderType,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\n\nexport const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;\n\nexport interface IsolatedMarginShortfall {\n\tmarketIndex: number;\n\tshortfall: BN;\n}\n\n/**\n * Computes the initial margin shortfall for all isolated perp positions.\n * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).\n * Only includes positions that are under initial margin (shortfall > 0).\n */\nexport function getIsolatedMarginShortfalls(user: User): Map<number, BN> {\n\tconst shortfalls = new Map<number, BN>();\n\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\n\tfor (const [\n\t\tmarketIndex,\n\t\tisolatedCalc,\n\t] of marginCalc.isolatedMarginCalculations) {\n\t\tconst shortfall = isolatedCalc.marginShortage();\n\t\tif (shortfall.gt(ZERO)) {\n\t\t\tshortfalls.set(marketIndex, shortfall);\n\t\t}\n\t}\n\n\treturn shortfalls;\n}\n\n/**\n * Computes the initial margin shortfall for a single isolated perp position.\n * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.\n */\nexport function getIsolatedMarginShortfall(\n\tuser: User,\n\tmarketIndex: number\n): BN {\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\tconst isolatedCalc = marginCalc.isolatedMarginCalculations.get(marketIndex);\n\n\tif (!isolatedCalc) {\n\t\treturn ZERO;\n\t}\n\n\treturn isolatedCalc.marginShortage();\n}\n\n/**\n * Returns all isolated margin shortfalls as an array, excluding a specific market index.\n * Useful for getting shortfalls for \"other\" isolated positions.\n */\nexport function getOtherIsolatedMarginShortfalls(\n\tuser: User,\n\texcludeMarketIndex?: number\n): IsolatedMarginShortfall[] {\n\tconst shortfalls = getIsolatedMarginShortfalls(user);\n\tconst result: IsolatedMarginShortfall[] = [];\n\n\tfor (const [marketIndex, shortfall] of shortfalls) {\n\t\tif (\n\t\t\texcludeMarketIndex !== undefined &&\n\t\t\tmarketIndex === excludeMarketIndex\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push({ marketIndex, shortfall });\n\t}\n\n\treturn result;\n}\n\n/**\n * Computes the total of all isolated margin shortfalls.\n */\nexport function getTotalIsolatedMarginShortfall(\n\tuser: User,\n\texcludeMarketIndex?: number\n): BN {\n\tconst shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);\n\treturn shortfalls.reduce((acc, s) => acc.add(s.shortfall), ZERO);\n}\n\nexport interface ComputeIsolatedPositionDepositParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\t/**\n\t * Optional direction of the order.\n\t * If provided, we will check if the order will increase the position.\n\t * If the order will not increase the position, we will return 0.\n\t */\n\tdirection?: PositionDirection;\n\t/**\n\t * Margin ratio to use for the position (e.g. 2000 for 5x leverage).\n\t */\n\tmarginRatio: number;\n\t/**\n\t * Optional estimated entry price to use for the margin calculation.\n\t */\n\tentryPrice?: BN;\n\t/**\n\t * Number of open high leverage spots available to the user (if any).\n\t * If greater than 0, we will consider the trade as entering high leverage mode.\n\t */\n\tnumOfOpenHighLeverageSpots?: number;\n\t/**\n\t * Optional buffer denominator for the isolated position deposit.\n\t *\n\t * Smaller numbers mean a bigger buffer.\n\t *\n\t * bufferDenominator -> Buffer %\n\t *\n\t * 15 -> 6.67%\n\t *\n\t * 20 (default) -> 5.00%\n\t *\n\t * 50 -> 2.00%\n\t *\n\t * 100 -> 1.00%\n\t *\n\t * 180 -> 0.56%\n\t *\n\t * 200 -> 0.50%\n\t */\n\tbufferDenominator?: number;\n\t/**\n\t * If true, the current market's initial margin shortfall (if any)\n\t * will be added to the deposit amount.\n\t */\n\tincludeExistingShortfall?: boolean;\n}\n\n/**\n * Computes the isolated position deposit required for opening an isolated perp position.\n * Returns a BN in QUOTE_PRECISION (USDC).\n */\nexport function computeIsolatedPositionDepositForTrade({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tbaseAssetAmount,\n\tdirection,\n\tmarginRatio,\n\tentryPrice,\n\tnumOfOpenHighLeverageSpots,\n\tbufferDenominator,\n\tincludeExistingShortfall,\n}: ComputeIsolatedPositionDepositParams): BN | null {\n\t// Only require isolated deposit if the order will increase the position (when direction is provided)\n\tif (direction !== undefined) {\n\t\tconst maybeOrderParams: OptionalOrderParams = {\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\torderType: OrderType.MARKET,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount,\n\t\t};\n\t\tconst subAccountId = user.getUserAccount().subAccountId;\n\t\tconst isIncreasing = driftClient.isOrderIncreasingPosition(\n\t\t\tmaybeOrderParams,\n\t\t\tsubAccountId\n\t\t);\n\t\tif (!isIncreasing) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tconst userIsInHighLeverageMode = user.isHighLeverageMode('Initial') ?? false;\n\tconst hasOpenHighLeverageSpots =\n\t\tnumOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;\n\tconst enteringHighLeverageMode =\n\t\tuserIsInHighLeverageMode || hasOpenHighLeverageSpots;\n\n\tconst marginRequired = calculateMarginUSDCRequiredForTrade(\n\t\tdriftClient,\n\t\tmarketIndex,\n\t\tbaseAssetAmount,\n\t\tmarginRatio,\n\t\tenteringHighLeverageMode,\n\t\tentryPrice\n\t);\n\n\tlet depositAmount = marginRequired.add(\n\t\tmarginRequired.div(\n\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t)\n\t); // buffer in basis points\n\n\t// Add existing shortfall for this market if requested\n\tif (includeExistingShortfall) {\n\t\tconst existingShortfall = getIsolatedMarginShortfall(user, marketIndex);\n\t\tif (existingShortfall.gt(ZERO)) {\n\t\t\t// Add shortfall with a 5% buffer on top (same as new margin)\n\t\t\tconst shortfallWithBuffer = existingShortfall.add(\n\t\t\t\texistingShortfall.div(\n\t\t\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t\t\t)\n\t\t\t);\n\t\t\tdepositAmount = depositAmount.add(shortfallWithBuffer);\n\t\t}\n\t}\n\n\treturn depositAmount;\n}\n\nexport async function getIsolatedPositionDepositIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tisolatedPositionDeposit?: BN,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!isolatedPositionDeposit) {\n\t\treturn undefined;\n\t}\n\tif (isolatedPositionDeposit.isZero()) {\n\t\treturn undefined;\n\t}\n\n\treturn driftClient.getTransferIsolatedPerpPositionDepositIx(\n\t\tisolatedPositionDeposit,\n\t\tmarketIndex,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined, // noAmountBuffer\n\t\tsigningAuthority\n\t);\n}\n"]}
@@ -5,7 +5,7 @@ import { OptionalAuctionParamsRequestInputs } from '../dlobServer';
5
5
  import { HighLeverageOptions } from '../../../../../../common-ui-utils/order';
6
6
  import { WithTxnParams } from '../../../../types';
7
7
  import { TxnOrSwiftResult } from '../types';
8
- import { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';
8
+ import { PlaceAndTakeParams, OptionalTriggerOrderParams, AdditionalIsolatedPositionDeposit } from '../types';
9
9
  import { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';
10
10
  export interface OpenPerpMarketOrderBaseParams {
11
11
  driftClient: DriftClient;
@@ -36,6 +36,12 @@ export interface OpenPerpMarketOrderBaseParams {
36
36
  * This field is used for opening isolated positions.
37
37
  */
38
38
  isolatedPositionDeposit?: BN;
39
+ /**
40
+ * Additional isolated position deposits needed to top up other
41
+ * under-collateralized isolated positions before placing the order.
42
+ * Each deposit will create a separate instruction.
43
+ */
44
+ additionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];
39
45
  /**
40
46
  * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.
41
47
  * This is only applicable for non-SWIFT orders.
@@ -123,7 +129,7 @@ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, directio
123
129
  * @param userOrderId - the order ID in terms of incremental fills (usually 0). do NOT use the nextOrderId from the user account. values over 255 will cause the order to fail onchain.
124
130
  * @returns Promise resolving to an array of transaction instructions for regular orders
125
131
  */
126
- export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, highLeverageOptions, isolatedPositionDeposit, callbacks, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
132
+ export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, highLeverageOptions, isolatedPositionDeposit, additionalIsolatedPositionDeposits, callbacks, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
127
133
  /**
128
134
  * Creates a complete transaction for opening a perp market order.
129
135
  *
@@ -127,7 +127,7 @@ exports.createPlaceAndTakePerpMarketOrderIx = createPlaceAndTakePerpMarketOrderI
127
127
  * @param userOrderId - the order ID in terms of incremental fills (usually 0). do NOT use the nextOrderId from the user account. values over 255 will cause the order to fail onchain.
128
128
  * @returns Promise resolving to an array of transaction instructions for regular orders
129
129
  */
130
- const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, positionMaxLeverage, mainSignerOverride, highLeverageOptions, isolatedPositionDeposit, callbacks, }) => {
130
+ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, positionMaxLeverage, mainSignerOverride, highLeverageOptions, isolatedPositionDeposit, additionalIsolatedPositionDeposits, callbacks, }) => {
131
131
  var _a, _b, _c, _d;
132
132
  if (!amount || amount.isZero()) {
133
133
  throw new Error('Amount must be greater than zero');
@@ -138,6 +138,16 @@ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, mark
138
138
  if (leverageIx) {
139
139
  allIxs.push(leverageIx);
140
140
  }
141
+ // Add additional isolated position deposit ixs for other under-collateralized positions
142
+ if (additionalIsolatedPositionDeposits === null || additionalIsolatedPositionDeposits === void 0 ? void 0 : additionalIsolatedPositionDeposits.length) {
143
+ const additionalDepositIxPromises = additionalIsolatedPositionDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride));
144
+ const additionalDepositIxs = await Promise.all(additionalDepositIxPromises);
145
+ for (const ix of additionalDepositIxs) {
146
+ if (ix) {
147
+ allIxs.push(ix);
148
+ }
149
+ }
150
+ }
141
151
  const isolatedPositionDepositIx = await (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, isolatedPositionDeposit, mainSignerOverride);
142
152
  if (isolatedPositionDepositIx) {
143
153
  allIxs.push(isolatedPositionDepositIx);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAGiD;AAGjD,kEAAyE;AAEzE,gEAA0E;AAE1E,wEAAkF;AA6FlF;;GAEG;AACI,KAAK,UAAU,sBAAsB,CAAC,EAC5C,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,UAAU,EACV,aAAa,EACb,iBAAiB,EACjB,2BAA2B,EAC3B,YAAY,EACZ,WAAW,GAAG,CAAC,EACf,mBAAmB,EACnB,uBAAuB,EACvB,aAAa,EACb,mBAAmB,EACnB,SAAS,GAC+B;I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AClC,mBAAmB,EAAE,WAAW;QAChC,iCAAiC,EAChC,WAAW,CAAC,2BAA2B,CAAC,IAAI,CAAC,WAAW,CAAC;QAC1D,QAAQ,EAAE,MAAM,CAAC,QAAQ;KACzB,CAAC,CAAC;IAEH,OAAO,sBAAsB,CAAC;AAC/B,CAAC,CAAC;AAlBW,QAAA,4BAA4B,gCAkBvC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,yBAAyB,GAAG,KAAK,EAC7C,MAAsE,EACvC,EAAE;IACjC,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEnD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAA6C,CAAC;AACtD,CAAC,CAAC;AAtBW,QAAA,yBAAyB,6BAsBpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils/order';\nimport { WithTxnParams } from '../../../../types';\nimport { TxnOrSwiftResult } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';\nimport { getIsolatedPositionDepositIxIfNeeded } from '../isolatedPositionDeposit';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\treduceOnly?: boolean;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Optional per-market leverage to set for this position.\n\t * If provided and different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\t/**\n\t * Optional isolated position deposit amount.\n\t * If provided, it will be added to the order params as isolatedPositionDeposit.\n\t * This field is used for opening isolated positions.\n\t */\n\tisolatedPositionDeposit?: BN;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\tcallbacks?: {\n\t\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\treduceOnly,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n\tpositionMaxLeverage,\n\tisolatedPositionDeposit,\n\tbuilderParams,\n\thighLeverageOptions,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t\treduceOnly,\n\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t});\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t\tisolatedPositionDeposit,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\torderType,\n\tprice,\n\treduceOnly,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tpositionMaxLeverage,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParams & {\n\torderType?: OrderType;\n\tprice?: BN;\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n\thighLeverageOptions?: HighLeverageOptions;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\treduceOnly,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (orderType) {\n\t\tfetchedOrderParams.orderType = orderType;\n\t}\n\n\tif (price) {\n\t\tfetchedOrderParams.price = price;\n\t\tfetchedOrderParams.auctionEndPrice = price;\n\t}\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * adds an instruction to update the position's maxMarginRatio before placing the order.\n * @param userOrderId - the order ID in terms of incremental fills (usually 0). do NOT use the nextOrderId from the user account. values over 255 will cause the order to fail onchain.\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\treduceOnly,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n\tpositionMaxLeverage,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tisolatedPositionDeposit,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\tconst isolatedPositionDepositIx = await getIsolatedPositionDepositIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tisolatedPositionDeposit,\n\t\tmainSignerOverride\n\t);\n\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\n\t}\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treduceOnly,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t\tmainSignerOverride,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\treduceOnly,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t});\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\n\t\t\thighLeverageOptions\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * includes an instruction to update the position's maxMarginRatio.\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIxs = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIxs,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). Only supported for regular transactions (not Swift).\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAGiD;AAGjD,kEAAyE;AAMzE,gEAA0E;AAE1E,wEAAkF;AAmGlF;;GAEG;AACI,KAAK,UAAU,sBAAsB,CA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AAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAA6C,CAAC;AACtD,CAAC,CAAC;AAtBW,QAAA,yBAAyB,6BAsBpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils/order';\nimport { WithTxnParams } from '../../../../types';\nimport { TxnOrSwiftResult } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport {\n\tPlaceAndTakeParams,\n\tOptionalTriggerOrderParams,\n\tAdditionalIsolatedPositionDeposit,\n} from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';\nimport { getIsolatedPositionDepositIxIfNeeded } from '../isolatedPositionDeposit';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\treduceOnly?: boolean;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Optional per-market leverage to set for this position.\n\t * If provided and different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\t/**\n\t * Optional isolated position deposit amount.\n\t * If provided, it will be added to the order params as isolatedPositionDeposit.\n\t * This field is used for opening isolated positions.\n\t */\n\tisolatedPositionDeposit?: BN;\n\t/**\n\t * Additional isolated position deposits needed to top up other\n\t * under-collateralized isolated positions before placing the order.\n\t * Each deposit will create a separate instruction.\n\t */\n\tadditionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\tcallbacks?: {\n\t\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\treduceOnly,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n\tpositionMaxLeverage,\n\tisolatedPositionDeposit,\n\tbuilderParams,\n\thighLeverageOptions,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t\treduceOnly,\n\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t});\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t\tisolatedPositionDeposit,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\torderType,\n\tprice,\n\treduceOnly,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tpositionMaxLeverage,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParams & {\n\torderType?: OrderType;\n\tprice?: BN;\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n\thighLeverageOptions?: HighLeverageOptions;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\treduceOnly,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (orderType) {\n\t\tfetchedOrderParams.orderType = orderType;\n\t}\n\n\tif (price) {\n\t\tfetchedOrderParams.price = price;\n\t\tfetchedOrderParams.auctionEndPrice = price;\n\t}\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * adds an instruction to update the position's maxMarginRatio before placing the order.\n * @param userOrderId - the order ID in terms of incremental fills (usually 0). do NOT use the nextOrderId from the user account. values over 255 will cause the order to fail onchain.\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\treduceOnly,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n\tpositionMaxLeverage,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tisolatedPositionDeposit,\n\tadditionalIsolatedPositionDeposits,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\t// Add additional isolated position deposit ixs for other under-collateralized positions\n\tif (additionalIsolatedPositionDeposits?.length) {\n\t\tconst additionalDepositIxPromises = additionalIsolatedPositionDeposits.map(\n\t\t\t(deposit) =>\n\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\tdeposit.amount,\n\t\t\t\t\tmainSignerOverride\n\t\t\t\t)\n\t\t);\n\t\tconst additionalDepositIxs = await Promise.all(additionalDepositIxPromises);\n\t\tfor (const ix of additionalDepositIxs) {\n\t\t\tif (ix) {\n\t\t\t\tallIxs.push(ix);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst isolatedPositionDepositIx = await getIsolatedPositionDepositIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tisolatedPositionDeposit,\n\t\tmainSignerOverride\n\t);\n\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\n\t}\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treduceOnly,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t\tmainSignerOverride,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\treduceOnly,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t});\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\n\t\t\thighLeverageOptions\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * includes an instruction to update the position's maxMarginRatio.\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIxs = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIxs,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). Only supported for regular transactions (not Swift).\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
@@ -2,7 +2,7 @@ import { DriftClient, User, BN, PostOnlyParams } from '@drift-labs/sdk';
2
2
  import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { SwiftOrderOptions } from '../openSwiftOrder';
4
4
  import { HighLeverageOptions } from '../../../../../../common-ui-utils';
5
- import { TxnOrSwiftResult, LimitOrderParamsOrderConfig, NonMarketOrderParamsConfig } from '../types';
5
+ import { TxnOrSwiftResult, LimitOrderParamsOrderConfig, NonMarketOrderParamsConfig, AdditionalIsolatedPositionDeposit } from '../types';
6
6
  import { WithTxnParams } from '../../../../types';
7
7
  export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {
8
8
  driftClient: DriftClient;
@@ -28,6 +28,12 @@ export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderPar
28
28
  builderFeeTenthBps: number;
29
29
  };
30
30
  highLeverageOptions?: HighLeverageOptions;
31
+ /**
32
+ * Additional isolated position deposits needed to top up other
33
+ * under-collateralized isolated positions before placing the order.
34
+ * Each deposit will create a separate instruction.
35
+ */
36
+ additionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];
31
37
  }
32
38
  export interface OpenPerpNonMarketOrderParamsWithSwift extends OpenPerpNonMarketOrderBaseParams {
33
39
  swiftOptions: SwiftOrderOptions;
@@ -34,7 +34,7 @@ exports.createMultipleOpenPerpNonMarketOrderIx = createMultipleOpenPerpNonMarket
34
34
  */
35
35
  const createOpenPerpNonMarketOrderIxs = async (params) => {
36
36
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
37
- const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, isolatedPositionDeposit, mainSignerOverride, highLeverageOptions, } = params;
37
+ const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, isolatedPositionDeposit, additionalIsolatedPositionDeposits, mainSignerOverride, highLeverageOptions, } = params;
38
38
  // Support both new (amount + assetType) and legacy (baseAssetAmount) approaches
39
39
  const finalBaseAssetAmount = (0, orderParams_1.resolveBaseAssetAmount)({
40
40
  amount: 'amount' in params ? params.amount : undefined,
@@ -53,6 +53,16 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
53
53
  if (leverageIx) {
54
54
  allIxs.push(leverageIx);
55
55
  }
56
+ // Add additional isolated position deposit ixs for other under-collateralized positions
57
+ if (additionalIsolatedPositionDeposits === null || additionalIsolatedPositionDeposits === void 0 ? void 0 : additionalIsolatedPositionDeposits.length) {
58
+ const additionalDepositIxPromises = additionalIsolatedPositionDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride));
59
+ const additionalDepositIxs = await Promise.all(additionalDepositIxPromises);
60
+ for (const ix of additionalDepositIxs) {
61
+ if (ix) {
62
+ allIxs.push(ix);
63
+ }
64
+ }
65
+ }
56
66
  const isolatedPositionDepositIx = await (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, isolatedPositionDeposit, mainSignerOverride);
57
67
  if (isolatedPositionDepositIx) {
58
68
  allIxs.push(isolatedPositionDepositIx);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,uEAG2C;AAC3C,gEAA6E;AAQ7E,gEAA0E;AAC1E,wCAAwD;AACxD,wEAAkF;AAqDlF;;GAEG;AACI,MAAM,sCAAsC,GAAG,KAAK,EAAE,MAS5D,EAAmC,EAAE;IACrC,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,GAAG,MAAM,CAAC;IAEvE,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,uCAAyB,C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7DW,QAAA,qBAAqB,yBA6DhC;AAEK,MAAM,+BAA+B,GAAG,KAAK,EACnD,MAAuD,EACT,EAAE;IAChD,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;IAE/B,MAAM,YAAY,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAEnE,MAAM,yBAAyB,GAAG,MAAM,WAAW,CAAC,gBAAgB,CACnE,YAAY,EACZ,MAAM,CAAC,QAAQ,CACf,CAAC;IAEF,OAAO,yBAAyB,CAAC;AAClC,CAAC,CAAC;AAbW,QAAA,+BAA+B,mCAa1C;AAEK,MAAM,4BAA4B,GAAG,KAAK,EAChD,MAAyE,EAC1C,EAAE;IACjC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;IAEvD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,WAAW,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC/D,CAAC;QAED,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAA,6BAAqB,EAAC;YACpD,GAAG,MAAM;YACT,YAAY;YACZ,WAAW;SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AA3BW,QAAA,4BAA4B,gCA2BvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\nimport { getIsolatedPositionDepositIxIfNeeded } from '../isolatedPositionDeposit';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now.\n\t */\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t */\n\tmainSignerOverride?: PublicKey;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs, mainSignerOverride } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\torderParams,\n\t\tundefined,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t\tpositionMaxLeverage,\n\t\tisolatedPositionDeposit,\n\t\tmainSignerOverride,\n\t\thighLeverageOptions,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\tconst isolatedPositionDepositIx: TransactionInstruction | undefined =\n\t\tawait getIsolatedPositionDepositIxIfNeeded(\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tisolatedPositionDeposit,\n\t\t\tmainSignerOverride\n\t\t);\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\n\t}\n\n\t// handle limit auction\n\tif (\n\t\torderConfig.orderType === 'limit' &&\n\t\torderConfig.limitAuction?.enable &&\n\t\tENUM_UTILS.match(postOnly, PostOnlyParams.NONE)\n\t) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\torderType: OrderType.LIMIT,\n\t\t\t\t\tprice: orderConfig.limitPrice,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\treduceOnly,\n\t\t\t\t\tpositionMaxLeverage,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t\thighLeverageOptions,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\n\t\t\thighLeverageOptions\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage, // TODO: this isn't referenced in the function... do we need it?\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tisolatedPositionDeposit: params.isolatedPositionDeposit,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,uEAG2C;AAC3C,gEAA6E;AAS7E,gEAA0E;AAC1E,wCAAwD;AACxD,wEAAkF;AA2DlF;;GAEG;AACI,MAAM,sCAAsC,GAAG,KAAK,EAAE,MAS5D,EAAmC,EAAE;IACrC,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,GAAG,MAAM,CAAC;IAEvE,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,uCAAyB,CAAC,CAAC;IAEtE,IAAI,MAAM,CAAC,qBAAqB,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5D,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,wBAAkB,CAAC,sBAAsB,CAAC;IAC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SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AA3BW,QAAA,4BAA4B,gCA2BvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tAdditionalIsolatedPositionDeposit,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\nimport { getIsolatedPositionDepositIxIfNeeded } from '../isolatedPositionDeposit';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now.\n\t */\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\t/**\n\t * Additional isolated position deposits needed to top up other\n\t * under-collateralized isolated positions before placing the order.\n\t * Each deposit will create a separate instruction.\n\t */\n\tadditionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t */\n\tmainSignerOverride?: PublicKey;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs, mainSignerOverride } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\torderParams,\n\t\tundefined,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t\tpositionMaxLeverage,\n\t\tisolatedPositionDeposit,\n\t\tadditionalIsolatedPositionDeposits,\n\t\tmainSignerOverride,\n\t\thighLeverageOptions,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\t// Add additional isolated position deposit ixs for other under-collateralized positions\n\tif (additionalIsolatedPositionDeposits?.length) {\n\t\tconst additionalDepositIxPromises = additionalIsolatedPositionDeposits.map(\n\t\t\t(deposit) =>\n\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\tdeposit.amount,\n\t\t\t\t\tmainSignerOverride\n\t\t\t\t)\n\t\t);\n\t\tconst additionalDepositIxs = await Promise.all(additionalDepositIxPromises);\n\t\tfor (const ix of additionalDepositIxs) {\n\t\t\tif (ix) {\n\t\t\t\tallIxs.push(ix);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst isolatedPositionDepositIx: TransactionInstruction | undefined =\n\t\tawait getIsolatedPositionDepositIxIfNeeded(\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tisolatedPositionDeposit,\n\t\t\tmainSignerOverride\n\t\t);\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\n\t}\n\n\t// handle limit auction\n\tif (\n\t\torderConfig.orderType === 'limit' &&\n\t\torderConfig.limitAuction?.enable &&\n\t\tENUM_UTILS.match(postOnly, PostOnlyParams.NONE)\n\t) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\torderType: OrderType.LIMIT,\n\t\t\t\t\tprice: orderConfig.limitPrice,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\treduceOnly,\n\t\t\t\t\tpositionMaxLeverage,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t\thighLeverageOptions,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\n\t\t\thighLeverageOptions\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t\tpositionMaxLeverage,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage, // TODO: this isn't referenced in the function... do we need it?\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tisolatedPositionDeposit: params.isolatedPositionDeposit,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
@@ -3,6 +3,14 @@ import { Transaction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { OptionalAuctionParamsRequestInputs } from './dlobServer';
4
4
  import { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';
5
5
  export type TxnOrSwiftResult<T extends boolean> = T extends true ? void : Transaction | VersionedTransaction;
6
+ /**
7
+ * Represents an additional isolated position deposit needed to top up
8
+ * an under-collateralized isolated position before placing an order.
9
+ */
10
+ export interface AdditionalIsolatedPositionDeposit {
11
+ marketIndex: number;
12
+ amount: BN;
13
+ }
6
14
  export type PlaceAndTakeParams = {
7
15
  enable: false;
8
16
  } | {
@@ -60,6 +68,11 @@ export interface NonMarketOrderParamsConfig {
60
68
  */
61
69
  positionMaxLeverage: number;
62
70
  isolatedPositionDeposit?: BN;
71
+ /**
72
+ * Additional isolated position deposits needed to top up other
73
+ * under-collateralized isolated positions before placing the order.
74
+ */
75
+ additionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];
63
76
  orderConfig: LimitOrderParamsOrderConfig | {
64
77
  orderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;
65
78
  triggerPrice: BN;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBN,\n\tMarketType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tReferrerInfo,\n} from '@drift-labs/sdk';\nimport { Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { OptionalAuctionParamsRequestInputs } from './dlobServer';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport type TxnOrSwiftResult<T extends boolean> = T extends true\n\t? void\n\t: Transaction | VersionedTransaction;\n\nexport type PlaceAndTakeParams =\n\t| {\n\t\t\tenable: false;\n\t }\n\t| {\n\t\t\tenable: true;\n\t\t\tauctionDurationPercentage?: number;\n\t\t\treferrerInfo: ReferrerInfo | undefined;\n\t };\n\nexport type NonMarketOrderType =\n\t| 'limit'\n\t| 'takeProfit'\n\t| 'stopLoss'\n\t| 'oracleLimit';\n\nexport interface LimitAuctionConfig {\n\tenable: boolean;\n\tdlobServerHttpUrl: string;\n\tauctionStartPriceOffset: number;\n\toraclePrice?: BN; // used to calculate oracle price bands\n\toptionalLimitAuctionParams?: OptionalAuctionParamsRequestInputs;\n\tusePlaceAndTake?: {\n\t\tenable: boolean;\n\t\treferrerInfo?: ReferrerInfo; // needed for place and take fallback\n\t\tauctionDurationPercentage?: number;\n\t};\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n}\n\nexport interface OptionalTriggerOrderParams {\n\tbaseAssetAmount?: BN;\n\ttriggerPrice: BN;\n\tlimitPrice?: BN;\n\treduceOnly?: boolean;\n}\n\nexport interface LimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'limit'>;\n\tlimitPrice: BN;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Limit orders can have an optional auction that allows it to go through the auction process.\n\t * Usually, the auction params are set up to the limit price, to allow for a possible improved\n\t * fill price. This is useful for when a limit order is crossing the orderbook.\n\t */\n\tlimitAuction?: LimitAuctionConfig;\n}\n\nexport interface NonMarketOrderParamsConfig {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\t/**\n\t * The leverage to be used for this position.\n\t * If different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\tisolatedPositionDeposit?: BN;\n\torderConfig:\n\t\t| LimitOrderParamsOrderConfig\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;\n\t\t\t\ttriggerPrice: BN;\n\t\t\t\tlimitPrice?: BN;\n\t\t }\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'oracleLimit'>;\n\t\t\t\toraclePriceOffset: BN;\n\t\t };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBN,\n\tMarketType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tReferrerInfo,\n} from '@drift-labs/sdk';\nimport { Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { OptionalAuctionParamsRequestInputs } from './dlobServer';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport type TxnOrSwiftResult<T extends boolean> = T extends true\n\t? void\n\t: Transaction | VersionedTransaction;\n\n/**\n * Represents an additional isolated position deposit needed to top up\n * an under-collateralized isolated position before placing an order.\n */\nexport interface AdditionalIsolatedPositionDeposit {\n\tmarketIndex: number;\n\tamount: BN;\n}\n\nexport type PlaceAndTakeParams =\n\t| {\n\t\t\tenable: false;\n\t }\n\t| {\n\t\t\tenable: true;\n\t\t\tauctionDurationPercentage?: number;\n\t\t\treferrerInfo: ReferrerInfo | undefined;\n\t };\n\nexport type NonMarketOrderType =\n\t| 'limit'\n\t| 'takeProfit'\n\t| 'stopLoss'\n\t| 'oracleLimit';\n\nexport interface LimitAuctionConfig {\n\tenable: boolean;\n\tdlobServerHttpUrl: string;\n\tauctionStartPriceOffset: number;\n\toraclePrice?: BN; // used to calculate oracle price bands\n\toptionalLimitAuctionParams?: OptionalAuctionParamsRequestInputs;\n\tusePlaceAndTake?: {\n\t\tenable: boolean;\n\t\treferrerInfo?: ReferrerInfo; // needed for place and take fallback\n\t\tauctionDurationPercentage?: number;\n\t};\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n}\n\nexport interface OptionalTriggerOrderParams {\n\tbaseAssetAmount?: BN;\n\ttriggerPrice: BN;\n\tlimitPrice?: BN;\n\treduceOnly?: boolean;\n}\n\nexport interface LimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'limit'>;\n\tlimitPrice: BN;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Limit orders can have an optional auction that allows it to go through the auction process.\n\t * Usually, the auction params are set up to the limit price, to allow for a possible improved\n\t * fill price. This is useful for when a limit order is crossing the orderbook.\n\t */\n\tlimitAuction?: LimitAuctionConfig;\n}\n\nexport interface NonMarketOrderParamsConfig {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\t/**\n\t * The leverage to be used for this position.\n\t * If different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\tisolatedPositionDeposit?: BN;\n\t/**\n\t * Additional isolated position deposits needed to top up other\n\t * under-collateralized isolated positions before placing the order.\n\t */\n\tadditionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];\n\torderConfig:\n\t\t| LimitOrderParamsOrderConfig\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;\n\t\t\t\ttriggerPrice: BN;\n\t\t\t\tlimitPrice?: BN;\n\t\t }\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'oracleLimit'>;\n\t\t\t\toraclePriceOffset: BN;\n\t\t };\n}\n"]}
@@ -67,7 +67,7 @@ class UIMarket {
67
67
  if (!marketConfig.category) {
68
68
  return false;
69
69
  }
70
- return (_b = (_a = marketConfig.category) === null || _a === void 0 ? void 0 : _a.includes('Prediction')) !== null && _b !== void 0 ? _b : false;
70
+ return ((_b = (_a = marketConfig.category) === null || _a === void 0 ? void 0 : _a.includes('Prediction')) !== null && _b !== void 0 ? _b : false);
71
71
  }
72
72
  get isSpot() {
73
73
  return this.marketId.isSpot;
@@ -1 +1 @@
1
- {"version":3,"file":"UIMarket.js","sourceRoot":"","sources":["../../src/types/UIMarket.ts"],"names":[],"mappings":";;;;;;AAAA,yCASyB;AACzB,yCAAsC;AACtC,oEAAuC;AACvC,8CAM4B;AAC5B,kDAA8D;AAC9D,oCAAsC;AACtC,sCAAmC;AAGnC,MAAM,qBAAqB,GAC1B,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,MAAM,CAAC;AAyD7D,MAAa,QAAQ;IAUpB,IAAI,SAAS;QACZ,OAAO,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IAED,IAAY,SAAS,CAAC,SAAoB;QACzC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,YAAqB,WAAmB,EAAW,UAAsB;QAApD,gBAAW,GAAX,WAAW,CAAQ;QAAW,eAAU,GAAV,UAAU,CAAY;QACxE,MAAM,QAAQ,GAAG,IAAI,mBAAQ,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvD,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,C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C,UAAU,CAAC,KAAK,CAAC;wBACpC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;wBACnC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACV,CAAC;gBAC7B,CAAC;gBACD;oBACC,OAAO,YAAY,CAAC,MAAgC,CAAC;YACvD,CAAC;QACF,CAAC;IACF,CAAC;;AA9PF,4BA+PC;AA9PO,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAC1C,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAClC,cAAK,GAAG,IAAI,GAAG,EAAoB,CAAC","sourcesContent":["import {\n\tMarketType,\n\tOracleSource,\n\tPerpMarketConfig,\n\tPerpMarkets,\n\tSpotMarkets,\n\tSpotMarketConfig,\n\tBASE_PRECISION,\n\tBASE_PRECISION_EXP,\n} from '@drift-labs/sdk';\nimport { MarketId } from './MarketId';\nimport invariant from 'tiny-invariant';\nimport {\n\tEXPONENT_POOL_ID,\n\tJLP_POOL_ID,\n\tLST_POOL_ID,\n\tMAIN_POOL_ID,\n\tSACRED_POOL_ID,\n} from '../constants/pools';\nimport { USDC_SPOT_MARKET_INDEX } from '../constants/markets';\nimport { ENUM_UTILS } from '../utils';\nimport { Config } from '../Config';\nimport { Opaque } from './utility';\n\nconst useAsyncMarketConfigs =\n\tprocess.env.NEXT_PUBLIC_USE_ASYNC_MARKET_CONFIGS === 'true';\n\n/**\n * MarketSymbol will uniquely identify a market\n */\nexport type MarketSymbol = Opaque<string, 'MarketSymbol'>;\n/**\n * MarketDisplaySymbol is the label for a market that we display to a user\n */\nexport type MarketDisplaySymbol = Opaque<string, 'MarketDisplaySymbol'>;\n/**\n * BaseAssetSymbol is the symbol for the underlying asset for a market\n */\nexport type BaseAssetSymbol = Opaque<string, 'BaseAssetSymbol'>;\n/**\n * BaseAssetDisplaySymbol is the label for the underlying asset for a market that we display to a user\n */\nexport type BaseAssetDisplaySymbol = Opaque<string, 'BaseAssetDisplaySymbol'>;\n\n/**\n * # Examples and explanations of the symbol types:\n *\n * ## MarketSymbol:\n * These are basically just the raw symbols in the market configs.\n * - 1KWEN-PERP\n * - JitoSOL-3\n * - PT-fragSOL-15JUN25-3\n *\n * ## MarketDisplaySymbol:\n * This is the symbol we use to display the market to the user. For SPOT markets it should be the exact same as the BaseAssetDisplaySymbol, but for PERP markets they might be different which is why we have this separate type.\n *\n * - 1KWEN-PERP => 1KWEN-PERP\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n *\n * ## BaseAssetDisplaySymbol:\n * This is the symbol we use to communicate \"what asset they are holding\". For SPOT markets it should be the same as the MarketDisplaySymbol, but for PERP markets it may be different, for example we show open interest denominated in \"1KWEN\", while the market is \"1KWEN-PERP\".\n *\n * - 1KWEN-PERP => 1KWEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => fragSOL\n *\n * ## BaseAssetSymbol:\n * This is the symbol for the underlying asset for a market. I don't believe we will display this anywhere but we use these for example when looking up the market icon to use.\n *\n * - 1KWEN-PERP => WEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25 (note: PT-fragSOL has an icon different to regular fragSOL, otherwise we would use 'fragSOL' for the base asset symbol)\n */\n\ntype UISymbols = {\n\tmarketSymbol: MarketSymbol;\n\tmarketDisplaySymbol: MarketDisplaySymbol;\n\tbaseAssetSymbol: BaseAssetSymbol;\n\tbaseAssetDisplaySymbol: BaseAssetDisplaySymbol;\n};\n\nexport class UIMarket {\n\tstatic perpMarkets = PerpMarkets['mainnet-beta'];\n\tstatic spotMarkets = SpotMarkets['mainnet-beta'];\n\tprivate static cache = new Map<string, UIMarket>();\n\n\treadonly market: SpotMarketConfig | PerpMarketConfig;\n\treadonly marketId: MarketId;\n\n\tprivate _uiSymbols: UISymbols;\n\n\tget uiSymbols() {\n\t\treturn this._uiSymbols;\n\t}\n\n\tprivate set uiSymbols(uiSymbols: UISymbols) {\n\t\tthis._uiSymbols = uiSymbols;\n\t}\n\n\tconstructor(readonly marketIndex: number, readonly marketType: MarketType) {\n\t\tconst marketId = new MarketId(marketIndex, marketType);\n\t\tconst perpMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.perpMarkets\n\t\t\t: Config.perpMarketsLookup;\n\t\tconst spotMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.spotMarkets\n\t\t\t: Config.spotMarketsLookup;\n\t\tconst markets = marketId.isPerp ? perpMarkets : spotMarkets;\n\n\t\t//@ts-ignore\n\t\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\t\t// TODO: should we purposely throw an error here? Or construct a default market?\n\t\tinvariant(\n\t\t\tmarket,\n\t\t\t`Market not found for type: ${marketId.marketTypeStr}, market index: ${marketIndex}`\n\t\t);\n\n\t\tthis.marketId = marketId;\n\t\tthis.market = market;\n\n\t\tthis.setUiSymbols();\n\t}\n\n\tstatic setPerpMarkets(perpMarkets: PerpMarketConfig[]) {\n\t\tthis.perpMarkets = perpMarkets;\n\t}\n\n\tstatic setSpotMarkets(spotMarkets: SpotMarketConfig[]) {\n\t\tthis.spotMarkets = spotMarkets;\n\t}\n\n\tprivate static getOrCreate(marketIndex: number, marketType: MarketType) {\n\t\tconst key = MarketId.key(marketIndex, marketType);\n\t\tif (UIMarket.cache.has(key)) {\n\t\t\treturn UIMarket.cache.get(key)!;\n\t\t}\n\t\tconst market = new UIMarket(marketIndex, marketType);\n\t\tUIMarket.cache.set(key, market);\n\t\treturn market;\n\t}\n\n\tstatic createSpotMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.SPOT);\n\t}\n\n\tstatic createPerpMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.PERP);\n\t}\n\n\tstatic fromMarketId(marketId: MarketId) {\n\t\treturn UIMarket.getOrCreate(marketId.marketIndex, marketId.marketType);\n\t}\n\n\tstatic checkIsPredictionMarket(marketConfig: PerpMarketConfig) {\n\t\tif (!(marketConfig as PerpMarketConfig).category) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (marketConfig as PerpMarketConfig).category?.includes('Prediction') ?? false;\n\t}\n\n\tget isSpot() {\n\t\treturn this.marketId.isSpot;\n\t}\n\n\tget isPerp() {\n\t\treturn this.marketId.isPerp;\n\t}\n\n\tget marketTypeStr() {\n\t\treturn this.marketId.marketTypeStr;\n\t}\n\n\tget key() {\n\t\treturn this.marketId.key;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketDisplaySymbol instead\n\tget marketName() {\n\t\treturn `${this.market.symbol}${this.isSpot ? '/USDC' : ''}`;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketSymbol instead\n\tget symbol() {\n\t\treturn this.market.symbol;\n\t}\n\n\tget isUsdcMarket() {\n\t\treturn this.isSpot && this.marketIndex === USDC_SPOT_MARKET_INDEX;\n\t}\n\n\tget isStableCoinMarket() {\n\t\treturn (\n\t\t\tthis.isSpot &&\n\t\t\tENUM_UTILS.match(this.market.oracleSource, OracleSource.PYTH_STABLE_COIN)\n\t\t);\n\t}\n\n\tget isPredictionMarket() {\n\t\treturn (\n\t\t\tthis.isPerp &&\n\t\t\tUIMarket.checkIsPredictionMarket(this.market as PerpMarketConfig)\n\t\t);\n\t}\n\n\tget precision() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precision;\n\t\t}\n\t}\n\n\tget precisionExp() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION_EXP;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precisionExp;\n\t\t}\n\t}\n\n\tequals(other: UIMarket) {\n\t\treturn this.marketId.equals(other.marketId);\n\t}\n\n\t// @deprecated : Use uiSymbols.baseAssetSymbol instead\n\tbaseAssetSymbol(removePrefix = false) {\n\t\tlet baseAssetSymbol = this.isPerp\n\t\t\t? (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t: this.market.symbol;\n\n\t\tif (removePrefix) {\n\t\t\tbaseAssetSymbol = baseAssetSymbol.replace('1K', '').replace('1M', '');\n\t\t}\n\n\t\treturn baseAssetSymbol;\n\t}\n\n\tprotected setUiSymbols() {\n\t\tinvariant(this.marketId, 'MarketId not set');\n\n\t\tconst marketSymbol = this.getMarketSymbol();\n\t\tconst marketDisplaySymbol = this.getMarketDisplaySymbol();\n\t\tconst baseAssetSymbol = this.getBaseAssetSymbol();\n\t\tconst baseAssetDisplaySymbol = this.getBaseAssetDisplaySymbol();\n\n\t\tthis.uiSymbols = {\n\t\t\tmarketSymbol,\n\t\t\tmarketDisplaySymbol,\n\t\t\tbaseAssetSymbol,\n\t\t\tbaseAssetDisplaySymbol,\n\t\t};\n\t}\n\n\tprivate getMarketSymbol(): MarketSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t} else {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t}\n\t}\n\n\tprivate getMarketDisplaySymbol(): MarketDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase MAIN_POOL_ID:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t\tcase JLP_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase LST_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n\t\t\t\t\tPT-kySOL-10JUL25-3 => PT-kySOL-10JUL25\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.slice(\n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\tmarketConfig.symbol.lastIndexOf('-')\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as MarketDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tcase SACRED_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getBaseAssetSymbol(): BaseAssetSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t\t.replace('1K', '')\n\t\t\t\t.replace('1M', '') as BaseAssetSymbol;\n\t\t} else {\n\t\t\treturn this.getMarketDisplaySymbol() as unknown as BaseAssetSymbol; // Currently no cases where SPOT baseAssetSymbol is different from marketDisplaySymbol\n\t\t}\n\t}\n\n\tprivate getBaseAssetDisplaySymbol(): BaseAssetDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig)\n\t\t\t\t.baseAssetSymbol as BaseAssetDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => fragSOL\n\t\t\t\t\tPT-kySOL-10JUL25-3 => kySOL\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.split('-')[1]\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as BaseAssetDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as BaseAssetDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"UIMarket.js","sourceRoot":"","sources":["../../src/types/UIMarket.ts"],"names":[],"mappings":";;;;;;AAAA,yCASyB;AACzB,yCAAsC;AACtC,oEAAuC;AACvC,8CAM4B;AAC5B,kDAA8D;AAC9D,oCAAsC;AACtC,sCAAmC;AAGnC,MAAM,qBAAqB,GAC1B,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,MAAM,CAAC;AAyD7D,MAAa,QAAQ;IAUpB,IAAI,SAAS;QACZ,OAAO,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IAED,IAAY,SAAS,CAAC,SAAoB;QACzC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,YAAqB,WAAmB,EAAW,UAAsB;QAApD,gBAAW,GAAX,WAAW,CAAQ;QAAW,eAAU,GAAV,UAAU,CAAY;QACxE,MAAM,QAAQ,GAAG,IAAI,mBAAQ,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvD,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,CAAC,iBAAiB,CAAC;QAC5B,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,CAAC,iB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ACnC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACV,CAAC;gBAC7B,CAAC;gBACD;oBACC,OAAO,YAAY,CAAC,MAAgC,CAAC;YACvD,CAAC;QACF,CAAC;IACF,CAAC;;AAjQF,4BAkQC;AAjQO,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAC1C,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAClC,cAAK,GAAG,IAAI,GAAG,EAAoB,CAAC","sourcesContent":["import {\n\tMarketType,\n\tOracleSource,\n\tPerpMarketConfig,\n\tPerpMarkets,\n\tSpotMarkets,\n\tSpotMarketConfig,\n\tBASE_PRECISION,\n\tBASE_PRECISION_EXP,\n} from '@drift-labs/sdk';\nimport { MarketId } from './MarketId';\nimport invariant from 'tiny-invariant';\nimport {\n\tEXPONENT_POOL_ID,\n\tJLP_POOL_ID,\n\tLST_POOL_ID,\n\tMAIN_POOL_ID,\n\tSACRED_POOL_ID,\n} from '../constants/pools';\nimport { USDC_SPOT_MARKET_INDEX } from '../constants/markets';\nimport { ENUM_UTILS } from '../utils';\nimport { Config } from '../Config';\nimport { Opaque } from './utility';\n\nconst useAsyncMarketConfigs =\n\tprocess.env.NEXT_PUBLIC_USE_ASYNC_MARKET_CONFIGS === 'true';\n\n/**\n * MarketSymbol will uniquely identify a market\n */\nexport type MarketSymbol = Opaque<string, 'MarketSymbol'>;\n/**\n * MarketDisplaySymbol is the label for a market that we display to a user\n */\nexport type MarketDisplaySymbol = Opaque<string, 'MarketDisplaySymbol'>;\n/**\n * BaseAssetSymbol is the symbol for the underlying asset for a market\n */\nexport type BaseAssetSymbol = Opaque<string, 'BaseAssetSymbol'>;\n/**\n * BaseAssetDisplaySymbol is the label for the underlying asset for a market that we display to a user\n */\nexport type BaseAssetDisplaySymbol = Opaque<string, 'BaseAssetDisplaySymbol'>;\n\n/**\n * # Examples and explanations of the symbol types:\n *\n * ## MarketSymbol:\n * These are basically just the raw symbols in the market configs.\n * - 1KWEN-PERP\n * - JitoSOL-3\n * - PT-fragSOL-15JUN25-3\n *\n * ## MarketDisplaySymbol:\n * This is the symbol we use to display the market to the user. For SPOT markets it should be the exact same as the BaseAssetDisplaySymbol, but for PERP markets they might be different which is why we have this separate type.\n *\n * - 1KWEN-PERP => 1KWEN-PERP\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n *\n * ## BaseAssetDisplaySymbol:\n * This is the symbol we use to communicate \"what asset they are holding\". For SPOT markets it should be the same as the MarketDisplaySymbol, but for PERP markets it may be different, for example we show open interest denominated in \"1KWEN\", while the market is \"1KWEN-PERP\".\n *\n * - 1KWEN-PERP => 1KWEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => fragSOL\n *\n * ## BaseAssetSymbol:\n * This is the symbol for the underlying asset for a market. I don't believe we will display this anywhere but we use these for example when looking up the market icon to use.\n *\n * - 1KWEN-PERP => WEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25 (note: PT-fragSOL has an icon different to regular fragSOL, otherwise we would use 'fragSOL' for the base asset symbol)\n */\n\ntype UISymbols = {\n\tmarketSymbol: MarketSymbol;\n\tmarketDisplaySymbol: MarketDisplaySymbol;\n\tbaseAssetSymbol: BaseAssetSymbol;\n\tbaseAssetDisplaySymbol: BaseAssetDisplaySymbol;\n};\n\nexport class UIMarket {\n\tstatic perpMarkets = PerpMarkets['mainnet-beta'];\n\tstatic spotMarkets = SpotMarkets['mainnet-beta'];\n\tprivate static cache = new Map<string, UIMarket>();\n\n\treadonly market: SpotMarketConfig | PerpMarketConfig;\n\treadonly marketId: MarketId;\n\n\tprivate _uiSymbols: UISymbols;\n\n\tget uiSymbols() {\n\t\treturn this._uiSymbols;\n\t}\n\n\tprivate set uiSymbols(uiSymbols: UISymbols) {\n\t\tthis._uiSymbols = uiSymbols;\n\t}\n\n\tconstructor(readonly marketIndex: number, readonly marketType: MarketType) {\n\t\tconst marketId = new MarketId(marketIndex, marketType);\n\t\tconst perpMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.perpMarkets\n\t\t\t: Config.perpMarketsLookup;\n\t\tconst spotMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.spotMarkets\n\t\t\t: Config.spotMarketsLookup;\n\t\tconst markets = marketId.isPerp ? perpMarkets : spotMarkets;\n\n\t\t//@ts-ignore\n\t\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\t\t// TODO: should we purposely throw an error here? Or construct a default market?\n\t\tinvariant(\n\t\t\tmarket,\n\t\t\t`Market not found for type: ${marketId.marketTypeStr}, market index: ${marketIndex}`\n\t\t);\n\n\t\tthis.marketId = marketId;\n\t\tthis.market = market;\n\n\t\tthis.setUiSymbols();\n\t}\n\n\tstatic setPerpMarkets(perpMarkets: PerpMarketConfig[]) {\n\t\tthis.perpMarkets = perpMarkets;\n\t}\n\n\tstatic setSpotMarkets(spotMarkets: SpotMarketConfig[]) {\n\t\tthis.spotMarkets = spotMarkets;\n\t}\n\n\tprivate static getOrCreate(marketIndex: number, marketType: MarketType) {\n\t\tconst key = MarketId.key(marketIndex, marketType);\n\t\tif (UIMarket.cache.has(key)) {\n\t\t\treturn UIMarket.cache.get(key)!;\n\t\t}\n\t\tconst market = new UIMarket(marketIndex, marketType);\n\t\tUIMarket.cache.set(key, market);\n\t\treturn market;\n\t}\n\n\tstatic createSpotMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.SPOT);\n\t}\n\n\tstatic createPerpMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.PERP);\n\t}\n\n\tstatic fromMarketId(marketId: MarketId) {\n\t\treturn UIMarket.getOrCreate(marketId.marketIndex, marketId.marketType);\n\t}\n\n\tstatic checkIsPredictionMarket(marketConfig: PerpMarketConfig) {\n\t\tif (!(marketConfig as PerpMarketConfig).category) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (\n\t\t\t(marketConfig as PerpMarketConfig).category?.includes('Prediction') ??\n\t\t\tfalse\n\t\t);\n\t}\n\n\tget isSpot() {\n\t\treturn this.marketId.isSpot;\n\t}\n\n\tget isPerp() {\n\t\treturn this.marketId.isPerp;\n\t}\n\n\tget marketTypeStr() {\n\t\treturn this.marketId.marketTypeStr;\n\t}\n\n\tget key() {\n\t\treturn this.marketId.key;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketDisplaySymbol instead\n\tget marketName() {\n\t\treturn `${this.market.symbol}${this.isSpot ? '/USDC' : ''}`;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketSymbol instead\n\tget symbol() {\n\t\treturn this.market.symbol;\n\t}\n\n\tget isUsdcMarket() {\n\t\treturn this.isSpot && this.marketIndex === USDC_SPOT_MARKET_INDEX;\n\t}\n\n\tget isStableCoinMarket() {\n\t\treturn (\n\t\t\tthis.isSpot &&\n\t\t\tENUM_UTILS.match(this.market.oracleSource, OracleSource.PYTH_STABLE_COIN)\n\t\t);\n\t}\n\n\tget isPredictionMarket() {\n\t\treturn (\n\t\t\tthis.isPerp &&\n\t\t\tUIMarket.checkIsPredictionMarket(this.market as PerpMarketConfig)\n\t\t);\n\t}\n\n\tget precision() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precision;\n\t\t}\n\t}\n\n\tget precisionExp() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION_EXP;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precisionExp;\n\t\t}\n\t}\n\n\tequals(other: UIMarket) {\n\t\treturn this.marketId.equals(other.marketId);\n\t}\n\n\t// @deprecated : Use uiSymbols.baseAssetSymbol instead\n\tbaseAssetSymbol(removePrefix = false) {\n\t\tlet baseAssetSymbol = this.isPerp\n\t\t\t? (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t: this.market.symbol;\n\n\t\tif (removePrefix) {\n\t\t\tbaseAssetSymbol = baseAssetSymbol.replace('1K', '').replace('1M', '');\n\t\t}\n\n\t\treturn baseAssetSymbol;\n\t}\n\n\tprotected setUiSymbols() {\n\t\tinvariant(this.marketId, 'MarketId not set');\n\n\t\tconst marketSymbol = this.getMarketSymbol();\n\t\tconst marketDisplaySymbol = this.getMarketDisplaySymbol();\n\t\tconst baseAssetSymbol = this.getBaseAssetSymbol();\n\t\tconst baseAssetDisplaySymbol = this.getBaseAssetDisplaySymbol();\n\n\t\tthis.uiSymbols = {\n\t\t\tmarketSymbol,\n\t\t\tmarketDisplaySymbol,\n\t\t\tbaseAssetSymbol,\n\t\t\tbaseAssetDisplaySymbol,\n\t\t};\n\t}\n\n\tprivate getMarketSymbol(): MarketSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t} else {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t}\n\t}\n\n\tprivate getMarketDisplaySymbol(): MarketDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase MAIN_POOL_ID:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t\tcase JLP_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase LST_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n\t\t\t\t\tPT-kySOL-10JUL25-3 => PT-kySOL-10JUL25\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.slice(\n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\tmarketConfig.symbol.lastIndexOf('-')\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as MarketDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tcase SACRED_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getBaseAssetSymbol(): BaseAssetSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t\t.replace('1K', '')\n\t\t\t\t.replace('1M', '') as BaseAssetSymbol;\n\t\t} else {\n\t\t\treturn this.getMarketDisplaySymbol() as unknown as BaseAssetSymbol; // Currently no cases where SPOT baseAssetSymbol is different from marketDisplaySymbol\n\t\t}\n\t}\n\n\tprivate getBaseAssetDisplaySymbol(): BaseAssetDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig)\n\t\t\t\t.baseAssetSymbol as BaseAssetDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => fragSOL\n\t\t\t\t\tPT-kySOL-10JUL25-3 => kySOL\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.split('-')[1]\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as BaseAssetDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as BaseAssetDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { PerpMarketAccount, SpotMarketAccount } from "@drift-labs/sdk";
1
+ import { PerpMarketAccount, SpotMarketAccount } from '@drift-labs/sdk';
2
2
  /**
3
3
  * Converts a size and precision exponent to the number of decimals in the size.
4
4
  * Size can refer to the step size or the tick size of a market.
@@ -1 +1 @@
1
- {"version":3,"file":"precisions.js","sourceRoot":"","sources":["../../../src/utils/markets/precisions.ts"],"names":[],"mappings":";;;AAAA,yCAA4H;AAE5H;;;GAGG;AACI,MAAM,mBAAmB,GAAG,CAAC,IAAQ,EAAE,YAAgB,EAAE,EAAE;IAChE,MAAM,aAAa,GAAG,YAAM,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,WAAW,EAAE,CAAC;IACpE,IAAI,aAAa,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAChC,OAAO,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC5C,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B;AAEK,MAAM,kBAAkB,GAAG,CAAC,iBAAoC,EAAE,EAAE;IACzE,MAAM,QAAQ,GAAG,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC;IACrD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC;IAErD,OAAO;QACL,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,wBAAkB,CAAC;QACnE,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,yBAAmB,CAAC;KACrE,CAAC;AACJ,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B;AAEK,MAAM,kBAAkB,GAAG,CAAC,iBAAoC,EAAE,EAAE;IACzE,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,CAAC;IACjD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,CAAC;IAEjD,OAAO;QACL,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,wBAAkB,CAAC;QACnE,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,yBAAmB,CAAC;KACrE,CAAC;AACJ,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B","sourcesContent":["import { BASE_PRECISION_EXP, BigNum, BN, PerpMarketAccount, QUOTE_PRECISION_EXP, SpotMarketAccount } from \"@drift-labs/sdk\";\n\n/**\n * Converts a size and precision exponent to the number of decimals in the size.\n * Size can refer to the step size or the tick size of a market.\n */\nexport const getDecimalsFromSize = (size: BN, precisionExp: BN) => {\n const formattedSize = BigNum.from(size, precisionExp).prettyPrint();\n if (formattedSize.includes('.')) {\n return formattedSize.split('.')[1].length;\n }\n return 0;\n};\n\nexport const getPerpMarketSizes = (perpMarketAccount: PerpMarketAccount) => {\n const stepSize = perpMarketAccount.amm.orderStepSize;\n const tickSize = perpMarketAccount.amm.orderTickSize;\n\n return {\n stepSizeDecimals: getDecimalsFromSize(stepSize, BASE_PRECISION_EXP),\n tickSizeDecimals: getDecimalsFromSize(tickSize, QUOTE_PRECISION_EXP),\n };\n};\n\nexport const getSpotMarketSizes = (spotMarketAccount: SpotMarketAccount) => {\n const stepSize = spotMarketAccount.orderStepSize;\n const tickSize = spotMarketAccount.orderTickSize;\n\n return {\n stepSizeDecimals: getDecimalsFromSize(stepSize, BASE_PRECISION_EXP),\n tickSizeDecimals: getDecimalsFromSize(tickSize, QUOTE_PRECISION_EXP),\n };\n};"]}
1
+ {"version":3,"file":"precisions.js","sourceRoot":"","sources":["../../../src/utils/markets/precisions.ts"],"names":[],"mappings":";;;AAAA,yCAOyB;AAEzB;;;GAGG;AACI,MAAM,mBAAmB,GAAG,CAAC,IAAQ,EAAE,YAAgB,EAAE,EAAE;IACjE,MAAM,aAAa,GAAG,YAAM,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,WAAW,EAAE,CAAC;IACpE,IAAI,aAAa,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACjC,OAAO,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3C,CAAC;IACD,OAAO,CAAC,CAAC;AACV,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B;AAEK,MAAM,kBAAkB,GAAG,CAAC,iBAAoC,EAAE,EAAE;IAC1E,MAAM,QAAQ,GAAG,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC;IACrD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC;IAErD,OAAO;QACN,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,wBAAkB,CAAC;QACnE,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,yBAAmB,CAAC;KACpE,CAAC;AACH,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B;AAEK,MAAM,kBAAkB,GAAG,CAAC,iBAAoC,EAAE,EAAE;IAC1E,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,CAAC;IACjD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,CAAC;IAEjD,OAAO;QACN,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,wBAAkB,CAAC;QACnE,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,yBAAmB,CAAC;KACpE,CAAC;AACH,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBigNum,\n\tBN,\n\tPerpMarketAccount,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n} from '@drift-labs/sdk';\n\n/**\n * Converts a size and precision exponent to the number of decimals in the size.\n * Size can refer to the step size or the tick size of a market.\n */\nexport const getDecimalsFromSize = (size: BN, precisionExp: BN) => {\n\tconst formattedSize = BigNum.from(size, precisionExp).prettyPrint();\n\tif (formattedSize.includes('.')) {\n\t\treturn formattedSize.split('.')[1].length;\n\t}\n\treturn 0;\n};\n\nexport const getPerpMarketSizes = (perpMarketAccount: PerpMarketAccount) => {\n\tconst stepSize = perpMarketAccount.amm.orderStepSize;\n\tconst tickSize = perpMarketAccount.amm.orderTickSize;\n\n\treturn {\n\t\tstepSizeDecimals: getDecimalsFromSize(stepSize, BASE_PRECISION_EXP),\n\t\ttickSizeDecimals: getDecimalsFromSize(tickSize, QUOTE_PRECISION_EXP),\n\t};\n};\n\nexport const getSpotMarketSizes = (spotMarketAccount: SpotMarketAccount) => {\n\tconst stepSize = spotMarketAccount.orderStepSize;\n\tconst tickSize = spotMarketAccount.orderTickSize;\n\n\treturn {\n\t\tstepSizeDecimals: getDecimalsFromSize(stepSize, BASE_PRECISION_EXP),\n\t\ttickSizeDecimals: getDecimalsFromSize(tickSize, QUOTE_PRECISION_EXP),\n\t};\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/common",
3
- "version": "1.0.23",
3
+ "version": "1.0.25",
4
4
  "description": "Common functions for Drift",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",