@drift-labs/common 1.0.22 → 1.0.24

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.
@@ -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
3
  export declare const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 20;
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;
@@ -26,13 +50,34 @@ export interface ComputeIsolatedPositionDepositParams {
26
50
  */
27
51
  numOfOpenHighLeverageSpots?: number;
28
52
  /**
29
- * Whether to use the buffer for the isolated position deposit.
53
+ * Optional buffer denominator for the isolated position deposit.
54
+ *
55
+ * Smaller numbers mean a bigger buffer.
56
+ *
57
+ * bufferDenominator -> Buffer %
58
+ *
59
+ * 15 -> 6.67%
60
+ *
61
+ * 20 (default) -> 5.00%
62
+ *
63
+ * 50 -> 2.00%
64
+ *
65
+ * 100 -> 1.00%
66
+ *
67
+ * 180 -> 0.56%
68
+ *
69
+ * 200 -> 0.50%
70
+ */
71
+ bufferDenominator?: number;
72
+ /**
73
+ * If true, the current market's initial margin shortfall (if any)
74
+ * will be added to the deposit amount.
30
75
  */
31
- bufferBpsDenominator?: number;
76
+ includeExistingShortfall?: boolean;
32
77
  }
33
78
  /**
34
79
  * Computes the isolated position deposit required for opening an isolated perp position.
35
80
  * Returns a BN in QUOTE_PRECISION (USDC).
36
81
  */
37
- export declare function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferBpsDenominator, }: ComputeIsolatedPositionDepositParams): BN | null;
82
+ export declare function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferDenominator, includeExistingShortfall, }: ComputeIsolatedPositionDepositParams): BN | null;
38
83
  export declare function getIsolatedPositionDepositIxIfNeeded(driftClient: DriftClient, user: User, marketIndex: number, isolatedPositionDeposit?: BN, signingAuthority?: PublicKey): Promise<TransactionInstruction | undefined>;
@@ -1,13 +1,67 @@
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
5
  exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 20;
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 && marketIndex === excludeMarketIndex) {
45
+ continue;
46
+ }
47
+ result.push({ marketIndex, shortfall });
48
+ }
49
+ return result;
50
+ }
51
+ exports.getOtherIsolatedMarginShortfalls = getOtherIsolatedMarginShortfalls;
52
+ /**
53
+ * Computes the total of all isolated margin shortfalls.
54
+ */
55
+ function getTotalIsolatedMarginShortfall(user, excludeMarketIndex) {
56
+ const shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);
57
+ return shortfalls.reduce((acc, s) => acc.add(s.shortfall), sdk_1.ZERO);
58
+ }
59
+ exports.getTotalIsolatedMarginShortfall = getTotalIsolatedMarginShortfall;
6
60
  /**
7
61
  * Computes the isolated position deposit required for opening an isolated perp position.
8
62
  * Returns a BN in QUOTE_PRECISION (USDC).
9
63
  */
10
- function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferBpsDenominator, }) {
64
+ function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex, baseAssetAmount, direction, marginRatio, entryPrice, numOfOpenHighLeverageSpots, bufferDenominator, includeExistingShortfall, }) {
11
65
  var _a;
12
66
  // Only require isolated deposit if the order will increase the position (when direction is provided)
13
67
  if (direction !== undefined) {
@@ -28,7 +82,17 @@ function computeIsolatedPositionDepositForTrade({ driftClient, user, marketIndex
28
82
  const hasOpenHighLeverageSpots = numOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;
29
83
  const enteringHighLeverageMode = userIsInHighLeverageMode || hasOpenHighLeverageSpots;
30
84
  const marginRequired = (0, sdk_1.calculateMarginUSDCRequiredForTrade)(driftClient, marketIndex, baseAssetAmount, marginRatio, enteringHighLeverageMode, entryPrice);
31
- return marginRequired.add(marginRequired.div(new sdk_1.BN(bufferBpsDenominator !== null && bufferBpsDenominator !== void 0 ? bufferBpsDenominator : exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS))); // buffer in basis points
85
+ 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
86
+ // Add existing shortfall for this market if requested
87
+ if (includeExistingShortfall) {
88
+ const existingShortfall = getIsolatedMarginShortfall(user, marketIndex);
89
+ if (existingShortfall.gt(sdk_1.ZERO)) {
90
+ // Add shortfall with a 5% buffer on top (same as new margin)
91
+ const shortfallWithBuffer = existingShortfall.add(existingShortfall.div(new sdk_1.BN(bufferDenominator !== null && bufferDenominator !== void 0 ? bufferDenominator : exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)));
92
+ depositAmount = depositAmount.add(shortfallWithBuffer);
93
+ }
94
+ }
95
+ return depositAmount;
32
96
  }
33
97
  exports.computeIsolatedPositionDepositForTrade = computeIsolatedPositionDepositForTrade;
34
98
  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;AAgCvD;;;GAGG;AACH,SAAgB,sCAAsC,CAAC,EACtD,WAAW,EACX,IAAI,EACJ,WAAW,EACX,eAAe,EACf,SAAS,EACT,WAAW,EACX,UAAU,EACV,0BAA0B,EAC1B,oBAAoB,GACkB;;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,oBAAoB,aAApB,oBAAoB,cAApB,oBAAoB,GAAI,4CAAoC,CAAC,CACpE,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 * Whether to use the buffer for the isolated position deposit.\n\t */\n\tbufferBpsDenominator?: 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\tbufferBpsDenominator,\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(bufferBpsDenominator ?? 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,WAAW,EACX,YAAY,EACZ,IAAI,UAAU,CAAC,0BAA0B,EAAE,CAAC;QAC5C,MAAM,SAAS,GAAG,YAAY,CAAC,cAAc,EAAE,CAAC;QAChD,IAAI,SAAS,CAAC,EAAE,CAAC,UAAI,CAAC,EAAE,CAAC;YACxB,UAAU,CAAC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AW,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 = 20;\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 (excludeMarketIndex !== undefined && marketIndex === excludeMarketIndex) {\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;IACxC,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACxD,WAAW;QACX,IAAI;QACJ,SAAS;QACT,WAAW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,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,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,SA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,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,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;IACrE,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,WAAW,C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AyB,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;IACrE,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,gBAAgB,CACtD,WAAW,EACX,SAAS,EACT;QACC,SAAS,EAAE,kBAAkB;KAC7B,CACD,CAAC;IACF,OAAO,YAAY,CAAC;AACrB,CAAC,CAAC;AA1BW,QAAA,sCAAsC,0CA0BjD;AAEF;;;;;;GAMG;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ient,\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/common",
3
- "version": "1.0.22",
3
+ "version": "1.0.24",
4
4
  "description": "Common functions for Drift",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",