@drift-labs/common 1.0.11 → 1.0.13

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 (73) hide show
  1. package/lib/common-ui-utils/commonUiUtils.d.ts +6 -0
  2. package/lib/common-ui-utils/trading.d.ts +6 -0
  3. package/lib/common-ui-utils/trading.js +59 -0
  4. package/lib/common-ui-utils/trading.js.map +1 -1
  5. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.d.ts +20 -2
  6. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +38 -1
  7. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  8. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +31 -1
  9. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
  10. package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +10 -2
  11. package/lib/drift/Drift/clients/AuthorityDrift/index.js +12 -0
  12. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
  13. package/lib/drift/Drift/clients/CentralServerDrift/index.js +11 -2
  14. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  15. package/lib/drift/Drift/clients/CentralServerDrift/types.d.ts +1 -1
  16. package/lib/drift/Drift/clients/CentralServerDrift/types.js.map +1 -1
  17. package/lib/drift/base/actions/builder/createRevenueShareAccount.d.ts +62 -0
  18. package/lib/drift/base/actions/builder/createRevenueShareAccount.js +59 -0
  19. package/lib/drift/base/actions/builder/createRevenueShareAccount.js.map +1 -0
  20. package/lib/drift/base/actions/builder/createRevenueShareEscrow.d.ts +126 -0
  21. package/lib/drift/base/actions/builder/createRevenueShareEscrow.js +114 -0
  22. package/lib/drift/base/actions/builder/createRevenueShareEscrow.js.map +1 -0
  23. package/lib/drift/base/actions/builder/index.d.ts +3 -0
  24. package/lib/drift/base/actions/builder/index.js +20 -0
  25. package/lib/drift/base/actions/builder/index.js.map +1 -0
  26. package/lib/drift/base/actions/builder/manageBuilder.d.ts +157 -0
  27. package/lib/drift/base/actions/builder/manageBuilder.js +139 -0
  28. package/lib/drift/base/actions/builder/manageBuilder.js.map +1 -0
  29. package/lib/drift/base/actions/index.d.ts +1 -0
  30. package/lib/drift/base/actions/index.js +1 -0
  31. package/lib/drift/base/actions/index.js.map +1 -1
  32. package/lib/drift/base/actions/trade/cancelOrder.d.ts +12 -4
  33. package/lib/drift/base/actions/trade/cancelOrder.js +7 -4
  34. package/lib/drift/base/actions/trade/cancelOrder.js.map +1 -1
  35. package/lib/drift/base/actions/trade/editOrder.d.ts +18 -4
  36. package/lib/drift/base/actions/trade/editOrder.js +44 -8
  37. package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
  38. package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +16 -0
  39. package/lib/drift/base/actions/trade/openPerpOrder/auction.js +68 -0
  40. package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -0
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +1 -1
  42. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +18 -9
  43. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
  44. package/lib/drift/base/actions/trade/openPerpOrder/index.d.ts +1 -0
  45. package/lib/drift/base/actions/trade/openPerpOrder/index.js +1 -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 +51 -5
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +24 -7
  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 +20 -2
  51. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +23 -61
  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 +62 -4
  54. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +9 -4
  55. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  56. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.d.ts +7 -0
  57. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +29 -0
  58. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -0
  59. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +8 -4
  60. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
  61. package/lib/drift/base/constants/auction.d.ts +1 -0
  62. package/lib/drift/base/constants/auction.js +5 -0
  63. package/lib/drift/base/constants/auction.js.map +1 -0
  64. package/lib/drift/base/constants/index.d.ts +2 -0
  65. package/lib/drift/base/constants/index.js +19 -0
  66. package/lib/drift/base/constants/index.js.map +1 -0
  67. package/lib/drift/base/types.d.ts +4 -0
  68. package/lib/drift/base/types.js +3 -0
  69. package/lib/drift/base/types.js.map +1 -0
  70. package/lib/drift/index.d.ts +1 -0
  71. package/lib/drift/index.js +1 -0
  72. package/lib/drift/index.js.map +1 -1
  73. package/package.json +4 -4
@@ -20,8 +20,11 @@ exports.createCancelOrdersTxn = exports.createCancelOrdersIx = void 0;
20
20
  *
21
21
  * ```
22
22
  */
23
- const createCancelOrdersIx = async (driftClient, orderIds, user) => {
24
- return driftClient.getCancelOrdersByIdsIx(orderIds, undefined, user);
23
+ const createCancelOrdersIx = async (params) => {
24
+ const { driftClient, user, orderIds, mainSignerOverride } = params;
25
+ return driftClient.getCancelOrdersByIdsIx(orderIds, undefined, user, {
26
+ authority: mainSignerOverride,
27
+ });
25
28
  };
26
29
  exports.createCancelOrdersIx = createCancelOrdersIx;
27
30
  /**
@@ -48,8 +51,8 @@ exports.createCancelOrdersIx = createCancelOrdersIx;
48
51
  * const signature = await wallet.sendTransaction(transaction, connection);
49
52
  * ```
50
53
  */
51
- const createCancelOrdersTxn = async (driftClient, user, orderIds, txParams) => {
52
- return driftClient.buildTransaction(await (0, exports.createCancelOrdersIx)(driftClient, orderIds, user), txParams);
54
+ const createCancelOrdersTxn = async (params) => {
55
+ return params.driftClient.buildTransaction(await (0, exports.createCancelOrdersIx)(params), params.txParams);
53
56
  };
54
57
  exports.createCancelOrdersTxn = createCancelOrdersTxn;
55
58
  //# sourceMappingURL=cancelOrder.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/cancelOrder.ts"],"names":[],"mappings":";;;AAOA;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,oBAAoB,GAAG,KAAK,EACxC,WAAwB,EACxB,QAAkB,EAClB,IAAU,EACwB,EAAE;IACpC,OAAO,WAAW,CAAC,sBAAsB,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACtE,CAAC,CAAC;AANW,QAAA,oBAAoB,wBAM/B;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACI,MAAM,qBAAqB,GAAG,KAAK,EACzC,WAAwB,EACxB,IAAU,EACV,QAAkB,EAClB,QAAmB,EAC2B,EAAE;IAChD,OAAO,WAAW,CAAC,gBAAgB,CAClC,MAAM,IAAA,4BAAoB,EAAC,WAAW,EAAE,QAAQ,EAAE,IAAI,CAAC,EACvD,QAAQ,CACR,CAAC;AACH,CAAC,CAAC;AAVW,QAAA,qBAAqB,yBAUhC","sourcesContent":["import { DriftClient, TxParams, User } from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\n\n/**\n * Creates a transaction instruction to cancel multiple orders by their order IDs.\n *\n * @param driftClient - The Drift client instance.\n * @param orderIds - Array of order IDs to cancel. Each ID corresponds to a specific order\n * @param user - The user client that owns the orders to be cancelled\n *\n * @returns Promise resolving to a TransactionInstruction that cancels the specified orders\n *\n * @example\n * ```typescript\n * const instruction = await cancelOrderIxs(\n * driftClient,\n * [123, 456, 789], // Cancel orders with IDs 123, 456, and 789\n * user\n * );\n *\n * ```\n */\nexport const createCancelOrdersIx = async (\n\tdriftClient: DriftClient,\n\torderIds: number[],\n\tuser: User\n): Promise<TransactionInstruction> => {\n\treturn driftClient.getCancelOrdersByIdsIx(orderIds, undefined, user);\n};\n\n/**\n * Creates a transaction to cancel multiple orders by their IDs.\n *\n * @param driftClient - The Drift client instance.\n * @param orderIds - Array of order IDs to cancel. Each ID corresponds to a specific order\n * @param user - The user client that owns the orders to be cancelled\n * @param txParams - Optional transaction parameters for customizing the transaction\n *\n * @returns Promise resolving to a Transaction or VersionedTransaction ready for signing\n *\n * @example\n * ```typescript\n * // Cancel multiple orders\n * const transaction = await cancelOrderTxn(\n * driftClient,\n * [123, 456], // Cancel orders with IDs 123 and 456\n * user,\n * { computeUnits: 200000 } // Optional transaction parameters\n * );\n *\n * // Sign and send the transaction\n * const signature = await wallet.sendTransaction(transaction, connection);\n * ```\n */\nexport const createCancelOrdersTxn = async (\n\tdriftClient: DriftClient,\n\tuser: User,\n\torderIds: number[],\n\ttxParams?: TxParams\n): Promise<Transaction | VersionedTransaction> => {\n\treturn driftClient.buildTransaction(\n\t\tawait createCancelOrdersIx(driftClient, orderIds, user),\n\t\ttxParams\n\t);\n};\n"]}
1
+ {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/cancelOrder.ts"],"names":[],"mappings":";;;AAgBA;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,oBAAoB,GAAG,KAAK,EACxC,MAAkC,EACA,EAAE;IACpC,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE,kBAAkB,EAAE,GAAG,MAAM,CAAC;IAEnE,OAAO,WAAW,CAAC,sBAAsB,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE;QACpE,SAAS,EAAE,kBAAkB;KAC7B,CAAC,CAAC;AACJ,CAAC,CAAC;AARW,QAAA,oBAAoB,wBAQ/B;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACI,MAAM,qBAAqB,GAAG,KAAK,EACzC,MAAiD,EACH,EAAE;IAChD,OAAO,MAAM,CAAC,WAAW,CAAC,gBAAgB,CACzC,MAAM,IAAA,4BAAoB,EAAC,MAAM,CAAC,EAClC,MAAM,CAAC,QAAQ,CACf,CAAC;AACH,CAAC,CAAC;AAPW,QAAA,qBAAqB,yBAOhC","sourcesContent":["import { DriftClient, User } from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n\tPublicKey,\n} from '@solana/web3.js';\nimport { WithTxnParams } from '../../types';\n\ninterface CreateCancelOrdersIxParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\torderIds: number[];\n\tmainSignerOverride?: PublicKey;\n}\n\n/**\n * Creates a transaction instruction to cancel multiple orders by their order IDs.\n *\n * @param driftClient - The Drift client instance.\n * @param orderIds - Array of order IDs to cancel. Each ID corresponds to a specific order\n * @param user - The user client that owns the orders to be cancelled\n *\n * @returns Promise resolving to a TransactionInstruction that cancels the specified orders\n *\n * @example\n * ```typescript\n * const instruction = await cancelOrderIxs(\n * driftClient,\n * [123, 456, 789], // Cancel orders with IDs 123, 456, and 789\n * user\n * );\n *\n * ```\n */\nexport const createCancelOrdersIx = async (\n\tparams: CreateCancelOrdersIxParams\n): Promise<TransactionInstruction> => {\n\tconst { driftClient, user, orderIds, mainSignerOverride } = params;\n\n\treturn driftClient.getCancelOrdersByIdsIx(orderIds, undefined, user, {\n\t\tauthority: mainSignerOverride,\n\t});\n};\n\n/**\n * Creates a transaction to cancel multiple orders by their IDs.\n *\n * @param driftClient - The Drift client instance.\n * @param orderIds - Array of order IDs to cancel. Each ID corresponds to a specific order\n * @param user - The user client that owns the orders to be cancelled\n * @param txParams - Optional transaction parameters for customizing the transaction\n *\n * @returns Promise resolving to a Transaction or VersionedTransaction ready for signing\n *\n * @example\n * ```typescript\n * // Cancel multiple orders\n * const transaction = await cancelOrderTxn(\n * driftClient,\n * [123, 456], // Cancel orders with IDs 123 and 456\n * user,\n * { computeUnits: 200000 } // Optional transaction parameters\n * );\n *\n * // Sign and send the transaction\n * const signature = await wallet.sendTransaction(transaction, connection);\n * ```\n */\nexport const createCancelOrdersTxn = async (\n\tparams: WithTxnParams<CreateCancelOrdersIxParams>\n): Promise<Transaction | VersionedTransaction> => {\n\treturn params.driftClient.buildTransaction(\n\t\tawait createCancelOrdersIx(params),\n\t\tparams.txParams\n\t);\n};\n"]}
@@ -1,5 +1,7 @@
1
- import { BN, DriftClient, OrderTriggerCondition, PositionDirection, TxParams, User } from '@drift-labs/sdk';
2
- import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
1
+ import { BN, DriftClient, OrderTriggerCondition, PositionDirection, User } from '@drift-labs/sdk';
2
+ import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
+ import { LimitAuctionConfig, LimitOrderParamsOrderConfig } from './openPerpOrder/types';
4
+ import { WithTxnParams } from '../../types';
3
5
  /**
4
6
  * Parameters for editing an existing order
5
7
  */
@@ -33,15 +35,27 @@ interface EditOrderParams {
33
35
  /** Order policy configuration */
34
36
  policy?: number;
35
37
  }
38
+ export interface CreateEditOrderIxParams {
39
+ driftClient: DriftClient;
40
+ user: User;
41
+ orderId: number;
42
+ editOrderParams: EditOrderParams;
43
+ mainSignerOverride?: PublicKey;
44
+ limitAuctionOrderConfig?: LimitOrderParamsOrderConfig & {
45
+ limitAuction: LimitAuctionConfig;
46
+ };
47
+ }
36
48
  /**
37
49
  * Creates a transaction instruction to edit an existing order
38
50
  * @param driftClient - The DriftClient instance
39
51
  * @param userPublicKey - The public key of the user who owns the order
40
52
  * @param orderId - The ID of the order to edit
41
53
  * @param editOrderParams - Parameters containing the new order values
54
+ * @param limitAuctionOrderConfig - Configuration for the limit auction order. If not provided, limit auction will not be enabled when relevant.
42
55
  * @returns Promise that resolves to a TransactionInstruction
43
56
  */
44
- export declare const createEditOrderIx: (driftClient: DriftClient, user: User, orderId: number, editOrderParams: EditOrderParams) => Promise<TransactionInstruction>;
57
+ export declare const createEditOrderIx: (params: CreateEditOrderIxParams) => Promise<TransactionInstruction>;
58
+ type CreateEditOrderTxnParams = WithTxnParams<CreateEditOrderIxParams>;
45
59
  /**
46
60
  * Creates a complete transaction to edit an existing order
47
61
  * @param driftClient - The DriftClient instance
@@ -51,5 +65,5 @@ export declare const createEditOrderIx: (driftClient: DriftClient, user: User, o
51
65
  * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)
52
66
  * @returns Promise that resolves to a Transaction or VersionedTransaction
53
67
  */
54
- export declare const createEditOrderTxn: (driftClient: DriftClient, user: User, orderId: number, editOrderParams: EditOrderParams, txParams?: TxParams) => Promise<Transaction | VersionedTransaction>;
68
+ export declare const createEditOrderTxn: ({ txParams, ...params }: CreateEditOrderTxnParams) => Promise<Transaction | VersionedTransaction>;
55
69
  export {};
@@ -1,22 +1,58 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.createEditOrderTxn = exports.createEditOrderIx = void 0;
7
+ const sdk_1 = require("@drift-labs/sdk");
8
+ const utils_1 = require("../../../../utils");
9
+ const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
10
+ const auction_1 = require("./openPerpOrder/auction");
4
11
  /**
5
12
  * Creates a transaction instruction to edit an existing order
6
13
  * @param driftClient - The DriftClient instance
7
14
  * @param userPublicKey - The public key of the user who owns the order
8
15
  * @param orderId - The ID of the order to edit
9
16
  * @param editOrderParams - Parameters containing the new order values
17
+ * @param limitAuctionOrderConfig - Configuration for the limit auction order. If not provided, limit auction will not be enabled when relevant.
10
18
  * @returns Promise that resolves to a TransactionInstruction
11
19
  */
12
- const createEditOrderIx = async (driftClient, user, orderId, editOrderParams) => {
13
- const userPublicKey = user.getUserAccountPublicKey();
14
- const _currentOrder = user.getOrderByUserOrderId(orderId);
15
- // TODO: handle auction params
20
+ const createEditOrderIx = async (params) => {
21
+ const { driftClient, user, orderId, editOrderParams, mainSignerOverride, limitAuctionOrderConfig, } = params;
22
+ const currentOrder = user.getOrder(orderId);
23
+ (0, tiny_invariant_1.default)(currentOrder, 'Current order not found');
24
+ const isLimitOrder = utils_1.ENUM_UTILS.match(currentOrder.orderType, sdk_1.OrderType.LIMIT);
25
+ let finalEditOrderParams = editOrderParams;
26
+ // handle limit auction if config is provided
27
+ if (isLimitOrder &&
28
+ limitAuctionOrderConfig &&
29
+ utils_1.ENUM_UTILS.match(currentOrder.postOnly, sdk_1.PostOnlyParams.NONE)) {
30
+ const limitAuctionOrderParams = await (0, auction_1.getLimitAuctionOrderParams)({
31
+ driftClient,
32
+ user,
33
+ marketIndex: currentOrder.marketIndex,
34
+ marketType: currentOrder.marketType,
35
+ direction: currentOrder.direction,
36
+ baseAssetAmount: currentOrder.baseAssetAmount,
37
+ userOrderId: currentOrder.userOrderId,
38
+ reduceOnly: currentOrder.reduceOnly,
39
+ postOnly: currentOrder.postOnly,
40
+ orderConfig: limitAuctionOrderConfig,
41
+ });
42
+ finalEditOrderParams = {
43
+ ...editOrderParams,
44
+ auctionDuration: limitAuctionOrderParams.auctionDuration,
45
+ auctionStartPrice: limitAuctionOrderParams.auctionStartPrice,
46
+ auctionEndPrice: limitAuctionOrderParams.auctionEndPrice,
47
+ };
48
+ }
16
49
  return driftClient.getModifyOrderIx({
17
50
  orderId,
18
- ...editOrderParams,
19
- }, undefined, userPublicKey);
51
+ ...finalEditOrderParams,
52
+ }, undefined, {
53
+ user,
54
+ authority: mainSignerOverride,
55
+ });
20
56
  };
21
57
  exports.createEditOrderIx = createEditOrderIx;
22
58
  /**
@@ -28,8 +64,8 @@ exports.createEditOrderIx = createEditOrderIx;
28
64
  * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)
29
65
  * @returns Promise that resolves to a Transaction or VersionedTransaction
30
66
  */
31
- const createEditOrderTxn = async (driftClient, user, orderId, editOrderParams, txParams) => {
32
- return driftClient.buildTransaction(await (0, exports.createEditOrderIx)(driftClient, user, orderId, editOrderParams), txParams);
67
+ const createEditOrderTxn = async ({ txParams, ...params }) => {
68
+ return params.driftClient.buildTransaction(await (0, exports.createEditOrderIx)(params), txParams);
33
69
  };
34
70
  exports.createEditOrderTxn = createEditOrderTxn;
35
71
  //# sourceMappingURL=editOrder.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"editOrder.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/editOrder.ts"],"names":[],"mappings":";;;AAgDA;;;;;;;GAOG;AACI,MAAM,iBAAiB,GAAG,KAAK,EACrC,WAAwB,EACxB,IAAU,EACV,OAAe,EACf,eAAgC,EACE,EAAE;IACpC,MAAM,aAAa,GAAG,IAAI,CAAC,uBAAuB,EAAE,CAAC;IACrD,MAAM,aAAa,GAAG,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;IAE1D,8BAA8B;IAE9B,OAAO,WAAW,CAAC,gBAAgB,CAClC;QACC,OAAO;QACP,GAAG,eAAe;KAClB,EACD,SAAS,EACT,aAAa,CACb,CAAC;AACH,CAAC,CAAC;AAnBW,QAAA,iBAAiB,qBAmB5B;AAEF;;;;;;;;GAQG;AACI,MAAM,kBAAkB,GAAG,KAAK,EACtC,WAAwB,EACxB,IAAU,EACV,OAAe,EACf,eAAgC,EAChC,QAAmB,EAC2B,EAAE;IAChD,OAAO,WAAW,CAAC,gBAAgB,CAClC,MAAM,IAAA,yBAAiB,EAAC,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,eAAe,CAAC,EACpE,QAAQ,CACR,CAAC;AACH,CAAC,CAAC;AAXW,QAAA,kBAAkB,sBAW7B","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tOrderTriggerCondition,\n\tPositionDirection,\n\tTxParams,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\n\n/**\n * Parameters for editing an existing order\n */\ninterface EditOrderParams {\n\t/** New direction for the order (long/short) */\n\tnewDirection?: PositionDirection;\n\t/** New base amount for the order */\n\tnewBaseAmount?: BN;\n\t/** New limit price for the order */\n\tnewLimitPrice?: BN;\n\t/** New oracle price offset for oracle market/limit orders */\n\tnewOraclePriceOffset?: number;\n\t/** New trigger price for conditional orders */\n\tnewTriggerPrice?: BN;\n\t/** New trigger condition for conditional orders */\n\tnewTriggerCondition?: OrderTriggerCondition;\n\t/** Duration of the auction in slots */\n\tauctionDuration?: number;\n\t/** Starting price for the auction */\n\tauctionStartPrice?: BN;\n\t/** Ending price for the auction */\n\tauctionEndPrice?: BN;\n\t/** Whether the order should only reduce position size */\n\treduceOnly?: boolean;\n\t/** Whether the order should only be posted (maker only) */\n\tpostOnly?: boolean;\n\t/** Bit flags for additional order configuration */\n\tbitFlags?: number;\n\t/** Maximum timestamp for order validity */\n\tmaxTs?: BN;\n\t/** Order policy configuration */\n\tpolicy?: number;\n}\n\n/**\n * Creates a transaction instruction to edit an existing order\n * @param driftClient - The DriftClient instance\n * @param userPublicKey - The public key of the user who owns the order\n * @param orderId - The ID of the order to edit\n * @param editOrderParams - Parameters containing the new order values\n * @returns Promise that resolves to a TransactionInstruction\n */\nexport const createEditOrderIx = async (\n\tdriftClient: DriftClient,\n\tuser: User,\n\torderId: number,\n\teditOrderParams: EditOrderParams\n): Promise<TransactionInstruction> => {\n\tconst userPublicKey = user.getUserAccountPublicKey();\n\tconst _currentOrder = user.getOrderByUserOrderId(orderId);\n\n\t// TODO: handle auction params\n\n\treturn driftClient.getModifyOrderIx(\n\t\t{\n\t\t\torderId,\n\t\t\t...editOrderParams,\n\t\t},\n\t\tundefined,\n\t\tuserPublicKey\n\t);\n};\n\n/**\n * Creates a complete transaction to edit an existing order\n * @param driftClient - The DriftClient instance\n * @param userPublicKey - The public key of the user who owns the order\n * @param orderId - The ID of the order to edit\n * @param editOrderParams - Parameters containing the new order values\n * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)\n * @returns Promise that resolves to a Transaction or VersionedTransaction\n */\nexport const createEditOrderTxn = async (\n\tdriftClient: DriftClient,\n\tuser: User,\n\torderId: number,\n\teditOrderParams: EditOrderParams,\n\ttxParams?: TxParams\n): Promise<Transaction | VersionedTransaction> => {\n\treturn driftClient.buildTransaction(\n\t\tawait createEditOrderIx(driftClient, user, orderId, editOrderParams),\n\t\ttxParams\n\t);\n};\n"]}
1
+ {"version":3,"file":"editOrder.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/editOrder.ts"],"names":[],"mappings":";;;;;;AAAA,yCAQyB;AAOzB,6CAA+C;AAC/C,oEAAuC;AACvC,qDAAqE;AAoDrE;;;;;;;;GAQG;AACI,MAAM,iBAAiB,GAAG,KAAK,EACrC,MAA+B,EACG,EAAE;IACpC,MAAM,EACL,WAAW,EACX,IAAI,EACJ,OAAO,EACP,eAAe,EACf,kBAAkB,EAClB,uBAAuB,GACvB,GAAG,MAAM,CAAC;IACX,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAE5C,IAAA,wBAAS,EAAC,YAAY,EAAE,yBAAyB,CAAC,CAAC;IAEnD,MAAM,YAAY,GAAG,kBAAU,CAAC,KAAK,CACpC,YAAY,CAAC,SAAS,EACtB,eAAS,CAAC,KAAK,CACf,CAAC;IAEF,IAAI,oBAAoB,GAAG,eAAe,CAAC;IAE3C,6CAA6C;IAC7C,IACC,YAAY;QACZ,uBAAuB;QACvB,kBAAU,CAAC,KAAK,CAAC,YAAY,CAAC,QAAQ,EAAE,oBAAc,CAAC,IAAI,CAAC,EAC3D,CAAC;QACF,MAAM,uBAAuB,GAAG,MAAM,IAAA,oCAA0B,EAAC;YAChE,WAAW;YACX,IAAI;YACJ,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,UAAU,EAAE,YAAY,CAAC,UAAU;YACnC,SAAS,EAAE,YAAY,CAAC,SAAS;YACjC,eAAe,EAAE,YAAY,CAAC,eAAe;YAC7C,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,UAAU,EAAE,YAAY,CAAC,UAAU;YACnC,QAAQ,EAAE,YAAY,CAAC,QAAQ;YAC/B,WAAW,EAAE,uBAAuB;SACpC,CAAC,CAAC;QAEH,oBAAoB,GAAG;YACtB,GAAG,eAAe;YAClB,eAAe,EAAE,uBAAuB,CAAC,eAAe;YACxD,iBAAiB,EAAE,uBAAuB,CAAC,iBAAiB;YAC5D,eAAe,EAAE,uBAAuB,CAAC,eAAe;SACxD,CAAC;IACH,CAAC;IAED,OAAO,WAAW,CAAC,gBAAgB,CAClC;QACC,OAAO;QACP,GAAG,oBAAoB;KACvB,EACD,SAAS,EACT;QACC,IAAI;QACJ,SAAS,EAAE,kBAAkB;KAC7B,CACD,CAAC;AACH,CAAC,CAAC;AA5DW,QAAA,iBAAiB,qBA4D5B;AAIF;;;;;;;;GAQG;AACI,MAAM,kBAAkB,GAAG,KAAK,EAAE,EACxC,QAAQ,EACR,GAAG,MAAM,EACiB,EAA+C,EAAE;IAC3E,OAAO,MAAM,CAAC,WAAW,CAAC,gBAAgB,CACzC,MAAM,IAAA,yBAAiB,EAAC,MAAM,CAAC,EAC/B,QAAQ,CACR,CAAC;AACH,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tOrderTriggerCondition,\n\tOrderType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../utils';\nimport invariant from 'tiny-invariant';\nimport { getLimitAuctionOrderParams } from './openPerpOrder/auction';\nimport {\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n} from './openPerpOrder/types';\nimport { WithTxnParams } from '../../types';\n\n/**\n * Parameters for editing an existing order\n */\ninterface EditOrderParams {\n\t/** New direction for the order (long/short) */\n\tnewDirection?: PositionDirection;\n\t/** New base amount for the order */\n\tnewBaseAmount?: BN;\n\t/** New limit price for the order */\n\tnewLimitPrice?: BN;\n\t/** New oracle price offset for oracle market/limit orders */\n\tnewOraclePriceOffset?: number;\n\t/** New trigger price for conditional orders */\n\tnewTriggerPrice?: BN;\n\t/** New trigger condition for conditional orders */\n\tnewTriggerCondition?: OrderTriggerCondition;\n\t/** Duration of the auction in slots */\n\tauctionDuration?: number;\n\t/** Starting price for the auction */\n\tauctionStartPrice?: BN;\n\t/** Ending price for the auction */\n\tauctionEndPrice?: BN;\n\t/** Whether the order should only reduce position size */\n\treduceOnly?: boolean;\n\t/** Whether the order should only be posted (maker only) */\n\tpostOnly?: boolean;\n\t/** Bit flags for additional order configuration */\n\tbitFlags?: number;\n\t/** Maximum timestamp for order validity */\n\tmaxTs?: BN;\n\t/** Order policy configuration */\n\tpolicy?: number;\n}\n\nexport interface CreateEditOrderIxParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\torderId: number;\n\teditOrderParams: EditOrderParams;\n\tmainSignerOverride?: PublicKey;\n\tlimitAuctionOrderConfig?: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}\n\n/**\n * Creates a transaction instruction to edit an existing order\n * @param driftClient - The DriftClient instance\n * @param userPublicKey - The public key of the user who owns the order\n * @param orderId - The ID of the order to edit\n * @param editOrderParams - Parameters containing the new order values\n * @param limitAuctionOrderConfig - Configuration for the limit auction order. If not provided, limit auction will not be enabled when relevant.\n * @returns Promise that resolves to a TransactionInstruction\n */\nexport const createEditOrderIx = async (\n\tparams: CreateEditOrderIxParams\n): Promise<TransactionInstruction> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\torderId,\n\t\teditOrderParams,\n\t\tmainSignerOverride,\n\t\tlimitAuctionOrderConfig,\n\t} = params;\n\tconst currentOrder = user.getOrder(orderId);\n\n\tinvariant(currentOrder, 'Current order not found');\n\n\tconst isLimitOrder = ENUM_UTILS.match(\n\t\tcurrentOrder.orderType,\n\t\tOrderType.LIMIT\n\t);\n\n\tlet finalEditOrderParams = editOrderParams;\n\n\t// handle limit auction if config is provided\n\tif (\n\t\tisLimitOrder &&\n\t\tlimitAuctionOrderConfig &&\n\t\tENUM_UTILS.match(currentOrder.postOnly, PostOnlyParams.NONE)\n\t) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex: currentOrder.marketIndex,\n\t\t\tmarketType: currentOrder.marketType,\n\t\t\tdirection: currentOrder.direction,\n\t\t\tbaseAssetAmount: currentOrder.baseAssetAmount,\n\t\t\tuserOrderId: currentOrder.userOrderId,\n\t\t\treduceOnly: currentOrder.reduceOnly,\n\t\t\tpostOnly: currentOrder.postOnly,\n\t\t\torderConfig: limitAuctionOrderConfig,\n\t\t});\n\n\t\tfinalEditOrderParams = {\n\t\t\t...editOrderParams,\n\t\t\tauctionDuration: limitAuctionOrderParams.auctionDuration,\n\t\t\tauctionStartPrice: limitAuctionOrderParams.auctionStartPrice,\n\t\t\tauctionEndPrice: limitAuctionOrderParams.auctionEndPrice,\n\t\t};\n\t}\n\n\treturn driftClient.getModifyOrderIx(\n\t\t{\n\t\t\torderId,\n\t\t\t...finalEditOrderParams,\n\t\t},\n\t\tundefined,\n\t\t{\n\t\t\tuser,\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n};\n\ntype CreateEditOrderTxnParams = WithTxnParams<CreateEditOrderIxParams>;\n\n/**\n * Creates a complete transaction to edit an existing order\n * @param driftClient - The DriftClient instance\n * @param userPublicKey - The public key of the user who owns the order\n * @param orderId - The ID of the order to edit\n * @param editOrderParams - Parameters containing the new order values\n * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)\n * @returns Promise that resolves to a Transaction or VersionedTransaction\n */\nexport const createEditOrderTxn = async ({\n\ttxParams,\n\t...params\n}: CreateEditOrderTxnParams): Promise<Transaction | VersionedTransaction> => {\n\treturn params.driftClient.buildTransaction(\n\t\tawait createEditOrderIx(params),\n\t\ttxParams\n\t);\n};\n"]}
@@ -0,0 +1,16 @@
1
+ import { PostOnlyParams, MarketType, BN, OptionalOrderParams, DriftClient, User, PositionDirection } from '@drift-labs/sdk';
2
+ import { LimitOrderParamsOrderConfig, LimitAuctionConfig } from './types';
3
+ export declare const getLimitAuctionOrderParams: ({ driftClient, user, marketIndex, marketType, direction, baseAssetAmount, userOrderId, reduceOnly, postOnly, orderConfig, }: {
4
+ driftClient: DriftClient;
5
+ user: User;
6
+ marketIndex: number;
7
+ marketType: MarketType;
8
+ direction: PositionDirection;
9
+ baseAssetAmount: BN;
10
+ userOrderId?: number;
11
+ reduceOnly?: boolean;
12
+ postOnly?: PostOnlyParams;
13
+ orderConfig: LimitOrderParamsOrderConfig & {
14
+ limitAuction: LimitAuctionConfig;
15
+ };
16
+ }) => Promise<OptionalOrderParams>;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getLimitAuctionOrderParams = void 0;
7
+ const sdk_1 = require("@drift-labs/sdk");
8
+ const common_ui_utils_1 = require("../../../../../common-ui-utils");
9
+ const auction_1 = require("../../../constants/auction");
10
+ const utils_1 = require("../../../../../utils");
11
+ const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
12
+ const dlobServer_1 = require("./dlobServer");
13
+ const getLimitAuctionOrderParams = async ({ driftClient, user, marketIndex, marketType, direction, baseAssetAmount, userOrderId = 0, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, }) => {
14
+ const orderParams = await (0, dlobServer_1.fetchAuctionOrderParams)({
15
+ driftClient,
16
+ user,
17
+ assetType: 'base',
18
+ marketIndex,
19
+ marketType,
20
+ direction,
21
+ amount: baseAssetAmount,
22
+ dlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,
23
+ optionalAuctionParamsInputs: orderConfig.limitAuction.optionalLimitAuctionParams,
24
+ });
25
+ const isPerp = utils_1.ENUM_UTILS.match(marketType, sdk_1.MarketType.PERP);
26
+ (0, tiny_invariant_1.default)(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');
27
+ (0, tiny_invariant_1.default)(orderParams.auctionStartPrice, 'Auction start price not found');
28
+ let oraclePriceBands = undefined;
29
+ let auctionDuration = auction_1.DEFAULT_LIMIT_AUCTION_DURATION;
30
+ if (isPerp) {
31
+ const perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);
32
+ (0, tiny_invariant_1.default)(isPerp && perpMarketAccount, 'Perp market account not found');
33
+ oraclePriceBands = orderConfig.limitAuction.oraclePrice
34
+ ? (0, sdk_1.oraclePriceBands)(perpMarketAccount, {
35
+ price: orderConfig.limitAuction.oraclePrice,
36
+ })
37
+ : undefined;
38
+ auctionDuration = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpAuctionDuration(orderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(), orderConfig.limitAuction.oraclePrice, perpMarketAccount.contractTier);
39
+ }
40
+ const limitAuctionParams = common_ui_utils_1.COMMON_UI_UTILS.getLimitAuctionParams({
41
+ direction,
42
+ inputPrice: sdk_1.BigNum.from(orderConfig.limitPrice, sdk_1.PRICE_PRECISION_EXP),
43
+ startPriceFromSettings: orderParams.auctionStartPrice,
44
+ duration: auctionDuration,
45
+ auctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,
46
+ oraclePriceBands,
47
+ });
48
+ const limitAuctionOrderParams = (0, sdk_1.getLimitOrderParams)({
49
+ marketIndex,
50
+ marketType,
51
+ direction,
52
+ baseAssetAmount,
53
+ reduceOnly,
54
+ postOnly,
55
+ price: orderConfig.limitPrice,
56
+ userOrderId,
57
+ ...limitAuctionParams,
58
+ });
59
+ const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
60
+ const totalQuoteAmount = baseAssetAmount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
61
+ const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
62
+ return {
63
+ ...limitAuctionOrderParams,
64
+ bitFlags,
65
+ };
66
+ };
67
+ exports.getLimitAuctionOrderParams = getLimitAuctionOrderParams;
68
+ //# sourceMappingURL=auction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auction.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/auction.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,oEAGwC;AACxC,wDAA4E;AAC5E,gDAAkD;AAClD,oEAAuC;AACvC,6CAAuD;AAGhD,MAAM,0BAA0B,GAAG,KAAK,EAAE,EAChD,WAAW,EACX,IAAI,EACJ,WAAW,EACX,UAAU,EACV,SAAS,EACT,eAAe,EACf,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,GAcX,EAAgC,EAAE;IAClC,MAAM,WAAW,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACjD,WAAW;QACX,IAAI;QACJ,SAAS,EAAE,MAAM;QACjB,WAAW;QACX,UAAU;QACV,SAAS;QACT,MAAM,EAAE,eAAe;QACvB,iBAAiB,EAAE,WAAW,CAAC,YAAY,CAAC,iBAAiB;QAC7D,2BAA2B,EAC1B,WAAW,CAAC,YAAY,CAAC,0BAA0B;KACpD,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,kBAAU,CAAC,KAAK,CAAC,UAAU,EAAE,gBAAU,CAAC,IA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AU;QACV,QAAQ;QACR,KAAK,EAAE,WAAW,CAAC,UAAU;QAC7B,WAAW;QACX,GAAG,kBAAkB;KACrB,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,WAAW,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC;IAC9E,MAAM,gBAAgB,GAAG,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,oBAAc,CAAC,CAAC;IAE9E,MAAM,QAAQ,GAAG,oCAAkB,CAAC,0BAA0B,CAC7D,WAAW,EACX,WAAW,EACX,IAAI,EACJ,gBAAgB,EAChB,SAAS,CACT,CAAC;IAEF,OAAO;QACN,GAAG,uBAAuB;QAC1B,QAAQ;KACR,CAAC;AACH,CAAC,CAAC;AAnGW,QAAA,0BAA0B,8BAmGrC","sourcesContent":["import {\n\tPostOnlyParams,\n\tMarketType,\n\tBN,\n\tOptionalOrderParams,\n\tBigNum,\n\tPRICE_PRECISION_EXP,\n\tgetLimitOrderParams,\n\tBASE_PRECISION,\n\toraclePriceBands as getOraclePriceBands,\n\tDriftClient,\n\tUser,\n\tPositionDirection,\n} from '@drift-labs/sdk';\nimport {\n\tORDER_COMMON_UTILS,\n\tCOMMON_UI_UTILS,\n} from '../../../../../common-ui-utils';\nimport { DEFAULT_LIMIT_AUCTION_DURATION } from '../../../constants/auction';\nimport { ENUM_UTILS } from '../../../../../utils';\nimport invariant from 'tiny-invariant';\nimport { fetchAuctionOrderParams } from './dlobServer';\nimport { LimitOrderParamsOrderConfig, LimitAuctionConfig } from './types';\n\nexport const getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tbaseAssetAmount,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n}: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\tuserOrderId?: number;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}): Promise<OptionalOrderParams> => {\n\tconst orderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType: 'base',\n\t\tmarketIndex,\n\t\tmarketType,\n\t\tdirection,\n\t\tamount: baseAssetAmount,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t});\n\n\tconst isPerp = ENUM_UTILS.match(marketType, MarketType.PERP);\n\n\tinvariant(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');\n\tinvariant(orderParams.auctionStartPrice, 'Auction start price not found');\n\n\tlet oraclePriceBands: [BN, BN] | undefined = undefined;\n\tlet auctionDuration = DEFAULT_LIMIT_AUCTION_DURATION;\n\n\tif (isPerp) {\n\t\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\t\tinvariant(isPerp && perpMarketAccount, 'Perp market account not found');\n\n\t\toraclePriceBands = orderConfig.limitAuction.oraclePrice\n\t\t\t? getOraclePriceBands(perpMarketAccount, {\n\t\t\t\t\tprice: orderConfig.limitAuction.oraclePrice,\n\t\t\t })\n\t\t\t: undefined;\n\n\t\tauctionDuration = ORDER_COMMON_UTILS.getPerpAuctionDuration(\n\t\t\torderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(),\n\t\t\torderConfig.limitAuction.oraclePrice,\n\t\t\tperpMarketAccount.contractTier\n\t\t);\n\t}\n\n\tconst limitAuctionParams = COMMON_UI_UTILS.getLimitAuctionParams({\n\t\tdirection,\n\t\tinputPrice: BigNum.from(orderConfig.limitPrice, PRICE_PRECISION_EXP),\n\t\tstartPriceFromSettings: orderParams.auctionStartPrice,\n\t\tduration: auctionDuration,\n\t\tauctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,\n\t\toraclePriceBands,\n\t});\n\n\tconst limitAuctionOrderParams = getLimitOrderParams({\n\t\tmarketIndex,\n\t\tmarketType,\n\t\tdirection,\n\t\tbaseAssetAmount,\n\t\treduceOnly,\n\t\tpostOnly,\n\t\tprice: orderConfig.limitPrice,\n\t\tuserOrderId,\n\t\t...limitAuctionParams,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = baseAssetAmount.mul(oraclePrice).div(BASE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n"]}
@@ -24,7 +24,7 @@ interface RegularOrderParams {
24
24
  driftClient: DriftClient;
25
25
  user: User;
26
26
  assetType: 'base' | 'quote';
27
- marketType?: MarketType;
27
+ marketType: MarketType;
28
28
  marketIndex: number;
29
29
  direction: PositionDirection;
30
30
  amount: BN;
@@ -88,17 +88,29 @@ async function fetchAuctionOrderParams(params) {
88
88
  }
89
89
  }
90
90
  exports.fetchAuctionOrderParams = fetchAuctionOrderParams;
91
+ const calcBaseFromQuote = (driftClient, marketType, marketIndex, amount) => {
92
+ const isPerp = utils_1.ENUM_UTILS.match(marketType, sdk_1.MarketType.PERP);
93
+ const oraclePrice = isPerp
94
+ ? driftClient.getOracleDataForPerpMarket(marketIndex).price
95
+ : driftClient.getOracleDataForSpotMarket(marketIndex).price;
96
+ if (isPerp) {
97
+ return amount.mul(sdk_1.BASE_PRECISION).div(oraclePrice);
98
+ }
99
+ else {
100
+ const spotMarketAccount = driftClient.getSpotMarketAccount(marketIndex);
101
+ (0, tiny_invariant_1.default)(spotMarketAccount, 'Spot market account not found');
102
+ const precision = sdk_1.TEN.pow(new sdk_1.BN(spotMarketAccount.decimals));
103
+ return amount.mul(precision).div(oraclePrice);
104
+ }
105
+ };
91
106
  /**
92
107
  * Fetches auction order parameters from the auction params endpoint
93
108
  */
94
- async function fetchAuctionOrderParamsFromDlob({ marketIndex, marketType = sdk_1.MarketType.PERP, direction, amount, dlobServerHttpUrl, assetType, driftClient, optionalAuctionParamsInputs = {}, }) {
109
+ async function fetchAuctionOrderParamsFromDlob({ marketIndex, marketType, direction, amount, dlobServerHttpUrl, assetType, driftClient, optionalAuctionParamsInputs = {}, }) {
95
110
  var _a, _b, _c, _d;
96
111
  const baseAmount = assetType === 'base'
97
112
  ? amount
98
- : (() => {
99
- const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
100
- return amount.mul(sdk_1.BASE_PRECISION).div(oraclePrice);
101
- })();
113
+ : calcBaseFromQuote(driftClient, marketType, marketIndex, amount);
102
114
  // Build URL parameters for server request
103
115
  const urlParamsObject = {
104
116
  // Required fields
@@ -154,10 +166,7 @@ async function fetchAuctionOrderParamsFromL2({ dlobServerHttpUrl, marketIndex, m
154
166
  const marketId = new types_1.MarketId(marketIndex, marketType);
155
167
  const baseAmount = assetType === 'base'
156
168
  ? amount
157
- : (() => {
158
- const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
159
- return amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
160
- })();
169
+ : calcBaseFromQuote(driftClient, marketType, marketIndex, amount);
161
170
  const l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [
162
171
  {
163
172
  marketId,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/dlobServer/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,mDAAqD;AACrD,kGAI0D;AAC1D,yDAAkE;AAClE,mDAAqE;AACrE,iEAO2C;AAC3C,uFAAoF;AACpF,qEAAiF;AACjF,uEAAoE;AACpE,o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AAC;QACZ,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC;AA3CD,wCA2CC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tUserAccount,\n\tPublicKey,\n\tdecodeUser,\n\tDefaultOrderParams,\n\tPRICE_PRECISION,\n\tBASE_PRECISION,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/fetch';\nimport { MarketId, TradeOffsetPrice } from '../../../../../../types';\nimport {\n\tconvertToL2OrderBook,\n\tdeserializeL2Response,\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport { PollingSequenceGuard } from '../../../../../../utils/pollingSequenceGuard';\nimport { calculatePriceImpactFromL2 } from '../../../../../../utils/priceImpact';\nimport { COMMON_UI_UTILS } from '../../../../../../common-ui-utils';\nimport invariant from 'tiny-invariant';\n\nexport interface OptionalAuctionParamsRequestInputs {\n\t// Optional parameters that can override defaults or provide additional configuration\n\tmaxLeverageSelected?: boolean;\n\tmaxLeverageOrderSize?: BN;\n\treduceOnly?: boolean;\n\tauctionDuration?: number;\n\tauctionStartPriceOffset?: number;\n\tauctionEndPriceOffset?: number;\n\tauctionStartPriceOffsetFrom?: TradeOffsetPrice;\n\tauctionEndPriceOffsetFrom?: TradeOffsetPrice;\n\tslippageTolerance?: number | 'dynamic';\n\tauctionPriceCaps?: {\n\t\tmin: BN;\n\t\tmax: BN;\n\t};\n\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\n\torderType?: 'market' | 'oracle';\n}\n\ninterface RegularOrderParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketType?: MarketType;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdlobServerHttpUrl: string;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n}\n\nexport interface BulkL2FetchingQueryParams {\n\tmarketIndex: number;\n\tmarketType: string;\n\tdepth: number;\n\tincludeVamm: boolean;\n\tincludePhoenix: boolean;\n\tincludeOpenbook: boolean;\n\tincludeSerum: boolean;\n\tincludeOracle: boolean;\n\tincludeIndicative: boolean;\n}\n\nexport interface BulkL2FetchingParams {\n\tmarkets: BulkL2FetchingQueryParams[];\n\tgrouping?: number;\n}\n\nconst BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');\n\n/**\n * Fetches the L2 data for the given markets and their depth\n */\nexport function fetchBulkMarketsDlobL2Data(\n\tdlobServerHttpUrl: string,\n\tmarkets: {\n\t\tmarketId: MarketId;\n\t\tdepth: number;\n\t}[],\n\tgroupingSize?: number,\n\texcludeIndicativeLiquidity = false\n): Promise<L2WithOracleAndMarketData[]> {\n\tconst params: BulkL2FetchingParams = {\n\t\tmarkets: markets.map((m) => ({\n\t\t\tmarketIndex: m.marketId.marketIndex,\n\t\t\tmarketType: m.marketId.marketTypeStr,\n\t\t\tdepth: m.depth,\n\t\t\tincludeVamm: m.marketId.isPerp,\n\t\t\tincludePhoenix: m.marketId.isSpot,\n\t\t\tincludeSerum: m.marketId.isSpot,\n\t\t\tincludeOpenbook: m.marketId.isSpot,\n\t\t\tincludeOracle: true,\n\t\t\tincludeIndicative: !excludeIndicativeLiquidity,\n\t\t})),\n\t\tgrouping: groupingSize,\n\t};\n\n\tconst queryParamsMap: {\n\t\t[K in keyof BulkL2FetchingQueryParams]: string;\n\t} & {\n\t\tgrouping?: string;\n\t} = {\n\t\tmarketType: params.markets.map((market) => market.marketType).join(','),\n\t\tmarketIndex: params.markets.map((market) => market.marketIndex).join(','),\n\t\tdepth: params.markets.map((market) => market.depth).join(','),\n\t\tincludeVamm: params.markets.map((market) => market.includeVamm).join(','),\n\t\tincludePhoenix: params.markets\n\t\t\t.map((market) => market.includePhoenix)\n\t\t\t.join(','),\n\t\tincludeOpenbook: params.markets\n\t\t\t.map((market) => market.includeOpenbook)\n\t\t\t.join(','),\n\t\tincludeSerum: params.markets.map((market) => market.includeSerum).join(','),\n\t\tgrouping: params.grouping\n\t\t\t? params.markets.map(() => params.grouping).join(',')\n\t\t\t: undefined,\n\t\tincludeOracle: params.markets\n\t\t\t.map((market) => market.includeOracle)\n\t\t\t.join(','),\n\t\tincludeIndicative: params.markets\n\t\t\t.map((market) => market.includeIndicative)\n\t\t\t.join(','),\n\t};\n\n\tconst queryParams = encodeQueryParams(queryParamsMap);\n\n\t// Use cached endpoint when exclusively fetching background markets\n\tconst useCachedEndpoint = !params.markets.some(\n\t\t(market) => market.depth !== 1\n\t);\n\n\tconst endpoint = useCachedEndpoint\n\t\t? `${dlobServerHttpUrl}/batchL2Cache`\n\t\t: `${dlobServerHttpUrl}/batchL2`;\n\n\treturn new Promise<L2WithOracleAndMarketData[]>((resolve, reject) => {\n\t\tPollingSequenceGuard.fetch(BACKGROUND_L2_POLLING_KEY, () => {\n\t\t\treturn fetch(`${endpoint}?${queryParams}`);\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tconst responseData = await response.json();\n\t\t\t\tconst resultsArray = responseData.l2s as RawL2Output[];\n\t\t\t\tconst deserializedL2 = resultsArray.map(deserializeL2Response);\n\t\t\t\tresolve(deserializedL2);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t});\n}\n\nexport async function fetchAuctionOrderParams(params: RegularOrderParams) {\n\ttry {\n\t\treturn await fetchAuctionOrderParamsFromDlob(params);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tconsole.log('Falling back to L2 data');\n\t\treturn await fetchAuctionOrderParamsFromL2(params);\n\t}\n}\n\n/**\n * Fetches auction order parameters from the auction params endpoint\n */\nexport async function fetchAuctionOrderParamsFromDlob({\n\tmarketIndex,\n\tmarketType = MarketType.PERP,\n\tdirection,\n\tamount,\n\tdlobServerHttpUrl,\n\tassetType,\n\tdriftClient,\n\toptionalAuctionParamsInputs = {},\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(BASE_PRECISION).div(oraclePrice);\n\t\t\t })();\n\n\t// Build URL parameters for server request\n\tconst urlParamsObject: Record<string, string> = {\n\t\t// Required fields\n\t\tassetType: 'base',\n\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\tmarketIndex: marketIndex.toString(),\n\t\tdirection: ENUM_UTILS.toStr(direction),\n\t\tamount: baseAmount.toString(),\n\t};\n\n\t// Add defined optional parameters\n\tObject.entries(optionalAuctionParamsInputs).forEach(([key, value]) => {\n\t\tif (value !== undefined) {\n\t\t\turlParamsObject[key] = value.toString();\n\t\t}\n\t});\n\n\tconst urlParams = encodeQueryParams(urlParamsObject);\n\n\t// Get order params from server\n\tconst requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;\n\tconst response = await fetch(requestUrl);\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\tconst serverResponse: ServerAuctionParamsResponse = await response.json();\n\tconst serverAuctionParams = serverResponse?.data?.params;\n\tinvariant(serverAuctionParams, 'Server auction params are required');\n\tconst mappedParams: MappedAuctionParams =\n\t\tmapAuctionParamsResponse(serverAuctionParams);\n\n\t// Convert MappedAuctionParams to OptionalOrderParams\n\treturn {\n\t\torderType: mappedParams.orderType,\n\t\tmarketType: mappedParams.marketType,\n\t\tuserOrderId: mappedParams.userOrderId,\n\t\tdirection: mappedParams.direction,\n\t\tbaseAssetAmount: mappedParams.baseAssetAmount,\n\t\tmarketIndex: mappedParams.marketIndex,\n\t\treduceOnly: mappedParams.reduceOnly,\n\t\tpostOnly: mappedParams.postOnly ?? DefaultOrderParams.postOnly,\n\t\ttriggerPrice: mappedParams.triggerPrice || null,\n\t\ttriggerCondition:\n\t\t\tmappedParams.triggerCondition ?? DefaultOrderParams.triggerCondition,\n\t\toraclePriceOffset: mappedParams.oraclePriceOffset?.toNumber() || null,\n\t\tauctionDuration: mappedParams.auctionDuration || null,\n\t\tmaxTs: mappedParams.maxTs,\n\t\tauctionStartPrice: mappedParams.auctionStartPrice || null,\n\t\tauctionEndPrice: mappedParams.auctionEndPrice || null,\n\t\t// no price, because market orders don't need a price\n\t};\n}\n\nconst DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS = 100;\n\n/**\n * Fetches auction order parameters from the L2 data\n */\nexport async function fetchAuctionOrderParamsFromL2({\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tassetType,\n\tamount,\n\toptionalAuctionParamsInputs,\n\tdriftClient,\n\tdynamicSlippageConfig,\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst marketId = new MarketId(marketIndex, marketType);\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\tconst l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [\n\t\t{\n\t\t\tmarketId,\n\t\t\tdepth: DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS,\n\t\t},\n\t]);\n\tconst oraclePriceData = l2DataResponse[0].oracleData;\n\tconst oraclePriceBn = oraclePriceData?.price;\n\tconst markPriceBn = l2DataResponse[0].markPrice;\n\tconst l2Data = convertToL2OrderBook(l2DataResponse);\n\n\tconst priceImpactData = calculatePriceImpactFromL2(\n\t\tmarketId,\n\t\tdirection,\n\t\tbaseAmount,\n\t\tl2Data,\n\t\toraclePriceBn\n\t);\n\n\tconst startPrices = COMMON_UI_UTILS.getPriceObject({\n\t\toraclePrice: oraclePriceBn,\n\t\tbestOffer: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tdirection: direction,\n\t});\n\tconst slippageToleranceInput = optionalAuctionParamsInputs.slippageTolerance;\n\tconst derivedSlippage =\n\t\tslippageToleranceInput === 'dynamic'\n\t\t\t? calculateDynamicSlippageFromL2({\n\t\t\t\t\tl2Data,\n\t\t\t\t\tmarketId,\n\t\t\t\t\tstartPrice:\n\t\t\t\t\t\tstartPrices[\n\t\t\t\t\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom as keyof typeof startPrices\n\t\t\t\t\t\t],\n\t\t\t\t\tworstPrice: priceImpactData.worstPrice,\n\t\t\t\t\toraclePrice: oraclePriceBn,\n\t\t\t\t\tdynamicSlippageConfig,\n\t\t\t })\n\t\t\t: typeof slippageToleranceInput === 'number'\n\t\t\t? slippageToleranceInput\n\t\t\t: 0.005;\n\n\tconst auctionOrderParams = COMMON_UI_UTILS.deriveMarketOrderParams({\n\t\tmarketType: marketType,\n\t\tmarketIndex: marketIndex,\n\t\tdirection: direction,\n\t\tmaxLeverageSelected: optionalAuctionParamsInputs.maxLeverageSelected,\n\t\tmaxLeverageOrderSize: optionalAuctionParamsInputs.maxLeverageOrderSize,\n\t\tbaseAmount: baseAmount,\n\t\treduceOnly: optionalAuctionParamsInputs.reduceOnly,\n\t\tallowInfSlippage: false,\n\t\toraclePrice: oraclePriceBn,\n\t\tbestPrice: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tauctionDuration: optionalAuctionParamsInputs.auctionDuration,\n\t\tauctionStartPriceOffset:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffset,\n\t\tauctionEndPriceOffset: optionalAuctionParamsInputs.auctionEndPriceOffset,\n\t\tauctionStartPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom,\n\t\tauctionEndPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionEndPriceOffsetFrom,\n\t\tslippageTolerance: derivedSlippage,\n\t\tisOracleOrder: optionalAuctionParamsInputs.isOracleOrder,\n\t\tadditionalEndPriceBuffer:\n\t\t\toptionalAuctionParamsInputs.additionalEndPriceBuffer,\n\t\tforceUpToSlippage: optionalAuctionParamsInputs.forceUpToSlippage,\n\t});\n\n\tif (!auctionOrderParams) {\n\t\tthrow new Error('Failed to derive auction params from L2');\n\t}\n\n\treturn auctionOrderParams;\n}\n\ntype FetchTopMakersParams = {\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tside: 'bid' | 'ask';\n\tlimit: number;\n};\n\n/**\n * Fetches the top makers information, for use as inputs in placeAndTake market orders.\n * The side of the request should be opposite of the side of the placeAndTake market order.\n */\nexport async function fetchTopMakers(params: FetchTopMakersParams): Promise<\n\t{\n\t\tuserAccountPubKey: PublicKey;\n\t\tuserAccount: UserAccount;\n\t}[]\n> {\n\ttry {\n\t\tconst { dlobServerHttpUrl, marketIndex, marketType, side, limit } = params;\n\n\t\tconst urlParams = encodeQueryParams({\n\t\t\tmarketIndex: marketIndex.toString(),\n\t\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\t\tside,\n\t\t\tlimit: limit.toString(),\n\t\t\tincludeAccounts: 'true',\n\t\t});\n\n\t\tconst requestUrl = `${dlobServerHttpUrl}/topMakers?${urlParams}`;\n\t\tconst response = await fetch(requestUrl);\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t\t);\n\t\t}\n\n\t\tconst serverResponse: {\n\t\t\tuserAccountPubKey: string;\n\t\t\taccountBase64: string;\n\t\t}[] = await response.json();\n\t\tconst mappedParams: {\n\t\t\tuserAccountPubKey: PublicKey;\n\t\t\tuserAccount: UserAccount;\n\t\t}[] = serverResponse.map((value) => ({\n\t\t\tuserAccountPubKey: new PublicKey(value.userAccountPubKey),\n\t\t\tuserAccount: decodeUser(Buffer.from(value.accountBase64, 'base64')),\n\t\t}));\n\n\t\treturn mappedParams;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn [];\n\t}\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/dlobServer/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,mDAAqD;AACrD,kGAI0D;AAC1D,yDAAkE;AAClE,mDAAqE;AACrE,iEAO2C;AAC3C,uFAAoF;AACpF,qEAAiF;AACjF,uEAAoE;AACpE,oEAAuC;AAqDvC,MAAM,yBAAyB,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAEtE;;GAEG;AACH,SAAgB,0BAA0B,CACzC,iBAAyB,EACzB,OAGG,EACH,YAAqB,EACrB,0BAA0B,GAAG,KAAK;IAElC,MAAM,MAAM,GAAyB;QACpC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC5B,WAAW,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW;YACnC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,aAAa;YACpC,KAAK,EAAE,CAAC,CAAC,KAAK;YACd,WAAW,EAAE,CAAC,CAAC,QAAQ,CAAC,MAAM;YAC9B,cAAc,EAAE,CAAC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OAAO,YAAY,CAAC;IACrB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC;AA3CD,wCA2CC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tUserAccount,\n\tPublicKey,\n\tdecodeUser,\n\tDefaultOrderParams,\n\tBASE_PRECISION,\n\tTEN,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/fetch';\nimport { MarketId, TradeOffsetPrice } from '../../../../../../types';\nimport {\n\tconvertToL2OrderBook,\n\tdeserializeL2Response,\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport { PollingSequenceGuard } from '../../../../../../utils/pollingSequenceGuard';\nimport { calculatePriceImpactFromL2 } from '../../../../../../utils/priceImpact';\nimport { COMMON_UI_UTILS } from '../../../../../../common-ui-utils';\nimport invariant from 'tiny-invariant';\n\nexport interface OptionalAuctionParamsRequestInputs {\n\t// Optional parameters that can override defaults or provide additional configuration\n\tmaxLeverageSelected?: boolean;\n\tmaxLeverageOrderSize?: BN;\n\treduceOnly?: boolean;\n\tauctionDuration?: number;\n\tauctionStartPriceOffset?: number;\n\tauctionEndPriceOffset?: number;\n\tauctionStartPriceOffsetFrom?: TradeOffsetPrice;\n\tauctionEndPriceOffsetFrom?: TradeOffsetPrice;\n\tslippageTolerance?: number | 'dynamic';\n\tauctionPriceCaps?: {\n\t\tmin: BN;\n\t\tmax: BN;\n\t};\n\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\n\torderType?: 'market' | 'oracle';\n}\n\ninterface RegularOrderParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketType: MarketType;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdlobServerHttpUrl: string;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n}\n\nexport interface BulkL2FetchingQueryParams {\n\tmarketIndex: number;\n\tmarketType: string;\n\tdepth: number;\n\tincludeVamm: boolean;\n\tincludePhoenix: boolean;\n\tincludeOpenbook: boolean;\n\tincludeSerum: boolean;\n\tincludeOracle: boolean;\n\tincludeIndicative: boolean;\n}\n\nexport interface BulkL2FetchingParams {\n\tmarkets: BulkL2FetchingQueryParams[];\n\tgrouping?: number;\n}\n\nconst BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');\n\n/**\n * Fetches the L2 data for the given markets and their depth\n */\nexport function fetchBulkMarketsDlobL2Data(\n\tdlobServerHttpUrl: string,\n\tmarkets: {\n\t\tmarketId: MarketId;\n\t\tdepth: number;\n\t}[],\n\tgroupingSize?: number,\n\texcludeIndicativeLiquidity = false\n): Promise<L2WithOracleAndMarketData[]> {\n\tconst params: BulkL2FetchingParams = {\n\t\tmarkets: markets.map((m) => ({\n\t\t\tmarketIndex: m.marketId.marketIndex,\n\t\t\tmarketType: m.marketId.marketTypeStr,\n\t\t\tdepth: m.depth,\n\t\t\tincludeVamm: m.marketId.isPerp,\n\t\t\tincludePhoenix: m.marketId.isSpot,\n\t\t\tincludeSerum: m.marketId.isSpot,\n\t\t\tincludeOpenbook: m.marketId.isSpot,\n\t\t\tincludeOracle: true,\n\t\t\tincludeIndicative: !excludeIndicativeLiquidity,\n\t\t})),\n\t\tgrouping: groupingSize,\n\t};\n\n\tconst queryParamsMap: {\n\t\t[K in keyof BulkL2FetchingQueryParams]: string;\n\t} & {\n\t\tgrouping?: string;\n\t} = {\n\t\tmarketType: params.markets.map((market) => market.marketType).join(','),\n\t\tmarketIndex: params.markets.map((market) => market.marketIndex).join(','),\n\t\tdepth: params.markets.map((market) => market.depth).join(','),\n\t\tincludeVamm: params.markets.map((market) => market.includeVamm).join(','),\n\t\tincludePhoenix: params.markets\n\t\t\t.map((market) => market.includePhoenix)\n\t\t\t.join(','),\n\t\tincludeOpenbook: params.markets\n\t\t\t.map((market) => market.includeOpenbook)\n\t\t\t.join(','),\n\t\tincludeSerum: params.markets.map((market) => market.includeSerum).join(','),\n\t\tgrouping: params.grouping\n\t\t\t? params.markets.map(() => params.grouping).join(',')\n\t\t\t: undefined,\n\t\tincludeOracle: params.markets\n\t\t\t.map((market) => market.includeOracle)\n\t\t\t.join(','),\n\t\tincludeIndicative: params.markets\n\t\t\t.map((market) => market.includeIndicative)\n\t\t\t.join(','),\n\t};\n\n\tconst queryParams = encodeQueryParams(queryParamsMap);\n\n\t// Use cached endpoint when exclusively fetching background markets\n\tconst useCachedEndpoint = !params.markets.some(\n\t\t(market) => market.depth !== 1\n\t);\n\n\tconst endpoint = useCachedEndpoint\n\t\t? `${dlobServerHttpUrl}/batchL2Cache`\n\t\t: `${dlobServerHttpUrl}/batchL2`;\n\n\treturn new Promise<L2WithOracleAndMarketData[]>((resolve, reject) => {\n\t\tPollingSequenceGuard.fetch(BACKGROUND_L2_POLLING_KEY, () => {\n\t\t\treturn fetch(`${endpoint}?${queryParams}`);\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tconst responseData = await response.json();\n\t\t\t\tconst resultsArray = responseData.l2s as RawL2Output[];\n\t\t\t\tconst deserializedL2 = resultsArray.map(deserializeL2Response);\n\t\t\t\tresolve(deserializedL2);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t});\n}\n\nexport async function fetchAuctionOrderParams(params: RegularOrderParams) {\n\ttry {\n\t\treturn await fetchAuctionOrderParamsFromDlob(params);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tconsole.log('Falling back to L2 data');\n\t\treturn await fetchAuctionOrderParamsFromL2(params);\n\t}\n}\n\nconst calcBaseFromQuote = (\n\tdriftClient: DriftClient,\n\tmarketType: MarketType,\n\tmarketIndex: number,\n\tamount: BN\n) => {\n\tconst isPerp = ENUM_UTILS.match(marketType, MarketType.PERP);\n\n\tconst oraclePrice = isPerp\n\t\t? driftClient.getOracleDataForPerpMarket(marketIndex).price\n\t\t: driftClient.getOracleDataForSpotMarket(marketIndex).price;\n\n\tif (isPerp) {\n\t\treturn amount.mul(BASE_PRECISION).div(oraclePrice);\n\t} else {\n\t\tconst spotMarketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\t\tinvariant(spotMarketAccount, 'Spot market account not found');\n\t\tconst precision = TEN.pow(new BN(spotMarketAccount.decimals));\n\t\treturn amount.mul(precision).div(oraclePrice);\n\t}\n};\n\n/**\n * Fetches auction order parameters from the auction params endpoint\n */\nexport async function fetchAuctionOrderParamsFromDlob({\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tamount,\n\tdlobServerHttpUrl,\n\tassetType,\n\tdriftClient,\n\toptionalAuctionParamsInputs = {},\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: calcBaseFromQuote(driftClient, marketType, marketIndex, amount);\n\n\t// Build URL parameters for server request\n\tconst urlParamsObject: Record<string, string> = {\n\t\t// Required fields\n\t\tassetType: 'base',\n\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\tmarketIndex: marketIndex.toString(),\n\t\tdirection: ENUM_UTILS.toStr(direction),\n\t\tamount: baseAmount.toString(),\n\t};\n\n\t// Add defined optional parameters\n\tObject.entries(optionalAuctionParamsInputs).forEach(([key, value]) => {\n\t\tif (value !== undefined) {\n\t\t\turlParamsObject[key] = value.toString();\n\t\t}\n\t});\n\n\tconst urlParams = encodeQueryParams(urlParamsObject);\n\n\t// Get order params from server\n\tconst requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;\n\tconst response = await fetch(requestUrl);\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\tconst serverResponse: ServerAuctionParamsResponse = await response.json();\n\tconst serverAuctionParams = serverResponse?.data?.params;\n\tinvariant(serverAuctionParams, 'Server auction params are required');\n\tconst mappedParams: MappedAuctionParams =\n\t\tmapAuctionParamsResponse(serverAuctionParams);\n\n\t// Convert MappedAuctionParams to OptionalOrderParams\n\treturn {\n\t\torderType: mappedParams.orderType,\n\t\tmarketType: mappedParams.marketType,\n\t\tuserOrderId: mappedParams.userOrderId,\n\t\tdirection: mappedParams.direction,\n\t\tbaseAssetAmount: mappedParams.baseAssetAmount,\n\t\tmarketIndex: mappedParams.marketIndex,\n\t\treduceOnly: mappedParams.reduceOnly,\n\t\tpostOnly: mappedParams.postOnly ?? DefaultOrderParams.postOnly,\n\t\ttriggerPrice: mappedParams.triggerPrice || null,\n\t\ttriggerCondition:\n\t\t\tmappedParams.triggerCondition ?? DefaultOrderParams.triggerCondition,\n\t\toraclePriceOffset: mappedParams.oraclePriceOffset?.toNumber() || null,\n\t\tauctionDuration: mappedParams.auctionDuration || null,\n\t\tmaxTs: mappedParams.maxTs,\n\t\tauctionStartPrice: mappedParams.auctionStartPrice || null,\n\t\tauctionEndPrice: mappedParams.auctionEndPrice || null,\n\t\t// no price, because market orders don't need a price\n\t};\n}\n\nconst DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS = 100;\n\n/**\n * Fetches auction order parameters from the L2 data\n */\nexport async function fetchAuctionOrderParamsFromL2({\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tassetType,\n\tamount,\n\toptionalAuctionParamsInputs,\n\tdriftClient,\n\tdynamicSlippageConfig,\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst marketId = new MarketId(marketIndex, marketType);\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: calcBaseFromQuote(driftClient, marketType, marketIndex, amount);\n\n\tconst l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [\n\t\t{\n\t\t\tmarketId,\n\t\t\tdepth: DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS,\n\t\t},\n\t]);\n\tconst oraclePriceData = l2DataResponse[0].oracleData;\n\tconst oraclePriceBn = oraclePriceData?.price;\n\tconst markPriceBn = l2DataResponse[0].markPrice;\n\tconst l2Data = convertToL2OrderBook(l2DataResponse);\n\n\tconst priceImpactData = calculatePriceImpactFromL2(\n\t\tmarketId,\n\t\tdirection,\n\t\tbaseAmount,\n\t\tl2Data,\n\t\toraclePriceBn\n\t);\n\n\tconst startPrices = COMMON_UI_UTILS.getPriceObject({\n\t\toraclePrice: oraclePriceBn,\n\t\tbestOffer: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tdirection: direction,\n\t});\n\tconst slippageToleranceInput = optionalAuctionParamsInputs.slippageTolerance;\n\tconst derivedSlippage =\n\t\tslippageToleranceInput === 'dynamic'\n\t\t\t? calculateDynamicSlippageFromL2({\n\t\t\t\t\tl2Data,\n\t\t\t\t\tmarketId,\n\t\t\t\t\tstartPrice:\n\t\t\t\t\t\tstartPrices[\n\t\t\t\t\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom as keyof typeof startPrices\n\t\t\t\t\t\t],\n\t\t\t\t\tworstPrice: priceImpactData.worstPrice,\n\t\t\t\t\toraclePrice: oraclePriceBn,\n\t\t\t\t\tdynamicSlippageConfig,\n\t\t\t })\n\t\t\t: typeof slippageToleranceInput === 'number'\n\t\t\t? slippageToleranceInput\n\t\t\t: 0.005;\n\n\tconst auctionOrderParams = COMMON_UI_UTILS.deriveMarketOrderParams({\n\t\tmarketType: marketType,\n\t\tmarketIndex: marketIndex,\n\t\tdirection: direction,\n\t\tmaxLeverageSelected: optionalAuctionParamsInputs.maxLeverageSelected,\n\t\tmaxLeverageOrderSize: optionalAuctionParamsInputs.maxLeverageOrderSize,\n\t\tbaseAmount: baseAmount,\n\t\treduceOnly: optionalAuctionParamsInputs.reduceOnly,\n\t\tallowInfSlippage: false,\n\t\toraclePrice: oraclePriceBn,\n\t\tbestPrice: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tauctionDuration: optionalAuctionParamsInputs.auctionDuration,\n\t\tauctionStartPriceOffset:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffset,\n\t\tauctionEndPriceOffset: optionalAuctionParamsInputs.auctionEndPriceOffset,\n\t\tauctionStartPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom,\n\t\tauctionEndPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionEndPriceOffsetFrom,\n\t\tslippageTolerance: derivedSlippage,\n\t\tisOracleOrder: optionalAuctionParamsInputs.isOracleOrder,\n\t\tadditionalEndPriceBuffer:\n\t\t\toptionalAuctionParamsInputs.additionalEndPriceBuffer,\n\t\tforceUpToSlippage: optionalAuctionParamsInputs.forceUpToSlippage,\n\t});\n\n\tif (!auctionOrderParams) {\n\t\tthrow new Error('Failed to derive auction params from L2');\n\t}\n\n\treturn auctionOrderParams;\n}\n\ntype FetchTopMakersParams = {\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tside: 'bid' | 'ask';\n\tlimit: number;\n};\n\n/**\n * Fetches the top makers information, for use as inputs in placeAndTake market orders.\n * The side of the request should be opposite of the side of the placeAndTake market order.\n */\nexport async function fetchTopMakers(params: FetchTopMakersParams): Promise<\n\t{\n\t\tuserAccountPubKey: PublicKey;\n\t\tuserAccount: UserAccount;\n\t}[]\n> {\n\ttry {\n\t\tconst { dlobServerHttpUrl, marketIndex, marketType, side, limit } = params;\n\n\t\tconst urlParams = encodeQueryParams({\n\t\t\tmarketIndex: marketIndex.toString(),\n\t\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\t\tside,\n\t\t\tlimit: limit.toString(),\n\t\t\tincludeAccounts: 'true',\n\t\t});\n\n\t\tconst requestUrl = `${dlobServerHttpUrl}/topMakers?${urlParams}`;\n\t\tconst response = await fetch(requestUrl);\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t\t);\n\t\t}\n\n\t\tconst serverResponse: {\n\t\t\tuserAccountPubKey: string;\n\t\t\taccountBase64: string;\n\t\t}[] = await response.json();\n\t\tconst mappedParams: {\n\t\t\tuserAccountPubKey: PublicKey;\n\t\t\tuserAccount: UserAccount;\n\t\t}[] = serverResponse.map((value) => ({\n\t\t\tuserAccountPubKey: new PublicKey(value.userAccountPubKey),\n\t\t\tuserAccount: decodeUser(Buffer.from(value.accountBase64, 'base64')),\n\t\t}));\n\n\t\treturn mappedParams;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn [];\n\t}\n}\n"]}
@@ -3,3 +3,4 @@ export * from './openPerpNonMarketOrder';
3
3
  export * from './openSwiftOrder';
4
4
  export * from './dlobServer';
5
5
  export * from './types';
6
+ export * from './positionMaxLeverage';
@@ -19,4 +19,5 @@ __exportStar(require("./openPerpNonMarketOrder"), exports);
19
19
  __exportStar(require("./openSwiftOrder"), exports);
20
20
  __exportStar(require("./dlobServer"), exports);
21
21
  __exportStar(require("./types"), exports);
22
+ __exportStar(require("./positionMaxLeverage"), exports);
22
23
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAAsC;AACtC,2DAAyC;AACzC,mDAAiC;AACjC,+CAA6B;AAC7B,0CAAwB","sourcesContent":["export * from './openPerpMarketOrder';\nexport * from './openPerpNonMarketOrder';\nexport * from './openSwiftOrder';\nexport * from './dlobServer';\nexport * from './types';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAAsC;AACtC,2DAAyC;AACzC,mDAAiC;AACjC,+CAA6B;AAC7B,0CAAwB;AACxB,wDAAsC","sourcesContent":["export * from './openPerpMarketOrder';\nexport * from './openPerpNonMarketOrder';\nexport * from './openSwiftOrder';\nexport * from './dlobServer';\nexport * from './types';\nexport * from './positionMaxLeverage';\n"]}
@@ -1,8 +1,9 @@
1
1
  import { DriftClient, User, BN, PositionDirection, ReferrerInfo } from '@drift-labs/sdk';
2
- import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
2
+ import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { SwiftOrderOptions } from '../openSwiftOrder';
4
4
  import { OptionalAuctionParamsRequestInputs } from '../dlobServer';
5
- import { TxnOrSwiftResult, WithTxnParams } from '../types';
5
+ import { WithTxnParams } from '../../../../types';
6
+ import { TxnOrSwiftResult } from '../types';
6
7
  import { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';
7
8
  export interface OpenPerpMarketOrderBaseParams {
8
9
  driftClient: DriftClient;
@@ -19,6 +20,46 @@ export interface OpenPerpMarketOrderBaseParams {
19
20
  takeProfit?: OptionalTriggerOrderParams;
20
21
  stopLoss?: OptionalTriggerOrderParams;
21
22
  };
23
+ /**
24
+ * Optional per-market leverage to set for this position.
25
+ * If provided and different from current position's leverage, will add an instruction
26
+ * to update the position's maxMarginRatio before placing the order.
27
+ * Example: 5 for 5x leverage, 10 for 10x leverage
28
+ */
29
+ positionMaxLeverage?: number;
30
+ /**
31
+ * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.
32
+ * This is only applicable for non-SWIFT orders.
33
+ */
34
+ mainSignerOverride?: PublicKey;
35
+ /**
36
+ * Optional builder code parameters for revenue sharing.
37
+ * Only applicable for Swift orders.
38
+ *
39
+ * Prerequisites:
40
+ * - User must have initialized a RevenueShareEscrow account
41
+ * - Builder must be in the user's approved_builders list
42
+ * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * builderParams: {
47
+ * builderIdx: 0, // First builder in approved list
48
+ * builderFeeTenthBps: 50 // 5 bps = 0.05%
49
+ * }
50
+ * ```
51
+ */
52
+ builderParams?: {
53
+ /**
54
+ * Index of the builder in the user's approved_builders list.
55
+ */
56
+ builderIdx: number;
57
+ /**
58
+ * Fee to charge for this order, in tenths of basis points.
59
+ * Must be <= the builder's max_fee_tenth_bps.
60
+ */
61
+ builderFeeTenthBps: number;
62
+ };
22
63
  }
23
64
  export interface OpenPerpMarketOrderBaseParamsWithSwift extends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {
24
65
  swiftOptions: SwiftOrderOptions;
@@ -35,12 +76,12 @@ export type OpenPerpMarketOrderParams<T extends boolean = boolean, S extends Omi
35
76
  /**
36
77
  * Creates and submits a Swift (signed message) order. Only available for perp orders.
37
78
  */
38
- export declare function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId, }: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void>;
79
+ export declare function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId, positionMaxLeverage, builderParams, }: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void>;
39
80
  /**
40
81
  * Creates a placeAndTake transaction instruction.
41
82
  * Fallbacks to a regular market order if no top makers are found.
42
83
  */
43
- export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, }: OpenPerpMarketOrderBaseParams & {
84
+ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, }: OpenPerpMarketOrderBaseParams & {
44
85
  direction: PositionDirection;
45
86
  dlobServerHttpUrl: string;
46
87
  marketIndex: number;
@@ -61,10 +102,12 @@ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, directio
61
102
  * @param amount - The amount to trade
62
103
  * @param dlobServerHttpUrl - Server URL for the auction params endpoint
63
104
  * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
105
+ * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,
106
+ * adds an instruction to update the position's maxMarginRatio before placing the order.
64
107
  *
65
108
  * @returns Promise resolving to an array of transaction instructions for regular orders
66
109
  */
67
- export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
110
+ export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
68
111
  /**
69
112
  * Creates a complete transaction for opening a perp market order.
70
113
  *
@@ -75,6 +118,8 @@ export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetTy
75
118
  * @param amount - The amount to trade
76
119
  * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration
77
120
  * @param dlobServerHttpUrl - Server URL for the auction params endpoint
121
+ * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,
122
+ * includes an instruction to update the position's maxMarginRatio.
78
123
  *
79
124
  * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
80
125
  */
@@ -92,6 +137,7 @@ export declare const createOpenPerpMarketOrderTxn: (params: WithTxnParams<OpenPe
92
137
  * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions
93
138
  * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true
94
139
  * @param userOrderId - The user order id for UI identification
140
+ * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). Only supported for regular transactions (not Swift).
95
141
  *
96
142
  * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
97
143
  */