@drift-labs/common 1.0.46 → 1.0.48

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.
Files changed (31) hide show
  1. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -4
  2. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  3. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +4 -2
  4. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
  5. package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +5 -3
  6. package/lib/drift/Drift/clients/CentralServerDrift/index.js +40 -46
  7. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  8. package/lib/drift/Drift/clients/CentralServerDrift/types.d.ts +27 -10
  9. package/lib/drift/Drift/clients/CentralServerDrift/types.js.map +1 -1
  10. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.d.ts +56 -1
  11. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +102 -4
  12. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
  13. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +26 -14
  14. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +88 -18
  15. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  16. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +26 -8
  17. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +90 -21
  18. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  19. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +55 -0
  20. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +60 -25
  21. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  22. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +10 -6
  23. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
  24. package/lib/drift/base/details/user/positionMarginMode.d.ts +8 -0
  25. package/lib/drift/base/details/user/positionMarginMode.js +18 -0
  26. package/lib/drift/base/details/user/positionMarginMode.js.map +1 -0
  27. package/lib/drift/cli.js +65 -56
  28. package/lib/drift/cli.js.map +1 -1
  29. package/lib/drift/utils/orderParams.d.ts +1 -1
  30. package/lib/drift/utils/orderParams.js.map +1 -1
  31. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createOpenPerpNonMarketOrder = exports.createOpenPerpNonMarketOrderTxn = exports.createSwiftLimitOrder = exports.createOpenPerpNonMarketOrderIxs = exports.createMultipleOpenPerpNonMarketOrderIx = void 0;
3
+ exports.createOpenPerpNonMarketOrder = exports.createOpenPerpNonMarketOrderTxn = exports.createSwiftLimitOrderMessage = exports.createSwiftLimitOrder = exports.createOpenPerpNonMarketOrderIxs = exports.createMultipleOpenPerpNonMarketOrderIx = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
5
  const openSwiftOrder_1 = require("../openSwiftOrder");
6
6
  const orderParams_1 = require("../../../../../utils/orderParams");
@@ -10,6 +10,7 @@ const openPerpMarketOrder_1 = require("../openPerpMarketOrder");
10
10
  const positionMaxLeverage_1 = require("../positionMaxLeverage");
11
11
  const auction_1 = require("../auction");
12
12
  const isolatedPositionDeposit_1 = require("../isolatedPositionDeposit");
13
+ // TODO: add isolated margin?
13
14
  /**
14
15
  * Creates a transaction instruction to open multiple non-market orders.
15
16
  */
@@ -34,7 +35,7 @@ exports.createMultipleOpenPerpNonMarketOrderIx = createMultipleOpenPerpNonMarket
34
35
  */
35
36
  const createOpenPerpNonMarketOrderIxs = async (params) => {
36
37
  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, additionalIsolatedPositionDeposits, mainSignerOverride, highLeverageOptions, } = params;
38
+ const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, marginMode, mainSignerOverride, highLeverageOptions, isolatedPositionDepositsOverride, } = params;
38
39
  // Support both new (amount + assetType) and legacy (baseAssetAmount) approaches
39
40
  const finalBaseAssetAmount = (0, orderParams_1.resolveBaseAssetAmount)({
40
41
  amount: 'amount' in params ? params.amount : undefined,
@@ -47,23 +48,37 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
47
48
  if (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {
48
49
  throw new Error('Final base asset amount must be greater than zero');
49
50
  }
51
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(isolatedPositionDepositsOverride, {
52
+ driftClient,
53
+ user,
54
+ marketIndex,
55
+ baseAssetAmount: finalBaseAssetAmount,
56
+ direction,
57
+ positionMaxLeverage,
58
+ marginMode,
59
+ replenishUnderwaterPositions: true,
60
+ numOfOpenHighLeverageSpots: highLeverageOptions === null || highLeverageOptions === void 0 ? void 0 : highLeverageOptions.numOfOpenHighLeverageSpots,
61
+ });
62
+ const mainIsolatedPositionDeposit = resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit;
63
+ const resolvedAdditionalDeposits = resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.additionalIsolatedPositionDeposits;
50
64
  const allOrders = [];
51
65
  const allIxs = [];
52
- const leverageIx = await (0, positionMaxLeverage_1.getPositionMaxLeverageIxIfNeeded)(driftClient, user, marketIndex, positionMaxLeverage, mainSignerOverride);
66
+ // Fetch all deposit/leverage ixs in parallel
67
+ const [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] = await Promise.all([
68
+ (0, positionMaxLeverage_1.getPositionMaxLeverageIxIfNeeded)(driftClient, user, marketIndex, positionMaxLeverage, mainSignerOverride),
69
+ (resolvedAdditionalDeposits === null || resolvedAdditionalDeposits === void 0 ? void 0 : resolvedAdditionalDeposits.length)
70
+ ? Promise.all(resolvedAdditionalDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride)))
71
+ : Promise.resolve([]),
72
+ (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, mainIsolatedPositionDeposit, mainSignerOverride),
73
+ ]);
53
74
  if (leverageIx) {
54
75
  allIxs.push(leverageIx);
55
76
  }
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
- }
77
+ for (const ix of additionalDepositIxs) {
78
+ if (ix) {
79
+ allIxs.push(ix);
64
80
  }
65
81
  }
66
- const isolatedPositionDepositIx = await (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, isolatedPositionDeposit, mainSignerOverride);
67
82
  if (isolatedPositionDepositIx) {
68
83
  allIxs.push(isolatedPositionDepositIx);
69
84
  }
@@ -126,7 +141,6 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
126
141
  reduceOnly,
127
142
  postOnly,
128
143
  userOrderId,
129
- positionMaxLeverage,
130
144
  });
131
145
  const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
132
146
  orderParams.bitFlags = bitFlags;
@@ -147,7 +161,6 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
147
161
  limitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,
148
162
  },
149
163
  reduceOnly: (_f = orderConfig.bracketOrders.takeProfit.reduceOnly) !== null && _f !== void 0 ? _f : true,
150
- positionMaxLeverage,
151
164
  });
152
165
  allOrders.push(takeProfitParams);
153
166
  }
@@ -163,7 +176,6 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
163
176
  limitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,
164
177
  },
165
178
  reduceOnly: (_j = orderConfig.bracketOrders.stopLoss.reduceOnly) !== null && _j !== void 0 ? _j : true,
166
- positionMaxLeverage,
167
179
  });
168
180
  allOrders.push(stopLossParams);
169
181
  }
@@ -176,14 +188,17 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
176
188
  return allIxs;
177
189
  };
178
190
  exports.createOpenPerpNonMarketOrderIxs = createOpenPerpNonMarketOrderIxs;
179
- const createSwiftLimitOrder = async (params) => {
180
- var _a, _b, _c;
181
- const { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;
191
+ /**
192
+ * Shared prep logic for swift limit orders: validates limit price, resolves base asset amount,
193
+ * computes order params (with or without limit auction), and resolves the user account.
194
+ */
195
+ async function prepSwiftLimitOrderData(params) {
196
+ var _a;
197
+ const { user, marketIndex, orderConfig } = params;
182
198
  const limitPrice = orderConfig.limitPrice;
183
199
  if (limitPrice.isZero()) {
184
200
  throw new Error('LIMIT orders require limitPrice');
185
201
  }
186
- // Support both new (amount + assetType) and legacy (baseAssetAmount) approaches
187
202
  const finalBaseAssetAmount = (0, orderParams_1.resolveBaseAssetAmount)({
188
203
  amount: 'amount' in params ? params.amount : undefined,
189
204
  assetType: 'assetType' in params ? params.assetType : undefined,
@@ -206,9 +221,25 @@ const createSwiftLimitOrder = async (params) => {
206
221
  reduceOnly: params.reduceOnly,
207
222
  postOnly: params.postOnly,
208
223
  userOrderId: params.userOrderId,
209
- positionMaxLeverage: params.positionMaxLeverage, // TODO: this isn't referenced in the function... do we need it?
210
224
  });
211
225
  const userAccount = user.getUserAccount();
226
+ return { userAccount, orderParams };
227
+ }
228
+ const createSwiftLimitOrder = async (params) => {
229
+ var _a, _b, _c;
230
+ const { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;
231
+ const { userAccount, orderParams } = await prepSwiftLimitOrderData(params);
232
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(params.isolatedPositionDepositsOverride, {
233
+ driftClient,
234
+ user,
235
+ marketIndex,
236
+ baseAssetAmount: orderParams.baseAssetAmount,
237
+ direction: orderParams.direction,
238
+ positionMaxLeverage: params.positionMaxLeverage,
239
+ marginMode: params.marginMode,
240
+ replenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions
241
+ numOfOpenHighLeverageSpots: (_a = params.highLeverageOptions) === null || _a === void 0 ? void 0 : _a.numOfOpenHighLeverageSpots,
242
+ });
212
243
  await (0, openSwiftOrder_1.prepSignAndSendSwiftOrder)({
213
244
  driftClient,
214
245
  subAccountId: userAccount.subAccountId,
@@ -221,12 +252,50 @@ const createSwiftLimitOrder = async (params) => {
221
252
  takeProfit: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.takeProfit,
222
253
  stopLoss: (_c = orderConfig.bracketOrders) === null || _c === void 0 ? void 0 : _c.stopLoss,
223
254
  positionMaxLeverage: params.positionMaxLeverage,
224
- isolatedPositionDeposit: params.isolatedPositionDeposit,
255
+ isolatedPositionDeposit: resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit,
225
256
  },
226
257
  builderParams: params.builderParams,
227
258
  });
228
259
  };
229
260
  exports.createSwiftLimitOrder = createSwiftLimitOrder;
261
+ /**
262
+ * Prepares a Swift limit order message without signing or sending it.
263
+ *
264
+ * @returns The prepared SwiftOrderMessage ready for client-side signing and sending
265
+ */
266
+ const createSwiftLimitOrderMessage = async (params) => {
267
+ var _a, _b, _c;
268
+ const { driftClient, user, marketIndex, orderConfig, isDelegate = false, userSigningSlotBuffer, } = params;
269
+ const { userAccount, orderParams } = await prepSwiftLimitOrderData(params);
270
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(params.isolatedPositionDepositsOverride, {
271
+ driftClient,
272
+ user,
273
+ marketIndex,
274
+ baseAssetAmount: orderParams.baseAssetAmount,
275
+ direction: orderParams.direction,
276
+ positionMaxLeverage: params.positionMaxLeverage,
277
+ marginMode: params.marginMode,
278
+ replenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions
279
+ numOfOpenHighLeverageSpots: (_a = params.highLeverageOptions) === null || _a === void 0 ? void 0 : _a.numOfOpenHighLeverageSpots,
280
+ });
281
+ return (0, openSwiftOrder_1.prepSwiftOrderMessage)({
282
+ driftClient,
283
+ subAccountId: userAccount.subAccountId,
284
+ userAccountPubKey: user.userAccountPublicKey,
285
+ marketIndex,
286
+ userSigningSlotBuffer,
287
+ isDelegate,
288
+ orderParams: {
289
+ main: orderParams,
290
+ takeProfit: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.takeProfit,
291
+ stopLoss: (_c = orderConfig.bracketOrders) === null || _c === void 0 ? void 0 : _c.stopLoss,
292
+ positionMaxLeverage: params.positionMaxLeverage,
293
+ isolatedPositionDeposit: resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit,
294
+ },
295
+ builderParams: params.builderParams,
296
+ });
297
+ };
298
+ exports.createSwiftLimitOrderMessage = createSwiftLimitOrderMessage;
230
299
  const createOpenPerpNonMarketOrderTxn = async (params) => {
231
300
  const { driftClient } = params;
232
301
  const instructions = await (0, exports.createOpenPerpNonMarketOrderIxs)(params);
@@ -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;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;AACI,MAAM,+BAA+B,GAAG,KAAK,EACnD,MAAwC,EACJ,EAAE;;IACtC,MAAM,EACL,WAAW,EACX,IAAI,EACJ,WAAW,EACX,SAAS,EACT,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,EACX,WAAW,GAAG,CAAC,EACf,mBAAmB,EACnB,uBAAuB,EACvB,kCAAkC,EAClC,kBAAkB,EAClB,mBAAmB,GACnB,GAAG,MAAM,CAAC;IACX,gFAAgF;IAChF,MAAM,oBAA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,CAAC,CAAC;IAEnE,MAAM,yBAAyB,GAAG,MAAM,WAAW,CAAC,gBAAgB,CACnE,YAAY,EACZ,MAAM,CAAC,QAAQ,CACf,CAAC;IAEF,OAAO,yBAAyB,CAAC;AAClC,CAAC,CAAC;AAbW,QAAA,+BAA+B,mCAa1C;AAEK,MAAM,4BAA4B,GAAG,KAAK,EAChD,MAAyE,EAC1C,EAAE;IACjC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;IAEvD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,WAAW,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC/D,CAAC;QAED,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAA,6BAAqB,EAAC;YACpD,GAAG,MAAM;YACT,YAAY;YACZ,WAAW;SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AA3BW,QAAA,4BAA4B,gCA2BvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\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"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,sDAK2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,uEAG2C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,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\tprepSwiftOrderMessage,\n\tSwiftOrderOptions,\n\tSwiftOrderMessage,\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\tIsolatedPositionDepositsOverride,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\nimport {\n\tgetIsolatedPositionDepositIxIfNeeded,\n\tresolveIsolatedPositionDepositsWithOverride,\n} 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\t/**\n\t * Position margin mode to use for the order.\n\t * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,\n\t * and any additional isolated position deposits need to replenish under-collateralized positions.\n\t * If not provided, the position margin mode will be derived from the user's position margin mode,\n\t * and if that does not exist, it will default to 'cross'.\n\t */\n\tmarginMode?: 'isolated' | 'cross';\n\t/**\n\t * Pre-computed isolated position deposits override. When provided,\n\t * skips auto-compute and uses these values directly.\n\t */\n\tisolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;\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// TODO: add isolated margin?\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\tmarginMode,\n\t\tmainSignerOverride,\n\t\thighLeverageOptions,\n\t\tisolatedPositionDepositsOverride,\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 resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tisolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: true,\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst mainIsolatedPositionDeposit = resolvedDeposits?.mainDeposit;\n\tconst resolvedAdditionalDeposits =\n\t\tresolvedDeposits?.additionalIsolatedPositionDeposits;\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// Fetch all deposit/leverage ixs in parallel\n\tconst [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] =\n\t\tawait Promise.all([\n\t\t\tgetPositionMaxLeverageIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t\tresolvedAdditionalDeposits?.length\n\t\t\t\t? Promise.all(\n\t\t\t\t\t\tresolvedAdditionalDeposits.map((deposit) =>\n\t\t\t\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\t\t\t\tdriftClient,\n\t\t\t\t\t\t\t\tuser,\n\t\t\t\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\t\t\t\tdeposit.amount,\n\t\t\t\t\t\t\t\tmainSignerOverride\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Promise.resolve([] as (TransactionInstruction | undefined)[]),\n\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tmainIsolatedPositionDeposit,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t]);\n\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\tfor (const ix of additionalDepositIxs) {\n\t\tif (ix) {\n\t\t\tallIxs.push(ix);\n\t\t}\n\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});\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});\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});\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\n/**\n * Shared prep logic for swift limit orders: validates limit price, resolves base asset amount,\n * computes order params (with or without limit auction), and resolves the user account.\n */\nasync function prepSwiftLimitOrderData(\n\tparams: OpenPerpNonMarketOrderBaseParams & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n) {\n\tconst { user, marketIndex, 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\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 });\n\n\tconst userAccount = user.getUserAccount();\n\n\treturn { userAccount, orderParams };\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 { userAccount, orderParams } = await prepSwiftLimitOrderData(params);\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: orderParams.baseAssetAmount,\n\t\t\tdirection: orderParams.direction,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tmarginMode: params.marginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\tparams.highLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\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: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport type CreateSwiftLimitOrderMessageParams = Omit<\n\tOpenPerpNonMarketOrderBaseParams,\n\t'mainSignerOverride'\n> & {\n\torderConfig: LimitOrderParamsOrderConfig;\n\tisDelegate?: boolean;\n\tuserSigningSlotBuffer?: number;\n};\n\n/**\n * Prepares a Swift limit order message without signing or sending it.\n *\n * @returns The prepared SwiftOrderMessage ready for client-side signing and sending\n */\nexport const createSwiftLimitOrderMessage = async (\n\tparams: CreateSwiftLimitOrderMessageParams\n): Promise<SwiftOrderMessage> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\torderConfig,\n\t\tisDelegate = false,\n\t\tuserSigningSlotBuffer,\n\t} = params;\n\n\tconst { userAccount, orderParams } = await prepSwiftLimitOrderData(params);\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: orderParams.baseAssetAmount,\n\t\t\tdirection: orderParams.direction,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tmarginMode: params.marginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\tparams.highLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\treturn prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate,\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: resolvedDeposits?.mainDeposit,\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"]}
@@ -49,6 +49,33 @@ export interface SwiftOrderOptions {
49
49
  */
50
50
  source?: string;
51
51
  }
52
+ /**
53
+ * Represents a prepared SWIFT order message that is ready to be signed and sent.
54
+ * This is the output of the "prep" step, before signing occurs.
55
+ *
56
+ * Consumers should:
57
+ * 1. Sign `hexEncodedSwiftOrderMessage.uInt8Array` with the user's wallet
58
+ * 2. Send the signed message along with the other fields to the SWIFT server
59
+ */
60
+ export interface SwiftOrderMessage {
61
+ /** The encoded order message in both Uint8Array (for signing) and string (for sending) formats */
62
+ hexEncodedSwiftOrderMessage: {
63
+ uInt8Array: Uint8Array;
64
+ string: string;
65
+ };
66
+ /** The order parameters message that was encoded */
67
+ signedMsgOrderParamsMessage: SignedMsgOrderParamsMessage | SignedMsgOrderParamsDelegateMessage;
68
+ /** The slot number used for the signed message */
69
+ slotForSignedMsg: BN;
70
+ /** Unique identifier for the signed message order */
71
+ signedMsgOrderUuid: Uint8Array;
72
+ /** The market index this order is for */
73
+ marketIndex: number;
74
+ /** Number of slots till the auction ends (used for confirmation timeout) */
75
+ slotsTillAuctionEnd: number;
76
+ /** Time in milliseconds before the signing window expires */
77
+ expirationTimeMs: number;
78
+ }
52
79
  export type SwiftOrderObservable = Observable<SwiftOrderEvent>;
53
80
  interface PrepSwiftOrderParams {
54
81
  /** The Drift client instance */
@@ -134,6 +161,7 @@ export declare const prepSwiftOrder: ({ driftClient, takerUserAccount, currentSl
134
161
  signedMsgOrderParamsMessage: SignedMsgOrderParamsMessage | SignedMsgOrderParamsDelegateMessage;
135
162
  slotForSignedMsg: BN;
136
163
  signedMsgOrderUuid: Uint8Array;
164
+ resolvedUserSigningSlotBuffer: number;
137
165
  };
138
166
  /**
139
167
  * Error thrown when an auction slot has expired
@@ -220,6 +248,33 @@ interface SendSwiftOrderParams {
220
248
  *
221
249
  */
222
250
  export declare const sendSwiftOrder: ({ driftClient, marketId, hexEncodedSwiftOrderMessageString, signedMessage, signedMsgOrderUuid, takerAuthority, signingAuthority, slotsTillAuctionEnd, confirmationMultiplier, confirmationConnection, }: SendSwiftOrderParams) => SwiftOrderObservable;
251
+ type PrepSwiftOrderMessageParams = {
252
+ driftClient: DriftClient;
253
+ subAccountId: number;
254
+ userAccountPubKey: PublicKey;
255
+ marketIndex: number;
256
+ userSigningSlotBuffer: number;
257
+ isDelegate?: boolean;
258
+ orderParams: {
259
+ main: OptionalOrderParams;
260
+ takeProfit?: OptionalTriggerOrderParams;
261
+ stopLoss?: OptionalTriggerOrderParams;
262
+ positionMaxLeverage?: number;
263
+ isolatedPositionDeposit?: BN;
264
+ };
265
+ builderParams?: {
266
+ builderIdx: number;
267
+ builderFeeTenthBps: number;
268
+ };
269
+ };
270
+ /**
271
+ * Prepares a SWIFT order message without signing or sending it.
272
+ * Returns all data needed for the consumer to sign and send the order themselves.
273
+ *
274
+ * This is useful for server-side contexts (e.g., CentralServerDrift) where
275
+ * the server prepares the message but the client handles signing and sending.
276
+ */
277
+ export declare const prepSwiftOrderMessage: ({ driftClient, subAccountId, userAccountPubKey, marketIndex, userSigningSlotBuffer, isDelegate, orderParams, builderParams, }: PrepSwiftOrderMessageParams) => Promise<SwiftOrderMessage>;
223
278
  type PrepSignAndSendSwiftOrderParams = {
224
279
  driftClient: DriftClient;
225
280
  subAccountId: number;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prepSignAndSendSwiftOrder = exports.sendSwiftOrder = exports.signSwiftOrderMsg = exports.AuctionSlotExpiredError = exports.prepSwiftOrder = exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.USER_SIGNING_MESSAGE_BUFFER_SLOTS = void 0;
3
+ exports.prepSignAndSendSwiftOrder = exports.prepSwiftOrderMessage = exports.sendSwiftOrder = exports.signSwiftOrderMsg = exports.AuctionSlotExpiredError = exports.prepSwiftOrder = exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.USER_SIGNING_MESSAGE_BUFFER_SLOTS = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
5
  const sdk_2 = require("@drift-labs/sdk");
6
6
  const utils_1 = require("../../../../../../utils");
@@ -100,6 +100,7 @@ const prepSwiftOrder = ({ driftClient, takerUserAccount, currentSlot, isDelegate
100
100
  signedMsgOrderParamsMessage,
101
101
  slotForSignedMsg: auctionStartSlot,
102
102
  signedMsgOrderUuid,
103
+ resolvedUserSigningSlotBuffer: userSigningSlotBuffer,
103
104
  };
104
105
  };
105
106
  exports.prepSwiftOrder = prepSwiftOrder;
@@ -185,42 +186,76 @@ const sendSwiftOrder = ({ driftClient, marketId, hexEncodedSwiftOrderMessageStri
185
186
  };
186
187
  exports.sendSwiftOrder = sendSwiftOrder;
187
188
  /**
188
- * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.
189
- * Callbacks can be provided to handle the events of the Swift order.
190
- * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).
189
+ * Computes the timing parameters for a SWIFT order:
190
+ * - slotsTillAuctionEnd: how many slots until the auction is considered ended
191
+ * - expirationTimeMs: how long (in ms) the user has to sign before the window expires
192
+ *
193
+ * For market orders, auction duration + signing buffer is used directly.
194
+ * For non-market orders, a minimum is enforced because limit auctions can have
195
+ * very small durations but the order is still valid after the auction ends.
191
196
  */
192
- const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccountPubKey, marketIndex, userSigningSlotBuffer, swiftOptions, orderParams, builderParams, confirmationMultiplier, }) => {
193
- var _a, _b, _c, _d, _e, _f;
197
+ const computeSwiftOrderTiming = (mainOrderParams, userSigningSlotBuffer) => {
198
+ const isMarketOrder = utils_1.ENUM_UTILS.match(mainOrderParams.orderType, sdk_1.OrderType.ORACLE) ||
199
+ utils_1.ENUM_UTILS.match(mainOrderParams.orderType, sdk_1.OrderType.MARKET);
200
+ const slotsTillAuctionEnd = mainOrderParams.auctionDuration
201
+ ? isMarketOrder
202
+ ? userSigningSlotBuffer + mainOrderParams.auctionDuration
203
+ : Math.max(exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS, userSigningSlotBuffer + mainOrderParams.auctionDuration)
204
+ : exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;
205
+ const expirationTimeMs = Math.max(slotsTillAuctionEnd - exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS, exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS) * sdk_1.SLOT_TIME_ESTIMATE_MS;
206
+ return { slotsTillAuctionEnd, expirationTimeMs };
207
+ };
208
+ /**
209
+ * Prepares a SWIFT order message without signing or sending it.
210
+ * Returns all data needed for the consumer to sign and send the order themselves.
211
+ *
212
+ * This is useful for server-side contexts (e.g., CentralServerDrift) where
213
+ * the server prepares the message but the client handles signing and sending.
214
+ */
215
+ const prepSwiftOrderMessage = async ({ driftClient, subAccountId, userAccountPubKey, marketIndex, userSigningSlotBuffer, isDelegate = false, orderParams, builderParams, }) => {
194
216
  const currentSlot = await driftClient.connection.getSlot('confirmed');
195
- const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage, } = (0, exports.prepSwiftOrder)({
217
+ const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage, slotForSignedMsg, resolvedUserSigningSlotBuffer, } = (0, exports.prepSwiftOrder)({
196
218
  driftClient,
197
219
  takerUserAccount: {
198
220
  pubKey: userAccountPubKey,
199
- subAccountId: subAccountId,
221
+ subAccountId,
200
222
  },
201
223
  currentSlot,
202
- isDelegate: swiftOptions.isDelegate || false,
224
+ isDelegate,
203
225
  orderParams,
204
226
  userSigningSlotBuffer,
205
227
  builderParams,
206
228
  });
229
+ const { slotsTillAuctionEnd, expirationTimeMs } = computeSwiftOrderTiming(orderParams.main, resolvedUserSigningSlotBuffer);
230
+ return {
231
+ hexEncodedSwiftOrderMessage,
232
+ signedMsgOrderParamsMessage,
233
+ slotForSignedMsg,
234
+ signedMsgOrderUuid,
235
+ marketIndex,
236
+ slotsTillAuctionEnd,
237
+ expirationTimeMs,
238
+ };
239
+ };
240
+ exports.prepSwiftOrderMessage = prepSwiftOrderMessage;
241
+ /**
242
+ * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.
243
+ * Callbacks can be provided to handle the events of the Swift order.
244
+ * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).
245
+ */
246
+ const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccountPubKey, marketIndex, userSigningSlotBuffer, swiftOptions, orderParams, builderParams, confirmationMultiplier, }) => {
247
+ var _a, _b, _c, _d, _e, _f;
248
+ const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage, slotsTillAuctionEnd, expirationTimeMs, } = await (0, exports.prepSwiftOrderMessage)({
249
+ driftClient,
250
+ subAccountId,
251
+ userAccountPubKey,
252
+ marketIndex,
253
+ userSigningSlotBuffer,
254
+ isDelegate: swiftOptions.isDelegate || false,
255
+ orderParams,
256
+ builderParams,
257
+ });
207
258
  (_b = (_a = swiftOptions.callbacks) === null || _a === void 0 ? void 0 : _a.onOrderParamsMessagePrepped) === null || _b === void 0 ? void 0 : _b.call(_a, signedMsgOrderParamsMessage);
208
- // both market and non-market orders can have auction durations.
209
- //
210
- // for market orders, the auction duration + user signing slot buffer is a good gauge for slots until auction end
211
- //
212
- // for non-market orders, if they have an auction duration, we use the maximum of MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS
213
- // and the (auction duration + user signing slot buffer). This is because limit auctions can have very small auction durations,
214
- // but the limit order is still valid to be placed even after the auction ends, hence we enforce a minimum duration so that
215
- // short limit auction durations can still be placed
216
- const isMarketOrder = utils_1.ENUM_UTILS.match(orderParams.main.orderType, sdk_1.OrderType.ORACLE) ||
217
- utils_1.ENUM_UTILS.match(orderParams.main.orderType, sdk_1.OrderType.MARKET);
218
- const slotsTillAuctionEnd = orderParams.main.auctionDuration
219
- ? isMarketOrder
220
- ? userSigningSlotBuffer + orderParams.main.auctionDuration
221
- : Math.max(exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS, userSigningSlotBuffer + orderParams.main.auctionDuration)
222
- : exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;
223
- const expirationTimeMs = Math.max(slotsTillAuctionEnd - exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS, exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS) * sdk_1.SLOT_TIME_ESTIMATE_MS;
224
259
  // Ensure that the user signs the message before the expiration time
225
260
  const signedMessage = await (0, exports.signSwiftOrderMsg)({
226
261
  wallet: swiftOptions.wallet,