@drift-labs/common 1.0.0 → 1.0.2

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 (92) hide show
  1. package/lib/clients/swiftClient.d.ts +5 -1
  2. package/lib/clients/swiftClient.js +17 -7
  3. package/lib/clients/swiftClient.js.map +1 -1
  4. package/lib/clients/tvFeed.d.ts +3 -1
  5. package/lib/clients/tvFeed.js +27 -13
  6. package/lib/clients/tvFeed.js.map +1 -1
  7. package/lib/common-ui-utils/commonUiUtils.d.ts +7 -0
  8. package/lib/common-ui-utils/market.d.ts +6 -1
  9. package/lib/common-ui-utils/market.js +46 -0
  10. package/lib/common-ui-utils/market.js.map +1 -1
  11. package/lib/common-ui-utils/order.d.ts +8 -1
  12. package/lib/common-ui-utils/order.js +39 -0
  13. package/lib/common-ui-utils/order.js.map +1 -1
  14. package/lib/common-ui-utils/user.js +1 -0
  15. package/lib/common-ui-utils/user.js.map +1 -1
  16. package/lib/constants/markets.d.ts +1 -0
  17. package/lib/constants/markets.js +2 -1
  18. package/lib/constants/markets.js.map +1 -1
  19. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.d.ts +1 -6
  20. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -22
  21. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  22. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +2 -2
  23. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
  24. package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +1 -2
  25. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
  26. package/lib/drift/Drift/clients/CentralServerDrift.d.ts +10 -5
  27. package/lib/drift/Drift/clients/CentralServerDrift.js +5 -48
  28. package/lib/drift/Drift/clients/CentralServerDrift.js.map +1 -1
  29. package/lib/drift/Drift/constants/errors.d.ts +9 -1
  30. package/lib/drift/Drift/constants/errors.js +13 -2
  31. package/lib/drift/Drift/constants/errors.js.map +1 -1
  32. package/lib/drift/Drift/data/PollingDlob.d.ts +0 -20
  33. package/lib/drift/Drift/data/PollingDlob.js +2 -78
  34. package/lib/drift/Drift/data/PollingDlob.js.map +1 -1
  35. package/lib/drift/base/actions/perp/settlePnl.d.ts +3 -3
  36. package/lib/drift/base/actions/perp/settlePnl.js +3 -3
  37. package/lib/drift/base/actions/perp/settlePnl.js.map +1 -1
  38. package/lib/drift/base/actions/spot/index.d.ts +0 -1
  39. package/lib/drift/base/actions/spot/index.js +0 -1
  40. package/lib/drift/base/actions/spot/index.js.map +1 -1
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +81 -0
  42. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +255 -0
  43. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -0
  44. package/lib/drift/base/actions/trade/openPerpOrder/index.d.ts +2 -0
  45. package/lib/drift/base/actions/trade/openPerpOrder/index.js +2 -0
  46. package/lib/drift/base/actions/trade/openPerpOrder/index.js.map +1 -1
  47. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +53 -43
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +180 -201
  49. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  50. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +37 -9
  51. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +194 -83
  52. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  53. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +40 -27
  54. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +111 -32
  55. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  56. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +64 -0
  57. package/lib/drift/base/actions/trade/openPerpOrder/types.js +3 -0
  58. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -0
  59. package/lib/drift/base/actions/user/create.js +9 -3
  60. package/lib/drift/base/actions/user/create.js.map +1 -1
  61. package/lib/drift/cli.js +114 -71
  62. package/lib/drift/cli.js.map +1 -1
  63. package/lib/drift/index.d.ts +1 -0
  64. package/lib/drift/index.js +1 -0
  65. package/lib/drift/index.js.map +1 -1
  66. package/lib/drift/utils/auctionParamsResponseMapper.d.ts +25 -23
  67. package/lib/drift/utils/auctionParamsResponseMapper.js +4 -6
  68. package/lib/drift/utils/auctionParamsResponseMapper.js.map +1 -1
  69. package/lib/drift/utils/index.d.ts +1 -1
  70. package/lib/drift/utils/index.js +1 -4
  71. package/lib/drift/utils/index.js.map +1 -1
  72. package/lib/drift/utils/orderParams.d.ts +3 -28
  73. package/lib/drift/utils/orderParams.js +9 -1
  74. package/lib/drift/utils/orderParams.js.map +1 -1
  75. package/lib/index.d.ts +2 -0
  76. package/lib/index.js +2 -0
  77. package/lib/index.js.map +1 -1
  78. package/lib/types/user.d.ts +1 -0
  79. package/lib/types/user.js.map +1 -1
  80. package/lib/utils/fetch.d.ts +1 -0
  81. package/lib/utils/fetch.js +11 -0
  82. package/lib/utils/fetch.js.map +1 -0
  83. package/lib/utils/orderbook/index.d.ts +18 -0
  84. package/lib/utils/orderbook/index.js +68 -1
  85. package/lib/utils/orderbook/index.js.map +1 -1
  86. package/lib/utils/priceImpact.d.ts +14 -0
  87. package/lib/utils/priceImpact.js +71 -0
  88. package/lib/utils/priceImpact.js.map +1 -0
  89. package/package.json +1 -1
  90. package/lib/drift/base/actions/spot/borrow.d.ts +0 -1
  91. package/lib/drift/base/actions/spot/borrow.js +0 -8
  92. package/lib/drift/base/actions/spot/borrow.js.map +0 -1
@@ -1,45 +1,50 @@
1
- import { DriftClient, User, BN, PositionDirection, MarketType } from '@drift-labs/sdk';
1
+ import { DriftClient, User, BN, PositionDirection, ReferrerInfo } from '@drift-labs/sdk';
2
2
  import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
- import { OptionalTriggerOrderParams, SwiftOrderOptions, SwiftOrderResult } from '../openSwiftOrder';
4
- export interface AuctionParamsRequestOptions {
5
- maxLeverageSelected?: boolean;
6
- maxLeverageOrderSize?: BN;
7
- reduceOnly?: boolean;
8
- auctionDuration?: number;
9
- auctionStartPriceOffset?: number;
10
- auctionEndPriceOffset?: number;
11
- auctionStartPriceOffsetFrom?: string;
12
- auctionEndPriceOffsetFrom?: string;
13
- slippageTolerance?: number | 'dynamic';
14
- auctionPriceCaps?: {
15
- min: BN;
16
- max: BN;
17
- };
18
- isOracleOrder?: boolean;
19
- additionalEndPriceBuffer?: BN;
20
- forceUpToSlippage?: boolean;
21
- orderType?: 'market' | 'oracle';
22
- }
23
- export type OpenPerpMarketOrderParams<T extends boolean = boolean> = {
3
+ import { SwiftOrderOptions } from '../openSwiftOrder';
4
+ import { OptionalAuctionParamsRequestInputs } from '../dlobServer';
5
+ import { TxnOrSwiftResult, WithTxnParams } from '../types';
6
+ import { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';
7
+ export interface OpenPerpMarketOrderBaseParams {
24
8
  driftClient: DriftClient;
25
9
  user: User;
26
10
  assetType: 'base' | 'quote';
27
11
  marketIndex: number;
28
12
  direction: PositionDirection;
29
13
  amount: BN;
30
- auctionParamsOptions?: AuctionParamsRequestOptions;
31
14
  dlobServerHttpUrl: string;
15
+ userOrderId?: number;
16
+ placeAndTake?: PlaceAndTakeParams;
17
+ optionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;
32
18
  bracketOrders?: {
33
19
  takeProfit?: OptionalTriggerOrderParams;
34
20
  stopLoss?: OptionalTriggerOrderParams;
35
21
  };
36
- marketType?: MarketType;
37
- useSwift: T;
38
- } & (T extends true ? {
22
+ }
23
+ export interface OpenPerpMarketOrderBaseParamsWithSwift extends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {
39
24
  swiftOptions: SwiftOrderOptions;
40
- } : {
41
- swiftOptions?: never;
42
- });
25
+ }
26
+ export interface OpenPerpMarketOrderParams<T extends boolean = boolean> extends OpenPerpMarketOrderBaseParams {
27
+ useSwift: T;
28
+ swiftOptions?: T extends true ? SwiftOrderOptions : never;
29
+ placeAndTake?: T extends true ? never : PlaceAndTakeParams;
30
+ }
31
+ /**
32
+ * Creates and submits a Swift (signed message) order. Only available for perp orders.
33
+ */
34
+ export declare function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId, }: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void>;
35
+ /**
36
+ * Creates a placeAndTake transaction instruction.
37
+ * Fallbacks to a regular market order if no top makers are found.
38
+ */
39
+ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, }: OpenPerpMarketOrderBaseParams & {
40
+ direction: PositionDirection;
41
+ dlobServerHttpUrl: string;
42
+ marketIndex: number;
43
+ driftClient: DriftClient;
44
+ user: User;
45
+ referrerInfo?: ReferrerInfo;
46
+ auctionDurationPercentage?: number;
47
+ }) => Promise<TransactionInstruction>;
43
48
  /**
44
49
  * Creates transaction instructions for opening a perp market order.
45
50
  * If swiftOptions is provided, it will create a Swift (signed message) order instead.
@@ -51,13 +56,11 @@ export type OpenPerpMarketOrderParams<T extends boolean = boolean> = {
51
56
  * @param direction - The direction of the trade (long/short)
52
57
  * @param amount - The amount to trade
53
58
  * @param dlobServerHttpUrl - Server URL for the auction params endpoint
54
- * @param auctionParamsOptions - Optional parameters for auction params endpoint and order configuration
55
- * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions
56
- * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true
59
+ * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
57
60
  *
58
- * @returns Promise resolving to an array of transaction instructions for regular orders, or empty array for Swift orders
61
+ * @returns Promise resolving to an array of transaction instructions for regular orders
59
62
  */
60
- export declare const createOpenPerpMarketOrderIx: ({ driftClient, user, assetType, marketIndex, direction, amount, dlobServerHttpUrl, auctionParamsOptions, useSwift, swiftOptions, }: OpenPerpMarketOrderParams) => Promise<TransactionInstruction[]>;
63
+ export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
61
64
  /**
62
65
  * Creates a complete transaction for opening a perp market order.
63
66
  *
@@ -66,19 +69,26 @@ export declare const createOpenPerpMarketOrderIx: ({ driftClient, user, assetTyp
66
69
  * @param marketIndex - The perp market index to trade
67
70
  * @param direction - The direction of the trade (long/short)
68
71
  * @param amount - The amount to trade
69
- * @param auctionParamsOptions - Optional parameters for auction params endpoint and order configuration
72
+ * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
70
73
  * @param dlobServerHttpUrl - Server URL for the auction params endpoint
71
74
  *
72
75
  * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
73
76
  */
74
- export declare const createOpenPerpMarketOrderTxn: <T extends boolean>({ driftClient, user, assetType, marketIndex, direction, amount, dlobServerHttpUrl, auctionParamsOptions, bracketOrders, useSwift, swiftOptions, }: OpenPerpMarketOrderParams<T>) => Promise<T extends true ? SwiftOrderResult : Transaction | VersionedTransaction>;
77
+ export declare const createOpenPerpMarketOrderTxn: (params: WithTxnParams<OpenPerpMarketOrderBaseParams>) => Promise<Transaction | VersionedTransaction>;
75
78
  /**
76
- * Creates a Swift (signed message) order directly.
77
- * This is a convenience function for when you only want to create Swift orders.
79
+ * Creates a transaction or swift order for a perp market order.
80
+ *
81
+ * @param driftClient - The Drift client instance for interacting with the protocol
82
+ * @param user - The user account that will place the order
83
+ * @param marketIndex - The perp market index to trade
84
+ * @param direction - The direction of the trade (long/short)
85
+ * @param amount - The amount to trade
86
+ * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
87
+ * @param dlobServerHttpUrl - Server URL for the auction params endpoint
88
+ * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions
89
+ * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true
90
+ * @param userOrderId - The user order id for UI identification
78
91
  *
79
- * @param params - All the parameters needed for creating a Swift order
80
- * @returns Promise resolving to SwiftOrderResult with observable and order UUID
92
+ * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
81
93
  */
82
- export declare const createSwiftPerpMarketOrder: (params: Omit<OpenPerpMarketOrderParams, 'useSwift'> & {
83
- swiftOptions: SwiftOrderOptions;
84
- }) => Promise<SwiftOrderResult>;
94
+ export declare const createOpenPerpMarketOrder: <T extends boolean>(params: WithTxnParams<OpenPerpMarketOrderParams<T>>) => Promise<TxnOrSwiftResult<T>>;
@@ -1,85 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSwiftPerpMarketOrder = exports.createOpenPerpMarketOrderTxn = exports.createOpenPerpMarketOrderIx = void 0;
3
+ exports.createOpenPerpMarketOrder = exports.createOpenPerpMarketOrderTxn = exports.createOpenPerpMarketOrderIxs = exports.createPlaceAndTakePerpMarketOrderIx = exports.createSwiftMarketOrder = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
5
  const utils_1 = require("../../../../../../utils");
6
- const auctionParamsResponseMapper_1 = require("../../../../../utils/auctionParamsResponseMapper");
7
6
  const openSwiftOrder_1 = require("../openSwiftOrder");
8
- const types_1 = require("../../../../../../types");
9
- const swiftClient_1 = require("../../../../../../clients/swiftClient");
10
7
  const orderParams_1 = require("../../../../../utils/orderParams");
11
- /**
12
- * Fetches order parameters from the auction params server
13
- */
14
- async function fetchOrderParamsFromServer({ assetType, marketIndex, marketType = sdk_1.MarketType.PERP, direction, amount, dlobServerHttpUrl, auctionParamsOptions = {}, }) {
15
- var _a;
16
- // Extract optional parameters (no defaults except for what's required by server)
17
- const { maxLeverageSelected, maxLeverageOrderSize, reduceOnly, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, slippageTolerance, isOracleOrder, orderType, ...restOptions } = auctionParamsOptions;
18
- // Build URL parameters for server request
19
- const urlParamsObject = {
20
- // Required fields
21
- assetType,
22
- marketType: utils_1.ENUM_UTILS.toStr(marketType),
23
- marketIndex: marketIndex.toString(),
24
- direction: utils_1.ENUM_UTILS.toStr(direction),
25
- amount: amount.toString(),
26
- };
27
- // Add optional parameters only if they are provided
28
- const optionalParams = {
29
- maxLeverageSelected,
30
- maxLeverageOrderSize,
31
- reduceOnly,
32
- auctionDuration,
33
- auctionStartPriceOffset,
34
- auctionEndPriceOffset,
35
- auctionStartPriceOffsetFrom,
36
- auctionEndPriceOffsetFrom,
37
- slippageTolerance,
38
- isOracleOrder,
39
- orderType,
40
- additionalEndPriceBuffer: restOptions.additionalEndPriceBuffer,
41
- forceUpToSlippage: restOptions.forceUpToSlippage,
42
- };
43
- // Add defined optional parameters
44
- Object.entries(optionalParams).forEach(([key, value]) => {
45
- if (value !== undefined) {
46
- urlParamsObject[key] = value.toString();
47
- }
48
- });
49
- const urlParams = new URLSearchParams(urlParamsObject);
50
- // Get order params from server
51
- const requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;
52
- const response = await fetch(requestUrl);
53
- if (!response.ok) {
54
- throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
55
- }
56
- const serverResponse = await response.json();
57
- const mappedParams = (0, auctionParamsResponseMapper_1.mapAuctionParamsResponse)(serverResponse);
58
- // Convert MappedAuctionParams to OptionalOrderParams
59
- return {
60
- orderType: mappedParams.orderType,
61
- marketType: mappedParams.marketType,
62
- userOrderId: mappedParams.userOrderId,
63
- direction: mappedParams.direction,
64
- baseAssetAmount: mappedParams.baseAssetAmount,
65
- marketIndex: mappedParams.marketIndex,
66
- reduceOnly: mappedParams.reduceOnly,
67
- postOnly: mappedParams.postOnly,
68
- triggerPrice: mappedParams.triggerPrice,
69
- triggerCondition: mappedParams.triggerCondition,
70
- oraclePriceOffset: ((_a = mappedParams.oraclePriceOffset) === null || _a === void 0 ? void 0 : _a.toNumber()) || null,
71
- auctionDuration: mappedParams.auctionDuration,
72
- maxTs: mappedParams.maxTs,
73
- auctionStartPrice: mappedParams.auctionStartPrice,
74
- auctionEndPrice: mappedParams.auctionEndPrice,
75
- };
76
- }
8
+ const dlobServer_1 = require("../dlobServer");
9
+ const order_1 = require("../../../../../../common-ui-utils/order");
10
+ const errors_1 = require("../../../../../Drift/constants/errors");
77
11
  /**
78
12
  * Creates and submits a Swift (signed message) order. Only available for perp orders.
79
13
  */
80
- async function createSwiftOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, auctionParamsOptions, swiftOptions, }) {
14
+ async function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId = 0, }) {
15
+ if (amount.isZero()) {
16
+ throw new Error('Amount must be greater than zero');
17
+ }
81
18
  // Get order parameters from server
82
- const orderParams = await fetchOrderParamsFromServer({
19
+ const fetchedOrderParams = await (0, dlobServer_1.fetchAuctionOrderParams)({
83
20
  driftClient,
84
21
  user,
85
22
  assetType,
@@ -88,166 +25,163 @@ async function createSwiftOrder({ driftClient, user, assetType, marketIndex, dir
88
25
  direction,
89
26
  amount,
90
27
  dlobServerHttpUrl,
91
- auctionParamsOptions,
28
+ optionalAuctionParamsInputs,
92
29
  });
93
- // Fetch current slot programmatically
94
- const currentSlot = await driftClient.connection.getSlot();
30
+ const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
31
+ const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
32
+ const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
33
+ const orderParams = {
34
+ ...fetchedOrderParams,
35
+ userOrderId,
36
+ bitFlags,
37
+ };
95
38
  const userAccount = user.getUserAccount();
96
- // Use the existing prepSwiftOrder helper function
97
- const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid } = (0, openSwiftOrder_1.prepSwiftOrder)({
39
+ const slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;
40
+ await (0, openSwiftOrder_1.prepSignAndSendSwiftOrder)({
98
41
  driftClient,
99
- takerUserAccount: {
100
- pubKey: swiftOptions.wallet.publicKey,
101
- subAccountId: userAccount.subAccountId,
102
- },
103
- currentSlot,
104
- isDelegate: swiftOptions.isDelegate || false,
42
+ subAccountId: userAccount.subAccountId,
43
+ marketIndex,
44
+ slotBuffer,
45
+ swiftOptions,
105
46
  orderParams: {
106
47
  main: orderParams,
107
48
  takeProfit: bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.takeProfit,
108
49
  stopLoss: bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.stopLoss,
109
50
  },
110
- slotBuffer: swiftOptions.signedMessageOrderSlotBuffer || 30,
111
51
  });
112
- // Sign the message
113
- const signedMessage = await swiftOptions.wallet.signMessage(hexEncodedSwiftOrderMessage.uInt8Array);
114
- // Initialize SwiftClient (required before using sendSwiftOrder)
115
- swiftClient_1.SwiftClient.init(swiftOptions.swiftServerUrl);
116
- const swiftOrderResult = (0, openSwiftOrder_1.sendSwiftOrder)({
117
- driftClient,
118
- marketId: types_1.MarketId.createPerpMarket(marketIndex),
119
- hexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,
120
- signedMessage,
121
- signedMsgOrderUuid,
122
- takerAuthority: swiftOptions.wallet.publicKey,
123
- signingAuthority: swiftOptions.wallet.publicKey,
124
- auctionDurationSlot: orderParams.auctionDuration || undefined,
125
- swiftConfirmationSlotBuffer: 15,
126
- });
127
- return swiftOrderResult;
128
52
  }
53
+ exports.createSwiftMarketOrder = createSwiftMarketOrder;
129
54
  /**
130
- * Creates transaction instructions for opening a perp market order.
131
- * If swiftOptions is provided, it will create a Swift (signed message) order instead.
132
- *
133
- * @param driftClient - The Drift client instance for interacting with the protocol
134
- * @param user - The user account that will place the order
135
- * @param assetType - Whether the amount is in base or quote units
136
- * @param marketIndex - The perp market index to trade
137
- * @param direction - The direction of the trade (long/short)
138
- * @param amount - The amount to trade
139
- * @param dlobServerHttpUrl - Server URL for the auction params endpoint
140
- * @param auctionParamsOptions - Optional parameters for auction params endpoint and order configuration
141
- * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions
142
- * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true
143
- *
144
- * @returns Promise resolving to an array of transaction instructions for regular orders, or empty array for Swift orders
55
+ * Creates a placeAndTake transaction instruction.
56
+ * Fallbacks to a regular market order if no top makers are found.
145
57
  */
146
- const createOpenPerpMarketOrderIx = async ({ driftClient, user, assetType, marketIndex, direction, amount, dlobServerHttpUrl, auctionParamsOptions = {}, useSwift = false, swiftOptions, }) => {
147
- if (!amount || amount.isZero()) {
148
- throw new Error('Amount must be greater than zero');
149
- }
150
- // First, get order parameters from server (same for both Swift and regular orders)
151
- const orderParams = await fetchOrderParamsFromServer({
152
- driftClient,
153
- user,
154
- assetType,
155
- marketIndex,
156
- marketType: sdk_1.MarketType.PERP,
157
- direction,
158
- amount,
159
- dlobServerHttpUrl,
160
- auctionParamsOptions,
161
- });
162
- // If useSwift is true, use prepSwiftOrder and return empty array
163
- if (useSwift) {
164
- if (!swiftOptions) {
165
- throw new Error('swiftOptions is required when useSwift is true');
166
- }
167
- const currentSlot = await driftClient.connection.getSlot();
168
- const userAccount = user.getUserAccount();
169
- // Use the existing prepSwiftOrder helper function
170
- (0, openSwiftOrder_1.prepSwiftOrder)({
58
+ const createPlaceAndTakePerpMarketOrderIx = async ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, }) => {
59
+ const counterPartySide = utils_1.ENUM_UTILS.match(direction, sdk_1.PositionDirection.LONG)
60
+ ? 'ask'
61
+ : 'bid';
62
+ const [fetchedOrderParams, topMakersResult] = await Promise.all([
63
+ (0, dlobServer_1.fetchAuctionOrderParams)({
171
64
  driftClient,
172
- takerUserAccount: {
173
- pubKey: swiftOptions.wallet.publicKey,
174
- subAccountId: userAccount.subAccountId,
175
- },
176
- currentSlot,
177
- isDelegate: swiftOptions.isDelegate || false,
178
- orderParams: {
179
- main: orderParams,
180
- // TODO: Add support for stopLoss and takeProfit
181
- },
182
- slotBuffer: swiftOptions.signedMessageOrderSlotBuffer || 30,
183
- });
184
- // Swift orders don't return transaction instructions
185
- return [];
65
+ user,
66
+ assetType,
67
+ marketIndex,
68
+ marketType: sdk_1.MarketType.PERP,
69
+ direction,
70
+ amount,
71
+ dlobServerHttpUrl,
72
+ optionalAuctionParamsInputs,
73
+ }),
74
+ (0, dlobServer_1.fetchTopMakers)({
75
+ dlobServerHttpUrl,
76
+ marketIndex,
77
+ marketType: sdk_1.MarketType.PERP,
78
+ side: counterPartySide,
79
+ limit: 4,
80
+ }),
81
+ ]);
82
+ const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
83
+ const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
84
+ const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
85
+ fetchedOrderParams.bitFlags = bitFlags;
86
+ fetchedOrderParams.userOrderId = userOrderId;
87
+ if (!topMakersResult || topMakersResult.length === 0) {
88
+ throw new errors_1.NoTopMakersError('No top makers found', fetchedOrderParams);
186
89
  }
187
- // Regular order flow - create transaction instruction
188
- const placeOrderIx = await driftClient.getPlaceOrdersIx([orderParams]);
189
- return [placeOrderIx];
90
+ const topMakersInfo = topMakersResult.map((maker) => ({
91
+ maker: maker.userAccountPubKey,
92
+ makerUserAccount: maker.userAccount,
93
+ makerStats: (0, sdk_1.getUserStatsAccountPublicKey)(driftClient.program.programId, maker.userAccount.authority),
94
+ }));
95
+ const placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(fetchedOrderParams, topMakersInfo, referrerInfo, undefined, auctionDurationPercentage, user.getUserAccount().subAccountId);
96
+ return placeAndTakeIx;
190
97
  };
191
- exports.createOpenPerpMarketOrderIx = createOpenPerpMarketOrderIx;
98
+ exports.createPlaceAndTakePerpMarketOrderIx = createPlaceAndTakePerpMarketOrderIx;
192
99
  /**
193
- * Creates a complete transaction for opening a perp market order.
100
+ * Creates transaction instructions for opening a perp market order.
101
+ * If swiftOptions is provided, it will create a Swift (signed message) order instead.
194
102
  *
195
103
  * @param driftClient - The Drift client instance for interacting with the protocol
196
104
  * @param user - The user account that will place the order
105
+ * @param assetType - Whether the amount is in base or quote units
197
106
  * @param marketIndex - The perp market index to trade
198
107
  * @param direction - The direction of the trade (long/short)
199
108
  * @param amount - The amount to trade
200
- * @param auctionParamsOptions - Optional parameters for auction params endpoint and order configuration
201
109
  * @param dlobServerHttpUrl - Server URL for the auction params endpoint
110
+ * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
202
111
  *
203
- * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
112
+ * @returns Promise resolving to an array of transaction instructions for regular orders
204
113
  */
205
- const createOpenPerpMarketOrderTxn = async ({ driftClient, user, assetType, marketIndex, direction, amount, dlobServerHttpUrl, auctionParamsOptions, bracketOrders, useSwift, swiftOptions, }) => {
114
+ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, }) => {
115
+ var _a, _b, _c, _d;
206
116
  if (!amount || amount.isZero()) {
207
117
  throw new Error('Amount must be greater than zero');
208
118
  }
209
- // First, get order parameters from server (same for both Swift and regular orders)
210
- const orderParams = await fetchOrderParamsFromServer({
211
- driftClient,
212
- user,
213
- assetType,
214
- marketIndex,
215
- marketType: sdk_1.MarketType.PERP,
216
- direction,
217
- amount,
218
- dlobServerHttpUrl,
219
- auctionParamsOptions,
220
- });
221
- // If useSwift is true, return the Swift result directly
222
- if (useSwift) {
223
- if (!swiftOptions) {
224
- throw new Error('swiftOptions is required when useSwift is true');
119
+ const allOrders = [];
120
+ const allIxs = [];
121
+ if (placeAndTake === null || placeAndTake === void 0 ? void 0 : placeAndTake.enable) {
122
+ try {
123
+ const placeAndTakeIx = await (0, exports.createPlaceAndTakePerpMarketOrderIx)({
124
+ assetType,
125
+ amount,
126
+ direction,
127
+ dlobServerHttpUrl,
128
+ marketIndex,
129
+ driftClient,
130
+ user,
131
+ userOrderId,
132
+ referrerInfo: placeAndTake.referrerInfo,
133
+ auctionDurationPercentage: placeAndTake.auctionDurationPercentage,
134
+ optionalAuctionParamsInputs,
135
+ });
136
+ allIxs.push(placeAndTakeIx);
225
137
  }
226
- return (await createSwiftOrder({
138
+ catch (e) {
139
+ if (e instanceof errors_1.NoTopMakersError) {
140
+ // fallback to regular order
141
+ allOrders.push(e.orderParams);
142
+ }
143
+ else {
144
+ throw e;
145
+ }
146
+ }
147
+ }
148
+ else {
149
+ const fetchedOrderParams = await (0, dlobServer_1.fetchAuctionOrderParams)({
227
150
  driftClient,
228
151
  user,
229
152
  assetType,
230
153
  marketIndex,
154
+ marketType: sdk_1.MarketType.PERP,
231
155
  direction,
232
156
  amount,
233
157
  dlobServerHttpUrl,
234
- bracketOrders,
235
- auctionParamsOptions,
236
- swiftOptions,
237
- }));
158
+ optionalAuctionParamsInputs,
159
+ });
160
+ const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
161
+ const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
162
+ const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
163
+ const orderParams = {
164
+ ...fetchedOrderParams,
165
+ userOrderId,
166
+ bitFlags,
167
+ };
168
+ allOrders.push(orderParams);
238
169
  }
239
- const allOrders = [orderParams];
170
+ const bracketOrdersDirection = utils_1.ENUM_UTILS.match(direction, sdk_1.PositionDirection.LONG)
171
+ ? sdk_1.PositionDirection.SHORT
172
+ : sdk_1.PositionDirection.LONG;
240
173
  if (bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.takeProfit) {
241
174
  const takeProfitParams = (0, orderParams_1.buildNonMarketOrderParams)({
242
175
  marketIndex,
243
176
  marketType: sdk_1.MarketType.PERP,
244
- direction: bracketOrders.takeProfit.direction,
245
- baseAssetAmount: amount,
177
+ direction: bracketOrdersDirection,
178
+ baseAssetAmount: (_a = bracketOrders.takeProfit.baseAssetAmount) !== null && _a !== void 0 ? _a : amount,
246
179
  orderConfig: {
247
180
  orderType: 'takeProfit',
248
181
  triggerPrice: bracketOrders.takeProfit.triggerPrice,
182
+ limitPrice: bracketOrders.takeProfit.limitPrice,
249
183
  },
250
- reduceOnly: true,
184
+ reduceOnly: (_b = bracketOrders.takeProfit.reduceOnly) !== null && _b !== void 0 ? _b : true,
251
185
  });
252
186
  allOrders.push(takeProfitParams);
253
187
  }
@@ -255,39 +189,84 @@ const createOpenPerpMarketOrderTxn = async ({ driftClient, user, assetType, mark
255
189
  const stopLossParams = (0, orderParams_1.buildNonMarketOrderParams)({
256
190
  marketIndex,
257
191
  marketType: sdk_1.MarketType.PERP,
258
- direction: bracketOrders.stopLoss.direction,
259
- baseAssetAmount: amount,
192
+ direction: bracketOrdersDirection,
193
+ baseAssetAmount: (_c = bracketOrders.stopLoss.baseAssetAmount) !== null && _c !== void 0 ? _c : amount,
260
194
  orderConfig: {
261
195
  orderType: 'stopLoss',
262
196
  triggerPrice: bracketOrders.stopLoss.triggerPrice,
197
+ limitPrice: bracketOrders.stopLoss.limitPrice,
263
198
  },
264
- reduceOnly: true,
199
+ reduceOnly: (_d = bracketOrders.stopLoss.reduceOnly) !== null && _d !== void 0 ? _d : true,
265
200
  });
266
201
  allOrders.push(stopLossParams);
267
202
  }
203
+ // Regular order flow - create transaction instruction
204
+ if (allOrders.length > 0) {
205
+ const placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);
206
+ allIxs.push(placeOrderIx);
207
+ }
208
+ return allIxs;
209
+ };
210
+ exports.createOpenPerpMarketOrderIxs = createOpenPerpMarketOrderIxs;
211
+ /**
212
+ * Creates a complete transaction for opening a perp market order.
213
+ *
214
+ * @param driftClient - The Drift client instance for interacting with the protocol
215
+ * @param user - The user account that will place the order
216
+ * @param marketIndex - The perp market index to trade
217
+ * @param direction - The direction of the trade (long/short)
218
+ * @param amount - The amount to trade
219
+ * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
220
+ * @param dlobServerHttpUrl - Server URL for the auction params endpoint
221
+ *
222
+ * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
223
+ */
224
+ const createOpenPerpMarketOrderTxn = async (params) => {
225
+ const { driftClient } = params;
268
226
  // Regular order flow - create transaction instruction and build transaction
269
- const placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);
227
+ const placeOrderIx = await (0, exports.createOpenPerpMarketOrderIxs)(params);
270
228
  const openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({
271
- instructions: [placeOrderIx],
229
+ instructions: placeOrderIx,
272
230
  txVersion: 0,
273
231
  connection: driftClient.connection,
274
232
  preFlightCommitment: 'confirmed',
275
233
  fetchAllMarketLookupTableAccounts: driftClient.fetchAllLookupTableAccounts.bind(driftClient),
234
+ txParams: params.txParams,
276
235
  });
277
236
  return openPerpMarketOrderTxn;
278
237
  };
279
238
  exports.createOpenPerpMarketOrderTxn = createOpenPerpMarketOrderTxn;
280
239
  /**
281
- * Creates a Swift (signed message) order directly.
282
- * This is a convenience function for when you only want to create Swift orders.
240
+ * Creates a transaction or swift order for a perp market order.
283
241
  *
284
- * @param params - All the parameters needed for creating a Swift order
285
- * @returns Promise resolving to SwiftOrderResult with observable and order UUID
242
+ * @param driftClient - The Drift client instance for interacting with the protocol
243
+ * @param user - The user account that will place the order
244
+ * @param marketIndex - The perp market index to trade
245
+ * @param direction - The direction of the trade (long/short)
246
+ * @param amount - The amount to trade
247
+ * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
248
+ * @param dlobServerHttpUrl - Server URL for the auction params endpoint
249
+ * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions
250
+ * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true
251
+ * @param userOrderId - The user order id for UI identification
252
+ *
253
+ * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
286
254
  */
287
- const createSwiftPerpMarketOrder = async (params) => {
288
- return await createSwiftOrder({
289
- ...params,
290
- });
255
+ const createOpenPerpMarketOrder = async (params) => {
256
+ const { useSwift, swiftOptions, ...rest } = params;
257
+ // If useSwift is true, return the Swift result directly
258
+ if (useSwift) {
259
+ if (!swiftOptions) {
260
+ throw new Error('swiftOptions is required when useSwift is true');
261
+ }
262
+ const swiftOrderResult = await createSwiftMarketOrder({
263
+ ...rest,
264
+ swiftOptions,
265
+ });
266
+ return swiftOrderResult;
267
+ }
268
+ const openPerpMarketOrderTxn = await (0, exports.createOpenPerpMarketOrderTxn)(rest);
269
+ return openPerpMarketOrderTxn;
291
270
  };
292
- exports.createSwiftPerpMarketOrder = createSwiftPerpMarketOrder;
271
+ exports.createOpenPerpMarketOrder = createOpenPerpMarketOrder;
293
272
  //# sourceMappingURL=index.js.map